diff --git a/AGENTS.md b/AGENTS.md index c00fd78..4485097 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -284,8 +284,13 @@ 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 5 additionally stores the manual quantity share -of every CircuitDeviceRow. Version 4 snapshots are upgraded with +Current snapshot schema version 6 additionally 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 6) +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 external-model source, import batches, room mappings and objects. Version 3 snapshots are upgraded with an empty external-model state; version 2 snapshots @@ -299,7 +304,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, restore and portable +delete, Undo and Redo are revision-safe. Snapshot schema 5/6, 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 @@ -313,7 +318,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 version 5 +to typed command adapters. Snapshot/restore and portable project transfer schema version 5/6 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 @@ -402,6 +407,10 @@ Project settings use the persistent `project.update-settings` command. Project metadata, the public-building classification, both voltage defaults and the enabled distribution-board supply types change in one revision and Undo/Redo restores them together; the project PUT route requires `expectedRevision`. +Schema version 3 additionally carries the print cover fields `siteAddress`, +`workStage`, `projectLead` and `projectEditor` (migration `0008`); version 2 +(without them) and baseline version 1 stay executable and keep the current +cover values. The PUT route accepts the cover fields optionally. The public-building flag is the future sizing input for requiring halogen-free cables and lines. The system catalog is `AV`, `SV`, `EV`, `USV`, `MSR`, `SiBe`; at least one must be enabled and a type used by a board @@ -456,6 +465,18 @@ the only supported circuit-protection source; no flat compatibility fields remai 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 +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. +These fields are intended to be prefillable from Revit parameters later, but +only through the Phase 14 rules (preview, explicit confirmation, no silent +overwrite). Floor and room setup uses persistent insert, update and delete commands with complete stable snapshots. Their inverses remove or restore only unchanged records and reject floors with assigned rooms/distribution boards or rooms referenced by @@ -477,6 +498,35 @@ Required operations: - synchronization changes +## Print View (Seitenansicht) + +- Route `src/app/projects/[projectId]/print/page.tsx`, opened from the project + page button "Seitenansicht". Read-only: it only uses existing GET endpoints. +- Pure read model `src/frontend/print/print-document-model.ts` (tested in + `tests/print-document-model.test.ts`); React sheets in + `src/frontend/print/print-document.tsx`; styles scoped to `.print-view` in + `src/frontend/print/print-document.css`. +- Pages: cover (A4 portrait, tabular), board overview with structure and + power sums, one plan per board (A4/A3 landscape) whose title block sits in + `` 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. +- 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 + `projectEditor` because snapshots do not record an editor. +- The document logo and the office profile (office name/address on the + cover) are global office branding: tables `document_branding_assets` + (migration `0007`) and `document_branding_settings` (migration `0008`), + endpoints `GET|PUT|DELETE /api/document-branding/logo`, + `PUT /api/document-branding/office` and `GET /api/document-branding`. + It is intentionally outside project revisions, snapshots and transfer. + 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 When explicitly working on Phase 14, use @@ -572,6 +622,9 @@ Users must be able to override sizing suggestions. - 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 Do not implement these while working on an unrelated phase. diff --git a/README.md b/README.md index 55c4f65..2577989 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ Objektzuordnung, Folgeimporte und Rückexport stehen noch aus. - Änderungen projektweit und auch nach einem Reload rückgängig machen und wiederholen - benannte Sicherungspunkte anlegen, wiederherstellen und Revisionen einsehen - automatische Sicherungspunkte mit begrenzter Aufbewahrung nutzen +- Seitenansicht mit Deckblatt, Verteilerübersicht und Verteilerplänen öffnen + und über den Browser als PDF drucken; Büroangaben und Logo zentral pflegen - 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 @@ -147,6 +149,7 @@ vor der Baseline werden nicht unterstützt. - [Aktuelle Architektur](docs/current-architecture.md) - [Editor-Interaktionen](docs/circuit-list-editor-interactions.md) - [API des Stromkreislisten-Editors](docs/circuit-list-editor-api.md) +- [Seitenansicht und PDF-Export](docs/print-view.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/docs/README.md b/docs/README.md index 69a2115..395b1ac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,8 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we fachliches Modell und Grid-Aufteilung - [Editor-Interaktionen](circuit-list-editor-interactions.md) – Tastatur, Drag-and-drop, Sortierung, Filterung und Undo/Redo +- [Seitenansicht und PDF-Export](print-view.md) – Deckblatt, + Verteilerübersicht, Verteilerpläne, Büro-Logo - [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 9ed9e0a..d325944 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -74,8 +74,9 @@ Protected-board structure uses persisted inverse of a delete. The dispatcher also supports the documented project-device, project settings, distribution-board and project-location commands. The generic editor commands listed here use schema version `1`. -`project.update-settings` uses version `2` and still accepts supported baseline -version `1` commands without changing the newer building classification. +`project.update-settings` uses version `3` (including the print cover fields) +and still accepts version `2` and supported baseline version `1` commands +without changing the newer cover fields or building classification. Pre-baseline formats remain unsupported. Unsupported types or schema versions are rejected. Insert commands contain the complete entity or circuit block with stable ids; delete commands include the expected parent identity. Circuit @@ -173,6 +174,9 @@ synchronizes linked circuit rows implicitly. - `PUT /projects/:projectId` - request: `{ "expectedRevision": 12, "isPublicBuilding": true, "singlePhaseVoltageV": 230, "threePhaseVoltageV": 400, "enabledDistributionBoardSupplyTypes": ["AV", "MSR", "SiBe"], ...projectMetadata }` + - optional print cover fields `siteAddress` (max. 500), `workStage` (max. + 100), `projectLead` and `projectEditor` (max. 200 each); omitted fields keep + their value, empty strings are stored as `null` - executes `project.update-settings` as one atomic revision - response: `{ "project": { ... }, "revision": { ... }, "history": { ... } }` @@ -230,9 +234,13 @@ returns HTTP `409` with `PROJECT_HISTORY_OPERATION_UNAVAILABLE`. - stale revisions return `409 PROJECT_REVISION_CONFLICT` - `PUT /projects/:projectId/distribution-boards/:distributionBoardId` - body: - `{ "floorId": null, "supplyType": "AV", "expectedRevision": 13 }` - - executes `distribution-board.update`; floor and supply type are restored - together by persistent Undo/Redo + `{ "floorId": null, "supplyType": "AV", "simultaneityFactor": 1, "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 + submitted info fields, are restored together by persistent Undo/Redo + - `fedFrom` is free text until the logical feed link is modeled - `POST /projects/:projectId/distribution-boards/:distributionBoardId/copy` - body: `{ "name": "UV-02 Kopie", "expectedRevision": 14 }` - duplicates the complete distribution-board subtree with new owning UUIDs @@ -425,3 +433,27 @@ project device never triggers synchronization implicitly. Parser errors expose stable codes such as `header-not-found`, `ambiguous-header`, `invalid-ifc-guid` and `duplicate-ifc-guid`. The confirmed import uploads and parses the file again and verifies its hash. + +## Document Branding (print view) + +Office-wide branding for the print view. These endpoints are mounted at +`/api/document-branding`, outside `/api/projects`, because the data is global +and intentionally not part of project revisions, snapshots or transfer. + +- `GET /document-branding` + - returns `{ "logo": { "mimeType", "fileName", "sizeBytes", "updatedAtIso" } | null, "office": { "officeName", "officeAddress" } }` +- `GET /document-branding/logo` + - returns the stored image bytes with its media type, or `404` without logo + - responses carry `X-Content-Type-Options: nosniff` and a restrictive + Content-Security-Policy so an SVG logo cannot execute scripts +- `PUT /document-branding/logo` + - request: `{ "fileName": "logo.png", "mimeType": "image/png", "contentBase64": "..." }` + - accepted types: `image/png`, `image/jpeg`, `image/svg+xml`; at most 2 MB + after decoding; the content signature must match the declared type + - replaces an existing logo; returns the logo metadata +- `DELETE /document-branding/logo` + - removes the logo; returns `204` +- `PUT /document-branding/office` + - request: `{ "officeName": "…" | null, "officeAddress": "…" | null }` + (at most 200 / 500 characters; empty text is stored as not set) + - returns `{ "office": { "officeName", "officeAddress" } }` diff --git a/docs/circuit-list-editor-known-limitations.md b/docs/circuit-list-editor-known-limitations.md index 4f7f660..3e70e76 100644 --- a/docs/circuit-list-editor-known-limitations.md +++ b/docs/circuit-list-editor-known-limitations.md @@ -27,3 +27,12 @@ - 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`). +- 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 + board plans are not split into pages; pagination happens in the browser print + dialog. diff --git a/docs/current-architecture.md b/docs/current-architecture.md index ab223bd..06e4b06 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -241,8 +241,9 @@ und Historienstapel teilen dieselbe Transaktion. Create, Import aus der globalen Gerätebibliothek und Delete laufen über dieselbe Command-Grenze; ihre Antworten liefern Gerät und aktualisierten Historienstand an die Projektseite zurück. `project.update-settings` versioniert Projektname, interne und externe -Projektnummer, Bauherr, Beschreibung, die Kennzeichnung als öffentliches -Gebäude, beide Standardspannungen sowie die im Projekt freigeschalteten +Projektnummer, Bauherr, Beschreibung, die Deckblattangaben (Anschrift, +Leistungsphase, Projektleitung, Bearbeitung; Schema-Version 3, Migration +`0008`), die Kennzeichnung als öffentliches Gebäude, beide Standardspannungen sowie die im Projekt freigeschalteten Verteiler-Netzarten als eine atomare Änderung. Die Gebäudekennzeichnung ist der spätere Eingang für die Auswahl halogenfreier Kabel und Leitungen. Der Systemkatalog besteht aus `AV`, `SV`, `EV`, `USV`, `MSR` und `SiBe`; mindestens @@ -271,7 +272,8 @@ Die allgemeinen Anwendungskarten verwenden in `src/app/globals.css` einen gleichmäßigen Rahmen, 16-px-Rundungen und einen Schatten mit eigener Dark-Mode-Abstimmung. Bootstrap-Karten mit `shadow-sm` nutzen denselben Schatten; der Stromkreis-Grid bleibt eine eigenständige Komponente. -Die Verteilersuche berücksichtigt aktuell Name und Etagenname; die Gerätesuche +Die Verteilersuche berücksichtigt Name, Verteilernummer, Örtlichkeit und +Etagenname; die Gerätesuche Name, Anzeigename, Kategorie einschließlich deutscher Bezeichnung, Anschlussart und Kostengruppe. Der Gerätefilter „Anschluss“ wählt zwischen 1- und 3-phasig. Mehrere Werte innerhalb eines Filters gelten alternativ, verschiedene Filter @@ -450,7 +452,14 @@ wieder her. verteilerweiten Gleichzeitigkeitsfaktor gemeinsam und stellt alle Werte über dauerhaftes Undo/Redo wieder her. Der Faktor liegt zwischen `0` und `1` und ist für bestehende sowie neu angelegte Verteilungen standardmäßig `1`. -Snapshot-Schema 5 enthält zusätzlich den manuellen Mengenanteil jeder +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 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 @@ -520,7 +529,7 @@ Kopieren in ein Projekt erzeugt ein eigenständiges Projektgerät. `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 5. Persistente + Transfer-Integration verwenden aktuell Snapshot-Schema 6. 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 @@ -548,7 +557,7 @@ einschließlich BOM, CRLF und Quotierung bytegleich zurück. Der lokale Befehl `external_csv_configurations` enthält höchstens eine versionierte Konfiguration je Projekt. `external-csv-configuration.update` schreibt Anlage, Änderung oder -Entfernung zusammen mit Revision und persistentem Undo/Redo. Snapshot-Schema 5, +Entfernung zusammen mit Revision und persistentem Undo/Redo. Snapshot-Schema 6, Restore und portabler Projekttransfer enthalten diesen Zustand; beim Duplizieren werden Konfigurations-UUID und Projektlink remapped. diff --git a/docs/print-view.md b/docs/print-view.md new file mode 100644 index 0000000..eba91ed --- /dev/null +++ b/docs/print-view.md @@ -0,0 +1,127 @@ +# Seitenansicht und PDF-Export + +Die Seitenansicht ist rein lesend und verändert keine Projektdaten. +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 +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. + +## Aufruf + +- Projektseite → Button **Seitenansicht** öffnet + `/projects/:projectId/print` in einem neuen Tab. +- **Als PDF speichern / Drucken** nutzt den Druckdialog des Browsers + (Ziel „Als PDF speichern“). Der Dokumenttitel `Leistungsbilanz – ` + wird als Dateiname vorgeschlagen. +- **Planformat** schaltet die Verteilerpläne zwischen A4 quer und A3 quer um. + Deckblatt bleibt A4 hoch. +- **Büroangaben** pflegt Büroname und Büroanschrift (Planverfasser, für alle + Projekte). +- **Logo hinterlegen / ersetzen / entfernen** verwaltet das Büro-Logo. + +## Seiten + +1. **Deckblatt (A4 hoch)** – tabellarisch: Projekt, Planverfasser, Dokument, + Planstände (aus benannten Sicherungspunkten) und Inhalt. Leere Angaben + 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“. +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), + Gruppensummen und Verteilersumme. Fehlende Kabelangaben sind als „offen“ + markiert. Die Titelleiste steht im Tabellenkopf und wiederholt sich beim + Drucken auf Folgeseiten. + +Seitenformat, Ränder und „Seite x von y“ kommen beim Drucken aus benannten +`@page`-Regeln (`lb-portrait`, `lb-landscape`), die die Seite zur Laufzeit +einfügt. Die Bildschirmansicht zeigt Blätter in Papiergröße; die exakte +Seitenaufteilung langer Verteilerpläne entsteht erst beim Drucken. + +## Vorläufige 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. +- **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 + CD-Vorgabe ersetzt, falls diese abweicht. +- **Planstände:** Die Spalte „Bearbeitung“ zeigt für jeden Planstand die + aktuelle Bearbeitung aus den Projekteinstellungen, weil Sicherungspunkte + (noch) keinen Bearbeiter speichern. + +## Datenquellen des Deckblatts + +| Feld | Quelle | +|---|---| +| Bauvorhaben, Bauherr, Projektnummern, Beschreibung | Projekteinstellungen | +| Anschrift Bauvorhaben, Leistungsphase, Projektleitung, Bearbeitung | Projekteinstellungen → Abschnitt „Deckblatt“ (`siteAddress`, `workStage`, `projectLead`, `projectEditor`) | +| Büro, Anschrift Büro | Seitenansicht → „Büroangaben“ (global) | +| Stand, Datenstand, Anzahl Verteiler, Inhalt | automatisch | +| Planstände | benannte Sicherungspunkte | + +Die vier Projektfelder laufen über `project.update-settings` (Schema-Version +3, Migration `0008`) und sind Teil von Snapshot-Schema 6 und Projektexport. +Im `PUT /api/projects/:projectId` sind sie optional; fehlende Felder behalten +ihren Wert. + +## Büroangaben + +- Tabelle `document_branding_settings` (Schlüssel/Wert, Migration `0008`), + global wie das Logo. +- `GET /api/document-branding` liefert zusätzlich + `office: { officeName, officeAddress }`. +- `PUT /api/document-branding/office` mit `{ "officeName", "officeAddress" }` + (max. 200 / 500 Zeichen, leerer Text = nicht gesetzt). + +## Logo + +- Globale Büro-Einstellung, nicht Teil von Projekten, Revisionen, Snapshots + oder Projektexport. +- Tabelle `document_branding_assets` (Migration `0007`). +- `GET /api/document-branding` → `{ logo: { mimeType, fileName, sizeBytes, updatedAtIso } | null }` +- `GET /api/document-branding/logo` → Bilddaten (`404` ohne Logo), mit + `X-Content-Type-Options: nosniff` und restriktiver CSP. +- `PUT /api/document-branding/logo` mit + `{ "fileName", "mimeType": "image/png" | "image/jpeg" | "image/svg+xml", "contentBase64" }`, + maximal 2 MB; der Dateiinhalt wird gegen das Format geprüft. +- `DELETE /api/document-branding/logo` → `204`. + +## Code + +- `src/app/projects/[projectId]/print/page.tsx` – Datenladen, Werkzeugleiste, + `@page`-Regeln +- `src/frontend/print/print-document-model.ts` – reine Berechnungen und + Formatierung (Tests: `tests/print-document-model.test.ts`) +- `src/frontend/print/print-document.tsx` – Blätter und Tabellen +- `src/frontend/print/print-document.css` – Layout, auf `.print-view` + begrenzt +- `src/frontend/components/distribution-board-info-card.tsx` – Infokarte im + Bearbeiten-Dialog der Verteilung + +## Bestehende Datenbanken + +Vor dem Anwenden der additiven Migrationen `0007` und `0008` 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 +zum logischen Projektsnapshot oder Projekttransfer. diff --git a/scripts/db-verify-circuit-schema.js b/scripts/db-verify-circuit-schema.js index 8680f59..8d27b1d 100644 --- a/scripts/db-verify-circuit-schema.js +++ b/scripts/db-verify-circuit-schema.js @@ -12,6 +12,8 @@ const requiredTables = [ "circuit_protection_devices", "distribution_board_components", "distribution_board_component_protection_devices", + "document_branding_assets", + "document_branding_settings", ]; const tablePlaceholders = requiredTables.map(() => "?").join(", "); @@ -87,6 +89,10 @@ const requiredProjectColumns = [ "description", "is_public_building", "enabled_distribution_board_supply_types", + "site_address", + "work_stage", + "project_lead", + "project_editor", ]; const projectColumns = new Set( db.prepare("PRAGMA table_info(projects)").all().map((column) => column.name) @@ -98,6 +104,10 @@ const requiredDistributionBoardColumns = [ "floor_id", "supply_type", "simultaneity_factor", + "board_number", + "location", + "fed_from", + "remark", ]; const distributionBoardColumns = new Set( db diff --git a/src/app/projects/[projectId]/page.tsx b/src/app/projects/[projectId]/page.tsx index c08b72e..ab172bd 100644 --- a/src/app/projects/[projectId]/page.tsx +++ b/src/app/projects/[projectId]/page.tsx @@ -95,6 +95,13 @@ import { type DistributionBoardSupplyType, } from "../../../shared/constants/distribution-board"; import { ProjectVersionHistory } from "../../../frontend/components/project-version-history"; +import { + DistributionBoardInfoCard, + fromDistributionBoardInfoDraft, + toDistributionBoardInfoDraft, + type DistributionBoardInfoDraft, +} from "../../../frontend/components/distribution-board-info-card"; +import { Printer } from "lucide-react"; import { ProjectSettingsModal, type ProjectSettingsInput, @@ -165,6 +172,15 @@ export default function ProjectDetailPage() { setEditingBoardSimultaneityFactor, ] = useState("1"); const [editingBoardCopyName, setEditingBoardCopyName] = useState(""); + const [editingBoardInfo, setEditingBoardInfo] = + useState( + toDistributionBoardInfoDraft({ + boardNumber: null, + location: null, + fedFrom: null, + remark: null, + }) + ); const [floorName, setFloorName] = useState(""); const [editingFloor, setEditingFloor] = useState(null); const [editingRoom, setEditingRoom] = useState(null); @@ -542,6 +558,7 @@ export default function ProjectDetailPage() { String(board.simultaneityFactor) ); setEditingBoardCopyName(`${board.name} Kopie`); + setEditingBoardInfo(toDistributionBoardInfoDraft(board)); } function openBoardCreator() { @@ -577,6 +594,7 @@ export default function ProjectDetailPage() { floorId: editingBoardFloorId || null, supplyType: editingBoardSupplyType, simultaneityFactor, + ...fromDistributionBoardInfoDraft(editingBoardInfo), }, project.currentRevision ); @@ -967,6 +985,14 @@ export default function ProjectDetailPage() {

+ +
+
+ +

\r\n]/g, " ")); +} + +function pageRules(project: ProjectDto, stand: string, format: PlanFormat) { + const marginBoxes = ` + @bottom-left { content: ${cssString(`${project.name} · Leistungsbilanz`)}; font: 7.5pt Arial, sans-serif; color: #6b7280; } + @bottom-center { content: ${cssString(`Stand ${stand} · Datenstand Rev. ${project.currentRevision}`)}; 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 ` + @page lb-portrait { size: A4 portrait; margin: 14mm 16mm 16mm; ${marginBoxes} } + @page lb-landscape { size: ${format === "a3" ? "A3" : "A4"} landscape; margin: 10mm 10mm 13mm; ${marginBoxes} }`; +} + +export default function ProjectPrintPage() { + const params = useParams<{ projectId: string }>(); + const projectId = params.projectId; + const [data, setData] = useState(null); + const [logo, setLogo] = useState(null); + const [office, setOffice] = useState({ + officeName: null, + officeAddress: null, + }); + const [officeDraft, setOfficeDraft] = useState<{ + officeName: string; + officeAddress: string; + } | null>(null); + const [format, setFormat] = useState("a4"); + const [error, setError] = useState(null); + const [message, setMessage] = useState(null); + const [isBusy, setIsBusy] = useState(false); + const [printedAt] = useState(() => new Date()); + + useEffect(() => { + if (!projectId) { + return; + } + let cancelled = false; + async function load() { + const [project, boards, circuitLists, floors, snapshots, branding] = + await Promise.all([ + getProject(projectId), + listDistributionBoards(projectId), + listCircuitLists(projectId), + listFloors(projectId), + listProjectSnapshots(projectId), + getDocumentBranding(), + ]); + const floorNameById = new Map(floors.map((floor) => [floor.id, floor.name])); + const summaries = await Promise.all( + [...boards] + .sort( + (left, right) => + boardSortCollator.compare(left.boardNumber ?? "", right.boardNumber ?? "") || + boardSortCollator.compare(left.name, right.name) + ) + .flatMap((board) => { + const circuitList = circuitLists.find( + (list) => list.distributionBoardId === board.id + ); + return circuitList ? [{ board, circuitList }] : []; + }) + .map(async ({ board, circuitList }) => + summarizePrintBoard({ + board, + circuitListId: circuitList.id, + tree: await getCircuitTree(projectId, circuitList.id), + floorName: board.floorId ? floorNameById.get(board.floorId) ?? null : null, + }) + ) + ); + const finalProject = await getProject(projectId); + assertPrintRevisionConsistency(project.currentRevision, summaries, finalProject.currentRevision); + if (cancelled) { + return; + } + setData({ + project, + summaries, + namedSnapshots: snapshots + .filter((snapshot) => snapshot.kind === "named") + .sort((left, right) => left.createdAtIso.localeCompare(right.createdAtIso)), + }); + setLogo(branding.logo); + setOffice(branding.office); + document.title = `Leistungsbilanz – ${project.name}`; + } + load().catch((err: unknown) => { + if (!cancelled) { + setError(err instanceof Error ? err.message : "Die Seitenansicht konnte nicht geladen werden."); + } + }); + return () => { + cancelled = true; + }; + }, [projectId]); + + const entries = useMemo( + () => (data ? buildPreliminaryBoardHierarchy(data.summaries) : []), + [data] + ); + const stand = useMemo( + () => + new Intl.DateTimeFormat("de-DE", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }).format(printedAt), + [printedAt] + ); + const logoSrc = logo + ? `${documentLogoUrl}?v=${encodeURIComponent(logo.updatedAtIso)}` + : null; + + async function handleLogoUpload(event: ChangeEvent) { + const file = event.target.files?.[0]; + event.target.value = ""; + if (!file) { + return; + } + if (!(documentLogoMimeTypes as readonly string[]).includes(file.type)) { + setError("Bitte ein PNG-, JPG- oder SVG-Bild wählen."); + return; + } + if (file.size > maxDocumentLogoBytes) { + setError("Das Logo darf höchstens 2 MB groß sein."); + return; + } + setIsBusy(true); + setError(null); + try { + const result = await uploadDocumentLogo(file); + setLogo(result.logo); + setMessage("Logo hinterlegt. Es gilt für alle Projekte."); + } catch (err) { + setError(err instanceof Error ? err.message : "Das Logo konnte nicht gespeichert werden."); + } finally { + setIsBusy(false); + } + } + + async function handleOfficeSave(event: FormEvent) { + event.preventDefault(); + if (!officeDraft) { + return; + } + setIsBusy(true); + setError(null); + try { + const result = await updateOfficeProfile({ + officeName: officeDraft.officeName.trim() || null, + officeAddress: officeDraft.officeAddress.trim() || null, + }); + setOffice(result.office); + setOfficeDraft(null); + setMessage("Büroangaben gespeichert. Sie gelten für alle Projekte."); + } catch (err) { + setError(err instanceof Error ? err.message : "Die Büroangaben konnten nicht gespeichert werden."); + } finally { + setIsBusy(false); + } + } + + async function handleLogoDelete() { + if (!window.confirm("Hinterlegtes Logo für alle Projekte entfernen?")) { + return; + } + setIsBusy(true); + setError(null); + try { + await deleteDocumentLogo(); + setLogo(null); + setMessage("Logo entfernt."); + } catch (err) { + setError(err instanceof Error ? err.message : "Das Logo konnte nicht entfernt werden."); + } finally { + setIsBusy(false); + } + } + + return ( + // Paper output: always light, independent of the app's dark mode. +
+ {data ? : null} +
+ + Seitenansicht{data ? ` · ${data.project.name}` : ""} + + {message ? {message} : null} + {error ? {error} : null} + + + + {logo ? ( + + ) : null} + + + Zum Projekt + +
+ {officeDraft ? ( + setOfficeDraft(null)} + onSubmit={handleOfficeSave} + submitLabel="Büroangaben speichern" + title="Büroangaben" + > +
+
+ + + setOfficeDraft({ ...officeDraft, officeName: event.target.value }) + } + value={officeDraft.officeName} + /> +
+
+ +