From 49488f4e1b3e1e242a0b8d28bf96f5945ed726b4 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Sat, 26 Sep 2026 10:59:41 +0200 Subject: [PATCH 01/38] Add optional cable-sizing module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per-circuit cross-section recommendation as a separate module attached to the circuit list. It never writes project data itself: "Übernehmen" applies cable type, cross-section and length through the regular circuit.update command, so revisions and Undo/Redo stay intact. - Pure domain module (src/cable-sizing) with IEC 60364-5-52:2009 Annex B tables for PVC and XLPE, copper and aluminium, methods A1, A2, B1, B2, C, D1, D2 and E. Every value was cross-checked against public reproductions; where sources differ the lower value is used (docs/cable-sizing-module.md). - Temperature and grouping between table values round to the safer value; values outside the tables return no result instead of a factor of 1. Ground methods use B.52.18 (D2) and B.52.19 A (D1). - Overload protection: circuit-breakers In <= Iz; gG fuses additionally I2 <= 1.45 Iz with I2 = 1.6/1.9/2.1 In. - Inputs prefilled from the circuit: power, phase (group or device rows), project voltage, power-weighted cos phi, length and protective device. - Opened from a "Leitungsberechnung" button in the row actions, not from a grid cell, so cable cells keep the spreadsheet behavior. - Stateless API under /api/cable-sizing; no database table or migration. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 24 +- docs/README.md | 2 + docs/cable-sizing-module.md | 159 ++++ docs/circuit-list-editor-api.md | 22 + docs/circuit-list-editor-known-limitations.md | 8 +- docs/current-architecture.md | 12 + docs/spec/08-current-product-backlog.md | 4 +- .../domain/cable-sizing-calculation.ts | 689 ++++++++++++++++++ .../domain/cable-sizing-contracts.ts | 47 ++ src/frontend/components/cable-sizing-api.ts | 37 + .../components/cable-sizing-defaults.ts | 54 ++ .../components/cable-sizing-modal.tsx | 571 +++++++++++++++ .../components/circuit-tree-editor.tsx | 52 ++ .../controllers/cable-sizing.controller.ts | 37 + src/server/index.ts | 2 + src/server/routes/cable-sizing.routes.ts | 9 + tests/cable-sizing-calculation.test.ts | 274 +++++++ 17 files changed, 1999 insertions(+), 4 deletions(-) create mode 100644 docs/cable-sizing-module.md create mode 100644 src/cable-sizing/domain/cable-sizing-calculation.ts create mode 100644 src/cable-sizing/domain/cable-sizing-contracts.ts create mode 100644 src/frontend/components/cable-sizing-api.ts create mode 100644 src/frontend/components/cable-sizing-defaults.ts create mode 100644 src/frontend/components/cable-sizing-modal.tsx create mode 100644 src/server/controllers/cable-sizing.controller.ts create mode 100644 src/server/routes/cable-sizing.routes.ts create mode 100644 tests/cable-sizing-calculation.test.ts diff --git a/AGENTS.md b/AGENTS.md index ab8393e..d7c67ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -507,9 +507,31 @@ Before implementation, audit the current ProjectDevice, CircuitDeviceRow, command, snapshot, transfer and editor drag-and-drop paths. Propose concrete domain objects and commands before adding migrations. +## Cable Sizing Module + +`src/cable-sizing` is an agreed, separate calculator module attached to the +circuit list (see `docs/cable-sizing-module.md`). Rules: + +- The domain code stays pure: no imports from `db/`, `server/` or `frontend/`. +- It never writes project data. Results are applied only by an explicit + "Übernehmen", which runs the regular `circuit.update` command. +- It is opened from the circuit row action button "Leitungsberechnung", never + by clicking a grid cell; cable cells keep the normal spreadsheet behavior. +- It has no database table and no migration; `/api/cable-sizing/*` is + stateless. +- Reference data is IEC 60364-5-52:2009 Annex B. Change table values only with + a documented source in `docs/cable-sizing-module.md`; where sources differ, + use the lower value. Inputs outside the tables return no result instead of + assuming a factor of 1. +- Inputs are prefilled from the circuit (power, phase, voltage, weighted cos φ, + length, protective device) and remain editable; manual cable entry without + a calculation stays possible. + ## Future Sizing -Do not implement full cable/protection sizing unless explicitly requested. +Do not implement full automatic cable/protection sizing of all circuits +unless explicitly requested. The cable sizing module above only suggests +values for one circuit on demand. Keep the structure ready for it. diff --git a/docs/README.md b/docs/README.md index 69a2115..5e37408 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,8 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we - [Editor-API](circuit-list-editor-api.md) – unterstützte Circuit-First-Endpunkte - [Bekannte Einschränkungen](circuit-list-editor-known-limitations.md) – bewusst noch nicht implementierte oder begrenzte Funktionen +- [Leitungsberechnung](cable-sizing-module.md) – optionales Rechenmodul, + Rechenweg, Datenbasis und Prüfnachweis der Tabellen ## Entwicklung und Betrieb diff --git a/docs/cable-sizing-module.md b/docs/cable-sizing-module.md new file mode 100644 index 0000000..374994e --- /dev/null +++ b/docs/cable-sizing-module.md @@ -0,0 +1,159 @@ +# Leitungsberechnung (Cable-Sizing-Modul) + +Optionales, abgegrenztes Rechenmodul für die Querschnittsempfehlung eines +Stromkreises. Es wurde als eigenständiges Modul vereinbart, das an die +Stromkreisliste angedockt ist. Es **schreibt keine Projektdaten selbst**: Ein +Ergebnis wird erst durch ausdrückliches „Übernehmen“ über den bestehenden +Befehl `circuit.update` in den Stromkreis geschrieben. Revisionen und +Undo/Redo bleiben damit unverändert gültig. + +Die vollständige, automatische Bemessung aller Stromkreise (siehe +`docs/spec/06-future-sizing-and-calculations.md`) ist weiterhin **nicht** +Teil dieses Moduls. + +## Aufbau und Andockpunkte + +``` +src/cable-sizing/domain/cable-sizing-calculation.ts reine Berechnung + Tabellen +src/cable-sizing/domain/cable-sizing-contracts.ts Zod-Schema der API +src/server/controllers/cable-sizing.controller.ts zustandslose Endpunkte +src/server/routes/cable-sizing.routes.ts Router unter /api/cable-sizing +src/frontend/components/cable-sizing-api.ts Fetch-Client +src/frontend/components/cable-sizing-defaults.ts Vorbelegung aus dem Stromkreis +src/frontend/components/cable-sizing-modal.tsx Dialog +tests/cable-sizing-calculation.test.ts Tabellen, Rechnung, Vorbelegung +``` + +Das Domänenmodul importiert nichts aus `db/`, `server/` oder `frontend/`. +Außerhalb dieser Dateien gibt es genau zwei Andockpunkte: + +1. `src/server/index.ts`: `app.use("/api/cable-sizing", cableSizingRouter)`. +2. `src/frontend/components/circuit-tree-editor.tsx`: Zustand für den + geöffneten Dialog, ein Button **Leitungsberechnung** (Rechner-Icon) in der + Aktionsspalte jeder Stromkreiszeile, der Dialog selbst und + `handleApplyCableSizing`, das über `updateCircuitById` den regulären + `circuit.update`-Befehl ausführt. + +Der Aufruf liegt bewusst **nicht** auf einer Tabellenzelle: Klick, Doppelklick, +Enter, F2 und Tippen in den Kabelspalten verhalten sich wie in jeder anderen +Zelle (Spreadsheet-Regel in `AGENTS.md`). Es gibt keine eigene Datenbanktabelle +und keine Migration. + +## Eingaben und Vorbelegung + +| Eingabe | Vorbelegung | +|---|---| +| Leistung | `circuitTotalPower` des Stromkreises (mit Geräte-GZF), nicht editierbar | +| Phasen | 3~, wenn die Stromkreisgruppe 3-phasig ist oder eine Gerätezeile `three_phase` hat, sonst 1~ | +| Spannung | `circuit.voltage` (aus den Projekteinstellungen abgeleitet); bei manuell abweichender Phasenzahl die jeweilige Projektspannung | +| cos φ | leistungsgewichtet aus den Gerätezeilen: P / Σ(P_Zeile / cos φ_Zeile), fehlendes cos φ = 1; änderbar | +| Länge | `cableLength` des Stromkreises | +| Schutzorgan | Schutzgerät des Stromkreises: LS, FI/LS, AFDD = Leitungsschutzschalter; D0/NH = Sicherung gG; FI ohne Überstromauslöser wird nicht berücksichtigt | +| Verlegeart, Isolierstoff, Leitermaterial, Temperatur, Häufung, max. ΔU, Oberschwingungen | Planereingaben | + +Kabeltyp und Querschnitt lassen sich im Dialog auch ohne Berechnung direkt +eintragen. Weicht der Eintrag von der Empfehlung oder dem +Praxis-Mindestquerschnitt ab, erscheint nur ein Hinweis. + +## Rechenweg + +1. Betriebsstrom I_B aus Leistung, Spannung, cos φ und Phasenzahl. +2. Erforderliche Belastbarkeit: ohne Schutzorgan I_B; mit Schutzorgan + max(I_B, I_n, I₂/1,45) nach IEC 60364-4-43 (I_n ≤ I_z und I₂ ≤ 1,45 · I_z). + I₂/I_n: Leitungsschutzschalter 1,45; Sicherung gG 2,1 (I_n ≤ 4 A), + 1,9 (4 A < I_n < 16 A), 1,6 (I_n ≥ 16 A). +3. Tabellenwert I_z je Querschnitt × Temperaturfaktor × Häufungsfaktor + (× 0,86 bei 15–33 % 3. Harmonischer im Drehstromkreis). +4. Spannungsfall ΔU = k · L · I_B · cos φ / (κ · A · U) mit k = 2 (1~) bzw. + √3 (3~), κ = 48 (Cu) bzw. 30 (Al) m/(Ω·mm²) bei Betriebstemperatur; + Reaktanz wird vernachlässigt. +5. Empfehlung = größerer Querschnitt aus Belastbarkeit und Spannungsfall; + 1-phasige Stromkreise werden auf den Praxis-Mindestquerschnitt 2,5 mm² + angehoben (Planungskonvention aus `docs/spec/06-…`, keine Rechenanforderung). +6. Zusätzlich: maximale Länge für den zulässigen Spannungsfall. + +Temperaturen und Häufungen **zwischen** Tabellenwerten werden auf den nächsten +ungünstigeren Tabellenwert gerundet (höhere Temperatur, mehr Stromkreise). +Werte **außerhalb** der Tabellen liefern kein Ergebnis und eine Meldung – es +wird nie stillschweigend mit Faktor 1 gerechnet. + +## Datenbasis und Prüfnachweis + +Grundlage ist **IEC 60364-5-52:2009, Anhang B**. Alle Werte wurden am +26.09.2026 zeilenweise mit öffentlich zugänglichen Wiedergaben abgeglichen: +TiSoft ElectricalDesign-Hilfe zu IEC 60364-5-52 +(`ti-soft.com/en/support/help/electricaldesign/standards/iec-60364-5-52/…`) +und ECalPro (`ecalpro.com/standards/iec-60364/…`). Wo die Quellen voneinander +abweichen, ist der kleinere, sichere Wert eingetragen. + +| Tabelle | Inhalt | Abgleich | Abweichungen | +|---|---|---|---| +| B.52.2 | PVC, 2 belastete Adern, Cu/Al, A1–D2 | TiSoft; Cu A1–C zusätzlich ECalPro | Cu A1 240 mm²: 321 / 320 → 320 | +| B.52.3 | VPE, 2 belastete Adern, Cu/Al, A1–D2 | TiSoft | – | +| B.52.4 | PVC, 3 belastete Adern, Cu/Al, A1–D2 | TiSoft | – | +| B.52.5 | VPE, 3 belastete Adern, Cu/Al, A1–D2 | TiSoft | – | +| B.52.10 / .11 | PVC, Verlegeart E, mehradrig, Cu / Al | TiSoft; Cu 2 Adern zusätzlich ECalPro | Cu 3 Adern 70 / 120 mm²: 198 / 278 bzw. 196 / 276 → 196 / 276 | +| B.52.12 / .13 | VPE, Verlegeart E, mehradrig, Cu / Al | TiSoft | – | +| B.52.14 | Temperatur Luft, PVC / VPE | TiSoft, ECalPro | – | +| B.52.15 | Temperatur Erde, PVC / VPE | TiSoft | – | +| B.52.17 | Häufung Luft, Zeile 1 (gebündelt) | TiSoft, ECalPro | – | +| B.52.18 | Häufung Erde direkt, Kabel berührend | TiSoft | – | +| B.52.19 A | Häufung mehradrige Kabel in berührenden Rohren im Erdreich | TiSoft | – | + +Anwendung der Tabellen: + +- Verlegearten A1, A2, B1, B2, C, E in Luft (Bezug 30 °C), D1 und D2 im + Erdreich (Bezug 20 °C, Bodenwärmewiderstand 2,5 K·m/W). Nach Tabelle B.52.1 + ist **D1 = Leitung im Rohr/Kabelschutzrohr im Erdreich** und **D2 = Kabel + direkt im Erdreich**. +- Häufung in Luft immer nach B.52.17 Zeile 1, auch für Verlegeart E; das ist + die ungünstigste Anordnung (einlagig auf Pritschen wären höhere Faktoren + zulässig). D1 nach B.52.19 A, D2 nach B.52.18 jeweils „berührend“. +- Aluminium nur mit den echten Aluminiumwerten (ab 2,5 mm², D2 ab 16 mm²); + Querschnitte ohne Tabellenwert werden nie empfohlen. +- Die Verlegearten F und G (Einzeladern mit Abstand) sind nicht enthalten. + +**Vor produktivem Einsatz:** Die nationalen Tabellen der DIN VDE 0298-4 +können in einzelnen Werten abweichen. Der Planer muss die Tabellen gegen den +Normtext prüfen. Die Prüfung ist in `tests/cable-sizing-calculation.test.ts` +über Stichwerte und eine Monotonieprüfung jeder Tabellenzeile abgesichert. + +## Nicht enthalten + +- Kurzschlussfestigkeit, Abschaltbedingungen (Schleifenimpedanz) und + Selektivität +- Bodenwärmewiderstand ≠ 2,5 K·m/W, Häufung mit Abstand, Verlegearten F/G +- Bemessung des Neutralleiters bei > 33 % 3. Harmonischer (nur Hinweis) +- automatische Bemessung oder Prüfung aller Stromkreise + +## API + +`POST /api/cable-sizing/calculate` – zustandslos, liest und schreibt keine +Projektdaten. + +```jsonc +{ + "phase": 1, // 1 | 3 + "mode": "power", // "power" | "current" + "powerKw": 4.2, // bei mode "power" + "currentA": 18.3, // bei mode "current" + "cosPhi": 0.95, // 0,1 … 1 + "voltage": 230, + "lengthM": 23.5, + "layingMethod": "C", // A1 | A2 | B1 | B2 | C | D1 | D2 | E + "conductorMaterial": "copper", // copper | aluminum + "insulation": "pvc", // pvc | xlpe + "ambientTemperatureC": 30, // Luft; bei D1/D2 Bodentemperatur + "groupingCircuits": 1, // 1 … 100, Tabellen bis 20 + "maxVoltageDropPercent": 3, + "harmonicNeutralLoad": "none", // none | 15to33Percent | over33Percent + "existingProtection": { "ratedCurrentA": 16, "kind": "breaker" }, // optional; kind: breaker | fuse + "circuitCategory": "single_phase" // optional +} +``` + +Antwort: `{ "result": CableSizingResult, "alerts": CableSizingAlert[] }`. +`result.supported = false` mit `unsupportedReason` (`temperature` oder +`grouping`), wenn die Eingaben außerhalb der Tabellen liegen. +`GET /api/cable-sizing/laying-methods` und `GET /api/cable-sizing/insulation-materials` +liefern die Auswahllisten. diff --git a/docs/circuit-list-editor-api.md b/docs/circuit-list-editor-api.md index 9ed9e0a..0b24cc0 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -391,6 +391,28 @@ inverse command. The former direct restore/reconnect endpoints are removed. `displayName` is included in the comparison but is not selected by default in the UI. Updating a project device never triggers synchronization implicitly. +## Cable Sizing (optional module) + +Stateless calculator endpoints mounted at `/api/cable-sizing`. They neither +read nor write project data; applying a result uses `circuit.update` through +`POST /projects/:projectId/commands`. + +- `POST /cable-sizing/calculate` + - request: phase, mode (`power` | `current`), powerKw or currentA, cosPhi, + voltage, lengthM, layingMethod (`A1` | `A2` | `B1` | `B2` | `C` | `D1` | + `D2` | `E`), conductorMaterial, insulation (`pvc` | `xlpe`), + ambientTemperatureC, groupingCircuits, maxVoltageDropPercent, + harmonicNeutralLoad, optional `existingProtection` + (`{ ratedCurrentA, kind: "breaker" | "fuse" }`) and circuitCategory + - returns `{ "result": { ... }, "alerts": [ ... ] }`; `result.supported` + is `false` with `unsupportedReason` when temperature or grouping lie + outside the tables + - unknown fields are rejected (`400`) +- `GET /cable-sizing/laying-methods` +- `GET /cable-sizing/insulation-materials` + +Full request example and calculation rules: `docs/cable-sizing-module.md`. + ## Revit CSV Foundation - `GET /projects/:projectId/external-csv/configuration` diff --git a/docs/circuit-list-editor-known-limitations.md b/docs/circuit-list-editor-known-limitations.md index 4f7f660..521a9dc 100644 --- a/docs/circuit-list-editor-known-limitations.md +++ b/docs/circuit-list-editor-known-limitations.md @@ -17,8 +17,12 @@ - Persistence currently targets local SQLite; PostgreSQL is an architectural option, not an implemented runtime. - The global device library supports basic CRUD and copy operations, but has no versioning, permissions or controlled synchronization model. -- Final electrical sizing logic is not implemented yet. -- No full norm-compliant voltage-drop and protection-dimensioning calculation flow yet. +- There is no automatic sizing of all circuits. The optional cable sizing + module suggests a cross-section for one circuit on demand (IEC 60364-5-52 + Annex B tables; no short-circuit, disconnection-time or selectivity checks, + no methods F/G, soil resistivity fixed at 2.5 K·m/W) and does not validate + manually entered cable values. National tables (DIN VDE 0298-4) must be + checked by the planner; see `docs/cable-sizing-module.md`. - Sorting is view-only until users explicitly apply sorted order. - Complete-circuit drag supports one circuit at a time between groups of the same category. Cross-category moves and multi-circuit moves across group diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 92efc98..7e78fac 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -452,6 +452,18 @@ werden als Diff angezeigt und nur für ausdrücklich gewählte Felder und Zeilen Die globale Gerätebibliothek ist ein einfacher, datenbankweiter Vorlagenbestand. Kopieren in ein Projekt erzeugt ein eigenständiges Projektgerät. +## Leitungsberechnung + +Das optionale Modul `src/cable-sizing` berechnet auf Anforderung eine +Querschnittsempfehlung für einen Stromkreis (IEC 60364-5-52 Anhang B: +Belastbarkeit, Temperatur, Häufung, Spannungsfall, Schutzorgan). Die +Domänenlogik ist rein, `POST /api/cable-sizing/calculate` ist zustandslos und +es gibt keine eigene Tabelle. Der Editor öffnet den Dialog über den Button +„Leitungsberechnung“ in der Aktionsspalte; „Übernehmen“ schreibt Kabeltyp, +Querschnitt und Länge über den regulären `circuit.update`-Befehl, also mit +Revision und Undo/Redo. Details, Rechenweg und Prüfnachweis der Tabellen: +`docs/cable-sizing-module.md`. + ## Persistenz und Migration - SQLite ist die aktuell unterstützte Datenbank. diff --git a/docs/spec/08-current-product-backlog.md b/docs/spec/08-current-product-backlog.md index c90dd24..519fd8d 100644 --- a/docs/spec/08-current-product-backlog.md +++ b/docs/spec/08-current-product-backlog.md @@ -46,7 +46,9 @@ requirements and intended sequencing, not proof of implementation. - [x] Phase E: editor projection and editing. - [x] Phase F: documentation and full GUI verification. - [ ] Keep full electrical sizing and cable-dimensioning rules separate until - the planner supplies the calculation requirements. + the planner supplies the calculation requirements. The optional per-circuit + cable sizing module (`docs/cable-sizing-module.md`) exists; its tables must + be confirmed by the planner against DIN VDE 0298-4. - Detailed specification: `docs/spec/09-distribution-board-components-and-protection-groups.md` diff --git a/src/cable-sizing/domain/cable-sizing-calculation.ts b/src/cable-sizing/domain/cable-sizing-calculation.ts new file mode 100644 index 0000000..3c881bd --- /dev/null +++ b/src/cable-sizing/domain/cable-sizing-calculation.ts @@ -0,0 +1,689 @@ +// Pure cable sizing domain logic. No imports from db/, server/ or frontend/; +// the module is an optional calculator attached to the circuit list and never +// writes project data itself (see docs/cable-sizing-module.md). +// +// Reference data: IEC 60364-5-52:2009, Annex B (tables B.52.2 to B.52.5, +// B.52.10 to B.52.19). Every value was cross-checked against publicly +// available reproductions of these tables; where sources disagreed the lower, +// i.e. safer, value is used. The table-by-table verification record is in +// docs/cable-sizing-module.md. National tables (DIN VDE 0298-4) may differ in +// individual values and must be checked by the planner against the norm text. + +// -- Reference installation methods (IEC 60364-5-52, Table B.52.1) ---------- + +export const LAYING_METHODS = ["A1", "A2", "B1", "B2", "C", "D1", "D2", "E"] as const; +export type LayingMethod = (typeof LAYING_METHODS)[number]; + +export const LAYING_METHOD_GROUP: Record = { + A1: "air", + A2: "air", + B1: "air", + B2: "air", + C: "air", + E: "air", + D1: "ground", + D2: "ground", +}; + +export const LAYING_METHOD_LABELS: Record = { + A1: "A1 – Einzeladern im Rohr in wärmegedämmter Wand", + A2: "A2 – Mehradrige Leitung im Rohr in wärmegedämmter Wand", + B1: "B1 – Einzeladern im Rohr auf oder in der Wand", + B2: "B2 – Mehradrige Leitung im Rohr auf oder in der Wand", + C: "C – Mehradrige Leitung direkt auf oder in der Wand", + D1: "D1 – Leitung im Rohr oder Kabelschutzrohr im Erdreich", + D2: "D2 – Kabel direkt im Erdreich", + E: "E – Mehradrige Leitung frei in Luft", +}; + +// -- Insulation / conductor material ---------------------------------------- + +export const INSULATION_MATERIALS = ["pvc", "xlpe"] as const; +export type InsulationMaterial = (typeof INSULATION_MATERIALS)[number]; + +export const INSULATION_MATERIAL_LABELS: Record = { + pvc: "PVC (70 °C), z. B. NYM, NYY", + xlpe: "VPE/XLPE (90 °C), z. B. N2XH, NHXH", +}; + +export const CONDUCTOR_MATERIALS = ["copper", "aluminum"] as const; +export type ConductorMaterial = (typeof CONDUCTOR_MATERIALS)[number]; + +// -- Harmonic neutral loading (IEC 60364-5-52, Annex E, three-phase only) --- + +export const HARMONIC_NEUTRAL_LOAD_OPTIONS = [ + "none", + "15to33Percent", + "over33Percent", +] as const; +export type HarmonicNeutralLoad = (typeof HARMONIC_NEUTRAL_LOAD_OPTIONS)[number]; + +export const HARMONIC_NEUTRAL_LOAD_LABELS: Record = { + none: "Keine nennenswerte 3. Harmonische (< 15 %) – Standardfall", + "15to33Percent": "3. Harmonische 15–33 % – Reduktionsfaktor 0,86", + over33Percent: "3. Harmonische > 33 % – Neutralleiter wie Außenleiter dimensionieren", +}; + +export const HARMONIC_REDUCTION_FACTOR = 0.86; + +// -- Current-carrying capacity tables ---------------------------------------- + +export const CROSS_SECTIONS_MM2 = [ + 1.5, 2.5, 4, 6, 10, 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, +] as const; + +type CoreCount = 2 | 3; +type CapacityRow = readonly (number | null)[]; +type CapacityTable = Record>; + +const n = null; + +/** Iz in A at 30 °C air / 20 °C ground, soil resistivity 2.5 K·m/W. */ +export const CURRENT_CAPACITY_A: Record< + InsulationMaterial, + Record +> = { + pvc: { + copper: { + // B.52.2 / B.52.4; E: B.52.10 multi-core. A1 2L 240 mm²: sources 320/321 → 320. + // E 3L 70/120 mm²: sources 196/198 and 276/278 → 196 and 276. + A1: { + 2: [14.5, 19.5, 26, 34, 46, 61, 80, 99, 119, 151, 182, 210, 240, 273, 320], + 3: [13.5, 18, 24, 31, 42, 56, 73, 89, 108, 136, 164, 188, 216, 245, 286], + }, + A2: { + 2: [14, 18.5, 25, 32, 43, 57, 75, 92, 110, 139, 167, 192, 219, 248, 291], + 3: [13, 17.5, 23, 29, 39, 52, 68, 83, 99, 125, 150, 172, 196, 223, 261], + }, + B1: { + 2: [17.5, 24, 32, 41, 57, 76, 101, 125, 151, 192, 232, 269, 300, 341, 400], + 3: [15.5, 21, 28, 36, 50, 68, 89, 110, 134, 171, 207, 239, 262, 296, 346], + }, + B2: { + 2: [16.5, 23, 30, 38, 52, 69, 90, 111, 133, 168, 201, 232, 258, 294, 344], + 3: [15, 20, 27, 34, 46, 62, 80, 99, 118, 149, 179, 206, 225, 255, 297], + }, + C: { + 2: [19.5, 27, 36, 46, 63, 85, 112, 138, 168, 213, 258, 299, 344, 392, 461], + 3: [17.5, 24, 32, 41, 57, 76, 96, 119, 144, 184, 223, 259, 299, 341, 403], + }, + D1: { + 2: [22, 29, 37, 46, 60, 78, 99, 119, 140, 173, 204, 231, 261, 292, 336], + 3: [18, 24, 30, 38, 50, 64, 82, 98, 116, 143, 169, 192, 217, 243, 280], + }, + D2: { + 2: [22, 28, 38, 48, 64, 83, 110, 132, 156, 192, 230, 261, 293, 331, 382], + 3: [19, 24, 33, 41, 54, 70, 92, 110, 130, 162, 193, 220, 246, 278, 320], + }, + E: { + 2: [22, 30, 40, 51, 70, 94, 119, 148, 180, 232, 282, 328, 379, 434, 514], + 3: [18.5, 25, 34, 43, 60, 80, 101, 126, 153, 196, 238, 276, 319, 364, 430], + }, + }, + aluminum: { + // B.52.2 / B.52.4 aluminium; E: B.52.11. No values below 2.5 mm² + // (D2 below 16 mm²). + A1: { + 2: [n, 15, 20, 26, 36, 48, 63, 77, 93, 118, 142, 164, 189, 215, 252], + 3: [n, 14, 18.5, 24, 32, 43, 57, 70, 84, 107, 129, 149, 170, 194, 227], + }, + A2: { + 2: [n, 14.5, 19.5, 25, 33, 44, 58, 71, 86, 108, 130, 150, 172, 195, 229], + 3: [n, 13.5, 17.5, 23, 31, 41, 53, 65, 78, 98, 118, 135, 155, 176, 207], + }, + B1: { + 2: [n, 18.5, 25, 32, 44, 60, 79, 97, 118, 150, 181, 210, 234, 266, 312], + 3: [n, 16.5, 22, 28, 39, 53, 70, 86, 104, 133, 161, 186, 204, 230, 269], + }, + B2: { + 2: [n, 17.5, 24, 30, 41, 54, 71, 86, 104, 131, 157, 181, 201, 230, 269], + 3: [n, 15.5, 21, 27, 36, 48, 62, 77, 92, 116, 139, 160, 176, 199, 232], + }, + C: { + 2: [n, 21, 28, 36, 49, 66, 83, 103, 125, 160, 195, 226, 261, 298, 352], + 3: [n, 18.5, 25, 32, 44, 59, 73, 90, 110, 140, 170, 197, 227, 259, 305], + }, + D1: { + 2: [n, 22, 29, 36, 47, 61, 77, 93, 109, 135, 159, 180, 204, 228, 262], + 3: [n, 18.5, 24, 30, 39, 50, 64, 77, 91, 112, 132, 150, 169, 190, 218], + }, + D2: { + 2: [n, n, n, n, n, 63, 82, 98, 117, 145, 173, 200, 224, 255, 298], + 3: [n, n, n, n, n, 53, 69, 83, 99, 122, 148, 169, 189, 214, 250], + }, + E: { + 2: [n, 23, 31, 39, 54, 73, 89, 111, 135, 173, 210, 244, 282, 322, 380], + 3: [n, 19.5, 26, 33, 46, 61, 78, 96, 117, 150, 183, 212, 245, 280, 330], + }, + }, + }, + xlpe: { + copper: { + // B.52.3 / B.52.5; E: B.52.12 multi-core. + A1: { + 2: [19, 26, 35, 45, 61, 81, 106, 131, 158, 200, 241, 278, 318, 362, 424], + 3: [17, 23, 31, 40, 54, 73, 95, 117, 141, 179, 216, 249, 285, 324, 380], + }, + A2: { + 2: [18.5, 25, 33, 42, 57, 76, 99, 121, 145, 183, 220, 253, 290, 329, 386], + 3: [16.5, 22, 30, 38, 51, 68, 89, 109, 130, 164, 197, 227, 259, 295, 346], + }, + B1: { + 2: [23, 31, 42, 54, 75, 100, 133, 164, 198, 253, 306, 354, 393, 449, 528], + 3: [20, 28, 37, 48, 66, 88, 117, 144, 175, 222, 269, 312, 342, 384, 450], + }, + B2: { + 2: [22, 30, 40, 51, 69, 91, 119, 146, 175, 221, 265, 305, 334, 384, 459], + 3: [19.5, 26, 35, 44, 60, 80, 105, 128, 154, 194, 233, 268, 300, 340, 398], + }, + C: { + 2: [24, 33, 45, 58, 80, 107, 138, 171, 209, 269, 328, 382, 441, 506, 599], + 3: [22, 30, 40, 52, 71, 96, 119, 147, 179, 229, 278, 322, 371, 424, 500], + }, + D1: { + 2: [25, 33, 43, 53, 71, 91, 116, 139, 164, 203, 239, 271, 306, 343, 395], + 3: [21, 28, 36, 44, 58, 75, 96, 115, 135, 167, 197, 223, 251, 281, 324], + }, + D2: { + 2: [27, 35, 46, 58, 77, 100, 129, 155, 183, 225, 270, 306, 343, 387, 448], + 3: [23, 30, 39, 49, 65, 84, 107, 129, 153, 188, 226, 257, 287, 324, 375], + }, + E: { + 2: [26, 36, 49, 63, 86, 115, 149, 185, 225, 289, 352, 410, 473, 542, 641], + 3: [23, 32, 42, 54, 75, 100, 127, 158, 192, 246, 298, 346, 399, 456, 538], + }, + }, + aluminum: { + // B.52.3 / B.52.5 aluminium; E: B.52.13. + A1: { + 2: [n, 20, 27, 35, 48, 64, 84, 103, 125, 158, 191, 220, 253, 288, 338], + 3: [n, 19, 25, 32, 44, 58, 76, 94, 113, 142, 171, 197, 226, 256, 300], + }, + A2: { + 2: [n, 19.5, 26, 33, 45, 60, 78, 96, 115, 145, 175, 201, 230, 262, 307], + 3: [n, 18, 24, 31, 41, 55, 71, 87, 104, 131, 157, 180, 206, 233, 273], + }, + B1: { + 2: [n, 25, 33, 43, 59, 79, 105, 130, 157, 200, 242, 281, 307, 351, 412], + 3: [n, 22, 29, 38, 52, 71, 93, 116, 140, 179, 217, 251, 267, 300, 351], + }, + B2: { + 2: [n, 23, 31, 40, 54, 72, 94, 115, 138, 175, 210, 242, 261, 300, 358], + 3: [n, 21, 28, 35, 48, 64, 84, 103, 124, 156, 188, 216, 240, 272, 318], + }, + C: { + 2: [n, 26, 35, 45, 62, 84, 101, 126, 154, 198, 241, 280, 324, 371, 439], + 3: [n, 24, 32, 41, 57, 76, 90, 112, 136, 174, 211, 245, 283, 323, 382], + }, + D1: { + 2: [n, 26, 33, 42, 55, 71, 90, 108, 128, 158, 186, 211, 238, 267, 307], + 3: [n, 22, 28, 35, 46, 59, 75, 90, 106, 130, 154, 174, 197, 220, 253], + }, + D2: { + 2: [n, n, n, n, n, 76, 98, 117, 139, 170, 204, 233, 261, 296, 343], + 3: [n, n, n, n, n, 64, 82, 98, 117, 144, 172, 197, 220, 250, 290], + }, + E: { + 2: [n, 28, 38, 49, 67, 91, 108, 135, 164, 211, 257, 300, 346, 397, 470], + 3: [n, 24, 32, 42, 58, 77, 97, 120, 146, 187, 227, 263, 304, 347, 409], + }, + }, + }, +}; + +// -- Correction factors ------------------------------------------------------ + +/** B.52.14 (air, reference 30 °C) and B.52.15 (ground, reference 20 °C). */ +export const TEMPERATURE_FACTORS: Record< + "air" | "ground", + Record> +> = { + air: { + pvc: { 10: 1.22, 15: 1.17, 20: 1.12, 25: 1.06, 30: 1.0, 35: 0.94, 40: 0.87, 45: 0.79, 50: 0.71, 55: 0.61, 60: 0.5 }, + xlpe: { + 10: 1.15, 15: 1.12, 20: 1.08, 25: 1.04, 30: 1.0, 35: 0.96, 40: 0.91, 45: 0.87, + 50: 0.82, 55: 0.76, 60: 0.71, 65: 0.65, 70: 0.58, 75: 0.5, 80: 0.41, + }, + }, + ground: { + pvc: { 10: 1.1, 15: 1.05, 20: 1.0, 25: 0.95, 30: 0.89, 35: 0.84, 40: 0.77, 45: 0.71, 50: 0.63, 55: 0.55, 60: 0.45 }, + xlpe: { + 10: 1.07, 15: 1.04, 20: 1.0, 25: 0.96, 30: 0.93, 35: 0.89, 40: 0.85, 45: 0.8, + 50: 0.76, 55: 0.71, 60: 0.65, 65: 0.6, 70: 0.53, 75: 0.46, 80: 0.38, + }, + }, +}; + +export const REFERENCE_TEMPERATURE_C: Record<"air" | "ground", number> = { + air: 30, + ground: 20, +}; + +/** + * Grouping reduction factors for touching circuits/cables: + * air (A1–C, E): B.52.17 item 1 "bunched in air, on a surface, embedded or + * enclosed" – the most restrictive arrangement, also used for E (single + * layers on trays would allow higher factors); + * D1: B.52.19 A (multi-core cables in touching ducts); + * D2: B.52.18 (cables direct in ground, touching). + */ +export const GROUPING_FACTORS: Record<"air" | "D1" | "D2", Record> = { + air: { 1: 1.0, 2: 0.8, 3: 0.7, 4: 0.65, 5: 0.6, 6: 0.57, 7: 0.54, 8: 0.52, 9: 0.5, 12: 0.45, 16: 0.41, 20: 0.38 }, + D1: { + 1: 1.0, 2: 0.85, 3: 0.75, 4: 0.7, 5: 0.65, 6: 0.6, 7: 0.57, 8: 0.54, 9: 0.52, 10: 0.49, + 11: 0.47, 12: 0.45, 13: 0.44, 14: 0.42, 15: 0.41, 16: 0.39, 17: 0.38, 18: 0.37, 19: 0.35, 20: 0.34, + }, + D2: { 1: 1.0, 2: 0.75, 3: 0.65, 4: 0.6, 5: 0.55, 6: 0.5, 7: 0.45, 8: 0.43, 9: 0.41, 12: 0.36, 16: 0.32, 20: 0.29 }, +}; + +export const MAX_GROUPING_CIRCUITS = 20; + +function groupingTableFor(method: LayingMethod) { + return method === "D1" ? GROUPING_FACTORS.D1 : method === "D2" ? GROUPING_FACTORS.D2 : GROUPING_FACTORS.air; +} + +/** + * Looks up a tabulated factor. Values between tabulated keys use the next + * higher key (the lower, safer factor); values above the table are not + * supported (null) and values below the smallest key use the smallest key + * (whose factor is lower than the true one, i.e. safe). + */ +function lookupConservative(table: Record, value: number): { key: number; factor: number } | null { + const keys = Object.keys(table).map(Number).sort((a, b) => a - b); + const key = keys.find((candidate) => candidate >= value); + if (key === undefined) { + return null; + } + return { key, factor: table[key] }; +} + +/** Tabulated temperatures offered by the UI for a laying method and insulation. */ +export function temperatureOptions(method: LayingMethod, insulation: InsulationMaterial): number[] { + return Object.keys(TEMPERATURE_FACTORS[LAYING_METHOD_GROUP[method]][insulation]) + .map(Number) + .sort((a, b) => a - b); +} + +// -- Conductor resistivity for the voltage drop ------------------------------- + +/** Conductivity in m/(Ω·mm²) at the maximum operating temperature (conservative). */ +export const KAPPA: Record = { copper: 48, aluminum: 30 }; + +// -- Practical minimum cross-sections by circuit category -------------------- +// A planning convention from docs/spec/06-future-sizing-and-calculations.md +// ("Standard Single-Phase Circuits ... cable cross-section: 2.5 mm²"), not a +// calculation result. It only ever raises a recommendation. +export type CircuitCategory = "lighting" | "single_phase" | "three_phase"; + +export const PRACTICAL_MINIMUM_CROSS_SECTION_MM2: Partial> = { + single_phase: 2.5, +}; + +// -- Protective device -------------------------------------------------------- + +export const PROTECTION_KINDS = ["breaker", "fuse"] as const; +export type ProtectionKind = (typeof PROTECTION_KINDS)[number]; + +export interface ExistingProtection { + ratedCurrentA: number; + /** breaker: circuit-breaker (I2 ≤ 1.45 In); fuse: gG fuse (I2 up to 2.1 In). */ + kind: ProtectionKind; +} + +/** + * Conventional tripping/fusing current I2 as multiple of In. + * Circuit-breakers (IEC 60898-1): 1.45. gG fuses (IEC 60269-2): + * In ≤ 4 A: 2.1, 4 A < In < 16 A: 1.9, In ≥ 16 A: 1.6. + */ +export function conventionalTrippingFactor(protection: ExistingProtection): number { + if (protection.kind === "breaker") { + return 1.45; + } + if (protection.ratedCurrentA <= 4) { + return 2.1; + } + return protection.ratedCurrentA < 16 ? 1.9 : 1.6; +} + +/** + * Minimum Iz required by overload protection (IEC 60364-4-43, 433.1): + * In ≤ Iz and I2 ≤ 1.45 · Iz. + */ +export function minimumIzForProtection(protection: ExistingProtection): number { + return Math.max( + protection.ratedCurrentA, + (conventionalTrippingFactor(protection) * protection.ratedCurrentA) / 1.45 + ); +} + +// -- Input / result ----------------------------------------------------------- + +export interface CableSizingInput { + phase: 1 | 3; + mode: "power" | "current"; + /** kW, only used when mode === "power" */ + powerKw?: number; + /** A, only used when mode === "current" */ + currentA?: number; + cosPhi: number; + /** Line voltage in V (project single-/three-phase voltage). */ + voltage: number; + /** Single-run cable length in m. */ + lengthM: number; + layingMethod: LayingMethod; + conductorMaterial: ConductorMaterial; + insulation: InsulationMaterial; + /** Ambient air temperature, or ground temperature for D1/D2. */ + ambientTemperatureC: number; + /** Number of grouped circuits or multi-core cables, including this one. */ + groupingCircuits: number; + maxVoltageDropPercent: number; + harmonicNeutralLoad: HarmonicNeutralLoad; + existingProtection?: ExistingProtection; + circuitCategory?: CircuitCategory; +} + +export interface CrossSectionRow { + crossSectionMm2: number; + /** Tabulated Iz; null if the table has no value for this size. */ + ratedCurrentA: number | null; + correctedCurrentA: number | null; + currentSufficient: boolean | null; + voltageDropPercent: number | null; + voltageDropSufficient: boolean | null; + /** Longest single run meeting maxVoltageDropPercent at this load. */ + maxLengthForVoltageDropM: number | null; + recommended: boolean; +} + +export interface ProtectionCoordinationResult { + ratedCurrentA: number; + kind: ProtectionKind; + /** I2 / In used for the check. */ + conventionalTrippingFactor: number; + /** In ≤ Iz and I2 ≤ 1.45 · Iz for the recommended cross-section. */ + coordinated: boolean; +} + +export type UnsupportedReason = "temperature" | "grouping"; + +export interface CableSizingResult { + /** false: the inputs are outside the tabulated range – no numeric result. */ + supported: boolean; + unsupportedReason: UnsupportedReason | null; + operatingCurrentA: number; + /** + * Current the cross-section must carry after correction: + * max(Ib, In, I2/1.45) with an existing protective device, otherwise Ib. + */ + designCurrentA: number; + /** Tabulated temperature/grouping actually used (rounded to the safe side). */ + temperatureUsedC: number | null; + groupingUsed: number | null; + temperatureFactor: number | null; + groupingFactor: number | null; + crossSectionByCapacityMm2: number | null; + crossSectionByVoltageDropMm2: number | null; + recommendedCrossSectionMm2: number | null; + voltageDropAtRecommendedPercent: number | null; + combinedDerationFactor: number; + harmonicReductionApplied: boolean; + practicalMinimumApplied: boolean; + rows: CrossSectionRow[]; + protectionCoordination: ProtectionCoordinationResult | null; +} + +function operatingCurrentA(input: CableSizingInput): number { + if (input.mode === "current") { + return input.currentA ?? 0; + } + const powerW = (input.powerKw ?? 0) * 1000; + return input.phase === 1 + ? powerW / (input.voltage * input.cosPhi) + : powerW / (Math.sqrt(3) * input.voltage * input.cosPhi); +} + +export function calculateCableSizing(input: CableSizingInput): CableSizingResult { + const ib = operatingCurrentA(input); + const designCurrentA = input.existingProtection + ? Math.max(ib, minimumIzForProtection(input.existingProtection)) + : ib; + const group = LAYING_METHOD_GROUP[input.layingMethod]; + const temperature = lookupConservative( + TEMPERATURE_FACTORS[group][input.insulation], + input.ambientTemperatureC + ); + const grouping = + input.groupingCircuits <= MAX_GROUPING_CIRCUITS + ? lookupConservative(groupingTableFor(input.layingMethod), Math.max(1, input.groupingCircuits)) + : null; + + const empty: CableSizingResult = { + supported: false, + unsupportedReason: !temperature ? "temperature" : "grouping", + operatingCurrentA: ib, + designCurrentA, + temperatureUsedC: temperature?.key ?? null, + groupingUsed: grouping?.key ?? null, + temperatureFactor: temperature?.factor ?? null, + groupingFactor: grouping?.factor ?? null, + crossSectionByCapacityMm2: null, + crossSectionByVoltageDropMm2: null, + recommendedCrossSectionMm2: null, + voltageDropAtRecommendedPercent: null, + combinedDerationFactor: 1, + harmonicReductionApplied: false, + practicalMinimumApplied: false, + rows: [], + protectionCoordination: null, + }; + if (!temperature || !grouping) { + return empty; + } + + const coreCount: CoreCount = input.phase === 1 ? 2 : 3; + const harmonicReductionApplied = + input.phase === 3 && input.harmonicNeutralLoad === "15to33Percent"; + const combinedDerationFactor = + temperature.factor * grouping.factor * (harmonicReductionApplied ? HARMONIC_REDUCTION_FACTOR : 1); + const voltageDropCoefficient = input.phase === 1 ? 2 : Math.sqrt(3); + const kappa = KAPPA[input.conductorMaterial]; + + const ratedCurrents = + CURRENT_CAPACITY_A[input.insulation][input.conductorMaterial][input.layingMethod][coreCount]; + const correctedCurrents = ratedCurrents.map((value) => + value == null ? null : value * combinedDerationFactor + ); + const voltageDrops = CROSS_SECTIONS_MM2.map( + (crossSection) => + ((voltageDropCoefficient * input.lengthM * ib * input.cosPhi) / (kappa * crossSection) / input.voltage) * 100 + ); + + const indexByCapacity = correctedCurrents.findIndex( + (value) => value != null && value >= designCurrentA + ); + const indexByVoltageDrop = voltageDrops.findIndex( + (value, index) => ratedCurrents[index] != null && value <= input.maxVoltageDropPercent + ); + let indexRecommended = + indexByCapacity >= 0 && indexByVoltageDrop >= 0 ? Math.max(indexByCapacity, indexByVoltageDrop) : -1; + + const practicalMinimumMm2 = input.circuitCategory + ? PRACTICAL_MINIMUM_CROSS_SECTION_MM2[input.circuitCategory] + : undefined; + let practicalMinimumApplied = false; + if (indexRecommended >= 0 && practicalMinimumMm2 != null && CROSS_SECTIONS_MM2[indexRecommended] < practicalMinimumMm2) { + const minimumIndex = CROSS_SECTIONS_MM2.indexOf(practicalMinimumMm2 as (typeof CROSS_SECTIONS_MM2)[number]); + if (minimumIndex >= 0 && ratedCurrents[minimumIndex] != null) { + indexRecommended = minimumIndex; + practicalMinimumApplied = true; + } + } + + const voltageDropCurrentBasis = ib * input.cosPhi; + const rows: CrossSectionRow[] = CROSS_SECTIONS_MM2.map((crossSection, index) => { + const rated = ratedCurrents[index]; + const corrected = correctedCurrents[index]; + return { + crossSectionMm2: crossSection, + ratedCurrentA: rated, + correctedCurrentA: corrected, + currentSufficient: corrected == null ? null : corrected >= designCurrentA, + voltageDropPercent: rated == null ? null : voltageDrops[index], + voltageDropSufficient: rated == null ? null : voltageDrops[index] <= input.maxVoltageDropPercent, + maxLengthForVoltageDropM: + rated == null || voltageDropCurrentBasis <= 0 + ? null + : (input.maxVoltageDropPercent * kappa * crossSection * input.voltage) / + (100 * voltageDropCoefficient * voltageDropCurrentBasis), + recommended: index === indexRecommended, + }; + }); + + let protectionCoordination: ProtectionCoordinationResult | null = null; + if (input.existingProtection && indexRecommended >= 0) { + const iz = rows[indexRecommended].correctedCurrentA; + const factor = conventionalTrippingFactor(input.existingProtection); + const inA = input.existingProtection.ratedCurrentA; + protectionCoordination = { + ratedCurrentA: inA, + kind: input.existingProtection.kind, + conventionalTrippingFactor: factor, + coordinated: iz != null && inA <= iz && factor * inA <= 1.45 * iz, + }; + } + + return { + ...empty, + supported: true, + unsupportedReason: null, + crossSectionByCapacityMm2: indexByCapacity >= 0 ? CROSS_SECTIONS_MM2[indexByCapacity] : null, + crossSectionByVoltageDropMm2: indexByVoltageDrop >= 0 ? CROSS_SECTIONS_MM2[indexByVoltageDrop] : null, + recommendedCrossSectionMm2: indexRecommended >= 0 ? CROSS_SECTIONS_MM2[indexRecommended] : null, + voltageDropAtRecommendedPercent: indexRecommended >= 0 ? voltageDrops[indexRecommended] : null, + combinedDerationFactor, + harmonicReductionApplied, + practicalMinimumApplied, + rows, + protectionCoordination, + }; +} + +// -- Alerts ------------------------------------------------------------------- + +export interface CableSizingAlert { + kind: "critical" | "warn" | "info" | "ok"; + text: string; +} + +const numberFormat = (value: number, digits = 1) => + value.toLocaleString("de-DE", { minimumFractionDigits: digits, maximumFractionDigits: digits }); +const crossSectionFormat = (value: number) => + `${value.toLocaleString("de-DE", { maximumFractionDigits: 1 })} mm²`; + +export function buildCableSizingAlerts(input: CableSizingInput, result: CableSizingResult): CableSizingAlert[] { + const alerts: CableSizingAlert[] = []; + const group = LAYING_METHOD_GROUP[input.layingMethod]; + + if (!result.supported) { + alerts.push({ + kind: "critical", + text: + result.unsupportedReason === "temperature" + ? `${group === "air" ? "Umgebungstemperatur" : "Bodentemperatur"} ${input.ambientTemperatureC} °C liegt außerhalb der Tabelle für ${input.insulation === "pvc" ? "PVC" : "VPE"} – keine Berechnung möglich.` + : `Häufung mit ${input.groupingCircuits} Stromkreisen liegt außerhalb der Tabelle (max. ${MAX_GROUPING_CIRCUITS}) – keine Berechnung möglich.`, + }); + return alerts; + } + + if (result.temperatureUsedC !== input.ambientTemperatureC) { + alerts.push({ + kind: "info", + text: `Temperatur auf den nächsten Tabellenwert ${result.temperatureUsedC} °C gerundet (sichere Seite).`, + }); + } + if (result.groupingUsed !== input.groupingCircuits) { + alerts.push({ + kind: "info", + text: `Häufung auf den nächsten Tabellenwert ${result.groupingUsed} Stromkreise gerundet (sichere Seite).`, + }); + } + + const byCapacity = result.crossSectionByCapacityMm2; + const byDrop = result.crossSectionByVoltageDropMm2; + if (byCapacity == null) { + const dueToProtection = + input.existingProtection != null && result.designCurrentA > result.operatingCurrentA; + alerts.push({ + kind: "critical", + text: dueToProtection + ? `Das vorhandene Schutzorgan (${input.existingProtection!.ratedCurrentA} A) verlangt Iz ≥ ${numberFormat(result.designCurrentA)} A – das erreicht bei Verlegeart ${input.layingMethod} kein Querschnitt bis 240 mm². Verlegeart oder Schutzorgan prüfen.` + : `Der Betriebsstrom ${numberFormat(result.operatingCurrentA)} A übersteigt bei Verlegeart ${input.layingMethod} die Belastbarkeit aller Querschnitte bis 240 mm².`, + }); + } else if (byDrop == null) { + alerts.push({ + kind: "critical", + text: `Der Spannungsfall von ${numberFormat(input.maxVoltageDropPercent)} % wird bei ${input.lengthM} m mit keinem Querschnitt bis 240 mm² eingehalten.`, + }); + } else if (byDrop > byCapacity) { + alerts.push({ + kind: "warn", + text: `Der Spannungsfall ist maßgeblich: ${crossSectionFormat(byCapacity)} reichen thermisch, für ΔU ≤ ${numberFormat(input.maxVoltageDropPercent)} % sind ${crossSectionFormat(byDrop)} nötig.`, + }); + } + if (result.harmonicReductionApplied) { + alerts.push({ + kind: "info", + text: "Reduktionsfaktor 0,86 wegen 15–33 % 3. Harmonischer im Neutralleiter angewendet.", + }); + } + if (input.phase === 3 && input.harmonicNeutralLoad === "over33Percent") { + alerts.push({ + kind: "warn", + text: "3. Harmonische > 33 %: Der Neutralleiter ist nach dem Neutralleiterstrom zu bemessen – hier nicht berücksichtigt.", + }); + } + if (group === "ground") { + alerts.push({ + kind: "info", + text: "Erdverlegung: Bodenwärmewiderstand 2,5 K·m/W angenommen (Tabellenreferenz).", + }); + } + if (result.practicalMinimumApplied) { + alerts.push({ + kind: "info", + text: `Auf ${crossSectionFormat(result.recommendedCrossSectionMm2!)} angehoben (Praxis-Mindestquerschnitt für 1-phasige Stromkreise, keine Rechenanforderung).`, + }); + } + if (result.protectionCoordination) { + const coordination = result.protectionCoordination; + const kindLabel = coordination.kind === "breaker" ? "Leitungsschutzschalter" : "Sicherung gG"; + alerts.push( + coordination.coordinated + ? { + kind: "info", + text: `Schutzorgan ${kindLabel} ${coordination.ratedCurrentA} A berücksichtigt: In ≤ Iz und I₂ = ${numberFormat(coordination.conventionalTrippingFactor, 2)} · In ≤ 1,45 · Iz. Kurzschlussschutz und Abschaltbedingungen sind nicht Teil dieser Berechnung.`, + } + : { + kind: "warn", + text: `Schutzorgan ${kindLabel} ${coordination.ratedCurrentA} A ist mit dem empfohlenen Querschnitt nicht koordiniert (In ≤ Iz, I₂ ≤ 1,45 · Iz).`, + } + ); + } + const recommendedRow = result.rows.find((row) => row.recommended); + if (recommendedRow && byCapacity != null && byDrop != null) { + if (!alerts.some((alert) => alert.kind === "warn" || alert.kind === "critical")) { + alerts.push({ + kind: "ok", + text: `${crossSectionFormat(recommendedRow.crossSectionMm2)} ${input.conductorMaterial === "aluminum" ? "Al" : "Cu"} erfüllt bei ${input.lengthM} m Belastbarkeit (${numberFormat(result.designCurrentA)} A) und Spannungsfall (ΔU ≤ ${numberFormat(input.maxVoltageDropPercent)} %).`, + }); + } + if (recommendedRow.maxLengthForVoltageDropM != null) { + alerts.push({ + kind: "info", + text: `Maximale Länge bei ${crossSectionFormat(recommendedRow.crossSectionMm2)} für ΔU ≤ ${numberFormat(input.maxVoltageDropPercent)} %: ${recommendedRow.maxLengthForVoltageDropM.toFixed(0)} m.`, + }); + } + } + return alerts; +} diff --git a/src/cable-sizing/domain/cable-sizing-contracts.ts b/src/cable-sizing/domain/cable-sizing-contracts.ts new file mode 100644 index 0000000..2a2cc02 --- /dev/null +++ b/src/cable-sizing/domain/cable-sizing-contracts.ts @@ -0,0 +1,47 @@ +// Request validation for the cable-sizing HTTP API. Pure - depends only on +// zod and the sibling calculation module, never on db/server. +import { z } from "zod"; +import { + CONDUCTOR_MATERIALS, + HARMONIC_NEUTRAL_LOAD_OPTIONS, + INSULATION_MATERIALS, + LAYING_METHODS, + PROTECTION_KINDS, + type CableSizingInput, +} from "./cable-sizing-calculation.js"; + +export const cableSizingRequestSchema = z + .object({ + phase: z.union([z.literal(1), z.literal(3)]), + mode: z.enum(["power", "current"]), + powerKw: z.number().finite().min(0).optional(), + currentA: z.number().finite().min(0).optional(), + cosPhi: z.number().finite().min(0.1).max(1), + voltage: z.number().finite().positive(), + lengthM: z.number().finite().min(0).max(10000), + layingMethod: z.enum(LAYING_METHODS), + conductorMaterial: z.enum(CONDUCTOR_MATERIALS), + insulation: z.enum(INSULATION_MATERIALS), + ambientTemperatureC: z.number().finite().min(-40).max(120), + groupingCircuits: z.number().int().min(1).max(100), + maxVoltageDropPercent: z.number().finite().min(0.5).max(10), + harmonicNeutralLoad: z.enum(HARMONIC_NEUTRAL_LOAD_OPTIONS), + existingProtection: z + .object({ + ratedCurrentA: z.number().finite().positive(), + kind: z.enum(PROTECTION_KINDS), + }) + .strict() + .optional(), + circuitCategory: z.enum(["lighting", "single_phase", "three_phase"]).optional(), + }) + .strict() + .refine((value) => (value.mode === "power" ? value.powerKw != null : value.currentA != null), { + message: "powerKw is required for mode 'power', currentA for mode 'current'", + }); + +export type CableSizingRequest = z.infer; + +// The request schema must stay assignable to the domain input shape. +type AssertAssignable = T; +export type CableSizingRequestIsDomainInput = AssertAssignable; diff --git a/src/frontend/components/cable-sizing-api.ts b/src/frontend/components/cable-sizing-api.ts new file mode 100644 index 0000000..28530d2 --- /dev/null +++ b/src/frontend/components/cable-sizing-api.ts @@ -0,0 +1,37 @@ +// Thin fetch client for the cable-sizing module, kept separate from +// ../utils/api.ts so the module stays self-contained (see +// docs/cable-sizing-module.md). +import type { + CableSizingAlert, + CableSizingInput, + CableSizingResult, +} from "../../cable-sizing/domain/cable-sizing-calculation"; + +export interface CalculateCableSizingResponse { + result: CableSizingResult; + alerts: CableSizingAlert[]; +} + +export async function calculateCableSizing( + input: CableSizingInput +): Promise { + const response = await fetch("/api/cable-sizing/calculate", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(input), + cache: "no-store", + }); + if (!response.ok) { + let details = await response.text(); + try { + const parsed = JSON.parse(details) as { error?: unknown }; + if (typeof parsed.error === "string") { + details = parsed.error; + } + } catch { + // keep raw text + } + throw new Error(details || `Anfrage fehlgeschlagen (Status ${response.status})`); + } + return response.json() as Promise; +} diff --git a/src/frontend/components/cable-sizing-defaults.ts b/src/frontend/components/cable-sizing-defaults.ts new file mode 100644 index 0000000..ae4c7a4 --- /dev/null +++ b/src/frontend/components/cable-sizing-defaults.ts @@ -0,0 +1,54 @@ +// Derives the cable-sizing inputs that follow from the circuit itself, so the +// planner starts from the circuit's real values instead of fixed defaults. +import type { + CircuitCategory, + ExistingProtection, +} from "../../cable-sizing/domain/cable-sizing-calculation"; +import type { CircuitTreeCircuitDto, CircuitTreeProtectionDeviceDto } from "../types"; + +/** Three-phase if the circuit group or any device row is three-phase. */ +export function deriveCircuitPhase( + circuit: CircuitTreeCircuitDto, + circuitCategory?: CircuitCategory +): 1 | 3 { + return circuitCategory === "three_phase" || + circuit.deviceRows.some((row) => row.phaseType === "three_phase") + ? 3 + : 1; +} + +/** + * Power-weighted cos φ of the circuit: P / S with S = Σ P_row / cos φ_row. + * Rows without cos φ count as 1; a circuit without load yields 1. + */ +export function deriveCircuitCosPhi(circuit: CircuitTreeCircuitDto): number { + let activePowerKw = 0; + let apparentPowerKva = 0; + for (const row of circuit.deviceRows) { + activePowerKw += row.rowTotalPower; + apparentPowerKva += row.rowTotalPower / (row.cosPhi || 1); + } + if (activePowerKw <= 0 || apparentPowerKva <= 0) { + return 1; + } + return Math.round((activePowerKw / apparentPowerKva) * 100) / 100; +} + +/** + * Maps the circuit's protective device to the overload-protection kind of the + * calculation. Circuit-breakers (LS, FI/LS, AFDD) are "breaker", D0 and NH + * fuse links "fuse"; a residual-current device without overcurrent release + * (FI) provides no overload protection and is ignored. + */ +export function toExistingProtection( + protection: CircuitTreeProtectionDeviceDto | undefined +): ExistingProtection | undefined { + if (!protection || protection.type === "FI") { + return undefined; + } + const kind = + protection.type === "LS" || protection.type === "FI_LS" || protection.type === "AFDD" + ? "breaker" + : "fuse"; + return { ratedCurrentA: protection.ratedCurrentA, kind }; +} diff --git a/src/frontend/components/cable-sizing-modal.tsx b/src/frontend/components/cable-sizing-modal.tsx new file mode 100644 index 0000000..deb01b2 --- /dev/null +++ b/src/frontend/components/cable-sizing-modal.tsx @@ -0,0 +1,571 @@ +"use client"; + +import { type FormEvent, useMemo, useState } from "react"; +import { + CONDUCTOR_MATERIALS, + CROSS_SECTIONS_MM2, + HARMONIC_NEUTRAL_LOAD_LABELS, + HARMONIC_NEUTRAL_LOAD_OPTIONS, + INSULATION_MATERIALS, + INSULATION_MATERIAL_LABELS, + LAYING_METHODS, + LAYING_METHOD_GROUP, + LAYING_METHOD_LABELS, + MAX_GROUPING_CIRCUITS, + PRACTICAL_MINIMUM_CROSS_SECTION_MM2, + REFERENCE_TEMPERATURE_C, + temperatureOptions, + type CableSizingAlert, + type CableSizingInput, + type CableSizingResult, + type CircuitCategory, + type ConductorMaterial, + type HarmonicNeutralLoad, + type InsulationMaterial, + type LayingMethod, +} from "../../cable-sizing/domain/cable-sizing-calculation"; +import { calculateCableSizing } from "./cable-sizing-api"; +import type { CircuitTreeCircuitDto } from "../types"; +import { + deriveCircuitCosPhi, + deriveCircuitPhase, + toExistingProtection, +} from "./cable-sizing-defaults"; +import { FormModal } from "./form-modal"; + +interface CableSizingModalProps { + circuit: CircuitTreeCircuitDto; + circuitCategory?: CircuitCategory; + singlePhaseVoltageV: number; + threePhaseVoltageV: number; + isSaving: boolean; + onClose: () => void; + onApply: (patch: { + cableCrossSection: string; + cableType?: string; + cableLength?: number; + }) => Promise; +} + +// Extracts the first decimal number from a free-text cross-section entry +// like "2.5 mm²" or "2,5"; used only for the manual-entry sanity check. +function parseCrossSectionMm2(text: string): number | null { + const match = text.match(/([0-9]+(?:[.,][0-9]+)?)/); + if (!match) return null; + const value = Number(match[1].replace(",", ".")); + return Number.isFinite(value) ? value : null; +} + +const formatNumber = (value: number, digits: number) => + value.toLocaleString("de-DE", { minimumFractionDigits: digits, maximumFractionDigits: digits }); + +export function CableSizingModal({ + circuit, + circuitCategory, + singlePhaseVoltageV, + threePhaseVoltageV, + isSaving, + onClose, + onApply, +}: CableSizingModalProps) { + const derivedPhase = deriveCircuitPhase(circuit, circuitCategory); + const derivedCosPhi = deriveCircuitCosPhi(circuit); + const existingProtection = toExistingProtection(circuit.protectionDevice); + + const [layingMethod, setLayingMethod] = useState("C"); + const [insulation, setInsulation] = useState("pvc"); + const [conductorMaterial, setConductorMaterial] = useState("copper"); + const [ambientTemperatureC, setAmbientTemperatureC] = useState(30); + const [groupingCircuits, setGroupingCircuits] = useState(1); + const [cosPhi, setCosPhi] = useState(derivedCosPhi); + const [maxVoltageDropPercent, setMaxVoltageDropPercent] = useState(3); + const [harmonicNeutralLoad, setHarmonicNeutralLoad] = useState("none"); + const [lengthM, setLengthM] = useState(circuit.cableLength ?? 0); + const [phase, setPhase] = useState<1 | 3>(derivedPhase); + + // Manual entry: applying never requires a calculation. Prefilled from the + // circuit so an existing cable specification is not lost. + const [manualCableType, setManualCableType] = useState(circuit.cableType ?? ""); + const [manualCrossSection, setManualCrossSection] = useState(circuit.cableCrossSection ?? ""); + + const [calculating, setCalculating] = useState(false); + const [result, setResult] = useState(null); + const [alerts, setAlerts] = useState([]); + const [error, setError] = useState(null); + + const voltage = + phase === derivedPhase && circuit.voltage + ? circuit.voltage + : phase === 3 + ? threePhaseVoltageV + : singlePhaseVoltageV; + const group = LAYING_METHOD_GROUP[layingMethod]; + const availableTemperatures = temperatureOptions(layingMethod, insulation); + + const input: CableSizingInput = useMemo( + () => ({ + phase, + mode: "power", + powerKw: circuit.circuitTotalPower, + cosPhi, + voltage, + lengthM, + layingMethod, + conductorMaterial, + insulation, + ambientTemperatureC, + groupingCircuits, + maxVoltageDropPercent, + harmonicNeutralLoad, + existingProtection, + circuitCategory, + }), + [ + phase, + circuit.circuitTotalPower, + cosPhi, + voltage, + lengthM, + layingMethod, + conductorMaterial, + insulation, + ambientTemperatureC, + groupingCircuits, + maxVoltageDropPercent, + harmonicNeutralLoad, + existingProtection?.ratedCurrentA, + existingProtection?.kind, + circuitCategory, + ] + ); + + const manualCrossSectionWarning = useMemo(() => { + const trimmed = manualCrossSection.trim(); + if (!trimmed) return null; + const parsed = parseCrossSectionMm2(trimmed); + if (parsed == null) return null; + if (!(CROSS_SECTIONS_MM2 as readonly number[]).includes(parsed)) { + return `${formatNumber(parsed, parsed % 1 ? 1 : 0)} mm² ist kein Normquerschnitt (${CROSS_SECTIONS_MM2.map((value) => formatNumber(value, value % 1 ? 1 : 0)).join(", ")}).`; + } + if ( + result?.supported && + result.recommendedCrossSectionMm2 != null && + parsed < result.recommendedCrossSectionMm2 + ) { + return `${formatNumber(parsed, parsed % 1 ? 1 : 0)} mm² ist kleiner als die zuletzt berechnete Empfehlung (${formatNumber(result.recommendedCrossSectionMm2, result.recommendedCrossSectionMm2 % 1 ? 1 : 0)} mm²).`; + } + const practicalMinimum = circuitCategory + ? PRACTICAL_MINIMUM_CROSS_SECTION_MM2[circuitCategory] + : undefined; + if (practicalMinimum != null && parsed < practicalMinimum) { + return `${formatNumber(parsed, parsed % 1 ? 1 : 0)} mm² liegt unter dem Praxis-Mindestquerschnitt für 1-phasige Stromkreise (${formatNumber(practicalMinimum, 1)} mm²).`; + } + return null; + }, [manualCrossSection, result, circuitCategory]); + + function resetResult() { + setResult(null); + setAlerts([]); + } + + function applyReferenceTemperature(method: LayingMethod, material: InsulationMaterial) { + const options = temperatureOptions(method, material); + const reference = REFERENCE_TEMPERATURE_C[LAYING_METHOD_GROUP[method]]; + setAmbientTemperatureC(options.includes(reference) ? reference : options[0]); + } + + async function handleCalculate() { + setCalculating(true); + setError(null); + try { + const response = await calculateCableSizing(input); + setResult(response.result); + setAlerts(response.alerts); + // The suggestion fills the manual field, which stays the single source + // of truth for what gets applied. + if (response.result.supported && response.result.recommendedCrossSectionMm2) { + const size = response.result.recommendedCrossSectionMm2; + setManualCrossSection(`${formatNumber(size, size % 1 ? 1 : 0)} mm²`); + } + } catch (err) { + setError(err instanceof Error ? err.message : "Berechnung fehlgeschlagen"); + } finally { + setCalculating(false); + } + } + + async function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (!manualCrossSection.trim()) return; + await onApply({ + cableCrossSection: manualCrossSection.trim(), + cableType: manualCableType.trim() || undefined, + cableLength: lengthM, + }); + } + + const recommendedRow = result?.rows.find((row) => row.recommended); + + return ( + +
+
+ + { + setLengthM(Number(event.target.value)); + resetResult(); + }} + type="number" + value={lengthM} + /> +
+
+ + + {phase !== derivedPhase ? ( +
+ Abweichend vom Stromkreis ({derivedPhase === 3 ? "3~" : "1~"}). +
+ ) : null} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + { + setGroupingCircuits(Math.max(1, Math.round(Number(event.target.value) || 1))); + resetResult(); + }} + step={1} + type="number" + value={groupingCircuits} + /> +
+ Anzahl gemeinsam verlegter Stromkreise, einschließlich dieses. +
+
+ {phase === 3 ? ( +
+ + +
+ ) : null} +
+ + { + setCosPhi(Math.min(1, Math.max(0.1, Number(event.target.value) || 1))); + resetResult(); + }} + step={0.01} + type="number" + value={cosPhi} + /> +
+ Aus den Gerätezeilen: {formatNumber(derivedCosPhi, 2)} +
+
+
+ + { + setMaxVoltageDropPercent(Number(event.target.value) || 3); + resetResult(); + }} + step={0.5} + type="number" + value={maxVoltageDropPercent} + /> +
+
+
+ Schutzorgan:{" "} + {existingProtection + ? `${existingProtection.kind === "breaker" ? "Leitungsschutzschalter" : "Sicherung gG"} ${existingProtection.ratedCurrentA} A (aus dem Stromkreis, In ≤ Iz und I₂ ≤ 1,45 · Iz)` + : "keines mit Überstromschutz hinterlegt – Bemessung nur nach Betriebsstrom"} +
+
+
+ + + {error ?

{error}

: null} + + {result ? ( +
+ {result.supported ? ( +
+
+
Betriebsstrom IB
+
{formatNumber(result.operatingCurrentA, 1)} A
+
+
+
Erforderliches Iz
+
+ {formatNumber(result.designCurrentA, 1)} A +
+
+
+
Empfohlener Querschnitt
+
+ + {result.recommendedCrossSectionMm2 != null + ? `${formatNumber(result.recommendedCrossSectionMm2, result.recommendedCrossSectionMm2 % 1 ? 1 : 0)} mm²` + : "–"} + +
+
+
+
ΔU bei Empfehlung
+
+ {result.voltageDropAtRecommendedPercent != null + ? `${formatNumber(result.voltageDropAtRecommendedPercent, 2)} %` + : "–"} +
+
+
+
Korrekturfaktor gesamt
+
{formatNumber(result.combinedDerationFactor, 2)}
+
+
+
Temperatur / Häufung (gerechnet)
+
+ {result.temperatureUsedC} °C ({formatNumber(result.temperatureFactor ?? 1, 2)}) /{" "} + {result.groupingUsed} ({formatNumber(result.groupingFactor ?? 1, 2)}) +
+
+
+
Max. Länge für ΔU
+
+ {recommendedRow?.maxLengthForVoltageDropM != null + ? `${recommendedRow.maxLengthForVoltageDropM.toFixed(0)} m` + : "–"} +
+
+
+ ) : null} + {alerts.map((alert, index) => ( +
+ {alert.text} +
+ ))} +
+ ) : null} + +
+

+ Kabeltyp und Querschnitt direkt eingeben oder die Empfehlung übernehmen. + Beides landet in denselben Feldern und kann vor dem Übernehmen angepasst + werden. +

+
+
+ + setManualCableType(event.target.value)} + placeholder="z. B. NYM-J 3x2,5" + value={manualCableType} + /> +
+
+ + setManualCrossSection(event.target.value)} + placeholder="z. B. 4 mm²" + value={manualCrossSection} + /> +
+ {manualCrossSectionWarning ? ( +
+
{manualCrossSectionWarning}
+
+ ) : null} +
+
+ ); +} diff --git a/src/frontend/components/circuit-tree-editor.tsx b/src/frontend/components/circuit-tree-editor.tsx index e559303..6851122 100644 --- a/src/frontend/components/circuit-tree-editor.tsx +++ b/src/frontend/components/circuit-tree-editor.tsx @@ -5,6 +5,7 @@ import { ArrowDown, ArrowDown01, ArrowUp, + Calculator, Check, Columns3, FilterX, @@ -160,6 +161,7 @@ import type { import { DistributionBoardComponentModal } from "./distribution-board-component-modal"; import { CircuitGroupModal } from "./circuit-group-modal"; import { CircuitProtectionModal } from "./circuit-protection-modal"; +import { CableSizingModal } from "./cable-sizing-modal"; import { circuitGroupCategoryLabels, type CircuitGroupCategory, @@ -319,6 +321,8 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str useState(null); const [protectionEditorCircuit, setProtectionEditorCircuit] = useState(null); + const [cableSizingEditorCircuit, setCableSizingEditorCircuit] = + useState(null); const [projectDevices, setProjectDevices] = useState([]); const [isProjectDeviceDrawerOpen, setIsProjectDeviceDrawerOpen] = useState(false); @@ -1439,6 +1443,31 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str }); } + async function handleApplyCableSizing(patch: { + cableCrossSection: string; + cableType?: string; + cableLength?: number; + }) { + const circuit = cableSizingEditorCircuit; + if (!circuit) { + return; + } + await runCommand({ + label: "Leitungsberechnung übernehmen", + redo: async () => { + const result = await updateCircuitById( + projectId, + getExpectedProjectRevision(), + circuit.id, + patch + ); + applyProjectCommandResult(result); + setCableSizingEditorCircuit(null); + return null; + }, + }); + } + async function handleRedo() { if (historyBusy || isSaving || !historyState || historyState.redoDepth === 0) { return; @@ -3185,6 +3214,21 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str onSave={handleSaveCircuitProtection} /> ) : null} + {cableSizingEditorCircuit ? ( + section.id === cableSizingEditorCircuit.sectionId + )?.category + } + isSaving={isSaving} + onApply={handleApplyCableSizing} + onClose={() => setCableSizingEditorCircuit(null)} + singlePhaseVoltageV={data.singlePhaseVoltageV} + threePhaseVoltageV={data.threePhaseVoltageV} + /> + ) : null}
{row.circuit && row.rowType !== "deviceRow" ? ( <> + setCableSizingEditorCircuit(row.circuit!)} + tabIndex={-1} + title="Leitungsberechnung: Querschnitt ermitteln oder Kabel eintragen" + /> ({ method, label: LAYING_METHOD_LABELS[method] })) + ); +} + +export function listInsulationMaterialsHandler(_req: Request, res: Response) { + return res.json( + INSULATION_MATERIALS.map((insulation) => ({ + insulation, + label: INSULATION_MATERIAL_LABELS[insulation], + })) + ); +} diff --git a/src/server/index.ts b/src/server/index.ts index 1f5c9b2..02c5cdc 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -2,6 +2,7 @@ import express from "express"; import { globalDeviceRouter } from "./routes/global-device.routes.js"; import { projectDeviceRouter } from "./routes/project-device.routes.js"; import { projectRouter } from "./routes/project.routes.js"; +import { cableSizingRouter } from "./routes/cable-sizing.routes.js"; import { errorMiddleware } from "./middleware/error.middleware.js"; import { createLogger, toErrorMeta } from "../shared/logging/logger.js"; import { closeDefaultDatabase } from "../db/client.js"; @@ -48,6 +49,7 @@ app.get("/health", (_req, res) => { res.json({ ok: true }); }); +app.use("/api/cable-sizing", cableSizingRouter); app.use("/api/projects", projectRouter); app.use("/api/global-devices", globalDeviceRouter); app.use("/api/project-devices", projectDeviceRouter); diff --git a/src/server/routes/cable-sizing.routes.ts b/src/server/routes/cable-sizing.routes.ts new file mode 100644 index 0000000..485e9c1 --- /dev/null +++ b/src/server/routes/cable-sizing.routes.ts @@ -0,0 +1,9 @@ +import express from "express"; +import * as cableSizingController from "../controllers/cable-sizing.controller.js"; + +// Stateless calculator endpoints; no project data is read or written here. +export const cableSizingRouter = express.Router(); + +cableSizingRouter.post("/calculate", cableSizingController.calculateCableSizingHandler); +cableSizingRouter.get("/laying-methods", cableSizingController.listLayingMethodsHandler); +cableSizingRouter.get("/insulation-materials", cableSizingController.listInsulationMaterialsHandler); diff --git a/tests/cable-sizing-calculation.test.ts b/tests/cable-sizing-calculation.test.ts new file mode 100644 index 0000000..05e4f3d --- /dev/null +++ b/tests/cable-sizing-calculation.test.ts @@ -0,0 +1,274 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + buildCableSizingAlerts, + calculateCableSizing, + conventionalTrippingFactor, + CROSS_SECTIONS_MM2, + CURRENT_CAPACITY_A, + minimumIzForProtection, + temperatureOptions, + type CableSizingInput, +} from "../src/cable-sizing/domain/cable-sizing-calculation.js"; +import { cableSizingRequestSchema } from "../src/cable-sizing/domain/cable-sizing-contracts.js"; +import { + deriveCircuitCosPhi, + deriveCircuitPhase, + toExistingProtection, +} from "../src/frontend/components/cable-sizing-defaults.js"; +import type { CircuitTreeCircuitDto } from "../src/frontend/types.js"; + +const BASE_INPUT: CableSizingInput = { + phase: 1, + mode: "power", + powerKw: 5, + cosPhi: 1, + voltage: 230, + lengthM: 30, + layingMethod: "C", + conductorMaterial: "copper", + insulation: "pvc", + ambientTemperatureC: 30, + groupingCircuits: 1, + maxVoltageDropPercent: 3, + harmonicNeutralLoad: "none", +}; + +const capacity = ( + insulation: "pvc" | "xlpe", + material: "copper" | "aluminum", + method: keyof (typeof CURRENT_CAPACITY_A)["pvc"]["copper"], + cores: 2 | 3, + crossSection: number +) => + CURRENT_CAPACITY_A[insulation][material][method][cores][ + CROSS_SECTIONS_MM2.indexOf(crossSection as (typeof CROSS_SECTIONS_MM2)[number]) + ]; + +describe("cable sizing reference tables (IEC 60364-5-52 Annex B)", () => { + it("contains the checked PVC copper values", () => { + // B.52.2: A1 two loaded conductors (the previously wrong row) + assert.equal(capacity("pvc", "copper", "A1", 2, 2.5), 19.5); + assert.equal(capacity("pvc", "copper", "A1", 2, 16), 61); + assert.equal(capacity("pvc", "copper", "A1", 2, 120), 210); + // B.52.2: B2 from 50 mm² (previously copied from B1) + assert.equal(capacity("pvc", "copper", "B2", 2, 50), 133); + assert.equal(capacity("pvc", "copper", "B2", 2, 120), 232); + // B.52.4 and D1/D2 + assert.equal(capacity("pvc", "copper", "C", 3, 6), 41); + assert.equal(capacity("pvc", "copper", "D1", 2, 2.5), 29); + assert.equal(capacity("pvc", "copper", "D2", 3, 16), 70); + // Conflicting sources resolved to the lower value + assert.equal(capacity("pvc", "copper", "A1", 2, 240), 320); + assert.equal(capacity("pvc", "copper", "E", 3, 70), 196); + }); + + it("uses the aluminium and XLPE tables instead of flat factors", () => { + assert.equal(capacity("pvc", "aluminum", "A1", 2, 1.5), null); + assert.equal(capacity("pvc", "aluminum", "C", 3, 16), 59); + assert.equal(capacity("pvc", "aluminum", "D2", 2, 10), null); + assert.equal(capacity("xlpe", "copper", "C", 2, 2.5), 33); + assert.equal(capacity("xlpe", "aluminum", "E", 3, 25), 97); + }); + + it("has a complete, increasing row for every combination", () => { + for (const insulation of ["pvc", "xlpe"] as const) { + for (const material of ["copper", "aluminum"] as const) { + for (const [method, rows] of Object.entries(CURRENT_CAPACITY_A[insulation][material])) { + for (const cores of [2, 3] as const) { + const row = rows[cores]; + assert.equal(row.length, CROSS_SECTIONS_MM2.length, `${insulation}/${material}/${method}/${cores}`); + const values = row.filter((value): value is number => value != null); + for (let index = 1; index < values.length; index += 1) { + assert.ok(values[index] > values[index - 1], `${insulation}/${material}/${method}/${cores}`); + } + } + } + } + } + }); +}); + +describe("calculateCableSizing", () => { + it("sizes the reference case (1~, 5 kW, 230 V, 30 m, method C, Cu/PVC)", () => { + const result = calculateCableSizing(BASE_INPUT); + assert.equal(result.supported, true); + assert.ok(Math.abs(result.operatingCurrentA - 21.739) < 0.01); + assert.equal(result.crossSectionByCapacityMm2, 2.5); + assert.equal(result.crossSectionByVoltageDropMm2, 4); + assert.equal(result.recommendedCrossSectionMm2, 4); + const recommended = result.rows.find((row) => row.recommended)!; + // The maximum length is the inverse of the voltage-drop formula. + const atMaximum = calculateCableSizing({ + ...BASE_INPUT, + lengthM: recommended.maxLengthForVoltageDropM!, + }); + assert.ok(Math.abs(atMaximum.rows.find((row) => row.crossSectionMm2 === 4)!.voltageDropPercent! - 3) < 1e-9); + }); + + it("rounds temperature and grouping to the next tabulated, safer value", () => { + const warm = calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 32 }); + assert.equal(warm.temperatureUsedC, 35); + assert.equal(warm.temperatureFactor, 0.94); + const cold = calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 5 }); + assert.equal(cold.temperatureUsedC, 10); + assert.equal(cold.temperatureFactor, 1.22); + const grouped = calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 10 }); + assert.equal(grouped.groupingUsed, 12); + assert.equal(grouped.groupingFactor, 0.45); + const alerts = buildCableSizingAlerts({ ...BASE_INPUT, groupingCircuits: 10 }, grouped); + assert.ok(alerts.some((alert) => alert.text.includes("12 Stromkreise gerundet"))); + }); + + it("uses the PVC 70 °C air factors, not the 60 °C column", () => { + assert.equal(calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 20 }).temperatureFactor, 1.12); + assert.equal(calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 50 }).temperatureFactor, 0.71); + assert.equal( + calculateCableSizing({ ...BASE_INPUT, insulation: "xlpe", ambientTemperatureC: 65 }).temperatureFactor, + 0.65 + ); + }); + + it("uses the ground tables for D1 (ducts) and D2 (direct)", () => { + const d1 = calculateCableSizing({ ...BASE_INPUT, layingMethod: "D1", ambientTemperatureC: 20, groupingCircuits: 10 }); + assert.equal(d1.groupingFactor, 0.49); + const d2 = calculateCableSizing({ ...BASE_INPUT, layingMethod: "D2", ambientTemperatureC: 20, groupingCircuits: 10 }); + assert.equal(d2.groupingUsed, 12); + assert.equal(d2.groupingFactor, 0.36); + assert.equal(calculateCableSizing({ ...BASE_INPUT, layingMethod: "D2", ambientTemperatureC: 30 }).temperatureFactor, 0.89); + }); + + it("refuses inputs outside the tables instead of assuming a factor of 1", () => { + const hot = calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 65 }); + assert.equal(hot.supported, false); + assert.equal(hot.unsupportedReason, "temperature"); + assert.equal(hot.recommendedCrossSectionMm2, null); + assert.equal(buildCableSizingAlerts({ ...BASE_INPUT, ambientTemperatureC: 65 }, hot)[0]?.kind, "critical"); + const crowded = calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 21 }); + assert.equal(crowded.supported, false); + assert.equal(crowded.unsupportedReason, "grouping"); + }); + + it("never recommends a cross-section without tabulated capacity", () => { + const result = calculateCableSizing({ + ...BASE_INPUT, + powerKw: 0.5, + lengthM: 5, + conductorMaterial: "aluminum", + }); + assert.equal(result.recommendedCrossSectionMm2, 2.5); + assert.equal(result.rows[0].ratedCurrentA, null); + assert.equal(result.rows[0].recommended, false); + }); + + it("checks gG fuses with I2 = 1.6 In and circuit-breakers with In ≤ Iz", () => { + assert.equal(conventionalTrippingFactor({ kind: "breaker", ratedCurrentA: 16 }), 1.45); + assert.equal(conventionalTrippingFactor({ kind: "fuse", ratedCurrentA: 16 }), 1.6); + assert.equal(conventionalTrippingFactor({ kind: "fuse", ratedCurrentA: 10 }), 1.9); + assert.equal(conventionalTrippingFactor({ kind: "fuse", ratedCurrentA: 4 }), 2.1); + assert.ok(Math.abs(minimumIzForProtection({ kind: "fuse", ratedCurrentA: 16 }) - 17.655) < 0.01); + + // At 40 °C: 1.5 mm² (C, 2 loaded) carries 19.5 × 0.87 = 16.97 A. + const input = { ...BASE_INPUT, powerKw: 1, lengthM: 5, ambientTemperatureC: 40 }; + const breaker = calculateCableSizing({ ...input, existingProtection: { kind: "breaker", ratedCurrentA: 16 } }); + assert.equal(breaker.recommendedCrossSectionMm2, 1.5); + assert.equal(breaker.protectionCoordination?.coordinated, true); + const fuse = calculateCableSizing({ ...input, existingProtection: { kind: "fuse", ratedCurrentA: 16 } }); + assert.equal(fuse.recommendedCrossSectionMm2, 2.5); + assert.equal(fuse.protectionCoordination?.coordinated, true); + }); + + it("applies the 0.86 harmonic factor only for three-phase circuits with 15–33 %", () => { + const three = calculateCableSizing({ ...BASE_INPUT, phase: 3, voltage: 400, harmonicNeutralLoad: "15to33Percent" }); + assert.equal(three.harmonicReductionApplied, true); + assert.ok(Math.abs(three.combinedDerationFactor - 0.86) < 1e-9); + const single = calculateCableSizing({ ...BASE_INPUT, harmonicNeutralLoad: "15to33Percent" }); + assert.equal(single.harmonicReductionApplied, false); + }); + + it("raises single-phase circuits to the 2.5 mm² practical minimum", () => { + const result = calculateCableSizing({ + ...BASE_INPUT, + powerKw: 1, + lengthM: 5, + circuitCategory: "single_phase", + }); + assert.equal(result.recommendedCrossSectionMm2, 2.5); + assert.equal(result.practicalMinimumApplied, true); + const alerts = buildCableSizingAlerts({ ...BASE_INPUT, powerKw: 1, lengthM: 5, circuitCategory: "single_phase" }, result); + assert.ok(alerts.some((alert) => alert.text.includes("Auf 2,5 mm² angehoben"))); + assert.ok(!alerts.some((alert) => /d.d mm²/.test(alert.text))); + }); + + it("offers only tabulated temperatures", () => { + assert.deepEqual(temperatureOptions("C", "pvc").at(-1), 60); + assert.deepEqual(temperatureOptions("C", "xlpe").at(-1), 80); + assert.deepEqual(temperatureOptions("D1", "pvc")[2], 20); + }); +}); + +describe("cable sizing request schema", () => { + it("accepts a complete request and rejects unknown or legacy fields", () => { + assert.equal(cableSizingRequestSchema.safeParse(BASE_INPUT).success, true); + assert.equal( + cableSizingRequestSchema.safeParse({ ...BASE_INPUT, existingProtection: { kind: "fuse", ratedCurrentA: 25 } }).success, + true + ); + assert.equal( + cableSizingRequestSchema.safeParse({ ...BASE_INPUT, existingProtectionRatedCurrentA: 16 }).success, + false + ); + assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, layingMethod: "F" }).success, false); + assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, mode: "current" }).success, false); + }); +}); + +describe("cable sizing defaults from the circuit", () => { + const circuit = (rows: Array<{ power: number; cosPhi?: number; phaseType?: string }>): CircuitTreeCircuitDto => ({ + id: "circuit", + circuitListId: "list", + sectionId: "section", + equipmentIdentifier: "-2F1.1", + sortOrder: 1, + isReserve: rows.length === 0, + circuitTotalPower: rows.reduce((sum, row) => sum + row.power, 0), + deviceRows: rows.map((row, index) => ({ + id: `row-${index}`, + sortOrder: index, + name: "Gerät", + displayName: "Gerät", + quantity: 1, + manualQuantity: 1, + powerPerUnit: row.power, + simultaneityFactor: 1, + rowTotalPower: row.power, + cosPhi: row.cosPhi, + phaseType: row.phaseType, + })), + }); + + it("derives a power-weighted cos φ", () => { + // P = 3 kW, S = 2 / 0.8 + 1 / 1 = 3.5 kVA → 0.857 + assert.equal(deriveCircuitCosPhi(circuit([{ power: 2, cosPhi: 0.8 }, { power: 1 }])), 0.86); + assert.equal(deriveCircuitCosPhi(circuit([])), 1); + }); + + it("derives the phase from the group category or three-phase rows", () => { + assert.equal(deriveCircuitPhase(circuit([{ power: 1, phaseType: "single_phase" }]), "single_phase"), 1); + assert.equal(deriveCircuitPhase(circuit([{ power: 1, phaseType: "three_phase" }]), "single_phase"), 3); + assert.equal(deriveCircuitPhase(circuit([]), "three_phase"), 3); + }); + + it("maps protective devices to the overload-protection kind", () => { + assert.deepEqual(toExistingProtection({ type: "LS", ratedCurrentA: 16, tripCharacteristic: "B" }), { + kind: "breaker", + ratedCurrentA: 16, + }); + assert.deepEqual(toExistingProtection({ type: "NH00", ratedCurrentA: 63, fuseUtilizationCategory: "gG" }), { + kind: "fuse", + ratedCurrentA: 63, + }); + assert.equal(toExistingProtection({ type: "FI", ratedCurrentA: 40, rcdType: "A", ratedResidualCurrentMa: 30 }), undefined); + assert.equal(toExistingProtection(undefined), undefined); + }); +}); From 37a70b6b363959d3018c48d5c40b94e1d25a3163 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Sat, 26 Sep 2026 14:50:48 +0200 Subject: [PATCH 02/38] Add the rough power balance module for early design phases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In LPH 2/3 there are no circuits yet, but the office needs a power balance by DIN 276 cost group, as in the Excel template "Leistungsbilanz - KG400": each trade enters consumers by piece or by area (W/m²) with GLF and cos phi; the balance sums AV and SV per cost group, adds a reserve and derives the maximum current. The module is separate from the circuit structure: own tables (migration 0010), own folder src/estimate-balance and an import-free shared calculation used by API and UI. Writes go through project commands (estimate-balance.insert/.update/.delete with complete documents), so revision checks and Undo/Redo apply; it is not part of project snapshots or transfer yet. A comparison endpoint sums the device rows of all circuit lists by cost group (longest prefix) against the estimate. The UI adds a sidebar entry, a list of Stände (template KG 400, empty or copy) and a spreadsheet-like editor with autosave, AMEV picker for the GLF, totals, reserve, maximum current, comparison table and print layout. The tests reproduce the template example exactly (143.24 kW, 148.48 kVA, 157.56 kW / 163.33 kVA with 10 % reserve, 235.75 A). See docs/estimate-balance.md and issue #7. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 21 + docs/README.md | 2 + docs/circuit-list-editor-api.md | 6 + docs/estimate-balance.md | 108 + scripts/db-verify-circuit-schema.js | 3 + src/app/globals.css | 490 +++ .../grobbilanz/[balanceId]/page.tsx | 743 +++++ .../projects/[projectId]/grobbilanz/page.tsx | 292 ++ src/db/migrations/0010_estimate_balances.sql | 43 + src/db/migrations/meta/0010_snapshot.json | 2931 +++++++++++++++++ src/db/migrations/meta/_journal.json | 7 + ...mate-balance-project-command.repository.ts | 132 + .../estimate-balance.persistence.ts | 121 + .../estimate-balance.repository.ts | 60 + src/db/schema/estimate-balances.ts | 61 + .../services/project-command.service.ts | 30 +- .../api/estimate-balance-request.schemas.ts | 33 + .../domain/estimate-balance-command.model.ts | 320 ++ .../estimate-balance-project-command.store.ts | 24 + src/frontend/components/Sidebar.tsx | 1 + .../estimate-balance-create-modal.tsx | 162 + .../estimate-balance-document.ts | 301 ++ .../estimate-balance-format.ts | 122 + .../estimate-balance-sheet.tsx | 652 ++++ .../estimate-comparison-table.tsx | 88 + .../estimate-balance/estimate-draft-input.tsx | 107 + .../estimate-balance/estimate-group-modal.tsx | 128 + src/frontend/types.ts | 31 + src/frontend/utils/api.ts | 104 +- src/frontend/utils/project-version-history.ts | 3 + .../composition/application-repositories.ts | 2 + .../composition/project-command-stores.ts | 6 +- .../estimate-balance.controller.ts | 180 + src/server/routes/project.routes.ts | 17 + .../estimate-balance/estimate-balance.ts | 316 ++ tests/estimate-balance-frontend.test.ts | 435 +++ tests/estimate-balance.test.ts | 459 +++ 37 files changed, 8537 insertions(+), 4 deletions(-) create mode 100644 docs/estimate-balance.md create mode 100644 src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx create mode 100644 src/app/projects/[projectId]/grobbilanz/page.tsx create mode 100644 src/db/migrations/0010_estimate_balances.sql create mode 100644 src/db/migrations/meta/0010_snapshot.json create mode 100644 src/db/repositories/estimate-balance-project-command.repository.ts create mode 100644 src/db/repositories/estimate-balance.persistence.ts create mode 100644 src/db/repositories/estimate-balance.repository.ts create mode 100644 src/db/schema/estimate-balances.ts create mode 100644 src/estimate-balance/api/estimate-balance-request.schemas.ts create mode 100644 src/estimate-balance/domain/estimate-balance-command.model.ts create mode 100644 src/estimate-balance/domain/estimate-balance-project-command.store.ts create mode 100644 src/frontend/estimate-balance/estimate-balance-create-modal.tsx create mode 100644 src/frontend/estimate-balance/estimate-balance-document.ts create mode 100644 src/frontend/estimate-balance/estimate-balance-format.ts create mode 100644 src/frontend/estimate-balance/estimate-balance-sheet.tsx create mode 100644 src/frontend/estimate-balance/estimate-comparison-table.tsx create mode 100644 src/frontend/estimate-balance/estimate-draft-input.tsx create mode 100644 src/frontend/estimate-balance/estimate-group-modal.tsx create mode 100644 src/server/controllers/estimate-balance.controller.ts create mode 100644 src/shared/estimate-balance/estimate-balance.ts create mode 100644 tests/estimate-balance-frontend.test.ts create mode 100644 tests/estimate-balance.test.ts diff --git a/AGENTS.md b/AGENTS.md index 77b0170..d435cf3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -576,6 +576,27 @@ Future sizing will need: Users must be able to override sizing suggestions. +## Estimate Balance Module (Grobe Leistungsbilanz) + +`src/estimate-balance` plus `src/shared/estimate-balance` is a separate module +for the early-phase power balance by DIN 276 cost group (see +`docs/estimate-balance.md`). Rules: + +- It has its own tables (`estimate_*`) and never writes circuit, board or + project-device data; it only reads device rows for the comparison. +- Writes use the project command mechanism (`estimate-balance.insert/.update/ + .delete` with complete documents), so revision checks and Undo/Redo apply. +- The calculation and comparison live in the import-free + `src/shared/estimate-balance/estimate-balance.ts` and are shared by API and UI; + displayed values use `roundEstimateValue`. +- It is not part of project snapshots or project transfer yet (open question + in issue #7); do not add it there without a snapshot schema version. +- UI: `/projects/:id/grobbilanz` (Stände) and `/grobbilanz/:balanceId` (editor, + `src/frontend/estimate-balance/`). The editor autosaves the whole document + debounced (one Undo step per save), keeps invalid raw input local, and on a + 409 reloads only if the balance itself changed; otherwise it re-saves with + the new revision. `request()` throws `ApiRequestError` (status, code). + ## Persistence and Migration Rules - SQLite is the currently supported database. diff --git a/docs/README.md b/docs/README.md index cdddb67..09a3668 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,8 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we Verteilerübersicht, Verteilerpläne, Büro-Logo - [Gebäudestruktur](building-structure.md) – Gebäude → Etagen → Räume, Befehle, Snapshot-Schema 7, eigene Seite +- [Grobe Leistungsbilanz](estimate-balance.md) – LPH 2/3 nach Kostengruppen, + Rechnung, Vergleich mit der detaillierten Bilanz - [Editor-API](circuit-list-editor-api.md) – unterstützte Circuit-First-Endpunkte - [Bekannte Einschränkungen](circuit-list-editor-known-limitations.md) – bewusst noch nicht implementierte oder begrenzte Funktionen diff --git a/docs/circuit-list-editor-api.md b/docs/circuit-list-editor-api.md index 156be62..8e6e720 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -214,6 +214,12 @@ A stale `expectedRevision` returns HTTP `409` with `PROJECT_REVISION_CONFLICT`. Undo or redo without an eligible stack entry returns HTTP `409` with `PROJECT_HISTORY_OPERATION_UNAVAILABLE`. +## Estimate Balance (Grobe Leistungsbilanz) + +Separate module under `/projects/:projectId/estimate-balances`; complete +documents are written through `estimate-balance.insert/.update/.delete` project +commands. Endpoints, payloads and calculation rules: `docs/estimate-balance.md`. + ## Circuit-First Endpoints ### Distribution Board Setup diff --git a/docs/estimate-balance.md b/docs/estimate-balance.md new file mode 100644 index 0000000..4e43cec --- /dev/null +++ b/docs/estimate-balance.md @@ -0,0 +1,108 @@ +# Grobe Leistungsbilanz (LPH 2/3) + +Eigenes Modul für die Leistungsbilanz der Vor- und Entwurfsplanung, gegliedert +nach Kostengruppen (DIN 276, KG 400). Es gibt dort noch keine Verteilungen und +Stromkreise: Jedes Gewerk trägt unter seiner Kostengruppe Verbraucher als +Stückzahl mit Einzelleistung oder als Fläche mit W/m² ein. Aufbau und Rechnung +folgen der bisherigen Excel-Vorlage „Leistungsbilanz – KG400“. Abstimmung: +Issue #7. + +Das Modul ist **nicht** mit der Stromkreisstruktur verknüpft. Es liest die +Gerätezeilen nur für den Vergleich „geschätzt ↔ detailliert“ und schreibt +nichts in Stromkreislisten, Verteilungen oder Projektgeräte. + +## Aufbau + +``` +src/shared/estimate-balance/estimate-balance.ts Datenform, Rechnung, Vergleich (rein, ohne Imports) +src/estimate-balance/domain/estimate-balance-command.model.ts Snapshot-Schema (Zod), Befehle +src/estimate-balance/domain/estimate-balance-project-command.store.ts Store-Port +src/estimate-balance/api/estimate-balance-request.schemas.ts Request-Schemas +src/db/schema/estimate-balances.ts Tabellen (Migration 0010) +src/db/repositories/estimate-balance*.ts Lesen, Schreiben, Befehls-Store +src/server/controllers/estimate-balance.controller.ts API +src/app/projects/[projectId]/grobbilanz/ Übersicht der Stände und Editor +src/frontend/estimate-balance/ Editor-Komponenten und Helfer +``` + +Die gemeinsame Datei unter `src/shared/estimate-balance` hat keine Imports, weil +das Frontend sie direkt nutzt (Turbopack löst die `.js`-Suffixe der API nicht auf). + +## Datenmodell + +| Tabelle | Inhalt | +|---|---| +| `estimate_balances` | ein **Stand** je Projekt (z. B. Vorplanung, Entwurfsplanung): Name, LPH, Datum, Reserve AV/SV in %, Sortierung | +| `estimate_groups` | Kostengruppe (`"410"` … `"480"`, `""` für „Allgemein“), Titel, „bearbeitet von“, Sortierung | +| `estimate_rows` | Versorgung, Stromkreis-Nr. (Freitext), Verbraucher/Fläche, Anzahl bzw. Fläche, Einheit (`piece` = St., `area` = m²), Anschluss (fest/Steckdose), Einzelleistung in W bzw. W/m², GLF, cos φ, SV ja/nein, Anmerkung | + +Neue Stände entstehen aus der Vorlage KG 400 (410 Sanitär, 420 Wärme, 430 Luft, +434 Kälte, 440 Starkstrom, 450 Schwachstrom, 460 Förder, 470 Nutzungsspezifisch, +480 GA, Allgemein; Reserve AV 10 %), leer oder als Kopie eines bestehenden +Stands mit neuen IDs. So lässt sich ein Stand einfrieren und später vergleichen. + +## Rechnung + +- Zeile: P = Anzahl bzw. Fläche × Einzelleistung × GLF, S = P / cos φ. +- **AV** enthält alle Verbraucher (Normalversorgung). **SV** listet zusätzlich + die Zeilen mit „SV = ja“, die auch aus der Sicherheitsstromversorgung versorgt + werden müssen. Das ist die Lesart der Vorlage; die Regel liegt in + `calculateEstimateRow` und lässt sich dort zentral ändern. +- Summen je Kostengruppe, Gesamtsumme, Reserve in % (AV und SV getrennt), + Leistung inklusive Reserve und Maximalstrom I = S / (√3 · U) mit der + Drehstromspannung aus den Projekteinstellungen. +- Anzeige wie in der Tabellenkalkulation gerundet (`roundEstimateValue`, + 40,175 → 40,18). Der Test `tests/estimate-balance.test.ts` rechnet das + Beispiel der Vorlage vollständig nach (143,24 kW, 148,48 kVA, mit 10 % + Reserve 157,56 kW / 163,33 kVA, 235,75 A). + +## Vergleich geschätzt ↔ detailliert + +`GET …/comparison` summiert alle Gerätezeilen aller Stromkreislisten des +Projekts (Anzahl × Leistung je Stück × Geräte-GZF, wie der Stromkreisbaum) und +ordnet sie über das Feld **Kostengruppe** der Gerätezeile zu. Maßgeblich ist das +längste passende Präfix: `434` → Gruppe 434, `431` → Gruppe 430, `444` → 440. +Zeilen ohne passende Kostengruppe erscheinen als „nicht zugeordnet“. Der +Verteiler-GZF wird auf keiner Seite angewendet; ein fehlendes cos φ zählt als 1. +Verglichen wird die AV-Leistung (kW) mit Differenz absolut und in %. + +## Befehle, Undo/Redo + +Alle Änderungen laufen über den bestehenden Projekt-Befehlsmechanismus mit +Revision, Inverse und persistentem Undo/Redo: + +- `estimate-balance.insert` / `estimate-balance.delete` mit dem vollständigen + Stand (Gruppen und Zeilen) +- `estimate-balance.update` mit vollständigem `expected`/`target`-Dokument; der + Store prüft, dass der gespeicherte Stand genau `expected` entspricht, und + ersetzt ihn atomar. Die Inverse ist das vertauschte Paar. + +Der Editor speichert das ganze Dokument verzögert (Autosave); jeder +Speichervorgang ist ein Undo-Schritt. Unveränderte Dokumente erzeugen keine +Revision (`{ unchanged: true }`). + +## Bewusst nicht enthalten (Fragen an Julian, Issue #7) + +- Die grobe Bilanz ist **nicht** Teil von Projekt-Snapshot, Restore und + Projekttransfer; das Snapshot-Schema bleibt unverändert. Ein Restore lässt + die Stände unverändert, eine Projektkopie übernimmt sie nicht. +- Keine Rechte je Gewerk; „bearbeitet von“ ist ein Freitext je Kostengruppe. +- Kostengruppen der Gerätezeilen sind nicht normiert; der Vergleich arbeitet + mit Präfixen. + +## API + +- `GET /api/projects/:projectId/estimate-balances` +- `POST /api/projects/:projectId/estimate-balances` – + `{ "expectedRevision": 7, "name": "Entwurfsplanung", "workStage": "LPH 3", "dateIso": "2026-09-26", "template": "kg400" }` + (`template`: `kg400` | `empty` | `copy` mit `copyFromBalanceId`) +- `GET /api/projects/:projectId/estimate-balances/:balanceId` +- `PUT /api/projects/:projectId/estimate-balances/:balanceId` – + `{ "expectedRevision": 8, "balance": { …vollständiges Dokument… } }` +- `DELETE /api/projects/:projectId/estimate-balances/:balanceId` – `{ "expectedRevision": 9 }` +- `GET /api/projects/:projectId/estimate-balances/:balanceId/comparison` + +Validierung: Name 1–200 Zeichen, getrimmte Texte, Anzahl/Fläche und +Einzelleistung ≥ 0, GLF 0–1, cos φ > 0 bis 1, Reserve 0–100 %, Datum +`YYYY-MM-DD`, eindeutige Gruppen- und Zeilen-IDs, unbekannte Felder werden +abgelehnt. diff --git a/scripts/db-verify-circuit-schema.js b/scripts/db-verify-circuit-schema.js index 947767a..fa91cc4 100644 --- a/scripts/db-verify-circuit-schema.js +++ b/scripts/db-verify-circuit-schema.js @@ -6,6 +6,9 @@ const db = new Database(dbPath, { readonly: true }); const requiredTables = [ "buildings", + "estimate_balances", + "estimate_groups", + "estimate_rows", "circuit_sections", "circuits", "circuit_device_rows", diff --git a/src/app/globals.css b/src/app/globals.css index 0c40c5c..b3f526a 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1602,3 +1602,493 @@ button.structure-entry-main:focus-visible { color: var(--color-ink-soft); font-size: 0.9rem; } + +/* ── Grobe Leistungsbilanz ──────────────────────────────────────────── */ +/* Tabelle im Stil der Büro-Vorlage „Leistungsbilanz – KG400“: kompakte + Zellen-Inputs statt Bootstrap-Formularfelder, Druck als A4 quer. */ + +.estimate-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-sm); +} + +.estimate-save-status { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-sm); + font-size: 0.8rem; +} + +.estimate-save-badge { + display: inline-block; + padding: 0.2rem 0.55rem; + border-radius: 999px; + font-weight: 600; + border: 1px solid var(--color-border); + color: var(--color-ink-soft); + background: var(--color-bg); +} + +.estimate-save-badge.is-saved { + color: var(--color-signal-dark); + border-color: var(--color-signal); +} + +.estimate-save-badge.is-busy { + color: var(--color-warn); + border-color: var(--color-warn); +} + +.estimate-save-badge.is-error { + color: var(--color-danger); + border-color: var(--color-danger); + background: var(--color-danger-bg); +} + +.estimate-save-hint { + color: var(--color-danger); +} + +.estimate-header-fields { + display: flex; + flex-wrap: wrap; + gap: var(--space-sm) var(--space-lg); + margin-bottom: var(--space-md); +} + +.estimate-header-field { + display: flex; + align-items: center; + gap: var(--space-sm); + min-width: 10rem; +} + +.estimate-header-field.is-wide { + flex: 1 1 18rem; +} + +.estimate-header-label { + font-size: 0.7rem; + letter-spacing: 0.06em; + text-transform: uppercase; + font-weight: 600; + color: var(--color-ink-soft); +} + +.estimate-header-value { + font-weight: 600; +} + +.estimate-header-input { + font-size: 0.95rem; + font-weight: 600; + border-color: var(--panel-border); +} + +.estimate-sheet-wrap { + overflow-x: auto; +} + +.estimate-sheet { + width: 100%; + min-width: 1400px; + table-layout: fixed; + border-collapse: collapse; + font-size: 0.82rem; + background: var(--panel-bg); + color: var(--text-strong); +} + +.estimate-comparison { + min-width: 640px; + table-layout: auto; +} + +.estimate-sheet th, +.estimate-sheet td { + border: 1px solid var(--panel-border); + padding: 2px 4px; + vertical-align: middle; +} + +.estimate-sheet thead th { + background: var(--surface-header-row); + font-size: 0.72rem; + font-weight: 700; + text-align: center; + line-height: 1.2; +} + +.estimate-th-hint { + display: block; + font-size: 0.68rem; + font-weight: 400; + color: var(--text-faint); +} + +.estimate-col-kg { width: 3rem; } +.estimate-col-supply { width: 4rem; } +.estimate-col-circuit { width: 4.6rem; } +.estimate-col-name { width: auto; } +.estimate-col-quantity { width: 4.8rem; } +.estimate-col-unit { width: 3.8rem; } +.estimate-col-connection { width: 5rem; } +.estimate-col-power { width: 6.4rem; } +.estimate-col-gzf { width: 6.8rem; } +.estimate-col-cosphi { width: 3.8rem; } +.estimate-col-result { width: 4.6rem; } +.estimate-col-sv { width: 3.2rem; } +.estimate-col-remark { width: 9rem; } +.estimate-col-actions { width: 2.4rem; } + +.estimate-cell-input, +.estimate-cell-select { + width: 100%; + min-width: 0; + border: 1px solid transparent; + border-radius: 3px; + background: transparent; + color: inherit; + font: inherit; + padding: 1px 4px; + line-height: 1.4; +} + +.estimate-cell-select { + padding-right: 0; + cursor: pointer; +} + +.estimate-cell-input:hover:not(:disabled), +.estimate-cell-select:hover:not(:disabled) { + border-color: var(--panel-border-strong); +} + +.estimate-cell-input:focus, +.estimate-cell-select:focus { + outline: none; + border-color: var(--accent-blue); + background: var(--panel-bg); + box-shadow: 0 0 0 2px var(--accent-blue-soft-bg); +} + +.estimate-cell-input.is-numeric { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.estimate-cell-input.is-invalid, +.estimate-cell-input.is-invalid:focus, +.estimate-cell-input.is-invalid:hover { + border-color: var(--color-danger); + background: var(--color-danger-bg); +} + +.estimate-cell-input::placeholder { + color: var(--text-faint); + opacity: 0.7; +} + +.estimate-unit-input, +.estimate-gzf-input { + display: flex; + align-items: center; + gap: 2px; +} + +.estimate-unit-label { + flex: 0 0 auto; + font-size: 0.7rem; + color: var(--text-faint); + min-width: 1.9rem; +} + +.estimate-amev-button { + flex: 0 0 auto; + border: 1px solid var(--panel-border-strong); + border-radius: 3px; + background: var(--panel-bg-subtle); + color: var(--text-subtle); + font-size: 0.6rem; + font-weight: 700; + letter-spacing: 0.03em; + padding: 1px 3px; + line-height: 1.3; +} + +.estimate-amev-button:hover:not(:disabled) { + border-color: var(--accent-blue); + color: var(--accent-blue); +} + +.estimate-number { + text-align: right; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.estimate-number.is-muted { + color: var(--text-faint); +} + +.estimate-number.is-over { + color: var(--color-attention-dark); +} + +.estimate-number.is-under { + color: var(--color-signal-dark); +} + +.estimate-center { + text-align: center; +} + +.estimate-cost-group-cell { + font-weight: 700; + text-align: center; + font-variant-numeric: tabular-nums; +} + +.estimate-group-title-row td { + background: var(--surface-component-header); + font-weight: 700; +} + +.estimate-group-title { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-xs) var(--space-lg); +} + +.estimate-group-name { + font-size: 0.9rem; +} + +.estimate-group-editor { + display: inline-flex; + align-items: center; + gap: var(--space-xs); + font-weight: 400; + font-size: 0.75rem; + color: var(--text-muted); +} + +.estimate-group-editor .estimate-cell-input { + width: 12rem; +} + +.estimate-group-actions { + display: flex; + justify-content: flex-end; + gap: 2px; +} + +.estimate-group-title-row .estimate-actions-cell { + width: auto; + white-space: nowrap; +} + +.estimate-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.15rem 0.3rem; + line-height: 1; +} + +.estimate-actions-cell { + text-align: center; +} + +.estimate-empty-row td { + color: var(--text-faint); + font-style: italic; +} + +.estimate-subtotal-row td { + background: var(--panel-bg-subtle); + font-weight: 700; +} + +.estimate-total-label { + text-align: right; + font-weight: 700; +} + +.estimate-total-hint { + font-weight: 400; + color: var(--text-faint); +} + +.estimate-total-row td { + background: var(--surface-header-row); + font-weight: 600; +} + +.estimate-total-row.is-strong td { + font-weight: 800; + border-top: 2px solid var(--panel-border-strong); +} + +.estimate-add-group-row td { + background: var(--panel-bg); + padding: var(--space-sm) 4px; +} + +.estimate-unassigned-row td { + font-style: italic; + color: var(--text-muted); +} + +.estimate-collapse-toggle { + display: inline-flex; + align-items: center; + gap: var(--space-xs); + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-weight: 700; + padding: 0; +} + +.estimate-list-table .estimate-number { + font-variant-numeric: tabular-nums; +} + +/* Druck-Textwerte: auf dem Bildschirm unsichtbar, im Druck statt Inputs */ +.estimate-print-value { + display: none; +} + +@page estimate-balance { + size: A4 landscape; + margin: 10mm; +} + +@media print { + body:has(.estimate-print-root) .sidebar, + .estimate-print-root .estimate-no-print, + .estimate-print-root .alert, + .estimate-print-root input, + .estimate-print-root select, + .estimate-print-root button { + display: none !important; + } + + body:has(.estimate-print-root) { + background: #fff !important; + } + + body:has(.estimate-print-root) .app-shell { + display: block; + } + + .estimate-print-root { + page: estimate-balance; + padding: 0 !important; + max-width: none; + color: #000; + } + + .estimate-print-root .estimate-print-value { + display: inline; + } + + .estimate-print-root .page-header { + margin-bottom: 4mm; + } + + .estimate-print-root .page-header h1 { + font-size: 14pt; + color: #000; + } + + .estimate-print-root .card { + border: 0; + box-shadow: none; + background: transparent; + } + + .estimate-print-root .card-body, + .estimate-print-root .card-header { + padding: 0; + background: transparent; + border: 0; + } + + .estimate-print-root .estimate-comparison-card { + margin-top: 6mm; + break-inside: avoid; + } + + .estimate-sheet-wrap { + overflow: visible; + } + + .estimate-sheet { + min-width: 0; + table-layout: auto; + font-size: 7.5pt; + background: #fff; + color: #000; + } + + .estimate-sheet th, + .estimate-sheet td { + border-color: #999; + padding: 1px 3px; + } + + .estimate-sheet thead { + display: table-header-group; + } + + .estimate-sheet thead th, + .estimate-total-row td { + background: #e8e8e8 !important; + } + + .estimate-group-title-row td { + background: #d9d9d9 !important; + } + + .estimate-subtotal-row td { + background: #f2f2f2 !important; + } + + .estimate-group-title-row, + .estimate-subtotal-row, + .estimate-total-row { + break-inside: avoid; + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + } + + .estimate-group-title-row { + break-after: avoid; + } + + /* Totals print once at the end, not repeated on every page. */ + .estimate-sheet tfoot { + display: table-row-group; + break-inside: avoid; + } + + .estimate-col-actions { + width: 0; + } + + .estimate-unit-input, + .estimate-gzf-input { + justify-content: flex-end; + } + + .estimate-header-fields { + margin-bottom: 3mm; + } +} diff --git a/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx new file mode 100644 index 0000000..2aa7f5e --- /dev/null +++ b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx @@ -0,0 +1,743 @@ +"use client"; + +import Link from "next/link"; +import { useParams, useRouter } from "next/navigation"; +import { type MouseEvent, useCallback, useEffect, useRef, useState } from "react"; +import { + ArrowLeft, + ChevronDown, + ChevronRight, + Printer, + Redo2, + RefreshCw, + Undo2, +} from "lucide-react"; +import { + ApiRequestError, + getEstimateBalance, + getEstimateComparison, + getProject, + getProjectHistory, + isRevisionConflictError, + redoProjectCommand, + undoProjectCommand, + updateEstimateBalance, +} from "../../../../../frontend/utils/api"; +import type { + EstimateBalanceDto, + EstimateComparisonDto, + ProjectDto, + ProjectHistoryStateDto, +} from "../../../../../frontend/types"; +import type { EstimateGroupSnapshot } from "../../../../../shared/estimate-balance/estimate-balance"; +import { GzfPickerModal } from "../../../../../frontend/components/gzf-picker-modal"; +import { + addEstimateGroup, + estimateBalanceFingerprint, + estimateTextLimits, + normalizeEstimateSortOrder, + toSaveableEstimateBalance, + updateEstimateGroup, + updateEstimateRow, + validateEstimateBalance, +} from "../../../../../frontend/estimate-balance/estimate-balance-document"; +import { formatIsoDateGerman } from "../../../../../frontend/estimate-balance/estimate-balance-format"; +import { + EstimateBalanceSheet, + type EstimateBalanceUpdate, +} from "../../../../../frontend/estimate-balance/estimate-balance-sheet"; +import { EstimateComparisonTable } from "../../../../../frontend/estimate-balance/estimate-comparison-table"; +import { DraftInput } from "../../../../../frontend/estimate-balance/estimate-draft-input"; +import { + EstimateGroupModal, + type EstimateGroupFormValues, +} from "../../../../../frontend/estimate-balance/estimate-group-modal"; + +const AUTOSAVE_DELAY_MS = 800; +const CONFLICT_MESSAGE = "Die Bilanz wurde zwischenzeitlich geändert und neu geladen."; + +type SaveStatus = "saved" | "pending" | "saving" | "error" | "invalid"; + +type GroupDialog = { group: EstimateGroupSnapshot | null }; + +function errorMessage(error: unknown, fallback: string) { + return error instanceof Error && error.message ? error.message : fallback; +} + +function isNotFoundError(error: unknown) { + return error instanceof ApiRequestError && error.status === 404; +} + +export default function EstimateBalanceEditorPage() { + const params = useParams<{ projectId: string; balanceId: string }>(); + const { projectId, balanceId } = params; + const router = useRouter(); + + const [project, setProject] = useState(null); + const [draft, setDraft] = useState(null); + const [history, setHistory] = useState(null); + const [comparison, setComparison] = useState(null); + const [comparisonError, setComparisonError] = useState(null); + const [isComparisonOpen, setIsComparisonOpen] = useState(false); + const [saveStatus, setSaveStatus] = useState("saved"); + const [saveError, setSaveError] = useState(null); + const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [isMissing, setIsMissing] = useState(false); + const [isHistoryBusy, setIsHistoryBusy] = useState(false); + const [invalidFieldKeys, setInvalidFieldKeys] = useState>( + () => new Set() + ); + const [groupDialog, setGroupDialog] = useState(null); + const [gzfTarget, setGzfTarget] = useState<{ groupId: string; rowId: string } | null>( + null + ); + + // Refs carry the latest values into timers, unload handlers and chained + // async saves without re-creating them. + const draftRef = useRef(null); + const revisionRef = useRef(null); + const savedFingerprintRef = useRef(null); + const saveInFlightRef = useRef | null>(null); + const saveTimerRef = useRef | null>(null); + + useEffect(() => { + draftRef.current = draft; + }, [draft]); + + const applyServerBalance = useCallback((balance: EstimateBalanceDto) => { + const normalized = normalizeEstimateSortOrder(balance); + savedFingerprintRef.current = estimateBalanceFingerprint(normalized); + draftRef.current = normalized; + setDraft(normalized); + setSaveStatus("saved"); + setSaveError(null); + }, []); + + const reloadComparison = useCallback(async () => { + try { + setComparison(await getEstimateComparison(projectId, balanceId)); + setComparisonError(null); + } catch (err) { + setComparisonError( + errorMessage(err, "Der Vergleich konnte nicht geladen werden.") + ); + } + }, [balanceId, projectId]); + + /** Reloads project, document and history; replaces the local draft. */ + const reloadAll = useCallback(async () => { + const balanceRequest = getEstimateBalance(projectId, balanceId); + // Handled below; avoids an "unhandled rejection" while project/history load. + balanceRequest.catch(() => undefined); + // Project and history are applied even when the balance is missing, so + // Redo stays available after its creation was undone. + const [currentProject, currentHistory] = await Promise.all([ + getProject(projectId), + getProjectHistory(projectId).catch(() => null), + ]); + setProject(currentProject); + revisionRef.current = currentHistory?.currentRevision ?? currentProject.currentRevision; + setHistory(currentHistory); + const balance = await balanceRequest; + applyServerBalance(balance); + setIsMissing(false); + void reloadComparison(); + }, [applyServerBalance, balanceId, projectId, reloadComparison]); + + const handleReloadError = useCallback((err: unknown) => { + if (isNotFoundError(err)) { + setIsMissing(true); + setDraft(null); + draftRef.current = null; + return; + } + setError(errorMessage(err, "Die grobe Leistungsbilanz konnte nicht geladen werden.")); + }, []); + + useEffect(() => { + if (!projectId || !balanceId) { + return; + } + setIsLoading(true); + reloadAll() + .then(() => setError(null)) + .catch(handleReloadError) + .finally(() => setIsLoading(false)); + }, [balanceId, handleReloadError, projectId, reloadAll]); + + const clearSaveTimer = useCallback(() => { + if (saveTimerRef.current) { + clearTimeout(saveTimerRef.current); + saveTimerRef.current = null; + } + }, []); + + /** + * Saves the current draft if it differs from the last saved state. Saves + * never overlap: a save requested while another runs waits for it and then + * saves whatever changed in the meantime. Resolves to false when the draft + * could not be saved. + */ + const saveNow = useCallback(async (): Promise => { + clearSaveTimer(); + while (saveInFlightRef.current) { + await saveInFlightRef.current; + } + const current = draftRef.current; + const revision = revisionRef.current; + if (!current || revision === null) { + return true; + } + const fingerprint = estimateBalanceFingerprint(current); + if (fingerprint === savedFingerprintRef.current) { + setSaveStatus("saved"); + return true; + } + const problems = validateEstimateBalance(current); + if (problems.length) { + setSaveStatus("invalid"); + setSaveError(problems.join(" ")); + return false; + } + const body = toSaveableEstimateBalance(current); + + /** + * Another command changed the project revision. When this document is + * still unchanged on the server (e.g. an edit in a circuit list), the + * draft is kept and saved again; otherwise the server state wins. + */ + async function resolveConflict(): Promise<"retry" | "reloaded"> { + const [currentProject, serverBalance, currentHistory] = await Promise.all([ + getProject(projectId), + getEstimateBalance(projectId, balanceId), + getProjectHistory(projectId).catch(() => null), + ]); + setProject(currentProject); + setHistory(currentHistory); + revisionRef.current = currentHistory?.currentRevision ?? currentProject.currentRevision; + if (estimateBalanceFingerprint(serverBalance) === savedFingerprintRef.current) { + return "retry"; + } + applyServerBalance(serverBalance); + setNotice(CONFLICT_MESSAGE); + void reloadComparison(); + return "reloaded"; + } + + const run = (async () => { + setSaveStatus("saving"); + for (let attempt = 0; ; attempt += 1) { + try { + const result = await updateEstimateBalance( + projectId, + body, + attempt === 0 ? revision : revisionRef.current ?? revision + ); + if (!("unchanged" in result)) { + revisionRef.current = result.history.currentRevision; + setHistory(result.history); + setProject((currentProject) => + currentProject + ? { ...currentProject, currentRevision: result.history.currentRevision } + : currentProject + ); + } + // The sent document is the saved state; the local draft is kept so + // typing is never interrupted by the server's copy. + savedFingerprintRef.current = fingerprint; + setSaveError(null); + const latest = draftRef.current; + if (latest && estimateBalanceFingerprint(latest) !== fingerprint) { + setSaveStatus("pending"); + } else { + setSaveStatus("saved"); + } + void reloadComparison(); + return true; + } catch (err) { + if (isRevisionConflictError(err)) { + try { + if (attempt === 0 && (await resolveConflict()) === "retry") { + continue; + } + if (attempt > 0) { + await reloadAll(); + setNotice(CONFLICT_MESSAGE); + } + } catch (reloadError) { + handleReloadError(reloadError); + } + return false; + } + if (isNotFoundError(err)) { + handleReloadError(err); + return false; + } + setSaveStatus("error"); + setSaveError(errorMessage(err, "Die Änderungen konnten nicht gespeichert werden.")); + return false; + } + } + })(); + saveInFlightRef.current = run; + try { + return await run; + } finally { + saveInFlightRef.current = null; + } + }, [ + applyServerBalance, + balanceId, + clearSaveTimer, + handleReloadError, + projectId, + reloadAll, + reloadComparison, + ]); + + // Debounced autosave after every change of the draft. + useEffect(() => { + if (!draft) { + return; + } + if (estimateBalanceFingerprint(draft) === savedFingerprintRef.current) { + return; + } + setSaveStatus((status) => (status === "saving" ? status : "pending")); + clearSaveTimer(); + saveTimerRef.current = setTimeout(() => { + saveTimerRef.current = null; + void saveNow(); + }, AUTOSAVE_DELAY_MS); + return clearSaveTimer; + }, [clearSaveTimer, draft, saveNow]); + + // Save immediately when the tab is hidden; on unload/unmount send the last + // change with keepalive so it survives the page. + useEffect(() => { + function hasUnsavedDraft() { + const current = draftRef.current; + return Boolean( + current && estimateBalanceFingerprint(current) !== savedFingerprintRef.current + ); + } + function sendKeepalive(): boolean { + const current = draftRef.current; + const revision = revisionRef.current; + if ( + !current || + revision === null || + saveInFlightRef.current || + validateEstimateBalance(current).length + ) { + return false; + } + savedFingerprintRef.current = estimateBalanceFingerprint(current); + void updateEstimateBalance(projectId, toSaveableEstimateBalance(current), revision, { + keepalive: true, + }).catch(() => undefined); + return true; + } + function handleVisibilityChange() { + if (document.visibilityState === "hidden" && hasUnsavedDraft()) { + void saveNow(); + } + } + function handleBeforeUnload(event: BeforeUnloadEvent) { + if (!hasUnsavedDraft() || sendKeepalive()) { + return; + } + // A save is still running or the draft is invalid: let the browser ask. + event.preventDefault(); + event.returnValue = ""; + } + document.addEventListener("visibilitychange", handleVisibilityChange); + window.addEventListener("beforeunload", handleBeforeUnload); + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange); + window.removeEventListener("beforeunload", handleBeforeUnload); + // In-app navigation (e.g. sidebar) unmounts the editor. + if (hasUnsavedDraft()) { + sendKeepalive(); + } + }; + }, [projectId, saveNow]); + + const handleChange: EstimateBalanceUpdate = useCallback((update) => { + setNotice(null); + setDraft((current) => (current ? update(current) : current)); + }, []); + + const handleValidityChange = useCallback((fieldKey: string, isValid: boolean) => { + setInvalidFieldKeys((current) => { + if (isValid ? !current.has(fieldKey) : current.has(fieldKey)) { + return current; + } + const next = new Set(current); + if (isValid) { + next.delete(fieldKey); + } else { + next.add(fieldKey); + } + return next; + }); + }, []); + + async function handleHistory(direction: "undo" | "redo") { + setError(null); + setNotice(null); + setIsHistoryBusy(true); + try { + // Pending edits are saved first so they become their own undo step. + await saveNow(); + const revision = revisionRef.current; + if (revision === null) { + return; + } + const result = + direction === "undo" + ? await undoProjectCommand(projectId, revision) + : await redoProjectCommand(projectId, revision); + revisionRef.current = result.history.currentRevision; + setHistory(result.history); + await reloadAll(); + } catch (err) { + if (isRevisionConflictError(err)) { + await reloadAll().catch(handleReloadError); + setNotice(CONFLICT_MESSAGE); + } else if (isNotFoundError(err)) { + handleReloadError(err); + } else { + setError( + errorMessage( + err, + direction === "undo" + ? "Die letzte Änderung konnte nicht rückgängig gemacht werden." + : "Die letzte Änderung konnte nicht wiederholt werden." + ) + ); + } + } finally { + setIsHistoryBusy(false); + } + } + + async function handleBackClick(event: MouseEvent) { + const current = draftRef.current; + if (!current || estimateBalanceFingerprint(current) === savedFingerprintRef.current) { + return; + } + event.preventDefault(); + await saveNow(); + router.push(`/projects/${projectId}/grobbilanz`); + } + + function handleSaveGroup(values: EstimateGroupFormValues) { + const editingGroup = groupDialog?.group ?? null; + handleChange((current) => + editingGroup + ? updateEstimateGroup(current, editingGroup.id, values) + : addEstimateGroup(current, values).balance + ); + setGroupDialog(null); + } + + function handleSelectGzf(value: number) { + if (gzfTarget) { + handleChange((current) => + updateEstimateRow(current, gzfTarget.groupId, gzfTarget.rowId, { + simultaneityFactor: value, + }) + ); + } + setGzfTarget(null); + } + + const isEditingDisabled = !draft || isHistoryBusy; + const invalidCount = invalidFieldKeys.size; + const listHref = `/projects/${projectId}/grobbilanz`; + + return ( +
+
+
+ void handleBackClick(event)} + title="Zurück zur Übersicht der Stände" + > +
+
+ void saveNow()} + status={saveStatus} + /> +
+ + +
+ +
+
+ + {notice ? ( +
+ {notice} +
+ ) : null} + {error ? ( +
+ {error} +
+ ) : null} + {isLoading ? ( +

+ Grobe Leistungsbilanz wird geladen … +

+ ) : null} + {isMissing ? ( +
+ Dieser Stand existiert nicht (mehr), z. B. weil er gelöscht oder sein Anlegen + rückgängig gemacht wurde.{" "} + Zur Übersicht der Stände +
+ ) : null} + + {draft && project ? ( + <> +
+
+
+
+ Projekt + {project.name} +
+ + + +
+ setGroupDialog({ group: null })} + onChange={handleChange} + onEditGroup={(group) => setGroupDialog({ group })} + onOpenGzfPicker={(groupId, rowId) => setGzfTarget({ groupId, rowId })} + onValidityChange={handleValidityChange} + threePhaseVoltageV={project.threePhaseVoltageV} + /> +
+
+ +
+
+ + {isComparisonOpen ? ( + + ) : null} +
+ {isComparisonOpen ? ( +
+ {comparisonError ? ( +
+ {comparisonError} +
+ ) : null} + {comparison ? : null} +

+ Detailliert = Summe der Gerätezeilen aller Stromkreislisten (Anzahl × + Leistung × Geräte-GZF), zugeordnet über die Kostengruppe; ohne + Verteiler-GZF. +

+
+ ) : null} +
+ + ) : null} + + {groupDialog ? ( + setGroupDialog(null)} + onSave={handleSaveGroup} + /> + ) : null} + {gzfTarget ? ( + setGzfTarget(null)} onSelect={handleSelectGzf} /> + ) : null} +
+ ); +} + +function SaveStatusBadge({ + error, + invalidCount, + onRetry, + status, +}: { + error: string | null; + invalidCount: number; + onRetry: () => void; + status: SaveStatus; +}) { + const label = + status === "saving" + ? "Wird gespeichert …" + : status === "pending" + ? "Ungespeicherte Änderungen" + : status === "error" + ? "Nicht gespeichert – Fehler" + : status === "invalid" + ? "Nicht gespeichert – ungültige Eingaben" + : "Gespeichert"; + const tone = + status === "error" || status === "invalid" + ? "is-error" + : status === "saved" + ? "is-saved" + : "is-busy"; + return ( +
+ + {label} + + {invalidCount ? ( + + {invalidCount === 1 + ? "1 ungültige Eingabe wird nicht gespeichert" + : `${invalidCount} ungültige Eingaben werden nicht gespeichert`} + + ) : null} + {status === "error" ? ( + + ) : null} +
+ ); +} diff --git a/src/app/projects/[projectId]/grobbilanz/page.tsx b/src/app/projects/[projectId]/grobbilanz/page.tsx new file mode 100644 index 0000000..4b2cf81 --- /dev/null +++ b/src/app/projects/[projectId]/grobbilanz/page.tsx @@ -0,0 +1,292 @@ +"use client"; + +import Link from "next/link"; +import { useParams, useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { ArrowLeft, Copy, FolderOpen, Plus, Trash2 } from "lucide-react"; +import { + createEstimateBalance, + deleteEstimateBalance, + getProject, + listEstimateBalances, +} from "../../../../frontend/utils/api"; +import type { + CreateEstimateBalanceInput, + EstimateBalanceDto, + ProjectCommandResultDto, + ProjectDto, +} from "../../../../frontend/types"; +import { calculateEstimateBalance } from "../../../../shared/estimate-balance/estimate-balance"; +import { + EstimateBalanceCreateModal, + type EstimateBalanceCreateDefaults, +} from "../../../../frontend/estimate-balance/estimate-balance-create-modal"; +import { createCopyName } from "../../../../frontend/estimate-balance/estimate-balance-document"; +import { + formatIsoDateGerman, + formatKw, +} from "../../../../frontend/estimate-balance/estimate-balance-format"; + +function countRows(balance: EstimateBalanceDto) { + return balance.groups.reduce((sum, group) => sum + group.rows.length, 0); +} + +export default function EstimateBalanceListPage() { + const params = useParams<{ projectId: string }>(); + const projectId = params.projectId; + const router = useRouter(); + const [project, setProject] = useState(null); + const [balances, setBalances] = useState([]); + const [createDefaults, setCreateDefaults] = + useState(null); + const [error, setError] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [isSaving, setIsSaving] = useState(false); + + const reload = useCallback(async () => { + const [currentProject, loadedBalances] = await Promise.all([ + getProject(projectId), + listEstimateBalances(projectId), + ]); + setProject(currentProject); + setBalances([...loadedBalances].sort((left, right) => left.sortOrder - right.sortOrder)); + }, [projectId]); + + useEffect(() => { + if (!projectId) { + return; + } + setIsLoading(true); + reload() + .then(() => setError(null)) + .catch((err: unknown) => + setError( + err instanceof Error + ? err.message + : "Grobe Leistungsbilanzen konnten nicht geladen werden." + ) + ) + .finally(() => setIsLoading(false)); + }, [projectId, reload]); + + async function runCommand( + execute: (expectedRevision: number) => Promise, + fallbackMessage: string + ): Promise { + if (!project) { + return null; + } + setIsSaving(true); + setError(null); + try { + const result = await execute(project.currentRevision); + setProject((current) => + current ? { ...current, currentRevision: result.history.currentRevision } : current + ); + await reload(); + return result; + } catch (err) { + setError(err instanceof Error ? err.message : fallbackMessage); + // Refresh revision and list so a stale state does not block the next + // attempt; the command error stays visible. + await reload().catch(() => undefined); + return null; + } finally { + setIsSaving(false); + } + } + + async function handleCreate(input: CreateEstimateBalanceInput) { + const result = await runCommand( + (expectedRevision) => createEstimateBalance(projectId, input, expectedRevision), + "Stand konnte nicht angelegt werden." + ); + if (result) { + setCreateDefaults(null); + router.push(`/projects/${projectId}/grobbilanz/${result.balance.id}`); + } + } + + async function handleDelete(balance: EstimateBalanceDto) { + if ( + !window.confirm( + `Stand „${balance.name}“ der groben Leistungsbilanz wirklich löschen?` + ) + ) { + return; + } + await runCommand( + (expectedRevision) => deleteEstimateBalance(projectId, balance.id, expectedRevision), + "Stand konnte nicht gelöscht werden." + ); + } + + const isBusy = isSaving || !project; + const voltage = project?.threePhaseVoltageV ?? 400; + + return ( +
+
+
+ +
+ +
+ + {error ? ( +
+ {error} +
+ ) : null} + {isLoading ? ( +

+ Grobe Leistungsbilanzen werden geladen … +

+ ) : null} + +
+
+

+ Stände + {balances.length} +

+
+ {balances.length ? ( +
+ + + + + + + + + + + + + + + {balances.map((balance) => { + const result = calculateEstimateBalance(balance, voltage); + const href = `/projects/${projectId}/grobbilanz/${balance.id}`; + const rowCount = countRows(balance); + return ( + + + + + + + + + + + ); + })} + +
StandLPHDatumAV kWAV kVASV kWSV kVAAktionen
+ + {balance.name} + +
+ {balance.groups.length} Kostengruppen ·{" "} + {rowCount === 1 ? "1 Zeile" : `${rowCount} Zeilen`} +
+
{balance.workStage ?? "–"}{formatIsoDateGerman(balance.dateIso)} + {formatKw(result.withReserve.av.kw)} + + {formatKw(result.withReserve.av.kva)} + + {formatKw(result.withReserve.sv.kw)} + + {formatKw(result.withReserve.sv.kva)} + +
+ +
+
+

+ Leistungen jeweils inklusive Reserve. +

+
+ ) : !isLoading ? ( +
+

+ Noch kein Stand vorhanden. Mit „Neuer Stand“ eine grobe Leistungsbilanz auf + Basis der Vorlage KG 400 anlegen. +

+
+ ) : null} +
+ + {createDefaults ? ( + setCreateDefaults(null)} + onCreate={(input) => void handleCreate(input)} + /> + ) : null} +
+ ); +} diff --git a/src/db/migrations/0010_estimate_balances.sql b/src/db/migrations/0010_estimate_balances.sql new file mode 100644 index 0000000..645ccbe --- /dev/null +++ b/src/db/migrations/0010_estimate_balances.sql @@ -0,0 +1,43 @@ +CREATE TABLE `estimate_balances` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `name` text NOT NULL, + `work_stage` text, + `date_iso` text, + `reserve_av_percent` real DEFAULT 0 NOT NULL, + `reserve_sv_percent` real DEFAULT 0 NOT NULL, + `sort_order` integer DEFAULT 0 NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `estimate_balances_project_id_idx` ON `estimate_balances` (`project_id`);--> statement-breakpoint +CREATE TABLE `estimate_groups` ( + `id` text PRIMARY KEY NOT NULL, + `balance_id` text NOT NULL, + `cost_group` text DEFAULT '' NOT NULL, + `title` text NOT NULL, + `editor` text, + `sort_order` integer DEFAULT 0 NOT NULL, + FOREIGN KEY (`balance_id`) REFERENCES `estimate_balances`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `estimate_groups_balance_id_idx` ON `estimate_groups` (`balance_id`);--> statement-breakpoint +CREATE TABLE `estimate_rows` ( + `id` text PRIMARY KEY NOT NULL, + `group_id` text NOT NULL, + `sort_order` integer DEFAULT 0 NOT NULL, + `supply` text, + `circuit_ref` text, + `name` text DEFAULT '' NOT NULL, + `quantity` real DEFAULT 0 NOT NULL, + `unit` text DEFAULT 'piece' NOT NULL, + `connection` text, + `power_per_unit_w` real DEFAULT 0 NOT NULL, + `simultaneity_factor` real DEFAULT 1 NOT NULL, + `cos_phi` real DEFAULT 1 NOT NULL, + `safety_supply` integer DEFAULT false NOT NULL, + `remark` text, + FOREIGN KEY (`group_id`) REFERENCES `estimate_groups`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `estimate_rows_group_id_idx` ON `estimate_rows` (`group_id`); \ No newline at end of file diff --git a/src/db/migrations/meta/0010_snapshot.json b/src/db/migrations/meta/0010_snapshot.json new file mode 100644 index 0000000..869d504 --- /dev/null +++ b/src/db/migrations/meta/0010_snapshot.json @@ -0,0 +1,2931 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "6df688bd-a78a-46a1-ba7a-4068119bf8bd", + "prevId": "2cd9adef-2f08-4635-b3d9-ecf71f624c7f", + "tables": { + "buildings": { + "name": "buildings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "buildings_project_id_projects_id_fk": { + "name": "buildings_project_id_projects_id_fk", + "tableFrom": "buildings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_device_rows": { + "name": "circuit_device_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number_snapshot": { + "name": "room_number_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_name_snapshot": { + "name": "room_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manual_quantity": { + "name": "manual_quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_device_rows_circuit_id_idx": { + "name": "circuit_device_rows_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "circuit_device_rows_circuit_id_circuits_id_fk": { + "name": "circuit_device_rows_circuit_id_circuits_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_device_rows_linked_project_device_id_project_devices_id_fk": { + "name": "circuit_device_rows_linked_project_device_id_project_devices_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "circuit_device_rows_room_id_rooms_id_fk": { + "name": "circuit_device_rows_room_id_rooms_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_list_equipment_identifiers": { + "name": "circuit_list_equipment_identifiers", + "columns": { + "owner_type": { + "name": "owner_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_list_equipment_identifiers_owner_unique": { + "name": "circuit_list_equipment_identifiers_owner_unique", + "columns": [ + "owner_type", + "owner_id" + ], + "isUnique": true + }, + "circuit_list_equipment_identifiers_list_identifier_unique": { + "name": "circuit_list_equipment_identifiers_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_list_equipment_identifiers", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_lists": { + "name": "circuit_lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_lists_distribution_board_id_unique": { + "name": "circuit_lists_distribution_board_id_unique", + "columns": [ + "distribution_board_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_lists_project_id_projects_id_fk": { + "name": "circuit_lists_project_id_projects_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_lists_distribution_board_id_distribution_boards_id_fk": { + "name": "circuit_lists_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_protection_devices": { + "name": "circuit_protection_devices", + "columns": { + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "circuit_protection_devices_circuit_id_circuits_id_fk": { + "name": "circuit_protection_devices_circuit_id_circuits_id_fk", + "tableFrom": "circuit_protection_devices", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_sections": { + "name": "circuit_sections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "group_number": { + "name": "group_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_sections_list_key_unique": { + "name": "circuit_sections_list_key_unique", + "columns": [ + "circuit_list_id", + "key" + ], + "isUnique": true + }, + "circuit_sections_list_prefix_unique": { + "name": "circuit_sections_list_prefix_unique", + "columns": [ + "circuit_list_id", + "prefix" + ], + "isUnique": true + }, + "circuit_sections_list_category_group_unique": { + "name": "circuit_sections_list_category_group_unique", + "columns": [ + "circuit_list_id", + "category", + "group_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_sections_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_sections_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_sections", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuits": { + "name": "circuits", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "cable_type": { + "name": "cable_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_cross_section": { + "name": "cable_cross_section", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_length": { + "name": "cable_length", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_assignment": { + "name": "rcd_assignment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "terminal_designation": { + "name": "terminal_designation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage": { + "name": "voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "control_requirement": { + "name": "control_requirement", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_reserve": { + "name": "is_reserve", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuits_section_id_idx": { + "name": "circuits_section_id_idx", + "columns": [ + "section_id" + ], + "isUnique": false + }, + "circuits_list_equipment_identifier_unique": { + "name": "circuits_list_equipment_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuits_circuit_list_id_circuit_lists_id_fk": { + "name": "circuits_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuits_section_id_circuit_sections_id_fk": { + "name": "circuits_section_id_circuit_sections_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_component_protection_devices": { + "name": "distribution_board_component_protection_devices", + "columns": { + "component_id": { + "name": "component_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk": { + "name": "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk", + "tableFrom": "distribution_board_component_protection_devices", + "tableTo": "distribution_board_components", + "columnsFrom": [ + "component_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_components": { + "name": "distribution_board_components", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "placement": { + "name": "placement", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "distribution_board_components_list_identifier_unique": { + "name": "distribution_board_components_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + }, + "distribution_board_components_section_role_unique": { + "name": "distribution_board_components_section_role_unique", + "columns": [ + "section_id", + "role" + ], + "isUnique": true + } + }, + "foreignKeys": { + "distribution_board_components_circuit_list_id_circuit_lists_id_fk": { + "name": "distribution_board_components_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_board_components_section_id_circuit_sections_id_fk": { + "name": "distribution_board_components_section_id_circuit_sections_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_boards": { + "name": "distribution_boards", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "supply_type": { + "name": "supply_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "board_number": { + "name": "board_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fed_from": { + "name": "fed_from", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "distribution_boards_project_id_projects_id_fk": { + "name": "distribution_boards_project_id_projects_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_boards_floor_id_floors_id_fk": { + "name": "distribution_boards_floor_id_floors_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_assets": { + "name": "document_branding_assets", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "data": { + "name": "data", + "type": "blob", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_settings": { + "name": "document_branding_settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_balances": { + "name": "estimate_balances", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date_iso": { + "name": "date_iso", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reserve_av_percent": { + "name": "reserve_av_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "reserve_sv_percent": { + "name": "reserve_sv_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_balances_project_id_idx": { + "name": "estimate_balances_project_id_idx", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_balances_project_id_projects_id_fk": { + "name": "estimate_balances_project_id_projects_id_fk", + "tableFrom": "estimate_balances", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_groups": { + "name": "estimate_groups", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "balance_id": { + "name": "balance_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "editor": { + "name": "editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_groups_balance_id_idx": { + "name": "estimate_groups_balance_id_idx", + "columns": [ + "balance_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_groups_balance_id_estimate_balances_id_fk": { + "name": "estimate_groups_balance_id_estimate_balances_id_fk", + "tableFrom": "estimate_groups", + "tableTo": "estimate_balances", + "columnsFrom": [ + "balance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_rows": { + "name": "estimate_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "supply": { + "name": "supply", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_ref": { + "name": "circuit_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "quantity": { + "name": "quantity", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'piece'" + }, + "connection": { + "name": "connection", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_per_unit_w": { + "name": "power_per_unit_w", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "safety_supply": { + "name": "safety_supply", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "estimate_rows_group_id_idx": { + "name": "estimate_rows_group_id_idx", + "columns": [ + "group_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_rows_group_id_estimate_groups_id_fk": { + "name": "estimate_rows_group_id_estimate_groups_id_fk", + "tableFrom": "estimate_rows", + "tableTo": "estimate_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_csv_configurations": { + "name": "external_csv_configurations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_version": { + "name": "configuration_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration": { + "name": "configuration", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "external_csv_configurations_project_id_unique": { + "name": "external_csv_configurations_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_csv_configurations_project_id_projects_id_fk": { + "name": "external_csv_configurations_project_id_projects_id_fk", + "tableFrom": "external_csv_configurations", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_import_batches": { + "name": "external_import_batches", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "import_kind": { + "name": "import_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "imported_at_iso": { + "name": "imported_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_project_revision": { + "name": "applied_project_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_version": { + "name": "configuration_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_snapshot": { + "name": "configuration_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_bytes": { + "name": "original_bytes", + "type": "blob", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "document": { + "name": "document", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "external_import_batches_project_revision_idx": { + "name": "external_import_batches_project_revision_idx", + "columns": [ + "project_id", + "applied_project_revision" + ], + "isUnique": false + }, + "external_import_batches_source_imported_idx": { + "name": "external_import_batches_source_imported_idx", + "columns": [ + "source_id", + "imported_at_iso" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_import_batches_project_id_projects_id_fk": { + "name": "external_import_batches_project_id_projects_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_import_batches_source_id_external_model_sources_id_fk": { + "name": "external_import_batches_source_id_external_model_sources_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_objects": { + "name": "external_model_objects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ifc_guid": { + "name": "ifc_guid", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_import_batch_id": { + "name": "last_seen_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_accepted_import_batch_id": { + "name": "last_accepted_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_source_values": { + "name": "accepted_source_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "planning_values": { + "name": "planning_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_room_mapping_id": { + "name": "external_room_mapping_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_device_row_id": { + "name": "circuit_device_row_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "presence_status": { + "name": "presence_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'present'" + } + }, + "indexes": { + "external_model_objects_source_ifc_guid_unique": { + "name": "external_model_objects_source_ifc_guid_unique", + "columns": [ + "source_id", + "ifc_guid" + ], + "isUnique": true + }, + "external_model_objects_project_presence_idx": { + "name": "external_model_objects_project_presence_idx", + "columns": [ + "project_id", + "presence_status" + ], + "isUnique": false + }, + "external_model_objects_distribution_board_idx": { + "name": "external_model_objects_distribution_board_idx", + "columns": [ + "distribution_board_id" + ], + "isUnique": false + }, + "external_model_objects_circuit_device_row_idx": { + "name": "external_model_objects_circuit_device_row_idx", + "columns": [ + "circuit_device_row_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_model_objects_project_id_projects_id_fk": { + "name": "external_model_objects_project_id_projects_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_source_id_external_model_sources_id_fk": { + "name": "external_model_objects_source_id_external_model_sources_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_seen_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_accepted_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk": { + "name": "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_room_mappings", + "columnsFrom": [ + "external_room_mapping_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_distribution_board_id_distribution_boards_id_fk": { + "name": "external_model_objects_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_linked_project_device_id_project_devices_id_fk": { + "name": "external_model_objects_linked_project_device_id_project_devices_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk": { + "name": "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "circuit_device_rows", + "columnsFrom": [ + "circuit_device_row_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_sources": { + "name": "external_model_sources", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'revit_csv'" + } + }, + "indexes": { + "external_model_sources_project_type_unique": { + "name": "external_model_sources_project_type_unique", + "columns": [ + "project_id", + "source_type" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_model_sources_project_id_projects_id_fk": { + "name": "external_model_sources_project_id_projects_id_fk", + "tableFrom": "external_model_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_room_mappings": { + "name": "external_room_mappings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "normalized_source_room_key": { + "name": "normalized_source_room_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_floor_name": { + "name": "source_floor_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_room_number": { + "name": "source_room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_room_name": { + "name": "source_room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_distribution_board_id": { + "name": "default_distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "external_room_mappings_source_key_unique": { + "name": "external_room_mappings_source_key_unique", + "columns": [ + "source_id", + "normalized_source_room_key" + ], + "isUnique": true + }, + "external_room_mappings_project_room_idx": { + "name": "external_room_mappings_project_room_idx", + "columns": [ + "project_id", + "room_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_room_mappings_project_id_projects_id_fk": { + "name": "external_room_mappings_project_id_projects_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_source_id_external_model_sources_id_fk": { + "name": "external_room_mappings_source_id_external_model_sources_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_room_id_rooms_id_fk": { + "name": "external_room_mappings_room_id_rooms_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk": { + "name": "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "distribution_boards", + "columnsFrom": [ + "default_distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "floors": { + "name": "floors", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "building_id": { + "name": "building_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "floors_project_id_projects_id_fk": { + "name": "floors_project_id_projects_id_fk", + "tableFrom": "floors", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "floors_building_id_buildings_id_fk": { + "name": "floors_building_id_buildings_id_fk", + "tableFrom": "floors", + "tableTo": "buildings", + "columnsFrom": [ + "building_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "global_devices": { + "name": "global_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installed_power_per_unit_kw": { + "name": "installed_power_per_unit_kw", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "demand_factor": { + "name": "demand_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phase_count": { + "name": "phase_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_factor": { + "name": "power_factor", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_change_sets": { + "name": "project_change_sets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_revision_id": { + "name": "project_revision_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command_type": { + "name": "command_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_schema_version": { + "name": "payload_schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "forward_payload_json": { + "name": "forward_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "inverse_payload_json": { + "name": "inverse_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_change_sets_revision_unique": { + "name": "project_change_sets_revision_unique", + "columns": [ + "project_revision_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_change_sets_project_revision_id_project_revisions_id_fk": { + "name": "project_change_sets_project_revision_id_project_revisions_id_fk", + "tableFrom": "project_change_sets", + "tableTo": "project_revisions", + "columnsFrom": [ + "project_revision_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_devices": { + "name": "project_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'single_phase'" + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "project_devices_project_id_projects_id_fk": { + "name": "project_devices_project_id_projects_id_fk", + "tableFrom": "project_devices", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_history_stack_entries": { + "name": "project_history_stack_entries", + "columns": { + "change_set_id": { + "name": "change_set_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_history_stack_entries_position_unique": { + "name": "project_history_stack_entries_position_unique", + "columns": [ + "project_id", + "stack", + "position" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_history_stack_entries_change_set_id_project_change_sets_id_fk": { + "name": "project_history_stack_entries_change_set_id_project_change_sets_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "project_change_sets", + "columnsFrom": [ + "change_set_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_history_stack_entries_project_id_projects_id_fk": { + "name": "project_history_stack_entries_project_id_projects_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "project_history_stack_entries_stack_check": { + "name": "project_history_stack_entries_stack_check", + "value": "\"project_history_stack_entries\".\"stack\" in ('undo', 'redo')" + } + } + }, + "project_revisions": { + "name": "project_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision_number": { + "name": "revision_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_revisions_project_number_unique": { + "name": "project_revisions_project_number_unique", + "columns": [ + "project_id", + "revision_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_revisions_project_id_projects_id_fk": { + "name": "project_revisions_project_id_projects_id_fk", + "tableFrom": "project_revisions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_snapshots": { + "name": "project_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_revision": { + "name": "source_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'named'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_sha256": { + "name": "payload_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_actor_id": { + "name": "created_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_snapshots_project_created_idx": { + "name": "project_snapshots_project_created_idx", + "columns": [ + "project_id", + "created_at_iso" + ], + "isUnique": false + }, + "project_snapshots_project_kind_revision_idx": { + "name": "project_snapshots_project_kind_revision_idx", + "columns": [ + "project_id", + "kind", + "source_revision" + ], + "isUnique": false + }, + "project_snapshots_project_name_unique": { + "name": "project_snapshots_project_name_unique", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_snapshots_project_id_projects_id_fk": { + "name": "project_snapshots_project_id_projects_id_fk", + "tableFrom": "project_snapshots", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "internal_project_number": { + "name": "internal_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "external_project_number": { + "name": "external_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "building_owner": { + "name": "building_owner", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_public_building": { + "name": "is_public_building", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "single_phase_voltage_v": { + "name": "single_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 230 + }, + "three_phase_voltage_v": { + "name": "three_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 400 + }, + "enabled_distribution_board_supply_types": { + "name": "enabled_distribution_board_supply_types", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"AV\",\"SV\",\"EV\",\"USV\",\"MSR\",\"SiBe\"]'" + }, + "site_address": { + "name": "site_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_lead": { + "name": "project_lead", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_editor": { + "name": "project_editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "current_revision": { + "name": "current_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "rooms": { + "name": "rooms", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number": { + "name": "room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_name": { + "name": "room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "rooms_project_id_projects_id_fk": { + "name": "rooms_project_id_projects_id_fk", + "tableFrom": "rooms", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "rooms_floor_id_floors_id_fk": { + "name": "rooms_floor_id_floors_id_fk", + "tableFrom": "rooms", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index 485b8f4..209a0a2 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -71,6 +71,13 @@ "when": 1790419185882, "tag": "0009_buildings", "breakpoints": true + }, + { + "idx": 10, + "version": "6", + "when": 1790425784626, + "tag": "0010_estimate_balances", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/repositories/estimate-balance-project-command.repository.ts b/src/db/repositories/estimate-balance-project-command.repository.ts new file mode 100644 index 0000000..b31ca78 --- /dev/null +++ b/src/db/repositories/estimate-balance-project-command.repository.ts @@ -0,0 +1,132 @@ +import { eq } from "drizzle-orm"; +import { + assertEstimateBalanceDeleteProjectCommand, + assertEstimateBalanceInsertProjectCommand, + assertEstimateBalanceUpdateProjectCommand, + createEstimateBalanceDeleteProjectCommand, + createEstimateBalanceInsertProjectCommand, + createEstimateBalanceUpdateProjectCommand, + estimateBalanceDeleteCommandType, + estimateBalanceInsertCommandType, + estimateBalanceUpdateCommandType, + normalizeEstimateBalanceSnapshot, + sameEstimateBalance, + type EstimateBalanceProjectCommand, +} from "../../estimate-balance/domain/estimate-balance-command.model.js"; +import type { + EstimateBalanceProjectCommandStore, + ExecuteEstimateBalanceCommandInput, +} from "../../estimate-balance/domain/estimate-balance-project-command.store.js"; +import type { EstimateBalanceSnapshot } from "../../shared/estimate-balance/estimate-balance.js"; +import type { AppDatabase } from "../database-context.js"; +import { estimateBalances } from "../schema/estimate-balances.js"; +import { projects } from "../schema/projects.js"; +import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { + deleteEstimateBalance, + insertEstimateBalance, + readEstimateBalances, +} from "./estimate-balance.persistence.js"; + +export class EstimateBalanceProjectCommandRepository + implements EstimateBalanceProjectCommandStore +{ + constructor(private readonly database: AppDatabase) {} + + execute(input: ExecuteEstimateBalanceCommandInput) { + return executeProjectCommandTransaction(this.database, input, (tx) => + this.applyCommand(tx, input.projectId, input.command) + ); + } + + private applyCommand( + database: AppDatabase, + projectId: string, + command: EstimateBalanceProjectCommand + ): EstimateBalanceProjectCommand { + switch (command.type) { + case estimateBalanceInsertCommandType: + assertEstimateBalanceInsertProjectCommand(command); + return this.insert(database, projectId, command.payload.balance); + case estimateBalanceDeleteCommandType: + assertEstimateBalanceDeleteProjectCommand(command); + return this.delete(database, projectId, command.payload.balance); + case estimateBalanceUpdateCommandType: + assertEstimateBalanceUpdateProjectCommand(command); + return this.update( + database, + projectId, + command.payload.expected, + command.payload.target + ); + } + } + + private insert( + database: AppDatabase, + projectId: string, + balance: EstimateBalanceSnapshot + ) { + if (balance.projectId !== projectId) { + throw new Error("Estimate-balance snapshot does not belong to project."); + } + const project = database + .select({ id: projects.id }) + .from(projects) + .where(eq(projects.id, projectId)) + .get(); + if (!project) { + throw new Error("Project does not exist."); + } + const existing = database + .select({ id: estimateBalances.id }) + .from(estimateBalances) + .where(eq(estimateBalances.id, balance.id)) + .get(); + if (existing) { + throw new Error("Estimate-balance id already exists."); + } + const normalized = normalizeEstimateBalanceSnapshot(balance); + insertEstimateBalance(database, normalized); + return createEstimateBalanceDeleteProjectCommand(normalized); + } + + private delete( + database: AppDatabase, + projectId: string, + expected: EstimateBalanceSnapshot + ) { + this.assertPersisted(database, projectId, expected, "deletion"); + if (deleteEstimateBalance(database, projectId, expected.id) !== 1) { + throw new Error("Estimate balance could not be deleted."); + } + return createEstimateBalanceInsertProjectCommand(expected); + } + + private update( + database: AppDatabase, + projectId: string, + expected: EstimateBalanceSnapshot, + target: EstimateBalanceSnapshot + ) { + this.assertPersisted(database, projectId, expected, "update"); + // Group and row ids stay stable; replacing the whole document keeps the + // command exact and its inverse trivially the swapped pair. + deleteEstimateBalance(database, projectId, expected.id); + const normalized = normalizeEstimateBalanceSnapshot(target); + insertEstimateBalance(database, normalized); + return createEstimateBalanceUpdateProjectCommand(normalized, expected); + } + + private assertPersisted( + database: AppDatabase, + projectId: string, + expected: EstimateBalanceSnapshot, + action: string + ) { + const [persisted] = readEstimateBalances(database, projectId, expected.id); + if (!persisted || !sameEstimateBalance(persisted, expected)) { + throw new Error(`Estimate balance changed before ${action}.`); + } + } +} diff --git a/src/db/repositories/estimate-balance.persistence.ts b/src/db/repositories/estimate-balance.persistence.ts new file mode 100644 index 0000000..4d59aa6 --- /dev/null +++ b/src/db/repositories/estimate-balance.persistence.ts @@ -0,0 +1,121 @@ +import { and, asc, eq, inArray } from "drizzle-orm"; +import type { EstimateBalanceSnapshot } from "../../shared/estimate-balance/estimate-balance.js"; +import type { AppDatabase } from "../database-context.js"; +import { + estimateBalances, + estimateGroups, + estimateRows, +} from "../schema/estimate-balances.js"; + +/** Reads complete balance documents of a project, ordered like the UI shows them. */ +export function readEstimateBalances( + database: AppDatabase, + projectId: string, + balanceId?: string +): EstimateBalanceSnapshot[] { + const balances = database + .select() + .from(estimateBalances) + .where( + balanceId + ? and( + eq(estimateBalances.projectId, projectId), + eq(estimateBalances.id, balanceId) + ) + : eq(estimateBalances.projectId, projectId) + ) + .orderBy(asc(estimateBalances.sortOrder), asc(estimateBalances.id)) + .all(); + if (!balances.length) { + return []; + } + const groups = database + .select() + .from(estimateGroups) + .where(inArray(estimateGroups.balanceId, balances.map((balance) => balance.id))) + .orderBy(asc(estimateGroups.sortOrder), asc(estimateGroups.id)) + .all(); + const rows = groups.length + ? database + .select() + .from(estimateRows) + .where(inArray(estimateRows.groupId, groups.map((group) => group.id))) + .orderBy(asc(estimateRows.sortOrder), asc(estimateRows.id)) + .all() + : []; + return balances.map((balance) => ({ + id: balance.id, + projectId: balance.projectId, + name: balance.name, + workStage: balance.workStage, + dateIso: balance.dateIso, + reserveAvPercent: balance.reserveAvPercent, + reserveSvPercent: balance.reserveSvPercent, + sortOrder: balance.sortOrder, + groups: groups + .filter((group) => group.balanceId === balance.id) + .map((group) => ({ + id: group.id, + costGroup: group.costGroup, + title: group.title, + editor: group.editor, + sortOrder: group.sortOrder, + rows: rows + .filter((row) => row.groupId === group.id) + .map(({ groupId: _groupId, ...row }) => row), + })), + })); +} + +/** Writes a complete balance document (the caller removed an older version first). */ +export function insertEstimateBalance( + database: AppDatabase, + balance: EstimateBalanceSnapshot +) { + database + .insert(estimateBalances) + .values({ + id: balance.id, + projectId: balance.projectId, + name: balance.name, + workStage: balance.workStage, + dateIso: balance.dateIso, + reserveAvPercent: balance.reserveAvPercent, + reserveSvPercent: balance.reserveSvPercent, + sortOrder: balance.sortOrder, + }) + .run(); + for (const group of balance.groups) { + database + .insert(estimateGroups) + .values({ + id: group.id, + balanceId: balance.id, + costGroup: group.costGroup, + title: group.title, + editor: group.editor, + sortOrder: group.sortOrder, + }) + .run(); + if (group.rows.length) { + database + .insert(estimateRows) + .values(group.rows.map((row) => ({ ...row, groupId: group.id }))) + .run(); + } + } +} + +/** Removes a balance with its groups and rows (foreign keys cascade). */ +export function deleteEstimateBalance( + database: AppDatabase, + projectId: string, + balanceId: string +) { + return database + .delete(estimateBalances) + .where( + and(eq(estimateBalances.projectId, projectId), eq(estimateBalances.id, balanceId)) + ) + .run().changes; +} diff --git a/src/db/repositories/estimate-balance.repository.ts b/src/db/repositories/estimate-balance.repository.ts new file mode 100644 index 0000000..4c70d27 --- /dev/null +++ b/src/db/repositories/estimate-balance.repository.ts @@ -0,0 +1,60 @@ +import { asc, eq } from "drizzle-orm"; +import type { + DetailedDeviceRowPower, + EstimateBalanceSnapshot, +} from "../../shared/estimate-balance/estimate-balance.js"; +import { calculateRowTotalPower } from "../../domain/calculations/circuit-power-calculation.js"; +import type { AppDatabase } from "../database-context.js"; +import { circuitDeviceRows } from "../schema/circuit-device-rows.js"; +import { circuitLists } from "../schema/circuit-lists.js"; +import { circuits } from "../schema/circuits.js"; +import { estimateBalances } from "../schema/estimate-balances.js"; +import { readEstimateBalances } from "./estimate-balance.persistence.js"; + +/** Read side of the estimate-balance module; writes go through commands. */ +export class EstimateBalanceRepository { + constructor(private readonly database: AppDatabase) {} + + listByProject(projectId: string): EstimateBalanceSnapshot[] { + return readEstimateBalances(this.database, projectId); + } + + findById(projectId: string, balanceId: string): EstimateBalanceSnapshot | null { + return readEstimateBalances(this.database, projectId, balanceId)[0] ?? null; + } + + nextSortOrder(projectId: string): number { + const rows = this.database + .select({ sortOrder: estimateBalances.sortOrder }) + .from(estimateBalances) + .where(eq(estimateBalances.projectId, projectId)) + .orderBy(asc(estimateBalances.sortOrder)) + .all(); + return rows.length ? Math.max(...rows.map((row) => row.sortOrder)) + 1 : 0; + } + + /** + * Device rows of all circuit lists of the project with their total power + * (quantity · power per unit · device GZF, like the circuit tree). + */ + listDetailedDeviceRowPower(projectId: string): DetailedDeviceRowPower[] { + return this.database + .select({ + costGroup: circuitDeviceRows.costGroup, + quantity: circuitDeviceRows.quantity, + powerPerUnit: circuitDeviceRows.powerPerUnit, + simultaneityFactor: circuitDeviceRows.simultaneityFactor, + cosPhi: circuitDeviceRows.cosPhi, + }) + .from(circuitDeviceRows) + .innerJoin(circuits, eq(circuits.id, circuitDeviceRows.circuitId)) + .innerJoin(circuitLists, eq(circuitLists.id, circuits.circuitListId)) + .where(eq(circuitLists.projectId, projectId)) + .all() + .map((row) => ({ + costGroup: row.costGroup, + kw: calculateRowTotalPower(row.quantity, row.powerPerUnit, row.simultaneityFactor), + cosPhi: row.cosPhi, + })); + } +} diff --git a/src/db/schema/estimate-balances.ts b/src/db/schema/estimate-balances.ts new file mode 100644 index 0000000..81420f1 --- /dev/null +++ b/src/db/schema/estimate-balances.ts @@ -0,0 +1,61 @@ +import { index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { projects } from "./projects.js"; + +// Grobe Leistungsbilanz (LPH 2/3): a separate module without links into the +// circuit structure. See docs/estimate-balance.md. +export const estimateBalances = sqliteTable( + "estimate_balances", + { + id: text("id").primaryKey(), + projectId: text("project_id") + .notNull() + .references(() => projects.id, { onDelete: "cascade" }), + name: text("name").notNull(), + workStage: text("work_stage"), + dateIso: text("date_iso"), + reserveAvPercent: real("reserve_av_percent").notNull().default(0), + reserveSvPercent: real("reserve_sv_percent").notNull().default(0), + sortOrder: integer("sort_order").notNull().default(0), + }, + (table) => [index("estimate_balances_project_id_idx").on(table.projectId)] +); + +export const estimateGroups = sqliteTable( + "estimate_groups", + { + id: text("id").primaryKey(), + balanceId: text("balance_id") + .notNull() + .references(() => estimateBalances.id, { onDelete: "cascade" }), + costGroup: text("cost_group").notNull().default(""), + title: text("title").notNull(), + editor: text("editor"), + sortOrder: integer("sort_order").notNull().default(0), + }, + (table) => [index("estimate_groups_balance_id_idx").on(table.balanceId)] +); + +export const estimateRows = sqliteTable( + "estimate_rows", + { + id: text("id").primaryKey(), + groupId: text("group_id") + .notNull() + .references(() => estimateGroups.id, { onDelete: "cascade" }), + sortOrder: integer("sort_order").notNull().default(0), + supply: text("supply"), + circuitRef: text("circuit_ref"), + name: text("name").notNull().default(""), + quantity: real("quantity").notNull().default(0), + unit: text("unit", { enum: ["piece", "area"] }).notNull().default("piece"), + connection: text("connection", { enum: ["fixed", "socket"] }), + powerPerUnitW: real("power_per_unit_w").notNull().default(0), + simultaneityFactor: real("simultaneity_factor").notNull().default(1), + cosPhi: real("cos_phi").notNull().default(1), + safetySupply: integer("safety_supply", { mode: "boolean" }) + .notNull() + .default(false), + remark: text("remark"), + }, + (table) => [index("estimate_rows_group_id_idx").on(table.groupId)] +); diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index 91ee754..cf1f740 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -194,6 +194,15 @@ import { externalObjectDeleteCreatedCircuitCommandType, } from "../models/external-object-new-circuit-project-command.model.js"; import type { ExternalObjectNewCircuitProjectCommandStore } from "../ports/external-object-new-circuit-project-command.store.js"; +import { + assertEstimateBalanceDeleteProjectCommand, + assertEstimateBalanceInsertProjectCommand, + assertEstimateBalanceUpdateProjectCommand, + estimateBalanceDeleteCommandType, + estimateBalanceInsertCommandType, + estimateBalanceUpdateCommandType, +} from "../../estimate-balance/domain/estimate-balance-command.model.js"; +import type { EstimateBalanceProjectCommandStore } from "../../estimate-balance/domain/estimate-balance-project-command.store.js"; interface DispatchProjectCommandInput { projectId: string; @@ -233,7 +242,8 @@ export class ProjectCommandService implements ProjectCommandExecutor { private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore, private readonly externalObjectRowAssignmentStore?: ExternalObjectRowAssignmentProjectCommandStore, private readonly externalObjectNewRowStore?: ExternalObjectNewRowProjectCommandStore, - private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore + private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore, + private readonly estimateBalanceStore?: EstimateBalanceProjectCommandStore ) {} executeUser( @@ -654,6 +664,24 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } + case estimateBalanceInsertCommandType: + case estimateBalanceDeleteCommandType: + case estimateBalanceUpdateCommandType: { + if (input.command.type === estimateBalanceInsertCommandType) { + assertEstimateBalanceInsertProjectCommand(input.command); + } else if (input.command.type === estimateBalanceDeleteCommandType) { + assertEstimateBalanceDeleteProjectCommand(input.command); + } else { + assertEstimateBalanceUpdateProjectCommand(input.command); + } + if (!this.estimateBalanceStore) { + throw new Error("Estimate-balance store is not available."); + } + return this.estimateBalanceStore.execute({ + ...input, + command: input.command, + }).revision; + } case projectStateRestoreCommandType: { assertProjectStateRestoreCommand(input.command); return this.projectStateRestoreStore.execute({ diff --git a/src/estimate-balance/api/estimate-balance-request.schemas.ts b/src/estimate-balance/api/estimate-balance-request.schemas.ts new file mode 100644 index 0000000..d1f1a5f --- /dev/null +++ b/src/estimate-balance/api/estimate-balance-request.schemas.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; +import { expectedProjectRevisionSchema } from "../../shared/validation/project-command.schemas.js"; + +export const createEstimateBalanceRequestSchema = z + .object({ + expectedRevision: expectedProjectRevisionSchema, + name: z.string().trim().min(1).max(200), + workStage: z.string().trim().max(50).nullable().optional(), + dateIso: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .nullable() + .optional(), + template: z.enum(["kg400", "empty", "copy"]), + copyFromBalanceId: z.string().trim().min(1).optional(), + }) + .strict() + .refine((input) => input.template !== "copy" || Boolean(input.copyFromBalanceId), { + message: "copyFromBalanceId is required for template copy", + path: ["copyFromBalanceId"], + }); + +export const updateEstimateBalanceRequestSchema = z + .object({ + expectedRevision: expectedProjectRevisionSchema, + // Validated in detail by parseEstimateBalanceSnapshot. + balance: z.unknown(), + }) + .strict(); + +export const deleteEstimateBalanceRequestSchema = z + .object({ expectedRevision: expectedProjectRevisionSchema }) + .strict(); diff --git a/src/estimate-balance/domain/estimate-balance-command.model.ts b/src/estimate-balance/domain/estimate-balance-command.model.ts new file mode 100644 index 0000000..44263e4 --- /dev/null +++ b/src/estimate-balance/domain/estimate-balance-command.model.ts @@ -0,0 +1,320 @@ +import crypto from "node:crypto"; +import { z } from "zod"; +import type { SerializedProjectCommand } from "../../domain/models/project-command.model.js"; +import { + estimateDefaultGroups, + type EstimateBalanceSnapshot, + type EstimateGroupSnapshot, +} from "../../shared/estimate-balance/estimate-balance.js"; + +export const estimateBalanceInsertCommandType = "estimate-balance.insert" as const; +export const estimateBalanceDeleteCommandType = "estimate-balance.delete" as const; +export const estimateBalanceUpdateCommandType = "estimate-balance.update" as const; +export const estimateBalanceCommandSchemaVersion = 1 as const; + +const idSchema = z.string().trim().min(1).max(100); +const trimmed = (max: number) => + z.string().max(max).refine((value) => value === value.trim(), { + message: "must be trimmed", + }); +const nullableText = (max: number) => + trimmed(max) + .refine((value) => value.length > 0, { message: "use null instead of empty" }) + .nullable(); +const finite = z.number().finite(); + +export const estimateRowSnapshotSchema = z + .object({ + id: idSchema, + sortOrder: z.number().int().min(0), + supply: nullableText(50), + circuitRef: nullableText(50), + name: trimmed(200), + quantity: finite.min(0), + unit: z.enum(["piece", "area"]), + connection: z.enum(["fixed", "socket"]).nullable(), + powerPerUnitW: finite.min(0), + simultaneityFactor: finite.min(0).max(1), + cosPhi: finite.gt(0).max(1), + safetySupply: z.boolean(), + remark: nullableText(500), + }) + .strict(); + +export const estimateGroupSnapshotSchema = z + .object({ + id: idSchema, + costGroup: trimmed(20), + title: trimmed(200).refine((value) => value.length > 0, { + message: "title must not be empty", + }), + editor: nullableText(100), + sortOrder: z.number().int().min(0), + rows: z.array(estimateRowSnapshotSchema).max(1000), + }) + .strict(); + +export const estimateBalanceSnapshotSchema = z + .object({ + id: idSchema, + projectId: idSchema, + name: trimmed(200).refine((value) => value.length > 0, { + message: "name must not be empty", + }), + workStage: nullableText(50), + dateIso: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .refine((value) => !Number.isNaN(Date.parse(`${value}T00:00:00Z`)), { + message: "invalid date", + }) + .nullable(), + reserveAvPercent: finite.min(0).max(100), + reserveSvPercent: finite.min(0).max(100), + sortOrder: z.number().int().min(0), + groups: z.array(estimateGroupSnapshotSchema).max(200), + }) + .strict() + .superRefine((balance, context) => { + const ids = new Set(); + for (const group of balance.groups) { + for (const id of [group.id, ...group.rows.map((row) => row.id)]) { + if (ids.has(id)) { + context.addIssue({ + code: "custom", + message: `duplicate id ${id}`, + path: ["groups"], + }); + } + ids.add(id); + } + } + }); + +export interface EstimateBalanceInsertProjectCommand + extends SerializedProjectCommand<{ balance: EstimateBalanceSnapshot }> { + schemaVersion: typeof estimateBalanceCommandSchemaVersion; + type: typeof estimateBalanceInsertCommandType; +} + +export interface EstimateBalanceDeleteProjectCommand + extends SerializedProjectCommand<{ balance: EstimateBalanceSnapshot }> { + schemaVersion: typeof estimateBalanceCommandSchemaVersion; + type: typeof estimateBalanceDeleteCommandType; +} + +export interface EstimateBalanceUpdateProjectCommand + extends SerializedProjectCommand<{ + expected: EstimateBalanceSnapshot; + target: EstimateBalanceSnapshot; + }> { + schemaVersion: typeof estimateBalanceCommandSchemaVersion; + type: typeof estimateBalanceUpdateCommandType; +} + +export type EstimateBalanceProjectCommand = + | EstimateBalanceInsertProjectCommand + | EstimateBalanceDeleteProjectCommand + | EstimateBalanceUpdateProjectCommand; + +/** Parses and normalizes a snapshot (sort orders of groups and rows follow the array order). */ +export function parseEstimateBalanceSnapshot(value: unknown): EstimateBalanceSnapshot { + const parsed = estimateBalanceSnapshotSchema.parse(value); + return normalizeEstimateBalanceSnapshot(parsed); +} + +export function normalizeEstimateBalanceSnapshot( + balance: EstimateBalanceSnapshot +): EstimateBalanceSnapshot { + return { + ...balance, + groups: balance.groups.map((group, groupIndex) => ({ + ...group, + sortOrder: groupIndex, + rows: group.rows.map((row, rowIndex) => ({ ...row, sortOrder: rowIndex })), + })), + }; +} + +/** Stable JSON for exact equality checks of two snapshots. */ +export function canonicalEstimateBalance(balance: EstimateBalanceSnapshot): string { + const normalized = normalizeEstimateBalanceSnapshot(balance); + return JSON.stringify({ + id: normalized.id, + projectId: normalized.projectId, + name: normalized.name, + workStage: normalized.workStage, + dateIso: normalized.dateIso, + reserveAvPercent: normalized.reserveAvPercent, + reserveSvPercent: normalized.reserveSvPercent, + sortOrder: normalized.sortOrder, + groups: normalized.groups.map((group) => ({ + id: group.id, + costGroup: group.costGroup, + title: group.title, + editor: group.editor, + sortOrder: group.sortOrder, + rows: group.rows.map((row) => ({ + id: row.id, + sortOrder: row.sortOrder, + supply: row.supply, + circuitRef: row.circuitRef, + name: row.name, + quantity: row.quantity, + unit: row.unit, + connection: row.connection, + powerPerUnitW: row.powerPerUnitW, + simultaneityFactor: row.simultaneityFactor, + cosPhi: row.cosPhi, + safetySupply: row.safetySupply, + remark: row.remark, + })), + })), + }); +} + +export function sameEstimateBalance( + left: EstimateBalanceSnapshot, + right: EstimateBalanceSnapshot +): boolean { + return canonicalEstimateBalance(left) === canonicalEstimateBalance(right); +} + +export function createEstimateBalanceSnapshot(input: { + projectId: string; + name: string; + workStage: string | null; + dateIso: string | null; + sortOrder: number; + template: "kg400" | "empty" | { copyFrom: EstimateBalanceSnapshot }; + createId?: () => string; +}): EstimateBalanceSnapshot { + const createId = input.createId ?? (() => crypto.randomUUID()); + let groups: EstimateGroupSnapshot[] = []; + let reserveAvPercent = 10; + let reserveSvPercent = 0; + if (input.template === "kg400") { + groups = estimateDefaultGroups.map((group, index) => ({ + id: createId(), + costGroup: group.costGroup, + title: group.title, + editor: null, + sortOrder: index, + rows: [], + })); + } else if (input.template !== "empty") { + const source = input.template.copyFrom; + reserveAvPercent = source.reserveAvPercent; + reserveSvPercent = source.reserveSvPercent; + groups = source.groups.map((group) => ({ + ...group, + id: createId(), + rows: group.rows.map((row) => ({ ...row, id: createId() })), + })); + } + return parseEstimateBalanceSnapshot({ + id: createId(), + projectId: input.projectId, + name: input.name.trim(), + workStage: input.workStage?.trim() || null, + dateIso: input.dateIso || null, + reserveAvPercent, + reserveSvPercent, + sortOrder: input.sortOrder, + groups, + }); +} + +export function createEstimateBalanceInsertProjectCommand( + balance: EstimateBalanceSnapshot +): EstimateBalanceInsertProjectCommand { + return { + schemaVersion: estimateBalanceCommandSchemaVersion, + type: estimateBalanceInsertCommandType, + payload: { balance: parseEstimateBalanceSnapshot(balance) }, + }; +} + +export function createEstimateBalanceDeleteProjectCommand( + balance: EstimateBalanceSnapshot +): EstimateBalanceDeleteProjectCommand { + return { + schemaVersion: estimateBalanceCommandSchemaVersion, + type: estimateBalanceDeleteCommandType, + payload: { balance: parseEstimateBalanceSnapshot(balance) }, + }; +} + +export function createEstimateBalanceUpdateProjectCommand( + expected: EstimateBalanceSnapshot, + target: EstimateBalanceSnapshot +): EstimateBalanceUpdateProjectCommand { + const payload = { + expected: parseEstimateBalanceSnapshot(expected), + target: parseEstimateBalanceSnapshot(target), + }; + assertMatchingUpdate(payload.expected, payload.target); + return { + schemaVersion: estimateBalanceCommandSchemaVersion, + type: estimateBalanceUpdateCommandType, + payload, + }; +} + +function assertMatchingUpdate( + expected: EstimateBalanceSnapshot, + target: EstimateBalanceSnapshot +) { + if (expected.id !== target.id || expected.projectId !== target.projectId) { + throw new Error("Estimate-balance update must keep id and project."); + } + if (sameEstimateBalance(expected, target)) { + throw new Error("Estimate-balance update must change the balance."); + } +} + +function assertCommandShape( + command: SerializedProjectCommand, + type: string, + keys: string[] +): Record { + const payload = command.payload; + if ( + command.schemaVersion !== estimateBalanceCommandSchemaVersion || + command.type !== type || + payload === null || + typeof payload !== "object" || + Array.isArray(payload) || + Object.keys(payload).sort().join(",") !== [...keys].sort().join(",") + ) { + throw new Error("Unsupported estimate-balance command."); + } + return payload as Record; +} + +export function assertEstimateBalanceInsertProjectCommand( + command: SerializedProjectCommand +): asserts command is EstimateBalanceInsertProjectCommand { + const payload = assertCommandShape(command, estimateBalanceInsertCommandType, ["balance"]); + parseEstimateBalanceSnapshot(payload.balance); +} + +export function assertEstimateBalanceDeleteProjectCommand( + command: SerializedProjectCommand +): asserts command is EstimateBalanceDeleteProjectCommand { + const payload = assertCommandShape(command, estimateBalanceDeleteCommandType, ["balance"]); + parseEstimateBalanceSnapshot(payload.balance); +} + +export function assertEstimateBalanceUpdateProjectCommand( + command: SerializedProjectCommand +): asserts command is EstimateBalanceUpdateProjectCommand { + const payload = assertCommandShape(command, estimateBalanceUpdateCommandType, [ + "expected", + "target", + ]); + assertMatchingUpdate( + parseEstimateBalanceSnapshot(payload.expected), + parseEstimateBalanceSnapshot(payload.target) + ); +} diff --git a/src/estimate-balance/domain/estimate-balance-project-command.store.ts b/src/estimate-balance/domain/estimate-balance-project-command.store.ts new file mode 100644 index 0000000..e5f7e04 --- /dev/null +++ b/src/estimate-balance/domain/estimate-balance-project-command.store.ts @@ -0,0 +1,24 @@ +import type { + AppendedProjectRevision, + ProjectRevisionSource, +} from "../../domain/ports/project-revision.store.js"; +import type { EstimateBalanceProjectCommand } from "./estimate-balance-command.model.js"; + +export interface ExecuteEstimateBalanceCommandInput { + projectId: string; + expectedRevision: number; + source: ProjectRevisionSource; + description?: string; + actorId?: string; + historyTargetChangeSetId?: string; + command: EstimateBalanceProjectCommand; +} + +export interface ExecutedEstimateBalanceCommand { + revision: AppendedProjectRevision; + inverse: EstimateBalanceProjectCommand; +} + +export interface EstimateBalanceProjectCommandStore { + execute(input: ExecuteEstimateBalanceCommandInput): ExecutedEstimateBalanceCommand; +} diff --git a/src/frontend/components/Sidebar.tsx b/src/frontend/components/Sidebar.tsx index a94378e..395cd7c 100644 --- a/src/frontend/components/Sidebar.tsx +++ b/src/frontend/components/Sidebar.tsx @@ -17,6 +17,7 @@ const PROJECT_SECTIONS = [ // Separate project sub-routes (/projects/[id]/). const PROJECT_ROUTES = [ { segment: "struktur", label: "Gebäudestruktur", icon: "▥" }, + { segment: "grobbilanz", label: "Grobe Leistungsbilanz", icon: "Σ" }, ] as const; // Matches the project overview and all of its sub-routes (group 2 = rest). diff --git a/src/frontend/estimate-balance/estimate-balance-create-modal.tsx b/src/frontend/estimate-balance/estimate-balance-create-modal.tsx new file mode 100644 index 0000000..6d8f123 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-balance-create-modal.tsx @@ -0,0 +1,162 @@ +"use client"; + +import { type FormEvent, useState } from "react"; +import { FormModal } from "../components/form-modal"; +import type { + CreateEstimateBalanceInput, + EstimateBalanceDto, + EstimateBalanceTemplate, +} from "../types"; +import { estimateTextLimits } from "./estimate-balance-document"; +import { getTodayIsoDate } from "./estimate-balance-format"; + +export interface EstimateBalanceCreateDefaults { + name?: string; + workStage?: string | null; + template?: EstimateBalanceTemplate; + copyFromBalanceId?: string; +} + +interface EstimateBalanceCreateModalProps { + balances: EstimateBalanceDto[]; + defaults: EstimateBalanceCreateDefaults; + isSaving: boolean; + onClose: () => void; + onCreate: (input: CreateEstimateBalanceInput) => void; +} + +/** "Neuer Stand": name, LPH, date and the starting content. */ +export function EstimateBalanceCreateModal({ + balances, + defaults, + isSaving, + onClose, + onCreate, +}: EstimateBalanceCreateModalProps) { + const [name, setName] = useState(defaults.name ?? ""); + const [workStage, setWorkStage] = useState(defaults.workStage ?? ""); + const [dateIso, setDateIso] = useState(getTodayIsoDate()); + const [template, setTemplate] = useState( + defaults.template ?? "kg400" + ); + const [copyFromBalanceId, setCopyFromBalanceId] = useState( + defaults.copyFromBalanceId ?? balances[0]?.id ?? "" + ); + const isCopyInvalid = template === "copy" && !copyFromBalanceId; + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (!name.trim() || isCopyInvalid) { + return; + } + onCreate({ + name: name.trim(), + workStage: workStage.trim() || null, + dateIso: dateIso || null, + template, + ...(template === "copy" ? { copyFromBalanceId } : {}), + }); + } + + return ( + +
+
+ + setName(event.target.value)} + placeholder="z. B. Entwurfsplanung" + required + value={name} + /> +
+
+ + setWorkStage(event.target.value)} + placeholder="z. B. LPH 3" + value={workStage} + /> +
+
+ + setDateIso(event.target.value)} + type="date" + value={dateIso} + /> +
+
+ + +
+ {template === "copy" ? ( +
+ + +
+ ) : null} +
+

+ {template === "kg400" + ? "Legt die Kostengruppen 410 bis 480 und „Allgemein“ ohne Einträge an." + : template === "empty" + ? "Legt einen Stand ohne Kostengruppen an." + : "Übernimmt alle Kostengruppen und Zeilen des gewählten Stands."} +

+
+
+
+ ); +} diff --git a/src/frontend/estimate-balance/estimate-balance-document.ts b/src/frontend/estimate-balance/estimate-balance-document.ts new file mode 100644 index 0000000..0049dc2 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-balance-document.ts @@ -0,0 +1,301 @@ +// Pure, immutable editing rules for one "Grobe Leistungsbilanz" document. +// The editor keeps the complete document as local draft and saves it as a +// whole (PUT), so every edit is a function draft → new draft. +import type { + EstimateBalanceSnapshot, + EstimateGroupSnapshot, + EstimateRowSnapshot, +} from "../../shared/estimate-balance/estimate-balance"; +import { createClientId } from "../utils/client-id"; + +export type MoveDirection = -1 | 1; + +/** Maximum text lengths accepted by the server. */ +export const estimateTextLimits = { + balanceName: 200, + workStage: 50, + costGroup: 20, + groupTitle: 200, + groupEditor: 100, + supply: 50, + circuitRef: 50, + rowName: 200, + remark: 500, +} as const; + +export type EstimateRowPatch = Partial>; +export type EstimateGroupPatch = Partial>; + +export function createEstimateRow( + sortOrder: number, + createId: () => string = createClientId +): EstimateRowSnapshot { + return { + id: createId(), + sortOrder, + supply: null, + circuitRef: null, + name: "", + quantity: 1, + unit: "piece", + connection: null, + powerPerUnitW: 0, + simultaneityFactor: 1, + cosPhi: 1, + safetySupply: false, + remark: null, + }; +} + +export function createEstimateGroup( + input: { costGroup: string; title: string; editor?: string | null }, + sortOrder: number, + createId: () => string = createClientId +): EstimateGroupSnapshot { + return { + id: createId(), + costGroup: input.costGroup, + title: input.title, + editor: input.editor ?? null, + sortOrder, + rows: [], + }; +} + +function bySortOrder(left: T, right: T) { + return left.sortOrder - right.sortOrder; +} + +/** Orders groups and rows by sortOrder and renumbers both from 0. */ +export function normalizeEstimateSortOrder( + balance: EstimateBalanceSnapshot +): EstimateBalanceSnapshot { + return { + ...balance, + groups: [...balance.groups].sort(bySortOrder).map((group, groupIndex) => ({ + ...group, + sortOrder: groupIndex, + rows: [...group.rows].sort(bySortOrder).map((row, rowIndex) => ({ + ...row, + sortOrder: rowIndex, + })), + })), + }; +} + +function renumber(items: T[]): T[] { + return items.map((item, index) => + item.sortOrder === index ? item : { ...item, sortOrder: index } + ); +} + +function mapGroup( + balance: EstimateBalanceSnapshot, + groupId: string, + update: (group: EstimateGroupSnapshot) => EstimateGroupSnapshot +): EstimateBalanceSnapshot { + let changed = false; + const groups = balance.groups.map((group) => { + if (group.id !== groupId) { + return group; + } + const next = update(group); + changed = next !== group; + return next; + }); + // An unknown group or a no-op keeps the identical document. + return changed ? { ...balance, groups } : balance; +} + +function moveItem(items: T[], index: number, direction: MoveDirection): T[] | null { + const target = index + direction; + if (index < 0 || target < 0 || target >= items.length) { + return null; + } + const next = [...items]; + [next[index], next[target]] = [next[target]!, next[index]!]; + return next; +} + +/** Appends a row (or inserts it after `afterRowId`) and returns the new row id. */ +export function addEstimateRow( + balance: EstimateBalanceSnapshot, + groupId: string, + options: { afterRowId?: string; createId?: () => string } = {} +): { balance: EstimateBalanceSnapshot; rowId: string | null } { + let rowId: string | null = null; + const next = mapGroup(balance, groupId, (group) => { + const row = createEstimateRow(0, options.createId); + rowId = row.id; + const afterIndex = options.afterRowId + ? group.rows.findIndex((candidate) => candidate.id === options.afterRowId) + : -1; + const rows = [...group.rows]; + rows.splice(afterIndex >= 0 ? afterIndex + 1 : rows.length, 0, row); + return { ...group, rows: renumber(rows) }; + }); + return { balance: next, rowId }; +} + +export function updateEstimateRow( + balance: EstimateBalanceSnapshot, + groupId: string, + rowId: string, + patch: EstimateRowPatch +): EstimateBalanceSnapshot { + return mapGroup(balance, groupId, (group) => ({ + ...group, + rows: group.rows.map((row) => (row.id === rowId ? { ...row, ...patch } : row)), + })); +} + +export function removeEstimateRow( + balance: EstimateBalanceSnapshot, + groupId: string, + rowId: string +): EstimateBalanceSnapshot { + return mapGroup(balance, groupId, (group) => ({ + ...group, + rows: renumber(group.rows.filter((row) => row.id !== rowId)), + })); +} + +export function moveEstimateRow( + balance: EstimateBalanceSnapshot, + groupId: string, + rowId: string, + direction: MoveDirection +): EstimateBalanceSnapshot { + return mapGroup(balance, groupId, (group) => { + const rows = moveItem( + group.rows, + group.rows.findIndex((row) => row.id === rowId), + direction + ); + return rows ? { ...group, rows: renumber(rows) } : group; + }); +} + +/** Appends a group and returns its id. */ +export function addEstimateGroup( + balance: EstimateBalanceSnapshot, + input: { costGroup: string; title: string; editor?: string | null }, + createId: () => string = createClientId +): { balance: EstimateBalanceSnapshot; groupId: string } { + const group = createEstimateGroup(input, balance.groups.length, createId); + return { + balance: { ...balance, groups: renumber([...balance.groups, group]) }, + groupId: group.id, + }; +} + +export function updateEstimateGroup( + balance: EstimateBalanceSnapshot, + groupId: string, + patch: EstimateGroupPatch +): EstimateBalanceSnapshot { + return mapGroup(balance, groupId, (group) => ({ ...group, ...patch })); +} + +export function removeEstimateGroup( + balance: EstimateBalanceSnapshot, + groupId: string +): EstimateBalanceSnapshot { + const groups = balance.groups.filter((group) => group.id !== groupId); + return groups.length === balance.groups.length + ? balance + : { ...balance, groups: renumber(groups) }; +} + +export function moveEstimateGroup( + balance: EstimateBalanceSnapshot, + groupId: string, + direction: MoveDirection +): EstimateBalanceSnapshot { + const groups = moveItem( + balance.groups, + balance.groups.findIndex((group) => group.id === groupId), + direction + ); + return groups ? { ...balance, groups: renumber(groups) } : balance; +} + +function requiredText(value: string) { + return value.trim(); +} + +function optionalText(value: string | null) { + const trimmed = value?.trim() ?? ""; + return trimmed ? trimmed : null; +} + +/** + * The exact document the server accepts: strings trimmed, empty optional + * texts as null, sort orders continuous. Only fields of the shared snapshot + * type are copied, so no UI state can leak into the request. + */ +export function toSaveableEstimateBalance( + balance: EstimateBalanceSnapshot +): EstimateBalanceSnapshot { + const normalized = normalizeEstimateSortOrder(balance); + return { + id: normalized.id, + projectId: normalized.projectId, + name: requiredText(normalized.name), + workStage: optionalText(normalized.workStage), + dateIso: normalized.dateIso || null, + reserveAvPercent: normalized.reserveAvPercent, + reserveSvPercent: normalized.reserveSvPercent, + sortOrder: normalized.sortOrder, + groups: normalized.groups.map((group) => ({ + id: group.id, + costGroup: requiredText(group.costGroup), + title: requiredText(group.title), + editor: optionalText(group.editor), + sortOrder: group.sortOrder, + rows: group.rows.map((row) => ({ + id: row.id, + sortOrder: row.sortOrder, + supply: optionalText(row.supply), + circuitRef: optionalText(row.circuitRef), + name: requiredText(row.name), + quantity: row.quantity, + unit: row.unit, + connection: row.connection, + powerPerUnitW: row.powerPerUnitW, + simultaneityFactor: row.simultaneityFactor, + cosPhi: row.cosPhi, + safetySupply: row.safetySupply, + remark: optionalText(row.remark), + })), + })), + }; +} + +/** Stable comparison key of the saveable document (dirty detection). */ +export function estimateBalanceFingerprint(balance: EstimateBalanceSnapshot): string { + return JSON.stringify(toSaveableEstimateBalance(balance)); +} + +/** + * German problems that would make the server reject the document. The + * editor never saves while this list is not empty. + */ +export function validateEstimateBalance(balance: EstimateBalanceSnapshot): string[] { + const problems: string[] = []; + const saveable = toSaveableEstimateBalance(balance); + if (!saveable.name) { + problems.push("Die Bezeichnung des Stands darf nicht leer sein."); + } + for (const group of saveable.groups) { + if (!group.title) { + problems.push(`Kostengruppe ${group.costGroup || "ohne Nummer"}: Titel fehlt.`); + } + } + return problems; +} + +export function createCopyName(name: string) { + const copyName = `${name.trim()} (Kopie)`; + return copyName.slice(0, estimateTextLimits.balanceName); +} diff --git a/src/frontend/estimate-balance/estimate-balance-format.ts b/src/frontend/estimate-balance/estimate-balance-format.ts new file mode 100644 index 0000000..85cddf3 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-balance-format.ts @@ -0,0 +1,122 @@ +// Pure parsing and formatting rules of the "Grobe Leistungsbilanz" editor. +// Numbers are entered and shown in German notation. As in the circuit list +// editor, only "," is accepted as decimal separator: a "." is ambiguous +// (decimal point or thousands separator) and is rejected instead of guessed. +import { roundEstimateValue } from "../../shared/estimate-balance/estimate-balance"; + +export type DecimalParseResult = + | { ok: true; value: number } + | { ok: false; error: string }; + +export interface DecimalRange { + min?: number; + /** Excludes `min` itself (e.g. cos φ > 0). */ + minExclusive?: boolean; + max?: number; +} + +const DECIMAL_PATTERN = /^[+-]?(\d+(,\d*)?|,\d+)$/; + +function formatBound(value: number) { + return value.toLocaleString("de-DE", { maximumFractionDigits: 6, useGrouping: false }); +} + +export function parseGermanDecimal(text: string, range: DecimalRange = {}): DecimalParseResult { + const trimmed = text.trim(); + if (!trimmed) { + return { ok: false, error: "Bitte einen Wert eingeben." }; + } + if (trimmed.includes(".")) { + return { ok: false, error: "Dezimalstellen mit Komma eingeben (z. B. 0,8)." }; + } + if (!DECIMAL_PATTERN.test(trimmed)) { + return { ok: false, error: "Ungültiger Zahlenwert." }; + } + const value = Number(trimmed.replace(",", ".")); + if (!Number.isFinite(value)) { + return { ok: false, error: "Ungültiger Zahlenwert." }; + } + if (range.min !== undefined) { + if (range.minExclusive ? value <= range.min : value < range.min) { + return { + ok: false, + error: range.minExclusive + ? `Der Wert muss größer als ${formatBound(range.min)} sein.` + : `Der Wert darf nicht kleiner als ${formatBound(range.min)} sein.`, + }; + } + } + if (range.max !== undefined && value > range.max) { + return { ok: false, error: `Der Wert darf nicht größer als ${formatBound(range.max)} sein.` }; + } + return { ok: true, value }; +} + +/** Value ranges accepted by the server for the numeric document fields. */ +export const estimateNumberRanges = { + quantity: { min: 0 }, + powerPerUnitW: { min: 0 }, + simultaneityFactor: { min: 0, max: 1 }, + cosPhi: { min: 0, minExclusive: true, max: 1 }, + reservePercent: { min: 0, max: 100 }, +} satisfies Record; + +/** + * Text of a numeric input field: German comma, no thousands separator, so the + * shown text can be parsed again unchanged. + */ +export function formatDecimalInput(value: number, maximumFractionDigits = 6): string { + return value.toLocaleString("de-DE", { maximumFractionDigits, useGrouping: false }); +} + +/** + * Read-only display of a calculated value with thousands separator ("1.200", + * "30,24"). The value is rounded half away from zero first, like Excel does + * (40,175 → 40,18 instead of the binary-rounded 40,17). + */ +export function formatGermanNumber( + value: number, + minimumFractionDigits: number, + maximumFractionDigits = minimumFractionDigits +): string { + const rounded = roundEstimateValue(value, maximumFractionDigits); + // "+ 0" turns -0 into 0 and avoids "-0,00". + return (rounded + 0).toLocaleString("de-DE", { + minimumFractionDigits, + maximumFractionDigits, + }); +} + +export function formatKw(value: number) { + return formatGermanNumber(value, 2); +} + +export function formatAmpere(value: number) { + return formatGermanNumber(value, 2); +} + +export function formatSignedKw(value: number) { + const text = formatKw(value); + return value > 0 && text !== "0,00" ? `+${text}` : text; +} + +export function formatDeltaPercent(value: number | null) { + if (value === null) { + return "–"; + } + const text = formatGermanNumber(value, 1); + return `${value > 0 && text !== "0,0" ? "+" : ""}${text} %`; +} + +/** "2026-09-26" → "26.09.2026"; empty/invalid → "–". */ +export function formatIsoDateGerman(dateIso: string | null): string { + const match = dateIso?.match(/^(\d{4})-(\d{2})-(\d{2})$/); + return match ? `${match[3]}.${match[2]}.${match[1]}` : "–"; +} + +/** Local calendar date as YYYY-MM-DD (not UTC, so late evenings stay today). */ +export function getTodayIsoDate(now: Date = new Date()): string { + const month = String(now.getMonth() + 1).padStart(2, "0"); + const day = String(now.getDate()).padStart(2, "0"); + return `${now.getFullYear()}-${month}-${day}`; +} diff --git a/src/frontend/estimate-balance/estimate-balance-sheet.tsx b/src/frontend/estimate-balance/estimate-balance-sheet.tsx new file mode 100644 index 0000000..debba7f --- /dev/null +++ b/src/frontend/estimate-balance/estimate-balance-sheet.tsx @@ -0,0 +1,652 @@ +"use client"; + +import type { ReactNode } from "react"; +import { ArrowDown, ArrowUp, Pencil, Plus, Trash2 } from "lucide-react"; +import { + calculateEstimateBalance, + calculateEstimateRow, + estimateRowConnectionLabels, + estimateRowUnitLabels, + type EstimateBalanceSnapshot, + type EstimateGroupSnapshot, + type EstimatePower, + type EstimateRowConnection, + type EstimateRowSnapshot, + type EstimateRowUnit, +} from "../../shared/estimate-balance/estimate-balance"; +import { + addEstimateRow, + estimateTextLimits, + moveEstimateGroup, + removeEstimateGroup, + removeEstimateRow, + updateEstimateGroup, + updateEstimateRow, + type EstimateRowPatch, +} from "./estimate-balance-document"; +import { + estimateNumberRanges, + formatAmpere, + formatDecimalInput, + formatKw, + parseGermanDecimal, + type DecimalRange, +} from "./estimate-balance-format"; +import { DraftInput } from "./estimate-draft-input"; + +export type EstimateBalanceUpdate = ( + update: (balance: EstimateBalanceSnapshot) => EstimateBalanceSnapshot +) => void; + +interface EstimateBalanceSheetProps { + balance: EstimateBalanceSnapshot; + disabled: boolean; + onAddGroup: () => void; + onChange: EstimateBalanceUpdate; + onEditGroup: (group: EstimateGroupSnapshot) => void; + onOpenGzfPicker: (groupId: string, rowId: string) => void; + onValidityChange: (fieldKey: string, isValid: boolean) => void; + threePhaseVoltageV: number; +} + +// Leading columns up to cos φ; the power columns follow. +const LEADING_COLUMN_COUNT = 10; +const COLUMN_COUNT = 17; + +function NumberInput({ + ariaLabel, + disabled, + fieldKey, + onCommit, + onValidityChange, + range, + value, +}: { + ariaLabel: string; + disabled: boolean; + fieldKey: string; + onCommit: (value: number) => void; + onValidityChange: (fieldKey: string, isValid: boolean) => void; + range: DecimalRange; + value: number; +}) { + return ( + formatDecimalInput(current)} + inputMode="decimal" + onCommit={onCommit} + onValidityChange={(isValid) => onValidityChange(fieldKey, isValid)} + parse={(text) => parseGermanDecimal(text, range)} + value={value} + /> + ); +} + +function TextInput({ + ariaLabel, + disabled, + maxLength, + onChange, + placeholder, + value, +}: { + ariaLabel: string; + disabled: boolean; + maxLength: number; + onChange: (value: string) => void; + placeholder?: string; + value: string | null; +}) { + return ( + <> + onChange(event.target.value)} + placeholder={placeholder} + type="text" + value={value ?? ""} + /> + {value ?? ""} + + ); +} + +function IconButton({ + children, + disabled, + label, + onClick, + variant = "secondary", +}: { + children: ReactNode; + disabled: boolean; + label: string; + onClick: () => void; + variant?: "secondary" | "danger" | "primary"; +}) { + return ( + + ); +} + +function PowerCells({ power, className = "" }: { power: EstimatePower; className?: string }) { + return ( + <> + {formatKw(power.kw)} + {formatKw(power.kva)} + + ); +} + +function groupLabel(group: EstimateGroupSnapshot) { + return [group.costGroup, group.title].filter(Boolean).join(" "); +} + +function EstimateRowLine({ + disabled, + group, + onChange, + onOpenGzfPicker, + onValidityChange, + row, + rowIndex, +}: { + disabled: boolean; + group: EstimateGroupSnapshot; + onChange: EstimateBalanceUpdate; + onOpenGzfPicker: (groupId: string, rowId: string) => void; + onValidityChange: (fieldKey: string, isValid: boolean) => void; + row: EstimateRowSnapshot; + rowIndex: number; +}) { + const result = calculateEstimateRow(row); + const rowLabel = `${groupLabel(group)}, Zeile ${rowIndex + 1}`; + const fieldKey = (field: string) => `${row.id}:${field}`; + + function patch(rowPatch: EstimateRowPatch) { + onChange((balance) => updateEstimateRow(balance, group.id, row.id, rowPatch)); + } + + return ( + + + + patch({ supply })} + placeholder="ELT" + value={row.supply} + /> + + + patch({ circuitRef })} + value={row.circuitRef} + /> + + + patch({ name })} + placeholder="Verbraucher oder Fläche" + value={row.name} + /> + + + patch({ quantity })} + onValidityChange={onValidityChange} + range={estimateNumberRanges.quantity} + value={row.quantity} + /> + + + + {estimateRowUnitLabels[row.unit]} + + + + + {row.connection ? estimateRowConnectionLabels[row.connection] : ""} + + + +
+ patch({ powerPerUnitW })} + onValidityChange={onValidityChange} + range={estimateNumberRanges.powerPerUnitW} + value={row.powerPerUnitW} + /> + {row.unit === "area" ? "W/m²" : "W"} +
+ + +
+ patch({ simultaneityFactor })} + onValidityChange={onValidityChange} + range={estimateNumberRanges.simultaneityFactor} + value={row.simultaneityFactor} + /> + +
+ + + patch({ cosPhi })} + onValidityChange={onValidityChange} + range={estimateNumberRanges.cosPhi} + value={row.cosPhi} + /> + + + + patch({ safetySupply: event.target.checked })} + type="checkbox" + /> + {row.safetySupply ? "ja" : "nein"} + + + + patch({ remark })} + value={row.remark} + /> + + + onChange((balance) => removeEstimateRow(balance, group.id, row.id))} + variant="danger" + > + + + + ); +} + +/** + * Spreadsheet-like editor in the layout of the office template + * "Leistungsbilanz – KG400": one section per cost group with title and + * subtotal row, totals, reserve and maximum current at the end. + */ +export function EstimateBalanceSheet({ + balance, + disabled, + onAddGroup, + onChange, + onEditGroup, + onOpenGzfPicker, + onValidityChange, + threePhaseVoltageV, +}: EstimateBalanceSheetProps) { + const result = calculateEstimateBalance(balance, threePhaseVoltageV); + + function confirmRemoveGroup(group: EstimateGroupSnapshot) { + const rowText = + group.rows.length === 1 ? "1 Zeile" : `${group.rows.length} Zeilen`; + if ( + window.confirm( + `Kostengruppe „${groupLabel(group)}“ mit ${rowText} wirklich löschen?` + ) + ) { + onChange((current) => removeEstimateGroup(current, group.id)); + } + } + + return ( +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {balance.groups.map((group, groupIndex) => { + const groupResult = result.groups[groupIndex]!; + const label = groupLabel(group) || "Kostengruppe"; + return ( + + + + + + + {group.rows.map((row, rowIndex) => ( + + ))} + {!group.rows.length ? ( + + + + ) : null} + + + + + + ); + })} + + + + + + + + + + + + + + + + + + + + + + + + + +
KG + Versorgung + ELT/ISP … + Stromkreis-Nr.Verbraucher / Flächen + Anzahl / Fläche + St. / m² + + Anschl. + Fest/Steckd. + + Einzelleist. + W bzw. W/m² + GL-Faktorcos φNötige AV-LeistungSicherheitsversorgung (SV)Anmerkungen +
WertEinh.kWkVAja/neinkWkVA
{group.costGroup} +
+ {group.title} + +
+
+
+ + onChange((current) => addEstimateRow(current, group.id).balance) + } + variant="primary" + > + + onEditGroup(group)} + > + + + onChange((current) => moveEstimateGroup(current, group.id, -1)) + } + > + + + onChange((current) => moveEstimateGroup(current, group.id, 1)) + } + > + + confirmRemoveGroup(group)} + variant="danger" + > + +
+
+ + Noch keine Einträge – mit „+“ eine Zeile hinzufügen. +
+ Summe {label} + + + + +
+ +
+ Gesamtsumme + + + +
+ Reserveleistung + +
+ + onChange((current) => ({ ...current, reserveAvPercent })) + } + onValidityChange={onValidityChange} + range={estimateNumberRanges.reservePercent} + value={balance.reserveAvPercent} + /> + % +
+
+
+ + onChange((current) => ({ ...current, reserveSvPercent })) + } + onValidityChange={onValidityChange} + range={estimateNumberRanges.reservePercent} + value={balance.reserveSvPercent} + /> + % +
+
+
+ Leistung inkl. Reserve + + + +
+ Maximalstrom + + {threePhaseVoltageV > 0 + ? ` (3~, U = ${formatDecimalInput(threePhaseVoltageV)} V)` + : " (Drehstromspannung im Projekt fehlt)"} + + + {formatAmpere(result.maxCurrentA.av)} A + + + {formatAmpere(result.maxCurrentA.sv)} A + +
+
+ ); +} diff --git a/src/frontend/estimate-balance/estimate-comparison-table.tsx b/src/frontend/estimate-balance/estimate-comparison-table.tsx new file mode 100644 index 0000000..f7098b0 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-comparison-table.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { + roundEstimateValue, + type EstimateComparison, +} from "../../shared/estimate-balance/estimate-balance"; +import { formatDeltaPercent, formatKw, formatSignedKw } from "./estimate-balance-format"; + +function deltaClass(deltaKw: number) { + if (roundEstimateValue(deltaKw, 2) === 0) { + return "estimate-number"; + } + return deltaKw > 0 ? "estimate-number is-over" : "estimate-number is-under"; +} + +/** Estimated AV power per cost group vs. the detailed circuit-list rows. */ +export function EstimateComparisonTable({ comparison }: { comparison: EstimateComparison }) { + return ( +
+ + + + + + + + + + + + + {comparison.groups.map((group) => ( + + + + + + + + + ))} + + + + + + + + + + + + + + + + + +
KGTitelgeschätzt AV kWdetailliert kWΔ kWΔ %
{group.costGroup} + {group.title} + {group.detailedRowCount ? ( + + {group.detailedRowCount === 1 + ? "1 Gerätezeile" + : `${group.detailedRowCount} Gerätezeilen`} + + ) : null} + {formatKw(group.estimatedAv.kw)}{formatKw(group.detailed.kw)}{formatSignedKw(group.deltaKw)} + {formatDeltaPercent(group.deltaPercent)} +
+ + ohne Kostengruppe / nicht zugeordnet + {comparison.unassigned.rowCount ? ( + + {comparison.unassigned.rowCount === 1 + ? "1 Gerätezeile" + : `${comparison.unassigned.rowCount} Gerätezeilen`} + + ) : null} + –{formatKw(comparison.unassigned.kw)}––
+ Summe{formatKw(comparison.total.estimatedAv.kw)}{formatKw(comparison.total.detailed.kw)} + {formatSignedKw(comparison.total.deltaKw)} + + {formatDeltaPercent(comparison.total.deltaPercent)} +
+
+ ); +} diff --git a/src/frontend/estimate-balance/estimate-draft-input.tsx b/src/frontend/estimate-balance/estimate-draft-input.tsx new file mode 100644 index 0000000..805b264 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-draft-input.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; + +export type DraftParseResult = { ok: true; value: T } | { ok: false; error: string }; + +interface DraftInputProps { + ariaLabel: string; + className?: string; + disabled?: boolean; + format: (value: T) => string; + inputMode?: "decimal" | "text"; + maxLength?: number; + onCommit: (value: T) => void; + /** Reports whether the raw text is currently valid (false while invalid). */ + onValidityChange?: (isValid: boolean) => void; + parse: (text: string) => DraftParseResult; + placeholder?: string; + value: T; +} + +/** + * Input that keeps the raw text the user typed. Only a valid text is + * committed into the document; an invalid text stays visible with a red + * border and is never saved. A value changed from outside (reload, undo) + * replaces the text unless the text already represents that value. + */ +export function DraftInput({ + ariaLabel, + className = "estimate-cell-input", + disabled, + format, + inputMode = "text", + maxLength, + onCommit, + onValidityChange, + parse, + placeholder, + value, +}: DraftInputProps) { + const [text, setText] = useState(() => format(value)); + const [error, setError] = useState(null); + const [syncedValue, setSyncedValue] = useState(value); + + if (!Object.is(syncedValue, value)) { + // Adjusting state while rendering (instead of an effect) avoids a frame + // with stale text after an external change. + setSyncedValue(value); + const parsed = parse(text); + if (!parsed.ok || !Object.is(parsed.value, value)) { + setText(format(value)); + setError(null); + } + } + + const validityRef = useRef(onValidityChange); + useEffect(() => { + validityRef.current = onValidityChange; + }); + const isValid = error === null; + useEffect(() => { + validityRef.current?.(isValid); + }, [isValid]); + // A removed input (deleted row) must not leave an invalid marker behind. + useEffect(() => () => validityRef.current?.(true), []); + + function handleChange(nextText: string) { + setText(nextText); + const parsed = parse(nextText); + if (!parsed.ok) { + setError(parsed.error); + return; + } + setError(null); + if (!Object.is(parsed.value, value)) { + setSyncedValue(parsed.value); + onCommit(parsed.value); + } + } + + function handleBlur() { + // Show the canonical notation again ("0,80" → "0,8") once editing ends. + if (error === null) { + setText(format(value)); + } + } + + return ( + <> + handleChange(event.target.value)} + placeholder={placeholder} + title={error ?? undefined} + type="text" + value={text} + /> + {error ? format(value) : text} + + ); +} diff --git a/src/frontend/estimate-balance/estimate-group-modal.tsx b/src/frontend/estimate-balance/estimate-group-modal.tsx new file mode 100644 index 0000000..8d56308 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-group-modal.tsx @@ -0,0 +1,128 @@ +"use client"; + +import { type FormEvent, useState } from "react"; +import { FormModal } from "../components/form-modal"; +import { + estimateDefaultGroups, + type EstimateGroupSnapshot, +} from "../../shared/estimate-balance/estimate-balance"; +import { estimateTextLimits } from "./estimate-balance-document"; + +export interface EstimateGroupFormValues { + costGroup: string; + title: string; + editor: string | null; +} + +interface EstimateGroupModalProps { + group: EstimateGroupSnapshot | null; + onClose: () => void; + onSave: (values: EstimateGroupFormValues) => void; +} + +/** Creates or edits the KG number, title and "bearbeitet von" of one group. */ +export function EstimateGroupModal({ group, onClose, onSave }: EstimateGroupModalProps) { + const [costGroup, setCostGroup] = useState(group?.costGroup ?? ""); + const [title, setTitle] = useState(group?.title ?? ""); + const [editor, setEditor] = useState(group?.editor ?? ""); + + function applyTemplate(index: string) { + const template = estimateDefaultGroups[Number(index)]; + if (template) { + setCostGroup(template.costGroup); + setTitle(template.title); + } + } + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (!title.trim()) { + return; + } + onSave({ + costGroup: costGroup.trim(), + title: title.trim(), + editor: editor.trim() || null, + }); + } + + return ( + +
+ {!group ? ( +
+ + +
+ ) : null} +
+ + setCostGroup(event.target.value)} + placeholder="z. B. 440" + value={costGroup} + /> +
+
+ + setTitle(event.target.value)} + placeholder="z. B. Starkstromanlagen" + required + value={title} + /> +
+
+ + setEditor(event.target.value)} + placeholder="Gewerk oder Name (optional)" + value={editor} + /> +
+
+

+ Ohne KG-Nummer (z. B. „Allgemein“) wird die Gruppe im Vergleich mit der + detaillierten Bilanz keiner Kostengruppe zugeordnet. +

+
+
+
+ ); +} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 5c14f5e..11bde4a 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -535,3 +535,34 @@ export interface CreateCircuitDeviceRowInputDto { } import type { ProjectDeviceSyncField } from "../shared/constants/project-device-sync-fields"; + +// ── Grobe Leistungsbilanz (LPH 2/3) ───────────────────────────────────── +// The document shapes are shared with the API; see +// src/shared/estimate-balance/estimate-balance.ts. +import type { + EstimateBalanceSnapshot, + EstimateComparison, +} from "../shared/estimate-balance/estimate-balance"; + +export type EstimateBalanceDto = EstimateBalanceSnapshot; +export type EstimateComparisonDto = EstimateComparison; + +export type EstimateBalanceTemplate = "kg400" | "empty" | "copy"; + +export interface CreateEstimateBalanceInput { + name: string; + workStage?: string | null; + dateIso?: string | null; + template: EstimateBalanceTemplate; + /** Required for template "copy". */ + copyFromBalanceId?: string; +} + +export interface EstimateBalanceCommandResultDto extends ProjectCommandResultDto { + balance: EstimateBalanceDto; +} + +/** PUT result: either a new revision or an unchanged document. */ +export type EstimateBalanceUpdateResultDto = + | EstimateBalanceCommandResultDto + | { unchanged: true; balance: EstimateBalanceDto }; diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index e1f4608..501ed01 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -38,6 +38,11 @@ import type { ExternalInitialImportPlanDto, ApplyExternalInitialImportInput, ExternalInitialImportResultDto, + CreateEstimateBalanceInput, + EstimateBalanceCommandResultDto, + EstimateBalanceDto, + EstimateBalanceUpdateResultDto, + EstimateComparisonDto, } from "../types"; import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts"; import type { ProjectDeviceSyncField } from "../../shared/constants/project-device-sync-fields"; @@ -87,6 +92,30 @@ import type { CircuitGroupSubtreeSnapshot, } from "../../domain/models/circuit-group-subtree-snapshot.model"; +/** + * Error of a failed API request. The message stays the server's German + * error text; status and optional error code allow callers to react to + * specific failures such as a revision conflict (409). + */ +export class ApiRequestError extends Error { + readonly status: number; + readonly code: string | null; + + constructor(message: string, status: number, code: string | null = null) { + super(message); + this.name = "ApiRequestError"; + this.status = status; + this.code = code; + } +} + +export function isRevisionConflictError(error: unknown) { + return ( + error instanceof ApiRequestError && + (error.status === 409 || error.code === "PROJECT_REVISION_CONFLICT") + ); +} + async function request(url: string, init?: RequestInit): Promise { const response = await fetch(url, { ...init, @@ -99,15 +128,23 @@ async function request(url: string, init?: RequestInit): Promise { if (!response.ok) { let details = await response.text(); + let code: string | null = null; try { - const parsed = JSON.parse(details) as { error?: unknown }; + const parsed = JSON.parse(details) as { error?: unknown; code?: unknown }; if (typeof parsed.error === "string") { details = parsed.error; } + if (typeof parsed.code === "string") { + code = parsed.code; + } } catch { // Keep non-JSON error responses unchanged. } - throw new Error(details || `Anfrage fehlgeschlagen (Status ${response.status})`); + throw new ApiRequestError( + details || `Anfrage fehlgeschlagen (Status ${response.status})`, + response.status, + code + ); } if (response.status === 204) { @@ -1135,3 +1172,66 @@ export function disconnectProjectDeviceRows( } ); } + +// ── Grobe Leistungsbilanz (LPH 2/3) ───────────────────────────────────── + +function estimateBalancesUrl(projectId: string, balanceId?: string) { + const base = `/api/projects/${projectId}/estimate-balances`; + return balanceId ? `${base}/${balanceId}` : base; +} + +export function listEstimateBalances(projectId: string) { + return request(estimateBalancesUrl(projectId)); +} + +export function getEstimateBalance(projectId: string, balanceId: string) { + return request(estimateBalancesUrl(projectId, balanceId)); +} + +export function createEstimateBalance( + projectId: string, + input: CreateEstimateBalanceInput, + expectedRevision: number +) { + return request(estimateBalancesUrl(projectId), { + method: "POST", + body: JSON.stringify({ ...input, expectedRevision }), + }); +} + +/** + * Saves the complete target document. `keepalive` lets the request outlive + * the page, e.g. for the last autosave while the tab is being closed. + */ +export function updateEstimateBalance( + projectId: string, + balance: EstimateBalanceDto, + expectedRevision: number, + options: { keepalive?: boolean } = {} +) { + return request( + estimateBalancesUrl(projectId, balance.id), + { + method: "PUT", + body: JSON.stringify({ expectedRevision, balance }), + ...(options.keepalive ? { keepalive: true } : {}), + } + ); +} + +export function deleteEstimateBalance( + projectId: string, + balanceId: string, + expectedRevision: number +) { + return request(estimateBalancesUrl(projectId, balanceId), { + method: "DELETE", + body: JSON.stringify({ expectedRevision }), + }); +} + +export function getEstimateComparison(projectId: string, balanceId: string) { + return request( + `${estimateBalancesUrl(projectId, balanceId)}/comparison` + ); +} diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index a2880ec..146cda8 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -68,6 +68,9 @@ const commandTypeLabels: Record = { "external-object.unassign-and-delete-created-row": "Externes Objekt aus erzeugter Gerätezeile gelöst", "external-object.update-row-assignment": "Externe Objektzuordnung geändert", + "estimate-balance.insert": "Grobe Leistungsbilanz angelegt", + "estimate-balance.update": "Grobe Leistungsbilanz bearbeitet", + "estimate-balance.delete": "Grobe Leistungsbilanz entfernt", }; export function getProjectRevisionSourceLabel( diff --git a/src/server/composition/application-repositories.ts b/src/server/composition/application-repositories.ts index 4f9b5ee..66fdd92 100644 --- a/src/server/composition/application-repositories.ts +++ b/src/server/composition/application-repositories.ts @@ -7,6 +7,7 @@ import { CircuitProtectionDeviceRepository } from "../../db/repositories/circuit import { DistributionBoardComponentRepository } from "../../db/repositories/distribution-board-component.repository.js"; import { DistributionBoardRepository } from "../../db/repositories/distribution-board.repository.js"; import { BuildingRepository } from "../../db/repositories/building.repository.js"; +import { EstimateBalanceRepository } from "../../db/repositories/estimate-balance.repository.js"; import { FloorRepository } from "../../db/repositories/floor.repository.js"; import { GlobalDeviceRepository } from "../../db/repositories/global-device.repository.js"; import { ProjectDeviceRepository } from "../../db/repositories/project-device.repository.js"; @@ -28,6 +29,7 @@ export const distributionBoardComponentRepository = export const distributionBoardRepository = new DistributionBoardRepository(db); export const buildingRepository = new BuildingRepository(db); +export const estimateBalanceRepository = new EstimateBalanceRepository(db); export const floorRepository = new FloorRepository(db); export const globalDeviceRepository = new GlobalDeviceRepository(db); export const projectDeviceRepository = new ProjectDeviceRepository(db); diff --git a/src/server/composition/project-command-stores.ts b/src/server/composition/project-command-stores.ts index 79a4a9f..8768173 100644 --- a/src/server/composition/project-command-stores.ts +++ b/src/server/composition/project-command-stores.ts @@ -27,6 +27,7 @@ import { ExternalInitialImportProjectCommandRepository } from "../../db/reposito import { ExternalObjectRowAssignmentProjectCommandRepository } from "../../db/repositories/external-object-row-assignment-project-command.repository.js"; import { ExternalObjectNewRowProjectCommandRepository } from "../../db/repositories/external-object-new-row-project-command.repository.js"; import { ExternalObjectNewCircuitProjectCommandRepository } from "../../db/repositories/external-object-new-circuit-project-command.repository.js"; +import { EstimateBalanceProjectCommandRepository } from "../../db/repositories/estimate-balance-project-command.repository.js"; export const circuitProjectCommandStore = new CircuitProjectCommandRepository(db); export const circuitDeviceRowProjectCommandStore = @@ -80,6 +81,8 @@ export const externalObjectNewRowProjectCommandStore = new ExternalObjectNewRowProjectCommandRepository(db); export const externalObjectNewCircuitProjectCommandStore = new ExternalObjectNewCircuitProjectCommandRepository(db); +export const estimateBalanceProjectCommandStore = + new EstimateBalanceProjectCommandRepository(db); export const projectCommandService = new ProjectCommandService( circuitProjectCommandStore, circuitDeviceRowProjectCommandStore, @@ -107,5 +110,6 @@ export const projectCommandService = new ProjectCommandService( externalInitialImportProjectCommandStore, externalObjectRowAssignmentProjectCommandStore, externalObjectNewRowProjectCommandStore, - externalObjectNewCircuitProjectCommandStore + externalObjectNewCircuitProjectCommandStore, + estimateBalanceProjectCommandStore ); diff --git a/src/server/controllers/estimate-balance.controller.ts b/src/server/controllers/estimate-balance.controller.ts new file mode 100644 index 0000000..a22bcb1 --- /dev/null +++ b/src/server/controllers/estimate-balance.controller.ts @@ -0,0 +1,180 @@ +import type { Request, Response } from "express"; +import { ZodError } from "zod"; +import { + createEstimateBalanceDeleteProjectCommand, + createEstimateBalanceInsertProjectCommand, + createEstimateBalanceSnapshot, + createEstimateBalanceUpdateProjectCommand, + parseEstimateBalanceSnapshot, + sameEstimateBalance, +} from "../../estimate-balance/domain/estimate-balance-command.model.js"; +import { + createEstimateBalanceRequestSchema, + deleteEstimateBalanceRequestSchema, + updateEstimateBalanceRequestSchema, +} from "../../estimate-balance/api/estimate-balance-request.schemas.js"; +import { compareEstimateWithDetailed } from "../../shared/estimate-balance/estimate-balance.js"; +import { estimateBalanceRepository } from "../composition/application-repositories.js"; +import { projectCommandService } from "../composition/project-command-stores.js"; +import { respondWithProjectCommandError } from "./project-command.controller.js"; + +function params(req: Request) { + const { projectId, balanceId } = req.params; + return { + projectId: typeof projectId === "string" ? projectId : null, + balanceId: typeof balanceId === "string" ? balanceId : null, + }; +} + +export function listEstimateBalances(req: Request, res: Response) { + const { projectId } = params(req); + if (!projectId) { + return res.status(400).json({ error: "Ungültige Projekt-ID." }); + } + return res.json(estimateBalanceRepository.listByProject(projectId)); +} + +export function getEstimateBalance(req: Request, res: Response) { + const { projectId, balanceId } = params(req); + if (!projectId || !balanceId) { + return res.status(400).json({ error: "Ungültige Parameter." }); + } + const balance = estimateBalanceRepository.findById(projectId, balanceId); + if (!balance) { + return res.status(404).json({ error: "Grobe Leistungsbilanz nicht gefunden." }); + } + return res.json(balance); +} + +export function createEstimateBalance(req: Request, res: Response) { + const { projectId } = params(req); + if (!projectId) { + return res.status(400).json({ error: "Ungültige Projekt-ID." }); + } + const parsed = createEstimateBalanceRequestSchema.safeParse(req.body); + if (!parsed.success) { + return res.status(400).json({ error: parsed.error.flatten() }); + } + let template: Parameters[0]["template"] = + parsed.data.template === "copy" ? "empty" : parsed.data.template; + if (parsed.data.template === "copy") { + const source = estimateBalanceRepository.findById( + projectId, + parsed.data.copyFromBalanceId! + ); + if (!source) { + return res + .status(404) + .json({ error: "Der zu kopierende Stand wurde nicht gefunden." }); + } + template = { copyFrom: source }; + } + try { + const balance = createEstimateBalanceSnapshot({ + projectId, + name: parsed.data.name, + workStage: parsed.data.workStage ?? null, + dateIso: parsed.data.dateIso ?? null, + sortOrder: estimateBalanceRepository.nextSortOrder(projectId), + template, + }); + const result = projectCommandService.executeUser({ + projectId, + expectedRevision: parsed.data.expectedRevision, + description: "Grobe Leistungsbilanz anlegen", + command: createEstimateBalanceInsertProjectCommand(balance), + }); + return res.status(201).json({ ...result, balance }); + } catch (error) { + return respondWithProjectCommandError(error, res); + } +} + +export function updateEstimateBalance(req: Request, res: Response) { + const { projectId, balanceId } = params(req); + if (!projectId || !balanceId) { + return res.status(400).json({ error: "Ungültige Parameter." }); + } + const parsed = updateEstimateBalanceRequestSchema.safeParse(req.body); + if (!parsed.success) { + return res.status(400).json({ error: parsed.error.flatten() }); + } + let target; + try { + target = parseEstimateBalanceSnapshot(parsed.data.balance); + } catch (error) { + return res.status(400).json({ + error: "Die grobe Leistungsbilanz enthält ungültige Werte.", + issues: error instanceof ZodError ? error.issues : undefined, + }); + } + if (target.id !== balanceId || target.projectId !== projectId) { + return res + .status(400) + .json({ error: "Die Bilanz gehört nicht zu diesem Projekt oder dieser Adresse." }); + } + const current = estimateBalanceRepository.findById(projectId, balanceId); + if (!current) { + return res.status(404).json({ error: "Grobe Leistungsbilanz nicht gefunden." }); + } + if (sameEstimateBalance(current, target)) { + return res.json({ unchanged: true, balance: current }); + } + try { + const result = projectCommandService.executeUser({ + projectId, + expectedRevision: parsed.data.expectedRevision, + description: "Grobe Leistungsbilanz bearbeiten", + command: createEstimateBalanceUpdateProjectCommand(current, target), + }); + return res.json({ + ...result, + balance: estimateBalanceRepository.findById(projectId, balanceId), + }); + } catch (error) { + return respondWithProjectCommandError(error, res); + } +} + +export function deleteEstimateBalance(req: Request, res: Response) { + const { projectId, balanceId } = params(req); + if (!projectId || !balanceId) { + return res.status(400).json({ error: "Ungültige Parameter." }); + } + const parsed = deleteEstimateBalanceRequestSchema.safeParse(req.body); + if (!parsed.success) { + return res.status(400).json({ error: parsed.error.flatten() }); + } + const current = estimateBalanceRepository.findById(projectId, balanceId); + if (!current) { + return res.status(404).json({ error: "Grobe Leistungsbilanz nicht gefunden." }); + } + try { + const result = projectCommandService.executeUser({ + projectId, + expectedRevision: parsed.data.expectedRevision, + description: "Grobe Leistungsbilanz löschen", + command: createEstimateBalanceDeleteProjectCommand(current), + }); + return res.json(result); + } catch (error) { + return respondWithProjectCommandError(error, res); + } +} + +export function getEstimateComparison(req: Request, res: Response) { + const { projectId, balanceId } = params(req); + if (!projectId || !balanceId) { + return res.status(400).json({ error: "Ungültige Parameter." }); + } + const balance = estimateBalanceRepository.findById(projectId, balanceId); + if (!balance) { + return res.status(404).json({ error: "Grobe Leistungsbilanz nicht gefunden." }); + } + return res.json( + compareEstimateWithDetailed( + balance, + estimateBalanceRepository.listDetailedDeviceRowPower(projectId) + ) + ); +} diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index 0b61255..529def2 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -21,6 +21,14 @@ import { } from "../controllers/building.controller.js"; import { createFloor, deleteFloor, listFloorsByProject, updateFloor } from "../controllers/floor.controller.js"; import { createRoom, deleteRoom, listRoomsByProject, updateRoom } from "../controllers/room.controller.js"; +import { + createEstimateBalance, + deleteEstimateBalance, + getEstimateBalance, + getEstimateComparison, + listEstimateBalances, + updateEstimateBalance, +} from "../controllers/estimate-balance.controller.js"; import { getCircuitTree } from "../controllers/circuit-tree.controller.js"; import { getNextCircuitIdentifier } from "../controllers/circuit.controller.js"; import { @@ -118,3 +126,12 @@ projectRouter.get("/:projectId/rooms", listRoomsByProject); projectRouter.post("/:projectId/rooms", createRoom); projectRouter.put("/:projectId/rooms/:roomId", updateRoom); projectRouter.delete("/:projectId/rooms/:roomId", deleteRoom); +projectRouter.get("/:projectId/estimate-balances", listEstimateBalances); +projectRouter.post("/:projectId/estimate-balances", createEstimateBalance); +projectRouter.get("/:projectId/estimate-balances/:balanceId", getEstimateBalance); +projectRouter.put("/:projectId/estimate-balances/:balanceId", updateEstimateBalance); +projectRouter.delete("/:projectId/estimate-balances/:balanceId", deleteEstimateBalance); +projectRouter.get( + "/:projectId/estimate-balances/:balanceId/comparison", + getEstimateComparison +); diff --git a/src/shared/estimate-balance/estimate-balance.ts b/src/shared/estimate-balance/estimate-balance.ts new file mode 100644 index 0000000..1a7b5a5 --- /dev/null +++ b/src/shared/estimate-balance/estimate-balance.ts @@ -0,0 +1,316 @@ +/** + * Grobe Leistungsbilanz (LPH 2/3): shared data shapes and pure calculation. + * + * Used by the API (validation, comparison) and by the frontend (live totals), + * so this file has no imports: Turbopack resolves frontend imports without + * the `.js` suffix the API build needs. + */ + +export type EstimateRowUnit = "piece" | "area"; +export type EstimateRowConnection = "fixed" | "socket"; + +export interface EstimateRowSnapshot { + id: string; + sortOrder: number; + /** Versorgung, e.g. "ELT" or "ISP". */ + supply: string | null; + /** Optional circuit reference, free text. */ + circuitRef: string | null; + /** Verbraucher / Fläche. May be empty while a row is being typed. */ + name: string; + /** Anzahl (unit "piece") or area in m² (unit "area"). */ + quantity: number; + unit: EstimateRowUnit; + connection: EstimateRowConnection | null; + /** W per piece or W/m². */ + powerPerUnitW: number; + simultaneityFactor: number; + cosPhi: number; + /** Also needed on the safety power supply (SV). */ + safetySupply: boolean; + remark: string | null; +} + +export interface EstimateGroupSnapshot { + id: string; + /** DIN 276 cost group, e.g. "410" or "434"; empty for "Allgemein". */ + costGroup: string; + title: string; + /** Trade or person responsible for the entries ("bearbeitet von"). */ + editor: string | null; + sortOrder: number; + rows: EstimateRowSnapshot[]; +} + +export interface EstimateBalanceSnapshot { + id: string; + projectId: string; + /** Stand, e.g. "Vorplanung" or "Entwurfsplanung". */ + name: string; + workStage: string | null; + /** ISO date YYYY-MM-DD. */ + dateIso: string | null; + reserveAvPercent: number; + reserveSvPercent: number; + sortOrder: number; + groups: EstimateGroupSnapshot[]; +} + +/** Default structure of the office template "Leistungsbilanz - KG400". */ +export const estimateDefaultGroups: ReadonlyArray<{ costGroup: string; title: string }> = [ + { costGroup: "410", title: "Sanitärtechnik" }, + { costGroup: "420", title: "Wärmeversorgung" }, + { costGroup: "430", title: "Lufttechnische Anlagen" }, + { costGroup: "434", title: "Kälteanlagen" }, + { costGroup: "440", title: "Starkstromanlagen" }, + { costGroup: "450", title: "Schwachstromanlagen" }, + { costGroup: "460", title: "Fördertechnik" }, + { costGroup: "470", title: "Nutzungsspezifische Anlagen" }, + { costGroup: "480", title: "Gebäudeautomation" }, + { costGroup: "", title: "Allgemein" }, +]; + +export const estimateRowUnitLabels: Record = { + piece: "St.", + area: "m²", +}; + +export const estimateRowConnectionLabels: Record = { + fixed: "Fest", + socket: "Steckd.", +}; + +export interface EstimatePower { + kw: number; + kva: number; +} + +export interface EstimateRowResult { + av: EstimatePower; + sv: EstimatePower; +} + +export interface EstimateGroupResult { + groupId: string; + av: EstimatePower; + sv: EstimatePower; +} + +export interface EstimateBalanceResult { + groups: EstimateGroupResult[]; + total: { av: EstimatePower; sv: EstimatePower }; + reserve: { av: EstimatePower; sv: EstimatePower }; + withReserve: { av: EstimatePower; sv: EstimatePower }; + /** Maximum current of the three-phase supply in A (S / (√3 · U)). */ + maxCurrentA: { av: number; sv: number }; +} + +/** + * Rounds a calculated value for display like the spreadsheet does: binary + * floating point stores 40.175 as 40.17499…, so the scaled value is first + * cut to 6 decimals and only then rounded half away from zero + * (40.175 -> 40.18, -1.825 -> -1.83). + */ +export function roundEstimateValue(value: number, digits = 2): number { + const factor = 10 ** digits; + const scaled = Number((Math.abs(value) * factor).toFixed(6)); + return (Math.sign(value) * Math.round(scaled)) / factor; +} + +const zeroPower = (): EstimatePower => ({ kw: 0, kva: 0 }); + +function addPower(left: EstimatePower, right: EstimatePower): EstimatePower { + return { kw: left.kw + right.kw, kva: left.kva + right.kva }; +} + +function scalePower(power: EstimatePower, factor: number): EstimatePower { + return { kw: power.kw * factor, kva: power.kva * factor }; +} + +/** + * Required power of one row: P = quantity · power per unit · GLF, S = P / cos φ. + * AV covers every consumer (normal supply); SV additionally lists the rows + * that must also be supplied by the safety power supply. + */ +export function calculateEstimateRow( + row: Pick< + EstimateRowSnapshot, + "quantity" | "powerPerUnitW" | "simultaneityFactor" | "cosPhi" | "safetySupply" + > +): EstimateRowResult { + const kw = (row.quantity * row.powerPerUnitW * row.simultaneityFactor) / 1000; + const kva = row.cosPhi > 0 ? kw / row.cosPhi : 0; + const av = { kw, kva }; + return { av, sv: row.safetySupply ? { ...av } : zeroPower() }; +} + +export function calculateEstimateBalance( + balance: Pick, + threePhaseVoltageV: number +): EstimateBalanceResult { + const groups = balance.groups.map((group) => + group.rows.reduce( + (sum, row) => { + const result = calculateEstimateRow(row); + return { + groupId: group.id, + av: addPower(sum.av, result.av), + sv: addPower(sum.sv, result.sv), + }; + }, + { groupId: group.id, av: zeroPower(), sv: zeroPower() } + ) + ); + const total = groups.reduce( + (sum, group) => ({ av: addPower(sum.av, group.av), sv: addPower(sum.sv, group.sv) }), + { av: zeroPower(), sv: zeroPower() } + ); + const reserve = { + av: scalePower(total.av, balance.reserveAvPercent / 100), + sv: scalePower(total.sv, balance.reserveSvPercent / 100), + }; + const withReserve = { + av: addPower(total.av, reserve.av), + sv: addPower(total.sv, reserve.sv), + }; + const currentFactor = + threePhaseVoltageV > 0 ? 1000 / (Math.sqrt(3) * threePhaseVoltageV) : 0; + return { + groups, + total, + reserve, + withReserve, + maxCurrentA: { + av: withReserve.av.kva * currentFactor, + sv: withReserve.sv.kva * currentFactor, + }, + }; +} + +/** + * Assigns a detailed cost group (e.g. "444" or "440.1") to the best matching + * estimate group: a group code with trailing zeros removed is a prefix + * ("430" -> "43", "434" -> "434"); the longest prefix wins. Returns null when + * no group matches. + */ +export function matchEstimateCostGroup( + detailedCostGroup: string | null, + groupCostGroups: readonly string[] +): string | null { + const digits = (detailedCostGroup ?? "").replace(/\D/g, ""); + if (!digits) { + return null; + } + let best: { code: string; length: number } | null = null; + for (const code of groupCostGroups) { + const codeDigits = code.replace(/\D/g, ""); + const prefix = codeDigits.replace(/0+$/, ""); + if (!prefix || !digits.startsWith(prefix)) { + continue; + } + if (!best || prefix.length > best.length) { + best = { code, length: prefix.length }; + } + } + return best?.code ?? null; +} + +export interface EstimateComparisonGroup { + groupId: string; + costGroup: string; + title: string; + estimatedAv: EstimatePower; + detailed: EstimatePower; + detailedRowCount: number; + deltaKw: number; + /** Relative deviation of the detailed value from the estimate, null without estimate. */ + deltaPercent: number | null; +} + +export interface EstimateComparison { + groups: EstimateComparisonGroup[]; + unassigned: EstimatePower & { rowCount: number }; + total: { + estimatedAv: EstimatePower; + detailed: EstimatePower; + deltaKw: number; + deltaPercent: number | null; + }; +} + +export interface DetailedDeviceRowPower { + costGroup: string | null; + /** Total power of the device row in kW (quantity · power · device GZF). */ + kw: number; + cosPhi: number | null; +} + +function delta(estimated: number, detailed: number) { + return { + deltaKw: detailed - estimated, + deltaPercent: estimated > 0 ? ((detailed - estimated) / estimated) * 100 : null, + }; +} + +/** + * Compares the estimate per cost group with the detailed device rows of all + * circuit lists. The distribution-board simultaneity factor is not applied + * on either side; a missing cos φ counts as 1. + */ +export function compareEstimateWithDetailed( + balance: Pick, + detailedRows: readonly DetailedDeviceRowPower[] +): EstimateComparison { + const estimate = calculateEstimateBalance(balance, 0); + const codes = balance.groups.map((group) => group.costGroup).filter(Boolean); + const detailedByCode = new Map(); + const unassigned = { kw: 0, kva: 0, rowCount: 0 }; + for (const row of detailedRows) { + const kva = row.cosPhi && row.cosPhi > 0 ? row.kw / row.cosPhi : row.kw; + const code = matchEstimateCostGroup(row.costGroup, codes); + const target = + code === null + ? unassigned + : detailedByCode.get(code) ?? + detailedByCode.set(code, { kw: 0, kva: 0, rowCount: 0 }).get(code)!; + target.kw += row.kw; + target.kva += kva; + target.rowCount += 1; + } + // A cost group code can appear in several groups; the detailed value is + // shown once, on the first group with that code. + const shownCodes = new Set(); + const groups = balance.groups.map((group, index) => { + const estimatedAv = estimate.groups[index]!.av; + const detailedEntry = + group.costGroup && !shownCodes.has(group.costGroup) + ? detailedByCode.get(group.costGroup) + : undefined; + if (group.costGroup) { + shownCodes.add(group.costGroup); + } + const detailed = { kw: detailedEntry?.kw ?? 0, kva: detailedEntry?.kva ?? 0 }; + return { + groupId: group.id, + costGroup: group.costGroup, + title: group.title, + estimatedAv, + detailed, + detailedRowCount: detailedEntry?.rowCount ?? 0, + ...delta(estimatedAv.kw, detailed.kw), + }; + }); + const detailedTotal = groups.reduce( + (sum, group) => addPower(sum, group.detailed), + { kw: unassigned.kw, kva: unassigned.kva } + ); + return { + groups, + unassigned, + total: { + estimatedAv: estimate.total.av, + detailed: detailedTotal, + ...delta(estimate.total.av.kw, detailedTotal.kw), + }, + }; +} diff --git a/tests/estimate-balance-frontend.test.ts b/tests/estimate-balance-frontend.test.ts new file mode 100644 index 0000000..fa9368d --- /dev/null +++ b/tests/estimate-balance-frontend.test.ts @@ -0,0 +1,435 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import type { EstimateBalanceSnapshot } from "../src/shared/estimate-balance/estimate-balance.js"; +import { + addEstimateGroup, + addEstimateRow, + createCopyName, + createEstimateRow, + estimateBalanceFingerprint, + moveEstimateGroup, + moveEstimateRow, + normalizeEstimateSortOrder, + removeEstimateGroup, + removeEstimateRow, + toSaveableEstimateBalance, + updateEstimateGroup, + updateEstimateRow, + validateEstimateBalance, +} from "../src/frontend/estimate-balance/estimate-balance-document.js"; +import { + estimateNumberRanges, + formatAmpere, + formatDecimalInput, + formatDeltaPercent, + formatIsoDateGerman, + formatKw, + formatSignedKw, + getTodayIsoDate, + parseGermanDecimal, +} from "../src/frontend/estimate-balance/estimate-balance-format.js"; +import { + ApiRequestError, + createEstimateBalance, + deleteEstimateBalance, + getEstimateBalance, + getEstimateComparison, + isRevisionConflictError, + listEstimateBalances, + updateEstimateBalance, +} from "../src/frontend/utils/api.js"; + +function sequentialIds(prefix = "id") { + let next = 0; + return () => `${prefix}-${++next}`; +} + +function sampleBalance(): EstimateBalanceSnapshot { + return { + id: "balance-1", + projectId: "project-1", + name: "Entwurfsplanung", + workStage: "LPH 3", + dateIso: "2026-09-26", + reserveAvPercent: 20, + reserveSvPercent: 10, + sortOrder: 0, + groups: [ + { + id: "group-410", + costGroup: "410", + title: "Sanitärtechnik", + editor: null, + sortOrder: 0, + rows: [ + { ...createEstimateRow(0, () => "row-a"), name: "Hebeanlage", powerPerUnitW: 1200 }, + { ...createEstimateRow(1, () => "row-b"), name: "Durchlauferhitzer" }, + ], + }, + { + id: "group-440", + costGroup: "440", + title: "Starkstromanlagen", + editor: "ELT", + sortOrder: 1, + rows: [], + }, + ], + }; +} + +describe("estimate balance number input", () => { + it("accepts a comma as decimal separator", () => { + assert.deepEqual(parseGermanDecimal("0,8"), { ok: true, value: 0.8 }); + assert.deepEqual(parseGermanDecimal(" 1200 "), { ok: true, value: 1200 }); + assert.deepEqual(parseGermanDecimal(",5"), { ok: true, value: 0.5 }); + assert.deepEqual(parseGermanDecimal("3,"), { ok: true, value: 3 }); + }); + + it("rejects dots, empty input and garbage", () => { + for (const text of ["0.8", "1.200", "", " ", "abc", "1,2,3", "1e3", "--1"]) { + assert.equal(parseGermanDecimal(text).ok, false, text); + } + const dot = parseGermanDecimal("0.8"); + assert.equal(dot.ok === false && dot.error.includes("Komma"), true); + }); + + it("checks the server ranges of the document fields", () => { + assert.equal(parseGermanDecimal("-1", estimateNumberRanges.quantity).ok, false); + assert.equal(parseGermanDecimal("0", estimateNumberRanges.quantity).ok, true); + assert.equal(parseGermanDecimal("1,1", estimateNumberRanges.simultaneityFactor).ok, false); + assert.equal(parseGermanDecimal("1", estimateNumberRanges.simultaneityFactor).ok, true); + assert.equal(parseGermanDecimal("0", estimateNumberRanges.cosPhi).ok, false); + assert.equal(parseGermanDecimal("0,01", estimateNumberRanges.cosPhi).ok, true); + assert.equal(parseGermanDecimal("101", estimateNumberRanges.reservePercent).ok, false); + }); + + it("formats input text so it parses back unchanged", () => { + assert.equal(formatDecimalInput(1200), "1200"); + assert.equal(formatDecimalInput(0.8), "0,8"); + const parsed = parseGermanDecimal(formatDecimalInput(12345.678)); + assert.deepEqual(parsed, { ok: true, value: 12345.678 }); + }); +}); + +describe("estimate balance display format", () => { + it("rounds half away from zero like Excel", () => { + assert.equal(formatKw(40.175), "40,18"); + assert.equal(formatKw(30.24), "30,24"); + assert.equal(formatKw(1234.5), "1.234,50"); + assert.equal(formatKw(-0.001), "0,00"); + assert.equal(formatAmpere(57.75), "57,75"); + assert.equal(formatAmpere(235.749), "235,75"); + }); + + it("shows signed deltas and percentages", () => { + assert.equal(formatSignedKw(1.5), "+1,50"); + assert.equal(formatSignedKw(-1.825), "-1,83"); + assert.equal(formatSignedKw(0.001), "0,00"); + assert.equal(formatDeltaPercent(12.34), "+12,3 %"); + assert.equal(formatDeltaPercent(-5), "-5,0 %"); + assert.equal(formatDeltaPercent(null), "–"); + }); + + it("formats dates", () => { + assert.equal(formatIsoDateGerman("2026-09-26"), "26.09.2026"); + assert.equal(formatIsoDateGerman(null), "–"); + assert.equal(getTodayIsoDate(new Date(2026, 0, 5, 23, 30)), "2026-01-05"); + }); +}); + +describe("estimate balance document editing", () => { + it("adds rows at the end or after a row with continuous sort orders", () => { + const createId = sequentialIds("new"); + const appended = addEstimateRow(sampleBalance(), "group-410", { createId }); + assert.equal(appended.rowId, "new-1"); + assert.deepEqual( + appended.balance.groups[0]!.rows.map((row) => [row.id, row.sortOrder]), + [["row-a", 0], ["row-b", 1], ["new-1", 2]] + ); + const inserted = addEstimateRow(sampleBalance(), "group-410", { + afterRowId: "row-a", + createId, + }); + assert.deepEqual( + inserted.balance.groups[0]!.rows.map((row) => [row.id, row.sortOrder]), + [["row-a", 0], ["new-2", 1], ["row-b", 2]] + ); + const unknownGroup = addEstimateRow(sampleBalance(), "missing", { createId }); + assert.equal(unknownGroup.rowId, null); + }); + + it("creates rows with neutral defaults", () => { + const row = createEstimateRow(3, () => "row-x"); + assert.deepEqual(row, { + id: "row-x", + sortOrder: 3, + supply: null, + circuitRef: null, + name: "", + quantity: 1, + unit: "piece", + connection: null, + powerPerUnitW: 0, + simultaneityFactor: 1, + cosPhi: 1, + safetySupply: false, + remark: null, + }); + }); + + it("updates, removes and moves rows without touching the input", () => { + const original = sampleBalance(); + const updated = updateEstimateRow(original, "group-410", "row-b", { + quantity: 3, + safetySupply: true, + }); + assert.equal(updated.groups[0]!.rows[1]!.quantity, 3); + assert.equal(updated.groups[0]!.rows[1]!.safetySupply, true); + assert.equal(original.groups[0]!.rows[1]!.quantity, 1); + + const removed = removeEstimateRow(original, "group-410", "row-a"); + assert.deepEqual( + removed.groups[0]!.rows.map((row) => [row.id, row.sortOrder]), + [["row-b", 0]] + ); + + const moved = moveEstimateRow(original, "group-410", "row-b", -1); + assert.deepEqual( + moved.groups[0]!.rows.map((row) => [row.id, row.sortOrder]), + [["row-b", 0], ["row-a", 1]] + ); + assert.equal(moveEstimateRow(original, "group-410", "row-a", -1), original); + }); + + it("adds, edits, moves and removes groups", () => { + const added = addEstimateGroup( + sampleBalance(), + { costGroup: "480", title: "Gebäudeautomation" }, + () => "group-480" + ); + assert.equal(added.groupId, "group-480"); + assert.deepEqual( + added.balance.groups.map((group) => [group.id, group.sortOrder]), + [["group-410", 0], ["group-440", 1], ["group-480", 2]] + ); + assert.equal(added.balance.groups[2]!.editor, null); + + const edited = updateEstimateGroup(added.balance, "group-480", { + costGroup: "481", + editor: "MSR", + }); + assert.equal(edited.groups[2]!.costGroup, "481"); + assert.equal(edited.groups[2]!.title, "Gebäudeautomation"); + + const movedUp = moveEstimateGroup(edited, "group-480", -1); + assert.deepEqual( + movedUp.groups.map((group) => [group.id, group.sortOrder]), + [["group-410", 0], ["group-480", 1], ["group-440", 2]] + ); + assert.equal(moveEstimateGroup(movedUp, "group-440", 1), movedUp); + + const removed = removeEstimateGroup(movedUp, "group-410"); + assert.deepEqual( + removed.groups.map((group) => [group.id, group.sortOrder]), + [["group-480", 0], ["group-440", 1]] + ); + assert.equal(removeEstimateGroup(removed, "missing"), removed); + }); + + it("orders loaded documents by sortOrder", () => { + const balance = sampleBalance(); + const shuffled: EstimateBalanceSnapshot = { + ...balance, + groups: [ + { ...balance.groups[1]!, sortOrder: 7 }, + { + ...balance.groups[0]!, + sortOrder: 2, + rows: [ + { ...balance.groups[0]!.rows[1]!, sortOrder: 5 }, + { ...balance.groups[0]!.rows[0]!, sortOrder: 1 }, + ], + }, + ], + }; + const normalized = normalizeEstimateSortOrder(shuffled); + assert.deepEqual( + normalized.groups.map((group) => [group.id, group.sortOrder]), + [["group-410", 0], ["group-440", 1]] + ); + assert.deepEqual( + normalized.groups[0]!.rows.map((row) => [row.id, row.sortOrder]), + [["row-a", 0], ["row-b", 1]] + ); + }); +}); + +describe("estimate balance saving", () => { + it("builds the trimmed server document with null for empty optional texts", () => { + let balance = sampleBalance(); + balance = { ...balance, name: " Entwurf ", workStage: " ", dateIso: "" }; + balance = updateEstimateGroup(balance, "group-440", { title: " Starkstrom ", editor: " " }); + balance = updateEstimateRow(balance, "group-410", "row-a", { + name: " Hebeanlage ", + supply: " ELT ", + circuitRef: "", + remark: " ", + }); + const saveable = toSaveableEstimateBalance(balance); + assert.equal(saveable.name, "Entwurf"); + assert.equal(saveable.workStage, null); + assert.equal(saveable.dateIso, null); + assert.equal(saveable.groups[1]!.title, "Starkstrom"); + assert.equal(saveable.groups[1]!.editor, null); + assert.deepEqual( + { + name: saveable.groups[0]!.rows[0]!.name, + supply: saveable.groups[0]!.rows[0]!.supply, + circuitRef: saveable.groups[0]!.rows[0]!.circuitRef, + remark: saveable.groups[0]!.rows[0]!.remark, + }, + { name: "Hebeanlage", supply: "ELT", circuitRef: null, remark: null } + ); + }); + + it("copies only snapshot fields", () => { + const balance = sampleBalance() as EstimateBalanceSnapshot & { uiState?: string }; + balance.uiState = "leak"; + assert.equal("uiState" in toSaveableEstimateBalance(balance), false); + }); + + it("treats whitespace-only changes as unchanged", () => { + const balance = sampleBalance(); + const withSpace = updateEstimateRow(balance, "group-410", "row-a", { + name: "Hebeanlage ", + }); + assert.equal(estimateBalanceFingerprint(withSpace), estimateBalanceFingerprint(balance)); + const changed = updateEstimateRow(balance, "group-410", "row-a", { quantity: 2 }); + assert.notEqual(estimateBalanceFingerprint(changed), estimateBalanceFingerprint(balance)); + }); + + it("reports documents the server would reject", () => { + assert.deepEqual(validateEstimateBalance(sampleBalance()), []); + const invalid = updateEstimateGroup( + { ...sampleBalance(), name: " " }, + "group-440", + { title: " " } + ); + assert.equal(validateEstimateBalance(invalid).length, 2); + }); + + it("names copies", () => { + assert.equal(createCopyName("Entwurfsplanung "), "Entwurfsplanung (Kopie)"); + assert.equal(createCopyName("x".repeat(200)).length, 200); + }); +}); + +describe("estimate balance frontend API", () => { + it("calls the estimate balance endpoints", async () => { + const requests: Array<{ url: string; method: string; body: unknown; keepalive?: boolean }> = + []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (input, init) => { + requests.push({ + url: String(input), + method: init?.method ?? "GET", + body: init?.body === undefined ? undefined : JSON.parse(String(init.body)), + ...(init?.keepalive ? { keepalive: true } : {}), + }); + return new Response(JSON.stringify({}), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }; + try { + const balance = sampleBalance(); + await listEstimateBalances("project-1"); + await getEstimateBalance("project-1", "balance-1"); + await createEstimateBalance( + "project-1", + { name: "Vorplanung", workStage: null, dateIso: "2026-09-26", template: "kg400" }, + 4 + ); + await createEstimateBalance( + "project-1", + { name: "Kopie", template: "copy", copyFromBalanceId: "balance-1" }, + 5 + ); + await updateEstimateBalance("project-1", balance, 6); + await updateEstimateBalance("project-1", balance, 7, { keepalive: true }); + await deleteEstimateBalance("project-1", "balance-1", 8); + await getEstimateComparison("project-1", "balance-1"); + const base = "/api/projects/project-1/estimate-balances"; + assert.deepEqual(requests, [ + { url: base, method: "GET", body: undefined }, + { url: `${base}/balance-1`, method: "GET", body: undefined }, + { + url: base, + method: "POST", + body: { + name: "Vorplanung", + workStage: null, + dateIso: "2026-09-26", + template: "kg400", + expectedRevision: 4, + }, + }, + { + url: base, + method: "POST", + body: { + name: "Kopie", + template: "copy", + copyFromBalanceId: "balance-1", + expectedRevision: 5, + }, + }, + { + url: `${base}/balance-1`, + method: "PUT", + body: { expectedRevision: 6, balance }, + }, + { + url: `${base}/balance-1`, + method: "PUT", + body: { expectedRevision: 7, balance }, + keepalive: true, + }, + { url: `${base}/balance-1`, method: "DELETE", body: { expectedRevision: 8 } }, + { url: `${base}/balance-1/comparison`, method: "GET", body: undefined }, + ]); + } finally { + globalThis.fetch = originalFetch; + } + }); + + it("exposes status and code of failed requests", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => + new Response( + JSON.stringify({ + error: "Projektstand veraltet.", + code: "PROJECT_REVISION_CONFLICT", + }), + { status: 409, headers: { "Content-Type": "application/json" } } + ); + try { + await assert.rejects( + updateEstimateBalance("project-1", sampleBalance(), 1), + (error: unknown) => { + assert.ok(error instanceof ApiRequestError); + assert.equal(error.message, "Projektstand veraltet."); + assert.equal(error.status, 409); + assert.equal(error.code, "PROJECT_REVISION_CONFLICT"); + assert.equal(isRevisionConflictError(error), true); + return true; + } + ); + } finally { + globalThis.fetch = originalFetch; + } + assert.equal(isRevisionConflictError(new ApiRequestError("x", 400)), false); + assert.equal(isRevisionConflictError(new Error("x")), false); + }); +}); diff --git a/tests/estimate-balance.test.ts b/tests/estimate-balance.test.ts new file mode 100644 index 0000000..7d294da --- /dev/null +++ b/tests/estimate-balance.test.ts @@ -0,0 +1,459 @@ +import path from "node:path"; +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { + createDatabaseContext, + type DatabaseContext, +} from "../src/db/database-context.js"; +import { EstimateBalanceProjectCommandRepository } from "../src/db/repositories/estimate-balance-project-command.repository.js"; +import { EstimateBalanceRepository } from "../src/db/repositories/estimate-balance.repository.js"; +import { ProjectHistoryRepository } from "../src/db/repositories/project-history.repository.js"; +import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; +import { circuitLists } from "../src/db/schema/circuit-lists.js"; +import { circuitSections } from "../src/db/schema/circuit-sections.js"; +import { circuits } from "../src/db/schema/circuits.js"; +import { distributionBoards } from "../src/db/schema/distribution-boards.js"; +import { estimateRows } from "../src/db/schema/estimate-balances.js"; +import { projects } from "../src/db/schema/projects.js"; +import { + createEstimateBalanceDeleteProjectCommand, + createEstimateBalanceInsertProjectCommand, + createEstimateBalanceSnapshot, + createEstimateBalanceUpdateProjectCommand, + parseEstimateBalanceSnapshot, + type EstimateBalanceProjectCommand, +} from "../src/estimate-balance/domain/estimate-balance-command.model.js"; +import { createEstimateBalanceRequestSchema } from "../src/estimate-balance/api/estimate-balance-request.schemas.js"; +import { + calculateEstimateBalance, + calculateEstimateRow, + compareEstimateWithDetailed, + estimateDefaultGroups, + matchEstimateCostGroup, + roundEstimateValue, + type EstimateBalanceSnapshot, + type EstimateRowSnapshot, +} from "../src/shared/estimate-balance/estimate-balance.js"; + +const round2 = (value: number) => roundEstimateValue(value, 2); +let nextId = 0; +const id = () => `id-${++nextId}`; + +function row( + name: string, + quantity: number, + powerPerUnitW: number, + simultaneityFactor: number, + cosPhi: number, + extra: Partial = {} +): EstimateRowSnapshot { + return { + id: id(), + sortOrder: 0, + supply: "ELT", + circuitRef: null, + name, + quantity, + unit: "piece", + connection: null, + powerPerUnitW, + simultaneityFactor, + cosPhi, + safetySupply: false, + remark: null, + ...extra, + }; +} + +/** All rows of the office example "Leistungsbilanz - KG400" (Entwurfsplanung). */ +function templateExample(): EstimateBalanceSnapshot { + const rowsByGroup: Record = { + "410": [ + row("Durchlauferhitzer 11kW", 9, 11200, 0.3, 1), + row("Durchlauferhitzer 4,4kW", 4, 4400, 0.3, 1), + ], + "420": [ + row("Fernwärmestation", 1, 1000, 0.8, 1), + row("Pumpen", 4, 200, 0.8, 0.9), + row("Schaltschrank Heizung", 1, 2000, 0.8, 1), + ], + "430": [ + row("Lüftungsgerät", 1, 6000, 0.8, 0.9), + row("Schaltschrank Lüftung", 1, 2000, 0.8, 0.9), + ], + "434": [ + row("Kälteaggregat Dach", 1, 1000, 0.8, 1), + row("Serverraum Kühlung Aggregat Dach", 1, 2000, 0.8, 1), + row("Serverraum Innengerät", 1, 1000, 0.8, 1), + ], + "440": [ + row("Beleuchtungsanlage Klassenzimmer", 17, 500, 0.8, 0.95), + row("Beleuchtung Allgemein", 50, 45, 0.7, 0.95), + row("Außenbeleuchtung", 10, 100, 0.4, 0.95), + row("Fassadenbeleuchtung", 20, 60, 0.5, 0.95), + row("Beleuchtung MFR", 15, 50, 0.8, 0.95), + row("Steckdosen Klassenzimmer", 170, 300, 0.2, 0.95), + row("Steckdosen 230 V allg. Verbr.", 100, 500, 0.2, 0.95), + row("Veranstaltungstechnik", 1, 4000, 0.5, 0.95), + row("Küchentechnische Anlagen", 1, 10000, 0.4, 0.8), + row("Sicherheitsbeleuchtung Zentrale", 1, 2000, 0.8, 0.9), + row("Spezielle Experimentieranlagen", 1, 6000, 0.4, 0.9), + ], + "450": [row("EDV Systeme", 5, 3000, 0.8, 0.95)], + "460": [row("Aufzug", 1, 16000, 0.7, 0.95)], + "470": [row("E-Mobility Vorbereitung", 9, 11000, 0.3, 1)], + "480": [], + "": [row("Allgemein", 1, 2000, 1, 0.95)], + }; + return { + id: "balance-1", + projectId: "project-1", + name: "Entwurfsplanung", + workStage: "LPH 3", + dateIso: "2023-06-30", + reserveAvPercent: 10, + reserveSvPercent: 0, + sortOrder: 0, + groups: estimateDefaultGroups.map((group, index) => ({ + id: `group-${group.costGroup || "allg"}`, + costGroup: group.costGroup, + title: group.title, + editor: null, + sortOrder: index, + rows: rowsByGroup[group.costGroup] ?? [], + })), + }; +} + +function createTestDatabase(): DatabaseContext { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + context.db + .insert(projects) + .values([ + { id: "project-1", name: "Test project" }, + { id: "project-2", name: "Foreign project" }, + ]) + .run(); + return context; +} + +describe("estimate balance calculation", () => { + it("reproduces the office template totals", () => { + const result = calculateEstimateBalance(templateExample(), 400); + const groupTotals = result.groups.map((group) => [ + round2(group.av.kw), + round2(group.av.kva), + ]); + assert.deepEqual(groupTotals, [ + [35.52, 35.52], + [3.04, 3.11], + [6.4, 7.11], + [3.2, 3.2], + [40.18, 43.31], + [12, 12.63], + [11.2, 11.79], + [29.7, 29.7], + [0, 0], + [2, 2.11], + ]); + assert.equal(round2(result.total.av.kw), 143.24); + assert.equal(round2(result.total.av.kva), 148.48); + assert.equal(round2(result.reserve.av.kw), 14.32); + assert.equal(round2(result.reserve.av.kva), 14.85); + assert.equal(round2(result.withReserve.av.kw), 157.56); + assert.equal(round2(result.withReserve.av.kva), 163.33); + assert.equal(round2(result.maxCurrentA.av), 235.75); + assert.equal(result.total.sv.kw, 0); + assert.equal(result.maxCurrentA.sv, 0); + }); + + it("counts safety-supply rows in AV and additionally in SV, also per m²", () => { + const area = calculateEstimateRow({ + quantity: 250, + powerPerUnitW: 12, + simultaneityFactor: 0.8, + cosPhi: 0.95, + safetySupply: true, + }); + assert.equal(round2(area.av.kw), 2.4); + assert.equal(round2(area.av.kva), 2.53); + assert.deepEqual(area.sv, area.av); + const balance = templateExample(); + balance.reserveSvPercent = 20; + balance.groups[4]!.rows[9]!.safetySupply = true; // Sicherheitsbeleuchtung Zentrale + const result = calculateEstimateBalance(balance, 400); + assert.equal(round2(result.total.sv.kw), 1.6); + assert.equal(round2(result.withReserve.sv.kw), 1.92); + assert.equal(round2(result.total.av.kw), 143.24); + }); + + it("rounds displayed values like the spreadsheet", () => { + assert.equal(roundEstimateValue(40.175), 40.18); + assert.equal(roundEstimateValue(143.235), 143.24); + assert.equal(roundEstimateValue(-1.825), -1.83); + assert.equal(roundEstimateValue(0.711111), 0.71); + assert.equal(roundEstimateValue(235.749, 1), 235.7); + }); + + it("matches detailed cost groups to the most specific estimate group", () => { + const codes = ["410", "430", "434", "440", "480", ""]; + assert.equal(matchEstimateCostGroup("444", codes), "440"); + assert.equal(matchEstimateCostGroup("434", codes), "434"); + assert.equal(matchEstimateCostGroup("431", codes), "430"); + assert.equal(matchEstimateCostGroup("KG 481.1", codes), "480"); + assert.equal(matchEstimateCostGroup("4", codes), null); + assert.equal(matchEstimateCostGroup("", codes), null); + assert.equal(matchEstimateCostGroup(null, codes), null); + assert.equal(matchEstimateCostGroup("450", codes), null); + }); + + it("compares the estimate with detailed device rows per cost group", () => { + const comparison = compareEstimateWithDetailed(templateExample(), [ + { costGroup: "444", kw: 30, cosPhi: 0.9 }, + { costGroup: "445", kw: 12, cosPhi: null }, + { costGroup: "412", kw: 40, cosPhi: 1 }, + { costGroup: null, kw: 5, cosPhi: 1 }, + { costGroup: "399", kw: 1, cosPhi: 1 }, + ]); + const kg440 = comparison.groups.find((group) => group.costGroup === "440")!; + assert.equal(round2(kg440.detailed.kw), 42); + assert.equal(round2(kg440.detailed.kva), 45.33); + assert.equal(kg440.detailedRowCount, 2); + assert.ok(Math.abs(kg440.deltaKw - 1.825) < 1e-9); + assert.equal(round2(kg440.deltaPercent!), 4.54); + const kg410 = comparison.groups.find((group) => group.costGroup === "410")!; + assert.equal(round2(kg410.deltaKw), 4.48); + const kg480 = comparison.groups.find((group) => group.costGroup === "480")!; + assert.equal(kg480.deltaPercent, null); + assert.deepEqual(comparison.unassigned, { kw: 6, kva: 6, rowCount: 2 }); + assert.equal(round2(comparison.total.detailed.kw), 88); + assert.equal(round2(comparison.total.estimatedAv.kw), 143.24); + }); +}); + +describe("estimate balance snapshots and commands", () => { + it("validates snapshots strictly", () => { + const valid = templateExample(); + assert.equal(parseEstimateBalanceSnapshot(valid).groups[4]!.rows[3]!.sortOrder, 3); + const invalid: Array<(balance: EstimateBalanceSnapshot) => void> = [ + (balance) => (balance.groups[0]!.rows[0]!.cosPhi = 0), + (balance) => (balance.groups[0]!.rows[0]!.simultaneityFactor = 1.5), + (balance) => (balance.groups[0]!.rows[0]!.quantity = -1), + (balance) => (balance.groups[0]!.rows[0]!.name = " Leerzeichen "), + (balance) => (balance.groups[0]!.rows[0]!.supply = ""), + (balance) => (balance.groups[0]!.title = ""), + (balance) => (balance.dateIso = "30.06.2023"), + (balance) => (balance.reserveAvPercent = 101), + (balance) => (balance.groups[1]!.rows[0]!.id = balance.groups[0]!.rows[0]!.id), + (balance) => ((balance.groups[0]!.rows[0] as unknown as Record).extra = 1), + ]; + for (const mutate of invalid) { + const balance = structuredClone(valid); + mutate(balance); + assert.throws(() => parseEstimateBalanceSnapshot(balance)); + } + assert.equal( + createEstimateBalanceRequestSchema.safeParse({ + expectedRevision: 0, + name: "Entwurf", + template: "copy", + }).success, + false + ); + }); + + it("creates the KG 400 template and copies a Stand with new ids", () => { + const created = createEstimateBalanceSnapshot({ + projectId: "project-1", + name: " Vorplanung ", + workStage: "LPH 2", + dateIso: "2026-09-26", + sortOrder: 0, + template: "kg400", + }); + assert.equal(created.name, "Vorplanung"); + assert.deepEqual( + created.groups.map((group) => group.costGroup), + estimateDefaultGroups.map((group) => group.costGroup) + ); + assert.equal(created.reserveAvPercent, 10); + const source = templateExample(); + const copy = createEstimateBalanceSnapshot({ + projectId: "project-1", + name: "Entwurfsplanung Kopie", + workStage: null, + dateIso: null, + sortOrder: 1, + template: { copyFrom: source }, + }); + assert.notEqual(copy.id, source.id); + assert.notEqual(copy.groups[0]!.id, source.groups[0]!.id); + assert.notEqual(copy.groups[0]!.rows[0]!.id, source.groups[0]!.rows[0]!.id); + assert.equal( + round2(calculateEstimateBalance(copy, 400).total.av.kw), + 143.24 + ); + }); + + it("inserts, updates and deletes balances with persisted undo and redo", () => { + const context = createTestDatabase(); + try { + const store = new EstimateBalanceProjectCommandRepository(context.db); + const reader = new EstimateBalanceRepository(context.db); + const history = new ProjectHistoryRepository(context.db); + let revision = 0; + const run = ( + command: EstimateBalanceProjectCommand, + source: "user" | "undo" | "redo" = "user" + ) => { + const step = source === "user" ? null : history.getNextCommand("project-1", source); + const result = store.execute({ + projectId: "project-1", + expectedRevision: revision, + source, + historyTargetChangeSetId: step?.changeSetId, + command, + }); + revision += 1; + return result; + }; + + const balance = templateExample(); + const insert = createEstimateBalanceInsertProjectCommand(balance); + const inserted = run(insert); + const stored = reader.findById("project-1", balance.id); + assert.deepEqual(stored, parseEstimateBalanceSnapshot(balance)); + assert.equal(reader.listByProject("project-2").length, 0); + + const target = structuredClone(stored!); + target.groups[0]!.rows.splice(1, 1); + target.groups[0]!.rows[0]!.quantity = 10; + target.groups[8]!.rows.push(row("GLT-Schrank", 2, 500, 1, 0.95)); + target.groups[8]!.editor = "MSR"; + target.reserveAvPercent = 15; + const update = createEstimateBalanceUpdateProjectCommand(stored!, target); + const updated = run(update); + assert.deepEqual( + reader.findById("project-1", balance.id), + parseEstimateBalanceSnapshot(target) + ); + + run(updated.inverse, "undo"); + assert.deepEqual(reader.findById("project-1", balance.id), stored); + run(update, "redo"); + assert.deepEqual( + reader.findById("project-1", balance.id), + parseEstimateBalanceSnapshot(target) + ); + + // A stale expected document is rejected. + assert.throws( + () => run(createEstimateBalanceUpdateProjectCommand(stored!, { ...stored!, name: "X" })), + /changed before update/ + ); + assert.throws( + () => createEstimateBalanceUpdateProjectCommand(stored!, structuredClone(stored!)), + /must change/ + ); + + const current = reader.findById("project-1", balance.id)!; + const deleted = run(createEstimateBalanceDeleteProjectCommand(current)); + assert.equal(reader.findById("project-1", balance.id), null); + assert.equal(context.db.select().from(estimateRows).all().length, 0); + run(deleted.inverse, "undo"); + assert.deepEqual(reader.findById("project-1", balance.id), current); + // The original insert's inverse no longer matches the edited balance. + assert.throws(() => run(inserted.inverse), /changed before deletion/); + run(createEstimateBalanceDeleteProjectCommand(current)); + assert.equal(reader.listByProject("project-1").length, 0); + + assert.throws( + () => run(createEstimateBalanceInsertProjectCommand({ ...balance, projectId: "project-2" })), + /does not belong to project/ + ); + } finally { + context.close(); + } + }); + + it("sums detailed device rows of all circuit lists of the project", () => { + const context = createTestDatabase(); + try { + context.db + .insert(distributionBoards) + .values({ id: "board-1", projectId: "project-1", name: "UV 1" }) + .run(); + context.db + .insert(circuitLists) + .values({ id: "list-1", projectId: "project-1", distributionBoardId: "board-1", name: "UV 1" }) + .run(); + context.db + .insert(circuitSections) + .values({ + id: "section-1", + circuitListId: "list-1", + key: "lighting-1", + displayName: "Beleuchtung 1", + prefix: "1F1", + sortOrder: 0, + }) + .run(); + context.db + .insert(circuits) + .values({ + id: "circuit-1", + circuitListId: "list-1", + sectionId: "section-1", + equipmentIdentifier: "-1F1", + displayName: "Licht", + sortOrder: 0, + }) + .run(); + context.db + .insert(circuitDeviceRows) + .values([ + { + id: "row-1", + circuitId: "circuit-1", + name: "Leuchte", + displayName: "Leuchte", + costGroup: "445", + quantity: 10, + powerPerUnit: 0.05, + simultaneityFactor: 0.8, + cosPhi: 0.95, + }, + { + id: "row-2", + circuitId: "circuit-1", + name: "Steckdose", + displayName: "Steckdose", + costGroup: null, + quantity: 2, + powerPerUnit: 0.2, + simultaneityFactor: 0.5, + cosPhi: null, + }, + ]) + .run(); + const detailed = new EstimateBalanceRepository(context.db).listDetailedDeviceRowPower( + "project-1" + ); + assert.deepEqual( + detailed.map((entry) => ({ ...entry, kw: round2(entry.kw) })), + [ + { costGroup: "445", kw: 0.4, cosPhi: 0.95 }, + { costGroup: null, kw: 0.2, cosPhi: null }, + ] + ); + assert.equal( + new EstimateBalanceRepository(context.db).listDetailedDeviceRowPower("project-2").length, + 0 + ); + } finally { + context.close(); + } + }); +}); From e06c7d91e2fff2c764cf19b03a7cb88e73ce90ed Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Sat, 26 Sep 2026 17:48:37 +0200 Subject: [PATCH 03/38] Print the rough power balance in the kbp design The print of the rough power balance was plain grey. It now follows the kbp design of the print view: a title block with office logo, stand, project, number, owner, address, work stage, date, editor and office; header row in kbp blue, cost-group rows tinted with a lilac rule, bold subtotals, the total including reserve as a blue band, colored deviations in the comparison, Arial, exact print colors, and a footer with project, stand and "Seite x von y" on every page. Co-Authored-By: Claude Opus 5.5 --- src/app/globals.css | 210 ++++++++++++++++-- .../grobbilanz/[balanceId]/page.tsx | 2 + .../estimate-print-header.tsx | 104 +++++++++ 3 files changed, 292 insertions(+), 24 deletions(-) create mode 100644 src/frontend/estimate-balance/estimate-print-header.tsx diff --git a/src/app/globals.css b/src/app/globals.css index b3f526a..4a0adc8 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1965,14 +1965,23 @@ button.structure-entry-main:focus-visible { display: none; } +/* Druck im kbp-CD der Seitenansicht (src/frontend/print/print-document.css): + gleiche Farben, Schrift, Titelblock und Fußzeile. Die Fußzeile mit + Seitenzahlen setzt EstimatePrintHeader als @page-Regel mit Projektdaten. */ +.estimate-print-titleblock { + display: none; +} + @page estimate-balance { size: A4 landscape; - margin: 10mm; + margin: 10mm 10mm 13mm; } @media print { body:has(.estimate-print-root) .sidebar, .estimate-print-root .estimate-no-print, + .estimate-print-root .estimate-page-header, + .estimate-print-root .estimate-header-fields, .estimate-print-root .alert, .estimate-print-root input, .estimate-print-root select, @@ -1989,28 +1998,122 @@ button.structure-entry-main:focus-visible { } .estimate-print-root { + --ep-blue: #476088; + --ep-lilac: #9198c4; + --ep-line: #d6dae5; + --ep-tint: #f5f6fa; + --ep-text: #2b2b2b; + --ep-muted: #6b7280; + --ep-accent: #c9782a; page: estimate-balance; padding: 0 !important; max-width: none; - color: #000; + color: var(--ep-text); + font-family: Arial, "Helvetica Neue", Helvetica, sans-serif; + color-scheme: light; + } + + .estimate-print-root * { + -webkit-print-color-adjust: exact; + print-color-adjust: exact; } .estimate-print-root .estimate-print-value { display: inline; } - .estimate-print-root .page-header { + /* Titelblock wie der Plankopf der Seitenansicht */ + .estimate-print-titleblock { + display: grid; + grid-template-columns: 30mm 1fr auto auto; margin-bottom: 4mm; + border: 1.5px solid var(--ep-blue); + background: #fff; + font-size: 8.5pt; + break-inside: avoid; } - .estimate-print-root .page-header h1 { - font-size: 14pt; - color: #000; + .estimate-print-titleblock > * { + padding: 2.5mm 3.5mm; + border-left: 1px solid var(--ep-line); } + .estimate-print-titleblock > :first-child { + border-left: none; + } + + .estimate-print-logo { + display: flex; + align-items: center; + justify-content: center; + min-height: 16mm; + color: var(--ep-blue); + font-weight: bold; + text-align: center; + } + + .estimate-print-logo img { + max-width: 100%; + max-height: 10mm; + } + + .estimate-print-kicker { + color: var(--ep-muted); + font-size: 7pt; + letter-spacing: 0.05em; + text-transform: uppercase; + } + + .estimate-print-heading { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 1mm 4mm; + margin-top: 1mm; + } + + .estimate-print-stand { + color: var(--ep-blue); + font-size: 16pt; + font-weight: bold; + } + + .estimate-print-project { + font-size: 12pt; + font-weight: bold; + } + + .estimate-print-meta { + display: grid; + grid-template-columns: auto auto; + gap: 0.8mm 4mm; + align-content: center; + margin: 0; + font-size: 7.5pt; + } + + .estimate-print-meta div { + display: contents; + } + + .estimate-print-meta dt { + color: var(--ep-muted); + font-weight: normal; + } + + .estimate-print-meta dd { + margin: 0; + font-weight: bold; + } + + .estimate-print-meta.is-tinted { + background: var(--ep-tint); + } + + /* Karten und Ränder der Bildschirmansicht entfallen */ .estimate-print-root .card { border: 0; - box-shadow: none; + box-shadow: none !important; background: transparent; } @@ -2026,54 +2129,117 @@ button.structure-entry-main:focus-visible { break-inside: avoid; } + .estimate-print-root .estimate-comparison-card .card-header { + margin-bottom: 2mm; + color: var(--ep-blue); + font-size: 10pt; + font-weight: bold; + } + .estimate-sheet-wrap { overflow: visible; } + /* Tabelle */ .estimate-sheet { min-width: 0; table-layout: auto; - font-size: 7.5pt; + font-size: 7.4pt; + line-height: 1.2; background: #fff; - color: #000; + color: var(--ep-text); } .estimate-sheet th, .estimate-sheet td { - border-color: #999; - padding: 1px 3px; + border: 1px solid var(--ep-line) !important; + padding: 0.7mm 1.5mm; + background: #fff; + color: var(--ep-text); } .estimate-sheet thead { display: table-header-group; } - .estimate-sheet thead th, - .estimate-total-row td { - background: #e8e8e8 !important; + .estimate-sheet thead th { + background: var(--ep-blue) !important; + border-color: var(--ep-blue) !important; + color: #fff !important; + font-weight: bold; + vertical-align: bottom; + } + + .estimate-sheet thead .estimate-th-hint { + color: #dfe3f0 !important; } .estimate-group-title-row td { - background: #d9d9d9 !important; + background: var(--ep-tint) !important; + border-top: 1.5px solid var(--ep-lilac) !important; + font-weight: bold; + } + + .estimate-group-title-row .estimate-cost-group-cell { + color: var(--ep-blue) !important; + } + + .estimate-group-title-row .estimate-group-editor { + color: var(--ep-muted); + font-weight: normal; } .estimate-subtotal-row td { - background: #f2f2f2 !important; + border-bottom: 1.5px solid var(--ep-line) !important; + font-weight: bold; + } + + .estimate-subtotal-row .estimate-total-label { + color: var(--ep-muted); + } + + .estimate-total-row td { + background: var(--ep-tint) !important; + font-weight: bold; + } + + .estimate-total-row.is-strong td { + background: var(--ep-blue) !important; + border-color: var(--ep-blue) !important; + color: #fff !important; + } + + .estimate-total-row .estimate-total-hint { + color: var(--ep-muted); + font-weight: normal; + } + + .estimate-total-row.is-strong .estimate-total-hint { + color: #dfe3f0; + } + + .estimate-comparison .is-over { + color: var(--ep-accent) !important; + font-weight: bold; + } + + .estimate-comparison .is-under { + color: var(--ep-blue) !important; + font-weight: bold; } .estimate-group-title-row, .estimate-subtotal-row, - .estimate-total-row { + .estimate-total-row, + .estimate-row { break-inside: avoid; - -webkit-print-color-adjust: exact; - print-color-adjust: exact; } .estimate-group-title-row { break-after: avoid; } - /* Totals print once at the end, not repeated on every page. */ + /* Summen einmal am Ende, nicht auf jeder Seite */ .estimate-sheet tfoot { display: table-row-group; break-inside: avoid; @@ -2087,8 +2253,4 @@ button.structure-entry-main:focus-visible { .estimate-gzf-input { justify-content: flex-end; } - - .estimate-header-fields { - margin-bottom: 3mm; - } } diff --git a/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx index 2aa7f5e..584f5cf 100644 --- a/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx +++ b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx @@ -48,6 +48,7 @@ import { } from "../../../../../frontend/estimate-balance/estimate-balance-sheet"; import { EstimateComparisonTable } from "../../../../../frontend/estimate-balance/estimate-comparison-table"; import { DraftInput } from "../../../../../frontend/estimate-balance/estimate-draft-input"; +import { EstimatePrintHeader } from "../../../../../frontend/estimate-balance/estimate-print-header"; import { EstimateGroupModal, type EstimateGroupFormValues, @@ -461,6 +462,7 @@ export default function EstimateBalanceEditorPage() { return (
+ {project && draft ? : null}
\r\n]/g, " ")); +} + +/** + * Print-only title block and page footer of the rough power balance in the + * kbp corporate design of the print view (Seitenansicht): logo, blue title, + * meta data, "Seite x von y". Hidden on screen. + */ +export function EstimatePrintHeader({ project, balance }: EstimatePrintHeaderProps) { + const [office, setOffice] = useState(null); + const [hasLogo, setHasLogo] = useState(false); + const [logoVersion, setLogoVersion] = useState(""); + + useEffect(() => { + getDocumentBranding() + .then((branding) => { + setOffice(branding.office); + setHasLogo(Boolean(branding.logo)); + setLogoVersion(branding.logo ? branding.logo.updatedAtIso : ""); + }) + .catch(() => { + setOffice(null); + setHasLogo(false); + }); + }, []); + + const stand = [balance.name, balance.workStage].filter(Boolean).join(" · "); + const date = balance.dateIso ? formatIsoDateGerman(balance.dateIso) : null; + const footer = ` + @page estimate-balance { + size: A4 landscape; + margin: 10mm 10mm 13mm; + @bottom-left { content: ${cssString(`${project.name} · Grobe Leistungsbilanz`)}; font: 7.5pt Arial, sans-serif; color: #6b7280; } + @bottom-center { content: ${cssString(`Stand ${stand}${date ? ` · ${date}` : ""}`)}; font: 7.5pt Arial, sans-serif; color: #6b7280; } + @bottom-right { content: "Seite " counter(page) " von " counter(pages); font: 7.5pt Arial, sans-serif; color: #6b7280; } + }`; + + return ( + <> + + + + ); +} From 72189d23a50b12ade4672bd6901d2c78626710f2 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Sat, 26 Sep 2026 17:56:53 +0200 Subject: [PATCH 04/38] Offer supply suggestions, drop the circuit column, center cells MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Versorgung field suggests ELT and MSR (plus values already used in the balance) through a datalist and still accepts free text. The circuit number column is not needed in early design phases; it is removed from the data model, the regenerated migration 0010, the editor and the print. All cells are centered except "Verbraucher / Flächen", group titles and total labels. Co-Authored-By: Claude Opus 5.5 --- docs/estimate-balance.md | 2 +- src/app/globals.css | 33 +++++++++++++++- src/db/migrations/0010_estimate_balances.sql | 1 - src/db/migrations/meta/0010_snapshot.json | 9 +---- src/db/migrations/meta/_journal.json | 2 +- src/db/schema/estimate-balances.ts | 1 - .../domain/estimate-balance-command.model.ts | 2 - .../estimate-balance-document.ts | 3 -- .../estimate-balance-sheet.tsx | 39 ++++++++++++------- .../estimate-balance/estimate-balance.ts | 4 +- tests/estimate-balance-frontend.test.ts | 5 +-- tests/estimate-balance.test.ts | 1 - 12 files changed, 60 insertions(+), 42 deletions(-) diff --git a/docs/estimate-balance.md b/docs/estimate-balance.md index 4e43cec..afe4780 100644 --- a/docs/estimate-balance.md +++ b/docs/estimate-balance.md @@ -34,7 +34,7 @@ das Frontend sie direkt nutzt (Turbopack löst die `.js`-Suffixe der API nicht a |---|---| | `estimate_balances` | ein **Stand** je Projekt (z. B. Vorplanung, Entwurfsplanung): Name, LPH, Datum, Reserve AV/SV in %, Sortierung | | `estimate_groups` | Kostengruppe (`"410"` … `"480"`, `""` für „Allgemein“), Titel, „bearbeitet von“, Sortierung | -| `estimate_rows` | Versorgung, Stromkreis-Nr. (Freitext), Verbraucher/Fläche, Anzahl bzw. Fläche, Einheit (`piece` = St., `area` = m²), Anschluss (fest/Steckdose), Einzelleistung in W bzw. W/m², GLF, cos φ, SV ja/nein, Anmerkung | +| `estimate_rows` | Versorgung (Auswahl ELT/MSR oder Freitext), Verbraucher/Fläche, Anzahl bzw. Fläche, Einheit (`piece` = St., `area` = m²), Anschluss (fest/Steckdose), Einzelleistung in W bzw. W/m², GLF, cos φ, SV ja/nein, Anmerkung | Neue Stände entstehen aus der Vorlage KG 400 (410 Sanitär, 420 Wärme, 430 Luft, 434 Kälte, 440 Starkstrom, 450 Schwachstrom, 460 Förder, 470 Nutzungsspezifisch, diff --git a/src/app/globals.css b/src/app/globals.css index 4a0adc8..4f0bcb7 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1731,7 +1731,6 @@ button.structure-entry-main:focus-visible { .estimate-col-kg { width: 3rem; } .estimate-col-supply { width: 4rem; } -.estimate-col-circuit { width: 4.6rem; } .estimate-col-name { width: auto; } .estimate-col-quantity { width: 4.8rem; } .estimate-col-unit { width: 3.8rem; } @@ -1965,6 +1964,36 @@ button.structure-entry-main:focus-visible { display: none; } +/* Ausrichtung: alle Zellen zentriert, nur „Verbraucher / Flächen“, die + Gruppentitel und die Summenbeschriftungen stehen links bzw. rechts. */ +.estimate-sheet td, +.estimate-sheet td.estimate-number, +.estimate-sheet .estimate-cell-input, +.estimate-sheet .estimate-cell-input.is-numeric { + text-align: center; +} + +.estimate-sheet .estimate-cell-select { + text-align: center; + text-align-last: center; +} + +.estimate-sheet .estimate-unit-input, +.estimate-sheet .estimate-gzf-input { + justify-content: center; +} + +.estimate-sheet td.estimate-name-cell, +.estimate-sheet td.estimate-name-cell .estimate-cell-input, +.estimate-sheet .estimate-group-title-row td:not(.estimate-cost-group-cell), +.estimate-comparison td:nth-child(2) { + text-align: left; +} + +.estimate-sheet td.estimate-total-label { + text-align: right; +} + /* Druck im kbp-CD der Seitenansicht (src/frontend/print/print-document.css): gleiche Farben, Schrift, Titelblock und Fußzeile. Die Fußzeile mit Seitenzahlen setzt EstimatePrintHeader als @page-Regel mit Projektdaten. */ @@ -2251,6 +2280,6 @@ button.structure-entry-main:focus-visible { .estimate-unit-input, .estimate-gzf-input { - justify-content: flex-end; + justify-content: center; } } diff --git a/src/db/migrations/0010_estimate_balances.sql b/src/db/migrations/0010_estimate_balances.sql index 645ccbe..bfa9dd3 100644 --- a/src/db/migrations/0010_estimate_balances.sql +++ b/src/db/migrations/0010_estimate_balances.sql @@ -27,7 +27,6 @@ CREATE TABLE `estimate_rows` ( `group_id` text NOT NULL, `sort_order` integer DEFAULT 0 NOT NULL, `supply` text, - `circuit_ref` text, `name` text DEFAULT '' NOT NULL, `quantity` real DEFAULT 0 NOT NULL, `unit` text DEFAULT 'piece' NOT NULL, diff --git a/src/db/migrations/meta/0010_snapshot.json b/src/db/migrations/meta/0010_snapshot.json index 869d504..d58518a 100644 --- a/src/db/migrations/meta/0010_snapshot.json +++ b/src/db/migrations/meta/0010_snapshot.json @@ -1,7 +1,7 @@ { "version": "6", "dialect": "sqlite", - "id": "6df688bd-a78a-46a1-ba7a-4068119bf8bd", + "id": "5376ae9f-67c7-4603-b3d2-8527136436f9", "prevId": "2cd9adef-2f08-4635-b3d9-ecf71f624c7f", "tables": { "buildings": { @@ -1322,13 +1322,6 @@ "notNull": false, "autoincrement": false }, - "circuit_ref": { - "name": "circuit_ref", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, "name": { "name": "name", "type": "text", diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index 209a0a2..f2c5dba 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -75,7 +75,7 @@ { "idx": 10, "version": "6", - "when": 1790425784626, + "when": 1790438092269, "tag": "0010_estimate_balances", "breakpoints": true } diff --git a/src/db/schema/estimate-balances.ts b/src/db/schema/estimate-balances.ts index 81420f1..4425a03 100644 --- a/src/db/schema/estimate-balances.ts +++ b/src/db/schema/estimate-balances.ts @@ -44,7 +44,6 @@ export const estimateRows = sqliteTable( .references(() => estimateGroups.id, { onDelete: "cascade" }), sortOrder: integer("sort_order").notNull().default(0), supply: text("supply"), - circuitRef: text("circuit_ref"), name: text("name").notNull().default(""), quantity: real("quantity").notNull().default(0), unit: text("unit", { enum: ["piece", "area"] }).notNull().default("piece"), diff --git a/src/estimate-balance/domain/estimate-balance-command.model.ts b/src/estimate-balance/domain/estimate-balance-command.model.ts index 44263e4..f1b0da8 100644 --- a/src/estimate-balance/domain/estimate-balance-command.model.ts +++ b/src/estimate-balance/domain/estimate-balance-command.model.ts @@ -28,7 +28,6 @@ export const estimateRowSnapshotSchema = z id: idSchema, sortOrder: z.number().int().min(0), supply: nullableText(50), - circuitRef: nullableText(50), name: trimmed(200), quantity: finite.min(0), unit: z.enum(["piece", "area"]), @@ -158,7 +157,6 @@ export function canonicalEstimateBalance(balance: EstimateBalanceSnapshot): stri id: row.id, sortOrder: row.sortOrder, supply: row.supply, - circuitRef: row.circuitRef, name: row.name, quantity: row.quantity, unit: row.unit, diff --git a/src/frontend/estimate-balance/estimate-balance-document.ts b/src/frontend/estimate-balance/estimate-balance-document.ts index 0049dc2..e2726d1 100644 --- a/src/frontend/estimate-balance/estimate-balance-document.ts +++ b/src/frontend/estimate-balance/estimate-balance-document.ts @@ -18,7 +18,6 @@ export const estimateTextLimits = { groupTitle: 200, groupEditor: 100, supply: 50, - circuitRef: 50, rowName: 200, remark: 500, } as const; @@ -34,7 +33,6 @@ export function createEstimateRow( id: createId(), sortOrder, supply: null, - circuitRef: null, name: "", quantity: 1, unit: "piece", @@ -257,7 +255,6 @@ export function toSaveableEstimateBalance( id: row.id, sortOrder: row.sortOrder, supply: optionalText(row.supply), - circuitRef: optionalText(row.circuitRef), name: requiredText(row.name), quantity: row.quantity, unit: row.unit, diff --git a/src/frontend/estimate-balance/estimate-balance-sheet.tsx b/src/frontend/estimate-balance/estimate-balance-sheet.tsx index debba7f..4703397 100644 --- a/src/frontend/estimate-balance/estimate-balance-sheet.tsx +++ b/src/frontend/estimate-balance/estimate-balance-sheet.tsx @@ -50,8 +50,12 @@ interface EstimateBalanceSheetProps { } // Leading columns up to cos φ; the power columns follow. -const LEADING_COLUMN_COUNT = 10; -const COLUMN_COUNT = 17; +const LEADING_COLUMN_COUNT = 9; +const COLUMN_COUNT = 16; + +/** Suggested supply values; free text stays possible. */ +const SUPPLY_SUGGESTIONS = ["ELT", "MSR"]; +const SUPPLY_LIST_ID = "estimate-supply-options"; function NumberInput({ ariaLabel, @@ -85,9 +89,17 @@ function NumberInput({ ); } +function supplyOptions(balance: EstimateBalanceSnapshot): string[] { + const used = balance.groups.flatMap((group) => + group.rows.map((row) => row.supply?.trim() ?? "") + ); + return [...new Set([...SUPPLY_SUGGESTIONS, ...used.filter(Boolean)])]; +} + function TextInput({ ariaLabel, disabled, + list, maxLength, onChange, placeholder, @@ -95,6 +107,7 @@ function TextInput({ }: { ariaLabel: string; disabled: boolean; + list?: string; maxLength: number; onChange: (value: string) => void; placeholder?: string; @@ -106,6 +119,7 @@ function TextInput({ aria-label={ariaLabel} className="estimate-cell-input" disabled={disabled} + list={list} maxLength={maxLength} onChange={(event) => onChange(event.target.value)} placeholder={placeholder} @@ -189,22 +203,14 @@ function EstimateRowLine({ patch({ supply })} placeholder="ELT" value={row.supply} /> - - patch({ circuitRef })} - value={row.circuitRef} - /> - - + + + {supplyOptions(balance).map((supply) => ( + - @@ -409,9 +419,8 @@ export function EstimateBalanceSheet({ - ); @@ -373,6 +386,7 @@ export function EstimateBalanceSheet({ onChange, onEditGroup, onOpenGzfPicker, + onTakeOverRow, onValidityChange, threePhaseVoltageV, }: EstimateBalanceSheetProps) { @@ -546,6 +560,7 @@ export function EstimateBalanceSheet({ key={row.id} onChange={onChange} onOpenGzfPicker={onOpenGzfPicker} + onTakeOverRow={onTakeOverRow} onValidityChange={onValidityChange} row={row} rowIndex={rowIndex} diff --git a/src/frontend/estimate-balance/estimate-project-device-prefill.ts b/src/frontend/estimate-balance/estimate-project-device-prefill.ts new file mode 100644 index 0000000..4ef9b52 --- /dev/null +++ b/src/frontend/estimate-balance/estimate-project-device-prefill.ts @@ -0,0 +1,51 @@ +import type { CreateProjectDeviceInput } from "../types"; +import type { + EstimateGroupSnapshot, + EstimateRowSnapshot, +} from "../../shared/estimate-balance/estimate-balance"; + +export type EstimateProjectDeviceInitialValues = Omit< + Partial, + "quantity" | "powerPerUnit" +> & { + quantity?: number | null; + powerPerUnit?: number | null; +}; + +const connectionLabels = { + fixed: "Festanschluss", + socket: "Steckdose", +} as const; + +/** + * Builds the editable ProjectDevice proposal for one estimate row. Area rows + * deliberately leave quantity and power blank because W/m² has no equivalent + * in the current ProjectDevice model. + */ +export function createEstimateProjectDeviceInitialValues( + group: Pick, + row: Pick< + EstimateRowSnapshot, + | "name" + | "unit" + | "connection" + | "powerPerUnitW" + | "simultaneityFactor" + | "cosPhi" + | "remark" + > +): EstimateProjectDeviceInitialValues { + const name = row.name.trim(); + return { + name, + displayName: name, + category: "single_phase", + connectionKind: row.connection ? connectionLabels[row.connection] : undefined, + costGroup: group.costGroup || undefined, + quantity: row.unit === "area" ? null : 1, + powerPerUnit: row.unit === "area" ? null : row.powerPerUnitW / 1000, + simultaneityFactor: row.simultaneityFactor, + cosPhi: row.cosPhi, + remark: row.remark ?? undefined, + }; +} diff --git a/tests/estimate-balance-frontend.test.ts b/tests/estimate-balance-frontend.test.ts index ed5f4c7..7604de2 100644 --- a/tests/estimate-balance-frontend.test.ts +++ b/tests/estimate-balance-frontend.test.ts @@ -28,6 +28,7 @@ import { getTodayIsoDate, parseGermanDecimal, } from "../src/frontend/estimate-balance/estimate-balance-format.js"; +import { createEstimateProjectDeviceInitialValues } from "../src/frontend/estimate-balance/estimate-project-device-prefill.js"; import { ApiRequestError, createEstimateBalance, @@ -264,6 +265,55 @@ describe("estimate balance document editing", () => { }); }); +describe("estimate row to project device prefill", () => { + it("maps a piece row to one reusable project-device template", () => { + const balance = sampleBalance(); + const group = balance.groups[0]!; + const row = { + ...group.rows[0]!, + name: " Hebeanlage ", + quantity: 4, + connection: "fixed" as const, + powerPerUnitW: 1250, + simultaneityFactor: 0.8, + cosPhi: 0.9, + remark: "bauseits", + }; + + assert.deepEqual(createEstimateProjectDeviceInitialValues(group, row), { + name: "Hebeanlage", + displayName: "Hebeanlage", + category: "single_phase", + connectionKind: "Festanschluss", + costGroup: "410", + quantity: 1, + powerPerUnit: 1.25, + simultaneityFactor: 0.8, + cosPhi: 0.9, + remark: "bauseits", + }); + }); + + it("leaves quantity and power blank for an area row", () => { + const balance = sampleBalance(); + const group = balance.groups[1]!; + const row = { + ...createEstimateRow(0, () => "area-row"), + name: "Bürofläche", + unit: "area" as const, + connection: "socket" as const, + quantity: 250, + powerPerUnitW: 15, + }; + + const initial = createEstimateProjectDeviceInitialValues(group, row); + assert.equal(initial.quantity, null); + assert.equal(initial.powerPerUnit, null); + assert.equal(initial.connectionKind, "Steckdose"); + assert.equal(initial.costGroup, "440"); + }); +}); + describe("estimate balance saving", () => { it("builds the trimmed server document with null for empty optional texts", () => { let balance = sampleBalance(); diff --git a/tests/project-version-history.test.ts b/tests/project-version-history.test.ts index 59a2aac..4e85d41 100644 --- a/tests/project-version-history.test.ts +++ b/tests/project-version-history.test.ts @@ -3,7 +3,11 @@ import { describe, it } from "node:test"; import { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { ProjectVersionHistory } from "../src/frontend/components/project-version-history.js"; -import { ProjectDeviceModal } from "../src/frontend/components/project-device-modal.js"; +import { + hasExistingProjectDeviceName, + isProjectDeviceNumberInRange, + ProjectDeviceModal, +} from "../src/frontend/components/project-device-modal.js"; import { ProjectSettingsModal } from "../src/frontend/components/project-settings-modal.js"; import type { ProjectRevisionSummaryDto, @@ -324,6 +328,42 @@ describe("project device modal presentation", () => { assert.match(markup, /1-phasig/); assert.match(markup, /3-phasig/); }); + + it("rejects empty required numbers while keeping zero valid", () => { + assert.equal(isProjectDeviceNumberInRange("", 0), false); + assert.equal(isProjectDeviceNumberInRange(" ", 0), false); + assert.equal(isProjectDeviceNumberInRange("0", 0), true); + assert.equal(isProjectDeviceNumberInRange("0,8", 0, 1), true); + }); + + it("renders blank area values as invalid and warns about duplicate names", () => { + const markup = renderToStaticMarkup( + createElement(ProjectDeviceModal, { + existingDevices: [{ name: "Bürofläche", displayName: "Bürofläche" }], + globalDevices: [], + initialValues: { + name: "Bürofläche", + displayName: "Bürofläche", + quantity: null, + powerPerUnit: null, + }, + isSaving: false, + onClose: () => undefined, + onImportGlobal: async () => undefined, + onSave: async () => undefined, + }) + ); + assert.match(markup, /gleichem internen Namen oder Anzeigenamen/); + assert.match(markup, /id="device-quantity"[^>]*value=""/); + assert.match(markup, /id="device-power"[^>]*value=""/); + assert.match(markup, / + @@ -1015,6 +1089,7 @@ export default function ProjectDetailPage() { ] : "Nicht festgelegt"} + ` so it repeats on printed pages. PDF export uses the browser print dialog; page size, margins and "Seite x von y" come from injected named `@page` rules (`lb-portrait`, `lb-landscape`). -- The board hierarchy and "Σ inkl. unterlagert" in the overview are - PRELIMINARY (text match of `fedFrom` against board number/name, plain sum, - no upstream simultaneity factor). Replace this once the feed link is modeled. +- The board hierarchy follows logical board ids. The overview shows power + before board GZF and demand including linked downstream boards; it does not + add a second cumulative column. Board plans render downstream-board loads as + read-only rows. `fedFrom` groups only external root feeds. - Colors/fonts follow the kbp corporate design (`--pd-*` variables in `print-document.css`). Empty cover values are shown as "[ergänzen]"; the Planstände editor column shows the project's current @@ -701,9 +718,9 @@ for the early-phase power balance by DIN 276 cost group (see - full electrical sizing - multi-user/PostgreSQL operation - supported production deployment -- logical feed link between distribution boards (`fedFrom` stays free text - until the project owner decides whether it references a board, a feeding - circuit or both) and the resulting hierarchical power summation +- second/replacement board feeds, including changeover semantics for SV/SiBe +- Revit prefill proposals for logical board feeds through the Phase 14 preview + and explicit-confirmation workflow Do not implement these while working on an unrelated phase. diff --git a/docs/circuit-list-editor-api.md b/docs/circuit-list-editor-api.md index c9cd2b7..a8173f5 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -67,10 +67,13 @@ Prüfsumme; Ersetzen übernimmt die Grobbilanzen atomar und mit Undo/Redo, Duplizieren vergibt neue IDs. Transferformat 1 bleibt ohne Grobbilanzen importierbar. -Das aktuelle Projekt-Snapshot-Schema 8 enthält außerdem die optionale -Netto-Raumfläche `rooms[].areaM2`. Snapshot-Versionen 1–7 werden dafür mit +Das aktuelle Projekt-Snapshot-Schema 9 enthält die logischen Einspeisungsverweise +der Verteilungen; Versionen 1–8 werden mit leeren Verweisen hochgestuft. Schema 8 +enthält außerdem die optionale Netto-Raumfläche `rooms[].areaM2`. +Snapshot-Versionen 1–7 werden dafür mit `areaM2 = null` hochgestuft. Restore, Export und Import erhalten vorhandene -Flächen; eine eigene Transferformat-Version ist nicht nötig, weil Format 2 den +Flächen und Einspeisungsverweise; beim Duplizieren werden Board- und Circuit-IDs +neu zugeordnet. Eine eigene Transferformat-Version ist nicht nötig, weil Format 2 den versionierten Projektsnapshot einbettet. The public dispatcher supports the Circuit and CircuitDeviceRow commands @@ -254,23 +257,30 @@ commands. Endpoints, payloads and calculation rules: `docs/estimate-balance.md`. - stale revisions return `409 PROJECT_REVISION_CONFLICT` - `PUT /projects/:projectId/distribution-boards/:distributionBoardId` - body: - `{ "floorId": null, "supplyType": "AV", "simultaneityFactor": 1, "expectedRevision": 13 }` + `{ "floorId": null, "supplyType": "AV", "simultaneityFactor": 1, "feedingDistributionBoardId": "board_hv", "feedingCircuitId": "circuit_out", "expectedRevision": 13 }` - optional info-card fields: `boardNumber` (max. 50), `location`, `fedFrom` (max. 200 each) and `remark` (max. 2000); strings are trimmed and an empty string is stored as `null` - - executes `distribution-board.update`; all submitted values, including the + - `feedingDistributionBoardId` and `feedingCircuitId` are optional nullable + fields. A feeding circuit requires a feeding board and must belong to it; + self-links and cycles are rejected. A board-only link creates hierarchy + without assigning its load to an upstream circuit. + - executes `distribution-board.update` schema version 2; all submitted values, including the submitted info fields, are restored together by persistent Undo/Redo - - `fedFrom` is free text until the logical feed link is modeled + - `fedFrom` remains free text for external feeds such as HAK, metering, + transformer or generator and for supplementary notes - `POST /projects/:projectId/distribution-boards/:distributionBoardId/copy` - body: `{ "name": "UV-02 Kopie", "expectedRevision": 14 }` - duplicates the complete distribution-board subtree with new owning UUIDs - while preserving project-device and room links + while preserving project-device, room and incoming feeding links - response includes the new `distributionBoard`, its `circuitList`, the revision and current history state - `DELETE /projects/:projectId/distribution-boards/:distributionBoardId` - body: `{ "expectedRevision": 15 }` - removes the complete, exactly captured distribution-board subtree in one transaction + - rejects deletion while another board references this board or one of its + circuits as a feeder; circuit and populated-group deletion use the same guard - response includes `distributionBoardId`, the revision and current history state - Copy and deletion use `distribution-board.insert-subtree` and @@ -327,12 +337,17 @@ commands. Endpoints, payloads and calculation rules: `docs/estimate-balance.md`. ### Tree Endpoint +- `GET /projects/:projectId/circuit-trees` + - returns all circuit trees for one project from one project-wide read and is + used by the print view and feeding-board selection - `GET /projects/:projectId/circuit-lists/:circuitListId/tree` - Purpose: returns fixed header components, grouped sections with optional protection components, complete circuit/device-row blocks and auxiliary footer components. Circuit and component protection devices use their separate one-to-one DTOs. Calculated row, circuit, section and board totals - remain included. + remain included. Circuit totals contain the demand of linked downstream + boards. `downstreamBoardLoads` exposes those contributions as read-only rows; + `feedingReference` resolves the current board/circuit labels by id. Response sketch: diff --git a/docs/circuit-list-editor-known-limitations.md b/docs/circuit-list-editor-known-limitations.md index 78bb44e..fdc463a 100644 --- a/docs/circuit-list-editor-known-limitations.md +++ b/docs/circuit-list-editor-known-limitations.md @@ -33,10 +33,13 @@ - Protection and cable values are planner-owned manual selections. The later sizing/warning engine does not yet validate them against load, length or voltage-drop rules. -- Distribution-board `fedFrom` is free text. The print overview derives its - supply structure and "Σ inkl. unterlagert" only from exact text matches with - board numbers/names and adds values without an upstream simultaneity factor - (see `docs/print-view.md`). +- One logical incoming feed per distribution board is supported. A second or + replacement feed with changeover semantics (for example SV/SiBe) is still a + follow-up. `fedFrom` remains the free-text field for external sources and + supplementary notes. Revit does not yet propose logical feed links. +- A logical link without a selected feeding circuit appears in the hierarchy, + but deliberately contributes no load to an upstream circuit until the planner + selects that circuit (see `docs/print-view.md`). - The print view uses a kbp corporate design derived from logo and presentation material. Snapshots do not record an editor, so the cover's Planstände list shows the project's current editor for every entry. On screen, long diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 332b6a9..920002d 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -468,8 +468,22 @@ Derselbe Befehl versioniert die Felder der Verteiler-Infokarte (`boardNumber`, `location`, `fedFrom`, `remark`, Migration `0007`). Die Infokarte liegt im Bearbeiten-Dialog der Verteilung; die Werte sind lokale Planungswerte und sollen später über den Revit-Abgleich nur nach Vorschau und -ausdrücklicher Bestätigung vorbelegt werden. `fedFrom` ist vorerst Freitext. -Snapshot-Schema 8 enthält zusätzlich die optionale Netto-Raumfläche +ausdrücklicher Bestätigung vorbelegt werden. `fedFrom` bleibt Freitext für +externe Einspeisungen und Hinweise. +`distribution-board.update` verwendet Schema-Version 2 für die optionalen +logischen Verweise `feedingDistributionBoardId` und `feedingCircuitId`. +Version-1-Befehle aus der Historie bleiben ausführbar und verändern diese +Verweise nicht. Der speisende Stromkreis muss zur speisenden Verteilung gehören; +Selbstverweise und Zyklen werden abgelehnt. Löschbefehle für referenzierte +Verteilungen und Stromkreise, einschließlich Unterbaum- und Undo-Pfaden, werden +vor der Datenbankänderung fachlich gesperrt. +Die projektweite Circuit-Tree-Projektion berechnet rekursiv die Lasten aller +Verteilungen. Die Leistung einer Unterverteilung nach ihrem eigenen +Verteiler-GZF wird als virtuelle, schreibgeschützte Zeile genau dem gewählten +Abgang zugerechnet. Eine Verknüpfung ohne Stromkreis bildet nur die Hierarchie. +Snapshot-Schema 9 enthält die beiden Einspeisungsverweise; Versionen 1–8 werden +mit `null` hochgestuft. Restore und Projektduplizierung erhalten beziehungsweise +remappen die Verweise. Snapshot-Schema 8 enthält zusätzlich die optionale Netto-Raumfläche `rooms[].areaM2`; Versionen 1–7 werden dafür mit `null` hochgestuft. Snapshot-Schema 7 enthält die Gebäude und die Gebäudezuordnung der Etagen; ältere Versionen werden ohne Gebäude hochgestuft. @@ -580,7 +594,7 @@ Oberfläche: `/projects/:projectId/grobbilanz`. Details: `toLowerCase()` gegen das vollständige Register der Stromkreisliste und wird von jedem Anlage-/Umbenennungspfad für Stromkreise und Verteilerkomponenten aufgerufen, auch dort, wo zuvor kein Vorab-Check existierte. Snapshot- und - Transfer-Integration verwenden aktuell Snapshot-Schema 8. Persistente + Transfer-Integration verwenden aktuell Snapshot-Schema 9. Persistente Insert/Delete/Update-Commands für veränderliche Verteilerkomponenten, Gruppen einschließlich befüllter Unterbäume sowie vollständige Gruppensortierung sind integriert. Der Editor zeigt die geschützte Struktur diff --git a/docs/print-view.md b/docs/print-view.md index eba91ed..a843030 100644 --- a/docs/print-view.md +++ b/docs/print-view.md @@ -5,8 +5,9 @@ Die Aktionen für Büroangaben und Logo speichern dagegen globale Einstellungen. Projekt- und Verteilerangaben werden in den jeweiligen Bearbeitungsdialogen über Projektbefehle mit Undo/Redo gepflegt. -Beim Laden werden die Projektrevisionen aller Stromkreislisten und ein -abschließend erneut gelesener Projektstand verglichen. Ändert sich das Projekt +Beim Laden werden alle Stromkreislisten in einer projektweiten Abfrage gelesen; +deren Projektrevision und ein abschließend erneut gelesener Projektstand werden +verglichen. Ändert sich das Projekt währenddessen, wird statt eines gemischten Datenstands eine Aufforderung zum Neuladen angezeigt. Eine bereits geladene Seitenansicht aktualisiert sich nicht automatisch bei späteren Änderungen in einem anderen Tab. @@ -31,12 +32,14 @@ automatisch bei späteren Änderungen in einem anderen Tab. erscheinen als orangefarbenes „[ergänzen]“. 2. **Verteilerübersicht (quer)** – Versorgungsstruktur und Tabelle je Verteiler mit Stromkreisanzahl, Pinst (Anzahl × Leistung je - Stück), PGeräte (mit Geräte-GZF), Verteiler-GZF, - Pgl, IB und „Σ inkl. unterlagert“. + Stück, nur lokale Geräte), Leistung vor Verteiler-GZF einschließlich + gespeister Unterverteilungen, Verteiler-GZF, Pgl einschließlich + Unterverteilungen und IB. Die Hierarchie folgt den logischen IDs. 3. **Verteilerpläne (quer, je Verteiler)** – Titelleiste mit Verteilernummer, Bezeichnung, Örtlichkeit, Netzart, „Gespeist von“ und Pgl; darunter Kopfkomponenten, Gruppen, Stromkreise - (mehrzeilige mit Sammelzeile und eingerückten Gerätezeilen), + (mehrzeilige mit Sammelzeile, eingerückten Gerätezeilen und + schreibgeschützten Unterverteilungszeilen), Gruppensummen und Verteilersumme. Fehlende Kabelangaben sind als „offen“ markiert. Die Titelleiste steht im Tabellenkopf und wiederholt sich beim Drucken auf Folgeseiten. @@ -46,19 +49,25 @@ Seitenformat, Ränder und „Seite x von y“ kommen beim Drucken aus benannten einfügt. Die Bildschirmansicht zeigt Blätter in Papiergröße; die exakte Seitenaufteilung langer Verteilerpläne entsteht erst beim Drucken. -## Vorläufige Punkte +## Berechnung und offene Punkte -- **Einspeisung / Hierarchie:** `fedFrom` ist Freitext. Die Übersicht ordnet - einen Verteiler nur dann unter, wenn der Text eindeutig der Nummer oder - Bezeichnung eines anderen Verteilers entspricht (ohne Beachtung von - Groß-/Kleinschreibung und äußeren Leerzeichen). Mehrdeutige Treffer bleiben - ohne Zuordnung; „Σ inkl. unterlagert“ ist - eine einfache Summe ohne übergeordneten GZF. Die fachliche Verknüpfung - (Verteiler und/oder speisender Stromkreis) und die Summierungslogik sind - offen. -- **IB** ist ein symmetrischer Drehstromwert - S / (√3 · U3~) mit S aus P / cos φ je Gerätezeile - (fehlendes cos φ = 1) und Verteiler-GZF. +- **Einspeisung / Hierarchie:** `feedingDistributionBoardId` bestimmt die + Hierarchie. Ist zusätzlich `feedingCircuitId` gesetzt, fließt die Leistung + der Unterverteilung nach deren eigenem Verteiler-GZF als virtuelle Last in + genau diesen Abgang ein. Ketten werden rekursiv berechnet; mehrere + Unterverteilungen an einem Abgang sind erlaubt. Ohne Abgang bleibt es bei der + Hierarchie ohne Leistungsaufschlag. `fedFrom` bezeichnet nur externe Quellen + oder ergänzende Hinweise. +- **Keine Doppelzählung:** Die Abgangs- und Verteilersummen enthalten die + Unterverteilungsleistung bereits. Deshalb gibt es keine zusätzliche Spalte + „Σ inkl. unterlagert“. Die Summenzeile verwendet für hierarchische Leistungen + nur Wurzelverteilungen; Pinst summiert weiterhin die lokalen Geräte. +- **IB:** S entsteht aus Σ(P / cos φ) für Geräte und den wirksamen + cos φ der Unterverteilungen, jeweils mit dem fachlich zugehörigen GZF. Bei + einem 1-phasigen speisenden Abgang gilt I = S / U1~, sonst + I = S / (√3 · U3~). Für externe oder nur bis zur Verteilung + bekannte Einspeisungen bleibt die bisherige Darstellung als symmetrischer + Drehstromwert bestehen. - **Corporate Design:** Farben (`--pd-*` in `src/frontend/print/print-document.css`) und Schrift (Arial) sind aus Logo und kbp-Präsentationsmaterial abgeleitet und werden durch die offizielle @@ -118,10 +127,11 @@ ihren Wert. ## Bestehende Datenbanken -Vor dem Anwenden der additiven Migrationen `0007` und `0008` eine verifizierte +Vor dem Anwenden der additiven Migrationen einschließlich `0012` eine verifizierte Datenbanksicherung mit `npm run db:backup` erstellen. Die neuen Projekt- und Verteilerfelder bleiben bei bestehenden Datensätzen zunächst leer (`null`). -Snapshot-Schema 6 enthält beide Feldgruppen; die unterstützten Versionen 1–5 -werden beim Lesen hochgestuft. Restore und Projektkopie erhalten die neuen -Angaben. Globale Büroangaben und Logo gehören zur Datenbanksicherung, nicht +Snapshot-Schema 9 enthält zusätzlich die logischen Einspeisungsverweise; die +unterstützten Versionen 1–8 werden mit leeren Verweisen hochgestuft. Restore und +Projektkopie erhalten beziehungsweise remappen die neuen Angaben. Globale +Büroangaben und Logo gehören zur Datenbanksicherung, nicht zum logischen Projektsnapshot oder Projekttransfer. diff --git a/docs/spec/08-current-product-backlog.md b/docs/spec/08-current-product-backlog.md index d31eecc..c0a2720 100644 --- a/docs/spec/08-current-product-backlog.md +++ b/docs/spec/08-current-product-backlog.md @@ -149,9 +149,10 @@ The pre-release cleanup established the following compatibility boundary: - [x] Rough power balance for LPH 2/3 by cost group, including the comparison with the detailed balance and the explicit copy of one row as a ProjectDevice. +- [x] Logical distribution-board feed link with an optional feeding circuit, + recursive load rollup and deletion guards (#3). -Open follow-ups (Gitea issues): logical feed link between distribution boards -(#3), bill of quantities export (#5), area-based loads in W/m² for +Open follow-ups (Gitea issues): bill of quantities export (#5), area-based loads in W/m² for ProjectDevices and device rows (#20). ## Recommended Sequence diff --git a/src/app/projects/[projectId]/print/page.tsx b/src/app/projects/[projectId]/print/page.tsx index dcbe7b2..7762875 100644 --- a/src/app/projects/[projectId]/print/page.tsx +++ b/src/app/projects/[projectId]/print/page.tsx @@ -7,10 +7,9 @@ import "../../../../frontend/print/print-document.css"; import { deleteDocumentLogo, documentLogoUrl, - getCircuitTree, + getProjectCircuitTrees, getDocumentBranding, getProject, - listCircuitLists, listDistributionBoards, listFloors, listProjectSnapshots, @@ -31,7 +30,7 @@ import { import { PrintDocument } from "../../../../frontend/print/print-document"; import { assertPrintRevisionConsistency, - buildPreliminaryBoardHierarchy, + buildBoardHierarchy, summarizePrintBoard, type PrintBoardSummary, } from "../../../../frontend/print/print-document-model"; @@ -89,17 +88,20 @@ export default function ProjectPrintPage() { } let cancelled = false; async function load() { - const [project, boards, circuitLists, floors, snapshots, branding] = + const [project, boards, projectTrees, floors, snapshots, branding] = await Promise.all([ getProject(projectId), listDistributionBoards(projectId), - listCircuitLists(projectId), + getProjectCircuitTrees(projectId), listFloors(projectId), listProjectSnapshots(projectId), getDocumentBranding(), ]); const floorNameById = new Map(floors.map((floor) => [floor.id, floor.name])); - const summaries = await Promise.all( + const treeByBoardId = new Map( + projectTrees.trees.map((tree) => [tree.distributionBoardId, tree]) + ); + const summaries = [...boards] .sort( (left, right) => @@ -107,20 +109,17 @@ export default function ProjectPrintPage() { boardSortCollator.compare(left.name, right.name) ) .flatMap((board) => { - const circuitList = circuitLists.find( - (list) => list.distributionBoardId === board.id - ); - return circuitList ? [{ board, circuitList }] : []; + const tree = treeByBoardId.get(board.id); + return tree ? [{ board, tree }] : []; }) - .map(async ({ board, circuitList }) => + .map(({ board, tree }) => summarizePrintBoard({ board, - circuitListId: circuitList.id, - tree: await getCircuitTree(projectId, circuitList.id), + circuitListId: tree.circuitListId, + tree, floorName: board.floorId ? floorNameById.get(board.floorId) ?? null : null, }) - ) - ); + ); const finalProject = await getProject(projectId); assertPrintRevisionConsistency(project.currentRevision, summaries, finalProject.currentRevision); if (cancelled) { @@ -148,7 +147,7 @@ export default function ProjectPrintPage() { }, [projectId]); const entries = useMemo( - () => (data ? buildPreliminaryBoardHierarchy(data.summaries) : []), + () => (data ? buildBoardHierarchy(data.summaries) : []), [data] ); const stand = useMemo( diff --git a/src/frontend/print/print-document-model.ts b/src/frontend/print/print-document-model.ts index abe08fe..d3e4724 100644 --- a/src/frontend/print/print-document-model.ts +++ b/src/frontend/print/print-document-model.ts @@ -19,14 +19,14 @@ export interface PrintBoardSummary { circuitCount: number; /** Σ quantity × power per unit, without any simultaneity factor. */ installedPowerKw: number; - /** Σ row totals, i.e. with the device-row simultaneity factors. */ - devicePowerKw: number; + /** Device-row demand plus downstream-board demand before this board's GZF. */ + powerBeforeBoardSimultaneityKw: number; simultaneityFactor: number; - /** Device power with the board simultaneity factor applied. */ + /** Total active power with this board's simultaneity factor applied. */ demandPowerKw: number; /** - * Symmetrical three-phase design current from the apparent power - * S = Σ(row total / cos φ) × board GZF. A missing cos φ counts as 1. + * Design current from the apparent power including downstream boards. + * The selected feeder circuit determines whether one or three phases apply. */ designCurrentA: number; } @@ -46,8 +46,13 @@ export function summarizePrintBoard(input: { circuitCount += 1; for (const row of circuit.deviceRows) { installedPowerKw += row.quantity * row.powerPerUnit; - apparentPowerKva += row.rowTotalPower / (row.cosPhi || 1); } + apparentPowerKva += + circuit.circuitApparentPower ?? + circuit.deviceRows.reduce( + (sum, row) => sum + row.rowTotalPower / (row.cosPhi || 1), + 0 + ); } } const simultaneityFactor = tree.distributionBoardSimultaneityFactor; @@ -55,12 +60,13 @@ export function summarizePrintBoard(input: { ...input, circuitCount, installedPowerKw, - devicePowerKw: tree.distributionBoardTotalPower, + powerBeforeBoardSimultaneityKw: tree.distributionBoardTotalPower, simultaneityFactor, demandPowerKw: tree.distributionBoardTotalPowerWithSimultaneityFactor, - designCurrentA: - (apparentPowerKva * simultaneityFactor * 1000) / - (Math.sqrt(3) * tree.threePhaseVoltageV), + designCurrentA: calculateDesignCurrent( + apparentPowerKva * simultaneityFactor, + tree + ), }; } @@ -68,8 +74,6 @@ export interface PrintBoardHierarchyEntry { summary: PrintBoardSummary; depth: number; parentBoardId: string | null; - /** Own demand plus the plain sum of all resolved downstream boards. */ - cumulatedDemandPowerKw: number; } export function assertPrintRevisionConsistency( @@ -82,31 +86,21 @@ export function assertPrintRevisionConsistency( } } -/** - * PRELIMINARY: `fedFrom` is free text until the logical feed link is - * decided. A board is shown below another board only when its `fedFrom` - * text equals that board's number or name (case-insensitive). The - * cumulated value is a plain sum without an upstream simultaneity factor. - * Unresolved texts and cycles keep a board at the top level. - */ -export function buildPreliminaryBoardHierarchy( +export function buildBoardHierarchy( summaries: PrintBoardSummary[] ): PrintBoardHierarchyEntry[] { - const normalize = (value: string | null) => - value?.trim().toLocaleLowerCase("de") || null; + const summaryById = new Map( + summaries.map((summary) => [summary.board.id, summary]) + ); const parentById = new Map(); for (const summary of summaries) { - const fedFrom = normalize(summary.board.fedFrom); - const candidates = fedFrom - ? summaries.filter( - (candidate) => - candidate !== summary && - (normalize(candidate.board.boardNumber) === fedFrom || - normalize(candidate.board.name) === fedFrom) - ) - : []; - const parent = candidates.length === 1 ? candidates[0] : undefined; - parentById.set(summary.board.id, parent?.board.id ?? null); + const parentId = summary.board.feedingDistributionBoardId; + parentById.set( + summary.board.id, + parentId && parentId !== summary.board.id && summaryById.has(parentId) + ? parentId + : null + ); } for (const summary of summaries) { const visited = new Set([summary.board.id]); @@ -125,20 +119,12 @@ export function buildPreliminaryBoardHierarchy( summaries.filter( (summary) => parentById.get(summary.board.id) === boardId ); - const cumulated = (summary: PrintBoardSummary): number => - summary.demandPowerKw + - childrenOf(summary.board.id).reduce( - (sum, child) => sum + cumulated(child), - 0 - ); - const entries: PrintBoardHierarchyEntry[] = []; const walk = (summary: PrintBoardSummary, depth: number) => { entries.push({ summary, depth, parentBoardId: parentById.get(summary.board.id) ?? null, - cumulatedDemandPowerKw: cumulated(summary), }); childrenOf(summary.board.id).forEach((child) => walk(child, depth + 1)); }; @@ -146,6 +132,25 @@ export function buildPreliminaryBoardHierarchy( return entries; } +export function formatFeedingReference(summary: PrintBoardSummary): string { + const reference = summary.tree.feedingReference; + if (!reference) return summary.board.fedFrom ?? "–"; + return `${ + reference.distributionBoardNumber ?? reference.distributionBoardName + }${reference.circuitEquipmentIdentifier ?? ""}`; +} + +function calculateDesignCurrent( + apparentPowerKva: number, + tree: CircuitTreeResponseDto +) { + const category = tree.feedingReference?.circuitCategory; + return category === "lighting" || category === "single_phase" + ? (apparentPowerKva * 1000) / tree.singlePhaseVoltageV + : (apparentPowerKva * 1000) / + (Math.sqrt(3) * tree.threePhaseVoltageV); +} + const kilowattFormat = new Intl.NumberFormat("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2, diff --git a/src/frontend/print/print-document.tsx b/src/frontend/print/print-document.tsx index c39b4ba..5a0152b 100644 --- a/src/frontend/print/print-document.tsx +++ b/src/frontend/print/print-document.tsx @@ -13,6 +13,7 @@ import { formatCircuitCable, formatCurrent, formatFactor, + formatFeedingReference, formatKilowatt, formatProtectionDevice, formatUnitPower, @@ -269,8 +270,8 @@ function OverviewSheet({ stand: string; }) { const roots = entries.filter((entry) => entry.parentBoardId === null); - // Top-level boards whose "fed from" text names no other board are grouped - // below that text as an external feed (e.g. "HAK / Zähleranlage"). + // Root boards may still carry an external feed description such as + // "HAK / Zähleranlage"; logical board links determine the actual tree. const feedGroups = new Map(); for (const root of roots) { const feed = root.summary.board.fedFrom ?? ""; @@ -320,11 +321,10 @@ function OverviewSheet({ - + - + - @@ -340,41 +340,45 @@ function OverviewSheet({ - + - + - ); })} - + - - +
KG Versorgung - ELT/ISP … + ELT/MSR … Stromkreis-Nr. Verbraucher / Flächen Anzahl / Fläche diff --git a/src/shared/estimate-balance/estimate-balance.ts b/src/shared/estimate-balance/estimate-balance.ts index 1a7b5a5..63d3753 100644 --- a/src/shared/estimate-balance/estimate-balance.ts +++ b/src/shared/estimate-balance/estimate-balance.ts @@ -12,10 +12,8 @@ export type EstimateRowConnection = "fixed" | "socket"; export interface EstimateRowSnapshot { id: string; sortOrder: number; - /** Versorgung, e.g. "ELT" or "ISP". */ + /** Versorgung, e.g. "ELT" or "MSR" (free text). */ supply: string | null; - /** Optional circuit reference, free text. */ - circuitRef: string | null; /** Verbraucher / Fläche. May be empty while a row is being typed. */ name: string; /** Anzahl (unit "piece") or area in m² (unit "area"). */ diff --git a/tests/estimate-balance-frontend.test.ts b/tests/estimate-balance-frontend.test.ts index fa9368d..ed5f4c7 100644 --- a/tests/estimate-balance-frontend.test.ts +++ b/tests/estimate-balance-frontend.test.ts @@ -165,7 +165,6 @@ describe("estimate balance document editing", () => { id: "row-x", sortOrder: 3, supply: null, - circuitRef: null, name: "", quantity: 1, unit: "piece", @@ -273,7 +272,6 @@ describe("estimate balance saving", () => { balance = updateEstimateRow(balance, "group-410", "row-a", { name: " Hebeanlage ", supply: " ELT ", - circuitRef: "", remark: " ", }); const saveable = toSaveableEstimateBalance(balance); @@ -286,10 +284,9 @@ describe("estimate balance saving", () => { { name: saveable.groups[0]!.rows[0]!.name, supply: saveable.groups[0]!.rows[0]!.supply, - circuitRef: saveable.groups[0]!.rows[0]!.circuitRef, remark: saveable.groups[0]!.rows[0]!.remark, }, - { name: "Hebeanlage", supply: "ELT", circuitRef: null, remark: null } + { name: "Hebeanlage", supply: "ELT", remark: null } ); }); diff --git a/tests/estimate-balance.test.ts b/tests/estimate-balance.test.ts index 7d294da..1463fe4 100644 --- a/tests/estimate-balance.test.ts +++ b/tests/estimate-balance.test.ts @@ -52,7 +52,6 @@ function row( id: id(), sortOrder: 0, supply: "ELT", - circuitRef: null, name, quantity, unit: "piece", From 7b2419b347470807a6a5a9a6bc395fe9ba51009b Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Sat, 26 Sep 2026 18:00:57 +0200 Subject: [PATCH 05/38] Polish the printed rough power balance The printed page kept the dark app background in the page margins, the consumer column wrapped while the empty remark column took the space, an empty "bearbeitet von" label was printed, and numbers were printed as typed (11200). Print margins are white now, the consumer column is wider, empty editors are omitted and numbers print with thousands separators (11.200) like the template. Co-Authored-By: Claude Opus 5.5 --- src/app/globals.css | 28 ++++++++++++++++++- .../estimate-balance-sheet.tsx | 10 ++++++- .../estimate-balance/estimate-draft-input.tsx | 7 ++++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/app/globals.css b/src/app/globals.css index 4f0bcb7..dbf49fb 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -2018,10 +2018,36 @@ button.structure-entry-main:focus-visible { display: none !important; } - body:has(.estimate-print-root) { + html:has(.estimate-print-root), + body:has(.estimate-print-root), + body:has(.estimate-print-root) .app-shell, + body:has(.estimate-print-root) .app-shell-content { background: #fff !important; } + /* Der Dunkelmodus setzt color-scheme: dark; Chrome färbt damit auch den + Seitenrand dunkel. Im Druck gilt immer das helle Schema. */ + html:has(.estimate-print-root) { + color-scheme: light !important; + } + + .estimate-print-root .estimate-group-editor.is-empty { + display: none; + } + + /* Verbraucher bekommt den Platz; Anmerkungen bleiben schmal. */ + .estimate-sheet .estimate-col-name { + width: 52mm; + } + + .estimate-sheet .estimate-col-remark { + width: 24mm; + } + + .estimate-sheet .estimate-col-supply { + width: 13mm; + } + body:has(.estimate-print-root) .app-shell { display: block; } diff --git a/src/frontend/estimate-balance/estimate-balance-sheet.tsx b/src/frontend/estimate-balance/estimate-balance-sheet.tsx index 4703397..07dc19c 100644 --- a/src/frontend/estimate-balance/estimate-balance-sheet.tsx +++ b/src/frontend/estimate-balance/estimate-balance-sheet.tsx @@ -31,6 +31,7 @@ import { formatKw, parseGermanDecimal, type DecimalRange, + formatGermanNumber, } from "./estimate-balance-format"; import { DraftInput } from "./estimate-draft-input"; @@ -81,6 +82,7 @@ function NumberInput({ disabled={disabled} format={(current: number) => formatDecimalInput(current)} inputMode="decimal" + printFormat={(current: number) => formatGermanNumber(current, 0, 3)} onCommit={onCommit} onValidityChange={(isValid) => onValidityChange(fieldKey, isValid)} parse={(text) => parseGermanDecimal(text, range)} @@ -461,7 +463,13 @@ export function EstimateBalanceSheet({
{group.title} -
{phase === 3 ? ( diff --git a/tests/cable-sizing-calculation.test.ts b/tests/cable-sizing-calculation.test.ts index 05e4f3d..39cfbb1 100644 --- a/tests/cable-sizing-calculation.test.ts +++ b/tests/cable-sizing-calculation.test.ts @@ -45,28 +45,34 @@ const capacity = ( CROSS_SECTIONS_MM2.indexOf(crossSection as (typeof CROSS_SECTIONS_MM2)[number]) ]; -describe("cable sizing reference tables (IEC 60364-5-52 Annex B)", () => { +describe("cable sizing reference tables (DIN VDE 0298-4:2023-06)", () => { it("contains the checked PVC copper values", () => { - // B.52.2: A1 two loaded conductors (the previously wrong row) + assert.equal(capacity("pvc", "copper", "A1", 2, 1.5), 15.5); + assert.equal(capacity("pvc", "copper", "A2", 2, 1.5), 15.5); assert.equal(capacity("pvc", "copper", "A1", 2, 2.5), 19.5); assert.equal(capacity("pvc", "copper", "A1", 2, 16), 61); assert.equal(capacity("pvc", "copper", "A1", 2, 120), 210); - // B.52.2: B2 from 50 mm² (previously copied from B1) + // DIN table 3: B2 from 50 mm² (previously copied from B1) assert.equal(capacity("pvc", "copper", "B2", 2, 50), 133); assert.equal(capacity("pvc", "copper", "B2", 2, 120), 232); - // B.52.4 and D1/D2 + // Tables 3 and 4, including reference method D in conduits/ducts. assert.equal(capacity("pvc", "copper", "C", 3, 6), 41); - assert.equal(capacity("pvc", "copper", "D1", 2, 2.5), 29); - assert.equal(capacity("pvc", "copper", "D2", 3, 16), 70); - // Conflicting sources resolved to the lower value - assert.equal(capacity("pvc", "copper", "A1", 2, 240), 320); + assert.equal(capacity("pvc", "copper", "D", 2, 2.5), 29); + assert.equal(capacity("pvc", "copper", "A1", 2, 240), 321); assert.equal(capacity("pvc", "copper", "E", 3, 70), 196); }); - it("uses the aluminium and XLPE tables instead of flat factors", () => { - assert.equal(capacity("pvc", "aluminum", "A1", 2, 1.5), null); - assert.equal(capacity("pvc", "aluminum", "C", 3, 16), 59); - assert.equal(capacity("pvc", "aluminum", "D2", 2, 10), null); + it("uses aluminium only from the first DIN-tabulated size of 25 mm²", () => { + for (const insulation of ["pvc", "xlpe"] as const) { + for (const method of ["A1", "A2", "B1", "B2", "C", "D", "E"] as const) { + for (const cores of [2, 3] as const) { + for (const crossSection of CROSS_SECTIONS_MM2.filter((value) => value < 25)) { + assert.equal(capacity(insulation, "aluminum", method, cores, crossSection), null); + } + } + } + } + assert.equal(capacity("pvc", "aluminum", "C", 3, 25), 73); assert.equal(capacity("xlpe", "copper", "C", 2, 2.5), 33); assert.equal(capacity("xlpe", "aluminum", "E", 3, 25), 97); }); @@ -113,10 +119,15 @@ describe("calculateCableSizing", () => { const cold = calculateCableSizing({ ...BASE_INPUT, ambientTemperatureC: 5 }); assert.equal(cold.temperatureUsedC, 10); assert.equal(cold.temperatureFactor, 1.22); - const grouped = calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 10 }); + const exact = calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 10 }); + assert.equal(exact.groupingUsed, 10); + assert.equal(exact.groupingFactor, 0.48); + assert.equal(calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 14 }).groupingFactor, 0.43); + assert.equal(calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 18 }).groupingFactor, 0.39); + const grouped = calculateCableSizing({ ...BASE_INPUT, groupingCircuits: 11 }); assert.equal(grouped.groupingUsed, 12); assert.equal(grouped.groupingFactor, 0.45); - const alerts = buildCableSizingAlerts({ ...BASE_INPUT, groupingCircuits: 10 }, grouped); + const alerts = buildCableSizingAlerts({ ...BASE_INPUT, groupingCircuits: 11 }, grouped); assert.ok(alerts.some((alert) => alert.text.includes("12 Stromkreise gerundet"))); }); @@ -129,13 +140,15 @@ describe("calculateCableSizing", () => { ); }); - it("uses the ground tables for D1 (ducts) and D2 (direct)", () => { - const d1 = calculateCableSizing({ ...BASE_INPUT, layingMethod: "D1", ambientTemperatureC: 20, groupingCircuits: 10 }); - assert.equal(d1.groupingFactor, 0.49); - const d2 = calculateCableSizing({ ...BASE_INPUT, layingMethod: "D2", ambientTemperatureC: 20, groupingCircuits: 10 }); - assert.equal(d2.groupingUsed, 12); - assert.equal(d2.groupingFactor, 0.36); - assert.equal(calculateCableSizing({ ...BASE_INPUT, layingMethod: "D2", ambientTemperatureC: 30 }).temperatureFactor, 0.89); + it("limits grouping to the corrected DIN tables for D and E", () => { + const d = calculateCableSizing({ ...BASE_INPUT, layingMethod: "D", ambientTemperatureC: 20, groupingCircuits: 6 }); + assert.equal(d.groupingFactor, 0.6); + assert.equal(calculateCableSizing({ ...BASE_INPUT, layingMethod: "D", ambientTemperatureC: 20, groupingCircuits: 7 }).supported, false); + const e = calculateCableSizing({ ...BASE_INPUT, layingMethod: "E", groupingCircuits: 2 }); + assert.equal(e.supported, false); + assert.equal(e.unsupportedReason, "grouping"); + assert.ok(buildCableSizingAlerts({ ...BASE_INPUT, layingMethod: "E", groupingCircuits: 2 }, e)[0]?.text.includes("Kabelpritsche")); + assert.equal(calculateCableSizing({ ...BASE_INPUT, layingMethod: "D", ambientTemperatureC: 30 }).temperatureFactor, 0.89); }); it("refuses inputs outside the tables instead of assuming a factor of 1", () => { @@ -156,9 +169,11 @@ describe("calculateCableSizing", () => { lengthM: 5, conductorMaterial: "aluminum", }); - assert.equal(result.recommendedCrossSectionMm2, 2.5); - assert.equal(result.rows[0].ratedCurrentA, null); - assert.equal(result.rows[0].recommended, false); + assert.equal(result.recommendedCrossSectionMm2, 25); + for (const row of result.rows.filter((row) => row.crossSectionMm2 < 25)) { + assert.equal(row.ratedCurrentA, null); + assert.equal(row.recommended, false); + } }); it("checks gG fuses with I2 = 1.6 In and circuit-breakers with In ≤ Iz", () => { @@ -186,6 +201,23 @@ describe("calculateCableSizing", () => { assert.equal(single.harmonicReductionApplied, false); }); + it("does not recommend a cross-section above 33 % third harmonic without neutral current", () => { + const input = { ...BASE_INPUT, phase: 3 as const, voltage: 400, harmonicNeutralLoad: "over33Percent" as const }; + const result = calculateCableSizing(input); + assert.equal(result.supported, false); + assert.equal(result.unsupportedReason, "harmonics"); + assert.equal(result.recommendedCrossSectionMm2, null); + assert.equal(buildCableSizingAlerts(input, result)[0]?.kind, "critical"); + }); + + it("allows zero length and states that no voltage drop is applied", () => { + const input = { ...BASE_INPUT, lengthM: 0 }; + const result = calculateCableSizing(input); + assert.equal(result.supported, true); + assert.equal(result.voltageDropAtRecommendedPercent, 0); + assert.ok(buildCableSizingAlerts(input, result).some((alert) => alert.text.includes("kein Spannungsfall"))); + }); + it("raises single-phase circuits to the 2.5 mm² practical minimum", () => { const result = calculateCableSizing({ ...BASE_INPUT, @@ -203,7 +235,7 @@ describe("calculateCableSizing", () => { it("offers only tabulated temperatures", () => { assert.deepEqual(temperatureOptions("C", "pvc").at(-1), 60); assert.deepEqual(temperatureOptions("C", "xlpe").at(-1), 80); - assert.deepEqual(temperatureOptions("D1", "pvc")[2], 20); + assert.deepEqual(temperatureOptions("D", "pvc")[2], 20); }); }); @@ -219,6 +251,9 @@ describe("cable sizing request schema", () => { false ); assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, layingMethod: "F" }).success, false); + assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, layingMethod: "D1" }).success, false); + assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, layingMethod: "D2" }).success, false); + assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, layingMethod: "D" }).success, true); assert.equal(cableSizingRequestSchema.safeParse({ ...BASE_INPUT, mode: "current" }).success, false); }); }); From a6500e2b262219673303ad2b27a0d4405efd9bfc Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Sun, 27 Sep 2026 18:36:48 +0200 Subject: [PATCH 09/38] Add estimate row project device handoff --- AGENTS.md | 7 + docs/estimate-balance.md | 34 +++- src/app/globals.css | 9 +- .../grobbilanz/[balanceId]/page.tsx | 157 +++++++++++++++++- .../components/project-device-modal.tsx | 72 +++++++- .../estimate-balance-sheet.tsx | 33 +++- .../estimate-project-device-prefill.ts | 51 ++++++ tests/estimate-balance-frontend.test.ts | 50 ++++++ tests/project-version-history.test.ts | 42 ++++- 9 files changed, 434 insertions(+), 21 deletions(-) create mode 100644 src/frontend/estimate-balance/estimate-project-device-prefill.ts diff --git a/AGENTS.md b/AGENTS.md index e9db70a..eae68d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -663,6 +663,13 @@ for the early-phase power balance by DIN 276 cost group (see debounced (one Undo step per save), keeps invalid raw input local, and on a 409 reloads only if the balance itself changed; otherwise it re-saves with the new revision. `request()` throws `ApiRequestError` (status, code). +- A single estimate row can be copied explicitly through the existing + ProjectDevice dialog. The dialog is only a prefilled proposal; creation + happens after confirmation through `project-device.insert`, with the current + project revision and normal Undo/Redo. The copy stores no link back to the + estimate row, never places a circuit row automatically, and does not change + estimate, snapshot or transfer schemas. Area rows require manual quantity + and power because W/m² remains outside the ProjectDevice model. ## Persistence and Migration Rules diff --git a/docs/estimate-balance.md b/docs/estimate-balance.md index b8b675b..c68758d 100644 --- a/docs/estimate-balance.md +++ b/docs/estimate-balance.md @@ -9,7 +9,10 @@ Issue #7. Das Modul ist **nicht** mit der Stromkreisstruktur verknüpft. Es liest die Gerätezeilen nur für den Vergleich „geschätzt ↔ detailliert“ und schreibt -nichts in Stromkreislisten, Verteilungen oder Projektgeräte. +nichts automatisch in Stromkreislisten, Verteilungen oder Projektgeräte. Eine +ausdrückliche Einzelaktion kann die Werte einer Grobbilanz-Zeile als Vorschlag +in den bestehenden Projektgeräte-Dialog übernehmen; erst dessen Bestätigung +legt über `project-device.insert` ein unplatziertes Projektgerät an. ## Aufbau @@ -67,6 +70,35 @@ Zeilen ohne passende Kostengruppe erscheinen als „nicht zugeordnet“. Der Verteiler-GZF wird auf keiner Seite angewendet; ein fehlendes cos φ zählt als 1. Verglichen wird die AV-Leistung (kW) mit Differenz absolut und in %. +## Übernahme als Projektgerät + +Die Zeilenaktion „Als Projektgerät übernehmen“ ist eine einmalige, ausdrücklich +bestätigte Kopie. Vor dem Öffnen des Dialogs werden ausstehende Änderungen der +Grobbilanz gespeichert. Das Anlegen läuft anschließend mit der aktuellen +Projektrevision über den normalen Projektgeräte-Befehl und ist dadurch wie ein +manuell angelegtes Projektgerät rückgängig machbar. + +- Name und Anzeigename kommen aus dem Zeilennamen; Kostengruppe, GZF, cos φ und + Anmerkung werden vorgeschlagen. `fixed` und `socket` erscheinen als + „Festanschluss“ und „Steckdose“. +- W werden für Stückzeilen in kW umgerechnet. Die Projektgeräte-Anzahl ist 1, + weil das Projektgerät als Vorlage für eine spätere Gerätezeile dient; die + ursprüngliche Stückzahl bleibt im Herkunftshinweis sichtbar. +- Die Kategorie ist mangels Phaseninformation in der Grobbilanz mit + „1-phasig“ vorbelegt und muss im Dialog fachlich geprüft werden. +- Flächenzeilen dürfen übernommen werden. Anzahl und Leistung je Stück bleiben + leer und müssen manuell angegeben werden, da das Projektgerät noch keine + Einheit W/m² kennt (siehe Issue #20). +- SV wird nur im Herkunftshinweis gezeigt. Die tatsächliche Versorgungsart + gehört zur Verteilung. +- Gleichnamige vorhandene Projektgeräte erzeugen eine Warnung, sperren das + Anlegen aber nicht. + +Zwischen Grobbilanz-Zeile und Projektgerät wird keine Verbindung gespeichert. +Es gibt keine Stapelübernahme und keine automatische Platzierung in einer +Verteilung oder einem Stromkreis. Snapshot-, Transfer- und +Grobbilanz-Befehlsformate ändern sich dadurch nicht. + ## Befehle, Undo/Redo Alle Änderungen laufen über den bestehenden Projekt-Befehlsmechanismus mit diff --git a/src/app/globals.css b/src/app/globals.css index e5474b8..de46d37 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -2141,7 +2141,7 @@ button.structure-entry-main:focus-visible { .estimate-col-result { width: 4.6rem; } .estimate-col-sv { width: 3.2rem; } .estimate-col-remark { width: 9rem; } -.estimate-col-actions { width: 2.4rem; } +.estimate-col-actions { width: 4.5rem; } .estimate-cell-input, .estimate-cell-select { @@ -2286,6 +2286,13 @@ button.structure-entry-main:focus-visible { gap: 2px; } +.estimate-row-actions { + display: flex; + justify-content: center; + gap: 2px; + white-space: nowrap; +} + .estimate-group-title-row .estimate-actions-cell { width: auto; white-space: nowrap; diff --git a/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx index 584f5cf..933449d 100644 --- a/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx +++ b/src/app/projects/[projectId]/grobbilanz/[balanceId]/page.tsx @@ -14,11 +14,13 @@ import { } from "lucide-react"; import { ApiRequestError, + createProjectDevice, getEstimateBalance, getEstimateComparison, getProject, getProjectHistory, isRevisionConflictError, + listProjectDevices, redoProjectCommand, undoProjectCommand, updateEstimateBalance, @@ -26,11 +28,17 @@ import { import type { EstimateBalanceDto, EstimateComparisonDto, + CreateProjectDeviceInput, ProjectDto, + ProjectDeviceDto, ProjectHistoryStateDto, } from "../../../../../frontend/types"; -import type { EstimateGroupSnapshot } from "../../../../../shared/estimate-balance/estimate-balance"; +import type { + EstimateGroupSnapshot, + EstimateRowSnapshot, +} from "../../../../../shared/estimate-balance/estimate-balance"; import { GzfPickerModal } from "../../../../../frontend/components/gzf-picker-modal"; +import { ProjectDeviceModal } from "../../../../../frontend/components/project-device-modal"; import { addEstimateGroup, estimateBalanceFingerprint, @@ -41,7 +49,11 @@ import { updateEstimateRow, validateEstimateBalance, } from "../../../../../frontend/estimate-balance/estimate-balance-document"; -import { formatIsoDateGerman } from "../../../../../frontend/estimate-balance/estimate-balance-format"; +import { + formatGermanNumber, + formatIsoDateGerman, +} from "../../../../../frontend/estimate-balance/estimate-balance-format"; +import { createEstimateProjectDeviceInitialValues } from "../../../../../frontend/estimate-balance/estimate-project-device-prefill"; import { EstimateBalanceSheet, type EstimateBalanceUpdate, @@ -60,6 +72,10 @@ const CONFLICT_MESSAGE = "Die Bilanz wurde zwischenzeitlich geändert und neu ge type SaveStatus = "saved" | "pending" | "saving" | "error" | "invalid"; type GroupDialog = { group: EstimateGroupSnapshot | null }; +type ProjectDeviceDialog = { + group: EstimateGroupSnapshot; + row: EstimateRowSnapshot; +}; function errorMessage(error: unknown, fallback: string) { return error instanceof Error && error.message ? error.message : fallback; @@ -94,6 +110,11 @@ export default function EstimateBalanceEditorPage() { const [gzfTarget, setGzfTarget] = useState<{ groupId: string; rowId: string } | null>( null ); + const [projectDeviceDialog, setProjectDeviceDialog] = + useState(null); + const [projectDevices, setProjectDevices] = useState([]); + const [isPreparingProjectDevice, setIsPreparingProjectDevice] = useState(false); + const [isSavingProjectDevice, setIsSavingProjectDevice] = useState(false); // Refs carry the latest values into timers, unload handlers and chained // async saves without re-creating them. @@ -456,7 +477,77 @@ export default function EstimateBalanceEditorPage() { setGzfTarget(null); } - const isEditingDisabled = !draft || isHistoryBusy; + async function handleOpenProjectDevice(groupId: string, rowId: string) { + setError(null); + setNotice(null); + setIsPreparingProjectDevice(true); + try { + if (!(await saveNow())) { + setError( + "Die Grobbilanz muss zuerst fehlerfrei gespeichert werden, bevor ein Projektgerät angelegt werden kann." + ); + return; + } + const current = draftRef.current; + const group = current?.groups.find((entry) => entry.id === groupId); + const row = group?.rows.find((entry) => entry.id === rowId); + if (!group || !row) { + setError("Die gewählte Grobbilanz-Zeile ist nicht mehr vorhanden."); + return; + } + const existingDevices = await listProjectDevices(projectId); + setProjectDevices(existingDevices); + setProjectDeviceDialog({ group, row }); + } catch (err) { + setError( + errorMessage(err, "Der Projektgeräte-Dialog konnte nicht vorbereitet werden.") + ); + } finally { + setIsPreparingProjectDevice(false); + } + } + + async function handleCreateProjectDevice(input: CreateProjectDeviceInput) { + const revision = revisionRef.current; + if (!projectDeviceDialog || revision === null) return; + setError(null); + setIsSavingProjectDevice(true); + try { + if (!(await saveNow())) { + setError( + "Die Grobbilanz muss zuerst fehlerfrei gespeichert werden, bevor das Projektgerät angelegt werden kann." + ); + return; + } + const currentRevision = revisionRef.current; + if (currentRevision === null) return; + const result = await createProjectDevice(projectId, input, currentRevision); + revisionRef.current = result.history.currentRevision; + setHistory(result.history); + setProject((currentProject) => + currentProject + ? { ...currentProject, currentRevision: result.history.currentRevision } + : currentProject + ); + setProjectDevices((current) => [...current, result.projectDevice]); + setProjectDeviceDialog(null); + setNotice(`Projektgerät „${result.projectDevice.displayName}“ wurde angelegt.`); + } catch (err) { + if (isRevisionConflictError(err)) { + await reloadAll().catch(handleReloadError); + setError( + "Der Projektstand hat sich zwischenzeitlich geändert. Der aktuelle Stand wurde geladen; bitte das Projektgerät erneut speichern." + ); + } else { + setError(errorMessage(err, "Das Projektgerät konnte nicht angelegt werden.")); + } + } finally { + setIsSavingProjectDevice(false); + } + } + + const isEditingDisabled = + !draft || isHistoryBusy || isPreparingProjectDevice || isSavingProjectDevice; const invalidCount = invalidFieldKeys.size; const listHref = `/projects/${projectId}/grobbilanz`; @@ -623,6 +714,9 @@ export default function EstimateBalanceEditorPage() { onChange={handleChange} onEditGroup={(group) => setGroupDialog({ group })} onOpenGzfPicker={(groupId, rowId) => setGzfTarget({ groupId, rowId })} + onTakeOverRow={(groupId, rowId) => + void handleOpenProjectDevice(groupId, rowId) + } onValidityChange={handleValidityChange} threePhaseVoltageV={project.threePhaseVoltageV} /> @@ -692,10 +786,67 @@ export default function EstimateBalanceEditorPage() { {gzfTarget ? ( setGzfTarget(null)} onSelect={handleSelectGzf} /> ) : null} + {projectDeviceDialog ? ( + + } + existingDevices={projectDevices} + globalDevices={[]} + initialValues={createEstimateProjectDeviceInitialValues( + projectDeviceDialog.group, + projectDeviceDialog.row + )} + isSaving={isSavingProjectDevice} + onClose={() => setProjectDeviceDialog(null)} + onImportGlobal={async () => undefined} + onSave={handleCreateProjectDevice} + /> + ) : null} ); } +function EstimateProjectDeviceContext({ + balanceName, + group, + row, +}: { + balanceName: string; + group: EstimateGroupSnapshot; + row: EstimateRowSnapshot; +}) { + const originalUnit = row.unit === "area" ? "m²" : "St."; + const powerUnit = row.unit === "area" ? "W/m²" : "W"; + return ( + <> +
+ Herkunft: Stand „{balanceName}“, Kostengruppe{" "} + {group.costGroup || "ohne Nummer"}. +
+
+ Originalwerte: {formatGermanNumber(row.quantity, 0, 3)} {originalUnit} ×{" "} + {formatGermanNumber(row.powerPerUnitW, 0, 3)} {powerUnit}, GZF{" "} + {formatGermanNumber(row.simultaneityFactor, 0, 3)}, cos φ{" "} + {formatGermanNumber(row.cosPhi, 0, 3)}. +
+
+ {row.unit === "area" + ? "Das Projektgerät dient als Vorlage. Für Flächenwerte sind Anzahl und Leistung je Stück manuell einzutragen." + : "Das Projektgerät ist eine Vorlage mit Anzahl 1."}{" "} + Kategorie bitte prüfen. + {row.safetySupply + ? " SV ist nur ein Hinweis; die Versorgungsart wird an der Verteilung festgelegt." + : ""} +
+ + ); +} + function SaveStatusBadge({ error, invalidCount, diff --git a/src/frontend/components/project-device-modal.tsx b/src/frontend/components/project-device-modal.tsx index 27c24d0..0d95223 100644 --- a/src/frontend/components/project-device-modal.tsx +++ b/src/frontend/components/project-device-modal.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { FormEvent, useState } from "react"; +import React, { FormEvent, type ReactNode, useState } from "react"; import type { CreateProjectDeviceInput, GlobalDeviceDto, @@ -14,10 +14,20 @@ import { } from "../../shared/constants/circuit-group"; import { GzfPickerModal } from "./gzf-picker-modal"; +export type ProjectDeviceModalInitialValues = Omit< + Partial, + "quantity" | "powerPerUnit" +> & { + quantity?: number | null; + powerPerUnit?: number | null; +}; + interface ProjectDeviceModalProps { + context?: ReactNode; + existingDevices?: ReadonlyArray>; globalDevices: GlobalDeviceDto[]; initialDevice?: ProjectDeviceDto; - initialValues?: Partial; + initialValues?: ProjectDeviceModalInitialValues; isSaving: boolean; onClose: () => void; onImportGlobal: (globalDeviceId: string) => Promise; @@ -25,6 +35,8 @@ interface ProjectDeviceModalProps { } export function ProjectDeviceModal({ + context, + existingDevices = [], globalDevices, initialDevice, initialValues, @@ -36,6 +48,11 @@ export function ProjectDeviceModal({ const [values, setValues] = useState(() => toFormValues(initialDevice, initialValues)); const [selectedGlobalDeviceId, setSelectedGlobalDeviceId] = useState(""); const [isGzfPickerOpen, setIsGzfPickerOpen] = useState(false); + const hasDuplicateName = hasExistingProjectDeviceName( + values.name, + values.displayName, + existingDevices + ); function update(key: keyof typeof values, value: string) { setValues((current) => ({ ...current, [key]: value })); @@ -79,6 +96,17 @@ export function ProjectDeviceModal({ submitLabel={initialDevice ? "Änderungen speichern" : "Gerät anlegen"} title={initialDevice ? "Projektgerät bearbeiten" : "Projektgerät hinzufügen"} > + {context ? ( +
+ {context} +
+ ) : null} + {hasDuplicateName ? ( +
+ Ein Projektgerät mit gleichem internen Namen oder Anzeigenamen ist bereits vorhanden. + Das Anlegen bleibt möglich. +
+ ) : null} {!initialDevice && globalDevices.length > 0 ? (
- onChange((balance) => removeEstimateRow(balance, group.id, row.id))} - variant="danger" - > - +
+ onTakeOverRow(group.id, row.id)} + variant="primary" + > + + onChange((balance) => removeEstimateRow(balance, group.id, row.id))} + variant="danger" + > + +
Örtlichkeit Etage NetzartGespeist von GZF Aktionen
{formatBoardFeedingReference(board)} {board.simultaneityFactor.toLocaleString( "de-DE", @@ -1392,7 +1467,7 @@ export default function ProjectDetailPage() { {editingBoard ? ( setEditingBoard(null)} onSubmit={handleUpdateBoard} @@ -1479,6 +1554,91 @@ export default function ProjectDetailPage() { +
+
+ Logische Einspeisung +
+
+
+ + +
+
+ + +
+ {editingFeedingBoardId && !editingFeedingCircuitId ? ( +
+
+ Ohne speisenden Abgang wird die Hierarchie angezeigt, die + Leistung dieser Verteilung aber keinem Stromkreis zugerechnet. +
+
+ ) : null} + {selectedFeedingBoard?.supplyType && + editingBoardSupplyType !== selectedFeedingBoard.supplyType ? ( +
+
+ Die Netzarten weichen ab: {selectedFeedingBoard.supplyType} + {" → "}{editingBoardSupplyType}. Bitte Umschaltung und + Versorgungskonzept prüfen. +
+
+ ) : null} + {selectedFeedingCircuit && + selectedFeedingCircuit.section.category !== "three_phase" ? ( +
+
+ Der gewählte Abgang ist 1-phasig. Bitte prüfen, ob diese + Einspeisung für die Unterverteilung geeignet ist. +
+
+ ) : null} + {selectedFeedingCircuitUseCount > 0 ? ( +
+
+ Dieser Abgang speist bereits {selectedFeedingCircuitUseCount} + {selectedFeedingCircuitUseCount === 1 + ? " weitere Verteilung." + : " weitere Verteilungen."} +
+
+ ) : null} +
+
0) { + return Math.round(circuit.circuitCosPhi * 100) / 100; + } let activePowerKw = 0; let apparentPowerKva = 0; for (const row of circuit.deviceRows) { diff --git a/src/frontend/components/circuit-tree-editor.tsx b/src/frontend/components/circuit-tree-editor.tsx index e8a2f23..bac08ce 100644 --- a/src/frontend/components/circuit-tree-editor.tsx +++ b/src/frontend/components/circuit-tree-editor.tsx @@ -1,5 +1,6 @@ "use client"; +import Link from "next/link"; import { DragEvent, KeyboardEvent, useEffect, useMemo, useRef, useState } from "react"; import { ArrowDown, @@ -3293,6 +3294,23 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str threePhaseVoltageV={data.threePhaseVoltageV} /> ) : null} + {data.feedingReference ? ( +
+ Gespeist von{" "} + + {data.feedingReference.distributionBoardNumber ?? + data.feedingReference.distributionBoardName} + {data.feedingReference.circuitEquipmentIdentifier ?? ""} + + {data.feedingReference.circuitId + ? null + : " (speisender Stromkreis noch nicht festgelegt)"} +
+ ) : null}
- {row.circuit && row.rowType !== "deviceRow" ? ( + {row.circuit && + (row.rowType === "circuitCompact" || + row.rowType === "circuitSummary" || + row.rowType === "reserveCircuit") ? ( <> = { boardNumber: "z. B. UV 1.1", location: "z. B. Raum 003 Technik", - fedFrom: "z. B. HV 0.1 oder HAK / Zähleranlage", + fedFrom: "z. B. HAK, Zähleranlage, Trafo oder NEA", remark: "", }; @@ -98,8 +98,8 @@ export function DistributionBoardInfoCard({ )} {field === "fedFrom" ? (
- Vorerst Freitext. Die logische Verknüpfung mit dem - speisenden Verteiler folgt. + Für externe Einspeisungen oder ergänzende Hinweise. Eine + speisende Projektverteilung wird oben logisch verknüpft.
) : null}
diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 8a2dec4..572182b 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -494,6 +494,7 @@ export interface CircuitTreeDownstreamBoardLoadDto { export interface CircuitTreeFeedingReferenceDto { distributionBoardId: string; + circuitListId: string; distributionBoardName: string; distributionBoardNumber?: string; circuitId?: string; diff --git a/src/frontend/utils/circuit-grid-model.ts b/src/frontend/utils/circuit-grid-model.ts index ba4be98..faa4a11 100644 --- a/src/frontend/utils/circuit-grid-model.ts +++ b/src/frontend/utils/circuit-grid-model.ts @@ -44,6 +44,7 @@ export type RowType = | "circuitCompact" | "circuitSummary" | "deviceRow" + | "downstreamBoardLoad" | "reserveCircuit" | "placeholder" | "footerComponent"; @@ -614,6 +615,7 @@ export function getCellKind(rowType: RowType, key: CellKey): CellKind { return "readonly"; } if (rowType === "deviceRow") return deviceFieldKeys.has(key) ? "deviceField" : "readonly"; + if (rowType === "downstreamBoardLoad") return "readonly"; if (rowType === "circuitSummary") return circuitFieldKeys.has(key) ? "circuitField" : "readonly"; if (rowType === "reserveCircuit" || rowType === "circuitCompact") { if (deviceFieldKeys.has(key)) return "deviceField"; diff --git a/src/frontend/utils/circuit-grid-projection.ts b/src/frontend/utils/circuit-grid-projection.ts index fb2a846..a9b11de 100644 --- a/src/frontend/utils/circuit-grid-projection.ts +++ b/src/frontend/utils/circuit-grid-projection.ts @@ -2,6 +2,7 @@ import type { CircuitTreeCircuitDto, CircuitTreeComponentDto, CircuitTreeDeviceRowDto, + CircuitTreeDownstreamBoardLoadDto, CircuitTreeSectionDto, } from "../types.js"; import { buildCircuitStructureProjection } from "./circuit-structure-projection"; @@ -45,6 +46,7 @@ export interface VisibleGridRow { circuit?: CircuitTreeCircuitDto; device?: CircuitTreeDeviceRowDto; component?: CircuitTreeComponentDto; + downstreamBoardLoad?: CircuitTreeDownstreamBoardLoadDto; cells: VisibleGridCell[]; } @@ -126,13 +128,16 @@ function makeVisibleGridRow( rowType: RowType, sectionId: string, circuit?: CircuitTreeCircuitDto, - device?: CircuitTreeDeviceRowDto + device?: CircuitTreeDeviceRowDto, + downstreamBoardLoad?: CircuitTreeDownstreamBoardLoadDto ): VisibleGridRow { const rowKey = rowType === "placeholder" ? `placeholder:${sectionId}` : rowType === "deviceRow" && device ? `device:${device.id}` + : rowType === "downstreamBoardLoad" && downstreamBoardLoad + ? `downstream-board:${circuit?.id}:${downstreamBoardLoad.distributionBoardId}` : `${rowType}:${circuit?.id ?? sectionId}`; const cells = allColumns.map((column): VisibleGridCell => { @@ -140,7 +145,17 @@ function makeVisibleGridRow( const editable = kind === "circuitField" || kind === "deviceField"; let value: GridValue; - if (rowType === "placeholder") { + if (rowType === "downstreamBoardLoad" && downstreamBoardLoad) { + value = column.key === "displayName" + ? `Unterverteilung ${downstreamBoardLoad.boardNumber ?? downstreamBoardLoad.name}` + : column.key === "rowTotalPower" + ? downstreamBoardLoad.activePowerKw + : column.key === "cosPhi" + ? downstreamBoardLoad.cosPhi + : column.key === "remark" + ? "Automatisch aus der verknüpften Verteilung" + : undefined; + } else if (rowType === "placeholder") { value = column.key === "equipmentIdentifier" ? "-frei-" : undefined; } else if (kind === "deviceField" && device) { value = getDeviceValue(device, column.key); @@ -166,7 +181,15 @@ function makeVisibleGridRow( return { cellKey: column.key, editable, kind, value }; }); - return { rowKey, rowType, sectionId, circuit, device, cells }; + return { + rowKey, + rowType, + sectionId, + circuit, + device, + downstreamBoardLoad, + cells, + }; } export function buildVisibleGridRowsWithStructure( @@ -221,15 +244,27 @@ export function buildVisibleGridRowsWithStructure( } if (row.rowType === "circuitBlock") { const circuit = row.circuit; - if (circuit.deviceRows.length === 0) { + const downstreamLoads = circuit.downstreamBoardLoads ?? []; + if (circuit.deviceRows.length === 0 && downstreamLoads.length === 0) { rows.push(makeVisibleGridRow("reserveCircuit", section.id, circuit)); - } else if (circuit.deviceRows.length === 1) { + } else if (circuit.deviceRows.length === 1 && downstreamLoads.length === 0) { rows.push(makeVisibleGridRow("circuitCompact", section.id, circuit, circuit.deviceRows[0])); } else { rows.push(makeVisibleGridRow("circuitSummary", section.id, circuit)); for (const device of circuit.deviceRows) { rows.push(makeVisibleGridRow("deviceRow", section.id, circuit, device)); } + for (const load of downstreamLoads) { + rows.push( + makeVisibleGridRow( + "downstreamBoardLoad", + section.id, + circuit, + undefined, + load + ) + ); + } } continue; } diff --git a/src/server/controllers/circuit-tree.controller.ts b/src/server/controllers/circuit-tree.controller.ts index 22b4a73..17ac134 100644 --- a/src/server/controllers/circuit-tree.controller.ts +++ b/src/server/controllers/circuit-tree.controller.ts @@ -104,6 +104,9 @@ export async function buildProjectCircuitTrees( const boardById = new Map(boards.map((board) => [board.id, board])); const listById = new Map(lists.map((list) => [list.id, list])); + const listByBoardId = new Map( + lists.map((list) => [list.distributionBoardId, list]) + ); const sectionById = new Map(sections.map((section) => [section.id, section])); const circuitById = new Map(circuits.map((circuit) => [circuit.id, circuit])); const rowsByCircuitId = groupBy(rows, (row) => row.circuitId); @@ -158,6 +161,7 @@ export async function buildProjectCircuitTrees( feedingReference: resolveFeedingReference( board, boardById, + listByBoardId, circuitById, sectionById ), @@ -252,7 +256,9 @@ export async function buildProjectCircuitTrees( voltage: circuit.voltage ?? undefined, controlRequirement: circuit.controlRequirement ?? undefined, status: circuit.status ?? undefined, - isReserve: Boolean(circuit.isReserve), + isReserve: + Boolean(circuit.isReserve) && + circuitLoad.downstreamBoards.length === 0, remark: circuit.remark ?? undefined, circuitTotalPower: circuitLoad.activePowerKw, circuitApparentPower: circuitLoad.apparentPowerKva, @@ -292,17 +298,21 @@ export async function buildProjectCircuitTrees( function resolveFeedingReference( board: Awaited>[number], boardById: Map>[number]>, + listByBoardId: Map>[number]>, circuitById: Map>[number]>, sectionById: Map>[number]> ) { if (board.feedingDistributionBoardId === null) return undefined; const feedingBoard = boardById.get(board.feedingDistributionBoardId); if (!feedingBoard) throw new Error("Feeding distribution board is missing."); + const feedingList = listByBoardId.get(feedingBoard.id); + if (!feedingList) throw new Error("Feeding circuit list is missing."); const feedingCircuit = board.feedingCircuitId === null ? undefined : circuitById.get(board.feedingCircuitId); return { distributionBoardId: feedingBoard.id, + circuitListId: feedingList.id, distributionBoardName: feedingBoard.name, distributionBoardNumber: feedingBoard.boardNumber ?? undefined, circuitId: feedingCircuit?.id, diff --git a/tests/cable-sizing-calculation.test.ts b/tests/cable-sizing-calculation.test.ts index 39cfbb1..53d81a1 100644 --- a/tests/cable-sizing-calculation.test.ts +++ b/tests/cable-sizing-calculation.test.ts @@ -267,6 +267,15 @@ describe("cable sizing defaults from the circuit", () => { sortOrder: 1, isReserve: rows.length === 0, circuitTotalPower: rows.reduce((sum, row) => sum + row.power, 0), + circuitApparentPower: rows.reduce( + (sum, row) => sum + row.power / (row.cosPhi ?? 1), + 0 + ), + circuitCosPhi: rows.length + ? rows.reduce((sum, row) => sum + row.power, 0) / + rows.reduce((sum, row) => sum + row.power / (row.cosPhi ?? 1), 0) + : 1, + downstreamBoardLoads: [], deviceRows: rows.map((row, index) => ({ id: `row-${index}`, sortOrder: index, @@ -288,6 +297,19 @@ describe("cable sizing defaults from the circuit", () => { assert.equal(deriveCircuitCosPhi(circuit([])), 1); }); + it("uses the projected cos φ including downstream boards", () => { + const feeder = circuit([{ power: 1, cosPhi: 1 }]); + feeder.circuitCosPhi = 0.67; + feeder.downstreamBoardLoads = [{ + distributionBoardId: "uv-2", + name: "UV 2", + activePowerKw: 3, + apparentPowerKva: 5, + cosPhi: 0.6, + }]; + assert.equal(deriveCircuitCosPhi(feeder), 0.67); + }); + it("derives the phase from the group category or three-phase rows", () => { assert.equal(deriveCircuitPhase(circuit([{ power: 1, phaseType: "single_phase" }]), "single_phase"), 1); assert.equal(deriveCircuitPhase(circuit([{ power: 1, phaseType: "three_phase" }]), "single_phase"), 3); diff --git a/tests/circuit-grid-projection.test.ts b/tests/circuit-grid-projection.test.ts index 952e3d6..1a16913 100644 --- a/tests/circuit-grid-projection.test.ts +++ b/tests/circuit-grid-projection.test.ts @@ -47,7 +47,10 @@ function makeCircuit( sortOrder, isReserve: deviceRows.length === 0, circuitTotalPower: deviceRows.reduce((total, row) => total + row.rowTotalPower, 0), + circuitApparentPower: deviceRows.reduce((total, row) => total + row.rowTotalPower, 0), + circuitCosPhi: 1, deviceRows, + downstreamBoardLoads: [], }; } @@ -176,6 +179,44 @@ describe("circuit grid projection", () => { ); }); + it("renders linked downstream boards as separate read-only rows", () => { + const feeder = { + ...reserveCircuit, + isReserve: false, + circuitTotalPower: 4, + circuitApparentPower: 5, + circuitCosPhi: 0.8, + downstreamBoardLoads: [{ + distributionBoardId: "board-child", + name: "Unterverteilung", + boardNumber: "UV-02", + activePowerKw: 4, + apparentPowerKva: 5, + cosPhi: 0.8, + }], + }; + const rows = buildVisibleGridRowsWithStructure( + [{ ...sections[0], circuits: [feeder] }], + { headerComponents: [], footerComponents: [] } + ); + assert.deepEqual(rows.map((row) => row.rowType), [ + "section", + "circuitSummary", + "downstreamBoardLoad", + "placeholder", + ]); + const loadRow = rows[2]; + assert.equal( + loadRow.cells.find((cell) => cell.cellKey === "displayName")?.value, + "Unterverteilung UV-02" + ); + assert.equal( + loadRow.cells.find((cell) => cell.cellKey === "rowTotalPower")?.value, + 4 + ); + assert.equal(loadRow.cells.every((cell) => !cell.editable), true); + }); + it("shows circuit protection once on each visible circuit row", () => { const protectedSections = sections.map((section) => ({ ...section, From c56cfb30ada12f7ab0801c2bfbb540925573d80c Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Mon, 28 Sep 2026 19:51:47 +0200 Subject: [PATCH 16/38] Add login-required user management (admin/user roles, Config->Benutzer) No self-signup: admins create every account in Config -> Benutzer with a typed start password; a forced password change gates first use. Session- cookie auth protects all /api/* routes; /api/users additionally requires the admin role. See docs/authentication.md. Co-Authored-By: Claude Sonnet 5 --- AGENTS.md | 11 + compose.dev.yaml | 6 +- compose.yaml | 11 +- docs/README.md | 2 + docs/authentication.md | 61 + src/app/config/benutzer/page.tsx | 325 ++ src/app/config/konto/page.tsx | 103 + src/app/config/layout.tsx | 51 + src/app/config/page.tsx | 5 + src/app/globals.css | 113 + src/app/layout.tsx | 8 +- src/db/migrations/0012_lively_turbo.sql | 13 + src/db/migrations/meta/0012_snapshot.json | 3017 +++++++++++++++++ src/db/migrations/meta/_journal.json | 7 + src/db/repositories/user.repository.ts | 87 + src/db/schema/users.ts | 27 + src/domain/services/user.service.ts | 104 + src/frontend/components/AuthProvider.tsx | 61 + src/frontend/components/LoginGate.tsx | 179 + src/frontend/components/Sidebar.tsx | 25 + src/frontend/utils/auth-api.ts | 86 + src/server/auth/auth-config.ts | 44 + src/server/auth/auth.middleware.ts | 111 + src/server/auth/cookie.ts | 15 + src/server/auth/password.ts | 63 + src/server/auth/sessions.ts | 55 + .../composition/application-repositories.ts | 2 + src/server/composition/auth.ts | 8 + src/server/controllers/auth.controller.ts | 88 + src/server/controllers/user.controller.ts | 103 + src/server/index.ts | 88 +- src/server/routes/auth.routes.ts | 16 + src/server/routes/user.routes.ts | 16 + src/shared/constants/user-roles.ts | 7 + src/shared/validation/auth.schemas.ts | 15 + src/shared/validation/user.schemas.ts | 33 + 36 files changed, 4928 insertions(+), 38 deletions(-) create mode 100644 docs/authentication.md create mode 100644 src/app/config/benutzer/page.tsx create mode 100644 src/app/config/konto/page.tsx create mode 100644 src/app/config/layout.tsx create mode 100644 src/app/config/page.tsx create mode 100644 src/db/migrations/0012_lively_turbo.sql create mode 100644 src/db/migrations/meta/0012_snapshot.json create mode 100644 src/db/repositories/user.repository.ts create mode 100644 src/db/schema/users.ts create mode 100644 src/domain/services/user.service.ts create mode 100644 src/frontend/components/AuthProvider.tsx create mode 100644 src/frontend/components/LoginGate.tsx create mode 100644 src/frontend/utils/auth-api.ts create mode 100644 src/server/auth/auth-config.ts create mode 100644 src/server/auth/auth.middleware.ts create mode 100644 src/server/auth/cookie.ts create mode 100644 src/server/auth/password.ts create mode 100644 src/server/auth/sessions.ts create mode 100644 src/server/composition/auth.ts create mode 100644 src/server/controllers/auth.controller.ts create mode 100644 src/server/controllers/user.controller.ts create mode 100644 src/server/routes/auth.routes.ts create mode 100644 src/server/routes/user.routes.ts create mode 100644 src/shared/constants/user-roles.ts create mode 100644 src/shared/validation/auth.schemas.ts create mode 100644 src/shared/validation/user.schemas.ts diff --git a/AGENTS.md b/AGENTS.md index 8312d55..5c70f07 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,13 @@ It must support circuits, device rows, project devices, drag-and-drop restructur - General Circuit, CircuitDeviceRow, CircuitList and DistributionBoard repositories expose only active reads. Runtime writes belong in typed command repositories; direct integration fixtures belong under `tests/support`. +- Authentication: session-cookie login with two fixed roles (`admin`, `user`), + no self-signup. `src/server/auth/*` (password hashing, sessions, Express + middleware), `src/domain/services/user.service.ts`, + `src/db/repositories/user.repository.ts`. Every `/api/*` route requires a + signed-in user (`src/server/index.ts`); `/api/users/*` additionally + requires `admin`. Frontend gate: `AuthProvider` + `LoginGate` + (`src/app/layout.tsx`). See `docs/authentication.md` for the full picture. The supported runtime model is Circuit-First. The former Consumer UI, API, tables and upgrade tooling are removed; do not reintroduce them. @@ -704,6 +711,10 @@ for the early-phase power balance by DIN 276 cost group (see - logical feed link between distribution boards (`fedFrom` stays free text until the project owner decides whether it references a board, a feeding circuit or both) and the resulting hierarchical power summation +- configurable role/rights matrix instead of the fixed `admin`/`user` roles +- account lockout after failed login attempts +- email/one-time-link password provisioning, OIDC/Entra login +- linking user accounts to a personnel/employee master table Do not implement these while working on an unrelated phase. diff --git a/compose.dev.yaml b/compose.dev.yaml index b9c64b4..2c362bc 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -35,8 +35,10 @@ services: PORT: "3000" CHOKIDAR_USEPOLLING: "true" LOG_LEVEL: "${LOG_LEVEL:-debug}" - # Nur auf dem Loopback: nichts davon ist authentifiziert, die API darf - # nicht aus dem LAN erreichbar sein. + AUTH_BOOTSTRAP_USERNAME: "${AUTH_BOOTSTRAP_USERNAME:-}" + AUTH_BOOTSTRAP_PASSWORT: "${AUTH_BOOTSTRAP_PASSWORT:-}" + AUTH_SESSION_HOURS: "${AUTH_SESSION_HOURS:-12}" + # Nur auf dem Loopback: die API darf nicht aus dem LAN erreichbar sein. ports: - "127.0.0.1:3000:3000" # Kein memswap_limit wie im Server-Stack: beim Entwickeln ist Swap als diff --git a/compose.yaml b/compose.yaml index 3438f90..bab8c3d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -45,8 +45,15 @@ services: NODE_ENV: production PORT: "3000" LOG_LEVEL: "${LOG_LEVEL:-info}" - # Nicht auf dem Host veroeffentlicht: die API hat keine Authentifizierung - # und wird ueber den Next.js-Rewrite im Web-Dienst erreicht. + # AUTH_BOOTSTRAP_* legen nur den allerersten Admin an (solange die + # users-Tabelle leer ist) und gehoeren in eine lokale, nicht versionierte + # .env - siehe docs/AUTH.md. + AUTH_BOOTSTRAP_USERNAME: "${AUTH_BOOTSTRAP_USERNAME:-}" + AUTH_BOOTSTRAP_PASSWORT: "${AUTH_BOOTSTRAP_PASSWORT:-}" + AUTH_SESSION_HOURS: "${AUTH_SESSION_HOURS:-12}" + COOKIE_SECURE: "${COOKIE_SECURE:-false}" + # Nicht auf dem Host veroeffentlicht: die API wird ueber den + # Next.js-Rewrite im Web-Dienst erreicht. expose: - "3000" # Harte Obergrenze statt unbegrenztem Wachstum. memswap_limit == mem_limit diff --git a/docs/README.md b/docs/README.md index 01b5588..3569b42 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,6 +23,8 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we bewusst noch nicht implementierte oder begrenzte Funktionen - [Leitungsberechnung](cable-sizing-module.md) – optionales Rechenmodul, Rechenweg, Datenbasis und Prüfnachweis der Tabellen +- [Anmeldung und Benutzerverwaltung](authentication.md) – Rollen, Ablauf beim + Anlegen eines Zugangs, Sessions, Bootstrap-Admin ## Entwicklung und Betrieb diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 0000000..3d197cf --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,61 @@ +# Anmeldung und Benutzerverwaltung + +Die Leistungsbilanz verlangt eine Anmeldung. Es gibt kein Self-Signup: jeder +Zugang wird von einem Administrator über **Config → Benutzer** angelegt. + +## Rollen + +Es gibt genau zwei Rollen (`src/shared/constants/user-roles.ts`): + +- **admin** – wie `user`, zusätzlich Zugriff auf den Config-Bereich + (Benutzerverwaltung, eigenes Konto) +- **user** – volle Nutzung der Leistungsbilanz (Projekte, Stromkreislisten, + Grobbilanz, …), kein Zugriff auf Config + +Es gibt (bewusst, siehe unten) keine konfigurierbare Rechte-Matrix und keine +Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. + +## Ablauf beim Anlegen eines Zugangs + +1. Ein Administrator öffnet Config → Benutzer und legt einen neuen Zugang mit + Anmeldename, Name, Rolle und einem **Startpasswort** an, das er selbst + eintippt. +2. Der Zugang startet mit `mustChangePassword = true`. +3. Beim ersten Anmelden zeigt die Oberfläche statt der App ein Formular, das + ein eigenes Passwort verlangt, bevor es weitergeht. +4. "Passwort zurücksetzen" (ebenfalls in Config → Benutzer) setzt ein neues + Startpasswort und `mustChangePassword` wieder auf `true` – z. B. wenn + jemand sein Passwort vergessen hat. + +## Technischer Aufbau + +- **Datenmodell:** Tabelle `users` (`src/db/schema/users.ts`) – + `username`, `passwordHash` (scrypt, `src/server/auth/password.ts`), `name`, + `role`, `active`, `mustChangePassword`. +- **Sessions:** In-Memory-Store (`src/server/auth/sessions.ts`), Cookie + `lb_session`, sliding expiry (`AUTH_SESSION_HOURS`, Standard 12h). Ein + Neustart der API beendet alle Sessions – für einen Single-Container-Dienst + ein akzeptabler Kompromiss gegenüber einer persistierten Session-Tabelle. +- **Middleware:** `src/server/auth/auth.middleware.ts` schützt `/api/*` + (außer `/api/auth/login`, `/api/auth/status`, `/api/auth/logout`) und + erzwingt den Passwortwechsel, solange `mustChangePassword` gesetzt ist. + `/api/users/*` verlangt zusätzlich die Rolle `admin`. +- **Frontend:** `AuthProvider` lädt `/api/auth/me`; `LoginGate` + (`src/app/layout.tsx`) zeigt Login- bzw. Passwortformular, solange nicht + angemeldet bzw. `mustChangePassword` gesetzt ist, sonst die App. + +## Bootstrap-Admin + +`AUTH_BOOTSTRAP_USERNAME` / `AUTH_BOOTSTRAP_PASSWORT` (Env-Variablen, siehe +`compose.yaml`) legen beim ersten Start einen Admin an – **nur falls die +`users`-Tabelle noch komplett leer ist**. Danach werden diese Variablen +ignoriert; jeder weitere Zugang entsteht über Config → Benutzer. Die Werte +gehören in eine lokale, nicht versionierte `.env` auf dem Deploy-Host, nicht +in `compose.yaml` selbst. + +## Bewusst nicht umgesetzt (Stand jetzt) + +- Konfigurierbare Rechte-Matrix statt fixer `admin`/`user`-Rollen +- Konten-Sperre nach Fehlversuchen +- E-Mail-/Einmal-Link-Passwortvergabe, OIDC/Entra-Anmeldung +- Verknüpfung von Zugängen mit einer Mitarbeiter-Stammdatentabelle diff --git a/src/app/config/benutzer/page.tsx b/src/app/config/benutzer/page.tsx new file mode 100644 index 0000000..134890d --- /dev/null +++ b/src/app/config/benutzer/page.tsx @@ -0,0 +1,325 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { userApi, type UserDto, type UserRole } from "../../../frontend/utils/auth-api"; +import { useAuth } from "../../../frontend/components/AuthProvider"; +import { USER_ROLES, USER_ROLE_LABEL } from "../../../shared/constants/user-roles"; + +const zeitpunkt = new Intl.DateTimeFormat("de-DE", { + dateStyle: "short", + timeStyle: "short", +}); + +export default function BenutzerPage() { + const { user: currentUser } = useAuth(); + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [busyUserId, setBusyUserId] = useState(null); + const [resetPasswordFor, setResetPasswordFor] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const rows = await userApi.list(); + setUsers(rows); + setError(null); + } catch (err) { + setError(err instanceof Error ? err.message : "Benutzer konnten nicht geladen werden."); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void load(); + }, [load]); + + async function withBusy(userId: string, action: () => Promise) { + setBusyUserId(userId); + setError(null); + try { + await action(); + } catch (err) { + setError(err instanceof Error ? err.message : "Aktion fehlgeschlagen."); + } finally { + setBusyUserId(null); + } + } + + async function changeRole(item: UserDto, role: UserRole) { + await withBusy(item.id, async () => { + const updated = await userApi.update(item.id, { role }); + setUsers((list) => list.map((row) => (row.id === updated.id ? updated : row))); + }); + } + + async function toggleActive(item: UserDto) { + await withBusy(item.id, async () => { + const updated = await userApi.update(item.id, { active: !item.active }); + setUsers((list) => list.map((row) => (row.id === updated.id ? updated : row))); + }); + } + + return ( +
+
+

+ Benutzer +

+
+

+ Es gibt kein Self-Signup: Jeder Zugang wird hier bewusst von einem + Administrator angelegt. Das Startpasswort wird direkt eingetragen; die + Person muss es beim ersten Anmelden durch ein eigenes ersetzen. +

+ + { + setUsers((list) => [...list, created]); + }} + /> + + {error &&

{error}

} + {loading &&

Lädt…

} + + {!loading && users.length > 0 && ( + + + + + + + + + + + + + + {users.map((item) => { + const isSelf = item.id === currentUser?.id; + const busy = busyUserId === item.id; + return ( + + + + + + + + + + ); + })} + +
NameAnmeldenameRolleAktivStatusAngelegtAktionen
{item.name}{item.username} + + + void toggleActive(item)} + /> + {item.mustChangePassword ? "Muss Passwort setzen" : "In Ordnung"}{zeitpunkt.format(new Date(item.createdAt))} + +
+ )} + + {!loading && users.length === 0 &&

Noch keine Benutzer angelegt.

} + + {resetPasswordFor && ( + setResetPasswordFor(null)} + onDone={(updated) => { + setUsers((list) => list.map((row) => (row.id === updated.id ? updated : row))); + setResetPasswordFor(null); + }} + /> + )} +
+ ); +} + +function NeuerBenutzerFormular({ onCreated }: { onCreated: (created: UserDto) => void }) { + const [username, setUsername] = useState(""); + const [name, setName] = useState(""); + const [role, setRole] = useState("user"); + const [initialPassword, setInitialPassword] = useState(""); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + setSubmitting(true); + setError(null); + try { + const created = await userApi.create({ username, name, role, initialPassword }); + onCreated(created); + setUsername(""); + setName(""); + setRole("user"); + setInitialPassword(""); + } catch (err) { + setError(err instanceof Error ? err.message : "Benutzer konnte nicht angelegt werden."); + } finally { + setSubmitting(false); + } + } + + return ( +
+
+ + setUsername(event.target.value)} + required + /> +
+
+ + setName(event.target.value)} + required + /> +
+
+ + +
+
+ + setInitialPassword(event.target.value)} + minLength={8} + required + /> +
+
+ +
+ {error && ( +
+

{error}

+
+ )} +
+ ); +} + +function PasswortZuruecksetzenDialog({ + item, + onClose, + onDone, +}: { + item: UserDto; + onClose: () => void; + onDone: (updated: UserDto) => void; +}) { + const [newPassword, setNewPassword] = useState(""); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + setSubmitting(true); + setError(null); + try { + const updated = await userApi.resetPassword(item.id, newPassword); + onDone(updated); + } catch (err) { + setError(err instanceof Error ? err.message : "Passwort konnte nicht zurückgesetzt werden."); + } finally { + setSubmitting(false); + } + } + + return ( +
+
+

Passwort zurücksetzen für {item.name}

+
+ + setNewPassword(event.target.value)} + minLength={8} + autoFocus + required + /> +
+ {error &&

{error}

} +
+ + +
+
+
+ ); +} diff --git a/src/app/config/konto/page.tsx b/src/app/config/konto/page.tsx new file mode 100644 index 0000000..2b58ee7 --- /dev/null +++ b/src/app/config/konto/page.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useState } from "react"; +import { authApi } from "../../../frontend/utils/auth-api"; +import { useAuth } from "../../../frontend/components/AuthProvider"; +import { USER_ROLE_LABEL } from "../../../shared/constants/user-roles"; + +export default function KontoPage() { + const { user } = useAuth(); + const [currentPassword, setCurrentPassword] = useState(""); + const [newPassword, setNewPassword] = useState(""); + const [newPasswordRepeat, setNewPasswordRepeat] = useState(""); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(false); + const [submitting, setSubmitting] = useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + if (newPassword !== newPasswordRepeat) { + setError("Die beiden neuen Passwörter stimmen nicht überein."); + return; + } + setSubmitting(true); + setError(null); + setSuccess(false); + try { + await authApi.changePassword(currentPassword, newPassword); + setCurrentPassword(""); + setNewPassword(""); + setNewPasswordRepeat(""); + setSuccess(true); + } catch (err) { + setError(err instanceof Error ? err.message : "Passwort konnte nicht geändert werden."); + } finally { + setSubmitting(false); + } + } + + return ( +
+

Konto

+ {user && ( +

+ Angemeldet als {user.name} ({user.username}) ·{" "} + {USER_ROLE_LABEL[user.role]} +

+ )} + +

Passwort ändern

+
+
+ + setCurrentPassword(event.target.value)} + autoComplete="current-password" + required + /> +
+
+ + setNewPassword(event.target.value)} + autoComplete="new-password" + minLength={8} + required + /> +
+
+ + setNewPasswordRepeat(event.target.value)} + autoComplete="new-password" + minLength={8} + required + /> +
+ {error &&

{error}

} + {success &&

Passwort wurde geändert.

} + +
+
+ ); +} diff --git a/src/app/config/layout.tsx b/src/app/config/layout.tsx new file mode 100644 index 0000000..1356d78 --- /dev/null +++ b/src/app/config/layout.tsx @@ -0,0 +1,51 @@ +"use client"; + +import Link from "next/link"; +import { usePathname, useRouter } from "next/navigation"; +import { useEffect } from "react"; +import { useAuth } from "../../frontend/components/AuthProvider"; + +const CONFIG_TABS = [ + { href: "/config/benutzer", label: "Benutzer" }, + { href: "/config/konto", label: "Konto" }, +] as const; + +export default function ConfigLayout({ children }: { children: React.ReactNode }) { + const pathname = usePathname(); + const router = useRouter(); + const { status, isAdmin } = useAuth(); + + useEffect(() => { + // LoginGate already guarantees a signed-in user with a set password by + // the time this layout renders; only the role still needs checking. + if (status === "signed-in" && !isAdmin) { + router.replace("/"); + } + }, [status, isAdmin, router]); + + if (status !== "signed-in" || !isAdmin) { + return null; + } + + return ( +
+
+

Config

+
+ + + + {children} +
+ ); +} diff --git a/src/app/config/page.tsx b/src/app/config/page.tsx new file mode 100644 index 0000000..7897dc7 --- /dev/null +++ b/src/app/config/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function ConfigPage() { + redirect("/config/benutzer"); +} diff --git a/src/app/globals.css b/src/app/globals.css index de46d37..f670173 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -2716,3 +2716,116 @@ button.structure-entry-main:focus-visible { justify-content: center; } } + +/* ── Anmeldung (Sidebar-Config-Link, Identität, Login-Gate) ─────────── */ + +.sidebar-nav-bottom { + flex: 0 0 auto; + border-top: 1px solid rgba(255, 255, 255, 0.12); +} + +.sidebar-identity { + display: flex; + flex-direction: column; + gap: 1px; + padding: 8px 14px 10px; +} + +.sidebar-identity-label { + font-size: 0.66rem; + letter-spacing: 0.08em; + text-transform: uppercase; + color: rgba(199, 214, 224, 0.7); +} + +.sidebar-identity-name { + font-size: 0.88rem; + font-weight: 600; + color: #fff; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sidebar-logout { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + margin-top: 8px; + padding: 8px 14px; + border-radius: 8px; + color: #c7d6e0; + font-size: 0.85rem; + font-weight: 500; + border: 1px solid rgba(255, 255, 255, 0.16); + background: transparent; + width: 100%; + cursor: pointer; +} + +.sidebar-logout:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.sidebar-collapsed .sidebar-identity { + display: none; +} + +.login-gate-screen { + min-height: 100vh; + display: flex; + align-items: center; + justify-content: center; + padding: var(--space-md); + background: linear-gradient( + 160deg, + var(--color-primary-deep) 0%, + var(--color-primary-dark) 45%, + var(--color-primary) 100% + ); +} + +.login-gate-card { + width: 100%; + max-width: 360px; + padding: 28px 26px; +} + +.config-tabs { + display: flex; + gap: 4px; + border-bottom: 1px solid var(--color-border, rgba(0, 0, 0, 0.12)); + margin-bottom: var(--space-md); +} + +.config-tab { + padding: 8px 16px; + border-radius: 6px 6px 0 0; + color: inherit; + text-decoration: none; + font-size: 0.9rem; + font-weight: 500; + opacity: 0.7; +} + +.config-tab:hover { + opacity: 1; + text-decoration: none; +} + +.config-tab.active { + opacity: 1; + box-shadow: inset 0 -2px 0 var(--color-primary); +} + +.modal-backdrop-inline { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.45); + display: flex; + align-items: center; + justify-content: center; + z-index: 1050; +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index cd2407b..c830c99 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -3,6 +3,8 @@ import Script from "next/script"; import "bootstrap/dist/css/bootstrap.min.css"; import "./globals.css"; import { AppShell } from "../frontend/components/AppShell"; +import { AuthProvider } from "../frontend/components/AuthProvider"; +import { LoginGate } from "../frontend/components/LoginGate"; export const metadata: Metadata = { title: "Leistungsbilanz", @@ -36,7 +38,11 @@ export default function RootLayout({ children }: Readonly<{ children: React.Reac - {children} + + + {children} + + ); diff --git a/src/db/migrations/0012_lively_turbo.sql b/src/db/migrations/0012_lively_turbo.sql new file mode 100644 index 0000000..6c07010 --- /dev/null +++ b/src/db/migrations/0012_lively_turbo.sql @@ -0,0 +1,13 @@ +CREATE TABLE `users` ( + `id` text PRIMARY KEY NOT NULL, + `username` text NOT NULL, + `password_hash` text NOT NULL, + `name` text NOT NULL, + `role` text DEFAULT 'user' NOT NULL, + `active` integer DEFAULT true NOT NULL, + `must_change_password` integer DEFAULT true NOT NULL, + `created_at` integer DEFAULT (unixepoch()) NOT NULL, + `updated_at` integer DEFAULT (unixepoch()) NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `users_username_unique` ON `users` (`username`); \ No newline at end of file diff --git a/src/db/migrations/meta/0012_snapshot.json b/src/db/migrations/meta/0012_snapshot.json new file mode 100644 index 0000000..ed30f77 --- /dev/null +++ b/src/db/migrations/meta/0012_snapshot.json @@ -0,0 +1,3017 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "7c6307b6-2516-445c-a088-c8ad746b9fde", + "prevId": "63f27b3a-7378-462d-8119-b67d67903dbb", + "tables": { + "buildings": { + "name": "buildings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "buildings_project_id_projects_id_fk": { + "name": "buildings_project_id_projects_id_fk", + "tableFrom": "buildings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_device_rows": { + "name": "circuit_device_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number_snapshot": { + "name": "room_number_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_name_snapshot": { + "name": "room_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manual_quantity": { + "name": "manual_quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_device_rows_circuit_id_idx": { + "name": "circuit_device_rows_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "circuit_device_rows_circuit_id_circuits_id_fk": { + "name": "circuit_device_rows_circuit_id_circuits_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_device_rows_linked_project_device_id_project_devices_id_fk": { + "name": "circuit_device_rows_linked_project_device_id_project_devices_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "circuit_device_rows_room_id_rooms_id_fk": { + "name": "circuit_device_rows_room_id_rooms_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_list_equipment_identifiers": { + "name": "circuit_list_equipment_identifiers", + "columns": { + "owner_type": { + "name": "owner_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_list_equipment_identifiers_owner_unique": { + "name": "circuit_list_equipment_identifiers_owner_unique", + "columns": [ + "owner_type", + "owner_id" + ], + "isUnique": true + }, + "circuit_list_equipment_identifiers_list_identifier_unique": { + "name": "circuit_list_equipment_identifiers_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_list_equipment_identifiers", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_lists": { + "name": "circuit_lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_lists_distribution_board_id_unique": { + "name": "circuit_lists_distribution_board_id_unique", + "columns": [ + "distribution_board_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_lists_project_id_projects_id_fk": { + "name": "circuit_lists_project_id_projects_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_lists_distribution_board_id_distribution_boards_id_fk": { + "name": "circuit_lists_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_protection_devices": { + "name": "circuit_protection_devices", + "columns": { + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "circuit_protection_devices_circuit_id_circuits_id_fk": { + "name": "circuit_protection_devices_circuit_id_circuits_id_fk", + "tableFrom": "circuit_protection_devices", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_sections": { + "name": "circuit_sections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "group_number": { + "name": "group_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_sections_list_key_unique": { + "name": "circuit_sections_list_key_unique", + "columns": [ + "circuit_list_id", + "key" + ], + "isUnique": true + }, + "circuit_sections_list_prefix_unique": { + "name": "circuit_sections_list_prefix_unique", + "columns": [ + "circuit_list_id", + "prefix" + ], + "isUnique": true + }, + "circuit_sections_list_category_group_unique": { + "name": "circuit_sections_list_category_group_unique", + "columns": [ + "circuit_list_id", + "category", + "group_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_sections_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_sections_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_sections", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuits": { + "name": "circuits", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "cable_type": { + "name": "cable_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_cross_section": { + "name": "cable_cross_section", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_length": { + "name": "cable_length", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_assignment": { + "name": "rcd_assignment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "terminal_designation": { + "name": "terminal_designation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage": { + "name": "voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "control_requirement": { + "name": "control_requirement", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_reserve": { + "name": "is_reserve", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuits_section_id_idx": { + "name": "circuits_section_id_idx", + "columns": [ + "section_id" + ], + "isUnique": false + }, + "circuits_list_equipment_identifier_unique": { + "name": "circuits_list_equipment_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuits_circuit_list_id_circuit_lists_id_fk": { + "name": "circuits_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuits_section_id_circuit_sections_id_fk": { + "name": "circuits_section_id_circuit_sections_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_component_protection_devices": { + "name": "distribution_board_component_protection_devices", + "columns": { + "component_id": { + "name": "component_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk": { + "name": "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk", + "tableFrom": "distribution_board_component_protection_devices", + "tableTo": "distribution_board_components", + "columnsFrom": [ + "component_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_components": { + "name": "distribution_board_components", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "placement": { + "name": "placement", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "distribution_board_components_list_identifier_unique": { + "name": "distribution_board_components_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + }, + "distribution_board_components_section_role_unique": { + "name": "distribution_board_components_section_role_unique", + "columns": [ + "section_id", + "role" + ], + "isUnique": true + } + }, + "foreignKeys": { + "distribution_board_components_circuit_list_id_circuit_lists_id_fk": { + "name": "distribution_board_components_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_board_components_section_id_circuit_sections_id_fk": { + "name": "distribution_board_components_section_id_circuit_sections_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_boards": { + "name": "distribution_boards", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "supply_type": { + "name": "supply_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "board_number": { + "name": "board_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fed_from": { + "name": "fed_from", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "distribution_boards_project_id_projects_id_fk": { + "name": "distribution_boards_project_id_projects_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_boards_floor_id_floors_id_fk": { + "name": "distribution_boards_floor_id_floors_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_assets": { + "name": "document_branding_assets", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "data": { + "name": "data", + "type": "blob", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_settings": { + "name": "document_branding_settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_balances": { + "name": "estimate_balances", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date_iso": { + "name": "date_iso", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reserve_av_percent": { + "name": "reserve_av_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "reserve_sv_percent": { + "name": "reserve_sv_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_balances_project_id_idx": { + "name": "estimate_balances_project_id_idx", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_balances_project_id_projects_id_fk": { + "name": "estimate_balances_project_id_projects_id_fk", + "tableFrom": "estimate_balances", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_groups": { + "name": "estimate_groups", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "balance_id": { + "name": "balance_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "editor": { + "name": "editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_groups_balance_id_idx": { + "name": "estimate_groups_balance_id_idx", + "columns": [ + "balance_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_groups_balance_id_estimate_balances_id_fk": { + "name": "estimate_groups_balance_id_estimate_balances_id_fk", + "tableFrom": "estimate_groups", + "tableTo": "estimate_balances", + "columnsFrom": [ + "balance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_rows": { + "name": "estimate_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "supply": { + "name": "supply", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "quantity": { + "name": "quantity", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'piece'" + }, + "connection": { + "name": "connection", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_per_unit_w": { + "name": "power_per_unit_w", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "safety_supply": { + "name": "safety_supply", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "estimate_rows_group_id_idx": { + "name": "estimate_rows_group_id_idx", + "columns": [ + "group_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_rows_group_id_estimate_groups_id_fk": { + "name": "estimate_rows_group_id_estimate_groups_id_fk", + "tableFrom": "estimate_rows", + "tableTo": "estimate_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_csv_configurations": { + "name": "external_csv_configurations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_version": { + "name": "configuration_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration": { + "name": "configuration", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "external_csv_configurations_project_id_unique": { + "name": "external_csv_configurations_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_csv_configurations_project_id_projects_id_fk": { + "name": "external_csv_configurations_project_id_projects_id_fk", + "tableFrom": "external_csv_configurations", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_import_batches": { + "name": "external_import_batches", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "import_kind": { + "name": "import_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "imported_at_iso": { + "name": "imported_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_project_revision": { + "name": "applied_project_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_version": { + "name": "configuration_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_snapshot": { + "name": "configuration_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_bytes": { + "name": "original_bytes", + "type": "blob", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "document": { + "name": "document", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "external_import_batches_project_revision_idx": { + "name": "external_import_batches_project_revision_idx", + "columns": [ + "project_id", + "applied_project_revision" + ], + "isUnique": false + }, + "external_import_batches_source_imported_idx": { + "name": "external_import_batches_source_imported_idx", + "columns": [ + "source_id", + "imported_at_iso" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_import_batches_project_id_projects_id_fk": { + "name": "external_import_batches_project_id_projects_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_import_batches_source_id_external_model_sources_id_fk": { + "name": "external_import_batches_source_id_external_model_sources_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_objects": { + "name": "external_model_objects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ifc_guid": { + "name": "ifc_guid", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_import_batch_id": { + "name": "last_seen_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_accepted_import_batch_id": { + "name": "last_accepted_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_source_values": { + "name": "accepted_source_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "planning_values": { + "name": "planning_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_room_mapping_id": { + "name": "external_room_mapping_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_device_row_id": { + "name": "circuit_device_row_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "presence_status": { + "name": "presence_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'present'" + } + }, + "indexes": { + "external_model_objects_source_ifc_guid_unique": { + "name": "external_model_objects_source_ifc_guid_unique", + "columns": [ + "source_id", + "ifc_guid" + ], + "isUnique": true + }, + "external_model_objects_project_presence_idx": { + "name": "external_model_objects_project_presence_idx", + "columns": [ + "project_id", + "presence_status" + ], + "isUnique": false + }, + "external_model_objects_distribution_board_idx": { + "name": "external_model_objects_distribution_board_idx", + "columns": [ + "distribution_board_id" + ], + "isUnique": false + }, + "external_model_objects_circuit_device_row_idx": { + "name": "external_model_objects_circuit_device_row_idx", + "columns": [ + "circuit_device_row_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_model_objects_project_id_projects_id_fk": { + "name": "external_model_objects_project_id_projects_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_source_id_external_model_sources_id_fk": { + "name": "external_model_objects_source_id_external_model_sources_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_seen_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_accepted_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk": { + "name": "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_room_mappings", + "columnsFrom": [ + "external_room_mapping_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_distribution_board_id_distribution_boards_id_fk": { + "name": "external_model_objects_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_linked_project_device_id_project_devices_id_fk": { + "name": "external_model_objects_linked_project_device_id_project_devices_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk": { + "name": "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "circuit_device_rows", + "columnsFrom": [ + "circuit_device_row_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_sources": { + "name": "external_model_sources", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'revit_csv'" + } + }, + "indexes": { + "external_model_sources_project_type_unique": { + "name": "external_model_sources_project_type_unique", + "columns": [ + "project_id", + "source_type" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_model_sources_project_id_projects_id_fk": { + "name": "external_model_sources_project_id_projects_id_fk", + "tableFrom": "external_model_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_room_mappings": { + "name": "external_room_mappings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "normalized_source_room_key": { + "name": "normalized_source_room_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_floor_name": { + "name": "source_floor_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_room_number": { + "name": "source_room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_room_name": { + "name": "source_room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_distribution_board_id": { + "name": "default_distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "external_room_mappings_source_key_unique": { + "name": "external_room_mappings_source_key_unique", + "columns": [ + "source_id", + "normalized_source_room_key" + ], + "isUnique": true + }, + "external_room_mappings_project_room_idx": { + "name": "external_room_mappings_project_room_idx", + "columns": [ + "project_id", + "room_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_room_mappings_project_id_projects_id_fk": { + "name": "external_room_mappings_project_id_projects_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_source_id_external_model_sources_id_fk": { + "name": "external_room_mappings_source_id_external_model_sources_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_room_id_rooms_id_fk": { + "name": "external_room_mappings_room_id_rooms_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk": { + "name": "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "distribution_boards", + "columnsFrom": [ + "default_distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "floors": { + "name": "floors", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "building_id": { + "name": "building_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "floors_project_id_projects_id_fk": { + "name": "floors_project_id_projects_id_fk", + "tableFrom": "floors", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "floors_building_id_buildings_id_fk": { + "name": "floors_building_id_buildings_id_fk", + "tableFrom": "floors", + "tableTo": "buildings", + "columnsFrom": [ + "building_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "global_devices": { + "name": "global_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installed_power_per_unit_kw": { + "name": "installed_power_per_unit_kw", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "demand_factor": { + "name": "demand_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phase_count": { + "name": "phase_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_factor": { + "name": "power_factor", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_change_sets": { + "name": "project_change_sets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_revision_id": { + "name": "project_revision_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command_type": { + "name": "command_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_schema_version": { + "name": "payload_schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "forward_payload_json": { + "name": "forward_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "inverse_payload_json": { + "name": "inverse_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_change_sets_revision_unique": { + "name": "project_change_sets_revision_unique", + "columns": [ + "project_revision_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_change_sets_project_revision_id_project_revisions_id_fk": { + "name": "project_change_sets_project_revision_id_project_revisions_id_fk", + "tableFrom": "project_change_sets", + "tableTo": "project_revisions", + "columnsFrom": [ + "project_revision_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_devices": { + "name": "project_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'single_phase'" + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "project_devices_project_id_projects_id_fk": { + "name": "project_devices_project_id_projects_id_fk", + "tableFrom": "project_devices", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_history_stack_entries": { + "name": "project_history_stack_entries", + "columns": { + "change_set_id": { + "name": "change_set_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_history_stack_entries_position_unique": { + "name": "project_history_stack_entries_position_unique", + "columns": [ + "project_id", + "stack", + "position" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_history_stack_entries_change_set_id_project_change_sets_id_fk": { + "name": "project_history_stack_entries_change_set_id_project_change_sets_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "project_change_sets", + "columnsFrom": [ + "change_set_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_history_stack_entries_project_id_projects_id_fk": { + "name": "project_history_stack_entries_project_id_projects_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "project_history_stack_entries_stack_check": { + "name": "project_history_stack_entries_stack_check", + "value": "\"project_history_stack_entries\".\"stack\" in ('undo', 'redo')" + } + } + }, + "project_revisions": { + "name": "project_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision_number": { + "name": "revision_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_revisions_project_number_unique": { + "name": "project_revisions_project_number_unique", + "columns": [ + "project_id", + "revision_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_revisions_project_id_projects_id_fk": { + "name": "project_revisions_project_id_projects_id_fk", + "tableFrom": "project_revisions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_snapshots": { + "name": "project_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_revision": { + "name": "source_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'named'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_sha256": { + "name": "payload_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_actor_id": { + "name": "created_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_snapshots_project_created_idx": { + "name": "project_snapshots_project_created_idx", + "columns": [ + "project_id", + "created_at_iso" + ], + "isUnique": false + }, + "project_snapshots_project_kind_revision_idx": { + "name": "project_snapshots_project_kind_revision_idx", + "columns": [ + "project_id", + "kind", + "source_revision" + ], + "isUnique": false + }, + "project_snapshots_project_name_unique": { + "name": "project_snapshots_project_name_unique", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_snapshots_project_id_projects_id_fk": { + "name": "project_snapshots_project_id_projects_id_fk", + "tableFrom": "project_snapshots", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "internal_project_number": { + "name": "internal_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "external_project_number": { + "name": "external_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "building_owner": { + "name": "building_owner", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_public_building": { + "name": "is_public_building", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "single_phase_voltage_v": { + "name": "single_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 230 + }, + "three_phase_voltage_v": { + "name": "three_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 400 + }, + "enabled_distribution_board_supply_types": { + "name": "enabled_distribution_board_supply_types", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"AV\",\"SV\",\"EV\",\"USV\",\"MSR\",\"SiBe\"]'" + }, + "site_address": { + "name": "site_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_lead": { + "name": "project_lead", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_editor": { + "name": "project_editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "current_revision": { + "name": "current_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "rooms": { + "name": "rooms", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number": { + "name": "room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_name": { + "name": "room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "area_m2": { + "name": "area_m2", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "rooms_project_id_projects_id_fk": { + "name": "rooms_project_id_projects_id_fk", + "tableFrom": "rooms", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "rooms_floor_id_floors_id_fk": { + "name": "rooms_floor_id_floors_id_fk", + "tableFrom": "rooms", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'user'" + }, + "active": { + "name": "active", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "must_change_password": { + "name": "must_change_password", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "users_username_unique": { + "name": "users_username_unique", + "columns": [ + "username" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index 90c3bd0..ddde03a 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1790531351492, "tag": "0011_glossy_norman_osborn", "breakpoints": true + }, + { + "idx": 12, + "version": "6", + "when": 1790617581434, + "tag": "0012_lively_turbo", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/repositories/user.repository.ts b/src/db/repositories/user.repository.ts new file mode 100644 index 0000000..071fc33 --- /dev/null +++ b/src/db/repositories/user.repository.ts @@ -0,0 +1,87 @@ +import crypto from "node:crypto"; +import { asc, eq } from "drizzle-orm"; +import type { AppDatabase } from "../database-context.js"; +import { users } from "../schema/users.js"; +import type { UserRole } from "../../shared/constants/user-roles.js"; + +export interface CreateUserRow { + username: string; + name: string; + role: UserRole; + passwordHash: string; +} + +export class UserRepository { + constructor(private readonly database: AppDatabase) {} + + async list() { + const db = this.database; + return db.select().from(users).orderBy(asc(users.name)); + } + + async count() { + const db = this.database; + const rows = await db.select({ id: users.id }).from(users).limit(1); + return rows.length; + } + + async findById(userId: string) { + const db = this.database; + const [row] = await db.select().from(users).where(eq(users.id, userId)).limit(1); + return row ?? null; + } + + async findByUsername(username: string) { + const db = this.database; + const [row] = await db + .select() + .from(users) + .where(eq(users.username, username.trim().toLowerCase())) + .limit(1); + return row ?? null; + } + + async create(input: CreateUserRow) { + const db = this.database; + const id = crypto.randomUUID(); + await db.insert(users).values({ + id, + username: input.username.trim().toLowerCase(), + name: input.name, + role: input.role, + passwordHash: input.passwordHash, + active: true, + mustChangePassword: true, + }); + return this.findById(id); + } + + async updateRoleAndActive( + userId: string, + patch: { role?: UserRole; active?: boolean } + ) { + const db = this.database; + await db + .update(users) + .set({ + ...(patch.role !== undefined ? { role: patch.role } : {}), + ...(patch.active !== undefined ? { active: patch.active } : {}), + updatedAt: new Date(), + }) + .where(eq(users.id, userId)); + return this.findById(userId); + } + + async setPassword( + userId: string, + passwordHash: string, + mustChangePassword: boolean + ) { + const db = this.database; + await db + .update(users) + .set({ passwordHash, mustChangePassword, updatedAt: new Date() }) + .where(eq(users.id, userId)); + return this.findById(userId); + } +} diff --git a/src/db/schema/users.ts b/src/db/schema/users.ts new file mode 100644 index 0000000..825b5e1 --- /dev/null +++ b/src/db/schema/users.ts @@ -0,0 +1,27 @@ +import { sql } from "drizzle-orm"; +import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; + +export const users = sqliteTable( + "users", + { + id: text("id").primaryKey(), + username: text("username").notNull(), + passwordHash: text("password_hash").notNull(), + name: text("name").notNull(), + role: text("role").notNull().default("user"), + active: integer("active", { mode: "boolean" }).notNull().default(true), + mustChangePassword: integer("must_change_password", { mode: "boolean" }) + .notNull() + .default(true), + createdAt: integer("created_at", { mode: "timestamp" }) + .notNull() + .default(sql`(unixepoch())`), + updatedAt: integer("updated_at", { mode: "timestamp" }) + .notNull() + .default(sql`(unixepoch())`), + }, + (table) => [uniqueIndex("users_username_unique").on(table.username)] +); + +export type User = typeof users.$inferSelect; +export type NewUser = typeof users.$inferInsert; diff --git a/src/domain/services/user.service.ts b/src/domain/services/user.service.ts new file mode 100644 index 0000000..55720c1 --- /dev/null +++ b/src/domain/services/user.service.ts @@ -0,0 +1,104 @@ +import type { UserRepository } from "../../db/repositories/user.repository.js"; +import { hashPassword, verifyPassword } from "../../server/auth/password.js"; +import type { UserRole } from "../../shared/constants/user-roles.js"; +import type { AuthConfig } from "../../server/auth/auth-config.js"; +import { createLogger } from "../../shared/logging/logger.js"; + +const logger = createLogger("user-service"); + +export class InvalidCredentialsError extends Error { + constructor() { + super("Anmeldung fehlgeschlagen."); + } +} + +export class UsernameTakenError extends Error { + constructor() { + super("Dieser Anmeldename ist bereits vergeben."); + } +} + +export class WrongPasswordError extends Error { + constructor() { + super("Das aktuelle Passwort ist falsch."); + } +} + +export class UserService { + constructor( + private readonly repository: UserRepository, + private readonly authConfig: AuthConfig + ) {} + + /** + * Creates the bootstrap admin from env vars, but only while the users + * table is still completely empty. After the first account exists, every + * further account is created through Config -> Benutzer, and the bootstrap + * env vars are ignored - that's the whole point of them being a one-time + * escape hatch instead of a standing backdoor. + */ + async ensureBootstrapAdmin(): Promise { + if (!this.authConfig.bootstrap) return; + const existingCount = await this.repository.count(); + if (existingCount > 0) return; + const passwordHash = await hashPassword(this.authConfig.bootstrap.password); + await this.repository.create({ + username: this.authConfig.bootstrap.username, + name: "Administrator", + role: "admin", + passwordHash, + }); + logger.info("bootstrap admin created", { + username: this.authConfig.bootstrap.username, + }); + } + + async authenticate(username: string, password: string) { + const user = await this.repository.findByUsername(username); + // Always hash something, even for an unknown user: otherwise the + // response time would leak which usernames exist. + const passwordHash = user?.passwordHash ?? (await hashPassword("placeholder")); + const passwordMatches = await verifyPassword(password, passwordHash); + if (!user || !user.active || !passwordMatches) { + throw new InvalidCredentialsError(); + } + return user; + } + + async createUser(input: { + username: string; + name: string; + role: UserRole; + initialPassword: string; + }) { + const existing = await this.repository.findByUsername(input.username); + if (existing) throw new UsernameTakenError(); + const passwordHash = await hashPassword(input.initialPassword); + return this.repository.create({ + username: input.username, + name: input.name, + role: input.role, + passwordHash, + }); + } + + async updateRoleAndActive(userId: string, patch: { role?: UserRole; active?: boolean }) { + return this.repository.updateRoleAndActive(userId, patch); + } + + /** Admin-triggered reset with a new start password; forces a change on next login. */ + async resetPassword(userId: string, newPassword: string) { + const passwordHash = await hashPassword(newPassword); + return this.repository.setPassword(userId, passwordHash, true); + } + + /** Self-service change by the signed-in user; clears mustChangePassword. */ + async changeOwnPassword(userId: string, currentPassword: string, newPassword: string) { + const user = await this.repository.findById(userId); + if (!user) throw new WrongPasswordError(); + const currentMatches = await verifyPassword(currentPassword, user.passwordHash); + if (!currentMatches) throw new WrongPasswordError(); + const passwordHash = await hashPassword(newPassword); + return this.repository.setPassword(userId, passwordHash, false); + } +} diff --git a/src/frontend/components/AuthProvider.tsx b/src/frontend/components/AuthProvider.tsx new file mode 100644 index 0000000..02ab833 --- /dev/null +++ b/src/frontend/components/AuthProvider.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { createContext, useCallback, useContext, useEffect, useState } from "react"; +import { authApi, type AuthUserDto } from "../utils/auth-api"; + +type AuthStatus = "loading" | "signed-in" | "signed-out"; + +interface AuthContextValue { + status: AuthStatus; + user: AuthUserDto | undefined; + isAdmin: boolean; + reload: () => Promise; + logout: () => Promise; +} + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: React.ReactNode }) { + const [status, setStatus] = useState("loading"); + const [user, setUser] = useState(undefined); + + const reload = useCallback(async () => { + try { + const current = await authApi.me(); + setUser(current); + setStatus("signed-in"); + } catch { + setUser(undefined); + setStatus("signed-out"); + } + }, []); + + useEffect(() => { + void reload(); + }, [reload]); + + async function logout() { + try { + await authApi.logout(); + } finally { + setUser(undefined); + setStatus("signed-out"); + } + } + + return ( + + {children} + + ); +} + +export function useAuth(): AuthContextValue { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within an AuthProvider"); + } + return context; +} diff --git a/src/frontend/components/LoginGate.tsx b/src/frontend/components/LoginGate.tsx new file mode 100644 index 0000000..23a2aeb --- /dev/null +++ b/src/frontend/components/LoginGate.tsx @@ -0,0 +1,179 @@ +"use client"; + +import { useState } from "react"; +import { authApi } from "../utils/auth-api"; +import { useAuth } from "./AuthProvider"; + +export function LoginGate({ children }: { children: React.ReactNode }) { + const { status, user, reload } = useAuth(); + + if (status === "loading") { + return ( +
+

Lädt…

+
+ ); + } + + if (status === "signed-out") { + return ( +
+ +
+ ); + } + + if (user?.mustChangePassword) { + return ( +
+ +
+ ); + } + + return <>{children}; +} + +function LoginForm({ onSignedIn }: { onSignedIn: () => Promise }) { + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + setSubmitting(true); + setError(null); + try { + await authApi.login(username, password); + await onSignedIn(); + } catch (err) { + setError(err instanceof Error ? err.message : "Anmeldung fehlgeschlagen."); + } finally { + setSubmitting(false); + } + } + + return ( +
+

Leistungsbilanz

+
+ + setUsername(event.target.value)} + autoFocus + autoComplete="username" + required + /> +
+
+ + setPassword(event.target.value)} + autoComplete="current-password" + required + /> +
+ {error &&

{error}

} + +
+ ); +} + +function ForcedPasswordChangeForm({ onChanged }: { onChanged: () => Promise }) { + const [currentPassword, setCurrentPassword] = useState(""); + const [newPassword, setNewPassword] = useState(""); + const [newPasswordRepeat, setNewPasswordRepeat] = useState(""); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + if (newPassword !== newPasswordRepeat) { + setError("Die beiden neuen Passwörter stimmen nicht überein."); + return; + } + setSubmitting(true); + setError(null); + try { + await authApi.changePassword(currentPassword, newPassword); + await onChanged(); + } catch (err) { + setError(err instanceof Error ? err.message : "Passwort konnte nicht geändert werden."); + } finally { + setSubmitting(false); + } + } + + return ( +
+

Neues Passwort setzen

+

+ Dieser Zugang wurde mit einem Startpasswort angelegt. Bitte vor der + weiteren Nutzung ein eigenes Passwort vergeben. +

+
+ + setCurrentPassword(event.target.value)} + autoComplete="current-password" + autoFocus + required + /> +
+
+ + setNewPassword(event.target.value)} + autoComplete="new-password" + minLength={8} + required + /> +
+
+ + setNewPasswordRepeat(event.target.value)} + autoComplete="new-password" + minLength={8} + required + /> +
+ {error &&

{error}

} + +
+ ); +} diff --git a/src/frontend/components/Sidebar.tsx b/src/frontend/components/Sidebar.tsx index 395cd7c..bb8aecd 100644 --- a/src/frontend/components/Sidebar.tsx +++ b/src/frontend/components/Sidebar.tsx @@ -6,6 +6,7 @@ import { useEffect, useState } from "react"; import { listProjects } from "../utils/api"; import type { ProjectDto } from "../types"; import { ThemeToggle } from "./ThemeToggle"; +import { useAuth } from "./AuthProvider"; // Anchors on the project overview page (/projects/[id]). const PROJECT_SECTIONS = [ @@ -30,6 +31,7 @@ interface SidebarProps { export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { const pathname = usePathname(); + const { user, isAdmin, logout } = useAuth(); const projectMatch = pathname?.match(PROJECT_PATH_PATTERN); const activeProjectId = projectMatch ? projectMatch[1] : null; const projectSubPath = projectMatch?.[2] ?? ""; @@ -179,8 +181,31 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { )} + {isAdmin && ( + + )}
+ {user && !isCollapsed && ( +
+ Angemeldet als + {user.name} +
+ )} + {user && ( + + )}
); diff --git a/src/frontend/utils/auth-api.ts b/src/frontend/utils/auth-api.ts new file mode 100644 index 0000000..f7057f9 --- /dev/null +++ b/src/frontend/utils/auth-api.ts @@ -0,0 +1,86 @@ +// Small, self-contained fetch helper for the auth/user endpoints - kept +// separate from the large domain api.ts so this feature doesn't have to +// touch that file's shared `request()` internals. + +export type UserRole = "admin" | "user"; + +export interface AuthStatusDto { + signedIn: boolean; + mustChangePassword: boolean; +} + +export interface AuthUserDto { + id: string; + username: string; + name: string; + role: UserRole; + mustChangePassword: boolean; +} + +export interface UserDto { + id: string; + username: string; + name: string; + role: UserRole; + active: boolean; + mustChangePassword: boolean; + createdAt: string; +} + +export class AuthApiError extends Error { + constructor( + message: string, + public readonly status: number + ) { + super(message); + } +} + +async function request(url: string, init?: RequestInit): Promise { + const response = await fetch(url, { + ...init, + headers: { "Content-Type": "application/json", ...init?.headers }, + cache: "no-store", + }); + if (!response.ok) { + let message = `Anfrage fehlgeschlagen (Status ${response.status})`; + try { + const body = (await response.json()) as { error?: unknown }; + if (typeof body.error === "string") message = body.error; + } catch { + // Keep the generic message for non-JSON error responses. + } + throw new AuthApiError(message, response.status); + } + if (response.status === 204) return undefined as T; + return response.json() as Promise; +} + +export const authApi = { + status: () => request("/api/auth/status"), + login: (username: string, password: string) => + request("/api/auth/login", { + method: "POST", + body: JSON.stringify({ username, password }), + }), + me: () => request("/api/auth/me"), + changePassword: (currentPassword: string, newPassword: string) => + request<{ changed: true }>("/api/auth/change-password", { + method: "POST", + body: JSON.stringify({ currentPassword, newPassword }), + }), + logout: () => request<{ signedOut: true }>("/api/auth/logout", { method: "POST" }), +}; + +export const userApi = { + list: () => request("/api/users"), + create: (input: { username: string; name: string; role: UserRole; initialPassword: string }) => + request("/api/users", { method: "POST", body: JSON.stringify(input) }), + update: (userId: string, patch: { role?: UserRole; active?: boolean }) => + request(`/api/users/${userId}`, { method: "PATCH", body: JSON.stringify(patch) }), + resetPassword: (userId: string, newPassword: string) => + request(`/api/users/${userId}/reset-password`, { + method: "POST", + body: JSON.stringify({ newPassword }), + }), +}; diff --git a/src/server/auth/auth-config.ts b/src/server/auth/auth-config.ts new file mode 100644 index 0000000..d2157f4 --- /dev/null +++ b/src/server/auth/auth-config.ts @@ -0,0 +1,44 @@ +export const SESSION_COOKIE = "lb_session"; + +const DEFAULT_SESSION_HOURS = 12; + +export interface AuthConfig { + sessionTtlMs: number; + cookieSecure: boolean; + /** + * Only used to create the very first admin when the users table is still + * empty - after that, every account is created through Config -> Benutzer. + * Unset means: no bootstrap account, the table must already have an admin. + */ + bootstrap: { username: string; password: string } | null; +} + +export class AuthConfigError extends Error {} + +export function readAuthConfig(env: NodeJS.ProcessEnv = process.env): AuthConfig { + const hours = Number(env.AUTH_SESSION_HOURS ?? DEFAULT_SESSION_HOURS); + if (!Number.isFinite(hours) || hours <= 0) { + throw new AuthConfigError("AUTH_SESSION_HOURS must be a positive number."); + } + + const bootstrapUsername = (env.AUTH_BOOTSTRAP_USERNAME ?? "").trim().toLowerCase(); + const bootstrapPassword = env.AUTH_BOOTSTRAP_PASSWORT ?? ""; + if (Boolean(bootstrapUsername) !== Boolean(bootstrapPassword)) { + throw new AuthConfigError( + "AUTH_BOOTSTRAP_USERNAME and AUTH_BOOTSTRAP_PASSWORT belong together - set both or neither." + ); + } + if (bootstrapPassword && bootstrapPassword.length < 12) { + throw new AuthConfigError( + "AUTH_BOOTSTRAP_PASSWORT must be at least 12 characters long." + ); + } + + return { + sessionTtlMs: hours * 60 * 60 * 1000, + cookieSecure: (env.COOKIE_SECURE ?? "").trim().toLowerCase() === "true", + bootstrap: bootstrapUsername + ? { username: bootstrapUsername, password: bootstrapPassword } + : null, + }; +} diff --git a/src/server/auth/auth.middleware.ts b/src/server/auth/auth.middleware.ts new file mode 100644 index 0000000..53a1767 --- /dev/null +++ b/src/server/auth/auth.middleware.ts @@ -0,0 +1,111 @@ +import type { NextFunction, Request, RequestHandler, Response } from "express"; +import { SESSION_COOKIE, type AuthConfig } from "./auth-config.js"; +import { readCookie } from "./cookie.js"; +import type { SessionStore } from "./sessions.js"; +import type { UserRepository } from "../../db/repositories/user.repository.js"; +import type { UserRole } from "../../shared/constants/user-roles.js"; + +export interface AuthUser { + id: string; + username: string; + name: string; + role: UserRole; + mustChangePassword: boolean; +} + +declare global { + namespace Express { + interface Request { + authUser?: AuthUser; + } + } +} + +export function sessionIdFromRequest(req: { + headers: { cookie?: string | undefined }; +}): string | undefined { + return readCookie(req.headers.cookie, SESSION_COOKIE); +} + +export async function identityFromRequest( + req: { headers: { cookie?: string | undefined } }, + sessions: SessionStore, + users: UserRepository, + slideExpiry = true +): Promise { + const session = sessions.get(sessionIdFromRequest(req), slideExpiry); + if (!session) return undefined; + const user = await users.findById(session.userId); + if (!user || !user.active) return undefined; + return { + id: user.id, + username: user.username, + name: user.name, + role: user.role as UserRole, + mustChangePassword: user.mustChangePassword, + }; +} + +export function cookieOptions(authConfig: AuthConfig) { + return { + httpOnly: true, + sameSite: "lax" as const, + secure: authConfig.cookieSecure, + path: "/", + maxAge: authConfig.sessionTtlMs, + }; +} + +/** Protects /api. Only the login route and the status check stay reachable without a session. */ +export function createAuthGuard( + authConfig: AuthConfig, + sessions: SessionStore, + users: UserRepository, + openPaths: readonly string[] = ["/auth/login", "/auth/status", "/auth/logout"] +): RequestHandler { + return (req: Request, res: Response, next: NextFunction) => { + if (openPaths.includes(req.path)) { + next(); + return; + } + identityFromRequest(req, sessions, users) + .then((identity) => { + if (!identity) { + res.status(401).json({ error: "Nicht angemeldet." }); + return; + } + req.authUser = identity; + const sessionId = sessionIdFromRequest(req); + if (sessionId) { + res.cookie(SESSION_COOKIE, sessionId, cookieOptions(authConfig)); + } + next(); + }) + .catch(next); + }; +} + +/** Blocks everything except logout and the password change while a start password is still in use. */ +export function requirePasswordChanged(): RequestHandler { + const allowed = new Set(["/auth/me", "/auth/change-password", "/auth/logout"]); + return (req: Request, res: Response, next: NextFunction) => { + if (!req.authUser?.mustChangePassword || allowed.has(req.path)) { + next(); + return; + } + res.status(403).json({ + error: "Bitte zuerst ein eigenes Passwort setzen.", + mustChangePassword: true, + }); + }; +} + +export function requireRole(role: UserRole): RequestHandler { + return (req: Request, res: Response, next: NextFunction) => { + if (req.authUser?.role !== role) { + res.status(403).json({ error: "Keine Berechtigung für diese Aktion." }); + return; + } + next(); + }; +} diff --git a/src/server/auth/cookie.ts b/src/server/auth/cookie.ts new file mode 100644 index 0000000..0204ca3 --- /dev/null +++ b/src/server/auth/cookie.ts @@ -0,0 +1,15 @@ +/** Reads one cookie value from a raw "Cookie" request header. No cookie-parser dependency needed for a single cookie. */ +export function readCookie( + header: string | undefined, + name: string +): string | undefined { + if (!header) return undefined; + for (const part of header.split(";")) { + const separatorIndex = part.indexOf("="); + if (separatorIndex === -1) continue; + const key = part.slice(0, separatorIndex).trim(); + if (key !== name) continue; + return decodeURIComponent(part.slice(separatorIndex + 1).trim()); + } + return undefined; +} diff --git a/src/server/auth/password.ts b/src/server/auth/password.ts new file mode 100644 index 0000000..96814e1 --- /dev/null +++ b/src/server/auth/password.ts @@ -0,0 +1,63 @@ +import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from "node:crypto"; + +const SCRYPT_N = 16384; +const SCRYPT_R = 8; +const SCRYPT_P = 1; +const KEY_LENGTH = 64; + +// A hand-rolled wrapper instead of util.promisify(scrypt): promisify only +// resolves to scrypt's 3-argument overload, so the 4-argument form used for +// verification (with explicit N/r/p) doesn't type-check through it. +function scryptAsync( + password: string, + salt: Buffer, + keyLength: number, + options?: ScryptOptions +): Promise { + return new Promise((resolve, reject) => { + const callback = (error: Error | null, derivedKey: Buffer) => { + if (error) reject(error); + else resolve(derivedKey); + }; + if (options) { + scrypt(password, salt, keyLength, options, callback); + } else { + scrypt(password, salt, keyLength, callback); + } + }); +} + +// Format: scrypt$N$r$p$saltHex$hashHex - the parameters travel with the +// hash so they can be tuned later without invalidating existing rows. +export async function hashPassword(password: string): Promise { + const salt = randomBytes(16); + const derivedKey = await scryptAsync(password, salt, KEY_LENGTH); + return [ + "scrypt", + SCRYPT_N, + SCRYPT_R, + SCRYPT_P, + salt.toString("hex"), + derivedKey.toString("hex"), + ].join("$"); +} + +export async function verifyPassword( + password: string, + storedHash: string +): Promise { + const parts = storedHash.split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return false; + const [, nRaw, rRaw, pRaw, saltHex, hashHex] = parts; + const n = Number(nRaw); + const r = Number(rRaw); + const p = Number(pRaw); + if (!Number.isFinite(n) || !Number.isFinite(r) || !Number.isFinite(p)) { + return false; + } + const salt = Buffer.from(saltHex, "hex"); + const expected = Buffer.from(hashHex, "hex"); + const derivedKey = await scryptAsync(password, salt, expected.length, { N: n, r, p }); + if (derivedKey.length !== expected.length) return false; + return timingSafeEqual(derivedKey, expected); +} diff --git a/src/server/auth/sessions.ts b/src/server/auth/sessions.ts new file mode 100644 index 0000000..501f4c4 --- /dev/null +++ b/src/server/auth/sessions.ts @@ -0,0 +1,55 @@ +import { randomUUID } from "node:crypto"; + +interface Session { + id: string; + userId: string; + expiresAt: number; +} + +/** + * In-memory session store. The API runs as a single container/process, so a + * restart clearing every session is an acceptable trade-off for the + * simplicity of not needing a persisted session table. + */ +export class SessionStore { + private readonly sessions = new Map(); + + constructor(private readonly ttlMs: number) {} + + create(userId: string): Session { + const session: Session = { + id: randomUUID(), + userId, + expiresAt: Date.now() + this.ttlMs, + }; + this.sessions.set(session.id, session); + return session; + } + + /** Returns the session and slides its expiry forward, or undefined if gone/expired. */ + get(sessionId: string | undefined, slideExpiry = true): Session | undefined { + if (!sessionId) return undefined; + const session = this.sessions.get(sessionId); + if (!session) return undefined; + if (session.expiresAt < Date.now()) { + this.sessions.delete(sessionId); + return undefined; + } + if (slideExpiry) session.expiresAt = Date.now() + this.ttlMs; + return session; + } + + destroy(sessionId: string | undefined): void { + if (!sessionId) return; + this.sessions.delete(sessionId); + } + + /** Ends every other session for a user, e.g. after a password change. */ + destroyAllForUser(userId: string, exceptSessionId?: string): void { + for (const [id, session] of this.sessions) { + if (session.userId === userId && id !== exceptSessionId) { + this.sessions.delete(id); + } + } + } +} diff --git a/src/server/composition/application-repositories.ts b/src/server/composition/application-repositories.ts index 66fdd92..846a0da 100644 --- a/src/server/composition/application-repositories.ts +++ b/src/server/composition/application-repositories.ts @@ -16,6 +16,7 @@ import { RoomRepository } from "../../db/repositories/room.repository.js"; import { ExternalCsvConfigurationRepository } from "../../db/repositories/external-csv-configuration.repository.js"; import { ExternalModelStateRepository } from "../../db/repositories/external-model-state.repository.js"; import { DocumentBrandingRepository } from "../../db/repositories/document-branding.repository.js"; +import { UserRepository } from "../../db/repositories/user.repository.js"; export const circuitDeviceRowRepository = new CircuitDeviceRowRepository(db); @@ -39,3 +40,4 @@ export const externalCsvConfigurationRepository = new ExternalCsvConfigurationRepository(db); export const externalModelStateRepository = new ExternalModelStateRepository(db); export const documentBrandingRepository = new DocumentBrandingRepository(db); +export const userRepository = new UserRepository(db); diff --git a/src/server/composition/auth.ts b/src/server/composition/auth.ts new file mode 100644 index 0000000..751f324 --- /dev/null +++ b/src/server/composition/auth.ts @@ -0,0 +1,8 @@ +import { readAuthConfig } from "../auth/auth-config.js"; +import { SessionStore } from "../auth/sessions.js"; +import { UserService } from "../../domain/services/user.service.js"; +import { userRepository } from "./application-repositories.js"; + +export const authConfig = readAuthConfig(); +export const sessionStore = new SessionStore(authConfig.sessionTtlMs); +export const userService = new UserService(userRepository, authConfig); diff --git a/src/server/controllers/auth.controller.ts b/src/server/controllers/auth.controller.ts new file mode 100644 index 0000000..9dabee5 --- /dev/null +++ b/src/server/controllers/auth.controller.ts @@ -0,0 +1,88 @@ +import type { Request, Response } from "express"; +import { changePasswordSchema, loginSchema } from "../../shared/validation/auth.schemas.js"; +import { InvalidCredentialsError, WrongPasswordError } from "../../domain/services/user.service.js"; +import { authConfig, sessionStore, userService } from "../composition/auth.js"; +import { + cookieOptions, + identityFromRequest, + sessionIdFromRequest, +} from "../auth/auth.middleware.js"; +import { SESSION_COOKIE } from "../auth/auth-config.js"; +import { userRepository } from "../composition/application-repositories.js"; + +export async function getAuthStatus(req: Request, res: Response) { + const identity = await identityFromRequest(req, sessionStore, userRepository); + const sessionId = sessionIdFromRequest(req); + if (identity && sessionId) { + res.cookie(SESSION_COOKIE, sessionId, cookieOptions(authConfig)); + } + res.json({ + signedIn: Boolean(identity), + mustChangePassword: identity?.mustChangePassword ?? false, + }); +} + +export async function login(req: Request, res: Response) { + const parsed = loginSchema.safeParse(req.body); + if (!parsed.success) { + res.status(401).json({ error: "Anmeldung fehlgeschlagen." }); + return; + } + try { + const user = await userService.authenticate(parsed.data.username, parsed.data.password); + const session = sessionStore.create(user.id); + res.cookie(SESSION_COOKIE, session.id, cookieOptions(authConfig)); + res.json({ signedIn: true, mustChangePassword: user.mustChangePassword }); + } catch (error) { + if (error instanceof InvalidCredentialsError) { + res.status(401).json({ error: error.message }); + return; + } + throw error; + } +} + +export function getMe(req: Request, res: Response) { + const identity = req.authUser; + if (!identity) { + res.status(401).json({ error: "Nicht angemeldet." }); + return; + } + res.json(identity); +} + +export async function changePassword(req: Request, res: Response) { + const identity = req.authUser; + if (!identity) { + res.status(401).json({ error: "Nicht angemeldet." }); + return; + } + const parsed = changePasswordSchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: parsed.error.flatten() }); + return; + } + try { + await userService.changeOwnPassword( + identity.id, + parsed.data.currentPassword, + parsed.data.newPassword + ); + } catch (error) { + if (error instanceof WrongPasswordError) { + res.status(400).json({ error: error.message }); + return; + } + throw error; + } + // A password change invalidates every other session of this account; the + // current one stays so the change doesn't log the user out themselves. + sessionStore.destroyAllForUser(identity.id, sessionIdFromRequest(req)); + res.json({ changed: true }); +} + +export function logout(req: Request, res: Response) { + sessionStore.destroy(sessionIdFromRequest(req)); + res.clearCookie(SESSION_COOKIE, { ...cookieOptions(authConfig), maxAge: undefined }); + res.json({ signedOut: true }); +} diff --git a/src/server/controllers/user.controller.ts b/src/server/controllers/user.controller.ts new file mode 100644 index 0000000..0ad3cbc --- /dev/null +++ b/src/server/controllers/user.controller.ts @@ -0,0 +1,103 @@ +import type { Request, Response } from "express"; +import { + createUserSchema, + resetPasswordSchema, + updateUserSchema, +} from "../../shared/validation/user.schemas.js"; +import { UsernameTakenError } from "../../domain/services/user.service.js"; +import { userService } from "../composition/auth.js"; +import { userRepository } from "../composition/application-repositories.js"; + +// The password hash never leaves this layer. +function toDto(user: { + id: string; + username: string; + name: string; + role: string; + active: boolean; + mustChangePassword: boolean; + createdAt: Date; +}) { + return { + id: user.id, + username: user.username, + name: user.name, + role: user.role, + active: user.active, + mustChangePassword: user.mustChangePassword, + createdAt: user.createdAt, + }; +} + +export async function listUsers(_req: Request, res: Response) { + const rows = await userRepository.list(); + res.json(rows.map(toDto)); +} + +export async function createUser(req: Request, res: Response) { + const parsed = createUserSchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: parsed.error.flatten() }); + return; + } + try { + const created = await userService.createUser(parsed.data); + if (!created) { + res.status(500).json({ error: "Benutzer konnte nicht angelegt werden." }); + return; + } + res.status(201).json(toDto(created)); + } catch (error) { + if (error instanceof UsernameTakenError) { + res.status(409).json({ error: error.message }); + return; + } + throw error; + } +} + +export async function updateUser(req: Request, res: Response) { + const { userId } = req.params; + if (typeof userId !== "string") { + res.status(400).json({ error: "Invalid userId" }); + return; + } + const parsed = updateUserSchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: parsed.error.flatten() }); + return; + } + // The signed-in admin can't lock themselves out by deactivating or + // demoting their own account through this endpoint. + if (userId === req.authUser?.id) { + res.status(400).json({ error: "Der eigene Zugang kann hier nicht geändert werden." }); + return; + } + const existing = await userRepository.findById(userId); + if (!existing) { + res.status(404).json({ error: "Benutzer nicht gefunden." }); + return; + } + const updated = await userService.updateRoleAndActive(userId, parsed.data); + res.json(updated ? toDto(updated) : null); +} + +export async function resetUserPassword(req: Request, res: Response) { + const { userId } = req.params; + if (typeof userId !== "string") { + res.status(400).json({ error: "Invalid userId" }); + return; + } + const parsed = resetPasswordSchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: parsed.error.flatten() }); + return; + } + const existing = await userRepository.findById(userId); + if (!existing) { + res.status(404).json({ error: "Benutzer nicht gefunden." }); + return; + } + const updated = await userService.resetPassword(userId, parsed.data.newPassword); + res.json(updated ? toDto(updated) : null); +} diff --git a/src/server/index.ts b/src/server/index.ts index 7cad7e3..868de79 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -4,7 +4,12 @@ import { projectDeviceRouter } from "./routes/project-device.routes.js"; import { documentBrandingRouter } from "./routes/document-branding.routes.js"; import { projectRouter } from "./routes/project.routes.js"; import { cableSizingRouter } from "./routes/cable-sizing.routes.js"; +import { authRouter } from "./routes/auth.routes.js"; +import { userRouter } from "./routes/user.routes.js"; import { errorMiddleware } from "./middleware/error.middleware.js"; +import { createAuthGuard, requirePasswordChanged } from "./auth/auth.middleware.js"; +import { authConfig, sessionStore, userService } from "./composition/auth.js"; +import { userRepository } from "./composition/application-repositories.js"; import { createLogger, toErrorMeta } from "../shared/logging/logger.js"; import { closeDefaultDatabase } from "../db/client.js"; @@ -50,6 +55,15 @@ app.get("/health", (_req, res) => { res.json({ ok: true }); }); +// Everything below /api requires a signed-in, active user, except +// /auth/login, /auth/status and /auth/logout (see createAuthGuard's +// openPaths). authRouter is mounted AFTER the guard (not before) so that +// /auth/me and /auth/change-password still get req.authUser populated by it. +app.use("/api", createAuthGuard(authConfig, sessionStore, userRepository)); +app.use("/api", requirePasswordChanged()); + +app.use("/api/auth", authRouter); +app.use("/api/users", userRouter); app.use("/api/cable-sizing", cableSizingRouter); app.use("/api/projects", projectRouter); app.use("/api/global-devices", globalDeviceRouter); @@ -77,40 +91,48 @@ setInterval(() => { }); }, heartbeatIntervalMs).unref(); -const server = app.listen(port, () => { - logger.info("server started", { port }); -}); - -let shuttingDown = false; - -function shutdown(signal: NodeJS.Signals): void { - if (shuttingDown) return; - shuttingDown = true; - logger.info("shutting down", { signal }); - - // Falls ein Request haengt oder ein Socket nicht freigegeben wird, soll der - // Prozess trotzdem enden, statt auf das SIGKILL des Containers zu warten. - const forceExit = setTimeout(() => { - logger.error("shutdown timed out, forcing exit"); +userService + .ensureBootstrapAdmin() + .catch((error) => { + logger.error("bootstrap admin setup failed", toErrorMeta(error)); process.exit(1); - }, shutdownTimeoutMs); - forceExit.unref(); + }) + .then(() => { + const server = app.listen(port, () => { + logger.info("server started", { port }); + }); - server.close((error) => { - if (error) logger.error("http server close failed", toErrorMeta(error)); - try { - closeDefaultDatabase(); - } catch (closeError) { - logger.error("database close failed", toErrorMeta(closeError)); + let shuttingDown = false; + + function shutdown(signal: NodeJS.Signals): void { + if (shuttingDown) return; + shuttingDown = true; + logger.info("shutting down", { signal }); + + // Falls ein Request haengt oder ein Socket nicht freigegeben wird, soll der + // Prozess trotzdem enden, statt auf das SIGKILL des Containers zu warten. + const forceExit = setTimeout(() => { + logger.error("shutdown timed out, forcing exit"); + process.exit(1); + }, shutdownTimeoutMs); + forceExit.unref(); + + server.close((error) => { + if (error) logger.error("http server close failed", toErrorMeta(error)); + try { + closeDefaultDatabase(); + } catch (closeError) { + logger.error("database close failed", toErrorMeta(closeError)); + } + logger.info("shutdown complete"); + process.exit(error ? 1 : 0); + }); + + // Ohne das warten offene Keep-Alive-Verbindungen (z. B. die des + // Next.js-Servers) den Timeout oben aus; laufende Requests laufen weiter. + server.closeIdleConnections(); } - logger.info("shutdown complete"); - process.exit(error ? 1 : 0); + + process.on("SIGTERM", shutdown); + process.on("SIGINT", shutdown); }); - - // Ohne das warten offene Keep-Alive-Verbindungen (z. B. die des - // Next.js-Servers) den Timeout oben aus; laufende Requests laufen weiter. - server.closeIdleConnections(); -} - -process.on("SIGTERM", shutdown); -process.on("SIGINT", shutdown); diff --git a/src/server/routes/auth.routes.ts b/src/server/routes/auth.routes.ts new file mode 100644 index 0000000..ee1cdd1 --- /dev/null +++ b/src/server/routes/auth.routes.ts @@ -0,0 +1,16 @@ +import { Router } from "express"; +import { + changePassword, + getAuthStatus, + getMe, + login, + logout, +} from "../controllers/auth.controller.js"; + +export const authRouter = Router(); + +authRouter.get("/status", getAuthStatus); +authRouter.post("/login", login); +authRouter.get("/me", getMe); +authRouter.post("/change-password", changePassword); +authRouter.post("/logout", logout); diff --git a/src/server/routes/user.routes.ts b/src/server/routes/user.routes.ts new file mode 100644 index 0000000..a34699c --- /dev/null +++ b/src/server/routes/user.routes.ts @@ -0,0 +1,16 @@ +import { Router } from "express"; +import { requireRole } from "../auth/auth.middleware.js"; +import { + createUser, + listUsers, + resetUserPassword, + updateUser, +} from "../controllers/user.controller.js"; + +export const userRouter = Router(); + +userRouter.use(requireRole("admin")); +userRouter.get("/", listUsers); +userRouter.post("/", createUser); +userRouter.patch("/:userId", updateUser); +userRouter.post("/:userId/reset-password", resetUserPassword); diff --git a/src/shared/constants/user-roles.ts b/src/shared/constants/user-roles.ts new file mode 100644 index 0000000..f123d5f --- /dev/null +++ b/src/shared/constants/user-roles.ts @@ -0,0 +1,7 @@ +export const USER_ROLES = ["admin", "user"] as const; +export type UserRole = (typeof USER_ROLES)[number]; + +export const USER_ROLE_LABEL: Record = { + admin: "Administrator", + user: "Benutzer", +}; diff --git a/src/shared/validation/auth.schemas.ts b/src/shared/validation/auth.schemas.ts new file mode 100644 index 0000000..544b052 --- /dev/null +++ b/src/shared/validation/auth.schemas.ts @@ -0,0 +1,15 @@ +import { z } from "zod"; + +export const loginSchema = z + .object({ + username: z.string().trim().min(1), + password: z.string().min(1), + }) + .strict(); + +export const changePasswordSchema = z + .object({ + currentPassword: z.string().min(1), + newPassword: z.string().min(8).max(200), + }) + .strict(); diff --git a/src/shared/validation/user.schemas.ts b/src/shared/validation/user.schemas.ts new file mode 100644 index 0000000..ceb8961 --- /dev/null +++ b/src/shared/validation/user.schemas.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; +import { USER_ROLES } from "../constants/user-roles.js"; + +const MIN_PASSWORD_LENGTH = 8; + +export const createUserSchema = z + .object({ + username: z.string().trim().min(1).max(200), + name: z.string().trim().min(1).max(200), + role: z.enum(USER_ROLES), + initialPassword: z.string().min(MIN_PASSWORD_LENGTH).max(200), + }) + .strict(); + +export const updateUserSchema = z + .object({ + role: z.enum(USER_ROLES).optional(), + active: z.boolean().optional(), + }) + .strict() + .refine((value) => value.role !== undefined || value.active !== undefined, { + message: "Nothing to update.", + }); + +export const resetPasswordSchema = z + .object({ + newPassword: z.string().min(MIN_PASSWORD_LENGTH).max(200), + }) + .strict(); + +export type CreateUserInput = z.infer; +export type UpdateUserInput = z.infer; +export type ResetPasswordInput = z.infer; From 8d2948cdb1efdee5e28a72b65ea9b45b9a281c72 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Mon, 28 Sep 2026 20:32:20 +0200 Subject: [PATCH 17/38] Match sidebar bottom layout to the Wochenplanung reference (theme toggle + Abmelden in one row) Square icon-only theme toggle sits next to the Abmelden button in a shared row, collapsing to just the toggle when the sidebar is collapsed - same arrangement as pm-app's Sidebar.tsx. Co-Authored-By: Claude Sonnet 5 --- src/app/globals.css | 31 ++++++++++++++++++------- src/frontend/components/Sidebar.tsx | 17 +++++++++----- src/frontend/components/ThemeToggle.tsx | 9 +++---- 3 files changed, 38 insertions(+), 19 deletions(-) diff --git a/src/app/globals.css b/src/app/globals.css index f670173..fec2745 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -323,23 +323,24 @@ a { } .sidebar-footer { - padding: 12px; + padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.12); } +/* Square and icon-only so it fits next to Abmelden in .sidebar-bottom-row. */ .sidebar-theme-toggle { display: flex; align-items: center; - gap: 10px; - padding: 10px 14px; + justify-content: center; + flex: 0 0 auto; + width: 36px; + height: 36px; + padding: 0; border-radius: 8px; color: #c7d6e0; font-size: 0.92rem; - font-weight: 500; border: 1px solid rgba(255, 255, 255, 0.16); background: rgba(255, 255, 255, 0.06); - width: 100%; - text-align: left; cursor: pointer; } @@ -2747,12 +2748,20 @@ button.structure-entry-main:focus-visible { white-space: nowrap; } +/* Toggle (square) and Abmelden (fills the rest) share one row. */ +.sidebar-bottom-row { + display: flex; + align-items: stretch; + gap: 8px; + padding: 0 14px 12px; +} + .sidebar-logout { display: flex; align-items: center; justify-content: center; - gap: 8px; - margin-top: 8px; + flex: 1 1 auto; + min-width: 0; padding: 8px 14px; border-radius: 8px; color: #c7d6e0; @@ -2760,7 +2769,6 @@ button.structure-entry-main:focus-visible { font-weight: 500; border: 1px solid rgba(255, 255, 255, 0.16); background: transparent; - width: 100%; cursor: pointer; } @@ -2773,6 +2781,11 @@ button.structure-entry-main:focus-visible { display: none; } +.sidebar-collapsed .sidebar-bottom-row { + justify-content: center; + padding-inline: 0; +} + .login-gate-screen { min-height: 100vh; display: flex; diff --git a/src/frontend/components/Sidebar.tsx b/src/frontend/components/Sidebar.tsx index bb8aecd..5130d5d 100644 --- a/src/frontend/components/Sidebar.tsx +++ b/src/frontend/components/Sidebar.tsx @@ -200,12 +200,17 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { {user.name}
)} - - {user && ( - - )} + {/* Toggle and Abmelden share one row: the toggle stays a fixed-size + square, Abmelden takes the rest of the width. Collapsed, only + the square toggle remains (centered). */} +
+ + {user && !isCollapsed && ( + + )} +
); diff --git a/src/frontend/components/ThemeToggle.tsx b/src/frontend/components/ThemeToggle.tsx index 355e0e2..2073a5e 100644 --- a/src/frontend/components/ThemeToggle.tsx +++ b/src/frontend/components/ThemeToggle.tsx @@ -48,16 +48,17 @@ export function ThemeToggle() { } return ( + // Square, icon-only: it shares a row with the Abmelden button, so there + // is no room for a text label. The label moves to title/aria-label. ); } From b74b495fabbf80476215bbcf8a9047d5e04bc5c6 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 20:57:58 +0200 Subject: [PATCH 18/38] Update print view and documentation for logical feeds --- AGENTS.md | 51 +++++++---- docs/circuit-list-editor-api.md | 31 +++++-- docs/circuit-list-editor-known-limitations.md | 11 ++- docs/current-architecture.md | 20 ++++- docs/print-view.md | 52 ++++++----- docs/spec/08-current-product-backlog.md | 5 +- src/app/projects/[projectId]/print/page.tsx | 31 ++++--- src/frontend/print/print-document-model.ts | 87 ++++++++++--------- src/frontend/print/print-document.tsx | 63 +++++++++----- tests/print-document-model.test.ts | 85 +++++++++++++----- 10 files changed, 278 insertions(+), 158 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8312d55..9ef5b87 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,8 @@ See `docs/current-architecture.md` for the complete module and request flow. - Device rows inside a circuit do not have their own equipment identifiers. - Protection and cable data belong to the circuit, not to individual devices. - Device-level values include quantity, power per unit, simultaneity factor, cosPhi, room data, cost group and category. -- Circuit total power is the sum of all device rows in that circuit. +- Circuit total power is the sum of all device rows in that circuit plus the + read-only loads of logically linked downstream boards on that feeder circuit. - Existing equipment identifiers must never be changed automatically. - Renumbering is always an explicit user action. @@ -284,16 +285,19 @@ not change the project revision or undo/redo stacks. Restoring a server-stored snapshot verifies its checksum and the current-state hash, replaces supported project data atomically and records a new `restore` revision with a complete inverse command. Restore can therefore be undone and redone after a restart. -Current snapshot schema version 8 additionally stores the optional net room -area `rooms[].areaM2` (see `docs/building-structure.md`); versions 1 to 7 are -upgraded with `areaM2 = null`. Version 7 stores the project buildings and +Current snapshot schema version 9 additionally stores +`feedingDistributionBoardId` and `feedingCircuitId` on distribution boards; +versions 1 to 8 are upgraded with both references set to `null`. Version 8 +stores the optional net room area `rooms[].areaM2` (see +`docs/building-structure.md`); versions 1 to 7 are upgraded with +`areaM2 = null`. Version 7 stores the project buildings and `floors[].buildingId`; versions 1 to 6 are upgraded with no buildings and `buildingId = null`. Version 6 stores the distribution-board info fields `boardNumber`, `location`, `fedFrom` and `remark` and the project cover fields `siteAddress`, `workStage`, `projectLead` and `projectEditor`; all older supported versions are upgraded with `null` for these fields. -Stored named and automatic snapshots of every supported version (1 to 8) +Stored named and automatic snapshots of every supported version (1 to 9) remain restorable; they are upgraded while parsing. Version 5 stores the manual quantity share of every CircuitDeviceRow. Version 4 snapshots are upgraded with `manualQuantity = quantity`; they already contain the complete confirmed @@ -309,7 +313,7 @@ project graph. Project-wide Revit CSV configuration uses `external-csv-configuration.update`. Its complete expected/target snapshot is persisted through the shared project-command transaction, so create, update, -delete, Undo and Redo are revision-safe. Snapshot schema 5-8, restore and portable +delete, Undo and Redo are revision-safe. Snapshot schema 5-9, restore and portable project duplication preserve the configuration; duplication remaps its internal id and project link. The project page exposes the Revit CSV modal. It edits the complete @@ -323,7 +327,7 @@ immutable import batches with original bytes plus the classified cell matrix, normalized source-room mappings and external objects unique by `(sourceId, ifcGuid)`. Source values, planning values and overrides are separate. The general external-model repository is read-only; runtime writes belong only -to typed command adapters. Snapshot/restore and portable project transfer schema versions 5-8 +to typed command adapters. Snapshot/restore and portable project transfer schema versions 5-9 capture the complete external state and remap every internal UUID and link while preserving IFCGUIDs, source values, original bytes and the classified matrix. Import batches additionally store the monotonic project CSV configuration @@ -463,22 +467,34 @@ snapshot contains the group, optional component protections, complete circuits, circuit protections and all device-row link/override metadata. Delete re-captures and compares the subtree before cascading; restore preserves every UUID in foreign-key-safe order. -The circuit-tree read model exposes fixed `headerComponents`, group-owned +The project-wide circuit-tree read model exposes fixed `headerComponents`, group-owned `components`, `footerComponents`, optional group category/number and optional one-to-one protection DTOs for circuits and group components. These are the only supported circuit-protection source; no flat compatibility fields remain. +It resolves logical board feeds once for the complete project and adds each +downstream board's demand after its own board simultaneity factor to the chosen +feeding circuit as a read-only virtual row. Recursive chains and several boards +on one circuit are supported. A board-only link affects hierarchy but adds no +load until a feeding circuit is selected. Distribution-board floor assignment and a project-enabled supply type use `distribution-board.update`; both values are snapshot/export fields and one persistent undo step. -The same command (still schema version 1, additively extended) carries the +The same command uses schema version 2 for the logical +`feedingDistributionBoardId` and optional matching `feedingCircuitId` together +with the existing fields. Version-1 history commands remain executable and do +not change logical feed references. The command rejects self-links, cycles and +circuits from another board. The board info-card fields `boardNumber`, `location`, `fedFrom` and `remark` (migration `0007`). They are nullable, trimmed planner values; the PUT route only includes submitted info fields in the command and its inverse. An empty board with info values is no longer an unchanged setup, so history deletion of it is rejected like a changed simultaneity factor. Populated-subtree commands stored before these fields existed are normalized to `null` values -(`normalizeDistributionBoardSubtreeSnapshot`). `fedFrom` is deliberately free -text: the logical link to the feeding board/circuit is an open design decision. +(`normalizeDistributionBoardSubtreeSnapshot`). `fedFrom` remains free text for +external feeds and notes; project-board feeds use the two UUID references. +Deleting a referenced board or feeding circuit is blocked in every direct, +subtree and history-only removal path. Board copies retain their incoming feed, +and project duplication remaps both references. These fields are intended to be prefillable from Revit parameters later, but only through the Phase 14 rules (preview, explicit confirmation, no silent overwrite). @@ -521,9 +537,10 @@ Required operations: `
Nr.BezeichnungÖrtlichkeitEtageNetzGespeist von SK Pinst
[kW]
PGeräte
[kW]
P vor Vert.-GZF
[kW]
GZF
Vert.
Pgl
[kW]
Pgl inkl. UV
[kW]
IB
[A]
Σ inkl.
unterlagert [kW]
{board.location ?? "–"} {entry.summary.floorName ?? "–"} {board.supplyType ?? "–"}{board.fedFrom ?? "–"}{formatFeedingReference(entry.summary)} {entry.summary.circuitCount} {formatKilowatt(entry.summary.installedPowerKw)}{formatKilowatt(entry.summary.devicePowerKw)}{formatKilowatt(entry.summary.powerBeforeBoardSimultaneityKw)} {formatFactor(entry.summary.simultaneityFactor)} {formatKilowatt(entry.summary.demandPowerKw)} {formatCurrent(entry.summary.designCurrentA)}{formatKilowatt(entry.cumulatedDemandPowerKw)}
Summe aller Verteiler (ohne übergeordneten GZF)Summe der Einspeisungen {formatKilowatt(sum((entry) => entry.summary.installedPowerKw))}{formatKilowatt(sum((entry) => entry.summary.devicePowerKw))} - {formatKilowatt(sum((entry) => entry.summary.demandPowerKw))}{formatKilowatt(sum((entry) => + entry.parentBoardId === null + ? entry.summary.powerBeforeBoardSimultaneityKw + : 0 + ))} + {formatKilowatt(sum((entry) => + entry.parentBoardId === null ? entry.summary.demandPowerKw : 0 + ))}

- Vorläufig: „Gespeist von“ ist noch ein Freitextfeld. Struktur und - „Σ inkl. unterlagert“ werden nur über eindeutig passende Verteilernummern bzw. - -bezeichnungen zugeordnet und einfach addiert (kein übergeordneter GZF). - Mehrdeutige Angaben bleiben ohne Zuordnung. Die fachliche - Verknüpfung und Summierung folgt. + Die Struktur folgt den logischen Verknüpfungen. Eine Unterverteilung + wird im gewählten Abgang mit ihrer Leistung nach eigenem + Verteiler-GZF berücksichtigt. Ohne gewählten Abgang erscheint sie + nur in der Hierarchie.

- Pinst = Anzahl × Leistung je Stück · PGeräte = mit Geräte-GZF · - Pgl = mit Verteiler-GZF · IB = S / (√3 · {project.threePhaseVoltageV} V), - S aus cos φ je Gerätezeile + Pinst = lokale Geräte ohne GZF · P vor Vert.-GZF = + Geräte-GZF einschließlich gespeister Unterverteilungen · Pgl = + zusätzlich mit Verteiler-GZF · IB aus S und der Phasenart + des speisenden Abgangs

@@ -404,6 +408,7 @@ function ComponentRow({ component }: { component: CircuitTreeComponentDto }) { function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { const rows = circuit.deviceRows; + const downstreamBoards = circuit.downstreamBoardLoads ?? []; const circuitCells = ( <> {formatProtectionDevice(circuit.protectionDevice) ?? } @@ -414,7 +419,7 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { {circuit.remark ?? ""} ); - if (rows.length === 0) { + if (rows.length === 0 && downstreamBoards.length === 0) { return ( {circuit.equipmentIdentifier} @@ -426,7 +431,7 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { ); } - if (rows.length === 1) { + if (rows.length === 1 && downstreamBoards.length === 0) { const row = rows[0]; const title = circuit.displayName ?? row.displayName; return ( @@ -468,6 +473,16 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { ))} + {downstreamBoards.map((load) => ( + + + Unterverteilung {load.boardNumber ?? load.name} + – + + {formatKilowatt(load.activePowerKw)} + Automatisch aus der verknüpften Verteilung + + ))} ); } @@ -501,7 +516,7 @@ function BoardPlanSheet({ rows={[ ["Örtlichkeit", [board.location, summary.floorName].filter(Boolean).join(" · ") || "–"], ["Netzart", board.supplyType ?? "–"], - ["Gespeist von", board.fedFrom ?? "–"], + ["Gespeist von", formatFeedingReference(summary)], [ <>Pgl, <> @@ -542,7 +557,7 @@ function BoardPlanSheet({ Summe Verteiler (Pinst {formatKilowatt(summary.installedPowerKw)} kW) - {formatKilowatt(summary.devicePowerKw)} + {formatKilowatt(summary.powerBeforeBoardSimultaneityKw)} diff --git a/tests/print-document-model.test.ts b/tests/print-document-model.test.ts index 80a5200..ba91c3e 100644 --- a/tests/print-document-model.test.ts +++ b/tests/print-document-model.test.ts @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { assertPrintRevisionConsistency, - buildPreliminaryBoardHierarchy, + buildBoardHierarchy, + formatFeedingReference, formatCircuitCable, formatProtectionDevice, summarizePrintBoard, @@ -27,6 +28,8 @@ function board( location: null, fedFrom: null, remark: null, + feedingDistributionBoardId: null, + feedingCircuitId: null, ...info, }; } @@ -52,6 +55,8 @@ function tree( const total = deviceRows.reduce((sum, row) => sum + row.rowTotalPower, 0); return { circuitListId: "list", + distributionBoardId: "board", + distributionBoardName: "Board", currentRevision: 1, singlePhaseVoltageV: 230, threePhaseVoltageV: 400, @@ -79,7 +84,13 @@ function tree( sortOrder: 1, isReserve: false, circuitTotalPower: total, + circuitApparentPower: deviceRows.reduce( + (sum, row) => sum + row.rowTotalPower / (row.cosPhi || 1), + 0 + ), + circuitCosPhi: 1, deviceRows, + downstreamBoardLoads: [], }, ], }, @@ -117,16 +128,15 @@ describe("print document model", () => { assert.equal(formatCircuitCable(circuit), null); }); - it("does not guess a parent when feed text matches more than one board", () => { + it("does not derive hierarchy from the external free text", () => { const summaries = [ summary("a", { boardNumber: "HV" }, 2), summary("b", { name: "HV" }, 3), summary("uv", { fedFrom: " hv " }, 1), ]; for (const ordered of [summaries, [...summaries].reverse()]) { - const entries = buildPreliminaryBoardHierarchy(ordered); + const entries = buildBoardHierarchy(ordered); assert.ok(entries.every((entry) => entry.parentBoardId === null)); - assert.equal(entries.reduce((sum, entry) => sum + entry.cumulatedDemandPowerKw, 0), 6); } }); @@ -145,17 +155,39 @@ describe("print document model", () => { }); assert.equal(result.circuitCount, 1); assert.equal(result.installedPowerKw, 14); - assert.equal(result.devicePowerKw, 10); + assert.equal(result.powerBeforeBoardSimultaneityKw, 10); assert.equal(result.demandPowerKw, 5); // S = (4 / 0.8 + 6 / 1) × 0.5 = 5.5 kVA → I = 5500 / (√3 · 400) assert.ok(Math.abs(result.designCurrentA - 5500 / (Math.sqrt(3) * 400)) < 1e-9); }); - it("nests boards by matching free-text feed and sums downstream demand", () => { - const entries = buildPreliminaryBoardHierarchy([ + it("uses the selected one-phase feeder circuit for the design current", () => { + const inputTree = tree([ + { quantity: 1, powerPerUnit: 2.3, simultaneityFactor: 1, cosPhi: 1 }, + ]); + inputTree.feedingReference = { + distributionBoardId: "hv", + circuitListId: "hv-list", + distributionBoardName: "Hauptverteilung", + distributionBoardNumber: "NSHV", + circuitId: "out", + circuitEquipmentIdentifier: "-2F1.1", + circuitCategory: "single_phase", + }; + const result = summarizePrintBoard({ + board: board("uv"), + circuitListId: "uv", + floorName: null, + tree: inputTree, + }); + assert.ok(Math.abs(result.designCurrentA - 10) < 1e-9); + }); + + it("nests boards by their logical feeding references", () => { + const entries = buildBoardHierarchy([ summary("hv", { boardNumber: "HV 0.1", fedFrom: "HAK" }, 10), - summary("uv-a", { boardNumber: "UV 1.1", fedFrom: " hv 0.1 " }, 4), - summary("uv-b", { boardNumber: "UV 1.2", fedFrom: "UV 1.1" }, 2), + summary("uv-a", { boardNumber: "UV 1.1", feedingDistributionBoardId: "hv" }, 4), + summary("uv-b", { boardNumber: "UV 1.2", feedingDistributionBoardId: "uv-a" }, 2), summary("uv-c", { name: "UV-C", fedFrom: "unbekannt" }, 1), ]); assert.deepEqual( @@ -163,28 +195,37 @@ describe("print document model", () => { entry.summary.board.id, entry.depth, entry.parentBoardId, - entry.cumulatedDemandPowerKw, ]), [ - ["hv", 0, null, 16], - ["uv-a", 1, "hv", 6], - ["uv-b", 2, "uv-a", 2], - ["uv-c", 0, null, 1], + ["hv", 0, null], + ["uv-a", 1, "hv"], + ["uv-b", 2, "uv-a"], + ["uv-c", 0, null], ] ); }); - it("keeps boards with cyclic feed texts at the top level", () => { - const entries = buildPreliminaryBoardHierarchy([ - summary("a", { boardNumber: "A", fedFrom: "B" }, 1), - summary("b", { boardNumber: "B", fedFrom: "A" }, 1), + it("keeps malformed cyclic logical links visible at the top level", () => { + const entries = buildBoardHierarchy([ + summary("a", { boardNumber: "A", feedingDistributionBoardId: "b" }, 1), + summary("b", { boardNumber: "B", feedingDistributionBoardId: "a" }, 1), ]); assert.equal(entries.length, 2); assert.ok(entries.some((entry) => entry.parentBoardId === null)); - assert.equal( - entries.reduce((sum, entry) => sum + (entry.depth === 0 ? entry.cumulatedDemandPowerKw : 0), 0), - 2 - ); + }); + + it("formats the resolved feeding board and circuit instead of free text", () => { + const value = summary("uv", { fedFrom: "Alttext" }, 1); + value.tree.feedingReference = { + distributionBoardId: "hv", + circuitListId: "hv-list", + distributionBoardName: "Hauptverteilung", + distributionBoardNumber: "NSHV", + circuitId: "out", + circuitEquipmentIdentifier: "-3F1.1", + circuitCategory: "three_phase", + }; + assert.equal(formatFeedingReference(value), "NSHV-3F1.1"); }); it("formats protection devices for the plan table", () => { From 5073d9342a287ec6d961f53b5178b7ca344ef3f2 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Mon, 28 Sep 2026 21:30:30 +0200 Subject: [PATCH 19/38] Harden authentication and put filter toggle and fields in one row Security: per-username login throttling, constant-time unknown-user check, Sec-Fetch-Site CSRF guard for writes, session rotation on login and password change, absolute session lifetime, sessions ended on reset and deactivation, last-admin protection, input length caps, ASCII usernames, clickjacking headers. Covered by tests/authentication.test.ts. Filter panel: toggle, fields and count share one row to save space. Co-Authored-By: Claude Opus 5.5 --- compose.yaml | 1 + docs/authentication.md | 28 ++- next.config.mjs | 16 ++ src/app/globals.css | 21 +- src/domain/services/user.service.ts | 67 +++++- src/frontend/components/filter-panel.tsx | 47 ++-- src/server/auth/auth-config.ts | 23 +- src/server/auth/auth.middleware.ts | 48 +++- src/server/auth/cookie.ts | 7 +- src/server/auth/login-throttle.ts | 53 +++++ src/server/auth/sessions.ts | 60 ++++- src/server/composition/auth.ts | 5 +- src/server/controllers/auth.controller.ts | 47 ++-- src/server/controllers/user.controller.ts | 32 ++- src/server/index.ts | 8 +- src/shared/validation/auth.schemas.ts | 13 +- src/shared/validation/user.schemas.ts | 23 +- tests/authentication.test.ts | 265 ++++++++++++++++++++++ 18 files changed, 683 insertions(+), 81 deletions(-) create mode 100644 src/server/auth/login-throttle.ts create mode 100644 tests/authentication.test.ts diff --git a/compose.yaml b/compose.yaml index bab8c3d..2a2eecd 100644 --- a/compose.yaml +++ b/compose.yaml @@ -51,6 +51,7 @@ services: AUTH_BOOTSTRAP_USERNAME: "${AUTH_BOOTSTRAP_USERNAME:-}" AUTH_BOOTSTRAP_PASSWORT: "${AUTH_BOOTSTRAP_PASSWORT:-}" AUTH_SESSION_HOURS: "${AUTH_SESSION_HOURS:-12}" + AUTH_SESSION_MAX_DAYS: "${AUTH_SESSION_MAX_DAYS:-7}" COOKIE_SECURE: "${COOKIE_SECURE:-false}" # Nicht auf dem Host veroeffentlicht: die API wird ueber den # Next.js-Rewrite im Web-Dienst erreicht. diff --git a/docs/authentication.md b/docs/authentication.md index 3d197cf..13a9f72 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -33,7 +33,8 @@ Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. `username`, `passwordHash` (scrypt, `src/server/auth/password.ts`), `name`, `role`, `active`, `mustChangePassword`. - **Sessions:** In-Memory-Store (`src/server/auth/sessions.ts`), Cookie - `lb_session`, sliding expiry (`AUTH_SESSION_HOURS`, Standard 12h). Ein + `lb_session`, sliding expiry (`AUTH_SESSION_HOURS`, Standard 12h) mit + absoluter Obergrenze (`AUTH_SESSION_MAX_DAYS`, Standard 7). Ein Neustart der API beendet alle Sessions – für einen Single-Container-Dienst ein akzeptabler Kompromiss gegenüber einer persistierten Session-Tabelle. - **Middleware:** `src/server/auth/auth.middleware.ts` schützt `/api/*` @@ -44,6 +45,28 @@ Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. (`src/app/layout.tsx`) zeigt Login- bzw. Passwortformular, solange nicht angemeldet bzw. `mustChangePassword` gesetzt ist, sonst die App. +## Schutzmechanismen + +| Angriff | Schutz | +|---|---| +| Passwort-Raten (online) | `LoginThrottle`: 5 Fehlversuche je Anmeldename in 15 min → HTTP 429 bis das Fenster abläuft. Schlüssel ist der Name, nicht die IP (alle Anfragen kommen über den Next-Rewrite mit derselben Quell-IP). | +| Passwort-Raten (offline, DB-Diebstahl) | scrypt (N=16384, r=8, p=1), eigenes Salt je Hash | +| Nutzernamen ausspähen (Timing) | Unbekannte Namen werden gegen einen festen Dummy-Hash geprüft – immer genau ein scrypt-Lauf; einheitliche Fehlermeldung | +| CSRF | SameSite=Lax **plus** `requireSameOriginForWrites`: schreibende Anfragen nur mit `Sec-Fetch-Site: same-origin`. Nötig, weil andere Dienste auf demselben Host (andere Ports) als „same-site“ gelten | +| Session-Fixation | Neue Session-ID bei jedem Login und nach jedem Passwortwechsel | +| Gestohlenes Cookie | httpOnly; gleitende Laufzeit (`AUTH_SESSION_HOURS`, 12 h) **und** harte Obergrenze (`AUTH_SESSION_MAX_DAYS`, 7 Tage) | +| Kompromittiertes Konto | Passwort-Reset und Deaktivieren beenden sofort alle Sessions des Kontos; Passwortwechsel beendet alle anderen | +| Aussperren | Der letzte aktive Admin kann weder herabgestuft noch deaktiviert werden; eigener Zugang ist in der Liste gesperrt | +| Rechteausweitung / Mass Assignment | Rolle kommt aus der DB, nie aus der Anfrage; zod-Schemas mit `.strict()` | +| DoS über riesige Passwörter | Längengrenzen (Name 100, Passwort 200 Zeichen) vor scrypt | +| Look-alike-Namen | Anmeldename nur `a-z 0-9 . _ @ -`, klein geschrieben | +| Clickjacking | `X-Frame-Options: SAMEORIGIN`, `frame-ancestors 'self'` (next.config.mjs) | +| Speicherwachstum | Max. 20 Sessions je Nutzer, periodisches Aufräumen abgelaufener Sessions, Throttle-Tabelle begrenzt | + +**Nicht durch Code lösbar:** Ohne TLS gehen Passwort und Session-Cookie im +Klartext durchs Netz. Für Zugriff außerhalb des LANs HTTPS über einen +Reverse-Proxy vorschalten und `COOKIE_SECURE=true` setzen. + ## Bootstrap-Admin `AUTH_BOOTSTRAP_USERNAME` / `AUTH_BOOTSTRAP_PASSWORT` (Env-Variablen, siehe @@ -56,6 +79,7 @@ in `compose.yaml` selbst. ## Bewusst nicht umgesetzt (Stand jetzt) - Konfigurierbare Rechte-Matrix statt fixer `admin`/`user`-Rollen -- Konten-Sperre nach Fehlversuchen +- Dauerhafte Konten-Sperre nach Fehlversuchen (es gibt nur die zeitlich + begrenzte Drosselung, siehe oben) - E-Mail-/Einmal-Link-Passwortvergabe, OIDC/Entra-Anmeldung - Verknüpfung von Zugängen mit einer Mitarbeiter-Stammdatentabelle diff --git a/next.config.mjs b/next.config.mjs index e0610b9..a6cb01e 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -11,6 +11,22 @@ const nextConfig = { typescript: { tsconfigPath: "./tsconfig.next.json", }, + poweredByHeader: false, + // Clickjacking: the Config pages hold admin actions, so no foreign page + // may frame the app. Same-origin framing stays allowed. + async headers() { + return [ + { + source: "/:path*", + headers: [ + { key: "X-Frame-Options", value: "SAMEORIGIN" }, + { key: "Content-Security-Policy", value: "frame-ancestors 'self'" }, + { key: "X-Content-Type-Options", value: "nosniff" }, + { key: "Referrer-Policy", value: "same-origin" }, + ], + }, + ]; + }, async rewrites() { return [ { diff --git a/src/app/globals.css b/src/app/globals.css index fec2745..0f1a642 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -452,13 +452,25 @@ a { background: var(--color-bg); } -.filter-panel-header { +.filter-panel-row { display: flex; align-items: center; gap: 10px; } -.filter-panel-header .filter-panel-toggle { +/* Expanded: the fields carry a label above their input, so toggle and + count sit on the input line (bottom) instead of the label line. */ +.filter-panel-row-expanded { + align-items: flex-end; +} + +.filter-panel-row-expanded .filter-panel-toggle, +.filter-panel-row-expanded .filter-panel-count { + margin-bottom: calc((2.1rem - 24px) / 2); +} + +.filter-panel-row .filter-panel-toggle { + flex: 0 0 auto; width: 24px; height: 24px; padding: 0; @@ -468,7 +480,7 @@ a { color: var(--color-ink-soft); } -.filter-panel-header .filter-panel-toggle:hover { +.filter-panel-row .filter-panel-toggle:hover { background: var(--color-surface); } @@ -503,10 +515,11 @@ a { .filter-bar { display: flex; + flex: 1 1 auto; + min-width: 0; flex-wrap: wrap; align-items: flex-end; gap: var(--space-sm) var(--space-md); - margin-top: 0.5rem; } .filter-bar-field, diff --git a/src/domain/services/user.service.ts b/src/domain/services/user.service.ts index 55720c1..0968d02 100644 --- a/src/domain/services/user.service.ts +++ b/src/domain/services/user.service.ts @@ -24,7 +24,29 @@ export class WrongPasswordError extends Error { } } +export class PasswordUnchangedError extends Error { + constructor() { + super("Das neue Passwort muss sich vom bisherigen unterscheiden."); + } +} + +export class LastAdminError extends Error { + constructor() { + super("Es muss mindestens ein aktiver Administrator bleiben."); + } +} + +function isUniqueConstraintError(error: unknown): boolean { + return ( + error instanceof Error && + "code" in error && + (error as { code?: unknown }).code === "SQLITE_CONSTRAINT_UNIQUE" + ); +} + export class UserService { + private dummyHash: Promise | null = null; + constructor( private readonly repository: UserRepository, private readonly authConfig: AuthConfig @@ -38,6 +60,9 @@ export class UserService { * escape hatch instead of a standing backdoor. */ async ensureBootstrapAdmin(): Promise { + // Warm the dummy hash at startup so even the first unknown-user login + // costs one scrypt run, not two. + await this.getDummyHash(); if (!this.authConfig.bootstrap) return; const existingCount = await this.repository.count(); if (existingCount > 0) return; @@ -55,9 +80,10 @@ export class UserService { async authenticate(username: string, password: string) { const user = await this.repository.findByUsername(username); - // Always hash something, even for an unknown user: otherwise the - // response time would leak which usernames exist. - const passwordHash = user?.passwordHash ?? (await hashPassword("placeholder")); + // Unknown users are verified against a fixed dummy hash: exactly one + // scrypt run either way, so response time doesn't reveal which usernames + // exist. + const passwordHash = user?.passwordHash ?? (await this.getDummyHash()); const passwordMatches = await verifyPassword(password, passwordHash); if (!user || !user.active || !passwordMatches) { throw new InvalidCredentialsError(); @@ -74,15 +100,32 @@ export class UserService { const existing = await this.repository.findByUsername(input.username); if (existing) throw new UsernameTakenError(); const passwordHash = await hashPassword(input.initialPassword); - return this.repository.create({ - username: input.username, - name: input.name, - role: input.role, - passwordHash, - }); + try { + return await this.repository.create({ + username: input.username, + name: input.name, + role: input.role, + passwordHash, + }); + } catch (error) { + // Two admins creating the same name at once: the unique index decides. + if (isUniqueConstraintError(error)) throw new UsernameTakenError(); + throw error; + } } async updateRoleAndActive(userId: string, patch: { role?: UserRole; active?: boolean }) { + const removesAdmin = patch.role === "user" || patch.active === false; + if (removesAdmin) { + const target = await this.repository.findById(userId); + const targetIsActiveAdmin = target?.role === "admin" && target.active; + if (targetIsActiveAdmin) { + const activeAdmins = (await this.repository.list()).filter( + (user) => user.role === "admin" && user.active + ); + if (activeAdmins.length <= 1) throw new LastAdminError(); + } + } return this.repository.updateRoleAndActive(userId, patch); } @@ -98,7 +141,13 @@ export class UserService { if (!user) throw new WrongPasswordError(); const currentMatches = await verifyPassword(currentPassword, user.passwordHash); if (!currentMatches) throw new WrongPasswordError(); + if (newPassword === currentPassword) throw new PasswordUnchangedError(); const passwordHash = await hashPassword(newPassword); return this.repository.setPassword(userId, passwordHash, false); } + + private getDummyHash(): Promise { + this.dummyHash ??= hashPassword("dummy-password-for-constant-time-login"); + return this.dummyHash; + } } diff --git a/src/frontend/components/filter-panel.tsx b/src/frontend/components/filter-panel.tsx index afa1fde..9c9923b 100644 --- a/src/frontend/components/filter-panel.tsx +++ b/src/frontend/components/filter-panel.tsx @@ -55,9 +55,15 @@ export function CollapsibleFilterPanel({ writeCollapsed(storageKey, next); } + // One row: toggle, then either the "Filter" label (collapsed) or the filter + // fields themselves (expanded), and the count at the right edge. return (
-
+
- Filter - {isCollapsed && isFilterActive ? ( - Filter aktiv - ) : null} + {isCollapsed ? ( + <> + Filter + {isFilterActive ? Filter aktiv : null} + + ) : ( +
+ {children} + {isFilterActive ? ( + + ) : null} +
+ )} {visibleCount} von {totalCount}
- {isCollapsed ? null : ( -
- {children} - {isFilterActive ? ( - - ) : null} -
- )}
); } diff --git a/src/server/auth/auth-config.ts b/src/server/auth/auth-config.ts index d2157f4..c4c3b44 100644 --- a/src/server/auth/auth-config.ts +++ b/src/server/auth/auth-config.ts @@ -1,9 +1,13 @@ export const SESSION_COOKIE = "lb_session"; const DEFAULT_SESSION_HOURS = 12; +const DEFAULT_SESSION_MAX_DAYS = 7; export interface AuthConfig { + /** Idle timeout; slides forward on activity. */ sessionTtlMs: number; + /** Hard upper bound for a session, regardless of activity. */ + sessionMaxAgeMs: number; cookieSecure: boolean; /** * Only used to create the very first admin when the users table is still @@ -15,11 +19,21 @@ export interface AuthConfig { export class AuthConfigError extends Error {} -export function readAuthConfig(env: NodeJS.ProcessEnv = process.env): AuthConfig { - const hours = Number(env.AUTH_SESSION_HOURS ?? DEFAULT_SESSION_HOURS); - if (!Number.isFinite(hours) || hours <= 0) { - throw new AuthConfigError("AUTH_SESSION_HOURS must be a positive number."); +function positiveNumber(raw: string | undefined, fallback: number, name: string): number { + const value = Number(raw ?? fallback); + if (!Number.isFinite(value) || value <= 0) { + throw new AuthConfigError(`${name} must be a positive number.`); } + return value; +} + +export function readAuthConfig(env: NodeJS.ProcessEnv = process.env): AuthConfig { + const hours = positiveNumber(env.AUTH_SESSION_HOURS, DEFAULT_SESSION_HOURS, "AUTH_SESSION_HOURS"); + const maxDays = positiveNumber( + env.AUTH_SESSION_MAX_DAYS, + DEFAULT_SESSION_MAX_DAYS, + "AUTH_SESSION_MAX_DAYS" + ); const bootstrapUsername = (env.AUTH_BOOTSTRAP_USERNAME ?? "").trim().toLowerCase(); const bootstrapPassword = env.AUTH_BOOTSTRAP_PASSWORT ?? ""; @@ -36,6 +50,7 @@ export function readAuthConfig(env: NodeJS.ProcessEnv = process.env): AuthConfig return { sessionTtlMs: hours * 60 * 60 * 1000, + sessionMaxAgeMs: maxDays * 24 * 60 * 60 * 1000, cookieSecure: (env.COOKIE_SECURE ?? "").trim().toLowerCase() === "true", bootstrap: bootstrapUsername ? { username: bootstrapUsername, password: bootstrapPassword } diff --git a/src/server/auth/auth.middleware.ts b/src/server/auth/auth.middleware.ts index 53a1767..ce65bfb 100644 --- a/src/server/auth/auth.middleware.ts +++ b/src/server/auth/auth.middleware.ts @@ -46,17 +46,55 @@ export async function identityFromRequest( }; } -export function cookieOptions(authConfig: AuthConfig) { +export function cookieOptions(authConfig: AuthConfig, maxAgeMs: number) { return { httpOnly: true, sameSite: "lax" as const, secure: authConfig.cookieSecure, path: "/", - maxAge: authConfig.sessionTtlMs, + maxAge: maxAgeMs, }; } -/** Protects /api. Only the login route and the status check stay reachable without a session. */ +/** Sets the session cookie with the same remaining lifetime the server uses. */ +export function setSessionCookie( + res: Response, + authConfig: AuthConfig, + sessions: SessionStore, + sessionId: string +): void { + const session = sessions.get(sessionId, false); + if (!session) return; + res.cookie(SESSION_COOKIE, sessionId, cookieOptions(authConfig, sessions.remainingMs(session))); +} + +const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); + +/** + * CSRF defense for cookie-authenticated writes. + * + * SameSite=Lax alone is not enough here: every other service on the same + * host (other ports of the same IP) counts as "same-site" and would get the + * cookie attached. Browsers send Sec-Fetch-Site on every request, so a write + * is only accepted from the app's own origin. Clients without the header + * (curl, scripts) carry no ambient browser cookie and are not a CSRF vector. + */ +export function requireSameOriginForWrites(): RequestHandler { + return (req: Request, res: Response, next: NextFunction) => { + if (SAFE_METHODS.has(req.method)) { + next(); + return; + } + const fetchSite = req.headers["sec-fetch-site"]; + if (fetchSite === undefined || fetchSite === "same-origin" || fetchSite === "none") { + next(); + return; + } + res.status(403).json({ error: "Anfrage von fremder Herkunft abgelehnt." }); + }; +} + +/** Protects /api. Only login, status and logout stay reachable without a session. */ export function createAuthGuard( authConfig: AuthConfig, sessions: SessionStore, @@ -76,9 +114,7 @@ export function createAuthGuard( } req.authUser = identity; const sessionId = sessionIdFromRequest(req); - if (sessionId) { - res.cookie(SESSION_COOKIE, sessionId, cookieOptions(authConfig)); - } + if (sessionId) setSessionCookie(res, authConfig, sessions, sessionId); next(); }) .catch(next); diff --git a/src/server/auth/cookie.ts b/src/server/auth/cookie.ts index 0204ca3..344ff65 100644 --- a/src/server/auth/cookie.ts +++ b/src/server/auth/cookie.ts @@ -9,7 +9,12 @@ export function readCookie( if (separatorIndex === -1) continue; const key = part.slice(0, separatorIndex).trim(); if (key !== name) continue; - return decodeURIComponent(part.slice(separatorIndex + 1).trim()); + // A malformed value must read as "no session", not throw into a 500. + try { + return decodeURIComponent(part.slice(separatorIndex + 1).trim()); + } catch { + return undefined; + } } return undefined; } diff --git a/src/server/auth/login-throttle.ts b/src/server/auth/login-throttle.ts new file mode 100644 index 0000000..d81719b --- /dev/null +++ b/src/server/auth/login-throttle.ts @@ -0,0 +1,53 @@ +/** + * Slows down online password guessing per username. + * + * Keyed by username, not by client IP: every request reaches the API through + * the Next.js rewrite, so the socket address is always the web container. + * The trade-off is that someone who knows a username can keep that account + * temporarily throttled; the block lifts by itself after the window, so it is + * a nuisance, not a lockout. + */ +export class LoginThrottle { + private readonly failures = new Map(); + + constructor( + private readonly maxFailures = 5, + private readonly windowMs = 15 * 60 * 1000, + private readonly maxTrackedKeys = 10_000, + private readonly now: () => number = Date.now + ) {} + + /** Milliseconds until another attempt is allowed; 0 = allowed now. */ + retryAfterMs(username: string): number { + const recent = this.recentFailures(this.key(username)); + if (recent.length < this.maxFailures) return 0; + return Math.max(0, recent[0] + this.windowMs - this.now()); + } + + recordFailure(username: string): void { + const key = this.key(username); + const recent = this.recentFailures(key); + recent.push(this.now()); + if (!this.failures.has(key) && this.failures.size >= this.maxTrackedKeys) { + // Bound memory under a flood of random usernames: drop the oldest key. + const oldestKey = this.failures.keys().next().value; + if (oldestKey !== undefined) this.failures.delete(oldestKey); + } + this.failures.set(key, recent); + } + + recordSuccess(username: string): void { + this.failures.delete(this.key(username)); + } + + private recentFailures(key: string): number[] { + const cutoff = this.now() - this.windowMs; + const recent = (this.failures.get(key) ?? []).filter((time) => time > cutoff); + if (recent.length === 0) this.failures.delete(key); + return recent; + } + + private key(username: string): string { + return username.trim().toLowerCase(); + } +} diff --git a/src/server/auth/sessions.ts b/src/server/auth/sessions.ts index 501f4c4..9ee1fe0 100644 --- a/src/server/auth/sessions.ts +++ b/src/server/auth/sessions.ts @@ -3,24 +3,50 @@ import { randomUUID } from "node:crypto"; interface Session { id: string; userId: string; + createdAt: number; expiresAt: number; } +const MAX_SESSIONS_PER_USER = 20; +const SWEEP_INTERVAL_MS = 10 * 60 * 1000; + /** * In-memory session store. The API runs as a single container/process, so a * restart clearing every session is an acceptable trade-off for the * simplicity of not needing a persisted session table. + * + * Sessions slide forward on activity (`idleTtlMs`) but never outlive + * `absoluteTtlMs` - otherwise a stolen cookie could be kept alive forever. */ export class SessionStore { private readonly sessions = new Map(); - constructor(private readonly ttlMs: number) {} + constructor( + private readonly idleTtlMs: number, + private readonly absoluteTtlMs: number, + private readonly now: () => number = Date.now + ) {} + + /** Removes expired sessions; unreferenced ones would otherwise pile up. */ + startSweeping(): void { + setInterval(() => this.sweep(), SWEEP_INTERVAL_MS).unref(); + } + + sweep(): void { + const now = this.now(); + for (const [id, session] of this.sessions) { + if (this.isExpired(session, now)) this.sessions.delete(id); + } + } create(userId: string): Session { + this.enforcePerUserLimit(userId); + const now = this.now(); const session: Session = { id: randomUUID(), userId, - expiresAt: Date.now() + this.ttlMs, + createdAt: now, + expiresAt: Math.min(now + this.idleTtlMs, now + this.absoluteTtlMs), }; this.sessions.set(session.id, session); return session; @@ -31,20 +57,28 @@ export class SessionStore { if (!sessionId) return undefined; const session = this.sessions.get(sessionId); if (!session) return undefined; - if (session.expiresAt < Date.now()) { + const now = this.now(); + if (this.isExpired(session, now)) { this.sessions.delete(sessionId); return undefined; } - if (slideExpiry) session.expiresAt = Date.now() + this.ttlMs; + if (slideExpiry) { + session.expiresAt = Math.min(now + this.idleTtlMs, session.createdAt + this.absoluteTtlMs); + } return session; } + /** Remaining lifetime, used as cookie max-age so browser and server agree. */ + remainingMs(session: Session): number { + return Math.max(0, session.expiresAt - this.now()); + } + destroy(sessionId: string | undefined): void { if (!sessionId) return; this.sessions.delete(sessionId); } - /** Ends every other session for a user, e.g. after a password change. */ + /** Ends every session of a user, optionally except one (e.g. the caller's own). */ destroyAllForUser(userId: string, exceptSessionId?: string): void { for (const [id, session] of this.sessions) { if (session.userId === userId && id !== exceptSessionId) { @@ -52,4 +86,20 @@ export class SessionStore { } } } + + private isExpired(session: Session, now: number): boolean { + return session.expiresAt <= now || session.createdAt + this.absoluteTtlMs <= now; + } + + // Oldest sessions go first, so a legitimate user logging in on a new + // device is never refused - only memory growth is bounded. + private enforcePerUserLimit(userId: string): void { + const own = [...this.sessions.values()] + .filter((session) => session.userId === userId) + .sort((a, b) => a.createdAt - b.createdAt); + while (own.length >= MAX_SESSIONS_PER_USER) { + const oldest = own.shift(); + if (oldest) this.sessions.delete(oldest.id); + } + } } diff --git a/src/server/composition/auth.ts b/src/server/composition/auth.ts index 751f324..1b5ce09 100644 --- a/src/server/composition/auth.ts +++ b/src/server/composition/auth.ts @@ -1,8 +1,11 @@ import { readAuthConfig } from "../auth/auth-config.js"; +import { LoginThrottle } from "../auth/login-throttle.js"; import { SessionStore } from "../auth/sessions.js"; import { UserService } from "../../domain/services/user.service.js"; import { userRepository } from "./application-repositories.js"; export const authConfig = readAuthConfig(); -export const sessionStore = new SessionStore(authConfig.sessionTtlMs); +export const sessionStore = new SessionStore(authConfig.sessionTtlMs, authConfig.sessionMaxAgeMs); +sessionStore.startSweeping(); +export const loginThrottle = new LoginThrottle(); export const userService = new UserService(userRepository, authConfig); diff --git a/src/server/controllers/auth.controller.ts b/src/server/controllers/auth.controller.ts index 9dabee5..5eaf699 100644 --- a/src/server/controllers/auth.controller.ts +++ b/src/server/controllers/auth.controller.ts @@ -1,11 +1,16 @@ import type { Request, Response } from "express"; import { changePasswordSchema, loginSchema } from "../../shared/validation/auth.schemas.js"; -import { InvalidCredentialsError, WrongPasswordError } from "../../domain/services/user.service.js"; -import { authConfig, sessionStore, userService } from "../composition/auth.js"; +import { + InvalidCredentialsError, + PasswordUnchangedError, + WrongPasswordError, +} from "../../domain/services/user.service.js"; +import { authConfig, loginThrottle, sessionStore, userService } from "../composition/auth.js"; import { cookieOptions, identityFromRequest, sessionIdFromRequest, + setSessionCookie, } from "../auth/auth.middleware.js"; import { SESSION_COOKIE } from "../auth/auth-config.js"; import { userRepository } from "../composition/application-repositories.js"; @@ -13,9 +18,7 @@ import { userRepository } from "../composition/application-repositories.js"; export async function getAuthStatus(req: Request, res: Response) { const identity = await identityFromRequest(req, sessionStore, userRepository); const sessionId = sessionIdFromRequest(req); - if (identity && sessionId) { - res.cookie(SESSION_COOKIE, sessionId, cookieOptions(authConfig)); - } + if (identity && sessionId) setSessionCookie(res, authConfig, sessionStore, sessionId); res.json({ signedIn: Boolean(identity), mustChangePassword: identity?.mustChangePassword ?? false, @@ -28,13 +31,29 @@ export async function login(req: Request, res: Response) { res.status(401).json({ error: "Anmeldung fehlgeschlagen." }); return; } + const { username, password } = parsed.data; + + const retryAfterMs = loginThrottle.retryAfterMs(username); + if (retryAfterMs > 0) { + res.setHeader("Retry-After", Math.ceil(retryAfterMs / 1000).toString()); + res.status(429).json({ + error: "Zu viele Fehlversuche. Bitte in einigen Minuten erneut versuchen.", + }); + return; + } + try { - const user = await userService.authenticate(parsed.data.username, parsed.data.password); + const user = await userService.authenticate(username, password); + loginThrottle.recordSuccess(username); + // A fresh session id on every login: an id planted before login + // (session fixation) never becomes authenticated. + sessionStore.destroy(sessionIdFromRequest(req)); const session = sessionStore.create(user.id); - res.cookie(SESSION_COOKIE, session.id, cookieOptions(authConfig)); + setSessionCookie(res, authConfig, sessionStore, session.id); res.json({ signedIn: true, mustChangePassword: user.mustChangePassword }); } catch (error) { if (error instanceof InvalidCredentialsError) { + loginThrottle.recordFailure(username); res.status(401).json({ error: error.message }); return; } @@ -59,7 +78,7 @@ export async function changePassword(req: Request, res: Response) { } const parsed = changePasswordSchema.safeParse(req.body); if (!parsed.success) { - res.status(400).json({ error: parsed.error.flatten() }); + res.status(400).json({ error: "Das neue Passwort muss 8 bis 200 Zeichen lang sein." }); return; } try { @@ -69,20 +88,22 @@ export async function changePassword(req: Request, res: Response) { parsed.data.newPassword ); } catch (error) { - if (error instanceof WrongPasswordError) { + if (error instanceof WrongPasswordError || error instanceof PasswordUnchangedError) { res.status(400).json({ error: error.message }); return; } throw error; } - // A password change invalidates every other session of this account; the - // current one stays so the change doesn't log the user out themselves. - sessionStore.destroyAllForUser(identity.id, sessionIdFromRequest(req)); + // Every session of this account ends - including the current one, which is + // replaced by a fresh id so the user stays signed in on this device only. + sessionStore.destroyAllForUser(identity.id); + const session = sessionStore.create(identity.id); + setSessionCookie(res, authConfig, sessionStore, session.id); res.json({ changed: true }); } export function logout(req: Request, res: Response) { sessionStore.destroy(sessionIdFromRequest(req)); - res.clearCookie(SESSION_COOKIE, { ...cookieOptions(authConfig), maxAge: undefined }); + res.clearCookie(SESSION_COOKIE, { ...cookieOptions(authConfig, 0), maxAge: undefined }); res.json({ signedOut: true }); } diff --git a/src/server/controllers/user.controller.ts b/src/server/controllers/user.controller.ts index 0ad3cbc..bdf8d0f 100644 --- a/src/server/controllers/user.controller.ts +++ b/src/server/controllers/user.controller.ts @@ -1,11 +1,12 @@ import type { Request, Response } from "express"; +import type { ZodError } from "zod"; import { createUserSchema, resetPasswordSchema, updateUserSchema, } from "../../shared/validation/user.schemas.js"; -import { UsernameTakenError } from "../../domain/services/user.service.js"; -import { userService } from "../composition/auth.js"; +import { LastAdminError, UsernameTakenError } from "../../domain/services/user.service.js"; +import { sessionStore, userService } from "../composition/auth.js"; import { userRepository } from "../composition/application-repositories.js"; // The password hash never leaves this layer. @@ -29,6 +30,10 @@ function toDto(user: { }; } +function firstIssue(error: ZodError): string { + return error.issues[0]?.message ?? "Ungültige Eingabe."; +} + export async function listUsers(_req: Request, res: Response) { const rows = await userRepository.list(); res.json(rows.map(toDto)); @@ -37,7 +42,7 @@ export async function listUsers(_req: Request, res: Response) { export async function createUser(req: Request, res: Response) { const parsed = createUserSchema.safeParse(req.body); if (!parsed.success) { - res.status(400).json({ error: parsed.error.flatten() }); + res.status(400).json({ error: firstIssue(parsed.error) }); return; } try { @@ -64,7 +69,7 @@ export async function updateUser(req: Request, res: Response) { } const parsed = updateUserSchema.safeParse(req.body); if (!parsed.success) { - res.status(400).json({ error: parsed.error.flatten() }); + res.status(400).json({ error: firstIssue(parsed.error) }); return; } // The signed-in admin can't lock themselves out by deactivating or @@ -78,8 +83,18 @@ export async function updateUser(req: Request, res: Response) { res.status(404).json({ error: "Benutzer nicht gefunden." }); return; } - const updated = await userService.updateRoleAndActive(userId, parsed.data); - res.json(updated ? toDto(updated) : null); + try { + const updated = await userService.updateRoleAndActive(userId, parsed.data); + // Deactivation takes effect immediately, not just at the next login. + if (parsed.data.active === false) sessionStore.destroyAllForUser(userId); + res.json(updated ? toDto(updated) : null); + } catch (error) { + if (error instanceof LastAdminError) { + res.status(400).json({ error: error.message }); + return; + } + throw error; + } } export async function resetUserPassword(req: Request, res: Response) { @@ -90,7 +105,7 @@ export async function resetUserPassword(req: Request, res: Response) { } const parsed = resetPasswordSchema.safeParse(req.body); if (!parsed.success) { - res.status(400).json({ error: parsed.error.flatten() }); + res.status(400).json({ error: firstIssue(parsed.error) }); return; } const existing = await userRepository.findById(userId); @@ -99,5 +114,8 @@ export async function resetUserPassword(req: Request, res: Response) { return; } const updated = await userService.resetPassword(userId, parsed.data.newPassword); + // A reset is usually a response to a suspected compromise: every open + // session of that account ends now. + sessionStore.destroyAllForUser(userId); res.json(updated ? toDto(updated) : null); } diff --git a/src/server/index.ts b/src/server/index.ts index 868de79..9a65ce0 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,7 +7,11 @@ import { cableSizingRouter } from "./routes/cable-sizing.routes.js"; import { authRouter } from "./routes/auth.routes.js"; import { userRouter } from "./routes/user.routes.js"; import { errorMiddleware } from "./middleware/error.middleware.js"; -import { createAuthGuard, requirePasswordChanged } from "./auth/auth.middleware.js"; +import { + createAuthGuard, + requirePasswordChanged, + requireSameOriginForWrites, +} from "./auth/auth.middleware.js"; import { authConfig, sessionStore, userService } from "./composition/auth.js"; import { userRepository } from "./composition/application-repositories.js"; import { createLogger, toErrorMeta } from "../shared/logging/logger.js"; @@ -19,6 +23,7 @@ const port = Number(process.env.PORT || 3000); const heartbeatIntervalMs = 5 * 60 * 1000; const shutdownTimeoutMs = 15 * 1000; +app.disable("x-powered-by"); app.use(express.json({ limit: "25mb" })); app.use((req, res, next) => { @@ -59,6 +64,7 @@ app.get("/health", (_req, res) => { // /auth/login, /auth/status and /auth/logout (see createAuthGuard's // openPaths). authRouter is mounted AFTER the guard (not before) so that // /auth/me and /auth/change-password still get req.authUser populated by it. +app.use("/api", requireSameOriginForWrites()); app.use("/api", createAuthGuard(authConfig, sessionStore, userRepository)); app.use("/api", requirePasswordChanged()); diff --git a/src/shared/validation/auth.schemas.ts b/src/shared/validation/auth.schemas.ts index 544b052..7d95eec 100644 --- a/src/shared/validation/auth.schemas.ts +++ b/src/shared/validation/auth.schemas.ts @@ -1,15 +1,20 @@ import { z } from "zod"; +// Upper bounds keep a huge request body from being fed into scrypt. +export const MAX_USERNAME_LENGTH = 100; +export const MAX_PASSWORD_LENGTH = 200; +export const MIN_PASSWORD_LENGTH = 8; + export const loginSchema = z .object({ - username: z.string().trim().min(1), - password: z.string().min(1), + username: z.string().trim().min(1).max(MAX_USERNAME_LENGTH), + password: z.string().min(1).max(MAX_PASSWORD_LENGTH), }) .strict(); export const changePasswordSchema = z .object({ - currentPassword: z.string().min(1), - newPassword: z.string().min(8).max(200), + currentPassword: z.string().min(1).max(MAX_PASSWORD_LENGTH), + newPassword: z.string().min(MIN_PASSWORD_LENGTH).max(MAX_PASSWORD_LENGTH), }) .strict(); diff --git a/src/shared/validation/user.schemas.ts b/src/shared/validation/user.schemas.ts index ceb8961..cec4c5f 100644 --- a/src/shared/validation/user.schemas.ts +++ b/src/shared/validation/user.schemas.ts @@ -1,14 +1,29 @@ import { z } from "zod"; import { USER_ROLES } from "../constants/user-roles.js"; +import { + MAX_PASSWORD_LENGTH, + MAX_USERNAME_LENGTH, + MIN_PASSWORD_LENGTH, +} from "./auth.schemas.js"; -const MIN_PASSWORD_LENGTH = 8; +// ASCII only: rules out look-alike Unicode names ("admіn" with a Cyrillic i) +// and invisible whitespace. E-mail addresses fit this pattern. +const USERNAME_PATTERN = /^[a-z0-9._@-]+$/; export const createUserSchema = z .object({ - username: z.string().trim().min(1).max(200), + username: z + .string() + .trim() + .toLowerCase() + .min(1) + .max(MAX_USERNAME_LENGTH) + .regex(USERNAME_PATTERN, { + message: "Anmeldename: nur a-z, 0-9 sowie . _ @ - erlaubt.", + }), name: z.string().trim().min(1).max(200), role: z.enum(USER_ROLES), - initialPassword: z.string().min(MIN_PASSWORD_LENGTH).max(200), + initialPassword: z.string().min(MIN_PASSWORD_LENGTH).max(MAX_PASSWORD_LENGTH), }) .strict(); @@ -24,7 +39,7 @@ export const updateUserSchema = z export const resetPasswordSchema = z .object({ - newPassword: z.string().min(MIN_PASSWORD_LENGTH).max(200), + newPassword: z.string().min(MIN_PASSWORD_LENGTH).max(MAX_PASSWORD_LENGTH), }) .strict(); diff --git a/tests/authentication.test.ts b/tests/authentication.test.ts new file mode 100644 index 0000000..e634716 --- /dev/null +++ b/tests/authentication.test.ts @@ -0,0 +1,265 @@ +import path from "node:path"; +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import type { Request, Response } from "express"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createDatabaseContext } from "../src/db/database-context.js"; +import { UserRepository } from "../src/db/repositories/user.repository.js"; +import { + InvalidCredentialsError, + LastAdminError, + PasswordUnchangedError, + UserService, + UsernameTakenError, + WrongPasswordError, +} from "../src/domain/services/user.service.js"; +import { hashPassword, verifyPassword } from "../src/server/auth/password.js"; +import { SessionStore } from "../src/server/auth/sessions.js"; +import { LoginThrottle } from "../src/server/auth/login-throttle.js"; +import { readCookie } from "../src/server/auth/cookie.js"; +import { requireSameOriginForWrites } from "../src/server/auth/auth.middleware.js"; +import type { AuthConfig } from "../src/server/auth/auth-config.js"; +import { createUserSchema } from "../src/shared/validation/user.schemas.js"; +import { loginSchema } from "../src/shared/validation/auth.schemas.js"; + +const HOUR = 60 * 60 * 1000; + +function createUserService() { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + const repository = new UserRepository(context.db); + const config: AuthConfig = { + sessionTtlMs: 12 * HOUR, + sessionMaxAgeMs: 7 * 24 * HOUR, + cookieSecure: false, + bootstrap: { username: "admin", password: "bootstrap-password-123" }, + }; + return { repository, service: new UserService(repository, config) }; +} + +describe("password hashing", () => { + it("verifies the right password and rejects a wrong one", async () => { + const hash = await hashPassword("richtiges-passwort"); + assert.match(hash, /^scrypt\$16384\$8\$1\$[0-9a-f]{32}\$[0-9a-f]{128}$/); + assert.equal(await verifyPassword("richtiges-passwort", hash), true); + assert.equal(await verifyPassword("falsches-passwort", hash), false); + }); + + it("uses a fresh salt per hash", async () => { + assert.notEqual(await hashPassword("gleich"), await hashPassword("gleich")); + }); + + it("rejects malformed stored hashes instead of throwing", async () => { + assert.equal(await verifyPassword("x", "not-a-hash"), false); + assert.equal(await verifyPassword("x", "scrypt$a$b$c$00$00"), false); + }); +}); + +describe("session store", () => { + it("expires idle sessions and slides on activity", () => { + let now = 0; + const store = new SessionStore(1 * HOUR, 24 * HOUR, () => now); + const session = store.create("user-1"); + now = 50 * 60 * 1000; + assert.ok(store.get(session.id)); + now += 50 * 60 * 1000; + assert.ok(store.get(session.id), "activity must have extended the idle window"); + now += 2 * HOUR; + assert.equal(store.get(session.id), undefined); + }); + + it("never outlives the absolute lifetime, even when constantly used", () => { + let now = 0; + const store = new SessionStore(1 * HOUR, 3 * HOUR, () => now); + const session = store.create("user-1"); + for (let step = 0; step < 5; step += 1) { + now += 30 * 60 * 1000; + store.get(session.id); + } + now = 3 * HOUR; + assert.equal(store.get(session.id), undefined); + }); + + it("ends all sessions of a user except an optional one", () => { + const store = new SessionStore(HOUR, 24 * HOUR); + const first = store.create("user-1"); + const second = store.create("user-1"); + const other = store.create("user-2"); + store.destroyAllForUser("user-1", second.id); + assert.equal(store.get(first.id), undefined); + assert.ok(store.get(second.id)); + assert.ok(store.get(other.id)); + }); + + it("bounds the number of sessions per user by dropping the oldest", () => { + let now = 0; + const store = new SessionStore(HOUR, 24 * HOUR, () => now); + const oldest = store.create("user-1"); + for (let index = 0; index < 20; index += 1) { + now += 1; + store.create("user-1"); + } + assert.equal(store.get(oldest.id), undefined); + }); +}); + +describe("login throttle", () => { + it("blocks a username after repeated failures and releases it after the window", () => { + let now = 0; + const throttle = new LoginThrottle(3, 15 * 60 * 1000, 100, () => now); + for (let attempt = 0; attempt < 3; attempt += 1) { + assert.equal(throttle.retryAfterMs("Admin"), 0); + throttle.recordFailure("admin "); + } + assert.ok(throttle.retryAfterMs("ADMIN") > 0, "normalized usernames share a counter"); + assert.equal(throttle.retryAfterMs("someone-else"), 0); + now = 15 * 60 * 1000 + 1; + assert.equal(throttle.retryAfterMs("admin"), 0); + }); + + it("resets the counter after a successful login", () => { + const throttle = new LoginThrottle(2); + throttle.recordFailure("admin"); + throttle.recordSuccess("admin"); + throttle.recordFailure("admin"); + assert.equal(throttle.retryAfterMs("admin"), 0); + }); +}); + +describe("cookie parsing", () => { + it("reads the session cookie and ignores malformed encodings", () => { + assert.equal(readCookie("a=1; lb_session=abc; b=2", "lb_session"), "abc"); + assert.equal(readCookie("lb_session=%E0%A4%A", "lb_session"), undefined); + assert.equal(readCookie(undefined, "lb_session"), undefined); + }); +}); + +describe("same-origin guard for writes", () => { + function run(method: string, fetchSite?: string) { + let status: number | undefined; + let passed = false; + const req = { + method, + headers: fetchSite ? { "sec-fetch-site": fetchSite } : {}, + } as unknown as Request; + const res = { + status(code: number) { + status = code; + return this; + }, + json() { + return this; + }, + } as unknown as Response; + requireSameOriginForWrites()(req, res, () => { + passed = true; + }); + return { passed, status }; + } + + it("lets reads and same-origin writes through", () => { + assert.equal(run("GET", "cross-site").passed, true); + assert.equal(run("POST", "same-origin").passed, true); + assert.equal(run("POST").passed, true, "non-browser clients carry no ambient cookie"); + }); + + it("rejects writes from other sites and other ports of the same host", () => { + assert.deepEqual(run("POST", "cross-site"), { passed: false, status: 403 }); + assert.deepEqual(run("PATCH", "same-site"), { passed: false, status: 403 }); + assert.deepEqual(run("DELETE", "same-site"), { passed: false, status: 403 }); + }); +}); + +describe("input validation", () => { + it("rejects look-alike and whitespace usernames and normalizes case", () => { + const base = { name: "Test", role: "user", initialPassword: "start-passwort" }; + assert.equal(createUserSchema.safeParse({ ...base, username: "admіn" }).success, false); + assert.equal(createUserSchema.safeParse({ ...base, username: "ad min" }).success, false); + const parsed = createUserSchema.parse({ ...base, username: " Max.Muster@Firma.de " }); + assert.equal(parsed.username, "max.muster@firma.de"); + }); + + it("caps login input length so huge bodies never reach scrypt", () => { + assert.equal( + loginSchema.safeParse({ username: "admin", password: "x".repeat(201) }).success, + false + ); + }); +}); + +describe("user service", () => { + it("creates the bootstrap admin only while the table is empty", async () => { + const { repository, service } = createUserService(); + await service.ensureBootstrapAdmin(); + await service.ensureBootstrapAdmin(); + const users = await repository.list(); + assert.equal(users.length, 1); + assert.equal(users[0].role, "admin"); + assert.equal(users[0].mustChangePassword, true); + }); + + it("rejects unknown users, wrong passwords and deactivated accounts alike", async () => { + const { service } = createUserService(); + const user = await service.createUser({ + username: "max", + name: "Max", + role: "user", + initialPassword: "start-passwort", + }); + assert.ok(user); + await assert.rejects(service.authenticate("niemand", "egal"), InvalidCredentialsError); + await assert.rejects(service.authenticate("max", "falsch"), InvalidCredentialsError); + assert.equal((await service.authenticate("MAX", "start-passwort")).id, user.id); + await service.updateRoleAndActive(user.id, { active: false }); + await assert.rejects(service.authenticate("max", "start-passwort"), InvalidCredentialsError); + }); + + it("refuses duplicate usernames", async () => { + const { service } = createUserService(); + const input = { username: "max", name: "Max", role: "user" as const, initialPassword: "start-passwort" }; + await service.createUser(input); + await assert.rejects(service.createUser(input), UsernameTakenError); + }); + + it("never removes the last active admin", async () => { + const { repository, service } = createUserService(); + await service.ensureBootstrapAdmin(); + const [admin] = await repository.list(); + await assert.rejects(service.updateRoleAndActive(admin.id, { role: "user" }), LastAdminError); + await assert.rejects(service.updateRoleAndActive(admin.id, { active: false }), LastAdminError); + + const second = await service.createUser({ + username: "zweiter", + name: "Zweiter", + role: "admin", + initialPassword: "start-passwort", + }); + assert.ok(second); + await service.updateRoleAndActive(admin.id, { role: "user" }); + await assert.rejects(service.updateRoleAndActive(second.id, { active: false }), LastAdminError); + }); + + it("requires the current password and a different new one", async () => { + const { service } = createUserService(); + const user = await service.createUser({ + username: "max", + name: "Max", + role: "user", + initialPassword: "start-passwort", + }); + assert.ok(user); + await assert.rejects( + service.changeOwnPassword(user.id, "falsch", "neues-passwort"), + WrongPasswordError + ); + await assert.rejects( + service.changeOwnPassword(user.id, "start-passwort", "start-passwort"), + PasswordUnchangedError + ); + const changed = await service.changeOwnPassword(user.id, "start-passwort", "neues-passwort"); + assert.equal(changed?.mustChangePassword, false); + + const reset = await service.resetPassword(user.id, "admin-vergeben"); + assert.equal(reset?.mustChangePassword, true); + }); +}); From 728132e52a2cdf230a0a86a65d57da5f03e454c1 Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Mon, 28 Sep 2026 21:47:30 +0200 Subject: [PATCH 20/38] Warn at startup when no user exists and no bootstrap admin is configured Also document that Sec-Fetch-Site is only sent over HTTPS, so plain-HTTP LAN access relies on SameSite=Lax alone. Co-Authored-By: Claude Opus 5.5 --- docs/authentication.md | 1 + src/domain/services/user.service.ts | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/authentication.md b/docs/authentication.md index 13a9f72..15729aa 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -53,6 +53,7 @@ Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. | Passwort-Raten (offline, DB-Diebstahl) | scrypt (N=16384, r=8, p=1), eigenes Salt je Hash | | Nutzernamen ausspähen (Timing) | Unbekannte Namen werden gegen einen festen Dummy-Hash geprüft – immer genau ein scrypt-Lauf; einheitliche Fehlermeldung | | CSRF | SameSite=Lax **plus** `requireSameOriginForWrites`: schreibende Anfragen nur mit `Sec-Fetch-Site: same-origin`. Nötig, weil andere Dienste auf demselben Host (andere Ports) als „same-site“ gelten | +| CSRF über reines HTTP | Browser senden `Sec-Fetch-Site` nur an HTTPS-Adressen. Beim Zugriff per `http://…` im LAN greift deshalb nur SameSite=Lax (schützt gegen fremde Domains, nicht gegen andere Ports desselben Hosts). | | Session-Fixation | Neue Session-ID bei jedem Login und nach jedem Passwortwechsel | | Gestohlenes Cookie | httpOnly; gleitende Laufzeit (`AUTH_SESSION_HOURS`, 12 h) **und** harte Obergrenze (`AUTH_SESSION_MAX_DAYS`, 7 Tage) | | Kompromittiertes Konto | Passwort-Reset und Deaktivieren beenden sofort alle Sessions des Kontos; Passwortwechsel beendet alle anderen | diff --git a/src/domain/services/user.service.ts b/src/domain/services/user.service.ts index 0968d02..1a3c27c 100644 --- a/src/domain/services/user.service.ts +++ b/src/domain/services/user.service.ts @@ -63,9 +63,14 @@ export class UserService { // Warm the dummy hash at startup so even the first unknown-user login // costs one scrypt run, not two. await this.getDummyHash(); - if (!this.authConfig.bootstrap) return; const existingCount = await this.repository.count(); if (existingCount > 0) return; + if (!this.authConfig.bootstrap) { + logger.warn( + "no users exist and AUTH_BOOTSTRAP_USERNAME/AUTH_BOOTSTRAP_PASSWORT are not set - nobody can sign in" + ); + return; + } const passwordHash = await hashPassword(this.authConfig.bootstrap.password); await this.repository.create({ username: this.authConfig.bootstrap.username, From ade21fe386eb0f8da3464391874d13e41f087a80 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 22:14:30 +0200 Subject: [PATCH 21/38] Create feeder circuits while linking boards --- src/app/projects/[projectId]/page.tsx | 198 +++++++++++++-- ...it-structure-project-command.repository.ts | 8 +- ...rd-structure-project-command.repository.ts | 98 +++++++ ...rd-feeder-circuit-project-command.model.ts | 132 ++++++++++ ...n-board-structure-project-command.store.ts | 12 + .../services/project-command.service.ts | 13 + src/frontend/utils/api.ts | 59 ++++- .../distribution-board-feeder-circuit.ts | 68 +++++ src/frontend/utils/project-version-history.ts | 4 + ...circuit-project-command.repository.test.ts | 240 ++++++++++++++++++ .../distribution-board-feeder-circuit.test.ts | 168 ++++++++++++ 11 files changed, 960 insertions(+), 40 deletions(-) create mode 100644 src/domain/models/distribution-board-feeder-circuit-project-command.model.ts create mode 100644 src/frontend/utils/distribution-board-feeder-circuit.ts create mode 100644 tests/distribution-board-feeder-circuit-project-command.repository.test.ts create mode 100644 tests/distribution-board-feeder-circuit.test.ts diff --git a/src/app/projects/[projectId]/page.tsx b/src/app/projects/[projectId]/page.tsx index 4a99cf0..37813c1 100644 --- a/src/app/projects/[projectId]/page.tsx +++ b/src/app/projects/[projectId]/page.tsx @@ -47,6 +47,7 @@ import { import { copyGlobalDeviceToProject, copyDistributionBoard, + createFeederCircuitAndUpdateDistributionBoard, copyProjectDeviceToGlobal, createDistributionBoard, createProjectDevice, @@ -71,6 +72,12 @@ import { updateProjectDevice, updateProjectSettings, } from "../../../frontend/utils/api"; +import { createClientId } from "../../../frontend/utils/client-id"; +import { + buildFeederCircuitSnapshot, + getDefaultFeederCircuitSection, + getNextFeederCircuitIdentifier, +} from "../../../frontend/utils/distribution-board-feeder-circuit"; import type { BuildingDto, CircuitListDto, @@ -146,6 +153,7 @@ const boardFilterCollapsedStorageKey = "leistungsbilanz:overview-filter-collapsed:distribution-boards"; const projectDeviceFilterCollapsedStorageKey = "leistungsbilanz:overview-filter-collapsed:project-devices"; +const createFeederCircuitSelectValue = "__create_feeder_circuit__"; export default function ProjectDetailPage() { const params = useParams<{ projectId: string }>(); @@ -175,6 +183,12 @@ export default function ProjectDetailPage() { const [editingBoardCopyName, setEditingBoardCopyName] = useState(""); const [editingFeedingBoardId, setEditingFeedingBoardId] = useState(""); const [editingFeedingCircuitId, setEditingFeedingCircuitId] = useState(""); + const [isCreatingFeederCircuit, setIsCreatingFeederCircuit] = + useState(false); + const [editingFeederCircuitSectionId, setEditingFeederCircuitSectionId] = + useState(""); + const [editingFeederCircuitDisplayName, setEditingFeederCircuitDisplayName] = + useState(""); const [editingBoardInfo, setEditingBoardInfo] = useState( toDistributionBoardInfoDraft({ @@ -350,6 +364,21 @@ export default function ProjectDetailPage() { const selectedFeedingCircuit = selectedFeedingCircuits.find( ({ circuit }) => circuit.id === editingFeedingCircuitId ); + const feederCircuitSections = + selectedFeedingTree?.sections.filter( + (section) => section.category !== undefined + ) ?? []; + const selectedNewFeederCircuitSection = feederCircuitSections.find( + (section) => section.id === editingFeederCircuitSectionId + ); + const newFeederCircuitIdentifier = selectedNewFeederCircuitSection + ? getNextFeederCircuitIdentifier(selectedNewFeederCircuitSection) + : null; + const selectedFeedingCircuitCategory = + selectedFeedingCircuit?.section.category ?? + (isCreatingFeederCircuit + ? selectedNewFeederCircuitSection?.category + : undefined); const selectedFeedingBoard = boards.find( (board) => board.id === editingFeedingBoardId ); @@ -556,6 +585,9 @@ export default function ProjectDetailPage() { setEditingBoardInfo(toDistributionBoardInfoDraft(board)); setEditingFeedingBoardId(board.feedingDistributionBoardId ?? ""); setEditingFeedingCircuitId(board.feedingCircuitId ?? ""); + setIsCreatingFeederCircuit(false); + setEditingFeederCircuitSectionId(""); + setEditingFeederCircuitDisplayName(""); } function openBoardCreator() { @@ -584,28 +616,56 @@ export default function ProjectDetailPage() { setIsSaving(true); setError(null); try { - const result = await updateDistributionBoard( - projectId, - editingBoard.id, - { - floorId: editingBoardFloorId || null, - supplyType: editingBoardSupplyType, - simultaneityFactor, - feedingDistributionBoardId: editingFeedingBoardId || null, - feedingCircuitId: editingFeedingCircuitId || null, - ...fromDistributionBoardInfoDraft(editingBoardInfo), - }, - project.currentRevision - ); - setBoards((current) => - current.map((board) => - board.id === result.distributionBoard.id - ? result.distributionBoard - : board - ) - ); + const boardInput = { + floorId: editingBoardFloorId || null, + supplyType: editingBoardSupplyType, + simultaneityFactor, + feedingDistributionBoardId: editingFeedingBoardId || null, + feedingCircuitId: editingFeedingCircuitId || null, + ...fromDistributionBoardInfoDraft(editingBoardInfo), + }; + let result; + if (isCreatingFeederCircuit) { + if (!editingFeedingBoardId || !selectedFeedingTree) { + throw new Error("Bitte eine speisende Verteilung wählen."); + } + if (!selectedNewFeederCircuitSection) { + throw new Error( + "Bitte eine Stromkreisgruppe für den neuen Abgang wählen." + ); + } + const circuit = buildFeederCircuitSnapshot({ + id: createClientId(), + tree: selectedFeedingTree, + sectionId: selectedNewFeederCircuitSection.id, + displayName: editingFeederCircuitDisplayName, + }); + result = await createFeederCircuitAndUpdateDistributionBoard( + projectId, + editingBoard.id, + { + ...boardInput, + feedingDistributionBoardId: editingFeedingBoardId, + feedingCircuitId: circuit.id, + }, + circuit, + project.currentRevision + ); + } else { + result = await updateDistributionBoard( + projectId, + editingBoard.id, + boardInput, + project.currentRevision + ); + } applyProjectRevision(result.history.currentRevision); - setCircuitTrees((await getProjectCircuitTrees(projectId)).trees); + const [updatedBoards, updatedTrees] = await Promise.all([ + listDistributionBoards(projectId), + getProjectCircuitTrees(projectId), + ]); + setBoards(updatedBoards); + setCircuitTrees(updatedTrees.trees); setEditingBoard(null); } catch (err) { setError( @@ -1567,8 +1627,16 @@ export default function ProjectDetailPage() { className="form-select" id="feeding-distribution-board" onChange={(event) => { - setEditingFeedingBoardId(event.target.value); + const boardId = event.target.value; + setEditingFeedingBoardId(boardId); setEditingFeedingCircuitId(""); + setIsCreatingFeederCircuit(false); + setEditingFeederCircuitSectionId( + getDefaultFeederCircuitSection( + circuitTreeByBoardId.get(boardId) + )?.id ?? "" + ); + setEditingFeederCircuitDisplayName(""); }} value={editingFeedingBoardId} > @@ -1588,10 +1656,31 @@ export default function ProjectDetailPage() { className="form-select" disabled={!editingFeedingBoardId} id="feeding-circuit" - onChange={(event) => setEditingFeedingCircuitId(event.target.value)} - value={editingFeedingCircuitId} + onChange={(event) => { + if (event.target.value === createFeederCircuitSelectValue) { + setEditingFeedingCircuitId(""); + setIsCreatingFeederCircuit(true); + setEditingFeederCircuitSectionId( + (current) => + current || + getDefaultFeederCircuitSection(selectedFeedingTree)?.id || + "" + ); + return; + } + setIsCreatingFeederCircuit(false); + setEditingFeedingCircuitId(event.target.value); + }} + value={ + isCreatingFeederCircuit + ? createFeederCircuitSelectValue + : editingFeedingCircuitId + } > + {selectedFeedingCircuits.map(({ circuit }) => (
- {editingFeedingBoardId && !editingFeedingCircuitId ? ( + {isCreatingFeederCircuit ? ( +
+
+
+
+ + +
+ Vorgesehenes BMK: {newFeederCircuitIdentifier ?? "–"} +
+
+
+ + + setEditingFeederCircuitDisplayName(event.target.value) + } + placeholder="z. B. Steigetrasse Ost" + value={editingFeederCircuitDisplayName} + /> +
+ Ohne Zusatzbezeichnung wird der Name der gespeisten + Verteilung angezeigt. +
+
+
+
+ Der Abgang wird erst beim Speichern angelegt und gemeinsam + mit dieser Verteilung verknüpft. Es entsteht keine Gerätezeile. +
+
+
+ ) : null} + {editingFeedingBoardId && + !editingFeedingCircuitId && + !isCreatingFeederCircuit ? (
Ohne speisenden Abgang wird die Hierarchie angezeigt, die @@ -1618,8 +1762,8 @@ export default function ProjectDetailPage() {
) : null} - {selectedFeedingCircuit && - selectedFeedingCircuit.section.category !== "three_phase" ? ( + {selectedFeedingCircuitCategory !== undefined && + selectedFeedingCircuitCategory !== "three_phase" ? (
Der gewählte Abgang ist 1-phasig. Bitte prüfen, ob diese diff --git a/src/db/repositories/circuit-structure-project-command.repository.ts b/src/db/repositories/circuit-structure-project-command.repository.ts index e7cfcb2..4841616 100644 --- a/src/db/repositories/circuit-structure-project-command.repository.ts +++ b/src/db/repositories/circuit-structure-project-command.repository.ts @@ -40,7 +40,7 @@ export class CircuitStructureProjectCommandRepository this.database, input, (tx) => - this.applyCommand( + this.applyInTransaction( tx, input.projectId, input.source, @@ -49,7 +49,11 @@ export class CircuitStructureProjectCommandRepository ); } - private applyCommand( + /** + * Applies the circuit write inside an already-owned project transaction. + * Composite project commands use this without creating a second revision. + */ + applyInTransaction( database: AppDatabase, projectId: string, source: ExecuteCircuitStructureCommandInput["source"], diff --git a/src/db/repositories/distribution-board-structure-project-command.repository.ts b/src/db/repositories/distribution-board-structure-project-command.repository.ts index 9346df7..115705b 100644 --- a/src/db/repositories/distribution-board-structure-project-command.repository.ts +++ b/src/db/repositories/distribution-board-structure-project-command.repository.ts @@ -1,4 +1,5 @@ import { and, asc, eq, inArray } from "drizzle-orm"; +import { isDeepStrictEqual } from "node:util"; import { assertDistributionBoardDeleteProjectCommand, assertDistributionBoardInsertProjectCommand, @@ -17,6 +18,20 @@ import { type DistributionBoardUpdateProjectCommand, type DistributionBoardUpdateValues, } from "../../domain/models/distribution-board-project-command.model.js"; +import { + assertDistributionBoardFeederCircuitProjectCommand, + createDistributionBoardCreateFeederCircuitProjectCommand, + createDistributionBoardRemoveFeederCircuitProjectCommand, + distributionBoardCreateFeederCircuitCommandType, + distributionBoardRemoveFeederCircuitCommandType, + type DistributionBoardFeederCircuitProjectCommand, +} from "../../domain/models/distribution-board-feeder-circuit-project-command.model.js"; +import { + circuitDeleteCommandType, + circuitInsertCommandType, + createCircuitDeleteProjectCommand, + createCircuitInsertProjectCommand, +} from "../../domain/models/circuit-structure-project-command.model.js"; import type { DistributionBoardStructureProjectCommandStore, ExecuteDistributionBoardStructureCommandInput, @@ -31,6 +46,7 @@ import { floors } from "../schema/floors.js"; import { projects } from "../schema/projects.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; import { assertBoardsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; +import { CircuitStructureProjectCommandRepository } from "./circuit-structure-project-command.repository.js"; export class DistributionBoardStructureProjectCommandRepository implements DistributionBoardStructureProjectCommandStore @@ -62,6 +78,30 @@ export class DistributionBoardStructureProjectCommandRepository ); } + executeFeederCircuit( + input: Omit< + ExecuteDistributionBoardStructureCommandInput, + "command" + > & { + command: DistributionBoardFeederCircuitProjectCommand; + } + ) { + assertDistributionBoardFeederCircuitProjectCommand(input.command); + if ( + input.source === "user" && + input.command.type === distributionBoardRemoveFeederCircuitCommandType + ) { + throw new Error( + "Generated feeder circuits may only be removed through project history." + ); + } + return executeProjectCommandTransaction( + this.database, + input, + (tx) => this.applyFeederCircuitCommand(tx, input) + ); + } + private applyCommand( database: AppDatabase, projectId: string, @@ -367,6 +407,64 @@ export class DistributionBoardStructureProjectCommandRepository return inverse; } + private applyFeederCircuitCommand( + database: AppDatabase, + input: Omit< + ExecuteDistributionBoardStructureCommandInput, + "command" + > & { + command: DistributionBoardFeederCircuitProjectCommand; + } + ): DistributionBoardFeederCircuitProjectCommand { + const circuitRepository = + new CircuitStructureProjectCommandRepository(database); + const { circuit, boardUpdate } = input.command.payload; + if ( + input.command.type === distributionBoardCreateFeederCircuitCommandType + ) { + const circuitInverse = circuitRepository.applyInTransaction( + database, + input.projectId, + input.source, + createCircuitInsertProjectCommand(circuit) + ); + if (circuitInverse.type !== circuitDeleteCommandType) { + throw new Error("Created feeder circuit returned an invalid inverse."); + } + const boardInverse = this.update(database, { + ...input, + command: boardUpdate, + }); + return createDistributionBoardRemoveFeederCircuitProjectCommand( + circuit, + boardInverse + ); + } + + const boardInverse = this.update(database, { + ...input, + command: boardUpdate, + }); + const circuitInverse = circuitRepository.applyInTransaction( + database, + input.projectId, + input.source, + createCircuitDeleteProjectCommand(circuit.id, circuit.circuitListId) + ); + if ( + circuitInverse.type !== circuitInsertCommandType || + !isDeepStrictEqual(circuitInverse.payload.circuit, circuit) + ) { + throw new Error( + "Generated feeder circuit changed before history removal." + ); + } + return createDistributionBoardCreateFeederCircuitProjectCommand( + circuit, + boardInverse + ); + } + private assertFeedingReference( database: AppDatabase, projectId: string, diff --git a/src/domain/models/distribution-board-feeder-circuit-project-command.model.ts b/src/domain/models/distribution-board-feeder-circuit-project-command.model.ts new file mode 100644 index 0000000..a1fc035 --- /dev/null +++ b/src/domain/models/distribution-board-feeder-circuit-project-command.model.ts @@ -0,0 +1,132 @@ +import { + assertCircuitInsertProjectCommand, + circuitInsertCommandType, + circuitStructureCommandSchemaVersion, + type CircuitSnapshot, +} from "./circuit-structure-project-command.model.js"; +import { + assertDistributionBoardUpdateProjectCommand, + type DistributionBoardUpdateProjectCommand, +} from "./distribution-board-project-command.model.js"; +import type { SerializedProjectCommand } from "./project-command.model.js"; + +export const distributionBoardCreateFeederCircuitCommandType = + "distribution-board.create-feeder-circuit" as const; +export const distributionBoardRemoveFeederCircuitCommandType = + "distribution-board.remove-feeder-circuit" as const; +export const distributionBoardFeederCircuitCommandSchemaVersion = 1 as const; + +export interface DistributionBoardFeederCircuitCommandPayload { + circuit: CircuitSnapshot; + boardUpdate: DistributionBoardUpdateProjectCommand; +} + +export interface DistributionBoardCreateFeederCircuitProjectCommand + extends SerializedProjectCommand { + schemaVersion: typeof distributionBoardFeederCircuitCommandSchemaVersion; + type: typeof distributionBoardCreateFeederCircuitCommandType; +} + +export interface DistributionBoardRemoveFeederCircuitProjectCommand + extends SerializedProjectCommand { + schemaVersion: typeof distributionBoardFeederCircuitCommandSchemaVersion; + type: typeof distributionBoardRemoveFeederCircuitCommandType; +} + +export type DistributionBoardFeederCircuitProjectCommand = + | DistributionBoardCreateFeederCircuitProjectCommand + | DistributionBoardRemoveFeederCircuitProjectCommand; + +export function createDistributionBoardCreateFeederCircuitProjectCommand( + circuit: CircuitSnapshot, + boardUpdate: DistributionBoardUpdateProjectCommand +): DistributionBoardCreateFeederCircuitProjectCommand { + const command: DistributionBoardCreateFeederCircuitProjectCommand = { + schemaVersion: distributionBoardFeederCircuitCommandSchemaVersion, + type: distributionBoardCreateFeederCircuitCommandType, + payload: { circuit, boardUpdate }, + }; + assertDistributionBoardFeederCircuitProjectCommand(command); + return command; +} + +export function createDistributionBoardRemoveFeederCircuitProjectCommand( + circuit: CircuitSnapshot, + boardUpdate: DistributionBoardUpdateProjectCommand +): DistributionBoardRemoveFeederCircuitProjectCommand { + const command: DistributionBoardRemoveFeederCircuitProjectCommand = { + schemaVersion: distributionBoardFeederCircuitCommandSchemaVersion, + type: distributionBoardRemoveFeederCircuitCommandType, + payload: { circuit, boardUpdate }, + }; + assertDistributionBoardFeederCircuitProjectCommand(command); + return command; +} + +export function assertDistributionBoardFeederCircuitProjectCommand( + command: SerializedProjectCommand +): asserts command is DistributionBoardFeederCircuitProjectCommand { + if ( + command.schemaVersion !== + distributionBoardFeederCircuitCommandSchemaVersion || + (command.type !== distributionBoardCreateFeederCircuitCommandType && + command.type !== distributionBoardRemoveFeederCircuitCommandType) || + !isPlainObject(command.payload) + ) { + throw new Error("Unsupported distribution-board feeder-circuit command."); + } + + const { circuit, boardUpdate } = command.payload; + if (!isPlainObject(boardUpdate)) { + throw new Error("Feeder-circuit command requires a board update."); + } + assertCircuitInsertProjectCommand({ + schemaVersion: circuitStructureCommandSchemaVersion, + type: circuitInsertCommandType, + payload: { circuit }, + }); + const boardUpdateCommand = + boardUpdate as unknown as SerializedProjectCommand; + assertDistributionBoardUpdateProjectCommand(boardUpdateCommand); + + const typedCircuit = circuit as CircuitSnapshot; + const typedBoardUpdate: DistributionBoardUpdateProjectCommand = + boardUpdateCommand; + if (typedCircuit.deviceRows.length !== 0 || !typedCircuit.isReserve) { + throw new Error( + "A generated feeder circuit must be empty before the board load is linked." + ); + } + const feedingBoard = getChangeValue( + typedBoardUpdate, + "feedingDistributionBoardId" + ); + const feedingCircuit = getChangeValue( + typedBoardUpdate, + "feedingCircuitId" + ); + if (feedingBoard === undefined || feedingCircuit === undefined) { + throw new Error( + "Feeder-circuit commands must update both logical feeding references." + ); + } + if ( + command.type === distributionBoardCreateFeederCircuitCommandType && + (typeof feedingBoard !== "string" || feedingCircuit !== typedCircuit.id) + ) { + throw new Error( + "The created feeder circuit must be linked by the distribution-board update." + ); + } +} + +function getChangeValue( + command: DistributionBoardUpdateProjectCommand, + field: "feedingDistributionBoardId" | "feedingCircuitId" +) { + return command.payload.changes.find((change) => change.field === field)?.value; +} + +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} diff --git a/src/domain/ports/distribution-board-structure-project-command.store.ts b/src/domain/ports/distribution-board-structure-project-command.store.ts index f0cb5c9..6dd8d8f 100644 --- a/src/domain/ports/distribution-board-structure-project-command.store.ts +++ b/src/domain/ports/distribution-board-structure-project-command.store.ts @@ -1,5 +1,6 @@ import type { DistributionBoardStructureProjectCommand } from "../models/distribution-board-structure-project-command.model.js"; import type { DistributionBoardUpdateProjectCommand } from "../models/distribution-board-project-command.model.js"; +import type { DistributionBoardFeederCircuitProjectCommand } from "../models/distribution-board-feeder-circuit-project-command.model.js"; import type { AppendedProjectRevision, ProjectRevisionSource, @@ -35,4 +36,15 @@ export interface DistributionBoardStructureProjectCommandStore { revision: AppendedProjectRevision; inverse: DistributionBoardUpdateProjectCommand; }; + executeFeederCircuit( + input: Omit< + ExecuteDistributionBoardStructureCommandInput, + "command" + > & { + command: DistributionBoardFeederCircuitProjectCommand; + } + ): { + revision: AppendedProjectRevision; + inverse: DistributionBoardFeederCircuitProjectCommand; + }; } diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index cf1f740..35dd9e8 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -45,6 +45,11 @@ import { assertDistributionBoardUpdateProjectCommand, distributionBoardUpdateCommandType, } from "../models/distribution-board-project-command.model.js"; +import { + assertDistributionBoardFeederCircuitProjectCommand, + distributionBoardCreateFeederCircuitCommandType, + distributionBoardRemoveFeederCircuitCommandType, +} from "../models/distribution-board-feeder-circuit-project-command.model.js"; import { assertDistributionBoardComponentDeleteProjectCommand, assertDistributionBoardComponentInsertProjectCommand, @@ -418,6 +423,14 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } + case distributionBoardCreateFeederCircuitCommandType: + case distributionBoardRemoveFeederCircuitCommandType: { + assertDistributionBoardFeederCircuitProjectCommand(input.command); + return this.distributionBoardStructureStore.executeFeederCircuit({ + ...input, + command: input.command, + }).revision; + } case distributionBoardComponentInsertCommandType: { assertDistributionBoardComponentInsertProjectCommand( input.command diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index 8473bfa..8f5a878 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -366,20 +366,22 @@ export function createDistributionBoard( ); } +export type UpdateDistributionBoardInput = { + floorId: string | null; + supplyType: NonNullable; + simultaneityFactor: number; +} & Partial & + Partial< + Pick< + DistributionBoardDto, + "feedingDistributionBoardId" | "feedingCircuitId" + > + >; + export function updateDistributionBoard( projectId: string, distributionBoardId: string, - input: { - floorId: string | null; - supplyType: NonNullable; - simultaneityFactor: number; - } & Partial & - Partial< - Pick< - DistributionBoardDto, - "feedingDistributionBoardId" | "feedingCircuitId" - > - >, + input: UpdateDistributionBoardInput, expectedRevision: number ) { return request( @@ -391,6 +393,41 @@ export function updateDistributionBoard( ); } +export function createFeederCircuitAndUpdateDistributionBoard( + projectId: string, + distributionBoardId: string, + input: UpdateDistributionBoardInput & { + feedingDistributionBoardId: string; + feedingCircuitId: string; + }, + circuit: CircuitSnapshot, + expectedRevision: number +) { + return executeProjectCommand( + projectId, + expectedRevision, + { + schemaVersion: 1, + type: "distribution-board.create-feeder-circuit", + payload: { + circuit, + boardUpdate: { + schemaVersion: 2, + type: "distribution-board.update", + payload: { + distributionBoardId, + changes: Object.entries(input).map(([field, value]) => ({ + field, + value, + })), + }, + }, + }, + }, + "Einspeiseabgang anlegen und Verteilung verknüpfen" + ); +} + export const documentLogoUrl = "/api/document-branding/logo"; export function getDocumentBranding() { diff --git a/src/frontend/utils/distribution-board-feeder-circuit.ts b/src/frontend/utils/distribution-board-feeder-circuit.ts new file mode 100644 index 0000000..c2c7f43 --- /dev/null +++ b/src/frontend/utils/distribution-board-feeder-circuit.ts @@ -0,0 +1,68 @@ +import type { CircuitSnapshot } from "../../domain/models/circuit-structure-project-command.model.js"; +import type { + CircuitTreeResponseDto, + CircuitTreeSectionDto, +} from "../types"; +import { buildCircuitInsertSnapshot } from "./circuit-structure-command"; + +export function getDefaultFeederCircuitSection( + tree: CircuitTreeResponseDto | undefined +) { + if (!tree) return undefined; + return ( + tree.sections.find((section) => section.category === "three_phase") ?? + tree.sections.find((section) => section.category !== undefined) + ); +} + +export function getNextFeederCircuitIdentifier( + section: CircuitTreeSectionDto +) { + let highestSuffix = 0; + for (const circuit of section.circuits) { + if (!circuit.equipmentIdentifier.startsWith(section.prefix)) continue; + const suffix = circuit.equipmentIdentifier.slice(section.prefix.length); + if (!/^\d+$/.test(suffix)) continue; + highestSuffix = Math.max(highestSuffix, Number(suffix)); + } + return `${section.prefix}${highestSuffix + 1}`; +} + +export function buildFeederCircuitSnapshot(input: { + id: string; + tree: CircuitTreeResponseDto; + sectionId: string; + displayName: string; +}): CircuitSnapshot { + const section = input.tree.sections.find( + (candidate) => candidate.id === input.sectionId + ); + if (!section || !section.category) { + throw new Error("Die gewählte Stromkreisgruppe ist nicht verfügbar."); + } + const snapshot = buildCircuitInsertSnapshot({ + id: input.id, + circuitListId: input.tree.circuitListId, + category: section.category, + deviceRows: [], + values: { + sectionId: section.id, + equipmentIdentifier: getNextFeederCircuitIdentifier(section), + displayName: input.displayName.trim() || undefined, + sortOrder: + section.circuits.length === 0 + ? 10 + : Math.max(...section.circuits.map((circuit) => circuit.sortOrder)) + + 10, + voltage: + section.category === "three_phase" + ? input.tree.threePhaseVoltageV + : input.tree.singlePhaseVoltageV, + isReserve: true, + }, + }); + // A distribution-board feeder is not a generic final circuit. Its protection + // must be selected from the calculated load and cable, so no 16 A group + // default is persisted here. + return { ...snapshot, protectionDevice: null }; +} diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index 146cda8..eb195d0 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -32,6 +32,10 @@ const commandTypeLabels: Record = { "project.update-settings": "Projekteinstellungen bearbeitet", "distribution-board.insert": "Verteilung angelegt", "distribution-board.update": "Verteilung bearbeitet", + "distribution-board.create-feeder-circuit": + "Einspeiseabgang angelegt und verknüpft", + "distribution-board.remove-feeder-circuit": + "Einspeiseabgang und Verknüpfung entfernt", "distribution-board.delete": "Verteilung entfernt", "distribution-board.insert-subtree": "Verteilung vollständig eingefügt", "distribution-board.delete-subtree": "Verteilung vollständig entfernt", diff --git a/tests/distribution-board-feeder-circuit-project-command.repository.test.ts b/tests/distribution-board-feeder-circuit-project-command.repository.test.ts new file mode 100644 index 0000000..d4d2c26 --- /dev/null +++ b/tests/distribution-board-feeder-circuit-project-command.repository.test.ts @@ -0,0 +1,240 @@ +import path from "node:path"; +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { eq } from "drizzle-orm"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { + createDatabaseContext, + type DatabaseContext, +} from "../src/db/database-context.js"; +import { DistributionBoardStructureProjectCommandRepository } from "../src/db/repositories/distribution-board-structure-project-command.repository.js"; +import { ProjectHistoryRepository } from "../src/db/repositories/project-history.repository.js"; +import { circuits } from "../src/db/schema/circuits.js"; +import { distributionBoards } from "../src/db/schema/distribution-boards.js"; +import { projects } from "../src/db/schema/projects.js"; +import { + assertDistributionBoardFeederCircuitProjectCommand, + createDistributionBoardCreateFeederCircuitProjectCommand, +} from "../src/domain/models/distribution-board-feeder-circuit-project-command.model.js"; +import { createDistributionBoardUpdateProjectCommand } from "../src/domain/models/distribution-board-project-command.model.js"; +import { + createDistributionBoardInsertProjectCommand, + createDistributionBoardStructureSnapshot, +} from "../src/domain/models/distribution-board-structure-project-command.model.js"; +import { buildCircuitInsertSnapshot } from "../src/frontend/utils/circuit-structure-command.js"; + +function createTestDatabase(): DatabaseContext { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { + migrationsFolder: path.resolve("src", "db", "migrations"), + }); + context.db + .insert(projects) + .values({ id: "project-1", name: "Test project" }) + .run(); + return context; +} + +function setupBoards( + context: DatabaseContext, + repository: DistributionBoardStructureProjectCommandRepository +) { + const source = createDistributionBoardStructureSnapshot( + "project-1", + "NSHV" + ); + const downstream = createDistributionBoardStructureSnapshot( + "project-1", + "UV EG" + ); + repository.execute({ + projectId: "project-1", + expectedRevision: 0, + source: "user", + command: createDistributionBoardInsertProjectCommand(source), + }); + repository.execute({ + projectId: "project-1", + expectedRevision: 1, + source: "user", + command: createDistributionBoardInsertProjectCommand(downstream), + }); + const section = source.sections.find( + (candidate) => candidate.key === "three_phase" + )!; + const circuit = { + ...buildCircuitInsertSnapshot({ + id: "feeder-circuit", + circuitListId: source.circuitList.id, + category: "three_phase", + deviceRows: [], + values: { + sectionId: section.id, + equipmentIdentifier: `${section.prefix}1`, + displayName: undefined, + sortOrder: 10, + voltage: 400, + isReserve: true, + }, + }), + protectionDevice: null, + }; + const boardUpdate = createDistributionBoardUpdateProjectCommand( + downstream.distributionBoard.id, + { + feedingDistributionBoardId: source.distributionBoard.id, + feedingCircuitId: circuit.id, + } + ); + const command = + createDistributionBoardCreateFeederCircuitProjectCommand( + circuit, + boardUpdate + ); + return { source, downstream, circuit, command }; +} + +describe("distribution-board feeder-circuit project command", () => { + it("creates and links one feeder atomically and supports undo and redo", () => { + const context = createTestDatabase(); + try { + const repository = + new DistributionBoardStructureProjectCommandRepository(context.db); + const history = new ProjectHistoryRepository(context.db); + const { source, downstream, circuit, command } = setupBoards( + context, + repository + ); + + repository.executeFeederCircuit({ + projectId: "project-1", + expectedRevision: 2, + source: "user", + command, + }); + assert.ok( + context.db + .select() + .from(circuits) + .where(eq(circuits.id, circuit.id)) + .get() + ); + assert.deepEqual( + context.db + .select({ + boardId: distributionBoards.feedingDistributionBoardId, + circuitId: distributionBoards.feedingCircuitId, + }) + .from(distributionBoards) + .where(eq(distributionBoards.id, downstream.distributionBoard.id)) + .get(), + { + boardId: source.distributionBoard.id, + circuitId: circuit.id, + } + ); + + const undo = history.getNextCommand("project-1", "undo"); + assert.ok(undo); + assertDistributionBoardFeederCircuitProjectCommand(undo.command); + repository.executeFeederCircuit({ + projectId: "project-1", + expectedRevision: 3, + source: "undo", + historyTargetChangeSetId: undo.changeSetId, + command: undo.command, + }); + assert.equal( + context.db + .select() + .from(circuits) + .where(eq(circuits.id, circuit.id)) + .get(), + undefined + ); + assert.deepEqual( + context.db + .select({ + boardId: distributionBoards.feedingDistributionBoardId, + circuitId: distributionBoards.feedingCircuitId, + }) + .from(distributionBoards) + .where(eq(distributionBoards.id, downstream.distributionBoard.id)) + .get(), + { boardId: null, circuitId: null } + ); + + const redo = history.getNextCommand("project-1", "redo"); + assert.ok(redo); + assertDistributionBoardFeederCircuitProjectCommand(redo.command); + repository.executeFeederCircuit({ + projectId: "project-1", + expectedRevision: 4, + source: "redo", + historyTargetChangeSetId: redo.changeSetId, + command: redo.command, + }); + assert.equal( + context.db + .select({ equipmentIdentifier: circuits.equipmentIdentifier }) + .from(circuits) + .where(eq(circuits.id, circuit.id)) + .get()?.equipmentIdentifier, + circuit.equipmentIdentifier + ); + } finally { + context.close(); + } + }); + + it("rolls back unlinking when the generated circuit changed before undo", () => { + const context = createTestDatabase(); + try { + const repository = + new DistributionBoardStructureProjectCommandRepository(context.db); + const history = new ProjectHistoryRepository(context.db); + const { downstream, circuit, command } = setupBoards(context, repository); + repository.executeFeederCircuit({ + projectId: "project-1", + expectedRevision: 2, + source: "user", + command, + }); + context.db + .update(circuits) + .set({ displayName: "Außerhalb der Historie geändert" }) + .where(eq(circuits.id, circuit.id)) + .run(); + + const undo = history.getNextCommand("project-1", "undo"); + assert.ok(undo); + assertDistributionBoardFeederCircuitProjectCommand(undo.command); + assert.throws( + () => + repository.executeFeederCircuit({ + projectId: "project-1", + expectedRevision: 3, + source: "undo", + historyTargetChangeSetId: undo.changeSetId, + command: undo.command, + }), + /changed before history removal/ + ); + const board = context.db + .select() + .from(distributionBoards) + .where(eq(distributionBoards.id, downstream.distributionBoard.id)) + .get(); + assert.equal(board?.feedingCircuitId, circuit.id); + assert.ok( + context.db + .select() + .from(circuits) + .where(eq(circuits.id, circuit.id)) + .get() + ); + } finally { + context.close(); + } + }); +}); diff --git a/tests/distribution-board-feeder-circuit.test.ts b/tests/distribution-board-feeder-circuit.test.ts new file mode 100644 index 0000000..fb143da --- /dev/null +++ b/tests/distribution-board-feeder-circuit.test.ts @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + buildFeederCircuitSnapshot, + getDefaultFeederCircuitSection, + getNextFeederCircuitIdentifier, +} from "../src/frontend/utils/distribution-board-feeder-circuit.js"; +import type { CircuitTreeResponseDto } from "../src/frontend/types.js"; +import { createFeederCircuitAndUpdateDistributionBoard } from "../src/frontend/utils/api.js"; + +function tree(): CircuitTreeResponseDto { + return { + circuitListId: "list-main", + distributionBoardId: "board-main", + distributionBoardName: "NSHV", + currentRevision: 2, + singlePhaseVoltageV: 230, + threePhaseVoltageV: 400, + distributionBoardSimultaneityFactor: 1, + distributionBoardTotalPower: 0, + distributionBoardTotalPowerWithSimultaneityFactor: 0, + headerComponents: [], + footerComponents: [], + sections: [ + { + id: "single", + key: "single_phase", + category: "single_phase", + groupNumber: 1, + displayName: "1-phasig 1", + prefix: "-2F1.", + sortOrder: 10, + sectionTotalPower: 0, + components: [], + circuits: [], + }, + { + id: "three", + key: "three_phase", + category: "three_phase", + groupNumber: 1, + displayName: "3-phasig 1", + prefix: "-3F1.", + sortOrder: 20, + sectionTotalPower: 0, + components: [], + circuits: [ + { + id: "existing-2", + circuitListId: "list-main", + sectionId: "three", + equipmentIdentifier: "-3F1.2", + sortOrder: 10, + isReserve: true, + circuitTotalPower: 0, + circuitApparentPower: 0, + circuitCosPhi: 1, + deviceRows: [], + downstreamBoardLoads: [], + }, + { + id: "existing-5", + circuitListId: "list-main", + sectionId: "three", + equipmentIdentifier: "-3F1.5", + sortOrder: 30, + isReserve: true, + circuitTotalPower: 0, + circuitApparentPower: 0, + circuitCosPhi: 1, + deviceRows: [], + downstreamBoardLoads: [], + }, + ], + }, + ], + }; +} + +describe("distribution-board feeder circuit planning", () => { + it("prefers a three-phase section and does not fill BMK gaps", () => { + const input = tree(); + const section = getDefaultFeederCircuitSection(input)!; + assert.equal(section.id, "three"); + assert.equal(getNextFeederCircuitIdentifier(section), "-3F1.6"); + }); + + it("builds an empty circuit with stable id, optional name and defaults", () => { + const input = tree(); + const snapshot = buildFeederCircuitSnapshot({ + id: "new-feeder", + tree: input, + sectionId: "three", + displayName: " ", + }); + assert.equal(snapshot.id, "new-feeder"); + assert.equal(snapshot.equipmentIdentifier, "-3F1.6"); + assert.equal(snapshot.displayName, null); + assert.equal(snapshot.sortOrder, 40); + assert.equal(snapshot.voltage, 400); + assert.equal(snapshot.isReserve, true); + assert.deepEqual(snapshot.deviceRows, []); + assert.equal(snapshot.protectionDevice, null); + }); + + it("sends circuit creation and board linking as one project command", async () => { + const input = tree(); + const circuit = buildFeederCircuitSnapshot({ + id: "new-feeder", + tree: input, + sectionId: "three", + displayName: "", + }); + const requests: Array<{ url: string; method: string; body: any }> = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (request, init) => { + requests.push({ + url: String(request), + method: init?.method ?? "GET", + body: JSON.parse(String(init?.body)), + }); + return new Response(JSON.stringify({}), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }; + try { + await createFeederCircuitAndUpdateDistributionBoard( + "project-1", + "board-child", + { + floorId: null, + supplyType: "AV", + simultaneityFactor: 0.8, + feedingDistributionBoardId: "board-main", + feedingCircuitId: circuit.id, + }, + circuit, + 7 + ); + } finally { + globalThis.fetch = originalFetch; + } + assert.equal(requests.length, 1); + assert.equal(requests[0].url, "/api/projects/project-1/commands"); + assert.equal(requests[0].method, "POST"); + assert.equal(requests[0].body.expectedRevision, 7); + assert.equal( + requests[0].body.command.type, + "distribution-board.create-feeder-circuit" + ); + assert.equal(requests[0].body.command.payload.circuit.id, "new-feeder"); + assert.deepEqual( + requests[0].body.command.payload.boardUpdate.payload.changes + .filter((change: { field: string }) => + change.field.startsWith("feeding") + ) + .map((change: { field: string; value: unknown }) => [ + change.field, + change.value, + ]), + [ + ["feedingDistributionBoardId", "board-main"], + ["feedingCircuitId", "new-feeder"], + ] + ); + }); +}); From 9165b8238c2ed67228ee0af9db5556fdf77e434c Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 22:14:39 +0200 Subject: [PATCH 22/38] Compact single-board feeder circuit rows --- AGENTS.md | 11 ++++ docs/circuit-list-editor-api.md | 11 +++- docs/current-architecture.md | 15 +++++ docs/print-view.md | 5 +- src/app/globals.css | 4 ++ .../components/circuit-tree-editor.tsx | 16 +++++- src/frontend/print/print-document.tsx | 19 +++++++ src/frontend/utils/circuit-grid-model.ts | 6 +- src/frontend/utils/circuit-grid-projection.ts | 47 ++++++++++++++- tests/circuit-grid-model.test.ts | 4 +- tests/circuit-grid-projection.test.ts | 57 +++++++++++++++++-- 11 files changed, 181 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9ef5b87..93e5108 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -476,6 +476,17 @@ downstream board's demand after its own board simultaneity factor to the chosen feeding circuit as a read-only virtual row. Recursive chains and several boards on one circuit are supported. A board-only link affects hierarchy but adds no load until a feeding circuit is selected. +The distribution-board dialog can create one empty feeder circuit and link it +in the same `distribution-board.create-feeder-circuit` project command. Its +history inverse restores the complete previous board update before removing +only the unchanged generated circuit; Redo reuses its UUID and BMK. No +CircuitDeviceRow is created. The three-phase group is suggested, the optional +circuit display name stays empty by default, and protection remains open for +planner sizing. A circuit with exactly one downstream board and no device rows +is rendered as one compact row using the live board number/name; several +downstream boards or additional devices retain summary and child rows. Editing +the name or remark of an empty reserve circuit changes the circuit itself and +does not implicitly create a device row. Distribution-board floor assignment and a project-enabled supply type use `distribution-board.update`; both values are snapshot/export fields and one persistent undo step. diff --git a/docs/circuit-list-editor-api.md b/docs/circuit-list-editor-api.md index a8173f5..de724aa 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -269,6 +269,13 @@ commands. Endpoints, payloads and calculation rules: `docs/estimate-balance.md`. submitted info fields, are restored together by persistent Undo/Redo - `fedFrom` remains free text for external feeds such as HAK, metering, transformer or generator and for supplementary notes +- The project-command endpoint additionally accepts + `distribution-board.create-feeder-circuit` with an empty complete circuit + snapshot and an embedded version-2 `distribution-board.update`. Both writes + are one transaction, revision and Undo step. The generated circuit has no + device row; Redo keeps its UUID and BMK. The history-only inverse + `distribution-board.remove-feeder-circuit` restores the previous board values + and removes only the unchanged circuit. - `POST /projects/:projectId/distribution-boards/:distributionBoardId/copy` - body: `{ "name": "UV-02 Kopie", "expectedRevision": 14 }` - duplicates the complete distribution-board subtree with new owning UUIDs @@ -346,7 +353,9 @@ commands. Endpoints, payloads and calculation rules: `docs/estimate-balance.md`. footer components. Circuit and component protection devices use their separate one-to-one DTOs. Calculated row, circuit, section and board totals remain included. Circuit totals contain the demand of linked downstream - boards. `downstreamBoardLoads` exposes those contributions as read-only rows; + boards. `downstreamBoardLoads` exposes those contributions as read-only + values; the grid combines exactly one downstream board without device rows + into the circuit row and keeps child rows for mixed or multiple loads. `feedingReference` resolves the current board/circuit labels by id. Response sketch: diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 920002d..71b7feb 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -477,6 +477,21 @@ Verweise nicht. Der speisende Stromkreis muss zur speisenden Verteilung gehören Selbstverweise und Zyklen werden abgelehnt. Löschbefehle für referenzierte Verteilungen und Stromkreise, einschließlich Unterbaum- und Undo-Pfaden, werden vor der Datenbankänderung fachlich gesperrt. +Im Bearbeiten-Dialog kann nach Auswahl der speisenden Verteilung direkt ein +neuer Einspeiseabgang geplant werden. Die Oberfläche schlägt die dreiphasige +Gruppe und das nächste BMK vor. Der Befehl +`distribution-board.create-feeder-circuit` legt den leeren Stromkreis an und +wendet die vollständige Verteilungsänderung in derselben Transaktion und +Revision an; es entsteht keine Gerätezeile. Schutz und Leitung bleiben bewusst +offen, weil sie aus Last und Verlegebedingungen geplant werden müssen. Undo +stellt zuerst die vorherigen Verteilungswerte wieder her und entfernt danach +nur den unveränderten erzeugten Stromkreis; Redo verwendet UUID und BMK erneut. +Bei genau einer gespeisten Unterverteilung ohne Gerätezeilen projiziert das +Grid nur eine kompakte Stromkreiszeile mit dem über die ID aufgelösten +Verteilernamen. Erst mehrere Unterverteilungen oder zusätzliche Geräte erzeugen +Sammel- und Unterzeilen. Anzeigename und Bemerkung eines leeren +Reservestromkreises gehören zum Stromkreis und erzeugen beim Bearbeiten keine +Gerätezeile. Die projektweite Circuit-Tree-Projektion berechnet rekursiv die Lasten aller Verteilungen. Die Leistung einer Unterverteilung nach ihrem eigenen Verteiler-GZF wird als virtuelle, schreibgeschützte Zeile genau dem gewählten diff --git a/docs/print-view.md b/docs/print-view.md index a843030..ecc00e2 100644 --- a/docs/print-view.md +++ b/docs/print-view.md @@ -38,8 +38,9 @@ automatisch bei späteren Änderungen in einem anderen Tab. 3. **Verteilerpläne (quer, je Verteiler)** – Titelleiste mit Verteilernummer, Bezeichnung, Örtlichkeit, Netzart, „Gespeist von“ und Pgl; darunter Kopfkomponenten, Gruppen, Stromkreise - (mehrzeilige mit Sammelzeile, eingerückten Gerätezeilen und - schreibgeschützten Unterverteilungszeilen), + (reine 1:1-Einspeiseabgänge kompakt in einer Zeile; sonst mehrzeilig mit + Sammelzeile, eingerückten Gerätezeilen und schreibgeschützten + Unterverteilungszeilen), Gruppensummen und Verteilersumme. Fehlende Kabelangaben sind als „offen“ markiert. Die Titelleiste steht im Tabellenkopf und wiederholt sich beim Drucken auf Folgeseiten. diff --git a/src/app/globals.css b/src/app/globals.css index d14431b..88df3e9 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1537,6 +1537,10 @@ a.kpi:hover { background: var(--panel-bg-subtle); } +.tree-grid .feeder-circuit-row td:nth-child(2) { + font-weight: 600; +} + .tree-grid .device-row td:first-child { color: var(--text-faint); } diff --git a/src/frontend/components/circuit-tree-editor.tsx b/src/frontend/components/circuit-tree-editor.tsx index bac08ce..f75b64e 100644 --- a/src/frontend/components/circuit-tree-editor.tsx +++ b/src/frontend/components/circuit-tree-editor.tsx @@ -1766,7 +1766,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const currentDisplay = mode === "replaceWithTypedChar" && cell.cellKey !== "phaseType" ? typedChar ?? "" - : String(visibleCell.value ?? ""); + : String(visibleCell.editValue ?? visibleCell.value ?? ""); focusTokenRef.current += 1; setEditingCell({ ...cell, @@ -4077,7 +4077,9 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str key={row.rowKey} className={`${ row.rowType === "circuitSummary" - ? "summary-row" + ? row.downstreamBoardLoad + ? "feeder-circuit-row" + : "summary-row" : row.rowType === "deviceRow" ? "device-row" : row.rowType === "downstreamBoardLoad" @@ -4708,11 +4710,19 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str tabIndex={-1} /> 0 + } icon={Trash2} label="Stromkreis löschen" onClick={() => void handleDeleteCircuit(row.circuit!.id)} tabIndex={-1} + title={ + (row.circuit.downstreamBoardLoads?.length ?? 0) > 0 + ? "Speist eine Unterverteilung – zuerst deren Einspeisung ändern" + : undefined + } variant="danger" /> diff --git a/src/frontend/print/print-document.tsx b/src/frontend/print/print-document.tsx index 5a0152b..a13d7e1 100644 --- a/src/frontend/print/print-document.tsx +++ b/src/frontend/print/print-document.tsx @@ -431,6 +431,25 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { ); } + if (rows.length === 0 && downstreamBoards.length === 1) { + const boardLabel = + downstreamBoards[0].boardNumber ?? downstreamBoards[0].name; + return ( + + {circuit.equipmentIdentifier} + + {boardLabel} + {circuit.displayName ? ( + · {circuit.displayName} + ) : null} + + – + + {formatKilowatt(circuit.circuitTotalPower)} + {circuitCells} + + ); + } if (rows.length === 1 && downstreamBoards.length === 0) { const row = rows[0]; const title = circuit.displayName ?? row.displayName; diff --git a/src/frontend/utils/circuit-grid-model.ts b/src/frontend/utils/circuit-grid-model.ts index faa4a11..fafeca4 100644 --- a/src/frontend/utils/circuit-grid-model.ts +++ b/src/frontend/utils/circuit-grid-model.ts @@ -617,7 +617,11 @@ export function getCellKind(rowType: RowType, key: CellKey): CellKind { if (rowType === "deviceRow") return deviceFieldKeys.has(key) ? "deviceField" : "readonly"; if (rowType === "downstreamBoardLoad") return "readonly"; if (rowType === "circuitSummary") return circuitFieldKeys.has(key) ? "circuitField" : "readonly"; - if (rowType === "reserveCircuit" || rowType === "circuitCompact") { + if (rowType === "reserveCircuit") { + if (circuitFieldKeys.has(key)) return "circuitField"; + if (deviceFieldKeys.has(key)) return "deviceField"; + } + if (rowType === "circuitCompact") { if (deviceFieldKeys.has(key)) return "deviceField"; if (circuitFieldKeys.has(key)) return "circuitField"; } diff --git a/src/frontend/utils/circuit-grid-projection.ts b/src/frontend/utils/circuit-grid-projection.ts index a9b11de..30e5ecf 100644 --- a/src/frontend/utils/circuit-grid-projection.ts +++ b/src/frontend/utils/circuit-grid-projection.ts @@ -37,6 +37,8 @@ export interface VisibleGridCell { editable: boolean; kind: CellKind; value: GridValue; + /** Separate persisted value when the displayed value is derived. */ + editValue?: GridValue; } export interface VisibleGridRow { @@ -144,6 +146,7 @@ function makeVisibleGridRow( const kind = getCellKind(rowType, column.key); const editable = kind === "circuitField" || kind === "deviceField"; let value: GridValue; + let editValue: GridValue | undefined; if (rowType === "downstreamBoardLoad" && downstreamBoardLoad) { value = column.key === "displayName" @@ -155,6 +158,35 @@ function makeVisibleGridRow( : column.key === "remark" ? "Automatisch aus der verknüpften Verteilung" : undefined; + } else if ( + rowType === "circuitSummary" && + circuit && + downstreamBoardLoad && + circuit.deviceRows.length === 0 + ) { + if (column.key === "displayName") { + const boardLabel = + downstreamBoardLoad.boardNumber ?? downstreamBoardLoad.name; + value = circuit.displayName + ? `${boardLabel} · ${circuit.displayName}` + : boardLabel; + editValue = circuit.displayName ?? ""; + } else if (column.key === "cosPhi") { + value = circuit.circuitCosPhi; + } else if ( + kind === "computed" && + circuitOnlyColumns.has(column.key) + ) { + value = getCircuitValue(circuit, column.key); + } else if (kind === "circuitField") { + value = getCircuitValue(circuit, column.key); + } else if (column.key === "rowTotalPower") { + value = circuit.circuitTotalPower; + } else if (column.key === "circuitTotalPower") { + value = circuit.circuitTotalPower; + } else if (column.key === "voltage") { + value = circuit.voltage; + } } else if (rowType === "placeholder") { value = column.key === "equipmentIdentifier" ? "-frei-" : undefined; } else if (kind === "deviceField" && device) { @@ -178,7 +210,7 @@ function makeVisibleGridRow( value = circuit.voltage; } - return { cellKey: column.key, editable, kind, value }; + return { cellKey: column.key, editable, kind, value, editValue }; }); return { @@ -247,6 +279,19 @@ export function buildVisibleGridRowsWithStructure( const downstreamLoads = circuit.downstreamBoardLoads ?? []; if (circuit.deviceRows.length === 0 && downstreamLoads.length === 0) { rows.push(makeVisibleGridRow("reserveCircuit", section.id, circuit)); + } else if ( + circuit.deviceRows.length === 0 && + downstreamLoads.length === 1 + ) { + rows.push( + makeVisibleGridRow( + "circuitSummary", + section.id, + circuit, + undefined, + downstreamLoads[0] + ) + ); } else if (circuit.deviceRows.length === 1 && downstreamLoads.length === 0) { rows.push(makeVisibleGridRow("circuitCompact", section.id, circuit, circuit.deviceRows[0])); } else { diff --git a/tests/circuit-grid-model.test.ts b/tests/circuit-grid-model.test.ts index 641a770..475d781 100644 --- a/tests/circuit-grid-model.test.ts +++ b/tests/circuit-grid-model.test.ts @@ -133,7 +133,9 @@ describe("circuit grid model", () => { assert.equal(getCellKind("circuitCompact", "equipmentIdentifier"), "circuitField"); assert.equal(getCellKind("circuitSummary", "displayName"), "circuitField"); assert.equal(getCellKind("deviceRow", "displayName"), "deviceField"); - assert.equal(getCellKind("reserveCircuit", "remark"), "deviceField"); + assert.equal(getCellKind("reserveCircuit", "displayName"), "circuitField"); + assert.equal(getCellKind("reserveCircuit", "remark"), "circuitField"); + assert.equal(getCellKind("reserveCircuit", "powerPerUnit"), "deviceField"); assert.equal(getCellKind("placeholder", "displayName"), "deviceField"); assert.equal(getCellKind("deviceRow", "equipmentIdentifier"), "readonly"); assert.equal(getCellKind("circuitSummary", "controlRequirement"), "circuitField"); diff --git a/tests/circuit-grid-projection.test.ts b/tests/circuit-grid-projection.test.ts index 1a16913..6551aee 100644 --- a/tests/circuit-grid-projection.test.ts +++ b/tests/circuit-grid-projection.test.ts @@ -179,9 +179,10 @@ describe("circuit grid projection", () => { ); }); - it("renders linked downstream boards as separate read-only rows", () => { + it("renders one linked downstream board as one compact editable circuit row", () => { const feeder = { ...reserveCircuit, + displayName: undefined, isReserve: false, circuitTotalPower: 4, circuitApparentPower: 5, @@ -202,19 +203,65 @@ describe("circuit grid projection", () => { assert.deepEqual(rows.map((row) => row.rowType), [ "section", "circuitSummary", - "downstreamBoardLoad", "placeholder", ]); - const loadRow = rows[2]; + const loadRow = rows[1]; assert.equal( loadRow.cells.find((cell) => cell.cellKey === "displayName")?.value, - "Unterverteilung UV-02" + "UV-02" + ); + assert.equal( + loadRow.cells.find((cell) => cell.cellKey === "displayName")?.editValue, + "" ); assert.equal( loadRow.cells.find((cell) => cell.cellKey === "rowTotalPower")?.value, 4 ); - assert.equal(loadRow.cells.every((cell) => !cell.editable), true); + assert.equal( + loadRow.cells.find((cell) => cell.cellKey === "displayName")?.kind, + "circuitField" + ); + }); + + it("keeps separate read-only rows for several linked downstream boards", () => { + const feeder = { + ...reserveCircuit, + isReserve: false, + circuitTotalPower: 6, + circuitApparentPower: 7, + circuitCosPhi: 6 / 7, + downstreamBoardLoads: [ + { + distributionBoardId: "board-a", + name: "Unterverteilung A", + boardNumber: "UV-A", + activePowerKw: 4, + apparentPowerKva: 5, + cosPhi: 0.8, + }, + { + distributionBoardId: "board-b", + name: "Unterverteilung B", + boardNumber: "UV-B", + activePowerKw: 2, + apparentPowerKva: 2, + cosPhi: 1, + }, + ], + }; + const rows = buildVisibleGridRowsWithStructure( + [{ ...sections[0], circuits: [feeder] }], + { headerComponents: [], footerComponents: [] } + ); + assert.deepEqual(rows.map((row) => row.rowType), [ + "section", + "circuitSummary", + "downstreamBoardLoad", + "downstreamBoardLoad", + "placeholder", + ]); + assert.equal(rows[2].cells.every((cell) => !cell.editable), true); }); it("shows circuit protection once on each visible circuit row", () => { From 847f4e9493c1c6fb55d63c7728d176c781592f0a Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 22:42:03 +0200 Subject: [PATCH 23/38] Harden user management integration --- src/app/config/layout.tsx | 27 +++---- src/app/config/page.tsx | 4 +- src/db/repositories/user.repository.ts | 84 ++++++++++++++------- src/db/schema/users.ts | 3 +- src/domain/ports/user.store.ts | 40 ++++++++++ src/domain/services/user.service.ts | 64 ++++++++-------- src/frontend/components/Sidebar.tsx | 24 +++--- src/frontend/components/cable-sizing-api.ts | 9 ++- src/frontend/utils/api.ts | 5 ++ src/frontend/utils/auth-api.ts | 11 ++- src/frontend/utils/config-access.ts | 25 ++++++ src/server/auth/auth.middleware.ts | 23 ++++-- src/server/auth/password.ts | 44 +++++++++-- src/server/composition/auth.ts | 7 +- src/shared/constants/request-security.ts | 2 + tests/authentication.test.ts | 67 ++++++++++++++-- tests/config-access.test.ts | 26 +++++++ tests/write-request-headers.test.ts | 40 ++++++++++ 18 files changed, 394 insertions(+), 111 deletions(-) create mode 100644 src/domain/ports/user.store.ts create mode 100644 src/frontend/utils/config-access.ts create mode 100644 src/shared/constants/request-security.ts create mode 100644 tests/config-access.test.ts create mode 100644 tests/write-request-headers.test.ts diff --git a/src/app/config/layout.tsx b/src/app/config/layout.tsx index 1356d78..72d9b6d 100644 --- a/src/app/config/layout.tsx +++ b/src/app/config/layout.tsx @@ -4,26 +4,27 @@ import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; import { useEffect } from "react"; import { useAuth } from "../../frontend/components/AuthProvider"; - -const CONFIG_TABS = [ - { href: "/config/benutzer", label: "Benutzer" }, - { href: "/config/konto", label: "Konto" }, -] as const; +import { + getConfigRedirect, + getConfigTabs, +} from "../../frontend/utils/config-access"; export default function ConfigLayout({ children }: { children: React.ReactNode }) { const pathname = usePathname(); const router = useRouter(); const { status, isAdmin } = useAuth(); + const tabs = getConfigTabs(isAdmin); + const redirectTarget = getConfigRedirect(pathname, isAdmin); useEffect(() => { - // LoginGate already guarantees a signed-in user with a set password by - // the time this layout renders; only the role still needs checking. - if (status === "signed-in" && !isAdmin) { - router.replace("/"); - } - }, [status, isAdmin, router]); + if (status !== "signed-in") return; + if (redirectTarget) router.replace(redirectTarget); + }, [status, redirectTarget, router]); - if (status !== "signed-in" || !isAdmin) { + if ( + status !== "signed-in" || + redirectTarget !== null + ) { return null; } @@ -34,7 +35,7 @@ export default function ConfigLayout({ children }: { children: React.ReactNode }
- {isAdmin && ( - - )} +
{user && !isCollapsed && (
diff --git a/src/frontend/components/cable-sizing-api.ts b/src/frontend/components/cable-sizing-api.ts index 28530d2..73582b5 100644 --- a/src/frontend/components/cable-sizing-api.ts +++ b/src/frontend/components/cable-sizing-api.ts @@ -6,6 +6,10 @@ import type { CableSizingInput, CableSizingResult, } from "../../cable-sizing/domain/cable-sizing-calculation"; +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../../shared/constants/request-security"; export interface CalculateCableSizingResponse { result: CableSizingResult; @@ -17,7 +21,10 @@ export async function calculateCableSizing( ): Promise { const response = await fetch("/api/cable-sizing/calculate", { method: "POST", - headers: { "Content-Type": "application/json" }, + headers: { + "Content-Type": "application/json", + [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, + }, body: JSON.stringify(input), cache: "no-store", }); diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index 8f5a878..5256195 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -1,3 +1,7 @@ +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../../shared/constants/request-security"; import type { BuildingDto, CircuitListDto, @@ -122,6 +126,7 @@ async function request(url: string, init?: RequestInit): Promise { ...init, headers: { "Content-Type": "application/json", + [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, ...init?.headers, }, cache: "no-store", diff --git a/src/frontend/utils/auth-api.ts b/src/frontend/utils/auth-api.ts index f7057f9..a6f12b3 100644 --- a/src/frontend/utils/auth-api.ts +++ b/src/frontend/utils/auth-api.ts @@ -1,3 +1,8 @@ +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../../shared/constants/request-security"; + // Small, self-contained fetch helper for the auth/user endpoints - kept // separate from the large domain api.ts so this feature doesn't have to // touch that file's shared `request()` internals. @@ -39,7 +44,11 @@ export class AuthApiError extends Error { async function request(url: string, init?: RequestInit): Promise { const response = await fetch(url, { ...init, - headers: { "Content-Type": "application/json", ...init?.headers }, + headers: { + "Content-Type": "application/json", + [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, + ...init?.headers, + }, cache: "no-store", }); if (!response.ok) { diff --git a/src/frontend/utils/config-access.ts b/src/frontend/utils/config-access.ts new file mode 100644 index 0000000..86dd2a2 --- /dev/null +++ b/src/frontend/utils/config-access.ts @@ -0,0 +1,25 @@ +export interface ConfigNavigationEntry { + href: string; + label: string; +} + +const ACCOUNT_ENTRY = { href: "/config/konto", label: "Konto" } as const; +const USERS_ENTRY = { href: "/config/benutzer", label: "Benutzer" } as const; + +export function getConfigTabs(isAdmin: boolean): ConfigNavigationEntry[] { + return isAdmin ? [USERS_ENTRY, ACCOUNT_ENTRY] : [ACCOUNT_ENTRY]; +} + +export function getConfigEntry(isAdmin: boolean): ConfigNavigationEntry { + return isAdmin ? { href: USERS_ENTRY.href, label: "Config" } : ACCOUNT_ENTRY; +} + +export function getConfigRedirect(pathname: string | null, isAdmin: boolean): string | null { + if (pathname === "/config") { + return isAdmin ? USERS_ENTRY.href : ACCOUNT_ENTRY.href; + } + if (!isAdmin && pathname?.startsWith(USERS_ENTRY.href)) { + return ACCOUNT_ENTRY.href; + } + return null; +} diff --git a/src/server/auth/auth.middleware.ts b/src/server/auth/auth.middleware.ts index ce65bfb..bafae03 100644 --- a/src/server/auth/auth.middleware.ts +++ b/src/server/auth/auth.middleware.ts @@ -2,8 +2,12 @@ import type { NextFunction, Request, RequestHandler, Response } from "express"; import { SESSION_COOKIE, type AuthConfig } from "./auth-config.js"; import { readCookie } from "./cookie.js"; import type { SessionStore } from "./sessions.js"; -import type { UserRepository } from "../../db/repositories/user.repository.js"; +import type { UserStore } from "../../domain/ports/user.store.js"; import type { UserRole } from "../../shared/constants/user-roles.js"; +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../../shared/constants/request-security.js"; export interface AuthUser { id: string; @@ -30,7 +34,7 @@ export function sessionIdFromRequest(req: { export async function identityFromRequest( req: { headers: { cookie?: string | undefined } }, sessions: SessionStore, - users: UserRepository, + users: Pick, slideExpiry = true ): Promise { const session = sessions.get(sessionIdFromRequest(req), slideExpiry); @@ -74,10 +78,11 @@ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); * CSRF defense for cookie-authenticated writes. * * SameSite=Lax alone is not enough here: every other service on the same - * host (other ports of the same IP) counts as "same-site" and would get the - * cookie attached. Browsers send Sec-Fetch-Site on every request, so a write - * is only accepted from the app's own origin. Clients without the header - * (curl, scripts) carry no ambient browser cookie and are not a CSRF vector. + * host (other ports of the same IP) counts as "same-site" and may receive the + * cookie. Fetch Metadata is also not guaranteed on plain HTTP in the LAN. + * Every write therefore needs an application header that HTML forms cannot + * set; a cross-origin fetch would require a CORS preflight, which the API does + * not permit. Sec-Fetch-Site remains an additional browser-side check. */ export function requireSameOriginForWrites(): RequestHandler { return (req: Request, res: Response, next: NextFunction) => { @@ -85,6 +90,10 @@ export function requireSameOriginForWrites(): RequestHandler { next(); return; } + if (req.get(WRITE_REQUEST_HEADER_NAME) !== WRITE_REQUEST_HEADER_VALUE) { + res.status(403).json({ error: "Schreibzugriff ohne gültigen Anwendungsnachweis abgelehnt." }); + return; + } const fetchSite = req.headers["sec-fetch-site"]; if (fetchSite === undefined || fetchSite === "same-origin" || fetchSite === "none") { next(); @@ -98,7 +107,7 @@ export function requireSameOriginForWrites(): RequestHandler { export function createAuthGuard( authConfig: AuthConfig, sessions: SessionStore, - users: UserRepository, + users: Pick, openPaths: readonly string[] = ["/auth/login", "/auth/status", "/auth/logout"] ): RequestHandler { return (req: Request, res: Response, next: NextFunction) => { diff --git a/src/server/auth/password.ts b/src/server/auth/password.ts index 96814e1..97132af 100644 --- a/src/server/auth/password.ts +++ b/src/server/auth/password.ts @@ -4,6 +4,12 @@ const SCRYPT_N = 16384; const SCRYPT_R = 8; const SCRYPT_P = 1; const KEY_LENGTH = 64; +const SALT_LENGTH = 16; +const MAX_SCRYPT_MEMORY = 64 * 1024 * 1024; +const MIN_SCRYPT_N = 1 << 14; +const MAX_SCRYPT_N = 1 << 16; +const MAX_SCRYPT_R = 16; +const MAX_SCRYPT_P = 8; // A hand-rolled wrapper instead of util.promisify(scrypt): promisify only // resolves to scrypt's 3-argument overload, so the 4-argument form used for @@ -30,8 +36,13 @@ function scryptAsync( // Format: scrypt$N$r$p$saltHex$hashHex - the parameters travel with the // hash so they can be tuned later without invalidating existing rows. export async function hashPassword(password: string): Promise { - const salt = randomBytes(16); - const derivedKey = await scryptAsync(password, salt, KEY_LENGTH); + const salt = randomBytes(SALT_LENGTH); + const derivedKey = await scryptAsync(password, salt, KEY_LENGTH, { + N: SCRYPT_N, + r: SCRYPT_R, + p: SCRYPT_P, + maxmem: MAX_SCRYPT_MEMORY, + }); return [ "scrypt", SCRYPT_N, @@ -52,12 +63,33 @@ export async function verifyPassword( const n = Number(nRaw); const r = Number(rRaw); const p = Number(pRaw); - if (!Number.isFinite(n) || !Number.isFinite(r) || !Number.isFinite(p)) { + if ( + !Number.isSafeInteger(n) || + n < MIN_SCRYPT_N || + n > MAX_SCRYPT_N || + (n & (n - 1)) !== 0 || + !Number.isSafeInteger(r) || + r < 1 || + r > MAX_SCRYPT_R || + !Number.isSafeInteger(p) || + p < 1 || + p > MAX_SCRYPT_P || + !/^[0-9a-f]{32}$/i.test(saltHex) || + !/^[0-9a-f]{128}$/i.test(hashHex) + ) { return false; } const salt = Buffer.from(saltHex, "hex"); const expected = Buffer.from(hashHex, "hex"); - const derivedKey = await scryptAsync(password, salt, expected.length, { N: n, r, p }); - if (derivedKey.length !== expected.length) return false; - return timingSafeEqual(derivedKey, expected); + try { + const derivedKey = await scryptAsync(password, salt, expected.length, { + N: n, + r, + p, + maxmem: MAX_SCRYPT_MEMORY, + }); + return timingSafeEqual(derivedKey, expected); + } catch { + return false; + } } diff --git a/src/server/composition/auth.ts b/src/server/composition/auth.ts index 1b5ce09..07b822b 100644 --- a/src/server/composition/auth.ts +++ b/src/server/composition/auth.ts @@ -3,9 +3,14 @@ import { LoginThrottle } from "../auth/login-throttle.js"; import { SessionStore } from "../auth/sessions.js"; import { UserService } from "../../domain/services/user.service.js"; import { userRepository } from "./application-repositories.js"; +import { hashPassword, verifyPassword } from "../auth/password.js"; export const authConfig = readAuthConfig(); export const sessionStore = new SessionStore(authConfig.sessionTtlMs, authConfig.sessionMaxAgeMs); sessionStore.startSweeping(); export const loginThrottle = new LoginThrottle(); -export const userService = new UserService(userRepository, authConfig); +export const userService = new UserService( + userRepository, + { bootstrap: authConfig.bootstrap }, + { hash: hashPassword, verify: verifyPassword } +); diff --git a/src/shared/constants/request-security.ts b/src/shared/constants/request-security.ts new file mode 100644 index 0000000..f89ce10 --- /dev/null +++ b/src/shared/constants/request-security.ts @@ -0,0 +1,2 @@ +export const WRITE_REQUEST_HEADER_NAME = "X-Leistungsbilanz-Request"; +export const WRITE_REQUEST_HEADER_VALUE = "1"; diff --git a/tests/authentication.test.ts b/tests/authentication.test.ts index e634716..e5c431d 100644 --- a/tests/authentication.test.ts +++ b/tests/authentication.test.ts @@ -21,6 +21,10 @@ import { requireSameOriginForWrites } from "../src/server/auth/auth.middleware.j import type { AuthConfig } from "../src/server/auth/auth-config.js"; import { createUserSchema } from "../src/shared/validation/user.schemas.js"; import { loginSchema } from "../src/shared/validation/auth.schemas.js"; +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../src/shared/constants/request-security.js"; const HOUR = 60 * 60 * 1000; @@ -34,7 +38,14 @@ function createUserService() { cookieSecure: false, bootstrap: { username: "admin", password: "bootstrap-password-123" }, }; - return { repository, service: new UserService(repository, config) }; + return { + repository, + service: new UserService( + repository, + { bootstrap: config.bootstrap }, + { hash: hashPassword, verify: verifyPassword } + ), + }; } describe("password hashing", () => { @@ -52,6 +63,17 @@ describe("password hashing", () => { it("rejects malformed stored hashes instead of throwing", async () => { assert.equal(await verifyPassword("x", "not-a-hash"), false); assert.equal(await verifyPassword("x", "scrypt$a$b$c$00$00"), false); + assert.equal( + await verifyPassword( + "x", + `scrypt$1073741824$8$1$${"00".repeat(16)}$${"00".repeat(64)}` + ), + false + ); + assert.equal( + await verifyPassword("x", `scrypt$16384$8$1$00$${"00".repeat(64)}`), + false + ); }); }); @@ -135,12 +157,20 @@ describe("cookie parsing", () => { }); describe("same-origin guard for writes", () => { - function run(method: string, fetchSite?: string) { + function run(method: string, fetchSite?: string, includeApplicationHeader = true) { let status: number | undefined; let passed = false; const req = { method, - headers: fetchSite ? { "sec-fetch-site": fetchSite } : {}, + headers: { + ...(fetchSite ? { "sec-fetch-site": fetchSite } : {}), + ...(includeApplicationHeader + ? { [WRITE_REQUEST_HEADER_NAME.toLowerCase()]: WRITE_REQUEST_HEADER_VALUE } + : {}), + }, + get(name: string) { + return this.headers[name.toLowerCase() as keyof typeof this.headers]; + }, } as unknown as Request; const res = { status(code: number) { @@ -158,12 +188,13 @@ describe("same-origin guard for writes", () => { } it("lets reads and same-origin writes through", () => { - assert.equal(run("GET", "cross-site").passed, true); + assert.equal(run("GET", "cross-site", false).passed, true); assert.equal(run("POST", "same-origin").passed, true); - assert.equal(run("POST").passed, true, "non-browser clients carry no ambient cookie"); + assert.equal(run("POST").passed, true, "scripts can send the explicit application header"); }); - it("rejects writes from other sites and other ports of the same host", () => { + it("rejects writes without the application header or from another origin", () => { + assert.deepEqual(run("POST", undefined, false), { passed: false, status: 403 }); assert.deepEqual(run("POST", "cross-site"), { passed: false, status: 403 }); assert.deepEqual(run("PATCH", "same-site"), { passed: false, status: 403 }); assert.deepEqual(run("DELETE", "same-site"), { passed: false, status: 403 }); @@ -239,6 +270,30 @@ describe("user service", () => { await assert.rejects(service.updateRoleAndActive(second.id, { active: false }), LastAdminError); }); + it("preserves one active admin across concurrent updates", async () => { + const { repository, service } = createUserService(); + await service.ensureBootstrapAdmin(); + const second = await service.createUser({ + username: "zweiter-admin", + name: "Zweiter Admin", + role: "admin", + initialPassword: "start-passwort", + }); + assert.ok(second); + const [first] = (await repository.list()).filter((user) => user.username === "admin"); + + const results = await Promise.allSettled([ + service.updateRoleAndActive(first.id, { role: "user" }), + service.updateRoleAndActive(second.id, { role: "user" }), + ]); + assert.equal(results.filter((result) => result.status === "fulfilled").length, 1); + assert.equal(results.filter((result) => result.status === "rejected").length, 1); + const activeAdmins = (await repository.list()).filter( + (user) => user.role === "admin" && user.active + ); + assert.equal(activeAdmins.length, 1); + }); + it("requires the current password and a different new one", async () => { const { service } = createUserService(); const user = await service.createUser({ diff --git a/tests/config-access.test.ts b/tests/config-access.test.ts new file mode 100644 index 0000000..3fdc83d --- /dev/null +++ b/tests/config-access.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + getConfigEntry, + getConfigRedirect, + getConfigTabs, +} from "../src/frontend/utils/config-access.js"; + +describe("config access", () => { + it("offers account settings to every signed-in user", () => { + assert.deepEqual(getConfigEntry(false), { href: "/config/konto", label: "Konto" }); + assert.deepEqual(getConfigTabs(false), [{ href: "/config/konto", label: "Konto" }]); + assert.equal(getConfigRedirect("/config", false), "/config/konto"); + assert.equal(getConfigRedirect("/config/konto", false), null); + }); + + it("keeps user administration admin-only", () => { + assert.equal(getConfigRedirect("/config/benutzer", false), "/config/konto"); + assert.deepEqual(getConfigTabs(true), [ + { href: "/config/benutzer", label: "Benutzer" }, + { href: "/config/konto", label: "Konto" }, + ]); + assert.deepEqual(getConfigEntry(true), { href: "/config/benutzer", label: "Config" }); + assert.equal(getConfigRedirect("/config/benutzer", true), null); + }); +}); diff --git a/tests/write-request-headers.test.ts b/tests/write-request-headers.test.ts new file mode 100644 index 0000000..c78a277 --- /dev/null +++ b/tests/write-request-headers.test.ts @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { authApi } from "../src/frontend/utils/auth-api.js"; +import { createProject } from "../src/frontend/utils/api.js"; +import { calculateCableSizing } from "../src/frontend/components/cable-sizing-api.js"; +import type { CableSizingInput } from "../src/cable-sizing/domain/cable-sizing-calculation.js"; +import { + WRITE_REQUEST_HEADER_NAME, + WRITE_REQUEST_HEADER_VALUE, +} from "../src/shared/constants/request-security.js"; + +describe("write request clients", () => { + it("send the application header from every frontend API client", async () => { + const originalFetch = globalThis.fetch; + const requests: RequestInit[] = []; + globalThis.fetch = async (_input, init) => { + requests.push(init ?? {}); + return new Response(JSON.stringify({}), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }; + + try { + await authApi.login("admin", "start-passwort"); + await createProject("Testprojekt"); + await calculateCableSizing({} as CableSizingInput); + } finally { + globalThis.fetch = originalFetch; + } + + assert.equal(requests.length, 3); + for (const request of requests) { + assert.equal( + new Headers(request.headers).get(WRITE_REQUEST_HEADER_NAME), + WRITE_REQUEST_HEADER_VALUE + ); + } + }); +}); From 3670f02ccdec07dacac7b475ea328dd72dad670a Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 22:42:11 +0200 Subject: [PATCH 24/38] Document authenticated deployment --- .env.example | 7 +++++++ .gitignore | 3 +++ AGENTS.md | 5 ++++- README.md | 21 ++++++++++++++++---- compose.dev.yaml | 2 ++ compose.yaml | 2 +- docs/authentication.md | 25 ++++++++++++++++++------ docs/current-architecture.md | 14 +++++++++++++ docs/deployment.md | 38 ++++++++++++++++++++++++++++-------- 9 files changed, 97 insertions(+), 20 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..46fa42a --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +# Nur beim ersten Start mit leerer Benutzertabelle erforderlich. +AUTH_BOOTSTRAP_USERNAME= +AUTH_BOOTSTRAP_PASSWORT= +AUTH_SESSION_HOURS=12 +AUTH_SESSION_MAX_DAYS=7 +# Hinter HTTPS true, bei direktem HTTP-Zugriff im LAN false. +COOKIE_SECURE=false diff --git a/.gitignore b/.gitignore index a6e1ff5..b237969 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ node_modules/ dist/ .next/ +.env +.env.* +!.env.example # Streuprodukt von tsc; drizzle-kit liest drizzle.config.ts. /drizzle.config.js data/*.db diff --git a/AGENTS.md b/AGENTS.md index 65b5fab..b01e6b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,10 @@ It must support circuits, device rows, project devices, drag-and-drop restructur `src/db/repositories/user.repository.ts`. Every `/api/*` route requires a signed-in user (`src/server/index.ts`); `/api/users/*` additionally requires `admin`. Frontend gate: `AuthProvider` + `LoginGate` - (`src/app/layout.tsx`). See `docs/authentication.md` for the full picture. + (`src/app/layout.tsx`). Every unsafe API request also requires the explicit + `X-Leistungsbilanz-Request: 1` application header, including over plain HTTP. + Account settings are available to every signed-in user; user administration + remains admin-only. See `docs/authentication.md` for the full picture. The supported runtime model is Circuit-First. The former Consumer UI, API, tables and upgrade tooling are removed; do not reintroduce them. diff --git a/README.md b/README.md index b01ae85..f64ae04 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ Gerätezeilen und wiederverwendbare Projektgeräte fachlich getrennt behandelt. Das Projekt befindet sich in aktiver Entwicklung. Für SQLite stehen ein Docker-Server-Stack mit gebautem Anwendungscode und ein separater Entwicklungsstack bereit. Ein vollständig unterstütztes Produktionsdeployment -und Mehrbenutzerbetrieb fehlen weiterhin. Revit-CSV-Konfiguration, Vorschau +für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstütztes +Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind +vorhanden. Revit-CSV-Konfiguration, Vorschau und bestätigter Erstimport sind implementiert; die Editoroberfläche zur Objektzuordnung, Folgeimporte und Rückexport stehen noch aus. Die weitere Revit-Arbeit ist zurückgestellt und erfolgt später über den CSV-Export/-Import @@ -60,6 +62,8 @@ Voraussetzungen: ```powershell git clone Set-Location leistungsbilanz-ts +$env:AUTH_BOOTSTRAP_USERNAME = "admin" +$env:AUTH_BOOTSTRAP_PASSWORT = "" docker compose up --build --detach ``` @@ -68,9 +72,15 @@ Danach: - Frontend: - API-Healthcheck: (über den Next.js-Rewrite) -Die Express-API ist nicht mehr auf dem Host veröffentlicht. Sie hat keine -Authentifizierung und ist nur innerhalb des Compose-Netzes erreichbar; der -Zugriff läuft über den Rewrite im Web-Dienst. +Beim ersten Start erzeugen diese beiden Variablen genau einen Administrator, +solange die Benutzertabelle noch leer ist. Danach werden sie ignoriert. Für +einen dauerhaften Serverbetrieb gehören die Werte in eine nicht versionierte +`.env` neben `compose.yaml`; Details stehen unter +[Anmeldung und Benutzerverwaltung](docs/authentication.md). + +Die Express-API ist nicht auf dem Host veröffentlicht. Sämtliche fachlichen +API-Routen verlangen eine gültige Anmeldung; der Zugriff läuft über den +Rewrite im Web-Dienst. Der API-Container führt ausstehende Migrationen und die Schemaprüfung beim Start automatisch aus. Die SQLite-Datei liegt auf dem Host unter @@ -116,6 +126,8 @@ Voraussetzungen: npm ci npm run db:migrate npm run db:verify:circuit-schema +$env:AUTH_BOOTSTRAP_USERNAME = "admin" +$env:AUTH_BOOTSTRAP_PASSWORT = "" npm run dev:api ``` @@ -162,6 +174,7 @@ vor der Baseline werden nicht unterstützt. - [Gebäudestruktur und Raumflächen](docs/building-structure.md) - [Grobe Leistungsbilanz](docs/estimate-balance.md) - [Leitungsberechnung](docs/cable-sizing-module.md) +- [Anmeldung und Benutzerverwaltung](docs/authentication.md) - [Entwicklungs- und Contributor-Workflow](docs/development-workflow.md) - [Bekannte Einschränkungen](docs/circuit-list-editor-known-limitations.md) - [Roadmap](docs/spec/07-implementation-phases-todo.md) diff --git a/compose.dev.yaml b/compose.dev.yaml index 2c362bc..f49e9e6 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -38,6 +38,8 @@ services: AUTH_BOOTSTRAP_USERNAME: "${AUTH_BOOTSTRAP_USERNAME:-}" AUTH_BOOTSTRAP_PASSWORT: "${AUTH_BOOTSTRAP_PASSWORT:-}" AUTH_SESSION_HOURS: "${AUTH_SESSION_HOURS:-12}" + AUTH_SESSION_MAX_DAYS: "${AUTH_SESSION_MAX_DAYS:-7}" + COOKIE_SECURE: "${COOKIE_SECURE:-false}" # Nur auf dem Loopback: die API darf nicht aus dem LAN erreichbar sein. ports: - "127.0.0.1:3000:3000" diff --git a/compose.yaml b/compose.yaml index 2a2eecd..1de9104 100644 --- a/compose.yaml +++ b/compose.yaml @@ -47,7 +47,7 @@ services: LOG_LEVEL: "${LOG_LEVEL:-info}" # AUTH_BOOTSTRAP_* legen nur den allerersten Admin an (solange die # users-Tabelle leer ist) und gehoeren in eine lokale, nicht versionierte - # .env - siehe docs/AUTH.md. + # .env - siehe docs/authentication.md. AUTH_BOOTSTRAP_USERNAME: "${AUTH_BOOTSTRAP_USERNAME:-}" AUTH_BOOTSTRAP_PASSWORT: "${AUTH_BOOTSTRAP_PASSWORT:-}" AUTH_SESSION_HOURS: "${AUTH_SESSION_HOURS:-12}" diff --git a/docs/authentication.md b/docs/authentication.md index 15729aa..32039cf 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -7,10 +7,9 @@ Zugang wird von einem Administrator über **Config → Benutzer** angelegt. Es gibt genau zwei Rollen (`src/shared/constants/user-roles.ts`): -- **admin** – wie `user`, zusätzlich Zugriff auf den Config-Bereich - (Benutzerverwaltung, eigenes Konto) +- **admin** – wie `user`, zusätzlich Zugriff auf **Config → Benutzer** - **user** – volle Nutzung der Leistungsbilanz (Projekte, Stromkreislisten, - Grobbilanz, …), kein Zugriff auf Config + Grobbilanz, …) und Zugriff auf das eigene Konto, keine Benutzerverwaltung Es gibt (bewusst, siehe unten) keine konfigurierbare Rechte-Matrix und keine Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. @@ -44,6 +43,8 @@ Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. - **Frontend:** `AuthProvider` lädt `/api/auth/me`; `LoginGate` (`src/app/layout.tsx`) zeigt Login- bzw. Passwortformular, solange nicht angemeldet bzw. `mustChangePassword` gesetzt ist, sonst die App. + **Konto** ist für jede angemeldete Person erreichbar; **Benutzer** nur für + Administratoren. ## Schutzmechanismen @@ -52,12 +53,12 @@ Verknüpfung mit einer Mitarbeiter-/Personen-Stammdatentabelle. | Passwort-Raten (online) | `LoginThrottle`: 5 Fehlversuche je Anmeldename in 15 min → HTTP 429 bis das Fenster abläuft. Schlüssel ist der Name, nicht die IP (alle Anfragen kommen über den Next-Rewrite mit derselben Quell-IP). | | Passwort-Raten (offline, DB-Diebstahl) | scrypt (N=16384, r=8, p=1), eigenes Salt je Hash | | Nutzernamen ausspähen (Timing) | Unbekannte Namen werden gegen einen festen Dummy-Hash geprüft – immer genau ein scrypt-Lauf; einheitliche Fehlermeldung | -| CSRF | SameSite=Lax **plus** `requireSameOriginForWrites`: schreibende Anfragen nur mit `Sec-Fetch-Site: same-origin`. Nötig, weil andere Dienste auf demselben Host (andere Ports) als „same-site“ gelten | -| CSRF über reines HTTP | Browser senden `Sec-Fetch-Site` nur an HTTPS-Adressen. Beim Zugriff per `http://…` im LAN greift deshalb nur SameSite=Lax (schützt gegen fremde Domains, nicht gegen andere Ports desselben Hosts). | +| CSRF | SameSite=Lax **plus** `requireSameOriginForWrites`: jeder Schreibzugriff braucht `X-Leistungsbilanz-Request: 1`; fremde HTML-Formulare können den Header nicht setzen und ein fremder Fetch scheitert an der notwendigen CORS-Preflight-Anfrage. Ein vorhandener `Sec-Fetch-Site`-Header wird zusätzlich geprüft. | +| CSRF über reines HTTP | Der eigene Anwendungsheader gilt auch dann, wenn Browser im HTTP-LAN keinen `Sec-Fetch-Site`-Header senden. Skripte und manuelle API-Aufrufe müssen ihn bei `POST`, `PUT`, `PATCH` und `DELETE` ausdrücklich mitsenden. | | Session-Fixation | Neue Session-ID bei jedem Login und nach jedem Passwortwechsel | | Gestohlenes Cookie | httpOnly; gleitende Laufzeit (`AUTH_SESSION_HOURS`, 12 h) **und** harte Obergrenze (`AUTH_SESSION_MAX_DAYS`, 7 Tage) | | Kompromittiertes Konto | Passwort-Reset und Deaktivieren beenden sofort alle Sessions des Kontos; Passwortwechsel beendet alle anderen | -| Aussperren | Der letzte aktive Admin kann weder herabgestuft noch deaktiviert werden; eigener Zugang ist in der Liste gesperrt | +| Aussperren | Der letzte aktive Admin kann weder herabgestuft noch deaktiviert werden; Prüfung und Änderung laufen atomar in einer SQLite-Transaktion. Der eigene Zugang ist in der Liste gesperrt. | | Rechteausweitung / Mass Assignment | Rolle kommt aus der DB, nie aus der Anfrage; zod-Schemas mit `.strict()` | | DoS über riesige Passwörter | Längengrenzen (Name 100, Passwort 200 Zeichen) vor scrypt | | Look-alike-Namen | Anmeldename nur `a-z 0-9 . _ @ -`, klein geschrieben | @@ -77,6 +78,18 @@ ignoriert; jeder weitere Zugang entsteht über Config → Benutzer. Die Werte gehören in eine lokale, nicht versionierte `.env` auf dem Deploy-Host, nicht in `compose.yaml` selbst. +```dotenv +AUTH_BOOTSTRAP_USERNAME=admin +AUTH_BOOTSTRAP_PASSWORT= +AUTH_SESSION_HOURS=12 +AUTH_SESSION_MAX_DAYS=7 +COOKIE_SECURE=false +``` + +Bei Zugriff über HTTPS muss `COOKIE_SECURE=true` gesetzt werden. Bei direktem +HTTP-Zugriff im LAN bleibt es `false`, da der Browser das Session-Cookie sonst +nicht speichert. + ## Bewusst nicht umgesetzt (Stand jetzt) - Konfigurierbare Rechte-Matrix statt fixer `admin`/`user`-Rollen diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 71b7feb..20c7ccd 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -33,6 +33,15 @@ mit Hot Reload. Das Frontend leitet `/api/*` über `API_INTERNAL_URL` an die API weiter; beim gebauten Stand wird das Ziel zur Build-Zeit festgelegt. Die Datenbank liegt über einen Host-Mount außerhalb des Containers. +Vor allen fachlichen `/api/*`-Routen liegt die Cookie-basierte Anmeldung aus +`src/server/auth`. Nur Login, Status und Logout sind ohne Session erreichbar. +Schreibzugriffe verlangen zusätzlich den Anwendungsheader +`X-Leistungsbilanz-Request: 1`, damit der Schutz auch beim HTTP-Zugriff im LAN +ohne Fetch-Metadata-Header greift. `/api/users/*` ist Administratoren +vorbehalten. Konten sind globale Betriebsdaten und gehören nicht zu +Projektkommandos, Snapshots oder Projekttransfers. Sessions liegen im Speicher +des einzelnen API-Prozesses und enden bei dessen Neustart. + Neue IDs für Stromkreise, Gerätezeilen, Gruppen und Verteilerkomponenten erzeugt der Editor über `src/frontend/utils/client-id.ts` (`createClientId`). Die Hilfsfunktion nutzt `crypto.randomUUID()`, sofern verfügbar, andernfalls @@ -57,6 +66,11 @@ vor dem Command und bleiben über Undo/Redo unverändert. - `src/frontend/components/circuit-grid-*.ts` – reine Grid-Projektion, Zellbesitz, Einfügen und Sicherheitsregeln - `src/frontend/utils/api.ts` – typisierte Frontend-API-Aufrufe +- `src/frontend/components/AuthProvider.tsx` und `LoginGate.tsx` – Anmeldung + und erzwungener Wechsel eines Startpassworts +- `src/server/auth/` – Passwort-Hashing, Sessions und Zugriffsschutz +- `src/domain/services/user.service.ts` und `src/domain/ports/user.store.ts` – + kontobezogene Regeln und schmale Persistenzgrenze - `src/server/index.ts` und `src/server/routes/` – API-Komposition - `src/domain/services/` – fachliche Command- und Synchronisierungsregeln - `src/server/composition/` – Verdrahtung fachlicher Services mit konkreten diff --git a/docs/deployment.md b/docs/deployment.md index 0b5baba..89c99a3 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -16,10 +16,10 @@ und macOS keine inotify-Events durchreichen; das kostet dauerhaft CPU, auch ohne Benutzeraktivität. Dieser Stack gehört deshalb nur auf einen Entwicklungsrechner. -Beide Stacks enthalten weder TLS, Authentifizierung, einen vorgeschalteten -Reverse Proxy noch ein zentral betriebenes Datenbanksystem. Die oben genannten -Container-Schutzmaßnahmen ersetzen diese Funktionen nicht. Der Stack darf -deshalb nicht öffentlich erreichbar gemacht werden. +Beide Stacks enthalten Anmeldung mit festen Rollen, aber weder TLS, einen +vorgeschalteten Reverse Proxy noch ein zentral betriebenes Datenbanksystem. +Passwörter und Session-Cookies werden bei reinem HTTP unverschlüsselt +übertragen. Der Stack darf deshalb nicht öffentlich erreichbar gemacht werden. ## Topologie @@ -29,9 +29,10 @@ deshalb nicht öffentlich erreichbar gemacht werden. | Express API | 3000 | nicht veröffentlicht (Server) / `127.0.0.1:3000` (Dev) | `GET /health` | `./data:/app/data` | | SQLite | Datei | – | Integritäts-/FK-Prüfung via Backup und Skript | `data/leistungsbilanz.db` | -Die Express-API wird im Server-Stack nicht mehr auf dem Host veröffentlicht -(`expose` statt `ports`). Sie hat keine Authentifizierung; jeder, der sie -erreicht, kann jedes Projekt lesen und ändern. Erreichbar ist sie nur aus dem +Die Express-API wird im Server-Stack nicht auf dem Host veröffentlicht +(`expose` statt `ports`). Alle fachlichen API-Routen verlangen eine aktive +Session; Schreibzugriffe zusätzlich den Anwendungsheader +`X-Leistungsbilanz-Request: 1`. Erreichbar ist die API nur aus dem Compose-Netz, praktisch also über den Next.js-Rewrite. Im Entwicklungs-Stack hängen beide Ports am Loopback und sind nicht aus dem LAN erreichbar. @@ -72,6 +73,26 @@ Verwendete Umgebungsvariablen: JSON-Loggers (`error`, `warn`, `info`, `verbose`, `debug`), Standard `info`. Setzbar über eine `.env`-Datei neben `compose.yaml` oder `LOG_LEVEL=verbose docker compose up`. +- `AUTH_BOOTSTRAP_USERNAME` und `AUTH_BOOTSTRAP_PASSWORT` – erzeugen nur bei + leerer Benutzertabelle den ersten Administrator; das Startpasswort hat + mindestens 12 Zeichen. +- `AUTH_SESSION_HOURS` – Inaktivitätsgrenze einer Session, Standard 12 Stunden. +- `AUTH_SESSION_MAX_DAYS` – absolute Session-Laufzeit, Standard 7 Tage. +- `COOKIE_SECURE` – hinter HTTPS `true`; beim direkten HTTP-Zugriff im LAN + `false`, da Browser das Cookie sonst nicht speichern. + +Vor dem ersten Start müssen mindestens die Bootstrap-Werte in einer lokalen, +nicht versionierten `.env` neben `compose.yaml` gesetzt werden: + +```dotenv +AUTH_BOOTSTRAP_USERNAME=admin +AUTH_BOOTSTRAP_PASSWORT= +``` + +Nach dem ersten erfolgreichen Start werden diese Werte ignoriert, solange +mindestens ein Benutzer existiert. Weitere Zugänge legt ein Administrator in +**Config → Benutzer** an. Details stehen in +[Anmeldung und Benutzerverwaltung](authentication.md). Beim API-Start laufen zuerst die Migrationen und die Schemaprüfung (`scripts/run-migrations.js` und `scripts/db-verify-circuit-schema.js`, im @@ -137,7 +158,8 @@ bleibt `sh` der Vordergrundprozess, und `SIGTERM` erreicht Node nie. Vor einer produktiven Installation werden mindestens benötigt: - TLS-Termination und Reverse Proxy -- Authentifizierung, Autorisierung und Benutzer-/Rollenmodell +- zentraler Identitätsanbieter oder eine feinere Rechte-Matrix, falls die zwei + festen Rollen später nicht ausreichen - definierte Secrets- und Konfigurationsverwaltung - persistenter, gesicherter Datenbankbetrieb - kontrollierter einmaliger Migrationsschritt vor dem API-Rollout From cf022b250f882d97bc897b0be4ce5329d29d8e91 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Mon, 28 Sep 2026 22:46:32 +0200 Subject: [PATCH 25/38] Format project device power values on project page Co-Authored-By: Claude Opus 5.5 --- src/app/projects/[projectId]/page.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/projects/[projectId]/page.tsx b/src/app/projects/[projectId]/page.tsx index 37813c1..ec99d54 100644 --- a/src/app/projects/[projectId]/page.tsx +++ b/src/app/projects/[projectId]/page.tsx @@ -73,6 +73,7 @@ import { updateProjectSettings, } from "../../../frontend/utils/api"; import { createClientId } from "../../../frontend/utils/client-id"; +import { formatValue } from "../../../frontend/utils/circuit-grid-model"; import { buildFeederCircuitSnapshot, getDefaultFeederCircuitSection, @@ -1294,10 +1295,11 @@ export default function ProjectDetailPage() { ) : null} - {device.totalPower} kW + {formatValue(device.totalPower, "rowTotalPower")} kW
- {device.quantity} × {device.powerPerUnit} kW · GZF{" "} - {device.simultaneityFactor} + {formatValue(device.quantity, "quantity")} ×{" "} + {formatValue(device.powerPerUnit, "powerPerUnit")} kW · GZF{" "} + {formatValue(device.simultaneityFactor, "simultaneityFactor")}
{device.costGroup ?? "-"} From ae318a51ac05baadf606a8ec3865df2674376ada Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Tue, 29 Sep 2026 21:57:40 +0200 Subject: [PATCH 26/38] Audit Linear Excel integration --- docs/spec/revit-excel-r0-audit.md | 521 ++++++++++++++++++++++++++++++ 1 file changed, 521 insertions(+) create mode 100644 docs/spec/revit-excel-r0-audit.md diff --git a/docs/spec/revit-excel-r0-audit.md b/docs/spec/revit-excel-r0-audit.md new file mode 100644 index 0000000..721e402 --- /dev/null +++ b/docs/spec/revit-excel-r0-audit.md @@ -0,0 +1,521 @@ +# R0 – Audit der Linear-Excel-Anbindung + +Stand: 29.09.2026. Geprüfter Code: `cf022b2`. + +**Status: R0 abgeschlossen, Freigabe für R1–R10 ausstehend.** Dieser Bericht +ist ein Umsetzungsvorschlag, kein Nachweis einer bereits implementierten +Excel-Anbindung. Der neue Nutzerauftrag ersetzt die CSV-/IfcGUID-Vorgaben und +die alte Phasenliste 14.0–14.6. R1 bereinigt die bestehenden Dokumente; R0 +ändert weder Laufzeitcode noch Datenbank noch Oberfläche. + +## 1. Geprüfter Bestand und Keep/Change/Remove + +Gelesene Grundlagen: `AGENTS.md`, `docs/current-architecture.md`, +`docs/project-history-and-external-model-architecture.md`, +`docs/spec/revit-csv-integration-requirements.md` und +`docs/spec/revit-csv-phase-14-audit-and-plan.md`. Der alte Plan widerspricht +sich bereits intern: Sein Status nennt die Erstübernahme noch nicht vorhanden, +während Implementierung und Tests sie nachweisen. Alte Erledigt-Markierungen +werden deshalb nicht übernommen. + +| Bereich / Codebeleg | Entscheidung | Begründung und Änderung | +| --- | --- | --- | +| `src/db/repositories/project-command-transaction.persistence.ts` | Keep | Eine Grenze für Fachänderung, Inverse, Revision und History; auch automatische Snapshots bleiben darin. | +| `src/db/repositories/external-model-state.repository.ts`, `src/db/schema/external-*.ts` | Change | Quelle, Batches, Raum-Mappings und Objekte wiederverwenden; neue Identität, Konfiguration und typisierte Matrix. Schlanke Objekt-Reads von großen Batch-Blobs trennen. | +| `src/domain/models/external-initial-import-project-command.model.ts`, zugehöriger Store | Change | Vollständiger erwarteter/Zielzustand und Row-freier Import bleiben; Worksharing-ID, Gerätearten und atomare Regelübernahme ergänzen. | +| `src/external-model/application/external-initial-import-plan.ts`, `external-initial-import-target.ts` | Change | Raumvorschläge, Kataloge, vollständige Entscheidungen und stabile UUIDs behalten. Objektentscheidungen und Gerätearten ergänzen. | +| `src/db/repositories/external-object-assignment.persistence.ts` und drei Zuordnungs-Stores | Change | Mengeninvariante und exakte Inversen behalten; Geräteart, effektiven Verteiler, Anwesenheit und Übernahme der Row-Werte beim Lösen ergänzen. | +| `CircuitDeviceRow.manualQuantity`, bestehende Mengenprüfungen | Keep | `quantity = manualQuantity + Summe(externer effektiver Mengen)`; Mehrfachsteckdosen bleiben unteilbar. | +| `src/external-model/application/external-circuit-list-objects.ts` | Change | Listen-/Projektprüfung behalten; vollständige Planungswerte, Geräteart, effektiver Verteiler, Status und Row-Anzahlen liefern. | +| `src/domain/models/project-state-snapshot.model.ts`, Snapshot-Persistenz und Transfer | Change | Schema 10; historische CSV-Zustände ausdrücklich ablehnen; alle neuen internen Referenzen remappen. | +| `src/external-model/csv/*`, CSV-Preview, CSV-Validierungen und Controller | Remove/replace | XLSX ersetzt CSV vollständig; kein zweiter aktiver Transportpfad. | +| `src/frontend/components/revit-csv-modal.tsx`, Einbindung auf Projektseite | Remove/replace | Eigene Revit-Seite; Einstellungen nur im Modal, Import in eigenem Wizard. | +| `src/frontend/components/Sidebar.tsx`, `src/frontend/utils/api.ts`, `src/frontend/types.ts` | Change | Route `revit`, neue DTOs und Endpunkte, CSV-Imports entfernen. | +| `src/frontend/components/circuit-tree-editor.tsx`, Grid-Drop-/Projektionsmodule | Change | Separater externer Drag-Payload; Row-, Circuit- und Freiplatz-Ziele bewusst unterscheiden. Bestehende Grid-Bedienung behalten. | +| Raum-/ProjectDevice-Formulare und Commands | Keep | Sichtbar vorbelegte, ausdrücklich bestätigte Anlage als eigener Undo-Schritt. | +| `scripts/verify-revit-reference-csv.ts`, Transporttests | Replace | Pfadargument für lokalen XLSX-Prüfer; ausschließlich synthetische Workbooks in Tests. | + +### Konkrete Lücken gegenüber dem Auftrag + +- `external-model-contracts.ts` importiert heute CSV-Verträge. Die neutralen + Konfigurations-/Matrixverträge gehören künftig in `external-model/domain`; + nur `external-model/xlsx` darf ExcelJS kennen. +- `ifc_guid` ist derzeit NOT NULL und je Quelle eindeutig; Matching, + Snapshots, DTOs und Commands setzen diese Identität voraus. +- `internalDeviceType` ist derzeit ein freier String in Planungswerten. + Es gibt keinen Geräteart-Katalog mit stabilen IDs und Standardwerten. +- Der Erstimport setzt den ProjectDevice-Link, verwendet im Target aber + weiterhin `suggestedPlanningValues`. Die neue Priorität ProjectDevice vor + Geräteart muss ausdrücklich implementiert werden; ein Link allein genügt + nicht. Revit-Leistung wird künftig nicht automatisch zum Planungswert. +- Der Import-Target setzt `distributionBoardId = null`; die Raumvorgabe liegt + separat im Mapping. Projektion und Zuordnungsprüfung vergleichen heute + direkt das Objektfeld. Eine zentrale Auflösung des effektiven Verteilers + fehlt und ist vor der Editor-Nutzung erforderlich. +- Die bisherige Row-Zuordnung darf laut Validator am Objekt ausschließlich + `circuitDeviceRowId` ändern; der Store schreibt auch nur dieses Feld. + Lösen mit aktuellen Row-Planungswerten benötigt eine neue Command-Version. +- Die Kompatibilitätsprüfung vergleicht Raum, Kategorie, Auswahlkenner und + Planungswerte, aber keine stabile Geräteart. Unterschiedliche Gerätearten + dürfen nicht versehentlich in dieselbe Row aggregiert werden. +- Rows speichern `powerPerUnit` in **kW**, externe Planung + `powerPerUnitW` in **W**. Eine zentrale bidirektionale Konvertierung ist + nötig; Exportleistung darf nicht um Faktor 1000 falsch sein. +- Externe FKs auf Row, ProjectDevice, Raum-Mapping und Verteiler verwenden + teilweise `ON DELETE SET NULL`. Bestehende allgemeine Löschpfade sichern + externe Objektübergänge nicht durchgängig in ihren Inversen. Auch + Unterbaum-/History-Löschungen müssen abgesichert werden. +- Ein Editor-Drawer, projektweite Objekttabelle, Exportnachweis und + ausführbarer Folgeimport fehlen. `follow_up` als vorhandener Enumwert ist + kein implementierter Folgeimport. +- Konfigurationsversionen steigen heute nur bei normalen Updates gegenüber + dem aktuellen Wert; Undo setzt alte Versionen zurück. Für eine tatsächlich + monotone Generation muss diese Semantik korrigiert werden. +- XLSX-Parsing ist asynchron. Das heutige erneute synchrone CSV-Parsing + innerhalb der SQLite-Transaktion darf nicht einfach durch `await` ersetzt + werden. + +## 2. Prüfung der lokalen Musterdatei + +`docs/spec/kbp-Stromkreis.xlsx` wurde ausschließlich lesend auf ZIP-/OOXML- +Ebene untersucht; keine Inhalte wurden hochgeladen oder in Fixtures kopiert. +Die Datei ist unversioniert und darf nicht committed werden. + +| Befund | Ergebnis | +| --- | --- | +| Dateigröße / entpackte ZIP-Einträge | 56.765 / 337.740 Bytes | +| Arbeitsblätter / Blattnamenlänge | 1 / 31 Zeichen | +| Zellbereich | A1:O490 | +| Kopfzeile / Leerzeile / Objekte / Abschluss | 1 / 2 / 3–489 / 490 | +| Objektidentitäten | 487 syntaktisch passende Worksharing-IDs, keine Duplikate | +| Kopfzeilenkommentare | 14, zu den 14 Spalten nach der ID-Spalte | +| Fehlende Raumangaben | 67 Objekte ohne Raumnummer und Raumname | +| IfcGUID-Duplikate | 2 Gruppen nichtleerer doppelter Werte | +| Formeln | Keine; synthetische Tests dafür erforderlich | +| Spaltendefinitionen | 16, obwohl nur 15 Datenspalten vorhanden sind | + +Das beobachtete Profil aus dem Auftrag wird damit bestätigt. Zusätzliche +Spaltenformatdefinitionen dürfen beim Export nicht auf die gemappten Spalten +gekürzt werden. Das Muster enthält die neuen getrennten Stromkreisfelder und +die Bezeichnung noch nicht. Fehlende Rückgabespalten werden angezeigt; sie +dürfen nicht ohne Linear-Parameterbindung erfunden werden. + +Nicht nachgewiesen: erfolgreicher Rückimport in Linear, dessen genaue +Auswertung der Kommentar-/VML-Metadaten und der ExcelJS-Roundtrip. R2 prüft +die Struktur, R8/R10 benötigen zusätzlich einen realen Linear-Abnahmelauf. + +## 3. Bibliothek, Adapter und Uploadgrenzen + +**Vorschlag: genau eine neue direkte Abhängigkeit `exceljs`.** Seine +öffentliche API unterstützt XLSX, Zellnotizen, Formate, Spaltenbreiten und +typisierte Werte. Das passt zum beobachteten klassischen Kommentarformat. +Version und transitive Abhängigkeiten werden in R2 festgeschrieben und +geprüft. Die veröffentlichte Version ist laut Paketregister 4.4.0; eine +aktuelle Releasepflege ist damit nicht bewiesen. Dies ist ein ausdrückliches +Wartungsrisiko, kein als erfüllt abgehakter Bibliotheksnachweis. + +Quellen, am 29.09.2026 geprüft: +[ExcelJS-Projekt](https://github.com/exceljs/exceljs), +[offizielle Paketdokumentation](https://www.npmjs.com/package/exceljs). +Keine Bibliothek wird in R0 installiert. R2 muss vor Integration Kommentar- +Roundtrip, Node-24-Verträglichkeit und Abhängigkeitsrisiken prüfen; bei einem +Blocker wird die Bibliotheksentscheidung neu vorgelegt. + +Vorgeschlagene Grenzen, zentral konfiguriert und synthetisch getestet: + +- ausschließlich `.xlsx`, passender OOXML-Inhalt und ZIP-Signatur; kein + `.xlsm`, verschlüsseltes Archiv, VBA, ActiveX oder externe Workbook-Links; +- maximal 10 MiB Upload, 100 MiB tatsächlich entpackte Daten, 2.000 ZIP- + Einträge, 50.000 Zeilen, 256 Spalten und 2 Millionen materialisierte Zellen; +- genau ein Arbeitsblatt; keine Formelausführung, kein Nachladen von URLs; +- ZIP-Vorprüfung vor ExcelJS: Verzeichniseinträge, doppelte Pfade, + Kompressionsverfahren und tatsächliche entpackte Bytezahl prüfen. + Zentralverzeichnisangaben allein schützen nicht vor manipulierten Archiven. + Begrenzte Dekompression mit Node-Bordmitteln, keine zweite direkte Library; +- Parser in begrenztem Worker mit Zeit-/Speichergrenze; Abbruch ohne DB- + Schreibvorgang. API-Body-Limit auf Uploadgrenze einschließlich Base64- + Overhead abstimmen, statt global beliebige Requestgrößen zuzulassen. + +Neutrale Matrix: Blattname, Kopfzeilen-/Startpositionen, Spaltenmetadaten +(Index, Name, Kommentartext, erkannter Parametertyp/Einheit), geordnete +Zeilen mit Originalzeilennummer und Klasse sowie Zellen als diskriminierte +Union `string | number | boolean | empty`. Formeltext und Cache-Status sind +optionale Transportmetadaten; fachlich zählt nur der gecachte skalare Wert. +Fehlender Cache oder Fehlerwert erzeugt einen Hinweis bzw. bei Pflichtfeldern +einen Blocker. Originalbytes bleiben unverändert gespeichert. + +Fehlende ID bei sonstigen Objektdaten blockiert; Leer-/eindeutige Summenzeilen +werden ignoriert. Nicht passende nichtleere IDs blockieren ebenfalls. +Worksharing-ID bleibt als Quelltext erhalten, Matching ist exakt; ungültige +Leerzeichen/uneindeutige Schreibweisen werden gemeldet statt still korrigiert. +IfcGUID wird optional gespeichert, doppelte Werte sind nur Hinweise. +Numerische Projektion rundet Leistung auf 0,01 W, nicht die gespeicherte +Quellzelle. Mengen aus `socketCount` müssen positive ganze Zahlen sein. + +Rückgabe lädt eine Kopie der Originalbytes, bewahrt den Bereich oberhalb der +ersten Datenzeile samt Kommentaren, Formatierung und Spaltenbreiten und +ersetzt den Datenbereich durch gewählte Objektzeilen in Originalreihenfolge. +Alle Spalten bleiben enthalten; Summenzeilen entfallen. Unveränderte Zellen +behalten ihre importierten Werte und Typen. Formeln in Objektzeilen werden +als gecachte Werte ausgegeben, damit Zeilenauswahl keine falschen relativen +Bezüge erzeugt; dies wird vor Export als Hinweis ausgewiesen. Keine Formeln +werden berechnet. Roundtrip bedeutet strukturelle/semantische Gleichheit, +nicht identische ZIP-Bytes. + +## 4. Konfigurationsschema + +Neuer neutraler Vertrag `ExternalModelConfiguration`, Schema-Version 1: + +```ts +{ + schemaVersion: 1, + layout: { + headerRow: 1, firstDataRow: 3, firstDataColumn: 1, + idColumn: "Worksharing-ID" + }, + circuitMode: "combined" | "separate", + columns: { + worksharingId: string, familyAndType: string, + ifcGuid: string | null, roomNumber: string | null, + roomName: string | null, selectionMarker: string | null, + socketCount: string | null, sourceRemark: string | null, + circuitCombined: string | null, boardName: string | null, + circuitIdentifier: string | null, designation: string | null, + electricalPowerW: string | null, voltageV: string | null, + currentA: string | null + }, + deviceTypes: [{ + id: UUID, name: string, + category: "lighting" | "single_phase" | "three_phase", + defaults: { + powerPerUnitW: number | null, simultaneityFactor: number | null, + cosPhi: number | null, costGroup: string | null + } + }], + familyTypeRules: [{ + id: UUID, exactFamilyAndType: string, deviceTypeId: UUID, + quantityRule: "one" | "socketCount" + }] +} +``` + +Zeilen/Spalten sind intern 1-basiert; UI stellt Spalten als A, B, … dar. +`layout.idColumn` und `columns.worksharingId` werden gemeinsam gesetzt und +müssen übereinstimmen. Jede gemappte Kopfzeile muss eindeutig auflösbar sein; +doppelte Ausgabebelegungen werden abgelehnt. Freie Eingabe bleibt zulässig, +aber ein nicht existierender Name erzeugt vor Import/Export einen konkreten +Fehler. Erkennung und Vorbelegung nutzen die exakten Standardnamen aus dem +Auftrag. Unbekannte Spalten bleiben ohne Mapping erhalten. + +Geräteart-IDs sind interne UUIDs, keine Namen als Relationsschlüssel. Regeln +sind exakt und je Familien-/Typtext eindeutig; jede importierte Familie muss +eine Geräteart haben. Gerätearten und Regeln werden als ein versioniertes +Konfigurationsaggregat gespeichert. Keine zusätzliche Gerätearttabelle ist +für diesen Umfang nötig; Validatoren erzwingen referenzielle Integrität. +Referenzierte Gerätearten können nicht kommentarlos entfernt werden. + +Startwerte: je Feld ProjectDevice vor Geräteart vor leer. Anzeigename: +Auswahlkenner, sonst Geräteartname, sonst Familie/Typ. Quellleistung bleibt +Quelle; eine Übernahme geschieht nur als sichtbare Planungsentscheidung. +Fehlender GZF bleibt vor Zuordnung leer; verlangt der Row-Vertrag einen Wert, +wird `1` sichtbar vorgeschlagen und ausdrücklich bestätigt. Geräteart- +Änderungen schreiben keine vorhandenen Objekt-Overrides oder Rows um. + +## 5. Konkretes Persistenzschema + +Bestehende UUID-/Projekt-FKs und Eigentumsprüfungen werden beibehalten. +`JSON` bezeichnet validierten JSON-Text in SQLite, nicht ExcelJS-Objekte. + +| Tabelle | Zielspalten / Constraints | +| --- | --- | +| `external_model_configurations` (ersetzt CSV-Tabelle) | `id TEXT PK`, `project_id TEXT NOT NULL UNIQUE FK projects`, `configuration_version INTEGER NOT NULL CHECK > 0`, `configuration JSON NOT NULL`. Enthält obiges vollständiges Aggregat. | +| `external_model_sources` | `id`, `project_id UNIQUE`, `name`, `source_type = revit_xlsx`. Genau eine implizite Quelle je Projekt. | +| `external_import_batches` | Bestehende IDs, Importart, Zeit, Dateiname, SHA-256, `applied_project_revision`, `configuration_version`, `configuration_snapshot JSON`, `original_bytes BLOB`, `document JSON`; Matrix jetzt typisiert und transportneutral. Unveränderlich innerhalb des aktiven Zustands; Undo/Restore darf ganze Batches entfernen/wiederherstellen. | +| `external_room_mappings` | Vorhandene Felder einschließlich normalisiertem Quellraumschlüssel, `room_id`, `default_distribution_board_id`; UNIQUE `(source_id, normalized_source_room_key)` bleibt. | +| `external_model_objects` | Bestehende interne IDs/Links; neu `worksharing_id TEXT NOT NULL`, UNIQUE `(source_id, worksharing_id)`; `ifc_guid TEXT NULL`, ohne Unique; `device_type_id TEXT NOT NULL` als validierter Verweis in das Konfigurationsaggregat. | +| Objektzustand | `accepted_source_values JSON` mit rohen typisierten Werten für Raum, Familie/Typ, Marker, Menge, Bemerkung und alle Rückgabefelder; `planning_values JSON` mit Anzeigename, Kategorie, Anschlussart, effektiver Menge, Einzelleistung W, nullable GZF/cosPhi/Kostengruppe/Bemerkung; `overridden_fields JSON`; bisherige Batch-/Raum-/Board-/ProjectDevice-/Row-Verweise und `presence_status` bleiben. | +| `external_export_batches` (neu) | `id TEXT PK`, `project_id FK`, `project_revision INTEGER`, `import_batch_id TEXT`, `exported_at_iso TEXT`, `file_name TEXT`, `sha256 TEXT`, `configuration_version INTEGER`, `scope TEXT`, `object_count INTEGER`. Append-only Audit-Store. | + +`import_batch_id` des Exportnachweises ist absichtlich eine historische UUID +ohne löschenden FK: Undo eines Imports oder Snapshot-Restore darf den Nachweis +nicht entfernen. Exportnachweise liegen außerhalb rücksetzbarer Fachsnapshots +und werden beim Projektduplikat nicht als dort erfolgte Exporte ausgegeben. +Sie bleiben beim Originalprojekt erhalten; diese Abgrenzung wird in R1 +dokumentiert. Importbatches selbst gehören vollständig zu Snapshot/Transfer. + +Indices: bisherige Projekt-/Presence-, Board- und Row-Indices behalten; +zusätzlich `(project_id, device_type_id)`, `external_room_mapping_id`, +`linked_project_device_id`, Export `(project_id, exported_at_iso)`. +Cross-Project-Links und Geräteart-Verweise prüft jeder Command in der +Transaktion; bloße Existenz eines UUID-FK genügt nicht. + +Effektiver Verteiler: ein gemeinsamer Resolver verwendet bei verknüpften +Objekten die Row/Circuit-Verteilung, sonst die Objektabweichung, sonst die +Raumvorgabe. `distributionBoardId = null` bedeutet Raumvorgabe verwenden; +bei fehlender Vorgabe ist das Objekt ohne Verteiler. Room-/Board- +Sammeländerungen prüfen alle betroffenen Row-Links und lehnen inkonsistente +Umbuchungen ab, bis diese ausdrücklich gelöst/verschoben sind. + +Planungswerte bleiben von Quellwerten getrennt. Nach Row-Zuordnung sind +Objekt-Planungswerte eingefrorene Startwerte; Anzeige, Abweichung und Export +verwenden die Row. Beim Lösen werden aktuelle Row-Werte einschließlich +Einheitenkonvertierung in die Objektplanung übernommen und als explizite +Overrides markiert. Effektive Objektmenge wird nicht durch die Row-Gesamtmenge +ersetzt. Die Row und ihr manueller Anteil bleiben erhalten. + +## 6. Commands und Transaktionsgrenze + +Alle öffentlichen Fach-Writes verlangen `expectedRevision`, Anmeldung und +`X-Leistungsbilanz-Request: 1`. `expectedRevision` gehört wie bisher zum +Ausführungsumschlag. Jede Transition enthält vollständige erwartete/Ziel- +Snapshots der betroffenen Datensätze, keine ungesicherten Teilpatches. + +| Command | Payload-Skizze und Gegenrichtung | +| --- | --- | +| `external-model-configuration.update` v1 | `{ expected, target }` einschließlich Layout, Mapping, Gerätearten und Regeln. Inverse tauscht Fachinhalt; Versionsgeneration siehe unten. | +| `external-import.apply-initial` v2 | `{ expectedConfiguration, targetConfiguration, expected, target }`. Quelle, Batch, Mapping, Objekte und neue Regeln zusammen; Inverse stellt leeren externen und vorherigen Konfigurationsinhalt wieder her. Keine Rows. | +| `external-import.apply-follow-up` v1 | `{ configuration: transition, batch: transition, roomMappings: transitions, objects: transitions, rows: quantityTransitions, decisions }`; Server erzeugt deterministischen Diff und alle UUIDs. Inverse tauscht alle betroffenen Zustände. | +| `external-model-object.update-planning` v1 | `{ objects: transitions }`; nur ungebundene Objekte; geänderte Felder in Overrides. Einzel-/Sammelbearbeitung identischer Regeln. | +| `external-model-object.update-distribution-board` v1 | `{ objects: transitions }`; explizite Objektabweichung, Projekt-/Row-Konsistenz. | +| `external-model-room-mapping.update` v1 | `{ mappings: transitions }`; interner Raum/Standardverteiler; betroffene Objekt-/Row-Konsistenz mitprüfen. | +| `external-model-object.update-project-device-link` v1 | `{ objects: transitions, confirmedPlanningFields }`; keine Vorlagenänderung; neue Startwerte nur für ausdrücklich bestätigte Felder. Gebundene Objekte werden über ihre Row bearbeitet. | +| `external-object.update-row-assignment` v2 | `{ rows: transitions, objects: transitions, confirmedConflictObjectIds }`; Linkwechsel, materialisierte Mengen, beim Lösen aktuelle Row-Planungswerte; vollständige Inverse. | +| `external-object.assign-to-new-row` v2 | Bestehender vollständiger Row-/Objekt-/Reserveplan mit neuen Objektverträgen; history-only Inverse entfernt nur exakt unveränderte Erzeugnisse. | +| `external-object.assign-to-new-circuit` v2 | Bestehender Circuit-/Protection-/Row-/Objektplan; BMK einmal planen und festschreiben, gleiche UUIDs bei Redo. | +| `external-model-object.delete-missing` v1 | `{ objects: transitionsToNull, rows: quantityTransitions }`; ausschließlich ausdrücklich bestätigte weiterhin fehlende Objekte, kein Row-/Circuit-Löschen; Inverse stellt IDs, Links und Mengen wieder her. | + +Bestehende `project-device.insert`, Room-/Floor-Commands bleiben eigenständige +Undo-Schritte. Familien-/Geräteartentscheidungen im Wizard sind lokale +Entwürfe und werden erst mit dem Import atomar persistiert. Nach separater +Kataloganlage aktualisiert der Wizard die Projektrevision und plant neu, +ohne lokale Entscheidungen zu verlieren. + +Konfigurationsgeneration: `configurationVersion` erhält bei jedem +Konfigurationswechsel einschließlich Undo/Redo/Restore die neu entstehende +Projektrevision. Sie ist damit strikt steigend, aber nicht lückenlos. +Historienbefehle vergleichen den erwarteten Fachinhalt und die aktuelle +Projektversion; die administrative Generation wird serverseitig neu erzeugt. +Die Inverse restauriert alle Fachwerte exakt, nicht einen alten Zählerstand. +Importbatches behalten ihre ursprüngliche Generation und ihren Snapshot. +Ein Restore/Projekttransfer erhält diese Herkunft; die aktive Konfiguration +wird an die Revision des Zielprojekts gebunden. Prüfen: Änderung → Undo → +anderer Zweig darf niemals denselben Vorschau-Token wieder gültig machen. + +XLSX wird vor der synchronen SQLite-Transaktion in einer serverinternen +Vorbereitung geparst. Apply überträgt Bytes erneut; Hash, Matrix und +Entscheidungen werden erneut validiert. Im Store werden Revision, +Konfigurationsinhalt/-generation, erwartete Objekte, Links und vollständiger +vorbereiteter Plan atomar geprüft. Vorbereitete Daten sind keine vom Client +behauptete Validierung: Generic-Command-Requests dürfen Importcommands nicht +an dieser serverseitigen Vorbereitung vorbeischleusen. Undo/Redo benutzen +denselben Prüfdienst für persistierte Bytes vor der Transaktion. Keine +asynchronen Callbacks in `better-sqlite3`-Transaktionen. + +Allgemeine Row-/Circuit-/Gruppen-/Board-/Raum-/ProjectDevice-Löschungen +erhalten Guards, solange externe Referenzen betroffen sind. Nutzer lösen die +Referenzen zuvor ausdrücklich über die passenden Commands. Guards gelten +auch in Unterbaum- und History-only-Pfaden. Dadurch werden vorhandene +Commands nicht unbemerkt zu unvollständigen externen Löschcommands. + +## 7. Migration, Snapshot 10, History und Transfer + +Neue additive Migration nach `0013_users` (voraussichtlich `0014`, Nummer +beim Beginn von R3 erneut prüfen). Bestehende SQL-/Metadateien unverändert. + +1. Vor R3-Anwendung API-Schreibzugriffe stoppen und `npm run db:backup` + ausführen; verifiziertes Backup samt Wiederherstellungsmöglichkeit sichern. + R0 verändert keine DB und benötigt daher kein Migrationsbackup. +2. Vorhandene externe CSV-Entwicklungsdaten dürfen gemäß Auftrag verworfen + werden. Zuerst je verknüpfter Row `quantity = manual_quantity` setzen; + sonst bliebe nach Entfernen der externen Objekte eine Phantomlast. + Rows, Circuits, manuelle Anteile, UUIDs und BMKs bleiben bestehen. +3. Externe Objekte → Mappings → Batches → Quellen → CSV-Konfiguration in + FK-sicherer Reihenfolge entfernen. Tabellen gezielt neu aufbauen, wo + SQLite NOT-NULL-/Unique-Änderungen dies erfordern. Neue Zieltabellen und + Indices erstellen. Keine leeren Worksharing-IDs als Backfill erfinden. +4. Generiertes SQL und Drizzle-Metadaten prüfen; saubere und bestehende + Test-DBs migrieren; FK-/Integritätsprüfung und Mengenabgleich ausführen. + Der Reset ist eine dokumentierte einmalige Entwicklungsmigration, + kein stiller Laufzeit-Import. +5. Alte Revisionsdaten nicht umschreiben, keine CSV-History heimlich + überspringen. An der Ausführungsgrenze alte CSV-Konfigurationscommands, + Initial-/Zuordnungscommands v1 einschließlich ihrer History-Inversen und + Restores mit CSV-Inhalt vor jedem Write ablehnen. + +Fehlermeldung für History: +„Dieser Verlaufsschritt verwendet die frühere CSV-/IfcGUID-Anbindung und +kann mit der Excel-Anbindung nicht ausgeführt werden.“ +Der History-Status sollte den blockierten obersten Schritt samt Grund zeigen; +keine automatisch geleerten Stacks und keine Änderung bei Ablehnung. Frühere +allgemeine Commands können nach dem Reset zusätzlich an ihren exakten +Vorbedingungen scheitern; das bleibt eine sichere, sichtbare Ablehnung. + +Snapshot v10 enthält aktive Excel-Konfiguration, Gerätearten/Regeln, Quelle, +alle Batches mit Originalbytes/Matrix, Raum-Mappings, Objekte und Links. +Upgrade v1–9: bestehende nicht-externe Upgrader erhalten. Nur wenn +`externalCsvConfiguration` fehlt/null ist **und** der externe Zustand leer +ist, verlustfrei auf v10 heben. Auch eine gespeicherte CSV-Konfiguration +allein zählt als nicht leerer CSV-Zustand und wird nicht still verworfen. +Snapshot-Checksumme am gespeicherten Original vor Upgrade prüfen. + +Fehlermeldung: +„Dieser Projektstand enthält Daten der früheren CSV-/IfcGUID-Anbindung. +Eine automatische Übernahme in die Excel-Anbindung ist nicht möglich. +Bitte verwenden Sie einen Projektstand ohne CSV-Daten.“ + +Der aktuelle portable Transfer ist bereits **Format 2** (Grobbilanzen), +nicht Format 1 wie im alten Audit. Envelope 2 und dessen Format-1-Lesepfad +bleiben; enthaltenes Projektzustandsschema wird 10. Duplizieren remappt +Projekt-, Konfigurations-, Geräteart-, Regel-, Quellen-, Batch-, Mapping-, +Objekt-UUIDs und alle internen Links, auch in Konfigurationssnapshots der +Batches. Worksharing-IDs, optionale IfcGUIDs und Originalbytes bleiben +unverändert. Grobbilanzen und globale Office-/Auth-Daten behalten ihre +bisherige Abgrenzung. Exportnachweise werden nicht als neue Projektexporte +dupliziert. + +## 8. Read-Modelle, Oberfläche und Rückgabe + +Vorgeschlagene API-Basis `/api/projects/:projectId/revit`: +`configuration` (GET/PUT), `profile/preview` (POST, zustandslos), +`initial-import/plan|apply`, `follow-up-import/plan|apply` (POST), +`status` und `objects` (GET), `return-workbook` (POST mit Export-Audit). +Der bestehende listenbezogene External-Objects-GET bleibt erhalten. +Objektmutationen verwenden den vorhandenen Project-Command-Endpunkt mit +neuen typisierten Verträgen. CSV-Endpunkte werden entfernt, keine Aliasse. + +Export verwendet `expectedRevision` für einen konsistent gelesenen Stand; +die Datei-Erzeugung erfolgt außerhalb des kurzen Read-Snapshots. Danach +separater append-only Audit-Write, ohne Projektrevision oder Undo-Schritt. +Bei Auditfehler kein Erfolg/download; ein Eintrag belegt Dateierzeugung, +nicht einen tatsächlich abgeschlossenen Browserdownload. + +Die Revit-Seite zeigt Status, Aktionen und eine paginierte Objekttabelle +(Vorschlag: 100 Zeilen pro Seite). Filter-/Sortierzustand, UUID-Auswahl und +Sammelaktionen sind unabhängig vom DOM. „Alle gefilterten“ verwendet eine +explizit aufgelöste Auswahl zur bekannten Revision; keine Mutation anhand +eines inzwischen veränderten Filters. Große Auswahlmengen werden nicht in +getrennte Undo-Schritte aufgeteilt. Kein vollständiges Batch-Blob im DTO. + +Einstellungen verwenden Musterdatei-Erkennung mit editierbaren Positionen, +Feld-Dropdowns/freier Eingabe und Kommentar-Typ-/Einheitenanzeige. Regeln +entstehen im Wizard und sind auf der Seite einklappbar nachbearbeitbar. +Fehlende Raumangaben bleiben zulässig, Board-Zuordnung ist auch ohne Raum +möglich. ProjectDevice-Zuordnung bleibt optional. + +Rechter Editor-Drawer: nur vorhandene, ungebundene konfliktfreie Objekte des +effektiven Verteilers. Gruppierung nach internem Raum, Auswahlkenner, +Geräteart-ID, Kategorie und identischen Planungswerten; unterschiedliche +ProjectDevice-Links bleiben ebenfalls getrennt, da eine Row nur einen Link +haben kann. Effektive Einzelmengen sind kein Gleichheitsfeld: Einfach- und +Mehrfachsteckdosen sollen gemeinsam gruppierbar sein. Anzeige enthält +Mengensumme und Objektanzahl. Fachlich heterogene Auswahl darf nicht +willkürlich auf eine einzelne Row zusammenfallen; Konfliktanzeige verlangt +eine kompatible Auswahl. Row-Indikator öffnet Objekte und explizites Lösen. + +Eine Funktion `getRevitBoardName(board)` liefert ausschließlich `board.name`. +Gemeinsam: Name + unverändertes `equipmentIdentifier`, ohne Separator. +Getrennt: Name und BMK in eigene Parameter. Ohne Circuit bleiben beide +Stromkreiswerte leer, auch wenn ein Planungsverteiler bekannt ist. + +Exportprojektion und Abweichungsanzeige teilen dieselbe reine Funktion: +Row-Anzeigename/-Leistung bei Link, sonst Objektplanung; Objektleistung in W += effektive Menge × Einzelleistung (Row-kW vorher × 1000), ohne GZF. +Spannung vom Circuit, sonst Projektstandard passend zur Kategorie. +Strom aus Objektleistung, U, cosPhi und Phasenart; Drehstrom mit Faktor √3, +auf 0,01 A. Fehlende/ungültige Werte ergeben leer plus Hinweis. Nullleistung +bleibt bei gültigem Nenner numerisch 0. Kein still angenommenes cosPhi. +Abweichungsvergleich normalisiert Zahlpräzision, Leere und skalare Typen +gegen den **zuletzt importierten**, nicht den zuletzt exportierten Stand. + +Umfang: alle im letzten Batch vorhandenen Objekte / abweichende / explizite +Auswahl. Fehlende Objekte haben keine aktuelle Originalzeile und werden +nicht künstlich wieder eingefügt. Alle Spalten bleiben, nicht ausgegebene +Parameter behalten importierte Werte. Fehlende benötigte Zielspalten bzw. +Linear-Bindungen blockieren die betreffende Exportkonfiguration mit Hinweis +auf einen neuen vollständigen Linear-Export. Dateiname gemäß Auftrag mit +bereinigtem Projektnamen und Tagesdatum. + +Folgeimport matcht ausschließlich Worksharing-ID. Ein neuer Batch speichert +immer den vollständigen letzten Quellstand. Unveränderte Objekte werden +nicht allein zum Fortschreiben von `lastSeenImportBatchId` neu geschrieben; +aktuelle Sichtbarkeit/Quellwerte kommen aus Batch/Matrix. Akzeptierte +Planungsgrundlage und letzte importierte Beobachtung sind getrennt. +Raum-/Familien-/Marker-/Mengenänderungen brauchen Entscheidungen. Bei +unvereinbarer Row-Zuordnung blockiert die Übernahme bis zum ausdrücklichen +Lösen/Umordnen, statt Rows automatisch zu erzeugen. Übernommene Mengen +ändern alle betroffenen Row-Summen im selben Importcommand. Fehlend setzt +nur den Status, erhält vorerst Link und Menge. Rückgabefeld-Abweichungen +sind Hinweise, keine Übernahmeentscheidungen. Ein völlig unveränderter +Folgeimport erzeugt einen nachvollziehbaren Batch, aber keine unnötigen +Objekt-/Row-Updates. + +## 9. Pakete, Verifikation und Risiken + +R0 liefert nur diesen Bericht und einen eigenen Commit. R1–R10 starten erst +nach Freigabe; keine Fortschreibung der alten 14.0–14.6-Liste. + +| Paket | Arbeit und entscheidende Abnahme | +| --- | --- | +| R1 | Neue Excel-Anforderungen und R0–R10-Plan; alte Dokumente archivieren/auf Verweise kürzen; AGENTS, Architektur, History-Doku, Phase-14-Abschnitt, LLM-Kontext und alle Links nachziehen. Referenzdatei gezielt ignorieren. | +| R2 | XLSX-Adapter und lokaler Referenzprüfer mit Pfadargument. Synthetischer Roundtrip für Kommentare, Blattname, Spaltenbreiten, Typen, Header-/Startpositionen, unbekannte Spalten, Auswahl und Summenausschluss; ZIP-/Formelgrenzen. Keine DB-Änderung. | +| R3 | Neue Konfiguration/Identität, additive Migration, Snapshot 10, Transfer und History-Ablehnungen; Backend-CSV entfernen. Parser-Vorbereitung von synchroner Transaktion trennen. | +| R4 | Revit-Seite, Navigation, Einstellungen; Projektseitenmodal und dessen CSV-Frontend-Verträge entfernen. | +| R5 | Erstimport mit atomaren Regeln, Geräten, Raum-/Board- und Objektentscheidungen; ProjectDevice-Vorbelegung nach Priorität; ein Import-Undo-Schritt. | +| R6 | Objekt-Reads, Paging/Filter, Sammel-Commands und Overrides; verwandte Lösch-/Referenzguards vollständig absichern. | +| R7 | Gruppierung, Drag-and-drop, Row-Indikatoren und Lösen inklusive aktueller Row-Werte; drei Drop-Ziele und Reload/Undo/Redo. | +| R8 | Drei Exportumfänge, gemeinsame Abweichungsprojektion, typisierte Rückgabe, append-only Nachweis und Linear-Strukturabnahme. | +| R9 | Kontrollierter Folgeimport, fehlende Objekte, explizites Löschen, mengenwirksame Entscheidungen und atomare Inverse. | +| R10 | Vollständige synthetische Ende-zu-Ende-Kette einschließlich Neustart, Snapshot/Restore und Duplikat; mehrere Tausend Objekte; Doku auf ausgelieferten Stand. | + +Die temporäre Grenze zwischen R3 und R4 wird ausdrücklich behandelt: +Buildfähige, nicht aktive Kompatibilitätstypen für das alte Modal dürfen bis +R4 bestehen, aber kein aktiver CSV-Backendpfad. Veraltete Projektaktion bis +zur neuen Seite deaktivieren/entfernen, keinen funktionslosen Upload anbieten. +Die Dokumentation darf Zwischenstände nicht als fertigen Workflow ausweisen. + +Pflicht je R1–R10: fokussierte Tests, `npm test`, `npm run build:api`, +`npm run build:web`, `npm run typecheck:scripts`, +`npx tsc --noEmit -p tsconfig.next.json`, je ein knapper imperativer Commit. +R0: 31 vorhandene Tests aus sechs Dateien erfolgreich ausgeführt: +`external-model-foundation`, `external-initial-import-plan`, +`external-initial-import-project-command.repository`, +`external-object-row-assignment-project-command.repository`, +`external-circuit-list-objects`, +`external-csv-configuration-project-command.repository` (je `.test.ts`). +Diese decken vorhandene Commit-/Rollback-, Undo-/Redo-, Snapshot-/Transfer- +Grundlagen ab, nicht die neue Excel-Funktion. Der erste Start scheiterte an +Sandbox-`spawn EPERM`; derselbe Lauf außerhalb der Sandbox bestand. +Vollständige Builds/Tests sind für diesen reinen R0-Bericht nicht ausgeführt. + +Zusätzlich erforderliche neue Prüfungen: + +- Migration mit externen Row-Anteilen; keine Phantomlast und unveränderte BMKs. +- v1–9 ohne CSV verlustfrei, mit CSV klare Ablehnung; alte Command-Inversen + und alte Restore-Payloads ebenfalls ohne Teilwrites ablehnen. +- Config-Änderung/Undo/Neuzweig invalidiert alte Pläne; Apply mit anderem + Dateiinhalt, fehlenden Entscheidungen oder fremden UUIDs rollt vollständig + zurück. Später Historyfehler rollt auch Regeln, Links und Mengen zurück. +- Gebundene Row ändern → Export → Lösen → Undo/Redo behält fachliche Werte. +- Mehrfachsteckdosen: unterschiedliche effektive Mengen, identische + Einzelwerte, richtige Gruppierung und objektweise Rückgabeleistung. +- Löschen über alle Unterbaum-/History-Pfade kann externe FKs nicht still + nullen. Fremde Verteilungen/Räume/Kategorien und Gerätearten blockieren. +- Export-Audit scheitert: keine fachliche Revision; SHA-256 entspricht exakt + den gelieferten Bytes. Snapshot/Restore entfernt keine Exportnachweise. +- 5.000/10.000 synthetische Objekte: Parserzeit, Peak-Speicher, Payloadgröße, + Command-/Snapshot-Dauer und UI-Reaktionszeit messen; höchstens eine + paginierte Seite im DOM, stabile Auswahl über Seitenwechsel. + +Wesentliche Restrisiken: Linear-Kommentarbindung ist nur anhand des +Exports beobachtet; ExcelJS-Releasepflege und Roundtrip sind in R2 zu +belegen. Große Originaldateien vervielfachen sich in History/Snapshots; +Limits und Messungen müssen reale Speichergrößen berücksichtigen. Die +CSV-Entwicklungsbereinigung ist absichtlich verlustbehaftet, aber auf den +externen Zustand begrenzt und nur nach verifiziertem Backup zulässig. +Fehlende Zielparameter im Muster verlangen einen neuen vollständigen +Linear-Export, keine geratenen GUID-Kommentare. + +**Freigabepunkt:** Der Nutzerauftrag verlangt wörtlich +„R0. Audit (danach stoppen und Freigabe abwarten)“. +Mit Freigabe dieses Vorschlags beginnt R1; R0 selbst autorisiert keine +Installation, Migration oder Implementierung von R1–R10. From d4803a18d28b7dd929a76c1638e49756bb3129e5 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Tue, 29 Sep 2026 22:28:16 +0200 Subject: [PATCH 27/38] Document Linear Excel integration --- .gitignore | 1 + AGENTS.md | 184 +-- README.md | 19 +- docs/README.md | 15 +- docs/building-structure.md | 4 +- docs/circuit-list-editor-known-limitations.md | 7 +- docs/current-architecture.md | 38 +- ...history-and-external-model-architecture.md | 45 +- docs/revit-requirements-llm-context.md | 282 +--- docs/spec/07-implementation-phases-todo.md | 48 +- docs/spec/08-current-product-backlog.md | 8 +- .../revit-csv-integration-requirements.md | 1390 +---------------- .../spec/revit-csv-phase-14-audit-and-plan.md | 410 +---- .../revit-excel-integration-requirements.md | 463 ++++++ docs/spec/revit-excel-phase-14-plan.md | 173 ++ docs/spec/revit-excel-r0-audit.md | 161 +- 16 files changed, 932 insertions(+), 2316 deletions(-) create mode 100644 docs/spec/revit-excel-integration-requirements.md create mode 100644 docs/spec/revit-excel-phase-14-plan.md diff --git a/.gitignore b/.gitignore index b237969..911c16f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ dist/ data/*.db data/backups/*.db .codex/*.log +/docs/spec/kbp-Stromkreis.xlsx diff --git a/AGENTS.md b/AGENTS.md index b01e6b5..7c0a120 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -320,29 +320,21 @@ supported versions contain circuit-group identity, distribution-board components separate circuit/component protection records. Portable duplicate imports remap component ids and protection-owner references together with the existing project graph. -Project-wide Revit CSV configuration uses -`external-csv-configuration.update`. Its complete expected/target snapshot is -persisted through the shared project-command transaction, so create, update, -delete, Undo and Redo are revision-safe. Snapshot schema 5-9, restore and portable -project duplication preserve the configuration; duplication remaps its internal -id and project link. -The project page exposes the Revit CSV modal. It edits the complete -transport/column/family-rule configuration through the revision-safe endpoint, -requests a stateless preview and then shows the Phase 14.2 initial-import -decisions. Preview responses include all mapped objects, while the UI renders -only the first 25. No preview or plan creates external objects, rows, revisions -or server-side drafts. -Phase 14.2 migration `0003` provides one implicit Revit CSV source per project, -immutable import batches with original bytes plus the classified cell matrix, -normalized source-room mappings and external objects unique by -`(sourceId, ifcGuid)`. Source values, planning values and overrides are separate. -The general external-model repository is read-only; runtime writes belong only -to typed command adapters. Snapshot/restore and portable project transfer schema versions 5-9 -capture the complete external state and remap every internal UUID and link while -preserving IFCGUIDs, source values, original bytes and the classified matrix. -Import batches additionally store the monotonic project CSV configuration -version introduced by additive migration `0004`; it is distinct from the CSV -configuration JSON schema version. +The current runtime still contains the legacy Revit-CSV/IfcGUID foundation: +project configuration, preview, confirmed initial import, external objects and +the three row-assignment commands. It remains the audited starting point, not +the Phase-14 target. Do not extend its CSV transport or IFCGUID identity model. +The approved cutover is Linear XLSX with exact case-sensitive Worksharing-ID +identity. See `docs/spec/revit-excel-integration-requirements.md` and +`docs/spec/revit-excel-phase-14-plan.md`. + +During R1/R2 no database or runtime schema changes are made. R3 will replace +the legacy configuration and transport additively, reject non-empty legacy CSV +snapshot/history state with a German error, and introduce snapshot schema 10. +The target configuration has no independent version counter; `expectedRevision` +invalidates stale plans, and each import batch stores a configuration copy. +Only the newest import batch retains workbook bytes and the full matrix; older +batches retain date, filename, SHA-256 and object count. Phase 14.3 migration `0005` adds `CircuitDeviceRow.manualQuantity`, backfills existing rows from `quantity` and keeps `quantity` as the materialized total. Normal manual row inserts and quantity edits update both values together. @@ -363,37 +355,12 @@ protection and its external object links. Its history-only inverse requires the complete unchanged circuit snapshot and exact link set. Redo never recalculates the BMK. All three external assignment stores share `external-object-assignment.persistence.ts` for compatibility and link safety. -The read-only +The current read-only `GET /api/projects/:projectId/circuit-lists/:circuitListId/external-objects` -projection resolves the board through the owned CircuitList and returns only -that board's compact external objects, unassigned first. It exposes no original -CSV bytes or command payloads and returns an empty list before optional import. -Confirmed initial state is written only through -`external-import.apply-initial`. The command rechecks configuration version, -original-byte SHA-256, parsed matrix, complete IFCGUID/source values, explicit -planning overrides and internal project links in the shared transaction. It -never creates or links a CircuitDeviceRow. Its exact inverse removes the whole -unchanged external state, and Redo restores the same UUIDs and bytes. -`POST /api/projects/:projectId/external-csv/initial-import/plan` is a stateless -read path for the first wizard stage. It rejects projects with an existing -external source and returns source-room groups, exact room-number suggestions, -exact family/type groups, projected object values, issue counts and the current -floor/room/board/ProjectDevice catalogs. It creates no draft, revision or -domain row. The wide modal renders these groups and catalogs as explicit -decisions and identifies exact, ambiguous and new room matches. Missing rooms -and ProjectDevices are created through the reused project forms with mapped -Revit values as visible defaults. Each catalog creation remains its own project -command; the wizard adds and selects the result without discarding its plan. -The dedicated -`POST /api/projects/:projectId/external-csv/initial-import/apply` endpoint -retransmits and replans the file against the expected hash, configuration -version and project revision. It requires one explicit decision per source-room -and exact family/type group, blocks unclassified families, creates all stable -external UUIDs server-side and invokes `external-import.apply-initial`. -Room/default-board and optional ProjectDevice links are supported; CSV circuit -values remain source-only and every `circuitDeviceRowId` remains null. The UI -blocks unclassified families, requires a final confirmation and applies the -whole import as one persistent Undo/Redo step. +projection resolves the board through the owned CircuitList and returns compact +legacy external objects. The target Revit page will load one compact project +list and filter/sort it client-side in a virtualized table, without server +pagination or batch blobs in the DTO. The central revision boundary creates an automatic logical snapshot after each 25 new revisions and retains only the newest 12 automatic snapshots per project. Named snapshots are never removed by this retention policy. @@ -575,70 +542,58 @@ Required operations: Uploads are PNG/JPEG/SVG up to 2 MB with a content signature check; the logo is served with `nosniff` and a restrictive CSP. -## Revit / CSV External Model Work +## Revit / Linear Excel External Model Work -Status: further Revit work (editor assignment UI, follow-up import, return -export) is deferred and will be tackled later. When it resumes, the exchange -stays CSV-based and uses the CSV export/import of the Linear plugin in Revit. -The internal Revit/CAD steering committee prefers this over manipulating the -model directly through Dynamo. Do not start Dynamo, Revit API or JSON -transport work. The Linear CSV layout is not yet known: check a sample export -against the existing project CSV configuration before changing the parser. -Earlier Dynamo considerations are archived in -`docs/archive/revit-dynamo-leistungsbilanz-integration-konzept.md`; the -removed diagnostic scripts remain reachable through the git tag -`archive/dynamo-vorueberlegungen`. +Phase 14 is active and follows +`docs/spec/revit-excel-integration-requirements.md` plus +`docs/spec/revit-excel-phase-14-plan.md`. The old CSV requirements and phases +14.0–14.6 are superseded. Dynamo, Revit API and JSON transport remain excluded. -When explicitly working on Phase 14, use -`docs/spec/revit-csv-integration-requirements.md` as the detailed source of -truth together with the current architecture documents. +Critical target rules: -Critical rules: +- Exchange uses only `.xlsx` files produced and consumed by the Linear plugin. +- Revit integration remains optional. Import never creates a CircuitDeviceRow, + Circuit or equipment identifier. +- Worksharing-ID is the external key and is compared exactly and + case-sensitively. It stays separate from internal UUIDs and circuit BMKs. + IfcGUID is optional redundancy, never a key, and duplicate values are only a + warning. +- A row without Worksharing-ID is suspicious only when `Familie und Typ` is + populated. Show a warning and skip it; do not block. Other ID-less rows, + including the sample summary in column B, are skipped silently. +- Source, planning and override values remain separate. Existing ProjectDevices + remain canonical and are never silently changed. +- Multi-socket objects remain indivisible. Row quantity stays + `manualQuantity + sum(effectiveQuantity)`. +- The project configuration has no independent version counter. Preview and + apply use `expectedRevision`; import batches store a configuration copy. +- Apply retransmits and parses the workbook. Undo/Redo never reads Excel; they + apply only stored before/after states. +- Only the newest import batch retains original bytes and the full matrix; + older batches retain date, filename, SHA-256 and object count. +- The Revit object table loads one compact list, filters/sorts in the client and + renders it virtually; do not add server pagination. +- Linked objects always follow their row's distribution board. Changing a + room's default board affects only unassigned objects and is not blocked. +- Deleting a row, circuit or group warns that X Revit objects become unassigned, + detaches them in the same command and restores links on Undo. Only deletion + of referenced rooms and distribution boards is blocked. +- Missing optional return columns for designation, power, voltage or current + produce warnings and are skipped. Only missing circuit columns for the + selected combined/separate mode block export. +- Missing GZF defaults visibly to 1 without separate confirmation. +- R2 must generate a changed return workbook from the local sample. The user + tests it in Linear before R3. If Linear rejects it, propose direct OOXML + modification of the original workbook before starting R3. +- All confirmed writes use typed project commands with `expectedRevision`, + complete inverse data and the shared project-command transaction boundary. +- Do not add automatic circuit planning, Revit circuit adoption, multi-source + management, partial imports, PostgreSQL, background jobs or new permissions. -- Revit integration is optional. Do not make imported external data mandatory - for projects, rooms, project devices, circuits or device rows. -- Parse imports into staging first. Never write CSV rows directly into circuits - or device rows. -- Keep external object identity separate from internal UUIDs and circuit BMKs. - `IfcGUID` identifies the external Revit object and must never replace an - internal UUID or `equipmentIdentifier`. -- One imported Revit object may exist without a `CircuitDeviceRow`. - Import, room assignment, distribution-board assignment, classification and - ProjectDevice linking do not create a row. -- Create or change a `CircuitDeviceRow` only after an explicit user action in - the circuit-list editor. -- Several external objects may link to one `CircuitDeviceRow`, while every - external object remains individually traceable for follow-up imports and - object-specific export. -- Multi-socket Revit objects are indivisible. Their effective quantity may be - greater than one, but one external object must never be split across circuits. -- Existing ProjectDevices are canonical project templates and must not be - overwritten from Revit values. When creating a new ProjectDevice, mapped - Revit values may prefill the creation form. -- Store imported source values separately from local planning values and local - overrides. Imports never silently overwrite local values. -- Repeated imports match deterministically by project/source and `IfcGUID`. - New, changed, missing and conflicting objects require preview and explicit - user decisions. -- The first implementation assumes one complete Revit model export per project. - Do not add visible multi-source, linked-model or partial-import management. -- CSV configuration is project-scoped. Preserve title, header, blank, subtotal - and unknown rows and columns for the return export. -- Treat rows without `IfcGUID` as passthrough when they contain no object data. - Do not report Revit subtotal rows as missing-identity objects. -- Apply each confirmed import diff through a typed project command with - `expectedRevision`, complete inverse data and the shared project command - transaction boundary. -- External-model state must be added to logical project snapshots and portable - project transfer when it becomes part of the supported runtime. -- Keep CSV parsing/serialization in a transport adapter. Domain services must - not depend on CSV syntax, React, `better-sqlite3` or concrete repositories. -- Do not implement automatic circuit planning, Dynamo/API exchange, - PostgreSQL, background jobs or permissions as part of the initial CSV phase. - -Before implementation, audit the current ProjectDevice, CircuitDeviceRow, -command, snapshot, transfer and editor drag-and-drop paths. Propose concrete -domain objects and commands before adding migrations. +The real sample `docs/spec/kbp-Stromkreis.xlsx` contains project data. It is +gitignored and must never be embedded in tests or committed. Use synthetic +workbooks for automated tests and accept the real file only as an explicit +local path in the reference checker. ## Cable Sizing Module @@ -733,9 +688,6 @@ for the early-phase power balance by DIN 276 cost group (see ## Current Deferred Work -- Revit/CSV/IFCGUID round-trip (deferred; later via Linear plugin CSV, never - Dynamo), except when Phase 14 is explicitly requested and - `docs/spec/revit-csv-integration-requirements.md` is being followed - full electrical sizing - multi-user/PostgreSQL operation - supported production deployment diff --git a/README.md b/README.md index f64ae04..3490332 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,12 @@ Docker-Server-Stack mit gebautem Anwendungscode und ein separater Entwicklungsstack bereit. Ein vollständig unterstütztes Produktionsdeployment für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstütztes Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind -vorhanden. Revit-CSV-Konfiguration, Vorschau -und bestätigter Erstimport sind implementiert; die Editoroberfläche zur -Objektzuordnung, Folgeimporte und Rückexport stehen noch aus. Die weitere -Revit-Arbeit ist zurückgestellt und erfolgt später über den CSV-Export/-Import -des Linear-Plugins in Revit. +vorhanden. Die bisherige Revit-CSV-/IfcGUID-Grundlage mit Vorschau und +bestätigtem Erstimport ist noch im Code vorhanden. Der freigegebene +Phase-14-Plan ersetzt sie schrittweise durch den XLSX-Austausch des +Linear-Plugins mit Worksharing-ID als externem Schlüssel. R0 ist abgeschlossen; +R1 aktualisiert die Dokumentation. Editorzuordnung, Folgeimport und Rückexport +sind noch nicht als neuer Excel-Pfad ausgeliefert. ## Unterstützter Arbeitsablauf @@ -40,9 +41,9 @@ des Linear-Plugins in Revit. - grobe Leistungsbilanzen für LPH 2/3 nach Kostengruppen führen, mit der detaillierten Bilanz vergleichen und einzelne Zeilen als Projektgerät übernehmen -- Revit-CSV-Dateien konfigurieren, prüfen und nach expliziter Zuordnung von - Räumen, Verteilungen und Projektgeräten erstmals importieren; dabei entstehen - noch keine Stromkreise oder Gerätezeilen +- den vorhandenen Legacy-Revit-CSV-Erstimport verwenden; der Zielpfad über + Linear-XLSX, eigene Revit-Seite, Editorzuordnung, Rückgabe und Folgeimport + wird gemäß Phase-14-Plan umgesetzt ## Technik @@ -177,6 +178,8 @@ vor der Baseline werden nicht unterstützt. - [Anmeldung und Benutzerverwaltung](docs/authentication.md) - [Entwicklungs- und Contributor-Workflow](docs/development-workflow.md) - [Bekannte Einschränkungen](docs/circuit-list-editor-known-limitations.md) +- [Revit-Integration über Linear-Excel](docs/spec/revit-excel-integration-requirements.md) +- [Phase-14-Plan R0–R10](docs/spec/revit-excel-phase-14-plan.md) - [Roadmap](docs/spec/07-implementation-phases-todo.md) Für LLM-gestützte Änderungen enthält [AGENTS.md](AGENTS.md) die verbindlichen diff --git a/docs/README.md b/docs/README.md index 3569b42..90c5fc3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,13 +31,18 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we - [Entwicklungs- und Contributor-Workflow](development-workflow.md) - [Deployment und Betrieb](deployment.md) -## Zukunftsarchitektur +## Aktive Revit-Umstellung - [Projektversionen und externer Modellaustausch](project-history-and-external-model-architecture.md) -- [LLM-Kontext für die Revit-Anforderungsplanung](revit-requirements-llm-context.md) -- [Revit-CSV-Anforderungen](spec/revit-csv-integration-requirements.md) – - zurückgestellt; später über den CSV-Export/-Import des Linear-Plugins -- [Phase-14-Audit und Implementierungsplan](spec/revit-csv-phase-14-audit-and-plan.md) +- [Revit-Integration über Linear-Excel](spec/revit-excel-integration-requirements.md) – + verbindliche Anforderungen für XLSX und Worksharing-ID +- [Phase-14-Plan R0–R10](spec/revit-excel-phase-14-plan.md) – Status, + Paketgrenzen und Linear-Freigabepunkt nach R2 +- [R0-Bestandsaudit](spec/revit-excel-r0-audit.md) +- [LLM-Kontext für Phase 14](revit-requirements-llm-context.md) + +## Zukunftsarchitektur + - [Zukünftige Dimensionierung](spec/06-future-sizing-and-calculations.md) - [Roadmap und Phasen](spec/07-implementation-phases-todo.md) - [Aktueller Produkt-Backlog](spec/08-current-product-backlog.md) diff --git a/docs/building-structure.md b/docs/building-structure.md index 21059b4..9db2c91 100644 --- a/docs/building-structure.md +++ b/docs/building-structure.md @@ -101,8 +101,8 @@ bleiben. ## Offen - Revit: Eine Übernahme des Gebäudes aus Revit ist derzeit nicht geplant. Die - Revit-Arbeit ist insgesamt zurückgestellt und läuft später über die - Linear-CSV; das Modell steht einer späteren CSV-Zuordnung nicht im Weg. + aktive Phase 14 verwendet Linear-XLSX; das Modell steht der expliziten + Raumzuordnung im Importwizard nicht im Weg. - Raumflächen werden derzeit ausschließlich manuell gepflegt. Ein späterer Revit-Abgleich muss die Phase-14-Regeln mit externem Modellzustand, Vorschau und ausdrücklicher Bestätigung einhalten. diff --git a/docs/circuit-list-editor-known-limitations.md b/docs/circuit-list-editor-known-limitations.md index fdc463a..ee2d470 100644 --- a/docs/circuit-list-editor-known-limitations.md +++ b/docs/circuit-list-editor-known-limitations.md @@ -9,9 +9,10 @@ - Named and automatic logical project snapshots can be listed and restored through the project page with persistent Undo/Redo. Automatic snapshots are created every 25 revisions and only their newest 12 entries are retained. -- Further Revit work is deferred; it will later use the CSV export/import of - the Linear plugin in Revit, not Dynamo. -- The Revit/CSV foundation and confirmed initial import are implemented. +- The current Revit/CSV foundation and confirmed initial import are a legacy + starting point. The active Phase-14 plan replaces them with the Linear XLSX + exchange and exact Worksharing-ID identity. + R2 must pass a real Linear return-import check before database cutover in R3. Existing-row assignment, move and detach plus creation of an external-only row in an existing or newly created circuit have atomic persistent commands. Their API planning and editor UI, follow-up import, conflict review and return diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 20c7ccd..8993974 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -640,11 +640,15 @@ PostgreSQL ist bewusst nicht implementiert. Die Domainregeln und Transaktionsgrenzen sollen portabel bleiben; Schema und Betriebsmodell benötigen bei einem späteren Wechsel trotzdem einen eigenen PostgreSQL-Adapter. -## Revit-CSV-Grundlage +## Revit-Anbindung: Legacy-Ausgangslage und freigegebener Excel-Cutover -**Zurückgestellt:** Die weitere Revit-Arbeit wird später angegangen, dann -über den CSV-Export/-Import des Linear-Plugins in Revit statt über Dynamo. -Details: [Revit-CSV-Anforderungen, Abschnitt 1](spec/revit-csv-integration-requirements.md). +Der nachfolgende Abschnitt beschreibt den am Ende von R1 noch vorhandenen +Legacy-Laufzeitpfad. Er verwendet CSV und IfcGUID und ist die geprüfte +Ausgangslage für den schrittweisen Cutover; er darf nicht erweitert werden. +Das verbindliche Ziel ist der XLSX-Austausch des Linear-Plugins mit exakter, +case-sensitiver Worksharing-ID. Details: +[Excel-Anforderungen](spec/revit-excel-integration-requirements.md) und +[R0–R10-Plan](spec/revit-excel-phase-14-plan.md). Der reine Adapter unter `src/external-model/csv` validiert die projektweite Transport- und Mappingkonfiguration und parst UTF-8-CSV verlustarm in eine @@ -774,11 +778,33 @@ Die Kataloganlage ist jeweils ein eigener Projekt-Command; der Wizard übernimmt den neuen Datensatz anschließend in seinen lokalen Auswahlkatalog und markiert ihn für die betroffene Gruppe. +### Freigegebener Zielpfad ab R2 + +R2 ersetzt zunächst nur den Transportadapter und endet mit einem realen +Linear-Rückimporttest. R3 bleibt bis zu dessen Freigabe gesperrt. Scheitert der +ExcelJS-Roundtrip, wird vor R3 ein Adapter vorgeschlagen, der die Original-XLSX +direkt auf OOXML-Ebene ändert. + +Der Zielzustand verwendet Worksharing-ID als exakten, case-sensitiven externen +Schlüssel; IfcGUID bleibt optional. Die Konfiguration hat keinen eigenen +Versionszähler. `expectedRevision` bindet Vorschau und Apply, Importbatches +speichern eine Konfigurationskopie. Nur der letzte Batch hält Workbook und +Matrix vollständig, ältere Batches nur Metadaten. Apply parst die erneut +übertragene Datei, Undo/Redo arbeitet nur auf persistierten Zuständen. + +Die eigene Route `/projects/:projectId/revit` lädt eine kompakte Objektliste +einmal und stellt sie clientseitig gefiltert, sortiert und virtualisiert dar. +Verknüpfte Objekte folgen dem Verteiler ihrer Row. Row-, Circuit- und +Gruppenlöschungen lösen externe Links nach Warnung im selben Command; Undo +stellt sie wieder her. Raum- und Verteilerlöschungen bleiben bei externen +Referenzen gesperrt. + ## Noch nicht unterstützt - Mehrbenutzerbetrieb und Konfliktauflösung -- Editor-Oberfläche für die vorhandene Zuordnungslogik, Folgeimport und - strukturtreuer Revit-Rückexport +- Linear-XLSX-Transport, eigene Revit-Seite, Editor-Oberfläche für die + Zuordnungslogik, Folgeimport und strukturtreuer Revit-Rückexport; Umsetzung + folgt dem R0–R10-Plan - vollständige elektrische Dimensionierung - Produktionsdeployment diff --git a/docs/project-history-and-external-model-architecture.md b/docs/project-history-and-external-model-architecture.md index f8ed263..91b82ca 100644 --- a/docs/project-history-and-external-model-architecture.md +++ b/docs/project-history-and-external-model-architecture.md @@ -9,7 +9,8 @@ This document records architectural direction for future work. It is not a final - persist undo/redo across page reloads and application restarts - provide a project-wide version history with named restore points - preserve an auditable sequence of user, import, migration and restore operations -- support future Revit/CSV round-trips using stable IFCGUID-based links +- support the Revit/Linear-XLSX round-trip using stable, exact + Worksharing-ID-based external identity - keep the persistence boundary replaceable so PostgreSQL can be adopted later ## Separate Concerns @@ -111,11 +112,12 @@ Implemented automatic-snapshot policy: - automatic capture and retention run inside the same transaction as the triggering project revision -## Revit / CSV / IFCGUID Round-Trip Direction +## Revit / Linear Excel Round-Trip Direction -**Deferred:** further Revit work will be tackled later, then through the -CSV export/import of the Linear plugin in Revit instead of Dynamo. Details: -[Revit-CSV requirements, section 1](spec/revit-csv-integration-requirements.md). +Phase 14 is active and follows the +[Linear-Excel requirements](spec/revit-excel-integration-requirements.md) and +[R0–R10 plan](spec/revit-excel-phase-14-plan.md). The existing CSV/IFCGUID +runtime is a legacy starting point for the cutover, not the target model. External model exchange should use explicit staging and link entities instead of writing imported rows directly into circuits. @@ -124,9 +126,12 @@ Conceptual entities: - `ExternalModelSource` - identifies a Revit/IFC model or another external source within a project - `ExternalImportBatch` - - file name, checksum, import time, format/version and processing status + - file name, checksum, import time, object count and processing status + - only the latest batch keeps original workbook bytes, matrix and the + configuration copy; older batches keep date, filename, checksum and count - `ExternalModelObject` - - stable IFCGUID and optional Revit element identifiers + - exact case-sensitive Worksharing-ID as external identity + - optional IfcGUID as non-unique source redundancy - source attributes and last-seen import batch - `ExternalObjectLink` - explicit relationship to a project device, circuit device row or another future domain entity @@ -137,13 +142,27 @@ Conceptual entities: Required behavior: -- IFCGUID uniqueness is scoped to project and external model source. +- Worksharing-ID uniqueness is scoped to the external source and uses exact, + case-sensitive comparison. IfcGUID is not a matching key. - Parsing writes to staging first. - Users preview additions, changes, missing objects and conflicts before applying them. - Applying an import creates one project revision and one auditable change set. - Imported source values and locally assigned planning values remain distinguishable. -- Export retains IFCGUID and source identifiers so Revit parameters can be matched deterministically. -- Missing objects and duplicate/conflicting identifiers are reported, never silently reassigned. +- Export retains Worksharing-ID so Linear can match rows deterministically. +- Missing objects and duplicate/conflicting Worksharing-IDs are reported, + never silently reassigned. + +The project configuration has no separate revision counter. Stateless plans +and apply requests bind to `expectedRevision`; every applied import batch holds +its configuration copy. Apply reparses the retransmitted workbook. Undo and +Redo operate only on persisted complete before/after states and never parse an +Excel file. + +Deleting a linked row, circuit or group detaches affected Revit objects in the +same typed command after an explicit warning; its inverse restores all links. +Only deleting referenced rooms and distribution boards is blocked. Linked +objects always derive their board from their row, while a room default-board +change affects only unassigned objects. ## SQLite and PostgreSQL Direction @@ -292,7 +311,8 @@ Remaining constraints before completing project version history: boundary; extend it whenever further project mutations are introduced - project creation remains initialization at revision zero, while global device templates remain outside any single project history -- do not model IFCGUID as an overloaded circuit equipment identifier +- do not model Worksharing-ID or IfcGUID as an overloaded circuit equipment + identifier or an internal relation id - keep database backup/restore checks separate from project history tests ## Deferred Decisions @@ -300,5 +320,6 @@ Remaining constraints before completing project version history: - whether large snapshot payloads remain in PostgreSQL or move to object storage - branch visualization after undo followed by new edits - user/role model and actor attribution -- supported Revit CSV dialects and parameter mapping UI +- Linear-XLSX compatibility beyond the observed sample and any future + project-independent mapping profiles - PostgreSQL deployment topology and migration date diff --git a/docs/revit-requirements-llm-context.md b/docs/revit-requirements-llm-context.md index cf10324..3782150 100644 --- a/docs/revit-requirements-llm-context.md +++ b/docs/revit-requirements-llm-context.md @@ -1,273 +1,15 @@ -# Kontext für die Revit-Anforderungsplanung +# LLM-Kontext für die Revit-Integration -**Zurückgestellt:** Die weitere Revit-Arbeit wird später angegangen, dann -über den CSV-Export/-Import des Linear-Plugins in Revit statt über Dynamo. -Details: [Revit-CSV-Anforderungen, Abschnitt 1](spec/revit-csv-integration-requirements.md). +Die frühere offene Revit-/CSV-Anforderungsplanung ist abgeschlossen und +abgelöst. Für Arbeiten an Phase 14 sind vollständig zu lesen: -## Zweck dieser Datei +- [Revit-Integration über Linear-Excel](spec/revit-excel-integration-requirements.md) +- [R0–R10-Plan](spec/revit-excel-phase-14-plan.md) +- [R0-Bestandsaudit](spec/revit-excel-r0-audit.md) +- [Aktuelle Systemarchitektur](current-architecture.md) +- [Projekt-History und externer Modellzustand](project-history-and-external-model-architecture.md) -Diese Datei ist eine kompakte Übergabe an ein anderes LLM. Sie soll dabei -helfen, gemeinsam mit dem Anwender die fachlichen und technischen Anforderungen -für einen zukünftigen Revit-Datenaustausch zu klären. - -Die Revit-Schnittstelle ist **noch nicht implementiert**. Das LLM soll zunächst -den tatsächlichen Arbeitsablauf erfragen, Unklarheiten sichtbar machen und -daraus eine neue, überprüfbare Arbeitsanweisung erstellen. Es soll weder ein -Dateiformat noch ein Datenbankschema oder eine UI ungefragt festlegen. - -## Produkt und fachliches Modell - -Leistungsbilanz ist eine Webanwendung für die elektrische Ausführungsplanung. -Ihr Kern ist ein tabellenähnlicher Stromkreislisten-Editor für Verteilungen. - -Das unterstützte Laufzeitmodell ist: - -```text -Project -├── Floor -│ └── Room -├── ProjectDevice -└── DistributionBoard - └── CircuitList - └── CircuitSection - └── Circuit - └── CircuitDeviceRow -``` - -Wichtige fachliche Grenzen: - -- Ein `Circuit` ist nicht dasselbe wie eine Gerätezeile. -- Ein Stromkreis kann null, eine oder mehrere `CircuitDeviceRow` enthalten. -- BMK (`equipmentIdentifier`), Schutz- und Kabeldaten gehören zum Stromkreis. -- Menge, Einzelleistung, Gleichzeitigkeitsfaktor, cosPhi, Raum, Kostengruppe - und Kategorie gehören zur Gerätezeile. -- Ein `ProjectDevice` ist eine wiederverwendbare, projektbezogene Vorlage. -- Eine Gerätezeile kann mit einem Projektgerät verknüpft sein, behält aber - lokale Werte und ausdrücklich erfasste Abweichungen. -- Änderungen eines Projektgeräts überschreiben verknüpfte Zeilen niemals - automatisch. Eine Synchronisierung benötigt Vorschau und Benutzerauswahl. -- Manuelle, nicht mit einem Projektgerät verknüpfte Gerätezeilen sind regulär - erlaubt. -- Bestehende BMKs und stabile UUIDs dürfen nicht automatisch verändert werden. -- Neunummerierung ist immer eine ausdrückliche Benutzeraktion. -- `IFCGUID` darf nicht als BMK oder als Ersatz für eine interne UUID verwendet - werden. - -Für einen späteren Revit-Austausch besonders relevante Daten sind: - -- Projekt: Name, interne/externe Projektnummer, Bauherr, Beschreibung, - Kennzeichnung als öffentliches Gebäude und Projektspannungen. -- Geschoss und Raum: interne UUID, Name beziehungsweise Raumnummer und - Raumname. -- Verteilung: interne UUID, Name, Etage, Netzart und Gleichzeitigkeitsfaktor. -- Stromkreis: interne UUID, BMK, Anzeigename, Bereich, Schutz-, Kabel-, - Spannungs-, Steuerungs-, Status- und Bemerkungsdaten. -- Gerätezeile: interne UUID, optionale Projektgeräteverknüpfung, Name, - Anzeigename, Phasenart, Anschlussart, Kostengruppe, Kategorie, Geschoss, - Raum, Menge, Einzelleistung, Gleichzeitigkeitsfaktor, cosPhi und Bemerkung. -- Projektgerät: interne UUID sowie die wiederverwendbaren Gerätewerte. - -Die Phasenart ist fachlich `1-phasig` oder `3-phasig`. Die Spannung wird daraus -und aus den Projekteinstellungen abgeleitet; freie Sonderspannungen sind im -aktuellen Produkt nicht vorgesehen. - -## Aktuelle technische Architektur - -- Frontend: Next.js App Router, React und TypeScript unter `src/app` und - `src/frontend`. -- API: Express und Zod unter `src/server`. -- Fachregeln und typisierte Commands: `src/domain`. -- Persistenz: SQLite, Drizzle und Repository-Adapter unter `src/db`. -- Laufzeitkomposition konkreter Repositories: - `src/server/composition`. -- Lokaler Betrieb: Browser/Next.js auf Port 3001, Express-API auf Port 3000, - SQLite-Datei unter `data/leistungsbilanz.db`. -- Docker Compose wird für die lokale Entwicklung unterstützt. -- PostgreSQL und Mehrbenutzerbetrieb sind noch nicht umgesetzt. - -Der zentrale Editor liegt unter: - -```text -src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx -src/frontend/components/circuit-tree-editor.tsx -``` - -Frontend-Aktionen werden als validierte API-Commands ausgeführt. Fachregeln -liegen in Domain-Services; konkrete SQLite-Zugriffe bleiben in -Persistenzadaptern. Neue Revit-Fachlogik darf deshalb nicht direkt von -`better-sqlite3`, React-Komponenten oder globalen Datenbankinstanzen abhängen. - -## Revisionen, Undo/Redo und Sicherungspunkte - -Alle normalen projektbezogenen Änderungen laufen über eine gemeinsame -Command- und Transaktionsgrenze: - -```text -Fachänderung + inverses Kommando + Revision + Undo/Redo-Übergang -``` - -Diese Bestandteile werden atomar geschrieben oder vollständig zurückgerollt. -Jedes Projekt besitzt eine monoton steigende `currentRevision`. Schreibbefehle -geben die erwartete Revision mit, damit veraltete Clients keine neueren -Änderungen überschreiben. - -Undo/Redo ist projektweit persistent und funktioniert nach Reload oder -Anwendungsneustart. Zusätzlich gibt es: - -- eine unveränderliche Revisions-Timeline; -- benannte und automatische logische Projektsnapshots; -- wiederherstellbare Snapshots mit Prüfsumme; -- einen portablen, versionierten JSON-Projekttransfer. - -Ein angewendeter Revit-Import muss später dieselbe Integritätsgrenze verwenden: -Die bestätigten Änderungen sollen als ein nachvollziehbarer Projekt-Command -beziehungsweise als ein fachlich definierter Änderungssatz atomar, -revisioniert und rückgängig machbar sein. - -## Klare Abgrenzung zum vorhandenen JSON-Projekttransfer - -Der vorhandene JSON-Export/-Import überträgt den vollständigen internen -Projektzustand. Er dient Sicherung, Wiederherstellung und Duplizierung eines -Projekts innerhalb von Leistungsbilanz. - -Dieser Projekttransfer ist **kein** Revit-Austauschformat. Er enthält interne -Strukturen und UUIDs und soll nicht ohne bewusste Entscheidung als Grundlage -für CSV-Dateien oder Revit-Parameter verwendet werden. - -Der zukünftige Revit-Workflow soll dagegen externe Modellobjekte anhand stabiler -externer Identitäten wiedererkennen, ausgewählte Planungswerte zuordnen und -Ergebnisse so exportieren, dass Revit sie wieder den richtigen Objekten -zuweisen kann. - -## Bereits vereinbarte Leitplanken für den externen Modellaustausch - -Diese Punkte gelten als Architekturvorgaben, noch nicht als fertiges -Implementierungsdesign: - -- Ein Import schreibt niemals ungeprüft direkt in Stromkreise oder - Gerätezeilen. -- Eingelesene Daten landen zuerst in einem Staging-/Vorschaubereich. -- Vor der Übernahme werden neue, geänderte, fehlende, doppelte und - widersprüchliche Objekte angezeigt. -- Wiederholte Importe müssen Objekte deterministisch anhand der externen Quelle - und einer stabilen Identität, voraussichtlich IFCGUID, erkennen. -- Die Eindeutigkeit einer IFCGUID ist mindestens auf Projekt und externe - Modellquelle begrenzt; die genaue Quellendefinition ist noch zu klären. -- Importierte Quellwerte und lokal in Leistungsbilanz geplante Werte müssen - unterscheidbar bleiben. -- Lokale Planungswerte dürfen niemals still überschrieben werden. -- Verknüpfungen zwischen externen Objekten und internen Fachobjekten müssen - ausdrücklich modelliert werden. -- Fehlende oder widersprüchliche Identitäten werden gemeldet und niemals - automatisch einem anderen Objekt zugeordnet. -- Ein Export bewahrt IFCGUID und erforderliche Quellidentitäten, damit Revit - die Werte deterministisch zurückschreiben kann. -- Ein Export bezieht sich auf eine bekannte Projektrevision. -- Große Datenmengen allein erzwingen noch keinen Wechsel von SQLite zu - PostgreSQL. PostgreSQL wird relevant bei Mehrbenutzerbetrieb, zentralem - Serverbetrieb oder unabhängigen Hintergrundjobs. - -Als mögliche, aber noch nicht beschlossene Konzepte wurden bisher genannt: - -- `ExternalModelSource` -- `ExternalImportBatch` -- `ExternalModelObject` -- `ExternalObjectLink` -- `ExternalParameterMapping` -- `ExternalExportBatch` - -Diese Namen beschreiben Verantwortlichkeiten. Das andere LLM darf sie -hinterfragen und verbessern, soll sie aber nicht als bereits vorhandene -Tabellen behandeln. - -## Auftrag an das andere LLM - -Erarbeite die Anforderungen dialogorientiert mit dem Anwender. Beginne mit dem -realen Ablauf in Revit und kläre danach schrittweise mindestens: - -1. Welche Revit-Objekte beziehungsweise Kategorien werden exportiert? -2. Wie entsteht die Ausgangsdatei in Revit und wie sieht sie technisch aus - (CSV-Dialekt, Trennzeichen, Encoding, Dezimalformat, Kopfzeilen, - Revit-Versionen)? -3. Welche Identitäten stehen zur Verfügung: IFCGUID, Revit `ElementId`, - Typ-ID, Modell-/Dateikennung oder weitere Schlüssel? -4. Wie werden Hauptmodell, Teilmodelle, verknüpfte Modelle, Modellkopien und - aktualisierte Revit-Dateien unterschieden? -5. Welche Parameter kommen aus Revit und welche Werte werden ausschließlich in - Leistungsbilanz geplant? -6. Welche internen Ziele können externe Objekte erhalten: Projektgerät, - Gerätezeile, Stromkreis, Raum, Verteilung oder weitere Entitäten? -7. Werden externe Objekte einzeln oder gesammelt einem Stromkreis, - Projektgerät, Raum oder einer Verteilung zugeordnet? -8. Welche Werte sollen nach Revit zurückgeschrieben werden, in welchen - Einheiten und unter welchen Revit-Parameternamen? -9. Muss die ursprüngliche Datei einschließlich unbekannter Spalten, - Zeilenreihenfolge und Formatierung erhalten werden, oder darf eine neue - Rückgabedatei erzeugt werden? -10. Wie sollen Spalten-/Parametermappings erstellt, gespeichert, - wiederverwendet und zwischen Projekten geteilt werden? -11. Was gilt bei erneutem Import für neue, geänderte, gelöschte, verschobene, - doppelte oder nicht mehr sichtbare Revit-Objekte? -12. Wer gewinnt bei Konflikten zwischen neuem Revit-Wert und lokaler Änderung? - Welche Konflikte dürfen automatisch gelöst werden und welche benötigen - eine Auswahl? -13. Welche Vorschau, Filter, Sammelaktionen und Bestätigungen benötigt der - Anwender vor der Übernahme? -14. Welche fachlichen Validierungen und Pflichtfelder müssen eine Übernahme - verhindern oder nur eine Warnung erzeugen? -15. Welche Dateigrößen, Objektzahlen und Laufzeiten sind realistisch? -16. Müssen Import und Export synchron im Browser laufen oder werden später - Hintergrundjobs benötigt? -17. Welche Informationen müssen für Nachvollziehbarkeit, Undo/Redo, - Versionshistorie und Support gespeichert werden? -18. Welche konkreten End-to-End-Beispiele und Fehlerfälle dienen als - Abnahmekriterien? - -Stelle Rückfragen in kleinen, zusammenhängenden Blöcken. Unterscheide in deinen -Notizen ausdrücklich: - -- vom Anwender bestätigte Anforderungen; -- sinnvolle Vorschläge; -- offene Entscheidungen; -- technische Folgerungen; -- bewusst nicht betrachtete spätere Ausbaustufen. - -## Erwartetes Ergebnis der Anforderungsrunde - -Erstelle am Ende eine neue Arbeitsanweisung für das implementierende LLM. Sie -soll mindestens enthalten: - -- Ziel, Umfang und ausdrücklich ausgeschlossene Funktionen; -- vollständigen Anwenderworkflow für Erstimport, Zuordnung, Folgeimport und - Rückexport; -- vereinbartes Dateiformat mit einem anonymisierten Beispiel; -- Feld- und Einheitenmapping einschließlich Richtung und Datenhoheit; -- Identitäts-, Matching- und Quellmodell; -- Regeln für neue, geänderte, fehlende und doppelte Objekte; -- Konflikt-, Validierungs- und Freigaberegeln; -- UI-Ablauf für Staging, Vorschau, Zuordnung und Bestätigung; -- Anforderungen an Revision, Atomarität, Undo/Redo und Audit; -- vorgeschlagene Modul- und Persistenzgrenzen, ohne bestehende - Architekturregeln zu umgehen; -- schrittweise Implementierungsphasen mit überprüfbaren Abnahmekriterien; -- offene Punkte, die vor dem jeweiligen Implementierungsschritt geklärt werden - müssen. - -Die Arbeitsanweisung soll noch keinen Code enthalten. Sie muss klar markieren, -welche Entscheidungen der Anwender tatsächlich getroffen hat und welche Teile -nur Architekturvorschläge des LLM sind. - -## Weiterführende Projektdokumente - -- `AGENTS.md` – verbindliche Domänen- und Implementierungsregeln -- `docs/current-architecture.md` – vollständiger aktueller Laufzeit- und - Command-Pfad -- `docs/project-history-and-external-model-architecture.md` – bisherige - Zukunftsrichtung für Versionierung, externes Modell und PostgreSQL -- `docs/spec/01-domain-context.md` – fachlicher Kontext -- `docs/spec/03-data-model-concept.md` – Datenmodellkonzept -- `docs/spec/05-linked-devices-and-sync.md` – Regeln für Projektgeräte und - kontrollierte Synchronisierung -- `docs/spec/07-implementation-phases-todo.md` – Roadmap, insbesondere Phase 14 -- `docs/circuit-list-editor-known-limitations.md` – noch nicht implementierte - Funktionen +Bei Widersprüchen gilt das Anforderungsdokument. CSV, IfcGUID als Schlüssel, +Dynamo, Revit-API und JSON-Transport sind keine Zielpfade. Der derzeit noch im +Code vorhandene CSV-Stand ist ausschließlich die in R1 dokumentierte +Legacy-Ausgangslage für den schrittweisen Cutover. diff --git a/docs/spec/07-implementation-phases-todo.md b/docs/spec/07-implementation-phases-todo.md index f36d60d..0043ef2 100644 --- a/docs/spec/07-implementation-phases-todo.md +++ b/docs/spec/07-implementation-phases-todo.md @@ -532,36 +532,34 @@ Acceptance criteria: ## Phase 14: External Model Round-Trip -**Zurückgestellt:** Die weitere Revit-Arbeit wird später angegangen, dann -über den CSV-Export/-Import des Linear-Plugins in Revit statt über Dynamo. -Details: [Revit-CSV-Anforderungen, Abschnitt 1](revit-csv-integration-requirements.md). +Status: R0 ist mit Korrekturen freigegeben; R1 stellt die Dokumentation auf +Linear-XLSX und Worksharing-ID um. Die frühere CSV-Planung 14.0–14.6 ist +abgelöst und wird nicht fortgeschrieben. -Status: Phase 14.2 (persistente externe Objekte und bestätigter Erstimport) ist -implementiert. Editor-Zuordnung, Rückexport und Folgeimport folgen. Siehe -[Phase-14-Audit und Implementierungsplan](revit-csv-phase-14-audit-and-plan.md) -und die verbindlichen -[Revit-CSV-Anforderungen](revit-csv-integration-requirements.md). +Verbindliche Quellen: -Goal: +- [Revit-Integration über Linear-Excel](revit-excel-integration-requirements.md) +- [R0–R10-Plan](revit-excel-phase-14-plan.md) +- [R0-Bestandsaudit](revit-excel-r0-audit.md) -Exchange model objects and planning parameters with Revit through CSV (Linear plugin export/import). +Die Umsetzung erfolgt ausschließlich in den Paketen R0–R10. R2 endet mit +einer aus der realen Musterdatei erzeugten Rückgabedatei. Der Nutzer muss sie +erfolgreich in Linear importieren, bevor R3 beginnt. Bei einem Fehlschlag wird +zuvor eine direkte OOXML-Änderung des Originalworkbooks als Alternative +vorgelegt. -Tasks: +Kernabnahme der Phase: -- model external sources, import batches and stable IFCGUID objects -- stage and validate imports before applying them -- show additions, changes, missing objects and conflicts -- link external objects explicitly to project-domain entities -- apply an import as one auditable project revision -- configure inbound and outbound parameter mappings -- export against a known project revision while preserving IFCGUID - -Acceptance criteria: - -- repeated imports match objects deterministically by source and IFCGUID -- imports never silently overwrite local planning values -- users approve the diff before it changes the project -- exported data can be assigned back to the correct Revit objects +- Worksharing-ID ist der exakte, case-sensitive externe Schlüssel; +- XLSX-Kopfkommentare, Struktur, Formate und unbekannte Spalten bleiben beim + Rückexport erhalten; +- Import erzeugt keine Rows und überschreibt keine lokale Planung still; +- Zuordnung, Löschung, Folgeimport und Undo/Redo sind atomar und nach Neustart + reproduzierbar; +- Undo/Redo liest keine Excel-Datei; +- nur der letzte Importbatch enthält Workbook und Matrix vollständig; +- mehrere Tausend Objekte bleiben über eine clientseitig gefilterte, + virtualisierte Liste bedienbar. PostgreSQL should be introduced when shared multi-user operation, background jobs or operational scale justify it. External-object count alone does not require an immediate migration. diff --git a/docs/spec/08-current-product-backlog.md b/docs/spec/08-current-product-backlog.md index c0a2720..6d1eae4 100644 --- a/docs/spec/08-current-product-backlog.md +++ b/docs/spec/08-current-product-backlog.md @@ -162,7 +162,7 @@ ProjectDevices and device rows (#20). 3. [x] Snapshot-to-revision descriptions and history presentation. 4. [x] Distribution-board power summary and project column layout. -The Revit/CSV/IFCGUID round-trip follows the distribution-board component -foundation as a separate jointly planned phase and must not be inferred from -these tasks. It is currently deferred and will later use the CSV -export/import of the Linear plugin in Revit, not Dynamo. +The Revit/Linear-XLSX round-trip is now the separately planned active Phase 14. +It uses exact Worksharing-ID identity and must not be inferred from these +unrelated backlog tasks. See +[the R0–R10 plan](revit-excel-phase-14-plan.md). diff --git a/docs/spec/revit-csv-integration-requirements.md b/docs/spec/revit-csv-integration-requirements.md index 4ce65ee..7889566 100644 --- a/docs/spec/revit-csv-integration-requirements.md +++ b/docs/spec/revit-csv-integration-requirements.md @@ -1,1386 +1,8 @@ -# Revit-CSV-Integration – Anforderungen und Implementierungsanweisung +# Abgelöst: Revit-CSV-Anforderungen -## 1. Status und Verbindlichkeit +Diese CSV-/IfcGUID-Spezifikation ist seit 29.09.2026 abgelöst. Die verbindliche +Quelle ist [Revit-Integration über Linear-Excel](revit-excel-integration-requirements.md). -> **Zurückgestellt (September 2026).** Die weitere Revit-Arbeit -> (Editor-Oberfläche zur Objektzuordnung, Folgeimport, Rückexport) wird später -> angegangen. Wenn sie wieder aufgenommen wird, bleibt der Austausch -> CSV-basiert: Export und Import laufen über das Linear-Plugin in Revit. Das -> entspricht der Vorgabe des internen Revit/CAD-Lenkungskreises, weil dabei -> nicht direkt per Dynamo im Modell gearbeitet wird. Eine Dynamo- oder -> API-Anbindung ist nicht vorgesehen; die früheren Vorüberlegungen liegen unter -> [docs/archive](../archive/revit-dynamo-leistungsbilanz-integration-konzept.md). -> Der Aufbau der Linear-CSV ist noch offen. Vor der Wiederaufnahme wird ein -> Musterexport gegen die bestehende projektweite CSV-Konfiguration und den -> Parser geprüft; erst danach wird entschieden, was anzupassen ist. Die bereits -> umgesetzten Schritte bleiben unverändert nutzbar. - -Dieses Dokument ist die verbindliche fachliche und technische Arbeitsgrundlage für **Phase 14: External Model Round-Trip**. - -Es unterscheidet ausdrücklich zwischen: - -- **Bestätigte Anforderung:** vom Anwender festgelegtes Verhalten. -- **Bestehende Architekturvorgabe:** bereits geltende Regel des Projekts. -- **Implementierungsvorschlag:** empfohlene technische Aufteilung, noch kein unveränderliches Datenbankschema. -- **Offene Entscheidung:** darf erst in der jeweils genannten Phase konkretisiert werden. - -Codex darf aus diesem Dokument kein vollständiges Event-Sourcing, keine PostgreSQL-Migration, keine automatische Stromkreisplanung und keine direkte Dynamo-Anbindung ableiten. - -Vor Implementierungsbeginn sind insbesondere zu lesen: - -- `AGENTS.md` -- `docs/current-architecture.md` -- `docs/spec/03-data-model-concept.md` -- `docs/spec/05-linked-devices-and-sync.md` -- `docs/project-history-and-external-model-architecture.md` -- `docs/spec/07-implementation-phases-todo.md` -- `docs/circuit-list-editor-known-limitations.md` - -## 2. Ziel - -Die Anwendung soll Revit-Objekte der Kategorie **Elektroinstallation** über eine CSV-Datei einlesen, dauerhaft anhand ihrer `IfcGUID` erkennen und mit der manuellen Elektroplanung in Leistungsbilanz verbinden. - -Der Workflow soll insbesondere vermeiden, dass Stromkreiskennzeichnungen und Leistungen für jedes Revit-Objekt händisch nachgetragen werden müssen. - -Der Nutzer soll: - -1. Revit-Objekte importieren, -2. Räume aus dem Import anlegen oder vorhandenen Räumen zuordnen, -3. Räume und einzelne Objekte Verteilungen zuordnen, -4. Objekte klassifizieren und optional mit `ProjectDevice`-Vorlagen verknüpfen, -5. noch nicht verschaltete Objekte im Stromkreislisteneditor manuell Stromkreisen und Gerätezeilen zuweisen, -6. Stromkreiskennzeichnung und Leistung in eine strukturgleiche Rückgabe-CSV schreiben, -7. denselben vollständigen Modellstand später erneut importieren und Änderungen kontrolliert abgleichen. - -## 3. Grundlegende Produktgrenzen - -### 3.1 Revit bleibt optional - -**Bestätigte Anforderung** - -Leistungsbilanz muss vollständig ohne Revit-Integration nutzbar bleiben. - -- Projekte, Ebenen, Räume, Verteilungen, Projektgeräte, Stromkreise und Gerätezeilen bleiben manuell anlegbar. -- Ein Projekt darf ausschließlich manuelle Daten, ausschließlich verknüpfte Revit-Daten oder eine Mischung enthalten. -- Revit ist nur für die Existenz und die Quellattribute der tatsächlich verknüpften Modellobjekte führend. -- Revit ist nicht die alleinige Quelle des gesamten Leistungsbilanzprojekts. - -### 3.2 Circuit-First-Modell bleibt unverändert - -**Bestehende Architekturvorgabe** - -```text -Project -├── Floor -│ └── Room -├── ProjectDevice -└── DistributionBoard - └── CircuitList - └── CircuitSection - └── Circuit - └── CircuitDeviceRow -``` - -- Ein `Circuit` ist nicht dasselbe wie eine `CircuitDeviceRow`. -- BMK, Schutz- und Kabeldaten gehören zum Stromkreis. -- Menge, Leistung, Gleichzeitigkeitsfaktor, cosPhi, Raum, Kostengruppe und Kategorie gehören zur Gerätezeile. -- Ein importiertes Revit-Objekt darf vor seiner Stromkreiszuordnung eigenständig existieren. -- Der Import legt nicht automatisch Stromkreise oder Gerätezeilen an. - -### 3.3 Stable IDs und BMK - -**Bestehende Architekturvorgabe** - -- `IfcGUID` ersetzt niemals eine interne UUID. -- `IfcGUID` wird niemals als Stromkreis-BMK verwendet. -- Bestehende interne UUIDs und BMKs dürfen nicht automatisch geändert werden. -- Neunummerierung bleibt eine ausdrückliche Benutzeraktion. -- Import, Sortierung, Verschieben und Folgeabgleich führen nicht automatisch zu einer Neunummerierung. - -## 4. Umfang der ersten Ausbaustufe - -### 4.1 Enthalten - -**Bestätigte Anforderungen** - -- projektweite CSV- und Mappingkonfiguration; -- Import vollständiger CSV-Dateien; -- Import von Revit-Objekten der Kategorie `Elektroinstallation`; -- deterministische Identifikation über `IfcGUID`; -- Import beziehungsweise Verknüpfung von Räumen; -- manuelle Verknüpfung von Räumen mit Ebenen; -- manuelle Anlage der Verteilungen; -- Standardverteilung je Raum und abweichende Verteilung je Objekt; -- exakte Klassifizierung über den CSV-Wert `Familie und Typ`; -- konfigurierbare Behandlung von Einzel- und Mehrfachsteckdosen; -- optionale Verknüpfung importierter Objekte mit vorhandenen `ProjectDevice`-Vorlagen; -- Erstellen neuer `ProjectDevice`-Vorlagen aus ausgewählten Importobjekten; -- lokale Planungswerte und Abweichungen bereits vor der Stromkreiszuordnung; -- projektweites Import-, Staging- und Abgleichs-UI; -- Bereich für unzugeordnete externe Objekte im Stromkreislisteneditor; -- manuelle Zuordnung zu bestehenden Gerätezeilen, bestehenden Stromkreisen oder neuen Stromkreisen; -- Rückexport von vollständiger Stromkreiskennzeichnung und elektrischer Leistung; -- Erhaltung der ursprünglichen CSV-Struktur; -- kontrollierter Folgeimport mit Einzel- und Sammelentscheidungen; -- atomare, revisionierte und rückgängig machbare Übernahmen. - -### 4.2 Ausdrücklich nicht enthalten - -**Bestätigte Anforderungen** - -- automatische Stromkreisbildung in der ersten Ausbaustufe; -- automatische Übernahme späterer Stromkreisvorschläge; -- Import von Verteilungen aus Revit; -- Import einer separaten MEP-Raumliste; -- Teilimporte einzelner Ansichten oder Geschosse; -- Verwaltung mehrerer sichtbarer Modellquellen; -- direkte Dynamo- oder API-Synchronisation; -- PostgreSQL- oder Mehrbenutzerbetrieb; -- automatische Reservekreisbildung; -- automatische elektrische Dimensionierung; -- automatische Konfliktentscheidung; -- automatische Freigabe oder Wiederverwendung leer gewordener Stromkreisnummern; -- Platzhalter, Teiltextsuche oder reguläre Ausdrücke in der ersten Familie-und-Typ-Klassifizierung. - -## 5. Begriffe - -### 5.1 Externes Modellobjekt - -Ein importiertes Revit-Exemplar mit eigener `IfcGUID`. - -Es ist weder automatisch ein `ProjectDevice` noch automatisch eine `CircuitDeviceRow`. - -### 5.2 Quellwert - -Ein Wert, der aus der zuletzt akzeptierten Revit-CSV stammt. - -Beispiele: - -- Revit-Raumnummer; -- Revit-Raumname; -- Familie und Typ; -- CAx-Auswahlkenner; -- vorhandene Stromkreiskennzeichnung; -- vorhandene elektrische Leistung. - -### 5.3 Lokaler Planungswert - -Ein in Leistungsbilanz bestätigter beziehungsweise bearbeiteter Wert. - -Lokale Planungswerte dürfen durch Importe niemals still überschrieben werden. - -### 5.4 Wirksame Menge - -Die fachliche Menge, die für Gerätezeile, Leistungsberechnung und Steckdosenbegrenzung zählt. - -Beispiel: - -```text -2 Doppelsteckdosen + 2 Einzelsteckdosen -= 4 Revit-Objekte -= 6 physische Steckdosen -= wirksame Menge 6 -``` - -## 6. Revit-CSV-Vertrag - -### 6.1 Konfigurierbare Transporteigenschaften - -**Bestätigte Anforderung** - -Die Konfiguration gilt projektweit und muss über eine GUI bearbeitbar sein. - -Mindestens konfigurierbar: - -- Encoding; -- Trennzeichen; -- Dezimaltrennzeichen; -- Zahlenformat; -- Einheit und Umrechnungsregel für Leistung; -- Spaltenname für `IfcGUID`; -- Spaltenname für Raumnummer; -- Spaltenname für Raumname; -- Spaltenname für `Familie und Typ`; -- Spaltenname für `CAx_Auswahlkenner`; -- Spaltenname für Stromkreiskennzeichnung; -- Spaltenname für elektrische Leistung; -- Spaltenname für den Mengenparameter einer Mehrfachsteckdose; -- weitere Quellspalten-zu-internen-Feld-Mappings. - -Erste Standardwerte: - -```text -Encoding: UTF-8 -Trennzeichen: ; -Leistung in Revit: W -``` - -### 6.2 Tatsächlich beobachtetes CSV-Profil - -Die bereitgestellte Referenzdatei besitzt: - -```text -Encoding: UTF-8 mit BOM -Zeilenende: CRLF -Trennzeichen: Semikolon -Quotierung: alle Felder in doppelten Anführungszeichen -Zeile 1: Titel-/Metadatenzeile -Zeile 2: Kopfzeile mit 12 Spalten -Zeile 3: vollständig leere Zeile -Objektzeilen mit IfcGUID: 897 -Summen-/Gruppierungszeilen ohne IfcGUID: 211 -Nichtleere doppelte IfcGUIDs: keine -``` - -Beispiel einer nicht als Objekt zu importierenden Summenzeile: - -```text -"UV_AV_DG_01-1F1: 8";"";"";"";"";"";"";"";"";"";"";"" -``` - -Die Implementierung darf daher nicht annehmen, dass: - -- die Kopfzeile immer die erste Dateizeile ist; -- jede Zeile nach der Kopfzeile ein Objekt ist; -- jede fehlende `IfcGUID` automatisch ein fehlerhaftes Objekt darstellt. - -### 6.3 Erkennen der Kopfzeile - -**Implementierungsvorschlag** - -Die Kopfzeile wird anhand der projektweit konfigurierten erforderlichen Spaltennamen gesucht. - -- Genau eine passende Kopfzeile: verwenden. -- Keine passende Kopfzeile: Import blockieren. -- Mehrere passende Kopfzeilen: Import blockieren und Auswahl beziehungsweise Konfiguration verlangen. -- Zeilen vor und nach der Kopfzeile bleiben als Transportbestandteil erhalten. - -### 6.4 Zeilenklassen - -**Implementierungsvorschlag** - -Jede CSV-Zeile wird genau einer Klasse zugeordnet: - -1. `metadata` - Zeile vor der Kopfzeile oder sonstige nicht tabellarische Metadaten. - -2. `header` - Erkannte Kopfzeile. - -3. `passthrough` - Leer-, Summen-, Gruppierungs- oder sonstige Zeile ohne externe Objektidentität, die nicht wie ein unvollständiges Objekt wirkt. - -4. `object` - Zeile mit nichtleerer, syntaktisch akzeptierter `IfcGUID`. - -5. `suspect-object` - Zeile ohne `IfcGUID`, aber mit befüllten objekttragenden Feldern wie Raum, Familie und Typ oder Auswahlkenner. - -`passthrough`-Zeilen werden unverändert erhalten und erzeugen keine externen Objekte. - -`suspect-object`-Zeilen werden als Konflikt angezeigt und nicht automatisch verworfen. - -### 6.5 Strukturtreuer Rückexport - -**Bestätigte Anforderung** - -Der Rückexport basiert auf der zuletzt akzeptierten vollständigen CSV und muss erhalten: - -- identische Anzahl und Reihenfolge der Zeilen; -- identische Anzahl und Reihenfolge der Spalten; -- Titel-, Leer-, Summen- und sonstige Passthrough-Zeilen; -- unbekannte beziehungsweise nicht gemappte Spalten; -- unveränderte Werte in nicht zu schreibenden Zellen; -- `IfcGUID` jeder Objektzeile; -- vorhandene Transportmerkmale, soweit technisch zuverlässig erkennbar. - -Mindestens zu erhalten sind: - -```text -BOM-Status -Encoding -Zeilenende -Trennzeichen -Spaltenreihenfolge -Zeilenreihenfolge -Titelzeilen -Leerzeilen -Summenzeilen -``` - -Nur explizit als Ausgangsparameter gemappte Zellen von erkannten Objektzeilen dürfen ergänzt oder überschrieben werden. - -Eine vollständig neu zusammengestellte Tabelle mit nur den fachlich verwendeten Spalten ist unzulässig. - -### 6.6 Anonymisiertes Beispiel - -```csv -"Projekt-Export";"";"";"";"" -"Stromkreis";"Raumnummer";"Raumname";"Familie und Typ";"Auswahlkenner";"Leistung";"IfcGUID" -"";"";"";"";"";"";"" -"UV_AV_01-2F1";"01/101";"Technik";"Steckdose: Doppelsteckdose";"Arbeitsplatz";"";"0AbCdEfGhIjKlMnOpQrStu" -"UV_AV_01-2F1: 2";"";"";"";"";"";"" -``` - -Die letzte Zeile ist eine Passthrough-Summenzeile, kein externes Modellobjekt. - -## 7. Identität und Matching - -### 7.1 Externe Identität - -**Bestätigte Anforderung** - -- `IfcGUID` ist der stabile Schlüssel für ein Revit-Objekt. -- Ein Objekt bleibt auch bei geänderten Quellwerten über seine `IfcGUID` bekannt. -- Doppelte nichtleere `IfcGUIDs` innerhalb eines Imports sind ein blockierender Konflikt. -- Eine fehlende `IfcGUID` in einer echten Objektzeile verhindert die automatische Verknüpfung. - -### 7.2 Quellmodell - -**Bestätigte Anforderung plus Architekturfolgerung** - -Für die erste Ausbaustufe gibt es pro Leistungsbilanzprojekt genau einen vollständigen Revit-Modellstrom. - -Die technische Architektur darf trotzdem eine implizite externe Quelle vorsehen, damit `IfcGUID` nicht global oder projektübergreifend eindeutig sein muss. - -Empfohlene Semantik: - -```text -Project -└── implicit ExternalModelSource - └── ExternalModelObject identified by IfcGUID -``` - -Es gibt in der ersten Ausbaustufe keine sichtbare Verwaltung von Hauptmodellen, Teilmodellen oder verknüpften Modellen. - -### 7.3 Interne Identität - -Jedes externe Objekt erhält zusätzlich eine stabile interne UUID. - -Diese UUID wird für interne Relationen, Commands, Snapshots und Undo/Redo verwendet. - -## 8. Datenhoheit - -### 8.1 Revit-geführt - -Revit ist zunächst führend für: - -- Existenz des externen Objekts; -- `IfcGUID`; -- Familie und Typ; -- Revit-Raumnummer und Revit-Raumname als Quellwerte; -- CAx-Auswahlkenner als Quellwert; -- sonstige ausschließlich aus Revit importierte Attribute. - -### 8.2 Leistungsbilanz-geführt - -Leistungsbilanz ist nach Bestätigung führend für: - -- interne Raum- und Ebenenverknüpfung; -- Standard- und Objektverteilung; -- Klassifizierung; -- `ProjectDevice`-Verknüpfung; -- lokale Planungswerte; -- Stromkreiszuordnung; -- `CircuitDeviceRow`-Zuordnung; -- Stromkreis-BMK; -- elektrische Planungsleistung; -- GZF, cosPhi, Kostengruppe, Kategorie und weitere lokale Gerätewerte. - -### 8.3 Konfliktregel - -Kein Folgeimport darf lokale Planungswerte automatisch überschreiben. - -Der Nutzer entscheidet je Konflikt oder per Sammelaktion zwischen: - -- Revit-Änderung übernehmen; -- lokalen Wert beibehalten; -- manuell einen dritten Wert festlegen. - -## 9. Projektweite Revit-Konfiguration - -### 9.1 Mapping - -Die Projektkonfiguration muss die CSV-Spalten auf interne Bedeutungen abbilden. - -Der CAx-Auswahlkenner muss mindestens als sichtbarer, filterbarer und gruppierbarer Wert verfügbar sein. Er kann als Vorschlag für einen Anzeigenamen verwendet werden. - -### 9.2 Familie-und-Typ-Regeln - -**Bestätigte Anforderung** - -In der ersten Ausbaustufe gilt ausschließlich exakter Textvergleich. - -Eine Regel kann mindestens festlegen: - -- exakter CSV-Wert `Familie und Typ`; -- interner Gerätetyp beziehungsweise fachliche Kategorie; -- Anschlussart; -- ProjectDevice-Kategorie `lighting`, `single_phase` oder `three_phase`; -- Mengenregel: - - feste Menge `1`; - - Menge aus gemappter CSV-Spalte; -- optional vorgeschlagener Anzeigename beziehungsweise Mappingquelle. - -Mehrere unterschiedliche Revit-Familien und -Typen dürfen demselben internen Gerätetyp zugeordnet werden. - -Beispiele: - -```text -_E_CAx Steckdose_AP: Steckdose Aufputz -→ interner Gerätetyp Steckdose -→ single_phase -→ Menge 1 -``` - -```text -_E_CAx Mehrfachsteckdose: Doppelsteckdose -→ interner Gerätetyp Steckdose -→ single_phase -→ Menge aus konfigurierter Anzahl-Spalte -``` - -### 9.3 Zugriff - -Der Konfigurationsbereich ist zunächst für alle Nutzer zugänglich, da noch kein Rollen- oder Rechtesystem existiert. - -## 10. Externes Objekt und Planungszustand - -### 10.1 Notwendige fachliche Informationen - -**Implementierungsvorschlag, kein finales Schema** - -Ein persistiertes externes Objekt benötigt mindestens: - -- interne UUID; -- Projekt- und implizite Quellenzugehörigkeit; -- `IfcGUID`; -- Referenz auf die aktuelle beziehungsweise zuletzt akzeptierte Quellzeile; -- importierte Quellwerte; -- zuletzt akzeptierte Quellwerte für den Folgeabgleich; -- verknüpften internen Raum, optional; -- Standardverteilung des Raums; -- abweichende Objektverteilung, optional; -- Klassifizierung; -- wirksame Menge; -- lokale Planungswerte; -- lokale Override-Metadaten; -- optionales `linkedProjectDeviceId`; -- optionalen Link zu einer `CircuitDeviceRow`; -- letzten Sichtbarkeits-/Importstatus; -- letzten gesehenen Importbatch; -- Konfliktstatus. - -### 10.2 Kein automatischer Row-Lebenszyklus - -Folgende Aktionen erzeugen keine `CircuitDeviceRow`: - -- CSV einlesen; -- Raum zuordnen; -- Verteilung zuordnen; -- klassifizieren; -- ProjectDevice verknüpfen; -- lokale Planungswerte bearbeiten. - -Eine Gerätezeile entsteht ausschließlich durch ausdrückliche Zuordnung im Stromkreislisteneditor. - -## 11. ProjectDevice-Verknüpfung - -### 11.1 Vorhandenes ProjectDevice - -Importierte Objekte dürfen mit einem vorhandenen `ProjectDevice` verknüpft werden. - -Das vorhandene `ProjectDevice` wird durch Revit-Werte niemals automatisch verändert. - -Die bestehende Regel bleibt verbindlich: - -- `ProjectDevice` ist die kanonische Projektvorlage; -- lokale Werte und Overrides bleiben möglich; -- Änderungen am ProjectDevice werden nie still synchronisiert; -- Synchronisierung benötigt Vorschau und Auswahl. - -### 11.2 Neues ProjectDevice aus Importobjekten - -**Bestätigte Anforderung** - -Der Nutzer darf im Importwizard ein neues `ProjectDevice` erstellen. - -Das Erstellformular darf anhand der gemappten Werte der ausgewählten Revit-Objekte vorausgefüllt werden. - -Mögliche Vorbelegungen: - -- `name`; -- `displayName`; -- Kategorie; -- Anschlussart; -- Kostengruppe; -- Einzelleistung; -- Gleichzeitigkeitsfaktor; -- cosPhi; -- Bemerkung. - -Die Kategorie des ProjectDevices bestimmt gemäß bestehendem Modell die Phasenart. Es darf kein paralleles, widersprüchliches Phasenmodell eingeführt werden. - -Bei einer Mehrfachauswahl mit unterschiedlichen Quellwerten muss die UI Abweichungen anzeigen. Sie darf nicht willkürlich einen Wert wählen. - -### 11.3 Lokale Werte vor der Stromkreiszuordnung - -Importierte Objekte dürfen bereits vor der Stromkreiszuordnung lokale Planungswerte und lokale Abweichungen vom verknüpften ProjectDevice besitzen. - -Beim späteren Erzeugen einer Gerätezeile werden diese bestätigten Objektplanungswerte als Ausgangswerte verwendet. - -## 12. Erstimport-Workflow - -### 12.1 Öffnen und Konfiguration - -1. Nutzer öffnet die projektweite Revit-Integration. -2. Falls keine gültige Mappingkonfiguration existiert, wird zuerst die Konfiguration geöffnet. -3. Nutzer lädt eine vollständige CSV hoch. -4. Parser erkennt Transportparameter und Kopfzeile. -5. Datei wird ohne fachliche Projektschreibvorgänge geparst und validiert. - -### 12.2 Vorschau - -Die Vorschau zeigt mindestens: - -- Anzahl erkannter Objektzeilen; -- Anzahl Passthrough-Zeilen; -- Anzahl verdächtiger Objektzeilen; -- fehlende und doppelte `IfcGUIDs`; -- unbekannte Familie-und-Typ-Werte; -- neue und bereits bekannte Räume; -- vorhandene Stromkreiswerte; -- nicht parsebare Leistungen oder Mengen. - -### 12.3 Raumwizard - -Räume werden aus den importierten Objektzeilen abgeleitet. - -Der Nutzer kann: - -- einen neuen internen Raum anlegen; -- einen importierten Raum mit einem vorhandenen internen Raum verknüpfen; -- mehrere Räume sortiert nach Raumnummer bearbeiten; -- Räume einer Ebene zuordnen. - -Die Raumnummer ist zunächst das primäre Matchingmerkmal. - -Eine eigene Revit-Raum-GUID ist nicht erforderlich. - -### 12.4 Verteilungen - -Verteilungen werden manuell angelegt. - -Der Nutzer kann: - -- einem Raum eine Standardverteilung zuweisen; -- mehrere Räume gesammelt einer Verteilung zuweisen; -- einzelne Objekte abweichend einer anderen Verteilung zuweisen; -- Objekte ohne MEP-Raum manuell einer Verteilung zuweisen. - -Neue Objekte eines bereits bekannten Raums erhalten die bestehende Standardverteilung als Vorschlag. - -### 12.5 Klassifizierung und ProjectDevices - -Der Nutzer kann: - -- Objekte nach Raum, Familie und Typ, CAx-Auswahlkenner und Status filtern; -- Familie-und-Typ-Werte klassifizieren; -- mehrere Objekte mit einem vorhandenen ProjectDevice verknüpfen; -- unmittelbar ein neues ProjectDevice erstellen; -- lokale Werte bearbeiten. - -### 12.6 Bereits gefüllte Stromkreiskennzeichnung - -Enthält eine Objektzeile bereits eine Stromkreiskennzeichnung, muss der Wizard fragen, wie sie behandelt wird. - -Möglichkeiten: - -- vorhandenen Wert nur als Quellwert behalten; -- vorhandene Zuordnung übernehmen; -- vorhandenen Wert ignorieren. - -Eine Übernahme ist nur zulässig, wenn: - -- die Präfix-Verteilung eindeutig vorhanden ist; -- die Zuordnung zur Raum- beziehungsweise Objektverteilung passt oder ausdrücklich bestätigt wird; -- der Stromkreis eindeutig vorhanden oder bewusst anzulegen ist; -- keine widersprüchliche Zuordnung entsteht. - -Keine Variante darf still gewählt werden. - -### 12.7 Übernahme - -Die bestätigte Erstübernahme schreibt mindestens: - -- Importbatch; -- vollständige Transportgrundlage für den Rückexport; -- externe Objekte; -- Quellwerte; -- Raum- und Verteilungslinks; -- Klassifizierungen; -- ProjectDevice-Links; -- lokale Planungswerte; -- Konfliktentscheidungen. - -Die Übernahme ist ein atomarer Projekt-Command mit `expectedRevision`. - -Sie erzeugt genau eine Projektrevision und einen Undo-Schritt. - -Nach erfolgreicher Übernahme erscheinen ausreichend klassifizierte, einer Verteilung zugeordnete und noch nicht verschaltete Objekte im Stromkreislisteneditor. - -## 13. UI 1 – Import-, Staging- und Abgleichswizard - -### 13.1 Pflichtfunktionen - -- sortierbare tabellarische Darstellung für mehrere Tausend Objekte; -- Volltextsuche; -- Filter nach Raum, Raumname, Familie und Typ, CAx-Auswahlkenner, Verteilung, ProjectDevice, Stromkreis und Status; -- Mehrfachauswahl; -- Shift-Bereichsauswahl; -- Auswahl aller gefilterten Treffer; -- Auswahl vollständiger Räume oder Gruppen; -- Sammelzuordnung zu Raum, Ebene, Verteilung, Klassifizierung und ProjectDevice; -- Erstellen eines ProjectDevices; -- Bearbeiten lokaler Planungswerte; -- Vergleich Quellwert gegen lokalen Wert; -- Konfliktentscheidungen einzeln und gesammelt; -- Vorschau des Änderungssatzes vor Übernahme. - -### 13.2 Sichtbare Objektinformationen - -Mindestens: - -- `IfcGUID`; -- Familie und Typ; -- CAx-Auswahlkenner; -- Revit-Raumnummer und Raumname; -- interner Raum und Ebene; -- Standardverteilung; -- tatsächliche Objektverteilung; -- Klassifizierung; -- wirksame Menge; -- verknüpftes ProjectDevice; -- lokaler Anzeigename; -- lokale Leistung; -- zugeordneter Stromkreis; -- zugeordnete CircuitDeviceRow; -- Import- und Konfliktstatus. - -### 13.3 Statusfilter - -Mindestens: - -- neu; -- bekannt und unverändert; -- geändert; -- Raum geändert; -- im vollständigen Folgeimport nicht enthalten; -- ohne Raum; -- ohne Verteilung; -- ohne Klassifizierung; -- ohne ProjectDevice; -- ohne Stromkreis; -- vollständig zugeordnet; -- konfliktbehaftet. - -`Ohne ProjectDevice` ist kein Fehler. - -## 14. UI 2 – Unzugeordnete Objekte im Stromkreislisteneditor - -### 14.1 Sichtbarkeit - -Der Editor zeigt einen separaten Bereich beziehungsweise Drawer mit Objekten, die: - -- der aktuellen Verteilung zugeordnet sind; -- noch mit keiner `CircuitDeviceRow` verknüpft sind; -- ausreichend klassifiziert sind; -- keinen blockierenden Konflikt besitzen. - -### 14.2 Darstellung und Filter - -Mindestens sichtbar: - -- Raum; -- Familie und Typ; -- CAx-Auswahlkenner; -- interner Gerätetyp; -- ProjectDevice; -- wirksame Menge; -- Einzelleistung; -- Objektgesamtleistung; -- Kategorie beziehungsweise Phasenart; -- Anschlussart; -- Status. - -Filter und Mehrfachauswahl müssen auch hier für große Mengen geeignet sein. - -### 14.3 Drag-and-drop-Semantik - -**Bestätigte Anforderung** - -Der Drop-Zielbereich bestimmt die fachliche Aktion. - -#### Drop auf bestehende CircuitDeviceRow - -- ausgewählte externe Objekte werden mit genau dieser Zeile verknüpft; -- Menge und Gesamtleistung werden neu berechnet; -- die Anwendung wählt niemals selbst eine andere passende Zeile. - -#### Drop auf bestehenden Circuit - -- in diesem Stromkreis wird eine neue CircuitDeviceRow angelegt; -- dies gilt auch, wenn bereits eine ähnliche Zeile vorhanden ist. - -#### Drop auf freien Zielbereich für neuen Circuit - -- ein neuer Circuit wird über den bestehenden Circuit-Insert-/Move-Mechanismus angelegt; -- mindestens eine neue CircuitDeviceRow wird erzeugt; -- BMK-Erzeugung folgt den bestehenden expliziten Regeln des Editors; -- keine Nachbarstromkreise werden neu nummeriert. - -Die gesamte jeweilige Aktion einschließlich externer Links, Mengenänderung, Circuit-/Row-Erzeugung, Revision und History-Transition ist atomar. - -### 14.4 Keine automatische Zusammenführung - -Gleiche Eigenschaften dürfen Hinweise und Vorschläge erzeugen. - -Die Anwendung darf externe Objekte aber nicht ohne Benutzeraktion automatisch: - -- zusammenführen; -- einer bestehenden Gerätezeile hinzufügen; -- in einen Stromkreis verschieben; -- auf mehrere Gerätezeilen verteilen. - -## 15. Gerätezeilen, Aggregation und Mehrfachsteckdosen - -### 15.1 Einzelobjekte bleiben erhalten - -Jedes Revit-Objekt bleibt intern separat anhand seiner `IfcGUID` nachvollziehbar, auch wenn mehrere Objekte in einer Gerätezeile aggregiert dargestellt werden. - -### 15.2 Mehrfachsteckdose - -**Bestätigte Anforderungen** - -- Eine Mehrfachsteckdose ist ein Revit-Objekt. -- Ihr Mengenparameter enthält die Anzahl physischer Schukosteckdosen. -- Eine Doppelsteckdose zählt als zwei Steckdosen. -- Das Objekt ist unteilbar und darf nicht auf mehrere Stromkreise verteilt werden. -- Die Leistung wird je physischer Steckdose angesetzt. -- Die Objektgesamtleistung ist `wirksame Menge × powerPerUnit`. - -### 15.3 Gerätezeilenmenge - -Die Menge einer CircuitDeviceRow ist die Summe der wirksamen Mengen aller mit ihr verknüpften externen Objekte plus gegebenenfalls manuell geführter Anteile, sofern das vorhandene Datenmodell dies eindeutig unterscheiden kann. - -Beispiel: - -```text -2 Doppelsteckdosen + 2 Einzelsteckdosen -→ 4 ExternalModelObjects -→ CircuitDeviceRow.quantity = 6 -``` - -### 15.4 Getrennte Gerätezeilen - -**Bestätigte Anforderungen** - -Unterschiedliche Räume werden in getrennten Gerätezeilen dargestellt. - -Unterschiedliche CAx-Auswahlkenner werden in getrennten Gerätezeilen dargestellt. - -Beispiel: - -```text -Circuit UV_AV_01-2F1 -- Raum 01/101: 4 × Arbeitsplatzsteckdose -- Raum 01/101: 2 × Mediensteckdose -- Raum 01/102: 1 × Arbeitsplatzsteckdose -``` - -Der Nutzer darf trotz gleicher Werte bewusst mehrere getrennte Gerätezeilen erzeugen. - -### 15.5 Raumübergreifende Stromkreise - -Raumübergreifende Stromkreise bleiben manuell zulässig und werden über mehrere Gerätezeilen übersichtlich dargestellt. - -Die spätere automatische Stromkreisvorschlagsfunktion darf nur raumbezogene Vorschläge erzeugen. - -## 16. Folgeimport - -### 16.1 Annahme - -Jeder Folgeimport enthält erneut den vollständigen relevanten Modellstand der Kategorie `Elektroinstallation`. - -Teilimporte sind in der ersten Ausbaustufe nicht zulässig beziehungsweise werden nicht als Löschgrundlage verwendet. - -### 16.2 Vergleichszustände - -Mindestens zu erkennen: - -- bekannte `IfcGUID`, unveränderte Quellwerte; -- neue `IfcGUID`; -- bekannte `IfcGUID` mit geänderten Quellwerten; -- geänderter Revit-Raum; -- geänderte Stromkreiskennzeichnung; -- geänderte Leistung; -- zuvor bekannte `IfcGUID` fehlt; -- doppelte `IfcGUID`; -- verdächtige Objektzeile ohne `IfcGUID`. - -### 16.3 Fehlende Objekte - -Fehlt eine bekannte `IfcGUID`, wird das Objekt nur als `nicht mehr im aktuellen vollständigen Export enthalten` markiert. - -Es wird nicht automatisch: - -- gelöscht; -- aus seiner Gerätezeile entfernt; -- aus seinem Stromkreis entfernt; -- von seinem ProjectDevice getrennt. - -Erst nach ausdrücklicher Bestätigung wird das externe Objekt entfernt beziehungsweise als gelöscht übernommen. - -Danach: - -- wird sein Link zur CircuitDeviceRow entfernt; -- werden Menge und Leistung der Zeile neu berechnet; -- bleibt ein dadurch leer gewordener Circuit bestehen; -- wird seine BMK nicht automatisch freigegeben oder neu vergeben. - -### 16.4 Raumänderung - -Eine Raumänderung wird anhand derselben `IfcGUID` erkannt und als Konflikt angezeigt. - -Sie wird nicht automatisch übernommen. - -### 16.5 Alle Änderungen sind nutzergesteuert - -Der Nutzer kann Konflikte: - -- einzeln behandeln; -- gruppiert behandeln; -- Revit-Werte übernehmen; -- lokale Werte behalten; -- manuell überschreiben. - -Die bestätigte Übernahme eines Folgeimports ist ein atomarer Projekt-Command und eine Projektrevision. - -## 17. Rückexport - -### 17.1 Grundlage - -Der Export verwendet den zuletzt akzeptierten vollständigen Importbatch und eine bekannte aktuelle Projektrevision. - -Ein Export verändert die Projektrevision nicht. - -### 17.2 Stromkreiskennzeichnung - -Für jedes einem Stromkreis zugeordnete externe Objekt wird geschrieben: - -```text - -``` - -Beispiel: - -```text -UV_AV_DG_01-2F1 -``` - -Die genaue Trennlogik folgt dem tatsächlich im Projekt verwendeten Verteilerpräfix und Stromkreis-BMK; es darf kein zweites unabhängiges Nummerierungssystem eingeführt werden. - -### 17.3 Leistung - -Die Rückgabe erfolgt in Watt. - -Für eine Mehrfachsteckdose wird die objektbezogene Gesamtleistung geschrieben: - -```text -Objektleistung = wirksame Menge des Revit-Objekts × powerPerUnit -``` - -Bei normalen Einzelobjekten ist die wirksame Menge `1`. - -### 17.4 Objektbezogene Ausgabe - -Sind mehrere Revit-Objekte mit einer gemeinsamen CircuitDeviceRow verknüpft: - -- erhält jedes Objekt seine eigene ursprüngliche CSV-Zeile; -- erhält jedes Objekt dieselbe Stromkreiskennzeichnung; -- erhält jedes Objekt seine eigene Objektgesamtleistung; -- bleibt seine `IfcGUID` unverändert. - -### 17.5 Exportnachweis - -**Implementierungsvorschlag** - -Ein Exportbatch speichert mindestens: - -- Projekt-ID; -- Projektrevision; -- zugrunde liegenden Importbatch; -- Zeitstempel; -- Dateiname; -- Prüfsumme; -- verwendete Mappingkonfiguration beziehungsweise deren Version. - -Dies ist Auditmetadaten und kein Ersatz für die Projekt-Revisionshistorie. - -## 18. Validierungen - -### 18.1 Blockierende Fehler - -Mindestens: - -- CSV kann mit der Konfiguration nicht geparst werden; -- erforderliche Kopfzeile ist nicht eindeutig; -- erforderliche Spalte fehlt; -- doppelte nichtleere `IfcGUID` unter Objektzeilen; -- ungültige oder nicht serialisierbare Projektwerte; -- stale `expectedRevision`; -- Verknüpfung zu einem anderen Projekt; -- Drop-Ziel gehört nicht zur zugeordneten Verteilung beziehungsweise Liste; -- Mehrfachsteckdose würde intern auf mehrere Stromkreise aufgeteilt; -- atomare Command-Vorbedingungen stimmen nicht mehr. - -### 18.2 Warnungen beziehungsweise aufzulösende Konflikte - -Mindestens: - -- unbekannter Familie-und-Typ-Wert; -- Objekt ohne Raum; -- Raumänderung; -- bestehende abweichende Stromkreiskennzeichnung; -- abweichende Revit-Leistung; -- Objekt im Folgeimport nicht enthalten; -- ausgewählte Objekte besitzen unterschiedliche lokale Planungswerte; -- vorhandene Stromkreiszuordnung passt nicht zur Verteilung; -- verdächtige Objektzeile ohne `IfcGUID`. - -## 19. Revision, Undo/Redo und Audit - -### 19.1 Gemeinsame Transaktionsgrenze - -**Bestehende Architekturvorgabe** - -Alle bestätigten projektbezogenen Änderungen laufen über: - -```text -domain mutation -+ inverse command -+ project revision -+ undo/redo transition -``` - -Sie werden gemeinsam über die bestehende Projekt-Command-Transaktionsgrenze committed oder vollständig zurückgerollt. - -Neue Revit-Fachlogik darf nicht direkt von React, `better-sqlite3`, globalen Datenbankinstanzen oder konkreten SQLite-Repositories abhängen. - -### 19.2 Neue logische Commands - -**Implementierungsvorschlag** - -Mindestens getrennte Command-Verantwortlichkeiten: - -- Revit-Projektkonfiguration ändern; -- akzeptierten Erstimport anwenden; -- akzeptierten Folgeimport anwenden; -- externe Objektplanungswerte ändern; -- externe Objekte mit ProjectDevices verknüpfen oder trennen; -- externe Objekte einer bestehenden CircuitDeviceRow zuweisen; -- externe Objekte als neue CircuitDeviceRow einem Circuit zuweisen; -- externe Objekte mit neuem Circuit und neuer Row zuweisen; -- externe Objektzuordnung aus einer Row lösen; -- externes Objekt nach bestätigtem Fehlen löschen. - -Die konkreten Command-Namen und Payloads sind beim Implementierungsaudit festzulegen. - -### 19.3 Undo - -Undo muss insbesondere wiederherstellen: - -- externe Objekte und Quellstände; -- Raum-, Verteilungs- und ProjectDevice-Links; -- lokale Planungswerte und Overrides; -- CircuitDeviceRow-Verknüpfungen; -- Mengen und Leistungen; -- erzeugte Row- und Circuit-UUIDs; -- Importstatus. - -Undo darf keine BMKs neu berechnen. - -## 20. Snapshots und portabler Projekttransfer - -**Bestehende Architekturfolgerung** - -Sobald die Revit-Integration unterstützt wird, gehört ihr bestätigter Projektzustand zum vollständigen logischen Projektzustand. - -Snapshot- und JSON-Transfer-Schema müssen deshalb nach einem bewussten Schema-Versionswechsel mindestens erhalten: - -- projektweite Revit-Konfiguration; -- Mappingregeln; -- Familie-und-Typ-Regeln; -- externe Objekte; -- Quell- und Planungswerte; -- Raum-, Verteilungs-, ProjectDevice- und CircuitDeviceRow-Links; -- relevante Importbatch-Grundlagen für den Rückexport; -- Konflikt- und Sichtbarkeitsstatus. - -Beim Duplizieren eines Projekts: - -- werden alle internen UUIDs remapped; -- bleiben externe `IfcGUIDs` als Quellidentitäten erhalten; -- werden interne Links auf die remappten Projektobjekte aktualisiert. - -Vorhandene Snapshot-Migrationen dürfen nicht still verändert werden. Es ist eine additive neue Schema-Version erforderlich. - -## 21. Modul- und Persistenzgrenzen - -### 21.1 Verbindliche Grenzen - -- Parsing und Serialisierung sind keine React-Aufgabe. -- CSV-Dialektlogik ist kein Bestandteil von Circuit-Domain-Services. -- Domain-Services kennen keine konkreten SQLite-Repositories. -- Controller importieren keinen globalen Datenbankclient. -- Writes erfolgen ausschließlich über typisierte Commands. -- Reads verwenden schmale, fachlich benannte Repositories. -- Server-Komposition erzeugt und injiziert konkrete Adapter. -- SQLite bleibt der unterstützte Adapter. -- PostgreSQL wird nicht in dieser Phase eingeführt. - -### 21.2 Empfohlene Verantwortlichkeiten - -**Implementierungsvorschlag** - -```text -CSV transport adapter -- dialect detection -- header and row classification -- lossless-enough matrix preservation -- mapped value parsing -- return serialization - -External model domain -- identity and matching -- source versus planning values -- conflict calculation -- object lifecycle -- aggregation invariants - -Application services / commands -- import preview -- first import apply -- follow import apply -- link and unlink operations -- export projection - -Persistence adapters -- project configuration -- import/export batches -- external objects -- links and accepted source state - -Frontend -- project configuration UI -- staging wizard -- unassigned-object editor drawer -``` - -Die Namen sind Verantwortlichkeiten, keine vorab beschlossenen Tabellen- oder Ordnernamen. - -## 22. Performanceanforderungen - -**Bestätigte Anforderung** - -Das UI muss mehrere Tausend Objektzeilen praktisch bearbeitbar machen. - -Mindestens: - -- keine vollständige DOM-Darstellung aller Zeilen, falls dies die Bedienbarkeit beeinträchtigt; -- server- oder clientseitige effiziente Sortierung und Filterung; -- stabile Mehrfachauswahl; -- Sammelaktionen auf gefilterte Treffer; -- keine fachliche Änderung beim bloßen Filtern und Sortieren; -- keine automatische Neunummerierung; -- Import und Export dürfen zunächst synchron laufen, solange reale Projektdateien zuverlässig verarbeitet werden. - -Die Referenzdatei mit rund 900 Objektzeilen und über 1.100 Gesamtzeilen ist als Mindest-Integrationstest zu verwenden. - -## 23. Implementierungsphasen - -### Phase 14.0 – Audit und Verträge - -Ziel: - -- aktuelle ProjectDevice-, Row-, Command-, Snapshot- und Editorpfade prüfen; -- konkretes Datenmodell und Command-Schnittstellen vorschlagen; -- keine Implementierung vor Freigabe des Auditberichts. - -Lieferung: - -- Keep/Refactor/Add-Liste; -- vorgeschlagene Domainobjekte; -- vorgeschlagene Commands; -- Snapshot-/Transfer-Auswirkungen; -- Risiken bei Row-Mengen und lokalen Objektwerten. - -Abnahme: - -- keine bestehende Architekturregel wird umgangen; -- offene Punkte sind klar als solche markiert. - -### Phase 14.1 – CSV-Konfiguration und Parser - -Ziel: - -- projektweite Mappingkonfiguration; -- Parser und Serializer für das beobachtete CSV-Profil; -- reine Vorschau ohne Projektschreibvorgang. - -Abnahme: - -- Referenzdatei wird mit 897 Objektzeilen und 211 Passthrough-Summenzeilen erkannt; -- Titel-, Leer- und Summenzeilen bleiben erhalten; -- nichtleere `IfcGUIDs` sind eindeutig; -- Rückserialisierung ohne fachliche Änderungen erhält Struktur und Zellenwerte; -- Parser besitzt fokussierte Tests für BOM, CRLF, Semikolon, Quotierung und Kopfzeile in Zeile 2. - -### Phase 14.2 – Externe Objekte und Erstimport - -Ziel: - -- persistente externe Objekte; -- Raum-, Ebenen-, Verteilungs-, Klassifizierungs- und ProjectDevice-Verknüpfung; -- atomare Importübernahme. - -Abnahme: - -- Import erzeugt keine CircuitDeviceRow; -- Raum- und Verteilungszuordnung kann gespeichert werden; -- neues ProjectDevice kann vorausgefüllt erstellt werden; -- vorhandenes ProjectDevice wird nicht durch Revit-Werte verändert; -- Import ist ein Undo-Schritt; -- Undo entfernt den vollständigen bestätigten Importzustand. - -### Phase 14.3 – Stromkreislisteneditor - -Ziel: - -- unzugeordnete externe Objekte je Verteilung; -- Drag-and-drop zu Row, Circuit oder neuem Circuit; -- Aggregation und Mehrfachsteckdosen. - -Abnahme: - -- Drop auf Row ergänzt genau diese Row; -- Drop auf Circuit erzeugt eine neue Row; -- Drop auf neuen Zielbereich erzeugt Circuit und Row atomar; -- 2 Doppel- plus 2 Einzelsteckdosen ergeben Menge 6; -- keine Mehrfachsteckdose kann geteilt werden; -- verschiedene Räume und Auswahlkenner bleiben in getrennten Rows; -- Undo stellt externe Links, Mengen, Row-/Circuit-UUIDs und BMKs exakt wieder her. - -### Phase 14.4 – Rückexport - -Ziel: - -- strukturtreue Revit-Rückgabe-CSV. - -Abnahme: - -- Zeilen- und Spaltenzahl sowie Reihenfolge entsprechen der Ausgangsdatei; -- unbekannte Spalten und Passthrough-Zeilen bleiben erhalten; -- Stromkreis und Leistung werden ausschließlich in gemappte Objektzellen geschrieben; -- jedes Objekt behält seine `IfcGUID`; -- Mehrfachsteckdosen erhalten ihre Objektgesamtleistung in Watt; -- Export referenziert eine bekannte Projektrevision. - -### Phase 14.5 – Folgeimport und Konflikte - -Ziel: - -- additions, changes, missing objects and conflicts; -- Einzel- und Sammelentscheidungen. - -Abnahme: - -- neue Objekte werden erkannt; -- Raumänderungen werden konfliktbehaftet angezeigt; -- fehlende Objekte werden nicht automatisch entfernt; -- lokale Werte werden nicht automatisch überschrieben; -- bestätigte Änderungen sind ein atomarer Undo-Schritt; -- unveränderte Objekte erzeugen keine unnötigen Domainänderungen. - -### Phase 14.6 – Snapshot, Transfer und Härtung - -Ziel: - -- vollständige Projektportabilität; -- Performance und End-to-End-Tests. - -Abnahme: - -- Snapshot/Restore erhält sämtliche externe Links und Exportgrundlagen; -- Projektduplikat remapped interne UUIDs und behält `IfcGUIDs`; -- Undo/Redo funktioniert nach Reload; -- Referenz-CSV durchläuft Erstimport, Row-Zuordnung, Export, Folgeimport und Restore; -- vollständige Test- und Build-Suite läuft erfolgreich. - -## 24. End-to-End-Abnahmeszenarien - -### Szenario A – Gemischte Steckdosen - -Aus Revit: - -```text -Raum 01/101 -- 2 Doppelsteckdosen, jeweils Menge 2 -- 2 Einzelsteckdosen, jeweils Menge 1 -- gleicher CAx-Auswahlkenner -``` - -Erwartung: - -- 4 externe Objekte; -- wirksame Menge 6; -- Nutzer zieht alle Objekte auf eine neue Row; -- Row zeigt `6 × Steckdose`; -- alle vier CSV-Zeilen erhalten denselben Stromkreis; -- Doppelsteckdosen erhalten jeweils `2 × powerPerUnit` als Objektleistung; -- Einzelsteckdosen erhalten jeweils `1 × powerPerUnit`. - -### Szenario B – Gleiches ProjectDevice in mehreren Räumen - -Aus Revit: - -- gleicher Leuchtentyp in drei Technikräumen. - -Erwartung: - -- Nutzer wählt alle Leuchten raumübergreifend; -- erstellt ein neues, aus Revit-Werten vorausgefülltes ProjectDevice; -- alle Objekte werden damit verknüpft; -- es wird noch keine CircuitDeviceRow erzeugt; -- später entstehen je Raum getrennte Rows, sofern die Objekte verschiedenen Räumen zugeordnet werden. - -### Szenario C – Raumübergreifender Putzsteckdosenstromkreis - -- mehrere Räume mit jeweils wenigen Putzsteckdosen; -- Nutzer ordnet sie manuell demselben Circuit zu; -- pro Raum entsteht eine getrennte Row; -- alle Objekte erhalten dieselbe Stromkreiskennzeichnung. - -### Szenario D – Folgeimport mit Raumänderung - -- bekannte `IfcGUID`; -- Revit-Raumnummer ist geändert. - -Erwartung: - -- Objekt wird nicht neu angelegt; -- Raumänderung wird als Konflikt angezeigt; -- bestehende interne Raum-, Verteilungs- und Stromkreiszuordnung bleibt unverändert; -- Nutzer kann die Änderung einzeln oder gesammelt übernehmen. - -### Szenario E – Fehlendes Objekt - -- eine zuvor bekannte `IfcGUID` fehlt im vollständigen Folgeimport. - -Erwartung: - -- Objekt wird als fehlend markiert; -- Row-Menge und Leistung bleiben zunächst unverändert; -- erst bestätigte Löschung entfernt Link und Mengenanteil; -- Circuit bleibt auch bei leerer Row beziehungsweise nach Row-Entfernung bestehen; -- BMK wird nicht automatisch wiederverwendet. - -### Szenario F – Bestehende Stromkreiskennzeichnung beim Erstimport - -- Revit-Zeile enthält bereits `UV_AV_01-2F3`. - -Erwartung: - -- Wizard zeigt den Wert; -- Nutzer kann Quellwert behalten, Zuordnung übernehmen oder ignorieren; -- keine Option wird automatisch gewählt; -- unpassende Verteilung oder fehlender Circuit erzeugt Konflikt beziehungsweise bewusste Anlageentscheidung. - -### Szenario G – CSV-Passthrough - -- Titelzeile; -- Kopfzeile in Zeile 2; -- Leerzeile; -- Objektzeilen; -- Summenzeile ohne `IfcGUID`. - -Erwartung: - -- nur Objektzeilen erzeugen externe Objekte; -- Summenzeile erzeugt keine Fehlermeldung; -- Rückexport enthält alle Zeilen an derselben Position. - -## 25. Noch offene, phasengebundene Entscheidungen - -Diese Punkte blockieren die Erstellung dieser Spezifikation nicht. - -### Vor Phase 14.2 zu entscheiden - -- konkrete Benennung der neuen Domainobjekte und Tabellen; -- ob Importentwürfe vor der endgültigen Übernahme serverseitig gespeichert werden; -- genaue Versionierung der Mappingkonfiguration; -- genaue Speicherung der Original-CSV: vollständige Rohdatei, logische Zellmatrix oder Kombination. - -### Vor Phase 14.3 zu entscheiden - -- visuelle Position des Objekt-Drawers; -- Verhalten einer Mehrfachauswahl mit widersprüchlichen Planungswerten; -- Warnungsdialog bei fachlich unpassender Row; -- Verhalten, wenn eine Row manuelle Mengenanteile und externe Objekte kombiniert; -- genaue UI für das Lösen einer einzelnen externen Objektverknüpfung aus einer aggregierten Row. - -### Vor Phase 14.4 zu entscheiden - -- exaktes Revit-Zahlenformat für Dezimalwerte; -- genaue Formatierung von Wattwerten, zum Beispiel `1000 W` oder `1000`; -- Umgang mit Objekten ohne Stromkreis beim Rückexport: leeres Feld oder unveränderter Quellwert; -- Dateinamenschema der Rückgabe. - -### Spätere Ausbaustufen - -- automatische raumbezogene Stromkreisvorschläge; -- projektübergreifend wiederverwendbare Mappingprofile; -- Teilmodelle und mehrere externe Quellen; -- Dynamo/API/JSON-Transportadapter (nicht vorgesehen, siehe Abschnitt 1); -- Rollen und Berechtigungen; -- Hintergrundjobs; -- PostgreSQL. - -## 26. Arbeitsweise für Codex - -Vor jeder Phase: - -1. relevante bestehende Module auditieren; -2. angeben, was erhalten, erweitert oder ersetzt wird; -3. betroffene Commands, Snapshots und Transferformate nennen; -4. Migration und Rückwärtsverträglichkeit erläutern; -5. fokussierte Tests festlegen. - -Während der Implementierung: - -- kleine reviewbare Arbeitspakete; -- keine fachlichen Writes außerhalb der Command-Grenze; -- keine automatische BMK-Änderung; -- keine stillen Revit- oder ProjectDevice-Synchronisationen; -- keine ungefragte PostgreSQL- oder Dynamo-Implementierung; -- keine Kopplung von Domainlogik an CSV, React oder SQLite. - -Nach jedem Arbeitspaket: - -- fokussierte Tests; -- `npm test`; -- `npm run build:api`; -- `npm run build:web`; -- `npm run typecheck:scripts`; -- `npx tsc --noEmit -p tsconfig.next.json`; -- Dokumentation des neuen unterstützten Laufzeitpfads aktualisieren. +Der historische Inhalt bleibt im Git-Verlauf bis einschließlich Commit +`ae318a5` erhalten. Er darf nicht mehr als Implementierungsanweisung oder +Statusquelle verwendet werden. diff --git a/docs/spec/revit-csv-phase-14-audit-and-plan.md b/docs/spec/revit-csv-phase-14-audit-and-plan.md index a4c21e4..2d116b2 100644 --- a/docs/spec/revit-csv-phase-14-audit-and-plan.md +++ b/docs/spec/revit-csv-phase-14-audit-and-plan.md @@ -1,406 +1,8 @@ -# Phase 14: Audit- und Implementierungsplan für die Revit-CSV-Anbindung +# Abgelöst: alter Phase-14-CSV-Plan -## Status +Die Phasen 14.0–14.6 und ihre Erledigt-Markierungen sind abgelöst. Für die +Umstellung auf Linear-Excel gelten der [R0–R10-Plan](revit-excel-phase-14-plan.md) +und die [neuen Anforderungen](revit-excel-integration-requirements.md). -**Zurückgestellt:** Die weitere Revit-Arbeit wird später angegangen, dann -über den CSV-Export/-Import des Linear-Plugins in Revit statt über Dynamo. -Details: [Revit-CSV-Anforderungen, Abschnitt 1](revit-csv-integration-requirements.md). - -Phase 14.0 ist abgeschlossen und freigegeben. Dieses Dokument beschreibt den -gegen den aktuellen Code geprüften Zielzuschnitt. Phase 14.1 ist abgeschlossen. -Phase 14.2 hat mit den externen Domänenverträgen, Identitätsregeln und dem -additiven Persistenzschema begonnen; eine bestätigte Importübernahme existiert -noch nicht. - -Fachliche Quelle bleibt -[Revit-CSV-Integration – Anforderungen und Implementierungsanweisung](revit-csv-integration-requirements.md). -Dieses Dokument konkretisiert dafür Namen, Modulgrenzen, Persistenz und die -Reihenfolge kleiner Arbeitspakete. - -## Ergebnis des Bestandsaudits - -### Beibehalten - -- Das Circuit-First-Modell bleibt unverändert: Ein `Circuit` besitzt null bis - viele `CircuitDeviceRow`-Datensätze. -- `ProjectDevice` bleibt die kanonische projektweite Vorlage. Ein Import darf - diese Datensätze weder erzeugen noch ändern, solange der Nutzer dies nicht - ausdrücklich bestätigt. -- `CircuitDeviceRow.linkedProjectDeviceId` bleibt die optionale Verbindung - zwischen einer Gerätezeile und genau einer Projektgerätevorlage. -- Die bestehenden getrennten Drag-and-drop-Pfade für Projektgeräte, - Gerätezeilen und Stromkreise bleiben bestehen. Externe Objekte erhalten einen - vierten, fachlich eigenen Pfad. -- Alle bestätigten Änderungen verwenden typisierte Commands mit - `expectedRevision`, vollständiger Gegenrichtung und - `project-command-transaction.persistence.ts` als gemeinsamer - Transaktionsgrenze. -- Snapshot-Erfassung, Restore und Projektduplikat bleiben explizite Adapter mit - fester Fremdschlüsselreihenfolge und UUID-Remapping. -- SQLite und die heutige Server-Komposition bleiben der einzige unterstützte - Laufzeitadapter. - -### Erweitern oder gezielt refaktorieren - -- `ProjectStateSnapshot` und der portable Projekttransfer werden additiv um den - bestätigten externen Projektzustand erweitert. Bereits veröffentlichte - Snapshot-Versionen werden nicht verändert. -- Der Command-Dispatcher erhält schmale Stores für externe Konfiguration, - Importübernahme, Objektplanung und Row-Zuordnung. Controller erhalten keine - konkreten SQLite-Abhängigkeiten. -- Der Stromkreislisteneditor erhält später einen separaten Drawer für - unzugeordnete externe Objekte. Die bestehende Projektgeräteauswahl wird nicht - dafür zweckentfremdet. -- Vor der ersten externen Row-Zuordnung wird die Mengenhoheit einer - `CircuitDeviceRow` explizit gemacht; Details stehen unter „Mengenmodell“. - -### Hinzufügen - -- verlustarmer CSV-Transportadapter außerhalb von React und Circuit-Domain; -- projektweite, versionierte Revit-CSV-Konfiguration; -- eine zunächst implizite externe Modellquelle je Projekt; -- Importbatches einschließlich Originaltransport und akzeptiertem - Konfigurationsstand; -- persistente externe Objekte mit `IfcGUID`, getrennten Quell- und - Planungswerten und einzelnem Lebenszyklus; -- Quellraum-Mappings auf interne Räume und Standardverteilungen; -- explizite Verknüpfungen zu `ProjectDevice`, `CircuitDeviceRow` und optionaler - abweichender Verteilung; -- Vorschau-, Konflikt- und Exportprojektionen als reine Anwendungsservices; -- fokussierte Parser-, Command-, Transaktions-, Snapshot-, Transfer- und - End-to-End-Tests. - -### Entfernen - -Es existiert kein unterstützter Revit-Laufzeitpfad. Deshalb wird in Phase 14 -kein bestehender Fachpfad entfernt und keine Legacy-Kompatibilität eingeführt. - -## Vorgeschlagenes Domänenmodell - -Die Namen sind ab Phase 14.1 verbindliche Arbeitsnamen. Tabellen verwenden die -jeweilige englische Pluralform in `snake_case`. - -### `ExternalModelSource` - -- stabile interne UUID; -- `projectId`; -- technischer Name und Quelltyp `revit_csv`; -- der zuletzt bestätigte Importbatch wird aus der geordneten Batchhistorie - abgeleitet und nicht als redundanter Zeiger gespeichert. - -In der ersten Ausbaustufe wird genau eine Quelle je Projekt automatisch -angelegt. Es gibt bewusst keine sichtbare Mehrquellenverwaltung. Die -Eindeutigkeit eines externen Objekts ist trotzdem von Anfang an -`(sourceId, ifcGuid)`. - -### `ExternalCsvConfiguration` - -- stabile UUID und `projectId` mit genau einer aktiven Konfiguration; -- Konfigurationsschema-Version; -- CSV-Dialekt: Encoding, BOM, Trennzeichen, Zeilenende, Quote-Zeichen, - Dezimalformat und Kopfzeilenerkennung; -- exakte Spaltenzuordnung; -- geordnete, exakte Familie-und-Typ-Regeln; -- monotoner Konfigurationsstand. - -Eine Änderung ersetzt den vollständigen erwarteten Konfigurationssnapshot in -einem Command. Jeder bestätigte Importbatch speichert zusätzlich den dabei -verwendeten Konfigurationssnapshot. Damit bleiben ältere Importe erklärbar, -ohne eine zweite veränderbare Historientabelle einzuführen. - -### `ExternalImportBatch` - -- stabile UUID, `projectId`, `sourceId`, Importart und Zeitstempel; -- Dateiname, SHA-256 und zugehörige Projektrevision; -- verwendete monotone Konfigurationsversion und vollständiger - Konfigurationssnapshot; -- Originaldatei als Bytes; -- verlustarme logische Zellmatrix mit Zeilenklassen und Dialektmetadaten. - -Die Kombination aus Originalbytes und Matrix ist bewusst gewählt: Die Bytes -belegen den unveränderten Eingang, die Matrix erlaubt einen gezielten -Rückexport einzelner gemappter Objektzellen, ohne unbekannte Spalten, -Titelzeilen, Leerzeilen oder Summenzeilen neu zu interpretieren. - -### `ExternalRoomMapping` - -- stabile UUID, `sourceId` und normalisierter Quellraumschlüssel; -- Quellgeschoss-, Raumnummer- und Raumname-Snapshot; -- optionales `roomId`; -- optionale `defaultDistributionBoardId`. - -Das Mapping bleibt Teil der optionalen externen Integration. Dadurch erhält -das allgemeine Raummodell keine Revit-spezifische Pflichtbeziehung. - -### `ExternalModelObject` - -- stabile interne UUID, `projectId`, `sourceId` und unveränderte `ifcGuid`; -- letzter gesehener und letzter akzeptierter Importbatch; -- akzeptierte Quellwerte getrennt als strukturierter Snapshot; -- lokale Planungswerte für Anzeigename, Kategorie, Anschlussart, wirksame - Menge, Leistung je Einheit, Gleichzeitigkeitsfaktor, `cosPhi`, Kostengruppe - und Bemerkung; -- explizite Override-Metadaten; -- optionales `externalRoomMappingId`; -- optionale abweichende `distributionBoardId`; -- optionales `linkedProjectDeviceId`; -- optionales `circuitDeviceRowId`; -- Anwesenheitsstatus für bestätigte fehlende Objekte. - -Die n:1-Beziehung entsteht durch `circuitDeviceRowId` am Einzelobjekt: Viele -einzeln nachverfolgbare IFC-Objekte dürfen genau einer Gerätezeile zugeordnet -sein. Eine Mehrfachsteckdose bleibt ein einzelnes Objekt und trägt ihre -wirksame Menge größer eins. - -Konflikte werden soweit möglich aus akzeptiertem Quellstand, neuem -Vorschaustand und lokalen Overrides berechnet. Nur ein vom Nutzer bestätigter -Anwesenheits- oder Planungszustand wird persistiert. - -## Mengenmodell der Gerätezeile - -Die heutige `CircuitDeviceRow.quantity` unterscheidet nicht zwischen manueller -Menge und verknüpften IFC-Objekten. Ohne Erweiterung könnte das Lösen eines -Objekts manuelle Mengen löschen oder doppelt zählen. - -Vor Phase 14.3 wird deshalb `manualQuantity` ergänzt: - -```text -quantity = manualQuantity - + Summe(effectiveQuantity aller verknüpften ExternalModelObjects) -``` - -- Bei der Migration erhält jede bestehende Row - `manualQuantity = quantity`; ihr Ergebnis bleibt unverändert. -- Eine ausschließlich aus externen Objekten erstellte Row startet mit - `manualQuantity = 0`. -- `quantity` bleibt zunächst der materialisierte Gesamtwert für bestehende - Berechnungen, Filter und Exporte und wird im selben Command aktualisiert. -- Ein externes Objekt wird nie geteilt und kann höchstens einer Row zugeordnet - sein. -- Objekte dürfen nur aggregiert werden, wenn die rowbestimmenden lokalen Werte - übereinstimmen. Widersprüchliche Werte werden in der ersten Ausbaustufe nicht - automatisch vereinheitlicht, sondern benötigen getrennte Rows oder eine - ausdrückliche Nutzerentscheidung. -- Eine bestehende Row mit manueller Menge darf externe Objekte aufnehmen; beim - Lösen bleibt der manuelle Anteil erhalten. - -Für die UI vor Phase 14.3 bleibt noch festzulegen, ob eine nach dem Lösen leere -Row stehen bleibt oder nach gesonderter Bestätigung gelöscht wird. Ein stiller -Row-Lebenszyklus ist ausgeschlossen. - -## Command-Schnittstellen - -Alle Payloads tragen `schemaVersion: 1`, vollständige erwartete und gewünschte -Snapshots und werden mit der aktuellen Projektrevision geplant. Große -Importcommands dürfen umfangreich sein; sie müssen für Redo deterministisch -bleiben und dürfen spätere Quellstände nicht erneut auswerten. - -- `external-csv-configuration.update`: vollständige projektweite - Konfiguration ändern. -- `external-import.apply-initial`: Quelle, Batch, Raum-Mappings, externe - Objekte und bestätigte Links atomar einfügen. -- `external-import.apply-follow-up`: neuen Batch und die vollständigen - erwarteten/gewünschten Änderungen bestehender, neuer und fehlender Objekte - atomar übernehmen. -- `external-model-object.update-planning`: lokale Werte und Overrides eines - oder mehrerer Objekte ändern. -- `external-model-object.update-project-device-link`: ProjectDevice-Links - explizit setzen oder lösen, ohne das ProjectDevice zu verändern. -- `external-object.update-row-assignment`: Ein oder mehrere Objekte einer - bestehenden Row zuweisen, zwischen bestehenden Rows verschieben oder lösen - und alle betroffenen materialisierten Mengen atomar aktualisieren. -- `external-object.assign-to-new-row`: stabile neue Row einfügen, - Objekte verknüpfen und gegebenenfalls den Reserve-Status aktualisieren. -- `external-object.assign-to-new-circuit`: stabilen Circuit samt Schutz, - Row und Objektlinks in einem Schritt einfügen. Das geplante BMK wird im - Command gespeichert und bei Redo nicht neu berechnet. -- `external-model-object.delete-missing`: nur ausdrücklich bestätigte, - weiterhin unveränderte fehlende Objekte löschen. - -Die Erzeugung eines neuen `ProjectDevice` verwendet weiterhin den vorhandenen -`project-device.insert`-Command. Revit-Werte füllen lediglich das sichtbare -Formular vor; erst dessen Bestätigung erzeugt die Vorlage. CSV-Vorschau und -Rückexport sind reine Leseoperationen. Append-only Exportnachweise verändern -keine Projektrevision und laufen über einen eigenen Audit-Store. - -## Snapshot-, Transfer- und Migrationsfolgen - -- Phase 14.1 führt Migration `0002` für die Konfiguration ein und erhöht das - Project-State-Snapshot-Schema additiv von 2 auf 3. Der Upgrader von Version 2 - ergänzt `externalCsvConfiguration = null`. -- Phase 14.2 führt Migration `0003` für Quelle, Batches, Raum-Mappings und - Objekte ein und erhöht das Snapshot-Schema von 3 auf 4. Der Upgrader ergänzt - leere externe Collections. -- Phase 14.3 führt die additive Row-Spalte `manual_quantity` ein. Bestehende - Werte werden einmalig aus `quantity` übernommen. -- Snapshot-Capture und Restore erhalten Konfiguration, Quelle, bestätigte - Batches, Raum-Mappings und Objekte in expliziter FK-Reihenfolge. -- Beim Projektduplikat werden alle neuen internen UUIDs und internen Links - remappt. `IfcGUID`, Quellwerte, Transportmatrix und unbekannte CSV-Inhalte - bleiben unverändert. -- Der Transfer-Envelope kann Version 1 bleiben; die enthaltene - Project-State-Schema-Version wird additiv erhöht. -- Vorhandene Migrationen und Snapshot-Upgrader werden nicht editiert. - -## Implementierungsfolge - -### 14.1 – CSV-Konfiguration und reine Vorschau - -1. Transport-Domainverträge, Dialekt- und Mappingvalidatoren sowie kleine - synthetische Fixtures ergänzen. **Erledigt.** -2. Zustandsfreien Parser und Serializer mit Round-trip-Tests für UTF-8-BOM, - CRLF, Semikolon, vollständige Quotierung, Kopfzeile in Zeile 2 sowie - Titel-, Leer-, Objekt- und Passthrough-Zeilen implementieren. **Erledigt für - synthetische Testdaten; die Referenzdatei steht noch aus.** -3. Konfiguration über Migration, Snapshot v3, Transfer und den Command - `external-csv-configuration.update` persistieren. **Erledigt.** -4. Vorschau-Endpunkt und deutschen Projekt-Wizard ergänzen. **Erledigt:** - Konfigurations-Read/Write- und zustandsfreier Vorschau-Endpunkt sowie das - deutsche Konfigurations-/Vorschaumodal. Der Server speichert keinen Entwurf: Bei - Bestätigung wird die Datei erneut übertragen, erneut geparst und ihr Hash - gegen die Vorschau geprüft. - -**Phase 14.1 ist damit technisch abgeschlossen.** Die fachliche GUI-Abnahme -erfolgt vor Beginn der persistenten externen Objekte aus Phase 14.2. - -Abnahme: fokussierte Tests, vollständige Tests und alle vorgeschriebenen -Build-/Typecheck-Schritte. Die lokal bereitgestellte Referenz-CSV wird mit -`npm run revit:verify-reference` auf 897 Objektzeilen, 211 nichtleere -Passthrough-Summenzeilen und einen bytegleichen Round-trip geprüft. Da die -Referenzdatei reale Modelldaten enthalten kann, wird sie nicht automatisch in -einen Commit aufgenommen. - -### 14.2 – Persistente Objekte und Erstimport - -1. Schema, Repositories und reine Identitäts-/Matchingregeln ergänzen. - **Erledigt:** Migration `0003`, vollständiger externer Read-State sowie - exaktes IFCGUID-, Raum- und Familie-und-Typ-Matching sind vorhanden. Es gibt - weiterhin keinen Import-Write außerhalb eines Commands. -2. Snapshot v4, Restore und Projektduplikat samt UUID-Remapping ergänzen. - **Erledigt:** Version 3 wird mit leerem externem Zustand hochgestuft; - Capture, Restore, Undo/Redo und beide Transfermodi erhalten Originalbytes, - Matrix und sämtliche internen Links. Duplikate remappen alle internen UUIDs, - lassen IFCGUID und Quelltransport jedoch unverändert. -3. Erstimport-Command mit echten SQLite-Commit-/Rollback-Tests ergänzen. - **Erledigt:** `external-import.apply-initial` wechselt ausschließlich - zwischen leerem und vollständig bestätigtem externem Zustand. Er prüft - Konfigurationsversion, Original-Hash, erneut geparste Matrix, vollständige - IFCGUID-Menge, Quellwerte, explizite Overrides und projektinterne Links. - Der Command verbietet CircuitDeviceRow-Links, ist ein atomarer Undo-Schritt - und verwendet für Redo dieselben UUIDs und Bytes. Migration `0004` ergänzt - die zuvor noch fehlende monotone Konfigurationsversion am Batch; `0003` - bleibt unverändert. -4. Raum-, Verteilungs-, Klassifizierungs- und ProjectDevice-Schritte im Wizard - ergänzen; der Import selbst erzeugt keine CircuitDeviceRow. **Erledigt:** - Der zustandsfreie Planungs-Endpunkt liefert gruppierte Quellräume mit - exaktem Raumnummernvorschlag, Familie-und-Typ-Gruppen, Objektvorschläge, - Warnungszahlen sowie vorhandene Ebenen, Räume, Verteilungen und - ProjectDevices. Er blockiert nach einem bereits bestätigten Erstimport und - schreibt weder Entwurf noch Projektzustand. Der dedizierte - Endpunkt verlangt denselben Datei-Hash und Konfigurationsstand wie die - Planung, vollständige Entscheidungen für alle Quellräume und exakten - Familie-und-Typ-Gruppen und baut daraus serverseitig stabile UUIDs. Nicht - klassifizierte Familien blockieren. Raum-/Standardverteiler- und optionale - ProjectDevice-Links werden bestätigt, Stromkreis- und Row-Links bleiben - ausgeschlossen. Das breite Projektmodal zeigt Raumtreffer und Warnungen, - bietet die vorhandenen Raum-, Verteiler- und ProjectDevice-Kataloge an und - verlangt vor der atomaren Übernahme eine ausdrückliche Bestätigung. Fehlende - Räume und ProjectDevices lassen sich über die regulären, vorausgefüllten - Projektformulare anlegen und werden danach unmittelbar ausgewählt. Diese - Kataloganlagen bleiben eigenständige, rückgängig machbare Projektrevisionen. - -Vor Beginn werden die oben vorgeschlagenen Namen, die erneute Dateiübertragung -statt serverseitiger Entwürfe, die Konfigurationsversionierung und die -Kombination aus Originalbytes und Matrix als Entscheidungen bestätigt. - -### 14.3 – Editor und explizite Zuordnung - -1. `manualQuantity` und Mengeninvarianten migrieren und testen. - **Erledigt:** Migration `0005` übernimmt für jede bestehende Gerätezeile - `manualQuantity = quantity`. Neue normale Zeilen und Mengenänderungen führen - beide Werte gemeinsam; Snapshot/Transfer v5 erhält den Anteil und stuft v4 - verlustfrei hoch. Die reine Mengenregel validiert den materialisierten Wert - als manuellen Anteil plus Summe der unteilbaren externen Objektmengen. -2. Commands für vorhandene Row, neue Row, neuen Circuit und Lösen ergänzen. - **Teilweise erledigt:** `external-object.update-row-assignment` deckt - Zuweisung zu vorhandenen Rows, Verschieben zwischen vorhandenen Rows und - Lösen ab. Der Command prüft Projekt, Verteilung, Gruppenkategorie, Raum, - Selektionskennzeichen und Planungswerte, verlangt für bestätigbare - Planungsabweichungen eine explizite Objektliste und aktualisiert Links und - Gesamtmengen in einer SQLite-Transaktion. Seine exakte Gegenrichtung ist - dauerhaft Undo/Redo-fähig. Beim Lösen bleibt die Row mit ihrem manuellen - Mengenanteil bestehen. `external-object.assign-to-new-row` ergänzt die - Zuordnung ungebundener Objekte als neue Row in einem vorhandenen Circuit. - Diese Row erhält eine stabile ID und `manualQuantity = 0`; ihr historischer - Gegenbefehl entfernt sie nur, solange Row und Objektlinks vollständig - unverändert sind. Ein direktes Löschen über diesen internen Gegenbefehl ist - als Nutzeraktion gesperrt. `external-object.assign-to-new-circuit` schließt - den dritten Zielpfad: Ein serverseitig vorgeplanter Circuit mit festem BMK, - Standardschutz und genau einer externen Row wird gemeinsam mit den - Objektlinks eingefügt. Seine Historiengegenrichtung prüft den vollständigen - Circuit-Snapshot und die exakte Linkmenge, bevor sie den Teilbaum entfernt. - BMK und UUIDs bleiben bei Redo unverändert. Damit ist die persistente - Command-Grundlage dieses Schritts abgeschlossen; API-Planung und UI folgen. -3. Verteilungsbezogenen Drawer, Filter und Vorschau der Mengenwirkung ergänzen. - **Begonnen:** Die reine Read-Projektion und der projekt-/listenbezogene - GET-Endpunkt liefern ausschließlich Objekte des zugehörigen Verteilers, - unzugeordnete Objekte zuerst, einschließlich Quellraum, Selektionsmarker, - Planungswerten und aktuellem Row-Link. API-Client und DTOs sind vorhanden; - Drawer, Filter und Mengenwirkung folgen. -4. Einzel- und Mehrfach-Drag-and-drop samt Warnungen, Undo/Redo und Reload - testen. - -Vor Beginn werden Drawerposition, Verhalten widersprüchlicher Mehrfachauswahl, -Warnungsdialoge und der Lebenszyklus leerer Rows festgelegt. - -### 14.4 – Strukturtreuer Rückexport - -1. Exportprojektion gegen eine bekannte Projektrevision ergänzen. -2. Nur gemappte Objektzellen in einer Kopie der akzeptierten Matrix ersetzen. -3. Dialekt, Reihenfolge, unbekannte Zellen und Passthrough-Zeilen erhalten. -4. Download und append-only Exportnachweis ergänzen. - -Zahlenformat, leere Stromkreiswerte und Dateiname werden vorher fachlich -festgelegt. - -### 14.5 – Folgeimport und Konflikte - -1. Deterministischen Diff nach `(sourceId, ifcGuid)` ergänzen. -2. Neu, geändert, unverändert, fehlend und konfliktbehaftet projizieren. -3. Einzel- und Sammelentscheidungen im Wizard ergänzen. -4. Akzeptierten Diff als einen atomaren Command mit vollständigem Undo/Redo - übernehmen. - -### 14.6 – Härtung und End-to-End-Abnahme - -1. Alle Szenarien A bis G der verbindlichen Spezifikation automatisieren. -2. Referenzdatei über Vorschau, Erstimport, Zuordnung, Export, Folgeimport, - Snapshot/Restore und Projektduplikat prüfen. -3. Abfrageindizes und große Payloads mit mehreren tausend Objekten messen. -4. Architektur-, API-, Betriebs- und Nutzerdokumentation auf den tatsächlich - ausgelieferten Stand nachziehen. - -## Risiken und Schutzmaßnahmen - -- **Mengenverlust:** `manualQuantity` trennt manuelle und externe Anteile; - Commands ändern Links und materialisierte Menge gemeinsam. -- **Stilles Überschreiben:** Quellwerte, lokale Werte und Overrides sind - getrennt; jede Übernahme benötigt eine Nutzerentscheidung. -- **ProjectDevice-Verfälschung:** Links ändern niemals die kanonische Vorlage; - deren bestehende Commands bleiben alleinige Schreibgrenze. -- **Nicht reproduzierbarer Export:** Jeder Batch hält Originalbytes, Matrix, - Dialekt, Konfiguration, Hash und Projektrevision. -- **Sehr große Undo-Payloads:** Importcommands speichern vollständige - erwartete/Zielzustände. Größe und Transaktionsdauer werden in 14.2 gemessen, - nicht durch indirekte oder nachträglich neu berechnete Payloads optimiert. -- **BMK-Drift:** Neue BMKs werden einmal bei der Planung berechnet und im - Command gespeichert; Import, Sortierung und Redo nummerieren nie implizit. -- **Vertrauliche Referenzdaten:** Der Referenzprüfer läuft lokal gegen die - bereitgestellte CSV. Vor einer Aufnahme dieser Datei in Git ist gesondert zu - klären, ob sie ausreichend anonymisiert und zur Weitergabe freigegeben ist. - -## Freigabepunkt - -Mit der Freigabe dieses Audits beginnt Arbeitspaket 14.1.1: reine -Transportverträge, Validatoren und synthetische CSV-Fixtures. Dieses Paket -ändert weder Datenbank noch GUI und führt keine Projektschreibvorgänge aus. +Der historische Inhalt bleibt im Git-Verlauf bis einschließlich Commit +`ae318a5` erhalten und darf nicht fortgeschrieben werden. diff --git a/docs/spec/revit-excel-integration-requirements.md b/docs/spec/revit-excel-integration-requirements.md new file mode 100644 index 0000000..ff580ec --- /dev/null +++ b/docs/spec/revit-excel-integration-requirements.md @@ -0,0 +1,463 @@ +# Revit-Integration über Linear-Excel – verbindliche Anforderungen + +Stand: 29.09.2026. Dieses Dokument ist die fachliche und technische +Arbeitsgrundlage für die neue Phase 14. Es ersetzt die frühere CSV-/IfcGUID- +Spezifikation. Der Umsetzungsstand steht im +[R0–R10-Plan](revit-excel-phase-14-plan.md); der geprüfte Ausgangszustand im +[R0-Audit](revit-excel-r0-audit.md). + +## 1. Ziel und Grenzen + +Der Austausch mit Revit erfolgt ausschließlich über den XLSX-Export/-Import +des Linear-Plugins. Eine vollständige Revit-Bauteilliste wird importiert, in +Leistungsbilanz geplant und mit gleichem Tabellenaufbau an Linear +zurückgegeben. Linear ordnet enthaltene Zeilen anhand der Worksharing-ID zu. + +Nicht Teil dieser Phase sind Dynamo, Revit-API, JSON-Transport, automatische +Stromkreisbildung, Übernahme vorhandener Revit-Stromkreiswerte, +Teilimporte, mehrere Modellquellen, PostgreSQL und neue Rollen/Rechte. + +Die Integration bleibt optional. Manuelle Projekte, Räume, ProjectDevices, +Stromkreise und Gerätezeilen funktionieren ohne externes Modell. Der +Circuit-First-Aufbau, stabile interne UUIDs und BMKs, ausdrückliche +Neunummerierung sowie die gemeinsame Project-Command-Transaktionsgrenze +bleiben unverändert. + +## 2. Verbindliche fachliche Regeln + +- Import erzeugt keine `CircuitDeviceRow`, keinen `Circuit` und kein BMK. +- Quellwerte, lokale Planungswerte und Overrides bleiben getrennt. +- Ein Folgeimport überschreibt keine lokale Planung still. +- Fehlende Objekte werden markiert und erst nach ausdrücklicher Bestätigung + entfernt. +- Mehrfachsteckdosen sind unteilbare externe Objekte. Ihre wirksame Menge kann + größer als eins sein. +- Die Row-Menge ist + `manualQuantity + Summe(effectiveQuantity der verknüpften Objekte)`. +- Nach einer Row-Zuordnung ist die `CircuitDeviceRow` die Planungsebene für + alle verknüpften Objekte. +- Bestehende ProjectDevices bleiben kanonische Vorlagen und werden durch + Importe nie verändert. +- Sortieren, Filtern, Importieren, Zuordnen und Verschieben nummeriert keine + Stromkreise automatisch neu. + +## 3. Linear-XLSX-Profil + +Die lokale Referenzdatei `docs/spec/kbp-Stromkreis.xlsx` enthält vertrauliche +Projektdaten. Sie wird nicht committed und nicht in Tests eingebettet. Tests +erzeugen synthetische Workbooks. Der lokale Referenzprüfer erhält den Pfad als +Argument. + +Beobachtetes Profil: + +- genau ein Arbeitsblatt; Blattname nach Excel-Regel maximal 31 Zeichen; +- Kopfzeile in Zeile 1, Zeile 2 leer, Daten ab Zeile 3, erste Datenspalte A; +- Spalte A `Worksharing-ID` im Format `-<8 Hex>`; +- Parameterbindungen stehen als klassische Excel-Kommentare in den übrigen + Kopfzellen; +- Zahlen sind typisierte Excel-Zahlen; importierte Werte bleiben unverändert, + fachlich verwendete Leistung wird auf 0,01 W projiziert; +- Objektzeilen dürfen keinen MEP-Raum besitzen; +- eine Schluss-/Summenzeile ohne ID kann vorkommen und wird weder importiert + noch zurückgegeben. + +Die Referenzdatei enthält 487 Objektzeilen, eindeutige Worksharing-IDs und +keine doppelten nichtleeren IfcGUIDs bei exaktem, case-sensitivem Vergleich. +Ihre Summenzeile steht in Spalte B (`CAx_Auswahlkenner`), während +`Familie und Typ` leer ist. + +### Zeilen ohne Worksharing-ID + +Nur eine Zeile ohne Worksharing-ID, aber mit befülltem Feld +`Familie und Typ`, gilt als verdächtige Objektzeile. Sie erzeugt einen Hinweis +und wird übersprungen; sie blockiert den Import nicht. Andere Zeilen ohne ID, +einschließlich einer nur in Spalte B befüllten Summenzeile, werden ohne Hinweis +übersprungen. Eine Objektzeile ist für den Import eine Zeile mit nichtleerer +Worksharing-ID. + +Worksharing-ID und IfcGUID werden stets exakt, ordinal und mit +Groß-/Kleinschreibung verglichen. Es findet kein Trimmen, Normalisieren oder +Case-Folding für die Identität statt. Eine nichtleere Worksharing-ID mit +unerlaubten äußeren Leerzeichen oder falschem Format blockiert. Doppelte +Worksharing-IDs blockieren. IfcGUID ist optional, kein Schlüssel und darf +doppelt vorkommen; Duplikate erzeugen lediglich einen Hinweis. + +## 4. Upload und Transportadapter + +Der Server akzeptiert ausschließlich Dateien mit Endung `.xlsx` bis 10 MiB. +`.xls` und `.xlsm` werden abgelehnt. Parsing findet serverseitig statt. Nach +dem Einlesen gelten feste Zeilen-, Spalten- und Zellgrenzen, die in R2 anhand +synthetischer Grenztests festgelegt und zentral definiert werden. Es gibt in +dieser Phase keinen eigenen ZIP-Prüfer und keinen Parser-Worker. + +Der Adapter unter `src/external-model/xlsx` liest eine transportneutrale +Zellmatrix. Eine Zelle ist `string`, `number`, `boolean` oder `empty`. +Zusätzlich werden Blattname, Originalzeilennummer, Kopfzeilenkommentare, +Spaltenbreiten und die für Hinweise nötigen Formelmetadaten erfasst. +Domain-Services kennen weder ExcelJS noch XLSX, React oder SQLite. + +Formeln werden niemals ausgeführt. Ist ein gecachter skalarer Wert vorhanden, +wird er verwendet und als Hinweis ausgewiesen. Fehlt er oder ist er ein +Fehlerwert, bleibt das Feld leer; bei der Worksharing-ID oder einem anderen +Pflichtfeld blockiert dies die betreffende Objektzeile beziehungsweise den +Import. + +Genau eine gepflegte Bibliothek wird ergänzt. Vorgesehen ist `exceljs`, sofern +R2 die Node-24-Verträglichkeit und den Roundtrip von Kopfkommentaren, +Blattname, Spaltenbreiten, Formaten und Zelltypen bestätigt. + +## 5. Projektkonfiguration + +Die Konfiguration ist projektweit, revisionssicher und besitzt keine eigene +Versionszählung. Jeder Plan und jedes Apply tragen `expectedRevision`. +Da die Projektrevision auch bei Undo/Redo strikt steigt, wird ein alter Plan +automatisch ungültig. Jeder Importbatch speichert eine vollständige Kopie der +beim Import verwendeten Konfiguration. + +Das Einstellungsmodal auf der Revit-Seite erkennt aus einer zustandslos +hochgeladenen Musterdatei Kopfzeile, erste Datenzeile und erste Datenspalte. +Diese Werte bleiben editierbar; Standard ist 1 / 3 / A. Es gibt nur ein Feld +für die Identitätsspalte: `columns.worksharingId`. Ein separates +`layout.idColumn` existiert nicht. + +Zielvertrag: + +```ts +interface ExternalModelConfiguration { + schemaVersion: 1; + layout: { + headerRow: number; + firstDataRow: number; + firstDataColumn: number; + }; + circuitMode: "combined" | "separate"; + columns: { + worksharingId: string; + ifcGuid: string | null; + roomNumber: string | null; + roomName: string | null; + familyAndType: string; + selectionMarker: string | null; + socketCount: string | null; + sourceRemark: string | null; + circuitCombined: string | null; + boardName: string | null; + circuitIdentifier: string | null; + designation: string | null; + electricalPowerW: string | null; + voltageV: string | null; + currentA: string | null; + }; + deviceTypes: DeviceTypeConfiguration[]; + familyTypeRules: FamilyTypeRule[]; +} +``` + +Standardzuordnung: + +| Schlüssel | Bedeutung | Standardspalte | +| --- | --- | --- | +| `worksharingId` | externe Identität, Pflicht | `Worksharing-ID` | +| `ifcGuid` | optionale Redundanz | `IfcGUID` | +| `roomNumber` | Raumnummer | `MEP-Raum: Nummer` | +| `roomName` | Raumname | `MEP-Raum: Name` | +| `familyAndType` | Familie und Typ, Pflicht | `Familie und Typ` | +| `selectionMarker` | CAx-Auswahlkenner | `CAx_Auswahlkenner` | +| `socketCount` | Anzahl Einzelsteckdosen | `CAX_AnzahlObjekte` | +| `sourceRemark` | Anmerkung | `CAx_Anmerkung` | +| `circuitCombined` | Stromkreis gesamt | `kbp_Stromkreisnummer` | +| `boardName` | Verteiler | `kbp-E-Verteiler` | +| `circuitIdentifier` | Stromkreis-BMK | `kbp-E-Stromkreis` | +| `designation` | Bezeichnung | `kbp-E-Bezeichnung` | +| `electricalPowerW` | elektrische Leistung [W] | `kbp-E-Elektrische Leistung` | +| `voltageV` | Spannung [V] | `kbp-E-Spannung` | +| `currentA` | Stromstärke [A] | `kbp-E-Stromstärke` | + +`worksharingId` und `familyAndType` sind Pflichtmappings. Im Modus +`combined` ist `circuitCombined` für den Rückexport Pflicht; im Modus +`separate` sind `boardName` und `circuitIdentifier` Pflicht. Fehlende optionale +Rückgabespalten `designation`, `electricalPowerW`, `voltageV` und `currentA` +werden mit Hinweis übersprungen und blockieren den Export nicht. + +Jedes interne Feld besitzt im Modal ein Dropdown aus den Kopfzellen und eine +freie Eingabe. Exakte kbp-Standardnamen werden vorbelegt. Typ und Einheit aus +dem Linear-Kommentar werden angezeigt. Nicht gemappte Spalten bleiben beim +Rückexport unverändert. + +## 6. Gerätearten und Familie-und-Typ-Regeln + +Eine Geräteart besitzt stabile interne UUID, Name, Kategorie +`lighting | single_phase | three_phase` sowie optionale Standardwerte für +Leistung je Einheit in W, GZF, cosPhi und Kostengruppe. Jede exakte +`Familie und Typ`-Regel verweist auf genau eine Geräteart und verwendet die +Mengenregel `1` oder `socketCount`. + +Mehrere Revit-Familien dürfen auf dieselbe Geräteart zeigen. Jedes Revit- +Objekt bleibt trotzdem einzeln über seine Worksharing-ID nachverfolgbar. +Unbekannte Familien müssen im Importwizard zugeordnet oder über eine neue +Geräteart klassifiziert werden; andernfalls blockiert Apply. + +Planungsstartwerte folgen dieser Reihenfolge: + +1. ausdrücklich verknüpftes ProjectDevice; +2. Geräteart-Standard; +3. leer. + +Der Anzeigename wird aus CAx-Auswahlkenner, dann Geräteartname, dann +`Familie und Typ` vorgeschlagen. Ein fehlender GZF wird mit `1` vorbelegt, +ohne zusätzliche Bestätigung. Standardwerte sind Startwerte, keine dauerhafte +Synchronisierung. + +## 7. Persistenter externer Zustand + +Pro Projekt existiert genau eine implizite Revit-XLSX-Quelle. Ein externes +Objekt besitzt eine interne UUID und ist je `(sourceId, worksharingId)` +eindeutig. `worksharingId` ist NOT NULL; `ifcGuid` ist nullable und nicht +eindeutig. Interne Relationen verwenden ausschließlich interne UUIDs. + +Gespeichert werden: + +- akzeptierte Quellwerte einschließlich aller Rückgabefelder; +- lokale Planungswerte und Override-Felder; +- Geräteart; +- optionales Raum-Mapping, abweichender Verteiler, ProjectDevice und + `CircuitDeviceRow`; +- Anwesenheitsstatus und Verweis auf den zuletzt relevanten Import; +- effektive Menge als fachlicher Wert des unteilbaren Objekts. + +Der effektive Verteiler eines verknüpften Objekts ist immer der Verteiler +seiner Row. Für ein unzugeordnetes Objekt gilt zuerst die explizite +Objektabweichung, danach der Standardverteiler seines Raum-Mappings. Ändert +sich der Standardverteiler eines Raums, betrifft das nur unzugeordnete +Objekte; verknüpfte Objekte bleiben über ihre Row unverändert und die Änderung +wird deshalb nicht gesperrt. + +## 8. Importbatch-Aufbewahrung, Snapshot und Transfer + +Der aktive Projektzustand enthält den letzten Importbatch vollständig: +Originalbytes, klassifizierte Matrix, Dateiname, SHA-256, Zeitpunkt, +Objektzahl, Importart, Projektrevision und Konfigurationskopie. Ältere Batches +werden zu Metadaten reduziert: Datum, Dateiname, SHA-256 und Objektzahl. +Sie enthalten keine Originalbytes, Matrix oder Konfigurationskopie mehr. + +Snapshot-Schema 10 und portabler Projekttransfer übernehmen genau diese +Aufteilung. Beim Duplizieren werden alle internen UUIDs und Links remapped; +Worksharing-IDs, optionale IfcGUIDs, Quellwerte und das letzte Workbook bleiben +unverändert. + +Versionen 1–9 ohne externe CSV-Daten werden verlustfrei auf Version 10 +hochgestuft. Enthält ein alter Stand eine CSV-Konfiguration oder einen nicht +leeren CSV-Zustand, wird er mit klarer deutscher Fehlermeldung abgelehnt. +Alte CSV-History-Commands werden ebenfalls vor jedem Write abgelehnt und nie +stillschweigend übersprungen. + +## 9. Erstimport + +Der Ablauf ist Upload → zustandslose Vorschau/Planung → erneute +Dateiübertragung bei Apply. Apply prüft SHA-256, `expectedRevision`, +Konfigurationskopie, Matrix und sämtliche Entscheidungen erneut. Nur Apply +liest die Excel-Datei erneut ein. + +Undo und Redo lesen keine Excel-Datei und parsen keine gespeicherten Bytes. +Sie arbeiten ausschließlich auf den im Command gespeicherten vollständigen +Vorher-/Nachher-Zuständen. Dadurch bleiben sie nach Neustart deterministisch +und unabhängig vom Parser. + +Der Wizard umfasst: + +1. Vorschau mit Objektzahl, übersprungenen und verdächtigen Zeilen, + doppelten Worksharing-IDs, doppelten IfcGUID-Hinweisen, unbekannten + Familien, nicht lesbaren Zahlen und Formeln; +2. Räume anlegen oder vorhandenen Räumen/Ebenen zuordnen; +3. Standardverteiler je Raum, Sammelzuordnung, Objektabweichungen und Objekte + ohne Raum; +4. Familien exakt Gerätearten und einer Mengenregel zuordnen; +5. optional vorhandene oder neu angelegte ProjectDevices verknüpfen; +6. Zusammenfassung und ausdrückliche Bestätigung. + +Die Übernahme ist ein atomarer Command und ein Undo-Schritt. Im Import +entstehen keine Rows. Neu angelegte Räume und ProjectDevices verwenden ihre +vorhandenen Commands und bleiben eigene Undo-Schritte. + +## 10. Objektplanung und Revit-Seite + +Route: `/projects/:projectId/revit`, erreichbar aus der Projektnavigation. +Der Revit-Button und das CSV-Modal auf der Projektübersicht entfallen. + +Die Seite besitzt: + +- Statuskarte mit letztem Import, Objektzahl, ohne Verteiler, ohne + Stromkreis, fehlend und Abweichung zu Revit; +- Aktionen `Import`, `Rückgabe-Excel`, `Einstellungen`; +- einklappbare Geräteart-/Familienregel-Übersicht; +- kompakte Objekttabelle mit Suche, Spaltenfiltern, Sortierung, + Mehrfachauswahl und Sammelzuordnung für Verteiler, ProjectDevice und + Planungswerte. + +Die kompakte Liste wird einmal geladen, vollständig im Client gefiltert und +sortiert und virtualisiert dargestellt. Es gibt keine Server-Pagination. +Originalbytes, Matrix und Command-Payloads gehören nicht in dieses DTO. + +Vor Row-Zuordnung lassen sich Leistung je Einheit, GZF, cosPhi, +Kostengruppe, Anzeigename und Bemerkung einzeln oder gesammelt ändern. +Geänderte Felder werden Overrides. Nach Row-Zuordnung werden diese Werte im +Grid an der Row bearbeitet. Beim ausdrücklichen Lösen erhält das Objekt die +aktuellen Row-Werte als Planungswerte und entsprechende Overrides. + +## 11. Editor-Zuordnung und Löschen + +Der rechte, überlagernde Editorbereich zeigt unzugeordnete konfliktfreie +Objekte des aktuellen Verteilers. Gruppierungsschlüssel sind interner Raum, +Auswahlkenner, Geräteart, Kategorie, identische Planungswerte und kompatibler +ProjectDevice-Link. Die Anzeige nennt Summe der wirksamen Mengen und Zahl der +externen Objekte. Gruppen sind aufklappbar; Einzel- und Mehrfachauswahl sowie +Filter bleiben möglich. + +Drag-and-drop: + +- auf vorhandene Row: genau diese Row; +- auf Circuit: neue Row mit `manualQuantity = 0`; +- auf freien Bereich: neuer Circuit, Schutz und Row in einem Command. + +Neue IDs und BMK werden einmal geplant; Redo rechnet sie nicht neu. Neue Rows +übernehmen den bestätigten Gruppenzustand und die Summe der effektiven Mengen. +An Rows zeigt ein Hinweis die Zahl verknüpfter Revit-Objekte; einzelne Objekte +können ausdrücklich gelöst werden. + +Wird eine Row, ein Circuit oder eine Gruppe mit verknüpften Revit-Objekten +gelöscht, zeigt die UI vor Bestätigung: +`X Revit-Objekte werden wieder unzugeordnet`. Derselbe Löschcommand löst die +Objekte, entfernt die Struktur und speichert alle Links in seiner Inversen. +Undo stellt Struktur und Links exakt wieder her. Diese Löschungen werden nicht +gesperrt. + +Das Löschen eines Verteilers oder Raums mit referenzierten externen Objekten +bleibt gesperrt. Der Nutzer muss die Verknüpfungen beziehungsweise Zuordnungen +zuvor ausdrücklich ändern. Die Regel gilt auch für Unterbaum- und History- +Pfade. + +## 12. Rückgabe-Excel + +Der Export ist eine Leseoperation ohne Projektrevision. Ein append-only +Nachweis speichert Projektrevision, zugrunde liegenden letzten Import, +Zeitpunkt, Dateiname, SHA-256, Konfigurationskopie beziehungsweise ihren Hash +und Objektzahl. + +Umfang: + +- alle im letzten Import vorhandenen Objekte (Standard); +- nur Objekte mit Abweichung zum zuletzt importierten Revit-Wert; +- Auswahl aus der Objekttabelle. + +Die Rückgabe basiert auf einer Kopie des zuletzt importierten Workbooks. +Zeilen oberhalb der ersten Datenzeile, Kopfkommentare, Formate, +Spaltenbreiten, Blattname und Spaltenreihenfolge bleiben erhalten. Danach +folgen nur die gewählten Objektzeilen in ihrer Originalreihenfolge. Alle +Spalten bleiben enthalten; Summenzeilen entfallen. + +Stromkreiswerte: + +- `combined`: `DistributionBoard.name + Circuit.equipmentIdentifier`, ohne + Trennzeichen; +- `separate`: Verteilername und unverändertes BMK in getrennten Spalten; +- ohne Circuit: Stromkreisfeld beziehungsweise beide Felder leer. + +Die Wahl des Verteilerwerts liegt in genau einer Funktion und verwendet +zunächst `DistributionBoard.name`. + +Weitere Rückgabewerte: + +- Bezeichnung = Row-`displayName`, ohne Row Planungs-Anzeigename; +- Leistung [W] = effektive Menge × Einzelleistung, ohne GZF; +- Spannung = Circuit-Spannung, sonst Projektstandard der Kategorie; +- Strom = `P / (U × cosPhi)` beziehungsweise + `P / (sqrt(3) × U × cosPhi)`, auf 0,01 A; +- nicht berechenbar = leere Zelle plus Hinweis. + +Zahlen werden als Excel-Zahlen geschrieben. Fehlende optionale Zielspalten +werden mit Hinweis ausgelassen. Nur fehlende Stromkreisspalten des gewählten +Modus blockieren. Dateiname: +`_Revit-Rueckgabe_.xlsx`. + +## 13. Verbindliche R2-Abnahme mit Linear + +R2 endet mit einer Rückgabedatei, die aus der lokalen realen Musterdatei +erzeugt wurde und einige klar identifizierbare Rückgabewerte verändert. Diese +Datei wird nicht committed. Der Nutzer testet sie in Linear. R3 darf erst nach +erfolgreichem Linear-Rückimport beginnen. + +Scheitert der Linear-Import, wird vor R3 eine Alternative zur Freigabe +vorgelegt: Die Original-XLSX wird direkt auf OOXML-Ebene kopiert und nur die +erforderlichen Zellwerte/-typen sowie Zeilenbereiche angepasst. Die +Alternative bleibt hinter demselben transportneutralen Adaptervertrag. + +## 14. Folgeimport + +Jeder Import ist eine vollständige Projektbauteilliste. Matching erfolgt +ausschließlich über exakt und case-sensitiv verglichene Worksharing-ID. + +- neu: Wizard-Schritte nur für neue Objekte und unbekannte Familien; +- geänderte Quellwerte: Einzel- oder Sammelentscheidung; +- akzeptierte Mengenänderung: verknüpfte Row-Menge im selben Command; +- fehlend: markieren, Link und Menge zunächst beibehalten; +- Löschen: erst nach gesonderter Bestätigung; +- abweichende Rückgabefelder: Hinweis `in Revit noch nicht aktualisiert`, + keine Übernahmeentscheidung. + +`external-import.apply-follow-up` ist atomar und ein Undo-Schritt. +Unveränderte Objekte erzeugen keine unnötigen Objekt- oder Row-Änderungen. +Der neue vollständige Batch wird letzter Batch; der zuvor letzte Batch wird +auf Metadaten reduziert. + +## 15. Commands, Persistenz und Sicherheit + +Projektbezogene Writes verwenden typisierte Commands mit vollständiger +Gegenrichtung, `expectedRevision`, Anmeldung, CSRF-Header und +`project-command-transaction.persistence.ts`. Dazu gehören mindestens: + +- `external-model-configuration.update`; +- `external-import.apply-initial`; +- `external-import.apply-follow-up`; +- `external-model-object.update-planning`; +- `external-model-object.update-distribution-board`; +- `external-model-room-mapping.update`; +- `external-model-object.update-project-device-link`; +- `external-object.update-row-assignment`; +- `external-object.assign-to-new-row`; +- `external-object.assign-to-new-circuit`; +- `external-model-object.delete-missing`; +- die erweiterten Row-/Circuit-/Gruppen-Löschcommands mit Objekt-Link- + Transitionen. + +Die Konfiguration selbst ist Teil der erwarteten/gewünschten Snapshots, aber +hat keinen eigenen monotonen Zähler. Importbatches halten eine unveränderliche +Konfigurationskopie. Preview/Plan sind zustandslos. Apply überträgt und parst +die Datei erneut; Undo/Redo führt nur gespeicherte Zustandsübergänge aus. + +Neue Migrationen sind additiv. Vor Anwendung wird die Datenbank gesichert und +das generierte SQL geprüft. Da nur Entwicklungsdaten existieren, darf die +Migration alte externe CSV-Daten verwerfen. Vor dem Löschen externer Objekte +werden betroffene Row-Mengen auf `manualQuantity` zurückgesetzt. Der Verlust +des alten externen Entwicklungszustands wird dokumentiert. + +## 16. Abnahme und Leistung + +Die Oberfläche muss mehrere Tausend Objekte flüssig bedienen. R10 misst +Import, Command-/Snapshot-Größe, Speicherbedarf und Client-Interaktion mit +synthetischen großen Workbooks. Die virtualisierte Tabelle rendert nur den +sichtbaren Ausschnitt, während Filterung, Sortierung und Auswahl auf der einmal +geladenen kompakten Liste arbeiten. + +Jedes Paket R1–R10 führt fokussierte Tests sowie aus: + +```text +npm test +npm run build:api +npm run build:web +npm run typecheck:scripts +npx tsc --noEmit -p tsconfig.next.json +``` + +Jedes Paket erhält einen eigenen knappen imperativen Commit. Die konkrete +Paketfolge und ihre Freigabepunkte stehen im +[R0–R10-Plan](revit-excel-phase-14-plan.md). diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md new file mode 100644 index 0000000..46b4fba --- /dev/null +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -0,0 +1,173 @@ +# Phase 14 neu – Plan für die Linear-Excel-Anbindung + +Verbindliche Fachgrundlage: +[Revit-Integration über Linear-Excel](revit-excel-integration-requirements.md). +Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. + +## Status + +| Paket | Status | Ergebnis / Freigabepunkt | +| --- | --- | --- | +| R0 | abgeschlossen und freigegeben | Bestandsaudit, Zielmodell, Migration und Risiken; Freigabekorrekturen in R1 eingearbeitet. | +| R1 | abgeschlossen | Anforderungen, Plan und Architektur auf Excel/Worksharing-ID umgestellt; alle Pflichtprüfungen bestanden. | +| R2 | offen | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei. Danach zwingende Linear-Abnahme durch den Nutzer. | +| R3 | gesperrt bis R2-Abnahme | Konfiguration, Identität, Migration, Snapshot 10, Transfer und Backend-CSV-Entfernung. | +| R4 | offen | Revit-Seite, Navigation, Einstellungen, altes Projektseitenmodal entfernen. | +| R5 | offen | Erstimportwizard mit Gerätearten, Familienregeln und optionalen ProjectDevices. | +| R6 | offen | Virtualisierte Objekttabelle und Sammelzuordnungen. | +| R7 | offen | Editorbereich, Gruppierung, Drag-and-drop, Lösen und integrierte Löschübergänge. | +| R8 | offen | Rückgabe-Excel und append-only Exportnachweis. | +| R9 | offen | Vollständiger Folgeimport nach Worksharing-ID. | +| R10 | offen | Ende-zu-Ende-Härtung, große Datenmengen und Abschlussdokumentation. | + +## R0 – Audit + +Ergebnis: [R0-Audit](revit-excel-r0-audit.md). Die Freigabe vom 29.09.2026 +enthält 13 Korrekturen. Bei Abweichungen zwischen dem historischen Audit und +der aktuellen Anforderung gilt das neue Anforderungsdokument. + +## R1 – Dokumentation + +Lieferumfang: + +- neues verbindliches Excel-Anforderungsdokument; +- dieser R0–R10-Plan; +- alte CSV-Anforderungen und alter Plan als kurze Ablösungshinweise; +- LLM-Kontext auf die neue Quelle der Wahrheit kürzen; +- `AGENTS.md`, aktuelle Architektur, History-/External-Model-Architektur, + Roadmap, README, Dokumentationsindex und bekannte Einschränkungen anpassen; +- reale Musterdatei per `.gitignore` vom Commit ausschließen; +- alle internen Links auf die neuen Dokumente umstellen. + +Keine Laufzeit-, Schema- oder UI-Änderung. Abnahme: keine aktive Dokumentation +nennt CSV/IfcGUID als künftigen Transport beziehungsweise Schlüssel; der +aktuell noch vorhandene Legacy-Code bleibt als solcher klar benannt. + +## R2 – XLSX-Transportadapter + +Dateien/Module: neues `src/external-model/xlsx`, synthetische Testfixtures und +ein auf XLSX umgestellter Referenzprüfer mit Dateipfadargument. Eine neue +direkte Bibliothek (`exceljs`, vorbehaltlich der Tests), keine DB-Änderung. + +Abnahme: + +- Kopfzeilenkommentare, Blattname, Spaltenbreiten, Formate und Zelltypen + überleben einen strukturellen Roundtrip; +- erste Datenzeile/-spalte und Mappings funktionieren ohne separates + `layout.idColumn`; +- Worksharing-ID/IfcGUID werden exakt und case-sensitiv behandelt; +- Zeile ohne ID und ohne `Familie und Typ` wird übersprungen, die Muster- + Summenzeile B490 blockiert nicht; +- Zeile ohne ID mit `Familie und Typ` erzeugt Hinweis und wird übersprungen; +- maximal 10 MiB, nur `.xlsx`, Zeilen-/Spaltengrenzen nach dem Einlesen; +- keine Formelausführung; +- lokale Referenzprüfung bestätigt 487 Objekte und keine ID-Duplikate; +- aus der realen Musterdatei entsteht lokal eine nicht versionierte + Rückgabedatei mit einigen geänderten Werten. + +Danach stoppt die Arbeit. Der Nutzer testet diese Datei in Linear. Erst sein +erfolgreicher Rückimport gibt R3 frei. Scheitert er, wird vor R3 ein konkreter +OOXML-Patchadapter vorgeschlagen, der das Originalworkbook direkt ändert. + +## R3 – Datenmodell und Backend-Cutover + +- Konfiguration ohne eigene Versionszählung; +- `worksharing_id NOT NULL`, Unique je Quelle; `ifc_guid` nullable ohne Unique; +- additive Migration nach vorherigem DB-Backup; alte externe Entwicklungsdaten + verwerfen und Row-Mengen vorher auf `manualQuantity` zurücksetzen; +- Batch-Aufbewahrung: nur letzter Batch vollständig, ältere nur Metadaten; +- Snapshot 10, Restore und Transfer; alte CSV-Zustände/History klar ablehnen; +- Backend-CSV-Parser, Endpunkte und Verträge entfernen; +- Apply parst erneut; Undo/Redo verwenden ausschließlich gespeicherte + Vorher-/Nachher-Zustände. + +Risiken: Migration mit verknüpften Row-Mengen, alte History-Spitzen und +vollständiges UUID-Remapping. Pflicht: echte SQLite-Commit-/Rollback-Tests. + +## R4 – Revit-Seite und Einstellungen + +- Route `/projects/:projectId/revit` und Navigationseintrag; +- Status-/Aktionsgrundgerüst; +- Einstellungsmodal mit Musterdateierkennung, Layout und Feldzuordnung; +- Stromkreismodus `combined | separate`; +- Projektseiten-Button und `revit-csv-modal.tsx` entfernen; +- nur deutsche UI-Texte und bestehende Icon-/Kartenregeln. + +## R5 – Erstimport + +- Vorschau und Plan mit erneuter Dateiübertragung beim Apply; +- Räume, Verteiler, Gerätearten, exakte Familienregeln und optionale + ProjectDevices; +- fehlender GZF als sichtbarer Startwert `1`, ohne Zusatzbestätigung; +- Warn-/Überspringregel für ID-lose Zeilen; +- ein atomarer Importcommand, keine Row-/Circuit-Erzeugung; +- Undo/Redo aus Commandzuständen ohne Workbook-Parsing. + +## R6 – Objekttabelle und Sammelaktionen + +- kompakte Objektliste einmal laden; +- clientseitig suchen, filtern und sortieren; +- virtualisierte Darstellung ohne Server-Pagination; +- stabile Mehrfachauswahl und Sammelaktionen für Verteiler, ProjectDevice und + Objektplanungswerte; +- Standardverteileränderung wirkt nur auf unzugeordnete Objekte; verknüpfte + Objekte folgen unverändert ihrer Row. + +## R7 – Stromkreislisteneditor + +- gruppierter rechter Revit-Bereich mit Anzahl-Badge; +- Drop auf Row, Circuit oder freien Bereich über vorhandene, angepasste + Commands; +- Row-Indikator, Objektanzeige und Lösen mit Übernahme aktueller Row-Werte; +- Row-/Circuit-/Gruppen-Löschcommands lösen verknüpfte Objekte atomar und + zeigen `X Revit-Objekte werden wieder unzugeordnet`; +- Undo stellt Objektlinks exakt wieder her; +- nur Raum-/Verteilerlöschung mit externen Referenzen bleibt gesperrt. + +## R8 – Rückgabe-Excel + +- alle / abweichende / ausgewählte Objekte; +- zuletzt importiertes Workbook als strukturelle Grundlage; +- Stromkreisfelder des gewählten Modus sind Pflicht; +- fehlende optionale Bezeichnung-/Leistung-/Spannung-/Stromspalten nur als + Hinweis überspringen; +- typisierte Zahlen, gemeinsame Export-/Abweichungsprojektion; +- append-only Exportnachweis ohne Projektrevision. + +R8 baut auf der in R2 durch Linear bestätigten Transportstrategie auf. + +## R9 – Folgeimport + +- exaktes, case-sensitives Matching nach Worksharing-ID; +- neu, geändert, unverändert, fehlend und Rückgabefeldabweichungen; +- Entscheidungen nur für fachliche Quelländerungen; +- akzeptierte Mengenänderungen und Row-Summen atomar; +- fehlende Objekte nicht automatisch lösen oder löschen; +- neuer letzter Vollbatch, vorheriger Batch auf Metadaten reduzieren; +- ein persistenter Undo-Schritt ohne Excel-Parsing bei Undo/Redo. + +## R10 – Härtung + +Ende-zu-Ende-Test: + +```text +Import → Objektplanung → Row-Zuordnung → Rückgabe → Folgeimport + → Snapshot/Restore → Projektduplikat → Undo/Redo nach Neustart +``` + +Zusätzlich: mehrere Tausend synthetische Objekte, virtualisierte UI, +Speicher-/Payload-/Transaktionsmessungen, Löschwarnungen samt Link-Inversen, +alte CSV-Ablehnungen und Dokumentation auf den ausgelieferten Stand. + +## Pflichtprüfungen je Paket R1–R10 + +```text +fokussierte Tests +npm test +npm run build:api +npm run build:web +npm run typecheck:scripts +npx tsc --noEmit -p tsconfig.next.json +``` + +Jedes Paket wird mit einer knappen imperativen Commit-Message abgeschlossen. diff --git a/docs/spec/revit-excel-r0-audit.md b/docs/spec/revit-excel-r0-audit.md index 721e402..84acc5a 100644 --- a/docs/spec/revit-excel-r0-audit.md +++ b/docs/spec/revit-excel-r0-audit.md @@ -2,12 +2,17 @@ Stand: 29.09.2026. Geprüfter Code: `cf022b2`. -**Status: R0 abgeschlossen, Freigabe für R1–R10 ausstehend.** Dieser Bericht +**Status: R0 abgeschlossen und mit Korrekturen für R1 freigegeben.** Dieser Bericht ist ein Umsetzungsvorschlag, kein Nachweis einer bereits implementierten Excel-Anbindung. Der neue Nutzerauftrag ersetzt die CSV-/IfcGUID-Vorgaben und die alte Phasenliste 14.0–14.6. R1 bereinigt die bestehenden Dokumente; R0 ändert weder Laufzeitcode noch Datenbank noch Oberfläche. +Die 13 Freigabekorrekturen vom 29.09.2026 sind in den +[verbindlichen Anforderungen](revit-excel-integration-requirements.md) und im +[R0–R10-Plan](revit-excel-phase-14-plan.md) eingearbeitet. Bei Abweichungen +gelten diese beiden R1-Dokumente. + ## 1. Geprüfter Bestand und Keep/Change/Remove Gelesene Grundlagen: `AGENTS.md`, `docs/current-architecture.md`, @@ -90,7 +95,7 @@ Die Datei ist unversioniert und darf nicht committed werden. | Objektidentitäten | 487 syntaktisch passende Worksharing-IDs, keine Duplikate | | Kopfzeilenkommentare | 14, zu den 14 Spalten nach der ID-Spalte | | Fehlende Raumangaben | 67 Objekte ohne Raumnummer und Raumname | -| IfcGUID-Duplikate | 2 Gruppen nichtleerer doppelter Werte | +| IfcGUID-Duplikate | Keine bei exaktem, case-sensitivem Vergleich | | Formeln | Keine; synthetische Tests dafür erforderlich | | Spaltendefinitionen | 16, obwohl nur 15 Datenspalten vorhanden sind | @@ -100,9 +105,15 @@ gekürzt werden. Das Muster enthält die neuen getrennten Stromkreisfelder und die Bezeichnung noch nicht. Fehlende Rückgabespalten werden angezeigt; sie dürfen nicht ohne Linear-Parameterbindung erfunden werden. +Die frühere Angabe von zwei IfcGUID-Duplikatgruppen war falsch: PowerShells +standardmäßiges Gruppieren verglich ohne Beachtung der Groß-/Kleinschreibung. +Ein erneuter ordinaler, case-sensitiver Vergleich ergab keine Duplikate. Die +Summenzeile hat nur in B490 einen Wert; `Familie und Typ` ist leer. + Nicht nachgewiesen: erfolgreicher Rückimport in Linear, dessen genaue -Auswertung der Kommentar-/VML-Metadaten und der ExcelJS-Roundtrip. R2 prüft -die Struktur, R8/R10 benötigen zusätzlich einen realen Linear-Abnahmelauf. +Auswertung der Kommentar-/VML-Metadaten und der ExcelJS-Roundtrip. R2 endet +deshalb mit einer aus der Musterdatei erzeugten Rückgabedatei und einem +verbindlichen Linear-Test durch den Nutzer vor R3. ## 3. Bibliothek, Adapter und Uploadgrenzen @@ -123,18 +134,12 @@ Blocker wird die Bibliotheksentscheidung neu vorgelegt. Vorgeschlagene Grenzen, zentral konfiguriert und synthetisch getestet: -- ausschließlich `.xlsx`, passender OOXML-Inhalt und ZIP-Signatur; kein - `.xlsm`, verschlüsseltes Archiv, VBA, ActiveX oder externe Workbook-Links; -- maximal 10 MiB Upload, 100 MiB tatsächlich entpackte Daten, 2.000 ZIP- - Einträge, 50.000 Zeilen, 256 Spalten und 2 Millionen materialisierte Zellen; -- genau ein Arbeitsblatt; keine Formelausführung, kein Nachladen von URLs; -- ZIP-Vorprüfung vor ExcelJS: Verzeichniseinträge, doppelte Pfade, - Kompressionsverfahren und tatsächliche entpackte Bytezahl prüfen. - Zentralverzeichnisangaben allein schützen nicht vor manipulierten Archiven. - Begrenzte Dekompression mit Node-Bordmitteln, keine zweite direkte Library; -- Parser in begrenztem Worker mit Zeit-/Speichergrenze; Abbruch ohne DB- - Schreibvorgang. API-Body-Limit auf Uploadgrenze einschließlich Base64- - Overhead abstimmen, statt global beliebige Requestgrößen zuzulassen. +- ausschließlich `.xlsx`, kein `.xls` oder `.xlsm`; +- maximal 10 MiB Upload; +- genau ein Arbeitsblatt und keine Formelausführung; +- feste Zeilen-, Spalten- und Zellgrenzen nach dem Einlesen. + +Es gibt keinen eigenen ZIP-Prüfer und keinen Parser-Worker. Neutrale Matrix: Blattname, Kopfzeilen-/Startpositionen, Spaltenmetadaten (Index, Name, Kommentartext, erkannter Parametertyp/Einheit), geordnete @@ -144,11 +149,14 @@ optionale Transportmetadaten; fachlich zählt nur der gecachte skalare Wert. Fehlender Cache oder Fehlerwert erzeugt einen Hinweis bzw. bei Pflichtfeldern einen Blocker. Originalbytes bleiben unverändert gespeichert. -Fehlende ID bei sonstigen Objektdaten blockiert; Leer-/eindeutige Summenzeilen -werden ignoriert. Nicht passende nichtleere IDs blockieren ebenfalls. -Worksharing-ID bleibt als Quelltext erhalten, Matching ist exakt; ungültige -Leerzeichen/uneindeutige Schreibweisen werden gemeldet statt still korrigiert. -IfcGUID wird optional gespeichert, doppelte Werte sind nur Hinweise. +Eine Zeile ohne Worksharing-ID ist nur verdächtig, wenn `Familie und Typ` +gefüllt ist. Sie erzeugt einen Hinweis und wird übersprungen, ohne zu +blockieren. Andere ID-lose Zeilen, auch die Summenzeile mit Inhalt in B, +werden still übersprungen. Nicht passende nichtleere IDs blockieren. +Worksharing-ID und IfcGUID bleiben als Quelltext erhalten und werden exakt, +ordinal und case-sensitiv verglichen; ungültige äußere Leerzeichen werden +gemeldet statt still korrigiert. IfcGUID wird optional gespeichert, doppelte +Werte sind nur Hinweise. Numerische Projektion rundet Leistung auf 0,01 W, nicht die gespeicherte Quellzelle. Mengen aus `socketCount` müssen positive ganze Zahlen sein. @@ -170,8 +178,7 @@ Neuer neutraler Vertrag `ExternalModelConfiguration`, Schema-Version 1: { schemaVersion: 1, layout: { - headerRow: 1, firstDataRow: 3, firstDataColumn: 1, - idColumn: "Worksharing-ID" + headerRow: 1, firstDataRow: 3, firstDataColumn: 1 }, circuitMode: "combined" | "separate", columns: { @@ -200,8 +207,8 @@ Neuer neutraler Vertrag `ExternalModelConfiguration`, Schema-Version 1: ``` Zeilen/Spalten sind intern 1-basiert; UI stellt Spalten als A, B, … dar. -`layout.idColumn` und `columns.worksharingId` werden gemeinsam gesetzt und -müssen übereinstimmen. Jede gemappte Kopfzeile muss eindeutig auflösbar sein; +Es gibt nur `columns.worksharingId` und kein separates `layout.idColumn`. +Jede gemappte Kopfzeile muss eindeutig auflösbar sein; doppelte Ausgabebelegungen werden abgelehnt. Freie Eingabe bleibt zulässig, aber ein nicht existierender Name erzeugt vor Import/Export einen konkreten Fehler. Erkennung und Vorbelegung nutzen die exakten Standardnamen aus dem @@ -217,8 +224,8 @@ Referenzierte Gerätearten können nicht kommentarlos entfernt werden. Startwerte: je Feld ProjectDevice vor Geräteart vor leer. Anzeigename: Auswahlkenner, sonst Geräteartname, sonst Familie/Typ. Quellleistung bleibt Quelle; eine Übernahme geschieht nur als sichtbare Planungsentscheidung. -Fehlender GZF bleibt vor Zuordnung leer; verlangt der Row-Vertrag einen Wert, -wird `1` sichtbar vorgeschlagen und ausdrücklich bestätigt. Geräteart- +Fehlender GZF wird sichtbar mit `1` vorbelegt, ohne zusätzliche Bestätigung. +Geräteart- Änderungen schreiben keine vorhandenen Objekt-Overrides oder Rows um. ## 5. Konkretes Persistenzschema @@ -228,20 +235,21 @@ Bestehende UUID-/Projekt-FKs und Eigentumsprüfungen werden beibehalten. | Tabelle | Zielspalten / Constraints | | --- | --- | -| `external_model_configurations` (ersetzt CSV-Tabelle) | `id TEXT PK`, `project_id TEXT NOT NULL UNIQUE FK projects`, `configuration_version INTEGER NOT NULL CHECK > 0`, `configuration JSON NOT NULL`. Enthält obiges vollständiges Aggregat. | +| `external_model_configurations` (ersetzt CSV-Tabelle) | `id TEXT PK`, `project_id TEXT NOT NULL UNIQUE FK projects`, `configuration JSON NOT NULL`. Enthält obiges vollständiges Aggregat; keine eigene Versionszählung. | | `external_model_sources` | `id`, `project_id UNIQUE`, `name`, `source_type = revit_xlsx`. Genau eine implizite Quelle je Projekt. | -| `external_import_batches` | Bestehende IDs, Importart, Zeit, Dateiname, SHA-256, `applied_project_revision`, `configuration_version`, `configuration_snapshot JSON`, `original_bytes BLOB`, `document JSON`; Matrix jetzt typisiert und transportneutral. Unveränderlich innerhalb des aktiven Zustands; Undo/Restore darf ganze Batches entfernen/wiederherstellen. | +| `external_import_batches` | Letzter Batch vollständig mit IDs, Importart, Zeit, Dateiname, SHA-256, Objektzahl, `applied_project_revision`, `configuration_snapshot JSON`, `original_bytes BLOB`, `document JSON`; ältere Batches nur als Metadaten Datum, Dateiname, SHA-256 und Objektzahl. | | `external_room_mappings` | Vorhandene Felder einschließlich normalisiertem Quellraumschlüssel, `room_id`, `default_distribution_board_id`; UNIQUE `(source_id, normalized_source_room_key)` bleibt. | | `external_model_objects` | Bestehende interne IDs/Links; neu `worksharing_id TEXT NOT NULL`, UNIQUE `(source_id, worksharing_id)`; `ifc_guid TEXT NULL`, ohne Unique; `device_type_id TEXT NOT NULL` als validierter Verweis in das Konfigurationsaggregat. | | Objektzustand | `accepted_source_values JSON` mit rohen typisierten Werten für Raum, Familie/Typ, Marker, Menge, Bemerkung und alle Rückgabefelder; `planning_values JSON` mit Anzeigename, Kategorie, Anschlussart, effektiver Menge, Einzelleistung W, nullable GZF/cosPhi/Kostengruppe/Bemerkung; `overridden_fields JSON`; bisherige Batch-/Raum-/Board-/ProjectDevice-/Row-Verweise und `presence_status` bleiben. | -| `external_export_batches` (neu) | `id TEXT PK`, `project_id FK`, `project_revision INTEGER`, `import_batch_id TEXT`, `exported_at_iso TEXT`, `file_name TEXT`, `sha256 TEXT`, `configuration_version INTEGER`, `scope TEXT`, `object_count INTEGER`. Append-only Audit-Store. | +| `external_export_batches` (neu) | `id TEXT PK`, `project_id FK`, `project_revision INTEGER`, `import_batch_id TEXT`, `exported_at_iso TEXT`, `file_name TEXT`, `sha256 TEXT`, `configuration_snapshot/hash`, `scope TEXT`, `object_count INTEGER`. Append-only Audit-Store. | `import_batch_id` des Exportnachweises ist absichtlich eine historische UUID ohne löschenden FK: Undo eines Imports oder Snapshot-Restore darf den Nachweis nicht entfernen. Exportnachweise liegen außerhalb rücksetzbarer Fachsnapshots und werden beim Projektduplikat nicht als dort erfolgte Exporte ausgegeben. Sie bleiben beim Originalprojekt erhalten; diese Abgrenzung wird in R1 -dokumentiert. Importbatches selbst gehören vollständig zu Snapshot/Transfer. +dokumentiert. Nur der letzte Importbatch gehört mit Bytes und Matrix zu +Snapshot/Transfer; ältere Batches werden dort nur als Metadaten erhalten. Indices: bisherige Projekt-/Presence-, Board- und Row-Indices behalten; zusätzlich `(project_id, device_type_id)`, `external_room_mapping_id`, @@ -252,9 +260,9 @@ Transaktion; bloße Existenz eines UUID-FK genügt nicht. Effektiver Verteiler: ein gemeinsamer Resolver verwendet bei verknüpften Objekten die Row/Circuit-Verteilung, sonst die Objektabweichung, sonst die Raumvorgabe. `distributionBoardId = null` bedeutet Raumvorgabe verwenden; -bei fehlender Vorgabe ist das Objekt ohne Verteiler. Room-/Board- -Sammeländerungen prüfen alle betroffenen Row-Links und lehnen inkonsistente -Umbuchungen ab, bis diese ausdrücklich gelöst/verschoben sind. +bei fehlender Vorgabe ist das Objekt ohne Verteiler. Eine Änderung des +Raum-Standardverteilers betrifft nur unzugeordnete Objekte; verknüpfte Objekte +folgen immer der Row-Verteilung und blockieren diese Änderung nicht. Planungswerte bleiben von Quellwerten getrennt. Nach Row-Zuordnung sind Objekt-Planungswerte eingefrorene Startwerte; Anzeige, Abweichung und Export @@ -272,7 +280,7 @@ Snapshots der betroffenen Datensätze, keine ungesicherten Teilpatches. | Command | Payload-Skizze und Gegenrichtung | | --- | --- | -| `external-model-configuration.update` v1 | `{ expected, target }` einschließlich Layout, Mapping, Gerätearten und Regeln. Inverse tauscht Fachinhalt; Versionsgeneration siehe unten. | +| `external-model-configuration.update` v1 | `{ expected, target }` einschließlich Layout, Mapping, Gerätearten und Regeln. Inverse tauscht den vollständigen Fachinhalt; keine eigene Konfigurationsversion. | | `external-import.apply-initial` v2 | `{ expectedConfiguration, targetConfiguration, expected, target }`. Quelle, Batch, Mapping, Objekte und neue Regeln zusammen; Inverse stellt leeren externen und vorherigen Konfigurationsinhalt wieder her. Keine Rows. | | `external-import.apply-follow-up` v1 | `{ configuration: transition, batch: transition, roomMappings: transitions, objects: transitions, rows: quantityTransitions, decisions }`; Server erzeugt deterministischen Diff und alle UUIDs. Inverse tauscht alle betroffenen Zustände. | | `external-model-object.update-planning` v1 | `{ objects: transitions }`; nur ungebundene Objekte; geänderte Felder in Overrides. Einzel-/Sammelbearbeitung identischer Regeln. | @@ -290,32 +298,29 @@ Entwürfe und werden erst mit dem Import atomar persistiert. Nach separater Kataloganlage aktualisiert der Wizard die Projektrevision und plant neu, ohne lokale Entscheidungen zu verlieren. -Konfigurationsgeneration: `configurationVersion` erhält bei jedem -Konfigurationswechsel einschließlich Undo/Redo/Restore die neu entstehende -Projektrevision. Sie ist damit strikt steigend, aber nicht lückenlos. -Historienbefehle vergleichen den erwarteten Fachinhalt und die aktuelle -Projektversion; die administrative Generation wird serverseitig neu erzeugt. -Die Inverse restauriert alle Fachwerte exakt, nicht einen alten Zählerstand. -Importbatches behalten ihre ursprüngliche Generation und ihren Snapshot. -Ein Restore/Projekttransfer erhält diese Herkunft; die aktive Konfiguration -wird an die Revision des Zielprojekts gebunden. Prüfen: Änderung → Undo → -anderer Zweig darf niemals denselben Vorschau-Token wieder gültig machen. +Die Konfiguration hat keine eigene Versionszählung. Vorschau und Apply binden +sich an `expectedRevision`; weil auch Undo/Redo neue, strikt steigende +Projektrevisionen erzeugen, wird ein veralteter Plan eindeutig ungültig. +Importbatches speichern eine vollständige Konfigurationskopie. Prüfen: +Änderung → Undo → anderer Zweig darf niemals denselben Plan wieder gültig +machen. XLSX wird vor der synchronen SQLite-Transaktion in einer serverinternen Vorbereitung geparst. Apply überträgt Bytes erneut; Hash, Matrix und Entscheidungen werden erneut validiert. Im Store werden Revision, -Konfigurationsinhalt/-generation, erwartete Objekte, Links und vollständiger +Konfigurationsinhalt, erwartete Objekte, Links und vollständiger vorbereiteter Plan atomar geprüft. Vorbereitete Daten sind keine vom Client behauptete Validierung: Generic-Command-Requests dürfen Importcommands nicht -an dieser serverseitigen Vorbereitung vorbeischleusen. Undo/Redo benutzen -denselben Prüfdienst für persistierte Bytes vor der Transaktion. Keine -asynchronen Callbacks in `better-sqlite3`-Transaktionen. +an dieser serverseitigen Vorbereitung vorbeischleusen. Undo/Redo lesen und +parsen keine Excel-Datei; sie wenden ausschließlich die gespeicherten +Vorher-/Nachher-Zustände an. Keine asynchronen Callbacks in +`better-sqlite3`-Transaktionen. -Allgemeine Row-/Circuit-/Gruppen-/Board-/Raum-/ProjectDevice-Löschungen -erhalten Guards, solange externe Referenzen betroffen sind. Nutzer lösen die -Referenzen zuvor ausdrücklich über die passenden Commands. Guards gelten -auch in Unterbaum- und History-only-Pfaden. Dadurch werden vorhandene -Commands nicht unbemerkt zu unvollständigen externen Löschcommands. +Row-/Circuit-/Gruppen-Löschcommands erfassen verknüpfte Objekte vollständig. +Nach der Warnung `X Revit-Objekte werden wieder unzugeordnet` lösen sie die +Links im selben Command; ihre Inverse stellt sie exakt wieder her. Sperren +bleiben nur für das Löschen referenzierter Verteiler und Räume und gelten auch +in Unterbaum- und History-only-Pfaden. ## 7. Migration, Snapshot 10, History und Transfer @@ -351,7 +356,8 @@ allgemeine Commands können nach dem Reset zusätzlich an ihren exakten Vorbedingungen scheitern; das bleibt eine sichere, sichtbare Ablehnung. Snapshot v10 enthält aktive Excel-Konfiguration, Gerätearten/Regeln, Quelle, -alle Batches mit Originalbytes/Matrix, Raum-Mappings, Objekte und Links. +den letzten Batch mit Originalbytes/Matrix, ältere Batches nur als Metadaten +sowie Raum-Mappings, Objekte und Links. Upgrade v1–9: bestehende nicht-externe Upgrader erhalten. Nur wenn `externalCsvConfiguration` fehlt/null ist **und** der externe Zustand leer ist, verlustfrei auf v10 heben. Auch eine gespeicherte CSV-Konfiguration @@ -389,12 +395,13 @@ separater append-only Audit-Write, ohne Projektrevision oder Undo-Schritt. Bei Auditfehler kein Erfolg/download; ein Eintrag belegt Dateierzeugung, nicht einen tatsächlich abgeschlossenen Browserdownload. -Die Revit-Seite zeigt Status, Aktionen und eine paginierte Objekttabelle -(Vorschlag: 100 Zeilen pro Seite). Filter-/Sortierzustand, UUID-Auswahl und -Sammelaktionen sind unabhängig vom DOM. „Alle gefilterten“ verwendet eine -explizit aufgelöste Auswahl zur bekannten Revision; keine Mutation anhand -eines inzwischen veränderten Filters. Große Auswahlmengen werden nicht in -getrennte Undo-Schritte aufgeteilt. Kein vollständiges Batch-Blob im DTO. +Die Revit-Seite lädt einmal eine kompakte Objektliste. Filterung und Sortierung +laufen im Client; die Tabelle wird virtualisiert und verwendet keine Server- +Pagination. Filter-/Sortierzustand, UUID-Auswahl und Sammelaktionen sind +unabhängig vom DOM. „Alle gefilterten“ wird vor einer Mutation zu einer +expliziten ID-Auswahl an der aktuellen Revision aufgelöst. Große Auswahlmengen +werden nicht in getrennte Undo-Schritte aufgeteilt. Kein vollständiges +Batch-Blob im DTO. Einstellungen verwenden Musterdatei-Erkennung mit editierbaren Positionen, Feld-Dropdowns/freier Eingabe und Kommentar-Typ-/Einheitenanzeige. Regeln @@ -430,10 +437,10 @@ gegen den **zuletzt importierten**, nicht den zuletzt exportierten Stand. Umfang: alle im letzten Batch vorhandenen Objekte / abweichende / explizite Auswahl. Fehlende Objekte haben keine aktuelle Originalzeile und werden nicht künstlich wieder eingefügt. Alle Spalten bleiben, nicht ausgegebene -Parameter behalten importierte Werte. Fehlende benötigte Zielspalten bzw. -Linear-Bindungen blockieren die betreffende Exportkonfiguration mit Hinweis -auf einen neuen vollständigen Linear-Export. Dateiname gemäß Auftrag mit -bereinigtem Projektnamen und Tagesdatum. +Parameter behalten importierte Werte. Fehlende optionale Spalten für +Bezeichnung, Leistung, Spannung und Strom werden mit Hinweis übersprungen. +Nur fehlende Stromkreisspalten des gewählten Modus blockieren. Dateiname gemäß +Auftrag mit bereinigtem Projektnamen und Tagesdatum. Folgeimport matcht ausschließlich Worksharing-ID. Ein neuer Batch speichert immer den vollständigen letzten Quellstand. Unveränderte Objekte werden @@ -457,12 +464,12 @@ nach Freigabe; keine Fortschreibung der alten 14.0–14.6-Liste. | Paket | Arbeit und entscheidende Abnahme | | --- | --- | | R1 | Neue Excel-Anforderungen und R0–R10-Plan; alte Dokumente archivieren/auf Verweise kürzen; AGENTS, Architektur, History-Doku, Phase-14-Abschnitt, LLM-Kontext und alle Links nachziehen. Referenzdatei gezielt ignorieren. | -| R2 | XLSX-Adapter und lokaler Referenzprüfer mit Pfadargument. Synthetischer Roundtrip für Kommentare, Blattname, Spaltenbreiten, Typen, Header-/Startpositionen, unbekannte Spalten, Auswahl und Summenausschluss; ZIP-/Formelgrenzen. Keine DB-Änderung. | +| R2 | XLSX-Adapter und lokaler Referenzprüfer mit Pfadargument. Synthetischer Roundtrip für Kommentare, Blattname, Spaltenbreiten, Typen, Header-/Startpositionen, unbekannte Spalten, Auswahl und Summenausschluss. Aus der lokalen Musterdatei entsteht eine Rückgabedatei mit geänderten Werten. Danach Nutzerabnahme in Linear; R3 bleibt bis zum Erfolg gesperrt. Bei Fehlschlag vor R3 OOXML-Direktänderung als Alternative vorlegen. Keine DB-Änderung. | | R3 | Neue Konfiguration/Identität, additive Migration, Snapshot 10, Transfer und History-Ablehnungen; Backend-CSV entfernen. Parser-Vorbereitung von synchroner Transaktion trennen. | | R4 | Revit-Seite, Navigation, Einstellungen; Projektseitenmodal und dessen CSV-Frontend-Verträge entfernen. | | R5 | Erstimport mit atomaren Regeln, Geräten, Raum-/Board- und Objektentscheidungen; ProjectDevice-Vorbelegung nach Priorität; ein Import-Undo-Schritt. | -| R6 | Objekt-Reads, Paging/Filter, Sammel-Commands und Overrides; verwandte Lösch-/Referenzguards vollständig absichern. | -| R7 | Gruppierung, Drag-and-drop, Row-Indikatoren und Lösen inklusive aktueller Row-Werte; drei Drop-Ziele und Reload/Undo/Redo. | +| R6 | Kompakte Objekt-Reads, clientseitige Filter/Sortierung, Virtualisierung, Sammel-Commands und Overrides. | +| R7 | Gruppierung, Drag-and-drop, Row-Indikatoren und Lösen inklusive aktueller Row-Werte; drei Drop-Ziele, atomare Objektlösung beim Row-/Circuit-/Gruppen-Löschen und Reload/Undo/Redo. | | R8 | Drei Exportumfänge, gemeinsame Abweichungsprojektion, typisierte Rückgabe, append-only Nachweis und Linear-Strukturabnahme. | | R9 | Kontrollierter Folgeimport, fehlende Objekte, explizites Löschen, mengenwirksame Entscheidungen und atomare Inverse. | | R10 | Vollständige synthetische Ende-zu-Ende-Kette einschließlich Neustart, Snapshot/Restore und Duplikat; mehrere Tausend Objekte; Doku auf ausgelieferten Stand. | @@ -492,19 +499,19 @@ Zusätzlich erforderliche neue Prüfungen: - Migration mit externen Row-Anteilen; keine Phantomlast und unveränderte BMKs. - v1–9 ohne CSV verlustfrei, mit CSV klare Ablehnung; alte Command-Inversen und alte Restore-Payloads ebenfalls ohne Teilwrites ablehnen. -- Config-Änderung/Undo/Neuzweig invalidiert alte Pläne; Apply mit anderem +- Config-Änderung/Undo/Neuzweig invalidiert alte Pläne über `expectedRevision`; Apply mit anderem Dateiinhalt, fehlenden Entscheidungen oder fremden UUIDs rollt vollständig zurück. Später Historyfehler rollt auch Regeln, Links und Mengen zurück. - Gebundene Row ändern → Export → Lösen → Undo/Redo behält fachliche Werte. - Mehrfachsteckdosen: unterschiedliche effektive Mengen, identische Einzelwerte, richtige Gruppierung und objektweise Rückgabeleistung. -- Löschen über alle Unterbaum-/History-Pfade kann externe FKs nicht still - nullen. Fremde Verteilungen/Räume/Kategorien und Gerätearten blockieren. +- Row-/Circuit-/Gruppen-Löschen löst externe Links im Command und stellt sie + per Undo wieder her. Raum-/Verteilerlöschen mit Referenzen blockiert. - Export-Audit scheitert: keine fachliche Revision; SHA-256 entspricht exakt den gelieferten Bytes. Snapshot/Restore entfernt keine Exportnachweise. - 5.000/10.000 synthetische Objekte: Parserzeit, Peak-Speicher, Payloadgröße, - Command-/Snapshot-Dauer und UI-Reaktionszeit messen; höchstens eine - paginierte Seite im DOM, stabile Auswahl über Seitenwechsel. + Command-/Snapshot-Dauer und UI-Reaktionszeit messen; nur sichtbare Zeilen im + DOM, stabile Auswahl über virtuelle Bereiche. Wesentliche Restrisiken: Linear-Kommentarbindung ist nur anhand des Exports beobachtet; ExcelJS-Releasepflege und Roundtrip sind in R2 zu @@ -515,7 +522,7 @@ externen Zustand begrenzt und nur nach verifiziertem Backup zulässig. Fehlende Zielparameter im Muster verlangen einen neuen vollständigen Linear-Export, keine geratenen GUID-Kommentare. -**Freigabepunkt:** Der Nutzerauftrag verlangt wörtlich -„R0. Audit (danach stoppen und Freigabe abwarten)“. -Mit Freigabe dieses Vorschlags beginnt R1; R0 selbst autorisiert keine -Installation, Migration oder Implementierung von R1–R10. +**Freigabepunkt:** R0 wurde am 29.09.2026 mit den in R1 dokumentierten +Korrekturen freigegeben. R2 besitzt einen neuen verbindlichen Freigabepunkt: +Vor Beginn von R3 muss der Nutzer die in R2 erzeugte Rückgabedatei erfolgreich +in Linear getestet haben. From 52d3b1a2708d6f350676533b46e555d2a0eaf2b0 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 07:33:06 +0200 Subject: [PATCH 28/38] Add Linear Excel transport --- .gitignore | 1 + docs/spec/revit-excel-phase-14-plan.md | 20 +- package-lock.json | 811 ++++++++++++++++++ package.json | 3 +- scripts/verify-revit-reference-csv.ts | 81 -- scripts/verify-revit-reference-xlsx.ts | 162 ++++ .../xlsx/external-xlsx-contracts.ts | 153 ++++ .../xlsx/external-xlsx-transport.ts | 582 +++++++++++++ tests/external-xlsx-transport.test.ts | 267 ++++++ tests/fixtures/revit-xlsx-fixtures.ts | 134 +++ 10 files changed, 2131 insertions(+), 83 deletions(-) delete mode 100644 scripts/verify-revit-reference-csv.ts create mode 100644 scripts/verify-revit-reference-xlsx.ts create mode 100644 src/external-model/xlsx/external-xlsx-contracts.ts create mode 100644 src/external-model/xlsx/external-xlsx-transport.ts create mode 100644 tests/external-xlsx-transport.test.ts create mode 100644 tests/fixtures/revit-xlsx-fixtures.ts diff --git a/.gitignore b/.gitignore index 911c16f..acbb157 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ data/*.db data/backups/*.db .codex/*.log /docs/spec/kbp-Stromkreis.xlsx +/data/revit-reference/*.xlsx diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index 46b4fba..bb00053 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -10,7 +10,7 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | --- | --- | --- | | R0 | abgeschlossen und freigegeben | Bestandsaudit, Zielmodell, Migration und Risiken; Freigabekorrekturen in R1 eingearbeitet. | | R1 | abgeschlossen | Anforderungen, Plan und Architektur auf Excel/Worksharing-ID umgestellt; alle Pflichtprüfungen bestanden. | -| R2 | offen | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei. Danach zwingende Linear-Abnahme durch den Nutzer. | +| R2 | implementiert, Linear-Abnahme ausstehend | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei sind erstellt. R3 bleibt bis zum erfolgreichen Linear-Test gesperrt. | | R3 | gesperrt bis R2-Abnahme | Konfiguration, Identität, Migration, Snapshot 10, Transfer und Backend-CSV-Entfernung. | | R4 | offen | Revit-Seite, Navigation, Einstellungen, altes Projektseitenmodal entfernen. | | R5 | offen | Erstimportwizard mit Gerätearten, Familienregeln und optionalen ProjectDevices. | @@ -69,6 +69,24 @@ Danach stoppt die Arbeit. Der Nutzer testet diese Datei in Linear. Erst sein erfolgreicher Rückimport gibt R3 frei. Scheitert er, wird vor R3 ein konkreter OOXML-Patchadapter vorgeschlagen, der das Originalworkbook direkt ändert. +Implementierungsstand vom 30.09.2026: Der Adapter liegt unter +`src/external-model/xlsx`, der Referenzprüfer unter +`scripts/verify-revit-reference-xlsx.ts`. Er hat aus der lokalen Musterdatei +die ignorierte Datei +`data/revit-reference/kbp-Stromkreis-R2-Rueckgabe.xlsx` erzeugt. Die Datei +enthält 487 Objektzeilen in Originalreihenfolge, keine Summenzeile und gezielte +Änderungen an den ersten drei Objekten. Synthetische Tests decken Zelltypen, +Zahlenformate, Formelergebnisse, Kommentare, Breiten, Auswahl, exakte +ID-Vergleiche und Grenzen ab. + +Für den Adapter ist `exceljs@4.4.0` als direkte Abhängigkeit aufgenommen. Der +Produktionsaudit meldet dafür ausschließlich `uuid@8.3.2`: Die gemeldete +Schwachstelle betrifft die UUID-Funktionen v3/v5 mit übergebenem Puffer; +ExcelJS verwendet die Abhängigkeit nur für UUID v4 bei erweiterten bedingten +Formatierungen. Dieser Adapter ruft keine UUID-Funktion auf. Weitere gemeldete +Auditbefunde gehören zu bereits vorhandenen Abhängigkeiten und werden nicht im +fachlich begrenzten R2-Paket aktualisiert. + ## R3 – Datenmodell und Backend-Cutover - Konfiguration ohne eigene Versionszählung; diff --git a/package-lock.json b/package-lock.json index 417421b..9d27840 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "better-sqlite3": "^12.9.0", "bootstrap": "^5.3.8", "drizzle-orm": "^0.45.2", + "exceljs": "^4.4.0", "express": "^5.2.1", "lucide-react": "^1.14.0", "next": "^16.2.4", @@ -875,6 +876,47 @@ "node": ">=18" } }, + "node_modules/@fast-csv/format": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz", + "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.isboolean": "^3.0.3", + "lodash.isequal": "^4.5.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0" + } + }, + "node_modules/@fast-csv/format/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, + "node_modules/@fast-csv/parse": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz", + "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.groupby": "^4.6.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0", + "lodash.isundefined": "^3.0.1", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/@fast-csv/parse/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -1587,6 +1629,87 @@ "node": ">= 0.6" } }, + "node_modules/archiver": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz", + "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^2.1.0", + "async": "^3.2.4", + "buffer-crc32": "^0.2.1", + "readable-stream": "^3.6.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^2.2.0", + "zip-stream": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/archiver-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz", + "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==", + "license": "MIT", + "dependencies": { + "glob": "^7.1.4", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^2.0.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/archiver-utils/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/archiver-utils/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -1630,6 +1753,28 @@ "node": "20.x || 22.x || 23.x || 24.x || 25.x" } }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/binary": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", + "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==", + "license": "MIT", + "dependencies": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + }, + "engines": { + "node": "*" + } + }, "node_modules/bindings": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", @@ -1648,6 +1793,12 @@ "readable-stream": "^3.4.0" } }, + "node_modules/bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", + "license": "MIT" + }, "node_modules/body-parser": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", @@ -1689,6 +1840,16 @@ "@popperjs/core": "^2.11.8" } }, + "node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -1712,12 +1873,38 @@ "ieee754": "^1.1.13" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/buffer-indexof-polyfill": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", + "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/buffers": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", + "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==", + "engines": { + "node": ">=0.2.0" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1772,6 +1959,18 @@ } ] }, + "node_modules/chainsaw": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", + "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==", + "license": "MIT/X11", + "dependencies": { + "traverse": ">=0.3.0 <0.4" + }, + "engines": { + "node": "*" + } + }, "node_modules/chownr": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", @@ -1782,6 +1981,27 @@ "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==" }, + "node_modules/compress-commons": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz", + "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "^0.2.13", + "crc32-stream": "^4.0.2", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, "node_modules/content-disposition": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", @@ -1818,12 +2038,49 @@ "node": ">=6.6.0" } }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/crc32-stream": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz", + "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==", + "license": "MIT", + "dependencies": { + "crc-32": "^1.2.0", + "readable-stream": "^3.4.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "dev": true }, + "node_modules/dayjs": { + "version": "1.11.23", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", + "license": "MIT" + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2030,6 +2287,45 @@ "node": ">= 0.4" } }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/duplexer2/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexer2/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/duplexer2/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -2132,6 +2428,26 @@ "node": ">= 0.6" } }, + "node_modules/exceljs": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", + "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==", + "license": "MIT", + "dependencies": { + "archiver": "^5.0.0", + "dayjs": "^1.8.34", + "fast-csv": "^4.3.1", + "jszip": "^3.10.1", + "readable-stream": "^3.6.0", + "saxes": "^5.0.1", + "tmp": "^0.2.0", + "unzipper": "^0.10.11", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=8.3.0" + } + }, "node_modules/expand-template": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", @@ -2182,6 +2498,19 @@ "url": "https://opencollective.com/express" } }, + "node_modules/fast-csv": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz", + "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==", + "license": "MIT", + "dependencies": { + "@fast-csv/format": "4.3.5", + "@fast-csv/parse": "4.3.6" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/file-uri-to-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", @@ -2228,6 +2557,12 @@ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2242,6 +2577,22 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "engines": { + "node": ">=0.6" + } + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -2302,6 +2653,27 @@ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==" }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2313,6 +2685,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -2388,6 +2766,23 @@ } ] }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -2411,6 +2806,190 @@ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==" }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jszip": { + "version": "3.10.2", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz", + "integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/jszip/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/jszip/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/jszip/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/lazystream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", + "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.0.5" + }, + "engines": { + "node": ">= 0.6.3" + } + }, + "node_modules/lazystream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/lazystream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/lazystream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==", + "license": "ISC" + }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, + "node_modules/lodash.difference": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", + "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==", + "license": "MIT" + }, + "node_modules/lodash.escaperegexp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", + "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==", + "license": "MIT" + }, + "node_modules/lodash.flatten": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", + "license": "MIT" + }, + "node_modules/lodash.groupby": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", + "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, + "node_modules/lodash.isfunction": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz", + "integrity": "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==", + "license": "MIT" + }, + "node_modules/lodash.isnil": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz", + "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isundefined": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz", + "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==", + "license": "MIT" + }, + "node_modules/lodash.union": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", + "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==", + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "license": "MIT" + }, "node_modules/lucide-react": { "version": "1.14.0", "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.14.0.tgz", @@ -2480,6 +3059,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/minimist": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", @@ -2488,6 +3079,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, "node_modules/mkdirp-classic": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", @@ -2591,6 +3194,15 @@ "node": ">=10" } }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -2621,6 +3233,12 @@ "wrappy": "1" } }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -2629,6 +3247,15 @@ "node": ">= 0.8" } }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/path-to-regexp": { "version": "8.4.2", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", @@ -2696,6 +3323,12 @@ "node": ">=10" } }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -2799,6 +3432,36 @@ "node": ">= 6" } }, + "node_modules/readdir-glob": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", + "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.1.0" + } + }, + "node_modules/readdir-glob/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/readdir-glob/node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -2808,6 +3471,19 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", @@ -2847,6 +3523,18 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "node_modules/saxes": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/scheduler": { "version": "0.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", @@ -2906,6 +3594,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -3165,6 +3859,15 @@ "node": ">=6" } }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -3173,6 +3876,15 @@ "node": ">=0.6" } }, + "node_modules/traverse": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", + "integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==", + "license": "MIT/X11", + "engines": { + "node": "*" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -3706,11 +4418,69 @@ "node": ">= 0.8" } }, + "node_modules/unzipper": { + "version": "0.10.14", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz", + "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==", + "license": "MIT", + "dependencies": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "graceful-fs": "^4.2.2", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, + "node_modules/unzipper/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/unzipper/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -3724,6 +4494,47 @@ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + }, + "node_modules/zip-stream": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", + "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^3.0.4", + "compress-commons": "^4.1.2", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz", + "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==", + "license": "MIT", + "dependencies": { + "glob": "^7.2.3", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/zod": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.1.tgz", diff --git a/package.json b/package.json index 414eb53..1c035ba 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "db:migrate": "drizzle-kit migrate", "db:backup": "tsx scripts/db-backup.ts", "db:verify:circuit-schema": "node scripts/db-verify-circuit-schema.js", - "revit:verify-reference": "tsx scripts/verify-revit-reference-csv.ts" + "revit:verify-reference": "tsx scripts/verify-revit-reference-xlsx.ts" }, "keywords": [], "author": "", @@ -36,6 +36,7 @@ "better-sqlite3": "^12.9.0", "bootstrap": "^5.3.8", "drizzle-orm": "^0.45.2", + "exceljs": "^4.4.0", "express": "^5.2.1", "lucide-react": "^1.14.0", "next": "^16.2.4", diff --git a/scripts/verify-revit-reference-csv.ts b/scripts/verify-revit-reference-csv.ts deleted file mode 100644 index 07d605b..0000000 --- a/scripts/verify-revit-reference-csv.ts +++ /dev/null @@ -1,81 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { createHash } from "node:crypto"; -import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; -import { - parseExternalCsv, - serializeExternalCsv, -} from "../src/external-model/csv/external-csv-transport.js"; -import { createExternalCsvPreview } from "../src/external-model/application/external-csv-preview.js"; - -const filePath = resolve( - process.argv[2] ?? "docs/spec/ELT Stromkreisnummernvergabe-Check_DIV.csv" -); -const source = readFileSync(filePath); -const configuration = createDefaultExternalCsvConfiguration({ - ifcGuid: "IfcGUID", - roomNumber: "MEP-Raum: Nummer", - roomName: "MEP-Raum: Name", - familyAndType: "Familie und Typ", - selectionMarker: "CAx_Auswahlkenner", - circuitIdentifier: "kbp_Stromkreisnummer", - power: "kbp-E-Elektrische Leistung", - quantity: null, -}); -configuration.additionalSourceMappings = [ - { sourceColumn: "CAx_Anmerkung", targetField: "sourceRemark" }, - { sourceColumn: "kbp-E-Spannung", targetField: "sourceVoltage" }, - { sourceColumn: "kbp-E-Stromstärke", targetField: "sourceCurrent" }, - { sourceColumn: "kbp-E-Versorgung von ELT", targetField: "sourceElectricalSupply" }, - { sourceColumn: "kbp-E-Versorgung von MSR/GLT", targetField: "sourceControlSupply" }, -]; - -const document = parseExternalCsv(source, configuration); -const counts = Object.fromEntries( - ["metadata", "header", "passthrough", "object", "suspect-object"].map( - (classification) => [ - classification, - document.rows.filter((row) => row.classification === classification).length, - ] - ) -); -const nonEmptyPassthroughRows = document.rows.filter( - (row) => - row.classification === "passthrough" && - row.cells.some((cell) => cell.value !== "") -).length; -const serialized = serializeExternalCsv(document); -const preview = createExternalCsvPreview({ - fileName: filePath, - bytes: source, - configuration, -}); - -assert.equal(counts.object, 897, "Expected 897 object rows."); -assert.equal(preview.objectCount, 897, "Expected 897 preview objects."); -assert.equal(nonEmptyPassthroughRows, 211, "Expected 211 non-empty passthrough rows."); -assert.equal(counts["suspect-object"], 0, "Expected no suspect object rows."); -assert.equal( - Buffer.compare(Buffer.from(serialized), source), - 0, - "Expected a byte-identical CSV round-trip." -); - -const sha256 = createHash("sha256").update(source).digest("hex"); -process.stdout.write( - `${JSON.stringify( - { - file: filePath, - bytes: source.length, - sha256, - dialect: document.dialect, - rows: counts, - nonEmptyPassthroughRows, - roundTripByteIdentical: true, - previewObjectCount: preview.objectCount, - }, - null, - 2 - )}\n` -); diff --git a/scripts/verify-revit-reference-xlsx.ts b/scripts/verify-revit-reference-xlsx.ts new file mode 100644 index 0000000..ed568d4 --- /dev/null +++ b/scripts/verify-revit-reference-xlsx.ts @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import ExcelJS from "exceljs"; +import { + createDefaultExternalXlsxTransportConfiguration, + type ExternalXlsxScalar, +} from "../src/external-model/xlsx/external-xlsx-contracts.js"; +import { + createExternalXlsxReturn, + parseExternalXlsx, +} from "../src/external-model/xlsx/external-xlsx-transport.js"; + +async function main() { +const inputPath = resolve( + process.argv[2] ?? "docs/spec/kbp-Stromkreis.xlsx" +); +const outputPath = resolve( + process.argv[3] ?? "data/revit-reference/kbp-Stromkreis-R2-Rueckgabe.xlsx" +); +assert.notEqual( + inputPath, + outputPath, + "Eingabe- und Ausgabedatei müssen verschieden sein." +); + +const source = readFileSync(inputPath); +const configuration = createDefaultExternalXlsxTransportConfiguration(); +const document = await parseExternalXlsx({ + fileName: inputPath, + bytes: source, + configuration, +}); +const objectRows = document.rows.filter((row) => row.classification === "object"); +const suspectRows = document.rows.filter( + (row) => row.classification === "suspect-object" +); +const worksharingIdColumn = document.columns.find( + (column) => column.header === configuration.columns.worksharingId +)?.columnNumber; +assert.ok(worksharingIdColumn, "Worksharing-ID-Spalte wurde nicht aufgelöst."); + +assert.equal(objectRows.length, 487, "Es werden 487 Objektzeilen erwartet."); +assert.equal(suspectRows.length, 0, "Es werden keine verdächtigen Zeilen erwartet."); +assert.equal( + document.columns.filter((column) => column.comment !== null).length, + 14, + "Es werden 14 Kopfzeilenkommentare erwartet." +); +assert.equal( + document.issues.filter((issue) => issue.code === "duplicate-ifc-guid").length, + 0, + "Die Musterdatei darf keine exakten IfcGUID-Duplikate enthalten." +); + +const testValues = [ + { + circuitCombined: "UV_R2_TEST-2F1", + electricalPowerW: 111, + voltageV: 230, + currentA: 0.48, + }, + { + circuitCombined: "UV_R2_TEST-2F2", + electricalPowerW: 222, + voltageV: 230, + currentA: 0.97, + }, + { + circuitCombined: "UV_R2_TEST-3F1", + electricalPowerW: 333, + voltageV: 400, + currentA: 0.48, + }, +] satisfies Record[]; + +const updates = testValues.map((values, index) => { + const value = objectRows[index]?.cells[worksharingIdColumn - 1]?.value; + if (typeof value !== "string") { + throw new Error("Worksharing-ID muss Text sein."); + } + return { worksharingId: value, values }; +}); +const result = await createExternalXlsxReturn({ + fileName: inputPath, + bytes: source, + configuration, + updates, +}); +assert.equal(result.exportedObjectCount, 487); +mkdirSync(dirname(outputPath), { recursive: true }); +writeFileSync(outputPath, result.bytes); + +const outputDocument = await parseExternalXlsx({ + fileName: outputPath, + bytes: result.bytes, + configuration, +}); +assert.equal( + outputDocument.rows.filter((row) => row.classification === "object").length, + 487 +); +assert.equal( + outputDocument.rows.some((row) => row.classification !== "object"), + false, + "Die Rückgabedatei darf keine Summen- oder Hinweiszeilen enthalten." +); +assert.equal(outputDocument.sheetName, document.sheetName); +assert.deepEqual( + outputDocument.columns, + document.columns, + "Kopfzeilen, Kommentare und Spaltenbreiten müssen erhalten bleiben." +); +assert.deepEqual( + outputDocument.rows.slice(updates.length).map((row) => row.cells), + objectRows.slice(updates.length).map((row) => row.cells), + "Nicht geänderte Objektzellen müssen Wert, Typ und Zahlenformat behalten." +); +const outputWorkbook = new ExcelJS.Workbook(); +await outputWorkbook.xlsx.load(result.bytes as never); +const commentedCells: string[] = []; +outputWorkbook.worksheets[0].eachRow({ includeEmpty: true }, (row) => { + row.eachCell({ includeEmpty: true }, (cell) => { + if (cell.note !== undefined) commentedCells.push(cell.address); + }); +}); +assert.equal( + commentedCells.length, + 14, + "Nur die 14 Kopfzellen dürfen Kommentare enthalten." +); +assert.equal( + commentedCells.every((address) => address.endsWith("1")), + true, + "Datenzellen dürfen keine Kommentare enthalten." +); + +process.stdout.write( + `${JSON.stringify( + { + input: inputPath, + output: outputPath, + inputBytes: source.length, + outputBytes: result.bytes.length, + inputSha256: createHash("sha256").update(source).digest("hex"), + outputSha256: createHash("sha256").update(result.bytes).digest("hex"), + sheetName: document.sheetName, + objectCount: objectRows.length, + headerCommentCount: document.columns.filter( + (column) => column.comment !== null + ).length, + exactDuplicateIfcGuidCount: 0, + changedObjectCount: updates.length, + }, + null, + 2 + )}\n` +); +} + +void main(); diff --git a/src/external-model/xlsx/external-xlsx-contracts.ts b/src/external-model/xlsx/external-xlsx-contracts.ts new file mode 100644 index 0000000..94c7b45 --- /dev/null +++ b/src/external-model/xlsx/external-xlsx-contracts.ts @@ -0,0 +1,153 @@ +export const MAX_EXTERNAL_XLSX_BYTES = 10 * 1024 * 1024; + +export const DEFAULT_EXTERNAL_XLSX_LIMITS = { + maxRows: 50_000, + maxColumns: 256, + maxCells: 2_000_000, +} as const; + +export type ExternalXlsxScalar = string | number | boolean | null; + +export interface ExternalXlsxCell { + columnNumber: number; + value: ExternalXlsxScalar; + valueType: "empty" | "string" | "number" | "boolean"; + numberFormat: string | null; + formula: string | null; + usedCachedFormulaValue: boolean; +} + +export type ExternalXlsxRowClassification = + | "object" + | "suspect-object" + | "passthrough"; + +export interface ExternalXlsxRow { + rowNumber: number; + classification: ExternalXlsxRowClassification; + cells: ExternalXlsxCell[]; +} + +export interface ExternalXlsxColumn { + columnNumber: number; + header: string; + comment: string | null; + width: number | null; +} + +export type ExternalXlsxIssueCode = + | "cached-formula-value-used" + | "formula-without-cached-value" + | "suspect-object-skipped" + | "duplicate-ifc-guid" + | "optional-return-column-missing"; + +export interface ExternalXlsxIssue { + code: ExternalXlsxIssueCode; + message: string; + rowNumber?: number; + columnNumber?: number; + field?: ExternalXlsxColumnKey; +} + +export interface ExternalXlsxDocument { + sheetName: string; + headerRowNumber: number; + firstDataRowNumber: number; + firstDataColumnNumber: number; + columns: ExternalXlsxColumn[]; + rows: ExternalXlsxRow[]; + issues: ExternalXlsxIssue[]; +} + +export interface ExternalXlsxLayoutConfiguration { + headerRow: number; + firstDataRow: number; + firstDataColumn: number; +} + +export type ExternalXlsxCircuitMode = "combined" | "separate"; + +export interface ExternalXlsxColumnConfiguration { + worksharingId: string; + ifcGuid: string | null; + roomNumber: string | null; + roomName: string | null; + familyAndType: string; + selectionMarker: string | null; + socketCount: string | null; + sourceRemark: string | null; + circuitCombined: string | null; + boardName: string | null; + circuitIdentifier: string | null; + designation: string | null; + electricalPowerW: string | null; + voltageV: string | null; + currentA: string | null; +} + +export type ExternalXlsxColumnKey = keyof ExternalXlsxColumnConfiguration; + +export interface ExternalXlsxTransportConfiguration { + layout: ExternalXlsxLayoutConfiguration; + circuitMode: ExternalXlsxCircuitMode; + columns: ExternalXlsxColumnConfiguration; +} + +export interface ExternalXlsxLimits { + maxRows: number; + maxColumns: number; + maxCells: number; +} + +export type ExternalXlsxReturnValues = Partial< + Record< + | "circuitCombined" + | "boardName" + | "circuitIdentifier" + | "designation" + | "electricalPowerW" + | "voltageV" + | "currentA", + ExternalXlsxScalar + > +>; + +export interface ExternalXlsxReturnUpdate { + worksharingId: string; + values: ExternalXlsxReturnValues; +} + +export interface ExternalXlsxReturnResult { + bytes: Uint8Array; + exportedObjectCount: number; + issues: ExternalXlsxIssue[]; +} + +export function createDefaultExternalXlsxTransportConfiguration(): ExternalXlsxTransportConfiguration { + return { + layout: { + headerRow: 1, + firstDataRow: 3, + firstDataColumn: 1, + }, + circuitMode: "combined", + columns: { + worksharingId: "Worksharing-ID", + ifcGuid: "IfcGUID", + roomNumber: "MEP-Raum: Nummer", + roomName: "MEP-Raum: Name", + familyAndType: "Familie und Typ", + selectionMarker: "CAx_Auswahlkenner", + socketCount: "CAX_AnzahlObjekte", + sourceRemark: "CAx_Anmerkung", + circuitCombined: "kbp_Stromkreisnummer", + boardName: "kbp-E-Verteiler", + circuitIdentifier: "kbp-E-Stromkreis", + designation: "kbp-E-Bezeichnung", + electricalPowerW: "kbp-E-Elektrische Leistung", + voltageV: "kbp-E-Spannung", + currentA: "kbp-E-Stromstärke", + }, + }; +} diff --git a/src/external-model/xlsx/external-xlsx-transport.ts b/src/external-model/xlsx/external-xlsx-transport.ts new file mode 100644 index 0000000..31cc707 --- /dev/null +++ b/src/external-model/xlsx/external-xlsx-transport.ts @@ -0,0 +1,582 @@ +import ExcelJS from "exceljs"; +import type { CellValue, Worksheet } from "exceljs"; +import { + DEFAULT_EXTERNAL_XLSX_LIMITS, + MAX_EXTERNAL_XLSX_BYTES, + type ExternalXlsxCell, + type ExternalXlsxColumnKey, + type ExternalXlsxDocument, + type ExternalXlsxIssue, + type ExternalXlsxLimits, + type ExternalXlsxReturnResult, + type ExternalXlsxReturnUpdate, + type ExternalXlsxScalar, + type ExternalXlsxTransportConfiguration, +} from "./external-xlsx-contracts.js"; + +export type ExternalXlsxErrorCode = + | "invalid-file-extension" + | "file-too-large" + | "invalid-workbook" + | "worksheet-count" + | "worksheet-too-large" + | "invalid-layout" + | "header-not-found" + | "ambiguous-header" + | "required-formula-result-missing" + | "invalid-worksharing-id" + | "duplicate-worksharing-id" + | "return-circuit-column-missing" + | "unknown-worksharing-id"; + +export class ExternalXlsxError extends Error { + constructor( + public readonly code: ExternalXlsxErrorCode, + message: string + ) { + super(message); + this.name = "ExternalXlsxError"; + } +} + +export interface ParseExternalXlsxInput { + fileName: string; + bytes: Uint8Array; + configuration: ExternalXlsxTransportConfiguration; + limits?: ExternalXlsxLimits; +} + +export interface CreateExternalXlsxReturnInput extends ParseExternalXlsxInput { + selectedWorksharingIds?: readonly string[]; + updates?: readonly ExternalXlsxReturnUpdate[]; +} + +export async function parseExternalXlsx( + input: ParseExternalXlsxInput +): Promise { + assertUpload(input.fileName, input.bytes); + assertConfiguration(input.configuration); + const workbook = await loadWorkbook(input.bytes); + const worksheet = getOnlyWorksheet(workbook); + assertWorksheetLimits( + worksheet, + input.limits ?? DEFAULT_EXTERNAL_XLSX_LIMITS + ); + return parseWorksheet(worksheet, input.configuration); +} + +export async function createExternalXlsxReturn( + input: CreateExternalXlsxReturnInput +): Promise { + assertUpload(input.fileName, input.bytes); + assertConfiguration(input.configuration); + const workbook = await loadWorkbook(input.bytes); + const worksheet = getOnlyWorksheet(workbook); + assertWorksheetLimits( + worksheet, + input.limits ?? DEFAULT_EXTERNAL_XLSX_LIMITS + ); + const document = parseWorksheet(worksheet, input.configuration); + const headerLookup = createHeaderLookup(worksheet, input.configuration); + const issues = [...document.issues]; + const returnColumns = resolveReturnColumns( + headerLookup, + input.configuration, + issues + ); + const worksharingIdColumn = headerLookup.get( + input.configuration.columns.worksharingId + )!; + const objectRows = document.rows.filter((row) => row.classification === "object"); + const objectRowById = new Map( + objectRows.map((row) => [ + scalarToIdentity(row.cells[worksharingIdColumn - 1]?.value ?? null), + row.rowNumber, + ]) + ); + const selectedIds = input.selectedWorksharingIds + ? new Set(input.selectedWorksharingIds) + : new Set(objectRowById.keys()); + for (const worksharingId of selectedIds) { + if (!objectRowById.has(worksharingId)) { + throw new ExternalXlsxError( + "unknown-worksharing-id", + `Die Worksharing-ID ist im Workbook nicht vorhanden: ${worksharingId}` + ); + } + } + const updates = new Map( + (input.updates ?? []).map((update) => [update.worksharingId, update.values]) + ); + for (const worksharingId of updates.keys()) { + if (!objectRowById.has(worksharingId)) { + throw new ExternalXlsxError( + "unknown-worksharing-id", + `Die Worksharing-ID ist im Workbook nicht vorhanden: ${worksharingId}` + ); + } + } + + const selectedRows = objectRows.filter((row) => { + const id = scalarToIdentity(row.cells[worksharingIdColumn - 1]?.value ?? null); + return selectedIds.has(id); + }); + const lastColumn = worksheet.columnCount; + const snapshots = selectedRows.map((row) => + captureRow(worksheet, row.rowNumber, lastColumn) + ); + snapshots.forEach((snapshot, index) => { + restoreRow( + worksheet, + input.configuration.layout.firstDataRow + index, + snapshot, + lastColumn + ); + const destinationRow = worksheet.getRow( + input.configuration.layout.firstDataRow + index + ); + const id = scalarToIdentity(destinationRow.getCell(worksharingIdColumn).value); + const values = updates.get(id); + if (!values) return; + for (const [field, value] of Object.entries(values) as [ + keyof typeof values, + ExternalXlsxScalar, + ][]) { + const columnNumber = returnColumns.get(field); + if (columnNumber !== undefined) { + destinationRow.getCell(columnNumber).value = value; + } + } + }); + + const firstRemovedRow = + input.configuration.layout.firstDataRow + snapshots.length; + const removeCount = Math.max(0, worksheet.rowCount - firstRemovedRow + 1); + // ExcelJS 4.4 does not shrink its internal row array when a multi-row + // splice removes the complete tail. Removing the tail one row at a time + // produces an actual OOXML deletion instead of serialized empty rows. + for (let index = 0; index < removeCount; index += 1) { + worksheet.spliceRows(worksheet.rowCount, 1); + } + const buffer = await workbook.xlsx.writeBuffer(); + return { + bytes: new Uint8Array(buffer), + exportedObjectCount: snapshots.length, + issues, + }; +} + +function parseWorksheet( + worksheet: Worksheet, + configuration: ExternalXlsxTransportConfiguration +): ExternalXlsxDocument { + const headerLookup = createHeaderLookup(worksheet, configuration); + const issues: ExternalXlsxIssue[] = []; + const worksharingIdColumn = headerLookup.get(configuration.columns.worksharingId)!; + const familyAndTypeColumn = headerLookup.get(configuration.columns.familyAndType)!; + const ifcGuidColumn = configuration.columns.ifcGuid + ? headerLookup.get(configuration.columns.ifcGuid) + : undefined; + const seenWorksharingIds = new Set(); + const seenIfcGuids = new Set(); + const rows = [] as ExternalXlsxDocument["rows"]; + + for ( + let rowNumber = configuration.layout.firstDataRow; + rowNumber <= worksheet.rowCount; + rowNumber += 1 + ) { + const row = worksheet.getRow(rowNumber); + const cells: ExternalXlsxCell[] = []; + for (let columnNumber = 1; columnNumber <= worksheet.columnCount; columnNumber += 1) { + cells.push( + toExternalCell(row.getCell(columnNumber), rowNumber, columnNumber, issues) + ); + } + const worksharingIdCell = cells[worksharingIdColumn - 1]; + const familyAndTypeCell = cells[familyAndTypeColumn - 1]; + for (const [field, requiredCell] of [ + ["Worksharing-ID", worksharingIdCell], + ["Familie und Typ", familyAndTypeCell], + ] as const) { + if (requiredCell?.formula != null && !requiredCell.usedCachedFormulaValue) { + throw new ExternalXlsxError( + "required-formula-result-missing", + `Das Pflichtfeld ${field} hat in Zeile ${rowNumber} kein gespeichertes Formelergebnis.` + ); + } + } + const worksharingId = scalarToIdentity(worksharingIdCell?.value ?? null); + const familyAndType = scalarToIdentity(familyAndTypeCell?.value ?? null); + if (!worksharingId) { + const classification = familyAndType ? "suspect-object" : "passthrough"; + if (classification === "suspect-object") { + issues.push({ + code: "suspect-object-skipped", + message: `Zeile ${rowNumber} enthält Familie und Typ, aber keine Worksharing-ID, und wird übersprungen.`, + rowNumber, + }); + } + rows.push({ rowNumber, classification, cells }); + continue; + } + if (!isWorksharingId(worksharingId)) { + throw new ExternalXlsxError( + "invalid-worksharing-id", + `Zeile ${rowNumber} enthält eine ungültige Worksharing-ID.` + ); + } + if (seenWorksharingIds.has(worksharingId)) { + throw new ExternalXlsxError( + "duplicate-worksharing-id", + `Die Worksharing-ID kommt mehrfach vor: ${worksharingId}` + ); + } + seenWorksharingIds.add(worksharingId); + if (ifcGuidColumn !== undefined) { + const ifcGuid = scalarToIdentity(cells[ifcGuidColumn - 1]?.value ?? null); + if (ifcGuid) { + if (seenIfcGuids.has(ifcGuid)) { + issues.push({ + code: "duplicate-ifc-guid", + message: `IfcGUID kommt mehrfach vor: ${ifcGuid}`, + rowNumber, + columnNumber: ifcGuidColumn, + field: "ifcGuid", + }); + } + seenIfcGuids.add(ifcGuid); + } + } + rows.push({ rowNumber, classification: "object", cells }); + } + + const headerRow = worksheet.getRow(configuration.layout.headerRow); + const columns = [] as ExternalXlsxDocument["columns"]; + for (let columnNumber = 1; columnNumber <= worksheet.columnCount; columnNumber += 1) { + const cell = headerRow.getCell(columnNumber); + columns.push({ + columnNumber, + header: scalarToIdentity(toScalar(cell.value).value), + comment: getCommentText(cell.note), + width: worksheet.getColumn(columnNumber).width ?? null, + }); + } + return { + sheetName: worksheet.name, + headerRowNumber: configuration.layout.headerRow, + firstDataRowNumber: configuration.layout.firstDataRow, + firstDataColumnNumber: configuration.layout.firstDataColumn, + columns, + rows, + issues, + }; +} + +function createHeaderLookup( + worksheet: Worksheet, + configuration: ExternalXlsxTransportConfiguration +) { + const headers = new Map(); + const row = worksheet.getRow(configuration.layout.headerRow); + for ( + let columnNumber = configuration.layout.firstDataColumn; + columnNumber <= worksheet.columnCount; + columnNumber += 1 + ) { + const header = scalarToIdentity(toScalar(row.getCell(columnNumber).value).value); + if (!header) continue; + headers.set(header, [...(headers.get(header) ?? []), columnNumber]); + } + const configured = Object.entries(configuration.columns) as [ + ExternalXlsxColumnKey, + string | null, + ][]; + const required = new Set(["worksharingId", "familyAndType"]); + const lookup = new Map(); + for (const [field, header] of configured) { + if (header === null) continue; + const matches = headers.get(header) ?? []; + if (matches.length > 1) { + throw new ExternalXlsxError( + "ambiguous-header", + `Die konfigurierte Kopfzelle ist nicht eindeutig: ${header}` + ); + } + if (matches.length === 0 && required.has(field)) { + throw new ExternalXlsxError( + "header-not-found", + `Die konfigurierte Pflichtspalte fehlt: ${header}` + ); + } + if (matches.length === 1) lookup.set(header, matches[0]); + } + return lookup; +} + +function resolveReturnColumns( + headerLookup: Map, + configuration: ExternalXlsxTransportConfiguration, + issues: ExternalXlsxIssue[] +) { + const result = new Map(); + const circuitFields: ("circuitCombined" | "boardName" | "circuitIdentifier")[] = + configuration.circuitMode === "combined" + ? ["circuitCombined"] + : ["boardName", "circuitIdentifier"]; + for (const field of circuitFields) { + const header = configuration.columns[field]; + const columnNumber = header === null ? undefined : headerLookup.get(header); + if (columnNumber === undefined) { + throw new ExternalXlsxError( + "return-circuit-column-missing", + `Die Stromkreisspalte des gewählten Modus fehlt: ${field}` + ); + } + result.set(field, columnNumber); + } + const optionalFields = [ + "designation", + "electricalPowerW", + "voltageV", + "currentA", + ] as const; + for (const field of optionalFields) { + const header = configuration.columns[field]; + const columnNumber = header === null ? undefined : headerLookup.get(header); + if (columnNumber === undefined) { + issues.push({ + code: "optional-return-column-missing", + message: `Die optionale Rückgabespalte fehlt und wird übersprungen: ${field}`, + field, + }); + } else { + result.set(field, columnNumber); + } + } + return result; +} + +function toExternalCell( + cell: ExcelJS.Cell, + rowNumber: number, + columnNumber: number, + issues: ExternalXlsxIssue[] +): ExternalXlsxCell { + const converted = toScalar(cell.value); + if (converted.formula !== null) { + issues.push({ + code: converted.usedCachedFormulaValue + ? "cached-formula-value-used" + : "formula-without-cached-value", + message: converted.usedCachedFormulaValue + ? `Formel in Zeile ${rowNumber}, Spalte ${columnNumber} wird mit ihrem gespeicherten Ergebnis gelesen.` + : `Formel in Zeile ${rowNumber}, Spalte ${columnNumber} hat kein nutzbares gespeichertes Ergebnis und bleibt leer.`, + rowNumber, + columnNumber, + }); + } + return { + columnNumber, + value: converted.value, + valueType: getScalarValueType(converted.value), + numberFormat: cell.numFmt || null, + formula: converted.formula, + usedCachedFormulaValue: converted.usedCachedFormulaValue, + }; +} + +function toScalar(value: CellValue): { + value: ExternalXlsxScalar; + formula: string | null; + usedCachedFormulaValue: boolean; +} { + if (value === null || value === undefined) { + return { value: null, formula: null, usedCachedFormulaValue: false }; + } + if ( + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return { value, formula: null, usedCachedFormulaValue: false }; + } + if (value instanceof Date) { + return { value: value.toISOString(), formula: null, usedCachedFormulaValue: false }; + } + if ("formula" in value || "sharedFormula" in value) { + const formula = + ("formula" in value ? value.formula : value.sharedFormula) ?? ""; + const result = "result" in value ? value.result : undefined; + if ( + typeof result === "string" || + typeof result === "number" || + typeof result === "boolean" + ) { + return { value: result, formula, usedCachedFormulaValue: true }; + } + return { value: null, formula, usedCachedFormulaValue: false }; + } + if ("error" in value) { + return { value: null, formula: null, usedCachedFormulaValue: false }; + } + if ("richText" in value) { + return { + value: value.richText.map((part) => part.text).join(""), + formula: null, + usedCachedFormulaValue: false, + }; + } + if ("text" in value) { + return { value: value.text, formula: null, usedCachedFormulaValue: false }; + } + return { value: null, formula: null, usedCachedFormulaValue: false }; +} + +function captureRow(worksheet: Worksheet, rowNumber: number, lastColumn: number) { + const row = worksheet.getRow(rowNumber); + return { + height: row.height, + cells: Array.from({ length: lastColumn }, (_, index) => { + const cell = row.getCell(index + 1); + const converted = toScalar(cell.value); + return { + value: converted.formula === null ? cloneValue(cell.value) : converted.value, + style: structuredClone(cell.style), + note: cell.note === undefined ? undefined : structuredClone(cell.note), + }; + }), + }; +} + +function restoreRow( + worksheet: Worksheet, + rowNumber: number, + snapshot: ReturnType, + lastColumn: number +) { + const row = worksheet.getRow(rowNumber); + row.height = snapshot.height; + for (let columnNumber = 1; columnNumber <= lastColumn; columnNumber += 1) { + const cell = row.getCell(columnNumber); + const source = snapshot.cells[columnNumber - 1]; + cell.value = source.value; + cell.style = structuredClone(source.style); + if (source.note === undefined) { + // ExcelJS has no public comment-removal API. Its note setter creates a + // Note even for undefined, which would add an empty comment to the cell. + (cell as unknown as { _comment?: unknown })._comment = undefined; + } else { + cell.note = source.note; + } + } +} + +function cloneValue(value: CellValue): CellValue { + if (value instanceof Date) return new Date(value); + if (value && typeof value === "object") return structuredClone(value); + return value; +} + +function getCommentText(note: ExcelJS.Cell["note"]): string | null { + if (note === undefined) return null; + if (typeof note === "string") return note; + return note.texts?.map((part) => part.text).join("") ?? null; +} + +function getScalarValueType(value: ExternalXlsxScalar): ExternalXlsxCell["valueType"] { + if (value === null) return "empty"; + if (typeof value === "string") return "string"; + if (typeof value === "number") return "number"; + return "boolean"; +} + +function scalarToIdentity(value: ExternalXlsxScalar | CellValue): string { + const scalar = + typeof value === "object" && value !== null ? toScalar(value).value : value; + return typeof scalar === "string" ? scalar : scalar === null ? "" : String(scalar); +} + +function isWorksharingId(value: string) { + return /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}-[0-9A-Fa-f]{8}$/.test( + value + ); +} + +function assertUpload(fileName: string, bytes: Uint8Array) { + if (!fileName.toLocaleLowerCase("en-US").endsWith(".xlsx")) { + throw new ExternalXlsxError( + "invalid-file-extension", + "Es werden ausschließlich .xlsx-Dateien unterstützt." + ); + } + if (bytes.byteLength > MAX_EXTERNAL_XLSX_BYTES) { + throw new ExternalXlsxError( + "file-too-large", + "Die XLSX-Datei darf höchstens 10 MiB groß sein." + ); + } +} + +async function loadWorkbook(bytes: Uint8Array) { + const workbook = new ExcelJS.Workbook(); + try { + await workbook.xlsx.load( + Buffer.from(bytes) as unknown as Parameters[0] + ); + } catch (error) { + throw new ExternalXlsxError( + "invalid-workbook", + `Die XLSX-Datei konnte nicht gelesen werden: ${error instanceof Error ? error.message : "Unbekannter Fehler"}` + ); + } + return workbook; +} + +function getOnlyWorksheet(workbook: ExcelJS.Workbook) { + if (workbook.worksheets.length !== 1) { + throw new ExternalXlsxError( + "worksheet-count", + "Die XLSX-Datei muss genau ein Arbeitsblatt enthalten." + ); + } + return workbook.worksheets[0]; +} + +function assertWorksheetLimits(worksheet: Worksheet, limits: ExternalXlsxLimits) { + const rowCount = worksheet.rowCount; + const columnCount = worksheet.columnCount; + if ( + rowCount > limits.maxRows || + columnCount > limits.maxColumns || + rowCount * columnCount > limits.maxCells + ) { + throw new ExternalXlsxError( + "worksheet-too-large", + `Das Arbeitsblatt überschreitet die Grenzen (${rowCount} Zeilen, ${columnCount} Spalten).` + ); + } +} + +function assertConfiguration(configuration: ExternalXlsxTransportConfiguration) { + const { headerRow, firstDataRow, firstDataColumn } = configuration.layout; + if ( + !Number.isInteger(headerRow) || + headerRow < 1 || + !Number.isInteger(firstDataRow) || + firstDataRow <= headerRow || + !Number.isInteger(firstDataColumn) || + firstDataColumn < 1 + ) { + throw new ExternalXlsxError( + "invalid-layout", + "Kopfzeile, erste Datenzeile oder erste Datenspalte sind ungültig." + ); + } + if (!configuration.columns.worksharingId || !configuration.columns.familyAndType) { + throw new ExternalXlsxError( + "invalid-layout", + "Worksharing-ID und Familie und Typ müssen konfiguriert sein." + ); + } +} diff --git a/tests/external-xlsx-transport.test.ts b/tests/external-xlsx-transport.test.ts new file mode 100644 index 0000000..32cd784 --- /dev/null +++ b/tests/external-xlsx-transport.test.ts @@ -0,0 +1,267 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import ExcelJS from "exceljs"; +import { + createExternalXlsxReturn, + ExternalXlsxError, + parseExternalXlsx, +} from "../src/external-model/xlsx/external-xlsx-transport.js"; +import { + createRevitXlsxFixture, + externalXlsxTestConfiguration, + firstWorksharingId, + secondWorksharingId, +} from "./fixtures/revit-xlsx-fixtures.js"; + +describe("external XLSX transport", () => { + it("reads typed cells and classifies ID-less rows without blocking summaries", async () => { + const document = await parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture(), + configuration: externalXlsxTestConfiguration, + }); + + assert.equal(document.sheetName, "Linear Export"); + assert.equal(document.headerRowNumber, 1); + assert.equal(document.firstDataRowNumber, 3); + assert.equal(document.firstDataColumnNumber, 1); + assert.deepEqual( + document.rows.map((row) => row.classification), + ["object", "object", "suspect-object", "passthrough"] + ); + assert.equal(document.rows[0].cells[5].value, 2); + assert.equal(document.rows[0].cells[15].value, true); + assert.equal(document.columns[0].comment, "Kommentar Worksharing-ID"); + assert.equal(document.columns[0].width, 12); + assert.deepEqual( + document.issues.map((issue) => issue.code), + ["suspect-object-skipped"] + ); + }); + + it("resolves editable layout positions without a separate ID column", async () => { + const configuration = { + ...externalXlsxTestConfiguration, + layout: { headerRow: 2, firstDataRow: 5, firstDataColumn: 2 }, + }; + const document = await parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture(configuration.layout), + configuration, + }); + + assert.equal(document.headerRowNumber, 2); + assert.equal(document.firstDataRowNumber, 5); + assert.equal(document.firstDataColumnNumber, 2); + assert.equal(document.columns[1].header, "Worksharing-ID"); + assert.equal(document.rows[0].cells[1].value, firstWorksharingId); + assert.deepEqual( + document.rows.map((row) => row.classification), + ["object", "object", "suspect-object", "passthrough"] + ); + }); + + it("compares Worksharing-ID and IfcGUID exactly and case-sensitively", async () => { + const lowerCaseId = secondWorksharingId.toLowerCase(); + const document = await parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture({ + secondWorksharingId: lowerCaseId, + firstIfcGuid: "IfcGUID", + secondIfcGuid: "IFCGUID", + }), + configuration: externalXlsxTestConfiguration, + }); + assert.equal( + document.rows.filter((row) => row.classification === "object").length, + 2 + ); + assert.equal( + document.issues.some((issue) => issue.code === "duplicate-ifc-guid"), + false + ); + + await assert.rejects( + parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture({ duplicateWorksharingId: true }), + configuration: externalXlsxTestConfiguration, + }), + isXlsxError("duplicate-worksharing-id") + ); + + const duplicateIfcDocument = await parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture({ + firstIfcGuid: "same", + secondIfcGuid: "same", + }), + configuration: externalXlsxTestConfiguration, + }); + assert.equal( + duplicateIfcDocument.issues.filter( + (issue) => issue.code === "duplicate-ifc-guid" + ).length, + 1 + ); + }); + + it("uses cached formula values without evaluating formulas", async () => { + const document = await parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture({ includeFormula: true }), + configuration: externalXlsxTestConfiguration, + }); + const powerCell = document.rows[0].cells[11]; + assert.equal(powerCell.value, 250); + assert.equal(powerCell.formula, "125*2"); + assert.equal(powerCell.usedCachedFormulaValue, true); + assert.equal( + document.issues.some( + (issue) => issue.code === "cached-formula-value-used" + ), + true + ); + }); + + it("blocks a required formula without a cached result", async () => { + await assert.rejects( + parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: await createRevitXlsxFixture({ + includeRequiredFormulaWithoutResult: true, + }), + configuration: externalXlsxTestConfiguration, + }), + isXlsxError("required-formula-result-missing") + ); + }); + + it("writes selected object rows in source order and preserves workbook structure", async () => { + const source = await createRevitXlsxFixture({ includeFormula: true }); + const result = await createExternalXlsxReturn({ + fileName: "linear.xlsx", + bytes: source, + configuration: externalXlsxTestConfiguration, + selectedWorksharingIds: [secondWorksharingId, firstWorksharingId], + updates: [ + { + worksharingId: firstWorksharingId, + values: { + circuitCombined: "UV99-3F7", + electricalPowerW: 321.5, + voltageV: 400, + currentA: 0.46, + }, + }, + ], + }); + + assert.equal(result.exportedObjectCount, 2); + const workbook = new ExcelJS.Workbook(); + await workbook.xlsx.load(result.bytes as never); + const worksheet = workbook.worksheets[0]; + assert.equal(worksheet.name, "Linear Export"); + assert.equal(worksheet.rowCount, 4); + assert.equal(worksheet.getCell("A3").value, firstWorksharingId); + assert.equal(worksheet.getCell("A4").value, secondWorksharingId); + assert.equal(worksheet.getCell("H3").value, "UV99-3F7"); + assert.equal(worksheet.getCell("L3").value, 321.5); + assert.equal(worksheet.getCell("M3").value, 400); + assert.equal(worksheet.getCell("N3").value, 0.46); + assert.equal(worksheet.getCell("P4").value, "bleibt"); + assert.equal(worksheet.getCell("L3").numFmt, "0.00"); + assert.equal(worksheet.getColumn(1).width, 12); + assert.equal( + typeof worksheet.getCell("A1").note === "string" + ? worksheet.getCell("A1").note + : worksheet.getCell("A1").note?.texts?.[0]?.text, + "Kommentar Worksharing-ID" + ); + const commentedCells: string[] = []; + worksheet.eachRow({ includeEmpty: true }, (row) => { + row.eachCell({ includeEmpty: true }, (cell) => { + if (cell.note !== undefined) commentedCells.push(cell.address); + }); + }); + assert.deepEqual( + commentedCells, + Array.from({ length: 16 }, (_, index) => + worksheet.getCell(1, index + 1).address + ) + ); + }); + + it("warns for missing optional return columns and blocks missing circuit columns", async () => { + const source = await createRevitXlsxFixture(); + const optionalMissing = { + ...externalXlsxTestConfiguration, + columns: { + ...externalXlsxTestConfiguration.columns, + designation: "Nicht vorhanden", + }, + }; + const result = await createExternalXlsxReturn({ + fileName: "linear.xlsx", + bytes: source, + configuration: optionalMissing, + }); + assert.equal( + result.issues.some( + (issue) => + issue.code === "optional-return-column-missing" && + issue.field === "designation" + ), + true + ); + + await assert.rejects( + createExternalXlsxReturn({ + fileName: "linear.xlsx", + bytes: source, + configuration: { + ...externalXlsxTestConfiguration, + columns: { + ...externalXlsxTestConfiguration.columns, + circuitCombined: "Nicht vorhanden", + }, + }, + }), + isXlsxError("return-circuit-column-missing") + ); + }); + + it("enforces extension, byte size and post-read sheet limits", async () => { + const source = await createRevitXlsxFixture(); + await assert.rejects( + parseExternalXlsx({ + fileName: "linear.xlsm", + bytes: source, + configuration: externalXlsxTestConfiguration, + }), + isXlsxError("invalid-file-extension") + ); + await assert.rejects( + parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: new Uint8Array(10 * 1024 * 1024 + 1), + configuration: externalXlsxTestConfiguration, + }), + isXlsxError("file-too-large") + ); + await assert.rejects( + parseExternalXlsx({ + fileName: "linear.xlsx", + bytes: source, + configuration: externalXlsxTestConfiguration, + limits: { maxRows: 3, maxColumns: 100, maxCells: 1_000 }, + }), + isXlsxError("worksheet-too-large") + ); + }); +}); + +function isXlsxError(code: ExternalXlsxError["code"]) { + return (error: unknown) => + error instanceof ExternalXlsxError && error.code === code; +} diff --git a/tests/fixtures/revit-xlsx-fixtures.ts b/tests/fixtures/revit-xlsx-fixtures.ts new file mode 100644 index 0000000..48e3cbd --- /dev/null +++ b/tests/fixtures/revit-xlsx-fixtures.ts @@ -0,0 +1,134 @@ +import ExcelJS from "exceljs"; +import { + createDefaultExternalXlsxTransportConfiguration, + type ExternalXlsxTransportConfiguration, +} from "../../src/external-model/xlsx/external-xlsx-contracts.js"; + +export const firstWorksharingId = + "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-00000001"; +export const secondWorksharingId = + "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-00000002"; + +export const externalXlsxTestConfiguration: ExternalXlsxTransportConfiguration = + createDefaultExternalXlsxTransportConfiguration(); + +export async function createRevitXlsxFixture(options?: { + duplicateWorksharingId?: boolean; + secondWorksharingId?: string; + firstIfcGuid?: string; + secondIfcGuid?: string; + includeFormula?: boolean; + includeRequiredFormulaWithoutResult?: boolean; + headerRow?: number; + firstDataRow?: number; + firstDataColumn?: number; +}) { + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet("Linear Export"); + const headerRow = options?.headerRow ?? 1; + const firstDataRow = options?.firstDataRow ?? 3; + const firstDataColumn = options?.firstDataColumn ?? 1; + const headers = [ + "Worksharing-ID", + "CAx_Auswahlkenner", + "MEP-Raum: Nummer", + "MEP-Raum: Name", + "Familie und Typ", + "CAX_AnzahlObjekte", + "CAx_Anmerkung", + "kbp_Stromkreisnummer", + "kbp-E-Verteiler", + "kbp-E-Stromkreis", + "kbp-E-Bezeichnung", + "kbp-E-Elektrische Leistung", + "kbp-E-Spannung", + "kbp-E-Stromstärke", + "IfcGUID", + "Unbekannt", + ]; + headers.forEach((header, index) => { + const columnNumber = firstDataColumn + index; + const cell = worksheet.getCell(headerRow, columnNumber); + cell.value = header; + cell.note = `Kommentar ${header}`; + cell.font = { bold: true }; + worksheet.getColumn(columnNumber).width = 12 + index; + }); + + setRowValues(worksheet, firstDataRow, firstDataColumn, [ + firstWorksharingId, + "Steckdose", + "01.101", + "Büro", + "Steckdose: Standard", + 2, + "Quelle A", + "UV01-2F1", + "UV01", + "-2F1", + "Arbeitsplatz", + 250, + 230, + 1.09, + options?.firstIfcGuid ?? "IfcCaseSensitive", + true, + ]); + worksheet.getCell(firstDataRow, firstDataColumn + 11).numFmt = "0.00"; + worksheet.getCell(firstDataRow, firstDataColumn + 12).numFmt = "0"; + worksheet.getCell(firstDataRow, firstDataColumn + 13).numFmt = "0.00"; + if (options?.includeFormula) { + worksheet.getCell(firstDataRow, firstDataColumn + 11).value = { + formula: "125*2", + result: 250, + }; + } + if (options?.includeRequiredFormulaWithoutResult) { + worksheet.getCell(firstDataRow, firstDataColumn).value = { formula: "\"\"" }; + } + + setRowValues(worksheet, firstDataRow + 1, firstDataColumn, [ + options?.duplicateWorksharingId + ? firstWorksharingId + : options?.secondWorksharingId ?? secondWorksharingId, + "Leuchte", + null, + null, + "Leuchte: Decke", + 1, + "Quelle B", + "UV01-1F1", + "UV01", + "-1F1", + "Beleuchtung", + 42.5, + 230, + 0.18, + options?.secondIfcGuid ?? "IfcCaseSensitive2", + "bleibt", + ]); + worksheet.getCell(firstDataRow + 1, firstDataColumn + 11).numFmt = "0.00"; + setRowValues(worksheet, firstDataRow + 2, firstDataColumn, [ + null, + "verdächtig", + null, + null, + "Gerät: Ohne ID", + ]); + setRowValues(worksheet, firstDataRow + 3, firstDataColumn, [ + null, + "Summe: 292,5 W", + ]); + + return new Uint8Array(await workbook.xlsx.writeBuffer()); +} + +function setRowValues( + worksheet: ExcelJS.Worksheet, + rowNumber: number, + firstColumn: number, + values: ExcelJS.CellValue[] +) { + values.forEach((value, index) => { + worksheet.getCell(rowNumber, firstColumn + index).value = value; + }); +} From 1cfeb06ec780da9efe02fe484ba30ee9dec12e7f Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 08:46:07 +0200 Subject: [PATCH 29/38] Replace Revit CSV backend with Linear XLSX --- AGENTS.md | 32 +- README.md | 17 +- docs/current-architecture.md | 38 +- .../revit-excel-integration-requirements.md | 3 + docs/spec/revit-excel-phase-14-plan.md | 4 +- package.json | 2 +- scripts/run-migrations.js | 64 +- .../0014_linear_xlsx_external_model.sql | 97 + src/db/migrations/meta/0014_snapshot.json | 3100 +++++++++++++++++ src/db/migrations/meta/_journal.json | 7 + ...onfiguration-project-command.repository.ts | 105 - ...itial-import-project-command.repository.ts | 252 -- ...onfiguration-project-command.repository.ts | 79 + ...xternal-model-configuration.repository.ts} | 17 +- .../external-model-state.repository.ts | 10 +- .../external-object-assignment.persistence.ts | 8 +- ...roject-state-restore-command.repository.ts | 19 +- .../project-state-snapshot.persistence.ts | 10 +- .../project-transfer.repository.ts | 13 +- src/db/schema/external-csv-configurations.ts | 22 - src/db/schema/external-import-batches.ts | 18 +- .../schema/external-model-configurations.ts | 21 + src/db/schema/external-model-objects.ts | 18 +- src/db/schema/external-model-sources.ts | 7 +- ...csv-configuration-project-command.model.ts | 94 - ...al-initial-import-project-command.model.ts | 134 - ...del-configuration-project-command.model.ts | 88 + .../models/project-state-snapshot.model.ts | 295 +- src/domain/models/project-transfer.model.ts | 64 +- ...csv-configuration-project-command.store.ts | 19 - .../external-csv-configuration.reader.ts | 10 - ...al-initial-import-project-command.store.ts | 19 - ...del-configuration-project-command.store.ts | 19 + .../external-model-configuration.reader.ts | 10 + .../services/project-command.service.ts | 51 +- .../external-circuit-list-objects.ts | 88 - .../application/external-csv-preview.ts | 91 - .../external-initial-import-plan.ts | 164 - .../external-initial-import-target.ts | 130 - .../external-model-configuration.ts | 246 ++ .../csv/external-csv-transport.ts | 356 -- .../domain/external-model-contracts.ts | 45 +- .../domain/external-model-matching.ts | 147 - src/frontend/types.ts | 78 +- .../composition/application-repositories.ts | 6 +- .../composition/project-command-stores.ts | 12 +- .../controllers/external-csv.controller.ts | 298 -- src/server/routes/project.routes.ts | 23 - src/shared/validation/external-csv.schemas.ts | 40 - tests/external-circuit-list-objects.test.ts | 105 - tests/external-csv-api-contract.test.ts | 83 - ...uration-project-command.repository.test.ts | 244 -- tests/external-csv-preview.test.ts | 56 - tests/external-csv-transport.test.ts | 146 - tests/external-initial-import-plan.test.ts | 149 - ...-import-project-command.repository.test.ts | 297 -- tests/external-model-configuration.test.ts | 132 + tests/external-model-foundation.test.ts | 431 --- tests/external-model-xlsx-foundation.test.ts | 87 + ...ignment-project-command.repository.test.ts | 25 +- ...near-xlsx-external-model-migration.test.ts | 115 + tests/project-command.service.test.ts | 56 +- ...ow-sync-project-command.repository.test.ts | 25 +- tests/project-snapshot.repository.test.ts | 2 + tests/project-state-snapshot.test.ts | 38 +- 65 files changed, 4764 insertions(+), 3717 deletions(-) create mode 100644 src/db/migrations/0014_linear_xlsx_external_model.sql create mode 100644 src/db/migrations/meta/0014_snapshot.json delete mode 100644 src/db/repositories/external-csv-configuration-project-command.repository.ts delete mode 100644 src/db/repositories/external-initial-import-project-command.repository.ts create mode 100644 src/db/repositories/external-model-configuration-project-command.repository.ts rename src/db/repositories/{external-csv-configuration.repository.ts => external-model-configuration.repository.ts} (51%) delete mode 100644 src/db/schema/external-csv-configurations.ts create mode 100644 src/db/schema/external-model-configurations.ts delete mode 100644 src/domain/models/external-csv-configuration-project-command.model.ts delete mode 100644 src/domain/models/external-initial-import-project-command.model.ts create mode 100644 src/domain/models/external-model-configuration-project-command.model.ts delete mode 100644 src/domain/ports/external-csv-configuration-project-command.store.ts delete mode 100644 src/domain/ports/external-csv-configuration.reader.ts delete mode 100644 src/domain/ports/external-initial-import-project-command.store.ts create mode 100644 src/domain/ports/external-model-configuration-project-command.store.ts create mode 100644 src/domain/ports/external-model-configuration.reader.ts delete mode 100644 src/external-model/application/external-circuit-list-objects.ts delete mode 100644 src/external-model/application/external-csv-preview.ts delete mode 100644 src/external-model/application/external-initial-import-plan.ts delete mode 100644 src/external-model/application/external-initial-import-target.ts create mode 100644 src/external-model/configuration/external-model-configuration.ts delete mode 100644 src/external-model/csv/external-csv-transport.ts delete mode 100644 src/external-model/domain/external-model-matching.ts delete mode 100644 src/server/controllers/external-csv.controller.ts delete mode 100644 src/shared/validation/external-csv.schemas.ts delete mode 100644 tests/external-circuit-list-objects.test.ts delete mode 100644 tests/external-csv-api-contract.test.ts delete mode 100644 tests/external-csv-configuration-project-command.repository.test.ts delete mode 100644 tests/external-csv-preview.test.ts delete mode 100644 tests/external-csv-transport.test.ts delete mode 100644 tests/external-initial-import-plan.test.ts delete mode 100644 tests/external-initial-import-project-command.repository.test.ts create mode 100644 tests/external-model-configuration.test.ts delete mode 100644 tests/external-model-foundation.test.ts create mode 100644 tests/external-model-xlsx-foundation.test.ts create mode 100644 tests/linear-xlsx-external-model-migration.test.ts diff --git a/AGENTS.md b/AGENTS.md index 7c0a120..c95a271 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -295,7 +295,10 @@ not change the project revision or undo/redo stacks. Restoring a server-stored snapshot verifies its checksum and the current-state hash, replaces supported project data atomically and records a new `restore` revision with a complete inverse command. Restore can therefore be undone and redone after a restart. -Current snapshot schema version 9 additionally stores +Current snapshot schema version 10 stores the Linear-XLSX configuration and +external state with Worksharing-ID identity. Empty versions 1 to 9 are upgraded; +versions containing legacy CSV configuration or external CSV state are rejected +with a German migration error. Version 9 additionally stores `feedingDistributionBoardId` and `feedingCircuitId` on distribution boards; versions 1 to 8 are upgraded with both references set to `null`. Version 8 stores the optional net room area `rooms[].areaM2` (see @@ -307,8 +310,8 @@ distribution-board info fields `boardNumber`, `location`, `fedFrom` and `remark` and the project cover fields `siteAddress`, `workStage`, `projectLead` and `projectEditor`; all older supported versions are upgraded with `null` for these fields. -Stored named and automatic snapshots of every supported version (1 to 9) -remain restorable; they are upgraded while parsing. Version 5 stores +Stored named and automatic snapshots of versions 1 to 9 remain restorable when +they contain no legacy CSV state; they are upgraded while parsing. Version 5 stores the manual quantity share of every CircuitDeviceRow. Version 4 snapshots are upgraded with `manualQuantity = quantity`; they already contain the complete confirmed external-model source, import batches, room mappings and objects. Version 3 @@ -320,17 +323,17 @@ supported versions contain circuit-group identity, distribution-board components separate circuit/component protection records. Portable duplicate imports remap component ids and protection-owner references together with the existing project graph. -The current runtime still contains the legacy Revit-CSV/IfcGUID foundation: -project configuration, preview, confirmed initial import, external objects and -the three row-assignment commands. It remains the audited starting point, not -the Phase-14 target. Do not extend its CSV transport or IFCGUID identity model. -The approved cutover is Linear XLSX with exact case-sensitive Worksharing-ID -identity. See `docs/spec/revit-excel-integration-requirements.md` and +R3 replaced the runtime configuration and persistence foundation with Linear +XLSX and exact case-sensitive Worksharing-ID identity. Migration `0014` drops +the old development-only external CSV data after resetting linked row totals to +their manual share. Snapshot schema 10, restore and project transfer use the +new state; non-empty legacy CSV snapshots and legacy CSV history entries are +rejected with a German error. The backend CSV parser and routes are removed. +The old project-page frontend remains only until its replacement in R4; do not +reconnect it to runtime CSV endpoints. See +`docs/spec/revit-excel-integration-requirements.md` and `docs/spec/revit-excel-phase-14-plan.md`. -During R1/R2 no database or runtime schema changes are made. R3 will replace -the legacy configuration and transport additively, reject non-empty legacy CSV -snapshot/history state with a German error, and introduce snapshot schema 10. The target configuration has no independent version counter; `expectedRevision` invalidates stale plans, and each import batch stores a configuration copy. Only the newest import batch retains workbook bytes and the full matrix; older @@ -582,9 +585,8 @@ Critical target rules: produce warnings and are skipped. Only missing circuit columns for the selected combined/separate mode block export. - Missing GZF defaults visibly to 1 without separate confirmation. -- R2 must generate a changed return workbook from the local sample. The user - tests it in Linear before R3. If Linear rejects it, propose direct OOXML - modification of the original workbook before starting R3. +- The corrected R2 return workbook was successfully imported into Linear on + 2026-09-30; R3 is complete and R4 is the next package. - All confirmed writes use typed project commands with `expectedRevision`, complete inverse data and the shared project-command transaction boundary. - Do not add automatic circuit planning, Revit circuit adoption, multi-source diff --git a/README.md b/README.md index 3490332..b8b9c3e 100644 --- a/README.md +++ b/README.md @@ -9,12 +9,11 @@ Docker-Server-Stack mit gebautem Anwendungscode und ein separater Entwicklungsstack bereit. Ein vollständig unterstütztes Produktionsdeployment für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstütztes Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind -vorhanden. Die bisherige Revit-CSV-/IfcGUID-Grundlage mit Vorschau und -bestätigtem Erstimport ist noch im Code vorhanden. Der freigegebene -Phase-14-Plan ersetzt sie schrittweise durch den XLSX-Austausch des -Linear-Plugins mit Worksharing-ID als externem Schlüssel. R0 ist abgeschlossen; -R1 aktualisiert die Dokumentation. Editorzuordnung, Folgeimport und Rückexport -sind noch nicht als neuer Excel-Pfad ausgeliefert. +vorhanden. Die Backend- und Persistenzgrundlage der bisherigen +Revit-CSV-/IfcGUID-Anbindung ist durch den XLSX-Austausch des Linear-Plugins mit +Worksharing-ID als externem Schlüssel ersetzt. R0 bis R3 sind abgeschlossen; +die eigene Revit-Seite, Erstimport, Editorzuordnung, Rückgabe und Folgeimport +folgen in R4 bis R10. ## Unterstützter Arbeitsablauf @@ -41,9 +40,9 @@ sind noch nicht als neuer Excel-Pfad ausgeliefert. - grobe Leistungsbilanzen für LPH 2/3 nach Kostengruppen führen, mit der detaillierten Bilanz vergleichen und einzelne Zeilen als Projektgerät übernehmen -- den vorhandenen Legacy-Revit-CSV-Erstimport verwenden; der Zielpfad über - Linear-XLSX, eigene Revit-Seite, Editorzuordnung, Rückgabe und Folgeimport - wird gemäß Phase-14-Plan umgesetzt +- Linear-XLSX-Dateien verlustarm lesen und schreiben; Revit-Seite, + Erstimport, Editorzuordnung, Rückgabe und Folgeimport werden gemäß + Phase-14-Plan in den nächsten Paketen angebunden ## Technik diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 8993974..846debb 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -510,6 +510,9 @@ Die projektweite Circuit-Tree-Projektion berechnet rekursiv die Lasten aller Verteilungen. Die Leistung einer Unterverteilung nach ihrem eigenen Verteiler-GZF wird als virtuelle, schreibgeschützte Zeile genau dem gewählten Abgang zugerechnet. Eine Verknüpfung ohne Stromkreis bildet nur die Hierarchie. +Snapshot-Schema 10 enthält zusätzlich die Linear-XLSX-Konfiguration und den +externen Zustand mit Worksharing-ID-Identität. Leere Versionen 1–9 werden +hochgestuft; Versionen mit tatsächlichem Legacy-CSV-Zustand werden abgelehnt. Snapshot-Schema 9 enthält die beiden Einspeisungsverweise; Versionen 1–8 werden mit `null` hochgestuft. Restore und Projektduplizierung erhalten beziehungsweise remappen die Verweise. Snapshot-Schema 8 enthält zusätzlich die optionale Netto-Raumfläche @@ -520,9 +523,9 @@ Snapshot-Schema 6 enthält diese Felder und die Deckblattangaben des Projekts; ältere Versionen werden mit `null` hochgestuft. Snapshot-Schema 5 enthält zusätzlich den manuellen Mengenanteil jeder Gerätezeile. Version 4 wird mit `manualQuantity = quantity` hochgestuft und -enthält bereits den vollständigen externen Modellzustand -aus Quelle, Batches, Raum-Mappings und Objekten. Es enthält außerdem die -projektweite Revit-CSV-Konfiguration, die Gebäudekennzeichnung sowie den Gleichzeitigkeitsfaktor, +enthielt bereits den damaligen externen CSV-Modellzustand +aus Quelle, Batches, Raum-Mappings und Objekten. Es enthielt außerdem die +damalige projektweite Revit-CSV-Konfiguration, die Gebäudekennzeichnung sowie den Gleichzeitigkeitsfaktor, Gruppenkategorie und -nummer, Verteilerkomponenten sowie die getrennten 1:1-Schutzgerätedaten. Capture, benannte und automatische Snapshots, Wiederherstellung, Undo/Redo und beide @@ -640,7 +643,34 @@ PostgreSQL ist bewusst nicht implementiert. Die Domainregeln und Transaktionsgrenzen sollen portabel bleiben; Schema und Betriebsmodell benötigen bei einem späteren Wechsel trotzdem einen eigenen PostgreSQL-Adapter. -## Revit-Anbindung: Legacy-Ausgangslage und freigegebener Excel-Cutover +## Revit-Anbindung: Linear-XLSX-Grundlage nach R3 + +R3 hat den Backend- und Persistenz-Cutover abgeschlossen. Migration `0014` +entfernt die alten externen CSV-Entwicklungsdaten, nachdem verknüpfte +Gerätezeilen auf `manualQuantity` zurückgesetzt wurden. Die neue +`external_model_configurations`-Tabelle besitzt keinen eigenen Versionszähler; +Änderungen laufen als Projekt-Commands über `expectedRevision`. + +Externe Objekte werden je Quelle durch `worksharing_id` exakt und +case-sensitiv identifiziert. `ifc_guid` ist nullable und nicht eindeutig. +Importbatches speichern eine Konfigurationskopie; nur der neueste Batch darf +Originalbytes und die vollständige XLSX-Matrix enthalten, ältere Batches nur +Datum, Dateiname, SHA-256 und Objektzahl. Snapshot-Schema 10, Restore und +Projekttransfer verwenden diesen Zustand und remappen alle internen +Konfigurations-, Gerätearten-, Regel- und Objekt-UUIDs. Leere Snapshots 1–9 +werden hochgestuft; alte Snapshots mit CSV-Konfiguration oder externem +CSV-Zustand sowie alte CSV-History-Commands werden mit einer deutschen Meldung +abgelehnt. + +Der XLSX-Adapter liegt unter `src/external-model/xlsx`. Der Backend-CSV-Parser, +seine Endpunkte und Laufzeitverträge sind entfernt. Die noch sichtbare alte +Projektseiten-Oberfläche ist bis R4 ohne Backend-Anbindung und wird dort durch +die Route `/projects/:projectId/revit` ersetzt. + +### Historische Ausgangslage vor R3 + +Der folgende Text beschreibt den Stand nach R1 und ist keine aktuelle +Laufzeitdokumentation mehr. Der nachfolgende Abschnitt beschreibt den am Ende von R1 noch vorhandenen Legacy-Laufzeitpfad. Er verwendet CSV und IfcGUID und ist die geprüfte diff --git a/docs/spec/revit-excel-integration-requirements.md b/docs/spec/revit-excel-integration-requirements.md index ff580ec..29a4aaf 100644 --- a/docs/spec/revit-excel-integration-requirements.md +++ b/docs/spec/revit-excel-integration-requirements.md @@ -386,6 +386,9 @@ erzeugt wurde und einige klar identifizierbare Rückgabewerte verändert. Diese Datei wird nicht committed. Der Nutzer testet sie in Linear. R3 darf erst nach erfolgreichem Linear-Rückimport beginnen. +Die korrigierte R2-Rückgabedatei wurde am 30.09.2026 erfolgreich in Linear +eingelesen. Damit ist diese Abnahme erfüllt und R3 freigegeben. + Scheitert der Linear-Import, wird vor R3 eine Alternative zur Freigabe vorgelegt: Die Original-XLSX wird direkt auf OOXML-Ebene kopiert und nur die erforderlichen Zellwerte/-typen sowie Zeilenbereiche angepasst. Die diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index bb00053..4004eb3 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -10,8 +10,8 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | --- | --- | --- | | R0 | abgeschlossen und freigegeben | Bestandsaudit, Zielmodell, Migration und Risiken; Freigabekorrekturen in R1 eingearbeitet. | | R1 | abgeschlossen | Anforderungen, Plan und Architektur auf Excel/Worksharing-ID umgestellt; alle Pflichtprüfungen bestanden. | -| R2 | implementiert, Linear-Abnahme ausstehend | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei sind erstellt. R3 bleibt bis zum erfolgreichen Linear-Test gesperrt. | -| R3 | gesperrt bis R2-Abnahme | Konfiguration, Identität, Migration, Snapshot 10, Transfer und Backend-CSV-Entfernung. | +| R2 | abgeschlossen und freigegeben | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei sind erstellt; der korrigierte Rückimport wurde am 30.09.2026 erfolgreich in Linear getestet. | +| R3 | abgeschlossen | Konfiguration ohne eigene Revision, Worksharing-ID-Datenmodell, Migration 0014, Snapshot 10, Transfer und Backend-CSV-Entfernung sind umgesetzt und geprüft. | | R4 | offen | Revit-Seite, Navigation, Einstellungen, altes Projektseitenmodal entfernen. | | R5 | offen | Erstimportwizard mit Gerätearten, Familienregeln und optionalen ProjectDevices. | | R6 | offen | Virtualisierte Objekttabelle und Sammelzuordnungen. | diff --git a/package.json b/package.json index 1c035ba..17837f1 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "test": "node scripts/run-tests.mjs", "test:watch": "node scripts/run-tests.mjs --watch", "db:generate": "drizzle-kit generate", - "db:migrate": "drizzle-kit migrate", + "db:migrate": "node scripts/run-migrations.js", "db:backup": "tsx scripts/db-backup.ts", "db:verify:circuit-schema": "node scripts/db-verify-circuit-schema.js", "revit:verify-reference": "tsx scripts/verify-revit-reference-xlsx.ts" diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js index ebbed8a..3a6fc84 100644 --- a/scripts/run-migrations.js +++ b/scripts/run-migrations.js @@ -4,13 +4,65 @@ const Database = require('better-sqlite3'); const fs = require('node:fs'); const path = require('node:path'); -const dataDir = path.resolve('data'); +const dataDir = path.resolve( + process.env.LEISTUNGSBILANZ_DATA_DIR || 'data' +); if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); -const sqlite = new Database(path.join(dataDir, 'leistungsbilanz.db')); -const db = drizzle(sqlite); +const databasePath = path.join(dataDir, 'leistungsbilanz.db'); -migrate(db, { migrationsFolder: path.resolve('src/db/migrations') }); -sqlite.close(); +async function run() { + const sqlite = new Database(databasePath); + try { + if (requiresLinearXlsxBackup(sqlite)) { + const backupDir = path.join(dataDir, 'backups'); + fs.mkdirSync(backupDir, { recursive: true }); + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const backupPath = path.join( + backupDir, + `leistungsbilanz-before-linear-xlsx-${timestamp}.db` + ); + await sqlite.backup(backupPath); + verifyBackup(backupPath); + console.log(`Verified pre-migration backup created: ${backupPath}`); + } -console.log('Migrations applied'); + migrate(drizzle(sqlite), { + migrationsFolder: path.resolve('src/db/migrations'), + }); + } finally { + sqlite.close(); + } + console.log('Migrations applied'); +} + +function requiresLinearXlsxBackup(sqlite) { + const tables = new Set( + sqlite.prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() + .map((row) => row.name) + ); + return tables.has('external_csv_configurations') && + !tables.has('external_model_configurations'); +} + +function verifyBackup(backupPath) { + const backup = new Database(backupPath, { readonly: true, fileMustExist: true }); + try { + const integrity = backup.pragma('integrity_check', { simple: true }); + const foreignKeyViolations = backup.pragma('foreign_key_check'); + if (integrity !== 'ok' || foreignKeyViolations.length > 0) { + throw new Error( + `Pre-migration backup verification failed: integrity=${integrity}, ` + + `foreign-key violations=${foreignKeyViolations.length}` + ); + } + } finally { + backup.close(); + } +} + +run().catch((error) => { + console.error('Migration failed:', error instanceof Error ? error.message : error); + process.exit(1); +}); diff --git a/src/db/migrations/0014_linear_xlsx_external_model.sql b/src/db/migrations/0014_linear_xlsx_external_model.sql new file mode 100644 index 0000000..cb8546b --- /dev/null +++ b/src/db/migrations/0014_linear_xlsx_external_model.sql @@ -0,0 +1,97 @@ +PRAGMA foreign_keys=OFF;--> statement-breakpoint +UPDATE `circuit_device_rows` +SET `quantity` = `manual_quantity` +WHERE EXISTS ( + SELECT 1 + FROM `external_model_objects` + WHERE `external_model_objects`.`circuit_device_row_id` = `circuit_device_rows`.`id` +);--> statement-breakpoint +DROP TABLE `external_model_objects`;--> statement-breakpoint +DROP TABLE `external_room_mappings`;--> statement-breakpoint +DROP TABLE `external_import_batches`;--> statement-breakpoint +DROP TABLE `external_model_sources`;--> statement-breakpoint +DROP TABLE `external_csv_configurations`;--> statement-breakpoint +CREATE TABLE `external_model_configurations` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `configuration` text NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +);--> statement-breakpoint +CREATE UNIQUE INDEX `external_model_configurations_project_id_unique` ON `external_model_configurations` (`project_id`);--> statement-breakpoint +CREATE TABLE `external_model_sources` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `name` text NOT NULL, + `source_type` text DEFAULT 'revit_xlsx' NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +);--> statement-breakpoint +CREATE UNIQUE INDEX `external_model_sources_project_unique` ON `external_model_sources` (`project_id`);--> statement-breakpoint +CREATE TABLE `external_import_batches` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `source_id` text NOT NULL, + `import_kind` text NOT NULL, + `imported_at_iso` text NOT NULL, + `file_name` text NOT NULL, + `sha256` text NOT NULL, + `object_count` integer NOT NULL, + `applied_project_revision` integer, + `configuration_snapshot` text, + `original_bytes` blob, + `document` text, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`source_id`) REFERENCES `external_model_sources`(`id`) ON UPDATE no action ON DELETE cascade +);--> statement-breakpoint +CREATE INDEX `external_import_batches_project_revision_idx` ON `external_import_batches` (`project_id`,`applied_project_revision`);--> statement-breakpoint +CREATE INDEX `external_import_batches_source_imported_idx` ON `external_import_batches` (`source_id`,`imported_at_iso`);--> statement-breakpoint +CREATE TABLE `external_room_mappings` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `source_id` text NOT NULL, + `normalized_source_room_key` text NOT NULL, + `source_floor_name` text, + `source_room_number` text NOT NULL, + `source_room_name` text NOT NULL, + `room_id` text, + `default_distribution_board_id` text, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`source_id`) REFERENCES `external_model_sources`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`room_id`) REFERENCES `rooms`(`id`) ON UPDATE no action ON DELETE set null, + FOREIGN KEY (`default_distribution_board_id`) REFERENCES `distribution_boards`(`id`) ON UPDATE no action ON DELETE set null +);--> statement-breakpoint +CREATE UNIQUE INDEX `external_room_mappings_source_key_unique` ON `external_room_mappings` (`source_id`,`normalized_source_room_key`);--> statement-breakpoint +CREATE INDEX `external_room_mappings_project_room_idx` ON `external_room_mappings` (`project_id`,`room_id`);--> statement-breakpoint +CREATE TABLE `external_model_objects` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text NOT NULL, + `source_id` text NOT NULL, + `worksharing_id` text NOT NULL, + `ifc_guid` text, + `device_type_id` text NOT NULL, + `last_seen_import_batch_id` text NOT NULL, + `last_accepted_import_batch_id` text NOT NULL, + `accepted_source_values` text NOT NULL, + `planning_values` text NOT NULL, + `overridden_fields` text NOT NULL, + `external_room_mapping_id` text, + `distribution_board_id` text, + `linked_project_device_id` text, + `circuit_device_row_id` text, + `presence_status` text DEFAULT 'present' NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`source_id`) REFERENCES `external_model_sources`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`last_seen_import_batch_id`) REFERENCES `external_import_batches`(`id`) ON UPDATE no action ON DELETE restrict, + FOREIGN KEY (`last_accepted_import_batch_id`) REFERENCES `external_import_batches`(`id`) ON UPDATE no action ON DELETE restrict, + FOREIGN KEY (`external_room_mapping_id`) REFERENCES `external_room_mappings`(`id`) ON UPDATE no action ON DELETE set null, + FOREIGN KEY (`distribution_board_id`) REFERENCES `distribution_boards`(`id`) ON UPDATE no action ON DELETE set null, + FOREIGN KEY (`linked_project_device_id`) REFERENCES `project_devices`(`id`) ON UPDATE no action ON DELETE set null, + FOREIGN KEY (`circuit_device_row_id`) REFERENCES `circuit_device_rows`(`id`) ON UPDATE no action ON DELETE set null +);--> statement-breakpoint +CREATE UNIQUE INDEX `external_model_objects_source_worksharing_id_unique` ON `external_model_objects` (`source_id`,`worksharing_id`);--> statement-breakpoint +CREATE INDEX `external_model_objects_project_presence_idx` ON `external_model_objects` (`project_id`,`presence_status`);--> statement-breakpoint +CREATE INDEX `external_model_objects_project_device_type_idx` ON `external_model_objects` (`project_id`,`device_type_id`);--> statement-breakpoint +CREATE INDEX `external_model_objects_external_room_mapping_idx` ON `external_model_objects` (`external_room_mapping_id`);--> statement-breakpoint +CREATE INDEX `external_model_objects_distribution_board_idx` ON `external_model_objects` (`distribution_board_id`);--> statement-breakpoint +CREATE INDEX `external_model_objects_linked_project_device_idx` ON `external_model_objects` (`linked_project_device_id`);--> statement-breakpoint +CREATE INDEX `external_model_objects_circuit_device_row_idx` ON `external_model_objects` (`circuit_device_row_id`);--> statement-breakpoint +PRAGMA foreign_keys=ON; diff --git a/src/db/migrations/meta/0014_snapshot.json b/src/db/migrations/meta/0014_snapshot.json new file mode 100644 index 0000000..dc4c096 --- /dev/null +++ b/src/db/migrations/meta/0014_snapshot.json @@ -0,0 +1,3100 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "b443af16-e0aa-459a-9443-62a7f8c6b6dd", + "prevId": "a967fdfb-171b-4f1d-aa0c-f7124e28fba3", + "tables": { + "buildings": { + "name": "buildings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "buildings_project_id_projects_id_fk": { + "name": "buildings_project_id_projects_id_fk", + "tableFrom": "buildings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_device_rows": { + "name": "circuit_device_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number_snapshot": { + "name": "room_number_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_name_snapshot": { + "name": "room_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manual_quantity": { + "name": "manual_quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_device_rows_circuit_id_idx": { + "name": "circuit_device_rows_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "circuit_device_rows_circuit_id_circuits_id_fk": { + "name": "circuit_device_rows_circuit_id_circuits_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_device_rows_linked_project_device_id_project_devices_id_fk": { + "name": "circuit_device_rows_linked_project_device_id_project_devices_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "circuit_device_rows_room_id_rooms_id_fk": { + "name": "circuit_device_rows_room_id_rooms_id_fk", + "tableFrom": "circuit_device_rows", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_list_equipment_identifiers": { + "name": "circuit_list_equipment_identifiers", + "columns": { + "owner_type": { + "name": "owner_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_list_equipment_identifiers_owner_unique": { + "name": "circuit_list_equipment_identifiers_owner_unique", + "columns": [ + "owner_type", + "owner_id" + ], + "isUnique": true + }, + "circuit_list_equipment_identifiers_list_identifier_unique": { + "name": "circuit_list_equipment_identifiers_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_list_equipment_identifiers_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_list_equipment_identifiers", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_lists": { + "name": "circuit_lists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "circuit_lists_distribution_board_id_unique": { + "name": "circuit_lists_distribution_board_id_unique", + "columns": [ + "distribution_board_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_lists_project_id_projects_id_fk": { + "name": "circuit_lists_project_id_projects_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuit_lists_distribution_board_id_distribution_boards_id_fk": { + "name": "circuit_lists_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "circuit_lists", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_protection_devices": { + "name": "circuit_protection_devices", + "columns": { + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "circuit_protection_devices_circuit_id_circuits_id_fk": { + "name": "circuit_protection_devices_circuit_id_circuits_id_fk", + "tableFrom": "circuit_protection_devices", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuit_sections": { + "name": "circuit_sections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "group_number": { + "name": "group_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuit_sections_list_key_unique": { + "name": "circuit_sections_list_key_unique", + "columns": [ + "circuit_list_id", + "key" + ], + "isUnique": true + }, + "circuit_sections_list_prefix_unique": { + "name": "circuit_sections_list_prefix_unique", + "columns": [ + "circuit_list_id", + "prefix" + ], + "isUnique": true + }, + "circuit_sections_list_category_group_unique": { + "name": "circuit_sections_list_category_group_unique", + "columns": [ + "circuit_list_id", + "category", + "group_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuit_sections_circuit_list_id_circuit_lists_id_fk": { + "name": "circuit_sections_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuit_sections", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "circuits": { + "name": "circuits", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "cable_type": { + "name": "cable_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_cross_section": { + "name": "cable_cross_section", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cable_length": { + "name": "cable_length", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_assignment": { + "name": "rcd_assignment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "terminal_designation": { + "name": "terminal_designation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage": { + "name": "voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "control_requirement": { + "name": "control_requirement", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_reserve": { + "name": "is_reserve", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "circuits_section_id_idx": { + "name": "circuits_section_id_idx", + "columns": [ + "section_id" + ], + "isUnique": false + }, + "circuits_list_equipment_identifier_unique": { + "name": "circuits_list_equipment_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + } + }, + "foreignKeys": { + "circuits_circuit_list_id_circuit_lists_id_fk": { + "name": "circuits_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "circuits_section_id_circuit_sections_id_fk": { + "name": "circuits_section_id_circuit_sections_id_fk", + "tableFrom": "circuits", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_component_protection_devices": { + "name": "distribution_board_component_protection_devices", + "columns": { + "component_id": { + "name": "component_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rated_current_a": { + "name": "rated_current_a", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fuse_utilization_category": { + "name": "fuse_utilization_category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trip_characteristic": { + "name": "trip_characteristic", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rcd_type": { + "name": "rcd_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rated_residual_current_ma": { + "name": "rated_residual_current_ma", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk": { + "name": "distribution_board_component_protection_devices_component_id_distribution_board_components_id_fk", + "tableFrom": "distribution_board_component_protection_devices", + "tableTo": "distribution_board_components", + "columnsFrom": [ + "component_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_board_components": { + "name": "distribution_board_components", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "circuit_list_id": { + "name": "circuit_list_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "section_id": { + "name": "section_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "placement": { + "name": "placement", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "distribution_board_components_list_identifier_unique": { + "name": "distribution_board_components_list_identifier_unique", + "columns": [ + "circuit_list_id", + "equipment_identifier" + ], + "isUnique": true + }, + "distribution_board_components_section_role_unique": { + "name": "distribution_board_components_section_role_unique", + "columns": [ + "section_id", + "role" + ], + "isUnique": true + } + }, + "foreignKeys": { + "distribution_board_components_circuit_list_id_circuit_lists_id_fk": { + "name": "distribution_board_components_circuit_list_id_circuit_lists_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_lists", + "columnsFrom": [ + "circuit_list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_board_components_section_id_circuit_sections_id_fk": { + "name": "distribution_board_components_section_id_circuit_sections_id_fk", + "tableFrom": "distribution_board_components", + "tableTo": "circuit_sections", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "distribution_boards": { + "name": "distribution_boards", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "supply_type": { + "name": "supply_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "board_number": { + "name": "board_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fed_from": { + "name": "fed_from", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "feeding_distribution_board_id": { + "name": "feeding_distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "feeding_circuit_id": { + "name": "feeding_circuit_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "distribution_boards_feeding_board_idx": { + "name": "distribution_boards_feeding_board_idx", + "columns": [ + "feeding_distribution_board_id" + ], + "isUnique": false + }, + "distribution_boards_feeding_circuit_idx": { + "name": "distribution_boards_feeding_circuit_idx", + "columns": [ + "feeding_circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "distribution_boards_project_id_projects_id_fk": { + "name": "distribution_boards_project_id_projects_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "distribution_boards_floor_id_floors_id_fk": { + "name": "distribution_boards_floor_id_floors_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "distribution_boards_feeding_distribution_board_id_distribution_boards_id_fk": { + "name": "distribution_boards_feeding_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "distribution_boards", + "columnsFrom": [ + "feeding_distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "distribution_boards_feeding_circuit_id_circuits_id_fk": { + "name": "distribution_boards_feeding_circuit_id_circuits_id_fk", + "tableFrom": "distribution_boards", + "tableTo": "circuits", + "columnsFrom": [ + "feeding_circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_assets": { + "name": "document_branding_assets", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "data": { + "name": "data", + "type": "blob", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "document_branding_settings": { + "name": "document_branding_settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_balances": { + "name": "estimate_balances", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date_iso": { + "name": "date_iso", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reserve_av_percent": { + "name": "reserve_av_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "reserve_sv_percent": { + "name": "reserve_sv_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_balances_project_id_idx": { + "name": "estimate_balances_project_id_idx", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_balances_project_id_projects_id_fk": { + "name": "estimate_balances_project_id_projects_id_fk", + "tableFrom": "estimate_balances", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_groups": { + "name": "estimate_groups", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "balance_id": { + "name": "balance_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "editor": { + "name": "editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "estimate_groups_balance_id_idx": { + "name": "estimate_groups_balance_id_idx", + "columns": [ + "balance_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_groups_balance_id_estimate_balances_id_fk": { + "name": "estimate_groups_balance_id_estimate_balances_id_fk", + "tableFrom": "estimate_groups", + "tableTo": "estimate_balances", + "columnsFrom": [ + "balance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "estimate_rows": { + "name": "estimate_rows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "supply": { + "name": "supply", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "quantity": { + "name": "quantity", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'piece'" + }, + "connection": { + "name": "connection", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_per_unit_w": { + "name": "power_per_unit_w", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "safety_supply": { + "name": "safety_supply", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "estimate_rows_group_id_idx": { + "name": "estimate_rows_group_id_idx", + "columns": [ + "group_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "estimate_rows_group_id_estimate_groups_id_fk": { + "name": "estimate_rows_group_id_estimate_groups_id_fk", + "tableFrom": "estimate_rows", + "tableTo": "estimate_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_import_batches": { + "name": "external_import_batches", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "import_kind": { + "name": "import_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "imported_at_iso": { + "name": "imported_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "object_count": { + "name": "object_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_project_revision": { + "name": "applied_project_revision", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "configuration_snapshot": { + "name": "configuration_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_bytes": { + "name": "original_bytes", + "type": "blob", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "document": { + "name": "document", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "external_import_batches_project_revision_idx": { + "name": "external_import_batches_project_revision_idx", + "columns": [ + "project_id", + "applied_project_revision" + ], + "isUnique": false + }, + "external_import_batches_source_imported_idx": { + "name": "external_import_batches_source_imported_idx", + "columns": [ + "source_id", + "imported_at_iso" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_import_batches_project_id_projects_id_fk": { + "name": "external_import_batches_project_id_projects_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_import_batches_source_id_external_model_sources_id_fk": { + "name": "external_import_batches_source_id_external_model_sources_id_fk", + "tableFrom": "external_import_batches", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_configurations": { + "name": "external_model_configurations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration": { + "name": "configuration", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "external_model_configurations_project_id_unique": { + "name": "external_model_configurations_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_model_configurations_project_id_projects_id_fk": { + "name": "external_model_configurations_project_id_projects_id_fk", + "tableFrom": "external_model_configurations", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_objects": { + "name": "external_model_objects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "worksharing_id": { + "name": "worksharing_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ifc_guid": { + "name": "ifc_guid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "device_type_id": { + "name": "device_type_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_import_batch_id": { + "name": "last_seen_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_accepted_import_batch_id": { + "name": "last_accepted_import_batch_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_source_values": { + "name": "accepted_source_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "planning_values": { + "name": "planning_values", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_room_mapping_id": { + "name": "external_room_mapping_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "distribution_board_id": { + "name": "distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "linked_project_device_id": { + "name": "linked_project_device_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_device_row_id": { + "name": "circuit_device_row_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "presence_status": { + "name": "presence_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'present'" + } + }, + "indexes": { + "external_model_objects_source_worksharing_id_unique": { + "name": "external_model_objects_source_worksharing_id_unique", + "columns": [ + "source_id", + "worksharing_id" + ], + "isUnique": true + }, + "external_model_objects_project_presence_idx": { + "name": "external_model_objects_project_presence_idx", + "columns": [ + "project_id", + "presence_status" + ], + "isUnique": false + }, + "external_model_objects_project_device_type_idx": { + "name": "external_model_objects_project_device_type_idx", + "columns": [ + "project_id", + "device_type_id" + ], + "isUnique": false + }, + "external_model_objects_external_room_mapping_idx": { + "name": "external_model_objects_external_room_mapping_idx", + "columns": [ + "external_room_mapping_id" + ], + "isUnique": false + }, + "external_model_objects_distribution_board_idx": { + "name": "external_model_objects_distribution_board_idx", + "columns": [ + "distribution_board_id" + ], + "isUnique": false + }, + "external_model_objects_linked_project_device_idx": { + "name": "external_model_objects_linked_project_device_idx", + "columns": [ + "linked_project_device_id" + ], + "isUnique": false + }, + "external_model_objects_circuit_device_row_idx": { + "name": "external_model_objects_circuit_device_row_idx", + "columns": [ + "circuit_device_row_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_model_objects_project_id_projects_id_fk": { + "name": "external_model_objects_project_id_projects_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_source_id_external_model_sources_id_fk": { + "name": "external_model_objects_source_id_external_model_sources_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_seen_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_seen_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk": { + "name": "external_model_objects_last_accepted_import_batch_id_external_import_batches_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_import_batches", + "columnsFrom": [ + "last_accepted_import_batch_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk": { + "name": "external_model_objects_external_room_mapping_id_external_room_mappings_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "external_room_mappings", + "columnsFrom": [ + "external_room_mapping_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_distribution_board_id_distribution_boards_id_fk": { + "name": "external_model_objects_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "distribution_boards", + "columnsFrom": [ + "distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_linked_project_device_id_project_devices_id_fk": { + "name": "external_model_objects_linked_project_device_id_project_devices_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "project_devices", + "columnsFrom": [ + "linked_project_device_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk": { + "name": "external_model_objects_circuit_device_row_id_circuit_device_rows_id_fk", + "tableFrom": "external_model_objects", + "tableTo": "circuit_device_rows", + "columnsFrom": [ + "circuit_device_row_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_model_sources": { + "name": "external_model_sources", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'revit_xlsx'" + } + }, + "indexes": { + "external_model_sources_project_unique": { + "name": "external_model_sources_project_unique", + "columns": [ + "project_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "external_model_sources_project_id_projects_id_fk": { + "name": "external_model_sources_project_id_projects_id_fk", + "tableFrom": "external_model_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "external_room_mappings": { + "name": "external_room_mappings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "normalized_source_room_key": { + "name": "normalized_source_room_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_floor_name": { + "name": "source_floor_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_room_number": { + "name": "source_room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_room_name": { + "name": "source_room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_id": { + "name": "room_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_distribution_board_id": { + "name": "default_distribution_board_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "external_room_mappings_source_key_unique": { + "name": "external_room_mappings_source_key_unique", + "columns": [ + "source_id", + "normalized_source_room_key" + ], + "isUnique": true + }, + "external_room_mappings_project_room_idx": { + "name": "external_room_mappings_project_room_idx", + "columns": [ + "project_id", + "room_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "external_room_mappings_project_id_projects_id_fk": { + "name": "external_room_mappings_project_id_projects_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_source_id_external_model_sources_id_fk": { + "name": "external_room_mappings_source_id_external_model_sources_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "external_model_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "external_room_mappings_room_id_rooms_id_fk": { + "name": "external_room_mappings_room_id_rooms_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "rooms", + "columnsFrom": [ + "room_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk": { + "name": "external_room_mappings_default_distribution_board_id_distribution_boards_id_fk", + "tableFrom": "external_room_mappings", + "tableTo": "distribution_boards", + "columnsFrom": [ + "default_distribution_board_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "floors": { + "name": "floors", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "building_id": { + "name": "building_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "floors_project_id_projects_id_fk": { + "name": "floors_project_id_projects_id_fk", + "tableFrom": "floors", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "floors_building_id_buildings_id_fk": { + "name": "floors_building_id_buildings_id_fk", + "tableFrom": "floors", + "tableTo": "buildings", + "columnsFrom": [ + "building_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "global_devices": { + "name": "global_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installed_power_per_unit_kw": { + "name": "installed_power_per_unit_kw", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "demand_factor": { + "name": "demand_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phase_count": { + "name": "phase_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_factor": { + "name": "power_factor", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_change_sets": { + "name": "project_change_sets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_revision_id": { + "name": "project_revision_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command_type": { + "name": "command_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_schema_version": { + "name": "payload_schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "forward_payload_json": { + "name": "forward_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "inverse_payload_json": { + "name": "inverse_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_change_sets_revision_unique": { + "name": "project_change_sets_revision_unique", + "columns": [ + "project_revision_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_change_sets_project_revision_id_project_revisions_id_fk": { + "name": "project_change_sets_project_revision_id_project_revisions_id_fk", + "tableFrom": "project_change_sets", + "tableTo": "project_revisions", + "columnsFrom": [ + "project_revision_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_devices": { + "name": "project_devices", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase_type": { + "name": "phase_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'single_phase'" + }, + "connection_kind": { + "name": "connection_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_group": { + "name": "cost_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "power_per_unit": { + "name": "power_per_unit", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "simultaneity_factor": { + "name": "simultaneity_factor", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "cos_phi": { + "name": "cos_phi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "voltage_v": { + "name": "voltage_v", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "project_devices_project_id_projects_id_fk": { + "name": "project_devices_project_id_projects_id_fk", + "tableFrom": "project_devices", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_history_stack_entries": { + "name": "project_history_stack_entries", + "columns": { + "change_set_id": { + "name": "change_set_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "project_history_stack_entries_position_unique": { + "name": "project_history_stack_entries_position_unique", + "columns": [ + "project_id", + "stack", + "position" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_history_stack_entries_change_set_id_project_change_sets_id_fk": { + "name": "project_history_stack_entries_change_set_id_project_change_sets_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "project_change_sets", + "columnsFrom": [ + "change_set_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_history_stack_entries_project_id_projects_id_fk": { + "name": "project_history_stack_entries_project_id_projects_id_fk", + "tableFrom": "project_history_stack_entries", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "project_history_stack_entries_stack_check": { + "name": "project_history_stack_entries_stack_check", + "value": "\"project_history_stack_entries\".\"stack\" in ('undo', 'redo')" + } + } + }, + "project_revisions": { + "name": "project_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision_number": { + "name": "revision_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_revisions_project_number_unique": { + "name": "project_revisions_project_number_unique", + "columns": [ + "project_id", + "revision_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_revisions_project_id_projects_id_fk": { + "name": "project_revisions_project_id_projects_id_fk", + "tableFrom": "project_revisions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_snapshots": { + "name": "project_snapshots", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_revision": { + "name": "source_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'named'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_sha256": { + "name": "payload_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at_iso": { + "name": "created_at_iso", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_actor_id": { + "name": "created_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_snapshots_project_created_idx": { + "name": "project_snapshots_project_created_idx", + "columns": [ + "project_id", + "created_at_iso" + ], + "isUnique": false + }, + "project_snapshots_project_kind_revision_idx": { + "name": "project_snapshots_project_kind_revision_idx", + "columns": [ + "project_id", + "kind", + "source_revision" + ], + "isUnique": false + }, + "project_snapshots_project_name_unique": { + "name": "project_snapshots_project_name_unique", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_snapshots_project_id_projects_id_fk": { + "name": "project_snapshots_project_id_projects_id_fk", + "tableFrom": "project_snapshots", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "internal_project_number": { + "name": "internal_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "external_project_number": { + "name": "external_project_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "building_owner": { + "name": "building_owner", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_public_building": { + "name": "is_public_building", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "single_phase_voltage_v": { + "name": "single_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 230 + }, + "three_phase_voltage_v": { + "name": "three_phase_voltage_v", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 400 + }, + "enabled_distribution_board_supply_types": { + "name": "enabled_distribution_board_supply_types", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"AV\",\"SV\",\"EV\",\"USV\",\"MSR\",\"SiBe\"]'" + }, + "site_address": { + "name": "site_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "work_stage": { + "name": "work_stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_lead": { + "name": "project_lead", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_editor": { + "name": "project_editor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "current_revision": { + "name": "current_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "rooms": { + "name": "rooms", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "floor_id": { + "name": "floor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "room_number": { + "name": "room_number", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_name": { + "name": "room_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "area_m2": { + "name": "area_m2", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "rooms_project_id_projects_id_fk": { + "name": "rooms_project_id_projects_id_fk", + "tableFrom": "rooms", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "rooms_floor_id_floors_id_fk": { + "name": "rooms_floor_id_floors_id_fk", + "tableFrom": "rooms", + "tableTo": "floors", + "columnsFrom": [ + "floor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'user'" + }, + "active": { + "name": "active", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "must_change_password": { + "name": "must_change_password", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "users_username_unique": { + "name": "users_username_unique", + "columns": [ + "username" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index 2a2e076..0f6c303 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -99,6 +99,13 @@ "when": 1790624623732, "tag": "0013_users", "breakpoints": true + }, + { + "idx": 14, + "version": "6", + "when": 1790748107566, + "tag": "0014_linear_xlsx_external_model", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/repositories/external-csv-configuration-project-command.repository.ts b/src/db/repositories/external-csv-configuration-project-command.repository.ts deleted file mode 100644 index c7d7bf7..0000000 --- a/src/db/repositories/external-csv-configuration-project-command.repository.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { eq } from "drizzle-orm"; -import { - assertExternalCsvConfigurationUpdateProjectCommand, - createExternalCsvConfigurationUpdateProjectCommand, - type ExternalCsvConfigurationSnapshot, -} from "../../domain/models/external-csv-configuration-project-command.model.js"; -import type { - ExecuteExternalCsvConfigurationCommandInput, - ExternalCsvConfigurationProjectCommandStore, -} from "../../domain/ports/external-csv-configuration-project-command.store.js"; -import type { AppDatabase } from "../database-context.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; -import { projects } from "../schema/projects.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; - -export class ExternalCsvConfigurationProjectCommandRepository - implements ExternalCsvConfigurationProjectCommandStore -{ - constructor(private readonly database: AppDatabase) {} - - execute(input: ExecuteExternalCsvConfigurationCommandInput) { - assertExternalCsvConfigurationUpdateProjectCommand(input.command); - return executeProjectCommandTransaction(this.database, input, (tx) => { - const project = tx - .select({ id: projects.id }) - .from(projects) - .where(eq(projects.id, input.projectId)) - .get(); - if (!project) { - throw new Error("Project not found."); - } - const current = tx - .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, input.projectId)) - .get() ?? null; - assertSameSnapshot(current, input.command.payload.expected); - const target = input.command.payload.target; - if (target !== null && target.projectId !== input.projectId) { - throw new Error("External CSV configuration belongs to a different project."); - } - if (sameSnapshot(current, target)) { - throw new Error("External CSV configuration did not change."); - } - if ( - input.source === "user" && - target !== null && - target.configurationVersion !== (current?.configurationVersion ?? 0) + 1 - ) { - throw new Error("External CSV configuration version must advance by one."); - } - - if (target === null) { - tx.delete(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, input.projectId)) - .run(); - } else if (current === null) { - tx.insert(externalCsvConfigurations).values(target).run(); - } else { - const updated = tx - .update(externalCsvConfigurations) - .set({ - configurationVersion: target.configurationVersion, - configuration: target.configuration, - }) - .where(eq(externalCsvConfigurations.id, current.id)) - .run(); - if (updated.changes !== 1) { - throw new Error("External CSV configuration changed before update."); - } - } - return createExternalCsvConfigurationUpdateProjectCommand(target, current); - }); - } -} - -function assertSameSnapshot( - current: ExternalCsvConfigurationSnapshot | null, - expected: ExternalCsvConfigurationSnapshot | null -) { - if (!sameSnapshot(current, expected)) { - throw new Error("External CSV configuration changed before update."); - } -} - -function sameSnapshot( - left: ExternalCsvConfigurationSnapshot | null, - right: ExternalCsvConfigurationSnapshot | null -) { - return canonicalJson(left) === canonicalJson(right); -} - -function canonicalJson(value: unknown): string { - if (Array.isArray(value)) { - return `[${value.map(canonicalJson).join(",")}]`; - } - if (value !== null && typeof value === "object") { - const record = value as Record; - return `{${Object.keys(record) - .sort() - .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`) - .join(",")}}`; - } - return JSON.stringify(value); -} diff --git a/src/db/repositories/external-initial-import-project-command.repository.ts b/src/db/repositories/external-initial-import-project-command.repository.ts deleted file mode 100644 index 1f2281e..0000000 --- a/src/db/repositories/external-initial-import-project-command.repository.ts +++ /dev/null @@ -1,252 +0,0 @@ -import crypto from "node:crypto"; -import { eq } from "drizzle-orm"; -import { - assertExternalInitialImportProjectCommand, - createExternalInitialImportProjectCommand, - isEmptyExternalModelState, -} from "../../domain/models/external-initial-import-project-command.model.js"; -import type { ExternalInitialImportProjectCommandStore } from "../../domain/ports/external-initial-import-project-command.store.js"; -import { createExternalCsvPreview } from "../../external-model/application/external-csv-preview.js"; -import { parseExternalCsv } from "../../external-model/csv/external-csv-transport.js"; -import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; -import { - createExternalRoomKey, - indexExternalObjectsByIfcGuid, - projectInitialExternalObject, -} from "../../external-model/domain/external-model-matching.js"; -import type { AppDatabase } from "../database-context.js"; -import { distributionBoards } from "../schema/distribution-boards.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; -import { externalImportBatches } from "../schema/external-import-batches.js"; -import { externalModelObjects } from "../schema/external-model-objects.js"; -import { externalModelSources } from "../schema/external-model-sources.js"; -import { externalRoomMappings } from "../schema/external-room-mappings.js"; -import { projectDevices } from "../schema/project-devices.js"; -import { rooms } from "../schema/rooms.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; -import { ExternalModelStateRepository } from "./external-model-state.repository.js"; - -export class ExternalInitialImportProjectCommandRepository - implements ExternalInitialImportProjectCommandStore -{ - constructor(private readonly database: AppDatabase) {} - - execute(input: Parameters[0]) { - assertExternalInitialImportProjectCommand(input.command); - return executeProjectCommandTransaction(this.database, input, (tx) => { - const currentResult = new ExternalModelStateRepository(tx) - .getByProject(input.projectId); - if (!currentResult.projectExists) throw new Error("Project not found."); - const expected = input.command.payload.expected; - if (!sameState(currentResult.state, expected)) { - throw new Error("External model state changed before initial import."); - } - const target = input.command.payload.target; - if (!isEmptyExternalModelState(target)) { - validatePopulatedTarget(tx, input, target); - } - - replaceExternalState(tx, input.projectId, target); - const persisted = new ExternalModelStateRepository(tx) - .getByProject(input.projectId).state; - if (!sameState(persisted, target)) { - throw new Error("Persisted external initial import differs from its target."); - } - return createExternalInitialImportProjectCommand(target, currentResult.state); - }); - } -} - -function validatePopulatedTarget( - database: AppDatabase, - input: Parameters[0], - target: ExternalModelStateSnapshot -) { - const source = target.source!; - const batch = target.importBatches[0]; - if (source.projectId !== input.projectId) { - throw new Error("External initial import belongs to a different project."); - } - if ( - input.source === "user" && - batch.appliedProjectRevision !== input.expectedRevision + 1 - ) { - throw new Error("External initial import revision is invalid."); - } - const configuration = database - .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, input.projectId)) - .get(); - if ( - !configuration || - configuration.configurationVersion !== batch.configurationVersion || - canonicalJson(configuration.configuration) !== - canonicalJson(batch.configurationSnapshot) - ) { - throw new Error("External initial import configuration changed before apply."); - } - - const bytes = decodeCanonicalBase64(batch.originalContentBase64); - const sha256 = crypto.createHash("sha256").update(bytes).digest("hex"); - if (sha256 !== batch.sha256) { - throw new Error("External initial import checksum is invalid."); - } - const parsedDocument = parseExternalCsv(bytes, batch.configurationSnapshot); - if (canonicalJson(parsedDocument) !== canonicalJson(batch.document)) { - throw new Error("External initial import document differs from the original bytes."); - } - const preview = createExternalCsvPreview({ - fileName: batch.fileName, - bytes, - configuration: batch.configurationSnapshot, - }); - const targetByIfcGuid = indexExternalObjectsByIfcGuid(target.objects); - if (targetByIfcGuid.size !== preview.objects.length) { - throw new Error("External initial import must contain every CSV object exactly once."); - } - const mappingsById = new Map( - target.roomMappings.map((mapping) => [mapping.id, mapping]) - ); - const expectedRoomKeys = new Set(); - for (const candidate of preview.objects) { - const object = targetByIfcGuid.get(candidate.ifcGuid); - if (!object) { - throw new Error(`External initial import is missing IFCGUID ${candidate.ifcGuid}.`); - } - const projected = projectInitialExternalObject( - candidate, - batch.configurationSnapshot - ); - if (canonicalJson(object.acceptedSourceValues) !== canonicalJson(projected.sourceValues)) { - throw new Error("External initial import source values differ from the CSV."); - } - for (const field of Object.keys(projected.planningValues) as Array) { - if ( - !object.overriddenFields.includes(field) && - canonicalJson(object.planningValues[field]) !== - canonicalJson(projected.planningValues[field]) - ) { - throw new Error(`External initial planning field ${field} changed without an override.`); - } - } - const roomKey = createExternalRoomKey(candidate.roomNumber, candidate.roomName); - if (roomKey === null) { - if (object.externalRoomMappingId !== null) { - throw new Error("External object without a source room must not use a room mapping."); - } - } else { - expectedRoomKeys.add(roomKey); - const mapping = object.externalRoomMappingId === null - ? null - : mappingsById.get(object.externalRoomMappingId); - if (!mapping || mapping.normalizedSourceRoomKey !== roomKey) { - throw new Error("External object source room mapping is incomplete."); - } - } - } - if ( - target.roomMappings.length !== expectedRoomKeys.size || - target.roomMappings.some( - (mapping) => !expectedRoomKeys.has(mapping.normalizedSourceRoomKey) - ) - ) { - throw new Error("External initial import room mappings do not match CSV rooms."); - } - validateInternalLinks(database, input.projectId, target); -} - -function validateInternalLinks( - database: AppDatabase, - projectId: string, - target: ExternalModelStateSnapshot -) { - const roomIds = new Set( - database.select({ id: rooms.id }).from(rooms) - .where(eq(rooms.projectId, projectId)).all().map((row) => row.id) - ); - const boardIds = new Set( - database.select({ id: distributionBoards.id }).from(distributionBoards) - .where(eq(distributionBoards.projectId, projectId)).all().map((row) => row.id) - ); - const deviceIds = new Set( - database.select({ id: projectDevices.id }).from(projectDevices) - .where(eq(projectDevices.projectId, projectId)).all().map((row) => row.id) - ); - for (const mapping of target.roomMappings) { - if (mapping.roomId !== null && !roomIds.has(mapping.roomId)) { - throw new Error("External room mapping references another project."); - } - if ( - mapping.defaultDistributionBoardId !== null && - !boardIds.has(mapping.defaultDistributionBoardId) - ) { - throw new Error("External room mapping distribution board belongs to another project."); - } - } - for (const object of target.objects) { - if (object.distributionBoardId !== null && !boardIds.has(object.distributionBoardId)) { - throw new Error("External object distribution board belongs to another project."); - } - if (object.linkedProjectDeviceId !== null && !deviceIds.has(object.linkedProjectDeviceId)) { - throw new Error("External object project device belongs to another project."); - } - } -} - -function replaceExternalState( - database: AppDatabase, - projectId: string, - target: ExternalModelStateSnapshot -) { - database.delete(externalModelSources) - .where(eq(externalModelSources.projectId, projectId)).run(); - if (target.source === null) return; - database.insert(externalModelSources).values(target.source).run(); - database.insert(externalImportBatches).values( - target.importBatches.map(({ originalContentBase64, ...batch }) => ({ - ...batch, - originalBytes: Buffer.from(originalContentBase64, "base64"), - })) - ).run(); - if (target.roomMappings.length) { - database.insert(externalRoomMappings).values(target.roomMappings).run(); - } - if (target.objects.length) { - database.insert(externalModelObjects).values(target.objects).run(); - } -} - -function decodeCanonicalBase64(value: string) { - const bytes = Buffer.from(value, "base64"); - if (bytes.toString("base64") !== value) { - throw new Error("External initial import bytes are not canonical base64."); - } - return bytes; -} - -function sameState(left: ExternalModelStateSnapshot, right: ExternalModelStateSnapshot) { - return canonicalJson(sortState(left)) === canonicalJson(sortState(right)); -} - -function sortState(state: ExternalModelStateSnapshot): ExternalModelStateSnapshot { - const byId = (entries: readonly T[]) => - [...entries].sort((left, right) => left.id.localeCompare(right.id)); - return { - source: state.source, - importBatches: byId(state.importBatches), - roomMappings: byId(state.roomMappings), - objects: byId(state.objects), - }; -} - -function canonicalJson(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; - if (value !== null && typeof value === "object") { - const record = value as Record; - return `{${Object.keys(record).sort().map( - (key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}` - ).join(",")}}`; - } - return JSON.stringify(value); -} diff --git a/src/db/repositories/external-model-configuration-project-command.repository.ts b/src/db/repositories/external-model-configuration-project-command.repository.ts new file mode 100644 index 0000000..881cc8a --- /dev/null +++ b/src/db/repositories/external-model-configuration-project-command.repository.ts @@ -0,0 +1,79 @@ +import { eq } from "drizzle-orm"; +import { + assertExternalModelConfigurationUpdateProjectCommand, + createExternalModelConfigurationUpdateProjectCommand, + type ExternalModelConfigurationSnapshot, +} from "../../domain/models/external-model-configuration-project-command.model.js"; +import type { + ExecuteExternalModelConfigurationCommandInput, + ExternalModelConfigurationProjectCommandStore, +} from "../../domain/ports/external-model-configuration-project-command.store.js"; +import type { AppDatabase } from "../database-context.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; +import { projects } from "../schema/projects.js"; +import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; + +export class ExternalModelConfigurationProjectCommandRepository + implements ExternalModelConfigurationProjectCommandStore { + constructor(private readonly database: AppDatabase) {} + + execute(input: ExecuteExternalModelConfigurationCommandInput) { + assertExternalModelConfigurationUpdateProjectCommand(input.command); + return executeProjectCommandTransaction(this.database, input, (tx) => { + const project = tx.select({ id: projects.id }).from(projects) + .where(eq(projects.id, input.projectId)).get(); + if (!project) throw new Error("Project not found."); + const current = tx.select().from(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, input.projectId)).get() ?? null; + assertSameSnapshot(current, input.command.payload.expected); + const target = input.command.payload.target; + if (target !== null && target.projectId !== input.projectId) { + throw new Error("Die Revit-XLSX-Konfiguration gehört zu einem anderen Projekt."); + } + if (sameSnapshot(current, target)) { + throw new Error("Die Revit-XLSX-Konfiguration wurde nicht geändert."); + } + if (target === null) { + tx.delete(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, input.projectId)).run(); + } else if (current === null) { + tx.insert(externalModelConfigurations).values(target).run(); + } else { + const updated = tx.update(externalModelConfigurations) + .set({ configuration: target.configuration }) + .where(eq(externalModelConfigurations.id, current.id)).run(); + if (updated.changes !== 1) { + throw new Error("Die Revit-XLSX-Konfiguration wurde zwischenzeitlich geändert."); + } + } + return createExternalModelConfigurationUpdateProjectCommand(target, current); + }); + } +} + +function assertSameSnapshot( + current: ExternalModelConfigurationSnapshot | null, + expected: ExternalModelConfigurationSnapshot | null +) { + if (!sameSnapshot(current, expected)) { + throw new Error("Die Revit-XLSX-Konfiguration wurde zwischenzeitlich geändert."); + } +} + +function sameSnapshot( + left: ExternalModelConfigurationSnapshot | null, + right: ExternalModelConfigurationSnapshot | null +) { + return canonicalJson(left) === canonicalJson(right); +} + +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (value !== null && typeof value === "object") { + const record = value as Record; + return `{${Object.keys(record).sort().map( + (key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}` + ).join(",")}}`; + } + return JSON.stringify(value); +} diff --git a/src/db/repositories/external-csv-configuration.repository.ts b/src/db/repositories/external-model-configuration.repository.ts similarity index 51% rename from src/db/repositories/external-csv-configuration.repository.ts rename to src/db/repositories/external-model-configuration.repository.ts index 2b39a65..7cbacab 100644 --- a/src/db/repositories/external-csv-configuration.repository.ts +++ b/src/db/repositories/external-model-configuration.repository.ts @@ -1,12 +1,11 @@ import { eq } from "drizzle-orm"; -import type { ExternalCsvConfigurationReader } from "../../domain/ports/external-csv-configuration.reader.js"; +import type { ExternalModelConfigurationReader } from "../../domain/ports/external-model-configuration.reader.js"; import type { AppDatabase } from "../database-context.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; import { projects } from "../schema/projects.js"; -export class ExternalCsvConfigurationRepository - implements ExternalCsvConfigurationReader -{ +export class ExternalModelConfigurationRepository + implements ExternalModelConfigurationReader { constructor(private readonly database: AppDatabase) {} getByProject(projectId: string) { @@ -15,13 +14,11 @@ export class ExternalCsvConfigurationRepository .from(projects) .where(eq(projects.id, projectId)) .get(); - if (!project) { - return { projectExists: false, configuration: null }; - } + if (!project) return { projectExists: false, configuration: null }; const configuration = this.database .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, projectId)) + .from(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, projectId)) .get() ?? null; return { projectExists: true, configuration }; } diff --git a/src/db/repositories/external-model-state.repository.ts b/src/db/repositories/external-model-state.repository.ts index 36079c9..c2adb7c 100644 --- a/src/db/repositories/external-model-state.repository.ts +++ b/src/db/repositories/external-model-state.repository.ts @@ -55,7 +55,10 @@ export class ExternalModelStateRepository implements ExternalModelStateReader { .select() .from(externalModelObjects) .where(eq(externalModelObjects.sourceId, source.id)) - .orderBy(asc(externalModelObjects.ifcGuid), asc(externalModelObjects.id)) + .orderBy( + asc(externalModelObjects.worksharingId), + asc(externalModelObjects.id) + ) .all(); return { @@ -64,7 +67,10 @@ export class ExternalModelStateRepository implements ExternalModelStateReader { source, importBatches: batches.map(({ originalBytes, ...batch }) => ({ ...batch, - originalContentBase64: Buffer.from(originalBytes).toString("base64"), + originalContentBase64: + originalBytes === null + ? null + : Buffer.from(originalBytes).toString("base64"), })), roomMappings, objects, diff --git a/src/db/repositories/external-object-assignment.persistence.ts b/src/db/repositories/external-object-assignment.persistence.ts index ddc9891..1111730 100644 --- a/src/db/repositories/external-object-assignment.persistence.ts +++ b/src/db/repositories/external-object-assignment.persistence.ts @@ -51,7 +51,7 @@ export function assertExternalObjectsCompatibleWithRow(input: { const roomIdByMappingId = new Map(mappings.map((mapping) => [mapping.id, mapping.roomId])); const markers = new Set( input.allLinkedObjects.map((object) => - object.acceptedSourceValues.selectionMarker.trim() + scalarText(object.acceptedSourceValues.selectionMarker).trim() ) ); if (markers.size > 1) { @@ -118,13 +118,17 @@ function matchesRowPlanningValues( row.category === planning.category && row.connectionKind === planning.connectionKind && (planning.powerPerUnitW === null || row.powerPerUnit === planning.powerPerUnitW / 1000) && - row.simultaneityFactor === planning.simultaneityFactor && + row.simultaneityFactor === (planning.simultaneityFactor ?? 1) && row.cosPhi === planning.cosPhi && row.costGroup === planning.costGroup && row.remark === planning.remark ); } +function scalarText(value: string | number | boolean | null) { + return value === null ? "" : String(value); +} + function canonicalJson(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (value !== null && typeof value === "object") { diff --git a/src/db/repositories/project-state-restore-command.repository.ts b/src/db/repositories/project-state-restore-command.repository.ts index 386d805..006b742 100644 --- a/src/db/repositories/project-state-restore-command.repository.ts +++ b/src/db/repositories/project-state-restore-command.repository.ts @@ -31,7 +31,7 @@ import { projectDevices } from "../schema/project-devices.js"; import { projectChangeSets } from "../schema/project-change-sets.js"; import { projects } from "../schema/projects.js"; import { rooms } from "../schema/rooms.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; import { externalImportBatches } from "../schema/external-import-batches.js"; import { externalModelObjects } from "../schema/external-model-objects.js"; import { externalModelSources } from "../schema/external-model-sources.js"; @@ -241,7 +241,7 @@ function canonicalProjectState(state: ProjectStateSnapshot) { buildings: byId(state.buildings), floors: byId(state.floors), rooms: byId(state.rooms), - externalCsvConfiguration: state.externalCsvConfiguration, + externalModelConfiguration: state.externalModelConfiguration, externalModel: { source: state.externalModel.source, importBatches: byId(state.externalModel.importBatches), @@ -283,8 +283,8 @@ function replaceProjectState( .where(eq(externalModelSources.projectId, state.project.id)) .run(); database - .delete(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, state.project.id)) + .delete(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, state.project.id)) .run(); database .delete(distributionBoards) @@ -330,10 +330,10 @@ function replaceProjectState( insertMany(database, buildings, state.buildings); insertMany(database, floors, state.floors); - if (state.externalCsvConfiguration !== null) { + if (state.externalModelConfiguration !== null) { database - .insert(externalCsvConfigurations) - .values(state.externalCsvConfiguration) + .insert(externalModelConfigurations) + .values(state.externalModelConfiguration) .run(); } insertMany(database, rooms, state.rooms); @@ -387,7 +387,10 @@ function replaceProjectState( state.externalModel.importBatches.map( ({ originalContentBase64, ...batch }) => ({ ...batch, - originalBytes: Buffer.from(originalContentBase64, "base64"), + originalBytes: + originalContentBase64 === null + ? null + : Buffer.from(originalContentBase64, "base64"), }) ) ); diff --git a/src/db/repositories/project-state-snapshot.persistence.ts b/src/db/repositories/project-state-snapshot.persistence.ts index a11cd58..431241b 100644 --- a/src/db/repositories/project-state-snapshot.persistence.ts +++ b/src/db/repositories/project-state-snapshot.persistence.ts @@ -20,7 +20,7 @@ import { floors } from "../schema/floors.js"; import { projectDevices } from "../schema/project-devices.js"; import { projects } from "../schema/projects.js"; import { rooms } from "../schema/rooms.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; import { ExternalModelStateRepository } from "./external-model-state.repository.js"; export interface PersistedProjectStateSnapshot { @@ -66,10 +66,10 @@ export function readProjectStateSnapshot( .where(eq(distributionBoards.projectId, projectId)) .orderBy(asc(distributionBoards.name), asc(distributionBoards.id)) .all(); - const externalCsvConfiguration = database + const externalModelConfiguration = database .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, projectId)) + .from(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, projectId)) .get() ?? null; const externalModel = new ExternalModelStateRepository(database) .getByProject(projectId).state; @@ -266,7 +266,7 @@ export function readProjectStateSnapshot( projectEditor: project.projectEditor, }, distributionBoards: boardRows, - externalCsvConfiguration, + externalModelConfiguration, externalModel, circuitLists: listRows, circuitSections: sectionRows, diff --git a/src/db/repositories/project-transfer.repository.ts b/src/db/repositories/project-transfer.repository.ts index 1d93afd..fc73db5 100644 --- a/src/db/repositories/project-transfer.repository.ts +++ b/src/db/repositories/project-transfer.repository.ts @@ -23,7 +23,7 @@ import { floors } from "../schema/floors.js"; import { projectDevices } from "../schema/project-devices.js"; import { projects } from "../schema/projects.js"; import { rooms } from "../schema/rooms.js"; -import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; import { externalImportBatches } from "../schema/external-import-batches.js"; import { externalModelObjects } from "../schema/external-model-objects.js"; import { externalModelSources } from "../schema/external-model-sources.js"; @@ -163,10 +163,10 @@ function insertProjectState( .insert(projects) .values({ ...state.project, currentRevision: 0 }) .run(); - if (state.externalCsvConfiguration !== null) { + if (state.externalModelConfiguration !== null) { database - .insert(externalCsvConfigurations) - .values(state.externalCsvConfiguration) + .insert(externalModelConfigurations) + .values(state.externalModelConfiguration) .run(); } insertMany(database, buildings, state.buildings); @@ -240,7 +240,10 @@ function insertProjectState( state.externalModel.importBatches.map( ({ originalContentBase64, ...batch }) => ({ ...batch, - originalBytes: Buffer.from(originalContentBase64, "base64"), + originalBytes: + originalContentBase64 === null + ? null + : Buffer.from(originalContentBase64, "base64"), }) ) ); diff --git a/src/db/schema/external-csv-configurations.ts b/src/db/schema/external-csv-configurations.ts deleted file mode 100644 index 2cbcd06..0000000 --- a/src/db/schema/external-csv-configurations.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; -import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts.js"; -import { projects } from "./projects.js"; - -export const externalCsvConfigurations = sqliteTable( - "external_csv_configurations", - { - id: text("id").primaryKey(), - projectId: text("project_id") - .notNull() - .references(() => projects.id, { onDelete: "cascade" }), - configurationVersion: integer("configuration_version").notNull(), - configuration: text("configuration", { mode: "json" }) - .$type() - .notNull(), - }, - (table) => [ - uniqueIndex("external_csv_configurations_project_id_unique").on( - table.projectId - ), - ] -); diff --git a/src/db/schema/external-import-batches.ts b/src/db/schema/external-import-batches.ts index 125077e..0919891 100644 --- a/src/db/schema/external-import-batches.ts +++ b/src/db/schema/external-import-batches.ts @@ -1,9 +1,7 @@ import { blob, index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import type { - ExternalCsvConfiguration, - ExternalCsvDocument, -} from "../../external-model/csv/external-csv-contracts.js"; +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; import { externalImportKinds } from "../../external-model/domain/external-model-contracts.js"; +import type { ExternalXlsxDocument } from "../../external-model/xlsx/external-xlsx-contracts.js"; import { externalModelSources } from "./external-model-sources.js"; import { projects } from "./projects.js"; @@ -21,15 +19,13 @@ export const externalImportBatches = sqliteTable( importedAtIso: text("imported_at_iso").notNull(), fileName: text("file_name").notNull(), sha256: text("sha256").notNull(), - appliedProjectRevision: integer("applied_project_revision").notNull(), - configurationVersion: integer("configuration_version").notNull(), + objectCount: integer("object_count").notNull(), + appliedProjectRevision: integer("applied_project_revision"), configurationSnapshot: text("configuration_snapshot", { mode: "json" }) - .$type() - .notNull(), - originalBytes: blob("original_bytes", { mode: "buffer" }).notNull(), + .$type(), + originalBytes: blob("original_bytes", { mode: "buffer" }), document: text("document", { mode: "json" }) - .$type() - .notNull(), + .$type(), }, (table) => [ index("external_import_batches_project_revision_idx").on( diff --git a/src/db/schema/external-model-configurations.ts b/src/db/schema/external-model-configurations.ts new file mode 100644 index 0000000..e28ced7 --- /dev/null +++ b/src/db/schema/external-model-configurations.ts @@ -0,0 +1,21 @@ +import { sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; +import { projects } from "./projects.js"; + +export const externalModelConfigurations = sqliteTable( + "external_model_configurations", + { + id: text("id").primaryKey(), + projectId: text("project_id") + .notNull() + .references(() => projects.id, { onDelete: "cascade" }), + configuration: text("configuration", { mode: "json" }) + .$type() + .notNull(), + }, + (table) => [ + uniqueIndex("external_model_configurations_project_id_unique").on( + table.projectId + ), + ] +); diff --git a/src/db/schema/external-model-objects.ts b/src/db/schema/external-model-objects.ts index fbd50b7..2de80cb 100644 --- a/src/db/schema/external-model-objects.ts +++ b/src/db/schema/external-model-objects.ts @@ -23,7 +23,9 @@ export const externalModelObjects = sqliteTable( sourceId: text("source_id") .notNull() .references(() => externalModelSources.id, { onDelete: "cascade" }), - ifcGuid: text("ifc_guid").notNull(), + worksharingId: text("worksharing_id").notNull(), + ifcGuid: text("ifc_guid"), + deviceTypeId: text("device_type_id").notNull(), lastSeenImportBatchId: text("last_seen_import_batch_id") .notNull() .references(() => externalImportBatches.id, { onDelete: "restrict" }), @@ -62,17 +64,27 @@ export const externalModelObjects = sqliteTable( .default("present"), }, (table) => [ - uniqueIndex("external_model_objects_source_ifc_guid_unique").on( + uniqueIndex("external_model_objects_source_worksharing_id_unique").on( table.sourceId, - table.ifcGuid + table.worksharingId ), index("external_model_objects_project_presence_idx").on( table.projectId, table.presenceStatus ), + index("external_model_objects_project_device_type_idx").on( + table.projectId, + table.deviceTypeId + ), + index("external_model_objects_external_room_mapping_idx").on( + table.externalRoomMappingId + ), index("external_model_objects_distribution_board_idx").on( table.distributionBoardId ), + index("external_model_objects_linked_project_device_idx").on( + table.linkedProjectDeviceId + ), index("external_model_objects_circuit_device_row_idx").on( table.circuitDeviceRowId ), diff --git a/src/db/schema/external-model-sources.ts b/src/db/schema/external-model-sources.ts index a4f9ded..7dfb3d1 100644 --- a/src/db/schema/external-model-sources.ts +++ b/src/db/schema/external-model-sources.ts @@ -12,12 +12,9 @@ export const externalModelSources = sqliteTable( name: text("name").notNull(), sourceType: text("source_type", { enum: externalModelSourceTypes }) .notNull() - .default("revit_csv"), + .default("revit_xlsx"), }, (table) => [ - uniqueIndex("external_model_sources_project_type_unique").on( - table.projectId, - table.sourceType - ), + uniqueIndex("external_model_sources_project_unique").on(table.projectId), ] ); diff --git a/src/domain/models/external-csv-configuration-project-command.model.ts b/src/domain/models/external-csv-configuration-project-command.model.ts deleted file mode 100644 index bb87342..0000000 --- a/src/domain/models/external-csv-configuration-project-command.model.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { assertExternalCsvConfiguration } from "../../external-model/csv/external-csv-configuration.js"; -import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts.js"; -import type { SerializedProjectCommand } from "./project-command.model.js"; - -export const externalCsvConfigurationUpdateCommandType = - "external-csv-configuration.update" as const; -export const externalCsvConfigurationCommandSchemaVersion = 1 as const; - -export interface ExternalCsvConfigurationSnapshot { - id: string; - projectId: string; - configurationVersion: number; - configuration: ExternalCsvConfiguration; -} - -export interface ExternalCsvConfigurationUpdatePayload { - expected: ExternalCsvConfigurationSnapshot | null; - target: ExternalCsvConfigurationSnapshot | null; -} - -export interface ExternalCsvConfigurationUpdateProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof externalCsvConfigurationCommandSchemaVersion; - type: typeof externalCsvConfigurationUpdateCommandType; -} - -export function createExternalCsvConfigurationUpdateProjectCommand( - expected: ExternalCsvConfigurationSnapshot | null, - target: ExternalCsvConfigurationSnapshot | null -): ExternalCsvConfigurationUpdateProjectCommand { - const command: ExternalCsvConfigurationUpdateProjectCommand = { - schemaVersion: externalCsvConfigurationCommandSchemaVersion, - type: externalCsvConfigurationUpdateCommandType, - payload: { expected, target }, - }; - assertExternalCsvConfigurationUpdateProjectCommand(command); - return command; -} - -export function assertExternalCsvConfigurationUpdateProjectCommand( - command: SerializedProjectCommand -): asserts command is ExternalCsvConfigurationUpdateProjectCommand { - if ( - command.schemaVersion !== externalCsvConfigurationCommandSchemaVersion || - command.type !== externalCsvConfigurationUpdateCommandType || - !isRecord(command.payload) - ) { - throw new Error("Unsupported external CSV configuration update command."); - } - assertSnapshot(command.payload.expected, "expected"); - assertSnapshot(command.payload.target, "target"); - if (command.payload.expected === null && command.payload.target === null) { - throw new Error("External CSV configuration command must change state."); - } - if ( - command.payload.expected !== null && - command.payload.target !== null && - (command.payload.expected.id !== command.payload.target.id || - command.payload.expected.projectId !== command.payload.target.projectId) - ) { - throw new Error("External CSV configuration identity must remain stable."); - } -} - -function assertSnapshot( - value: unknown, - field: string -): asserts value is ExternalCsvConfigurationSnapshot | null { - if (value === null) { - return; - } - if (!isRecord(value)) { - throw new Error(`${field} external CSV configuration must be an object or null.`); - } - assertId(value.id, `${field}.id`); - assertId(value.projectId, `${field}.projectId`); - if (!Number.isSafeInteger(value.configurationVersion) || (value.configurationVersion as number) < 1) { - throw new Error(`${field}.configurationVersion must be a positive integer.`); - } - assertExternalCsvConfiguration(value.configuration); - if (Object.keys(value).length !== 4) { - throw new Error(`${field} external CSV configuration contains unknown fields.`); - } -} - -function assertId(value: unknown, field: string) { - if (typeof value !== "string" || !value.trim()) { - throw new Error(`${field} must be a non-empty string.`); - } -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} diff --git a/src/domain/models/external-initial-import-project-command.model.ts b/src/domain/models/external-initial-import-project-command.model.ts deleted file mode 100644 index 2004cfc..0000000 --- a/src/domain/models/external-initial-import-project-command.model.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; -import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; -import type { SerializedProjectCommand } from "./project-command.model.js"; - -export const externalInitialImportCommandType = - "external-import.apply-initial" as const; -export const externalInitialImportCommandSchemaVersion = 1 as const; - -export interface ExternalInitialImportPayload { - expected: ExternalModelStateSnapshot; - target: ExternalModelStateSnapshot; -} - -export interface ExternalInitialImportProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof externalInitialImportCommandSchemaVersion; - type: typeof externalInitialImportCommandType; -} - -export function createExternalInitialImportProjectCommand( - expected: ExternalModelStateSnapshot, - target: ExternalModelStateSnapshot -): ExternalInitialImportProjectCommand { - const command: ExternalInitialImportProjectCommand = { - schemaVersion: externalInitialImportCommandSchemaVersion, - type: externalInitialImportCommandType, - payload: { expected, target }, - }; - assertExternalInitialImportProjectCommand(command); - return command; -} - -export function assertExternalInitialImportProjectCommand( - command: SerializedProjectCommand -): asserts command is ExternalInitialImportProjectCommand { - if ( - command.schemaVersion !== externalInitialImportCommandSchemaVersion || - command.type !== externalInitialImportCommandType || - !isRecord(command.payload) || - Object.keys(command.payload).length !== 2 - ) { - throw new Error("Unsupported external initial import command."); - } - const expected = parseExternalModelStateSnapshot(command.payload.expected); - const target = parseExternalModelStateSnapshot(command.payload.target); - const expectedIsEmpty = isEmptyExternalModelState(expected); - const targetIsEmpty = isEmptyExternalModelState(target); - if (expectedIsEmpty === targetIsEmpty) { - throw new Error("External initial import must transition between empty and populated state."); - } - assertPopulatedInitialState(expectedIsEmpty ? target : expected); -} - -export function createEmptyExternalModelState(): ExternalModelStateSnapshot { - return { source: null, importBatches: [], roomMappings: [], objects: [] }; -} - -export function isEmptyExternalModelState(state: ExternalModelStateSnapshot) { - return ( - state.source === null && - state.importBatches.length === 0 && - state.roomMappings.length === 0 && - state.objects.length === 0 - ); -} - -function assertPopulatedInitialState(state: ExternalModelStateSnapshot) { - if (state.source === null || state.importBatches.length !== 1 || state.objects.length === 0) { - throw new Error("External initial import requires one source, one batch and at least one object."); - } - const source = state.source; - const batch = state.importBatches[0]; - if ( - batch.importKind !== "initial" || - batch.projectId !== source.projectId || - batch.sourceId !== source.id - ) { - throw new Error("External initial import batch identity is invalid."); - } - const mappingIds = uniqueIds(state.roomMappings, "room mapping"); - const roomKeys = new Set(); - for (const mapping of state.roomMappings) { - if (mapping.projectId !== source.projectId || mapping.sourceId !== source.id) { - throw new Error("External initial room mapping identity is invalid."); - } - if (roomKeys.has(mapping.normalizedSourceRoomKey)) { - throw new Error("External initial import contains duplicate room keys."); - } - roomKeys.add(mapping.normalizedSourceRoomKey); - } - uniqueIds(state.objects, "object"); - const ifcGuids = new Set(); - for (const object of state.objects) { - if ( - object.projectId !== source.projectId || - object.sourceId !== source.id || - object.lastSeenImportBatchId !== batch.id || - object.lastAcceptedImportBatchId !== batch.id - ) { - throw new Error("External initial object identity is invalid."); - } - if (ifcGuids.has(object.ifcGuid)) { - throw new Error("External initial import contains duplicate IFCGUIDs."); - } - ifcGuids.add(object.ifcGuid); - if ( - object.externalRoomMappingId !== null && - !mappingIds.has(object.externalRoomMappingId) - ) { - throw new Error("External initial object room mapping is invalid."); - } - if (object.circuitDeviceRowId !== null) { - throw new Error("External initial import must not assign circuit device rows."); - } - if (object.presenceStatus !== "present") { - throw new Error("External initial import objects must be present."); - } - } -} - -function uniqueIds(entries: ReadonlyArray<{ id: string }>, label: string) { - const ids = new Set(); - for (const entry of entries) { - if (ids.has(entry.id)) { - throw new Error(`External initial import contains duplicate ${label} ids.`); - } - ids.add(entry.id); - } - return ids; -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} diff --git a/src/domain/models/external-model-configuration-project-command.model.ts b/src/domain/models/external-model-configuration-project-command.model.ts new file mode 100644 index 0000000..e606b6a --- /dev/null +++ b/src/domain/models/external-model-configuration-project-command.model.ts @@ -0,0 +1,88 @@ +import { + assertExternalModelConfiguration, + type ExternalModelConfiguration, +} from "../../external-model/configuration/external-model-configuration.js"; +import type { SerializedProjectCommand } from "./project-command.model.js"; + +export const externalModelConfigurationUpdateCommandType = + "external-model-configuration.update" as const; +export const externalModelConfigurationCommandSchemaVersion = 1 as const; + +export interface ExternalModelConfigurationSnapshot { + id: string; + projectId: string; + configuration: ExternalModelConfiguration; +} + +export interface ExternalModelConfigurationUpdatePayload { + expected: ExternalModelConfigurationSnapshot | null; + target: ExternalModelConfigurationSnapshot | null; +} + +export interface ExternalModelConfigurationUpdateProjectCommand + extends SerializedProjectCommand { + schemaVersion: typeof externalModelConfigurationCommandSchemaVersion; + type: typeof externalModelConfigurationUpdateCommandType; +} + +export function createExternalModelConfigurationUpdateProjectCommand( + expected: ExternalModelConfigurationSnapshot | null, + target: ExternalModelConfigurationSnapshot | null +): ExternalModelConfigurationUpdateProjectCommand { + const command: ExternalModelConfigurationUpdateProjectCommand = { + schemaVersion: externalModelConfigurationCommandSchemaVersion, + type: externalModelConfigurationUpdateCommandType, + payload: { expected, target }, + }; + assertExternalModelConfigurationUpdateProjectCommand(command); + return command; +} + +export function assertExternalModelConfigurationUpdateProjectCommand( + command: SerializedProjectCommand +): asserts command is ExternalModelConfigurationUpdateProjectCommand { + if ( + command.schemaVersion !== externalModelConfigurationCommandSchemaVersion || + command.type !== externalModelConfigurationUpdateCommandType || + !isRecord(command.payload) || + Object.keys(command.payload).length !== 2 + ) { + throw new Error("Nicht unterstützter Revit-XLSX-Konfigurationscommand."); + } + assertSnapshot(command.payload.expected, "expected"); + assertSnapshot(command.payload.target, "target"); + if (command.payload.expected === null && command.payload.target === null) { + throw new Error("Der Konfigurationscommand muss den Zustand ändern."); + } + if ( + command.payload.expected !== null && + command.payload.target !== null && + (command.payload.expected.id !== command.payload.target.id || + command.payload.expected.projectId !== command.payload.target.projectId) + ) { + throw new Error("Die Identität der Revit-XLSX-Konfiguration muss stabil bleiben."); + } +} + +function assertSnapshot( + value: unknown, + field: string +): asserts value is ExternalModelConfigurationSnapshot | null { + if (value === null) return; + if (!isRecord(value) || Object.keys(value).length !== 3) { + throw new Error(`${field} muss eine vollständige Konfiguration oder null sein.`); + } + assertId(value.id, `${field}.id`); + assertId(value.projectId, `${field}.projectId`); + assertExternalModelConfiguration(value.configuration); +} + +function assertId(value: unknown, field: string) { + if (typeof value !== "string" || !value.trim()) { + throw new Error(`${field} muss eine nichtleere ID sein.`); + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} diff --git a/src/domain/models/project-state-snapshot.model.ts b/src/domain/models/project-state-snapshot.model.ts index ea3aba7..2296bc1 100644 --- a/src/domain/models/project-state-snapshot.model.ts +++ b/src/domain/models/project-state-snapshot.model.ts @@ -28,6 +28,10 @@ import { } from "../services/project-voltage.service.js"; import { validateExternalCsvConfiguration } from "../../external-model/csv/external-csv-configuration.js"; import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts.js"; +import { + validateExternalModelConfiguration, + type ExternalModelConfiguration, +} from "../../external-model/configuration/external-model-configuration.js"; import { externalImportKinds, externalModelSourceTypes, @@ -35,7 +39,8 @@ import { type ExternalModelStateSnapshot, } from "../../external-model/domain/external-model-contracts.js"; -export const projectStateSnapshotSchemaVersion = 9 as const; +export const projectStateSnapshotSchemaVersion = 10 as const; +const legacyCsvProjectStateSnapshotSchemaVersion = 9 as const; const roomAreaProjectStateSnapshotSchemaVersion = 8 as const; const buildingProjectStateSnapshotSchemaVersion = 7 as const; const coverProjectStateSnapshotSchemaVersion = 6 as const; @@ -423,14 +428,14 @@ const externalCsvDocumentSchema = z.object({ }); }); -const externalModelSourceSchema = z.object({ +const legacyExternalModelSourceSchema = z.object({ id: idSchema, projectId: idSchema, name: z.string().trim().min(1), - sourceType: z.enum(externalModelSourceTypes), + sourceType: z.literal("revit_csv"), }).strict(); -const externalImportBatchSchema = z.object({ +const legacyExternalImportBatchSchema = z.object({ id: idSchema, projectId: idSchema, sourceId: idSchema, @@ -461,7 +466,7 @@ const externalRoomMappingSchema = z.object({ defaultDistributionBoardId: idSchema.nullable(), }).strict(); -const externalPlanningFieldNames = [ +const legacyExternalPlanningFieldNames = [ "displayName", "internalDeviceType", "category", @@ -474,7 +479,7 @@ const externalPlanningFieldNames = [ "remark", ] as const; -const externalModelObjectSchema = z.object({ +const legacyExternalModelObjectSchema = z.object({ id: idSchema, projectId: idSchema, sourceId: idSchema, @@ -504,6 +509,170 @@ const externalModelObjectSchema = z.object({ costGroup: nullableStringSchema, remark: nullableStringSchema, }).strict(), + overriddenFields: z.array(z.enum(legacyExternalPlanningFieldNames)).refine( + (values) => new Set(values).size === values.length + ), + externalRoomMappingId: idSchema.nullable(), + distributionBoardId: idSchema.nullable(), + linkedProjectDeviceId: idSchema.nullable(), + circuitDeviceRowId: idSchema.nullable(), + presenceStatus: z.enum(externalObjectPresenceStatuses), +}).strict(); + +const legacyExternalModelStateSchema = z.object({ + source: legacyExternalModelSourceSchema.nullable(), + importBatches: z.array(legacyExternalImportBatchSchema), + roomMappings: z.array(externalRoomMappingSchema), + objects: z.array(legacyExternalModelObjectSchema), +}).strict(); + +const externalModelConfigurationSnapshotSchema = z.object({ + id: idSchema, + projectId: idSchema, + configuration: z.custom( + (value) => validateExternalModelConfiguration(value).success + ), +}).strict(); + +const externalXlsxScalarSchema = z.union([ + z.string(), + finiteNumberSchema, + z.boolean(), + z.null(), +]); + +const externalXlsxDocumentSchema = z.object({ + sheetName: z.string().min(1).max(31), + headerRowNumber: z.number().int().positive(), + firstDataRowNumber: z.number().int().positive(), + firstDataColumnNumber: z.number().int().positive(), + columns: z.array(z.object({ + columnNumber: z.number().int().positive(), + header: z.string(), + comment: z.string().nullable(), + width: finiteNumberSchema.positive().nullable(), + }).strict()), + rows: z.array(z.object({ + rowNumber: z.number().int().positive(), + classification: z.enum(["object", "suspect-object", "passthrough"]), + cells: z.array(z.object({ + columnNumber: z.number().int().positive(), + value: externalXlsxScalarSchema, + valueType: z.enum(["empty", "string", "number", "boolean"]), + numberFormat: z.string().nullable(), + formula: z.string().nullable(), + usedCachedFormulaValue: z.boolean(), + }).strict()), + }).strict()), + issues: z.array(z.object({ + code: z.enum([ + "cached-formula-value-used", + "formula-without-cached-value", + "suspect-object-skipped", + "duplicate-ifc-guid", + "optional-return-column-missing", + ]), + message: z.string().min(1), + rowNumber: z.number().int().positive().optional(), + columnNumber: z.number().int().positive().optional(), + field: z.enum([ + "worksharingId", "ifcGuid", "roomNumber", "roomName", + "familyAndType", "selectionMarker", "socketCount", "sourceRemark", + "circuitCombined", "boardName", "circuitIdentifier", "designation", + "electricalPowerW", "voltageV", "currentA", + ]).optional(), + }).strict()), +}).strict(); + +const externalModelSourceSchema = z.object({ + id: idSchema, + projectId: idSchema, + name: z.string().trim().min(1), + sourceType: z.enum(externalModelSourceTypes), +}).strict(); + +const externalImportBatchSchema = z.object({ + id: idSchema, + projectId: idSchema, + sourceId: idSchema, + importKind: z.enum(externalImportKinds), + importedAtIso: z.string().refine((value) => Number.isFinite(Date.parse(value))), + fileName: z.string().trim().min(1), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + objectCount: z.number().int().nonnegative(), + appliedProjectRevision: z.number().int().nonnegative().nullable(), + configurationSnapshot: z.custom( + (value) => value === null || validateExternalModelConfiguration(value).success + ).nullable(), + originalContentBase64: z.string().min(1).regex( + /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/ + ).nullable(), + document: externalXlsxDocumentSchema.nullable(), +}).strict().superRefine((batch, context) => { + const complete = [ + batch.appliedProjectRevision, + batch.configurationSnapshot, + batch.originalContentBase64, + batch.document, + ].map((value) => value !== null); + if (!complete.every((value) => value === complete[0])) { + context.addIssue({ + code: "custom", + message: "Importbatch muss vollständig oder auf Metadaten reduziert sein.", + }); + } +}); + +const externalPlanningFieldNames = [ + "displayName", + "category", + "connectionKind", + "effectiveQuantity", + "powerPerUnitW", + "simultaneityFactor", + "cosPhi", + "costGroup", + "remark", +] as const; + +const externalModelObjectSchema = z.object({ + id: idSchema, + projectId: idSchema, + sourceId: idSchema, + worksharingId: z.string().regex( + /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}-[0-9A-Fa-f]{8}$/ + ), + ifcGuid: externalIfcGuidSchema.nullable(), + deviceTypeId: idSchema, + lastSeenImportBatchId: idSchema, + lastAcceptedImportBatchId: idSchema, + acceptedSourceValues: z.object({ + rowNumber: z.number().int().positive(), + roomNumber: externalXlsxScalarSchema, + roomName: externalXlsxScalarSchema, + familyAndType: z.string().min(1), + selectionMarker: externalXlsxScalarSchema, + socketCount: externalXlsxScalarSchema, + sourceRemark: externalXlsxScalarSchema, + circuitCombined: externalXlsxScalarSchema, + boardName: externalXlsxScalarSchema, + circuitIdentifier: externalXlsxScalarSchema, + designation: externalXlsxScalarSchema, + electricalPowerW: externalXlsxScalarSchema, + voltageV: externalXlsxScalarSchema, + currentA: externalXlsxScalarSchema, + }).strict(), + planningValues: z.object({ + displayName: nullableStringSchema, + category: z.enum(circuitGroupCategories).nullable(), + connectionKind: nullableStringSchema, + effectiveQuantity: finiteNumberSchema.positive(), + powerPerUnitW: finiteNumberSchema.nonnegative().nullable(), + simultaneityFactor: finiteNumberSchema.min(0).max(1).nullable(), + cosPhi: finiteNumberSchema.positive().max(1).nullable(), + costGroup: nullableStringSchema, + remark: nullableStringSchema, + }).strict(), overriddenFields: z.array(z.enum(externalPlanningFieldNames)).refine( (values) => new Set(values).size === values.length ), @@ -519,7 +688,21 @@ const externalModelStateSchema = z.object({ importBatches: z.array(externalImportBatchSchema), roomMappings: z.array(externalRoomMappingSchema), objects: z.array(externalModelObjectSchema), -}).strict(); +}).strict().superRefine((state, context) => { + const fullBatchIndexes = state.importBatches.flatMap((batch, index) => + batch.originalContentBase64 === null ? [] : [index] + ); + if ( + state.importBatches.length > 0 && + (fullBatchIndexes.length !== 1 || + fullBatchIndexes[0] !== state.importBatches.length - 1) + ) { + context.addIssue({ + code: "custom", + message: "Nur der letzte Importbatch darf vollständig gespeichert sein.", + }); + } +}); export function parseExternalModelStateSnapshot( value: unknown @@ -565,19 +748,30 @@ export const projectStateSnapshotSchema = z schemaVersion: z.literal(projectStateSnapshotSchemaVersion), project: projectSchema, distributionBoards: z.array(distributionBoardSchema), - externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), + externalModelConfiguration: externalModelConfigurationSnapshotSchema.nullable(), externalModel: externalModelStateSchema, ...projectStateSnapshotContents, }) .strict(); +const legacyCsvProjectStateSnapshotSchema = z + .object({ + schemaVersion: z.literal(legacyCsvProjectStateSnapshotSchemaVersion), + project: projectSchema, + distributionBoards: z.array(distributionBoardSchema), + externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), + externalModel: legacyExternalModelStateSchema, + ...projectStateSnapshotContents, + }) + .strict(); + const roomAreaProjectStateSnapshotSchema = z .object({ schemaVersion: z.literal(roomAreaProjectStateSnapshotSchemaVersion), project: projectSchema, distributionBoards: z.array(distributionBoardWithoutFeedingSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: externalModelStateSchema, + externalModel: legacyExternalModelStateSchema, ...projectStateSnapshotContents, }) .strict(); @@ -588,7 +782,7 @@ const buildingProjectStateSnapshotSchema = z project: projectSchema, distributionBoards: z.array(distributionBoardWithoutFeedingSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: externalModelStateSchema, + externalModel: legacyExternalModelStateSchema, ...buildingProjectStateSnapshotContents, }) .strict(); @@ -599,7 +793,7 @@ const coverProjectStateSnapshotSchema = z project: projectSchema, distributionBoards: z.array(distributionBoardWithoutFeedingSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: externalModelStateSchema, + externalModel: legacyExternalModelStateSchema, ...previousProjectStateSnapshotContents, }) .strict(); @@ -610,7 +804,7 @@ const boardInfoProjectStateSnapshotSchema = z project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: externalModelStateSchema, + externalModel: legacyExternalModelStateSchema, ...previousProjectStateSnapshotContents, }) .strict(); @@ -621,7 +815,7 @@ const previousProjectStateSnapshotSchema = z project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: externalModelStateSchema, + externalModel: legacyExternalModelStateSchema, ...previousProjectStateSnapshotContents, }) .strict(); @@ -684,6 +878,39 @@ export function parseProjectStateSnapshot( } function upgradePreviousProjectStateSnapshot(value: unknown): unknown { + const legacyCsv = upgradeToLegacyCsvProjectStateSnapshot(value); + if ( + legacyCsv !== null && + typeof legacyCsv === "object" && + !Array.isArray(legacyCsv) && + (legacyCsv as { schemaVersion?: unknown }).schemaVersion === + legacyCsvProjectStateSnapshotSchemaVersion + ) { + const previous = legacyCsvProjectStateSnapshotSchema.parse(legacyCsv); + if ( + previous.externalCsvConfiguration !== null || + !isEmptyExternalModelState(previous.externalModel) + ) { + throw new Error( + "Dieser alte Projektstand enthält Revit-CSV-Daten und kann nicht auf die Revit-XLSX-Struktur aktualisiert werden." + ); + } + const { + externalCsvConfiguration: _externalCsvConfiguration, + externalModel: _legacyExternalModel, + ...remaining + } = previous; + return { + ...remaining, + schemaVersion: projectStateSnapshotSchemaVersion, + externalModelConfiguration: null, + externalModel: emptyExternalModelState(), + }; + } + return legacyCsv; +} + +function upgradeToLegacyCsvProjectStateSnapshot(value: unknown): unknown { const roomArea = upgradeToRoomAreaProjectStateSnapshot(value); if ( roomArea !== null && @@ -695,7 +922,7 @@ function upgradePreviousProjectStateSnapshot(value: unknown): unknown { const previous = roomAreaProjectStateSnapshotSchema.parse(roomArea); return { ...previous, - schemaVersion: projectStateSnapshotSchemaVersion, + schemaVersion: legacyCsvProjectStateSnapshotSchemaVersion, distributionBoards: withEmptyDistributionBoardFeeding( previous.distributionBoards ), @@ -830,6 +1057,20 @@ function emptyExternalModelState() { }; } +function isEmptyExternalModelState(state: { + source: unknown; + importBatches: unknown[]; + roomMappings: unknown[]; + objects: unknown[]; +}) { + return ( + state.source === null && + state.importBatches.length === 0 && + state.roomMappings.length === 0 && + state.objects.length === 0 + ); +} + function normalizeSnapshotPhaseTypes( snapshot: ProjectStateSnapshot ): ProjectStateSnapshot { @@ -891,10 +1132,10 @@ function assertProjectStateSnapshotRelations( ) { const projectId = snapshot.project.id; if ( - snapshot.externalCsvConfiguration !== null && - snapshot.externalCsvConfiguration.projectId !== projectId + snapshot.externalModelConfiguration !== null && + snapshot.externalModelConfiguration.projectId !== projectId ) { - throw new Error("Snapshot external CSV configuration belongs to a different project."); + throw new Error("Snapshot Revit-XLSX configuration belongs to a different project."); } const boardIds = uniqueIds( snapshot.distributionBoards, @@ -1235,6 +1476,12 @@ function assertExternalModelRelations( } return; } + if (snapshot.externalModelConfiguration === null) { + throw new Error("Snapshot external model requires a Revit-XLSX configuration."); + } + if (importBatches.length === 0) { + throw new Error("Snapshot external model source requires an import batch."); + } assertProjectOwnership(source.projectId, references.projectId, "external model source"); const batchIds = uniqueIds(importBatches, "external import batch"); const mappingIds = uniqueIds(roomMappings, "external room mapping"); @@ -1270,17 +1517,23 @@ function assertExternalModelRelations( } } - const ifcGuids = new Set(); + const worksharingIds = new Set(); + const deviceTypeIds = new Set( + snapshot.externalModelConfiguration.configuration.deviceTypes.map( + (deviceType) => deviceType.id + ) + ); for (const object of objects) { assertProjectOwnership(object.projectId, references.projectId, "external model object"); if (object.sourceId !== source.id) { throw new Error("Snapshot external model object belongs to a different source."); } assertUniqueKey( - ifcGuids, - object.ifcGuid, - "Snapshot contains duplicate external IFCGUIDs." + worksharingIds, + object.worksharingId, + "Snapshot contains duplicate external Worksharing-IDs." ); + assertReference(deviceTypeIds, object.deviceTypeId, "external object device type"); assertReference(batchIds, object.lastSeenImportBatchId, "external object last-seen batch"); assertReference(batchIds, object.lastAcceptedImportBatchId, "external object accepted batch"); if (object.externalRoomMappingId !== null) { diff --git a/src/domain/models/project-transfer.model.ts b/src/domain/models/project-transfer.model.ts index d68b29e..e067896 100644 --- a/src/domain/models/project-transfer.model.ts +++ b/src/domain/models/project-transfer.model.ts @@ -146,16 +146,35 @@ export function remapProjectState( createId ); const externalObjectIds = idMap(source.externalModel.objects, createId); + const configurations = [ + source.externalModelConfiguration?.configuration ?? null, + ...source.externalModel.importBatches.map( + (batch) => batch.configurationSnapshot + ), + ].filter((configuration) => configuration !== null); + const deviceTypeIds = uniqueIdMap( + configurations.flatMap((configuration) => configuration.deviceTypes), + createId + ); + const familyRuleIds = uniqueIdMap( + configurations.flatMap((configuration) => configuration.familyTypeRules), + createId + ); return parseProjectStateSnapshot({ ...source, project: { ...source.project, id: targetProjectId, name }, - externalCsvConfiguration: - source.externalCsvConfiguration === null + externalModelConfiguration: + source.externalModelConfiguration === null ? null : { - ...source.externalCsvConfiguration, + ...source.externalModelConfiguration, id: createId(), projectId: targetProjectId, + configuration: remapExternalModelConfiguration( + source.externalModelConfiguration.configuration, + deviceTypeIds, + familyRuleIds + ), }, externalModel: { source: source.externalModel.source === null @@ -170,6 +189,14 @@ export function remapProjectState( id: requiredId(externalBatchIds, batch.id), projectId: targetProjectId, sourceId: externalSourceId!, + configurationSnapshot: + batch.configurationSnapshot === null + ? null + : remapExternalModelConfiguration( + batch.configurationSnapshot, + deviceTypeIds, + familyRuleIds + ), })), roomMappings: source.externalModel.roomMappings.map((mapping) => ({ ...mapping, @@ -190,6 +217,7 @@ export function remapProjectState( id: requiredId(externalObjectIds, object.id), projectId: targetProjectId, sourceId: externalSourceId!, + deviceTypeId: requiredId(deviceTypeIds, object.deviceTypeId), lastSeenImportBatchId: requiredId( externalBatchIds, object.lastSeenImportBatchId @@ -322,6 +350,36 @@ export function remapProjectState( }); } +function remapExternalModelConfiguration( + configuration: NonNullable< + ProjectStateSnapshot["externalModelConfiguration"] + >["configuration"], + deviceTypeIds: ReadonlyMap, + familyRuleIds: ReadonlyMap +) { + return { + ...configuration, + deviceTypes: configuration.deviceTypes.map((deviceType) => ({ + ...deviceType, + id: requiredId(deviceTypeIds, deviceType.id), + })), + familyTypeRules: configuration.familyTypeRules.map((rule) => ({ + ...rule, + id: requiredId(familyRuleIds, rule.id), + deviceTypeId: requiredId(deviceTypeIds, rule.deviceTypeId), + })), + }; +} + +function uniqueIdMap( + entries: ReadonlyArray<{ id: string }>, + createId: () => string +) { + return new Map( + [...new Set(entries.map((entry) => entry.id))].map((id) => [id, createId()]) + ); +} + function idMap( entries: ReadonlyArray<{ id: string }>, createId: () => string diff --git a/src/domain/ports/external-csv-configuration-project-command.store.ts b/src/domain/ports/external-csv-configuration-project-command.store.ts deleted file mode 100644 index 0bc74b4..0000000 --- a/src/domain/ports/external-csv-configuration-project-command.store.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ExternalCsvConfigurationUpdateProjectCommand } from "../models/external-csv-configuration-project-command.model.js"; -import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; - -export interface ExecuteExternalCsvConfigurationCommandInput { - projectId: string; - expectedRevision: number; - source: ProjectRevisionSource; - description?: string; - actorId?: string; - historyTargetChangeSetId?: string; - command: ExternalCsvConfigurationUpdateProjectCommand; -} - -export interface ExternalCsvConfigurationProjectCommandStore { - execute(input: ExecuteExternalCsvConfigurationCommandInput): { - revision: AppendedProjectRevision; - inverse: ExternalCsvConfigurationUpdateProjectCommand; - }; -} diff --git a/src/domain/ports/external-csv-configuration.reader.ts b/src/domain/ports/external-csv-configuration.reader.ts deleted file mode 100644 index a50144b..0000000 --- a/src/domain/ports/external-csv-configuration.reader.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { ExternalCsvConfigurationSnapshot } from "../models/external-csv-configuration-project-command.model.js"; - -export interface ExternalCsvConfigurationReadResult { - projectExists: boolean; - configuration: ExternalCsvConfigurationSnapshot | null; -} - -export interface ExternalCsvConfigurationReader { - getByProject(projectId: string): ExternalCsvConfigurationReadResult; -} diff --git a/src/domain/ports/external-initial-import-project-command.store.ts b/src/domain/ports/external-initial-import-project-command.store.ts deleted file mode 100644 index db1917e..0000000 --- a/src/domain/ports/external-initial-import-project-command.store.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ExternalInitialImportProjectCommand } from "../models/external-initial-import-project-command.model.js"; -import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; - -export interface ExecuteExternalInitialImportCommandInput { - projectId: string; - expectedRevision: number; - source: ProjectRevisionSource; - description?: string; - actorId?: string; - historyTargetChangeSetId?: string; - command: ExternalInitialImportProjectCommand; -} - -export interface ExternalInitialImportProjectCommandStore { - execute(input: ExecuteExternalInitialImportCommandInput): { - revision: AppendedProjectRevision; - inverse: ExternalInitialImportProjectCommand; - }; -} diff --git a/src/domain/ports/external-model-configuration-project-command.store.ts b/src/domain/ports/external-model-configuration-project-command.store.ts new file mode 100644 index 0000000..d6dce8c --- /dev/null +++ b/src/domain/ports/external-model-configuration-project-command.store.ts @@ -0,0 +1,19 @@ +import type { ExternalModelConfigurationUpdateProjectCommand } from "../models/external-model-configuration-project-command.model.js"; +import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; + +export interface ExecuteExternalModelConfigurationCommandInput { + projectId: string; + expectedRevision: number; + source: ProjectRevisionSource; + description?: string; + actorId?: string; + historyTargetChangeSetId?: string; + command: ExternalModelConfigurationUpdateProjectCommand; +} + +export interface ExternalModelConfigurationProjectCommandStore { + execute(input: ExecuteExternalModelConfigurationCommandInput): { + revision: AppendedProjectRevision; + inverse: ExternalModelConfigurationUpdateProjectCommand; + }; +} diff --git a/src/domain/ports/external-model-configuration.reader.ts b/src/domain/ports/external-model-configuration.reader.ts new file mode 100644 index 0000000..1b54f77 --- /dev/null +++ b/src/domain/ports/external-model-configuration.reader.ts @@ -0,0 +1,10 @@ +import type { ExternalModelConfigurationSnapshot } from "../models/external-model-configuration-project-command.model.js"; + +export interface ExternalModelConfigurationReadResult { + projectExists: boolean; + configuration: ExternalModelConfigurationSnapshot | null; +} + +export interface ExternalModelConfigurationReader { + getByProject(projectId: string): ExternalModelConfigurationReadResult; +} diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index 35dd9e8..603a4be 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -173,15 +173,10 @@ import type { ProjectRevisionSource } from "../ports/project-revision.store.js"; import type { ProjectSettingsProjectCommandStore } from "../ports/project-settings-project-command.store.js"; import type { ProjectStateRestoreCommandStore } from "../ports/project-state-restore-command.store.js"; import { - assertExternalCsvConfigurationUpdateProjectCommand, - externalCsvConfigurationUpdateCommandType, -} from "../models/external-csv-configuration-project-command.model.js"; -import type { ExternalCsvConfigurationProjectCommandStore } from "../ports/external-csv-configuration-project-command.store.js"; -import { - assertExternalInitialImportProjectCommand, - externalInitialImportCommandType, -} from "../models/external-initial-import-project-command.model.js"; -import type { ExternalInitialImportProjectCommandStore } from "../ports/external-initial-import-project-command.store.js"; + assertExternalModelConfigurationUpdateProjectCommand, + externalModelConfigurationUpdateCommandType, +} from "../models/external-model-configuration-project-command.model.js"; +import type { ExternalModelConfigurationProjectCommandStore } from "../ports/external-model-configuration-project-command.store.js"; import { assertExternalObjectRowAssignmentProjectCommand, externalObjectRowAssignmentCommandType, @@ -243,8 +238,7 @@ export class ProjectCommandService implements ProjectCommandExecutor { private readonly circuitGroupSubtreeStore: CircuitGroupSubtreeProjectCommandStore, private readonly circuitProtectionStore: CircuitProtectionProjectCommandStore, private readonly historyStore: ProjectHistoryStore, - private readonly externalCsvConfigurationStore?: ExternalCsvConfigurationProjectCommandStore, - private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore, + private readonly externalModelConfigurationStore?: ExternalModelConfigurationProjectCommandStore, private readonly externalObjectRowAssignmentStore?: ExternalObjectRowAssignmentProjectCommandStore, private readonly externalObjectNewRowStore?: ExternalObjectNewRowProjectCommandStore, private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore, @@ -308,6 +302,8 @@ export class ProjectCommandService implements ProjectCommandExecutor { ); } + assertNoLegacyExternalCsvHistoryCommand(step.command); + return this.dispatch({ ...input, source: direction, @@ -625,22 +621,12 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } - case externalCsvConfigurationUpdateCommandType: { - assertExternalCsvConfigurationUpdateProjectCommand(input.command); - if (!this.externalCsvConfigurationStore) { - throw new Error("External CSV configuration store is not available."); + case externalModelConfigurationUpdateCommandType: { + assertExternalModelConfigurationUpdateProjectCommand(input.command); + if (!this.externalModelConfigurationStore) { + throw new Error("External model configuration store is not available."); } - return this.externalCsvConfigurationStore.execute({ - ...input, - command: input.command, - }).revision; - } - case externalInitialImportCommandType: { - assertExternalInitialImportProjectCommand(input.command); - if (!this.externalInitialImportStore) { - throw new Error("External initial import store is not available."); - } - return this.externalInitialImportStore.execute({ + return this.externalModelConfigurationStore.execute({ ...input, command: input.command, }).revision; @@ -720,3 +706,16 @@ function assertExpectedRevision(expectedRevision: number) { ); } } + +function assertNoLegacyExternalCsvHistoryCommand( + command: SerializedProjectCommand +) { + if ( + command.type === "external-csv-configuration.update" || + command.type === "external-import.apply-initial" + ) { + throw new Error( + "Dieser Verlaufseintrag stammt aus der alten Revit-CSV-Anbindung und kann nach der Umstellung auf Linear-XLSX nicht mehr ausgef\u00fchrt werden." + ); + } +} diff --git a/src/external-model/application/external-circuit-list-objects.ts b/src/external-model/application/external-circuit-list-objects.ts deleted file mode 100644 index 43f57c5..0000000 --- a/src/external-model/application/external-circuit-list-objects.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { - ExternalModelStateSnapshot, -} from "../domain/external-model-contracts.js"; - -export interface ExternalCircuitListObjectDto { - id: string; - ifcGuid: string; - selectionMarker: string; - familyAndType: string; - sourceCircuitIdentifier: string; - displayName: string | null; - category: string | null; - connectionKind: string | null; - effectiveQuantity: number; - powerPerUnitW: number | null; - sourceRoomNumber: string; - sourceRoomName: string; - roomId: string | null; - linkedProjectDeviceId: string | null; - circuitDeviceRowId: string | null; - presenceStatus: "present" | "missing"; -} - -export interface ExternalCircuitListObjectsDto { - sourceName: string | null; - objectCount: number; - unassignedObjectCount: number; - objects: ExternalCircuitListObjectDto[]; -} - -export function createExternalCircuitListObjects(input: { - state: ExternalModelStateSnapshot; - distributionBoardId: string; -}): ExternalCircuitListObjectsDto { - const mappingById = new Map( - input.state.roomMappings.map((mapping) => [mapping.id, mapping]) - ); - const objects = input.state.objects - .filter((object) => object.distributionBoardId === input.distributionBoardId) - .map((object) => { - const mapping = object.externalRoomMappingId === null - ? null - : mappingById.get(object.externalRoomMappingId) ?? null; - return { - id: object.id, - ifcGuid: object.ifcGuid, - selectionMarker: object.acceptedSourceValues.selectionMarker, - familyAndType: object.acceptedSourceValues.familyAndType, - sourceCircuitIdentifier: object.acceptedSourceValues.circuitIdentifier, - displayName: object.planningValues.displayName, - category: object.planningValues.category, - connectionKind: object.planningValues.connectionKind, - effectiveQuantity: object.planningValues.effectiveQuantity, - powerPerUnitW: object.planningValues.powerPerUnitW, - sourceRoomNumber: - mapping?.sourceRoomNumber ?? object.acceptedSourceValues.roomNumber, - sourceRoomName: - mapping?.sourceRoomName ?? object.acceptedSourceValues.roomName, - roomId: mapping?.roomId ?? null, - linkedProjectDeviceId: object.linkedProjectDeviceId, - circuitDeviceRowId: object.circuitDeviceRowId, - presenceStatus: object.presenceStatus, - } satisfies ExternalCircuitListObjectDto; - }) - .sort(compareExternalObjects); - return { - sourceName: input.state.source?.name ?? null, - objectCount: objects.length, - unassignedObjectCount: objects.filter( - (object) => object.circuitDeviceRowId === null - ).length, - objects, - }; -} - -function compareExternalObjects( - left: ExternalCircuitListObjectDto, - right: ExternalCircuitListObjectDto -) { - const assignmentOrder = Number(left.circuitDeviceRowId !== null) - - Number(right.circuitDeviceRowId !== null); - if (assignmentOrder !== 0) return assignmentOrder; - return left.sourceRoomNumber.localeCompare(right.sourceRoomNumber, "de", { - numeric: true, - }) || left.selectionMarker.localeCompare(right.selectionMarker, "de", { - numeric: true, - }) || left.ifcGuid.localeCompare(right.ifcGuid); -} diff --git a/src/external-model/application/external-csv-preview.ts b/src/external-model/application/external-csv-preview.ts deleted file mode 100644 index 57aa480..0000000 --- a/src/external-model/application/external-csv-preview.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { createHash } from "node:crypto"; -import type { ExternalCsvConfiguration } from "../csv/external-csv-contracts.js"; -import { parseExternalCsv } from "../csv/external-csv-transport.js"; - -export interface ExternalCsvPreviewObject { - rowNumber: number; - ifcGuid: string; - roomNumber: string; - roomName: string; - familyAndType: string; - selectionMarker: string; - circuitIdentifier: string; - power: string; - quantity: string | null; - additionalSourceValues: Record; -} - -export interface ExternalCsvPreview { - fileName: string; - byteLength: number; - sha256: string; - dialect: ReturnType["dialect"]; - headerRowNumber: number; - headerColumns: string[]; - rowCount: number; - objectCount: number; - passthroughCount: number; - nonEmptyPassthroughCount: number; - suspectObjectCount: number; - objects: ExternalCsvPreviewObject[]; - suspectRowNumbers: number[]; -} - -export function createExternalCsvPreview(input: { - fileName: string; - bytes: Uint8Array; - configuration: ExternalCsvConfiguration; -}): ExternalCsvPreview { - const document = parseExternalCsv(input.bytes, input.configuration); - const header = document.rows[document.headerRowIndex]; - const headerIndex = new Map( - header.cells.map((cell, index) => [cell.value, index]) - ); - const valueAt = (row: (typeof document.rows)[number], column: string) => - row.cells[headerIndex.get(column)!]?.value ?? ""; - const objects = document.rows - .filter((row) => row.classification === "object") - .map((row): ExternalCsvPreviewObject => ({ - rowNumber: row.index + 1, - ifcGuid: valueAt(row, input.configuration.columns.ifcGuid), - roomNumber: valueAt(row, input.configuration.columns.roomNumber), - roomName: valueAt(row, input.configuration.columns.roomName), - familyAndType: valueAt(row, input.configuration.columns.familyAndType), - selectionMarker: valueAt(row, input.configuration.columns.selectionMarker), - circuitIdentifier: valueAt(row, input.configuration.columns.circuitIdentifier), - power: valueAt(row, input.configuration.columns.power), - quantity: - input.configuration.columns.quantity === null - ? null - : valueAt(row, input.configuration.columns.quantity), - additionalSourceValues: Object.fromEntries( - input.configuration.additionalSourceMappings.map((mapping) => [ - mapping.targetField, - valueAt(row, mapping.sourceColumn), - ]) - ), - })); - const passthroughRows = document.rows.filter( - (row) => row.classification === "passthrough" - ); - const suspectRows = document.rows.filter( - (row) => row.classification === "suspect-object" - ); - return { - fileName: input.fileName, - byteLength: input.bytes.byteLength, - sha256: createHash("sha256").update(input.bytes).digest("hex"), - dialect: document.dialect, - headerRowNumber: document.headerRowIndex + 1, - headerColumns: header.cells.map((cell) => cell.value), - rowCount: document.rows.length, - objectCount: objects.length, - passthroughCount: passthroughRows.length, - nonEmptyPassthroughCount: passthroughRows.filter((row) => - row.cells.some((cell) => cell.value !== "") - ).length, - suspectObjectCount: suspectRows.length, - objects, - suspectRowNumbers: suspectRows.map((row) => row.index + 1), - }; -} diff --git a/src/external-model/application/external-initial-import-plan.ts b/src/external-model/application/external-initial-import-plan.ts deleted file mode 100644 index bc916f8..0000000 --- a/src/external-model/application/external-initial-import-plan.ts +++ /dev/null @@ -1,164 +0,0 @@ -import type { ExternalCsvConfiguration } from "../csv/external-csv-contracts.js"; -import { - createExternalRoomKey, - normalizeExternalRoomPart, - projectInitialExternalObject, -} from "../domain/external-model-matching.js"; -import { createExternalCsvPreview } from "./external-csv-preview.js"; - -interface ExistingRoom { - id: string; - floorId: string | null; - roomNumber: string; - roomName: string; -} - -interface ExistingFloor { - id: string; - name: string; - sortOrder: number; -} - -interface ExistingDistributionBoard { - id: string; - name: string; - floorId: string | null; -} - -interface ExistingProjectDevice { - id: string; - name: string; - displayName: string; - category: string | null; - connectionKind: string | null; - powerPerUnit: number; -} - -export function createExternalInitialImportPlan(input: { - fileName: string; - bytes: Uint8Array; - configurationVersion: number; - configuration: ExternalCsvConfiguration; - rooms: ExistingRoom[]; - floors: ExistingFloor[]; - distributionBoards: ExistingDistributionBoard[]; - projectDevices: ExistingProjectDevice[]; -}) { - const preview = createExternalCsvPreview(input); - const roomCandidatesByNumber = new Map(); - for (const room of input.rooms) { - const key = normalizeExternalRoomPart(room.roomNumber); - if (!key) continue; - const candidates = roomCandidatesByNumber.get(key) ?? []; - candidates.push(room); - roomCandidatesByNumber.set(key, candidates); - } - - const objects = preview.objects.map((object) => { - const projected = projectInitialExternalObject(object, input.configuration); - return { - ifcGuid: projected.ifcGuid, - sourceRoomKey: createExternalRoomKey(object.roomNumber, object.roomName), - sourceValues: projected.sourceValues, - suggestedPlanningValues: projected.planningValues, - issues: projected.issues, - }; - }); - const sourceRooms = new Map(); - for (const object of objects) { - if (object.sourceRoomKey === null) continue; - const existing = sourceRooms.get(object.sourceRoomKey); - if (existing) { - existing.objectCount += 1; - } else { - sourceRooms.set(object.sourceRoomKey, { - sourceRoomKey: object.sourceRoomKey, - roomNumber: object.sourceValues.roomNumber, - roomName: object.sourceValues.roomName, - objectCount: 1, - }); - } - } - const roomPlans = [...sourceRooms.values()] - .map((room) => { - const candidates = roomCandidatesByNumber.get( - normalizeExternalRoomPart(room.roomNumber) - ) ?? []; - return { - ...room, - suggestedRoomId: candidates.length === 1 ? candidates[0].id : null, - matchStatus: - candidates.length === 1 - ? "exact-number" - : candidates.length > 1 - ? "ambiguous-number" - : "new", - candidateRoomIds: candidates.map((candidate) => candidate.id), - } as const; - }) - .sort((left, right) => - left.roomNumber.localeCompare(right.roomNumber, "de", { numeric: true }) || - left.roomName.localeCompare(right.roomName, "de") - ); - - const familyGroups = new Map(); - for (const object of objects) { - const key = object.sourceValues.familyAndType; - const group = familyGroups.get(key); - if (group) { - group.objectCount += 1; - } else { - familyGroups.set(key, { - familyAndType: key, - objectCount: 1, - classified: !object.issues.includes("unknown-family-and-type"), - category: object.suggestedPlanningValues.category, - connectionKind: object.suggestedPlanningValues.connectionKind, - internalDeviceType: object.suggestedPlanningValues.internalDeviceType, - }); - } - } - - return { - configurationVersion: input.configurationVersion, - fileName: preview.fileName, - sha256: preview.sha256, - byteLength: preview.byteLength, - rowCount: preview.rowCount, - objectCount: preview.objectCount, - passthroughCount: preview.passthroughCount, - suspectObjectCount: preview.suspectObjectCount, - suspectRowNumbers: preview.suspectRowNumbers, - sourceRooms: roomPlans, - familyGroups: [...familyGroups.values()].sort((left, right) => - left.familyAndType.localeCompare(right.familyAndType, "de") - ), - issueCounts: { - unknownFamilyAndType: objects.filter((object) => - object.issues.includes("unknown-family-and-type") - ).length, - invalidPower: objects.filter((object) => object.issues.includes("invalid-power")).length, - invalidQuantity: objects.filter((object) => object.issues.includes("invalid-quantity")).length, - missingRoom: objects.filter((object) => object.issues.includes("missing-room")).length, - }, - objects, - existing: { - floors: input.floors, - rooms: input.rooms, - distributionBoards: input.distributionBoards, - projectDevices: input.projectDevices, - }, - }; -} diff --git a/src/external-model/application/external-initial-import-target.ts b/src/external-model/application/external-initial-import-target.ts deleted file mode 100644 index be0925e..0000000 --- a/src/external-model/application/external-initial-import-target.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { ExternalCsvConfiguration, ExternalCsvDocument } from "../csv/external-csv-contracts.js"; -import type { ExternalModelStateSnapshot } from "../domain/external-model-contracts.js"; -import type { createExternalInitialImportPlan } from "./external-initial-import-plan.js"; - -type ExternalInitialImportPlan = ReturnType; - -export interface ExternalRoomDecision { - sourceRoomKey: string; - roomId: string | null; - defaultDistributionBoardId: string | null; -} - -export interface ExternalFamilyProjectDeviceDecision { - familyAndType: string; - projectDeviceId: string | null; -} - -export function buildExternalInitialImportTarget(input: { - projectId: string; - expectedRevision: number; - sourceName: string; - importedAtIso: string; - configurationVersion: number; - configuration: ExternalCsvConfiguration; - originalContentBase64: string; - document: ExternalCsvDocument; - plan: ExternalInitialImportPlan; - roomDecisions: ExternalRoomDecision[]; - familyProjectDeviceDecisions: ExternalFamilyProjectDeviceDecision[]; - createId: () => string; -}): ExternalModelStateSnapshot { - if (input.plan.familyGroups.some((group) => !group.classified)) { - throw new Error("Alle Familie-und-Typ-Werte müssen vor dem Erstimport klassifiziert sein."); - } - const roomDecisionByKey = exactDecisionMap( - input.plan.sourceRooms.map((room) => room.sourceRoomKey), - input.roomDecisions, - (decision) => decision.sourceRoomKey, - "Quellraum" - ); - const familyDecisionByName = exactDecisionMap( - input.plan.familyGroups.map((group) => group.familyAndType), - input.familyProjectDeviceDecisions, - (decision) => decision.familyAndType, - "Familie und Typ" - ); - const sourceId = input.createId(); - const batchId = input.createId(); - const roomMappingIdByKey = new Map( - input.plan.sourceRooms.map((room) => [room.sourceRoomKey, input.createId()]) - ); - return { - source: { - id: sourceId, - projectId: input.projectId, - name: input.sourceName.trim(), - sourceType: "revit_csv", - }, - importBatches: [{ - id: batchId, - projectId: input.projectId, - sourceId, - importKind: "initial", - importedAtIso: input.importedAtIso, - fileName: input.plan.fileName, - sha256: input.plan.sha256, - appliedProjectRevision: input.expectedRevision + 1, - configurationVersion: input.configurationVersion, - configurationSnapshot: input.configuration, - originalContentBase64: input.originalContentBase64, - document: input.document, - }], - roomMappings: input.plan.sourceRooms.map((room) => { - const decision = roomDecisionByKey.get(room.sourceRoomKey)!; - return { - id: roomMappingIdByKey.get(room.sourceRoomKey)!, - projectId: input.projectId, - sourceId, - normalizedSourceRoomKey: room.sourceRoomKey, - sourceFloorName: null, - sourceRoomNumber: room.roomNumber, - sourceRoomName: room.roomName, - roomId: decision.roomId, - defaultDistributionBoardId: decision.defaultDistributionBoardId, - }; - }), - objects: input.plan.objects.map((object) => ({ - id: input.createId(), - projectId: input.projectId, - sourceId, - ifcGuid: object.ifcGuid, - lastSeenImportBatchId: batchId, - lastAcceptedImportBatchId: batchId, - acceptedSourceValues: object.sourceValues, - planningValues: object.suggestedPlanningValues, - overriddenFields: [], - externalRoomMappingId: - object.sourceRoomKey === null - ? null - : roomMappingIdByKey.get(object.sourceRoomKey)!, - distributionBoardId: null, - linkedProjectDeviceId: - familyDecisionByName.get(object.sourceValues.familyAndType)! - .projectDeviceId, - circuitDeviceRowId: null, - presenceStatus: "present", - })), - }; -} - -function exactDecisionMap( - expectedKeys: string[], - decisions: T[], - keyOf: (decision: T) => string, - label: string -) { - const expected = new Set(expectedKeys); - const result = new Map(); - for (const decision of decisions) { - const key = keyOf(decision); - if (!expected.has(key) || result.has(key)) { - throw new Error(`${label}-Entscheidungen sind unvollständig oder doppelt.`); - } - result.set(key, decision); - } - if (result.size !== expected.size) { - throw new Error(`${label}-Entscheidungen sind unvollständig oder doppelt.`); - } - return result; -} diff --git a/src/external-model/configuration/external-model-configuration.ts b/src/external-model/configuration/external-model-configuration.ts new file mode 100644 index 0000000..b3dc20e --- /dev/null +++ b/src/external-model/configuration/external-model-configuration.ts @@ -0,0 +1,246 @@ +import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; +import { + createDefaultExternalXlsxTransportConfiguration, + type ExternalXlsxColumnConfiguration, + type ExternalXlsxTransportConfiguration, +} from "../xlsx/external-xlsx-contracts.js"; + +export const externalModelConfigurationSchemaVersion = 1 as const; +export const externalQuantityRules = ["one", "socketCount"] as const; +export type ExternalQuantityRule = (typeof externalQuantityRules)[number]; + +export interface ExternalDeviceTypeDefaults { + powerPerUnitW: number | null; + simultaneityFactor: number | null; + cosPhi: number | null; + costGroup: string | null; +} + +export interface ExternalDeviceTypeConfiguration { + id: string; + name: string; + category: CircuitGroupCategory; + defaults: ExternalDeviceTypeDefaults; +} + +export interface ExternalFamilyTypeRule { + id: string; + exactFamilyAndType: string; + deviceTypeId: string; + quantityRule: ExternalQuantityRule; +} + +export interface ExternalModelConfiguration + extends ExternalXlsxTransportConfiguration { + schemaVersion: typeof externalModelConfigurationSchemaVersion; + deviceTypes: ExternalDeviceTypeConfiguration[]; + familyTypeRules: ExternalFamilyTypeRule[]; +} + +export function createDefaultExternalModelConfiguration(): ExternalModelConfiguration { + return { + schemaVersion: externalModelConfigurationSchemaVersion, + ...createDefaultExternalXlsxTransportConfiguration(), + deviceTypes: [], + familyTypeRules: [], + }; +} + +export function assertExternalModelConfiguration( + value: unknown +): asserts value is ExternalModelConfiguration { + if (!isRecord(value) || value.schemaVersion !== externalModelConfigurationSchemaVersion) { + throw new Error("Nicht unterstützte Revit-XLSX-Konfiguration."); + } + assertExactKeys(value, [ + "schemaVersion", + "layout", + "circuitMode", + "columns", + "deviceTypes", + "familyTypeRules", + ], "Revit-XLSX-Konfiguration"); + assertLayout(value.layout); + if (value.circuitMode !== "combined" && value.circuitMode !== "separate") { + throw new Error("Der Stromkreismodus der Revit-XLSX-Konfiguration ist ungültig."); + } + assertColumns(value.columns, value.circuitMode); + if (!Array.isArray(value.deviceTypes) || !Array.isArray(value.familyTypeRules)) { + throw new Error("Gerätearten und Familienregeln müssen Listen sein."); + } + + const deviceTypeIds = new Set(); + const deviceTypeNames = new Set(); + for (const [index, deviceType] of value.deviceTypes.entries()) { + assertDeviceType(deviceType, index); + assertUnique(deviceTypeIds, deviceType.id, "Geräteart-ID"); + assertUnique(deviceTypeNames, deviceType.name, "Geräteartname"); + } + const ruleIds = new Set(); + const familyNames = new Set(); + for (const [index, rule] of value.familyTypeRules.entries()) { + assertFamilyRule(rule, index); + assertUnique(ruleIds, rule.id, "Familienregel-ID"); + assertUnique(familyNames, rule.exactFamilyAndType, "Familie und Typ"); + if (!deviceTypeIds.has(rule.deviceTypeId)) { + throw new Error( + `Familienregel ${index + 1} verweist auf eine unbekannte Geräteart.` + ); + } + } +} + +export function validateExternalModelConfiguration(value: unknown): + | { success: true; data: ExternalModelConfiguration } + | { success: false; error: string } { + try { + assertExternalModelConfiguration(value); + return { success: true, data: value }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : "Ungültige Konfiguration.", + }; + } +} + +function assertLayout(value: unknown) { + if (!isRecord(value)) throw new Error("Das XLSX-Layout fehlt."); + assertExactKeys(value, ["headerRow", "firstDataRow", "firstDataColumn"], "XLSX-Layout"); + assertPositiveInteger(value.headerRow, "Kopfzeile"); + assertPositiveInteger(value.firstDataRow, "erste Datenzeile"); + assertPositiveInteger(value.firstDataColumn, "erste Datenspalte"); + if ((value.firstDataRow as number) <= (value.headerRow as number)) { + throw new Error("Die erste Datenzeile muss nach der Kopfzeile liegen."); + } +} + +function assertColumns( + value: unknown, + circuitMode: ExternalModelConfiguration["circuitMode"] +) { + if (!isRecord(value)) throw new Error("Die XLSX-Spaltenzuordnung fehlt."); + const keys = [ + "worksharingId", + "ifcGuid", + "roomNumber", + "roomName", + "familyAndType", + "selectionMarker", + "socketCount", + "sourceRemark", + "circuitCombined", + "boardName", + "circuitIdentifier", + "designation", + "electricalPowerW", + "voltageV", + "currentA", + ] satisfies (keyof ExternalXlsxColumnConfiguration)[]; + assertExactKeys(value, keys, "XLSX-Spaltenzuordnung"); + const mappedNames = new Set(); + for (const key of keys) { + const columnName = value[key]; + const required = + key === "worksharingId" || + key === "familyAndType" || + (circuitMode === "combined" && key === "circuitCombined") || + (circuitMode === "separate" && + (key === "boardName" || key === "circuitIdentifier")); + if (columnName === null && !required) continue; + assertNonEmptyString(columnName, `Spalte ${key}`); + assertUnique(mappedNames, columnName, "Spaltenzuordnung"); + } +} + +function assertDeviceType(value: unknown, index: number): asserts value is ExternalDeviceTypeConfiguration { + if (!isRecord(value)) throw new Error(`Geräteart ${index + 1} ist ungültig.`); + assertExactKeys(value, ["id", "name", "category", "defaults"], `Geräteart ${index + 1}`); + assertUuid(value.id, `Geräteart ${index + 1}.id`); + assertNonEmptyString(value.name, `Geräteart ${index + 1}.name`); + if (!(["lighting", "single_phase", "three_phase"] as unknown[]).includes(value.category)) { + throw new Error(`Geräteart ${index + 1} besitzt eine ungültige Kategorie.`); + } + if (!isRecord(value.defaults)) throw new Error(`Geräteart ${index + 1}.defaults fehlt.`); + assertExactKeys( + value.defaults, + ["powerPerUnitW", "simultaneityFactor", "cosPhi", "costGroup"], + `Geräteart ${index + 1}.defaults` + ); + assertNullableNumber(value.defaults.powerPerUnitW, 0, Number.POSITIVE_INFINITY, "Leistung"); + assertNullableNumber(value.defaults.simultaneityFactor, 0, 1, "GZF"); + assertNullableNumber(value.defaults.cosPhi, Number.MIN_VALUE, 1, "cosPhi"); + if (value.defaults.costGroup !== null) { + assertNonEmptyString(value.defaults.costGroup, "Kostengruppe"); + } +} + +function assertFamilyRule(value: unknown, index: number): asserts value is ExternalFamilyTypeRule { + if (!isRecord(value)) throw new Error(`Familienregel ${index + 1} ist ungültig.`); + assertExactKeys( + value, + ["id", "exactFamilyAndType", "deviceTypeId", "quantityRule"], + `Familienregel ${index + 1}` + ); + assertUuid(value.id, `Familienregel ${index + 1}.id`); + assertNonEmptyString(value.exactFamilyAndType, `Familienregel ${index + 1}.exactFamilyAndType`); + assertUuid(value.deviceTypeId, `Familienregel ${index + 1}.deviceTypeId`); + if (!externalQuantityRules.includes(value.quantityRule as ExternalQuantityRule)) { + throw new Error(`Familienregel ${index + 1} besitzt eine ungültige Mengenregel.`); + } +} + +function assertPositiveInteger(value: unknown, label: string) { + if (!Number.isSafeInteger(value) || (value as number) < 1) { + throw new Error(`${label} muss eine positive Ganzzahl sein.`); + } +} + +function assertNullableNumber( + value: unknown, + minimum: number, + maximum: number, + label: string +) { + if (value === null) return; + if ( + typeof value !== "number" || + !Number.isFinite(value) || + value < minimum || + value > maximum + ) { + throw new Error(`${label} ist ungültig.`); + } +} + +function assertNonEmptyString(value: unknown, label: string): asserts value is string { + if (typeof value !== "string" || value.length === 0 || value !== value.trim()) { + throw new Error(`${label} muss nichtleer und ohne äußere Leerzeichen sein.`); + } +} + +function assertUuid(value: unknown, label: string): asserts value is string { + if ( + typeof value !== "string" || + !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) + ) { + throw new Error(`${label} muss eine UUID sein.`); + } +} + +function assertUnique(values: Set, value: string, label: string) { + if (values.has(value)) throw new Error(`${label} ist nicht eindeutig: ${value}`); + values.add(value); +} + +function assertExactKeys(value: Record, keys: readonly string[], label: string) { + const actual = Object.keys(value).sort(); + const expected = [...keys].sort(); + if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) { + throw new Error(`${label} enthält unbekannte oder fehlende Felder.`); + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} diff --git a/src/external-model/csv/external-csv-transport.ts b/src/external-model/csv/external-csv-transport.ts deleted file mode 100644 index 3446d24..0000000 --- a/src/external-model/csv/external-csv-transport.ts +++ /dev/null @@ -1,356 +0,0 @@ -import { assertExternalCsvConfiguration } from "./external-csv-configuration.js"; -import type { - ExternalCsvCell, - ExternalCsvConfiguration, - ExternalCsvDocument, - ExternalCsvLineEnding, - ExternalCsvRow, -} from "./external-csv-contracts.js"; - -export type ExternalCsvParseErrorCode = - | "invalid-encoding" - | "invalid-csv" - | "header-not-found" - | "ambiguous-header" - | "invalid-ifc-guid" - | "duplicate-ifc-guid"; - -export class ExternalCsvParseError extends Error { - constructor( - public readonly code: ExternalCsvParseErrorCode, - message: string - ) { - super(message); - this.name = "ExternalCsvParseError"; - } -} - -export function parseExternalCsv( - input: Uint8Array, - configuration: ExternalCsvConfiguration -): ExternalCsvDocument { - assertExternalCsvConfiguration(configuration); - const hasBom = hasUtf8Bom(input); - const contentBytes = hasBom ? input.subarray(3) : input; - let text: string; - try { - text = new TextDecoder("utf-8", { fatal: true }).decode(contentBytes); - } catch { - throw new ExternalCsvParseError( - "invalid-encoding", - "CSV is not valid UTF-8." - ); - } - - const parsed = parseRows(text, configuration.delimiter); - const headerMatches = findHeaderRows(parsed.rows, configuration); - if (headerMatches.length === 0) { - throw new ExternalCsvParseError( - "header-not-found", - "CSV does not contain exactly the configured required columns in one header row." - ); - } - if (headerMatches.length > 1) { - throw new ExternalCsvParseError( - "ambiguous-header", - "CSV contains more than one possible header row." - ); - } - - const headerRowIndex = headerMatches[0]; - const configuredColumnNames = [ - ...Object.values(configuration.columns).filter( - (column): column is string => column !== null - ), - ...configuration.additionalSourceMappings.map((mapping) => mapping.sourceColumn), - ]; - const headerValues = parsed.rows[headerRowIndex].map((cell) => cell.value); - if ( - configuredColumnNames.some( - (columnName) => headerValues.filter((value) => value === columnName).length !== 1 - ) - ) { - throw new ExternalCsvParseError( - "ambiguous-header", - "CSV header contains a configured column more than once." - ); - } - const headerLookup = createHeaderLookup(parsed.rows[headerRowIndex]); - const ifcGuidColumnIndex = headerLookup.get(configuration.columns.ifcGuid)!; - const objectBearingColumnIndexes = [ - configuration.columns.roomNumber, - configuration.columns.roomName, - configuration.columns.familyAndType, - configuration.columns.selectionMarker, - configuration.columns.power, - ...(configuration.columns.quantity === null - ? [] - : [configuration.columns.quantity]), - ...configuration.additionalSourceMappings.map((mapping) => mapping.sourceColumn), - ].map((column) => headerLookup.get(column)!); - const seenIfcGuids = new Set(); - - const rows: ExternalCsvRow[] = parsed.rows.map((cells, index) => { - if (index < headerRowIndex) { - return { index, cells, classification: "metadata" }; - } - if (index === headerRowIndex) { - return { index, cells, classification: "header" }; - } - - const rawIfcGuid = cells[ifcGuidColumnIndex]?.value ?? ""; - const ifcGuid = rawIfcGuid.trim(); - if (ifcGuid) { - if (ifcGuid !== rawIfcGuid || !isIfcGuid(ifcGuid)) { - throw new ExternalCsvParseError( - "invalid-ifc-guid", - `CSV row ${index + 1} contains an invalid IfcGUID.` - ); - } - if (seenIfcGuids.has(ifcGuid)) { - throw new ExternalCsvParseError( - "duplicate-ifc-guid", - `CSV contains the IfcGUID more than once: ${ifcGuid}` - ); - } - seenIfcGuids.add(ifcGuid); - return { index, cells, classification: "object" }; - } - - const looksLikeObject = objectBearingColumnIndexes.some( - (columnIndex) => (cells[columnIndex]?.value.trim() ?? "") !== "" - ); - return { - index, - cells, - classification: looksLikeObject ? "suspect-object" : "passthrough", - }; - }); - - return { - dialect: { - encoding: "utf-8", - hasBom, - delimiter: configuration.delimiter, - lineEnding: resolveLineEnding(parsed.lineEndings), - quoteCharacter: '"', - quoteAllFields: - rows.flatMap((row) => row.cells).length > 0 && - rows.flatMap((row) => row.cells).every((cell) => cell.wasQuoted), - hasTrailingLineEnding: parsed.hasTrailingLineEnding, - }, - headerRowIndex, - rows, - }; -} - -export function serializeExternalCsv(document: ExternalCsvDocument): Uint8Array { - assertSerializableDocument(document); - const serializedRows = document.rows.map((row) => - row.cells - .map((cell) => serializeCell(cell, document.dialect.delimiter)) - .join(document.dialect.delimiter) - ); - let text = serializedRows.join(document.dialect.lineEnding); - if (document.dialect.hasTrailingLineEnding && document.rows.length > 0) { - text += document.dialect.lineEnding; - } - const encoded = new TextEncoder().encode(text); - if (!document.dialect.hasBom) { - return encoded; - } - const result = new Uint8Array(encoded.length + 3); - result.set([0xef, 0xbb, 0xbf]); - result.set(encoded, 3); - return result; -} - -function parseRows(text: string, delimiter: string) { - const rows: ExternalCsvCell[][] = []; - const lineEndings: ExternalCsvLineEnding[] = []; - let cells: ExternalCsvCell[] = []; - let value = ""; - let wasQuoted = false; - let inQuotes = false; - let afterClosingQuote = false; - let fieldStarted = false; - let hasTrailingLineEnding = false; - - const finishCell = () => { - cells.push({ value, wasQuoted }); - value = ""; - wasQuoted = false; - inQuotes = false; - afterClosingQuote = false; - fieldStarted = false; - }; - const finishRow = (lineEnding: ExternalCsvLineEnding) => { - finishCell(); - rows.push(cells); - cells = []; - lineEndings.push(lineEnding); - hasTrailingLineEnding = true; - }; - - for (let index = 0; index < text.length; index += 1) { - const character = text[index]; - if (inQuotes) { - if (character === '"') { - if (text[index + 1] === '"') { - value += '"'; - index += 1; - } else { - inQuotes = false; - afterClosingQuote = true; - } - } else { - value += character; - } - hasTrailingLineEnding = false; - continue; - } - - if (afterClosingQuote) { - if (character !== delimiter && character !== "\r" && character !== "\n") { - throw new ExternalCsvParseError( - "invalid-csv", - "CSV contains characters after a closing quote." - ); - } - } - - if (character === delimiter) { - finishCell(); - hasTrailingLineEnding = false; - continue; - } - if (character === "\r" || character === "\n") { - const lineEnding: ExternalCsvLineEnding = - character === "\r" && text[index + 1] === "\n" - ? "\r\n" - : character; - if (lineEnding === "\r\n") { - index += 1; - } - finishRow(lineEnding); - continue; - } - if (character === '"') { - if (fieldStarted || value.length > 0 || afterClosingQuote) { - throw new ExternalCsvParseError( - "invalid-csv", - "CSV contains a quote inside an unquoted field." - ); - } - wasQuoted = true; - inQuotes = true; - fieldStarted = true; - hasTrailingLineEnding = false; - continue; - } - if (afterClosingQuote) { - throw new ExternalCsvParseError( - "invalid-csv", - "CSV contains invalid data after a quoted field." - ); - } - value += character; - fieldStarted = true; - hasTrailingLineEnding = false; - } - - if (inQuotes) { - throw new ExternalCsvParseError( - "invalid-csv", - "CSV contains an unterminated quoted field." - ); - } - if (!hasTrailingLineEnding || cells.length > 0 || fieldStarted || value.length > 0) { - finishCell(); - rows.push(cells); - } - - return { rows, lineEndings, hasTrailingLineEnding }; -} - -function findHeaderRows( - rows: ExternalCsvCell[][], - configuration: ExternalCsvConfiguration -) { - const requiredColumns = new Set([ - ...Object.values(configuration.columns).filter( - (column): column is string => column !== null - ), - ...configuration.additionalSourceMappings.map((mapping) => mapping.sourceColumn), - ]); - const matches: number[] = []; - rows.forEach((row, index) => { - const values = new Set(row.map((cell) => cell.value)); - if ([...requiredColumns].every((column) => values.has(column))) { - matches.push(index); - } - }); - return matches; -} - -function createHeaderLookup(cells: ExternalCsvCell[]) { - return new Map(cells.map((cell, index) => [cell.value, index])); -} - -function isIfcGuid(value: string) { - return /^[0-9A-Za-z_$]{22}$/.test(value); -} - -function resolveLineEnding(lineEndings: ExternalCsvLineEnding[]): ExternalCsvLineEnding { - if (lineEndings.length === 0) { - return "\r\n"; - } - const unique = new Set(lineEndings); - if (unique.size !== 1) { - throw new ExternalCsvParseError( - "invalid-csv", - "CSV contains mixed line endings that cannot be preserved reliably." - ); - } - return lineEndings[0]; -} - -function serializeCell(cell: ExternalCsvCell, delimiter: string) { - const mustQuote = - cell.wasQuoted || - cell.value.includes(delimiter) || - cell.value.includes('"') || - cell.value.includes("\r") || - cell.value.includes("\n"); - if (!mustQuote) { - return cell.value; - } - return `"${cell.value.replaceAll('"', '""')}"`; -} - -function assertSerializableDocument(document: ExternalCsvDocument) { - if (document.dialect.encoding !== "utf-8") { - throw new Error("Only UTF-8 external CSV documents can be serialized."); - } - if ( - document.headerRowIndex < 0 || - document.headerRowIndex >= document.rows.length || - document.rows[document.headerRowIndex]?.classification !== "header" - ) { - throw new Error("External CSV document has an invalid header row."); - } - document.rows.forEach((row, index) => { - if (row.index !== index) { - throw new Error("External CSV row indexes must be contiguous and stable."); - } - for (const cell of row.cells) { - if (typeof cell.value !== "string" || typeof cell.wasQuoted !== "boolean") { - throw new Error("External CSV document contains an invalid cell."); - } - } - }); -} - -function hasUtf8Bom(input: Uint8Array) { - return input.length >= 3 && input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf; -} diff --git a/src/external-model/domain/external-model-contracts.ts b/src/external-model/domain/external-model-contracts.ts index b06e2fb..95ab137 100644 --- a/src/external-model/domain/external-model-contracts.ts +++ b/src/external-model/domain/external-model-contracts.ts @@ -1,10 +1,11 @@ import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; +import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; import type { - ExternalCsvConfiguration, - ExternalCsvDocument, -} from "../csv/external-csv-contracts.js"; + ExternalXlsxDocument, + ExternalXlsxScalar, +} from "../xlsx/external-xlsx-contracts.js"; -export const externalModelSourceTypes = ["revit_csv"] as const; +export const externalModelSourceTypes = ["revit_xlsx"] as const; export type ExternalModelSourceType = (typeof externalModelSourceTypes)[number]; export const externalImportKinds = ["initial", "follow_up"] as const; @@ -29,11 +30,11 @@ export interface ExternalImportBatchSnapshot { importedAtIso: string; fileName: string; sha256: string; - appliedProjectRevision: number; - configurationVersion: number; - configurationSnapshot: ExternalCsvConfiguration; - originalContentBase64: string; - document: ExternalCsvDocument; + objectCount: number; + appliedProjectRevision: number | null; + configurationSnapshot: ExternalModelConfiguration | null; + originalContentBase64: string | null; + document: ExternalXlsxDocument | null; } export interface ExternalRoomMappingSnapshot { @@ -50,24 +51,28 @@ export interface ExternalRoomMappingSnapshot { export interface ExternalModelObjectSourceValues { rowNumber: number; - roomNumber: string; - roomName: string; + roomNumber: ExternalXlsxScalar; + roomName: ExternalXlsxScalar; familyAndType: string; - selectionMarker: string; - circuitIdentifier: string; - power: string; - quantity: string | null; - additionalSourceValues: Record; + selectionMarker: ExternalXlsxScalar; + socketCount: ExternalXlsxScalar; + sourceRemark: ExternalXlsxScalar; + circuitCombined: ExternalXlsxScalar; + boardName: ExternalXlsxScalar; + circuitIdentifier: ExternalXlsxScalar; + designation: ExternalXlsxScalar; + electricalPowerW: ExternalXlsxScalar; + voltageV: ExternalXlsxScalar; + currentA: ExternalXlsxScalar; } export interface ExternalModelObjectPlanningValues { displayName: string | null; - internalDeviceType: string | null; category: CircuitGroupCategory | null; connectionKind: string | null; effectiveQuantity: number; powerPerUnitW: number | null; - simultaneityFactor: number; + simultaneityFactor: number | null; cosPhi: number | null; costGroup: string | null; remark: string | null; @@ -80,7 +85,9 @@ export interface ExternalModelObjectSnapshot { id: string; projectId: string; sourceId: string; - ifcGuid: string; + worksharingId: string; + ifcGuid: string | null; + deviceTypeId: string; lastSeenImportBatchId: string; lastAcceptedImportBatchId: string; acceptedSourceValues: ExternalModelObjectSourceValues; diff --git a/src/external-model/domain/external-model-matching.ts b/src/external-model/domain/external-model-matching.ts deleted file mode 100644 index 3085211..0000000 --- a/src/external-model/domain/external-model-matching.ts +++ /dev/null @@ -1,147 +0,0 @@ -import type { ExternalCsvConfiguration } from "../csv/external-csv-contracts.js"; -import type { - ExternalModelObjectPlanningValues, - ExternalModelObjectSourceValues, -} from "./external-model-contracts.js"; - -export type InitialExternalObjectIssue = - | "unknown-family-and-type" - | "invalid-power" - | "invalid-quantity" - | "missing-room"; - -export interface InitialExternalObjectProjection { - ifcGuid: string; - sourceValues: ExternalModelObjectSourceValues; - planningValues: ExternalModelObjectPlanningValues; - issues: InitialExternalObjectIssue[]; -} - -export interface ExternalObjectImportCandidate { - rowNumber: number; - ifcGuid: string; - roomNumber: string; - roomName: string; - familyAndType: string; - selectionMarker: string; - circuitIdentifier: string; - power: string; - quantity: string | null; - additionalSourceValues: Record; -} - -export function normalizeExternalRoomPart(value: string): string { - return value.trim().normalize("NFKC").toLocaleUpperCase("de-DE"); -} - -export function createExternalRoomKey( - roomNumber: string, - roomName: string -): string | null { - const normalizedNumber = normalizeExternalRoomPart(roomNumber); - if (normalizedNumber) return `number:${normalizedNumber}`; - const normalizedName = normalizeExternalRoomPart(roomName); - return normalizedName ? `name:${normalizedName}` : null; -} - -export function indexExternalObjectsByIfcGuid( - objects: readonly T[] -): Map { - const index = new Map(); - for (const object of objects) { - if (!object.ifcGuid || object.ifcGuid !== object.ifcGuid.trim()) { - throw new Error("IfcGUID must be non-empty and must not contain outer whitespace."); - } - if (index.has(object.ifcGuid)) { - throw new Error(`Duplicate IfcGUID: ${object.ifcGuid}`); - } - index.set(object.ifcGuid, object); - } - return index; -} - -export function projectInitialExternalObject( - object: ExternalObjectImportCandidate, - configuration: ExternalCsvConfiguration -): InitialExternalObjectProjection { - const rule = configuration.familyTypeRules.find( - (candidate) => candidate.exactFamilyAndType === object.familyAndType - ); - const issues: InitialExternalObjectIssue[] = []; - if (!rule) issues.push("unknown-family-and-type"); - if (!createExternalRoomKey(object.roomNumber, object.roomName)) { - issues.push("missing-room"); - } - - const parsedPower = parseConfiguredNumber(object.power, configuration); - if (object.power.trim() && parsedPower === null) issues.push("invalid-power"); - - let effectiveQuantity = 1; - if (rule?.quantityRule.kind === "fixed") { - effectiveQuantity = rule.quantityRule.quantity; - } else if (rule?.quantityRule.kind === "mapped-column") { - const parsedQuantity = parseConfiguredNumber(object.quantity ?? "", configuration); - if (parsedQuantity === null || !Number.isInteger(parsedQuantity) || parsedQuantity <= 0) { - issues.push("invalid-quantity"); - } else { - effectiveQuantity = parsedQuantity; - } - } - - return { - ifcGuid: object.ifcGuid, - sourceValues: { - rowNumber: object.rowNumber, - roomNumber: object.roomNumber, - roomName: object.roomName, - familyAndType: object.familyAndType, - selectionMarker: object.selectionMarker, - circuitIdentifier: object.circuitIdentifier, - power: object.power, - quantity: object.quantity, - additionalSourceValues: { ...object.additionalSourceValues }, - }, - planningValues: { - displayName: rule - ? resolveDisplayName(rule.displayNameSuggestion, object) - : null, - internalDeviceType: rule?.internalDeviceType ?? null, - category: rule?.category ?? null, - connectionKind: rule?.connectionKind ?? null, - effectiveQuantity, - powerPerUnitW: - parsedPower === null ? null : parsedPower * configuration.wattsPerSourceUnit, - simultaneityFactor: 1, - cosPhi: null, - costGroup: null, - remark: null, - }, - issues, - }; -} - -function parseConfiguredNumber( - value: string, - configuration: ExternalCsvConfiguration -): number | null { - const trimmed = value.trim(); - if (!trimmed) return null; - const normalized = configuration.decimalSeparator === "," - ? trimmed.replace(",", ".") - : trimmed; - if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(normalized)) return null; - const parsed = Number(normalized); - return Number.isFinite(parsed) && parsed >= 0 ? parsed : null; -} - -function resolveDisplayName( - suggestion: ExternalCsvConfiguration["familyTypeRules"][number]["displayNameSuggestion"], - object: ExternalObjectImportCandidate -): string | null { - if (suggestion === null) return null; - if (suggestion.kind === "fixed") return suggestion.value; - if (suggestion.kind === "selection-marker") { - return object.selectionMarker.trim() || null; - } - return object.familyAndType.trim() || null; -} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 572182b..96fd6c2 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -14,7 +14,6 @@ import type { ExternalCsvConfiguration, ExternalCsvDialect, } from "../external-model/csv/external-csv-contracts"; -import type { createExternalInitialImportPlan } from "../external-model/application/external-initial-import-plan"; export interface ExternalCsvConfigurationSnapshotDto { id: string; @@ -52,9 +51,80 @@ export interface ExternalCsvPreviewDto { suspectRowNumbers: number[]; } -export type ExternalInitialImportPlanDto = ReturnType< - typeof createExternalInitialImportPlan ->; +export interface ExternalInitialImportPlanDto { + configurationVersion: number; + fileName: string; + sha256: string; + byteLength: number; + rowCount: number; + objectCount: number; + passthroughCount: number; + suspectObjectCount: number; + suspectRowNumbers: number[]; + sourceRooms: Array<{ + sourceRoomKey: string; + roomNumber: string; + roomName: string; + objectCount: number; + suggestedRoomId: string | null; + matchStatus: "exact-number" | "ambiguous-number" | "new"; + candidateRoomIds: string[]; + }>; + familyGroups: Array<{ + familyAndType: string; + objectCount: number; + classified: boolean; + category: string | null; + connectionKind: string | null; + internalDeviceType: string | null; + }>; + issueCounts: { + unknownFamilyAndType: number; + invalidPower: number; + invalidQuantity: number; + missingRoom: number; + }; + objects: Array<{ + ifcGuid: string; + sourceRoomKey: string | null; + sourceValues: ExternalCsvPreviewObjectDto; + suggestedPlanningValues: { + displayName: string | null; + internalDeviceType: string | null; + category: CircuitGroupCategory | null; + connectionKind: string | null; + effectiveQuantity: number; + powerPerUnitW: number | null; + simultaneityFactor: number; + cosPhi: number | null; + costGroup: string | null; + remark: string | null; + }; + issues: string[]; + }>; + existing: { + floors: Array<{ id: string; name: string; sortOrder: number }>; + rooms: Array<{ + id: string; + floorId: string | null; + roomNumber: string; + roomName: string; + }>; + distributionBoards: Array<{ + id: string; + name: string; + floorId: string | null; + }>; + projectDevices: Array<{ + id: string; + name: string; + displayName: string; + category: string | null; + connectionKind: string | null; + powerPerUnit: number; + }>; + }; +} export interface ApplyExternalInitialImportInput { expectedRevision: number; diff --git a/src/server/composition/application-repositories.ts b/src/server/composition/application-repositories.ts index 846a0da..a165a30 100644 --- a/src/server/composition/application-repositories.ts +++ b/src/server/composition/application-repositories.ts @@ -13,7 +13,7 @@ import { GlobalDeviceRepository } from "../../db/repositories/global-device.repo import { ProjectDeviceRepository } from "../../db/repositories/project-device.repository.js"; import { ProjectRepository } from "../../db/repositories/project.repository.js"; import { RoomRepository } from "../../db/repositories/room.repository.js"; -import { ExternalCsvConfigurationRepository } from "../../db/repositories/external-csv-configuration.repository.js"; +import { ExternalModelConfigurationRepository } from "../../db/repositories/external-model-configuration.repository.js"; import { ExternalModelStateRepository } from "../../db/repositories/external-model-state.repository.js"; import { DocumentBrandingRepository } from "../../db/repositories/document-branding.repository.js"; import { UserRepository } from "../../db/repositories/user.repository.js"; @@ -36,8 +36,8 @@ export const globalDeviceRepository = new GlobalDeviceRepository(db); export const projectDeviceRepository = new ProjectDeviceRepository(db); export const projectRepository = new ProjectRepository(db); export const roomRepository = new RoomRepository(db); -export const externalCsvConfigurationRepository = - new ExternalCsvConfigurationRepository(db); +export const externalModelConfigurationRepository = + new ExternalModelConfigurationRepository(db); export const externalModelStateRepository = new ExternalModelStateRepository(db); export const documentBrandingRepository = new DocumentBrandingRepository(db); export const userRepository = new UserRepository(db); diff --git a/src/server/composition/project-command-stores.ts b/src/server/composition/project-command-stores.ts index 8768173..00f2d5f 100644 --- a/src/server/composition/project-command-stores.ts +++ b/src/server/composition/project-command-stores.ts @@ -22,8 +22,7 @@ import { ProjectDeviceStructureProjectCommandRepository } from "../../db/reposit import { ProjectSettingsProjectCommandRepository } from "../../db/repositories/project-settings-project-command.repository.js"; import { ProjectStateRestoreCommandRepository } from "../../db/repositories/project-state-restore-command.repository.js"; import { ProjectCommandService } from "../../domain/services/project-command.service.js"; -import { ExternalCsvConfigurationProjectCommandRepository } from "../../db/repositories/external-csv-configuration-project-command.repository.js"; -import { ExternalInitialImportProjectCommandRepository } from "../../db/repositories/external-initial-import-project-command.repository.js"; +import { ExternalModelConfigurationProjectCommandRepository } from "../../db/repositories/external-model-configuration-project-command.repository.js"; import { ExternalObjectRowAssignmentProjectCommandRepository } from "../../db/repositories/external-object-row-assignment-project-command.repository.js"; import { ExternalObjectNewRowProjectCommandRepository } from "../../db/repositories/external-object-new-row-project-command.repository.js"; import { ExternalObjectNewCircuitProjectCommandRepository } from "../../db/repositories/external-object-new-circuit-project-command.repository.js"; @@ -71,10 +70,8 @@ export const projectSettingsProjectCommandStore = export const projectStateRestoreCommandStore = new ProjectStateRestoreCommandRepository(db); export const projectHistoryStore = new ProjectHistoryRepository(db); -export const externalCsvConfigurationProjectCommandStore = - new ExternalCsvConfigurationProjectCommandRepository(db); -export const externalInitialImportProjectCommandStore = - new ExternalInitialImportProjectCommandRepository(db); +export const externalModelConfigurationProjectCommandStore = + new ExternalModelConfigurationProjectCommandRepository(db); export const externalObjectRowAssignmentProjectCommandStore = new ExternalObjectRowAssignmentProjectCommandRepository(db); export const externalObjectNewRowProjectCommandStore = @@ -106,8 +103,7 @@ export const projectCommandService = new ProjectCommandService( circuitGroupSubtreeProjectCommandStore, circuitProtectionProjectCommandStore, projectHistoryStore, - externalCsvConfigurationProjectCommandStore, - externalInitialImportProjectCommandStore, + externalModelConfigurationProjectCommandStore, externalObjectRowAssignmentProjectCommandStore, externalObjectNewRowProjectCommandStore, externalObjectNewCircuitProjectCommandStore, diff --git a/src/server/controllers/external-csv.controller.ts b/src/server/controllers/external-csv.controller.ts deleted file mode 100644 index 4862d9b..0000000 --- a/src/server/controllers/external-csv.controller.ts +++ /dev/null @@ -1,298 +0,0 @@ -import crypto from "node:crypto"; -import type { Request, Response } from "express"; -import { assertExternalCsvConfiguration } from "../../external-model/csv/external-csv-configuration.js"; -import { ExternalCsvParseError } from "../../external-model/csv/external-csv-transport.js"; -import { createExternalCsvPreview } from "../../external-model/application/external-csv-preview.js"; -import { createExternalInitialImportPlan } from "../../external-model/application/external-initial-import-plan.js"; -import { buildExternalInitialImportTarget } from "../../external-model/application/external-initial-import-target.js"; -import { createExternalCircuitListObjects } from "../../external-model/application/external-circuit-list-objects.js"; -import { parseExternalCsv } from "../../external-model/csv/external-csv-transport.js"; -import { - createEmptyExternalModelState, - createExternalInitialImportProjectCommand, -} from "../../domain/models/external-initial-import-project-command.model.js"; -import { createExternalCsvConfigurationUpdateProjectCommand } from "../../domain/models/external-csv-configuration-project-command.model.js"; -import { - previewExternalCsvSchema, - planExternalInitialImportSchema, - applyExternalInitialImportSchema, - updateExternalCsvConfigurationSchema, -} from "../../shared/validation/external-csv.schemas.js"; -import { - distributionBoardRepository, - externalCsvConfigurationRepository, - externalModelStateRepository, - floorRepository, - projectDeviceRepository, - roomRepository, - circuitListRepository, -} from "../composition/application-repositories.js"; -import { projectCommandService } from "../composition/project-command-stores.js"; -import { respondWithProjectCommandError } from "./project-command.controller.js"; - -export function getExternalCsvConfiguration(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const result = externalCsvConfigurationRepository.getByProject(projectId); - if (!result.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - return res.json({ configuration: result.configuration }); -} - -export async function getExternalCircuitListObjects(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const { circuitListId } = req.params; - if (typeof circuitListId !== "string" || !circuitListId.trim()) { - return res.status(400).json({ error: "Invalid circuitListId" }); - } - const circuitList = await circuitListRepository.findById(projectId, circuitListId); - if (!circuitList) { - return res.status(404).json({ error: "Circuit list not found" }); - } - const state = externalModelStateRepository.getByProject(projectId); - if (!state.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - return res.json(createExternalCircuitListObjects({ - state: state.state, - distributionBoardId: circuitList.distributionBoardId, - })); -} - -export function updateExternalCsvConfiguration(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const parsed = updateExternalCsvConfigurationSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - try { - assertExternalCsvConfiguration(parsed.data.configuration); - const current = externalCsvConfigurationRepository.getByProject(projectId); - if (!current.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - const target = { - id: current.configuration?.id ?? crypto.randomUUID(), - projectId, - configurationVersion: - (current.configuration?.configurationVersion ?? 0) + 1, - configuration: parsed.data.configuration, - }; - const result = projectCommandService.executeUser({ - projectId, - expectedRevision: parsed.data.expectedRevision, - description: "Revit-CSV-Konfiguration bearbeiten", - command: createExternalCsvConfigurationUpdateProjectCommand( - current.configuration, - target - ), - }); - return res.json({ ...result, configuration: target }); - } catch (error) { - return respondWithProjectCommandError(error, res); - } -} - -export function previewExternalCsv(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const parsed = previewExternalCsvSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - const stored = externalCsvConfigurationRepository.getByProject(projectId); - if (!stored.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - if (!stored.configuration) { - return res.status(409).json({ - error: "Für das Projekt ist noch keine Revit-CSV-Konfiguration gespeichert.", - code: "EXTERNAL_CSV_CONFIGURATION_REQUIRED", - }); - } - try { - const bytes = decodeBase64(parsed.data.contentBase64); - return res.json( - createExternalCsvPreview({ - fileName: parsed.data.fileName, - bytes, - configuration: stored.configuration.configuration, - }) - ); - } catch (error) { - if (error instanceof ExternalCsvParseError) { - return res.status(400).json({ error: error.message, code: error.code }); - } - return res.status(400).json({ - error: error instanceof Error ? error.message : "CSV-Vorschau fehlgeschlagen.", - }); - } -} - -export async function planExternalInitialImport(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const parsed = planExternalInitialImportSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - const stored = externalCsvConfigurationRepository.getByProject(projectId); - if (!stored.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - if (!stored.configuration) { - return res.status(409).json({ - error: "Für das Projekt ist noch keine Revit-CSV-Konfiguration gespeichert.", - code: "EXTERNAL_CSV_CONFIGURATION_REQUIRED", - }); - } - const externalState = externalModelStateRepository.getByProject(projectId); - if (externalState.state.source !== null) { - return res.status(409).json({ - error: "Für dieses Projekt wurde bereits ein Revit-Modell importiert.", - code: "EXTERNAL_INITIAL_IMPORT_ALREADY_APPLIED", - }); - } - try { - const bytes = decodeBase64(parsed.data.contentBase64); - const [floors, rooms, distributionBoards, projectDevices] = await Promise.all([ - floorRepository.listByProject(projectId), - roomRepository.listByProject(projectId), - distributionBoardRepository.listByProject(projectId), - projectDeviceRepository.listByProject(projectId), - ]); - return res.json(createExternalInitialImportPlan({ - fileName: parsed.data.fileName, - bytes, - configurationVersion: stored.configuration.configurationVersion, - configuration: stored.configuration.configuration, - floors, - rooms, - distributionBoards, - projectDevices, - })); - } catch (error) { - if (error instanceof ExternalCsvParseError) { - return res.status(400).json({ error: error.message, code: error.code }); - } - return res.status(400).json({ - error: error instanceof Error ? error.message : "Erstimport-Planung fehlgeschlagen.", - }); - } -} - -export async function applyExternalInitialImport(req: Request, res: Response) { - const projectId = getProjectId(req, res); - if (!projectId) return; - const parsed = applyExternalInitialImportSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - const stored = externalCsvConfigurationRepository.getByProject(projectId); - if (!stored.projectExists) { - return res.status(404).json({ error: "Project not found" }); - } - if (!stored.configuration) { - return res.status(409).json({ - error: "Für das Projekt ist noch keine Revit-CSV-Konfiguration gespeichert.", - code: "EXTERNAL_CSV_CONFIGURATION_REQUIRED", - }); - } - if ( - stored.configuration.configurationVersion !== - parsed.data.expectedConfigurationVersion - ) { - return res.status(409).json({ - error: "Die Revit-CSV-Konfiguration wurde seit der Planung geändert.", - code: "EXTERNAL_CSV_CONFIGURATION_CHANGED", - }); - } - try { - const bytes = decodeBase64(parsed.data.contentBase64); - const [floors, rooms, distributionBoards, projectDevices] = await Promise.all([ - floorRepository.listByProject(projectId), - roomRepository.listByProject(projectId), - distributionBoardRepository.listByProject(projectId), - projectDeviceRepository.listByProject(projectId), - ]); - const plan = createExternalInitialImportPlan({ - fileName: parsed.data.fileName, - bytes, - configurationVersion: stored.configuration.configurationVersion, - configuration: stored.configuration.configuration, - floors, - rooms, - distributionBoards, - projectDevices, - }); - if (plan.sha256 !== parsed.data.expectedSha256) { - return res.status(409).json({ - error: "Die CSV-Datei stimmt nicht mehr mit der geprüften Planung überein.", - code: "EXTERNAL_CSV_FILE_CHANGED", - }); - } - const target = buildExternalInitialImportTarget({ - projectId, - expectedRevision: parsed.data.expectedRevision, - sourceName: parsed.data.sourceName, - importedAtIso: new Date().toISOString(), - configurationVersion: stored.configuration.configurationVersion, - configuration: stored.configuration.configuration, - originalContentBase64: parsed.data.contentBase64, - document: parseExternalCsv(bytes, stored.configuration.configuration), - plan, - roomDecisions: parsed.data.roomDecisions, - familyProjectDeviceDecisions: - parsed.data.familyProjectDeviceDecisions, - createId: () => crypto.randomUUID(), - }); - const result = projectCommandService.executeUser({ - projectId, - expectedRevision: parsed.data.expectedRevision, - description: `Revit-Erstimport ${parsed.data.fileName}`, - command: createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - target - ), - }); - return res.status(201).json({ - ...result, - import: { - sourceId: target.source!.id, - importBatchId: target.importBatches[0].id, - objectCount: target.objects.length, - }, - }); - } catch (error) { - if (error instanceof ExternalCsvParseError) { - return res.status(400).json({ error: error.message, code: error.code }); - } - return respondWithProjectCommandError(error, res); - } -} - -function decodeBase64(value: string) { - if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4 !== 0) { - throw new Error("CSV-Inhalt ist nicht gültig Base64-kodiert."); - } - const bytes = Buffer.from(value, "base64"); - if (bytes.toString("base64") !== value) { - throw new Error("CSV-Inhalt ist nicht kanonisch Base64-kodiert."); - } - if (bytes.length > 18 * 1024 * 1024) { - throw new Error("CSV-Datei überschreitet die maximale Größe von 18 MB."); - } - return bytes; -} - -function getProjectId(req: Request, res: Response) { - const { projectId } = req.params; - if (typeof projectId !== "string" || !projectId.trim()) { - res.status(400).json({ error: "Invalid projectId" }); - return null; - } - return projectId; -} diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index 927223e..06f9ec2 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -53,14 +53,6 @@ import { importProjectTransfer, importProjectTransferAsNewProject, } from "../controllers/project-transfer.controller.js"; -import { - getExternalCsvConfiguration, - applyExternalInitialImport, - previewExternalCsv, - planExternalInitialImport, - updateExternalCsvConfiguration, - getExternalCircuitListObjects, -} from "../controllers/external-csv.controller.js"; export const projectRouter = Router(); @@ -70,21 +62,6 @@ projectRouter.post("/import", importProjectTransferAsNewProject); projectRouter.get("/:projectId", getProject); projectRouter.get("/:projectId/export", exportProjectTransfer); projectRouter.post("/:projectId/import", importProjectTransfer); -projectRouter.get("/:projectId/external-csv/configuration", getExternalCsvConfiguration); -projectRouter.put("/:projectId/external-csv/configuration", updateExternalCsvConfiguration); -projectRouter.post("/:projectId/external-csv/preview", previewExternalCsv); -projectRouter.post( - "/:projectId/external-csv/initial-import/plan", - planExternalInitialImport -); -projectRouter.get( - "/:projectId/circuit-lists/:circuitListId/external-objects", - getExternalCircuitListObjects -); -projectRouter.post( - "/:projectId/external-csv/initial-import/apply", - applyExternalInitialImport -); projectRouter.get("/:projectId/history", getProjectHistory); projectRouter.get("/:projectId/history/revisions", listProjectRevisions); projectRouter.post("/:projectId/commands", executeProjectCommand); diff --git a/src/shared/validation/external-csv.schemas.ts b/src/shared/validation/external-csv.schemas.ts deleted file mode 100644 index cf99e66..0000000 --- a/src/shared/validation/external-csv.schemas.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { z } from "zod"; - -// Base64 length of the 18 MiB transport limit documented for CSV uploads -// (18 * 1024 * 1024 bytes, evenly divisible by 3, so ceil(N/3)*4 with no -// padding). Keep in sync with the controller's raw byte-length check. -export const MAX_CSV_CONTENT_BASE64_LENGTH = 25_165_824; - -export const updateExternalCsvConfigurationSchema = z - .object({ - expectedRevision: z.number().int().nonnegative(), - configuration: z.unknown(), - }) - .strict(); - -export const previewExternalCsvSchema = z - .object({ - fileName: z.string().trim().min(1).max(255), - contentBase64: z.string().min(1).max(MAX_CSV_CONTENT_BASE64_LENGTH), - }) - .strict(); - -export const planExternalInitialImportSchema = previewExternalCsvSchema; - -export const applyExternalInitialImportSchema = z.object({ - expectedRevision: z.number().int().nonnegative(), - expectedConfigurationVersion: z.number().int().positive(), - expectedSha256: z.string().regex(/^[a-f0-9]{64}$/), - fileName: z.string().trim().min(1).max(255), - contentBase64: z.string().min(1).max(MAX_CSV_CONTENT_BASE64_LENGTH), - sourceName: z.string().trim().min(1).max(200), - roomDecisions: z.array(z.object({ - sourceRoomKey: z.string().trim().min(1), - roomId: z.string().trim().min(1).nullable(), - defaultDistributionBoardId: z.string().trim().min(1).nullable(), - }).strict()), - familyProjectDeviceDecisions: z.array(z.object({ - familyAndType: z.string(), - projectDeviceId: z.string().trim().min(1).nullable(), - }).strict()), -}).strict(); diff --git a/tests/external-circuit-list-objects.test.ts b/tests/external-circuit-list-objects.test.ts deleted file mode 100644 index 4552d58..0000000 --- a/tests/external-circuit-list-objects.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { createExternalCircuitListObjects } from "../src/external-model/application/external-circuit-list-objects.js"; -import type { - ExternalModelObjectSnapshot, - ExternalModelStateSnapshot, -} from "../src/external-model/domain/external-model-contracts.js"; - -function object(input: { - id: string; - distributionBoardId: string; - circuitDeviceRowId: string | null; - roomNumber: string; -}): ExternalModelObjectSnapshot { - return { - id: input.id, - projectId: "project-1", - sourceId: "source-1", - ifcGuid: `ifc-${input.id}`, - lastSeenImportBatchId: "batch-1", - lastAcceptedImportBatchId: "batch-1", - acceptedSourceValues: { - rowNumber: 2, - roomNumber: input.roomNumber, - roomName: "Büro", - familyAndType: "Steckdose: Standard", - selectionMarker: `S-${input.id}`, - circuitIdentifier: "-2F1.1", - power: "120", - quantity: "1", - additionalSourceValues: {}, - }, - planningValues: { - displayName: "Steckdose", - internalDeviceType: "socket", - category: "single_phase", - connectionKind: "socket", - effectiveQuantity: 1, - powerPerUnitW: 120, - simultaneityFactor: 1, - cosPhi: null, - costGroup: null, - remark: null, - }, - overriddenFields: [], - externalRoomMappingId: input.distributionBoardId === "board-1" ? "mapping-1" : null, - distributionBoardId: input.distributionBoardId, - linkedProjectDeviceId: null, - circuitDeviceRowId: input.circuitDeviceRowId, - presenceStatus: "present", - }; -} - -describe("external circuit-list object projection", () => { - it("returns only the board objects with unassigned objects first", () => { - const state: ExternalModelStateSnapshot = { - source: { - id: "source-1", - projectId: "project-1", - name: "Revit-Gesamtmodell", - sourceType: "revit_csv", - }, - importBatches: [], - roomMappings: [{ - id: "mapping-1", - projectId: "project-1", - sourceId: "source-1", - normalizedSourceRoomKey: "number:101", - sourceFloorName: "EG", - sourceRoomNumber: "101", - sourceRoomName: "Besprechung", - roomId: "room-1", - defaultDistributionBoardId: "board-1", - }], - objects: [ - object({ id: "assigned", distributionBoardId: "board-1", circuitDeviceRowId: "row-1", roomNumber: "102" }), - object({ id: "unassigned", distributionBoardId: "board-1", circuitDeviceRowId: null, roomNumber: "101" }), - object({ id: "other-board", distributionBoardId: "board-2", circuitDeviceRowId: null, roomNumber: "001" }), - ], - }; - - const result = createExternalCircuitListObjects({ - state, - distributionBoardId: "board-1", - }); - - assert.equal(result.sourceName, "Revit-Gesamtmodell"); - assert.equal(result.objectCount, 2); - assert.equal(result.unassignedObjectCount, 1); - assert.deepEqual(result.objects.map(({ id }) => id), ["unassigned", "assigned"]); - assert.equal(result.objects[0].sourceRoomName, "Besprechung"); - assert.equal(result.objects[0].roomId, "room-1"); - assert.equal(result.objects[0].sourceCircuitIdentifier, "-2F1.1"); - }); - - it("returns an empty projection before the optional Revit import", () => { - assert.deepEqual( - createExternalCircuitListObjects({ - state: { source: null, importBatches: [], roomMappings: [], objects: [] }, - distributionBoardId: "board-1", - }), - { sourceName: null, objectCount: 0, unassignedObjectCount: 0, objects: [] } - ); - }); -}); diff --git a/tests/external-csv-api-contract.test.ts b/tests/external-csv-api-contract.test.ts deleted file mode 100644 index dfba2ae..0000000 --- a/tests/external-csv-api-contract.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { - applyExternalInitialImportSchema, - MAX_CSV_CONTENT_BASE64_LENGTH, - planExternalInitialImportSchema, - previewExternalCsvSchema, - updateExternalCsvConfigurationSchema, -} from "../src/shared/validation/external-csv.schemas.js"; -import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; -import { externalCsvTestColumns } from "./fixtures/revit-csv-fixtures.js"; - -describe("external CSV API contracts", () => { - it("accepts strict update and preview request envelopes", () => { - assert.equal( - updateExternalCsvConfigurationSchema.safeParse({ - expectedRevision: 4, - configuration: createDefaultExternalCsvConfiguration(externalCsvTestColumns), - }).success, - true - ); - assert.equal( - previewExternalCsvSchema.safeParse({ - fileName: "revit.csv", - contentBase64: "YWJj", - }).success, - true - ); - assert.equal( - planExternalInitialImportSchema.safeParse({ - fileName: "revit.csv", - contentBase64: "YWJj", - }).success, - true - ); - assert.equal( - applyExternalInitialImportSchema.safeParse({ - expectedRevision: 5, - expectedConfigurationVersion: 2, - expectedSha256: "a".repeat(64), - fileName: "revit.csv", - contentBase64: "YWJj", - sourceName: "Revit-Gesamtmodell", - roomDecisions: [], - familyProjectDeviceDecisions: [], - }).success, - true - ); - }); - - it("rejects stale-shaped, oversized and unknown request fields", () => { - assert.equal( - updateExternalCsvConfigurationSchema.safeParse({ - expectedRevision: -1, - configuration: {}, - }).success, - false - ); - assert.equal( - previewExternalCsvSchema.safeParse({ - fileName: "revit.csv", - contentBase64: "YWJj", - apply: true, - }).success, - false - ); - assert.equal( - planExternalInitialImportSchema.safeParse({ - fileName: "revit.csv", - contentBase64: "YWJj", - decisions: [], - }).success, - false - ); - assert.equal( - previewExternalCsvSchema.safeParse({ - fileName: "revit.csv", - contentBase64: "a".repeat(MAX_CSV_CONTENT_BASE64_LENGTH + 1), - }).success, - false - ); - }); -}); diff --git a/tests/external-csv-configuration-project-command.repository.test.ts b/tests/external-csv-configuration-project-command.repository.test.ts deleted file mode 100644 index 0186581..0000000 --- a/tests/external-csv-configuration-project-command.repository.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import path from "node:path"; -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { eq } from "drizzle-orm"; -import { migrate } from "drizzle-orm/better-sqlite3/migrator"; -import { - createDatabaseContext, - type DatabaseContext, -} from "../src/db/database-context.js"; -import { ExternalCsvConfigurationProjectCommandRepository } from "../src/db/repositories/external-csv-configuration-project-command.repository.js"; -import { ExternalCsvConfigurationRepository } from "../src/db/repositories/external-csv-configuration.repository.js"; -import { ProjectTransferRepository } from "../src/db/repositories/project-transfer.repository.js"; -import { ProjectStateRestoreCommandRepository } from "../src/db/repositories/project-state-restore-command.repository.js"; -import { readProjectStateSnapshot } from "../src/db/repositories/project-state-snapshot.persistence.js"; -import { externalCsvConfigurations } from "../src/db/schema/external-csv-configurations.js"; -import { projects } from "../src/db/schema/projects.js"; -import { createExternalCsvConfigurationUpdateProjectCommand } from "../src/domain/models/external-csv-configuration-project-command.model.js"; -import { createProjectStateRestoreCommand } from "../src/domain/models/project-state-restore-command.model.js"; -import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; -import { externalCsvTestColumns } from "./fixtures/revit-csv-fixtures.js"; - -function createTestDatabase(): DatabaseContext { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { - migrationsFolder: path.resolve("src", "db", "migrations"), - }); - context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - return context; -} - -function snapshot(version = 1) { - const configuration = createDefaultExternalCsvConfiguration(externalCsvTestColumns); - configuration.familyTypeRules.push({ - exactFamilyAndType: "Steckdose: Standard", - internalDeviceType: "Steckdose", - connectionKind: null, - category: "single_phase", - quantityRule: { kind: "fixed", quantity: 1 }, - displayNameSuggestion: { kind: "selection-marker" }, - }); - return { - id: "external-config-1", - projectId: "project-1", - configurationVersion: version, - configuration, - }; -} - -describe("external CSV configuration project command", () => { - it("persists insert and update with exact inverse commands", () => { - const context = createTestDatabase(); - try { - const repository = new ExternalCsvConfigurationProjectCommandRepository(context.db); - const initial = snapshot(); - const inserted = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - description: "Revit-CSV-Konfiguration anlegen", - command: createExternalCsvConfigurationUpdateProjectCommand(null, initial), - }); - assert.equal(inserted.revision.revisionNumber, 1); - assert.deepEqual(readConfiguration(context), initial); - assert.deepEqual(inserted.inverse.payload, { expected: initial, target: null }); - - const target = structuredClone(initial); - target.configurationVersion = 2; - target.configuration.decimalSeparator = "."; - const updated = repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(initial, target), - }); - assert.equal(updated.revision.revisionNumber, 2); - assert.deepEqual(readConfiguration(context), target); - assert.deepEqual(updated.inverse.payload, { expected: target, target: initial }); - } finally { - context.close(); - } - }); - - it("rejects stale state and cross-project targets without a partial revision", () => { - const context = createTestDatabase(); - try { - const repository = new ExternalCsvConfigurationProjectCommandRepository(context.db); - const initial = snapshot(); - repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(null, initial), - }); - - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(null, snapshot(2)), - }), - /changed before update/ - ); - const foreign = snapshot(2); - foreign.projectId = "project-2"; - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(initial, foreign), - }), - /identity must remain stable|different project/ - ); - assert.equal(context.db.select({ revision: projects.currentRevision }).from(projects).get()?.revision, 1); - - const skippedVersion = snapshot(3); - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(initial, skippedVersion), - }), - /version must advance by one/ - ); - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(initial, initial), - }), - /did not change/ - ); - } finally { - context.close(); - } - }); - - it("includes configuration in snapshots and remaps it for project duplicates", () => { - const context = createTestDatabase(); - try { - const repository = new ExternalCsvConfigurationProjectCommandRepository(context.db); - const initial = snapshot(); - repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(null, initial), - }); - - const state = readProjectStateSnapshot(context.db, "project-1")?.state; - assert.deepEqual(state?.externalCsvConfiguration, initial); - const transferRepository = new ProjectTransferRepository(context.db); - const transfer = transferRepository.exportProject("project-1"); - assert.ok(transfer); - const duplicate = transferRepository.importDuplicate(transfer); - const duplicatedConfiguration = context.db - .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, duplicate.projectId)) - .get(); - assert.ok(duplicatedConfiguration); - assert.notEqual(duplicatedConfiguration.id, initial.id); - assert.equal(duplicatedConfiguration.projectId, duplicate.projectId); - assert.deepEqual(duplicatedConfiguration.configuration, initial.configuration); - } finally { - context.close(); - } - }); - - it("distinguishes projects without configuration from unknown projects", () => { - const context = createTestDatabase(); - try { - const reader = new ExternalCsvConfigurationRepository(context.db); - assert.deepEqual(reader.getByProject("project-1"), { - projectExists: true, - configuration: null, - }); - assert.deepEqual(reader.getByProject("missing"), { - projectExists: false, - configuration: null, - }); - } finally { - context.close(); - } - }); - - it("restores and undoes the complete configuration through snapshot history", () => { - const context = createTestDatabase(); - try { - const configurationRepository = new ExternalCsvConfigurationProjectCommandRepository(context.db); - const initial = snapshot(); - configurationRepository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(null, initial), - }); - const configuredState = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(configuredState); - configurationRepository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createExternalCsvConfigurationUpdateProjectCommand(initial, null), - }); - const emptyState = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(emptyState); - - const restoreRepository = new ProjectStateRestoreCommandRepository(context.db); - const restored = restoreRepository.execute({ - projectId: "project-1", - expectedRevision: 2, - source: "user", - command: createProjectStateRestoreCommand( - emptyState.payloadSha256, - configuredState.state - ), - }); - assert.deepEqual(readConfiguration(context), initial); - - restoreRepository.execute({ - projectId: "project-1", - expectedRevision: 3, - source: "undo", - historyTargetChangeSetId: restored.revision.changeSetId, - command: restored.inverse, - }); - assert.equal(readConfiguration(context), null); - } finally { - context.close(); - } - }); -}); - -function readConfiguration(context: DatabaseContext) { - return context.db - .select() - .from(externalCsvConfigurations) - .where(eq(externalCsvConfigurations.projectId, "project-1")) - .get() ?? null; -} diff --git a/tests/external-csv-preview.test.ts b/tests/external-csv-preview.test.ts deleted file mode 100644 index b786ebd..0000000 --- a/tests/external-csv-preview.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { createExternalCsvPreview } from "../src/external-model/application/external-csv-preview.js"; -import { - externalCsvTestConfiguration, - firstIfcGuid, - quotedRevitCsv, - utf8Bytes, -} from "./fixtures/revit-csv-fixtures.js"; - -describe("external CSV preview", () => { - it("projects transport statistics and mapped object source values without writes", () => { - const configuration = structuredClone(externalCsvTestConfiguration); - configuration.additionalSourceMappings.push({ - sourceColumn: "Raumname", - targetField: "sourceRoomLabel", - }); - // The additional mapping intentionally needs a distinct source column in - // persisted configuration, so use a separately named synthetic header. - configuration.additionalSourceMappings[0].sourceColumn = "Zusatzwert"; - const csv = quotedRevitCsv - .replace('"Anzahl";"IfcGUID"', '"Anzahl";"Zusatzwert";"IfcGUID"') - .replaceAll(';"2";"0Ab', ';"2";"A";"0Ab') - .replaceAll(';"1";"1Ab', ';"1";"B";"1Ab') - .replaceAll(';"1";""', ';"1";"C";""') - .replaceAll(';"";""\r\n', ';"";"";""\r\n'); - - const preview = createExternalCsvPreview({ - fileName: "export.csv", - bytes: utf8Bytes(csv, true), - configuration, - }); - - assert.equal(preview.fileName, "export.csv"); - assert.equal(preview.headerRowNumber, 2); - assert.equal(preview.rowCount, 7); - assert.equal(preview.objectCount, 2); - assert.equal(preview.passthroughCount, 2); - assert.equal(preview.nonEmptyPassthroughCount, 1); - assert.equal(preview.suspectObjectCount, 1); - assert.deepEqual(preview.suspectRowNumbers, [6]); - assert.match(preview.sha256, /^[a-f0-9]{64}$/); - assert.deepEqual(preview.objects[0], { - rowNumber: 4, - ifcGuid: firstIfcGuid, - roomNumber: "01/101", - roomName: "Technik", - familyAndType: "Steckdose: Doppelsteckdose", - selectionMarker: "Arbeitsplatz", - circuitIdentifier: "UV_AV_01-2F1", - power: "120,5", - quantity: "2", - additionalSourceValues: { sourceRoomLabel: "A" }, - }); - }); -}); diff --git a/tests/external-csv-transport.test.ts b/tests/external-csv-transport.test.ts deleted file mode 100644 index 11a44ac..0000000 --- a/tests/external-csv-transport.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { - ExternalCsvParseError, - parseExternalCsv, - serializeExternalCsv, -} from "../src/external-model/csv/external-csv-transport.js"; -import { - externalCsvTestConfiguration, - firstIfcGuid, - quotedRevitCsv, - utf8Bytes, -} from "./fixtures/revit-csv-fixtures.js"; - -describe("external CSV transport", () => { - it("detects the observed Revit dialect and classifies every row", () => { - const document = parseExternalCsv( - utf8Bytes(quotedRevitCsv, true), - externalCsvTestConfiguration - ); - - assert.deepEqual(document.dialect, { - encoding: "utf-8", - hasBom: true, - delimiter: ";", - lineEnding: "\r\n", - quoteCharacter: '"', - quoteAllFields: true, - hasTrailingLineEnding: true, - }); - assert.equal(document.headerRowIndex, 1); - assert.deepEqual( - document.rows.map((row) => row.classification), - [ - "metadata", - "header", - "passthrough", - "object", - "passthrough", - "suspect-object", - "object", - ] - ); - assert.equal(document.rows[6].cells[2].value, 'Büro "Nord"'); - }); - - it("round-trips BOM, CRLF, quotation, order and cell values byte for byte", () => { - const source = utf8Bytes(quotedRevitCsv, true); - const document = parseExternalCsv(source, externalCsvTestConfiguration); - - assert.deepEqual(serializeExternalCsv(document), source); - }); - - it("parses exports without an optional quantity column", () => { - const configuration = { - ...externalCsvTestConfiguration, - columns: { - ...externalCsvTestConfiguration.columns, - quantity: null, - }, - }; - const csv = [ - '"Projekt-Export";"";"";"";"";"";""', - '"Stromkreis";"Raumnummer";"Raumname";"Familie und Typ";"CAx_Auswahlkenner";"Elektrische Leistung";"IfcGUID"', - `"UV_AV_01-2F1";"01/101";"Technik";"Steckdose: Standard";"Arbeitsplatz";"100";"${firstIfcGuid}"`, - ].join("\r\n") + "\r\n"; - - const document = parseExternalCsv(utf8Bytes(csv, true), configuration); - - assert.equal( - document.rows.filter((row) => row.classification === "object").length, - 1 - ); - }); - - it("preserves embedded delimiters and line endings inside quoted cells", () => { - const csv = quotedRevitCsv.replace( - '"Steckdose: Doppelsteckdose"', - '"Steckdose; Doppel\r\nsteckdose"' - ); - const source = utf8Bytes(csv, true); - const document = parseExternalCsv(source, externalCsvTestConfiguration); - - assert.equal( - document.rows[3].cells[3].value, - "Steckdose; Doppel\r\nsteckdose" - ); - assert.deepEqual(serializeExternalCsv(document), source); - }); - - it("blocks missing and ambiguous configured headers", () => { - assertParseError( - utf8Bytes(quotedRevitCsv.replace("IfcGUID", "Andere ID")), - "header-not-found" - ); - const duplicatedHeader = quotedRevitCsv.replace( - '"";"";"";"";"";"";"";""', - quotedRevitCsv.split("\r\n")[1] - ); - assertParseError(utf8Bytes(duplicatedHeader), "ambiguous-header"); - - const duplicateConfiguredColumn = quotedRevitCsv.replace( - '"Stromkreis";"Raumnummer"', - '"Stromkreis";"Raumnummer";"Raumnummer"' - ); - assertParseError( - utf8Bytes(duplicateConfiguredColumn), - "ambiguous-header" - ); - }); - - it("blocks invalid and duplicate non-empty IfcGUIDs", () => { - assertParseError( - utf8Bytes(quotedRevitCsv.replace(firstIfcGuid, "not-an-ifc-guid")), - "invalid-ifc-guid" - ); - assertParseError( - utf8Bytes(quotedRevitCsv.replace(firstIfcGuid, ` ${firstIfcGuid}`)), - "invalid-ifc-guid" - ); - const duplicate = quotedRevitCsv.replace( - "1AbCdEfGhIjKlMnOpQrStu", - firstIfcGuid - ); - assertParseError(utf8Bytes(duplicate), "duplicate-ifc-guid"); - }); - - it("blocks invalid UTF-8, unterminated quotes and mixed row endings", () => { - assertParseError(new Uint8Array([0xff, 0xfe, 0xfd]), "invalid-encoding"); - assertParseError( - utf8Bytes(quotedRevitCsv.replace(/"\r\n$/, "\r\n")), - "invalid-csv" - ); - assertParseError( - utf8Bytes(quotedRevitCsv.replace("\r\n", "\n")), - "invalid-csv" - ); - }); -}); - -function assertParseError(input: Uint8Array, code: ExternalCsvParseError["code"]) { - assert.throws( - () => parseExternalCsv(input, externalCsvTestConfiguration), - (error: unknown) => error instanceof ExternalCsvParseError && error.code === code - ); -} diff --git a/tests/external-initial-import-plan.test.ts b/tests/external-initial-import-plan.test.ts deleted file mode 100644 index 7fc1a43..0000000 --- a/tests/external-initial-import-plan.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { createExternalInitialImportPlan } from "../src/external-model/application/external-initial-import-plan.js"; -import { buildExternalInitialImportTarget } from "../src/external-model/application/external-initial-import-target.js"; -import { parseExternalCsv } from "../src/external-model/csv/external-csv-transport.js"; -import { - externalCsvTestConfiguration, - firstIfcGuid, - quotedRevitCsv, - utf8Bytes, -} from "./fixtures/revit-csv-fixtures.js"; - -describe("external initial import plan", () => { - it("groups source rooms and exposes exact room and classification suggestions", () => { - const configuration = structuredClone(externalCsvTestConfiguration); - configuration.familyTypeRules.push({ - exactFamilyAndType: "Steckdose: Doppelsteckdose", - internalDeviceType: "Steckdose", - connectionKind: "socket", - category: "single_phase", - quantityRule: { kind: "mapped-column" }, - displayNameSuggestion: { kind: "selection-marker" }, - }); - - const plan = createExternalInitialImportPlan({ - fileName: "revit.csv", - bytes: utf8Bytes(quotedRevitCsv, true), - configurationVersion: 4, - configuration, - floors: [{ id: "floor-1", name: "EG", sortOrder: 10 }], - rooms: [{ - id: "room-1", - floorId: "floor-1", - roomNumber: "01/101", - roomName: "Technik Bestand", - }], - distributionBoards: [{ id: "board-1", name: "UV 1", floorId: "floor-1" }], - projectDevices: [{ - id: "device-1", - name: "socket", - displayName: "Steckdose", - category: "single_phase", - connectionKind: "socket", - powerPerUnit: 0.12, - }], - }); - - assert.equal(plan.configurationVersion, 4); - assert.equal(plan.objectCount, 2); - assert.equal(plan.sourceRooms.length, 2); - assert.deepEqual( - plan.sourceRooms.map((room) => ({ - number: room.roomNumber, - status: room.matchStatus, - suggested: room.suggestedRoomId, - })), - [ - { number: "01/101", status: "exact-number", suggested: "room-1" }, - { number: "01/103", status: "new", suggested: null }, - ] - ); - assert.equal(plan.familyGroups.length, 2); - assert.equal(plan.issueCounts.unknownFamilyAndType, 1); - assert.equal(plan.issueCounts.invalidPower, 0); - assert.equal(plan.issueCounts.invalidQuantity, 0); - assert.equal(plan.objects[0].ifcGuid, firstIfcGuid); - assert.equal(plan.objects[0].suggestedPlanningValues.effectiveQuantity, 2); - assert.equal(plan.existing.distributionBoards[0].id, "board-1"); - assert.equal(plan.existing.projectDevices[0].id, "device-1"); - }); - - it("builds a stable row-free target only after every family is classified", () => { - const configuration = structuredClone(externalCsvTestConfiguration); - for (const exactFamilyAndType of [ - "Steckdose: Doppelsteckdose", - "Steckdose: Standard", - ]) { - configuration.familyTypeRules.push({ - exactFamilyAndType, - internalDeviceType: "Steckdose", - connectionKind: "socket", - category: "single_phase", - quantityRule: exactFamilyAndType.includes("Doppel") - ? { kind: "mapped-column" } - : { kind: "fixed", quantity: 1 }, - displayNameSuggestion: { kind: "selection-marker" }, - }); - } - const bytes = utf8Bytes(quotedRevitCsv, true); - const plan = createExternalInitialImportPlan({ - fileName: "revit.csv", - bytes, - configurationVersion: 2, - configuration, - floors: [], - rooms: [], - distributionBoards: [], - projectDevices: [], - }); - let id = 0; - const target = buildExternalInitialImportTarget({ - projectId: "project-1", - expectedRevision: 7, - sourceName: "Revit-Gesamtmodell", - importedAtIso: "2026-08-02T17:00:00.000Z", - configurationVersion: 2, - configuration, - originalContentBase64: Buffer.from(bytes).toString("base64"), - document: parseExternalCsv(bytes, configuration), - plan, - roomDecisions: plan.sourceRooms.map((room) => ({ - sourceRoomKey: room.sourceRoomKey, - roomId: null, - defaultDistributionBoardId: null, - })), - familyProjectDeviceDecisions: plan.familyGroups.map((group) => ({ - familyAndType: group.familyAndType, - projectDeviceId: null, - })), - createId: () => `generated-${++id}`, - }); - - assert.equal(target.importBatches[0].appliedProjectRevision, 8); - assert.equal(target.importBatches[0].configurationVersion, 2); - assert.equal(target.objects.length, 2); - assert.ok(target.objects.every((object) => object.circuitDeviceRowId === null)); - assert.ok(target.objects.every((object) => object.overriddenFields.length === 0)); - assert.throws( - () => buildExternalInitialImportTarget({ - projectId: "project-1", - expectedRevision: 7, - sourceName: "Revit-Gesamtmodell", - importedAtIso: "2026-08-02T17:00:00.000Z", - configurationVersion: 2, - configuration, - originalContentBase64: Buffer.from(bytes).toString("base64"), - document: parseExternalCsv(bytes, configuration), - plan, - roomDecisions: [], - familyProjectDeviceDecisions: plan.familyGroups.map((group) => ({ - familyAndType: group.familyAndType, - projectDeviceId: null, - })), - createId: () => "unused", - }), - /Quellraum-Entscheidungen/ - ); - }); -}); diff --git a/tests/external-initial-import-project-command.repository.test.ts b/tests/external-initial-import-project-command.repository.test.ts deleted file mode 100644 index b9acb83..0000000 --- a/tests/external-initial-import-project-command.repository.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import crypto from "node:crypto"; -import path from "node:path"; -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { migrate } from "drizzle-orm/better-sqlite3/migrator"; -import { createDatabaseContext } from "../src/db/database-context.js"; -import { ExternalInitialImportProjectCommandRepository } from "../src/db/repositories/external-initial-import-project-command.repository.js"; -import { ExternalModelStateRepository } from "../src/db/repositories/external-model-state.repository.js"; -import { externalCsvConfigurations } from "../src/db/schema/external-csv-configurations.js"; -import { projects } from "../src/db/schema/projects.js"; -import { - createEmptyExternalModelState, - createExternalInitialImportProjectCommand, -} from "../src/domain/models/external-initial-import-project-command.model.js"; -import { createExternalCsvPreview } from "../src/external-model/application/external-csv-preview.js"; -import { parseExternalCsv } from "../src/external-model/csv/external-csv-transport.js"; -import type { ExternalModelStateSnapshot } from "../src/external-model/domain/external-model-contracts.js"; -import { - createExternalRoomKey, - projectInitialExternalObject, -} from "../src/external-model/domain/external-model-matching.js"; -import { - externalCsvTestConfiguration, - quotedRevitCsv, - utf8Bytes, -} from "./fixtures/revit-csv-fixtures.js"; - -function createTestContext() { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - const configuration = configuredCsv(); - context.db.insert(externalCsvConfigurations).values({ - id: "config-1", - projectId: "project-1", - configurationVersion: 1, - configuration, - }).run(); - return { context, configuration }; -} - -function configuredCsv() { - const configuration = structuredClone(externalCsvTestConfiguration); - configuration.familyTypeRules.push( - { - exactFamilyAndType: "Steckdose: Doppelsteckdose", - internalDeviceType: "Steckdose", - connectionKind: "socket", - category: "single_phase", - quantityRule: { kind: "mapped-column" }, - displayNameSuggestion: { kind: "selection-marker" }, - }, - { - exactFamilyAndType: "Steckdose: Standard", - internalDeviceType: "Steckdose", - connectionKind: "socket", - category: "single_phase", - quantityRule: { kind: "fixed", quantity: 1 }, - displayNameSuggestion: { kind: "selection-marker" }, - } - ); - return configuration; -} - -function initialState( - configuration: ReturnType -): ExternalModelStateSnapshot { - const bytes = utf8Bytes(quotedRevitCsv, true); - const preview = createExternalCsvPreview({ - fileName: "revit.csv", - bytes, - configuration, - }); - const roomKeys = [...new Set(preview.objects.map((object) => - createExternalRoomKey(object.roomNumber, object.roomName) - ).filter((key): key is string => key !== null))]; - const roomMappings = roomKeys.map((key, index) => { - const object = preview.objects.find( - (candidate) => createExternalRoomKey(candidate.roomNumber, candidate.roomName) === key - )!; - return { - id: `mapping-${index + 1}`, - projectId: "project-1", - sourceId: "source-1", - normalizedSourceRoomKey: key, - sourceFloorName: null, - sourceRoomNumber: object.roomNumber, - sourceRoomName: object.roomName, - roomId: null, - defaultDistributionBoardId: null, - }; - }); - const mappingByKey = new Map( - roomMappings.map((mapping) => [mapping.normalizedSourceRoomKey, mapping.id]) - ); - return { - source: { - id: "source-1", - projectId: "project-1", - name: "Revit-Gesamtmodell", - sourceType: "revit_csv", - }, - importBatches: [{ - id: "batch-1", - projectId: "project-1", - sourceId: "source-1", - importKind: "initial", - importedAtIso: "2026-08-02T16:00:00.000Z", - fileName: "revit.csv", - sha256: crypto.createHash("sha256").update(bytes).digest("hex"), - appliedProjectRevision: 1, - configurationVersion: 1, - configurationSnapshot: configuration, - originalContentBase64: Buffer.from(bytes).toString("base64"), - document: parseExternalCsv(bytes, configuration), - }], - roomMappings, - objects: preview.objects.map((candidate, index) => { - const projected = projectInitialExternalObject(candidate, configuration); - const roomKey = createExternalRoomKey(candidate.roomNumber, candidate.roomName); - return { - id: `object-${index + 1}`, - projectId: "project-1", - sourceId: "source-1", - ifcGuid: projected.ifcGuid, - lastSeenImportBatchId: "batch-1", - lastAcceptedImportBatchId: "batch-1", - acceptedSourceValues: projected.sourceValues, - planningValues: projected.planningValues, - overriddenFields: [], - externalRoomMappingId: roomKey === null ? null : mappingByKey.get(roomKey)!, - distributionBoardId: null, - linkedProjectDeviceId: null, - circuitDeviceRowId: null, - presenceStatus: "present", - }; - }), - }; -} - -describe("external initial import project command", () => { - it("commits the complete import and supports persisted undo and redo", () => { - const { context, configuration } = createTestContext(); - try { - const target = initialState(configuration); - const repository = new ExternalInitialImportProjectCommandRepository(context.db); - const inserted = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - description: "Revit-Erstimport übernehmen", - command: createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - target - ), - }); - assert.equal(inserted.revision.revisionNumber, 1); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.objects.length, - 2 - ); - assert.ok( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.objects.every((object) => object.circuitDeviceRowId === null) - ); - - const undone = repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: inserted.revision.changeSetId, - command: inserted.inverse, - }); - assert.equal(undone.revision.revisionNumber, 2); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.source, - null - ); - - repository.execute({ - projectId: "project-1", - expectedRevision: 2, - source: "redo", - historyTargetChangeSetId: inserted.revision.changeSetId, - command: undone.inverse, - }); - const redone = new ExternalModelStateRepository(context.db) - .getByProject("project-1").state; - assert.deepEqual(redone.objects.map((object) => object.id), ["object-1", "object-2"]); - assert.equal(redone.importBatches[0].configurationVersion, 1); - } finally { - context.close(); - } - }); - - it("rejects a target state with zero classified objects before writing anything", () => { - // assertPopulatedInitialState requires at least one object, so a CSV - // that classified none must be rejected at command construction, not - // reach the persistence layer's bulk insert. - const { context, configuration } = createTestContext(); - try { - const target: ExternalModelStateSnapshot = { - ...initialState(configuration), - roomMappings: [], - objects: [], - }; - assert.throws( - () => - createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - target - ), - /at least one object/ - ); - } finally { - context.close(); - } - }); - - it("rejects changed state, checksum drift and row assignment", () => { - const { context, configuration } = createTestContext(); - try { - const target = initialState(configuration); - const repository = new ExternalInitialImportProjectCommandRepository(context.db); - const assigned = structuredClone(target); - assigned.objects[0].circuitDeviceRowId = "row-1"; - assert.throws( - () => createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - assigned - ), - /must not assign circuit device rows/ - ); - - const invalidHash = structuredClone(target); - invalidHash.importBatches[0].sha256 = "b".repeat(64); - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - invalidHash - ), - }), - /checksum is invalid/ - ); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.source, - null - ); - } finally { - context.close(); - } - }); - - it("rolls back all external rows when late history persistence fails", () => { - const { context, configuration } = createTestContext(); - try { - context.sqlite.exec(` - CREATE TRIGGER fail_external_import_history - BEFORE INSERT ON project_change_sets - BEGIN - SELECT RAISE(ABORT, 'late history failure'); - END; - `); - const repository = new ExternalInitialImportProjectCommandRepository(context.db); - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createExternalInitialImportProjectCommand( - createEmptyExternalModelState(), - initialState(configuration) - ), - }), - /late history failure/ - ); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.source, - null - ); - assert.equal( - context.db.select({ revision: projects.currentRevision }).from(projects).get()?.revision, - 0 - ); - } finally { - context.close(); - } - }); -}); diff --git a/tests/external-model-configuration.test.ts b/tests/external-model-configuration.test.ts new file mode 100644 index 0000000..7c1066a --- /dev/null +++ b/tests/external-model-configuration.test.ts @@ -0,0 +1,132 @@ +import path from "node:path"; +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { eq } from "drizzle-orm"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createDatabaseContext, type DatabaseContext } from "../src/db/database-context.js"; +import { ExternalModelConfigurationProjectCommandRepository } from "../src/db/repositories/external-model-configuration-project-command.repository.js"; +import { ExternalModelConfigurationRepository } from "../src/db/repositories/external-model-configuration.repository.js"; +import { ProjectTransferRepository } from "../src/db/repositories/project-transfer.repository.js"; +import { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; +import { projects } from "../src/db/schema/projects.js"; +import { createExternalModelConfigurationUpdateProjectCommand } from "../src/domain/models/external-model-configuration-project-command.model.js"; +import { + assertExternalModelConfiguration, + createDefaultExternalModelConfiguration, +} from "../src/external-model/configuration/external-model-configuration.js"; + +const deviceTypeId = "10000000-0000-4000-8000-000000000001"; +const ruleId = "20000000-0000-4000-8000-000000000001"; + +function configuration() { + const value = createDefaultExternalModelConfiguration(); + value.deviceTypes.push({ + id: deviceTypeId, + name: "Steckdose", + category: "single_phase", + defaults: { powerPerUnitW: 200, simultaneityFactor: null, cosPhi: 0.95, costGroup: "440" }, + }); + value.familyTypeRules.push({ + id: ruleId, + exactFamilyAndType: "Steckdose: Standard", + deviceTypeId, + quantityRule: "socketCount", + }); + return value; +} + +function snapshot(projectId = "project-1") { + return { id: "config-1", projectId, configuration: configuration() }; +} + +function createTestDatabase(): DatabaseContext { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); + return context; +} + +describe("external model configuration", () => { + it("validates the single Worksharing-ID mapping and exact family rules", () => { + const value = configuration(); + assert.doesNotThrow(() => assertExternalModelConfiguration(value)); + assert.equal("idColumn" in value.layout, false); + + const duplicate = structuredClone(value); + duplicate.columns.ifcGuid = duplicate.columns.worksharingId; + assert.throws(() => assertExternalModelConfiguration(duplicate), /nicht eindeutig/); + + const unknownType = structuredClone(value); + unknownType.familyTypeRules[0]!.deviceTypeId = "30000000-0000-4000-8000-000000000001"; + assert.throws(() => assertExternalModelConfiguration(unknownType), /unbekannte Ger.*teart/); + }); + + it("persists changes without an independent configuration revision", () => { + const context = createTestDatabase(); + try { + const repository = new ExternalModelConfigurationProjectCommandRepository(context.db); + const initial = snapshot(); + const inserted = repository.execute({ + projectId: "project-1", + expectedRevision: 0, + source: "user", + command: createExternalModelConfigurationUpdateProjectCommand(null, initial), + }); + assert.equal(inserted.revision.revisionNumber, 1); + assert.equal("configurationVersion" in initial, false); + + const target = structuredClone(initial); + target.configuration.deviceTypes[0]!.name = "Steckdose allgemein"; + const updated = repository.execute({ + projectId: "project-1", + expectedRevision: 1, + source: "user", + command: createExternalModelConfigurationUpdateProjectCommand(initial, target), + }); + assert.equal(updated.revision.revisionNumber, 2); + assert.deepEqual(updated.inverse.payload, { expected: target, target: initial }); + assert.throws( + () => repository.execute({ + projectId: "project-1", + expectedRevision: 2, + source: "user", + command: createExternalModelConfigurationUpdateProjectCommand(initial, target), + }), + /zwischenzeitlich ge.*ndert/ + ); + } finally { + context.close(); + } + }); + + it("distinguishes missing projects and remaps configuration identities on duplicate", () => { + const context = createTestDatabase(); + try { + const reader = new ExternalModelConfigurationRepository(context.db); + assert.deepEqual(reader.getByProject("project-1"), { projectExists: true, configuration: null }); + assert.deepEqual(reader.getByProject("missing"), { projectExists: false, configuration: null }); + + new ExternalModelConfigurationProjectCommandRepository(context.db).execute({ + projectId: "project-1", + expectedRevision: 0, + source: "user", + command: createExternalModelConfigurationUpdateProjectCommand(null, snapshot()), + }); + const transferRepository = new ProjectTransferRepository(context.db); + const transfer = transferRepository.exportProject("project-1"); + assert.ok(transfer); + const duplicate = transferRepository.importDuplicate(transfer); + const copied = context.db.select().from(externalModelConfigurations) + .where(eq(externalModelConfigurations.projectId, duplicate.projectId)).get(); + assert.ok(copied); + assert.notEqual(copied.id, "config-1"); + assert.notEqual(copied.configuration.deviceTypes[0]!.id, deviceTypeId); + assert.equal( + copied.configuration.familyTypeRules[0]!.deviceTypeId, + copied.configuration.deviceTypes[0]!.id + ); + } finally { + context.close(); + } + }); +}); diff --git a/tests/external-model-foundation.test.ts b/tests/external-model-foundation.test.ts deleted file mode 100644 index 08319ec..0000000 --- a/tests/external-model-foundation.test.ts +++ /dev/null @@ -1,431 +0,0 @@ -import path from "node:path"; -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { migrate } from "drizzle-orm/better-sqlite3/migrator"; -import { createDatabaseContext } from "../src/db/database-context.js"; -import { ExternalModelStateRepository } from "../src/db/repositories/external-model-state.repository.js"; -import { ProjectStateRestoreCommandRepository } from "../src/db/repositories/project-state-restore-command.repository.js"; -import { readProjectStateSnapshot } from "../src/db/repositories/project-state-snapshot.persistence.js"; -import { ProjectTransferRepository } from "../src/db/repositories/project-transfer.repository.js"; -import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; -import { circuitLists } from "../src/db/schema/circuit-lists.js"; -import { circuitSections } from "../src/db/schema/circuit-sections.js"; -import { circuits } from "../src/db/schema/circuits.js"; -import { distributionBoards } from "../src/db/schema/distribution-boards.js"; -import { externalImportBatches } from "../src/db/schema/external-import-batches.js"; -import { externalModelObjects } from "../src/db/schema/external-model-objects.js"; -import { externalModelSources } from "../src/db/schema/external-model-sources.js"; -import { externalRoomMappings } from "../src/db/schema/external-room-mappings.js"; -import { floors } from "../src/db/schema/floors.js"; -import { projectDevices } from "../src/db/schema/project-devices.js"; -import { projects } from "../src/db/schema/projects.js"; -import { rooms } from "../src/db/schema/rooms.js"; -import { createProjectStateRestoreCommand } from "../src/domain/models/project-state-restore-command.model.js"; -import { projectStateSnapshotSchemaVersion } from "../src/domain/models/project-state-snapshot.model.js"; -import { createExternalCsvPreview } from "../src/external-model/application/external-csv-preview.js"; -import { parseExternalCsv } from "../src/external-model/csv/external-csv-transport.js"; -import { - createExternalRoomKey, - indexExternalObjectsByIfcGuid, - projectInitialExternalObject, -} from "../src/external-model/domain/external-model-matching.js"; -import { - externalCsvTestConfiguration, - firstIfcGuid, - quotedRevitCsv, - utf8Bytes, -} from "./fixtures/revit-csv-fixtures.js"; - -function configuredCsv() { - const configuration = structuredClone(externalCsvTestConfiguration); - configuration.familyTypeRules.push({ - exactFamilyAndType: "Steckdose: Doppelsteckdose", - internalDeviceType: "Steckdose", - connectionKind: "socket", - category: "single_phase", - quantityRule: { kind: "mapped-column" }, - displayNameSuggestion: { kind: "selection-marker" }, - }); - return configuration; -} - -describe("external model matching", () => { - it("normalizes source rooms and rejects duplicate IFC identities", () => { - assert.equal(createExternalRoomKey(" 01/101 ", "Technik"), "number:01/101"); - assert.equal(createExternalRoomKey("", " Büro Nord "), "name:BÜRO NORD"); - assert.equal(createExternalRoomKey(" ", " "), null); - assert.throws( - () => indexExternalObjectsByIfcGuid([{ ifcGuid: firstIfcGuid }, { ifcGuid: firstIfcGuid }]), - /Duplicate IfcGUID/ - ); - }); - - it("derives initial planning values from an exact family rule", () => { - const configuration = configuredCsv(); - const preview = createExternalCsvPreview({ - fileName: "revit.csv", - bytes: utf8Bytes(quotedRevitCsv, true), - configuration, - }); - const projected = projectInitialExternalObject(preview.objects[0], configuration); - - assert.deepEqual(projected.issues, []); - assert.equal(projected.ifcGuid, firstIfcGuid); - assert.equal(projected.planningValues.displayName, "Arbeitsplatz"); - assert.equal(projected.planningValues.category, "single_phase"); - assert.equal(projected.planningValues.effectiveQuantity, 2); - assert.equal(projected.planningValues.powerPerUnitW, 120.5); - }); - - it("keeps unclassified or invalid values visible as issues", () => { - const projected = projectInitialExternalObject( - { - rowNumber: 4, - ifcGuid: firstIfcGuid, - roomNumber: "", - roomName: "", - familyAndType: "Unbekannt", - selectionMarker: "", - circuitIdentifier: "", - power: "12,3,4", - quantity: "0", - additionalSourceValues: {}, - }, - externalCsvTestConfiguration - ); - - assert.deepEqual(projected.issues, [ - "unknown-family-and-type", - "missing-room", - "invalid-power", - ]); - assert.equal(projected.planningValues.powerPerUnitW, null); - }); -}); - -describe("external model state repository", () => { - it("reads a deterministic complete external state without changing project data", () => { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - try { - context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - context.db.insert(externalModelSources).values({ - id: "source-1", - projectId: "project-1", - name: "Revit-Gesamtmodell", - sourceType: "revit_csv", - }).run(); - const configuration = configuredCsv(); - const bytes = utf8Bytes(quotedRevitCsv, true); - const document = parseExternalCsv(bytes, configuration); - context.db.insert(externalImportBatches).values({ - id: "batch-1", - projectId: "project-1", - sourceId: "source-1", - importKind: "initial", - importedAtIso: "2026-08-02T15:30:00.000Z", - fileName: "revit.csv", - sha256: "hash", - appliedProjectRevision: 1, - configurationVersion: 1, - configurationSnapshot: configuration, - originalBytes: Buffer.from(bytes), - document, - }).run(); - context.db.insert(externalRoomMappings).values({ - id: "mapping-1", - projectId: "project-1", - sourceId: "source-1", - normalizedSourceRoomKey: "number:01/101", - sourceFloorName: null, - sourceRoomNumber: "01/101", - sourceRoomName: "Technik", - roomId: null, - defaultDistributionBoardId: null, - }).run(); - const preview = createExternalCsvPreview({ - fileName: "revit.csv", - bytes, - configuration, - }); - const projected = projectInitialExternalObject(preview.objects[0], configuration); - context.db.insert(externalModelObjects).values({ - id: "object-1", - projectId: "project-1", - sourceId: "source-1", - ifcGuid: projected.ifcGuid, - lastSeenImportBatchId: "batch-1", - lastAcceptedImportBatchId: "batch-1", - acceptedSourceValues: projected.sourceValues, - planningValues: projected.planningValues, - overriddenFields: [], - externalRoomMappingId: "mapping-1", - distributionBoardId: null, - linkedProjectDeviceId: null, - circuitDeviceRowId: null, - presenceStatus: "present", - }).run(); - - const result = new ExternalModelStateRepository(context.db).getByProject("project-1"); - assert.equal(result.projectExists, true); - assert.equal(result.state.source?.id, "source-1"); - assert.equal(result.state.importBatches[0].originalContentBase64, Buffer.from(bytes).toString("base64")); - assert.equal(result.state.roomMappings[0].normalizedSourceRoomKey, "number:01/101"); - assert.equal(result.state.objects[0].ifcGuid, firstIfcGuid); - assert.equal(result.state.objects[0].circuitDeviceRowId, null); - assert.equal(result.state.objects[0].planningValues.effectiveQuantity, 2); - - assert.throws( - () => context.db.insert(externalModelObjects).values({ - ...context.db.select().from(externalModelObjects).get()!, - id: "object-2", - }).run(), - /UNIQUE constraint failed/ - ); - } finally { - context.close(); - } - }); - - it("distinguishes an empty project from an unknown project", () => { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - try { - context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - const repository = new ExternalModelStateRepository(context.db); - assert.deepEqual(repository.getByProject("project-1"), { - projectExists: true, - state: { source: null, importBatches: [], roomMappings: [], objects: [] }, - }); - assert.equal(repository.getByProject("missing").projectExists, false); - } finally { - context.close(); - } - }); -}); - -describe("external model snapshot and transfer", () => { - it("captures, restores and undoes the complete external state", () => { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - try { - insertLinkedExternalFixture(context.db); - const populated = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(populated); - assert.equal(populated.state.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(populated.state.externalModel.objects[0].circuitDeviceRowId, "row-1"); - - context.db.delete(externalModelSources).run(); - const empty = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(empty); - assert.equal(empty.state.externalModel.source, null); - - const repository = new ProjectStateRestoreCommandRepository(context.db); - const restored = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createProjectStateRestoreCommand( - empty.payloadSha256, - populated.state - ), - }); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.objects[0].linkedProjectDeviceId, - "device-1" - ); - - repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: restored.revision.changeSetId, - command: restored.inverse, - }); - assert.equal( - new ExternalModelStateRepository(context.db).getByProject("project-1") - .state.source, - null - ); - } finally { - context.close(); - } - }); - - it("remaps every internal external-model link for a project duplicate", () => { - const context = createDatabaseContext(":memory:"); - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - try { - insertLinkedExternalFixture(context.db); - const transferRepository = new ProjectTransferRepository(context.db); - const transfer = transferRepository.exportProject("project-1"); - assert.ok(transfer); - const duplicate = transferRepository.importDuplicate(transfer); - const copied = new ExternalModelStateRepository(context.db) - .getByProject(duplicate.projectId).state; - - assert.notEqual(copied.source?.id, "source-1"); - assert.notEqual(copied.importBatches[0].id, "batch-1"); - assert.notEqual(copied.roomMappings[0].id, "mapping-1"); - assert.notEqual(copied.objects[0].id, "object-1"); - assert.equal(copied.objects[0].ifcGuid, firstIfcGuid); - assert.equal(copied.objects[0].lastSeenImportBatchId, copied.importBatches[0].id); - assert.equal(copied.objects[0].externalRoomMappingId, copied.roomMappings[0].id); - assert.notEqual(copied.objects[0].distributionBoardId, "board-1"); - assert.notEqual(copied.objects[0].linkedProjectDeviceId, "device-1"); - assert.notEqual(copied.objects[0].circuitDeviceRowId, "row-1"); - assert.equal( - copied.importBatches[0].originalContentBase64, - Buffer.from(utf8Bytes(quotedRevitCsv, true)).toString("base64") - ); - } finally { - context.close(); - } - }); -}); - -function insertLinkedExternalFixture(database: ReturnType["db"]) { - database.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - database.insert(floors).values({ - id: "floor-1", - projectId: "project-1", - name: "EG", - sortOrder: 10, - }).run(); - database.insert(rooms).values({ - id: "room-1", - projectId: "project-1", - floorId: "floor-1", - roomNumber: "01/101", - roomName: "Technik", - }).run(); - database.insert(projectDevices).values({ - id: "device-1", - projectId: "project-1", - name: "socket", - displayName: "Steckdose", - phaseType: "single_phase", - connectionKind: "socket", - costGroup: null, - category: "single_phase", - quantity: 1, - powerPerUnit: 0.12, - simultaneityFactor: 1, - cosPhi: null, - remark: null, - voltageV: 230, - }).run(); - database.insert(distributionBoards).values({ - id: "board-1", - projectId: "project-1", - name: "UV 1", - floorId: "floor-1", - supplyType: "AV", - simultaneityFactor: 1, - }).run(); - database.insert(circuitLists).values({ - id: "list-1", - projectId: "project-1", - distributionBoardId: "board-1", - name: "UV 1 Stromkreisliste", - }).run(); - database.insert(circuitSections).values({ - id: "section-1", - circuitListId: "list-1", - key: "single_phase", - displayName: "1-phasig 1", - prefix: "-2F1.", - sortOrder: 10, - category: "single_phase", - groupNumber: 1, - }).run(); - database.insert(circuits).values({ - id: "circuit-1", - circuitListId: "list-1", - sectionId: "section-1", - equipmentIdentifier: "-2F1.1", - displayName: "Steckdosen", - sortOrder: 10, - voltage: 230, - isReserve: 0, - }).run(); - database.insert(circuitDeviceRows).values({ - id: "row-1", - circuitId: "circuit-1", - linkedProjectDeviceId: "device-1", - sortOrder: 10, - name: "socket", - displayName: "Steckdose", - phaseType: "single_phase", - connectionKind: "socket", - costGroup: null, - category: "single_phase", - level: null, - roomId: "room-1", - roomNumberSnapshot: "01/101", - roomNameSnapshot: "Technik", - quantity: 2, - powerPerUnit: 0.12, - simultaneityFactor: 1, - cosPhi: null, - remark: null, - overriddenFields: null, - }).run(); - - database.insert(externalModelSources).values({ - id: "source-1", - projectId: "project-1", - name: "Revit-Gesamtmodell", - sourceType: "revit_csv", - }).run(); - const configuration = configuredCsv(); - const bytes = utf8Bytes(quotedRevitCsv, true); - database.insert(externalImportBatches).values({ - id: "batch-1", - projectId: "project-1", - sourceId: "source-1", - importKind: "initial", - importedAtIso: "2026-08-02T15:30:00.000Z", - fileName: "revit.csv", - sha256: "a".repeat(64), - appliedProjectRevision: 0, - configurationVersion: 1, - configurationSnapshot: configuration, - originalBytes: Buffer.from(bytes), - document: parseExternalCsv(bytes, configuration), - }).run(); - database.insert(externalRoomMappings).values({ - id: "mapping-1", - projectId: "project-1", - sourceId: "source-1", - normalizedSourceRoomKey: "number:01/101", - sourceFloorName: "EG", - sourceRoomNumber: "01/101", - sourceRoomName: "Technik", - roomId: "room-1", - defaultDistributionBoardId: "board-1", - }).run(); - const preview = createExternalCsvPreview({ - fileName: "revit.csv", - bytes, - configuration, - }); - const projected = projectInitialExternalObject(preview.objects[0], configuration); - database.insert(externalModelObjects).values({ - id: "object-1", - projectId: "project-1", - sourceId: "source-1", - ifcGuid: projected.ifcGuid, - lastSeenImportBatchId: "batch-1", - lastAcceptedImportBatchId: "batch-1", - acceptedSourceValues: projected.sourceValues, - planningValues: projected.planningValues, - overriddenFields: [], - externalRoomMappingId: "mapping-1", - distributionBoardId: "board-1", - linkedProjectDeviceId: "device-1", - circuitDeviceRowId: "row-1", - presenceStatus: "present", - }).run(); -} diff --git a/tests/external-model-xlsx-foundation.test.ts b/tests/external-model-xlsx-foundation.test.ts new file mode 100644 index 0000000..a4836ac --- /dev/null +++ b/tests/external-model-xlsx-foundation.test.ts @@ -0,0 +1,87 @@ +import path from "node:path"; +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createDatabaseContext } from "../src/db/database-context.js"; +import { parseExternalModelStateSnapshot } from "../src/domain/models/project-state-snapshot.model.js"; +import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; + +const lowerId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee-ffffffff"; +const upperId = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-FFFFFFFF"; + +function fullBatch(id: string, importedAtIso: string) { + return { + id, + projectId: "p", + sourceId: "s", + importKind: "follow_up" as const, + importedAtIso, + fileName: `${id}.xlsx`, + sha256: "a".repeat(64), + objectCount: 1, + appliedProjectRevision: 3, + configurationSnapshot: createDefaultExternalModelConfiguration(), + originalContentBase64: "AA==", + document: { + sheetName: "Bauteilliste", + headerRowNumber: 1, + firstDataRowNumber: 3, + firstDataColumnNumber: 1, + columns: [], + rows: [], + issues: [], + }, + }; +} + +describe("Linear XLSX external model foundation", () => { + it("keeps only the newest batch complete", () => { + const newest = fullBatch("new", "2026-02-01T00:00:00.000Z"); + const older = { + ...fullBatch("old", "2026-01-01T00:00:00.000Z"), + appliedProjectRevision: null, + configurationSnapshot: null, + originalContentBase64: null, + document: null, + }; + assert.doesNotThrow(() => parseExternalModelStateSnapshot({ + source: { id: "s", projectId: "p", name: "Revit", sourceType: "revit_xlsx" }, + importBatches: [older, newest], + roomMappings: [], + objects: [], + })); + assert.throws(() => parseExternalModelStateSnapshot({ + source: { id: "s", projectId: "p", name: "Revit", sourceType: "revit_xlsx" }, + importBatches: [newest, fullBatch("newer", "2026-03-01T00:00:00.000Z")], + roomMappings: [], + objects: [], + }), /Nur der letzte Importbatch/); + }); + + it("compares Worksharing-IDs exactly and allows duplicate IfcGUID values", () => { + const context = createDatabaseContext(":memory:"); + try { + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + context.sqlite.exec(` + INSERT INTO projects (id, name) VALUES ('p', 'Projekt'); + INSERT INTO external_model_sources (id, project_id, name) VALUES ('s', 'p', 'Revit'); + INSERT INTO external_import_batches + (id, project_id, source_id, import_kind, imported_at_iso, file_name, sha256, object_count) + VALUES ('b', 'p', 's', 'initial', '2026-01-01T00:00:00.000Z', 'model.xlsx', '${"a".repeat(64)}', 2); + `); + const insert = context.sqlite.prepare(` + INSERT INTO external_model_objects + (id, project_id, source_id, worksharing_id, ifc_guid, device_type_id, + last_seen_import_batch_id, last_accepted_import_batch_id, + accepted_source_values, planning_values, overridden_fields) + VALUES (?, 'p', 's', ?, 'same-IfcGUID', 'type', 'b', 'b', '{}', '{}', '[]') + `); + insert.run("o1", lowerId); + insert.run("o2", upperId); + assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM external_model_objects").get()!.count, 2); + assert.throws(() => insert.run("o3", lowerId), /UNIQUE constraint failed/); + } finally { + context.close(); + } + }); +}); diff --git a/tests/external-object-row-assignment-project-command.repository.test.ts b/tests/external-object-row-assignment-project-command.repository.test.ts index 35579eb..4512e90 100644 --- a/tests/external-object-row-assignment-project-command.repository.test.ts +++ b/tests/external-object-row-assignment-project-command.repository.test.ts @@ -31,7 +31,6 @@ import { externalObjectAssignToNewCircuitCommandType, } from "../src/domain/models/external-object-new-circuit-project-command.model.js"; import type { ExternalModelObjectSnapshot } from "../src/external-model/domain/external-model-contracts.js"; -import { externalCsvTestConfiguration } from "./fixtures/revit-csv-fixtures.js"; function createFixture(initialObjectRowId: string | null = "row-1") { const context = createDatabaseContext(":memory:"); @@ -63,20 +62,16 @@ function createFixture(initialObjectRowId: string | null = "row-1") { simultaneityFactor: 1, }).run(); } - database.insert(externalModelSources).values({ id: "source-1", projectId: "project-1", name: "Revit", sourceType: "revit_csv" }).run(); + database.insert(externalModelSources).values({ id: "source-1", projectId: "project-1", name: "Revit", sourceType: "revit_xlsx" }).run(); database.insert(externalImportBatches).values({ id: "batch-1", projectId: "project-1", sourceId: "source-1", importKind: "initial", importedAtIso: "2026-08-02T16:00:00.000Z", - fileName: "revit.csv", + fileName: "revit.xlsx", sha256: "a".repeat(64), - appliedProjectRevision: 0, - configurationVersion: 1, - configurationSnapshot: externalCsvTestConfiguration, - originalBytes: Buffer.from("test"), - document: { delimiter: ";", encoding: "utf-8", headers: [], rows: [] }, + objectCount: 1, }).run(); database.insert(externalRoomMappings).values({ id: "mapping-1", @@ -98,7 +93,9 @@ function objectSnapshot(circuitDeviceRowId: string | null): ExternalModelObjectS id: "object-1", projectId: "project-1", sourceId: "source-1", + worksharingId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee-ffffffff", ifcGuid: "ifc-1", + deviceTypeId: "device-type-1", lastSeenImportBatchId: "batch-1", lastAcceptedImportBatchId: "batch-1", acceptedSourceValues: { @@ -107,14 +104,18 @@ function objectSnapshot(circuitDeviceRowId: string | null): ExternalModelObjectS roomName: "Büro", familyAndType: "Steckdose: Standard", selectionMarker: "Steckdose", + socketCount: "2", + sourceRemark: null, + circuitCombined: "-2F1.1", + boardName: "UV 1", circuitIdentifier: "-2F1.1", - power: "120", - quantity: "2", - additionalSourceValues: {}, + designation: null, + electricalPowerW: "120", + voltageV: 230, + currentA: null, }, planningValues: { displayName: "Steckdose", - internalDeviceType: "socket", category: "single_phase", connectionKind: "socket", effectiveQuantity: 2, diff --git a/tests/linear-xlsx-external-model-migration.test.ts b/tests/linear-xlsx-external-model-migration.test.ts new file mode 100644 index 0000000..6bfc8bf --- /dev/null +++ b/tests/linear-xlsx-external-model-migration.test.ts @@ -0,0 +1,115 @@ +import assert from "node:assert/strict"; +import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { it } from "node:test"; +import { spawnSync } from "node:child_process"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createDatabaseContext } from "../src/db/database-context.js"; + +it("replaces legacy CSV state and resets linked row quantities to their manual share", () => { + const source = path.resolve("src", "db", "migrations"); + const staging = mkdtempSync(path.join(tmpdir(), "leistungsbilanz-linear-xlsx-migration-")); + const journal = JSON.parse(readFileSync(path.join(source, "meta", "_journal.json"), "utf8")); + journal.entries = journal.entries.filter((entry: { idx: number }) => entry.idx <= 13); + mkdirSync(path.join(staging, "meta")); + writeFileSync(path.join(staging, "meta", "_journal.json"), JSON.stringify(journal)); + for (const entry of journal.entries) { + copyFileSync(path.join(source, `${entry.tag}.sql`), path.join(staging, `${entry.tag}.sql`)); + } + + const context = createDatabaseContext(":memory:"); + try { + migrate(context.db, { migrationsFolder: staging }); + context.sqlite.exec(` + INSERT INTO projects (id, name) VALUES ('p', 'Projekt'); + INSERT INTO distribution_boards (id, project_id, name) VALUES ('b', 'p', 'UV'); + INSERT INTO circuit_lists (id, project_id, distribution_board_id, name) VALUES ('l', 'p', 'b', 'Liste'); + INSERT INTO circuit_sections (id, circuit_list_id, key, display_name, prefix) VALUES ('s', 'l', 'single_phase', 'Einphasig', '-2F1.'); + INSERT INTO circuits (id, circuit_list_id, section_id, equipment_identifier) VALUES ('c', 'l', 's', '-2F1.1'); + INSERT INTO circuit_device_rows + (id, circuit_id, name, display_name, quantity, manual_quantity, power_per_unit, simultaneity_factor) + VALUES ('r', 'c', 'Steckdose', 'Steckdose', 5, 2, 0.2, 1); + INSERT INTO external_csv_configurations + (id, project_id, configuration_version, configuration) + VALUES ('cfg', 'p', 3, '{}'); + INSERT INTO external_model_sources (id, project_id, name, source_type) + VALUES ('src', 'p', 'Revit', 'revit_csv'); + INSERT INTO external_import_batches + (id, project_id, source_id, import_kind, imported_at_iso, file_name, sha256, + applied_project_revision, configuration_snapshot, original_bytes, document, configuration_version) + VALUES ('batch', 'p', 'src', 'initial', '2026-01-01T00:00:00.000Z', 'legacy.csv', + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 0, '{}', X'00', '{}', 3); + INSERT INTO external_model_objects + (id, project_id, source_id, ifc_guid, last_seen_import_batch_id, + last_accepted_import_batch_id, accepted_source_values, planning_values, + overridden_fields, circuit_device_row_id) + VALUES ('object', 'p', 'src', 'Ifc-GUID', 'batch', 'batch', '{}', '{}', '[]', 'r'); + `); + + migrate(context.db, { migrationsFolder: source }); + + assert.equal( + (context.sqlite.prepare("SELECT quantity FROM circuit_device_rows WHERE id = 'r'").get() as { quantity: number }).quantity, + 2 + ); + assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM external_model_objects").get()!.count, 0); + assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM external_model_configurations").get()!.count, 0); + assert.throws(() => context.sqlite.prepare("SELECT * FROM external_csv_configurations").all(), /no such table/); + + const columns = context.sqlite.prepare("PRAGMA table_info(external_model_objects)").all() as Array<{ name: string; notnull: number }>; + assert.equal(columns.find((column) => column.name === "worksharing_id")?.notnull, 1); + assert.equal(columns.find((column) => column.name === "ifc_guid")?.notnull, 0); + assert.deepEqual(context.sqlite.pragma("foreign_key_check"), []); + assert.equal(context.sqlite.pragma("integrity_check", { simple: true }), "ok"); + } finally { + context.close(); + rmSync(staging, { recursive: true, force: true }); + } +}); + +it("creates and verifies a backup before the Linear-XLSX migration", () => { + const source = path.resolve("src", "db", "migrations"); + const root = mkdtempSync(path.join(tmpdir(), "leistungsbilanz-linear-xlsx-backup-")); + const staging = path.join(root, "migrations"); + const dataDirectory = path.join(root, "data"); + mkdirSync(path.join(staging, "meta"), { recursive: true }); + mkdirSync(dataDirectory, { recursive: true }); + const journal = JSON.parse(readFileSync(path.join(source, "meta", "_journal.json"), "utf8")); + journal.entries = journal.entries.filter((entry: { idx: number }) => entry.idx <= 13); + writeFileSync(path.join(staging, "meta", "_journal.json"), JSON.stringify(journal)); + for (const entry of journal.entries) { + copyFileSync(path.join(source, `${entry.tag}.sql`), path.join(staging, `${entry.tag}.sql`)); + } + + const databasePath = path.join(dataDirectory, "leistungsbilanz.db"); + const context = createDatabaseContext(databasePath); + try { + migrate(context.db, { migrationsFolder: staging }); + } finally { + context.close(); + } + + try { + const result = spawnSync(process.execPath, ["scripts/run-migrations.js"], { + cwd: path.resolve("."), + env: { ...process.env, LEISTUNGSBILANZ_DATA_DIR: dataDirectory }, + encoding: "utf8", + }); + assert.equal(result.status, 0, result.stderr || result.stdout); + assert.match(result.stdout, /Verified pre-migration backup created/); + const backups = readdirSync(path.join(dataDirectory, "backups")); + assert.equal(backups.length, 1); + + const migrated = createDatabaseContext(databasePath); + try { + assert.ok(migrated.sqlite.prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'external_model_configurations'" + ).get()); + } finally { + migrated.close(); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/project-command.service.test.ts b/tests/project-command.service.test.ts index 5630cb8..ac6d887 100644 --- a/tests/project-command.service.test.ts +++ b/tests/project-command.service.test.ts @@ -30,7 +30,7 @@ import { ProjectDeviceRowSyncProjectCommandRepository } from "../src/db/reposito import { ProjectDeviceStructureProjectCommandRepository } from "../src/db/repositories/project-device-structure-project-command.repository.js"; import { ProjectStateRestoreCommandRepository } from "../src/db/repositories/project-state-restore-command.repository.js"; import { ProjectSettingsProjectCommandRepository } from "../src/db/repositories/project-settings-project-command.repository.js"; -import { ExternalCsvConfigurationProjectCommandRepository } from "../src/db/repositories/external-csv-configuration-project-command.repository.js"; +import { ExternalModelConfigurationProjectCommandRepository } from "../src/db/repositories/external-model-configuration-project-command.repository.js"; import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; import { circuitProtectionDevices } from "../src/db/schema/circuit-protection-devices.js"; import { circuitSections } from "../src/db/schema/circuit-sections.js"; @@ -44,7 +44,7 @@ import { projects } from "../src/db/schema/projects.js"; import { buildings } from "../src/db/schema/buildings.js"; import { floors } from "../src/db/schema/floors.js"; import { rooms } from "../src/db/schema/rooms.js"; -import { externalCsvConfigurations } from "../src/db/schema/external-csv-configurations.js"; +import { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; import { createCircuitProtectionUpdateProjectCommand } from "../src/domain/models/circuit-protection-project-command.model.js"; import { ProjectHistoryOperationUnavailableError } from "../src/domain/errors/project-history-operation-unavailable.error.js"; import { ProjectRevisionConflictError } from "../src/domain/errors/project-revision-conflict.error.js"; @@ -90,9 +90,8 @@ import { createProjectDeviceRowSyncProjectCommand } from "../src/domain/models/p import { createProjectDeviceUpdateProjectCommand } from "../src/domain/models/project-device-project-command.model.js"; import { createProjectDeviceInsertProjectCommand } from "../src/domain/models/project-device-structure-project-command.model.js"; import { createProjectSettingsUpdateProjectCommand } from "../src/domain/models/project-settings-project-command.model.js"; -import { createExternalCsvConfigurationUpdateProjectCommand } from "../src/domain/models/external-csv-configuration-project-command.model.js"; -import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; -import { externalCsvTestColumns } from "./fixtures/revit-csv-fixtures.js"; +import { createExternalModelConfigurationUpdateProjectCommand } from "../src/domain/models/external-model-configuration-project-command.model.js"; +import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; import { ProjectCommandService } from "../src/domain/services/project-command.service.js"; function createTestDatabase(): DatabaseContext { @@ -166,7 +165,7 @@ function createService(context: DatabaseContext) { new CircuitGroupSubtreeProjectCommandRepository(context.db), new CircuitProtectionProjectCommandRepository(context.db), new ProjectHistoryRepository(context.db), - new ExternalCsvConfigurationProjectCommandRepository(context.db) + new ExternalModelConfigurationProjectCommandRepository(context.db) ); } @@ -1127,31 +1126,62 @@ describe("project command service", () => { } }); - it("dispatches external CSV configuration updates through persistent history", () => { + it("dispatches external XLSX configuration updates through persistent history", () => { const context = createTestDatabase(); try { const service = createService(context); const target = { id: "external-config-1", projectId: "project-1", - configurationVersion: 1, - configuration: createDefaultExternalCsvConfiguration(externalCsvTestColumns), + configuration: createDefaultExternalModelConfiguration(), }; const updated = service.executeUser({ projectId: "project-1", expectedRevision: 0, - command: createExternalCsvConfigurationUpdateProjectCommand(null, target), + command: createExternalModelConfigurationUpdateProjectCommand(null, target), }); assert.equal(updated.history.currentRevision, 1); - assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 1); + assert.equal(context.db.select().from(externalModelConfigurations).all().length, 1); const undone = service.undo({ projectId: "project-1", expectedRevision: 1 }); assert.equal(undone.history.currentRevision, 2); - assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 0); + assert.equal(context.db.select().from(externalModelConfigurations).all().length, 0); const redone = service.redo({ projectId: "project-1", expectedRevision: 2 }); assert.equal(redone.history.currentRevision, 3); - assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 1); + assert.equal(context.db.select().from(externalModelConfigurations).all().length, 1); + } finally { + context.close(); + } + }); + + it("rejects legacy CSV commands stored in project history with a clear error", () => { + const context = createTestDatabase(); + try { + const service = createService(context); + service.executeUser({ + projectId: "project-1", + expectedRevision: 0, + command: createExternalModelConfigurationUpdateProjectCommand(null, { + id: "external-config-1", + projectId: "project-1", + configuration: createDefaultExternalModelConfiguration(), + }), + }); + context.db.update(projectChangeSets).set({ + inversePayloadJson: JSON.stringify({ + schemaVersion: 1, + type: "external-import.apply-initial", + payload: {}, + }), + }).run(); + + assert.throws( + () => service.undo({ projectId: "project-1", expectedRevision: 1 }), + /alten Revit-CSV-Anbindung/ + ); + assert.equal(context.db.select().from(externalModelConfigurations).all().length, 1); + assert.equal(context.db.select({ revision: projects.currentRevision }).from(projects).get()?.revision, 1); } finally { context.close(); } diff --git a/tests/project-device-row-sync-project-command.repository.test.ts b/tests/project-device-row-sync-project-command.repository.test.ts index 593a7f6..f5e7a60 100644 --- a/tests/project-device-row-sync-project-command.repository.test.ts +++ b/tests/project-device-row-sync-project-command.repository.test.ts @@ -19,7 +19,6 @@ import { externalModelSources } from "../src/db/schema/external-model-sources.js import { projectDevices } from "../src/db/schema/project-devices.js"; import { projectRevisions } from "../src/db/schema/project-revisions.js"; import { projects } from "../src/db/schema/projects.js"; -import { externalCsvTestConfiguration } from "./fixtures/revit-csv-fixtures.js"; import { createProjectDeviceRowSyncProjectCommand, type ProjectDeviceSyncRowSnapshot, @@ -178,7 +177,7 @@ function linkExternalObject( id: "source-1", projectId: "project-1", name: "Revit", - sourceType: "revit_csv", + sourceType: "revit_xlsx", }) .run(); context.db @@ -189,13 +188,9 @@ function linkExternalObject( sourceId: "source-1", importKind: "initial", importedAtIso: "2026-08-02T16:00:00.000Z", - fileName: "revit.csv", + fileName: "revit.xlsx", sha256: "a".repeat(64), - appliedProjectRevision: 0, - configurationVersion: 1, - configurationSnapshot: externalCsvTestConfiguration, - originalBytes: Buffer.from("test"), - document: { delimiter: ";", encoding: "utf-8", headers: [], rows: [] }, + objectCount: 1, }) .run(); context.db @@ -204,7 +199,9 @@ function linkExternalObject( id: "object-1", projectId: "project-1", sourceId: "source-1", + worksharingId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee-ffffffff", ifcGuid: "ifc-1", + deviceTypeId: "device-type-1", lastSeenImportBatchId: "batch-1", lastAcceptedImportBatchId: "batch-1", acceptedSourceValues: { @@ -213,14 +210,18 @@ function linkExternalObject( roomName: "Büro", familyAndType: "Leuchte: Standard", selectionMarker: "Leuchte", + socketCount: String(effectiveQuantity), + sourceRemark: null, + circuitCombined: "-1F1", + boardName: "UV 1", circuitIdentifier: "-1F1", - power: "30", - quantity: String(effectiveQuantity), - additionalSourceValues: {}, + designation: null, + electricalPowerW: "30", + voltageV: 230, + currentA: null, }, planningValues: { displayName: "Leuchte", - internalDeviceType: "luminaire", category: "single_phase", connectionKind: "fixed", effectiveQuantity, diff --git a/tests/project-snapshot.repository.test.ts b/tests/project-snapshot.repository.test.ts index bc4cd12..b85485c 100644 --- a/tests/project-snapshot.repository.test.ts +++ b/tests/project-snapshot.repository.test.ts @@ -465,6 +465,8 @@ describe("project snapshot repository", () => { rooms: Array>; }; payload.schemaVersion = 5; + (payload as Record).externalCsvConfiguration = null; + delete (payload as Record).externalModelConfiguration; delete payload.buildings; for (const floor of payload.floors) { delete floor.buildingId; diff --git a/tests/project-state-snapshot.test.ts b/tests/project-state-snapshot.test.ts index aa2371b..1ae460f 100644 --- a/tests/project-state-snapshot.test.ts +++ b/tests/project-state-snapshot.test.ts @@ -8,11 +8,16 @@ import { } from "../src/domain/models/project-state-snapshot.model.js"; import { remapProjectState } from "../src/domain/models/project-transfer.model.js"; import { createNamedProjectSnapshotSchema } from "../src/shared/validation/project-snapshot.schemas.js"; +import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; +import { externalCsvTestColumns } from "./fixtures/revit-csv-fixtures.js"; /** Removes the fields introduced by snapshot schema version 9. */ function withoutVersionNineFields< T extends { distributionBoards: object[] }, >(snapshot: T): T { + const record = snapshot as Record; + record.externalCsvConfiguration = null; + delete record.externalModelConfiguration; for (const board of snapshot.distributionBoards) { delete (board as Record).feedingDistributionBoardId; delete (board as Record).feedingCircuitId; @@ -77,7 +82,7 @@ function minimalSnapshot() { projectEditor: null as string | null, }, distributionBoards: [], - externalCsvConfiguration: null, + externalModelConfiguration: null, externalModel: { source: null, importBatches: [], @@ -315,6 +320,7 @@ describe("project state snapshot model", () => { const baseline = withoutVersionSixFields(structuredClone(minimalSnapshot())); baseline.schemaVersion = 1 as typeof baseline.schemaVersion; delete (baseline.project as Record).isPublicBuilding; + delete (baseline as Record).externalModelConfiguration; delete (baseline as Record).externalCsvConfiguration; delete (baseline as Record).externalModel; @@ -322,7 +328,7 @@ describe("project state snapshot model", () => { assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); assert.equal(upgraded.project.isPublicBuilding, false); - assert.equal(upgraded.externalCsvConfiguration, null); + assert.equal(upgraded.externalModelConfiguration, null); }); it("upgrades snapshot version 2 with an empty external CSV configuration", () => { @@ -334,7 +340,7 @@ describe("project state snapshot model", () => { const upgraded = parseProjectStateSnapshot(previous); assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(upgraded.externalCsvConfiguration, null); + assert.equal(upgraded.externalModelConfiguration, null); assert.deepEqual(upgraded.externalModel, { source: null, importBatches: [], @@ -351,7 +357,7 @@ describe("project state snapshot model", () => { const upgraded = parseProjectStateSnapshot(previous); assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(upgraded.externalCsvConfiguration, null); + assert.equal(upgraded.externalModelConfiguration, null); assert.deepEqual(upgraded.externalModel, { source: null, importBatches: [], @@ -360,6 +366,28 @@ describe("project state snapshot model", () => { }); }); + it("rejects legacy CSV configuration and imported state with a German migration error", () => { + const configured = withoutVersionNineFields(structuredClone(minimalSnapshot())); + configured.schemaVersion = 9 as typeof configured.schemaVersion; + configured.externalCsvConfiguration = { + id: "legacy", + projectId: "project-1", + configurationVersion: 1, + configuration: createDefaultExternalCsvConfiguration(externalCsvTestColumns), + }; + assert.throws(() => parseProjectStateSnapshot(configured), /Revit-CSV-Daten/); + + const imported = withoutVersionNineFields(structuredClone(minimalSnapshot())); + imported.schemaVersion = 9 as typeof imported.schemaVersion; + imported.externalModel.source = { + id: "legacy-source", + projectId: "project-1", + name: "Legacy", + sourceType: "revit_csv", + }; + assert.throws(() => parseProjectStateSnapshot(imported), /Revit-CSV-Daten/); + }); + it("upgrades snapshot version 5 with empty board info and cover fields", () => { const previous = withoutVersionSixFields(protectedSnapshot()); previous.schemaVersion = 5 as typeof previous.schemaVersion; @@ -567,7 +595,7 @@ describe("project state snapshot model", () => { }); assert.equal(parseProjectStateSnapshot(current).rooms[0]?.areaM2, 23.456); - const previous = structuredClone(current); + const previous = withoutVersionNineFields(structuredClone(current)); previous.schemaVersion = 7 as typeof previous.schemaVersion; delete (previous.rooms[0] as Partial<(typeof previous.rooms)[number]>).areaM2; const upgraded = parseProjectStateSnapshot(previous); From c633e78cd406688a23f89c0dc15569ad87f6f394 Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 09:02:52 +0200 Subject: [PATCH 30/38] Add Revit XLSX settings page --- AGENTS.md | 6 +- README.md | 6 +- docs/spec/revit-excel-phase-14-plan.md | 2 +- src/app/projects/[projectId]/page.tsx | 44 +- src/app/projects/[projectId]/revit/page.tsx | 34 + src/frontend/components/revit-csv-modal.tsx | 666 ------------------ .../components/revit-xlsx-settings-modal.tsx | 45 ++ src/frontend/types.ts | 7 + src/frontend/utils/api.ts | 99 +-- src/frontend/utils/project-version-history.ts | 1 + src/frontend/utils/revit-xlsx-settings.ts | 17 + ...external-model-configuration.controller.ts | 60 ++ src/server/routes/project.routes.ts | 8 + tests/revit-csv-frontend-api.test.ts | 251 ------- tests/revit-xlsx-settings-api.test.ts | 38 + 15 files changed, 259 insertions(+), 1025 deletions(-) create mode 100644 src/app/projects/[projectId]/revit/page.tsx delete mode 100644 src/frontend/components/revit-csv-modal.tsx create mode 100644 src/frontend/components/revit-xlsx-settings-modal.tsx create mode 100644 src/frontend/utils/revit-xlsx-settings.ts create mode 100644 src/server/controllers/external-model-configuration.controller.ts delete mode 100644 tests/revit-csv-frontend-api.test.ts create mode 100644 tests/revit-xlsx-settings-api.test.ts diff --git a/AGENTS.md b/AGENTS.md index c95a271..e8d4bff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -329,8 +329,8 @@ the old development-only external CSV data after resetting linked row totals to their manual share. Snapshot schema 10, restore and project transfer use the new state; non-empty legacy CSV snapshots and legacy CSV history entries are rejected with a German error. The backend CSV parser and routes are removed. -The old project-page frontend remains only until its replacement in R4; do not -reconnect it to runtime CSV endpoints. See +R4 adds `/projects/:projectId/revit`, its revisioned XLSX settings and +server-side sample detection, and removes the old project-page CSV modal. See `docs/spec/revit-excel-integration-requirements.md` and `docs/spec/revit-excel-phase-14-plan.md`. @@ -586,7 +586,7 @@ Critical target rules: selected combined/separate mode block export. - Missing GZF defaults visibly to 1 without separate confirmation. - The corrected R2 return workbook was successfully imported into Linear on - 2026-09-30; R3 is complete and R4 is the next package. + 2026-09-30; R3 and R4 are complete and R5 is the next package. - All confirmed writes use typed project commands with `expectedRevision`, complete inverse data and the shared project-command transaction boundary. - Do not add automatic circuit planning, Revit circuit adoption, multi-source diff --git a/README.md b/README.md index b8b9c3e..b70a145 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,9 @@ für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstützte Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind vorhanden. Die Backend- und Persistenzgrundlage der bisherigen Revit-CSV-/IfcGUID-Anbindung ist durch den XLSX-Austausch des Linear-Plugins mit -Worksharing-ID als externem Schlüssel ersetzt. R0 bis R3 sind abgeschlossen; -die eigene Revit-Seite, Erstimport, Editorzuordnung, Rückgabe und Folgeimport -folgen in R4 bis R10. +Worksharing-ID als externem Schlüssel ersetzt. R0 bis R4 sind abgeschlossen; +die eigene Revit-Seite mit XLSX-Einstellungen ist vorhanden. Erstimport, +Editorzuordnung, Rückgabe und Folgeimport folgen in R5 bis R10. ## Unterstützter Arbeitsablauf diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index 4004eb3..0b1b71a 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -12,7 +12,7 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | R1 | abgeschlossen | Anforderungen, Plan und Architektur auf Excel/Worksharing-ID umgestellt; alle Pflichtprüfungen bestanden. | | R2 | abgeschlossen und freigegeben | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei sind erstellt; der korrigierte Rückimport wurde am 30.09.2026 erfolgreich in Linear getestet. | | R3 | abgeschlossen | Konfiguration ohne eigene Revision, Worksharing-ID-Datenmodell, Migration 0014, Snapshot 10, Transfer und Backend-CSV-Entfernung sind umgesetzt und geprüft. | -| R4 | offen | Revit-Seite, Navigation, Einstellungen, altes Projektseitenmodal entfernen. | +| R4 | abgeschlossen | Revit-Seite, Navigation und revisionierte XLSX-Einstellungen mit Musterdateiprüfung sind umgesetzt; das alte Projektseitenmodal ist entfernt. | | R5 | offen | Erstimportwizard mit Gerätearten, Familienregeln und optionalen ProjectDevices. | | R6 | offen | Virtualisierte Objekttabelle und Sammelzuordnungen. | | R7 | offen | Editorbereich, Gruppierung, Drag-and-drop, Lösen und integrierte Löschübergänge. | diff --git a/src/app/projects/[projectId]/page.tsx b/src/app/projects/[projectId]/page.tsx index ec99d54..5eb864e 100644 --- a/src/app/projects/[projectId]/page.tsx +++ b/src/app/projects/[projectId]/page.tsx @@ -5,7 +5,7 @@ import { useParams } from "next/navigation"; import { FormEvent, useEffect, useMemo, useState } from "react"; import { ArrowLeft, - FileUp, + FileSpreadsheet, Library, Link2, ListTree, @@ -51,7 +51,6 @@ import { copyProjectDeviceToGlobal, createDistributionBoard, createProjectDevice, - createRoom, deleteProjectDevice, deleteDistributionBoard, disconnectProjectDeviceRows, @@ -83,7 +82,6 @@ import type { BuildingDto, CircuitListDto, CircuitTreeResponseDto, - CreateRoomInput, CreateProjectDeviceInput, DistributionBoardDto, FloorDto, @@ -115,7 +113,6 @@ import { } from "../../../frontend/components/project-settings-modal"; import { FormModal } from "../../../frontend/components/form-modal"; import { ProjectDeviceModal } from "../../../frontend/components/project-device-modal"; -import { RevitCsvModal } from "../../../frontend/components/revit-csv-modal"; import { FloorSelectOptions } from "../../../frontend/components/floor-select-options"; const projectDeviceSyncFieldLabels: Record = { @@ -200,7 +197,6 @@ export default function ProjectDetailPage() { }) ); const [isProjectSettingsOpen, setIsProjectSettingsOpen] = useState(false); - const [isRevitCsvOpen, setIsRevitCsvOpen] = useState(false); const [structureModal, setStructureModal] = useState<"board" | null>(null); const [isProjectDeviceModalOpen, setIsProjectDeviceModalOpen] = useState(false); @@ -679,22 +675,6 @@ export default function ProjectDetailPage() { } } - async function handleCreateRevitRoom(input: CreateRoomInput) { - if (!projectId || !project) throw new Error("Projekt ist nicht geladen."); - const result = await createRoom(projectId, input, project.currentRevision); - setRooms((current) => [...current, result.room]); - applyProjectRevision(result.history.currentRevision); - return result; - } - - async function handleCreateRevitProjectDevice(input: CreateProjectDeviceInput) { - if (!projectId || !project) throw new Error("Projekt ist nicht geladen."); - const result = await createProjectDevice(projectId, input, project.currentRevision); - setProjectDevices((current) => [...current, result.projectDevice]); - applyProjectRevision(result.history.currentRevision); - return result; - } - async function handleCopyBoard() { if ( !projectId || @@ -997,15 +977,13 @@ export default function ProjectDetailPage() {
); } diff --git a/src/app/projects/[projectId]/revit/page.tsx b/src/app/projects/[projectId]/revit/page.tsx new file mode 100644 index 0000000..96af41c --- /dev/null +++ b/src/app/projects/[projectId]/revit/page.tsx @@ -0,0 +1,34 @@ +"use client"; + +import { ArrowLeft, FileSpreadsheet, Settings } from "lucide-react"; +import { useParams } from "next/navigation"; +import { useEffect, useState } from "react"; +import { IconLink } from "../../../../frontend/components/icon-link"; +import { RevitXlsxSettingsModal } from "../../../../frontend/components/revit-xlsx-settings-modal"; +import type { ExternalModelConfiguration } from "../../../../external-model/configuration/external-model-configuration"; +import { detectExternalModelWorkbook, getExternalModelConfiguration, getProject, updateExternalModelConfiguration } from "../../../../frontend/utils/api"; +import { createDefaultRevitXlsxConfiguration } from "../../../../frontend/utils/revit-xlsx-settings"; +import type { ExternalModelConfigurationSnapshotDto, ProjectDto } from "../../../../frontend/types"; + +export default function RevitPage() { + const { projectId } = useParams<{ projectId: string }>(); + const [project, setProject] = useState(null); + const [snapshot, setSnapshot] = useState(null); + const [open, setOpen] = useState(false); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + useEffect(() => { Promise.all([getProject(projectId), getExternalModelConfiguration(projectId)]).then(([loadedProject, result]) => { setProject(loadedProject); setSnapshot(result.configuration); }).catch((value: unknown) => setError(value instanceof Error ? value.message : "Revit-Daten konnten nicht geladen werden.")); }, [projectId]); + async function save(configuration: ExternalModelConfiguration) { + if (!project) return; + setSaving(true); setError(null); + try { const result = await updateExternalModelConfiguration(projectId, project.currentRevision, configuration); setSnapshot(result.configuration); setProject({ ...project, currentRevision: result.history.currentRevision }); setOpen(false); } + catch (value) { setError(value instanceof Error ? value.message : "Einstellungen konnten nicht gespeichert werden."); } + finally { setSaving(false); } + } + return
+
Projekt · Revit

{project?.name ?? "Revit-Anbindung"}

Linear-XLSX austauschen und Revit-Objekte verwalten

+ {error ?
{error}
: null} +

XLSX-Konfiguration

{snapshot ? "Die Linear-Spalten und das Tabellenlayout sind konfiguriert." : "Noch keine XLSX-Konfiguration gespeichert."}

{snapshot ? "Konfiguriert" : "Offen"}

Importstatus

Noch kein Linear-XLSX-Import vorhanden. Der Erstimport folgt in R5.

+ {open ? setOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} +
; +} diff --git a/src/frontend/components/revit-csv-modal.tsx b/src/frontend/components/revit-csv-modal.tsx deleted file mode 100644 index 3602bd8..0000000 --- a/src/frontend/components/revit-csv-modal.tsx +++ /dev/null @@ -1,666 +0,0 @@ -"use client"; - -import React, { useEffect, useMemo, useState, type FormEvent } from "react"; -import { - createDefaultExternalCsvConfiguration, - type ExternalCsvConfiguration, - type ExternalCsvFamilyTypeRule, -} from "../../external-model/csv/external-csv-contracts"; -import type { - CreateProjectDeviceInput, - CreateRoomInput, - ExternalCsvPreviewDto, - ExternalInitialImportPlanDto, - ProjectDeviceCommandResultDto, - ProjectRoomCommandResultDto, -} from "../types"; -import { - applyExternalInitialImport, - getExternalCsvConfiguration, - planExternalInitialImport, - previewExternalCsv, - updateExternalCsvConfiguration, -} from "../utils/api"; -import { FormModal } from "./form-modal"; -import { ProjectDeviceModal } from "./project-device-modal"; -import { RoomModal } from "./room-modal"; - -interface RevitCsvModalProps { - currentRevision: number; - onClose: () => void; - onCreateProjectDevice: ( - input: CreateProjectDeviceInput - ) => Promise; - onCreateRoom: (input: CreateRoomInput) => Promise; - onRevisionChange: (currentRevision: number) => void; - projectId: string; -} - -const defaultConfiguration = createDefaultExternalCsvConfiguration({ - ifcGuid: "IfcGUID", - roomNumber: "MEP-Raum: Nummer", - roomName: "MEP-Raum: Name", - familyAndType: "Familie und Typ", - selectionMarker: "CAx_Auswahlkenner", - circuitIdentifier: "kbp_Stromkreisnummer", - power: "kbp-E-Elektrische Leistung", - quantity: null, -}); -defaultConfiguration.additionalSourceMappings = [ - { sourceColumn: "CAx_Anmerkung", targetField: "sourceRemark" }, - { sourceColumn: "kbp-E-Spannung", targetField: "sourceVoltage" }, - { sourceColumn: "kbp-E-Stromstärke", targetField: "sourceCurrent" }, - { sourceColumn: "kbp-E-Versorgung von ELT", targetField: "sourceElectricalSupply" }, - { sourceColumn: "kbp-E-Versorgung von MSR/GLT", targetField: "sourceControlSupply" }, -]; - -const columnFields = [ - ["ifcGuid", "IFC-GUID"], - ["roomNumber", "Raumnummer"], - ["roomName", "Raumname"], - ["familyAndType", "Familie und Typ"], - ["selectionMarker", "CAx-Auswahlkenner"], - ["circuitIdentifier", "Stromkreiskennzeichnung"], - ["power", "Elektrische Leistung"], - ["quantity", "Menge (optional)"], -] as const; - -export function RevitCsvModal({ - currentRevision, - onClose, - onCreateProjectDevice, - onCreateRoom, - onRevisionChange, - projectId, -}: RevitCsvModalProps) { - const [configuration, setConfiguration] = useState( - structuredClone(defaultConfiguration) - ); - const [savedConfiguration, setSavedConfiguration] = useState(null); - const [file, setFile] = useState(null); - const [preview, setPreview] = useState(null); - const [importPlan, setImportPlan] = useState(null); - const [roomDecisions, setRoomDecisions] = useState>({}); - const [familyLinks, setFamilyLinks] = useState>({}); - const [sourceName, setSourceName] = useState("Revit-Gesamtmodell"); - const [success, setSuccess] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const [isSaving, setIsSaving] = useState(false); - const [isPreviewing, setIsPreviewing] = useState(false); - const [isPlanning, setIsPlanning] = useState(false); - const [isApplying, setIsApplying] = useState(false); - const [isCreatingCatalogEntry, setIsCreatingCatalogEntry] = useState(false); - const [newRoomSourceKey, setNewRoomSourceKey] = useState(null); - const [newProjectDeviceFamily, setNewProjectDeviceFamily] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - getExternalCsvConfiguration(projectId) - .then(({ configuration: stored }) => { - const next = stored?.configuration ?? structuredClone(defaultConfiguration); - setConfiguration(next); - setSavedConfiguration(stored ? JSON.stringify(next) : null); - }) - .catch((reason: unknown) => - setError(reason instanceof Error ? reason.message : "Konfiguration konnte nicht geladen werden.") - ) - .finally(() => setIsLoading(false)); - }, [projectId]); - - const isDirty = savedConfiguration !== JSON.stringify(configuration); - - function replaceConfiguration(next: ExternalCsvConfiguration) { - setConfiguration(next); - setPreview(null); - setImportPlan(null); - setSuccess(null); - } - - async function handleSave(event: FormEvent) { - event.preventDefault(); - setIsSaving(true); - setError(null); - try { - const result = await updateExternalCsvConfiguration( - projectId, - currentRevision, - configuration - ); - setSavedConfiguration(JSON.stringify(result.configuration.configuration)); - setImportPlan(null); - onRevisionChange(result.history.currentRevision); - } catch (reason) { - setError(reason instanceof Error ? reason.message : "Konfiguration konnte nicht gespeichert werden."); - } finally { - setIsSaving(false); - } - } - - async function handlePreview() { - if (!file || isDirty || savedConfiguration === null) return; - setIsPreviewing(true); - setError(null); - try { - const contentBase64 = await fileToBase64(file); - setPreview(await previewExternalCsv(projectId, file.name, contentBase64)); - setImportPlan(null); - setSuccess(null); - } catch (reason) { - setPreview(null); - setError(reason instanceof Error ? reason.message : "CSV-Vorschau konnte nicht erstellt werden."); - } finally { - setIsPreviewing(false); - } - } - - async function handlePlanImport() { - if (!file || !preview || isDirty || savedConfiguration === null) return; - setIsPlanning(true); - setError(null); - try { - const contentBase64 = await fileToBase64(file); - const plan = await planExternalInitialImport(projectId, file.name, contentBase64); - if (plan.sha256 !== preview.sha256) { - throw new Error("Die Datei stimmt nicht mehr mit der Vorschau überein."); - } - setImportPlan(plan); - setRoomDecisions(Object.fromEntries(plan.sourceRooms.map((room) => [ - room.sourceRoomKey, - { roomId: room.suggestedRoomId, defaultDistributionBoardId: null }, - ]))); - setFamilyLinks(Object.fromEntries(plan.familyGroups.map((group) => [ - group.familyAndType, - null, - ]))); - } catch (reason) { - setImportPlan(null); - setError(reason instanceof Error ? reason.message : "Erstimport konnte nicht geplant werden."); - } finally { - setIsPlanning(false); - } - } - - async function handleApplyImport() { - if (!file || !importPlan) return; - if (!window.confirm( - `${importPlan.objectCount} Revit-Objekte jetzt als einen rückgängig machbaren Import übernehmen?` - )) return; - setIsApplying(true); - setError(null); - try { - const contentBase64 = await fileToBase64(file); - const result = await applyExternalInitialImport(projectId, { - expectedRevision: currentRevision, - expectedConfigurationVersion: importPlan.configurationVersion, - expectedSha256: importPlan.sha256, - fileName: file.name, - contentBase64, - sourceName, - roomDecisions: importPlan.sourceRooms.map((room) => ({ - sourceRoomKey: room.sourceRoomKey, - roomId: roomDecisions[room.sourceRoomKey]?.roomId ?? null, - defaultDistributionBoardId: - roomDecisions[room.sourceRoomKey]?.defaultDistributionBoardId ?? null, - })), - familyProjectDeviceDecisions: importPlan.familyGroups.map((group) => ({ - familyAndType: group.familyAndType, - projectDeviceId: familyLinks[group.familyAndType] ?? null, - })), - }); - onRevisionChange(result.history.currentRevision); - setSuccess(`${result.import.objectCount} Revit-Objekte wurden übernommen.`); - setImportPlan(null); - setPreview(null); - } catch (reason) { - setError(reason instanceof Error ? reason.message : "Erstimport konnte nicht übernommen werden."); - } finally { - setIsApplying(false); - } - } - - function updateColumn(key: (typeof columnFields)[number][0], value: string) { - setConfiguration((current) => ({ - ...current, - columns: { ...current.columns, [key]: key === "quantity" && !value.trim() ? null : value }, - })); - setPreview(null); - setImportPlan(null); - } - - async function handleCreateRoom(input: CreateRoomInput) { - if (!newRoomSourceKey) return; - setIsCreatingCatalogEntry(true); - setError(null); - try { - const result = await onCreateRoom(input); - setImportPlan((current) => current ? { - ...current, - existing: { - ...current.existing, - rooms: [...current.existing.rooms, result.room], - }, - } : current); - setRoomDecisions((current) => ({ - ...current, - [newRoomSourceKey]: { - roomId: result.room.id, - defaultDistributionBoardId: - current[newRoomSourceKey]?.defaultDistributionBoardId ?? null, - }, - })); - setNewRoomSourceKey(null); - } catch (reason) { - setError(reason instanceof Error ? reason.message : "Raum konnte nicht angelegt werden."); - setNewRoomSourceKey(null); - } finally { - setIsCreatingCatalogEntry(false); - } - } - - async function handleCreateProjectDevice(input: CreateProjectDeviceInput) { - if (!newProjectDeviceFamily) return; - setIsCreatingCatalogEntry(true); - setError(null); - try { - const result = await onCreateProjectDevice(input); - setImportPlan((current) => current ? { - ...current, - existing: { - ...current.existing, - projectDevices: [...current.existing.projectDevices, result.projectDevice], - }, - } : current); - setFamilyLinks((current) => ({ - ...current, - [newProjectDeviceFamily]: result.projectDevice.id, - })); - setNewProjectDeviceFamily(null); - } catch (reason) { - setError(reason instanceof Error ? reason.message : "ProjectDevice konnte nicht angelegt werden."); - setNewProjectDeviceFamily(null); - } finally { - setIsCreatingCatalogEntry(false); - } - } - - if (newRoomSourceKey && importPlan) { - const sourceRoom = importPlan.sourceRooms.find((room) => room.sourceRoomKey === newRoomSourceKey); - if (sourceRoom) { - return ( - ({ ...floor, projectId }))} - initialValues={{ roomNumber: sourceRoom.roomNumber, roomName: sourceRoom.roomName }} - isSaving={isCreatingCatalogEntry} - onClose={() => setNewRoomSourceKey(null)} - onSave={handleCreateRoom} - /> - ); - } - } - - if (newProjectDeviceFamily && importPlan) { - const group = importPlan.familyGroups.find((entry) => entry.familyAndType === newProjectDeviceFamily); - if (group) { - return ( - setNewProjectDeviceFamily(null)} - onImportGlobal={async () => undefined} - onSave={handleCreateProjectDevice} - /> - ); - } - } - - return ( - - {error ?
{error}
: null} - {success ?
{success}
: null} - {isLoading ?

Konfiguration wird geladen …

: ( -
-
-

Transport

-
- - - - - replaceConfiguration({ ...configuration, wattsPerSourceUnit: Number(event.target.value) })} /> -
-
- -
-

Spaltenzuordnung

-
- {columnFields.map(([key, label]) => ( - - updateColumn(key, event.target.value)} /> - - ))} -
-
- - replaceConfiguration({ ...configuration, additionalSourceMappings })} /> - replaceConfiguration({ ...configuration, familyTypeRules })} /> - -
-

CSV prüfen

-

Die Vorschau speichert keine Datei und verändert keine Projektdaten.

-
- { setFile(event.target.files?.[0] ?? null); setPreview(null); setImportPlan(null); setSuccess(null); }} style={{ maxWidth: 480 }} type="file" /> - - -
- {isDirty ?
Vor der Vorschau muss die Konfiguration gespeichert werden.
: null} -
- - {preview ? : null} - {importPlan ? ( - setFamilyLinks((current) => ({ ...current, [familyAndType]: projectDeviceId }))} - onRoomDecisionChange={(sourceRoomKey, decision) => setRoomDecisions((current) => ({ ...current, [sourceRoomKey]: decision }))} - plan={importPlan} - roomDecisions={roomDecisions} - setSourceName={setSourceName} - sourceName={sourceName} - /> - ) : null} -
- )} -
- ); -} - -function Field({ children, label }: { children: React.ReactNode; label: string }) { - return ; -} - -function AdditionalMappings({ configuration, onChange }: { configuration: ExternalCsvConfiguration; onChange: (value: ExternalCsvConfiguration["additionalSourceMappings"]) => void }) { - return

Weitere Quellfelder

{configuration.additionalSourceMappings.map((mapping, index) =>
onChange(configuration.additionalSourceMappings.map((entry, entryIndex) => entryIndex === index ? { ...entry, sourceColumn: event.target.value } : entry))} />
onChange(configuration.additionalSourceMappings.map((entry, entryIndex) => entryIndex === index ? { ...entry, targetField: event.target.value } : entry))} />
)}
; -} - -function FamilyRules({ configuration, onChange }: { configuration: ExternalCsvConfiguration; onChange: (value: ExternalCsvFamilyTypeRule[]) => void }) { - const rules = configuration.familyTypeRules; - function change(index: number, patch: Partial) { onChange(rules.map((rule, ruleIndex) => ruleIndex === index ? { ...rule, ...patch } : rule)); } - return

Familie-und-Typ-Regeln

Exakter Textvergleich; Reihenfolge wird beibehalten.
{rules.map((rule, index) =>
change(index, { exactFamilyAndType: event.target.value })} /> change(index, { internalDeviceType: event.target.value })} /> change(index, { connectionKind: event.target.value || null })} />{rule.quantityRule.kind === "fixed" ? change(index, { quantityRule: { kind: "fixed", quantity: Number(event.target.value) } })} /> : null}{rule.displayNameSuggestion?.kind === "fixed" ? change(index, { displayNameSuggestion: { kind: "fixed", value: event.target.value } })} /> : null}
)}
; -} - -function PreviewResult({ preview }: { preview: ExternalCsvPreviewDto }) { - const visibleObjects = useMemo(() => preview.objects.slice(0, 25), [preview]); - return

Prüfergebnis

SHA-256: {preview.sha256}

{visibleObjects.map((object) => )}
ZeileIFC-GUIDRaumFamilie und TypAuswahlkennerStromkreis
{object.rowNumber}{object.ifcGuid}{[object.roomNumber, object.roomName].filter(Boolean).join(" · ") || "–"}{object.familyAndType || "–"}{object.selectionMarker || "–"}{object.circuitIdentifier || "–"}
{preview.objects.length > visibleObjects.length ?

Es werden die ersten {visibleObjects.length} von {preview.objects.length} Objekten angezeigt.

: null}
; -} - -interface RoomDecision { - roomId: string | null; - defaultDistributionBoardId: string | null; -} - -export function RevitCsvImportPlan({ - familyLinks, - isApplying, - onApply, - onCreateProjectDevice, - onCreateRoom, - onFamilyLinkChange, - onRoomDecisionChange, - plan, - roomDecisions, - setSourceName, - sourceName, -}: { - familyLinks: Record; - isApplying: boolean; - onApply: () => void; - onCreateProjectDevice: (familyAndType: string) => void; - onCreateRoom: (sourceRoomKey: string) => void; - onFamilyLinkChange: (familyAndType: string, projectDeviceId: string | null) => void; - onRoomDecisionChange: (sourceRoomKey: string, decision: RoomDecision) => void; - plan: ExternalInitialImportPlanDto; - roomDecisions: Record; - setSourceName: (value: string) => void; - sourceName: string; -}) { - const hasBlockingIssues = plan.issueCounts.unknownFamilyAndType > 0; - const warningCount = - plan.issueCounts.invalidPower + - plan.issueCounts.invalidQuantity + - plan.issueCounts.missingRoom + - plan.suspectObjectCount; - const floorsById = new Map(plan.existing.floors.map((floor) => [floor.id, floor])); - - return ( -
-
-
-

Erstimport vorbereiten

-

- Raum- und Gerätekatalog-Zuordnungen werden zusammen mit {plan.objectCount} Revit-Objekten gespeichert. - Stromkreise und Gerätezeilen entstehen dabei noch nicht. -

-
- Konfiguration {plan.configurationVersion} -
- -
- - - - -
- - {hasBlockingIssues ? ( -
- {plan.issueCounts.unknownFamilyAndType} Objekte besitzen noch keine exakte Familie-und-Typ-Regel. - Ergänze die Regeln oben, speichere die Konfiguration und plane den Import erneut. -
- ) : null} - {plan.issueCounts.invalidPower > 0 ?
Bei {plan.issueCounts.invalidPower} Objekten ist die Leistung ungültig.
: null} - {plan.issueCounts.invalidQuantity > 0 ?
Bei {plan.issueCounts.invalidQuantity} Objekten ist die Menge ungültig.
: null} - {plan.issueCounts.missingRoom > 0 ?
{plan.issueCounts.missingRoom} Objekte besitzen keine Raumangabe.
: null} - {plan.suspectObjectCount > 0 ?
{plan.suspectObjectCount} Objektzeilen wurden als verdächtig erkannt.
: null} - - - -

Räume zuordnen

-
- - - - {plan.sourceRooms.map((sourceRoom) => { - const decision = roomDecisions[sourceRoom.sourceRoomKey] ?? { - roomId: sourceRoom.suggestedRoomId, - defaultDistributionBoardId: null, - }; - return ( - - - - - - - - ); - })} - -
QuellraumObjekteTrefferInterner RaumStandardverteilung
{[sourceRoom.roomNumber, sourceRoom.roomName].filter(Boolean).join(" · ")}{sourceRoom.objectCount} -
- - -
-
- -
-
- -

Familien und Typen zuordnen

-
- - - - {plan.familyGroups.map((group) => ( - - - - - - - ))} - -
Familie und TypObjekteKlassifizierungProjectDevice (optional)
{group.familyAndType || "–"}{group.objectCount} - {group.classified - ? `${group.internalDeviceType ?? "–"} · ${categoryLabel(group.category)}` - : Regel fehlt} - -
- - -
-
-
- -
- -
-
- ); -} - -function RoomMatchBadge({ status }: { status: ExternalInitialImportPlanDto["sourceRooms"][number]["matchStatus"] }) { - if (status === "exact-number") return Eindeutig; - if (status === "ambiguous-number") return Mehrdeutig; - return Neu; -} - -function categoryLabel(category: string | null) { - if (category === "lighting") return "Beleuchtung"; - if (category === "single_phase") return "1-phasig"; - if (category === "three_phase") return "3-phasig"; - return "Ohne Kategorie"; -} - -export function createRevitProjectDevicePrefill( - plan: ExternalInitialImportPlanDto, - familyAndType: string -): Partial { - const group = plan.familyGroups.find((entry) => entry.familyAndType === familyAndType); - const firstObject = plan.objects.find( - (object) => object.sourceValues.familyAndType === familyAndType - ); - const category = group?.category; - return { - name: group?.internalDeviceType || familyAndType || "Revit-Gerät", - displayName: firstObject?.suggestedPlanningValues.displayName || familyAndType, - connectionKind: group?.connectionKind ?? undefined, - category: - category === "lighting" || category === "three_phase" - ? category - : "single_phase", - quantity: firstObject?.suggestedPlanningValues.effectiveQuantity ?? 1, - powerPerUnit: - firstObject?.suggestedPlanningValues.powerPerUnitW === null || - firstObject?.suggestedPlanningValues.powerPerUnitW === undefined - ? 0.1 - : firstObject.suggestedPlanningValues.powerPerUnitW / 1000, - simultaneityFactor: - firstObject?.suggestedPlanningValues.simultaneityFactor ?? 1, - cosPhi: firstObject?.suggestedPlanningValues.cosPhi ?? undefined, - costGroup: firstObject?.suggestedPlanningValues.costGroup ?? undefined, - remark: firstObject?.suggestedPlanningValues.remark ?? undefined, - }; -} - -function Stat({ label, value }: { label: string; value: number }) { return
{label}
{value}
; } - -function fileToBase64(file: File) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onerror = () => reject(new Error("CSV-Datei konnte nicht gelesen werden.")); - reader.onload = () => { - const result = String(reader.result ?? ""); - const commaIndex = result.indexOf(","); - if (commaIndex < 0) reject(new Error("CSV-Datei konnte nicht kodiert werden.")); - else resolve(result.slice(commaIndex + 1)); - }; - reader.readAsDataURL(file); - }); -} diff --git a/src/frontend/components/revit-xlsx-settings-modal.tsx b/src/frontend/components/revit-xlsx-settings-modal.tsx new file mode 100644 index 0000000..7041ebc --- /dev/null +++ b/src/frontend/components/revit-xlsx-settings-modal.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useState, type FormEvent } from "react"; +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; +import type { ExternalXlsxColumnKey } from "../../external-model/xlsx/external-xlsx-contracts"; +import { FormModal } from "./form-modal"; + +const labels: Record = { + worksharingId: "Worksharing-ID", ifcGuid: "IfcGUID", roomNumber: "Raumnummer", + roomName: "Raumname", familyAndType: "Familie und Typ", selectionMarker: "Auswahlkenner", + socketCount: "Anzahl Objekte", sourceRemark: "Quellbemerkung", circuitCombined: "Stromkreis kombiniert", + boardName: "Verteiler", circuitIdentifier: "Stromkreis", designation: "Bezeichnung", + electricalPowerW: "Elektrische Leistung", voltageV: "Spannung", currentA: "Stromstärke", +}; + +export function RevitXlsxSettingsModal({ configuration, isSaving, onClose, onInspectSample, onSave }: { + configuration: ExternalModelConfiguration; + isSaving: boolean; + onClose: () => void; + onInspectSample: (file: File, configuration: ExternalModelConfiguration) => Promise; + onSave: (configuration: ExternalModelConfiguration) => Promise; +}) { + const [draft, setDraft] = useState(() => structuredClone(configuration)); + const [sampleStatus, setSampleStatus] = useState(null); + const columnKeys = Object.keys(draft.columns) as ExternalXlsxColumnKey[]; + + async function inspectSample(file: File | undefined) { + if (!file) return; + try { + setSampleStatus(await onInspectSample(file, draft)); + } catch (error) { + setSampleStatus(error instanceof Error ? error.message : "Musterdatei konnte nicht gelesen werden."); + } + } + + return { event.preventDefault(); void onSave(draft); }}> +
+
void inspectSample(event.target.files?.[0])} />{sampleStatus ?
{sampleStatus}
: null}
+ {(["headerRow", "firstDataRow", "firstDataColumn"] as const).map((key) =>
setDraft({ ...draft, layout: { ...draft.layout, [key]: Number(event.target.value) } })} />
)} +
+

Spaltenzuordnung

+ {columnKeys.map((key) =>
setDraft({ ...draft, columns: { ...draft.columns, [key]: event.target.value.trim() ? event.target.value : null } })} />
)} +
+
; +} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 96fd6c2..401b618 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -14,6 +14,13 @@ import type { ExternalCsvConfiguration, ExternalCsvDialect, } from "../external-model/csv/external-csv-contracts"; +import type { ExternalModelConfiguration } from "../external-model/configuration/external-model-configuration"; + +export interface ExternalModelConfigurationSnapshotDto { + id: string; + projectId: string; + configuration: ExternalModelConfiguration; +} export interface ExternalCsvConfigurationSnapshotDto { id: string; diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index 5256195..3694c2e 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -38,18 +38,14 @@ import type { RoomDto, CircuitTreeResponseDto, ProjectCircuitTreesResponseDto, - ExternalCsvConfigurationSnapshotDto, - ExternalCsvPreviewDto, - ExternalInitialImportPlanDto, - ApplyExternalInitialImportInput, - ExternalInitialImportResultDto, + ExternalModelConfigurationSnapshotDto, CreateEstimateBalanceInput, EstimateBalanceCommandResultDto, EstimateBalanceDto, EstimateBalanceUpdateResultDto, EstimateComparisonDto, } from "../types"; -import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts"; +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; import type { ProjectDeviceSyncField } from "../../shared/constants/project-device-sync-fields"; import { createCircuitUpdateProjectCommand, @@ -168,6 +164,40 @@ export function getProject(projectId: string) { return request(`/api/projects/${projectId}`); } +export function getExternalModelConfiguration(projectId: string) { + return request<{ configuration: ExternalModelConfigurationSnapshotDto | null }>( + `/api/projects/${projectId}/external-model/configuration` + ); +} + +export function updateExternalModelConfiguration( + projectId: string, + expectedRevision: number, + configuration: ExternalModelConfiguration +) { + return request<{ + configuration: ExternalModelConfigurationSnapshotDto; + history: ProjectHistoryStateDto; + }>(`/api/projects/${projectId}/external-model/configuration`, { + method: "PUT", + body: JSON.stringify({ expectedRevision, configuration }), + }); +} + +export async function detectExternalModelWorkbook( + projectId: string, + file: File, + configuration: ExternalModelConfiguration +) { + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return request<{ sheetName: string; columnCount: number; objectCount: number }>( + `/api/projects/${projectId}/external-model/configuration/detect`, + { method: "POST", body: JSON.stringify({ fileName: file.name, contentBase64: btoa(binary), configuration }) } + ); +} + export function getProjectHistory(projectId: string) { return request( `/api/projects/${projectId}/history` @@ -469,12 +499,6 @@ export function deleteDocumentLogo() { return request(documentLogoUrl, { method: "DELETE" }); } -export function getExternalCsvConfiguration(projectId: string) { - return request<{ configuration: ExternalCsvConfigurationSnapshotDto | null }>( - `/api/projects/${projectId}/external-csv/configuration` - ); -} - export function getExternalCircuitListObjects( projectId: string, circuitListId: string @@ -484,57 +508,6 @@ export function getExternalCircuitListObjects( ); } -export function updateExternalCsvConfiguration( - projectId: string, - expectedRevision: number, - configuration: ExternalCsvConfiguration -) { - return request< - ProjectCommandResultDto & { configuration: ExternalCsvConfigurationSnapshotDto } - >(`/api/projects/${projectId}/external-csv/configuration`, { - method: "PUT", - body: JSON.stringify({ expectedRevision, configuration }), - }); -} - -export function previewExternalCsv( - projectId: string, - fileName: string, - contentBase64: string -) { - return request( - `/api/projects/${projectId}/external-csv/preview`, - { - method: "POST", - body: JSON.stringify({ fileName, contentBase64 }), - } - ); -} - -export function planExternalInitialImport( - projectId: string, - fileName: string, - contentBase64: string -) { - return request( - `/api/projects/${projectId}/external-csv/initial-import/plan`, - { - method: "POST", - body: JSON.stringify({ fileName, contentBase64 }), - } - ); -} - -export function applyExternalInitialImport( - projectId: string, - input: ApplyExternalInitialImportInput -) { - return request( - `/api/projects/${projectId}/external-csv/initial-import/apply`, - { method: "POST", body: JSON.stringify(input) } - ); -} - export function copyDistributionBoard( projectId: string, distributionBoardId: string, diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index eb195d0..6a191cb 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -62,6 +62,7 @@ const commandTypeLabels: Record = { "project.restore-state": "Projektstand wiederhergestellt", "circuit-protection.update": "Stromkreisschutz bearbeitet", "external-csv-configuration.update": "Revit-CSV-Konfiguration bearbeitet", + "external-model-configuration.update": "Revit-XLSX-Einstellungen bearbeitet", "external-import.apply-initial": "Revit-Erstimport übernommen", "external-object.assign-to-new-circuit": "Externes Objekt in neuen Stromkreis übernommen", diff --git a/src/frontend/utils/revit-xlsx-settings.ts b/src/frontend/utils/revit-xlsx-settings.ts new file mode 100644 index 0000000..6c05c14 --- /dev/null +++ b/src/frontend/utils/revit-xlsx-settings.ts @@ -0,0 +1,17 @@ +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; + +export function createDefaultRevitXlsxConfiguration(): ExternalModelConfiguration { + return { + schemaVersion: 1, + layout: { headerRow: 1, firstDataRow: 3, firstDataColumn: 1 }, + circuitMode: "combined", + columns: { + worksharingId: "Worksharing-ID", ifcGuid: "IfcGUID", roomNumber: "MEP-Raum: Nummer", + roomName: "MEP-Raum: Name", familyAndType: "Familie und Typ", selectionMarker: "CAx_Auswahlkenner", + socketCount: "CAX_AnzahlObjekte", sourceRemark: "CAx_Anmerkung", circuitCombined: "kbp_Stromkreisnummer", + boardName: "kbp-E-Verteiler", circuitIdentifier: "kbp-E-Stromkreis", designation: "kbp-E-Bezeichnung", + electricalPowerW: "kbp-E-Elektrische Leistung", voltageV: "kbp-E-Spannung", currentA: "kbp-E-Stromstärke", + }, + deviceTypes: [], familyTypeRules: [], + }; +} diff --git a/src/server/controllers/external-model-configuration.controller.ts b/src/server/controllers/external-model-configuration.controller.ts new file mode 100644 index 0000000..0a4166a --- /dev/null +++ b/src/server/controllers/external-model-configuration.controller.ts @@ -0,0 +1,60 @@ +import { randomUUID } from "node:crypto"; +import type { Request, Response } from "express"; +import { createExternalModelConfigurationUpdateProjectCommand } from "../../domain/models/external-model-configuration-project-command.model.js"; +import { assertExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; +import { parseExternalXlsx } from "../../external-model/xlsx/external-xlsx-transport.js"; +import { externalModelConfigurationRepository } from "../composition/application-repositories.js"; +import { projectCommandService } from "../composition/project-command-stores.js"; +import { respondWithProjectCommandError } from "./project-command.controller.js"; + +export function getExternalModelConfiguration(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + const result = externalModelConfigurationRepository.getByProject(projectId); + if (!result.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + return res.json({ configuration: result.configuration }); +} + +export function updateExternalModelConfiguration(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + const expectedRevision = req.body?.expectedRevision; + if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) { + return res.status(400).json({ error: "Ungültige Projektrevision." }); + } + try { + assertExternalModelConfiguration(req.body?.configuration); + const current = externalModelConfigurationRepository.getByProject(projectId); + if (!current.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + const target = { + id: current.configuration?.id ?? randomUUID(), + projectId, + configuration: req.body.configuration, + }; + const result = projectCommandService.executeUser({ + projectId, + expectedRevision, + description: "Revit-XLSX-Einstellungen gespeichert", + command: createExternalModelConfigurationUpdateProjectCommand(current.configuration, target), + }); + return res.json({ configuration: target, history: result.history }); + } catch (error) { + return respondWithProjectCommandError(error, res); + } +} + +export async function detectExternalModelWorkbook(req: Request, res: Response) { + try { + assertExternalModelConfiguration(req.body?.configuration); + const document = await parseExternalXlsx({ + fileName: req.body?.fileName, + bytes: Buffer.from(req.body?.contentBase64 ?? "", "base64"), + configuration: req.body.configuration, + }); + return res.json({ + sheetName: document.sheetName, + columnCount: document.columns.length, + objectCount: document.rows.filter((row) => row.classification === "object").length, + }); + } catch (error) { + return res.status(400).json({ error: error instanceof Error ? error.message : "Musterdatei konnte nicht gelesen werden." }); + } +} diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index 06f9ec2..d0ca12d 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -53,6 +53,11 @@ import { importProjectTransfer, importProjectTransferAsNewProject, } from "../controllers/project-transfer.controller.js"; +import { + getExternalModelConfiguration, + detectExternalModelWorkbook, + updateExternalModelConfiguration, +} from "../controllers/external-model-configuration.controller.js"; export const projectRouter = Router(); @@ -74,6 +79,9 @@ projectRouter.post( restoreProjectSnapshot ); projectRouter.put("/:projectId", updateProjectSettings); +projectRouter.get("/:projectId/external-model/configuration", getExternalModelConfiguration); +projectRouter.put("/:projectId/external-model/configuration", updateExternalModelConfiguration); +projectRouter.post("/:projectId/external-model/configuration/detect", detectExternalModelWorkbook); projectRouter.get("/:projectId/distribution-boards", listDistributionBoardsByProject); projectRouter.post("/:projectId/distribution-boards", createDistributionBoard); projectRouter.post( diff --git a/tests/revit-csv-frontend-api.test.ts b/tests/revit-csv-frontend-api.test.ts deleted file mode 100644 index add2eb7..0000000 --- a/tests/revit-csv-frontend-api.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { createElement } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; -import { - createRevitProjectDevicePrefill, - RevitCsvImportPlan, - RevitCsvModal, -} from "../src/frontend/components/revit-csv-modal.js"; -import { ProjectDeviceModal } from "../src/frontend/components/project-device-modal.js"; -import { RoomModal } from "../src/frontend/components/room-modal.js"; -import { - applyExternalInitialImport, - getExternalCsvConfiguration, - getExternalCircuitListObjects, - planExternalInitialImport, - previewExternalCsv, - updateExternalCsvConfiguration, -} from "../src/frontend/utils/api.js"; -import type { ExternalInitialImportPlanDto } from "../src/frontend/types.js"; -import { createDefaultExternalCsvConfiguration } from "../src/external-model/csv/external-csv-contracts.js"; -import { externalCsvTestColumns } from "./fixtures/revit-csv-fixtures.js"; - -describe("Revit CSV frontend API", () => { - it("uses the project-scoped configuration, preview and import endpoints", async () => { - const requests: Array<{ url: string; method: string; body: unknown }> = []; - const originalFetch = globalThis.fetch; - globalThis.fetch = async (input, init) => { - requests.push({ - url: String(input), - method: init?.method ?? "GET", - body: init?.body ? JSON.parse(String(init.body)) : null, - }); - return new Response(JSON.stringify({ configuration: null }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - }; - const configuration = createDefaultExternalCsvConfiguration(externalCsvTestColumns); - - try { - await getExternalCsvConfiguration("project-1"); - await getExternalCircuitListObjects("project-1", "list-1"); - await updateExternalCsvConfiguration("project-1", 7, configuration); - await previewExternalCsv("project-1", "revit.csv", "YWJj"); - await planExternalInitialImport("project-1", "revit.csv", "YWJj"); - await applyExternalInitialImport("project-1", { - expectedRevision: 8, - expectedConfigurationVersion: 2, - expectedSha256: "sha", - fileName: "revit.csv", - contentBase64: "YWJj", - sourceName: "Revit-Gesamtmodell", - roomDecisions: [{ sourceRoomKey: "101|büro", roomId: "room-1", defaultDistributionBoardId: "board-1" }], - familyProjectDeviceDecisions: [{ familyAndType: "Steckdose : Standard", projectDeviceId: "device-1" }], - }); - } finally { - globalThis.fetch = originalFetch; - } - - assert.deepEqual(requests, [ - { - url: "/api/projects/project-1/external-csv/configuration", - method: "GET", - body: null, - }, - { - url: "/api/projects/project-1/circuit-lists/list-1/external-objects", - method: "GET", - body: null, - }, - { - url: "/api/projects/project-1/external-csv/configuration", - method: "PUT", - body: { expectedRevision: 7, configuration }, - }, - { - url: "/api/projects/project-1/external-csv/preview", - method: "POST", - body: { fileName: "revit.csv", contentBase64: "YWJj" }, - }, - { - url: "/api/projects/project-1/external-csv/initial-import/plan", - method: "POST", - body: { fileName: "revit.csv", contentBase64: "YWJj" }, - }, - { - url: "/api/projects/project-1/external-csv/initial-import/apply", - method: "POST", - body: { - expectedRevision: 8, - expectedConfigurationVersion: 2, - expectedSha256: "sha", - fileName: "revit.csv", - contentBase64: "YWJj", - sourceName: "Revit-Gesamtmodell", - roomDecisions: [{ sourceRoomKey: "101|büro", roomId: "room-1", defaultDistributionBoardId: "board-1" }], - familyProjectDeviceDecisions: [{ familyAndType: "Steckdose : Standard", projectDeviceId: "device-1" }], - }, - }, - ]); - }); -}); - -describe("Revit CSV modal presentation", () => { - it("uses the viewport-wide dialog variant", () => { - const markup = renderToStaticMarkup( - createElement(RevitCsvModal, { - currentRevision: 0, - onClose: () => undefined, - onCreateProjectDevice: async () => ({} as never), - onCreateRoom: async () => ({} as never), - onRevisionChange: () => undefined, - projectId: "project-1", - }) - ); - - assert.match(markup, /max-width:calc\(100vw - 2rem\)/); - assert.doesNotMatch(markup, /modal-lg/); - }); - - it("renders the initial import decisions without individual object rows", () => { - const plan: ExternalInitialImportPlanDto = { - configurationVersion: 2, - fileName: "revit.csv", - sha256: "sha", - byteLength: 100, - rowCount: 2, - objectCount: 1, - passthroughCount: 1, - suspectObjectCount: 0, - suspectRowNumbers: [], - sourceRooms: [{ - sourceRoomKey: "101|büro", - roomNumber: "101", - roomName: "Büro", - objectCount: 1, - suggestedRoomId: "room-1", - matchStatus: "exact-number", - candidateRoomIds: ["room-1"], - }], - familyGroups: [{ - familyAndType: "Steckdose : Standard", - objectCount: 1, - classified: true, - category: "single_phase", - connectionKind: null, - internalDeviceType: "socket", - }], - issueCounts: { unknownFamilyAndType: 0, invalidPower: 0, invalidQuantity: 0, missingRoom: 0 }, - objects: [], - existing: { - floors: [{ id: "floor-1", name: "EG", sortOrder: 0 }], - rooms: [{ id: "room-1", floorId: "floor-1", roomNumber: "101", roomName: "Büro", areaM2: null }], - distributionBoards: [{ id: "board-1", name: "UV-01", floorId: "floor-1" }], - projectDevices: [{ id: "device-1", name: "Steckdose", displayName: "Steckdose", category: "single_phase", connectionKind: null, powerPerUnit: 100 }], - }, - }; - const markup = renderToStaticMarkup(createElement(RevitCsvImportPlan, { - familyLinks: { "Steckdose : Standard": "device-1" }, - isApplying: false, - onApply: () => undefined, - onCreateProjectDevice: () => undefined, - onCreateRoom: () => undefined, - onFamilyLinkChange: () => undefined, - onRoomDecisionChange: () => undefined, - plan, - roomDecisions: { "101|büro": { roomId: "room-1", defaultDistributionBoardId: "board-1" } }, - setSourceName: () => undefined, - sourceName: "Revit-Gesamtmodell", - })); - - assert.match(markup, /Erstimport vorbereiten/); - assert.match(markup, /101 · Büro/); - assert.match(markup, /Steckdose : Standard/); - assert.match(markup, /Erstimport übernehmen/); - assert.match(markup, /Raum 101 neu anlegen/); - assert.match(markup, /ProjectDevice für Steckdose : Standard neu anlegen/); - assert.doesNotMatch(markup, /IFC-GUID/); - }); - - it("prefills the existing room and ProjectDevice forms from Revit decisions", () => { - const roomMarkup = renderToStaticMarkup(createElement(RoomModal, { - floors: [{ id: "floor-1", projectId: "project-1", name: "EG", sortOrder: 0 }], - initialValues: { roomNumber: "101", roomName: "Büro" }, - isSaving: false, - onClose: () => undefined, - onSave: async () => undefined, - })); - const deviceMarkup = renderToStaticMarkup(createElement(ProjectDeviceModal, { - globalDevices: [], - initialValues: { - name: "socket", - displayName: "Steckdose", - category: "single_phase", - quantity: 2, - powerPerUnit: 0.1, - simultaneityFactor: 1, - }, - isSaving: false, - onClose: () => undefined, - onImportGlobal: async () => undefined, - onSave: async () => undefined, - })); - - assert.match(roomMarkup, /value="101"/); - assert.match(roomMarkup, /value="Büro"/); - assert.match(deviceMarkup, /value="socket"/); - assert.match(deviceMarkup, /value="Steckdose"/); - assert.match(deviceMarkup, /value="2"/); - }); - - it("converts mapped Revit watts into ProjectDevice kilowatts", () => { - const plan = { - familyGroups: [{ - familyAndType: "Steckdose : Standard", - internalDeviceType: "socket", - category: "single_phase", - connectionKind: "230 V", - }], - objects: [{ - sourceValues: { familyAndType: "Steckdose : Standard" }, - suggestedPlanningValues: { - displayName: "Arbeitsplatzsteckdose", - effectiveQuantity: 4, - powerPerUnitW: 250, - simultaneityFactor: 0.8, - cosPhi: 0.95, - costGroup: "440", - remark: "Aus Revit", - }, - }], - } as ExternalInitialImportPlanDto; - - assert.deepEqual( - createRevitProjectDevicePrefill(plan, "Steckdose : Standard"), - { - name: "socket", - displayName: "Arbeitsplatzsteckdose", - connectionKind: "230 V", - category: "single_phase", - quantity: 4, - powerPerUnit: 0.25, - simultaneityFactor: 0.8, - cosPhi: 0.95, - costGroup: "440", - remark: "Aus Revit", - } - ); - }); -}); diff --git a/tests/revit-xlsx-settings-api.test.ts b/tests/revit-xlsx-settings-api.test.ts new file mode 100644 index 0000000..090e6b3 --- /dev/null +++ b/tests/revit-xlsx-settings-api.test.ts @@ -0,0 +1,38 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { describe, it } from "node:test"; +import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; +import { detectExternalModelWorkbook, getExternalModelConfiguration, updateExternalModelConfiguration } from "../src/frontend/utils/api.js"; + +describe("Revit XLSX settings", () => { + it("uses the project-scoped configuration endpoint with expectedRevision", async () => { + const requests: Array<{ url: string; method: string; body: unknown }> = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (input, init) => { + requests.push({ url: String(input), method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined }); + return new Response(JSON.stringify({ configuration: null, history: { currentRevision: 8 } }), { status: 200, headers: { "Content-Type": "application/json" } }); + }; + try { + const configuration = createDefaultExternalModelConfiguration(); + await getExternalModelConfiguration("project-1"); + await updateExternalModelConfiguration("project-1", 7, configuration); + await detectExternalModelWorkbook("project-1", new File([new Uint8Array([1, 2])], "sample.xlsx"), configuration); + assert.deepEqual(requests, [ + { url: "/api/projects/project-1/external-model/configuration", method: "GET", body: undefined }, + { url: "/api/projects/project-1/external-model/configuration", method: "PUT", body: { expectedRevision: 7, configuration } }, + { url: "/api/projects/project-1/external-model/configuration/detect", method: "POST", body: { fileName: "sample.xlsx", contentBase64: "AQI=", configuration } }, + ]); + } finally { globalThis.fetch = originalFetch; } + }); + + it("exposes the Revit route and removes the old project modal", () => { + const projectPage = readFileSync("src/app/projects/[projectId]/page.tsx", "utf8"); + const revitPage = readFileSync("src/app/projects/[projectId]/revit/page.tsx", "utf8"); + const settings = readFileSync("src/frontend/components/revit-xlsx-settings-modal.tsx", "utf8"); + assert.match(projectPage, /href={`\/projects\/\$\{projectId\}\/revit`}/); + assert.doesNotMatch(projectPage, /RevitCsvModal|Revit-CSV/); + assert.match(revitPage, /Importstatus/); + assert.match(settings, /Musterdatei prüfen/); + assert.match(settings, /Kombinierte Stromkreisspalte/); + }); +}); From bfdd0482695da50dc89f3ee6c0c5b670428902fa Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 09:50:58 +0200 Subject: [PATCH 31/38] Add Linear XLSX initial import --- AGENTS.md | 8 +- README.md | 7 +- docs/current-architecture.md | 19 +- docs/spec/revit-excel-phase-14-plan.md | 13 +- src/app/projects/[projectId]/revit/page.tsx | 35 ++- ...itial-import-project-command.repository.ts | 87 +++++++ ...al-initial-import-project-command.model.ts | 105 ++++++++ ...al-initial-import-project-command.store.ts | 15 ++ .../services/project-command.service.ts | 18 +- .../external-xlsx-initial-import-target.ts | 62 +++++ .../external-xlsx-initial-import.ts | 246 ++++++++++++++++++ .../revit-initial-import-wizard.tsx | 106 ++++++++ src/frontend/types.ts | 78 ++---- src/frontend/utils/api.ts | 38 +++ src/frontend/utils/project-version-history.ts | 1 + .../composition/project-command-stores.ts | 6 +- .../external-initial-import.controller.ts | 68 +++++ src/server/routes/project.routes.ts | 8 + tests/external-xlsx-initial-import.test.ts | 68 +++++ tests/revit-xlsx-settings-api.test.ts | 29 ++- 20 files changed, 932 insertions(+), 85 deletions(-) create mode 100644 src/db/repositories/external-initial-import-project-command.repository.ts create mode 100644 src/domain/models/external-initial-import-project-command.model.ts create mode 100644 src/domain/ports/external-initial-import-project-command.store.ts create mode 100644 src/external-model/application/external-xlsx-initial-import-target.ts create mode 100644 src/external-model/application/external-xlsx-initial-import.ts create mode 100644 src/frontend/components/revit-initial-import-wizard.tsx create mode 100644 src/server/controllers/external-initial-import.controller.ts create mode 100644 tests/external-xlsx-initial-import.test.ts diff --git a/AGENTS.md b/AGENTS.md index e8d4bff..d771e59 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -333,6 +333,12 @@ R4 adds `/projects/:projectId/revit`, its revisioned XLSX settings and server-side sample detection, and removes the old project-page CSV modal. See `docs/spec/revit-excel-integration-requirements.md` and `docs/spec/revit-excel-phase-14-plan.md`. +R5 adds stateless XLSX preview/planning and the six-step initial-import wizard. +`external-model.apply-initial-import` stores the configuration and complete +external model state atomically; its inverse powers persistent Undo/Redo +without parsing workbook bytes. Apply retransmits and reparses the XLSX, +verifies its preview SHA-256 and creates no circuit, equipment identifier or +CircuitDeviceRow. The target configuration has no independent version counter; `expectedRevision` invalidates stale plans, and each import batch stores a configuration copy. @@ -586,7 +592,7 @@ Critical target rules: selected combined/separate mode block export. - Missing GZF defaults visibly to 1 without separate confirmation. - The corrected R2 return workbook was successfully imported into Linear on - 2026-09-30; R3 and R4 are complete and R5 is the next package. + 2026-09-30; R3 through R5 are complete and R6 is the next package. - All confirmed writes use typed project commands with `expectedRevision`, complete inverse data and the shared project-command transaction boundary. - Do not add automatic circuit planning, Revit circuit adoption, multi-source diff --git a/README.md b/README.md index b70a145..b965df8 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,10 @@ für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstützte Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind vorhanden. Die Backend- und Persistenzgrundlage der bisherigen Revit-CSV-/IfcGUID-Anbindung ist durch den XLSX-Austausch des Linear-Plugins mit -Worksharing-ID als externem Schlüssel ersetzt. R0 bis R4 sind abgeschlossen; -die eigene Revit-Seite mit XLSX-Einstellungen ist vorhanden. Erstimport, -Editorzuordnung, Rückgabe und Folgeimport folgen in R5 bis R10. +Worksharing-ID als externem Schlüssel ersetzt. R0 bis R5 sind abgeschlossen; +die eigene Revit-Seite besitzt XLSX-Einstellungen und einen persistenten +Erstimport. Objekttabelle, Editorzuordnung, Rückgabe und Folgeimport folgen in +R6 bis R10. ## Unterstützter Arbeitsablauf diff --git a/docs/current-architecture.md b/docs/current-architecture.md index 846debb..4dfa96c 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -643,7 +643,7 @@ PostgreSQL ist bewusst nicht implementiert. Die Domainregeln und Transaktionsgrenzen sollen portabel bleiben; Schema und Betriebsmodell benötigen bei einem späteren Wechsel trotzdem einen eigenen PostgreSQL-Adapter. -## Revit-Anbindung: Linear-XLSX-Grundlage nach R3 +## Revit-Anbindung: Linear-XLSX-Erstimport nach R5 R3 hat den Backend- und Persistenz-Cutover abgeschlossen. Migration `0014` entfernt die alten externen CSV-Entwicklungsdaten, nachdem verknüpfte @@ -663,9 +663,20 @@ CSV-Zustand sowie alte CSV-History-Commands werden mit einer deutschen Meldung abgelehnt. Der XLSX-Adapter liegt unter `src/external-model/xlsx`. Der Backend-CSV-Parser, -seine Endpunkte und Laufzeitverträge sind entfernt. Die noch sichtbare alte -Projektseiten-Oberfläche ist bis R4 ohne Backend-Anbindung und wird dort durch -die Route `/projects/:projectId/revit` ersetzt. +seine Endpunkte und Laufzeitverträge sind entfernt. Die Route +`/projects/:projectId/revit` enthält Einstellungen, Importstatus und den +sechsstufigen Erstimportwizard. + +`POST /api/projects/:projectId/external-model/initial-import/plan` liest eine +lokale XLSX zustandslos, gruppiert Quellräume und exakte Familie-und-Typ-Werte +und liefert die vorhandenen Raum-, Verteiler- und ProjectDevice-Kataloge. +Unbekannte Familien bleiben blockierend; fehlender GZF wird sichtbar mit 1 +vorbelegt. `apply` erhält die Datei erneut, parst sie erneut und vergleicht den +Vorschau-SHA-256. Der Command `external-model.apply-initial-import` speichert +die dabei verwendete Konfiguration und den vollständigen externen Zustand in +derselben Transaktion. Er erzeugt weder CircuitDeviceRows noch Circuits oder +BMKs. Seine vollständige Inverse macht Undo/Redo nach Neustart möglich, ohne +Workbookbytes erneut einzulesen oder zu parsen. ### Historische Ausgangslage vor R3 diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index 0b1b71a..f4d1c7c 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -13,7 +13,7 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | R2 | abgeschlossen und freigegeben | XLSX-Adapter, Parser, synthetische Fixtures, lokaler Referenzprüfer und reale Rückgabedatei sind erstellt; der korrigierte Rückimport wurde am 30.09.2026 erfolgreich in Linear getestet. | | R3 | abgeschlossen | Konfiguration ohne eigene Revision, Worksharing-ID-Datenmodell, Migration 0014, Snapshot 10, Transfer und Backend-CSV-Entfernung sind umgesetzt und geprüft. | | R4 | abgeschlossen | Revit-Seite, Navigation und revisionierte XLSX-Einstellungen mit Musterdateiprüfung sind umgesetzt; das alte Projektseitenmodal ist entfernt. | -| R5 | offen | Erstimportwizard mit Gerätearten, Familienregeln und optionalen ProjectDevices. | +| R5 | abgeschlossen | Zustandslose XLSX-Vorschau, sechsstufiger Erstimportwizard und atomarer Importcommand mit parserfreiem Undo/Redo. | | R6 | offen | Virtualisierte Objekttabelle und Sammelzuordnungen. | | R7 | offen | Editorbereich, Gruppierung, Drag-and-drop, Lösen und integrierte Löschübergänge. | | R8 | offen | Rückgabe-Excel und append-only Exportnachweis. | @@ -121,6 +121,17 @@ vollständiges UUID-Remapping. Pflicht: echte SQLite-Commit-/Rollback-Tests. - ein atomarer Importcommand, keine Row-/Circuit-Erzeugung; - Undo/Redo aus Commandzuständen ohne Workbook-Parsing. +Implementierungsstand vom 30.09.2026: Vorschau und Apply verwenden die +projektweite XLSX-Konfiguration; Apply überträgt und parst die Datei erneut und +vergleicht den SHA-256 der Vorschau. Der Wizard führt über Vorschau, Räume, +Standardverteiler einschließlich Objekten ohne Raum, exakte Familienregeln, +optionale ProjectDevices und Bestätigung. Unbekannte Familien können als +Geräteart mit stabilen Client-UUIDs und sichtbarem GZF-Startwert 1 klassifiziert +werden. `external-model.apply-initial-import` schreibt Konfiguration, Quelle, +vollständigen letzten Batch, Raumzuordnungen und Objekte in einer Revision; +alle `circuitDeviceRowId` bleiben `null`. Seine Inverse speichert beide +Zustände vollständig, sodass Undo/Redo weder Datei noch Parser benötigen. + ## R6 – Objekttabelle und Sammelaktionen - kompakte Objektliste einmal laden; diff --git a/src/app/projects/[projectId]/revit/page.tsx b/src/app/projects/[projectId]/revit/page.tsx index 96af41c..bf9b39f 100644 --- a/src/app/projects/[projectId]/revit/page.tsx +++ b/src/app/projects/[projectId]/revit/page.tsx @@ -1,34 +1,49 @@ "use client"; -import { ArrowLeft, FileSpreadsheet, Settings } from "lucide-react"; +import { ArrowLeft, FileSpreadsheet, Settings, Upload } from "lucide-react"; import { useParams } from "next/navigation"; import { useEffect, useState } from "react"; import { IconLink } from "../../../../frontend/components/icon-link"; +import { RevitInitialImportWizard } from "../../../../frontend/components/revit-initial-import-wizard"; import { RevitXlsxSettingsModal } from "../../../../frontend/components/revit-xlsx-settings-modal"; import type { ExternalModelConfiguration } from "../../../../external-model/configuration/external-model-configuration"; -import { detectExternalModelWorkbook, getExternalModelConfiguration, getProject, updateExternalModelConfiguration } from "../../../../frontend/utils/api"; +import { detectExternalModelWorkbook, getExternalInitialImportStatus, getExternalModelConfiguration, getProject, updateExternalModelConfiguration } from "../../../../frontend/utils/api"; import { createDefaultRevitXlsxConfiguration } from "../../../../frontend/utils/revit-xlsx-settings"; -import type { ExternalModelConfigurationSnapshotDto, ProjectDto } from "../../../../frontend/types"; +import type { ExternalInitialImportStatusDto, ExternalModelConfigurationSnapshotDto, ProjectDto } from "../../../../frontend/types"; export default function RevitPage() { const { projectId } = useParams<{ projectId: string }>(); const [project, setProject] = useState(null); const [snapshot, setSnapshot] = useState(null); - const [open, setOpen] = useState(false); + const [importStatus, setImportStatus] = useState(null); + const [settingsOpen, setSettingsOpen] = useState(false); + const [importOpen, setImportOpen] = useState(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); - useEffect(() => { Promise.all([getProject(projectId), getExternalModelConfiguration(projectId)]).then(([loadedProject, result]) => { setProject(loadedProject); setSnapshot(result.configuration); }).catch((value: unknown) => setError(value instanceof Error ? value.message : "Revit-Daten konnten nicht geladen werden.")); }, [projectId]); + + useEffect(() => { + Promise.all([getProject(projectId), getExternalModelConfiguration(projectId), getExternalInitialImportStatus(projectId)]) + .then(([loadedProject, configuration, status]) => { setProject(loadedProject); setSnapshot(configuration.configuration); setImportStatus(status); }) + .catch((value: unknown) => setError(value instanceof Error ? value.message : "Revit-Daten konnten nicht geladen werden.")); + }, [projectId]); + async function save(configuration: ExternalModelConfiguration) { if (!project) return; setSaving(true); setError(null); - try { const result = await updateExternalModelConfiguration(projectId, project.currentRevision, configuration); setSnapshot(result.configuration); setProject({ ...project, currentRevision: result.history.currentRevision }); setOpen(false); } - catch (value) { setError(value instanceof Error ? value.message : "Einstellungen konnten nicht gespeichert werden."); } + try { + const result = await updateExternalModelConfiguration(projectId, project.currentRevision, configuration); + setSnapshot(result.configuration); + setProject({ ...project, currentRevision: result.history.currentRevision }); + setSettingsOpen(false); + } catch (value) { setError(value instanceof Error ? value.message : "Einstellungen konnten nicht gespeichert werden."); } finally { setSaving(false); } } + return
-
Projekt · Revit

{project?.name ?? "Revit-Anbindung"}

Linear-XLSX austauschen und Revit-Objekte verwalten

+
Projekt · Revit

{project?.name ?? "Revit-Anbindung"}

Linear-XLSX austauschen und Revit-Objekte verwalten

{error ?
{error}
: null} -

XLSX-Konfiguration

{snapshot ? "Die Linear-Spalten und das Tabellenlayout sind konfiguriert." : "Noch keine XLSX-Konfiguration gespeichert."}

{snapshot ? "Konfiguriert" : "Offen"}

Importstatus

Noch kein Linear-XLSX-Import vorhanden. Der Erstimport folgt in R5.

- {open ? setOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} +

XLSX-Konfiguration

{snapshot ? "Die Linear-Spalten und das Tabellenlayout sind konfiguriert." : "Noch keine XLSX-Konfiguration gespeichert."}

{snapshot ? "Konfiguriert" : "Offen"}

Importstatus

{importStatus?.imported ? <>

{importStatus.objectCount} Revit-Objekte{importStatus.fileName ? ` aus ${importStatus.fileName}` : ""}

Quelle: {importStatus.sourceName}

:

Noch kein Linear-XLSX-Import vorhanden.

}
+ {settingsOpen ? setSettingsOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} + {importOpen && project && snapshot ? setImportOpen(false)} onImported={({ history }) => { setProject({ ...project, currentRevision: history.currentRevision }); setImportOpen(false); void Promise.all([getExternalInitialImportStatus(projectId), getExternalModelConfiguration(projectId)]).then(([status, configuration]) => { setImportStatus(status); setSnapshot(configuration.configuration); }); }} /> : null}
; } diff --git a/src/db/repositories/external-initial-import-project-command.repository.ts b/src/db/repositories/external-initial-import-project-command.repository.ts new file mode 100644 index 0000000..70a249b --- /dev/null +++ b/src/db/repositories/external-initial-import-project-command.repository.ts @@ -0,0 +1,87 @@ +import { createHash } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { + assertExternalInitialImportProjectCommand, + createExternalInitialImportProjectCommand, + isEmptyExternalModelState, +} from "../../domain/models/external-initial-import-project-command.model.js"; +import type { ExternalModelConfigurationSnapshot } from "../../domain/models/external-model-configuration-project-command.model.js"; +import type { ExternalInitialImportProjectCommandStore } from "../../domain/ports/external-initial-import-project-command.store.js"; +import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; +import type { AppDatabase } from "../database-context.js"; +import { distributionBoards } from "../schema/distribution-boards.js"; +import { externalImportBatches } from "../schema/external-import-batches.js"; +import { externalModelConfigurations } from "../schema/external-model-configurations.js"; +import { externalModelObjects } from "../schema/external-model-objects.js"; +import { externalModelSources } from "../schema/external-model-sources.js"; +import { externalRoomMappings } from "../schema/external-room-mappings.js"; +import { projectDevices } from "../schema/project-devices.js"; +import { projects } from "../schema/projects.js"; +import { rooms } from "../schema/rooms.js"; +import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { ExternalModelStateRepository } from "./external-model-state.repository.js"; + +export class ExternalInitialImportProjectCommandRepository implements ExternalInitialImportProjectCommandStore { + constructor(private readonly database: AppDatabase) {} + + execute(input: Parameters[0]) { + assertExternalInitialImportProjectCommand(input.command); + return executeProjectCommandTransaction(this.database, input, (tx) => { + const currentStateResult = new ExternalModelStateRepository(tx).getByProject(input.projectId); + if (!currentStateResult.projectExists) throw new Error("Projekt nicht gefunden."); + const currentConfiguration = tx.select().from(externalModelConfigurations).where(eq(externalModelConfigurations.projectId, input.projectId)).get() ?? null; + const payload = input.command.payload; + if (!same(payload.expectedState, currentStateResult.state) || !same(payload.expectedConfiguration, currentConfiguration)) { + throw new Error("Revit-Zustand oder Konfiguration wurde zwischenzeitlich geändert."); + } + if (!isEmptyExternalModelState(payload.targetState)) validateTarget(tx, input.projectId, input.expectedRevision, input.source, payload.targetConfiguration, payload.targetState); + replaceConfiguration(tx, input.projectId, payload.targetConfiguration); + replaceState(tx, input.projectId, payload.targetState); + const persistedState = new ExternalModelStateRepository(tx).getByProject(input.projectId).state; + const persistedConfiguration = tx.select().from(externalModelConfigurations).where(eq(externalModelConfigurations.projectId, input.projectId)).get() ?? null; + if (!same(payload.targetState, persistedState) || !same(payload.targetConfiguration, persistedConfiguration)) throw new Error("Gespeicherter Revit-Erstimport weicht vom Zielzustand ab."); + return createExternalInitialImportProjectCommand(payload.targetConfiguration, currentConfiguration, payload.targetState, currentStateResult.state); + }); + } +} + +function validateTarget(database: AppDatabase, projectId: string, expectedRevision: number, source: string, configuration: ExternalModelConfigurationSnapshot | null, state: ExternalModelStateSnapshot) { + if (!configuration || configuration.projectId !== projectId || state.source?.projectId !== projectId) throw new Error("Der Revit-Erstimport gehört zu einem anderen Projekt."); + const batch = state.importBatches[0]; + if (source === "user" && batch.appliedProjectRevision !== expectedRevision + 1) throw new Error("Die Projektrevision des Revit-Erstimports ist ungültig."); + if (!same(batch.configurationSnapshot, configuration.configuration)) throw new Error("Die Konfigurationskopie des Importbatches ist ungültig."); + const bytes = decodeCanonicalBase64(batch.originalContentBase64!); + if (createHash("sha256").update(bytes).digest("hex") !== batch.sha256) throw new Error("Die Prüfsumme des Revit-Erstimports ist ungültig."); + const roomIds = ids(database.select({ id: rooms.id }).from(rooms).where(eq(rooms.projectId, projectId)).all()); + const boardIds = ids(database.select({ id: distributionBoards.id }).from(distributionBoards).where(eq(distributionBoards.projectId, projectId)).all()); + const projectDeviceIds = ids(database.select({ id: projectDevices.id }).from(projectDevices).where(eq(projectDevices.projectId, projectId)).all()); + const deviceTypeIds = new Set(configuration.configuration.deviceTypes.map((type) => type.id)); + for (const mapping of state.roomMappings) { + if (mapping.roomId !== null && !roomIds.has(mapping.roomId)) throw new Error("Eine Raumzuordnung verweist auf ein anderes Projekt."); + if (mapping.defaultDistributionBoardId !== null && !boardIds.has(mapping.defaultDistributionBoardId)) throw new Error("Ein Standardverteiler verweist auf ein anderes Projekt."); + } + for (const object of state.objects) { + if (!deviceTypeIds.has(object.deviceTypeId)) throw new Error("Ein Revit-Objekt verweist auf eine unbekannte Geräteart."); + if (object.distributionBoardId !== null && !boardIds.has(object.distributionBoardId)) throw new Error("Ein Revit-Objekt verweist auf einen fremden Verteiler."); + if (object.linkedProjectDeviceId !== null && !projectDeviceIds.has(object.linkedProjectDeviceId)) throw new Error("Ein Revit-Objekt verweist auf ein fremdes Projektgerät."); + } +} + +function replaceConfiguration(database: AppDatabase, projectId: string, target: ExternalModelConfigurationSnapshot | null) { + database.delete(externalModelConfigurations).where(eq(externalModelConfigurations.projectId, projectId)).run(); + if (target) database.insert(externalModelConfigurations).values(target).run(); +} + +function replaceState(database: AppDatabase, projectId: string, target: ExternalModelStateSnapshot) { + database.delete(externalModelSources).where(eq(externalModelSources.projectId, projectId)).run(); + if (!target.source) return; + database.insert(externalModelSources).values(target.source).run(); + database.insert(externalImportBatches).values(target.importBatches.map(({ originalContentBase64, ...batch }) => ({ ...batch, originalBytes: originalContentBase64 === null ? null : Buffer.from(originalContentBase64, "base64") }))).run(); + if (target.roomMappings.length) database.insert(externalRoomMappings).values(target.roomMappings).run(); + if (target.objects.length) database.insert(externalModelObjects).values(target.objects).run(); +} + +function decodeCanonicalBase64(value: string) { const bytes = Buffer.from(value, "base64"); if (bytes.toString("base64") !== value) throw new Error("Der XLSX-Inhalt ist nicht kanonisch Base64-kodiert."); return bytes; } +function ids(entries: Array<{ id: string }>) { return new Set(entries.map((entry) => entry.id)); } +function same(left: unknown, right: unknown) { return canonical(left) === canonical(right); } +function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (value !== null && typeof value === "object") { const record = value as Record; return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonical(record[key])}`).join(",")}}`; } return JSON.stringify(value); } diff --git a/src/domain/models/external-initial-import-project-command.model.ts b/src/domain/models/external-initial-import-project-command.model.ts new file mode 100644 index 0000000..c63ae43 --- /dev/null +++ b/src/domain/models/external-initial-import-project-command.model.ts @@ -0,0 +1,105 @@ +import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; +import { assertExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; +import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; +import type { ExternalModelConfigurationSnapshot } from "./external-model-configuration-project-command.model.js"; +import type { SerializedProjectCommand } from "./project-command.model.js"; + +export const externalInitialImportCommandType = "external-model.apply-initial-import" as const; +export const externalInitialImportCommandSchemaVersion = 1 as const; + +export interface ExternalInitialImportPayload { + expectedConfiguration: ExternalModelConfigurationSnapshot | null; + targetConfiguration: ExternalModelConfigurationSnapshot | null; + expectedState: ExternalModelStateSnapshot; + targetState: ExternalModelStateSnapshot; +} + +export interface ExternalInitialImportProjectCommand extends SerializedProjectCommand { + schemaVersion: typeof externalInitialImportCommandSchemaVersion; + type: typeof externalInitialImportCommandType; +} + +export function createExternalInitialImportProjectCommand( + expectedConfiguration: ExternalModelConfigurationSnapshot | null, + targetConfiguration: ExternalModelConfigurationSnapshot | null, + expectedState: ExternalModelStateSnapshot, + targetState: ExternalModelStateSnapshot +): ExternalInitialImportProjectCommand { + const command: ExternalInitialImportProjectCommand = { + schemaVersion: externalInitialImportCommandSchemaVersion, + type: externalInitialImportCommandType, + payload: { expectedConfiguration, targetConfiguration, expectedState, targetState }, + }; + assertExternalInitialImportProjectCommand(command); + return command; +} + +export function assertExternalInitialImportProjectCommand( + command: SerializedProjectCommand +): asserts command is ExternalInitialImportProjectCommand { + if (command.schemaVersion !== 1 || command.type !== externalInitialImportCommandType || !isRecord(command.payload)) { + throw new Error("Nicht unterstützter Revit-Erstimport-Command."); + } + const keys = Object.keys(command.payload).sort().join(","); + if (keys !== "expectedConfiguration,expectedState,targetConfiguration,targetState") { + throw new Error("Der Revit-Erstimport-Command ist unvollständig."); + } + assertConfigurationSnapshot(command.payload.expectedConfiguration); + assertConfigurationSnapshot(command.payload.targetConfiguration); + const expected = parseExternalModelStateSnapshot(command.payload.expectedState); + const target = parseExternalModelStateSnapshot(command.payload.targetState); + if (isEmptyExternalModelState(expected) === isEmptyExternalModelState(target)) { + throw new Error("Der Erstimport muss zwischen leerem und gefülltem Modellzustand wechseln."); + } + assertPopulatedInitialState(isEmptyExternalModelState(expected) ? target : expected); +} + +export function createEmptyExternalModelState(): ExternalModelStateSnapshot { + return { source: null, importBatches: [], roomMappings: [], objects: [] }; +} + +export function isEmptyExternalModelState(state: ExternalModelStateSnapshot) { + return state.source === null && state.importBatches.length === 0 && state.roomMappings.length === 0 && state.objects.length === 0; +} + +function assertConfigurationSnapshot(value: unknown): asserts value is ExternalModelConfigurationSnapshot | null { + if (value === null) return; + if (!isRecord(value) || typeof value.id !== "string" || typeof value.projectId !== "string") { + throw new Error("Ungültiger Konfigurationszustand im Revit-Erstimport."); + } + assertExternalModelConfiguration(value.configuration); +} + +function assertPopulatedInitialState(state: ExternalModelStateSnapshot) { + if (!state.source || state.source.sourceType !== "revit_xlsx" || state.importBatches.length !== 1 || state.objects.length === 0) { + throw new Error("Der Erstimport benötigt eine Quelle, einen Batch und mindestens ein Objekt."); + } + const source = state.source; + const batch = state.importBatches[0]; + if (batch.importKind !== "initial" || batch.projectId !== source.projectId || batch.sourceId !== source.id || batch.configurationSnapshot === null || batch.originalContentBase64 === null || batch.document === null || batch.objectCount !== state.objects.length) { + throw new Error("Der Erstimport-Batch ist unvollständig."); + } + const mappingIds = uniqueIds(state.roomMappings); + const roomKeys = new Set(); + for (const mapping of state.roomMappings) { + if (mapping.projectId !== source.projectId || mapping.sourceId !== source.id || roomKeys.has(mapping.normalizedSourceRoomKey)) throw new Error("Ungültige oder doppelte Quellraumzuordnung."); + roomKeys.add(mapping.normalizedSourceRoomKey); + } + uniqueIds(state.objects); + const worksharingIds = new Set(); + for (const object of state.objects) { + if (object.projectId !== source.projectId || object.sourceId !== source.id || object.lastSeenImportBatchId !== batch.id || object.lastAcceptedImportBatchId !== batch.id) throw new Error("Ungültige Objektidentität im Erstimport."); + if (worksharingIds.has(object.worksharingId)) throw new Error("Doppelte Worksharing-ID im Erstimport."); + worksharingIds.add(object.worksharingId); + if (object.externalRoomMappingId !== null && !mappingIds.has(object.externalRoomMappingId)) throw new Error("Ungültige Quellraumzuordnung am Revit-Objekt."); + if (object.circuitDeviceRowId !== null) throw new Error("Der Erstimport darf keine Gerätezeile zuordnen."); + if (object.presenceStatus !== "present") throw new Error("Erstimportobjekte müssen vorhanden sein."); + } +} + +function uniqueIds(entries: ReadonlyArray<{ id: string }>) { + const ids = new Set(); + for (const entry of entries) { if (ids.has(entry.id)) throw new Error("Doppelte ID im Revit-Erstimport."); ids.add(entry.id); } + return ids; +} +function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } diff --git a/src/domain/ports/external-initial-import-project-command.store.ts b/src/domain/ports/external-initial-import-project-command.store.ts new file mode 100644 index 0000000..411d3c3 --- /dev/null +++ b/src/domain/ports/external-initial-import-project-command.store.ts @@ -0,0 +1,15 @@ +import type { ExternalInitialImportProjectCommand } from "../models/external-initial-import-project-command.model.js"; +import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; + +export interface ExecuteExternalInitialImportCommandInput { + projectId: string; + expectedRevision: number; + source: ProjectRevisionSource; + description?: string; + actorId?: string; + historyTargetChangeSetId?: string; + command: ExternalInitialImportProjectCommand; +} +export interface ExternalInitialImportProjectCommandStore { + execute(input: ExecuteExternalInitialImportCommandInput): { revision: AppendedProjectRevision; inverse: ExternalInitialImportProjectCommand }; +} diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index 603a4be..8e4bf36 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -177,6 +177,11 @@ import { externalModelConfigurationUpdateCommandType, } from "../models/external-model-configuration-project-command.model.js"; import type { ExternalModelConfigurationProjectCommandStore } from "../ports/external-model-configuration-project-command.store.js"; +import { + assertExternalInitialImportProjectCommand, + externalInitialImportCommandType, +} from "../models/external-initial-import-project-command.model.js"; +import type { ExternalInitialImportProjectCommandStore } from "../ports/external-initial-import-project-command.store.js"; import { assertExternalObjectRowAssignmentProjectCommand, externalObjectRowAssignmentCommandType, @@ -242,7 +247,8 @@ export class ProjectCommandService implements ProjectCommandExecutor { private readonly externalObjectRowAssignmentStore?: ExternalObjectRowAssignmentProjectCommandStore, private readonly externalObjectNewRowStore?: ExternalObjectNewRowProjectCommandStore, private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore, - private readonly estimateBalanceStore?: EstimateBalanceProjectCommandStore + private readonly estimateBalanceStore?: EstimateBalanceProjectCommandStore, + private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore ) {} executeUser( @@ -631,6 +637,16 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } + case externalInitialImportCommandType: { + assertExternalInitialImportProjectCommand(input.command); + if (!this.externalInitialImportStore) { + throw new Error("External initial import store is not available."); + } + return this.externalInitialImportStore.execute({ + ...input, + command: input.command, + }).revision; + } case externalObjectRowAssignmentCommandType: { assertExternalObjectRowAssignmentProjectCommand(input.command); if (!this.externalObjectRowAssignmentStore) { diff --git a/src/external-model/application/external-xlsx-initial-import-target.ts b/src/external-model/application/external-xlsx-initial-import-target.ts new file mode 100644 index 0000000..8a7fd27 --- /dev/null +++ b/src/external-model/application/external-xlsx-initial-import-target.ts @@ -0,0 +1,62 @@ +import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; +import type { ExternalModelStateSnapshot } from "../domain/external-model-contracts.js"; +import type { ExternalXlsxDocument } from "../xlsx/external-xlsx-contracts.js"; +import type { ExternalInitialImportPlan } from "./external-xlsx-initial-import.js"; + +export interface ExternalRoomDecision { sourceRoomKey: string; roomId: string | null; defaultDistributionBoardId: string | null; } +export interface ExternalFamilyProjectDeviceDecision { familyAndType: string; projectDeviceId: string | null; } + +export function buildExternalXlsxInitialImportTarget(input: { + projectId: string; + expectedRevision: number; + sourceName: string; + importedAtIso: string; + configuration: ExternalModelConfiguration; + originalContentBase64: string; + document: ExternalXlsxDocument; + plan: ExternalInitialImportPlan; + roomDecisions: ExternalRoomDecision[]; + familyProjectDeviceDecisions: ExternalFamilyProjectDeviceDecision[]; + objectsWithoutRoomDefaultDistributionBoardId: string | null; + createId: () => string; +}): ExternalModelStateSnapshot { + if (input.plan.familyGroups.some((group) => !group.classified) || input.plan.issueCounts.invalidQuantity > 0) { + throw new Error("Alle Familien müssen klassifiziert sein und gültige Mengen besitzen."); + } + const roomDecisions = exactDecisionMap(input.plan.sourceRooms.map((room) => room.sourceRoomKey), input.roomDecisions, (decision) => decision.sourceRoomKey, "Quellraum"); + const familyDecisions = exactDecisionMap(input.plan.familyGroups.map((group) => group.familyAndType), input.familyProjectDeviceDecisions, (decision) => decision.familyAndType, "Familie und Typ"); + const sourceId = input.createId(); + const batchId = input.createId(); + const mappingIds = new Map(input.plan.sourceRooms.map((room) => [room.sourceRoomKey, input.createId()])); + const mappings = input.plan.sourceRooms.map((room) => { + const decision = roomDecisions.get(room.sourceRoomKey)!; + return { id: mappingIds.get(room.sourceRoomKey)!, projectId: input.projectId, sourceId, normalizedSourceRoomKey: room.sourceRoomKey, sourceFloorName: null, sourceRoomNumber: room.roomNumber, sourceRoomName: room.roomName, roomId: decision.roomId, defaultDistributionBoardId: decision.defaultDistributionBoardId }; + }); + const mappingByKey = new Map(mappings.map((mapping) => [mapping.normalizedSourceRoomKey, mapping])); + const objects = input.plan.objects.map((object) => { + const roomMapping = object.sourceRoomKey === null ? null : mappingByKey.get(object.sourceRoomKey)!; + const rule = input.configuration.familyTypeRules.find((candidate) => candidate.exactFamilyAndType === object.sourceValues.familyAndType)!; + return { + id: input.createId(), projectId: input.projectId, sourceId, worksharingId: object.worksharingId, ifcGuid: object.ifcGuid, + deviceTypeId: rule.deviceTypeId, lastSeenImportBatchId: batchId, lastAcceptedImportBatchId: batchId, + acceptedSourceValues: object.sourceValues, planningValues: object.suggestedPlanningValues, overriddenFields: [], + externalRoomMappingId: roomMapping?.id ?? null, + distributionBoardId: roomMapping?.defaultDistributionBoardId ?? input.objectsWithoutRoomDefaultDistributionBoardId, + linkedProjectDeviceId: familyDecisions.get(object.sourceValues.familyAndType)!.projectDeviceId, + circuitDeviceRowId: null, presenceStatus: "present" as const, + }; + }); + return { + source: { id: sourceId, projectId: input.projectId, name: input.sourceName.trim(), sourceType: "revit_xlsx" }, + importBatches: [{ id: batchId, projectId: input.projectId, sourceId, importKind: "initial", importedAtIso: input.importedAtIso, fileName: input.plan.fileName, sha256: input.plan.sha256, objectCount: objects.length, appliedProjectRevision: input.expectedRevision + 1, configurationSnapshot: input.configuration, originalContentBase64: input.originalContentBase64, document: input.document }], + roomMappings: mappings, + objects, + }; +} + +function exactDecisionMap(expectedKeys: string[], decisions: T[], keyOf: (decision: T) => string, label: string) { + const expected = new Set(expectedKeys); const result = new Map(); + for (const decision of decisions) { const key = keyOf(decision); if (!expected.has(key) || result.has(key)) throw new Error(`${label}-Entscheidungen sind unvollständig oder doppelt.`); result.set(key, decision); } + if (result.size !== expected.size) throw new Error(`${label}-Entscheidungen sind unvollständig oder doppelt.`); + return result; +} diff --git a/src/external-model/application/external-xlsx-initial-import.ts b/src/external-model/application/external-xlsx-initial-import.ts new file mode 100644 index 0000000..f89403c --- /dev/null +++ b/src/external-model/application/external-xlsx-initial-import.ts @@ -0,0 +1,246 @@ +import { createHash } from "node:crypto"; +import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; +import type { + ExternalModelObjectPlanningValues, + ExternalModelObjectSourceValues, +} from "../domain/external-model-contracts.js"; +import type { + ExternalXlsxDocument, + ExternalXlsxRow, + ExternalXlsxScalar, +} from "../xlsx/external-xlsx-contracts.js"; +import { parseExternalXlsx } from "../xlsx/external-xlsx-transport.js"; + +export interface ExternalInitialImportCatalogs { + floors: Array<{ id: string; name: string; sortOrder: number }>; + rooms: Array<{ id: string; floorId: string | null; roomNumber: string; roomName: string }>; + distributionBoards: Array<{ id: string; name: string; floorId: string | null }>; + projectDevices: Array<{ + id: string; + name: string; + displayName: string; + category: string | null; + connectionKind: string | null; + powerPerUnit: number; + }>; +} + +export interface ExternalInitialImportProjectedObject { + worksharingId: string; + ifcGuid: string | null; + sourceRoomKey: string | null; + sourceValues: ExternalModelObjectSourceValues; + suggestedPlanningValues: ExternalModelObjectPlanningValues; + issues: string[]; +} + +export interface ExternalInitialImportPlan { + fileName: string; + sha256: string; + byteLength: number; + rowCount: number; + objectCount: number; + passthroughCount: number; + suspectObjectCount: number; + suspectRowNumbers: number[]; + warnings: string[]; + sourceRooms: Array<{ + sourceRoomKey: string; + roomNumber: string; + roomName: string; + objectCount: number; + suggestedRoomId: string | null; + matchStatus: "exact-number" | "ambiguous-number" | "new"; + candidateRoomIds: string[]; + }>; + familyGroups: Array<{ + familyAndType: string; + objectCount: number; + classified: boolean; + deviceTypeId: string | null; + deviceTypeName: string | null; + quantityRule: "one" | "socketCount" | null; + }>; + issueCounts: { + unknownFamilyAndType: number; + invalidPower: number; + invalidQuantity: number; + missingRoom: number; + }; + objects: ExternalInitialImportProjectedObject[]; + existing: ExternalInitialImportCatalogs; +} + +export async function createExternalXlsxInitialImportPlan(input: { + fileName: string; + bytes: Uint8Array; + configuration: ExternalModelConfiguration; + catalogs: ExternalInitialImportCatalogs; +}): Promise<{ plan: ExternalInitialImportPlan; document: ExternalXlsxDocument }> { + const document = await parseExternalXlsx(input); + const columns = resolveColumns(document, input.configuration); + const rules = new Map(input.configuration.familyTypeRules.map((rule) => [rule.exactFamilyAndType, rule])); + const deviceTypes = new Map(input.configuration.deviceTypes.map((type) => [type.id, type])); + const objects = document.rows + .filter((row) => row.classification === "object") + .map((row) => projectObject(row, columns, rules, deviceTypes)); + + const roomCandidates = new Map(); + for (const room of input.catalogs.rooms) { + const key = normalizeRoomPart(room.roomNumber); + if (!key) continue; + const entries = roomCandidates.get(key) ?? []; + entries.push(room); + roomCandidates.set(key, entries); + } + const sourceRoomMap = new Map(); + for (const object of objects) { + if (object.sourceRoomKey === null) continue; + const existing = sourceRoomMap.get(object.sourceRoomKey); + if (existing) existing.objectCount += 1; + else sourceRoomMap.set(object.sourceRoomKey, { + sourceRoomKey: object.sourceRoomKey, + roomNumber: scalarText(object.sourceValues.roomNumber), + roomName: scalarText(object.sourceValues.roomName), + objectCount: 1, + }); + } + const sourceRooms = [...sourceRoomMap.values()].map((room) => { + const candidates = roomCandidates.get(normalizeRoomPart(room.roomNumber)) ?? []; + return { + ...room, + suggestedRoomId: candidates.length === 1 ? candidates[0].id : null, + matchStatus: candidates.length === 1 ? "exact-number" as const : candidates.length > 1 ? "ambiguous-number" as const : "new" as const, + candidateRoomIds: candidates.map((candidate) => candidate.id), + }; + }).sort((a, b) => a.roomNumber.localeCompare(b.roomNumber, "de", { numeric: true }) || a.roomName.localeCompare(b.roomName, "de")); + + const familyMap = new Map(); + for (const object of objects) { + const name = object.sourceValues.familyAndType; + const existing = familyMap.get(name); + if (existing) { existing.objectCount += 1; continue; } + const rule = rules.get(name); + const type = rule ? deviceTypes.get(rule.deviceTypeId) : undefined; + familyMap.set(name, { + familyAndType: name, + objectCount: 1, + classified: Boolean(rule && type), + deviceTypeId: type?.id ?? null, + deviceTypeName: type?.name ?? null, + quantityRule: rule?.quantityRule ?? null, + }); + } + const countIssue = (issue: string) => objects.filter((object) => object.issues.includes(issue)).length; + return { + document, + plan: { + fileName: input.fileName, + sha256: createHash("sha256").update(input.bytes).digest("hex"), + byteLength: input.bytes.byteLength, + rowCount: document.rows.length, + objectCount: objects.length, + passthroughCount: document.rows.filter((row) => row.classification === "passthrough").length, + suspectObjectCount: document.rows.filter((row) => row.classification === "suspect-object").length, + suspectRowNumbers: document.rows.filter((row) => row.classification === "suspect-object").map((row) => row.rowNumber), + warnings: document.issues.map((issue) => issue.message), + sourceRooms, + familyGroups: [...familyMap.values()].sort((a, b) => a.familyAndType.localeCompare(b.familyAndType, "de")), + issueCounts: { + unknownFamilyAndType: countIssue("unknown-family-and-type"), + invalidPower: countIssue("invalid-power"), + invalidQuantity: countIssue("invalid-quantity"), + missingRoom: countIssue("missing-room"), + }, + objects, + existing: input.catalogs, + }, + }; +} + +function resolveColumns(document: ExternalXlsxDocument, configuration: ExternalModelConfiguration) { + const byHeader = new Map(document.columns.map((column) => [column.header, column.columnNumber])); + return Object.fromEntries(Object.entries(configuration.columns).map(([key, header]) => [key, header === null ? null : byHeader.get(header) ?? null])) as Record; +} + +function projectObject( + row: ExternalXlsxRow, + columns: Record, + rules: Map, + deviceTypes: Map +): ExternalInitialImportProjectedObject { + const value = (key: keyof typeof columns): ExternalXlsxScalar => { + const column = columns[key]; + return column === null ? null : row.cells[column - 1]?.value ?? null; + }; + const worksharingId = scalarText(value("worksharingId")); + const familyAndType = scalarText(value("familyAndType")); + const roomNumber = value("roomNumber"); + const roomName = value("roomName"); + const rule = rules.get(familyAndType); + const deviceType = rule ? deviceTypes.get(rule.deviceTypeId) : undefined; + const issues: string[] = []; + if (!rule || !deviceType) issues.push("unknown-family-and-type"); + const sourcePower = nullableNumber(value("electricalPowerW")); + if (value("electricalPowerW") !== null && sourcePower === null) issues.push("invalid-power"); + let quantity = 1; + if (rule?.quantityRule === "socketCount") { + const parsed = nullableNumber(value("socketCount")); + if (parsed === null || !Number.isSafeInteger(parsed) || parsed < 1) issues.push("invalid-quantity"); + else quantity = parsed; + } + const sourceRoomKey = createExternalRoomKey(roomNumber, roomName); + if (sourceRoomKey === null) issues.push("missing-room"); + const selectionMarker = value("selectionMarker"); + const designation = value("designation"); + const displayName = scalarText(designation) || scalarText(selectionMarker) || familyAndType || null; + return { + worksharingId, + ifcGuid: scalarText(value("ifcGuid")) || null, + sourceRoomKey, + sourceValues: { + rowNumber: row.rowNumber, + roomNumber, + roomName, + familyAndType, + selectionMarker, + socketCount: value("socketCount"), + sourceRemark: value("sourceRemark"), + circuitCombined: value("circuitCombined"), + boardName: value("boardName"), + circuitIdentifier: value("circuitIdentifier"), + designation, + electricalPowerW: value("electricalPowerW"), + voltageV: value("voltageV"), + currentA: value("currentA"), + }, + suggestedPlanningValues: { + displayName, + category: deviceType?.category ?? null, + connectionKind: null, + effectiveQuantity: quantity, + powerPerUnitW: sourcePower ?? deviceType?.defaults.powerPerUnitW ?? null, + simultaneityFactor: deviceType?.defaults.simultaneityFactor ?? 1, + cosPhi: deviceType?.defaults.cosPhi ?? null, + costGroup: deviceType?.defaults.costGroup ?? null, + remark: scalarText(value("sourceRemark")) || null, + }, + issues, + }; +} + +export function createExternalRoomKey(roomNumber: ExternalXlsxScalar, roomName: ExternalXlsxScalar) { + const number = normalizeRoomPart(scalarText(roomNumber)); + const name = normalizeRoomPart(scalarText(roomName)); + return number || name ? `${number}\u0000${name}` : null; +} + +function normalizeRoomPart(value: string) { return value.trim().toLocaleLowerCase("de-DE"); } +function scalarText(value: ExternalXlsxScalar) { return value === null ? "" : String(value).trim(); } +function nullableNumber(value: ExternalXlsxScalar) { + if (typeof value === "number") return Number.isFinite(value) ? value : null; + if (typeof value !== "string" || !value.trim()) return null; + const normalized = value.trim().replace(/\s/g, "").replace(/,(?=\d+$)/, "."); + const parsed = Number(normalized); + return Number.isFinite(parsed) ? parsed : null; +} diff --git a/src/frontend/components/revit-initial-import-wizard.tsx b/src/frontend/components/revit-initial-import-wizard.tsx new file mode 100644 index 0000000..8a4fc4d --- /dev/null +++ b/src/frontend/components/revit-initial-import-wizard.tsx @@ -0,0 +1,106 @@ +"use client"; + +import { useState, type FormEvent } from "react"; +import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; +import type { ExternalInitialImportPlanDto, ProjectHistoryStateDto } from "../types"; +import { applyExternalInitialImport, planExternalInitialImport } from "../utils/api"; +import { createClientId } from "../utils/client-id"; +import { FormModal } from "./form-modal"; + +const steps = ["Vorschau", "Räume", "Verteiler", "Familienregeln", "Projektgeräte", "Bestätigung"]; + +export function RevitInitialImportWizard({ projectId, expectedRevision, initialConfiguration, onClose, onImported }: { + projectId: string; + expectedRevision: number; + initialConfiguration: ExternalModelConfiguration; + onClose: () => void; + onImported: (result: { history: ProjectHistoryStateDto; objectCount: number }) => void; +}) { + const [step, setStep] = useState(0); + const [file, setFile] = useState(null); + const [configuration, setConfiguration] = useState(() => structuredClone(initialConfiguration)); + const [plan, setPlan] = useState(null); + const [roomIds, setRoomIds] = useState>( {} ); + const [boardIds, setBoardIds] = useState>( {} ); + const [deviceIds, setDeviceIds] = useState>( {} ); + const [sourceName, setSourceName] = useState("Revit-Gesamtmodell"); + const [noRoomBoardId, setNoRoomBoardId] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function loadPlan(nextFile: File, nextConfiguration = configuration) { + setBusy(true); setError(null); + try { + const loaded = await planExternalInitialImport(projectId, nextFile, nextConfiguration, expectedRevision); + setPlan(loaded); + setRoomIds((current) => Object.fromEntries(loaded.sourceRooms.map((room) => [room.sourceRoomKey, current[room.sourceRoomKey] ?? room.suggestedRoomId ?? ""]))); + setBoardIds((current) => Object.fromEntries(loaded.sourceRooms.map((room) => [room.sourceRoomKey, current[room.sourceRoomKey] ?? ""]))); + setDeviceIds((current) => Object.fromEntries(loaded.familyGroups.map((family) => [family.familyAndType, current[family.familyAndType] ?? ""]))); + } catch (value) { setError(value instanceof Error ? value.message : "XLSX-Vorschau fehlgeschlagen."); setPlan(null); } + finally { setBusy(false); } + } + + async function classifyFamily(familyAndType: string, category: "lighting" | "single_phase" | "three_phase", quantityRule: "one" | "socketCount") { + if (!file) return; + const deviceTypeId = createClientId(); + const next = structuredClone(configuration); + next.deviceTypes.push({ id: deviceTypeId, name: familyAndType, category, defaults: { powerPerUnitW: null, simultaneityFactor: 1, cosPhi: null, costGroup: null } }); + next.familyTypeRules.push({ id: createClientId(), exactFamilyAndType: familyAndType, deviceTypeId, quantityRule }); + setConfiguration(next); + await loadPlan(file, next); + } + + async function assignExistingDeviceType(familyAndType: string, encoded: string) { + if (!file || !encoded) return; + const separator = encoded.lastIndexOf("|"); + const deviceTypeId = encoded.slice(0, separator); + const quantityRule = encoded.slice(separator + 1) as "one" | "socketCount"; + const next = structuredClone(configuration); + next.familyTypeRules.push({ id: createClientId(), exactFamilyAndType: familyAndType, deviceTypeId, quantityRule }); + setConfiguration(next); + await loadPlan(file, next); + } + + async function toggleQuantityRule(familyAndType: string) { + if (!file) return; + const next = structuredClone(configuration); + const rule = next.familyTypeRules.find((candidate) => candidate.exactFamilyAndType === familyAndType); + if (!rule) return; + rule.quantityRule = rule.quantityRule === "one" ? "socketCount" : "one"; + setConfiguration(next); + await loadPlan(file, next); + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (step < steps.length - 1) { setStep(step + 1); return; } + if (!file || !plan) return; + setBusy(true); setError(null); + try { + const result = await applyExternalInitialImport(projectId, file, { + expectedRevision, + expectedSha256: plan.sha256, + sourceName, + configuration, + objectsWithoutRoomDefaultDistributionBoardId: noRoomBoardId || null, + roomDecisions: plan.sourceRooms.map((room) => ({ sourceRoomKey: room.sourceRoomKey, roomId: roomIds[room.sourceRoomKey] || null, defaultDistributionBoardId: boardIds[room.sourceRoomKey] || null })), + familyProjectDeviceDecisions: plan.familyGroups.map((family) => ({ familyAndType: family.familyAndType, projectDeviceId: deviceIds[family.familyAndType] || null })), + }); + onImported({ history: result.history, objectCount: result.import.objectCount }); + } catch (value) { setError(value instanceof Error ? value.message : "Erstimport fehlgeschlagen."); } + finally { setBusy(false); } + } + + const blocked = !plan || (step >= 3 && (plan.issueCounts.unknownFamilyAndType > 0 || plan.issueCounts.invalidQuantity > 0)); + return void submit(event)} submitDisabled={blocked} submitLabel={step === steps.length - 1 ? "Erstimport übernehmen" : "Weiter"}> +
{steps.map((label, index) => {index + 1}. {label})}
+ {error ?
{error}
: null} + {step === 0 ?
{ const selected = event.target.files?.[0] ?? null; setFile(selected); if (selected) void loadPlan(selected); }} />
{plan ? <>
{plan.objectCount}
Objekte
{plan.sourceRooms.length}
Quellräume
{plan.familyGroups.length}
Familien
{plan.suspectObjectCount}
übersprungene verdächtige Zeilen
Unbekannte Familien: {plan.issueCounts.unknownFamilyAndType} · Ungültige Leistungen: {plan.issueCounts.invalidPower} · Ungültige Mengen: {plan.issueCounts.invalidQuantity} · Objekte ohne Raum: {plan.issueCounts.missingRoom}
{plan.warnings.length ?
{plan.warnings.map((warning) =>
{warning}
)}
: null} : null}
: null} + {step === 1 && plan ?

Quellräume vorhandenen Projekträumen zuordnen. Neue Räume können vorher in der Gebäudestruktur angelegt werden.

{plan.sourceRooms.map((room) =>
{room.roomNumber || "–"} {room.roomName} {room.objectCount}
)}
: null} + {step === 2 && plan ?

Der Standardverteiler gilt beim Import nur für unzugeordnete Objekte.

{plan.sourceRooms.map((room) =>
{room.roomNumber || "–"} · {room.roomName}
)}{plan.issueCounts.missingRoom > 0 ?
Objekte ohne Quellraum {plan.issueCounts.missingRoom}
: null}
: null} + {step === 3 && plan ?

Exakte Familie-und-Typ-Werte werden einer Geräteart und Mengenregel zugeordnet. Ein fehlender GZF startet sichtbar mit 1.

{plan.familyGroups.map((family) =>
{family.familyAndType} {family.objectCount}
{family.classified ? `${family.deviceTypeName} · ${family.quantityRule === "socketCount" ? "Anzahl aus XLSX" : "Menge 1"} · GZF 1, falls nicht gepflegt` : "Noch nicht klassifiziert"}
{family.classified ? :
{configuration.deviceTypes.length ? : null}
}
)}
: null} + {step === 4 && plan ?

Optional kann jede Familie mit einem vorhandenen Projektgerät verknüpft werden.

{plan.familyGroups.map((family) =>
{family.familyAndType}
)}
: null} + {step === 5 && plan ?
setSourceName(event.target.value)} />
{plan.objectCount} Revit-Objekte werden importiert. Es werden keine Gerätezeilen, Stromkreise oder BMKs erzeugt. Die Datei wird beim Übernehmen erneut übertragen und geprüft.
: null} + {step > 0 ? : null} +
; +} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 401b618..9a18a94 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -10,10 +10,6 @@ import type { ProtectionDeviceType, RcdType, } from "../shared/constants/protection-device"; -import type { - ExternalCsvConfiguration, - ExternalCsvDialect, -} from "../external-model/csv/external-csv-contracts"; import type { ExternalModelConfiguration } from "../external-model/configuration/external-model-configuration"; export interface ExternalModelConfigurationSnapshotDto { @@ -22,44 +18,7 @@ export interface ExternalModelConfigurationSnapshotDto { configuration: ExternalModelConfiguration; } -export interface ExternalCsvConfigurationSnapshotDto { - id: string; - projectId: string; - configurationVersion: number; - configuration: ExternalCsvConfiguration; -} - -export interface ExternalCsvPreviewObjectDto { - rowNumber: number; - ifcGuid: string; - roomNumber: string; - roomName: string; - familyAndType: string; - selectionMarker: string; - circuitIdentifier: string; - power: string; - quantity: string | null; - additionalSourceValues: Record; -} - -export interface ExternalCsvPreviewDto { - fileName: string; - byteLength: number; - sha256: string; - dialect: ExternalCsvDialect; - headerRowNumber: number; - headerColumns: string[]; - rowCount: number; - objectCount: number; - passthroughCount: number; - nonEmptyPassthroughCount: number; - suspectObjectCount: number; - objects: ExternalCsvPreviewObjectDto[]; - suspectRowNumbers: number[]; -} - export interface ExternalInitialImportPlanDto { - configurationVersion: number; fileName: string; sha256: string; byteLength: number; @@ -68,6 +27,7 @@ export interface ExternalInitialImportPlanDto { passthroughCount: number; suspectObjectCount: number; suspectRowNumbers: number[]; + warnings: string[]; sourceRooms: Array<{ sourceRoomKey: string; roomNumber: string; @@ -81,9 +41,9 @@ export interface ExternalInitialImportPlanDto { familyAndType: string; objectCount: number; classified: boolean; - category: string | null; - connectionKind: string | null; - internalDeviceType: string | null; + deviceTypeId: string | null; + deviceTypeName: string | null; + quantityRule: "one" | "socketCount" | null; }>; issueCounts: { unknownFamilyAndType: number; @@ -91,24 +51,7 @@ export interface ExternalInitialImportPlanDto { invalidQuantity: number; missingRoom: number; }; - objects: Array<{ - ifcGuid: string; - sourceRoomKey: string | null; - sourceValues: ExternalCsvPreviewObjectDto; - suggestedPlanningValues: { - displayName: string | null; - internalDeviceType: string | null; - category: CircuitGroupCategory | null; - connectionKind: string | null; - effectiveQuantity: number; - powerPerUnitW: number | null; - simultaneityFactor: number; - cosPhi: number | null; - costGroup: string | null; - remark: string | null; - }; - issues: string[]; - }>; + objects: Array<{ worksharingId: string; ifcGuid: string | null; sourceRoomKey: string | null; sourceValues: { familyAndType: string }; suggestedPlanningValues: { simultaneityFactor: number; effectiveQuantity: number }; issues: string[] }>; existing: { floors: Array<{ id: string; name: string; sortOrder: number }>; rooms: Array<{ @@ -135,11 +78,12 @@ export interface ExternalInitialImportPlanDto { export interface ApplyExternalInitialImportInput { expectedRevision: number; - expectedConfigurationVersion: number; expectedSha256: string; fileName: string; contentBase64: string; sourceName: string; + configuration: ExternalModelConfiguration; + objectsWithoutRoomDefaultDistributionBoardId: string | null; roomDecisions: Array<{ sourceRoomKey: string; roomId: string | null; @@ -151,6 +95,14 @@ export interface ApplyExternalInitialImportInput { }>; } +export interface ExternalInitialImportStatusDto { + imported: boolean; + sourceName: string | null; + objectCount: number; + importedAtIso: string | null; + fileName: string | null; +} + export interface ExternalInitialImportResultDto extends ProjectCommandResultDto { import: { sourceId: string; diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index 3694c2e..692640d 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -39,6 +39,10 @@ import type { CircuitTreeResponseDto, ProjectCircuitTreesResponseDto, ExternalModelConfigurationSnapshotDto, + ExternalInitialImportPlanDto, + ExternalInitialImportResultDto, + ExternalInitialImportStatusDto, + ApplyExternalInitialImportInput, CreateEstimateBalanceInput, EstimateBalanceCommandResultDto, EstimateBalanceDto, @@ -198,6 +202,40 @@ export async function detectExternalModelWorkbook( ); } +export function getExternalInitialImportStatus(projectId: string) { + return request(`/api/projects/${projectId}/external-model/import-status`); +} + +export async function planExternalInitialImport( + projectId: string, + file: File, + configuration: ExternalModelConfiguration, + expectedRevision: number +) { + return request(`/api/projects/${projectId}/external-model/initial-import/plan`, { + method: "POST", + body: JSON.stringify({ fileName: file.name, contentBase64: await fileToBase64(file), configuration, expectedRevision }), + }); +} + +export async function applyExternalInitialImport( + projectId: string, + file: File, + input: Omit +) { + return request(`/api/projects/${projectId}/external-model/initial-import/apply`, { + method: "POST", + body: JSON.stringify({ ...input, fileName: file.name, contentBase64: await fileToBase64(file) }), + }); +} + +async function fileToBase64(file: File) { + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary); +} + export function getProjectHistory(projectId: string) { return request( `/api/projects/${projectId}/history` diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index 6a191cb..4d6003a 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -64,6 +64,7 @@ const commandTypeLabels: Record = { "external-csv-configuration.update": "Revit-CSV-Konfiguration bearbeitet", "external-model-configuration.update": "Revit-XLSX-Einstellungen bearbeitet", "external-import.apply-initial": "Revit-Erstimport übernommen", + "external-model.apply-initial-import": "Linear-XLSX-Erstimport übernommen", "external-object.assign-to-new-circuit": "Externes Objekt in neuen Stromkreis übernommen", "external-object.unassign-and-delete-created-circuit": diff --git a/src/server/composition/project-command-stores.ts b/src/server/composition/project-command-stores.ts index 00f2d5f..4017144 100644 --- a/src/server/composition/project-command-stores.ts +++ b/src/server/composition/project-command-stores.ts @@ -23,6 +23,7 @@ import { ProjectSettingsProjectCommandRepository } from "../../db/repositories/p import { ProjectStateRestoreCommandRepository } from "../../db/repositories/project-state-restore-command.repository.js"; import { ProjectCommandService } from "../../domain/services/project-command.service.js"; import { ExternalModelConfigurationProjectCommandRepository } from "../../db/repositories/external-model-configuration-project-command.repository.js"; +import { ExternalInitialImportProjectCommandRepository } from "../../db/repositories/external-initial-import-project-command.repository.js"; import { ExternalObjectRowAssignmentProjectCommandRepository } from "../../db/repositories/external-object-row-assignment-project-command.repository.js"; import { ExternalObjectNewRowProjectCommandRepository } from "../../db/repositories/external-object-new-row-project-command.repository.js"; import { ExternalObjectNewCircuitProjectCommandRepository } from "../../db/repositories/external-object-new-circuit-project-command.repository.js"; @@ -72,6 +73,8 @@ export const projectStateRestoreCommandStore = export const projectHistoryStore = new ProjectHistoryRepository(db); export const externalModelConfigurationProjectCommandStore = new ExternalModelConfigurationProjectCommandRepository(db); +export const externalInitialImportProjectCommandStore = + new ExternalInitialImportProjectCommandRepository(db); export const externalObjectRowAssignmentProjectCommandStore = new ExternalObjectRowAssignmentProjectCommandRepository(db); export const externalObjectNewRowProjectCommandStore = @@ -107,5 +110,6 @@ export const projectCommandService = new ProjectCommandService( externalObjectRowAssignmentProjectCommandStore, externalObjectNewRowProjectCommandStore, externalObjectNewCircuitProjectCommandStore, - estimateBalanceProjectCommandStore + estimateBalanceProjectCommandStore, + externalInitialImportProjectCommandStore ); diff --git a/src/server/controllers/external-initial-import.controller.ts b/src/server/controllers/external-initial-import.controller.ts new file mode 100644 index 0000000..53227f4 --- /dev/null +++ b/src/server/controllers/external-initial-import.controller.ts @@ -0,0 +1,68 @@ +import { randomUUID } from "node:crypto"; +import type { Request, Response } from "express"; +import { createEmptyExternalModelState, createExternalInitialImportProjectCommand } from "../../domain/models/external-initial-import-project-command.model.js"; +import { createExternalXlsxInitialImportPlan } from "../../external-model/application/external-xlsx-initial-import.js"; +import { buildExternalXlsxInitialImportTarget } from "../../external-model/application/external-xlsx-initial-import-target.js"; +import { assertExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; +import { distributionBoardRepository, externalModelConfigurationRepository, externalModelStateRepository, floorRepository, projectDeviceRepository, projectRepository, roomRepository } from "../composition/application-repositories.js"; +import { projectCommandService } from "../composition/project-command-stores.js"; +import { respondWithProjectCommandError } from "./project-command.controller.js"; + +export function getExternalInitialImportStatus(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + const result = externalModelStateRepository.getByProject(projectId); + if (!result.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + const batch = result.state.importBatches.at(-1) ?? null; + return res.json({ imported: result.state.source !== null, sourceName: result.state.source?.name ?? null, objectCount: result.state.objects.length, importedAtIso: batch?.importedAtIso ?? null, fileName: batch?.fileName ?? null }); +} + +export async function planExternalInitialImport(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + try { + const expectedRevision = req.body?.expectedRevision; + if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw new Error("Ungültige Projektrevision."); + const stored = externalModelConfigurationRepository.getByProject(projectId); + if (!stored.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + if (!stored.configuration) return res.status(409).json({ error: "Für das Projekt ist noch keine Revit-XLSX-Konfiguration gespeichert.", code: "EXTERNAL_XLSX_CONFIGURATION_REQUIRED" }); + const project = await projectRepository.findById(projectId); + if (!project || project.currentRevision !== expectedRevision) return res.status(409).json({ error: "Der Erstimportplan ist wegen einer neueren Projektrevision ungültig.", code: "PROJECT_REVISION_CONFLICT", expectedRevision, currentRevision: project?.currentRevision ?? null }); + if (externalModelStateRepository.getByProject(projectId).state.source) return res.status(409).json({ error: "Für dieses Projekt wurde bereits ein Revit-Modell importiert.", code: "EXTERNAL_INITIAL_IMPORT_ALREADY_APPLIED" }); + const configuration = req.body?.configuration ?? stored.configuration.configuration; + assertExternalModelConfiguration(configuration); + const { plan } = await createExternalXlsxInitialImportPlan({ fileName: requiredString(req.body?.fileName, "Dateiname"), bytes: decodeBase64(req.body?.contentBase64), configuration, catalogs: await loadCatalogs(projectId) }); + return res.json(plan); + } catch (error) { + return res.status(400).json({ error: error instanceof Error ? error.message : "Erstimport-Vorschau fehlgeschlagen." }); + } +} + +export async function applyExternalInitialImport(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + try { + const expectedRevision = req.body?.expectedRevision; + if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw new Error("Ungültige Projektrevision."); + const stored = externalModelConfigurationRepository.getByProject(projectId); + if (!stored.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + if (!stored.configuration) return res.status(409).json({ error: "Für das Projekt ist noch keine Revit-XLSX-Konfiguration gespeichert.", code: "EXTERNAL_XLSX_CONFIGURATION_REQUIRED" }); + if (externalModelStateRepository.getByProject(projectId).state.source) return res.status(409).json({ error: "Für dieses Projekt wurde bereits ein Revit-Modell importiert.", code: "EXTERNAL_INITIAL_IMPORT_ALREADY_APPLIED" }); + assertExternalModelConfiguration(req.body?.configuration); + const bytes = decodeBase64(req.body?.contentBase64); + const { plan, document } = await createExternalXlsxInitialImportPlan({ fileName: requiredString(req.body?.fileName, "Dateiname"), bytes, configuration: req.body.configuration, catalogs: await loadCatalogs(projectId) }); + if (plan.sha256 !== req.body?.expectedSha256) return res.status(409).json({ error: "Die XLSX-Datei stimmt nicht mehr mit der geprüften Vorschau überein.", code: "EXTERNAL_XLSX_FILE_CHANGED" }); + const target = buildExternalXlsxInitialImportTarget({ projectId, expectedRevision, sourceName: requiredString(req.body?.sourceName, "Quellenname"), importedAtIso: new Date().toISOString(), configuration: req.body.configuration, originalContentBase64: req.body.contentBase64, document, plan, roomDecisions: requireArray(req.body?.roomDecisions, "Raumentscheidungen"), familyProjectDeviceDecisions: requireArray(req.body?.familyProjectDeviceDecisions, "ProjectDevice-Entscheidungen"), objectsWithoutRoomDefaultDistributionBoardId: nullableString(req.body?.objectsWithoutRoomDefaultDistributionBoardId, "Standardverteiler ohne Raum"), createId: randomUUID }); + const targetConfiguration = { id: stored.configuration.id, projectId, configuration: req.body.configuration }; + const result = projectCommandService.executeUser({ projectId, expectedRevision, description: `Revit-Erstimport ${plan.fileName}`, command: createExternalInitialImportProjectCommand(stored.configuration, targetConfiguration, createEmptyExternalModelState(), target) }); + return res.status(201).json({ ...result, import: { sourceId: target.source!.id, importBatchId: target.importBatches[0].id, objectCount: target.objects.length } }); + } catch (error) { + return respondWithProjectCommandError(error, res); + } +} + +async function loadCatalogs(projectId: string) { + const [floors, rooms, distributionBoards, projectDevices] = await Promise.all([floorRepository.listByProject(projectId), roomRepository.listByProject(projectId), distributionBoardRepository.listByProject(projectId), projectDeviceRepository.listByProject(projectId)]); + return { floors, rooms, distributionBoards, projectDevices }; +} +function decodeBase64(value: unknown) { if (typeof value !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(value) || value.length % 4 !== 0) throw new Error("XLSX-Inhalt ist nicht gültig Base64-kodiert."); const bytes = Buffer.from(value, "base64"); if (bytes.toString("base64") !== value) throw new Error("XLSX-Inhalt ist nicht kanonisch Base64-kodiert."); return bytes; } +function requiredString(value: unknown, label: string) { if (typeof value !== "string" || !value.trim()) throw new Error(`${label} fehlt.`); return value.trim(); } +function nullableString(value: unknown, label: string) { if (value === null || value === undefined || value === "") return null; if (typeof value !== "string") throw new Error(`${label} ist ungültig.`); return value; } +function requireArray(value: unknown, label: string): T[] { if (!Array.isArray(value)) throw new Error(`${label} fehlen.`); return value as T[]; } diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index d0ca12d..84f2ea3 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -58,6 +58,11 @@ import { detectExternalModelWorkbook, updateExternalModelConfiguration, } from "../controllers/external-model-configuration.controller.js"; +import { + applyExternalInitialImport, + getExternalInitialImportStatus, + planExternalInitialImport, +} from "../controllers/external-initial-import.controller.js"; export const projectRouter = Router(); @@ -82,6 +87,9 @@ projectRouter.put("/:projectId", updateProjectSettings); projectRouter.get("/:projectId/external-model/configuration", getExternalModelConfiguration); projectRouter.put("/:projectId/external-model/configuration", updateExternalModelConfiguration); projectRouter.post("/:projectId/external-model/configuration/detect", detectExternalModelWorkbook); +projectRouter.get("/:projectId/external-model/import-status", getExternalInitialImportStatus); +projectRouter.post("/:projectId/external-model/initial-import/plan", planExternalInitialImport); +projectRouter.post("/:projectId/external-model/initial-import/apply", applyExternalInitialImport); projectRouter.get("/:projectId/distribution-boards", listDistributionBoardsByProject); projectRouter.post("/:projectId/distribution-boards", createDistributionBoard); projectRouter.post( diff --git a/tests/external-xlsx-initial-import.test.ts b/tests/external-xlsx-initial-import.test.ts new file mode 100644 index 0000000..33400d6 --- /dev/null +++ b/tests/external-xlsx-initial-import.test.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import { describe, it } from "node:test"; +import { migrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createDatabaseContext } from "../src/db/database-context.js"; +import { ExternalInitialImportProjectCommandRepository } from "../src/db/repositories/external-initial-import-project-command.repository.js"; +import { ExternalModelStateRepository } from "../src/db/repositories/external-model-state.repository.js"; +import { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; +import { projects } from "../src/db/schema/projects.js"; +import { createEmptyExternalModelState, createExternalInitialImportProjectCommand } from "../src/domain/models/external-initial-import-project-command.model.js"; +import { createExternalXlsxInitialImportPlan } from "../src/external-model/application/external-xlsx-initial-import.js"; +import { buildExternalXlsxInitialImportTarget } from "../src/external-model/application/external-xlsx-initial-import-target.js"; +import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; +import { createRevitXlsxFixture, externalXlsxTestConfiguration, firstWorksharingId } from "./fixtures/revit-xlsx-fixtures.js"; + +const deviceTypeA = "10000000-0000-4000-8000-000000000001"; +const deviceTypeB = "10000000-0000-4000-8000-000000000002"; + +function configured() { + return { + ...createDefaultExternalModelConfiguration(), + ...externalXlsxTestConfiguration, + deviceTypes: [ + { id: deviceTypeA, name: "Steckdose", category: "single_phase" as const, defaults: { powerPerUnitW: null, simultaneityFactor: null, cosPhi: 0.9, costGroup: "440" } }, + { id: deviceTypeB, name: "Leuchte", category: "lighting" as const, defaults: { powerPerUnitW: 40, simultaneityFactor: 0.8, cosPhi: null, costGroup: null } }, + ], + familyTypeRules: [ + { id: "20000000-0000-4000-8000-000000000001", exactFamilyAndType: "Steckdose: Standard", deviceTypeId: deviceTypeA, quantityRule: "socketCount" as const }, + { id: "20000000-0000-4000-8000-000000000002", exactFamilyAndType: "Leuchte: Decke", deviceTypeId: deviceTypeB, quantityRule: "one" as const }, + ], + }; +} + +describe("Linear XLSX initial import", () => { + it("plans exact families, skips suspicious rows and defaults missing GZF to one", async () => { + const { plan } = await createExternalXlsxInitialImportPlan({ fileName: "linear.xlsx", bytes: await createRevitXlsxFixture(), configuration: configured(), catalogs: { floors: [], rooms: [], distributionBoards: [], projectDevices: [] } }); + assert.equal(plan.objectCount, 2); + assert.equal(plan.suspectObjectCount, 1); + assert.equal(plan.issueCounts.unknownFamilyAndType, 0); + assert.equal(plan.objects[0].worksharingId, firstWorksharingId); + assert.equal(plan.objects[0].suggestedPlanningValues.effectiveQuantity, 2); + assert.equal(plan.objects[0].suggestedPlanningValues.simultaneityFactor, 1); + assert.equal(plan.objects[1].suggestedPlanningValues.simultaneityFactor, 0.8); + }); + + it("commits atomically and undo/redo uses stored states", async () => { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); + const configuration = configured(); + const configurationSnapshot = { id: "config-1", projectId: "project-1", configuration }; + context.db.insert(externalModelConfigurations).values(configurationSnapshot).run(); + try { + const bytes = await createRevitXlsxFixture(); + const { plan, document } = await createExternalXlsxInitialImportPlan({ fileName: "linear.xlsx", bytes, configuration, catalogs: { floors: [], rooms: [], distributionBoards: [], projectDevices: [] } }); + let sequence = 0; + const target = buildExternalXlsxInitialImportTarget({ projectId: "project-1", expectedRevision: 0, sourceName: "Revit", importedAtIso: "2026-09-30T10:00:00.000Z", configuration, originalContentBase64: Buffer.from(bytes).toString("base64"), document, plan, roomDecisions: plan.sourceRooms.map((room) => ({ sourceRoomKey: room.sourceRoomKey, roomId: null, defaultDistributionBoardId: null })), familyProjectDeviceDecisions: plan.familyGroups.map((family) => ({ familyAndType: family.familyAndType, projectDeviceId: null })), objectsWithoutRoomDefaultDistributionBoardId: null, createId: () => `30000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}` }); + const repository = new ExternalInitialImportProjectCommandRepository(context.db); + const inserted = repository.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createExternalInitialImportProjectCommand(configurationSnapshot, configurationSnapshot, createEmptyExternalModelState(), target) }); + assert.equal(inserted.revision.revisionNumber, 1); + assert.equal(new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects.length, 2); + const undone = repository.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: inserted.revision.changeSetId, command: inserted.inverse }); + assert.equal(new ExternalModelStateRepository(context.db).getByProject("project-1").state.source, null); + repository.execute({ projectId: "project-1", expectedRevision: 2, source: "redo", historyTargetChangeSetId: inserted.revision.changeSetId, command: undone.inverse }); + assert.deepEqual(new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects.map((object) => object.worksharingId), plan.objects.map((object) => object.worksharingId).sort()); + } finally { context.close(); } + }); +}); diff --git a/tests/revit-xlsx-settings-api.test.ts b/tests/revit-xlsx-settings-api.test.ts index 090e6b3..22d633c 100644 --- a/tests/revit-xlsx-settings-api.test.ts +++ b/tests/revit-xlsx-settings-api.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { describe, it } from "node:test"; import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; -import { detectExternalModelWorkbook, getExternalModelConfiguration, updateExternalModelConfiguration } from "../src/frontend/utils/api.js"; +import { applyExternalInitialImport, detectExternalModelWorkbook, getExternalInitialImportStatus, getExternalModelConfiguration, planExternalInitialImport, updateExternalModelConfiguration } from "../src/frontend/utils/api.js"; describe("Revit XLSX settings", () => { it("uses the project-scoped configuration endpoint with expectedRevision", async () => { @@ -25,14 +25,41 @@ describe("Revit XLSX settings", () => { } finally { globalThis.fetch = originalFetch; } }); + it("uses stateless preview and retransmits the workbook for apply", async () => { + const requests: Array<{ url: string; method: string; body: Record | undefined }> = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (input, init) => { + requests.push({ url: String(input), method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined }); + return new Response(JSON.stringify({ imported: false, familyGroups: [], sourceRooms: [], objects: [], warnings: [], issueCounts: {}, existing: {}, history: { currentRevision: 9 }, import: { objectCount: 2 } }), { status: 200, headers: { "Content-Type": "application/json" } }); + }; + try { + const configuration = createDefaultExternalModelConfiguration(); + const file = new File([new Uint8Array([1, 2])], "linear.xlsx"); + await getExternalInitialImportStatus("project-1"); + await planExternalInitialImport("project-1", file, configuration, 8); + await applyExternalInitialImport("project-1", file, { expectedRevision: 8, expectedSha256: "a".repeat(64), sourceName: "Revit", configuration, objectsWithoutRoomDefaultDistributionBoardId: null, roomDecisions: [], familyProjectDeviceDecisions: [] }); + assert.equal(requests[0].url, "/api/projects/project-1/external-model/import-status"); + assert.equal(requests[1].url, "/api/projects/project-1/external-model/initial-import/plan"); + assert.equal(requests[2].url, "/api/projects/project-1/external-model/initial-import/apply"); + assert.equal(requests[1].body?.contentBase64, "AQI="); + assert.equal(requests[1].body?.expectedRevision, 8); + assert.equal(requests[2].body?.contentBase64, "AQI="); + assert.equal(requests[2].body?.expectedRevision, 8); + } finally { globalThis.fetch = originalFetch; } + }); + it("exposes the Revit route and removes the old project modal", () => { const projectPage = readFileSync("src/app/projects/[projectId]/page.tsx", "utf8"); const revitPage = readFileSync("src/app/projects/[projectId]/revit/page.tsx", "utf8"); const settings = readFileSync("src/frontend/components/revit-xlsx-settings-modal.tsx", "utf8"); + const wizard = readFileSync("src/frontend/components/revit-initial-import-wizard.tsx", "utf8"); assert.match(projectPage, /href={`\/projects\/\$\{projectId\}\/revit`}/); assert.doesNotMatch(projectPage, /RevitCsvModal|Revit-CSV/); assert.match(revitPage, /Importstatus/); assert.match(settings, /Musterdatei prüfen/); assert.match(settings, /Kombinierte Stromkreisspalte/); + assert.match(wizard, /Schritt.*von/); + assert.match(wizard, /keine Gerätezeilen, Stromkreise oder BMKs/); + assert.match(wizard, /GZF 1/); }); }); From 4ac32e103da9b9c81772687002147ba1987c0d8d Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 10:03:36 +0200 Subject: [PATCH 32/38] Add virtualized Revit object planning --- AGENTS.md | 7 +- README.md | 6 +- docs/spec/revit-excel-phase-14-plan.md | 10 ++- src/app/projects/[projectId]/revit/page.tsx | 2 + ...ect-planning-project-command.repository.ts | 29 ++++++++ ...l-object-planning-project-command.model.ts | 30 ++++++++ ...l-object-planning-project-command.store.ts | 3 + .../services/project-command.service.ts | 10 ++- .../components/revit-object-table.tsx | 73 +++++++++++++++++++ src/frontend/types.ts | 15 ++++ src/frontend/utils/api.ts | 9 +++ src/frontend/utils/project-version-history.ts | 1 + .../composition/project-command-stores.ts | 6 +- .../external-objects.controller.ts | 56 ++++++++++++++ src/server/routes/project.routes.ts | 3 + tests/external-xlsx-initial-import.test.ts | 12 ++- tests/revit-xlsx-settings-api.test.ts | 14 +++- 17 files changed, 277 insertions(+), 9 deletions(-) create mode 100644 src/db/repositories/external-object-planning-project-command.repository.ts create mode 100644 src/domain/models/external-object-planning-project-command.model.ts create mode 100644 src/domain/ports/external-object-planning-project-command.store.ts create mode 100644 src/frontend/components/revit-object-table.tsx create mode 100644 src/server/controllers/external-objects.controller.ts diff --git a/AGENTS.md b/AGENTS.md index d771e59..d438bae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -339,6 +339,11 @@ external model state atomically; its inverse powers persistent Undo/Redo without parsing workbook bytes. Apply retransmits and reparses the XLSX, verifies its preview SHA-256 and creates no circuit, equipment identifier or CircuitDeviceRow. +R6 adds one compact project-wide external-object GET without pagination or +batch payloads. The Revit page filters and sorts it in the client and renders a +virtualized window. `external-object.update-planning` applies multi-object +board, ProjectDevice and planning-value changes as one persistent command; +linked objects are excluded because they follow their CircuitDeviceRow board. The target configuration has no independent version counter; `expectedRevision` invalidates stale plans, and each import batch stores a configuration copy. @@ -592,7 +597,7 @@ Critical target rules: selected combined/separate mode block export. - Missing GZF defaults visibly to 1 without separate confirmation. - The corrected R2 return workbook was successfully imported into Linear on - 2026-09-30; R3 through R5 are complete and R6 is the next package. + 2026-09-30; R3 through R6 are complete and R7 is the next package. - All confirmed writes use typed project commands with `expectedRevision`, complete inverse data and the shared project-command transaction boundary. - Do not add automatic circuit planning, Revit circuit adoption, multi-source diff --git a/README.md b/README.md index b965df8..d4aeae4 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,10 @@ für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstützte Produktionsdeployment fehlen weiterhin. Anmeldung und zwei feste Rollen sind vorhanden. Die Backend- und Persistenzgrundlage der bisherigen Revit-CSV-/IfcGUID-Anbindung ist durch den XLSX-Austausch des Linear-Plugins mit -Worksharing-ID als externem Schlüssel ersetzt. R0 bis R5 sind abgeschlossen; +Worksharing-ID als externem Schlüssel ersetzt. R0 bis R6 sind abgeschlossen; die eigene Revit-Seite besitzt XLSX-Einstellungen und einen persistenten -Erstimport. Objekttabelle, Editorzuordnung, Rückgabe und Folgeimport folgen in -R6 bis R10. +Erstimport sowie eine virtualisierte Objekttabelle mit Sammeländerungen. +Editorzuordnung, Rückgabe und Folgeimport folgen in R7 bis R10. ## Unterstützter Arbeitsablauf diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index f4d1c7c..9b43c4f 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -14,7 +14,7 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | R3 | abgeschlossen | Konfiguration ohne eigene Revision, Worksharing-ID-Datenmodell, Migration 0014, Snapshot 10, Transfer und Backend-CSV-Entfernung sind umgesetzt und geprüft. | | R4 | abgeschlossen | Revit-Seite, Navigation und revisionierte XLSX-Einstellungen mit Musterdateiprüfung sind umgesetzt; das alte Projektseitenmodal ist entfernt. | | R5 | abgeschlossen | Zustandslose XLSX-Vorschau, sechsstufiger Erstimportwizard und atomarer Importcommand mit parserfreiem Undo/Redo. | -| R6 | offen | Virtualisierte Objekttabelle und Sammelzuordnungen. | +| R6 | abgeschlossen | Projektweite kompakte Objektliste, clientseitige Filter/Sortierung, Virtualisierung und revisionierte Sammeländerungen. | | R7 | offen | Editorbereich, Gruppierung, Drag-and-drop, Lösen und integrierte Löschübergänge. | | R8 | offen | Rückgabe-Excel und append-only Exportnachweis. | | R9 | offen | Vollständiger Folgeimport nach Worksharing-ID. | @@ -142,6 +142,14 @@ Zustände vollständig, sodass Undo/Redo weder Datei noch Parser benötigen. - Standardverteileränderung wirkt nur auf unzugeordnete Objekte; verknüpfte Objekte folgen unverändert ihrer Row. +Implementierungsstand vom 30.09.2026: Der projektweite GET-Endpunkt liefert +eine kompakte Liste ohne Batchbytes, Matrix oder Pagination. Die Revit-Seite +sucht, filtert und sortiert vollständig im Client und rendert nur den +sichtbaren Ausschnitt. Eine stabile Mehrfachauswahl ändert Verteiler, +ProjectDevice, Leistung und GZF in einem persistenten +`external-object.update-planning`-Command. Verknüpfte Objekte sind für diese +Sammelaktionen gesperrt und folgen weiterhin ausschließlich ihrer Row. + ## R7 – Stromkreislisteneditor - gruppierter rechter Revit-Bereich mit Anzahl-Badge; diff --git a/src/app/projects/[projectId]/revit/page.tsx b/src/app/projects/[projectId]/revit/page.tsx index bf9b39f..fc8b85e 100644 --- a/src/app/projects/[projectId]/revit/page.tsx +++ b/src/app/projects/[projectId]/revit/page.tsx @@ -5,6 +5,7 @@ import { useParams } from "next/navigation"; import { useEffect, useState } from "react"; import { IconLink } from "../../../../frontend/components/icon-link"; import { RevitInitialImportWizard } from "../../../../frontend/components/revit-initial-import-wizard"; +import { RevitObjectTable } from "../../../../frontend/components/revit-object-table"; import { RevitXlsxSettingsModal } from "../../../../frontend/components/revit-xlsx-settings-modal"; import type { ExternalModelConfiguration } from "../../../../external-model/configuration/external-model-configuration"; import { detectExternalModelWorkbook, getExternalInitialImportStatus, getExternalModelConfiguration, getProject, updateExternalModelConfiguration } from "../../../../frontend/utils/api"; @@ -43,6 +44,7 @@ export default function RevitPage() {
Projekt · Revit

{project?.name ?? "Revit-Anbindung"}

Linear-XLSX austauschen und Revit-Objekte verwalten

{error ?
{error}
: null}

XLSX-Konfiguration

{snapshot ? "Die Linear-Spalten und das Tabellenlayout sind konfiguriert." : "Noch keine XLSX-Konfiguration gespeichert."}

{snapshot ? "Konfiguriert" : "Offen"}

Importstatus

{importStatus?.imported ? <>

{importStatus.objectCount} Revit-Objekte{importStatus.fileName ? ` aus ${importStatus.fileName}` : ""}

Quelle: {importStatus.sourceName}

:

Noch kein Linear-XLSX-Import vorhanden.

}
+ {importStatus?.imported ? setProject((current) => current ? { ...current, currentRevision: revision } : current)} /> : null} {settingsOpen ? setSettingsOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} {importOpen && project && snapshot ? setImportOpen(false)} onImported={({ history }) => { setProject({ ...project, currentRevision: history.currentRevision }); setImportOpen(false); void Promise.all([getExternalInitialImportStatus(projectId), getExternalModelConfiguration(projectId)]).then(([status, configuration]) => { setImportStatus(status); setSnapshot(configuration.configuration); }); }} /> : null} ; diff --git a/src/db/repositories/external-object-planning-project-command.repository.ts b/src/db/repositories/external-object-planning-project-command.repository.ts new file mode 100644 index 0000000..e6b3b1f --- /dev/null +++ b/src/db/repositories/external-object-planning-project-command.repository.ts @@ -0,0 +1,29 @@ +import { and, eq } from "drizzle-orm"; +import { assertExternalObjectPlanningUpdateProjectCommand, invertExternalObjectPlanningUpdateProjectCommand } from "../../domain/models/external-object-planning-project-command.model.js"; +import type { ExternalObjectPlanningProjectCommandStore } from "../../domain/ports/external-object-planning-project-command.store.js"; +import type { AppDatabase } from "../database-context.js"; +import { distributionBoards } from "../schema/distribution-boards.js"; +import { externalModelObjects } from "../schema/external-model-objects.js"; +import { projectDevices } from "../schema/project-devices.js"; +import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { snapshotsEqual, toExternalObjectSnapshot } from "./external-object-assignment.persistence.js"; + +export class ExternalObjectPlanningProjectCommandRepository implements ExternalObjectPlanningProjectCommandStore { + constructor(private readonly database: AppDatabase) {} + execute(input: Parameters[0]) { + assertExternalObjectPlanningUpdateProjectCommand(input.command); + return executeProjectCommandTransaction(this.database, input, (tx) => { + const boardIds = new Set(tx.select({ id: distributionBoards.id }).from(distributionBoards).where(eq(distributionBoards.projectId, input.projectId)).all().map((row) => row.id)); + const deviceIds = new Set(tx.select({ id: projectDevices.id }).from(projectDevices).where(eq(projectDevices.projectId, input.projectId)).all().map((row) => row.id)); + for (const { expected, target } of input.command.payload.objects) { + const current = tx.select().from(externalModelObjects).where(and(eq(externalModelObjects.id, expected.id), eq(externalModelObjects.projectId, input.projectId))).get(); + if (!current || !snapshotsEqual(toExternalObjectSnapshot(current), expected)) throw new Error("Ein Revit-Objekt wurde zwischenzeitlich geändert."); + if (target.distributionBoardId !== null && !boardIds.has(target.distributionBoardId)) throw new Error("Der Verteiler gehört zu einem anderen Projekt."); + if (target.linkedProjectDeviceId !== null && !deviceIds.has(target.linkedProjectDeviceId)) throw new Error("Das Projektgerät gehört zu einem anderen Projekt."); + const updated = tx.update(externalModelObjects).set({ planningValues: target.planningValues, overriddenFields: target.overriddenFields, distributionBoardId: target.distributionBoardId, linkedProjectDeviceId: target.linkedProjectDeviceId }).where(and(eq(externalModelObjects.id, expected.id), eq(externalModelObjects.projectId, input.projectId))).run(); + if (updated.changes !== 1) throw new Error("Revit-Objekt konnte nicht geändert werden."); + } + return invertExternalObjectPlanningUpdateProjectCommand(input.command); + }); + } +} diff --git a/src/domain/models/external-object-planning-project-command.model.ts b/src/domain/models/external-object-planning-project-command.model.ts new file mode 100644 index 0000000..f31d126 --- /dev/null +++ b/src/domain/models/external-object-planning-project-command.model.ts @@ -0,0 +1,30 @@ +import type { ExternalModelObjectSnapshot } from "../../external-model/domain/external-model-contracts.js"; +import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; +import type { SerializedProjectCommand } from "./project-command.model.js"; + +export const externalObjectPlanningUpdateCommandType = "external-object.update-planning" as const; +export interface ExternalObjectPlanningUpdateProjectCommand extends SerializedProjectCommand<{ objects: Array<{ expected: ExternalModelObjectSnapshot; target: ExternalModelObjectSnapshot }> }> { + schemaVersion: 1; + type: typeof externalObjectPlanningUpdateCommandType; +} +export function createExternalObjectPlanningUpdateProjectCommand(objects: Array<{ expected: ExternalModelObjectSnapshot; target: ExternalModelObjectSnapshot }>): ExternalObjectPlanningUpdateProjectCommand { + const command: ExternalObjectPlanningUpdateProjectCommand = { schemaVersion: 1, type: externalObjectPlanningUpdateCommandType, payload: { objects } }; + assertExternalObjectPlanningUpdateProjectCommand(command); return command; +} +export function invertExternalObjectPlanningUpdateProjectCommand(command: ExternalObjectPlanningUpdateProjectCommand) { return createExternalObjectPlanningUpdateProjectCommand(command.payload.objects.map(({ expected, target }) => ({ expected: target, target: expected }))); } +export function assertExternalObjectPlanningUpdateProjectCommand(command: SerializedProjectCommand): asserts command is ExternalObjectPlanningUpdateProjectCommand { + if (command.schemaVersion !== 1 || command.type !== externalObjectPlanningUpdateCommandType || !isRecord(command.payload) || !Array.isArray(command.payload.objects) || command.payload.objects.length === 0) throw new Error("Nicht unterstützter Revit-Objektplanungs-Command."); + const ids = new Set(); + for (const transition of command.payload.objects) { + if (!isRecord(transition)) throw new Error("Ungültiger Revit-Objektübergang."); + const expected = parseObject(transition.expected); const target = parseObject(transition.target); + if (expected.id !== target.id || ids.has(expected.id)) throw new Error("Doppelte oder abweichende Revit-Objekt-ID."); + ids.add(expected.id); + if (expected.circuitDeviceRowId !== null || target.circuitDeviceRowId !== null) throw new Error("Verknüpfte Revit-Objekte werden über ihre Gerätezeile geplant."); + const left = { ...expected, planningValues: undefined, overriddenFields: undefined, distributionBoardId: undefined, linkedProjectDeviceId: undefined }; + const right = { ...target, planningValues: undefined, overriddenFields: undefined, distributionBoardId: undefined, linkedProjectDeviceId: undefined }; + if (JSON.stringify(left) !== JSON.stringify(right) || JSON.stringify(expected) === JSON.stringify(target)) throw new Error("Der Objektplanungs-Command ändert unzulässige oder keine Felder."); + } +} +function parseObject(value: unknown) { return parseExternalModelStateSnapshot({ source: null, importBatches: [], roomMappings: [], objects: [value] }).objects[0]!; } +function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } diff --git a/src/domain/ports/external-object-planning-project-command.store.ts b/src/domain/ports/external-object-planning-project-command.store.ts new file mode 100644 index 0000000..19c610b --- /dev/null +++ b/src/domain/ports/external-object-planning-project-command.store.ts @@ -0,0 +1,3 @@ +import type { ExternalObjectPlanningUpdateProjectCommand } from "../models/external-object-planning-project-command.model.js"; +import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; +export interface ExternalObjectPlanningProjectCommandStore { execute(input: { projectId: string; expectedRevision: number; source: ProjectRevisionSource; description?: string; actorId?: string; historyTargetChangeSetId?: string; command: ExternalObjectPlanningUpdateProjectCommand }): { revision: AppendedProjectRevision; inverse: ExternalObjectPlanningUpdateProjectCommand }; } diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index 8e4bf36..ca99c5f 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -182,6 +182,8 @@ import { externalInitialImportCommandType, } from "../models/external-initial-import-project-command.model.js"; import type { ExternalInitialImportProjectCommandStore } from "../ports/external-initial-import-project-command.store.js"; +import { assertExternalObjectPlanningUpdateProjectCommand, externalObjectPlanningUpdateCommandType } from "../models/external-object-planning-project-command.model.js"; +import type { ExternalObjectPlanningProjectCommandStore } from "../ports/external-object-planning-project-command.store.js"; import { assertExternalObjectRowAssignmentProjectCommand, externalObjectRowAssignmentCommandType, @@ -248,7 +250,8 @@ export class ProjectCommandService implements ProjectCommandExecutor { private readonly externalObjectNewRowStore?: ExternalObjectNewRowProjectCommandStore, private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore, private readonly estimateBalanceStore?: EstimateBalanceProjectCommandStore, - private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore + private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore, + private readonly externalObjectPlanningStore?: ExternalObjectPlanningProjectCommandStore ) {} executeUser( @@ -647,6 +650,11 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } + case externalObjectPlanningUpdateCommandType: { + assertExternalObjectPlanningUpdateProjectCommand(input.command); + if (!this.externalObjectPlanningStore) throw new Error("External object planning store is not available."); + return this.externalObjectPlanningStore.execute({ ...input, command: input.command }).revision; + } case externalObjectRowAssignmentCommandType: { assertExternalObjectRowAssignmentProjectCommand(input.command); if (!this.externalObjectRowAssignmentStore) { diff --git a/src/frontend/components/revit-object-table.tsx b/src/frontend/components/revit-object-table.tsx new file mode 100644 index 0000000..c82d9c7 --- /dev/null +++ b/src/frontend/components/revit-object-table.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; +import type { ExternalProjectObjectsDto } from "../types"; +import { getExternalProjectObjects, updateExternalProjectObjects } from "../utils/api"; + +const rowHeight = 44; +const viewportHeight = 520; + +export function RevitObjectTable({ projectId, onRevision }: { projectId: string; onRevision: (revision: number) => void }) { + const [data, setData] = useState(null); + const [search, setSearch] = useState(""); + const [boardFilter, setBoardFilter] = useState("all"); + const [assignmentFilter, setAssignmentFilter] = useState("all"); + const [sort, setSort] = useState<"family" | "room" | "worksharing">("family"); + const [selected, setSelected] = useState>(new Set()); + const [scrollTop, setScrollTop] = useState(0); + const [bulkBoard, setBulkBoard] = useState(""); + const [bulkDevice, setBulkDevice] = useState(""); + const [power, setPower] = useState(""); + const [gzf, setGzf] = useState(""); + const [planningField, setPlanningField] = useState(""); + const [planningValue, setPlanningValue] = useState(""); + const [error, setError] = useState(null); + const [saving, setSaving] = useState(false); + + async function load() { try { const loaded = await getExternalProjectObjects(projectId); setData(loaded); onRevision(loaded.currentRevision); } catch (value) { setError(value instanceof Error ? value.message : "Revit-Objekte konnten nicht geladen werden."); } } + useEffect(() => { void load(); }, [projectId]); // eslint-disable-line react-hooks/exhaustive-deps + + const rows = useMemo(() => { + if (!data) return []; + const needle = search.trim().toLocaleLowerCase("de-DE"); + return data.objects.filter((object) => { + if (boardFilter !== "all" && (boardFilter === "none" ? object.distributionBoardId !== null : object.distributionBoardId !== boardFilter)) return false; + if (assignmentFilter === "unassigned" && object.circuitDeviceRowId !== null) return false; + if (assignmentFilter === "linked" && object.circuitDeviceRowId === null) return false; + return !needle || [object.worksharingId, object.familyAndType, object.selectionMarker, object.sourceRoomNumber, object.sourceRoomName, object.planningValues.displayName ?? ""].some((value) => value.toLocaleLowerCase("de-DE").includes(needle)); + }).sort((a, b) => { + const left = sort === "family" ? a.familyAndType : sort === "room" ? `${a.sourceRoomNumber}\u0000${a.sourceRoomName}` : a.worksharingId; + const right = sort === "family" ? b.familyAndType : sort === "room" ? `${b.sourceRoomNumber}\u0000${b.sourceRoomName}` : b.worksharingId; + return left.localeCompare(right, "de", { numeric: true }) || a.worksharingId.localeCompare(b.worksharingId); + }); + }, [data, search, boardFilter, assignmentFilter, sort]); + const first = Math.max(0, Math.floor(scrollTop / rowHeight) - 5); + const visible = rows.slice(first, first + Math.ceil(viewportHeight / rowHeight) + 10); + const selectable = rows.filter((object) => object.circuitDeviceRowId === null); + + async function applyBulk() { + if (!data || selected.size === 0) return; + const patch: Record = {}; + if (bulkBoard !== "") patch.distributionBoardId = bulkBoard === "none" ? null : bulkBoard; + if (bulkDevice !== "") patch.linkedProjectDeviceId = bulkDevice === "none" ? null : bulkDevice; + if (power !== "") patch.powerPerUnitW = Number(power.replace(",", ".")); + if (gzf !== "") patch.simultaneityFactor = Number(gzf.replace(",", ".")); + if (planningField) { + patch[planningField] = ["effectiveQuantity", "cosPhi"].includes(planningField) + ? Number(planningValue.replace(",", ".")) + : planningValue === "" ? null : planningValue; + } + if (Object.keys(patch).length === 0) { setError("Mindestens eine Sammeländerung auswählen."); return; } + setSaving(true); setError(null); + try { const result = await updateExternalProjectObjects(projectId, data.currentRevision, [...selected], patch); onRevision(result.history.currentRevision); setSelected(new Set()); await load(); } + catch (value) { setError(value instanceof Error ? value.message : "Sammeländerung fehlgeschlagen."); } + finally { setSaving(false); } + } + + if (!data) return
Revit-Objekte werden geladen …
; + return

Revit-Objekte

{rows.length} von {data.objects.length} · {selected.size} ausgewählt
setSearch(event.target.value)} />
+ {error ?
{error}
: null} +
setScrollTop(event.currentTarget.scrollTop)}>
{visible.map((object, index) => { const top = (first + index) * rowHeight; const linked = object.circuitDeviceRowId !== null; return
setSelected((current) => { const next = new Set(current); if (next.has(object.id)) next.delete(object.id); else next.add(object.id); return next; })} />
{object.planningValues.displayName ?? object.familyAndType}
{object.familyAndType}
{object.sourceRoomNumber} {object.sourceRoomName}
{data.distributionBoards.find((board) => board.id === object.distributionBoardId)?.name ?? "Ohne Verteiler"}
{object.selectionMarker || object.worksharingId}
{linked ? "verknüpft" : "frei"}
; })}
+
{planningField ? : null}
+
; +} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 9a18a94..49466f5 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -111,6 +111,21 @@ export interface ExternalInitialImportResultDto extends ProjectCommandResultDto }; } +export interface ExternalProjectObjectDto { + id: string; worksharingId: string; ifcGuid: string | null; deviceTypeId: string; + familyAndType: string; selectionMarker: string; sourceCircuitIdentifier: string; + sourceRoomNumber: string; sourceRoomName: string; roomId: string | null; + distributionBoardId: string | null; linkedProjectDeviceId: string | null; + circuitDeviceRowId: string | null; presenceStatus: "present" | "missing"; + planningValues: { displayName: string | null; category: CircuitGroupCategory | null; connectionKind: string | null; effectiveQuantity: number; powerPerUnitW: number | null; simultaneityFactor: number | null; cosPhi: number | null; costGroup: string | null; remark: string | null }; +} +export interface ExternalProjectObjectsDto { + currentRevision: number; sourceName: string | null; + distributionBoards: Array<{ id: string; name: string }>; + projectDevices: Array<{ id: string; name: string; displayName: string }>; + objects: ExternalProjectObjectDto[]; +} + export interface ProjectDto { id: string; name: string; diff --git a/src/frontend/utils/api.ts b/src/frontend/utils/api.ts index 692640d..c46f80b 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -43,6 +43,7 @@ import type { ExternalInitialImportResultDto, ExternalInitialImportStatusDto, ApplyExternalInitialImportInput, + ExternalProjectObjectsDto, CreateEstimateBalanceInput, EstimateBalanceCommandResultDto, EstimateBalanceDto, @@ -236,6 +237,14 @@ async function fileToBase64(file: File) { return btoa(binary); } +export function getExternalProjectObjects(projectId: string) { + return request(`/api/projects/${projectId}/external-model/objects`); +} + +export function updateExternalProjectObjects(projectId: string, expectedRevision: number, objectIds: string[], patch: Record) { + return request(`/api/projects/${projectId}/external-model/objects`, { method: "PUT", body: JSON.stringify({ expectedRevision, objectIds, patch }) }); +} + export function getProjectHistory(projectId: string) { return request( `/api/projects/${projectId}/history` diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index 4d6003a..2f1f35b 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -65,6 +65,7 @@ const commandTypeLabels: Record = { "external-model-configuration.update": "Revit-XLSX-Einstellungen bearbeitet", "external-import.apply-initial": "Revit-Erstimport übernommen", "external-model.apply-initial-import": "Linear-XLSX-Erstimport übernommen", + "external-object.update-planning": "Revit-Objekte bearbeitet", "external-object.assign-to-new-circuit": "Externes Objekt in neuen Stromkreis übernommen", "external-object.unassign-and-delete-created-circuit": diff --git a/src/server/composition/project-command-stores.ts b/src/server/composition/project-command-stores.ts index 4017144..669e25d 100644 --- a/src/server/composition/project-command-stores.ts +++ b/src/server/composition/project-command-stores.ts @@ -24,6 +24,7 @@ import { ProjectStateRestoreCommandRepository } from "../../db/repositories/proj import { ProjectCommandService } from "../../domain/services/project-command.service.js"; import { ExternalModelConfigurationProjectCommandRepository } from "../../db/repositories/external-model-configuration-project-command.repository.js"; import { ExternalInitialImportProjectCommandRepository } from "../../db/repositories/external-initial-import-project-command.repository.js"; +import { ExternalObjectPlanningProjectCommandRepository } from "../../db/repositories/external-object-planning-project-command.repository.js"; import { ExternalObjectRowAssignmentProjectCommandRepository } from "../../db/repositories/external-object-row-assignment-project-command.repository.js"; import { ExternalObjectNewRowProjectCommandRepository } from "../../db/repositories/external-object-new-row-project-command.repository.js"; import { ExternalObjectNewCircuitProjectCommandRepository } from "../../db/repositories/external-object-new-circuit-project-command.repository.js"; @@ -75,6 +76,8 @@ export const externalModelConfigurationProjectCommandStore = new ExternalModelConfigurationProjectCommandRepository(db); export const externalInitialImportProjectCommandStore = new ExternalInitialImportProjectCommandRepository(db); +export const externalObjectPlanningProjectCommandStore = + new ExternalObjectPlanningProjectCommandRepository(db); export const externalObjectRowAssignmentProjectCommandStore = new ExternalObjectRowAssignmentProjectCommandRepository(db); export const externalObjectNewRowProjectCommandStore = @@ -111,5 +114,6 @@ export const projectCommandService = new ProjectCommandService( externalObjectNewRowProjectCommandStore, externalObjectNewCircuitProjectCommandStore, estimateBalanceProjectCommandStore, - externalInitialImportProjectCommandStore + externalInitialImportProjectCommandStore, + externalObjectPlanningProjectCommandStore ); diff --git a/src/server/controllers/external-objects.controller.ts b/src/server/controllers/external-objects.controller.ts new file mode 100644 index 0000000..f56f7be --- /dev/null +++ b/src/server/controllers/external-objects.controller.ts @@ -0,0 +1,56 @@ +import type { Request, Response } from "express"; +import { createExternalObjectPlanningUpdateProjectCommand } from "../../domain/models/external-object-planning-project-command.model.js"; +import type { ExternalModelObjectPlanningValues } from "../../external-model/domain/external-model-contracts.js"; +import { distributionBoardRepository, externalModelStateRepository, projectDeviceRepository, projectRepository } from "../composition/application-repositories.js"; +import { projectCommandService } from "../composition/project-command-stores.js"; +import { respondWithProjectCommandError } from "./project-command.controller.js"; + +export async function listExternalObjects(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + const [project, boards, devices] = await Promise.all([projectRepository.findById(projectId), distributionBoardRepository.listByProject(projectId), projectDeviceRepository.listByProject(projectId)]); + if (!project) return res.status(404).json({ error: "Projekt nicht gefunden." }); + const state = externalModelStateRepository.getByProject(projectId).state; + const mappings = new Map(state.roomMappings.map((mapping) => [mapping.id, mapping])); + return res.json({ + currentRevision: project.currentRevision, + sourceName: state.source?.name ?? null, + distributionBoards: boards.map(({ id, name }) => ({ id, name })), + projectDevices: devices.map(({ id, name, displayName }) => ({ id, name, displayName })), + objects: state.objects.map((object) => { + const mapping = object.externalRoomMappingId ? mappings.get(object.externalRoomMappingId) : null; + return { id: object.id, worksharingId: object.worksharingId, ifcGuid: object.ifcGuid, deviceTypeId: object.deviceTypeId, familyAndType: object.acceptedSourceValues.familyAndType, selectionMarker: scalarText(object.acceptedSourceValues.selectionMarker), sourceCircuitIdentifier: scalarText(object.acceptedSourceValues.circuitCombined) || scalarText(object.acceptedSourceValues.circuitIdentifier), sourceRoomNumber: scalarText(object.acceptedSourceValues.roomNumber), sourceRoomName: scalarText(object.acceptedSourceValues.roomName), roomId: mapping?.roomId ?? null, distributionBoardId: object.distributionBoardId, linkedProjectDeviceId: object.linkedProjectDeviceId, circuitDeviceRowId: object.circuitDeviceRowId, presenceStatus: object.presenceStatus, planningValues: object.planningValues }; + }), + }); +} + +export function updateExternalObjects(req: Request, res: Response) { + const projectId = String(req.params.projectId ?? ""); + try { + const expectedRevision = req.body?.expectedRevision; + if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw new Error("Ungültige Projektrevision."); + const objectIds = req.body?.objectIds; + const patch = req.body?.patch; + if (!Array.isArray(objectIds) || objectIds.length === 0 || new Set(objectIds).size !== objectIds.length || !isRecord(patch)) throw new Error("Objektauswahl oder Änderungen sind ungültig."); + const state = externalModelStateRepository.getByProject(projectId); + if (!state.projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); + const byId = new Map(state.state.objects.map((object) => [object.id, object])); + const transitions = objectIds.map((id: unknown) => { + if (typeof id !== "string") throw new Error("Ungültige Revit-Objekt-ID."); + const expected = byId.get(id); + if (!expected) throw new Error("Ein ausgewähltes Revit-Objekt wurde nicht gefunden."); + if (expected.circuitDeviceRowId !== null) throw new Error("Verknüpfte Revit-Objekte folgen ihrer Gerätezeile und können hier nicht geändert werden."); + const planningValues = { ...expected.planningValues }; + const overriddenFields = new Set(expected.overriddenFields); + for (const field of planningFields) if (hasOwn(patch, field)) { planningValues[field] = patch[field] as never; overriddenFields.add(field); } + return { expected, target: { ...expected, planningValues, overriddenFields: [...overriddenFields], distributionBoardId: hasOwn(patch, "distributionBoardId") ? nullableId(patch.distributionBoardId) : expected.distributionBoardId, linkedProjectDeviceId: hasOwn(patch, "linkedProjectDeviceId") ? nullableId(patch.linkedProjectDeviceId) : expected.linkedProjectDeviceId } }; + }); + const result = projectCommandService.executeUser({ projectId, expectedRevision, description: `${transitions.length} Revit-Objekte bearbeitet`, command: createExternalObjectPlanningUpdateProjectCommand(transitions) }); + return res.json(result); + } catch (error) { return respondWithProjectCommandError(error, res); } +} + +const planningFields = ["displayName", "category", "connectionKind", "effectiveQuantity", "powerPerUnitW", "simultaneityFactor", "cosPhi", "costGroup", "remark"] as const satisfies readonly (keyof ExternalModelObjectPlanningValues)[]; +function scalarText(value: string | number | boolean | null) { return value === null ? "" : String(value); } +function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } +function hasOwn(value: object, key: PropertyKey) { return Object.prototype.hasOwnProperty.call(value, key); } +function nullableId(value: unknown) { if (value === null || value === "") return null; if (typeof value !== "string") throw new Error("Ungültige Zuordnungs-ID."); return value; } diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index 84f2ea3..53c2225 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -63,6 +63,7 @@ import { getExternalInitialImportStatus, planExternalInitialImport, } from "../controllers/external-initial-import.controller.js"; +import { listExternalObjects, updateExternalObjects } from "../controllers/external-objects.controller.js"; export const projectRouter = Router(); @@ -90,6 +91,8 @@ projectRouter.post("/:projectId/external-model/configuration/detect", detectExte projectRouter.get("/:projectId/external-model/import-status", getExternalInitialImportStatus); projectRouter.post("/:projectId/external-model/initial-import/plan", planExternalInitialImport); projectRouter.post("/:projectId/external-model/initial-import/apply", applyExternalInitialImport); +projectRouter.get("/:projectId/external-model/objects", listExternalObjects); +projectRouter.put("/:projectId/external-model/objects", updateExternalObjects); projectRouter.get("/:projectId/distribution-boards", listDistributionBoardsByProject); projectRouter.post("/:projectId/distribution-boards", createDistributionBoard); projectRouter.post( diff --git a/tests/external-xlsx-initial-import.test.ts b/tests/external-xlsx-initial-import.test.ts index 33400d6..75af423 100644 --- a/tests/external-xlsx-initial-import.test.ts +++ b/tests/external-xlsx-initial-import.test.ts @@ -5,9 +5,11 @@ import { migrate } from "drizzle-orm/better-sqlite3/migrator"; import { createDatabaseContext } from "../src/db/database-context.js"; import { ExternalInitialImportProjectCommandRepository } from "../src/db/repositories/external-initial-import-project-command.repository.js"; import { ExternalModelStateRepository } from "../src/db/repositories/external-model-state.repository.js"; +import { ExternalObjectPlanningProjectCommandRepository } from "../src/db/repositories/external-object-planning-project-command.repository.js"; import { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; import { projects } from "../src/db/schema/projects.js"; import { createEmptyExternalModelState, createExternalInitialImportProjectCommand } from "../src/domain/models/external-initial-import-project-command.model.js"; +import { createExternalObjectPlanningUpdateProjectCommand } from "../src/domain/models/external-object-planning-project-command.model.js"; import { createExternalXlsxInitialImportPlan } from "../src/external-model/application/external-xlsx-initial-import.js"; import { buildExternalXlsxInitialImportTarget } from "../src/external-model/application/external-xlsx-initial-import-target.js"; import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; @@ -62,7 +64,15 @@ describe("Linear XLSX initial import", () => { const undone = repository.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: inserted.revision.changeSetId, command: inserted.inverse }); assert.equal(new ExternalModelStateRepository(context.db).getByProject("project-1").state.source, null); repository.execute({ projectId: "project-1", expectedRevision: 2, source: "redo", historyTargetChangeSetId: inserted.revision.changeSetId, command: undone.inverse }); - assert.deepEqual(new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects.map((object) => object.worksharingId), plan.objects.map((object) => object.worksharingId).sort()); + const redone = new ExternalModelStateRepository(context.db).getByProject("project-1").state; + assert.deepEqual(redone.objects.map((object) => object.worksharingId), plan.objects.map((object) => object.worksharingId).sort()); + const expectedObject = redone.objects[0]; + const targetObject = { ...expectedObject, planningValues: { ...expectedObject.planningValues, simultaneityFactor: 0.5 }, overriddenFields: [...expectedObject.overriddenFields, "simultaneityFactor" as const] }; + const planningRepository = new ExternalObjectPlanningProjectCommandRepository(context.db); + const planned = planningRepository.execute({ projectId: "project-1", expectedRevision: 3, source: "user", command: createExternalObjectPlanningUpdateProjectCommand([{ expected: expectedObject, target: targetObject }]) }); + assert.equal(new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects[0].planningValues.simultaneityFactor, 0.5); + planningRepository.execute({ projectId: "project-1", expectedRevision: 4, source: "undo", historyTargetChangeSetId: planned.revision.changeSetId, command: planned.inverse }); + assert.equal(new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects[0].planningValues.simultaneityFactor, 1); } finally { context.close(); } }); }); diff --git a/tests/revit-xlsx-settings-api.test.ts b/tests/revit-xlsx-settings-api.test.ts index 22d633c..ed91b57 100644 --- a/tests/revit-xlsx-settings-api.test.ts +++ b/tests/revit-xlsx-settings-api.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { describe, it } from "node:test"; import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; -import { applyExternalInitialImport, detectExternalModelWorkbook, getExternalInitialImportStatus, getExternalModelConfiguration, planExternalInitialImport, updateExternalModelConfiguration } from "../src/frontend/utils/api.js"; +import { applyExternalInitialImport, detectExternalModelWorkbook, getExternalInitialImportStatus, getExternalModelConfiguration, getExternalProjectObjects, planExternalInitialImport, updateExternalModelConfiguration, updateExternalProjectObjects } from "../src/frontend/utils/api.js"; describe("Revit XLSX settings", () => { it("uses the project-scoped configuration endpoint with expectedRevision", async () => { @@ -53,6 +53,7 @@ describe("Revit XLSX settings", () => { const revitPage = readFileSync("src/app/projects/[projectId]/revit/page.tsx", "utf8"); const settings = readFileSync("src/frontend/components/revit-xlsx-settings-modal.tsx", "utf8"); const wizard = readFileSync("src/frontend/components/revit-initial-import-wizard.tsx", "utf8"); + const objectTable = readFileSync("src/frontend/components/revit-object-table.tsx", "utf8"); assert.match(projectPage, /href={`\/projects\/\$\{projectId\}\/revit`}/); assert.doesNotMatch(projectPage, /RevitCsvModal|Revit-CSV/); assert.match(revitPage, /Importstatus/); @@ -61,5 +62,16 @@ describe("Revit XLSX settings", () => { assert.match(wizard, /Schritt.*von/); assert.match(wizard, /keine Gerätezeilen, Stromkreise oder BMKs/); assert.match(wizard, /GZF 1/); + assert.match(objectTable, /viewportHeight/); + assert.match(objectTable, /Sammeländerung anwenden/); + }); + + it("loads one project object list and sends revision-safe bulk updates", async () => { + const requests: Array<{ url: string; method: string; body: unknown }> = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (input, init) => { requests.push({ url: String(input), method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined }); return new Response(JSON.stringify({ currentRevision: 4, sourceName: null, distributionBoards: [], projectDevices: [], objects: [], history: { currentRevision: 5 } }), { status: 200, headers: { "Content-Type": "application/json" } }); }; + try { await getExternalProjectObjects("project-1"); await updateExternalProjectObjects("project-1", 4, ["object-1"], { simultaneityFactor: 0.7 }); } + finally { globalThis.fetch = originalFetch; } + assert.deepEqual(requests, [{ url: "/api/projects/project-1/external-model/objects", method: "GET", body: undefined }, { url: "/api/projects/project-1/external-model/objects", method: "PUT", body: { expectedRevision: 4, objectIds: ["object-1"], patch: { simultaneityFactor: 0.7 } } }]); }); }); From 4489cd76f0fb5b38a0399d4cac59b75a05a6d85e Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 13:51:43 +0200 Subject: [PATCH 33/38] Allow saving default Revit settings --- src/app/projects/[projectId]/revit/page.tsx | 2 +- src/frontend/components/revit-xlsx-settings-modal.tsx | 5 +++-- tests/revit-xlsx-settings-api.test.ts | 2 ++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/app/projects/[projectId]/revit/page.tsx b/src/app/projects/[projectId]/revit/page.tsx index fc8b85e..46c3d5d 100644 --- a/src/app/projects/[projectId]/revit/page.tsx +++ b/src/app/projects/[projectId]/revit/page.tsx @@ -45,7 +45,7 @@ export default function RevitPage() { {error ?
{error}
: null}

XLSX-Konfiguration

{snapshot ? "Die Linear-Spalten und das Tabellenlayout sind konfiguriert." : "Noch keine XLSX-Konfiguration gespeichert."}

{snapshot ? "Konfiguriert" : "Offen"}

Importstatus

{importStatus?.imported ? <>

{importStatus.objectCount} Revit-Objekte{importStatus.fileName ? ` aus ${importStatus.fileName}` : ""}

Quelle: {importStatus.sourceName}

:

Noch kein Linear-XLSX-Import vorhanden.

}
{importStatus?.imported ? setProject((current) => current ? { ...current, currentRevision: revision } : current)} /> : null} - {settingsOpen ? setSettingsOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} + {settingsOpen ? setSettingsOpen(false)} onInspectSample={async (file, configuration) => { const result = await detectExternalModelWorkbook(projectId, file, configuration); return `Muster erkannt: ${result.sheetName}, ${result.columnCount} Spalten, ${result.objectCount} Objekte.`; }} onSave={save} /> : null} {importOpen && project && snapshot ? setImportOpen(false)} onImported={({ history }) => { setProject({ ...project, currentRevision: history.currentRevision }); setImportOpen(false); void Promise.all([getExternalInitialImportStatus(projectId), getExternalModelConfiguration(projectId)]).then(([status, configuration]) => { setImportStatus(status); setSnapshot(configuration.configuration); }); }} /> : null} ; } diff --git a/src/frontend/components/revit-xlsx-settings-modal.tsx b/src/frontend/components/revit-xlsx-settings-modal.tsx index 7041ebc..899c3ca 100644 --- a/src/frontend/components/revit-xlsx-settings-modal.tsx +++ b/src/frontend/components/revit-xlsx-settings-modal.tsx @@ -13,8 +13,9 @@ const labels: Record = { electricalPowerW: "Elektrische Leistung", voltageV: "Spannung", currentA: "Stromstärke", }; -export function RevitXlsxSettingsModal({ configuration, isSaving, onClose, onInspectSample, onSave }: { +export function RevitXlsxSettingsModal({ configuration, isNewConfiguration = false, isSaving, onClose, onInspectSample, onSave }: { configuration: ExternalModelConfiguration; + isNewConfiguration?: boolean; isSaving: boolean; onClose: () => void; onInspectSample: (file: File, configuration: ExternalModelConfiguration) => Promise; @@ -33,7 +34,7 @@ export function RevitXlsxSettingsModal({ configuration, isSaving, onClose, onIns } } - return { event.preventDefault(); void onSave(draft); }}> + return { event.preventDefault(); void onSave(draft); }}>
void inspectSample(event.target.files?.[0])} />{sampleStatus ?
{sampleStatus}
: null}
{(["headerRow", "firstDataRow", "firstDataColumn"] as const).map((key) =>
setDraft({ ...draft, layout: { ...draft.layout, [key]: Number(event.target.value) } })} />
)} diff --git a/tests/revit-xlsx-settings-api.test.ts b/tests/revit-xlsx-settings-api.test.ts index ed91b57..4f13b70 100644 --- a/tests/revit-xlsx-settings-api.test.ts +++ b/tests/revit-xlsx-settings-api.test.ts @@ -59,6 +59,8 @@ describe("Revit XLSX settings", () => { assert.match(revitPage, /Importstatus/); assert.match(settings, /Musterdatei prüfen/); assert.match(settings, /Kombinierte Stromkreisspalte/); + assert.match(settings, /isNewConfiguration/); + assert.match(revitPage, /isNewConfiguration={snapshot === null}/); assert.match(wizard, /Schritt.*von/); assert.match(wizard, /keine Gerätezeilen, Stromkreise oder BMKs/); assert.match(wizard, /GZF 1/); From 77d775fde11224b4297de9206c5f89633ef36d8f Mon Sep 17 00:00:00 2001 From: Julian Appel Date: Wed, 30 Sep 2026 14:35:14 +0200 Subject: [PATCH 34/38] Complete Revit object editor assignments --- .../revit-excel-integration-requirements.md | 10 + docs/spec/revit-excel-phase-14-plan.md | 2 +- src/app/globals.css | 11 + ...ow-structure-project-command.repository.ts | 53 ++-- ...roup-subtree-project-command.repository.ts | 41 +++- ...it-structure-project-command.repository.ts | 65 +++-- ...rd-structure-project-command.repository.ts | 2 + ...oard-subtree-project-command.repository.ts | 2 + .../external-object-assignment.persistence.ts | 29 ++- ...ernal-object-deletion-guard.persistence.ts | 37 +++ ...on-structure-project-command.repository.ts | 2 + ...ice-row-structure-project-command.model.ts | 55 ++++- ...uit-group-subtree-project-command.model.ts | 15 +- ...circuit-structure-project-command.model.ts | 16 +- src/domain/models/circuit-tree.model.ts | 1 + ...bject-new-circuit-project-command.model.ts | 4 +- ...al-object-new-row-project-command.model.ts | 4 +- ...ct-row-assignment-project-command.model.ts | 19 +- .../components/circuit-tree-editor.tsx | 231 ++++++++++++++++-- src/frontend/types.ts | 1 + src/frontend/utils/api.ts | 26 ++ .../controllers/circuit-tree.controller.ts | 9 + .../external-objects.controller.ts | 223 +++++++++++++++++ src/server/routes/project.routes.ts | 6 +- ...ignment-project-command.repository.test.ts | 66 +++++ 25 files changed, 853 insertions(+), 77 deletions(-) create mode 100644 src/db/repositories/external-object-deletion-guard.persistence.ts diff --git a/docs/spec/revit-excel-integration-requirements.md b/docs/spec/revit-excel-integration-requirements.md index 29a4aaf..5add6fb 100644 --- a/docs/spec/revit-excel-integration-requirements.md +++ b/docs/spec/revit-excel-integration-requirements.md @@ -306,6 +306,16 @@ aktuellen Row-Werte als Planungswerte und entsprechende Overrides. ## 11. Editor-Zuordnung und Löschen +Umsetzungsstand R7: Der Stromkreislisteneditor lädt die kompakte Projektliste +gemeinsam mit dem Baum, gruppiert unzugeordnete Objekte des aktuellen +Verteilers im Client und bietet Gruppen sowie einzelne Worksharing-IDs als +Drag-Quelle an. Drop auf Row, Circuit und freien Gruppenbereich verwendet die +drei persistenten Zuordnungscommands. Row-Badges zeigen die Linkzahl; Lösen +kopiert die aktuellen Row-Planungswerte als Overrides. Row-, Circuit- und +Gruppenlöschungen speichern die vollständigen Linkübergänge im Forward- und +Inverse-Command. Raum- und Verteilerlöschungen prüfen externe Referenzen +explizit. + Der rechte, überlagernde Editorbereich zeigt unzugeordnete konfliktfreie Objekte des aktuellen Verteilers. Gruppierungsschlüssel sind interner Raum, Auswahlkenner, Geräteart, Kategorie, identische Planungswerte und kompatibler diff --git a/docs/spec/revit-excel-phase-14-plan.md b/docs/spec/revit-excel-phase-14-plan.md index 9b43c4f..700db4c 100644 --- a/docs/spec/revit-excel-phase-14-plan.md +++ b/docs/spec/revit-excel-phase-14-plan.md @@ -15,7 +15,7 @@ Der alte CSV-Plan 14.0–14.6 ist abgelöst und wird nicht fortgeschrieben. | R4 | abgeschlossen | Revit-Seite, Navigation und revisionierte XLSX-Einstellungen mit Musterdateiprüfung sind umgesetzt; das alte Projektseitenmodal ist entfernt. | | R5 | abgeschlossen | Zustandslose XLSX-Vorschau, sechsstufiger Erstimportwizard und atomarer Importcommand mit parserfreiem Undo/Redo. | | R6 | abgeschlossen | Projektweite kompakte Objektliste, clientseitige Filter/Sortierung, Virtualisierung und revisionierte Sammeländerungen. | -| R7 | offen | Editorbereich, Gruppierung, Drag-and-drop, Lösen und integrierte Löschübergänge. | +| R7 | abgeschlossen | Gruppierter Editorbereich, drei Drag-and-drop-Ziele, Row-Indikator, ausdrückliches Lösen und atomare Löschübergänge mit exaktem Undo/Redo. | | R8 | offen | Rückgabe-Excel und append-only Exportnachweis. | | R9 | offen | Vollständiger Folgeimport nach Worksharing-ID. | | R10 | offen | Ende-zu-Ende-Härtung, große Datenmengen und Abschlussdokumentation. | diff --git a/src/app/globals.css b/src/app/globals.css index 8b55c75..67985f4 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1128,6 +1128,17 @@ a.kpi:hover { border-style: dashed; } +.project-device-item > summary { + display: flex; + flex-direction: column; + gap: 0.1rem; + cursor: grab; +} + +.project-device-item > summary::marker { + color: var(--text-faint); +} + .sidebar-actions { display: flex; flex-direction: column; diff --git a/src/db/repositories/circuit-device-row-structure-project-command.repository.ts b/src/db/repositories/circuit-device-row-structure-project-command.repository.ts index 6919d20..f69dc78 100644 --- a/src/db/repositories/circuit-device-row-structure-project-command.repository.ts +++ b/src/db/repositories/circuit-device-row-structure-project-command.repository.ts @@ -23,8 +23,15 @@ import { toCircuitDeviceRowInsertValues, toCircuitDeviceRowSnapshot, } from "./circuit-device-row-structure.persistence.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { executeProjectCommandTransactionWithAppliedForward, type AppliedProjectCommand } from "./project-command-transaction.persistence.js"; import { updateDerivedCircuitVoltage } from "./project-voltage.persistence.js"; +import { + applyExternalObjectLinks, + captureExternalObjectDetachTransitions, + invertExternalObjectLinkTransitions, + loadExpectedExternalObjectTransitions, + type ExternalObjectLinkTransition, +} from "./external-object-assignment.persistence.js"; export class CircuitDeviceRowStructureProjectCommandRepository implements CircuitDeviceRowStructureProjectCommandStore @@ -32,7 +39,11 @@ export class CircuitDeviceRowStructureProjectCommandRepository constructor(private readonly database: AppDatabase) {} execute(input: ExecuteCircuitDeviceRowStructureCommandInput) { - return executeProjectCommandTransaction( + return executeProjectCommandTransactionWithAppliedForward< + CircuitDeviceRowStructureProjectCommand, + CircuitDeviceRowStructureProjectCommand, + CircuitDeviceRowStructureProjectCommand + >( this.database, input, (tx) => @@ -50,14 +61,15 @@ export class CircuitDeviceRowStructureProjectCommandRepository projectId: string, source: ExecuteCircuitDeviceRowStructureCommandInput["source"], command: CircuitDeviceRowStructureProjectCommand - ): CircuitDeviceRowStructureProjectCommand { + ): AppliedProjectCommand { if (command.type === circuitDeviceRowInsertCommandType) { assertCircuitDeviceRowInsertProjectCommand(command); return this.insert( database, projectId, source, - command.payload.row + command.payload.row, + command.payload.externalObjects ?? [] ); } if (command.type === circuitDeviceRowDeleteCommandType) { @@ -66,7 +78,8 @@ export class CircuitDeviceRowStructureProjectCommandRepository database, projectId, command.payload.rowId, - command.payload.expectedCircuitId + command.payload.expectedCircuitId, + command.payload.externalObjects ); } throw new Error("Unsupported circuit device-row structure command."); @@ -76,7 +89,8 @@ export class CircuitDeviceRowStructureProjectCommandRepository database: AppDatabase, projectId: string, source: ExecuteCircuitDeviceRowStructureCommandInput["source"], - row: CircuitDeviceRowSnapshot + row: CircuitDeviceRowSnapshot, + externalObjects: ExternalObjectLinkTransition[] ) { if (source === "user" && !isElectricalPhaseType(row.phaseType)) { throw new Error("Device-row phase type is invalid."); @@ -107,17 +121,23 @@ export class CircuitDeviceRowStructureProjectCommandRepository } updateDerivedCircuitVoltage(database, projectId, row.circuitId); - return createCircuitDeviceRowDeleteProjectCommand( - row.id, - row.circuitId - ); + if (externalObjects.length > 0) { + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Wiederherstellen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Wiederherstellen geändert."); + } + + return { + forward: createCircuitDeviceRowInsertProjectCommand(row, externalObjects), + inverse: createCircuitDeviceRowDeleteProjectCommand(row.id, row.circuitId, invertExternalObjectLinkTransitions(externalObjects)), + }; } private delete( database: AppDatabase, projectId: string, rowId: string, - expectedCircuitId: string + expectedCircuitId: string, + suppliedExternalObjects?: ExternalObjectLinkTransition[] ) { const row = database .select() @@ -130,6 +150,10 @@ export class CircuitDeviceRowStructureProjectCommandRepository ); } this.assertCircuitInProject(database, projectId, row.circuitId); + const externalObjects = suppliedExternalObjects ?? + captureExternalObjectDetachTransitions(database, projectId, [rowId]); + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Löschen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Löschen geändert."); const result = database .delete(circuitDeviceRows) @@ -164,9 +188,10 @@ export class CircuitDeviceRowStructureProjectCommandRepository expectedCircuitId ); - return createCircuitDeviceRowInsertProjectCommand( - toCircuitDeviceRowSnapshot(row) - ); + return { + forward: createCircuitDeviceRowDeleteProjectCommand(rowId, expectedCircuitId, externalObjects), + inverse: createCircuitDeviceRowInsertProjectCommand(toCircuitDeviceRowSnapshot(row), invertExternalObjectLinkTransitions(externalObjects)), + }; } private assertCircuitInProject( diff --git a/src/db/repositories/circuit-group-subtree-project-command.repository.ts b/src/db/repositories/circuit-group-subtree-project-command.repository.ts index 9bf27a0..b4baeb6 100644 --- a/src/db/repositories/circuit-group-subtree-project-command.repository.ts +++ b/src/db/repositories/circuit-group-subtree-project-command.repository.ts @@ -25,8 +25,14 @@ import { circuits } from "../schema/circuits.js"; import { distributionBoardComponentProtectionDevices } from "../schema/distribution-board-component-protection-devices.js"; import { distributionBoardComponents } from "../schema/distribution-board-components.js"; import { toCircuitDeviceRowInsertValues } from "./circuit-device-row-structure.persistence.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { executeProjectCommandTransactionWithAppliedForward, type AppliedProjectCommand } from "./project-command-transaction.persistence.js"; import { assertCircuitsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; +import { + applyExternalObjectLinks, + captureExternalObjectDetachTransitions, + invertExternalObjectLinkTransitions, + loadExpectedExternalObjectTransitions, +} from "./external-object-assignment.persistence.js"; export class CircuitGroupSubtreeProjectCommandRepository implements CircuitGroupSubtreeProjectCommandStore @@ -43,7 +49,11 @@ export class CircuitGroupSubtreeProjectCommandRepository } else { assertCircuitGroupRestoreSubtreeProjectCommand(input.command); } - return executeProjectCommandTransaction( + return executeProjectCommandTransactionWithAppliedForward< + CircuitGroupSubtreeProjectCommand, + CircuitGroupSubtreeProjectCommand, + CircuitGroupSubtreeProjectCommand + >( this.database, input, (tx) => this.applyCommand(tx, input.projectId, input.command) @@ -54,7 +64,7 @@ export class CircuitGroupSubtreeProjectCommandRepository database: AppDatabase, projectId: string, command: CircuitGroupSubtreeProjectCommand - ) { + ): AppliedProjectCommand { if (command.type === circuitGroupDeleteSubtreeCommandType) { const current = this.captureFrom( database, @@ -71,6 +81,14 @@ export class CircuitGroupSubtreeProjectCommandRepository projectId, current.circuits.map((entry) => entry.circuit.id) ); + const externalObjects = command.payload.externalObjects ?? + captureExternalObjectDetachTransitions( + database, + projectId, + current.circuits.flatMap((entry) => entry.circuit.deviceRows.map((row) => row.id)) + ); + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Löschen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Löschen geändert."); const deleted = database .delete(circuitSections) .where(eq(circuitSections.id, current.group.id)) @@ -78,15 +96,20 @@ export class CircuitGroupSubtreeProjectCommandRepository if (deleted.changes !== 1) { throw new Error("Circuit-group subtree could not be deleted."); } - return createCircuitGroupRestoreSubtreeProjectCommand( - command.payload.snapshot - ); + return { + forward: createCircuitGroupDeleteSubtreeProjectCommand(command.payload.snapshot, externalObjects), + inverse: createCircuitGroupRestoreSubtreeProjectCommand(command.payload.snapshot, invertExternalObjectLinkTransitions(externalObjects)), + }; } if (command.type === circuitGroupRestoreSubtreeCommandType) { this.restore(database, projectId, command.payload.snapshot); - return createCircuitGroupDeleteSubtreeProjectCommand( - command.payload.snapshot - ); + const externalObjects = command.payload.externalObjects ?? []; + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Wiederherstellen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Wiederherstellen geändert."); + return { + forward: createCircuitGroupRestoreSubtreeProjectCommand(command.payload.snapshot, externalObjects), + inverse: createCircuitGroupDeleteSubtreeProjectCommand(command.payload.snapshot, invertExternalObjectLinkTransitions(externalObjects)), + }; } throw new Error("Unsupported circuit-group subtree command."); } diff --git a/src/db/repositories/circuit-structure-project-command.repository.ts b/src/db/repositories/circuit-structure-project-command.repository.ts index 4841616..f4fc420 100644 --- a/src/db/repositories/circuit-structure-project-command.repository.ts +++ b/src/db/repositories/circuit-structure-project-command.repository.ts @@ -25,10 +25,17 @@ import { toCircuitDeviceRowInsertValues, toCircuitDeviceRowSnapshot, } from "./circuit-device-row-structure.persistence.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { executeProjectCommandTransactionWithAppliedForward, type AppliedProjectCommand } from "./project-command-transaction.persistence.js"; import { assertCircuitsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; import { resolveCircuitVoltage } from "./project-voltage.persistence.js"; import { assertEquipmentIdentifierAvailable } from "./equipment-identifier-uniqueness.persistence.js"; +import { + applyExternalObjectLinks, + captureExternalObjectDetachTransitions, + invertExternalObjectLinkTransitions, + loadExpectedExternalObjectTransitions, + type ExternalObjectLinkTransition, +} from "./external-object-assignment.persistence.js"; export class CircuitStructureProjectCommandRepository implements CircuitStructureProjectCommandStore @@ -36,11 +43,15 @@ export class CircuitStructureProjectCommandRepository constructor(private readonly database: AppDatabase) {} execute(input: ExecuteCircuitStructureCommandInput) { - return executeProjectCommandTransaction( + return executeProjectCommandTransactionWithAppliedForward< + CircuitStructureProjectCommand, + CircuitStructureProjectCommand, + CircuitStructureProjectCommand + >( this.database, input, (tx) => - this.applyInTransaction( + this.applyWithForward( tx, input.projectId, input.source, @@ -59,13 +70,23 @@ export class CircuitStructureProjectCommandRepository source: ExecuteCircuitStructureCommandInput["source"], command: CircuitStructureProjectCommand ): CircuitStructureProjectCommand { + return this.applyWithForward(database, projectId, source, command).inverse; + } + + private applyWithForward( + database: AppDatabase, + projectId: string, + source: ExecuteCircuitStructureCommandInput["source"], + command: CircuitStructureProjectCommand + ): AppliedProjectCommand { if (command.type === circuitInsertCommandType) { assertCircuitInsertProjectCommand(command); return this.insert( database, projectId, source, - command.payload.circuit + command.payload.circuit, + command.payload.externalObjects ?? [] ); } if (command.type === circuitDeleteCommandType) { @@ -74,7 +95,8 @@ export class CircuitStructureProjectCommandRepository database, projectId, command.payload.circuitId, - command.payload.expectedCircuitListId + command.payload.expectedCircuitListId, + command.payload.externalObjects ); } throw new Error("Unsupported circuit structure command."); @@ -84,7 +106,8 @@ export class CircuitStructureProjectCommandRepository database: AppDatabase, projectId: string, source: ExecuteCircuitStructureCommandInput["source"], - snapshot: CircuitSnapshot + snapshot: CircuitSnapshot, + externalObjects: ExternalObjectLinkTransition[] ) { this.assertCircuitLocation(database, projectId, snapshot); if (source === "user") { @@ -172,17 +195,23 @@ export class CircuitStructureProjectCommandRepository .run(); } - return createCircuitDeleteProjectCommand( - snapshot.id, - snapshot.circuitListId - ); + if (externalObjects.length > 0) { + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Wiederherstellen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Wiederherstellen geändert."); + } + + return { + forward: createCircuitInsertProjectCommand(snapshot, externalObjects), + inverse: createCircuitDeleteProjectCommand(snapshot.id, snapshot.circuitListId, invertExternalObjectLinkTransitions(externalObjects)), + }; } private delete( database: AppDatabase, projectId: string, circuitId: string, - expectedCircuitListId: string + expectedCircuitListId: string, + suppliedExternalObjects?: ExternalObjectLinkTransition[] ) { const circuit = database .select() @@ -220,7 +249,12 @@ export class CircuitStructureProjectCommandRepository .from(circuitProtectionDevices) .where(eq(circuitProtectionDevices.circuitId, circuit.id)) .get(); - const inverse = createCircuitInsertProjectCommand({ + const externalObjects = suppliedExternalObjects ?? captureExternalObjectDetachTransitions( + database, projectId, rows.map((row) => row.id) + ); + loadExpectedExternalObjectTransitions(database, projectId, externalObjects, "Revit-Objekt wurde vor dem Löschen geändert."); + applyExternalObjectLinks(database, externalObjects, "Revit-Objekt wurde beim Löschen geändert."); + const circuitSnapshot: CircuitSnapshot = { id: circuit.id, circuitListId: circuit.circuitListId, sectionId: circuit.sectionId, @@ -239,7 +273,7 @@ export class CircuitStructureProjectCommandRepository remark: circuit.remark, deviceRows: rows.map(toCircuitDeviceRowSnapshot), protectionDevice: protectionDevice ?? null, - }); + }; assertCircuitsAreNotReferencedAsFeeders(database, projectId, [circuit.id]); @@ -255,7 +289,10 @@ export class CircuitStructureProjectCommandRepository if (result.changes !== 1) { throw new Error("Circuit could not be deleted."); } - return inverse; + return { + forward: createCircuitDeleteProjectCommand(circuitId, expectedCircuitListId, externalObjects), + inverse: createCircuitInsertProjectCommand(circuitSnapshot, invertExternalObjectLinkTransitions(externalObjects)), + }; } private assertCircuitLocation( diff --git a/src/db/repositories/distribution-board-structure-project-command.repository.ts b/src/db/repositories/distribution-board-structure-project-command.repository.ts index 115705b..f7003c5 100644 --- a/src/db/repositories/distribution-board-structure-project-command.repository.ts +++ b/src/db/repositories/distribution-board-structure-project-command.repository.ts @@ -46,6 +46,7 @@ import { floors } from "../schema/floors.js"; import { projects } from "../schema/projects.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; import { assertBoardsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; +import { assertDistributionBoardHasNoExternalObjects } from "./external-object-deletion-guard.persistence.js"; import { CircuitStructureProjectCommandRepository } from "./circuit-structure-project-command.repository.js"; export class DistributionBoardStructureProjectCommandRepository @@ -290,6 +291,7 @@ export class DistributionBoardStructureProjectCommandRepository } assertBoardsAreNotReferencedAsFeeders(database, projectId, [board.id]); + assertDistributionBoardHasNoExternalObjects(database, projectId, board.id); const deleted = database .delete(distributionBoards) diff --git a/src/db/repositories/distribution-board-subtree-project-command.repository.ts b/src/db/repositories/distribution-board-subtree-project-command.repository.ts index 969c287..b32fee5 100644 --- a/src/db/repositories/distribution-board-subtree-project-command.repository.ts +++ b/src/db/repositories/distribution-board-subtree-project-command.repository.ts @@ -33,6 +33,7 @@ import { rooms } from "../schema/rooms.js"; import { toCircuitDeviceRowInsertValues } from "./circuit-device-row-structure.persistence.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; import { assertBoardsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; +import { assertDistributionBoardHasNoExternalObjects } from "./external-object-deletion-guard.persistence.js"; export class DistributionBoardSubtreeProjectCommandRepository implements DistributionBoardSubtreeProjectCommandStore @@ -86,6 +87,7 @@ export class DistributionBoardSubtreeProjectCommandRepository assertBoardsAreNotReferencedAsFeeders(database, projectId, [ current.distributionBoard.id, ]); + assertDistributionBoardHasNoExternalObjects(database, projectId, current.distributionBoard.id); const deleted = database .delete(distributionBoards) .where( diff --git a/src/db/repositories/external-object-assignment.persistence.ts b/src/db/repositories/external-object-assignment.persistence.ts index 1111730..505481d 100644 --- a/src/db/repositories/external-object-assignment.persistence.ts +++ b/src/db/repositories/external-object-assignment.persistence.ts @@ -11,6 +11,27 @@ export interface ExternalObjectLinkTransition { target: ExternalModelObjectSnapshot; } +export function captureExternalObjectDetachTransitions( + database: AppDatabase, + projectId: string, + rowIds: string[] +): ExternalObjectLinkTransition[] { + if (rowIds.length === 0) return []; + return database.select().from(externalModelObjects) + .where(and( + eq(externalModelObjects.projectId, projectId), + inArray(externalModelObjects.circuitDeviceRowId, rowIds) + )).all() + .map(toExternalObjectSnapshot) + .map((expected) => ({ expected, target: { ...expected, circuitDeviceRowId: null } })); +} + +export function invertExternalObjectLinkTransitions( + transitions: ExternalObjectLinkTransition[] +): ExternalObjectLinkTransition[] { + return transitions.map(({ expected, target }) => ({ expected: target, target: expected })); +} + export function loadExpectedExternalObjectTransitions( database: AppDatabase, projectId: string, @@ -86,7 +107,13 @@ export function applyExternalObjectLinks( ) { for (const { expected, target } of transitions) { const updated = database.update(externalModelObjects) - .set({ circuitDeviceRowId: target.circuitDeviceRowId }) + .set({ + circuitDeviceRowId: target.circuitDeviceRowId, + distributionBoardId: target.distributionBoardId, + linkedProjectDeviceId: target.linkedProjectDeviceId, + planningValues: target.planningValues, + overriddenFields: target.overriddenFields, + }) .where(and( eq(externalModelObjects.id, expected.id), expected.circuitDeviceRowId === null diff --git a/src/db/repositories/external-object-deletion-guard.persistence.ts b/src/db/repositories/external-object-deletion-guard.persistence.ts new file mode 100644 index 0000000..45fdac7 --- /dev/null +++ b/src/db/repositories/external-object-deletion-guard.persistence.ts @@ -0,0 +1,37 @@ +import { and, eq } from "drizzle-orm"; +import type { AppDatabase } from "../database-context.js"; +import { externalModelObjects } from "../schema/external-model-objects.js"; +import { externalRoomMappings } from "../schema/external-room-mappings.js"; + +export function assertDistributionBoardHasNoExternalObjects( + database: AppDatabase, + projectId: string, + distributionBoardId: string +) { + const reference = database.select({ id: externalModelObjects.id }) + .from(externalModelObjects) + .where(and( + eq(externalModelObjects.projectId, projectId), + eq(externalModelObjects.distributionBoardId, distributionBoardId) + )).limit(1).get(); + if (reference) { + throw new Error("Der Verteiler kann nicht gelöscht werden, solange Revit-Objekte auf ihn verweisen."); + } +} + +export function assertRoomHasNoExternalObjects( + database: AppDatabase, + projectId: string, + roomId: string +) { + const reference = database.select({ id: externalModelObjects.id }) + .from(externalModelObjects) + .innerJoin(externalRoomMappings, eq(externalRoomMappings.id, externalModelObjects.externalRoomMappingId)) + .where(and( + eq(externalModelObjects.projectId, projectId), + eq(externalRoomMappings.roomId, roomId) + )).limit(1).get(); + if (reference) { + throw new Error("Der Raum kann nicht gelöscht werden, solange Revit-Objekte auf ihn verweisen."); + } +} diff --git a/src/db/repositories/project-location-structure-project-command.repository.ts b/src/db/repositories/project-location-structure-project-command.repository.ts index 51edb3b..40a1743 100644 --- a/src/db/repositories/project-location-structure-project-command.repository.ts +++ b/src/db/repositories/project-location-structure-project-command.repository.ts @@ -46,6 +46,7 @@ import { distributionBoards } from "../schema/distribution-boards.js"; import { projects } from "../schema/projects.js"; import { rooms } from "../schema/rooms.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; +import { assertRoomHasNoExternalObjects } from "./external-object-deletion-guard.persistence.js"; export class ProjectLocationStructureProjectCommandRepository implements ProjectLocationStructureProjectCommandStore @@ -439,6 +440,7 @@ export class ProjectLocationStructureProjectCommandRepository "Der Raum kann nicht gelöscht werden, solange er in einem Stromkreis verwendet wird." ); } + assertRoomHasNoExternalObjects(database, projectId, expected.id); const deleted = database .delete(rooms) .where( diff --git a/src/domain/models/circuit-device-row-structure-project-command.model.ts b/src/domain/models/circuit-device-row-structure-project-command.model.ts index 2464a27..ebba5ac 100644 --- a/src/domain/models/circuit-device-row-structure-project-command.model.ts +++ b/src/domain/models/circuit-device-row-structure-project-command.model.ts @@ -1,4 +1,11 @@ import type { SerializedProjectCommand } from "./project-command.model.js"; +import type { ExternalModelObjectSnapshot } from "../../external-model/domain/external-model-contracts.js"; +import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; + +export interface ExternalObjectLinkSnapshotTransition { + expected: ExternalModelObjectSnapshot; + target: ExternalModelObjectSnapshot; +} export const circuitDeviceRowInsertCommandType = "circuit-device-row.insert" as const; @@ -32,11 +39,13 @@ export interface CircuitDeviceRowSnapshot { export interface CircuitDeviceRowInsertCommandPayload { row: CircuitDeviceRowSnapshot; + externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeviceRowDeleteCommandPayload { rowId: string; expectedCircuitId: string; + externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeviceRowInsertProjectCommand @@ -56,7 +65,8 @@ export type CircuitDeviceRowStructureProjectCommand = | CircuitDeviceRowDeleteProjectCommand; export function createCircuitDeviceRowInsertProjectCommand( - row: CircuitDeviceRowSnapshot + row: CircuitDeviceRowSnapshot, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitDeviceRowInsertProjectCommand { const normalizedRow = { ...row, @@ -65,7 +75,7 @@ export function createCircuitDeviceRowInsertProjectCommand( const command: CircuitDeviceRowInsertProjectCommand = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowInsertCommandType, - payload: { row: normalizedRow }, + payload: { row: normalizedRow, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitDeviceRowInsertProjectCommand(command); return command; @@ -73,12 +83,13 @@ export function createCircuitDeviceRowInsertProjectCommand( export function createCircuitDeviceRowDeleteProjectCommand( rowId: string, - expectedCircuitId: string + expectedCircuitId: string, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitDeviceRowDeleteProjectCommand { const command: CircuitDeviceRowDeleteProjectCommand = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowDeleteCommandType, - payload: { rowId, expectedCircuitId }, + payload: { rowId, expectedCircuitId, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitDeviceRowDeleteProjectCommand(command); return command; @@ -143,6 +154,7 @@ export function assertCircuitDeviceRowInsertProjectCommand( throw new Error("row.cosPhi must be positive or null."); } } + assertExternalObjectLinkTransitions(command.payload.externalObjects); } export function assertCircuitDeviceRowDeleteProjectCommand( @@ -163,6 +175,41 @@ export function assertCircuitDeviceRowDeleteProjectCommand( command.payload.expectedCircuitId, "expectedCircuitId" ); + assertExternalObjectLinkTransitions(command.payload.externalObjects); +} + +export function assertExternalObjectLinkTransitions(value: unknown) { + if (value === undefined) return; + if (!Array.isArray(value)) throw new Error("externalObjects must be an array."); + const ids = new Set(); + for (const transition of value) { + if (!isPlainObject(transition) || !isPlainObject(transition.expected) || !isPlainObject(transition.target)) { + throw new Error("Invalid external object link transition."); + } + const expectedId = transition.expected.id; + const targetId = transition.target.id; + if (typeof expectedId !== "string" || expectedId !== targetId || ids.has(expectedId)) { + throw new Error("External object link transition has mismatched or duplicate ids."); + } + ids.add(expectedId); + const expectedRowId = transition.expected.circuitDeviceRowId; + const targetRowId = transition.target.circuitDeviceRowId; + if ((expectedRowId !== null && typeof expectedRowId !== "string") || (targetRowId !== null && typeof targetRowId !== "string")) { + throw new Error("Invalid external object row link."); + } + const parsed = parseExternalModelStateSnapshot({ source: null, importBatches: [], roomMappings: [], objects: [transition.expected, transition.target] }).objects; + const expectedRest = { ...parsed[0], circuitDeviceRowId: null }; + const targetRest = { ...parsed[1], circuitDeviceRowId: null }; + if (canonicalJson(expectedRest) !== canonicalJson(targetRest) || expectedRowId === targetRowId) { + throw new Error("External object transition may only change the row link."); + } + } +} + +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (isPlainObject(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`; + return JSON.stringify(value) ?? "null"; } function assertNonEmptyString(value: unknown, field: string) { diff --git a/src/domain/models/circuit-group-subtree-project-command.model.ts b/src/domain/models/circuit-group-subtree-project-command.model.ts index a3e53b3..4470cd2 100644 --- a/src/domain/models/circuit-group-subtree-project-command.model.ts +++ b/src/domain/models/circuit-group-subtree-project-command.model.ts @@ -3,6 +3,7 @@ import { type CircuitGroupSubtreeSnapshot, } from "./circuit-group-subtree-snapshot.model.js"; import type { SerializedProjectCommand } from "./project-command.model.js"; +import { assertExternalObjectLinkTransitions, type ExternalObjectLinkSnapshotTransition } from "./circuit-device-row-structure-project-command.model.js"; export const circuitGroupDeleteSubtreeCommandType = "circuit-group.delete-subtree" as const; @@ -12,6 +13,7 @@ export const circuitGroupSubtreeCommandSchemaVersion = 1 as const; interface Payload { snapshot: CircuitGroupSubtreeSnapshot; + externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitGroupDeleteSubtreeProjectCommand @@ -31,24 +33,26 @@ export type CircuitGroupSubtreeProjectCommand = | CircuitGroupRestoreSubtreeProjectCommand; export function createCircuitGroupDeleteSubtreeProjectCommand( - snapshot: CircuitGroupSubtreeSnapshot + snapshot: CircuitGroupSubtreeSnapshot, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitGroupDeleteSubtreeProjectCommand { const command: CircuitGroupDeleteSubtreeProjectCommand = { schemaVersion: circuitGroupSubtreeCommandSchemaVersion, type: circuitGroupDeleteSubtreeCommandType, - payload: { snapshot }, + payload: { snapshot, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitGroupDeleteSubtreeProjectCommand(command); return command; } export function createCircuitGroupRestoreSubtreeProjectCommand( - snapshot: CircuitGroupSubtreeSnapshot + snapshot: CircuitGroupSubtreeSnapshot, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitGroupRestoreSubtreeProjectCommand { const command: CircuitGroupRestoreSubtreeProjectCommand = { schemaVersion: circuitGroupSubtreeCommandSchemaVersion, type: circuitGroupRestoreSubtreeCommandType, - payload: { snapshot }, + payload: { snapshot, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitGroupRestoreSubtreeProjectCommand(command); return command; @@ -76,11 +80,12 @@ function assertCommand( command.schemaVersion !== circuitGroupSubtreeCommandSchemaVersion || command.type !== type || !isPlainObject(command.payload) || - Object.keys(command.payload).length !== 1 + Object.keys(command.payload).some((key) => key !== "snapshot" && key !== "externalObjects") ) { throw new Error("Unsupported circuit-group subtree command."); } assertCircuitGroupSubtreeSnapshot(command.payload.snapshot); + assertExternalObjectLinkTransitions(command.payload.externalObjects); } function isPlainObject(value: unknown): value is Record { diff --git a/src/domain/models/circuit-structure-project-command.model.ts b/src/domain/models/circuit-structure-project-command.model.ts index 5260c4b..292c776 100644 --- a/src/domain/models/circuit-structure-project-command.model.ts +++ b/src/domain/models/circuit-structure-project-command.model.ts @@ -3,6 +3,8 @@ import { circuitDeviceRowInsertCommandType, circuitDeviceRowStructureCommandSchemaVersion, type CircuitDeviceRowSnapshot, + type ExternalObjectLinkSnapshotTransition, + assertExternalObjectLinkTransitions, } from "./circuit-device-row-structure-project-command.model.js"; import type { SerializedProjectCommand } from "./project-command.model.js"; import { @@ -37,11 +39,13 @@ export interface CircuitSnapshot { export interface CircuitInsertCommandPayload { circuit: CircuitSnapshot; + externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeleteCommandPayload { circuitId: string; expectedCircuitListId: string; + externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitInsertProjectCommand @@ -61,12 +65,13 @@ export type CircuitStructureProjectCommand = | CircuitDeleteProjectCommand; export function createCircuitInsertProjectCommand( - circuit: CircuitSnapshot + circuit: CircuitSnapshot, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitInsertProjectCommand { const command: CircuitInsertProjectCommand = { schemaVersion: circuitStructureCommandSchemaVersion, type: circuitInsertCommandType, - payload: { circuit }, + payload: { circuit, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitInsertProjectCommand(command); return command; @@ -74,12 +79,13 @@ export function createCircuitInsertProjectCommand( export function createCircuitDeleteProjectCommand( circuitId: string, - expectedCircuitListId: string + expectedCircuitListId: string, + externalObjects?: ExternalObjectLinkSnapshotTransition[] ): CircuitDeleteProjectCommand { const command: CircuitDeleteProjectCommand = { schemaVersion: circuitStructureCommandSchemaVersion, type: circuitDeleteCommandType, - payload: { circuitId, expectedCircuitListId }, + payload: { circuitId, expectedCircuitListId, ...(externalObjects?.length ? { externalObjects } : {}) }, }; assertCircuitDeleteProjectCommand(command); return command; @@ -168,6 +174,7 @@ export function assertCircuitInsertProjectCommand( } rowIds.add(row.id); } + assertExternalObjectLinkTransitions(command.payload.externalObjects); } export function assertCircuitDeleteProjectCommand( @@ -187,6 +194,7 @@ export function assertCircuitDeleteProjectCommand( command.payload.expectedCircuitListId, "expectedCircuitListId" ); + assertExternalObjectLinkTransitions(command.payload.externalObjects); } function assertNonEmptyString(value: unknown, field: string) { diff --git a/src/domain/models/circuit-tree.model.ts b/src/domain/models/circuit-tree.model.ts index 00a0c2d..fd1bd2c 100644 --- a/src/domain/models/circuit-tree.model.ts +++ b/src/domain/models/circuit-tree.model.ts @@ -20,6 +20,7 @@ export interface CircuitTreeDeviceRow { remark?: string; overriddenFields?: string; rowTotalPower: number; + externalObjectCount?: number; } export interface CircuitTreeCircuit { diff --git a/src/domain/models/external-object-new-circuit-project-command.model.ts b/src/domain/models/external-object-new-circuit-project-command.model.ts index b34a449..e7a3e23 100644 --- a/src/domain/models/external-object-new-circuit-project-command.model.ts +++ b/src/domain/models/external-object-new-circuit-project-command.model.ts @@ -146,8 +146,8 @@ function assertOnlyAssignmentChanged( expected: ExternalModelObjectSnapshot, target: ExternalModelObjectSnapshot ) { - const expectedRest = { ...expected, circuitDeviceRowId: null }; - const targetRest = { ...target, circuitDeviceRowId: null }; + const expectedRest = { ...expected, circuitDeviceRowId: null, distributionBoardId: null }; + const targetRest = { ...target, circuitDeviceRowId: null, distributionBoardId: null }; if (canonicalJson(expectedRest) !== canonicalJson(targetRest)) { throw new Error("New-circuit assignment may only change the external object row link."); } diff --git a/src/domain/models/external-object-new-row-project-command.model.ts b/src/domain/models/external-object-new-row-project-command.model.ts index d0416dd..6bae039 100644 --- a/src/domain/models/external-object-new-row-project-command.model.ts +++ b/src/domain/models/external-object-new-row-project-command.model.ts @@ -141,8 +141,8 @@ function assertOnlyAssignmentChanged( expected: ExternalModelObjectSnapshot, target: ExternalModelObjectSnapshot ) { - const expectedRest = { ...expected, circuitDeviceRowId: null }; - const targetRest = { ...target, circuitDeviceRowId: null }; + const expectedRest = { ...expected, circuitDeviceRowId: null, distributionBoardId: null }; + const targetRest = { ...target, circuitDeviceRowId: null, distributionBoardId: null }; if (canonicalJson(expectedRest) !== canonicalJson(targetRest)) { throw new Error("New-row assignment may only change the external object row link."); } diff --git a/src/domain/models/external-object-row-assignment-project-command.model.ts b/src/domain/models/external-object-row-assignment-project-command.model.ts index a45fe31..cb4ae97 100644 --- a/src/domain/models/external-object-row-assignment-project-command.model.ts +++ b/src/domain/models/external-object-row-assignment-project-command.model.ts @@ -104,10 +104,10 @@ export function assertExternalObjectRowAssignmentProjectCommand( if (expected.circuitDeviceRowId === target.circuitDeviceRowId) { throw new Error("External object row assignment must change its row link."); } - assertOnlyFieldChanged( + assertOnlyFieldsChanged( expected as unknown as Record, target as unknown as Record, - "circuitDeviceRowId", + new Set(["circuitDeviceRowId", "distributionBoardId", "linkedProjectDeviceId", "planningValues", "overriddenFields"]), "external object" ); if (expected.circuitDeviceRowId) affectedRowIds.add(expected.circuitDeviceRowId); @@ -161,11 +161,22 @@ function assertOnlyFieldChanged( target: Record, allowedField: string, label: string +) { + assertOnlyFieldsChanged(expected, target, new Set([allowedField]), label); +} + +function assertOnlyFieldsChanged( + expected: Record, + target: Record, + allowedFields: ReadonlySet, + label: string ) { const expectedRest = { ...expected }; const targetRest = { ...target }; - delete expectedRest[allowedField]; - delete targetRest[allowedField]; + for (const field of allowedFields) { + delete expectedRest[field]; + delete targetRest[field]; + } if (canonicalJson(expectedRest) !== canonicalJson(targetRest)) { throw new Error(`Row assignment may only change the ${label} assignment state.`); } diff --git a/src/frontend/components/circuit-tree-editor.tsx b/src/frontend/components/circuit-tree-editor.tsx index f75b64e..5418922 100644 --- a/src/frontend/components/circuit-tree-editor.tsx +++ b/src/frontend/components/circuit-tree-editor.tsx @@ -120,6 +120,11 @@ import { deleteCircuitGroupCommand, deleteCircuitGroupSubtreeCommand, deleteDistributionBoardComponentCommand, + assignExternalProjectObjectsToRow, + assignExternalProjectObjectsToNewRow, + assignExternalProjectObjectsToNewCircuit, + detachExternalProjectObjectsFromRow, + getExternalProjectObjects, getCircuitTree, getNextCircuitIdentifier, getProjectHistory, @@ -154,6 +159,7 @@ import type { ProjectCommandResultDto, ProjectDeviceDto, ProjectHistoryStateDto, + ExternalProjectObjectsDto, } from "../types"; import type { CircuitDeviceRowSnapshot, @@ -330,6 +336,9 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const [cableSizingEditorCircuit, setCableSizingEditorCircuit] = useState(null); const [projectDevices, setProjectDevices] = useState([]); + const [externalObjects, setExternalObjects] = useState(null); + const [isRevitDrawerOpen, setIsRevitDrawerOpen] = useState(false); + const [draggingExternalObjectIds, setDraggingExternalObjectIds] = useState([]); const [isProjectDeviceDrawerOpen, setIsProjectDeviceDrawerOpen] = useState(false); const [projectDeviceSearch, setProjectDeviceSearch] = useState(""); @@ -381,6 +390,26 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str () => orderedColumns.filter((column) => visibleColumnKeys.includes(column.key)), [orderedColumns, visibleColumnKeys] ); + const externalObjectGroups = useMemo(() => { + if (!data || !externalObjects) return []; + const groups = new Map(); + for (const object of externalObjects.objects) { + if (object.presenceStatus !== "present" || object.circuitDeviceRowId !== null || object.distributionBoardId !== data.distributionBoardId) continue; + const key = JSON.stringify([ + object.roomId, object.selectionMarker, object.deviceTypeId, + object.planningValues.category, object.linkedProjectDeviceId, + object.planningValues, + ]); + const entries = groups.get(key) ?? []; + entries.push(object); + groups.set(key, entries); + } + return [...groups.values()].map((objects) => ({ + key: objects.map((object) => object.id).sort().join("|"), + objects, + quantity: objects.reduce((sum, object) => sum + object.planningValues.effectiveQuantity, 0), + })); + }, [data, externalObjects]); async function loadTree(options?: { showLoading?: boolean }) { const showLoading = options?.showLoading ?? false; @@ -389,13 +418,17 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } setError(null); try { - const { tree, history } = await loadCircuitEditorSnapshot( - () => getCircuitTree(projectId, circuitListId), - () => getProjectHistory(projectId) - ); + const [{ tree, history }, external] = await Promise.all([ + loadCircuitEditorSnapshot( + () => getCircuitTree(projectId, circuitListId), + () => getProjectHistory(projectId) + ), + getExternalProjectObjects(projectId), + ]); projectRevisionRef.current = history.currentRevision; setHistoryState(history); setData(tree); + setExternalObjects(external); } catch (err) { setError(normalizeUiError(err)); } finally { @@ -1321,12 +1354,20 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const summary = subtree ? summarizeCircuitGroupSubtree(subtree) : null; + const externalObjectCount = section.circuits.reduce( + (total, circuit) => total + circuit.deviceRows.reduce( + (rowTotal, row) => rowTotal + (row.externalObjectCount ?? 0), 0 + ), 0 + ); + const externalWarning = externalObjectCount > 0 + ? `\n\n${externalObjectCount} Revit-Objekte werden wieder unzugeordnet.` + : ""; const warning = isEmpty ? `Leere Stromkreisgruppe „${section.displayName}“ entfernen?` : `Stromkreisgruppe „${section.displayName}“ vollständig entfernen?\n\n` + `Dabei werden ${summary!.circuitCount} Stromkreis(e), ${summary!.deviceRowCount} Gerätezeile(n) und ${summary!.protectionComponentCount} Gruppenschutzgerät(e) gelöscht.\n\n` + "Die Änderung kann über die projektweite Versionshistorie rückgängig gemacht werden."; - if (!confirm(warning)) { + if (!confirm(warning + externalWarning)) { return; } await runCommand({ @@ -2878,11 +2919,15 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str setError("Die Gerätezeile ist ungültig."); return; } + const externalWarning = (rowSnapshot.externalObjectCount ?? 0) > 0 + ? `\n\n${rowSnapshot.externalObjectCount} Revit-Objekte werden wieder unzugeordnet.` + : ""; if (sourceCircuit.deviceRows.length === 1) { const keepAsReserve = confirm( `„${rowSnapshot.displayName}“ ist das letzte Gerät in ${sourceCircuit.equipmentIdentifier}.\n\n` + "OK: Gerät löschen und den leeren Stromkreis als Reserve behalten.\n" + - "Abbrechen: anschließend entscheiden, ob stattdessen der gesamte Stromkreis gelöscht werden soll." + "Abbrechen: anschließend entscheiden, ob stattdessen der gesamte Stromkreis gelöscht werden soll." + + externalWarning ); if (!keepAsReserve) { const deleteCircuit = confirm( @@ -2894,7 +2939,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } return; } - } else if (!confirm(`Gerätezeile „${rowSnapshot.displayName}“ löschen?`)) { + } else if (!confirm(`Gerätezeile „${rowSnapshot.displayName}“ löschen?${externalWarning}`)) { return; } await runCommand({ @@ -2917,11 +2962,18 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str setError("Der Stromkreis ist ungültig."); return; } + const externalObjectCount = circuit.deviceRows.reduce( + (total, row) => total + (row.externalObjectCount ?? 0), 0 + ); + const externalWarning = externalObjectCount > 0 + ? `\n\n${externalObjectCount} Revit-Objekte werden wieder unzugeordnet.` + : ""; if ( askForConfirmation && !confirm( `Stromkreis ${circuit.equipmentIdentifier} und ${circuit.deviceRows.length} zugeordnete Gerätezeile(n) löschen?\n\n` + - "Bestehende Betriebsmittelkennzeichen werden nicht neu nummeriert." + "Bestehende Betriebsmittelkennzeichen werden nicht neu nummeriert." + + externalWarning ) ) { return; @@ -2958,6 +3010,56 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str await handleDeleteCircuit(intent.circuitId); } + async function handleAssignExternalObjects(rowId: string, objectIds: string[]) { + if (!confirm(`${objectIds.length} Revit-Objekt(e) dieser Gerätezeile zuordnen?\n\nAbweichende Planungswerte werden ausdrücklich zugunsten der Gerätezeile bestätigt.`)) return; + await runCommand({ + label: "Revit-Objekte zuordnen", + redo: async () => { + const result = await assignExternalProjectObjectsToRow( + projectId, + getExpectedProjectRevision(), + objectIds, + rowId, + objectIds + ); + applyProjectCommandResult(result); + setDraggingExternalObjectIds([]); + return null; + }, + }); + } + + async function handleAssignExternalObjectsToNewRow(circuitId: string, objectIds: string[]) { + if (!confirm(`${objectIds.length} Revit-Objekt(e) als neue Gerätezeile anlegen?`)) return; + await runCommand({ label: "Revit-Objekte als Gerätezeile zuordnen", redo: async () => { + const result = await assignExternalProjectObjectsToNewRow(projectId, getExpectedProjectRevision(), objectIds, circuitId); + applyProjectCommandResult(result); setDraggingExternalObjectIds([]); return null; + }}); + } + + async function handleAssignExternalObjectsToNewCircuit(sectionId: string, objectIds: string[]) { + if (!confirm(`${objectIds.length} Revit-Objekt(e) als neuen Stromkreis anlegen?`)) return; + await runCommand({ label: "Revit-Objekte als Stromkreis zuordnen", redo: async () => { + const result = await assignExternalProjectObjectsToNewCircuit(projectId, getExpectedProjectRevision(), objectIds, sectionId); + applyProjectCommandResult(result); setDraggingExternalObjectIds([]); return null; + }}); + } + + async function handleDetachExternalObjects(rowId: string) { + const objectIds = externalObjects?.objects + .filter((object) => object.circuitDeviceRowId === rowId) + .map((object) => object.id) ?? []; + if (objectIds.length === 0 || !confirm(`${objectIds.length} Revit-Objekt(e) lösen?\n\nDie aktuellen Werte der Gerätezeile werden als Planungswerte und Overrides übernommen.`)) return; + await runCommand({ + label: "Revit-Objekte lösen", + redo: async () => { + const result = await detachExternalProjectObjectsFromRow(projectId, getExpectedProjectRevision(), objectIds); + applyProjectCommandResult(result); + return null; + }, + }); + } + // Explicit renumber action through project history. Sorting and device rows // remain unchanged; the server handles collision-safe identifier swaps. async function handleRenumberSection(sectionId: string) { @@ -3381,6 +3483,15 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } showLabel /> + sum + group.objects.length, 0)})`} + onClick={() => setIsRevitDrawerOpen((current) => !current)} + showLabel + /> Wird gespeichert …
: null}
+ {isRevitDrawerOpen ? ( + + ) : null} {isProjectDeviceDrawerOpen ? (