diff --git a/.env.example b/.env.example deleted file mode 100644 index 46fa42a..0000000 --- a/.env.example +++ /dev/null @@ -1,7 +0,0 @@ -# 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 acbb157..e0ef1d2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,9 @@ node_modules/ dist/ .next/ -.env -.env.* -!.env.example # Streuprodukt von tsc; drizzle-kit liest drizzle.config.ts. /drizzle.config.js data/*.db data/backups/*.db .codex/*.log -/docs/spec/kbp-Stromkreis.xlsx -/data/revit-reference/*.xlsx +dynamo/output/ diff --git a/AGENTS.md b/AGENTS.md index 75fdcf3..500e9a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,16 +36,6 @@ 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`). 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. @@ -62,8 +52,7 @@ 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 plus the - read-only loads of logically linked downstream boards on that feeder circuit. +- Circuit total power is the sum of all device rows in that circuit. - Existing equipment identifiers must never be changed automatically. - Renumbering is always an explicit user action. @@ -175,53 +164,19 @@ Keyboard behavior: - Escape cancels - Tab / Shift+Tab navigates editable cells - Arrow keys navigate cells when not editing -- Alt+ArrowDown on a GZF cell opens the AMEV table (`GzfPickerModal`); the - selected GZF cell also shows a small table-icon button. The picked value is - committed like a typed edit. Support Ctrl+Plus and Ctrl+Shift+Plus for insertion. -Editor actions use `IconButton` (`src/frontend/components/icon-button.tsx`, -`lucide-react` icons). The German action text is always the accessible name and -tooltip; the toolbar shows icon plus text, group headers and rows show icons -only, separated into logical blocks with `IconButtonSeparator`. Destructive -actions use `variant="danger"` (trash icon for circuits and groups, `ListX` for -removing a device row). -Column headers show the label (click to sort) with a funnel icon for the -value filter; an active filter is highlighted and shows its value count. -Header labels break only between words and put a trailing unit such as -`[kW]` on a second line. -The project overview uses the same rule: row actions are icon-only -`IconButton`s, card-header and panel actions show icon plus text, navigation -uses `IconLink` (`src/frontend/components/icon-link.tsx`). Page-header buttons -stay Bootstrap `btn` with a lucide icon (`btn-with-icon`). List cards filter -through a collapsible PM-style filter bar (`CollapsibleFilterPanel`, -`MultiSelectDropdown`; logic in `src/frontend/utils/overview-filters.ts`): only -the bar collapses, its state is kept per card in `localStorage`, a collapsed -active filter shows "Filter aktiv". - ## Bootstrap / Styling Rule Bootstrap may be used for the general application UI, such as navigation, page layout, buttons, forms, cards, alerts and modals. -Cards follow the PM app look: 1px border all around, 16px radius and the -soft shadow defined on `.card` in `globals.css` (own dark-mode value). The -`.card` rule maps Bootstrap's `shadow-sm` to the same shadow; do not add other -`shadow-*` classes or a colored top border to cards. - Do not use Bootstrap as the core table/grid framework for the circuit list editor. The circuit list editor must remain a custom spreadsheet-like component with controlled cell selection, inline edit mode, row grouping, drag-and-drop indicators and keyboard behavior. Avoid permanent Bootstrap form controls inside table cells. Table cells should show static text by default and switch to inputs only while editing. -## Browser Runtime - -The web UI is also opened over plain HTTP from other machines in the LAN, which -is not a secure context. Do not call secure-context-only browser APIs such as -`crypto.randomUUID()` directly; create client-side ids with `createClientId()` -from `src/frontend/utils/client-id.ts`. - ## Drag-and-Drop Rules Dragging from the circuit identifier / circuit handle moves the whole circuit. @@ -295,23 +250,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 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 -`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 versions 1 to 9 remain restorable when -they contain no legacy CSV state; they are upgraded while parsing. Version 5 stores +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. 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 @@ -323,45 +265,29 @@ 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. -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. -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. -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. -R9 adds the complete Linear-XLSX follow-up import. It matches Worksharing-IDs -exactly, separates source decisions from return deviations, updates accepted -linked quantities atomically, retains missing objects and compacts every older -batch to metadata. `external-import.apply-follow-up` stores complete inverse -states, so Undo/Redo never parses Excel. A separately confirmed -`external-model-object.delete-missing` command removes missing objects and -adjusts linked row quantities; Undo restores objects, links and quantities. -R10 verifies the complete path through return workbook, follow-up import, -snapshot restore, portable duplicate and restart-safe Undo/Redo. A 5,000-object -synthetic workbook covers parser, command/snapshot size, transactions and the -client-side virtual window. Complete external-state inserts use bounded batches -inside their existing transaction for initial/follow-up import, restore and -duplicate. See `docs/spec/revit-excel-r10-validation.md`. - -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. +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/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 +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 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 +version introduced by additive migration `0004`; it is distinct from the CSV +configuration JSON schema version. 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. @@ -382,12 +308,37 @@ 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 current read-only +The read-only `GET /api/projects/:projectId/circuit-lists/:circuitListId/external-objects` -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. +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. 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. @@ -421,7 +372,7 @@ 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 +`workStage`, `projectLead` and `projectEditor` (migration `0009`); 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 @@ -471,58 +422,30 @@ 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 project-wide circuit-tree read model exposes fixed `headerComponents`, group-owned +The 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. -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. -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 +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 +(migration `0008`). 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` 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. +(`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. Room command schema version 2 stores the optional, -finite, non-negative net room area `areaM2`; persisted version-1 commands are -upgraded with `areaM2 = null` and exact record comparison prevents them from -silently overwriting a newer area. Room areas are maintained manually, shown -with two decimals and summarized per floor and building with a separate missing -count. Revit import and W/m² use remain follow-up work. Command inverses remove -or restore only unchanged records and reject floors with -assigned rooms/distribution boards or rooms referenced by device rows. All -write routes require `expectedRevision` and return the updated history state. +complete stable snapshots. Their inverses remove or restore only unchanged records and +reject floors with assigned rooms/distribution boards or rooms referenced by +device rows. All write routes require `expectedRevision` and return the updated +history state. Required operations: @@ -552,103 +475,78 @@ Required operations: `` 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 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 +- 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 are the provisional kbp CD (`--pd-*` variables) until the + official CD specification exists. 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`), + (migration `0008`) and `document_branding_settings` (migration `0009`), 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 / Linear Excel External Model Work +## Revit / CSV External Model Work -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. -- The corrected R2 return workbook was successfully imported into Linear on - 2026-09-30; R3 through R10 and Phase 14 are complete. -- 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. -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 - -`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. -- Current-carrying capacities and correction factors use - DIN VDE 0298-4:2023-06 with Berichtigung 1:2023-10; the exact scope and the - separate basis of voltage-drop and protection checks are documented in - `docs/cable-sizing-module.md`. Inputs outside the supported tables return no - result instead of assuming a factor of 1. Direct burial, grouped method E, - aluminium below 25 mm² and neutral-current sizing above 33 % third harmonic - remain unsupported until their required inputs or normative basis exist. -- 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. +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. ## Future Sizing -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. +Do not implement full cable/protection sizing unless explicitly requested. Keep the structure ready for it. @@ -666,37 +564,6 @@ 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 deliberately not part of named/automatic project snapshots or snapshot - restore; those operations leave estimate balances unchanged. Portable project - transfer format version 2 includes every estimate balance and remaps balance, - group and row ids when duplicating a project. Version 1 transfers remain - importable and contain no estimate balances. -- 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). -- 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 - SQLite is the currently supported database. @@ -714,17 +581,14 @@ for the early-phase power balance by DIN 276 cost group (see ## Current Deferred Work +- Revit/CSV/IFCGUID round-trip, 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 -- 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 -- configurable role/rights matrix instead of the fixed `admin`/`user` roles -- permanent account lockout (only temporary per-username login throttling - exists) -- email/one-time-link password provisioning, OIDC/Entra login -- linking user accounts to a personnel/employee master table +- 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 51a3860..58f1832 100644 --- a/README.md +++ b/README.md @@ -4,30 +4,19 @@ Leistungsbilanz ist eine Webanwendung für die elektrische Ausführungsplanung. Mittelpunkt steht ein tabellenähnlicher Stromkreislisten-Editor, der Stromkreise, 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 -für mehrere gleichzeitig arbeitende Prozesse und ein vollständig unterstütztes -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 R10 sind abgeschlossen; -die eigene Revit-Seite unterstützt Einstellungen, Erst- und Folgeimport, -virtuelle Objektbearbeitung, Editorzuordnung und strukturtreue Rückgabe. -Die Phase-14-Kette ist Ende zu Ende und mit 5.000 synthetischen Objekten geprüft. +Das Projekt befindet sich in aktiver Entwicklung. Der lokale Entwicklungsbetrieb +mit SQLite und Docker Compose ist unterstützt. Ein Produktionsdeployment, +Mehrbenutzerbetrieb und der Revit-/IFCGUID-Datenaustausch sind noch nicht +implementiert. ## Unterstützter Arbeitsablauf -- Projekte und Verteilungen verwalten; Gebäude, Etagen und Räume auf einer - eigenen Seite pflegen, Räume optional mit Fläche und Summen je Etage und - Gebäude +- Projekte, Verteilungen, Etagen und Räume verwalten - pro Verteilung geschützte Stromkreisgruppen für Beleuchtung, 1-phasige und 3-phasige Stromkreise verwalten - Hauptschalter, Überspannungsableiter, Gruppenschutz und zusätzliche Verteilergeräte in der Stromkreisliste abbilden - Schutzgeräte je Stromkreis und optional je Gruppe konfigurieren -- Leitungsquerschnitte für einzelne Stromkreise auf Anforderung nach - DIN VDE 0298-4 berechnen und ausdrücklich übernehmen - leere, einzeilige und mehrzeilige Stromkreise abbilden - Stromkreise und Gerätezeilen per Drag-and-drop umstrukturieren - Projektgeräte einfügen, verknüpfen und kontrolliert synchronisieren @@ -36,14 +25,6 @@ Die Phase-14-Kette ist Ende zu Ende und mit 5.000 synthetischen Objekten geprüf - Ä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 -- grobe Leistungsbilanzen für LPH 2/3 nach Kostengruppen führen, mit der - detaillierten Bilanz vergleichen und einzelne Zeilen als Projektgerät - übernehmen -- Linear-XLSX-Dateien verlustarm lesen und schreiben; Erst- und Folgeimporte - prüfen, Revit-Objekte zuordnen und geplante Werte strukturerhaltend an - Linear zurückgeben ## Technik @@ -63,8 +44,6 @@ Voraussetzungen: ```powershell git clone Set-Location leistungsbilanz-ts -$env:AUTH_BOOTSTRAP_USERNAME = "admin" -$env:AUTH_BOOTSTRAP_PASSWORT = "" docker compose up --build --detach ``` @@ -73,15 +52,9 @@ Danach: - Frontend: - API-Healthcheck: (über den Next.js-Rewrite) -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. +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. Der API-Container führt ausstehende Migrationen und die Schemaprüfung beim Start automatisch aus. Die SQLite-Datei liegt auf dem Host unter @@ -127,8 +100,6 @@ 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 ``` @@ -171,15 +142,8 @@ 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) -- [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) -- [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/compose.dev.yaml b/compose.dev.yaml index f49e9e6..b9c64b4 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -35,12 +35,8 @@ services: PORT: "3000" CHOKIDAR_USEPOLLING: "true" LOG_LEVEL: "${LOG_LEVEL:-debug}" - 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. + # Nur auf dem Loopback: nichts davon ist authentifiziert, 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 1de9104..3438f90 100644 --- a/compose.yaml +++ b/compose.yaml @@ -45,16 +45,8 @@ services: NODE_ENV: production PORT: "3000" 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/authentication.md. - 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. + # Nicht auf dem Host veroeffentlicht: die API hat keine Authentifizierung + # und 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 be55461..395b1ac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,37 +14,21 @@ ausdrücklich getrennt und dürfen nicht als bereits implementiert verstanden we Drag-and-drop, Sortierung, Filterung und Undo/Redo - [Seitenansicht und PDF-Export](print-view.md) – Deckblatt, Verteilerübersicht, Verteilerpläne, Büro-Logo -- [Gebäudestruktur](building-structure.md) – Gebäude → Etagen → Räume, - Raumflächen und Summen, Befehle, Snapshot-Schema 8, eigene Seite -- [Grobe Leistungsbilanz](estimate-balance.md) – LPH 2/3 nach Kostengruppen, - Rechnung, Vergleich mit der detaillierten Bilanz, Übernahme als Projektgerät - [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 -- [Anmeldung und Benutzerverwaltung](authentication.md) – Rollen, Ablauf beim - Anlegen eines Zugangs, Sessions, Bootstrap-Admin ## Entwicklung und Betrieb - [Entwicklungs- und Contributor-Workflow](development-workflow.md) - [Deployment und Betrieb](deployment.md) -## Revit / Linear XLSX - -- [Projektversionen und externer Modellaustausch](project-history-and-external-model-architecture.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) -- [R10-Abnahme](spec/revit-excel-r10-validation.md) – Ende-zu-Ende- und - 5.000-Objekte-Nachweis -- [LLM-Kontext für Phase 14](revit-requirements-llm-context.md) - ## Zukunftsarchitektur +- [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) +- [Phase-14-Audit und Implementierungsplan](spec/revit-csv-phase-14-audit-and-plan.md) - [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) @@ -66,6 +50,3 @@ Limitierungen und Roadmap. - [Frühe Codex-Promptvorlagen](archive/initial-codex-prompts.md) – historischer Arbeitsstand, keine aktuelle Implementierungsanweisung -- [Revit-/Dynamo-Anbindung](archive/revit-dynamo-leistungsbilanz-integration-konzept.md) – - nicht weiterverfolgte Vorüberlegung zur direkten Dynamo-/API-Anbindung; - Diagnoseskripte über den Git-Tag `archive/dynamo-vorueberlegungen` diff --git a/docs/archive/revit-dynamo-leistungsbilanz-integration-konzept.md b/docs/archive/revit-dynamo-leistungsbilanz-integration-konzept.md deleted file mode 100644 index aa0ae97..0000000 --- a/docs/archive/revit-dynamo-leistungsbilanz-integration-konzept.md +++ /dev/null @@ -1,1152 +0,0 @@ -# Revit-/Dynamo-Anbindung an die Leistungsbilanz - -> **Archiviert (September 2026), keine aktuelle Implementierungsanweisung.** -> Die direkte Revit-Anbindung über Dynamo/Python, Revit-API und JSON wird nicht -> weiterverfolgt. Die weitere Revit-Arbeit ist zurückgestellt und erfolgt, wenn -> sie wieder aufgenommen wird, über den CSV-Export/-Import des Linear-Plugins -> in Revit. Siehe -> [Revit-CSV-Anforderungen](../spec/revit-csv-integration-requirements.md). -> Die zugehörigen Dynamo-Diagnoseskripte sind über den Git-Tag -> `archive/dynamo-vorueberlegungen` erreichbar. - -## Zweck dieses Dokuments - -Dieses Dokument beschreibt den aktuellen Stand und die gewünschte Zielrichtung für die Anbindung von Revit an die Leistungsbilanz-App. - -Es soll als Arbeitsgrundlage für Codex dienen. Codex soll **zuerst die bestehende Architektur des Repositories analysieren** und danach konkrete Vorschläge für: - -1. die API-Struktur der Leistungsbilanz, -2. das Austauschformat zwischen Revit und Leistungsbilanz, -3. die benötigten Dynamo-/Python-Skripte, -4. die Synchronisationslogik Revit → Leistungsbilanz, -5. die spätere Rückrichtung Leistungsbilanz → Revit - -erarbeiten. - -Die nachfolgend genannten Klassennamen, Endpoints und DTOs sind **Vorschläge und keine zwingenden Vorgaben**. Sie sollen an die tatsächlich vorhandene Architektur angepasst werden. - ---- - -# 1. Ausgangssituation - -Die Leistungsbilanz-App soll Daten aus Revit übernehmen können. - -Ursprünglich war dafür ein CSV-basierter Import vorgesehen, weil Revit-Bauteillisten nativ als CSV exportiert werden können. - -Inzwischen ist klar, dass Dynamo mit Python genutzt werden kann und damit ein direkter Zugriff auf die Revit API möglich ist. - -Dadurch ist eine wesentlich sauberere direkte Integration möglich. - -Die CSV-Schnittstelle soll deshalb **nicht zwingend entfallen**, aber künftig eher als: - -- manueller Importweg, -- Fallback, -- allgemeine Austauschmöglichkeit, -- Debug-/Testformat - -verstanden werden. - -Die primäre Revit-Integration soll perspektivisch über eine **versionierte API mit JSON als Austauschformat** erfolgen. - ---- - -# 2. Aktueller Dynamo-Stand - -Ein erster Dynamo-Python-Test funktioniert bereits. - -Aktuell werden über die Revit API alle Exemplare der Kategorie: - -```text -BuiltInCategory.OST_ElectricalFixtures -``` - -also Revit **Elektroinstallationen / Electrical Fixtures** gesammelt. - -Für den aktuellen Entwicklungsstand soll bewusst zunächst **nur diese Kategorie** betrachtet werden. - -Andere Kategorien können später ergänzt werden. - ---- - -# 3. Bereits erfolgreich aus Revit gelesene Daten - -Der aktuelle Python-Ansatz kann bereits folgende Daten ausgeben: - -```text -ElementId -UniqueId -Familie -Typ -MEP_Raumnummer -MEP_Raumname -IFC_GUID -``` - -Die Zuordnung zum MEP-Raum erfolgt über den zum FamilyInstance gehörenden MEP Space. - -Der aktuelle Test zeigt, dass das grundsätzliche Auslesen über Dynamo/Python funktioniert. - ---- - -# 4. Relevante Identitäten - -Für die Kopplung zwischen Revit und Leistungsbilanz sollen mehrere Identifikatoren berücksichtigt werden. - -## 4.1 Revit UniqueId - -Die `UniqueId` soll die primäre Revit-seitige Elementidentität darstellen. - -Sie sollte für die dauerhafte Zuordnung eines Revit-Elements verwendet werden. - -Beispiel: - -```text -revitUniqueId = "0a52cc55-..." -``` - ---- - -## 4.2 ElementId - -Die Revit `ElementId` soll ebenfalls übertragen werden. - -Sie ist nützlich für: - -- Debugging, -- Fehlersuche, -- Anzeige für den Anwender, -- direkte Suche eines Elements in Revit. - -Sie soll aber **nicht als alleiniger persistenter Schlüssel** zwischen den Systemen verwendet werden. - ---- - -## 4.3 IFC GUID - -Die IFC GUID soll ebenfalls mitgeführt werden, sofern sie im Revit-Modell vorhanden ist. - -Damit entsteht perspektivisch eine Verbindung: - -```text -Revit - ↕ UniqueId -Leistungsbilanz - ↕ IFC GUID -IFC -``` - -Die IFC GUID ist damit insbesondere für spätere IFC-basierte Integrationen relevant. - ---- - -# 5. Zusätzlich benötigte Modellidentität - -Die `UniqueId` identifiziert ein Element innerhalb eines Revit-Modells. - -Deshalb benötigt die Leistungsbilanz zusätzlich eine stabile Identität des Revit-Modells. - -Vorgeschlagener Schlüssel: - -```text -revitModelId -``` - -Beispiel: - -```text -550e8400-e29b-41d4-a716-446655440000 -``` - -Diese ID darf nicht ausschließlich aus folgenden Informationen erzeugt werden: - -```text -Dateiname -Dateipfad -lokaler Speicherort -``` - -da sich diese ändern können. - -Mögliche Speicherorte in Revit: - -### Variante A – Projektparameter - -Zum Beispiel: - -```text -LB_ProjectId -LB_ModelId -``` - -Vorteile: - -- einfach umzusetzen, -- sichtbar, -- leicht zu debuggen, -- direkt über Dynamo lesbar. - -### Variante B – Revit Extensible Storage - -Langfristig eleganter, weil integrationsspezifische Metadaten unsichtbar im Modell gespeichert werden können. - -Beispielsweise: - -```text -LeistungsbilanzConnector -{ - modelId - projectId - lastSync -} -``` - -Für einen ersten Prototyp ist ein Projektparameter wahrscheinlich ausreichend. - ---- - -# 6. Grundprinzip der Zielarchitektur - -Die Revit-Schnittstelle soll nicht direkt an interne Datenbanktabellen gekoppelt werden. - -Empfohlen wird: - -```text -┌──────────────────────────── REVIT ────────────────────────────┐ -│ │ -│ Revit API │ -│ ↓ │ -│ Dynamo + Python │ -│ ↓ │ -│ Revit-Adapter │ -│ ↓ │ -│ definiertes Austauschmodell │ -│ ↓ │ -│ JSON │ -│ │ -└───────────────────────┬───────────────────────────────────────┘ - │ - │ HTTP / REST - ▼ -┌──────────────────── LEISTUNGSBILANZ ──────────────────────────┐ -│ │ -│ Revit Integration API │ -│ ↓ │ -│ Import-/Sync-Service │ -│ ↓ │ -│ persistierte Revit-Referenz │ -│ ↓ │ -│ Zuordnung zu DeviceRow / Circuit / bestehendem Datenmodell │ -│ │ -└───────────────────────────────────────────────────────────────┘ -``` - -Wichtig: - -> JSON ist das Austauschformat. HTTP ist nur der Transportweg. - -Dasselbe Datenmodell soll deshalb bei Bedarf auch als JSON-Datei gespeichert und eingelesen werden können. - ---- - -# 7. Austauschmodell / DTO - -Es soll ein klar definiertes und versioniertes Austauschformat geben. - -Beispiel: - -```json -{ - "schemaVersion": 1, - "source": "revit", - "model": { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "26009_F60_ELT" - }, - "elements": [ - { - "uniqueId": "f4d3c...", - "elementId": 471123, - "ifcGuid": "2X9...", - "category": "Electrical Fixtures", - "family": "Steckdose JUNG LS990", - "type": "Schuko 1-fach", - "space": { - "number": "1.03", - "name": "Schlafen" - }, - "parameters": { - "power": 250, - "cosPhi": 0.95 - } - } - ] -} -``` - -Das tatsächliche Schema soll durch Codex anhand des bestehenden Datenmodells der Leistungsbilanz konkretisiert werden. - ---- - -# 8. Trennung zwischen Revit-Objekt und Leistungsbilanz-Objekt - -Ein Revit-Element soll **nicht direkt mit einer DeviceRow gleichgesetzt werden**. - -Das ist wichtig, weil: - -- Revit den geplanten Modellstand enthält, -- Nutzer Werte in der Leistungsbilanz überschreiben können, -- ein importiertes Revit-Element erst vom Nutzer einem bestehenden oder neuen Stromkreis bzw. einer DeviceRow zugeordnet werden kann, -- ein erneuter Sync keine bewussten Benutzeränderungen überschreiben darf. - -Konzeptionell sollte deshalb eine separate Revit-Referenz existieren. - -Beispiel: - -```text -RevitElement - │ - │ verknüpft mit - ▼ -LinkedDevice / Zuordnung - │ - ▼ -DeviceRow - │ - ▼ -Circuit -``` - -Die tatsächliche Umsetzung muss Codex mit der vorhandenen Architektur abgleichen. - -Mögliche Eigenschaften einer persistierten Revit-Referenz: - -```text -id -revitModelId -revitUniqueId -revitElementId -ifcGuid - -category -family -type - -spaceNumber -spaceName - -rawData -lastSeenAt -lastSyncAt -``` - -Die Bezeichnung `RevitElement` ist nur ein Vorschlag. - -Wenn es im aktuellen Datenmodell bereits eine passende Entität gibt, soll diese verwendet oder erweitert werden. - ---- - -# 9. Revit → Leistungsbilanz - -Der erste zu implementierende Sync soll in diese Richtung erfolgen. - -```text -Revit - ↓ -Dynamo - ↓ -Python / Revit API - ↓ -JSON Payload - ↓ -HTTP POST - ↓ -Leistungsbilanz API - ↓ -Sync-Service -``` - -## Vorgeschlagenes Verhalten - -Der Benutzer startet in Dynamo bewusst einen Export bzw. Sync. - -Das Python-Skript: - -1. liest alle relevanten `OST_ElectricalFixtures`, -2. liest die definierten Revit-Daten, -3. erzeugt das versionierte JSON, -4. sendet es an die Leistungsbilanz, -5. wertet die HTTP-Antwort aus, -6. zeigt dem Benutzer das Ergebnis in Dynamo an. - ---- - -# 10. Snapshot-Sync statt Delta-Sync - -Für den ersten Stand soll **kein komplexer Delta-Sync** gebaut werden. - -Stattdessen soll Revit bei jedem Sync einen vollständigen Snapshot aller aktuell relevanten Elektroinstallationen liefern. - -Beispiel: - -```text -vorher aktueller Snapshot ------------------------------------------------- -Element A vorhanden Element A vorhanden -Element B vorhanden Element B vorhanden -Element C vorhanden Element C fehlt - Element D neu -``` - -Die Leistungsbilanz kann daraus ableiten: - -```text -A → unchanged oder updated -B → unchanged oder updated -C → missing / deleted / not seen -D → created -``` - -Das ist für zunächst einige hundert oder tausend Elemente ausreichend und deutlich robuster. - ---- - -# 11. Upsert-Verhalten - -Auf Leistungsbilanzseite soll ein Revit-Element anhand eines stabilen Schlüssels identifiziert werden. - -Vorgeschlagen: - -```text -(revitModelId, revitUniqueId) -``` - -Beim Empfang eines Snapshots: - -```text -Element bereits vorhanden? - │ - ├─ Nein - │ ↓ - │ Create - │ - └─ Ja - ↓ - Update -``` - -Die Revit-Referenz soll dabei aktualisiert werden. - -Benutzerseitig überschriebene Werte einer DeviceRow dürfen dadurch jedoch nicht ungeprüft überschrieben werden. - ---- - -# 12. Mögliche API-Struktur - -Nicht zwingend exakt so umsetzen. - -Codex soll prüfen, wie die aktuelle API strukturiert ist. - -Mögliche Endpoints: - -```http -POST /api/integrations/revit/v1/models/{modelId}/sync -``` - -Alternativ logisch getrennt: - -```http -POST /api/integrations/revit/v1/models/{modelId}/elements -GET /api/integrations/revit/v1/models/{modelId}/writeback -``` - -Beispielantwort auf einen Revit-Sync: - -```json -{ - "syncId": "sync-9384", - "received": 483, - "created": 17, - "updated": 45, - "unchanged": 421, - "missing": 3 -} -``` - -Die konkrete Antwortstruktur soll so gewählt werden, dass Dynamo dem Nutzer eine verständliche Zusammenfassung anzeigen kann. - ---- - -# 13. Leistungsbilanz → Revit - -Die Rückrichtung soll später ebenfalls unterstützt werden. - -Sie soll jedoch zunächst **logisch vom Revit-Import getrennt** werden. - -Also: - -```text -PUSH - -Revit - ↓ -Leistungsbilanz -``` - -und: - -```text -PULL / WRITEBACK - -Leistungsbilanz - ↓ -Revit -``` - -Der Benutzer soll bewusst entscheiden können, wann Daten nach Revit zurückgeschrieben werden. - -Zum Beispiel: - -```text -[ Revit-Daten importieren ] - -[ Änderungen nach Revit schreiben ] -``` - ---- - -# 14. Writeback nicht generisch ausführen - -Die Leistungsbilanz soll nicht beliebige Parameter-Namen an Revit schicken, die Dynamo anschließend blind beschreibt. - -Stattdessen soll es ein definiertes Writeback-Schema geben. - -Beispiel: - -```json -{ - "updates": [ - { - "uniqueId": "abcdef...", - "values": { - "circuitNumber": "UV01-2F17", - "panel": "UV01", - "connectedLoad": 250 - } - } - ] -} -``` - -Der Revit-Adapter besitzt anschließend eine feste Allowlist bzw. ein Mapping: - -```text -circuitNumber - ↓ -LB_Stromkreisnummer - -panel - ↓ -LB_Verteiler - -connectedLoad - ↓ -LB_Anschlussleistung -``` - -Damit ist kontrolliert, welche Revit-Parameter durch die Leistungsbilanz beschrieben werden dürfen. - ---- - -# 15. Field Ownership / Datenhoheit - -Für bidirektionale Synchronisation muss definiert sein, welches System für welches Feld führend ist. - -Beispiel: - -| Information | Führendes System | -|---|---| -| Revit UniqueId | Revit | -| Revit ElementId | Revit | -| IFC GUID | Revit | -| Familie | Revit | -| Typ | Revit | -| MEP Raum | Revit | -| MEP Raumnummer | Revit | -| Zuordnung zu DeviceRow | Leistungsbilanz | -| Zuordnung zu Circuit | Leistungsbilanz | -| manuell überschriebene Leistung | Leistungsbilanz | -| Sicherung | Leistungsbilanz | -| Leitung | Leistungsbilanz | -| Stromkreisnummer | Leistungsbilanz, ggf. Writeback | -| Verteilerzuordnung | Leistungsbilanz, ggf. Writeback | - -Diese Tabelle muss anhand des bestehenden Datenmodells vervollständigt werden. - -Ziel ist, Konflikte wie diesen zu vermeiden: - -```text -Revit: -Leistung = 500 W - -Leistungsbilanz: -Nutzer überschreibt auf 750 W - -nächster Revit-Sync: -Revit liefert wieder 500 W -``` - -Der bewusste Benutzerwert darf nicht kommentarlos verloren gehen. - ---- - -# 16. Rohdaten und normalisierte Daten - -Es sollte geprüft werden, ob zusätzlich zu den normalisierten Daten ein Teil des ursprünglichen Revit-Payloads gespeichert werden sollte. - -Beispiel: - -```text -rawData / rawPayload -``` - -Vorteile: - -- Debugging, -- spätere Erweiterung ohne sofortigen Revit-Neuexport, -- Nachvollziehbarkeit, -- Erkennung neuer Parameter. - -Dabei soll aber vermieden werden, die eigentliche Business-Logik auf unstrukturiertem JSON aufzubauen. - ---- - -# 17. CSV und JSON-Datei weiterhin unterstützen - -Auch bei einer direkten API-Anbindung sollen Datei-basierte Wege sinnvoll bleiben. - -Mögliche Architektur: - -```text - ┌─────────────────────┐ - │ Leistungsbilanz │ - │ RevitSyncService │ - └─────────┬───────────┘ - │ - ┌─────────────┴─────────────┐ - │ │ - REST Datei - │ │ - ▼ ▼ - Dynamo Python JSON / CSV - │ - ▼ - Revit -``` - -Der gleiche interne Import-Service sollte möglichst sowohl: - -```text -HTTP JSON -``` - -als auch: - -```text -JSON-Datei -``` - -verarbeiten können. - -CSV kann als separates allgemeines Importformat bestehen bleiben. - ---- - -# 18. Kein direkter Datenbankzugriff aus Dynamo - -Dynamo soll nicht direkt auf SQLite, PostgreSQL oder andere Datenbanken der Leistungsbilanz zugreifen. - -Nicht empfohlen: - -```text -Dynamo - ↓ -direkte SQL-Verbindung - ↓ -DB -``` - -Empfohlen: - -```text -Dynamo - ↓ -API - ↓ -Business Logic - ↓ -ORM - ↓ -DB -``` - -Dadurch bleibt der Revit-Connector unabhängig von: - -- Tabellenstruktur, -- ORM, -- Migrationen, -- internen Relationen, -- späteren Änderungen des Backends. - ---- - -# 19. Zunächst kein WebSocket / Echtzeit-Sync - -Für den aktuellen Anwendungsfall ist kein permanenter Echtzeitkanal erforderlich. - -Nicht notwendig: - -```text -Leistungsbilanz wird geändert - ↓ -sofort automatische Änderung in Revit -``` - -Stattdessen soll zunächst mit expliziten Sync-Aktionen gearbeitet werden. - -Das ist auch im Hinblick auf Revit sinnvoll, da Änderungen über die Revit API kontrolliert und innerhalb gültiger Revit-Transactions vorgenommen werden müssen. - ---- - -# 20. Fehlerbehandlung - -Die Integration muss mit Teilfehlern umgehen können. - -Beispiele: - -- ein Element besitzt keinen MEP Space, -- IFC GUID fehlt, -- ein erwarteter Parameter fehlt, -- ein Revit-Parameter ist schreibgeschützt, -- HTTP-Verbindung schlägt fehl, -- API antwortet mit Validierungsfehler, -- Element wurde zwischen Abfrage und Writeback gelöscht, -- Revit-Modell ist noch nicht mit einem Leistungsbilanz-Projekt verknüpft. - -Das Dynamo-Skript soll möglichst nicht beim ersten fehlerhaften Element komplett abbrechen. - -Stattdessen sollte die Antwort z. B. unterscheiden: - -```text -success -warnings -errors -``` - -und am Ende eine Zusammenfassung ausgeben. - ---- - -# 21. Authentifizierung - -Codex soll prüfen, welche Authentifizierung die aktuelle Leistungsbilanz-App bereits verwendet. - -Der Dynamo-Connector soll keine unnötige zweite Authentifizierungsarchitektur einführen. - -Mögliche Varianten: - -- API Token, -- projektbezogenes Integration Token, -- bestehender Login-Mechanismus, -- kurzfristige Connector-Tokens. - -Secrets sollen nicht fest im Dynamo-Python-Code hinterlegt werden. - ---- - -# 22. Versionierung - -Das JSON-Schema und die API sollen versioniert sein. - -Beispielsweise: - -```text -schemaVersion = 1 -``` - -und/oder: - -```text -/api/integrations/revit/v1/ -``` - -Dadurch kann ein älteres Dynamo-Skript später noch mit einer neueren App-Version umgehen oder zumindest kontrolliert abgelehnt werden. - ---- - -# 23. Langfristige Perspektive: Revit Add-in - -Dynamo + Python ist für die erste Implementierung ideal, weil schnell getestet und angepasst werden kann. - -Langfristig könnte daraus ein echtes Revit-Add-in in C#/.NET werden. - -Beispiel: - -```text -Revit Ribbon - -┌──────── Leistungsbilanz ─────────┐ -│ │ -│ ↑ Daten übertragen │ -│ ↓ Daten aus Leistungsbilanz │ -│ │ -│ Projekt verbinden │ -│ Sync-Status │ -│ │ -└──────────────────────────────────┘ -``` - -Wichtig ist deshalb, dass die API nicht speziell auf Dynamo zugeschnitten wird. - -Ziel: - -```text -heute: -Dynamo + Python - ↓ -gleiche REST API - -später: -Revit Add-in C# - ↓ -gleiche REST API -``` - ---- - -# 24. Aktuell gewünschter Dynamo-Umfang - -Für den ersten produktiven Revit-Export soll Codex ein Dynamo-Python-Skript vorschlagen, das mindestens folgende Daten aus `OST_ElectricalFixtures` ermittelt: - -```text -revitModelId -ElementId -UniqueId -IFC GUID -Kategorie -Familie -Typ -MEP Raumnummer -MEP Raumname -``` - -Zusätzlich soll Codex anhand der aktuellen Leistungsbilanz-Datenstruktur prüfen, welche weiteren Felder bereits jetzt sinnvoll mitgegeben werden sollten. - -Dazu könnten später gehören: - -```text -Ebene -BMK -Leistung -cosPhi -Spannung -Anzahl -Kommentar -Stromkreis -Verteiler -weitere Shared Parameters -``` - -Diese zusätzlichen Felder sollen aber nicht willkürlich eingebaut werden, sondern aus der bestehenden Architektur und den fachlichen Anforderungen der Leistungsbilanz abgeleitet werden. - ---- - -# 25. Anforderungen an das Dynamo-Python-Skript - -Das Skript soll möglichst: - -- ohne externe Dynamo-Packages funktionieren, -- nur Revit API / Dynamo-eigene Python-Möglichkeiten verwenden, -- mit der im Projekt eingesetzten Revit-/Dynamo-Version kompatibel sein, -- alle Elektroinstallationen im gesamten aktuellen Revit-Dokument lesen, -- nicht nur die aktive Ansicht betrachten, -- fehlende optionale Parameter tolerieren, -- verständliche Fehlermeldungen liefern, -- eine gut lesbare Statusausgabe an `OUT` zurückgeben, -- JSON mit UTF-8 erzeugen, -- HTTP-Requests ohne unnötige externe Python-Abhängigkeiten ausführen, -- Timeouts behandeln, -- API-Fehler auswerten, -- keinen Datenverlust verursachen. - -Für spätere Writebacks muss das Skript Revit-Änderungen ausschließlich innerhalb gültiger Revit-Transactions durchführen. - ---- - -# 26. Gewünschter Arbeitsauftrag an Codex - -## Schritt 1 – Repository analysieren - -Vor Änderungen zuerst: - -1. `AGENTS.md` lesen. -2. Bestehende Architektur-Dokumentation lesen. -3. Datenmodell der Leistungsbilanz nachvollziehen. -4. Aktuelle Import-/CSV-Architektur untersuchen. -5. Vorhandene API-Routen analysieren. -6. Prüfen, ob bereits Entitäten oder Konzepte für: - - externe Modelle, - - Revit-Elemente, - - Linked Devices, - - Sync, - - Imports, - - Projekt-Historie - existieren. -7. Authentifizierung und Berechtigungssystem prüfen. -8. Bestehende Tests und Testkonventionen prüfen. - -Noch keine größere Implementierung beginnen, bevor diese Analyse abgeschlossen ist. - ---- - -## Schritt 2 – Bestehende Architektur gegen dieses Konzept abgleichen - -Codex soll beantworten: - -1. Welche vorhandenen Entitäten können wiederverwendet werden? -2. Brauchen wir überhaupt eine neue `RevitElement`-Entität? -3. Wie passt die Revit-Referenz in das bestehende `LinkedDevice`-/DeviceRow-Konzept? -4. Wo sollte das Sync-Verhalten im Backend liegen? -5. Wie soll die Modellidentität gespeichert werden? -6. Welche Felder sind Revit-Master? -7. Welche Felder sind Leistungsbilanz-Master? -8. Wie werden manuell überschriebene Werte geschützt? -9. Wie werden nicht mehr vorhandene Revit-Elemente behandelt? -10. Wie lässt sich das bestehende CSV-System sinnvoll weiterverwenden? - ---- - -## Schritt 3 – Konkreten Zielentwurf erstellen - -Codex soll danach einen konkreten Entwurf liefern für: - -### Datenmodell - -Mit tatsächlichen Namen passend zum Repository. - -### API - -Mit: - -```text -HTTP Method -Route -Request DTO -Response DTO -Validierung -Fehlercodes -Authentifizierung -``` - -### Sync-Service - -Mit klarer Verantwortung für: - -```text -Create -Update -Unchanged -Missing -Deleted -Linking -Conflict handling -``` - -### Dynamo-Schnittstelle - -Mit dem exakten JSON, das Dynamo senden bzw. empfangen soll. - ---- - -## Schritt 4 – Dynamo-Skripte vorschlagen - -Erst nachdem die Zielarchitektur feststeht, soll Codex konkrete Dynamo-Python-Skripte erstellen. - -Mindestens: - -### Script A – Revit → Leistungsbilanz - -Funktionen: - -```text -Revit-Modell-ID ermitteln -Electrical Fixtures sammeln -Daten auslesen -Payload erzeugen -JSON serialisieren -API aufrufen -Antwort auswerten -Status in Dynamo ausgeben -``` - -### Script B – Leistungsbilanz → Revit - -Noch nicht zwingend sofort implementieren, aber vollständig konzipieren. - -Funktionen: - -```text -Writeback-Daten von API abrufen -Element über UniqueId finden -Allowlist-Mapping anwenden -Werte prüfen -Revit Transaction starten -Parameter schreiben -Ergebnis an API melden -Status ausgeben -``` - -### Optional Script C – Debug-/Offline-Export - -Export des exakt gleichen Payloads als lokale JSON-Datei. - -Damit kann die Schnittstelle auch ohne erreichbare API getestet werden. - ---- - -# 27. Erwartete Ausgabe von Codex - -Codex soll nach der Analyse **nicht sofort große Änderungen durchführen**, sondern zuerst eine strukturierte Empfehlung liefern. - -Gewünschte Reihenfolge: - -```text -1. Analyse des Ist-Zustands -2. Abweichungen / bereits vorhandene passende Architektur -3. Empfohlenes Zieldesign -4. Datenmodelländerungen -5. API-Design -6. Sync-Logik -7. Exaktes JSON-Schema -8. Vorschlag Dynamo Script A -9. Vorschlag Dynamo Script B -10. Migrations-/Implementierungsreihenfolge -11. Tests -12. Offene Entscheidungen -``` - -Bei Architekturentscheidungen soll Codex die einfachste robuste Lösung bevorzugen und unnötige neue Abstraktionen vermeiden. - ---- - -# 28. Bevorzugte Implementierungsreihenfolge - -Voraussichtlich sinnvoll: - -```text -Phase 1 -──────────────────────────── -Austauschformat / DTO festlegen - -Phase 2 -──────────────────────────── -Backend API für Revit-Snapshot - -Phase 3 -──────────────────────────── -Persistierung und Upsert-Logik - -Phase 4 -──────────────────────────── -Dynamo Revit → API - -Phase 5 -──────────────────────────── -UI für importierte / nicht zugeordnete Revit-Elemente - -Phase 6 -──────────────────────────── -Zuordnungs- und Override-Verhalten - -Phase 7 -──────────────────────────── -Writeback API - -Phase 8 -──────────────────────────── -Dynamo API → Revit - -Phase 9 -──────────────────────────── -ggf. später Revit C# Add-in -``` - ---- - -# 29. Zentrale Architekturentscheidung - -Die wichtigste Vorgabe lautet: - -> Dynamo soll als Revit-Adapter dienen. Die eigentliche Fachlogik der Leistungsbilanz bleibt in der Leistungsbilanz-App. - -Dynamo soll deshalb nicht entscheiden: - -```text -welche Sicherung gewählt wird -welche Leitung verwendet wird -wie Stromkreise aufgebaut werden -wie Geräte gruppiert werden -welche Leistungswerte fachlich gültig sind -``` - -Dynamo liefert primär Revit-Daten und schreibt später explizit freigegebene Ergebnisse zurück. - -Die fachliche Entscheidung bleibt in der Webapp. - ---- - -# 30. Zielbild - -```text - REVIT - │ - Revit API - │ - Dynamo / Python - │ - JSON DTO - │ - REST / HTTP - │ - ▼ - Leistungsbilanz API - │ - Sync Service - │ - ┌───────────┴───────────┐ - │ │ - Revit-Referenz Business Logic - │ │ - └───────────┬───────────┘ - │ - DeviceRow - │ - Circuit - │ - Distributor -``` - -Später: - -```text -Leistungsbilanz - │ - Writeback - │ - ▼ -Dynamo / Python - │ - ▼ - Revit -``` - -Das Ziel ist keine möglichst komplexe Echtzeitkopplung, sondern eine robuste, nachvollziehbare und versionierbare Integration, die zunächst über Dynamo/Python funktioniert und später bei Bedarf durch ein natives Revit-Add-in ersetzt werden kann. diff --git a/docs/authentication.md b/docs/authentication.md deleted file mode 100644 index 32039cf..0000000 --- a/docs/authentication.md +++ /dev/null @@ -1,99 +0,0 @@ -# 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 **Config → Benutzer** -- **user** – volle Nutzung der Leistungsbilanz (Projekte, Stromkreislisten, - 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. - -## 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) 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/*` - (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. - **Konto** ist für jede angemeldete Person erreichbar; **Benutzer** nur für - Administratoren. - -## 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`: 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; 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 | -| 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 -`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. - -```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 -- 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/docs/building-structure.md b/docs/building-structure.md deleted file mode 100644 index 2264b3f..0000000 --- a/docs/building-structure.md +++ /dev/null @@ -1,112 +0,0 @@ -# Gebäudestruktur (Gebäude → Etagen → Räume) - -Projekte mit mehreren Gebäuden werden über eine eigene Ebene **Gebäude** -gegliedert. Etagen können einem Gebäude zugeordnet sein, Räume und Verteilungen -hängen wie bisher an der Etage. Das Gebäude eines Raums oder einer Verteilung -ergibt sich also aus der Etage; eine zweite, konkurrierende Zuordnung gibt es -nicht. Abgestimmt in Issue #6: Das Modell ist so bestätigt, und Gebäude mit -zugeordneten Etagen lassen sich nicht löschen. - -## Datenmodell - -| Tabelle | Feld | Bedeutung | -|---|---|---| -| `buildings` | `id`, `project_id` (FK, cascade), `name`, `sort_order` | Gebäude eines Projekts | -| `floors` | `building_id` (nullable FK → `buildings`, `ON DELETE set null`) | optionales übergeordnetes Gebäude | -| `rooms` | `area_m2` (nullable `REAL`) | optional gepflegte Netto-Raumfläche in m² | - -Migration `0009_buildings`. Bestehende Etagen behalten `building_id = null` und -erscheinen in der Oberfläche als „Ohne Gebäude“. Es gibt keine Zwangsmigration -und kein automatisch angelegtes Standardgebäude. Vor dem Anwenden der Migration -auf eine bestehende Datenbank ist wie bei jeder Schemamigration eine separate -Datenbanksicherung anzulegen. - -Migration `0011_glossy_norman_osborn` ergänzt ausschließlich das nullable Feld -`rooms.area_m2`. Bestehende Räume behalten damit eine unbekannte Fläche. Vor -dem Anwenden auf eine bestehende Datenbank ist ebenfalls eine separate -Datenbanksicherung erforderlich. - -## Befehle, Undo/Redo - -Alle Änderungen laufen über die bestehende Orts-Struktur -(`ProjectLocationStructureProjectCommandRepository`) mit Revision, Inverse und -persistentem Undo/Redo: - -- `project-building.insert` / `project-building.delete` mit vollständigem - Gebäude-Snapshot (Schema-Version 1) -- `project-building.update`: ändert nur den Namen -- Löschen eines Gebäudes wird abgelehnt, solange Etagen zugeordnet sind - („Das Gebäude kann nicht gelöscht werden, solange Etagen zugeordnet sind.“) -- Etagenbefehle `project-floor.insert/.update/.delete` haben seit - Schema-Version **2** das Feld `buildingId`. `project-floor.update` darf Name - und/oder Gebäude ändern, nicht aber `sortOrder`. Ein referenziertes Gebäude - muss zum Projekt gehören. -- Version-1-Etagenbefehle aus bestehender Historie bleiben ausführbar. Sie - stammen aus der Zeit vor den Gebäuden und werden vor der Ausführung mit - `buildingId = null` auf Version 2 gehoben; auch die daraus neu gespeicherten - Vorwärts- und Inversbefehle sind Version 2. Das ist bei linearer Historie - exakt: Wird ein Gebäude später zugeordnet, liegt dieser neuere Befehl im - Undo-Stapel vor dem alten Befehl und wird zuerst zurückgenommen. -- Raumbefehle `project-room.insert/.update/.delete` haben seit Schema-Version - **2** das Feld `areaM2`. Version-1-Befehle werden beim Einlesen mit - `areaM2 = null` hochgestuft. Vor einem alten Update oder Delete wird weiterhin - der vollständige erwartete Datensatz verglichen; eine inzwischen vorhandene - Fläche kann deshalb nicht unbemerkt gelöscht werden. - -## Snapshots und Transfer - -Projekt-Snapshot-Schema **8** enthält zusätzlich `rooms[].areaM2`. Version 7 -wird mit `areaM2 = null` hochgestuft; die älteren unterstützten Versionen 1–6 -werden außerdem mit leerer Gebäudeliste und `buildingId = null` hochgestuft. -Gespeicherte Sicherungspunkte bleiben wiederherstellbar. Die Relationen werden -geprüft (Gebäude gehört zum Projekt, `buildingId` verweist auf ein Gebäude des -Snapshots). Restore und Projekttransfer erhalten die Raumfläche. Das portable -Transferformat bleibt Version 2, weil es den versionierten Projektsnapshot -bereits einbettet; beim Duplizieren werden nur IDs und Relationen umgesetzt. - -## API - -- `GET /api/projects/:projectId/buildings` – Gebäude sortiert nach - `sortOrder`, Name -- `POST /api/projects/:projectId/buildings` – `{ "name": "Haus A", "expectedRevision": 3 }` -- `PUT /api/projects/:projectId/buildings/:buildingId` – `{ "name": "Haus B", "expectedRevision": 4 }` -- `DELETE /api/projects/:projectId/buildings/:buildingId` – `{ "expectedRevision": 5 }` -- `POST/PUT /api/projects/:projectId/floors[/:floorId]` akzeptieren zusätzlich - optional `buildingId` (`string | null`). Fehlt das Feld, bleibt beim Bearbeiten - das bisherige Gebäude erhalten; ältere Clients funktionieren unverändert. -- `POST/PUT /api/projects/:projectId/rooms[/:roomId]` akzeptieren zusätzlich - optional `areaM2` (`number | null`, endlich und ≥ 0). Beim Anlegen bedeutet - ein fehlendes Feld `null`; beim Bearbeiten bleibt die vorhandene Fläche - erhalten, wenn das Feld fehlt. - -## Oberfläche - -Gebäude, Etagen und Räume werden auf der eigenen Seite -`/projects/:projectId/struktur` („Gebäudestruktur“) gepflegt, erreichbar über -die Seitenleiste und die Kennzahlen der Projektübersicht. Drei Spalten -Gebäude → Etagen → Räume filtern sich gegenseitig: Klick auf ein Gebäude zeigt -nur dessen Etagen, Klick auf eine Etage nur deren Räume, „Alle“ hebt den Filter -auf. Hinzufügen, Bearbeiten und Löschen laufen über Icon-Buttons wie in der -Stromkreisliste. - -Der Raumdialog pflegt die optionale **Fläche [m²]** mit deutscher -Dezimaltrennzeichen-Eingabe. Gemeint ist die Netto-Raumfläche, wie sie der -Revit-Raumparameter „Fläche“ liefert, nicht eine Flächenart nach DIN 277. Die -Fläche wird ohne fachliche Rundung gespeichert und mit zwei Nachkommastellen -angezeigt. Die Gebäudestruktur zeigt die Fläche je Raum sowie Summen je Etage, -je Gebäude, „Ohne Etage“ und „Ohne Gebäude“. Fehlende Flächen werden nicht als -Nullfläche ausgegeben, sondern separat gezählt, damit Teilsummen erkennbar -bleiben. - -## Offen - -- Revit: Eine Übernahme des Gebäudes aus Revit ist derzeit nicht geplant. Die - abgeschlossene 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. -- Eine W/m²-Auswertung oder Übernahme der Raumfläche in Flächenlasten ist nicht - Teil dieser Funktion; das ist Folgethema von Issue #20. -- Sortierung von Gebäuden per Drag-and-drop ist noch nicht umgesetzt; neue - Gebäude werden hinten angehängt. diff --git a/docs/cable-sizing-module.md b/docs/cable-sizing-module.md index cd8b08d..80b7cc8 100644 --- a/docs/cable-sizing-module.md +++ b/docs/cable-sizing-module.md @@ -1,109 +1,243 @@ -# Leitungsberechnung +# Cable Sizing Module (Proposal) -Das optionale Modul gibt für einen einzelnen Stromkreis eine prüfbare -Querschnittsempfehlung aus. Es schreibt selbst keine Projektdaten. Erst die -ausdrückliche Aktion **Übernehmen** aktualisiert `cableCrossSection`, -`cableType` und `cableLength` über den vorhandenen Befehl `circuit.update`. -Revisionen sowie Undo/Redo bleiben dadurch erhalten. +**Status: proposal, not yet reviewed or merged by the project owner.** This +document and the accompanying `src/cable-sizing/`, `src/db/schema/cable-sizing-calculations.ts`, +`src/server/{controllers,routes}/cable-sizing.*` and `src/frontend/components/cable-sizing-*` +files were written by a third party (see git history/authorship) against the +project's own stated direction in `docs/spec/06-future-sizing-and-calculations.md` +("The app should later support rule-based protection and cable sizing") and +`AGENTS.md` ("... and later electrical sizing logic"). Nothing here has been +pushed to the project's own repository; it exists as a local branch for +review, testing and discussion. -Eine automatische Bemessung aller Stromkreise ist weiterhin nicht Bestandteil -des Moduls. +## Why a separate module instead of extending core domain code -## Aufbau +`AGENTS.md` is explicit that critical multi-write commands, the revision/undo +system and the Circuit-First domain model are the supported architecture, and +that changes should be small and reviewable. A cable-sizing calculation is +**not** a project mutation - it doesn't need `expectedRevision`, doesn't +belong in the undo/redo stack, and shouldn't grow the `circuit.update` +command's `switch` statement or the DTOs it doesn't already have. -```text -src/cable-sizing/domain/cable-sizing-calculation.ts Berechnung und Tabellen -src/cable-sizing/domain/cable-sizing-contracts.ts API-Validierung -src/server/controllers/cable-sizing.controller.ts zustandslose Endpunkte -src/server/routes/cable-sizing.routes.ts Router -src/frontend/components/cable-sizing-api.ts Fetch-Client -src/frontend/components/cable-sizing-defaults.ts Vorbelegung -src/frontend/components/cable-sizing-modal.tsx Dialog -tests/cable-sizing-calculation.test.ts Tabellen und Grenzfälle +So this module is built exactly like the existing `src/external-model/` +adapter (the Revit/CSV import foundation): a one-way dependency boundary. + +``` +src/cable-sizing/domain/ <- pure functions and types, zero imports from + db/, server/ or frontend/ +src/db/schema/ <- one new, fully additive table +src/db/repositories/ <- one plain repository (no revision semantics) +src/server/{controllers,routes}/cable-sizing.* <- one new, isolated route + group, mounted with a single app.use() line +src/frontend/components/cable-sizing-* <- one new modal + one small + API client, following the existing + FormModal / CircuitProtectionModal pattern ``` -Das Domänenmodul hängt weder von Datenbank, Server noch React ab. Die API ist -zustandslos. Im Stromkreis-Editor öffnet ein Rechner-Symbol den Dialog; die -Kabelzellen behalten ihr übliches Spreadsheet-Verhalten. +Nothing outside these files imports from them except the two required +one-line hooks described below. If this module is rejected or needs to move +out again, removing it is a matter of deleting these files, the two +one-line hooks, and running a `DROP TABLE` migration - it never touches +`circuits`, `project_revisions` or any command/history table. -## Eingaben +## The two required hooks into existing code -Aus dem Stromkreis werden Leistung, Phasen, Spannung, leistungsgewichtetes -cos φ, Leitungslänge und ein vorhandenes Überstromschutzorgan vorbelegt. Der -Planer wählt Verlegeart, Isolierstoff, Leitermaterial, Temperatur, Häufung, -zulässigen Spannungsfall und bei Drehstrom den Anteil der dritten Harmonischen. +1. `src/server/index.ts`: one import + one `app.use("/api/cable-sizing", cableSizingRouter)` + line, next to the existing `app.use("/api/projects", ...)` etc. +2. `src/frontend/components/circuit-tree-editor.tsx`: one new `useState` for + the open modal, one new trigger condition (mirroring the existing + `isProtectionTrigger` / `protectionEditorCircuit` pattern almost exactly), + and one new conditionally-rendered `` alongside the + existing ``. See the diff for the exact lines. -Eine Leitungslänge von `0 m` ist zulässig. Der Dialog weist sichtbar darauf -hin, dass dann kein Spannungsfall angesetzt wird. +No changes to `circuit-project-command.model.ts`, `project-command.service.ts`, +any Zod command schema, any migration for `circuits`/`project_revisions`, or +any existing test. -## Normative Grundlage und Grenzen +## Coupling to the grid UI (the one fragile point) -Die Strombelastbarkeiten und Korrekturfaktoren wurden gegen -**DIN VDE 0298-4 (VDE 0298-4):2023-06** einschließlich -**Berichtigung 1:2023-10** geprüft: +Everything described above - the calculation, the audit table, applying a +result via `circuit.update` - depends only on stable, explicitly documented +domain fields (`cableType`/`cableCrossSection`/`cableLength`/ +`circuitTotalPower`/`voltage`/`protectionDevice.ratedCurrentA`), the same +ones `AGENTS.md` already treats as protected ("Protection and cable data +belong to the circuit"). None of that breaks if the grid UI changes. -- Strombelastbarkeit: Tabellen 3 bis 6. -- Temperaturfaktoren: Tabellen 17 und 20. -- Häufung A1 bis C: Tabelle 22 nach der korrigierten Zuordnung. -- Häufung D: Tabelle 26 für sich berührende Rohre oder Kanäle im Erdreich. -- Oberschwingungen: Anhang B, insbesondere Tabelle B.1. +The one place that *is* coupled to a UI implementation detail: the click +trigger in `circuit-tree-editor.tsx` matches grid **column keys** +(`cableSummary` and `cableCrossSection`, defined in +`circuit-grid-model.ts`) to decide where to show the calculator icon. +Column visibility and order in this app are a per-browser user preference, +not fixed - so this is checked against both known cable-related columns to +reduce (not eliminate) the chance a user's personal column layout hides the +trigger entirely. If a future column rename removes both keys, the failure +mode is purely cosmetic: the calculator icon/click stops appearing on that +cell, nothing crashes, no data is affected, and the rest of the app +(including manual cable-field editing) is completely unaffected - the +module's actual logic and persistence never depend on this column key. -Unterstützt werden A1, A2, B1, B2, C, D und E. D bezeichnet ausschließlich -mehradrige Kabel oder Mantelleitungen im Rohr beziehungsweise Kanal im -Erdreich. Direkte Erdverlegung wird nicht angeboten, weil DIN VDE 0298-4 dafür -auf die Kabel-Produktnorm DIN VDE 0276-603 verweist. +## Feature overview -Für Verlegeart E hängen Häufungsfaktoren von Trägerart, Abstand und Anzahl der -Kabelpritschen ab. Diese Angaben gehören noch nicht zum Eingabemodell. Daher -ist E nur für einen einzelnen Stromkreis berechenbar. Für D sind höchstens -sechs gehäufte Stromkreise durch die verwendete Tabellenzeile abgedeckt. +- **Calculate a recommendation**: laying method, insulation, conductor + material, ambient temperature, grouping, cos phi and max voltage drop - + same VDE 0298-4 reference-method model as the sibling Kabelliste tool + (see Verification status below). +- **Breaker-aware sizing**: if the circuit already has a protection device + (`circuit.protectionDevice`), the cross-section is selected against + `designCurrentA = max(operatingCurrentA, protectionDevice.ratedCurrentA)`, + not the load current alone - the standard `In <= Iz` rule (a breaker only + trips at its own rated current, so a cable sized for the actual load + alone could overheat under sustained current below that threshold). If no + cross-section can cover an oversized breaker, that is reported as the + limiting factor by name, not a generic capacity error. +- **Maximum length for the voltage-drop limit**: each cross-section option + also reports the longest single run that still meets the requested + `maxVoltageDropPercent` at the given load - the inverse of the + voltage-drop check, shown for the recommended cross-section. +- **Practical minimum for socket circuits**: `single_phase`-category + circuits are raised to at least 2.5 mm² if the calculation alone would + recommend less - see the dedicated note under Verification status. Never + lowers a calculation that already needs more. +- **Manual entry, always available**: the modal has a plain text Kabeltyp/ + Querschnitt field. Running a calculation pre-fills it as a suggestion, + but the field is the single source of truth for what gets applied, and + stays freely editable - satisfying + `docs/spec/06-future-sizing-and-calculations.md`'s explicit requirement + that "users must remain able to manually override suggestions" without + requiring a calculation to have been run first. A non-blocking warning + appears if the typed value is not a standard cross-section, is smaller + than the last calculation, or is below the practical minimum above - + informational only, never forced, matching the same spec doc's "shown as + a warning or status indicator, not as an automatic forced change." -Aluminium wird erst ab 25 mm² angeboten, weil die verwendeten Tabellen keine -kleineren Aluminiumquerschnitte enthalten. Bei mehr als 33 % dritter -Harmonischer ist der Neutralleiterstrom Bemessungsgrundlage. Solange dieser -nicht als Zahlenwert eingegeben und berechnet wird, liefert das Modul keine -Empfehlung. +## How a suggestion or manual entry is applied -Die Berechnung des Spannungsfalls ist eine vereinfachte Ergänzung mit -Leitfähigkeit bei Betriebstemperatur; Reaktanz wird vernachlässigt. Ihre -Planungsgrenzen folgen nicht allein aus DIN VDE 0298-4. Auch die Koordination -mit Leitungsschutzschaltern und gG-Sicherungen gehört zur -Überstromschutzbemessung und ist getrennt von der Strombelastbarkeit zu -beurteilen. Der Dialog bezeichnet diese Ergebnisse deshalb nicht als vollständig -normative Leitungsbemessung. +The module never writes to `circuits` directly. The modal's "Übernehmen" +button calls the **existing, unmodified** frontend helper with whatever is +currently in the Kabeltyp/Querschnitt fields, calculated or hand-typed: -## Rechenweg +```ts +updateCircuitById(projectId, expectedRevision, circuitId, { + cableCrossSection: "4 mm²", + cableType: "NYM-J 3x2.5", + cableLength: 30, +}); +``` -1. Betriebsstrom `I_B` aus Leistung, Spannung, cos φ und Phasenzahl. -2. Erforderliche Belastbarkeit aus `I_B` und gegebenenfalls dem vorhandenen - Schutzorgan. -3. Tabellenwert `I_z` multipliziert mit Temperatur-, Häufungs- und gegebenenfalls - Oberschwingungsfaktor. -4. Vereinfachter Spannungsfall für jeden verfügbaren Querschnitt. -5. Empfehlung als größerer Querschnitt aus Belastbarkeit und Spannungsfall. -6. Bei einphasigen Stromkreisen Anhebung auf den vereinbarten praktischen - Mindestquerschnitt von 2,5 mm². +which is the same `circuit.update` command the grid already uses for manual +cell edits. This means: -Temperaturen und Häufungen zwischen Tabellenwerten werden zum nächsten -ungünstigeren Tabellenwert gerundet. Außerhalb des belegten Tabellenbereichs -wird keine Empfehlung ausgegeben. Ein abweichender Querschnitt kann weiterhin -manuell eingetragen und bewusst übernommen werden. +- optimistic concurrency (`expectedRevision`) is respected automatically +- the change appears in the project's revision history and is undoable/ + redoable exactly like a manual edit +- nothing is ever written automatically - calculating only fills the modal's + own fields, applying is always an explicit, separate click -## Nicht enthalten +## API contract -- direkte Erdverlegung -- detaillierte Anordnung mehrerer Kabel bei Verlegeart E -- Neutralleiterbemessung bei mehr als 33 % dritter Harmonischer -- Kurzschlussfestigkeit, Schleifenimpedanz, Abschaltbedingungen und Selektivität -- abweichender Bodenwärmewiderstand sowie Verlegearten F und G -- automatische Berechnung oder Änderung mehrerer Stromkreise +`POST /api/cable-sizing/calculate` -## API +```jsonc +{ + "phase": 1, // 1 | 3 + "mode": "power", // "power" | "current" + "powerKw": 4.2, // circuit.circuitTotalPower, when mode="power" + "cosPhi": 1, + "voltage": 230, // circuit.voltage (already project-derived, read-only) + "lengthM": 23.5, // circuit.cableLength + "layingMethod": "C", // DIN VDE 0298-4 reference method, A1|A2|B1|B2|C|D1|D2|E|F|G + "conductorMaterial": "copper", // "copper" | "aluminum" + "insulation": "pvc", // "pvc" | "xlpe" + "ambientTemperatureC": 30, + "groupingCircuits": 1, + "maxVoltageDropPercent": 3, + "harmonicNeutralLoad": "none", // "none" | "15to33Percent" | "over33Percent", three-phase only + "existingProtectionRatedCurrentA": 16, // optional, from circuit.protectionDevice + "circuitCategory": "single_phase", // optional, from the circuit's section.category - + // enables the practical-minimum convention below + "context": { "projectId": "...", "circuitId": "...", "equipmentIdentifier": "-1F1.1" } +} +``` -`POST /api/cable-sizing/calculate` berechnet zustandslos. Die Verlegeart ist -`A1 | A2 | B1 | B2 | C | D | E`; `lengthM` darf `0` sein. Das Ergebnis enthält -`supported: false` und einen der Gründe `temperature`, `grouping` oder -`harmonics`, wenn keine belastbare Empfehlung möglich ist. +Response: `{ calculationId, result: CableSizingResult, alerts: CableSizingAlert[] }` +(see `src/cable-sizing/domain/cable-sizing-calculation.ts` for the exact +shape). `GET /api/cable-sizing/laying-methods` and `.../insulation-materials` +expose the pick-list metadata (including which combinations are verified) so +a future non-modal UI could build its own form without hard-coding the enum. -`GET /api/cable-sizing/laying-methods` und -`GET /api/cable-sizing/insulation-materials` liefern die Auswahllisten. +## Verification status - important + +The reference current-carrying-capacity tables are ported from a sibling +project's Kabelliste module, which was itself only verified against ~8 +public sources for **six** of the ten DIN VDE 0298-4 reference laying +methods (A1, B2, C, E, D1, D2) and **PVC insulation only**. The other four +methods (A2, B1, F, G) and XLPE/VPE insulation could not be verified without +contradiction across sources during that earlier work, so +`calculateCableSizing` deliberately returns `dataVerified: false` and no +numeric recommendation for those combinations, rather than a guessed value. +The UI surfaces this as a plain critical alert. Anyone with access to the +actual norm text can extend `LAYING_METHOD_VERIFIED` and +`CURRENT_CAPACITY_A` in `src/cable-sizing/domain/cable-sizing-calculation.ts` +once the missing tables are confirmed. + +The protection-coordination check (`existingProtectionRatedCurrentA` vs. the +recommended cross-section's corrected capacity) is a **simplified** `In <= +Iz` check only - it is not a full IEC 60364-4-43 overload (`I2 <= 1.45 x +Iz`) or short-circuit withstand check. + +`PRACTICAL_MINIMUM_CROSS_SECTION_MM2` (2.5 mm² for `single_phase`) is +**not** a verified norm value at all - it is a named planning convention, +sourced directly from this project's own +`docs/spec/06-future-sizing-and-calculations.md` ("Standard Single-Phase +Circuits ... usually use ... cable cross-section: 2.5 mm²"), applied as a +floor on top of the calculated recommendation. It intentionally only +covers the one category and one convention that document already states; +it is not a general substitute for norm-compliant calculation. + +## Relationship to the project's own future-sizing spec + +`docs/spec/06-future-sizing-and-calculations.md` separately describes simple +category-based defaults (e.g. lighting circuits -> 10 A / 1.5 mm²) as +"common planning defaults, not a replacement for full norm-compliant +calculation". This module is the latter: an on-demand, norm-referenced +calculation for one circuit at a time, not a bulk default-filling tool. The +two are complementary and could later be wired together (e.g. the category +defaults pre-fill this module's laying-method/insulation fields), but that +integration is out of scope here. + +The spec's `isPublicBuilding` halogen-free rule and the `Control Requirement` +(DALI/KNX/core-count) field are **not** implemented by this module - both +concern cable *type* selection, not cross-section sizing, and the latter +isn't in the current schema yet. They're natural follow-ups once this module +is reviewed. + +## Maintenance plan + +The `src/cable-sizing/domain/` folder has zero imports from the rest of the +app by design (see the dependency-direction note above), so it can be +extracted into an independently versioned/published package later (e.g. a +private npm package or a git subtree) without touching anything outside the +five files/folders listed above - "separately maintained but part of the +app for now", per the intent of this proposal. + +## Local testing + +Deployed and manually exercised end-to-end on an internal test host at +`http://192.168.0.133:3220` (own docker deployment, own subnet/ports to +avoid clashing with ~50 other containers on that host - see the two +commits marked "Local-only" in this branch, which are not part of this +proposal and should not be carried over if it is ever proposed upstream). +Exercised against seeded real project/circuit data created through the +actual command API (not direct DB writes), including a deliberately long +(85 m) circuit to trigger the voltage-drop-critical path. + +`npm test`, `npm run build:api`, `npm run build:web` and +`npm run typecheck:scripts` all pass with this module included at every +commit in this branch. + +This branch (`feature/cable-sizing-module`) is pushed to a mirror of this +repository under this homelab's own Forgejo instance, not to +`git.jappel.io` - no write access to the upstream repository was available +or used. See the branch's commit history for the incremental history of +this module, including fixes made during manual testing (trigger column, +icon rendering, breaker-aware sizing). diff --git a/docs/circuit-list-editor-api.md b/docs/circuit-list-editor-api.md index c88e4aa..b1d7f07 100644 --- a/docs/circuit-list-editor-api.md +++ b/docs/circuit-list-editor-api.md @@ -59,24 +59,6 @@ this value for optimistic concurrency checks. - clients cannot submit arbitrary `project.restore-state` payloads through the generic command endpoint -Grobbilanzen sind bewusst kein Teil dieser logischen Snapshots. Der portable -Projektexport unter `GET /projects/:projectId/export` verwendet dagegen -Transferformat 2 und enthält alle Grobbilanzen. Die beiden Importwege -`POST /projects/:projectId/import` und `POST /projects/import` prüfen ihre -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 10 enthält Linear-XLSX-Zustand und die in -Schema 9 eingeführten 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 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 `circuit.update`, `circuit.insert`, `circuit.delete`, `circuit-device-row.update`, `circuit-device-row.insert`, @@ -232,12 +214,6 @@ 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 @@ -258,106 +234,66 @@ 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, "feedingDistributionBoardId": "board_hv", "feedingCircuitId": "circuit_out", "expectedRevision": 13 }` + `{ "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` - - `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 + - executes `distribution-board.update`; all submitted values, including the 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. + - `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 - while preserving project-device, room and incoming feeding links + while preserving project-device and room 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 `distribution-board.delete-subtree`. Persistent Undo/Redo restores or removes the same complete subtree, including protection devices. -### Project Buildings, Floors and Rooms +### Project Floors and Rooms -- `GET /projects/:projectId/buildings` -- `POST /projects/:projectId/buildings` - - body: `{ "name": "Haus A", "expectedRevision": 12 }` - - executes `project-building.insert` with a stable building id - - response: `{ "building": { ... }, "revision": { ... }, "history": { ... } }` -- `PUT /projects/:projectId/buildings/:buildingId` - - body: `{ "name": "Haus B", "expectedRevision": 13 }` (name only) -- `DELETE /projects/:projectId/buildings/:buildingId` - - body: `{ "expectedRevision": 14 }` - - rejects buildings with assigned floors - `POST /projects/:projectId/floors` - - body: `{ "name": "EG", "buildingId": "building_1", "expectedRevision": 13 }` - (`buildingId` optional, `null` = no building) - - executes `project-floor.insert` (command version 2) with a stable floor id + - body: `{ "name": "EG", "expectedRevision": 13 }` + - executes `project-floor.insert` with a stable floor id - response: `{ "floor": { ... }, "revision": { ... }, "history": { ... } }` - `PUT /projects/:projectId/floors/:floorId` - - body: `{ "name": "1. OG", "buildingId": null, "expectedRevision": 14 }` - - executes an exact persistent floor update of name and/or building; a - missing `buildingId` keeps the current building + - body: `{ "name": "1. OG", "expectedRevision": 14 }` + - executes an exact persistent floor update - `DELETE /projects/:projectId/floors/:floorId` - body: `{ "expectedRevision": 15 }` - rejects floors with assigned rooms or distribution boards - `POST /projects/:projectId/rooms` - body: - `{ "floorId": "floor_1", "roomNumber": "001", "roomName": "Technik", "areaM2": 18.75, "expectedRevision": 14 }` - - executes `project-room.insert` command version 2 with a stable room id; - `floorId` and `areaM2` are optional. An omitted or explicit `null` area - creates a room without area; a value must be finite and non-negative. + `{ "floorId": "floor_1", "roomNumber": "001", "roomName": "Technik", "expectedRevision": 14 }` + - executes `project-room.insert` with a stable room id; `floorId` is optional + and must belong to the project when present - response: `{ "room": { ... }, "revision": { ... }, "history": { ... } }` - `PUT /projects/:projectId/rooms/:roomId` - body: - `{ "floorId": null, "roomNumber": "101", "roomName": "Büro", "areaM2": null, "expectedRevision": 16 }` - - updates number, name, optional floor and area as one persistent version-2 - command. If `areaM2` is omitted, the current area is retained; `null` - explicitly clears it. + `{ "floorId": null, "roomNumber": "101", "roomName": "Büro", "expectedRevision": 16 }` + - updates number, name and optional floor as one persistent command - `DELETE /projects/:projectId/rooms/:roomId` - body: `{ "expectedRevision": 17 }` - rejects rooms referenced by device rows - Persistent Undo/Redo restores exact previous and target records without silently clearing foreign keys. -- Stored version-1 room commands remain executable and are upgraded with - `areaM2 = null`. Exact expected-record checks reject an old update or delete - if a newer command has added an area, so legacy history cannot silently - erase it. - Stale revisions return `409 PROJECT_REVISION_CONFLICT`. ### 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. Circuit totals contain the demand of linked downstream - 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. + remain included. Response sketch: @@ -463,76 +399,37 @@ 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) +## Revit CSV Foundation -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`. +- `GET /projects/:projectId/external-csv/configuration` + - returns the complete versioned project configuration or `null` +- `PUT /projects/:projectId/external-csv/configuration` + - request: `expectedRevision` and the complete validated configuration + - executes `external-csv-configuration.update` + - returns configuration, revision and project history state +- `POST /projects/:projectId/external-csv/preview` + - request: file name and Base64-encoded CSV content up to 18 MB + - requires a stored project configuration + - returns transport metadata, SHA-256, row classifications, suspect row + numbers and mapped source values for every recognized IFC object + - does not persist a draft, mutate project state or create a revision +- `POST /projects/:projectId/external-csv/initial-import/plan` + - reparses the file and returns grouped room/family decisions plus current + room, distribution-board and ProjectDevice catalogs + - is stateless and rejects an already imported external source +- `POST /projects/:projectId/external-csv/initial-import/apply` + - requires the expected revision, configuration version, file hash and one + decision for every room and exact family/type group + - reparses the file, blocks unknown family/type values and executes + `external-import.apply-initial` as one undoable project revision + - creates no Circuit or CircuitDeviceRow +- `GET /projects/:projectId/circuit-lists/:circuitListId/external-objects` + - resolves the circuit list's distribution board server-side + - returns only external objects assigned to that board, with unassigned + objects first, their source room/marker values and current row-link status + - returns an empty list when the optional Revit import does not exist + - is read-only and exposes no stored command payloads or import bytes -- `POST /cable-sizing/calculate` - - request: phase, mode (`power` | `current`), powerKw or currentA, cosPhi, - voltage, lengthM, layingMethod (`A1` | `A2` | `B1` | `B2` | `C` | `D` | - `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 or the neutral current needed above 33 % third - harmonic is unavailable - - 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 / Linear XLSX - -- `GET|PUT /projects/:projectId/external-model/configuration` reads or writes - the complete XLSX configuration. PUT requires `expectedRevision`. -- `POST /projects/:projectId/external-model/configuration/detect` detects the - sheet layout and columns from an uploaded `.xlsx` sample without persisting. -- `GET /projects/:projectId/external-model/import-status` returns the latest - batch metadata, object count and current missing-object count. -- `POST .../initial-import/plan|apply` provides the stateless initial plan and - its confirmed atomic application. Apply retransmits and reparses the XLSX. -- `POST .../follow-up-import/plan|apply` classifies exact Worksharing-ID - additions, source changes, unchanged and missing objects. Apply requires the - preview hash and source decisions and updates linked row quantities atomically. -- `GET|PUT .../external-model/objects` loads one compact project list and - applies revision-safe multi-object planning changes. -- `POST .../objects/assign-row|assign-new-row|assign-new-circuit|detach-row` - changes external-object row assignments through persistent commands. -- `POST .../objects/delete-missing` requires `confirmed: true`, deletes only - objects marked missing and adjusts linked row quantities in the same command. -- `POST .../external-model/return-workbook` creates the structure-preserving - return XLSX for all, deviating or selected objects. -- `GET .../external-model/export-batches` returns append-only export metadata. - -Uploads accept only `.xlsx` up to 10 MiB. Worksharing-IDs are exact and -case-sensitive; IfcGUID is optional and non-unique. Undo/Redo uses persisted -command states and never reparses workbook bytes. - -## 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" } }` +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. diff --git a/docs/circuit-list-editor-interactions.md b/docs/circuit-list-editor-interactions.md index 8050cfe..c8c02aa 100644 --- a/docs/circuit-list-editor-interactions.md +++ b/docs/circuit-list-editor-interactions.md @@ -1,8 +1,5 @@ # Circuit List Editor Interactions -The back-arrow link beside the page title returns to the project's distribution -board overview without changing circuit-list data. - ## Editing Model Inline cells are static text by default. A cell enters edit mode by: @@ -47,7 +44,6 @@ Selection, keyboard movement, and editability checks run against this normalized - arrow keys: move selected cell in grid when not editing - type-to-edit: printable keys open edit mode and replace current display value with typed character - `Ctrl+Plus` / `Ctrl+Shift+Plus`: insert below the selected circuit or device context -- `Alt+ArrowDown` on a GZF cell (selected or editing): open the AMEV simultaneity-factor table - `Delete`: delete the selected circuit or device context after confirmation For insertion, a circuit-level cell creates a reserve circuit directly after the selected circuit. A device-level cell creates a manual device row directly after the selected device. On the virtual `-frei-` row, or without a valid row selection, the shortcut creates a circuit at the end of the active section. Insertions use command history and never renumber existing equipment identifiers. @@ -56,23 +52,6 @@ For deletion, a circuit-level cell targets the complete circuit and a device-lev Creating or deleting a device row updates the row and the circuit reserve state in one SQLite transaction. -## AMEV Simultaneity Factor - -The selected GZF cell shows a small table-icon button; it and `Alt+ArrowDown` open -the shared `GzfPickerModal` (AMEV Planungshilfe, Tabelle 3), which the project -device dialog uses as well. "Übernehmen" commits the mean value of the chosen -consumer group through the same path as a typed edit (`commitEdit` with an -explicit target cell), so it is one undoable command and works on device rows, -compact circuits, reserve circuits and the `-frei-` row. A running inline edit -of the cell is discarded when the picker opens. The button only appears on the -selected cell; the grid keeps its static-text cells. - -The dialog takes keyboard focus, keeps Tab/Shift+Tab within its actions and -closes on Escape without writing a value. Closing returns focus to the grid; -only "Übernehmen" saves the selected mean value. Opening the picker is disabled -while a write or history operation is running. Its cell button stays outside -the Tab order; `Alt+ArrowDown` provides keyboard access from the selected cell. - ## Equipment Identifier Validation Equipment identifiers are compared case-insensitively after trimming whitespace. A conflicting edit is highlighted before submission and cannot be committed. Existing conflicts are highlighted in the grid. Validation errors remain dismissible above the editor instead of replacing the complete workspace. @@ -148,30 +127,11 @@ Cross-section device moves show confirmation-required feedback before drop. The ## Filtering and Sorting -- Clicking a column label changes sorting; the funnel icon next to it opens - the value filter. An active filter is highlighted and shows the number of - selected values. Both controls retain German accessible names and tooltips. -- Header labels wrap between words; trailing units such as `[kW]` appear on - a separate line. - Per-column filtering works on normalized displayed values. - Sorting is view-level first and treats circuits as blocks. - Multi-device circuits are not split during sort. - Sorting alone does not persist order. -## Action Buttons - -The editor toolbar uses icons with visible German labels. Group headers and -circuit/device rows use compact icon buttons with German accessible names and -tooltips. Group protection buttons additionally show `VS` or `FI` to distinguish -their roles. Dividers separate related actions; destructive actions use the -danger style. Circuit deletion uses a trash icon, while device-row deletion -uses a crossed-out list icon. - -The shared `src/frontend/components/icon-button.tsx` component preserves -disabled states and expanded states for toggles. Row and group action buttons -retain `tabIndex={-1}` so the spreadsheet's existing cell navigation remains -unchanged. The existing command handlers and deletion confirmations are reused. - ## Apply Sorted Order `Apply sorted order` persists current sorted block order to backend by section. @@ -201,11 +161,6 @@ across multiple sections is atomic and occupies one history step. Explicit renumbering uses a collision-safe persistent project command and one project-history step. -The editor creates client-side UUIDs through `createClientId` in -`src/frontend/utils/client-id.ts`. It uses `crypto.randomUUID()` when available -and otherwise generates a UUID v4 with `crypto.getRandomValues()`, so insertion -also works over plain HTTP from another machine in the LAN. - Covered operations include: - insert/delete circuit diff --git a/docs/circuit-list-editor-known-limitations.md b/docs/circuit-list-editor-known-limitations.md index f9fecb5..3e70e76 100644 --- a/docs/circuit-list-editor-known-limitations.md +++ b/docs/circuit-list-editor-known-limitations.md @@ -9,20 +9,16 @@ - 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. -- Die Linear-XLSX-Anbindung bis R10 ist umgesetzt: Erst- und Folgeimport, - Objektplanung und Editorzuordnung, strukturtreue Rückgabe sowie bestätigtes - Löschen fehlender Objekte verwenden persistente Commands. Die vollständige - Kette ist mit 5.000 synthetischen Objekten sowie Snapshot-, Transfer- und - Neustarttests geprüft. +- The Revit/CSV foundation and confirmed initial import are implemented. + 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 + export are pending. - 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. -- There is no automatic sizing of all circuits. The optional cable sizing - module suggests a cross-section for one circuit on demand using - DIN VDE 0298-4:2023-06 with Berichtigung 1:2023-10. It excludes direct - burial, grouped method E and neutral-current sizing above 33 % third - harmonic, and it does not check short-circuit withstand, disconnection time - or selectivity. See `docs/cable-sizing-module.md`. +- Final electrical sizing logic is not implemented yet. +- No full norm-compliant voltage-drop and protection-dimensioning calculation flow yet. - 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 @@ -31,13 +27,10 @@ - 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. -- 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`). +- 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 diff --git a/docs/current-architecture.md b/docs/current-architecture.md index d7f28cb..5230b74 100644 --- a/docs/current-architecture.md +++ b/docs/current-architecture.md @@ -27,38 +27,15 @@ Next.js App Router ── /api/* Rewrite ──▶ Express API :3000 data/leistungsbilanz.db (SQLite) ``` -In beiden Docker-Stacks laufen Frontend und API in getrennten Containern. -`compose.yaml` startet den gebauten Stand, `compose.dev.yaml` die Entwicklung -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 -`crypto.getRandomValues()` mit UUID-v4-Format. Damit funktioniert das Anlegen -auch beim HTTP-Zugriff im LAN ohne sicheren Browserkontext. Die IDs entstehen -vor dem Command und bleiben über Undo/Redo unverändert. +Im Docker-Entwicklungssetup laufen Frontend und API in getrennten Containern. Das +Frontend leitet `/api/*` über `API_INTERNAL_URL` an die API weiter. Die Datenbank +liegt über einen Host-Mount außerhalb des Containers. ## Wichtige Einstiegspunkte - `src/app/projects/page.tsx` – Projektliste und globale Gerätebibliothek -- `src/app/projects/[projectId]/page.tsx` – Projektstammdaten, Verteilungen - und Projektgeräte -- `src/app/projects/[projectId]/struktur/page.tsx` – Gebäude, Etagen, Räume - und Raumflächen -- `src/app/projects/[projectId]/grobbilanz/` – Stände und Editor der groben - Leistungsbilanz -- `src/app/projects/[projectId]/print/page.tsx` – Seitenansicht und PDF-Export +- `src/app/projects/[projectId]/page.tsx` – Projektstammdaten, Verteilungen, + Räume und Projektgeräte - `src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx` – unterstützte Editorroute - `src/frontend/components/circuit-tree-editor.tsx` – Editorzustand, @@ -66,11 +43,6 @@ 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 @@ -262,7 +234,7 @@ liefern Gerät und aktualisierten Historienstand an die Projektseite zurück. `project.update-settings` versioniert Projektname, interne und externe 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 +`0009`), 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 @@ -274,55 +246,22 @@ Werte, Revision und Historienstapel gemeinsam. `PUT /api/projects/:projectId` verlangt deshalb `expectedRevision`, liefert Projekt plus aktualisierten Historienstand und besitzt keinen separaten direkten Settings-Schreibweg mehr. Kommando- und Snapshot-Payloads müssen dem aktuellen Baseline-Schema entsprechen. -Die Projektseite zeigt Verteilungen als kompakte Bestandsübersicht; ihre -versionierten Erstellwege öffnen beschriftete Modals statt dauerhafter -Eingabezeilen. Gebäude, Etagen und Räume werden auf der eigenen Seite -„Gebäudestruktur“ (`/projects/:projectId/struktur`) gepflegt; Etagen können -einem Gebäude zugeordnet sein (`docs/building-structure.md`). Projektgeräte werden als durchsuchbare, +Die Projektseite zeigt Verteilungen, Etagen und Räume als kompakte +Bestandsübersichten; ihre versionierten Erstellwege öffnen beschriftete Modals +statt dauerhafter Eingabezeilen. Projektgeräte werden als durchsuchbare, fünfspaltige Übersicht dargestellt. Manuelle Anlage, Übernahme aus der globalen Bibliothek und vollständige Bearbeitung erfolgen in einem gemeinsamen Modal. Die anschließende Vorschau verknüpfter Stromkreiszeilen bleibt davon getrennt, damit Änderungen weiterhin niemals still synchronisiert werden. -Die Karten Verteilungen und Projektgeräte besitzen je eine einklappbare -Filterleiste im Stil der PM-App (Suche, Mehrfachauswahl für Etage/Netzart bzw. -Kategorie/Phasenzahl/Kostengruppe, „Zurücksetzen“, Anzeige „x von y“); die -Filterlogik liegt rein in `src/frontend/utils/overview-filters.ts`, der -Einklappzustand je Karte in `localStorage`. Aktionen verwenden wie der Editor -`IconButton`/`IconLink`. -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 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 -und die Suche gemeinsam. Eine leere Auswahl bedeutet „Alle“; fehlende -Zuordnungen sind über „Ohne Etage“, „Nicht festgelegt“ beziehungsweise -„Ohne Kostengruppe“ auswählbar. Nicht mehr angebotene Auswahlwerte werden bei -der Filterung ignoriert. „Zurücksetzen“ leert die Filter der jeweiligen Karte. -Beim Einklappen bleiben aktive Filter wirksam und durch „Filter aktiv“ sichtbar. -Nur der Einklappzustand wird je Kartentyp im Browser gespeichert; Suchbegriffe -und Filterauswahl werden nicht dauerhaft gespeichert. Die Filter ändern keine -Projektdaten und erzeugen keine Revisionen. Das Löschen eines Projektgeräts -erfordert eine Bestätigung mit dessen Namen und verwendet weiterhin den -bestehenden persistenten Projektbefehl. - -`GET /api/projects/:projectId/export` verpackt den vollständigen portablen -Projektzustand in ein format- und schema-versioniertes JSON-Dokument mit -SHA-256-Prüfsumme. Transferformat 2 enthält zusätzlich alle Grobbilanzen, -ohne sie in das logische Snapshot-Schema aufzunehmen; Format 1 bleibt ohne -Grobbilanzen importierbar. `POST /api/projects/:projectId/import` prüft Format, -Snapshot-Relationen, Grobbilanzen und Prüfsumme vor jedem Schreibzugriff. Der -Modus `replace` läuft über `project.restore-state` Version 2 und ersetzt den -Projektzustand und die Grobbilanzen atomar und dauerhaft rückgängig machbar. -Normale Snapshot-Restores verwenden weiterhin Version 1 und lassen -Grobbilanzen unverändert. Der Modus `duplicate` ordnet Projekt-, +`GET /api/projects/:projectId/export` verpackt denselben vollständigen +Projektzustand in ein portables, format- und schema-versioniertes JSON-Dokument +mit SHA-256-Prüfsumme. `POST /api/projects/:projectId/import` prüft Format, +Snapshot-Relationen und Prüfsumme vor jedem Schreibzugriff. Der Modus `replace` +läuft über `project.restore-state` und ist dadurch eine atomare, dauerhaft +rückgängig machbare Projektrevision. Der Modus `duplicate` ordnet Projekt-, Struktur-, Gruppen-, Verteilerkomponenten-, Raum-, Stromkreis- und -Gerätezeilen-UUIDs sowie Schutzgeräte-Referenzen und die IDs aller Grobbilanzen -vollständig neu zu und legt die Kopie mit Revision `0` in einer Transaktion an. -Fachliche Verknüpfungen +Gerätezeilen-UUIDs sowie Schutzgeräte-Referenzen vollständig neu zu und legt +die Kopie mit Revision `0` in einer Transaktion an. Fachliche Verknüpfungen innerhalb des unterstützten Laufzeitmodells bleiben erhalten. Die Projektübersicht verwendet dafür den separaten Collection-Endpunkt @@ -479,53 +418,17 @@ 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`. Derselbe Befehl versioniert die Felder der Verteiler-Infokarte -(`boardNumber`, `location`, `fedFrom`, `remark`, Migration `0007`). Die +(`boardNumber`, `location`, `fedFrom`, `remark`, Migration `0008`). 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` 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. -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 -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 -`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. +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 -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, +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, Gruppenkategorie und -nummer, Verteilerkomponenten sowie die getrennten 1:1-Schutzgerätedaten. Capture, benannte und automatische Snapshots, Wiederherstellung, Undo/Redo und beide @@ -536,12 +439,7 @@ Baseline-Version 1 wird zusätzlich mit `isPublicBuilding = false` hochgestuft; dieser Baseline werden nicht eingelesen. Persistente Insert-, Update- und Delete-Commands versionieren Anlage, Bearbeitung und Löschung von Geschossen und Räumen mit stabilen UUIDs und -exakten Vorher-/Nachher-Snapshots. Raumbefehle verwenden Version 2 und führen -die nullable, nicht negative Netto-Raumfläche `areaM2`; Version-1-Befehle -werden mit `null` hochgestuft und bleiben durch den vollständigen -Snapshotvergleich konfliktfest. Der Raumdialog pflegt die Fläche manuell mit -deutscher Dezimaleingabe, die Gebäudestruktur zeigt zwei Nachkommastellen sowie -Summen und die Anzahl fehlender Flächen je Etage und Gebäude. Ein Geschoss wird nur +exakten Vorher-/Nachher-Snapshots. Ein Geschoss wird nur entfernt, solange ihm weder ein Raum noch eine Verteilung zugeordnet wurde. Ein Raum wird nur entfernt, solange keine CircuitDeviceRow auf ihn verweist. Alle Schreibendpunkte verlangen `expectedRevision` und liefern den aktualisierten @@ -562,36 +460,6 @@ 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. Strombelastbarkeit, Temperatur -und Häufung beruhen auf DIN VDE 0298-4:2023-06 einschließlich -Berichtigung 1:2023-10; Spannungsfall und Schutzorgan werden ergänzend und mit -den in der Moduldokumentation beschriebenen Grenzen geprüft. 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`. - -## Grobe Leistungsbilanz - -Das Modul `src/estimate-balance` mit der importfreien Rechnung in -`src/shared/estimate-balance` führt Leistungsbilanzen für LPH 2/3 nach -DIN-276-Kostengruppen in eigenen Tabellen (`estimate_*`, Migration `0010`). -Es ist nicht mit der Stromkreisstruktur verknüpft und liest Gerätezeilen nur -für den Vergleich „geschätzt ↔ detailliert“ über das längste passende -Kostengruppen-Präfix. Schreibzugriffe laufen über `estimate-balance.insert`, -`.update` und `.delete` mit vollständigen Dokumenten, also mit Revision und -Undo/Redo. Grobbilanzen sind Teil von Transferformat 2, aber bewusst nicht Teil -der logischen Snapshots; ein Restore lässt sie unverändert. Einzelne Zeilen -lassen sich über den vorbelegten Projektgeräte-Dialog ausdrücklich als -Projektgerät kopieren (`project-device.insert`, ohne gespeicherte Verknüpfung). -Oberfläche: `/projects/:projectId/grobbilanz`. Details: -`docs/estimate-balance.md`. - ## Persistenz und Migration - SQLite ist die aktuell unterstützte Datenbank. @@ -626,7 +494,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 10. Persistente + Transfer-Integration verwenden aktuell Snapshot-Schema 5. 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 @@ -643,67 +511,141 @@ 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 nach R10 +## Revit-CSV-Grundlage -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`. +Der reine Adapter unter `src/external-model/csv` validiert die projektweite +Transport- und Mappingkonfiguration und parst UTF-8-CSV verlustarm in eine +klassifizierte Zellmatrix. Er erkennt Metadaten, Header, Passthrough-, Objekt- +und Verdachtszeilen, prüft IFCGUIDs und serialisiert unveränderte Revit-Exporte +einschließlich BOM, CRLF und Quotierung bytegleich zurück. Der lokale Befehl +`npm run revit:verify-reference` prüft die bereitgestellte Referenzdatei. -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. +`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, +Restore und portabler Projekttransfer enthalten diesen Zustand; beim Duplizieren +werden Konfigurations-UUID und Projektlink remapped. -Der XLSX-Adapter liegt unter `src/external-model/xlsx`. Der Backend-CSV-Parser, -seine Endpunkte und Laufzeitverträge sind entfernt. Die Route -`/projects/:projectId/revit` enthält Einstellungen, Importstatus und den -sechsstufigen Erstimportwizard. +Migration `0003` ergänzt die relationale Grundlage für genau eine implizite +`revit_csv`-Quelle je Projekt, geordnete Importbatches, normalisierte +Quellraummappings und über `(sourceId, ifcGuid)` eindeutige externe Objekte. +Batches halten Konfigurationssnapshot, Originalbytes und die klassifizierte +Zellmatrix zusammen. Migration `0004` ergänzt die monotone projektweite +Konfigurationsversion am Batch, getrennt von der Schema-Version des +Konfigurationsformats. Quellwerte, lokale Planungswerte und Override-Metadaten +der Objekte sind getrennt; optionale Links auf Raum, Verteilung, ProjectDevice +und CircuitDeviceRow bleiben nullable. `ExternalModelStateRepository` liest den +vollständigen Zustand deterministisch und unterscheidet unbekannte von noch +nicht importierten Projekten. Der letzte bestätigte Batch wird aus der +Batchreihenfolge abgeleitet statt redundant an der Quelle gespeichert. +Snapshot/Transfer v5 erfasst zusätzlich `manualQuantity`; Version 4 wird mit +dem bisherigen Gesamtwert als manuellem Anteil hochgestuft. Originalbytes, +Matrix und alle internen Links werden weiterhin vollständig erfasst, +stellt sie in Fremdschlüsselreihenfolge wieder her und remappt beim +Projektduplikat jede interne UUID; IFCGUID und Quelltransport bleiben +unverändert. `external-import.apply-initial` ist die atomare Schreibgrenze für +einen bestätigten Erstimport. Vor dem Insert prüft sie den aktuellen +Konfigurationsstand, SHA-256 und Base64-Kanonizität, parst die Originalbytes +erneut, vergleicht Matrix, vollständige IFCGUID-Menge und Quellwerte und +validiert alle Raum-, Verteiler- und ProjectDevice-Links gegen das Projekt. +Nicht explizit als Override markierte Planungswerte müssen dem regelbasierten +Vorschlag entsprechen. Der Command erzeugt und verknüpft ausdrücklich keine +CircuitDeviceRow; Undo entfernt den vollständigen unveränderten Importzustand, +Redo verwendet dieselben UUIDs und Bytes. Bloße Vorschau und Importplanung +erzeugen weiterhin keine dieser Zeilen. -`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. - -R6 bis R9 ergänzen die einmal geladene, clientseitig gefilterte und -virtualisierte Projektobjektliste, revisionierte Sammelplanung, atomare -Zuordnung im Stromkreislisteneditor, strukturtreue Rückgabe und den -vollständigen Folgeimport. Der Folgeimport trennt fachliche Quelländerungen -von noch nicht nach Revit übernommenen Rückgabewerten, aktualisiert akzeptierte -Mengen samt Row-Summe und markiert fehlende Objekte ohne ihren Link zu lösen. -Eine gesondert bestätigte Aktion löscht fehlende Objekte samt Mengenübergang; -Undo stellt Objekt, Link und Menge wieder her. - -R10 weist den Ablauf über Rückgabe, Folgeimport, Snapshot-Restore, -Projektduplikat und Undo/Redo nach Datenbankneustart nach. Persistenzpfade für -vollständige externe Zustände schreiben große Mengen in begrenzten -SQLite-Blöcken. Der synthetische Abnahmetest verarbeitet 5.000 Objekte; Details -und Messwerte stehen in -[R10-Abnahme](spec/revit-excel-r10-validation.md). - -## Historische CSV-Unterlagen - -Der vor R3 vorhandene CSV-/IfcGUID-Laufzeitpfad ist entfernt. Seine damalige -Ausgangslage bleibt ausschließlich im [R0-Audit](spec/revit-excel-r0-audit.md) -und in den als abgelöst markierten CSV-Spezifikationen nachvollziehbar. Alte -CSV-Snapshots und CSV-History werden weiterhin ausdrücklich abgelehnt. +Migration `0005` trennt bei `CircuitDeviceRow` den manuellen Mengenanteil vom +weiterhin materialisierten Gesamtwert. Bestehende Daten werden mit +`manualQuantity = quantity` übernommen. Die Fachregel für spätere externe +Zuordnungs-Commands lautet `quantity = manualQuantity + Summe der +effectiveQuantity aller verknüpften ExternalModelObjects`; Link und beide +Mengenwerte müssen innerhalb desselben Projekt-Commands wechseln. +`external-object.update-row-assignment` ist diese atomare Schreibgrenze für +bestehende Gerätezeilen. Sie weist mehrere externe Einzelobjekte zu, verschiebt +sie zwischen vorhandenen Rows oder löst ihre Links. Vor dem Schreiben werden +die vollständigen erwarteten Row- und Objektsnapshots, Projektzugehörigkeit, +Verteilung, Gruppenkategorie, Raum und Selektionskennzeichen geprüft. +Abweichende lokale Planungswerte benötigen eine explizite Konfliktbestätigung; +unterschiedliche Räume, Kategorien oder Selektionskennzeichen werden nicht +still zusammengeführt. Alle betroffenen materialisierten Mengen werden aus dem +unveränderten manuellen Anteil und sämtlichen Ziel-Objektlinks validiert. Die +Gegenrichtung enthält dieselben vollständigen Snapshots und funktioniert nach +Neustart; beim Lösen des letzten Objekts bleibt die Row bestehen. +`external-object.assign-to-new-row` fügt unzugeordnete Objekte atomar als neue +Gerätezeile in einen vorhandenen Stromkreis ein. Der manuelle Anteil dieser Row +ist null; Gesamtmenge, Raum, Verteilung, Kategorie, Selektionskennzeichen und +Planungswerte werden vor dem Schreiben geprüft. Undo löst exakt diese Objekte +und löscht die erzeugte Row nur, wenn sie und ihre Linkmenge unverändert sind. +Der Löschbefehl ist ausschließlich für die Projekthistorie zugelassen; eine +normale spätere Trennung lässt die Row gemäß der allgemeinen Zuordnungsregel +bestehen. +`external-object.assign-to-new-circuit` erzeugt einen neuen Stromkreis mit +vorab festgeschriebenem BMK, abgeleiteter Projektspannung, genau einer +externen Row und verpflichtendem Standardschutz zusammen mit den Objektlinks. +Verteilungs-, Gruppen-, Raum-, Mengen- und Planungsregeln werden vor dem Insert +gegen den aktuellen Projektstand geprüft. Der historische Gegenbefehl ist kein +allgemeiner Löschpfad: Er entfernt den vollständigen Circuit-Teilbaum nur bei +unverändertem Snapshot und unveränderter Objektlinkmenge. Redo verwendet exakt +dieselben IDs, dasselbe BMK und denselben Schutzsnapshot. +Die drei Zuordnungsadapter teilen sich +`external-object-assignment.persistence.ts` für Snapshotvergleich, +Kompatibilitätsregeln und link-sichere Updates. +`GET /api/projects/:projectId/circuit-lists/:circuitListId/external-objects` +liefert die verteilungsbezogene Read-Projektion für den späteren Editor-Drawer. +Die CircuitList bestimmt den Verteiler serverseitig; die Antwort enthält nur +dessen externe Objekte, sortiert unzugeordnet vor zugeordnet, sowie kompakte +Quell-, Raum-, Planungs- und Linkangaben. Originalbytes und vollständige +Command-Snapshots werden nicht an diese Oberfläche gegeben. Ohne optionalen +Revit-Import ist die Projektion leer. +`GET` und `PUT /api/projects/:projectId/external-csv/configuration` lesen oder +ändern die Konfiguration; der PUT plant Identität und nächsten +Konfigurationsstand serverseitig und verwendet den typisierten Command. +`POST /api/projects/:projectId/external-csv/preview` nimmt Dateiname und +Base64-kodierte CSV bis 18 MB entgegen. Der zustandsfreie Service liefert Hash, +Dialekt, Header, Klassifikationszahlen, Verdachtszeilen und gemappte +Objektquellwerte. Er schreibt weder Entwurf noch Projektdaten. +`POST /api/projects/:projectId/external-csv/initial-import/plan` verwendet +denselben begrenzten Transport, setzt eine gespeicherte Konfiguration und einen +noch leeren externen Projektzustand voraus und bleibt ebenfalls zustandsfrei. +Die Antwort gruppiert Quellräume, schlägt bei genau einer identischen +Raumnummer den vorhandenen Raum vor, gruppiert exakte Familie-und-Typ-Werte, +liefert regelbasierte Objektplanungswerte und Konfliktzahlen und enthält die +vorhandenen Ebenen, Räume, Verteilungen und ProjectDevices als Auswahlkataloge. +Unbekannte Familien, ungültige Leistungen/Mengen und Objekte ohne Raum bleiben +sichtbare Warnungen; es wird keine Entscheidung automatisch bestätigt. +`POST /api/projects/:projectId/external-csv/initial-import/apply` nimmt Datei, +erwarteten Hash, Konfigurationsversion und Projektrevision erneut entgegen. +Vollständige Entscheidungen ordnen jeden Quellraum optional einem vorhandenen +Raum und einer Standardverteilung sowie jede exakte Familiengruppe optional +einem vorhandenen ProjectDevice zu. Unklassifizierte Familien oder fehlende +Gruppenentscheidungen blockieren. Der Server parst und plant erneut, erzeugt +stabile interne UUIDs und übergibt den vollständigen Zustand an +`external-import.apply-initial`; CSV-Stromkreiswerte bleiben reine Quellwerte +und alle `circuitDeviceRowId` bleiben `null`. +Die Projektseite öffnet über „Revit-CSV“ ein deutsches Modal für Dialekt, +Spaltenzuordnung, zusätzliche Quellfelder und exakte Familie-und-Typ-Regeln. +Nach dem revisionierten Speichern kann eine lokale CSV gewählt und über den +zustandsfreien Endpunkt geprüft werden. Die Oberfläche zeigt Kennzahlen und nur +die ersten 25 erkannten Objekte; die vollständigen Objekte bleiben in der +Response verfügbar, ohne alle Zeilen in den DOM einzufügen. Der anschließende +Erstimport-Wizard gruppiert Quellräume und exakte Familie-und-Typ-Werte. Er +zeigt eindeutige, mehrdeutige und neue Raumtreffer, lässt vorhandene Räume, +Standardverteilungen und ProjectDevices explizit zuordnen und blockiert die +Übernahme bei unklassifizierten Familien. Erst nach einem Bestätigungsdialog +wird der vollständige Import als eine persistente, rückgängig machbare +Projektrevision angewendet. Dabei entstehen keine Stromkreise oder Gerätezeilen. +Fehlende Räume und ProjectDevices können direkt aus der jeweiligen Gruppe über +die regulären Projektformulare angelegt werden. Revit-Werte befüllen diese +Formulare vor, werden aber vor dem Speichern sichtbar vom Nutzer bestätigt. +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. ## Noch nicht unterstützt - Mehrbenutzerbetrieb und Konfliktauflösung +- Editor-Oberfläche für die vorhandene Zuordnungslogik, Folgeimport und + strukturtreuer Revit-Rückexport - vollständige elektrische Dimensionierung - Produktionsdeployment diff --git a/docs/deployment.md b/docs/deployment.md index 89c99a3..909c2c0 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -16,10 +16,9 @@ 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 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. +Beides enthält weder TLS, Authentifizierung, Reverse Proxy, Prozesshärtung noch +ein zentral betriebenes Datenbanksystem. Der Stack darf deshalb nicht öffentlich +erreichbar gemacht werden. ## Topologie @@ -29,18 +28,12 @@ Passwörter und Session-Cookies werden bei reinem HTTP unverschlüsselt | 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 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 +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 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. -Beim HTTP-Zugriff auf den Server-Stack aus dem LAN erzeugt der Editor neue -UUIDs über `createClientId`, mit `crypto.getRandomValues()` als Ersatz für das -dort nicht verfügbare `crypto.randomUUID()`. HTTPS ist für diese -ID-Erzeugung nicht erforderlich. - ### Speichergrenzen Jeder Dienst hat ein `mem_limit`. Im Server-Stack ist zusätzlich @@ -73,26 +66,6 @@ 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 @@ -158,8 +131,7 @@ bleibt `sh` der Vordergrundprozess, und `SIGTERM` erreicht Node nie. Vor einer produktiven Installation werden mindestens benötigt: - TLS-Termination und Reverse Proxy -- zentraler Identitätsanbieter oder eine feinere Rechte-Matrix, falls die zwei - festen Rollen später nicht ausreichen +- Authentifizierung, Autorisierung und Benutzer-/Rollenmodell - definierte Secrets- und Konfigurationsverwaltung - persistenter, gesicherter Datenbankbetrieb - kontrollierter einmaliger Migrationsschritt vor dem API-Rollout @@ -168,17 +140,14 @@ Vor einer produktiven Installation werden mindestens benötigt: - Entscheidung, ob SQLite für einen einzelnen Prozess genügt oder PostgreSQL für Mehrbenutzerbetrieb erforderlich ist -Der in der README beschriebene Server-Stack ermöglicht bereits den Betrieb des -gebauten Stands in einer geschützten Umgebung. Ein vollständig unterstütztes -Produktionssetup bleibt bis zur Umsetzung und Prüfung dieser Punkte offen. +Bis diese Punkte umgesetzt und getestet sind, besteht die „Installation“ aus dem +lokalen Entwicklungsstart in der README. ## Backup und Wiederherstellung `npm run db:backup` erzeugt unter `data/backups/` ein konsistentes SQLite-Backup, öffnet es unabhängig und prüft Integrität sowie Fremdschlüssel. Diese -Dateisicherungen sind von den bereits vorhandenen benannten und automatischen -logischen Projektsicherungen getrennt. Projektsicherungen werden über die -Projektseite wiederhergestellt und unterstützen persistentes Undo/Redo. +Dateisicherungen sind von zukünftigen logischen Projektversionen getrennt. Eine produktive Restore-Anweisung wird erst zusammen mit einem unterstützten Produktionsbetrieb veröffentlicht. Lokale Wiederherstellung darf nur bei diff --git a/docs/development-workflow.md b/docs/development-workflow.md index f630063..b19b7ff 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -13,11 +13,6 @@ Ein sauberer Clone enthält keine SQLite-Datenbank. Beim ersten Start werden `data/leistungsbilanz.db`, alle Tabellen und Migrationseinträge automatisch angelegt. Das Frontend ist unter erreichbar. -Dieser Standard-Stack verwendet gebauten Anwendungscode. Für die Entwicklung -mit Quellcode-Mounts und Hot Reload stattdessen -`docker compose -f compose.dev.yaml up --build --detach` verwenden; die Dienste -sind dabei nur über die Loopback-Ports des Entwicklungsrechners erreichbar. - Für direkte Node.js-Entwicklung: ```powershell @@ -91,8 +86,7 @@ Bei Docker- oder Laufzeitänderungen zusätzlich: ```powershell docker compose up --build --detach docker compose ps -Invoke-WebRequest http://localhost:3001/health -Invoke-WebRequest http://localhost:3001/web-health +Invoke-WebRequest http://localhost:3000/health ``` Bei sichtbaren Editoränderungen ist außerdem ein kurzer GUI-Test erforderlich. diff --git a/docs/estimate-balance.md b/docs/estimate-balance.md deleted file mode 100644 index c68758d..0000000 --- a/docs/estimate-balance.md +++ /dev/null @@ -1,151 +0,0 @@ -# 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 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 - -``` -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 (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, -480 GA, Allgemein; Reserve AV 10 %), leer oder als Kopie eines bestehenden -Stands mit neuen IDs. Stände bleiben bearbeitbar; ein zusätzlicher Status oder -eine Bearbeitungssperre ist derzeit nicht vorgesehen. - -## 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 %. - -## Ü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 -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 }`). - -## Projekttransfer und bewusste Abgrenzung - -- Das reguläre SQLite-Datenbank-Backup sichert die Grobbilanz-Tabellen zusammen - mit allen übrigen Anwendungsdaten. -- Benannte und automatische Projektsnapshots enthalten keine Grobbilanzen; das - Snapshot-Schema bleibt Version 7. Snapshot-Restore und dessen Undo/Redo lassen - vorhandene Grobbilanzen unverändert. -- Der portable Projektexport enthält alle Grobbilanzen ab Transferformat 2. - Ersetzen übernimmt sie atomar und rückgängig machbar; Duplizieren vergibt neue - IDs für Bilanz, Gruppen und Zeilen. Alte Transferdateien in Version 1 bleiben - importierbar und enthalten definitionsgemäß keine Grobbilanzen. -- Keine Rechte je Gewerk; „bearbeitet von“ ist ein Freitext je Kostengruppe. -- Kostengruppen der Gerätezeilen sind nicht normiert; der Vergleich arbeitet - mit Präfixen. -- Der erste Vergleich zeigt die geschätzte und detaillierte AV-Wirkleistung in - kW. SV- und kVA-Vergleiche können später ergänzt werden. -- Eine Stromkreisnummer gehört nicht zur Grobbilanz, weil sie eine frühe - Abschätzung ohne Stromkreisplanung ist. - -## 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/docs/print-view.md b/docs/print-view.md index 04b266d..202f172 100644 --- a/docs/print-view.md +++ b/docs/print-view.md @@ -1,16 +1,6 @@ # 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 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. ## Aufruf @@ -32,15 +22,12 @@ 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, 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. + 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 - (reine 1:1-Einspeiseabgänge kompakt in einer Zeile; sonst mehrzeilig mit - Sammelzeile, eingerückten Gerätezeilen und schreibgeschützten - Unterverteilungszeilen), + (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. @@ -50,25 +37,17 @@ 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. -## Berechnung und offene Punkte +## Vorläufige Punkte -- **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. +- **Einspeisung / Hierarchie:** `fedFrom` ist Freitext. Die Übersicht ordnet + einen Verteiler nur dann unter, wenn der Text genau der Nummer oder + Bezeichnung eines anderen Verteilers entspricht; „Σ 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 @@ -88,13 +67,13 @@ Seitenaufteilung langer Verteilerpläne entsteht erst beim Drucken. | 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. +3, Migration `0009`) 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`), +- Tabelle `document_branding_settings` (Schlüssel/Wert, Migration `0009`), global wie das Logo. - `GET /api/document-branding` liefert zusätzlich `office: { officeName, officeAddress }`. @@ -105,7 +84,7 @@ ihren Wert. - Globale Büro-Einstellung, nicht Teil von Projekten, Revisionen, Snapshots oder Projektexport. -- Tabelle `document_branding_assets` (Migration `0007`). +- Tabelle `document_branding_assets` (Migration `0008`). - `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. @@ -125,15 +104,3 @@ ihren Wert. begrenzt - `src/frontend/components/distribution-board-info-card.tsx` – Infokarte im Bearbeiten-Dialog der Verteilung - -## Bestehende Datenbanken - -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 10 enthält den aktuellen Projektzustand; die in Schema 9 -eingeführten Einspeisungsverweise werden in den unterstützten Versionen 1–8 -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/project-history-and-external-model-architecture.md b/docs/project-history-and-external-model-architecture.md index 3629c23..4c0a8ea 100644 --- a/docs/project-history-and-external-model-architecture.md +++ b/docs/project-history-and-external-model-architecture.md @@ -9,8 +9,7 @@ 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 the Revit/Linear-XLSX round-trip using stable, exact - Worksharing-ID-based external identity +- support future Revit/CSV round-trips using stable IFCGUID-based links - keep the persistence boundary replaceable so PostgreSQL can be adopted later ## Separate Concerns @@ -112,12 +111,7 @@ Implemented automatic-snapshot policy: - automatic capture and retention run inside the same transaction as the triggering project revision -## Revit / Linear Excel Round-Trip Direction - -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 CSV/IFCGUID runtime has -been removed; the implemented runtime uses Linear XLSX and exact Worksharing-ID. +## Revit / CSV / IFCGUID Round-Trip Direction External model exchange should use explicit staging and link entities instead of writing imported rows directly into circuits. @@ -126,12 +120,9 @@ Conceptual entities: - `ExternalModelSource` - identifies a Revit/IFC model or another external source within a project - `ExternalImportBatch` - - 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 + - file name, checksum, import time, format/version and processing status - `ExternalModelObject` - - exact case-sensitive Worksharing-ID as external identity - - optional IfcGUID as non-unique source redundancy + - stable IFCGUID and optional Revit element identifiers - source attributes and last-seen import batch - `ExternalObjectLink` - explicit relationship to a project device, circuit device row or another future domain entity @@ -142,33 +133,13 @@ Conceptual entities: Required behavior: -- Worksharing-ID uniqueness is scoped to the external source and uses exact, - case-sensitive comparison. IfcGUID is not a matching key. +- IFCGUID uniqueness is scoped to project and external model source. - 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 Worksharing-ID so Linear can match rows deterministically. -- Missing objects and duplicate/conflicting Worksharing-IDs are reported, - never silently reassigned. - -R10 verifies the complete implemented path through initial import, planning, -row assignment, return workbook, follow-up import, snapshot restore, portable -duplicate and restart-safe Undo/Redo. Large state replacement uses bounded -SQLite insert batches so imports, restores and duplicates do not exceed the -driver's SQL-variable limit. - -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. +- Export retains IFCGUID and source identifiers so Revit parameters can be matched deterministically. +- Missing objects and duplicate/conflicting identifiers are reported, never silently reassigned. ## SQLite and PostgreSQL Direction @@ -304,10 +275,6 @@ Completed foundation: - `project-floor.insert` and `project-room.insert` persist complete location records with stable ids; their inverses reject changed or referenced records so Undo never clears room assignments or device-row links implicitly -- `project-building.insert/.update/.delete` persist complete building records; - deleting a building with assigned floors is rejected. Floor commands carry - `buildingId` since command version 2; version 1 floor commands from older - history are upgraded with `buildingId = null` before execution - the floor and room POST routes require the current expected revision and the project page tracks the returned history state @@ -317,8 +284,7 @@ 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 Worksharing-ID or IfcGUID as an overloaded circuit equipment - identifier or an internal relation id +- do not model IFCGUID as an overloaded circuit equipment identifier - keep database backup/restore checks separate from project history tests ## Deferred Decisions @@ -326,6 +292,5 @@ 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 -- Linear-XLSX compatibility beyond the observed sample and any future - project-independent mapping profiles +- supported Revit CSV dialects and parameter mapping UI - PostgreSQL deployment topology and migration date diff --git a/docs/revit-requirements-llm-context.md b/docs/revit-requirements-llm-context.md index b9f84b2..314820b 100644 --- a/docs/revit-requirements-llm-context.md +++ b/docs/revit-requirements-llm-context.md @@ -1,17 +1,269 @@ -# LLM-Kontext für die Revit-Integration +# Kontext für die Revit-Anforderungsplanung -Die frühere Revit-/CSV-Anforderungsplanung ist abgelöst und Phase 14 ist mit -R10 abgeschlossen. Für Arbeiten an der Linear-XLSX-Anbindung 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) -- [R10-Abnahme](spec/revit-excel-r10-validation.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. -Bei Widersprüchen gilt das Anforderungsdokument. CSV, IfcGUID als Schlüssel, -Dynamo, Revit-API und JSON-Transport sind keine Zielpfade. Der CSV-Laufzeitpfad -ist entfernt; alte CSV-Snapshots und CSV-History werden mit einer deutschen -Migrationsmeldung abgelehnt. +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 diff --git a/docs/spec/07-implementation-phases-todo.md b/docs/spec/07-implementation-phases-todo.md index 5968766..b665e85 100644 --- a/docs/spec/07-implementation-phases-todo.md +++ b/docs/spec/07-implementation-phases-todo.md @@ -532,37 +532,32 @@ Acceptance criteria: ## Phase 14: External Model Round-Trip -Status: abgeschlossen am 30.09.2026 mit R10. Siehe -[R10-Abnahme](revit-excel-r10-validation.md). +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). -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. +Goal: -Verbindliche Quellen: +Exchange model objects and planning parameters with Revit or comparable tools through CSV or another agreed format. -- [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) +Tasks: -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. +- 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 -Kernabnahme der Phase: +Acceptance criteria: -- 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. +- 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 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 dda8fbb..c90dd24 100644 --- a/docs/spec/08-current-product-backlog.md +++ b/docs/spec/08-current-product-backlog.md @@ -46,10 +46,7 @@ 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 optional per-circuit - cable sizing module (`docs/cable-sizing-module.md`) exists; its supported - tables were confirmed against DIN VDE 0298-4:2023-06 with - Berichtigung 1:2023-10. Unsupported arrangements stay explicitly blocked. + the planner supplies the calculation requirements. - Detailed specification: `docs/spec/09-distribution-board-components-and-protection-groups.md` @@ -135,26 +132,6 @@ The pre-release cleanup established the following compatibility boundary: - [x] Keep column visibility and order as a project-specific UI preference so all distribution boards in the same project open with the same columns. -## Integrated Contributor Features (September 2026) - -- [x] Client ids without secure-context browser APIs (`createClientId`). -- [x] Icon actions, compact column headers and the AMEV picker in the circuit - list; icon actions and collapsible filters on the project overview. -- [x] Print view with cover, board overview, board plans, board info card and - office branding. -- [x] Buildings above floors and a dedicated building structure page. -- [x] Optional net room area with sums per floor and building. -- [x] Optional cable-sizing module for one circuit on demand - (DIN VDE 0298-4:2023-06 with Berichtigung 1). -- [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): bill of quantities export (#5), area-based loads in W/m² for -ProjectDevices and device rows (#20). - ## Recommended Sequence 1. [x] Distribution-board floor and supply fields. @@ -162,7 +139,6 @@ 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/Linear-XLSX round-trip was completed separately in 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). +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. diff --git a/docs/spec/revit-csv-integration-requirements.md b/docs/spec/revit-csv-integration-requirements.md index 7889566..973c1a6 100644 --- a/docs/spec/revit-csv-integration-requirements.md +++ b/docs/spec/revit-csv-integration-requirements.md @@ -1,8 +1,1373 @@ -# Abgelöst: Revit-CSV-Anforderungen +# Revit-CSV-Integration – Anforderungen und Implementierungsanweisung -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). +## 1. Status und Verbindlichkeit -Der historische Inhalt bleibt im Git-Verlauf bis einschließlich Commit -`ae318a5` erhalten. Er darf nicht mehr als Implementierungsanweisung oder -Statusquelle verwendet werden. +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; +- 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. 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 2d116b2..be50eb1 100644 --- a/docs/spec/revit-csv-phase-14-audit-and-plan.md +++ b/docs/spec/revit-csv-phase-14-audit-and-plan.md @@ -1,8 +1,402 @@ -# Abgelöst: alter Phase-14-CSV-Plan +# Phase 14: Audit- und Implementierungsplan für die Revit-CSV-Anbindung -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). +## Status -Der historische Inhalt bleibt im Git-Verlauf bis einschließlich Commit -`ae318a5` erhalten und darf nicht fortgeschrieben werden. +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. diff --git a/docs/spec/revit-excel-integration-requirements.md b/docs/spec/revit-excel-integration-requirements.md deleted file mode 100644 index effceb6..0000000 --- a/docs/spec/revit-excel-integration-requirements.md +++ /dev/null @@ -1,501 +0,0 @@ -# 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 - -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 -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 - -Umsetzungsstand R8: Die Revit-Objekttabelle bietet alle drei Rückgabeumfänge -an und lädt eine aus dem letzten vollständigen Import erzeugte XLSX herunter. -Die Serverprojektion verwendet für verknüpfte Objekte die aktuellen Row- und -Circuit-Werte, für freie Objekte die Planungswerte und schreibt Zahlen als -Excel-Zahlen. Hinweise zu nicht berechenbaren Werten und fehlenden optionalen -Spalten werden nach dem Download angezeigt. Der append-only Exportnachweis -liegt außerhalb von Projektrevision, Undo/Redo, Snapshots und Transfer. - -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. - -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 -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. - -Umsetzungsstand R9: Der sechsstufige Folgeimportwizard, die erneute -Apply-Prüfung, die getrennte Rückgabeabweichungsanzeige und der atomare -`external-import.apply-follow-up`-Command sind umgesetzt. Akzeptierte -Mengenänderungen aktualisieren verknüpfte Row-Summen im selben Command. -Fehlende Objekte bleiben zunächst samt Link und Menge erhalten und erscheinen -in der virtuellen Objekttabelle als `fehlend`. Ihre gesondert bestätigte -Löschung verwendet `external-model-object.delete-missing`; Undo stellt -Objekte, Links und Row-Mengen exakt wieder her. - -## 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. - -Umsetzungsstand R10: Die vollständige Kette ist mit dateibasierter SQLite- -Persistenz und Neustart getestet. Der synthetische Lasttest verarbeitet 5.000 -Objekte, misst Transport, Planung, Transaktionen, Command-/Snapshotgröße, -Heap und Clientprojektion und prüft Restore sowie Projektduplikat. Große -Zustandsersetzungen verwenden begrenzte Insertblöcke innerhalb derselben -atomaren Transaktion. Die Ergebnisse sind in der -[R10-Abnahme](revit-excel-r10-validation.md) dokumentiert. - -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 deleted file mode 100644 index 5039852..0000000 --- a/docs/spec/revit-excel-phase-14-plan.md +++ /dev/null @@ -1,237 +0,0 @@ -# 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 | 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 | 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 | 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 | abgeschlossen | Rückgabe-Excel für alle, abweichende oder ausgewählte Objekte und append-only Exportnachweis sind umgesetzt. | -| R9 | abgeschlossen | Vollständiger Folgeimport nach exakter Worksharing-ID mit Quellentscheidungen, fehlenden Objekten, bestätigtem Löschen und persistentem Undo/Redo. | -| R10 | abgeschlossen | Ende-zu-Ende-Kette, 5.000-Objekte-Lasttest, gebatchte Zustandspersistenz 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. - -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; -- `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. - -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; -- 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. - -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; -- 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. - -Umsetzungsstand: Die Revit-Objekttabelle erzeugt die Rückgabe revisionssicher -aus dem letzten vollständigen Import. Die gemeinsame Projektion berechnet -Stromkreis, Bezeichnung, Leistung, Spannung und Strom; der XLSX-Adapter erhält -Struktur und Formate und meldet fehlende optionale Spalten. Jeder erfolgreiche -Download wird außerhalb von Projektcommands, Snapshots und Transfers mit -Revision, Importbatch, Konfigurationskopie und Prüfsummen protokolliert. - -## 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. - -Umsetzungsstand vom 30.09.2026: Vorschau und Apply klassifizieren die vollständige -XLSX nach exakter Worksharing-ID als neu, geändert, unverändert oder fehlend -und weisen Rückgabefeldabweichungen getrennt aus. Der Wizard fordert -Entscheidungen nur für fachliche Quelländerungen an. Apply überträgt und parst -die Datei erneut, aktualisiert akzeptierte Mengen samt verknüpfter Row-Summe -atomar und speichert den neuen Vollbatch; alle älteren Batches werden auf ihre -Metadaten reduziert. Fehlende Objekte behalten zunächst Link und Menge. Eine -gesondert bestätigte Aktion kann sie anschließend mit passender -Row-Mengenänderung löschen. Beide Commands besitzen vollständige Inversen; -Undo/Redo liest keine XLSX-Datei. - -## 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. - -Umsetzungsstand vom 30.09.2026: Der dateibasierte Integrationstest deckt die -vollständige Kette bis zu Undo/Redo nach einem Datenbankneustart ab. Ein -synthetisches Workbook mit 5.000 Objekten durchläuft Erst- und Folgeimport, -Snapshot-Restore, Projektduplikat sowie die extrahierte Clientfilter- und -Virtualisierungslogik. Die dabei gefundene SQLite-Grenze ungebatchter Inserts -ist für alle vollständigen External-Model-Zustandspfade behoben. Messwerte und -Abnahme stehen in [R10-Abnahme](revit-excel-r10-validation.md). Phase 14 ist -damit abgeschlossen. - -## 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 deleted file mode 100644 index 84acc5a..0000000 --- a/docs/spec/revit-excel-r0-audit.md +++ /dev/null @@ -1,528 +0,0 @@ -# R0 – Audit der Linear-Excel-Anbindung - -Stand: 29.09.2026. Geprüfter Code: `cf022b2`. - -**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`, -`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 | Keine bei exaktem, case-sensitivem Vergleich | -| 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. - -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 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 - -**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`, 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 -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. - -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. - -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 - }, - 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. -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 -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 wird sichtbar mit `1` vorbelegt, ohne zusätzliche Bestätigung. -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 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` | 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_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. 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`, -`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. 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 -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 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. | -| `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. - -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, 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 lesen und -parsen keine Excel-Datei; sie wenden ausschließlich die gespeicherten -Vorher-/Nachher-Zustände an. Keine asynchronen Callbacks in -`better-sqlite3`-Transaktionen. - -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 - -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, -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 -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 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 -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 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 -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. 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 | 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. | - -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 ü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. -- 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; 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 -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:** 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. diff --git a/docs/spec/revit-excel-r10-validation.md b/docs/spec/revit-excel-r10-validation.md deleted file mode 100644 index 0bdc392..0000000 --- a/docs/spec/revit-excel-r10-validation.md +++ /dev/null @@ -1,60 +0,0 @@ -# R10-Abnahme der Linear-XLSX-Anbindung - -Stand: 30.09.2026. R10 schließt Phase 14 mit synthetischen, reproduzierbaren -Integrations- und Lasttests ab. Die reale Musterdatei wird dafür nicht benötigt -und bleibt unversioniert. - -## Ende-zu-Ende-Nachweis - -`tests/revit-xlsx-end-to-end.test.ts` verwendet eine dateibasierte SQLite- -Datenbank und prüft in einer Kette: - -```text -Erstimport → Objektplanung → Row-Zuordnung → Rückgabe-XLSX - → Folgeimport → Snapshot/Restore → Projektduplikat - → Datenbankneustart → Undo → Redo -``` - -Der Test bestätigt insbesondere die materialisierte Row-Menge, die Reduktion -des älteren Importbatches auf Metadaten, das Remapping aller internen UUIDs im -Duplikat und parserfreies Undo/Redo nach dem Neustart. - -## Last- und Größenmessung - -`tests/revit-xlsx-scale.test.ts` erzeugt 5.000 synthetische Objekte in einer -Linear-kompatiblen XLSX. Der Test misst Erst- und Folgeimport, Command- und -Snapshotgröße, Heap-Wachstum sowie clientseitiges Filtern, Sortieren und das -virtuelle Fenster. Er führt außerdem Snapshot-Restore und Projektduplikat mit -dem vollständigen Zustand aus. - -Messung auf der Entwicklungsumgebung am 30.09.2026: - -| Messwert | Ergebnis | -| --- | ---: | -| Objekte | 5.000 | -| XLSX-Datei | 191.019 Bytes | -| Erstimport-Command | 15.598.253 Bytes | -| logischer Projektsnapshot | 15.598.071 Bytes | -| XLSX-Erstplanung | 6.831 ms | -| atomare Erstimporttransaktion | 672 ms | -| XLSX-Folgeplanung | 6.303 ms | -| atomare Folgeimporttransaktion | 887 ms | -| Clientfilter, Sortierung und Fenster | 37 ms | -| Heap-Zuwachs des erfolgreichen Gesamtlaufs | 154.125.568 Bytes | - -Der Heap-Wert ist wegen Garbage Collection und der absichtlich verwendeten -In-Memory-Datenbank nicht deterministisch. Wiederholte Auditläufe lagen unter -der Testobergrenze von 768 MiB. Das virtuelle Fenster enthält bei 520 px Höhe -maximal 22 statt 5.000 Zeilen. - -## Gefundene und behobene Grenze - -Der erste 5.000-Objekte-Lauf scheiterte an einem ungebatchten SQLite- -Mehrfach-Insert. `insertManyInBatches` begrenzt nun die Insertblöcke für -Erstimport, Folgeimport, Snapshot-Restore und Projektduplikat. Alle Blöcke -bleiben Teil der jeweiligen bestehenden Transaktion; ein Fehler rollt weiterhin -die gesamte Operation zurück. - -Die vorhandenen Tests decken außerdem die deutschen Ablehnungen alter -CSV-Snapshots und CSV-History, Löschwarnungen, atomare Link-Inversen und den -Schutz referenzierter Räume und Verteiler ab. diff --git a/dynamo/01_check_model_identity.py b/dynamo/01_check_model_identity.py new file mode 100644 index 0000000..a3fe009 --- /dev/null +++ b/dynamo/01_check_model_identity.py @@ -0,0 +1,385 @@ +"""Read-only Revit 2026 model-identity diagnostics for a Dynamo Python node. + +Optional Dynamo input: + IN[0]: output directory or complete .json file path + +The script intentionally performs no Revit transaction and changes no model +data. OUT contains a compact summary plus the complete report. +""" + +import datetime +import json +import os +import platform +import sys +import tempfile +import traceback + +import clr + +clr.AddReference("RevitAPI") +clr.AddReference("RevitServices") + +from Autodesk.Revit.DB import ModelPathUtils, StorageType # noqa: E402 +from RevitServices.Persistence import DocumentManager # noqa: E402 + + +CHECKED_PARAMETER_NAMES = ("LB_ModelId", "LB_ProjectId") + + +def safe_text(value): + if value is None: + return None + try: + return str(value) + except Exception: + return None + + +def element_id_text(element_id): + if element_id is None: + return None + try: + return str(element_id.Value) + except Exception: + try: + return str(element_id.IntegerValue) + except Exception: + return safe_text(element_id) + + +def forge_type_id_text(value): + if value is None: + return None + try: + return value.TypeId + except Exception: + return safe_text(value) + + +def parameter_value(parameter): + result = { + "hasValue": False, + "raw": None, + "display": None, + } + try: + result["hasValue"] = bool(parameter.HasValue) + except Exception: + pass + + try: + storage_type = parameter.StorageType + if storage_type == StorageType.String: + result["raw"] = parameter.AsString() + elif storage_type == StorageType.Integer: + result["raw"] = int(parameter.AsInteger()) + elif storage_type == StorageType.Double: + result["raw"] = float(parameter.AsDouble()) + elif storage_type == StorageType.ElementId: + result["raw"] = element_id_text(parameter.AsElementId()) + except Exception as error: + result["readError"] = safe_text(error) + + try: + result["display"] = parameter.AsValueString() + except Exception: + pass + return result + + +def describe_parameter(parameter): + definition = None + try: + definition = parameter.Definition + except Exception: + pass + + name = None + if definition is not None: + try: + name = definition.Name + except Exception: + pass + + is_shared = False + try: + is_shared = bool(parameter.IsShared) + except Exception: + pass + + shared_guid = None + if is_shared: + try: + shared_guid = str(parameter.GUID) + except Exception: + pass + + data_type = None + group_type = None + if definition is not None: + try: + data_type = forge_type_id_text(definition.GetDataType()) + except Exception: + pass + try: + group_type = forge_type_id_text(definition.GetGroupTypeId()) + except Exception: + pass + + unit_type = None + try: + unit_type = forge_type_id_text(parameter.GetUnitTypeId()) + except Exception: + pass + + try: + storage_type = str(parameter.StorageType) + except Exception: + storage_type = None + + try: + is_read_only = bool(parameter.IsReadOnly) + except Exception: + is_read_only = None + + try: + user_modifiable = bool(parameter.UserModifiable) + except Exception: + user_modifiable = None + + return { + "name": name, + "parameterId": element_id_text(getattr(parameter, "Id", None)), + "isShared": is_shared, + "sharedGuid": shared_guid, + "storageType": storage_type, + "dataTypeId": data_type, + "groupTypeId": group_type, + "unitTypeId": unit_type, + "isReadOnly": is_read_only, + "userModifiable": user_modifiable, + "value": parameter_value(parameter), + } + + +def sorted_parameters(element): + parameters = [] + try: + parameters = [describe_parameter(parameter) for parameter in element.Parameters] + except Exception: + return [] + return sorted( + parameters, + key=lambda parameter: ( + (parameter.get("name") or "").casefold(), + parameter.get("parameterId") or "", + ), + ) + + +def named_parameter_occurrences(element, parameter_name): + result = [] + try: + parameters = element.GetParameters(parameter_name) + if parameters is not None: + result = [describe_parameter(parameter) for parameter in parameters] + except Exception: + parameter = None + try: + parameter = element.LookupParameter(parameter_name) + except Exception: + pass + if parameter is not None: + result = [describe_parameter(parameter)] + return result + + +def loaded_assembly_versions(): + result = {} + try: + from System import AppDomain + + for assembly in AppDomain.CurrentDomain.GetAssemblies(): + try: + name = assembly.GetName() + simple_name = str(name.Name) + if simple_name in ( + "DynamoCore", + "DynamoCoreWpf", + "DynamoRevitDS", + "RevitAPI", + "RevitServices", + ): + result[simple_name] = str(name.Version) + except Exception: + continue + except Exception: + pass + return dict(sorted(result.items())) + + +def get_cloud_identity(document): + result = {"isModelInCloud": False} + try: + result["isModelInCloud"] = bool(document.IsModelInCloud) + except Exception: + return result + if not result["isModelInCloud"]: + return result + + try: + model_path = document.GetCloudModelPath() + result["userVisiblePath"] = ModelPathUtils.ConvertModelPathToUserVisiblePath( + model_path + ) + for property_name, output_name in ( + ("GetProjectGUID", "projectGuid"), + ("GetModelGUID", "modelGuid"), + ): + try: + result[output_name] = str(getattr(model_path, property_name)()) + except Exception: + pass + except Exception as error: + result["readError"] = safe_text(error) + return result + + +def get_worksharing_identity(document): + result = {"isWorkshared": False} + try: + result["isWorkshared"] = bool(document.IsWorkshared) + except Exception: + return result + if not result["isWorkshared"]: + return result + + try: + model_path = document.GetWorksharingCentralModelPath() + result["centralModelPath"] = ModelPathUtils.ConvertModelPathToUserVisiblePath( + model_path + ) + except Exception as error: + result["readError"] = safe_text(error) + return result + + +def resolve_output_path(configured_path, report_name): + timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + default_directory = os.path.join(tempfile.gettempdir(), "leistungsbilanz-dynamo") + raw_path = safe_text(configured_path) + if raw_path is None or not raw_path.strip(): + directory = default_directory + file_path = os.path.join(directory, report_name + "-" + timestamp + ".json") + else: + expanded = os.path.abspath(os.path.expandvars(os.path.expanduser(raw_path.strip()))) + if expanded.lower().endswith(".json"): + file_path = expanded + directory = os.path.dirname(file_path) + else: + directory = expanded + file_path = os.path.join(directory, report_name + "-" + timestamp + ".json") + if not directory: + directory = os.getcwd() + if not os.path.isdir(directory): + os.makedirs(directory) + return file_path + + +def write_json(file_path, payload): + temporary_path = file_path + ".tmp" + with open(temporary_path, "w", encoding="utf-8", newline="\n") as output: + json.dump(payload, output, ensure_ascii=False, indent=2, sort_keys=True) + output.write("\n") + os.replace(temporary_path, file_path) + + +def get_input(index, default=None): + values = globals().get("IN", []) + try: + value = values[index] + return default if value is None else value + except Exception: + return default + + +def build_report(): + document = DocumentManager.Instance.CurrentDBDocument + if document is None: + raise RuntimeError("No active Revit document is available.") + + project_information = document.ProjectInformation + if project_information is None: + raise RuntimeError("The active document has no Project Information element.") + + application = document.Application + checked_parameters = { + name: named_parameter_occurrences(project_information, name) + for name in CHECKED_PARAMETER_NAMES + } + warnings = [] + for name in CHECKED_PARAMETER_NAMES: + occurrences = checked_parameters[name] + populated = [ + parameter + for parameter in occurrences + if parameter.get("value", {}).get("raw") not in (None, "") + ] + if not occurrences: + warnings.append(name + " is not bound to Project Information.") + elif not populated: + warnings.append(name + " exists but has no value on Project Information.") + elif len(occurrences) > 1: + warnings.append(name + " occurs more than once; use a shared-parameter GUID later.") + + return { + "reportSchemaVersion": 1, + "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "readOnly": True, + "environment": { + "revitVersionNumber": safe_text(getattr(application, "VersionNumber", None)), + "revitVersionName": safe_text(getattr(application, "VersionName", None)), + "revitSubVersionNumber": safe_text( + getattr(application, "SubVersionNumber", None) + ), + "pythonImplementation": safe_text(getattr(sys.implementation, "name", None)), + "pythonVersion": platform.python_version(), + "assemblies": loaded_assembly_versions(), + }, + "document": { + "title": safe_text(document.Title), + "pathName": safe_text(document.PathName), + "isFamilyDocument": bool(document.IsFamilyDocument), + "cloud": get_cloud_identity(document), + "worksharing": get_worksharing_identity(document), + }, + "modelIdentityCandidates": { + "projectInformationUniqueId": safe_text(project_information.UniqueId), + "projectInformationElementId": element_id_text(project_information.Id), + "checkedProjectParameters": checked_parameters, + }, + "projectInformationParameters": sorted_parameters(project_information), + "warnings": warnings, + } + + +try: + report = build_report() + output_path = resolve_output_path(get_input(0), "model-identity") + write_json(output_path, report) + OUT = { + "ok": True, + "filePath": output_path, + "projectInformationUniqueId": report["modelIdentityCandidates"][ + "projectInformationUniqueId" + ], + "warnings": report["warnings"], + "report": report, + } +except Exception as error: + OUT = { + "ok": False, + "error": safe_text(error), + "traceback": traceback.format_exc(), + } diff --git a/dynamo/02_export_electrical_fixture_parameter_inventory.py b/dynamo/02_export_electrical_fixture_parameter_inventory.py new file mode 100644 index 0000000..440a222 --- /dev/null +++ b/dynamo/02_export_electrical_fixture_parameter_inventory.py @@ -0,0 +1,517 @@ +"""Export all Electrical Fixtures instance/type parameters from Revit 2026. + +Optional Dynamo inputs: + IN[0]: output directory or complete .json file path + IN[1]: include empty parameters (default True) + IN[2]: maximum aggregated sample values (default 5) + +The script is read-only and performs no Revit transaction. +""" + +import datetime +import json +import os +import platform +import sys +import tempfile +import traceback + +import clr + +clr.AddReference("RevitAPI") +clr.AddReference("RevitServices") + +from Autodesk.Revit.DB import ( # noqa: E402 + BuiltInCategory, + FilteredElementCollector, + ModelPathUtils, + StorageType, +) +from RevitServices.Persistence import DocumentManager # noqa: E402 + + +def safe_text(value): + if value is None: + return None + try: + return str(value) + except Exception: + return None + + +def element_id_text(element_id): + if element_id is None: + return None + try: + return str(element_id.Value) + except Exception: + try: + return str(element_id.IntegerValue) + except Exception: + return safe_text(element_id) + + +def forge_type_id_text(value): + if value is None: + return None + try: + return value.TypeId + except Exception: + return safe_text(value) + + +def parameter_value(parameter): + result = {"hasValue": False, "raw": None, "display": None} + try: + result["hasValue"] = bool(parameter.HasValue) + except Exception: + pass + + try: + storage_type = parameter.StorageType + if storage_type == StorageType.String: + result["raw"] = parameter.AsString() + elif storage_type == StorageType.Integer: + result["raw"] = int(parameter.AsInteger()) + elif storage_type == StorageType.Double: + result["raw"] = float(parameter.AsDouble()) + elif storage_type == StorageType.ElementId: + result["raw"] = element_id_text(parameter.AsElementId()) + except Exception as error: + result["readError"] = safe_text(error) + + try: + result["display"] = parameter.AsValueString() + except Exception: + pass + return result + + +def describe_parameter(parameter, scope): + definition = None + try: + definition = parameter.Definition + except Exception: + pass + + name = None + data_type = None + group_type = None + if definition is not None: + try: + name = definition.Name + except Exception: + pass + try: + data_type = forge_type_id_text(definition.GetDataType()) + except Exception: + pass + try: + group_type = forge_type_id_text(definition.GetGroupTypeId()) + except Exception: + pass + + is_shared = False + try: + is_shared = bool(parameter.IsShared) + except Exception: + pass + + shared_guid = None + if is_shared: + try: + shared_guid = str(parameter.GUID) + except Exception: + pass + + unit_type = None + try: + unit_type = forge_type_id_text(parameter.GetUnitTypeId()) + except Exception: + pass + + try: + storage_type = str(parameter.StorageType) + except Exception: + storage_type = None + + try: + is_read_only = bool(parameter.IsReadOnly) + except Exception: + is_read_only = None + + try: + user_modifiable = bool(parameter.UserModifiable) + except Exception: + user_modifiable = None + + return { + "scope": scope, + "name": name, + "parameterId": element_id_text(getattr(parameter, "Id", None)), + "isShared": is_shared, + "sharedGuid": shared_guid, + "storageType": storage_type, + "dataTypeId": data_type, + "groupTypeId": group_type, + "unitTypeId": unit_type, + "isReadOnly": is_read_only, + "userModifiable": user_modifiable, + "value": parameter_value(parameter), + } + + +def has_meaningful_value(parameter_description): + value = parameter_description.get("value", {}) + return bool(value.get("hasValue")) or value.get("raw") not in (None, "") or value.get( + "display" + ) not in (None, "") + + +def read_parameters(element, scope, include_empty): + result = [] + try: + for parameter in element.Parameters: + description = describe_parameter(parameter, scope) + if include_empty or has_meaningful_value(description): + result.append(description) + except Exception as error: + return [], [safe_text(error)] + result.sort( + key=lambda parameter: ( + (parameter.get("name") or "").casefold(), + parameter.get("parameterId") or "", + ) + ) + return result, [] + + +def read_space(element, document): + try: + space = element.Space + except Exception as error: + return None, safe_text(error) + if space is None: + return None, None + + level_name = None + try: + level = document.GetElement(space.LevelId) + level_name = None if level is None else safe_text(level.Name) + except Exception: + pass + + return { + "uniqueId": safe_text(space.UniqueId), + "elementId": element_id_text(space.Id), + "number": safe_text(getattr(space, "Number", None)), + "name": safe_text(getattr(space, "Name", None)), + "levelName": level_name, + }, None + + +def read_family_identity(element, document): + symbol = None + try: + symbol = element.Symbol + except Exception: + try: + symbol = document.GetElement(element.GetTypeId()) + except Exception: + pass + + family_name = None + type_name = None + type_unique_id = None + type_element_id = None + if symbol is not None: + try: + family_name = safe_text(symbol.Family.Name) + except Exception: + family_name = safe_text(getattr(symbol, "FamilyName", None)) + type_name = safe_text(getattr(symbol, "Name", None)) + type_unique_id = safe_text(getattr(symbol, "UniqueId", None)) + type_element_id = element_id_text(getattr(symbol, "Id", None)) + + return { + "familyName": family_name, + "typeName": type_name, + "typeUniqueId": type_unique_id, + "typeElementId": type_element_id, + }, symbol + + +def parameter_inventory_key(parameter): + stable_id = parameter.get("sharedGuid") or parameter.get("parameterId") or "" + return "|".join( + ( + parameter.get("scope") or "", + stable_id, + parameter.get("name") or "", + parameter.get("dataTypeId") or "", + ) + ) + + +def sample_value_key(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def add_to_inventory(inventory, parameter, max_samples): + key = parameter_inventory_key(parameter) + entry = inventory.get(key) + if entry is None: + entry = { + "scope": parameter.get("scope"), + "name": parameter.get("name"), + "parameterId": parameter.get("parameterId"), + "isShared": parameter.get("isShared"), + "sharedGuid": parameter.get("sharedGuid"), + "storageType": parameter.get("storageType"), + "dataTypeId": parameter.get("dataTypeId"), + "groupTypeId": parameter.get("groupTypeId"), + "unitTypeId": parameter.get("unitTypeId"), + "occurrenceCount": 0, + "populatedCount": 0, + "sampleValues": [], + "_sampleKeys": set(), + } + inventory[key] = entry + entry["occurrenceCount"] += 1 + if has_meaningful_value(parameter): + entry["populatedCount"] += 1 + value = parameter.get("value") + value_key = sample_value_key(value) + if len(entry["sampleValues"]) < max_samples and value_key not in entry["_sampleKeys"]: + entry["_sampleKeys"].add(value_key) + entry["sampleValues"].append(value) + + +def finalize_inventory(inventory): + result = [] + for entry in inventory.values(): + clean_entry = dict(entry) + clean_entry.pop("_sampleKeys", None) + result.append(clean_entry) + return sorted( + result, + key=lambda entry: ( + entry.get("scope") or "", + (entry.get("name") or "").casefold(), + entry.get("sharedGuid") or entry.get("parameterId") or "", + ), + ) + + +def loaded_assembly_versions(): + result = {} + try: + from System import AppDomain + + for assembly in AppDomain.CurrentDomain.GetAssemblies(): + try: + name = assembly.GetName() + simple_name = str(name.Name) + if simple_name in ( + "DynamoCore", + "DynamoCoreWpf", + "DynamoRevitDS", + "RevitAPI", + "RevitServices", + ): + result[simple_name] = str(name.Version) + except Exception: + continue + except Exception: + pass + return dict(sorted(result.items())) + + +def resolve_output_path(configured_path): + timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + default_directory = os.path.join(tempfile.gettempdir(), "leistungsbilanz-dynamo") + raw_path = safe_text(configured_path) + if raw_path is None or not raw_path.strip(): + directory = default_directory + file_path = os.path.join( + directory, "electrical-fixture-parameters-" + timestamp + ".json" + ) + else: + expanded = os.path.abspath(os.path.expandvars(os.path.expanduser(raw_path.strip()))) + if expanded.lower().endswith(".json"): + file_path = expanded + directory = os.path.dirname(file_path) + else: + directory = expanded + file_path = os.path.join( + directory, "electrical-fixture-parameters-" + timestamp + ".json" + ) + if not directory: + directory = os.getcwd() + if not os.path.isdir(directory): + os.makedirs(directory) + return file_path + + +def write_json(file_path, payload): + temporary_path = file_path + ".tmp" + with open(temporary_path, "w", encoding="utf-8", newline="\n") as output: + json.dump(payload, output, ensure_ascii=False, indent=2, sort_keys=True) + output.write("\n") + os.replace(temporary_path, file_path) + + +def get_input(index, default=None): + values = globals().get("IN", []) + try: + value = values[index] + return default if value is None else value + except Exception: + return default + + +def build_report(include_empty, max_samples): + document = DocumentManager.Instance.CurrentDBDocument + if document is None: + raise RuntimeError("No active Revit document is available.") + if document.IsFamilyDocument: + raise RuntimeError("Open a Revit project document, not a family document.") + + application = document.Application + collector = ( + FilteredElementCollector(document) + .OfCategory(BuiltInCategory.OST_ElectricalFixtures) + .WhereElementIsNotElementType() + ) + source_elements = list(collector) + source_elements.sort(key=lambda element: safe_text(element.UniqueId) or "") + + elements = [] + types_by_unique_id = {} + inventory = {} + errors = [] + elements_without_space = 0 + + for element in source_elements: + element_errors = [] + try: + family_identity, symbol = read_family_identity(element, document) + instance_parameters, parameter_errors = read_parameters( + element, "instance", include_empty + ) + element_errors.extend(parameter_errors) + for parameter in instance_parameters: + add_to_inventory(inventory, parameter, max_samples) + + type_unique_id = family_identity.get("typeUniqueId") + if symbol is not None and type_unique_id and type_unique_id not in types_by_unique_id: + type_parameters, type_errors = read_parameters(symbol, "type", include_empty) + element_errors.extend(type_errors) + for parameter in type_parameters: + add_to_inventory(inventory, parameter, max_samples) + types_by_unique_id[type_unique_id] = { + **family_identity, + "parameters": type_parameters, + } + + space, space_error = read_space(element, document) + if space_error: + element_errors.append("MEP Space: " + space_error) + if space is None: + elements_without_space += 1 + + elements.append( + { + "uniqueId": safe_text(element.UniqueId), + "elementId": element_id_text(element.Id), + "categoryName": safe_text( + None if element.Category is None else element.Category.Name + ), + "family": family_identity, + "space": space, + "instanceParameters": instance_parameters, + "warnings": element_errors, + } + ) + except Exception as error: + errors.append( + { + "uniqueId": safe_text(getattr(element, "UniqueId", None)), + "elementId": element_id_text(getattr(element, "Id", None)), + "error": safe_text(error), + } + ) + + return { + "reportSchemaVersion": 1, + "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "readOnly": True, + "complete": len(errors) == 0, + "scope": { + "builtInCategory": "OST_ElectricalFixtures", + "wholeDocument": True, + "elementTypesExcluded": True, + "includeEmptyParameters": include_empty, + }, + "environment": { + "revitVersionNumber": safe_text(getattr(application, "VersionNumber", None)), + "revitVersionName": safe_text(getattr(application, "VersionName", None)), + "revitSubVersionNumber": safe_text( + getattr(application, "SubVersionNumber", None) + ), + "pythonImplementation": safe_text(getattr(sys.implementation, "name", None)), + "pythonVersion": platform.python_version(), + "assemblies": loaded_assembly_versions(), + }, + "document": { + "title": safe_text(document.Title), + "pathName": safe_text(document.PathName), + "projectInformationUniqueId": safe_text(document.ProjectInformation.UniqueId), + }, + "summary": { + "elementCount": len(source_elements), + "exportedElementCount": len(elements), + "typeCount": len(types_by_unique_id), + "parameterDefinitionCount": len(inventory), + "elementsWithoutMepSpace": elements_without_space, + "elementErrorCount": len(errors), + }, + "parameterInventory": finalize_inventory(inventory), + "types": sorted( + types_by_unique_id.values(), + key=lambda entry: ( + (entry.get("familyName") or "").casefold(), + (entry.get("typeName") or "").casefold(), + entry.get("typeUniqueId") or "", + ), + ), + "elements": elements, + "errors": errors, + } + + +try: + include_empty_input = get_input(1, True) + include_empty = bool(include_empty_input) + try: + max_samples = int(get_input(2, 5)) + except Exception: + max_samples = 5 + max_samples = max(0, min(max_samples, 50)) + + report = build_report(include_empty, max_samples) + output_path = resolve_output_path(get_input(0)) + write_json(output_path, report) + OUT = { + "ok": True, + "filePath": output_path, + "complete": report["complete"], + "summary": report["summary"], + "errors": report["errors"], + } +except Exception as error: + OUT = { + "ok": False, + "error": safe_text(error), + "traceback": traceback.format_exc(), + } diff --git a/dynamo/README.md b/dynamo/README.md new file mode 100644 index 0000000..800eded --- /dev/null +++ b/dynamo/README.md @@ -0,0 +1,69 @@ +# Revit 2026 / Dynamo diagnostics + +This directory contains self-contained Python scripts for a Dynamo **Python +Script** node. They use only Dynamo's built-in Revit integration, the Revit API +and the Python standard library. No Dynamo package is required. + +The scripts are read-only. They do not start a Revit transaction and do not +change the open model. + +## Python engine + +Use the built-in `CPython3` engine in Revit 2026. Autodesk ships Dynamo with +Revit; optional PythonNet3 packages are not required by these diagnostics. + +## 01 - Check model identity + +File: `01_check_model_identity.py` + +The script reports: + +- Revit, Dynamo and Python versions; +- `ProjectInformation.UniqueId` as a native model-identity candidate; +- all occurrences and values of `LB_ModelId` and `LB_ProjectId` on Project + Information; +- all Project Information parameters; +- optional cloud/worksharing identity information when the API exposes it. + +Input `IN[0]` is optional. It may be either an output directory or a complete +`.json` file path. With no input, the report is written below the current +Windows temporary directory in `leistungsbilanz-dynamo`. + +## 02 - Inventory Electrical Fixtures parameters + +File: `02_export_electrical_fixture_parameter_inventory.py` + +The script reads every instance of +`BuiltInCategory.OST_ElectricalFixtures` in the complete current document. It +exports: + +- element, family, type and MEP Space identities; +- every instance parameter and value; +- every unique family-type parameter and value; +- an aggregated parameter inventory with occurrence counts and sample values; +- per-element warnings instead of aborting at the first unreadable element. + +Inputs: + +- `IN[0]` (optional): output directory or complete `.json` path; +- `IN[1]` (optional): include empty parameters, default `true`; +- `IN[2]` (optional): maximum sample values per aggregated parameter, default + `5`. + +The default output location is again the Windows temporary directory. The +generated report can contain model paths and project-specific parameter values; +review it before sharing or committing it. + +## Running a script + +1. Open the target model in Revit 2026. +2. Open Dynamo from **Manage > Visual Programming > Dynamo**. +3. Create a graph and add a **Python Script** node. +4. Select the `CPython3` engine for the node. +5. Copy the complete content of the desired `.py` file into the node. +6. Optionally connect a String node containing the output path to `IN[0]`. +7. Run the graph and inspect `OUT` for status, counts and the generated path. + +For the first test, run `01_check_model_identity.py` in the Revit main model. +Then run the parameter inventory. Keep both generated JSON files so their +structure can be checked before the production snapshot DTO is finalized. diff --git a/next.config.mjs b/next.config.mjs index a6cb01e..e0610b9 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -11,22 +11,6 @@ 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/package-lock.json b/package-lock.json index 9d27840..417421b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,6 @@ "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", @@ -876,47 +875,6 @@ "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", @@ -1629,87 +1587,6 @@ "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", @@ -1753,28 +1630,6 @@ "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", @@ -1793,12 +1648,6 @@ "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", @@ -1840,16 +1689,6 @@ "@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", @@ -1873,38 +1712,12 @@ "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", @@ -1959,18 +1772,6 @@ } ] }, - "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", @@ -1981,27 +1782,6 @@ "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", @@ -2038,49 +1818,12 @@ "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", @@ -2287,45 +2030,6 @@ "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", @@ -2428,26 +2132,6 @@ "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", @@ -2498,19 +2182,6 @@ "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", @@ -2557,12 +2228,6 @@ "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", @@ -2577,22 +2242,6 @@ "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", @@ -2653,27 +2302,6 @@ "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", @@ -2685,12 +2313,6 @@ "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", @@ -2766,23 +2388,6 @@ } ] }, - "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", @@ -2806,190 +2411,6 @@ "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", @@ -3059,18 +2480,6 @@ "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", @@ -3079,18 +2488,6 @@ "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", @@ -3194,15 +2591,6 @@ "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", @@ -3233,12 +2621,6 @@ "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", @@ -3247,15 +2629,6 @@ "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", @@ -3323,12 +2696,6 @@ "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", @@ -3432,36 +2799,6 @@ "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", @@ -3471,19 +2808,6 @@ "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", @@ -3523,18 +2847,6 @@ "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", @@ -3594,12 +2906,6 @@ "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", @@ -3859,15 +3165,6 @@ "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", @@ -3876,15 +3173,6 @@ "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", @@ -4418,69 +3706,11 @@ "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", @@ -4494,47 +3724,6 @@ "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 17837f1..414eb53 100644 --- a/package.json +++ b/package.json @@ -24,10 +24,10 @@ "test": "node scripts/run-tests.mjs", "test:watch": "node scripts/run-tests.mjs --watch", "db:generate": "drizzle-kit generate", - "db:migrate": "node scripts/run-migrations.js", + "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-xlsx.ts" + "revit:verify-reference": "tsx scripts/verify-revit-reference-csv.ts" }, "keywords": [], "author": "", @@ -36,7 +36,6 @@ "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/db-verify-circuit-schema.js b/scripts/db-verify-circuit-schema.js index fa91cc4..8d27b1d 100644 --- a/scripts/db-verify-circuit-schema.js +++ b/scripts/db-verify-circuit-schema.js @@ -5,10 +5,6 @@ const dbPath = path.resolve("data", "leistungsbilanz.db"); const db = new Database(dbPath, { readonly: true }); const requiredTables = [ - "buildings", - "estimate_balances", - "estimate_groups", - "estimate_rows", "circuit_sections", "circuits", "circuit_device_rows", @@ -104,13 +100,6 @@ const projectColumns = new Set( const missingProjectColumns = requiredProjectColumns.filter( (name) => !projectColumns.has(name) ); -const requiredFloorColumns = ["building_id"]; -const floorColumns = new Set( - db.prepare("PRAGMA table_info(floors)").all().map((column) => column.name) -); -const missingFloorColumns = requiredFloorColumns.filter( - (name) => !floorColumns.has(name) -); const requiredDistributionBoardColumns = [ "floor_id", "supply_type", @@ -166,7 +155,6 @@ console.log( requiredCircuitSectionColumns.join(", ") ); console.log("Required project columns:", requiredProjectColumns.join(", ")); -console.log("Required floor columns:", requiredFloorColumns.join(", ")); console.log( "Required distribution-board columns:", requiredDistributionBoardColumns.join(", ") @@ -183,11 +171,6 @@ if (missing.length > 0) { process.exit(1); } -if (missingFloorColumns.length > 0) { - console.error("Missing floor columns:", missingFloorColumns.join(", ")); - process.exit(1); -} - if (missingProjectDeviceColumns.length > 0) { console.error("Missing project-device columns:", missingProjectDeviceColumns.join(", ")); process.exit(1); diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js index 3a6fc84..ebbed8a 100644 --- a/scripts/run-migrations.js +++ b/scripts/run-migrations.js @@ -4,65 +4,13 @@ const Database = require('better-sqlite3'); const fs = require('node:fs'); const path = require('node:path'); -const dataDir = path.resolve( - process.env.LEISTUNGSBILANZ_DATA_DIR || 'data' -); +const dataDir = path.resolve('data'); if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); -const databasePath = path.join(dataDir, 'leistungsbilanz.db'); +const sqlite = new Database(path.join(dataDir, 'leistungsbilanz.db')); +const db = drizzle(sqlite); -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}`); - } +migrate(db, { migrationsFolder: path.resolve('src/db/migrations') }); +sqlite.close(); - 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); -}); +console.log('Migrations applied'); diff --git a/scripts/verify-revit-reference-csv.ts b/scripts/verify-revit-reference-csv.ts new file mode 100644 index 0000000..07d605b --- /dev/null +++ b/scripts/verify-revit-reference-csv.ts @@ -0,0 +1,81 @@ +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 deleted file mode 100644 index ed568d4..0000000 --- a/scripts/verify-revit-reference-xlsx.ts +++ /dev/null @@ -1,162 +0,0 @@ -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/app/config/benutzer/page.tsx b/src/app/config/benutzer/page.tsx deleted file mode 100644 index 134890d..0000000 --- a/src/app/config/benutzer/page.tsx +++ /dev/null @@ -1,325 +0,0 @@ -"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 deleted file mode 100644 index 2b58ee7..0000000 --- a/src/app/config/konto/page.tsx +++ /dev/null @@ -1,103 +0,0 @@ -"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 deleted file mode 100644 index 72d9b6d..0000000 --- a/src/app/config/layout.tsx +++ /dev/null @@ -1,52 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { usePathname, useRouter } from "next/navigation"; -import { useEffect } from "react"; -import { useAuth } from "../../frontend/components/AuthProvider"; -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(() => { - if (status !== "signed-in") return; - if (redirectTarget) router.replace(redirectTarget); - }, [status, redirectTarget, router]); - - if ( - status !== "signed-in" || - redirectTarget !== null - ) { - return null; - } - - return ( -
-
-

Config

-
- - - - {children} -
- ); -} diff --git a/src/app/config/page.tsx b/src/app/config/page.tsx deleted file mode 100644 index 3c9d8fd..0000000 --- a/src/app/config/page.tsx +++ /dev/null @@ -1,3 +0,0 @@ -export default function ConfigPage() { - return null; -} diff --git a/src/app/globals.css b/src/app/globals.css index 67985f4..88e1c35 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -220,7 +220,7 @@ a { --bs-alert-border-color: #205a38; } -/* ── App-Shell / Seitenleiste (alle Seiten außer der Seitenansicht) ──── */ +/* ── App-Shell / Seitenleiste (nur auf der Projektseite) ────────────────── */ .app-shell { display: grid; @@ -323,24 +323,23 @@ a { } .sidebar-footer { - padding-top: 12px; + padding: 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; - justify-content: center; - flex: 0 0 auto; - width: 36px; - height: 36px; - padding: 0; + gap: 10px; + padding: 10px 14px; 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; } @@ -382,276 +381,6 @@ a { font-weight: 600; } -/* ── Projektübersicht: Icon-Aktionen und einklappbare Filterleisten ───── - Aktionen nutzen IconButton/IconLink wie die Stromkreisliste; der Rahmen - kommt hier aus dem Kontext `.overview-actions`. Filterleisten folgen der - PM-App (Suche + Mehrfachauswahl mit „Alle“ + „Zurücksetzen“), angepasst an - die Tokens dieser App. */ - -.btn-with-icon { - display: inline-flex; - align-items: center; - gap: 0.4rem; -} - -.overview-actions { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.3rem; -} - -.overview-actions .icon-button { - min-width: 1.9rem; - min-height: 1.85rem; - padding: 0.2rem 0.45rem; - border: 1px solid var(--color-border); - border-radius: 6px; - background: var(--color-bg); - color: var(--color-ink); - font-size: 0.82rem; - font-weight: 500; - text-decoration: none; - white-space: nowrap; -} - -.overview-actions .icon-button:disabled { - opacity: 0.45; -} - -.overview-actions .icon-button-primary { - border-color: var(--color-primary); - background: var(--color-primary); - color: #fff; -} - -.overview-actions .icon-button-primary:not(:disabled):hover { - border-color: var(--color-primary-dark); - background: var(--color-primary-dark); - color: #fff; -} - -:root[data-bs-theme="dark"] .overview-actions .icon-button-primary { - border-color: var(--color-accent); - background: var(--color-accent); -} - -:root[data-bs-theme="dark"] .overview-actions .icon-button-primary:not(:disabled):hover { - border-color: var(--color-accent-pale); - background: var(--color-accent-pale); - color: var(--color-primary-deep); -} - -.overview-actions .icon-button-danger { - color: var(--color-danger); -} - -.filter-panel { - padding: 0.55rem 1rem 0.7rem; - border-bottom: 1px solid var(--color-border); - background: var(--color-bg); -} - -.filter-panel-row { - display: flex; - align-items: center; - gap: 10px; -} - -/* 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; - border: 1px solid var(--color-border); - border-radius: 6px; - background: none; - color: var(--color-ink-soft); -} - -.filter-panel-row .filter-panel-toggle:hover { - background: var(--color-surface); -} - -.filter-panel-label, -.filter-bar-label { - font-size: 0.78rem; - font-weight: 500; - color: var(--color-ink-soft); -} - -.filter-panel-badge { - padding: 3px 10px; - border-radius: 999px; - background: #fbe9d9; - color: var(--color-attention-dark); - font-size: 0.72rem; - font-weight: 500; - white-space: nowrap; -} - -:root[data-bs-theme="dark"] .filter-panel-badge { - background: #3a2e1c; - color: #f0b880; -} - -.filter-panel-count { - margin-left: auto; - font-size: 0.78rem; - color: var(--color-ink-soft); - white-space: nowrap; -} - -.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); -} - -.filter-bar-field, -.filter-dropdown { - position: relative; - display: flex; - flex-direction: column; - gap: var(--space-xs); - margin: 0; -} - -.filter-bar-search, -.filter-dropdown-toggle { - min-height: 2.1rem; - padding: 0.35rem 0.65rem; - border: 1.5px solid var(--color-border); - border-radius: 8px; - background: var(--color-bg); - color: var(--color-ink); - font: inherit; - font-size: 0.82rem; -} - -.filter-bar-search { - width: 15em; -} - -.filter-bar-search:focus, -.filter-dropdown-toggle:focus-visible { - outline: 2px solid var(--color-accent); - outline-offset: 1px; - border-color: var(--color-accent); -} - -.filter-dropdown-toggle { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - min-width: 11em; - max-width: 18em; - font-weight: 500; - cursor: pointer; -} - -.filter-dropdown-toggle:hover, -.filter-dropdown-toggle.is-active { - border-color: var(--color-accent); -} - -.filter-dropdown-toggle.is-active { - color: var(--color-primary); -} - -:root[data-bs-theme="dark"] .filter-dropdown-toggle.is-active { - color: var(--color-accent-pale); -} - -.filter-dropdown-value { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.filter-dropdown-toggle svg { - flex: none; - color: var(--color-ink-soft); -} - -.filter-dropdown-panel { - position: absolute; - top: calc(100% + 4px); - left: 0; - z-index: 20; - display: flex; - flex-direction: column; - gap: 2px; - min-width: 220px; - max-height: 280px; - overflow-y: auto; - padding: 8px; - border: 1.5px solid var(--color-border); - border-radius: 8px; - background: var(--color-bg); - box-shadow: 0 6px 20px var(--shadow-menu); -} - -.filter-dropdown-option { - display: flex; - align-items: center; - gap: 8px; - margin: 0; - padding: 6px 8px; - border-radius: 6px; - color: var(--color-ink); - font-size: 0.82rem; - font-weight: 400; - cursor: pointer; -} - -.filter-dropdown-option:hover { - background: var(--color-surface); -} - -.filter-dropdown-option input { - accent-color: var(--color-primary); -} - -.filter-dropdown-option-all { - margin-bottom: 2px; - padding-bottom: 8px; - border-bottom: 1px solid var(--color-border); - border-radius: 6px 6px 0 0; -} - -.filter-dropdown-empty { - padding: 6px 8px; - color: var(--color-ink-soft); - font-size: 0.8rem; -} - -.filter-bar .filter-bar-reset { - min-height: 2.1rem; - padding: 0.3rem 0.65rem; - border: 1px solid var(--color-border); - border-radius: 8px; - background: var(--color-bg); - color: var(--color-ink); - font-size: 0.82rem; - font-weight: 500; -} - /* ── KPI-Kacheln ─────────────────────────────────────────────────────── */ .kpi-grid { @@ -702,29 +431,12 @@ a.kpi:hover { color: var(--color-accent-pale); } -/* Flächen-Look wie in der PM-App (Vorbild grow-monitor): gleichmäßiger - 1-px-Rahmen statt farbigem Balken an der Oberkante, größerer Radius und ein - weicher Streuschatten mit feiner heller Innenkante oben. Der Akzent kommt - über Kopfzeile und Inhalt, nicht über die Kante. Bootstraps shadow-sm - setzt box-shadow mit !important aus --bs-box-shadow-sm; die Karte legt diese - Variable auf denselben Schatten, damit Karten mit und ohne shadow-sm gleich - aussehen. */ .card { - --lb-card-shadow: - 0 4px 24px var(--shadow-soft), - 0 1px 0 rgba(255, 255, 255, 0.7) inset; - --bs-box-shadow-sm: var(--lb-card-shadow); - --bs-card-border-radius: 16px; - --bs-card-border-color: var(--color-border); - box-shadow: var(--lb-card-shadow); -} - -/* Auf dunklem Grund ein kräftigerer Streuschatten und nur eine schwache - Innenkante, sonst wirkt sie wie ein harter weißer Strich. */ -:root[data-bs-theme="dark"] .card { - --lb-card-shadow: - 0 4px 24px rgba(0, 0, 0, 0.4), - 0 1px 0 rgba(255, 255, 255, 0.05) inset; + border-radius: var(--radius); + border-top: 3px solid var(--color-primary); + box-shadow: + 0 1px 2px var(--shadow-soft), + 0 10px 24px -14px var(--shadow-strong); } .card-header { @@ -775,54 +487,6 @@ a.kpi:hover { opacity: 0.45; } -/* Icon buttons (circuit list editor toolbar, group and row actions) */ -.icon-button { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 0.35rem; - line-height: 1.2; - cursor: pointer; - transition: color 0.12s ease, border-color 0.12s ease, background-color 0.12s ease; -} - -.icon-button svg { - flex: none; -} - -.icon-button:disabled { - cursor: not-allowed; -} - -.icon-button:not(:disabled):hover { - border-color: var(--accent-blue); - color: var(--accent-blue); -} - -.icon-button-danger:not(:disabled):hover { - border-color: var(--color-danger); - background: var(--color-danger-bg); - color: var(--color-danger); -} - -.editor-toolbar .project-device-drawer-toggle:not(:disabled):hover { - color: #fff; - filter: brightness(1.08); -} - -.icon-button-text { - font-size: 0.7rem; - font-weight: 700; - letter-spacing: 0.02em; -} - -.icon-button-separator { - align-self: stretch; - width: 1px; - margin: 0.1rem 0.15rem; - background: var(--panel-border-strong); -} - .editor-toolbar .project-device-drawer-toggle { border-color: var(--accent-blue); background: var(--accent-blue); @@ -1128,17 +792,6 @@ 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; @@ -1191,37 +844,24 @@ a.kpi:hover { white-space: nowrap; } -/* One header row: label (sort) on the left, filter icon on the right. */ .tree-grid .header-cell { display: flex; - flex-direction: row; - align-items: flex-start; - justify-content: space-between; + flex-direction: column; + align-items: stretch; gap: 0.2rem; min-width: 0; } .tree-grid .header-filter-btn { - display: inline-flex; - flex: none; - align-items: center; - gap: 0.15rem; - border: 1px solid transparent; - background: transparent; - color: var(--text-faint); - border-radius: 3px; - font-size: 0.7rem; - font-weight: 700; - line-height: 1; - padding: 0.15rem 0.2rem; - white-space: nowrap; - cursor: pointer; -} - -.tree-grid .header-filter-btn:hover, -.tree-grid .header-filter-btn:focus-visible { - border-color: var(--panel-border-strong); + display: block; + width: 100%; + border: 1px solid var(--panel-border-strong); + background: var(--panel-bg); color: var(--text-strong); + border-radius: 3px; + font-size: 0.75rem; + padding: 0.15rem 0.35rem; + white-space: nowrap; } .tree-grid .header-sort-btn { @@ -1239,10 +879,7 @@ a.kpi:hover { font-size: 0.78rem; font-weight: 600; line-height: 1.15; - /* Break only between words; never inside a word such as "Bemerkung". */ - overflow-wrap: normal; - word-break: normal; - hyphens: manual; + overflow-wrap: anywhere; white-space: normal; text-align: left; cursor: pointer; @@ -1282,18 +919,6 @@ a.kpi:hover { font-size: 0.78rem; } -.tree-grid .header-cell .header-sort-btn { - flex: 1 1 auto; - width: auto; - align-items: flex-start; -} - -.tree-grid .header-unit { - display: block; - font-weight: 500; - color: var(--text-faint); -} - .tree-grid .header-sort-btn:hover span:first-child, .tree-grid .header-sort-btn:focus-visible span:first-child { text-decoration: underline; @@ -1310,11 +935,6 @@ a.kpi:hover { background: var(--accent-blue-soft-bg); } -.tree-grid .header-filter-count { - min-width: 0.7rem; - text-align: center; -} - .tree-grid .header-filter-menu { position: absolute; z-index: 7; @@ -1533,20 +1153,7 @@ a.kpi:hover { .tree-grid .section-actions { display: flex; - align-items: center; - gap: 0.25rem; -} - -.tree-grid .section-actions .icon-button, -.tree-grid .action-cell .icon-button { - min-width: 1.75rem; - min-height: 1.6rem; - padding: 0.15rem 0.3rem; -} - -.tree-grid .section-actions .icon-button:disabled, -.tree-grid .action-cell .icon-button:disabled { - opacity: 0.35; + gap: 0.35rem; } .tree-grid .section-actions button { @@ -1562,24 +1169,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); } -.tree-grid .downstream-board-load-row td { - background: var(--panel-bg-subtle); - color: var(--text-muted); - font-style: italic; -} - -.tree-grid .downstream-board-load-row td:nth-child(2) { - padding-left: 1.5rem; -} - .tree-grid .empty-circuit-row td { background: var(--panel-bg-subtle); } @@ -1616,6 +1209,48 @@ a.kpi:hover { box-shadow: inset 0 0 0 1px var(--color-signal); } +.tree-grid .cell-cable-sizing-trigger { + color: var(--color-primary); + cursor: pointer; + font-weight: 600; + transition: + background-color 0.12s ease, + box-shadow 0.12s ease; +} + +:root[data-bs-theme="dark"] .tree-grid .cell-cable-sizing-trigger { + color: var(--color-accent-pale); +} + +.tree-grid .cell-cable-sizing-trigger:hover { + background: rgba(63, 130, 166, 0.15); + box-shadow: inset 0 0 0 1px var(--color-primary); +} + +.tree-grid .cell-cable-sizing-trigger { + position: relative; + padding-left: 1.4em; +} + +.tree-grid .cell-cable-sizing-trigger::before { + content: ""; + position: absolute; + left: 0.2em; + top: 50%; + transform: translateY(-50%); + width: 0.9em; + height: 0.9em; + opacity: 0.85; + background-repeat: no-repeat; + background-position: center; + background-size: contain; + background-image: url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%233f82a6' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='2' width='16' height='20' rx='2'/%3E%3Cline x1='8' y1='6' x2='16' y2='6'/%3E%3Cline x1='8' y1='10' x2='8' y2='10.01'/%3E%3Cline x1='12' y1='10' x2='12' y2='10.01'/%3E%3Cline x1='16' y1='10' x2='16' y2='10.01'/%3E%3Cline x1='8' y1='14' x2='8' y2='14.01'/%3E%3Cline x1='12' y1='14' x2='12' y2='14.01'/%3E%3Cline x1='16' y1='14' x2='16' y2='14.01'/%3E%3Cline x1='8' y1='18' x2='8' y2='18.01'/%3E%3Cline x1='12' y1='18' x2='12' y2='18.01'/%3E%3Cline x1='16' y1='18' x2='16' y2='18.01'/%3E%3C/svg%3E"); +} + +:root[data-bs-theme="dark"] .tree-grid .cell-cable-sizing-trigger::before { + background-image: url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a9d2e6' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='2' width='16' height='20' rx='2'/%3E%3Cline x1='8' y1='6' x2='16' y2='6'/%3E%3Cline x1='8' y1='10' x2='8' y2='10.01'/%3E%3Cline x1='12' y1='10' x2='12' y2='10.01'/%3E%3Cline x1='16' y1='10' x2='16' y2='10.01'/%3E%3Cline x1='8' y1='14' x2='8' y2='14.01'/%3E%3Cline x1='12' y1='14' x2='12' y2='14.01'/%3E%3Cline x1='16' y1='14' x2='16' y2='14.01'/%3E%3Cline x1='8' y1='18' x2='8' y2='18.01'/%3E%3Cline x1='12' y1='18' x2='12' y2='18.01'/%3E%3Cline x1='16' y1='18' x2='16' y2='18.01'/%3E%3C/svg%3E"); +} + .tree-grid .device-drag-handle { cursor: grab; } @@ -1637,38 +1272,6 @@ a.kpi:hover { outline-offset: -2px; } -/* Picker trigger on the selected GZF cell. Positioned over the cell so the - column width does not change while the selection moves. */ -.tree-grid td:has(> .cell-picker-trigger) { - position: relative; -} - -.tree-grid .cell-picker-trigger { - position: absolute; - top: 50%; - left: 0.2rem; - transform: translateY(-50%); - display: inline-flex; - align-items: center; - justify-content: center; - width: 1.15rem; - height: 1.15rem; - border: 1px solid var(--accent-blue-strong-border); - border-radius: 3px; - padding: 0; - background: var(--panel-bg); - color: var(--color-primary); - cursor: pointer; -} - -:root[data-bs-theme="dark"] .tree-grid .cell-picker-trigger { - color: var(--color-accent-pale); -} - -.tree-grid .cell-picker-trigger:hover { - background: var(--accent-blue-soft-bg); -} - .tree-grid .section-title { display: flex; align-items: baseline; @@ -1704,7 +1307,7 @@ a.kpi:hover { .tree-grid .action-cell { display: flex; - gap: 0.25rem; + gap: 0.3rem; } .tree-grid .action-cell button { @@ -1900,983 +1503,3 @@ a.kpi:hover { .sidebar-collapsed .sidebar-label { display: none; } - -/* ── Gebäudestruktur (Gebäude → Etagen → Räume) ─────────────────────── */ - -.structure-columns { - display: grid; - grid-template-columns: minmax(0, 1fr); - gap: var(--space-md); - align-items: start; -} - -@media (min-width: 992px) { - .structure-columns { - grid-template-columns: repeat(3, minmax(0, 1fr)); - } -} - -.structure-column-title { - font-size: 1rem; - font-weight: 700; - margin: 0; - display: flex; - align-items: center; -} - -.structure-icon-button { - display: inline-flex; - align-items: center; - justify-content: center; - padding: 0.25rem 0.4rem; - line-height: 1; -} - -.structure-back-link { - display: inline-flex; - align-items: center; - justify-content: center; - padding: 0.35rem 0.45rem; - margin-top: 0.1rem; -} - -.structure-list { - max-height: 70vh; - overflow-y: auto; -} - -.structure-entry { - display: flex; - align-items: center; - gap: var(--space-sm); - padding: 0; -} - -.structure-entry-main { - flex: 1 1 auto; - min-width: 0; - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-sm); - padding: 0.55rem 0.75rem; - border: 0; - background: transparent; - color: inherit; - text-align: left; - font: inherit; -} - -button.structure-entry-main { - cursor: pointer; -} - -button.structure-entry-main:hover { - background: var(--surface-hover); -} - -button.structure-entry-main:focus-visible { - outline: 2px solid var(--accent-blue); - outline-offset: -2px; -} - -.structure-entry.is-selected { - background: var(--surface-selected); - box-shadow: inset 3px 0 0 var(--color-signal); -} - -.structure-entry.is-selected .structure-entry-label { - font-weight: 600; -} - -.structure-entry.is-selected button.structure-entry-main:hover { - background: transparent; -} - -.structure-entry-text { - min-width: 0; - display: flex; - flex-direction: column; -} - -.structure-entry-label { - overflow-wrap: anywhere; -} - -.structure-entry-hint { - font-size: 0.78rem; - color: var(--color-ink-soft); -} - -.structure-entry-meta { - flex: 0 0 auto; - font-size: 0.78rem; - color: var(--color-ink-soft); - white-space: nowrap; -} - -.structure-entry-actions { - flex: 0 0 auto; - display: inline-flex; - gap: 4px; - padding-right: 0.75rem; -} - -.structure-room-number { - font-weight: 600; - font-variant-numeric: tabular-nums; -} - -.structure-group-label { - font-size: 0.66rem; - letter-spacing: 0.08em; - text-transform: uppercase; - font-weight: 600; - color: var(--color-accent); - background: var(--panel-bg-subtle); - padding: 0.35rem 0.75rem; -} - -.structure-empty { - 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-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: 4.5rem; } - -.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-row-actions { - display: flex; - justify-content: center; - gap: 2px; - white-space: nowrap; -} - -.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; -} - -/* 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. */ -.estimate-print-titleblock { - display: none; -} - -@page estimate-balance { - size: A4 landscape; - 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, - .estimate-print-root button { - display: none !important; - } - - 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; - } - - .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: 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; - } - - /* 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-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 !important; - 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-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.4pt; - line-height: 1.2; - background: #fff; - color: var(--ep-text); - } - - .estimate-sheet th, - .estimate-sheet td { - 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 { - 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: 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 { - 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-row { - break-inside: avoid; - } - - .estimate-group-title-row { - break-after: avoid; - } - - /* Summen einmal am Ende, nicht auf jeder Seite */ - .estimate-sheet tfoot { - display: table-row-group; - break-inside: avoid; - } - - .estimate-col-actions { - width: 0; - } - - .estimate-unit-input, - .estimate-gzf-input { - 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; -} - -/* 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; - flex: 1 1 auto; - min-width: 0; - 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; - cursor: pointer; -} - -.sidebar-logout:hover { - background: rgba(255, 255, 255, 0.1); - color: #fff; -} - -.sidebar-collapsed .sidebar-identity { - display: none; -} - -.sidebar-collapsed .sidebar-bottom-row { - justify-content: center; - padding-inline: 0; -} - -.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 c830c99..cd2407b 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -3,8 +3,6 @@ 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", @@ -38,11 +36,7 @@ export default function RootLayout({ children }: Readonly<{ children: React.Reac - - - {children} - - + {children} ); diff --git a/src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx b/src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx index 90893f6..89679cf 100644 --- a/src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx +++ b/src/app/projects/[projectId]/circuit-lists/[circuitListId]/tree-edit/page.tsx @@ -1,6 +1,5 @@ "use client"; -import { ArrowLeft } from "lucide-react"; import Link from "next/link"; import { useParams } from "next/navigation"; import { CircuitTreeEditor } from "../../../../../../frontend/components/circuit-tree-editor"; @@ -11,19 +10,9 @@ export default function CircuitTreeEditPage() { return (
-
- -
-
- -
+
- setBoardFilters(emptyDistributionBoardFilters)} - storageKey={boardFilterCollapsedStorageKey} - totalCount={boards.length} - visibleCount={visibleBoards.length} - > - - setBoardFilters((current) => ({ ...current, query })) - } - placeholder="Verteilungen durchsuchen …" - value={boardFilters.query} - /> - - setBoardFilters((current) => ({ ...current, floorIds })) - } - options={floorFilterOptions} - selected={effectiveBoardFilters.floorIds} - /> - - setBoardFilters((current) => ({ ...current, supplyTypes })) - } - options={supplyTypeFilterOptions} - selected={effectiveBoardFilters.supplyTypes} - /> -
@@ -1101,13 +951,12 @@ export default function ProjectDetailPage() { - - {visibleBoards.map((board) => { + {boards.map((board) => { const circuitList = circuitListByBoardId.get(board.id); return ( @@ -1128,7 +977,6 @@ export default function ProjectDetailPage() { ] : "Nicht festgelegt"} -
Örtlichkeit Etage NetzartGespeist von GZF Aktionen
{formatBoardFeedingReference(board)} {board.simultaneityFactor.toLocaleString( "de-DE", @@ -1139,21 +987,22 @@ export default function ProjectDetailPage() { )} -
- + {circuitList ? ( - + > + Stromkreisliste öffnen + ) : ( Keine Stromkreisliste vorhanden @@ -1173,11 +1022,88 @@ export default function ProjectDetailPage() { ) : null}
- {boards.length > 0 && visibleBoards.length === 0 ? ( -

- Keine Verteilungen entsprechen den Filtern. -

+
+ + + +
+
+
+
+ Etagen + {floorCount} +
+ +
+
    + {floors.map((floor) => ( +
  • + {floor.name} + +
  • + ))} + {!floors.length ? ( +
  • Noch keine Etagen vorhanden.
  • ) : null} +
+
+
+ +
+
+
+
+ Räume + {roomCount} +
+ +
+
+ + + + + + + + + + + {rooms.map((room) => ( + + + + + + + ))} + {!rooms.length ? ( + + + + ) : null} + +
RaumnummerRaumnameEtageAktionen
{room.roomNumber}{room.roomName}{room.floorId ? floorById.get(room.floorId)?.name ?? "-" : "-"} + +
+ Noch keine Räume vorhanden. +
@@ -1189,58 +1115,24 @@ export default function ProjectDetailPage() { Projektgeräte {projectDeviceCount} -
- setIsProjectDeviceModalOpen(true)} - showLabel - variant="primary" +
+ setProjectDeviceQuery(event.target.value)} + placeholder="Geräte durchsuchen" + type="search" + value={projectDeviceQuery} /> +
- setProjectDeviceFilters(emptyProjectDeviceFilters)} - storageKey={projectDeviceFilterCollapsedStorageKey} - totalCount={projectDevices.length} - visibleCount={visibleProjectDevices.length} - > - - setProjectDeviceFilters((current) => ({ ...current, query })) - } - placeholder="Gerät, Anschlussart, KG …" - value={projectDeviceFilters.query} - /> - - setProjectDeviceFilters((current) => ({ ...current, categories })) - } - options={projectDeviceCategoryFilterOptions} - selected={effectiveProjectDeviceFilters.categories} - /> - - setProjectDeviceFilters((current) => ({ ...current, phaseTypes })) - } - options={projectDevicePhaseTypeFilterOptions} - selected={effectiveProjectDeviceFilters.phaseTypes} - /> - - setProjectDeviceFilters((current) => ({ ...current, costGroups })) - } - options={costGroupFilterOptions} - selected={effectiveProjectDeviceFilters.costGroups} - /> -
@@ -1259,13 +1151,11 @@ export default function ProjectDetailPage() { {device.displayName}
{device.name} - {device.category - ? ` · ${circuitGroupCategoryLabels[device.category] ?? device.category}` - : ""} + {device.category ? ` · ${device.category}` : ""}
@@ -1316,7 +1212,7 @@ export default function ProjectDetailPage() { @@ -1333,13 +1229,9 @@ export default function ProjectDetailPage() { Nur ausgewählte Felder und Zeilen werden übernommen. Der Anzeigename bleibt standardmäßig lokal.

-
- setSyncPreview(null)} - /> -
+
@@ -1418,23 +1310,23 @@ export default function ProjectDetailPage() {
- {projectDevicePhaseTypeLabels[device.phaseType]} + {device.phaseType === "three_phase" ? "3-phasig" : "1-phasig"} {device.connectionKind ? (
{device.connectionKind} @@ -1273,41 +1163,47 @@ export default function ProjectDetailPage() { ) : null}
- {formatValue(device.totalPower, "rowTotalPower")} kW + {device.totalPower} kW
- {formatValue(device.quantity, "quantity")} ×{" "} - {formatValue(device.powerPerUnit, "powerPerUnit")} kW · GZF{" "} - {formatValue(device.simultaneityFactor, "simultaneityFactor")} + {device.quantity} × {device.powerPerUnit} kW · GZF{" "} + {device.simultaneityFactor}
{device.costGroup ?? "-"} -
- + + + +
{projectDevices.length - ? "Keine Projektgeräte entsprechen den Filtern." + ? "Keine Projektgeräte entsprechen der Suche." : "Noch keine Projektgeräte vorhanden."}
-
- + +
) : null} @@ -1474,7 +1366,11 @@ export default function ProjectDetailPage() { value={boardFloorId} > - + {floors.map((floor) => ( + + ))}
@@ -1507,7 +1403,7 @@ export default function ProjectDetailPage() { {editingBoard ? ( setEditingBoard(null)} onSubmit={handleUpdateBoard} @@ -1540,7 +1436,11 @@ export default function ProjectDetailPage() { value={editingBoardFloorId} > - + {floors.map((floor) => ( + + ))}
@@ -1594,175 +1494,6 @@ export default function ProjectDetailPage() {
-
-
- Logische Einspeisung -
-
-
- - -
-
- - -
- {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 - 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} - {selectedFeedingCircuitCategory !== undefined && - selectedFeedingCircuitCategory !== "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} -
-
) : null} + {structureModal === "floor" ? ( + { + setStructureModal(null); + setEditingFloor(null); + }} + onSubmit={handleSaveFloor} + submitDisabled={!floorName.trim()} + submitLabel={editingFloor ? "Änderungen speichern" : "Etage hinzufügen"} + title={editingFloor ? "Etage bearbeiten" : "Etage hinzufügen"} + > + + setFloorName(event.target.value)} + placeholder="z. B. EG" + required + value={floorName} + /> + {editingFloor ? ( +
+

+ Etagen mit zugeordneten Räumen oder Verteilungen können nicht gelöscht werden. +

+ +
+ ) : null} +
+ ) : null} + + {structureModal === "room" ? ( + { + setStructureModal(null); + setEditingRoom(null); + }} + onDelete={editingRoom ? () => void handleDeleteRoom() : undefined} + onSave={handleSaveRoom} + /> + ) : null} + {isProjectDeviceModalOpen ? ( ) : null} + {project && isRevitCsvOpen ? ( + setIsRevitCsvOpen(false)} + onCreateProjectDevice={handleCreateRevitProjectDevice} + onCreateRoom={handleCreateRevitRoom} + onRevisionChange={applyProjectRevision} + projectId={projectId} + /> + ) : null}
); } diff --git a/src/app/projects/[projectId]/print/page.tsx b/src/app/projects/[projectId]/print/page.tsx index 7762875..11e6710 100644 --- a/src/app/projects/[projectId]/print/page.tsx +++ b/src/app/projects/[projectId]/print/page.tsx @@ -7,9 +7,10 @@ import "../../../../frontend/print/print-document.css"; import { deleteDocumentLogo, documentLogoUrl, - getProjectCircuitTrees, + getCircuitTree, getDocumentBranding, getProject, + listCircuitLists, listDistributionBoards, listFloors, listProjectSnapshots, @@ -29,8 +30,7 @@ import { } from "../../../../shared/constants/project-cover"; import { PrintDocument } from "../../../../frontend/print/print-document"; import { - assertPrintRevisionConsistency, - buildBoardHierarchy, + buildPreliminaryBoardHierarchy, summarizePrintBoard, type PrintBoardSummary, } from "../../../../frontend/print/print-document-model"; @@ -88,20 +88,17 @@ export default function ProjectPrintPage() { } let cancelled = false; async function load() { - const [project, boards, projectTrees, floors, snapshots, branding] = + const [project, boards, circuitLists, floors, snapshots, branding] = await Promise.all([ getProject(projectId), listDistributionBoards(projectId), - getProjectCircuitTrees(projectId), + listCircuitLists(projectId), listFloors(projectId), listProjectSnapshots(projectId), getDocumentBranding(), ]); const floorNameById = new Map(floors.map((floor) => [floor.id, floor.name])); - const treeByBoardId = new Map( - projectTrees.trees.map((tree) => [tree.distributionBoardId, tree]) - ); - const summaries = + const summaries = await Promise.all( [...boards] .sort( (left, right) => @@ -109,19 +106,20 @@ export default function ProjectPrintPage() { boardSortCollator.compare(left.name, right.name) ) .flatMap((board) => { - const tree = treeByBoardId.get(board.id); - return tree ? [{ board, tree }] : []; + const circuitList = circuitLists.find( + (list) => list.distributionBoardId === board.id + ); + return circuitList ? [{ board, circuitList }] : []; }) - .map(({ board, tree }) => + .map(async ({ board, circuitList }) => summarizePrintBoard({ board, - circuitListId: tree.circuitListId, - tree, + 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; } @@ -147,7 +145,7 @@ export default function ProjectPrintPage() { }, [projectId]); const entries = useMemo( - () => (data ? buildBoardHierarchy(data.summaries) : []), + () => (data ? buildPreliminaryBoardHierarchy(data.summaries) : []), [data] ); const stand = useMemo( diff --git a/src/app/projects/[projectId]/revit/page.tsx b/src/app/projects/[projectId]/revit/page.tsx deleted file mode 100644 index 8c2735c..0000000 --- a/src/app/projects/[projectId]/revit/page.tsx +++ /dev/null @@ -1,54 +0,0 @@ -"use client"; - -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 { RevitFollowUpImportWizard } from "../../../../frontend/components/revit-follow-up-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"; -import { createDefaultRevitXlsxConfiguration } from "../../../../frontend/utils/revit-xlsx-settings"; -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 [importStatus, setImportStatus] = useState(null); - const [settingsOpen, setSettingsOpen] = useState(false); - const [importOpen, setImportOpen] = useState(false); - const [followUpOpen, setFollowUpOpen] = useState(false); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); - - 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 }); - 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

- {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} · Fehlend: {importStatus.missingObjectCount}

:

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} - {followUpOpen && project && snapshot ? setFollowUpOpen(false)} onImported={({ history }) => { setProject({ ...project, currentRevision: history.currentRevision }); setFollowUpOpen(false); void Promise.all([getExternalInitialImportStatus(projectId), getExternalModelConfiguration(projectId)]).then(([status, configuration]) => { setImportStatus(status); setSnapshot(configuration.configuration); }); }} /> : null} -
; -} diff --git a/src/app/projects/[projectId]/struktur/page.tsx b/src/app/projects/[projectId]/struktur/page.tsx deleted file mode 100644 index 3cefa62..0000000 --- a/src/app/projects/[projectId]/struktur/page.tsx +++ /dev/null @@ -1,855 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { useParams } from "next/navigation"; -import { - type FormEvent, - type ReactNode, - useCallback, - useEffect, - useMemo, - useState, -} from "react"; -import { ArrowLeft, Pencil, Plus, Trash2 } from "lucide-react"; -import { - createBuilding, - createFloor, - createRoom, - deleteBuilding, - deleteFloor, - deleteRoom, - getProject, - listBuildings, - listFloors, - listRooms, - updateBuilding, - updateFloor, - updateRoom, -} from "../../../../frontend/utils/api"; -import type { - BuildingDto, - CreateRoomInput, - FloorDto, - ProjectCommandResultDto, - ProjectDto, - RoomDto, -} from "../../../../frontend/types"; -import { - ALL_SELECTION, - UNASSIGNED_BUILDING_LABEL, - UNASSIGNED_FLOOR_LABEL, - UNASSIGNED_SELECTION, - countFloorsByBuilding, - countRoomsByFloor, - defaultBuildingIdForNewFloor, - defaultFloorIdForNewRoom, - describeRoomLocation, - filterFloorsByBuilding, - filterRooms, - groupFloorsByBuilding, - hasFloorsWithoutBuilding, - hasRoomsWithoutFloor, - normalizeBuildingSelection, - normalizeFloorSelection, - showsRoomsWithoutFloorEntry, - summarizeRoomAreas, - type RoomAreaSummary, - type StructureSelection, -} from "../../../../frontend/utils/building-structure"; -import { FormModal } from "../../../../frontend/components/form-modal"; -import { RoomModal } from "../../../../frontend/components/room-modal"; -import { formatRoomArea } from "../../../../frontend/utils/room-area"; - -const BUILDING_HAS_FLOORS_MESSAGE = - "Das Gebäude kann nicht gelöscht werden, solange Etagen zugeordnet sind."; - -type StructureDialog = - | { kind: "building"; building: BuildingDto | null } - | { kind: "floor"; floor: FloorDto | null } - | { kind: "room"; room: RoomDto | null; defaultFloorId: string }; - -function formatCount(count: number, singular: string, plural: string) { - return `${count} ${count === 1 ? singular : plural}`; -} - -function formatAreaSummary(summary: RoomAreaSummary) { - return `${formatRoomArea(summary.areaM2)} m² · ${formatCount( - summary.missingAreaCount, - "Raum ohne Fläche", - "Räume ohne Fläche" - )}`; -} - -function formatStructureMeta( - count: number, - singular: string, - plural: string, - summary: RoomAreaSummary -) { - return `${formatCount(count, singular, plural)} · ${formatAreaSummary(summary)}`; -} - -function compareRooms(left: RoomDto, right: RoomDto) { - return ( - left.roomNumber.localeCompare(right.roomNumber, "de", { numeric: true }) || - left.roomName.localeCompare(right.roomName, "de") - ); -} - -interface StructureColumnProps { - addLabel: string; - children: ReactNode; - count: number; - headingId: string; - isAddDisabled: boolean; - onAdd: () => void; - title: string; -} - -function StructureColumn({ - addLabel, - children, - count, - headingId, - isAddDisabled, - onAdd, - title, -}: StructureColumnProps) { - return ( -
-
-

- {title} - {count} -

- -
-
    {children}
-
- ); -} - -interface StructureEntryProps { - actions?: ReactNode; - hint?: string; - isSelected?: boolean; - label: ReactNode; - meta?: string; - onSelect?: () => void; -} - -function StructureEntry({ - actions, - hint, - isSelected = false, - label, - meta, - onSelect, -}: StructureEntryProps) { - const content = ( - <> - - {label} - {hint ? {hint} : null} - - {meta ? {meta} : null} - - ); - return ( -
  • - {onSelect ? ( - - ) : ( -
    {content}
    - )} - {actions ?
    {actions}
    : null} -
  • - ); -} - -interface EntryActionsProps { - deleteLabel: string; - editLabel: string; - isDisabled: boolean; - onDelete: () => void; - onEdit: () => void; -} - -function EntryActions({ - deleteLabel, - editLabel, - isDisabled, - onDelete, - onEdit, -}: EntryActionsProps) { - return ( - <> - - - - ); -} - -export default function BuildingStructurePage() { - const params = useParams<{ projectId: string }>(); - const projectId = params.projectId; - const [project, setProject] = useState(null); - const [buildings, setBuildings] = useState([]); - const [floors, setFloors] = useState([]); - const [rooms, setRooms] = useState([]); - const [buildingSelection, setBuildingSelection] = - useState(ALL_SELECTION); - const [floorSelection, setFloorSelection] = - useState(ALL_SELECTION); - const [dialog, setDialog] = useState(null); - const [dialogName, setDialogName] = useState(""); - const [dialogBuildingId, setDialogBuildingId] = useState(""); - const [error, setError] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const [isSaving, setIsSaving] = useState(false); - - const reloadStructure = useCallback(async () => { - const [currentProject, loadedBuildings, loadedFloors, loadedRooms] = - await Promise.all([ - getProject(projectId), - listBuildings(projectId), - listFloors(projectId), - listRooms(projectId), - ]); - setProject(currentProject); - setBuildings(loadedBuildings); - setFloors(loadedFloors); - setRooms(loadedRooms); - }, [projectId]); - - useEffect(() => { - if (!projectId) { - return; - } - setIsLoading(true); - reloadStructure() - .then(() => setError(null)) - .catch((err: unknown) => - setError( - err instanceof Error - ? err.message - : "Gebäudestruktur konnte nicht geladen werden." - ) - ) - .finally(() => setIsLoading(false)); - }, [projectId, reloadStructure]); - - const effectiveBuildingSelection = normalizeBuildingSelection( - buildingSelection, - floors, - buildings - ); - const effectiveFloorSelection = normalizeFloorSelection( - floorSelection, - rooms, - floors, - buildings, - effectiveBuildingSelection - ); - - const visibleFloors = useMemo( - () => filterFloorsByBuilding(floors, buildings, effectiveBuildingSelection), - [buildings, effectiveBuildingSelection, floors] - ); - const visibleFloorGroups = useMemo( - () => - effectiveBuildingSelection === ALL_SELECTION && buildings.length - ? groupFloorsByBuilding(visibleFloors, buildings) - : [{ buildingId: null, label: "", floors: visibleFloors }], - [buildings, effectiveBuildingSelection, visibleFloors] - ); - const visibleRooms = useMemo( - () => - filterRooms( - rooms, - floors, - buildings, - effectiveBuildingSelection, - effectiveFloorSelection - ).sort(compareRooms), - [buildings, effectiveBuildingSelection, effectiveFloorSelection, floors, rooms] - ); - const roomsInBuildingSelection = useMemo( - () => - filterRooms(rooms, floors, buildings, effectiveBuildingSelection, ALL_SELECTION) - .length, - [buildings, effectiveBuildingSelection, floors, rooms] - ); - const floorCountByBuilding = useMemo( - () => countFloorsByBuilding(floors, buildings), - [buildings, floors] - ); - const roomCountByFloor = useMemo( - () => countRoomsByFloor(rooms, floors), - [floors, rooms] - ); - const areaSummaries = useMemo( - () => summarizeRoomAreas(rooms, floors, buildings), - [buildings, floors, rooms] - ); - const emptyAreaSummary: RoomAreaSummary = { - areaM2: 0, - roomCount: 0, - missingAreaCount: 0, - }; - const selectedBuildingAreaSummary = - effectiveBuildingSelection === ALL_SELECTION - ? areaSummaries.total - : areaSummaries.byBuilding.get( - effectiveBuildingSelection === UNASSIGNED_SELECTION - ? null - : effectiveBuildingSelection - ) ?? emptyAreaSummary; - const showUnassignedBuilding = - hasFloorsWithoutBuilding(floors, buildings) || hasRoomsWithoutFloor(rooms, floors); - const showUnassignedFloor = showsRoomsWithoutFloorEntry( - rooms, - floors, - effectiveBuildingSelection - ); - const isBusy = isSaving || !project; - - function selectBuilding(selection: StructureSelection) { - setBuildingSelection(selection); - setFloorSelection(ALL_SELECTION); - } - - async function runCommand( - execute: (expectedRevision: number) => Promise, - fallbackMessage: string - ): Promise { - if (!project) { - return false; - } - setIsSaving(true); - setError(null); - try { - const result = await execute(project.currentRevision); - setProject((current) => - current - ? { ...current, currentRevision: result.history.currentRevision } - : current - ); - await reloadStructure(); - return true; - } catch (err) { - setError(err instanceof Error ? err.message : fallbackMessage); - // Refresh the revision and lists so a stale state does not block the - // next attempt; the command error stays visible. - await reloadStructure().catch(() => undefined); - return false; - } finally { - setIsSaving(false); - } - } - - function openBuildingDialog(building: BuildingDto | null) { - setDialogName(building?.name ?? ""); - setDialog({ kind: "building", building }); - } - - function openFloorDialog(floor: FloorDto | null) { - setDialogName(floor?.name ?? ""); - setDialogBuildingId( - floor - ? floor.buildingId ?? "" - : defaultBuildingIdForNewFloor(effectiveBuildingSelection) - ); - setDialog({ kind: "floor", floor }); - } - - function openRoomDialog(room: RoomDto | null) { - setDialog({ - kind: "room", - room, - defaultFloorId: defaultFloorIdForNewRoom(effectiveFloorSelection), - }); - } - - async function handleSaveBuilding(event: FormEvent) { - event.preventDefault(); - if (dialog?.kind !== "building" || !dialogName.trim()) { - return; - } - const editingBuilding = dialog.building; - const name = dialogName.trim(); - // An unchanged dialog is not a command; the backend rejects no-op updates. - if (editingBuilding && editingBuilding.name === name) { - setDialog(null); - return; - } - const saved = await runCommand( - (expectedRevision) => - editingBuilding - ? updateBuilding(projectId, editingBuilding.id, { name }, expectedRevision) - : createBuilding(projectId, { name }, expectedRevision), - "Gebäude konnte nicht gespeichert werden." - ); - if (saved) { - setDialog(null); - } - } - - async function handleSaveFloor(event: FormEvent) { - event.preventDefault(); - if (dialog?.kind !== "floor" || !dialogName.trim()) { - return; - } - const editingFloor = dialog.floor; - const input = { - name: dialogName.trim(), - buildingId: dialogBuildingId || null, - }; - if ( - editingFloor && - editingFloor.name === input.name && - editingFloor.buildingId === input.buildingId - ) { - setDialog(null); - return; - } - const saved = await runCommand( - (expectedRevision) => - editingFloor - ? updateFloor(projectId, editingFloor.id, input, expectedRevision) - : createFloor(projectId, input, expectedRevision), - "Etage konnte nicht gespeichert werden." - ); - if (saved) { - setDialog(null); - } - } - - async function handleSaveRoom(input: CreateRoomInput) { - if (dialog?.kind !== "room") { - return; - } - const editingRoom = dialog.room; - if ( - editingRoom && - editingRoom.roomNumber === input.roomNumber.trim() && - editingRoom.roomName === input.roomName.trim() && - editingRoom.floorId === (input.floorId || null) && - editingRoom.areaM2 === input.areaM2 - ) { - setDialog(null); - return; - } - const saved = await runCommand( - (expectedRevision) => - editingRoom - ? updateRoom(projectId, editingRoom.id, input, expectedRevision) - : createRoom(projectId, input, expectedRevision), - "Raum konnte nicht gespeichert werden." - ); - if (saved) { - setDialog(null); - } - } - - async function handleDeleteBuilding(building: BuildingDto) { - if ((floorCountByBuilding.get(building.id) ?? 0) > 0) { - setError(BUILDING_HAS_FLOORS_MESSAGE); - return; - } - if (!window.confirm(`Gebäude „${building.name}“ wirklich löschen?`)) { - return; - } - await runCommand( - (expectedRevision) => - deleteBuilding(projectId, building.id, expectedRevision), - "Gebäude konnte nicht gelöscht werden." - ); - } - - async function handleDeleteFloor(floor: FloorDto) { - if (!window.confirm(`Etage „${floor.name}“ wirklich löschen?`)) { - return; - } - await runCommand( - (expectedRevision) => deleteFloor(projectId, floor.id, expectedRevision), - "Etage konnte nicht gelöscht werden." - ); - } - - async function handleDeleteRoom(room: RoomDto) { - if ( - !window.confirm( - `Raum „${room.roomNumber} ${room.roomName}“ wirklich löschen?` - ) - ) { - return; - } - await runCommand( - (expectedRevision) => deleteRoom(projectId, room.id, expectedRevision), - "Raum konnte nicht gelöscht werden." - ); - } - - return ( -
    -
    -
    - -
    -
    - - {error ? ( -
    - {error} -
    - ) : null} - {isLoading ? ( -

    - Gebäudestruktur wird geladen … -

    - ) : null} - -
    - openBuildingDialog(null)} - title="Gebäude" - > - selectBuilding(ALL_SELECTION)} - /> - {buildings.map((building) => ( - void handleDeleteBuilding(building)} - onEdit={() => openBuildingDialog(building)} - /> - } - isSelected={effectiveBuildingSelection === building.id} - key={building.id} - label={building.name} - meta={formatStructureMeta( - floorCountByBuilding.get(building.id) ?? 0, - "Etage", - "Etagen", - areaSummaries.byBuilding.get(building.id) ?? emptyAreaSummary - )} - onSelect={() => selectBuilding(building.id)} - /> - ))} - {showUnassignedBuilding ? ( - {UNASSIGNED_BUILDING_LABEL}} - meta={formatStructureMeta( - floorCountByBuilding.get(null) ?? 0, - "Etage", - "Etagen", - areaSummaries.byBuilding.get(null) ?? emptyAreaSummary - )} - onSelect={() => selectBuilding(UNASSIGNED_SELECTION)} - /> - ) : null} - {!buildings.length && !isLoading ? ( -
  • - Noch keine Gebäude vorhanden. -
  • - ) : null} -
    - - openFloorDialog(null)} - title="Etagen" - > - setFloorSelection(ALL_SELECTION)} - /> - {visibleFloorGroups.map((group) => ( - - {group.floors.map((floor) => ( - void handleDeleteFloor(floor)} - onEdit={() => openFloorDialog(floor)} - /> - } - isSelected={effectiveFloorSelection === floor.id} - key={floor.id} - label={floor.name} - meta={formatStructureMeta( - roomCountByFloor.get(floor.id) ?? 0, - "Raum", - "Räume", - areaSummaries.byFloor.get(floor.id) ?? emptyAreaSummary - )} - onSelect={() => setFloorSelection(floor.id)} - /> - ))} - - ))} - {showUnassignedFloor ? ( - {UNASSIGNED_FLOOR_LABEL}} - meta={formatStructureMeta( - roomCountByFloor.get(null) ?? 0, - "Raum", - "Räume", - areaSummaries.byFloor.get(null) ?? emptyAreaSummary - )} - onSelect={() => setFloorSelection(UNASSIGNED_SELECTION)} - /> - ) : null} - {!visibleFloors.length && !isLoading ? ( -
  • - {floors.length - ? "Keine Etagen in dieser Auswahl." - : "Noch keine Etagen vorhanden."} -
  • - ) : null} -
    - - openRoomDialog(null)} - title="Räume" - > - {visibleRooms.map((room) => ( - void handleDeleteRoom(room)} - onEdit={() => openRoomDialog(room)} - /> - } - hint={ - effectiveFloorSelection === ALL_SELECTION - ? describeRoomLocation(room, floors, buildings) - : undefined - } - key={room.id} - label={ - <> - {room.roomNumber}{" "} - {room.roomName} - - } - meta={ - room.areaM2 === null - ? "Fläche fehlt" - : `${formatRoomArea(room.areaM2)} m²` - } - /> - ))} - {!visibleRooms.length && !isLoading ? ( -
  • - {rooms.length - ? "Keine Räume in dieser Auswahl." - : "Noch keine Räume vorhanden."} -
  • - ) : null} -
    -
    - - {dialog?.kind === "building" ? ( - setDialog(null)} - onSubmit={handleSaveBuilding} - submitDisabled={!dialogName.trim()} - submitLabel={dialog.building ? "Änderungen speichern" : "Gebäude hinzufügen"} - title={dialog.building ? "Gebäude bearbeiten" : "Gebäude hinzufügen"} - > - - setDialogName(event.target.value)} - placeholder="z. B. Haus A" - required - value={dialogName} - /> - - ) : null} - - {dialog?.kind === "floor" ? ( - setDialog(null)} - onSubmit={handleSaveFloor} - submitDisabled={!dialogName.trim()} - submitLabel={dialog.floor ? "Änderungen speichern" : "Etage hinzufügen"} - title={dialog.floor ? "Etage bearbeiten" : "Etage hinzufügen"} - > -
    -
    - - setDialogName(event.target.value)} - placeholder="z. B. EG" - required - value={dialogName} - /> -
    -
    - - -
    -
    -
    - ) : null} - - {dialog?.kind === "room" ? ( - setDialog(null)} - onSave={handleSaveRoom} - /> - ) : null} -
    - ); -} - -function FloorGroupEntries({ - children, - label, -}: { - children: ReactNode; - label: string; -}) { - return ( - <> - {label ? ( -
  • - {label} -
  • - ) : null} - {children} - - ); -} diff --git a/src/cable-sizing/domain/cable-sizing-calculation.ts b/src/cable-sizing/domain/cable-sizing-calculation.ts index 07dd052..3f228f4 100644 --- a/src/cable-sizing/domain/cable-sizing-calculation.ts +++ b/src/cable-sizing/domain/cable-sizing-calculation.ts @@ -1,15 +1,31 @@ -// 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). +// Pure cable sizing domain logic. No imports from db/, server/ or frontend/ - +// mirrors the dependency direction of src/external-model/ (see +// docs/cable-sizing-module.md). Everything here is a stateless function on +// plain data; persistence and the versioned circuit.update command live +// outside this module. // -// Reference data: DIN VDE 0298-4 (VDE 0298-4):2023-06 together with -// Berichtigung 1:2023-10. The table-by-table scope and the separate sources -// required for voltage drop and protection coordination are documented in -// docs/cable-sizing-module.md. +// The numeric reference tables below (cross-section current-carrying +// capacity, temperature/grouping correction factors) are ported from a +// sibling project's already-verified Kabelliste module +// (elt-planung-suite/src/tools/kabel/index.ts), not re-derived. See +// docs/cable-sizing-module.md for the verification history and the explicit +// "not yet verified" methods, which intentionally return no numeric result +// instead of a guessed one (dataVerified: false). -// -- Reference installation methods (DIN VDE 0298-4, Table 2) --------------- +// -- Laying methods (DIN VDE 0298-4 reference installation methods) -------- -export const LAYING_METHODS = ["A1", "A2", "B1", "B2", "C", "D", "E"] as const; +export const LAYING_METHODS = [ + "A1", + "A2", + "B1", + "B2", + "C", + "D1", + "D2", + "E", + "F", + "G", +] as const; export type LayingMethod = (typeof LAYING_METHODS)[number]; export const LAYING_METHOD_GROUP: Record = { @@ -19,17 +35,40 @@ export const LAYING_METHOD_GROUP: Record = { B2: "air", C: "air", E: "air", - D: "ground", + F: "air", + D1: "ground", + D2: "ground", + G: "ground", +}; + +// A1, B2, C, E, D1, D2: verified against elt-planung-suite's ported original +// tool. A2, B1, F, G: no verified capacity table available yet (see +// docs/cable-sizing-module.md) - calculateCableSizing returns +// dataVerified: false for these instead of a guessed number. +export const LAYING_METHOD_VERIFIED: Record = { + A1: true, + B2: true, + C: true, + E: true, + D1: true, + D2: true, + A2: false, + B1: false, + F: false, + G: false, }; 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", - D: "D – Mehradriges Kabel im Rohr oder Kanal im Erdreich", - E: "E – Mehradrige Leitung frei in Luft", + A1: "A1 - Rohr in wärmegedämmter Wand", + A2: "A2 - Mehradriges Kabel im Rohr in wärmegedämmter Wand (Werte nicht hinterlegt)", + B1: "B1 - Einzeladern im Rohr auf/unter Putz (Werte nicht hinterlegt)", + B2: "B2 - Rohr auf/unter Putz", + C: "C - Kabel direkt auf Wand verlegt", + E: "E - Kabelpritsche / frei in Luft", + F: "F - Kabel frei in Luft, einzeln mit Abstand (Werte nicht hinterlegt)", + D1: "D1 - Kabel direkt im Erdreich", + D2: "D2 - Kabel im Rohr im Erdreich", + G: "G - Erdverlegung, Sonderfall (Werte nicht hinterlegt)", }; // -- Insulation / conductor material ---------------------------------------- @@ -38,14 +77,23 @@ 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", + pvc: "PVC (Grenztemperatur 70 °C)", + xlpe: "VPE/XLPE (Grenztemperatur 90 °C) - Strombelastbarkeitswerte nicht hinterlegt", }; export const CONDUCTOR_MATERIALS = ["copper", "aluminum"] as const; export type ConductorMaterial = (typeof CONDUCTOR_MATERIALS)[number]; -// -- Harmonic neutral loading (DIN VDE 0298-4, Annex B, three-phase only) --- +// Only PVC combined with one of the six verified laying methods returns a +// numeric result. XLPE has no verified capacity table for any method yet. +export function isCableSizingDataVerified( + layingMethod: LayingMethod, + insulation: InsulationMaterial +): boolean { + return insulation === "pvc" && LAYING_METHOD_VERIFIED[layingMethod]; +} + +// -- Harmonic neutral loading (IEC 60364-5-52, three-phase only) ----------- export const HARMONIC_NEUTRAL_LOAD_OPTIONS = [ "none", @@ -55,309 +103,128 @@ export const HARMONIC_NEUTRAL_LOAD_OPTIONS = [ 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 % – ohne Neutralleiterstrom keine Empfehlung", + none: "Keine nennenswerte 3. Harmonische (< 15 %) - Standardfall", + "15to33Percent": + "3. Harmonische 15-33 % - Reduktionsfaktor 0,86 (IEC 60364-5-52)", + over33Percent: + "3. Harmonische > 33 % - Neutralleiter wie Außenleiter dimensionieren", }; export const HARMONIC_REDUCTION_FACTOR = 0.86; -// -- Current-carrying capacity tables ---------------------------------------- +// -- Reference tables (ported, verified subset only) ------------------------ 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 +export const CURRENT_CAPACITY_A: Partial< + Record> > = { - pvc: { - copper: { - // DIN VDE 0298-4, tables 3 and 4. - A1: { - 2: [15.5, 19.5, 26, 34, 46, 61, 80, 99, 119, 151, 182, 210, 240, 273, 321], - 3: [13.5, 18, 24, 31, 42, 56, 73, 89, 108, 136, 164, 188, 216, 245, 286], - }, - A2: { - 2: [15.5, 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], - }, - D: { - 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], - }, - 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: { - // DIN VDE 0298-4 aluminium values; the normalization below removes all - // entries below the first tabulated aluminium size of 25 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], - }, - D: { - 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], - }, - 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], - }, - }, + A1: { + 2: [15.5, 21, 28, 36, 50, 68, 89, 110, 134, 171, 207, 239, null, null, null], + 3: [13.5, 18, 24, 31, 42, 56, 73, 89, 108, 136, 164, 188, null, null, null], }, - 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], - }, - D: { - 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], - }, - 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], - }, - D: { - 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], - }, - 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], - }, - }, + B2: { + 2: [16.5, 23, 30, 38, 52, 69, 90, 111, 134, 171, 207, 239, null, null, null], + 3: [15, 20, 27, 34, 46, 62, 80, 99, 118, 149, 179, 206, null, null, null], + }, + 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], + }, + 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], + }, + D1: { + 2: [26, 34, 44, 56, 74, 96, 123, 147, 174, 216, 256, 290, 328, 367, 424], + 3: [22, 29, 38, 47, 63, 81, 104, 125, 148, 183, 216, 246, 278, 312, 361], + }, + D2: { + 2: [22, 29, 38, 47, 63, 81, 104, 125, 148, 183, 216, 246, 278, 312, 360], + 3: [18.5, 24, 31, 39, 52, 67, 86, 103, 122, 151, 179, 203, 230, 258, 297], }, }; -// DIN VDE 0298-4 only supplies aluminium current-carrying capacities from -// 25 mm² onward. Smaller values from the former IEC data set must therefore -// never participate in a recommendation. -for (const insulation of INSULATION_MATERIALS) { - for (const method of LAYING_METHODS) { - for (const coreCount of [2, 3] as const) { - const row = CURRENT_CAPACITY_A[insulation].aluminum[method][coreCount] as (number | null)[]; - CROSS_SECTIONS_MM2.forEach((crossSection, index) => { - if (crossSection < 25) { - row[index] = null; - } - }); - } - } -} - -// -- Correction factors ------------------------------------------------------ - -/** DIN VDE 0298-4 tables 17 (air) and 20 (ground). */ -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 TEMPERATURE_FACTOR_AIR: Record = { + 10: 1.29, + 15: 1.22, + 20: 1.15, + 25: 1.08, + 30: 1.0, + 35: 0.91, + 40: 0.82, + 45: 0.71, + 50: 0.58, }; -export const REFERENCE_TEMPERATURE_C: Record<"air" | "ground", number> = { - air: 30, - ground: 20, +export const TEMPERATURE_FACTOR_GROUND: Record = { + 10: 1.1, + 15: 1.05, + 20: 1.0, + 25: 0.95, + 30: 0.89, + 35: 0.84, + 40: 0.77, }; -/** - * Grouping reduction factors according to the corrected references in - * DIN VDE 0298-4 Berichtigung 1:2023-10: - * A1–C use table 22, row 1 (bundled/touching), D uses table 26 for touching - * conduits/ducts in earth. Method E needs details about support, spacing and - * number of trays from table 23, which the current input model does not carry; - * it is therefore supported only for one circuit. - */ -export const GROUPING_FACTORS: Record<"A1_TO_C" | "D" | "E", Record> = { - A1_TO_C: { - 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, 10: 0.48, 12: 0.45, 14: 0.43, 16: 0.41, 18: 0.39, 20: 0.38, - }, - D: { 1: 1.0, 2: 0.85, 3: 0.75, 4: 0.7, 5: 0.65, 6: 0.6 }, - E: { 1: 1.0 }, +export const GROUPING_FACTOR_AIR: Record = { + 1: 1.0, + 2: 0.8, + 3: 0.7, + 4: 0.65, + 5: 0.6, + 6: 0.57, + 8: 0.54, + 10: 0.5, }; -function groupingTableFor(method: LayingMethod) { - return method === "D" - ? GROUPING_FACTORS.D - : method === "E" - ? GROUPING_FACTORS.E - : GROUPING_FACTORS.A1_TO_C; -} +export const GROUPING_FACTOR_GROUND: Record = { + 1: 1.0, + 2: 0.75, + 3: 0.65, + 4: 0.6, + 5: 0.55, + 6: 0.52, + 8: 0.49, + 10: 0.46, +}; -export function maxGroupingCircuits(method: LayingMethod): number { - return Math.max(...Object.keys(groupingTableFor(method)).map(Number)); -} - -/** - * 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 ALUMINUM_CAPACITY_FACTOR = 0.78; 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 GROUPING_OPTIONS = [1, 2, 3, 4, 5, 6, 8, 10] as const; +export const GROUPING_LABELS: Record = { + 1: "1 (keine Häufung)", + 2: "2", + 3: "3", + 4: "4", + 5: "5", + 6: "6", + 8: "7-9", + 10: "≥10", +}; + +// -- Practical minimum cross-sections by circuit category ------------------ +// Not a thermal/voltage-drop calculation result - a widely used planning +// convention for margin against future load growth, mechanical robustness +// and fault-current withstand, beyond what a pure Ib-based calculation +// would give. Matches this project's own docs/spec/06-future-sizing-and- +// calculations.md ("Standard Single-Phase Circuits ... usually use ... +// cable cross-section: 2.5 mm²"). Only applied for the "single_phase" +// circuit category (general sockets and similar loads); lighting and +// three-phase circuits are not covered by this specific convention. export const PRACTICAL_MINIMUM_CROSS_SECTION_MM2: Partial> = { single_phase: 2.5, }; -// -- Protective device -------------------------------------------------------- +export type CircuitCategory = "lighting" | "single_phase" | "three_phase"; -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 ----------------------------------------------------------- +// -- Input / result ----------------------------------------------------- export interface CableSizingInput { phase: 1 | 3; @@ -367,68 +234,70 @@ export interface CableSizingInput { /** A, only used when mode === "current" */ currentA?: number; cosPhi: number; - /** Line voltage in V (project single-/three-phase voltage). */ + /** Line voltage in V. The circuit-list app derives this from project + * settings (singlePhaseVoltageV / threePhaseVoltageV); pass it through + * rather than hard-coding 230/400 here. */ voltage: number; - /** Single-run cable length in m. */ + /** Single-run cable length in meters (circuits.cableLength). */ lengthM: number; layingMethod: LayingMethod; conductorMaterial: ConductorMaterial; insulation: InsulationMaterial; - /** Ambient air temperature, or ground temperature for D. */ ambientTemperatureC: number; - /** Number of grouped circuits or multi-core cables, including this one. */ groupingCircuits: number; maxVoltageDropPercent: number; harmonicNeutralLoad: HarmonicNeutralLoad; - existingProtection?: ExistingProtection; + /** Optional: existing protection device rated current (LS/circuit + * breaker), for the simplified coordination check below. */ + existingProtectionRatedCurrentA?: number; + /** Optional: enables the practical-minimum-cross-section convention for + * "single_phase" circuits, see PRACTICAL_MINIMUM_CROSS_SECTION_MM2. */ 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. */ + /** Longest single-run length (m) at which this cross-section still meets + * the requested max voltage drop, at the given load/cosPhi/phase - the + * inverse of the voltage-drop formula used for voltageDropPercent above. + * null when the operating current is zero (division by zero). */ 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. */ + /** Simplified In <= Iz check only - not full overload (I2 <= 1.45 x Iz) + * or short-circuit coordination. */ coordinated: boolean; } -export type UnsupportedReason = "temperature" | "grouping" | "harmonics"; - export interface CableSizingResult { - /** false: the inputs are outside the tabulated range – no numeric result. */ - supported: boolean; - unsupportedReason: UnsupportedReason | null; + /** false: no verified capacity table for this layingMethod/insulation + * combination - every field below is null/empty, never a guess. */ + dataVerified: boolean; operatingCurrentA: number; - /** - * Current the cross-section must carry after correction: - * max(Ib, In, I2/1.45) with an existing protective device, otherwise Ib. - */ + /** max(operatingCurrentA, existingProtectionRatedCurrentA). The cable + * capacity (Iz) must cover the protective device's rated current (In), + * not just the actual load current - a breaker only trips at In, so a + * cable sized for Ib alone could overheat under sustained load below the + * trip threshold. This is the value cross-section selection actually + * uses; operatingCurrentA is kept for display/voltage-drop only. */ 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; + /** true if the recommendation was raised to satisfy + * PRACTICAL_MINIMUM_CROSS_SECTION_MM2 (a convention, not a thermal/ + * voltage-drop requirement of this specific circuit). */ practicalMinimumApplied: boolean; rows: CrossSectionRow[]; protectionCoordination: ProtectionCoordinationResult | null; @@ -446,132 +315,137 @@ function operatingCurrentA(input: CableSizingInput): number { 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 <= maxGroupingCircuits(input.layingMethod) - ? lookupConservative(groupingTableFor(input.layingMethod), Math.max(1, input.groupingCircuits)) - : null; - const harmonicsSupported = !( - input.phase === 3 && input.harmonicNeutralLoad === "over33Percent" - ); - const unsupportedReason: UnsupportedReason | null = !temperature - ? "temperature" - : !grouping - ? "grouping" - : !harmonicsSupported - ? "harmonics" - : null; - const empty: CableSizingResult = { - supported: false, - unsupportedReason, - 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 (unsupportedReason || !temperature || !grouping) { - return empty; + const designCurrentA = + input.existingProtectionRatedCurrentA != null + ? Math.max(ib, input.existingProtectionRatedCurrentA) + : ib; + + if (!isCableSizingDataVerified(input.layingMethod, input.insulation)) { + return { + dataVerified: false, + operatingCurrentA: ib, + designCurrentA, + crossSectionByCapacityMm2: null, + crossSectionByVoltageDropMm2: null, + recommendedCrossSectionMm2: null, + voltageDropAtRecommendedPercent: null, + combinedDerationFactor: 1, + harmonicReductionApplied: false, + practicalMinimumApplied: false, + rows: [], + protectionCoordination: null, + }; } const coreCount: CoreCount = input.phase === 1 ? 2 : 3; + const aluminumFactor = + input.conductorMaterial === "aluminum" ? ALUMINUM_CAPACITY_FACTOR : 1; + const kappa = KAPPA[input.conductorMaterial]; + const group = LAYING_METHOD_GROUP[input.layingMethod]; + const temperatureTable = + group === "air" ? TEMPERATURE_FACTOR_AIR : TEMPERATURE_FACTOR_GROUND; + const groupingTable = group === "air" ? GROUPING_FACTOR_AIR : GROUPING_FACTOR_GROUND; + const temperatureFactor = temperatureTable[input.ambientTemperatureC] ?? 1; + const groupingFactor = groupingTable[input.groupingCircuits] ?? 1; + 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 harmonicFactor = harmonicReductionApplied ? HARMONIC_REDUCTION_FACTOR : 1; - const ratedCurrents = - CURRENT_CAPACITY_A[input.insulation][input.conductorMaterial][input.layingMethod][coreCount]; + const combinedDerationFactor = temperatureFactor * groupingFactor * harmonicFactor; + const voltageDropCoefficient = input.phase === 1 ? 2 : Math.sqrt(3); + + const ratedCurrents = CURRENT_CAPACITY_A[input.layingMethod]![coreCount]; const correctedCurrents = ratedCurrents.map((value) => - value == null ? null : value * combinedDerationFactor + value == null ? null : value * aluminumFactor * combinedDerationFactor ); const voltageDrops = CROSS_SECTIONS_MM2.map( (crossSection) => - ((voltageDropCoefficient * input.lengthM * ib * input.cosPhi) / (kappa * crossSection) / input.voltage) * 100 + ((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 + (value) => value <= input.maxVoltageDropPercent ); - let indexRecommended = - indexByCapacity >= 0 && indexByVoltageDrop >= 0 ? Math.max(indexByCapacity, indexByVoltageDrop) : -1; + let indexRecommended = -1; + if (indexByCapacity >= 0 && indexByVoltageDrop >= 0) { + indexRecommended = Math.max(indexByCapacity, indexByVoltageDrop); + } + // Practical-minimum convention (see PRACTICAL_MINIMUM_CROSS_SECTION_MM2): + // only ever raises the recommendation, never lowers what the thermal/ + // voltage-drop calculation already required. 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) { + 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) { 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]; + const rows: CrossSectionRow[] = CROSS_SECTIONS_MM2.map((crossSection, i) => { + const rated = ratedCurrents[i]; + const corrected = correctedCurrents[i]; + const currentSufficient = corrected == null ? null : corrected >= designCurrentA; + const voltageDropSufficient = voltageDrops[i] <= input.maxVoltageDropPercent; + const maxLengthForVoltageDropM = + rated == null || voltageDropCurrentBasis <= 0 + ? null + : (input.maxVoltageDropPercent * kappa * crossSection * input.voltage) / + (100 * voltageDropCoefficient * voltageDropCurrentBasis); 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, + currentSufficient, + voltageDropPercent: rated == null ? null : voltageDrops[i], + voltageDropSufficient: rated == null ? null : voltageDropSufficient, + maxLengthForVoltageDropM, + recommended: i === 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; + if (input.existingProtectionRatedCurrentA != null && indexRecommended >= 0) { + const recommendedRow = rows[indexRecommended]; protectionCoordination = { - ratedCurrentA: inA, - kind: input.existingProtection.kind, - conventionalTrippingFactor: factor, - coordinated: iz != null && inA <= iz && factor * inA <= 1.45 * iz, + ratedCurrentA: input.existingProtectionRatedCurrentA, + coordinated: + recommendedRow.correctedCurrentA != null && + input.existingProtectionRatedCurrentA <= recommendedRow.correctedCurrentA, }; } 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, + dataVerified: true, + operatingCurrentA: ib, + designCurrentA, + 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, @@ -580,126 +454,94 @@ export function calculateCableSizing(input: CableSizingInput): CableSizingResult }; } -// -- 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[] { +export function buildCableSizingAlerts( + input: CableSizingInput, + result: CableSizingResult +): CableSizingAlert[] { const alerts: CableSizingAlert[] = []; - const group = LAYING_METHOD_GROUP[input.layingMethod]; - if (!result.supported) { - const groupingMaximum = maxGroupingCircuits(input.layingMethod); + if (!result.dataVerified) { 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.` - : result.unsupportedReason === "harmonics" - ? "Bei mehr als 33 % dritter Harmonischer muss nach dem Neutralleiterstrom bemessen werden. Ohne diesen Wert wird keine Querschnittsempfehlung ausgegeben." - : input.layingMethod === "E" - ? "Für Verlegeart E benötigt die Norm bei Häufung Angaben zu Trägerart, Abstand und Anzahl der Kabelpritschen. Ohne diese Angaben ist nur ein einzelner Stromkreis berechenbar." - : `Häufung mit ${input.groupingCircuits} Stromkreisen liegt für Verlegeart ${input.layingMethod} außerhalb der verwendeten Tabelle (max. ${groupingMaximum}) – keine Berechnung möglich.`, + text: `Für Verlegeart ${input.layingMethod} mit Isolierstoff ${input.insulation.toUpperCase()} liegen keine geprüften Strombelastbarkeits-Tabellenwerte vor - keine Dimensionierung 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; + const recommended = result.recommendedCrossSectionMm2; + if (byCapacity == null) { - const dueToProtection = - input.existingProtection != null && result.designCurrentA > result.operatingCurrentA; + const dueToBreaker = + input.existingProtectionRatedCurrentA != null && + input.existingProtectionRatedCurrentA > 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².`, + text: dueToBreaker + ? `Vorhandene Sicherung (${input.existingProtectionRatedCurrentA} A) übersteigt die Belastbarkeit aller Standardquerschnitte bei Verlegeart ${input.layingMethod} - nicht der Betriebsstrom (${result.operatingCurrentA.toFixed(1)} A). Größere Verlegeart oder kleinere Sicherung prüfen.` + : `Betriebsstrom ${result.operatingCurrentA.toFixed(1)} A übersteigt die Belastbarkeit aller Standardquerschnitte bei Verlegeart ${input.layingMethod}.`, }); - } 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) { + } else if (byDrop != null && 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.`, + text: `Spannungsfall ist maßgeblich, nicht die Belastbarkeit: ${byCapacity} mm² würde thermisch reichen, ${byDrop} mm² ist wegen ΔU ≤ ${input.maxVoltageDropPercent}% nötig.`, }); } if (result.harmonicReductionApplied) { alerts.push({ kind: "info", - text: "Reduktionsfaktor 0,86 wegen 15–33 % 3. Harmonischer im Neutralleiter angewendet.", + text: "Reduktionsfaktor 0,86 wegen Oberschwingungsanteil 15-33 % im Neutralleiter angewendet (IEC 60364-5-52).", }); } - if (input.lengthM === 0) { + if (input.phase === 3 && input.harmonicNeutralLoad === "over33Percent") { alerts.push({ - kind: "info", - text: "Leitungslänge 0 m: Für diese Berechnung wird kein Spannungsfall angesetzt.", - }); - } - if (group === "ground") { - alerts.push({ - kind: "info", - text: "Erdverlegung: Bodenwärmewiderstand 2,5 K·m/W angenommen (Tabellenreferenz).", + kind: "warn", + text: "3. Harmonische > 33 %: Neutralleiter muss wie ein Außenleiter dimensioniert werden - hier nicht automatisch berücksichtigt.", }); } if (result.practicalMinimumApplied) { alerts.push({ kind: "info", - text: `Auf ${crossSectionFormat(result.recommendedCrossSectionMm2!)} angehoben (Praxis-Mindestquerschnitt für 1-phasige Stromkreise, keine Rechenanforderung).`, + text: `Auf ${result.recommendedCrossSectionMm2} mm² angehoben (Praxis-Mindestquerschnitt für 1-phasige Stromkreise, keine reine Berechnungsanforderung).`, + }); + } + if (result.combinedDerationFactor < 1) { + alerts.push({ + kind: "info", + text: `Korrekturfaktor angewendet: ${result.combinedDerationFactor.toFixed(2)} (Temperatur × Häufung${result.harmonicReductionApplied ? " × Oberschwingungen" : ""}).`, }); } if (result.protectionCoordination) { - const coordination = result.protectionCoordination; - const kindLabel = coordination.kind === "breaker" ? "Leitungsschutzschalter" : "Sicherung gG"; alerts.push( - coordination.coordinated + result.protectionCoordination.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.`, + text: `Vorhandene Sicherung (${result.protectionCoordination.ratedCurrentA} A) ist bei der Dimensionierung berücksichtigt (In ≤ Iz, vereinfachte Prüfung, ersetzt keine vollständige Überlast-/Kurzschlussprüfung).`, } : { kind: "warn", - text: `Schutzorgan ${kindLabel} ${coordination.ratedCurrentA} A ist mit dem empfohlenen Querschnitt nicht koordiniert (In ≤ Iz, I₂ ≤ 1,45 · Iz).`, + text: `Vorhandene Sicherung (${result.protectionCoordination.ratedCurrentA} A) übersteigt die Belastbarkeit des empfohlenen Querschnitts - Koordination prüfen.`, } ); } + if (alerts.length === 0 && recommended != null) { + alerts.push({ + kind: "ok", + text: `${recommended} mm² (${input.conductorMaterial === "aluminum" ? "Alu" : "Cu"}) deckt bei ${input.lengthM} m Länge sowohl Belastbarkeit (${result.designCurrentA.toFixed(1)} A${input.existingProtectionRatedCurrentA != null ? ", inkl. vorhandener Sicherung" : ""}) als auch Spannungsfall (≤ ${input.maxVoltageDropPercent}%) ab.`, + }); + } 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.`, - }); - } + if (recommendedRow?.maxLengthForVoltageDropM != null) { + alerts.push({ + kind: "info", + text: `Maximale Länge bei ${recommendedRow.crossSectionMm2} mm² und ΔU ≤ ${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 index 2a2cc02..5648d8d 100644 --- a/src/cable-sizing/domain/cable-sizing-contracts.ts +++ b/src/cable-sizing/domain/cable-sizing-contracts.ts @@ -1,12 +1,11 @@ -// Request validation for the cable-sizing HTTP API. Pure - depends only on -// zod and the sibling calculation module, never on db/server. +// Request/response 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"; @@ -14,34 +13,37 @@ 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), + powerKw: z.number().min(0).optional(), + currentA: z.number().min(0).optional(), + cosPhi: z.number().min(0.6).max(1), + voltage: z.number().positive(), + lengthM: z.number().min(0), 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), + ambientTemperatureC: z.number(), + groupingCircuits: z.number().int().min(1), + maxVoltageDropPercent: z.number().min(1).max(5), harmonicNeutralLoad: z.enum(HARMONIC_NEUTRAL_LOAD_OPTIONS), - existingProtection: z - .object({ - ratedCurrentA: z.number().finite().positive(), - kind: z.enum(PROTECTION_KINDS), - }) - .strict() - .optional(), + existingProtectionRatedCurrentA: z.number().positive().optional(), circuitCategory: z.enum(["lighting", "single_phase", "three_phase"]).optional(), + // Optional context, persisted with the audit-log entry only - never + // used for the calculation itself. + context: z + .object({ + projectId: z.string().min(1).optional(), + circuitId: z.string().min(1).optional(), + equipmentIdentifier: z.string().min(1).optional(), + }) + .optional(), }) - .strict() - .refine((value) => (value.mode === "power" ? value.powerKw != null : value.currentA != null), { + .refine((v) => (v.mode === "power" ? v.powerKw != null : v.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; +// Structural check that the request schema stays a superset of the domain +// input shape (minus context, which is API-only metadata). +type _AssertAssignable = T; +type _Check = _AssertAssignable>; diff --git a/src/db/migrations/0007_watery_kingpin.sql b/src/db/migrations/0007_watery_kingpin.sql new file mode 100644 index 0000000..a4f22bf --- /dev/null +++ b/src/db/migrations/0007_watery_kingpin.sql @@ -0,0 +1,14 @@ +CREATE TABLE `cable_sizing_calculations` ( + `id` text PRIMARY KEY NOT NULL, + `project_id` text, + `circuit_id` text, + `equipment_identifier` text, + `input` text NOT NULL, + `result` text NOT NULL, + `applied_to_circuit` integer DEFAULT 0 NOT NULL, + `created_at` integer DEFAULT (unixepoch()) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE set null, + FOREIGN KEY (`circuit_id`) REFERENCES `circuits`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE INDEX `cable_sizing_calculations_circuit_id_idx` ON `cable_sizing_calculations` (`circuit_id`); \ No newline at end of file diff --git a/src/db/migrations/0007_board_info_and_document_logo.sql b/src/db/migrations/0008_colossal_terrax.sql similarity index 100% rename from src/db/migrations/0007_board_info_and_document_logo.sql rename to src/db/migrations/0008_colossal_terrax.sql diff --git a/src/db/migrations/0008_project_cover_and_office_profile.sql b/src/db/migrations/0009_amazing_cable.sql similarity index 100% rename from src/db/migrations/0008_project_cover_and_office_profile.sql rename to src/db/migrations/0009_amazing_cable.sql diff --git a/src/db/migrations/0009_buildings.sql b/src/db/migrations/0009_buildings.sql deleted file mode 100644 index 6f65174..0000000 --- a/src/db/migrations/0009_buildings.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `buildings` ( - `id` text PRIMARY KEY NOT NULL, - `project_id` text NOT NULL, - `name` text 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 -ALTER TABLE `floors` ADD `building_id` text REFERENCES buildings(id) ON DELETE set null; \ No newline at end of file diff --git a/src/db/migrations/0010_estimate_balances.sql b/src/db/migrations/0010_estimate_balances.sql deleted file mode 100644 index bfa9dd3..0000000 --- a/src/db/migrations/0010_estimate_balances.sql +++ /dev/null @@ -1,42 +0,0 @@ -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, - `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/0011_glossy_norman_osborn.sql b/src/db/migrations/0011_glossy_norman_osborn.sql deleted file mode 100644 index c91b51b..0000000 --- a/src/db/migrations/0011_glossy_norman_osborn.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `rooms` ADD `area_m2` real; \ No newline at end of file diff --git a/src/db/migrations/0012_good_gateway.sql b/src/db/migrations/0012_good_gateway.sql deleted file mode 100644 index 57ad9dc..0000000 --- a/src/db/migrations/0012_good_gateway.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE `distribution_boards` ADD `feeding_distribution_board_id` text REFERENCES distribution_boards(id);--> statement-breakpoint -ALTER TABLE `distribution_boards` ADD `feeding_circuit_id` text REFERENCES circuits(id);--> statement-breakpoint -CREATE INDEX `distribution_boards_feeding_board_idx` ON `distribution_boards` (`feeding_distribution_board_id`);--> statement-breakpoint -CREATE INDEX `distribution_boards_feeding_circuit_idx` ON `distribution_boards` (`feeding_circuit_id`); \ No newline at end of file diff --git a/src/db/migrations/0013_users.sql b/src/db/migrations/0013_users.sql deleted file mode 100644 index 6c07010..0000000 --- a/src/db/migrations/0013_users.sql +++ /dev/null @@ -1,13 +0,0 @@ -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/0014_linear_xlsx_external_model.sql b/src/db/migrations/0014_linear_xlsx_external_model.sql deleted file mode 100644 index cb8546b..0000000 --- a/src/db/migrations/0014_linear_xlsx_external_model.sql +++ /dev/null @@ -1,97 +0,0 @@ -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/0015_wide_night_thrasher.sql b/src/db/migrations/0015_wide_night_thrasher.sql deleted file mode 100644 index fcd376b..0000000 --- a/src/db/migrations/0015_wide_night_thrasher.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE `external_export_batches` ( - `id` text PRIMARY KEY NOT NULL, - `project_id` text NOT NULL, - `project_revision` integer NOT NULL, - `import_batch_id` text NOT NULL, - `exported_at_iso` text NOT NULL, - `file_name` text NOT NULL, - `sha256` text NOT NULL, - `configuration_snapshot` text NOT NULL, - `configuration_sha256` text NOT NULL, - `scope` text NOT NULL, - `object_count` integer NOT NULL, - FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade -); ---> statement-breakpoint -CREATE INDEX `external_export_batches_project_exported_idx` ON `external_export_batches` (`project_id`,`exported_at_iso`); \ No newline at end of file diff --git a/src/db/migrations/meta/0007_snapshot.json b/src/db/migrations/meta/0007_snapshot.json index d0c04de..8a67832 100644 --- a/src/db/migrations/meta/0007_snapshot.json +++ b/src/db/migrations/meta/0007_snapshot.json @@ -1,9 +1,112 @@ { "version": "6", "dialect": "sqlite", - "id": "4db6e93a-3070-459a-94ef-587fd4929411", + "id": "98546058-8ad8-4aa1-99ad-f4e915bea89c", "prevId": "b25e1a40-c400-4848-bc24-a04bda7a8209", "tables": { + "cable_sizing_calculations": { + "name": "cable_sizing_calculations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input": { + "name": "input", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_to_circuit": { + "name": "applied_to_circuit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "cable_sizing_calculations_circuit_id_idx": { + "name": "cable_sizing_calculations_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "cable_sizing_calculations_project_id_projects_id_fk": { + "name": "cable_sizing_calculations_project_id_projects_id_fk", + "tableFrom": "cable_sizing_calculations", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "cable_sizing_calculations_circuit_id_circuits_id_fk": { + "name": "cable_sizing_calculations_circuit_id_circuits_id_fk", + "tableFrom": "cable_sizing_calculations", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, "circuit_device_rows": { "name": "circuit_device_rows", "columns": { @@ -929,34 +1032,6 @@ "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": {}, @@ -992,52 +1067,6 @@ "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": {} - }, "external_csv_configurations": { "name": "external_csv_configurations", "columns": { diff --git a/src/db/migrations/meta/0008_snapshot.json b/src/db/migrations/meta/0008_snapshot.json index 8d3cc3a..b5ef997 100644 --- a/src/db/migrations/meta/0008_snapshot.json +++ b/src/db/migrations/meta/0008_snapshot.json @@ -1,9 +1,112 @@ { "version": "6", "dialect": "sqlite", - "id": "fb609719-ea17-4833-a27b-f75da0d3e860", - "prevId": "4db6e93a-3070-459a-94ef-587fd4929411", + "id": "e2b212f8-6d6c-4096-a983-2195cdf13d6e", + "prevId": "98546058-8ad8-4aa1-99ad-f4e915bea89c", "tables": { + "cable_sizing_calculations": { + "name": "cable_sizing_calculations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input": { + "name": "input", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_to_circuit": { + "name": "applied_to_circuit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "cable_sizing_calculations_circuit_id_idx": { + "name": "cable_sizing_calculations_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "cable_sizing_calculations_project_id_projects_id_fk": { + "name": "cable_sizing_calculations_project_id_projects_id_fk", + "tableFrom": "cable_sizing_calculations", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "cable_sizing_calculations_circuit_id_circuits_id_fk": { + "name": "cable_sizing_calculations_circuit_id_circuits_id_fk", + "tableFrom": "cable_sizing_calculations", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, "circuit_device_rows": { "name": "circuit_device_rows", "columns": { @@ -1038,38 +1141,6 @@ "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": {} - }, "external_csv_configurations": { "name": "external_csv_configurations", "columns": { @@ -2424,34 +2495,6 @@ "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", diff --git a/src/db/migrations/meta/0009_snapshot.json b/src/db/migrations/meta/0009_snapshot.json index 1b7d566..c098db1 100644 --- a/src/db/migrations/meta/0009_snapshot.json +++ b/src/db/migrations/meta/0009_snapshot.json @@ -1,11 +1,11 @@ { "version": "6", "dialect": "sqlite", - "id": "2cd9adef-2f08-4635-b3d9-ecf71f624c7f", - "prevId": "fb609719-ea17-4833-a27b-f75da0d3e860", + "id": "7e984920-56d7-4bce-8762-3616bb32d10a", + "prevId": "e2b212f8-6d6c-4096-a983-2195cdf13d6e", "tables": { - "buildings": { - "name": "buildings", + "cable_sizing_calculations": { + "name": "cable_sizing_calculations", "columns": { "id": { "name": "id", @@ -18,30 +18,67 @@ "name": "project_id", "type": "text", "primaryKey": false, - "notNull": true, + "notNull": false, "autoincrement": false }, - "name": { - "name": "name", + "circuit_id": { + "name": "circuit_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "equipment_identifier": { + "name": "equipment_identifier", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input": { + "name": "input", "type": "text", "primaryKey": false, "notNull": true, "autoincrement": false }, - "sort_order": { - "name": "sort_order", + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "applied_to_circuit": { + "name": "applied_to_circuit", "type": "integer", "primaryKey": false, "notNull": true, "autoincrement": false, "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "cable_sizing_calculations_circuit_id_idx": { + "name": "cable_sizing_calculations_circuit_id_idx", + "columns": [ + "circuit_id" + ], + "isUnique": false } }, - "indexes": {}, "foreignKeys": { - "buildings_project_id_projects_id_fk": { - "name": "buildings_project_id_projects_id_fk", - "tableFrom": "buildings", + "cable_sizing_calculations_project_id_projects_id_fk": { + "name": "cable_sizing_calculations_project_id_projects_id_fk", + "tableFrom": "cable_sizing_calculations", "tableTo": "projects", "columnsFrom": [ "project_id" @@ -49,7 +86,20 @@ "columnsTo": [ "id" ], - "onDelete": "cascade", + "onDelete": "set null", + "onUpdate": "no action" + }, + "cable_sizing_calculations_circuit_id_circuits_id_fk": { + "name": "cable_sizing_calculations_circuit_id_circuits_id_fk", + "tableFrom": "cable_sizing_calculations", + "tableTo": "circuits", + "columnsFrom": [ + "circuit_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", "onUpdate": "no action" } }, @@ -1802,13 +1852,6 @@ "notNull": true, "autoincrement": false, "default": 0 - }, - "building_id": { - "name": "building_id", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false } }, "indexes": {}, @@ -1825,19 +1868,6 @@ ], "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": {}, diff --git a/src/db/migrations/meta/0010_snapshot.json b/src/db/migrations/meta/0010_snapshot.json deleted file mode 100644 index d58518a..0000000 --- a/src/db/migrations/meta/0010_snapshot.json +++ /dev/null @@ -1,2924 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "5376ae9f-67c7-4603-b3d2-8527136436f9", - "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 - }, - "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/0011_snapshot.json b/src/db/migrations/meta/0011_snapshot.json deleted file mode 100644 index 2974cf1..0000000 --- a/src/db/migrations/meta/0011_snapshot.json +++ /dev/null @@ -1,2931 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "63f27b3a-7378-462d-8119-b67d67903dbb", - "prevId": "5376ae9f-67c7-4603-b3d2-8527136436f9", - "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": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -} \ No newline at end of file diff --git a/src/db/migrations/meta/0012_snapshot.json b/src/db/migrations/meta/0012_snapshot.json deleted file mode 100644 index 832cf1a..0000000 --- a/src/db/migrations/meta/0012_snapshot.json +++ /dev/null @@ -1,2986 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "8029e6ab-56de-4345-8d38-0ca7462640de", - "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 - }, - "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_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": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -} \ No newline at end of file diff --git a/src/db/migrations/meta/0013_snapshot.json b/src/db/migrations/meta/0013_snapshot.json deleted file mode 100644 index bd091fb..0000000 --- a/src/db/migrations/meta/0013_snapshot.json +++ /dev/null @@ -1,3072 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "a967fdfb-171b-4f1d-aa0c-f7124e28fba3", - "prevId": "8029e6ab-56de-4345-8d38-0ca7462640de", - "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_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/0014_snapshot.json b/src/db/migrations/meta/0014_snapshot.json deleted file mode 100644 index dc4c096..0000000 --- a/src/db/migrations/meta/0014_snapshot.json +++ /dev/null @@ -1,3100 +0,0 @@ -{ - "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/0015_snapshot.json b/src/db/migrations/meta/0015_snapshot.json deleted file mode 100644 index 9c00cc3..0000000 --- a/src/db/migrations/meta/0015_snapshot.json +++ /dev/null @@ -1,3210 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "eab4abfa-dc46-4330-9ddd-b4676343d610", - "prevId": "b443af16-e0aa-459a-9443-62a7f8c6b6dd", - "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_export_batches": { - "name": "external_export_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 - }, - "project_revision": { - "name": "project_revision", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "import_batch_id": { - "name": "import_batch_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "exported_at_iso": { - "name": "exported_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 - }, - "configuration_snapshot": { - "name": "configuration_snapshot", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "configuration_sha256": { - "name": "configuration_sha256", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "object_count": { - "name": "object_count", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "external_export_batches_project_exported_idx": { - "name": "external_export_batches_project_exported_idx", - "columns": [ - "project_id", - "exported_at_iso" - ], - "isUnique": false - } - }, - "foreignKeys": { - "external_export_batches_project_id_projects_id_fk": { - "name": "external_export_batches_project_id_projects_id_fk", - "tableFrom": "external_export_batches", - "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 - }, - "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 0ab138e..7969e04 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -54,64 +54,22 @@ { "idx": 7, "version": "6", - "when": 1790411540872, - "tag": "0007_board_info_and_document_logo", + "when": 1786114831610, + "tag": "0007_watery_kingpin", "breakpoints": true }, { "idx": 8, "version": "6", - "when": 1790411560953, - "tag": "0008_project_cover_and_office_profile", + "when": 1790356758671, + "tag": "0008_colossal_terrax", "breakpoints": true }, { "idx": 9, "version": "6", - "when": 1790419185882, - "tag": "0009_buildings", - "breakpoints": true - }, - { - "idx": 10, - "version": "6", - "when": 1790438092269, - "tag": "0010_estimate_balances", - "breakpoints": true - }, - { - "idx": 11, - "version": "6", - "when": 1790531351492, - "tag": "0011_glossy_norman_osborn", - "breakpoints": true - }, - { - "idx": 12, - "version": "6", - "when": 1790540142918, - "tag": "0012_good_gateway", - "breakpoints": true - }, - { - "idx": 13, - "version": "6", - "when": 1790624623732, - "tag": "0013_users", - "breakpoints": true - }, - { - "idx": 14, - "version": "6", - "when": 1790748107566, - "tag": "0014_linear_xlsx_external_model", - "breakpoints": true - }, - { - "idx": 15, - "version": "6", - "when": 1790773066696, - "tag": "0015_wide_night_thrasher", + "when": 1790360862160, + "tag": "0009_amazing_cable", "breakpoints": true } ] diff --git a/src/db/repositories/batched-insert.persistence.ts b/src/db/repositories/batched-insert.persistence.ts deleted file mode 100644 index 1dea2e1..0000000 --- a/src/db/repositories/batched-insert.persistence.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { AppDatabase } from "../database-context.js"; - -const defaultInsertBatchSize = 200; - -export function insertManyInBatches[0]>( - database: AppDatabase, - table: TTable, - values: readonly unknown[], - batchSize = defaultInsertBatchSize -) { - if (!Number.isSafeInteger(batchSize) || batchSize < 1) throw new Error("Insert batch size must be a positive integer."); - for (let index = 0; index < values.length; index += batchSize) { - database.insert(table).values(values.slice(index, index + batchSize) as never).run(); - } -} diff --git a/src/db/repositories/building.repository.ts b/src/db/repositories/building.repository.ts deleted file mode 100644 index 011739f..0000000 --- a/src/db/repositories/building.repository.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { and, asc, eq } from "drizzle-orm"; -import type { AppDatabase } from "../database-context.js"; -import { buildings } from "../schema/buildings.js"; - -export class BuildingRepository { - constructor(private readonly database: AppDatabase) {} - - async listByProject(projectId: string) { - return this.database - .select() - .from(buildings) - .where(eq(buildings.projectId, projectId)) - .orderBy(asc(buildings.sortOrder), asc(buildings.name)); - } - - async findById(projectId: string, buildingId: string) { - return ( - this.database - .select() - .from(buildings) - .where( - and(eq(buildings.projectId, projectId), eq(buildings.id, buildingId)) - ) - .get() ?? null - ); - } -} diff --git a/src/db/repositories/cable-sizing-calculation.repository.ts b/src/db/repositories/cable-sizing-calculation.repository.ts new file mode 100644 index 0000000..803965b --- /dev/null +++ b/src/db/repositories/cable-sizing-calculation.repository.ts @@ -0,0 +1,37 @@ +import { desc, eq } from "drizzle-orm"; +import type { AppDatabase } from "../database-context.js"; +import { + cableSizingCalculations, + type CableSizingCalculation, + type NewCableSizingCalculation, +} from "../schema/cable-sizing-calculations.js"; + +// Plain repository, no revision/command semantics - mirrors +// application-repositories.ts's flat repository pattern, not the +// project-command-transaction boundary. A calculation is an audit record, +// not a project mutation. +export class CableSizingCalculationRepository { + constructor(private readonly db: AppDatabase) {} + + create(input: NewCableSizingCalculation): CableSizingCalculation { + return this.db.insert(cableSizingCalculations).values(input).returning().get(); + } + + listByCircuit(circuitId: string): CableSizingCalculation[] { + return this.db + .select() + .from(cableSizingCalculations) + .where(eq(cableSizingCalculations.circuitId, circuitId)) + .orderBy(desc(cableSizingCalculations.createdAt)) + .all(); + } + + markApplied(id: string): CableSizingCalculation | undefined { + return this.db + .update(cableSizingCalculations) + .set({ appliedToCircuit: 1 }) + .where(eq(cableSizingCalculations.id, id)) + .returning() + .get(); + } +} diff --git a/src/db/repositories/circuit-device-row-move-project-command.repository.ts b/src/db/repositories/circuit-device-row-move-project-command.repository.ts index e1e3f5a..2c5bfc9 100644 --- a/src/db/repositories/circuit-device-row-move-project-command.repository.ts +++ b/src/db/repositories/circuit-device-row-move-project-command.repository.ts @@ -23,7 +23,6 @@ import { circuits } from "../schema/circuits.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; import { updateDerivedCircuitVoltage } from "./project-voltage.persistence.js"; import { resolveCircuitVoltage } from "./project-voltage.persistence.js"; -import { assertCircuitsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; interface PersistedMoveRow { id: string; @@ -172,9 +171,6 @@ export class CircuitDeviceRowMoveProjectCommandRepository projectId, destinationCircuitIds ); - assertCircuitsAreNotReferencedAsFeeders(database, projectId, [ - targetCircuit.id, - ]); const deleted = database .delete(circuits) .where( 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 f69dc78..6919d20 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,15 +23,8 @@ import { toCircuitDeviceRowInsertValues, toCircuitDeviceRowSnapshot, } from "./circuit-device-row-structure.persistence.js"; -import { executeProjectCommandTransactionWithAppliedForward, type AppliedProjectCommand } from "./project-command-transaction.persistence.js"; +import { executeProjectCommandTransaction } 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 @@ -39,11 +32,7 @@ export class CircuitDeviceRowStructureProjectCommandRepository constructor(private readonly database: AppDatabase) {} execute(input: ExecuteCircuitDeviceRowStructureCommandInput) { - return executeProjectCommandTransactionWithAppliedForward< - CircuitDeviceRowStructureProjectCommand, - CircuitDeviceRowStructureProjectCommand, - CircuitDeviceRowStructureProjectCommand - >( + return executeProjectCommandTransaction( this.database, input, (tx) => @@ -61,15 +50,14 @@ export class CircuitDeviceRowStructureProjectCommandRepository projectId: string, source: ExecuteCircuitDeviceRowStructureCommandInput["source"], command: CircuitDeviceRowStructureProjectCommand - ): AppliedProjectCommand { + ): CircuitDeviceRowStructureProjectCommand { if (command.type === circuitDeviceRowInsertCommandType) { assertCircuitDeviceRowInsertProjectCommand(command); return this.insert( database, projectId, source, - command.payload.row, - command.payload.externalObjects ?? [] + command.payload.row ); } if (command.type === circuitDeviceRowDeleteCommandType) { @@ -78,8 +66,7 @@ export class CircuitDeviceRowStructureProjectCommandRepository database, projectId, command.payload.rowId, - command.payload.expectedCircuitId, - command.payload.externalObjects + command.payload.expectedCircuitId ); } throw new Error("Unsupported circuit device-row structure command."); @@ -89,8 +76,7 @@ export class CircuitDeviceRowStructureProjectCommandRepository database: AppDatabase, projectId: string, source: ExecuteCircuitDeviceRowStructureCommandInput["source"], - row: CircuitDeviceRowSnapshot, - externalObjects: ExternalObjectLinkTransition[] + row: CircuitDeviceRowSnapshot ) { if (source === "user" && !isElectricalPhaseType(row.phaseType)) { throw new Error("Device-row phase type is invalid."); @@ -121,23 +107,17 @@ export class CircuitDeviceRowStructureProjectCommandRepository } updateDerivedCircuitVoltage(database, projectId, 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)), - }; + return createCircuitDeviceRowDeleteProjectCommand( + row.id, + row.circuitId + ); } private delete( database: AppDatabase, projectId: string, rowId: string, - expectedCircuitId: string, - suppliedExternalObjects?: ExternalObjectLinkTransition[] + expectedCircuitId: string ) { const row = database .select() @@ -150,10 +130,6 @@ 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) @@ -188,10 +164,9 @@ export class CircuitDeviceRowStructureProjectCommandRepository expectedCircuitId ); - return { - forward: createCircuitDeviceRowDeleteProjectCommand(rowId, expectedCircuitId, externalObjects), - inverse: createCircuitDeviceRowInsertProjectCommand(toCircuitDeviceRowSnapshot(row), invertExternalObjectLinkTransitions(externalObjects)), - }; + return createCircuitDeviceRowInsertProjectCommand( + toCircuitDeviceRowSnapshot(row) + ); } 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 b4baeb6..448cf99 100644 --- a/src/db/repositories/circuit-group-subtree-project-command.repository.ts +++ b/src/db/repositories/circuit-group-subtree-project-command.repository.ts @@ -25,14 +25,7 @@ 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 { 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"; +import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; export class CircuitGroupSubtreeProjectCommandRepository implements CircuitGroupSubtreeProjectCommandStore @@ -49,11 +42,7 @@ export class CircuitGroupSubtreeProjectCommandRepository } else { assertCircuitGroupRestoreSubtreeProjectCommand(input.command); } - return executeProjectCommandTransactionWithAppliedForward< - CircuitGroupSubtreeProjectCommand, - CircuitGroupSubtreeProjectCommand, - CircuitGroupSubtreeProjectCommand - >( + return executeProjectCommandTransaction( this.database, input, (tx) => this.applyCommand(tx, input.projectId, input.command) @@ -64,7 +53,7 @@ export class CircuitGroupSubtreeProjectCommandRepository database: AppDatabase, projectId: string, command: CircuitGroupSubtreeProjectCommand - ): AppliedProjectCommand { + ) { if (command.type === circuitGroupDeleteSubtreeCommandType) { const current = this.captureFrom( database, @@ -76,19 +65,6 @@ export class CircuitGroupSubtreeProjectCommandRepository "Circuit-group subtree changed before deletion." ); } - assertCircuitsAreNotReferencedAsFeeders( - database, - 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)) @@ -96,20 +72,15 @@ export class CircuitGroupSubtreeProjectCommandRepository if (deleted.changes !== 1) { throw new Error("Circuit-group subtree could not be deleted."); } - return { - forward: createCircuitGroupDeleteSubtreeProjectCommand(command.payload.snapshot, externalObjects), - inverse: createCircuitGroupRestoreSubtreeProjectCommand(command.payload.snapshot, invertExternalObjectLinkTransitions(externalObjects)), - }; + return createCircuitGroupRestoreSubtreeProjectCommand( + command.payload.snapshot + ); } if (command.type === circuitGroupRestoreSubtreeCommandType) { this.restore(database, projectId, 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)), - }; + return createCircuitGroupDeleteSubtreeProjectCommand( + command.payload.snapshot + ); } throw new Error("Unsupported circuit-group subtree command."); } diff --git a/src/db/repositories/circuit-section.repository.ts b/src/db/repositories/circuit-section.repository.ts index 79a3704..d7817ec 100644 --- a/src/db/repositories/circuit-section.repository.ts +++ b/src/db/repositories/circuit-section.repository.ts @@ -1,5 +1,5 @@ import crypto from "node:crypto"; -import { and, asc, eq, inArray } from "drizzle-orm"; +import { and, asc, eq } from "drizzle-orm"; import { defaultCircuitSectionDefinitions } from "../../domain/models/distribution-board-structure-project-command.model.js"; import type { AppDatabase } from "../database-context.js"; import { circuitSections } from "../schema/circuit-sections.js"; @@ -30,15 +30,6 @@ export class CircuitSectionRepository { .orderBy(asc(circuitSections.sortOrder)); } - async listByCircuitLists(circuitListIds: string[]) { - if (circuitListIds.length === 0) return []; - return this.database - .select() - .from(circuitSections) - .where(inArray(circuitSections.circuitListId, circuitListIds)) - .orderBy(asc(circuitSections.sortOrder), asc(circuitSections.id)); - } - async createDefaults(circuitListId: string) { const db = this.database; for (const entry of createDefaultCircuitSectionValues(circuitListId)) { diff --git a/src/db/repositories/circuit-structure-project-command.repository.ts b/src/db/repositories/circuit-structure-project-command.repository.ts index f4fc420..9b8941d 100644 --- a/src/db/repositories/circuit-structure-project-command.repository.ts +++ b/src/db/repositories/circuit-structure-project-command.repository.ts @@ -25,17 +25,9 @@ import { toCircuitDeviceRowInsertValues, toCircuitDeviceRowSnapshot, } from "./circuit-device-row-structure.persistence.js"; -import { executeProjectCommandTransactionWithAppliedForward, type AppliedProjectCommand } from "./project-command-transaction.persistence.js"; -import { assertCircuitsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; +import { executeProjectCommandTransaction } from "./project-command-transaction.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 @@ -43,15 +35,11 @@ export class CircuitStructureProjectCommandRepository constructor(private readonly database: AppDatabase) {} execute(input: ExecuteCircuitStructureCommandInput) { - return executeProjectCommandTransactionWithAppliedForward< - CircuitStructureProjectCommand, - CircuitStructureProjectCommand, - CircuitStructureProjectCommand - >( + return executeProjectCommandTransaction( this.database, input, (tx) => - this.applyWithForward( + this.applyCommand( tx, input.projectId, input.source, @@ -60,33 +48,19 @@ export class CircuitStructureProjectCommandRepository ); } - /** - * Applies the circuit write inside an already-owned project transaction. - * Composite project commands use this without creating a second revision. - */ - applyInTransaction( + private applyCommand( database: AppDatabase, projectId: string, 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.externalObjects ?? [] + command.payload.circuit ); } if (command.type === circuitDeleteCommandType) { @@ -95,8 +69,7 @@ export class CircuitStructureProjectCommandRepository database, projectId, command.payload.circuitId, - command.payload.expectedCircuitListId, - command.payload.externalObjects + command.payload.expectedCircuitListId ); } throw new Error("Unsupported circuit structure command."); @@ -106,8 +79,7 @@ export class CircuitStructureProjectCommandRepository database: AppDatabase, projectId: string, source: ExecuteCircuitStructureCommandInput["source"], - snapshot: CircuitSnapshot, - externalObjects: ExternalObjectLinkTransition[] + snapshot: CircuitSnapshot ) { this.assertCircuitLocation(database, projectId, snapshot); if (source === "user") { @@ -195,23 +167,17 @@ export class CircuitStructureProjectCommandRepository .run(); } - 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)), - }; + return createCircuitDeleteProjectCommand( + snapshot.id, + snapshot.circuitListId + ); } private delete( database: AppDatabase, projectId: string, circuitId: string, - expectedCircuitListId: string, - suppliedExternalObjects?: ExternalObjectLinkTransition[] + expectedCircuitListId: string ) { const circuit = database .select() @@ -249,12 +215,7 @@ export class CircuitStructureProjectCommandRepository .from(circuitProtectionDevices) .where(eq(circuitProtectionDevices.circuitId, circuit.id)) .get(); - 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 = { + const inverse = createCircuitInsertProjectCommand({ id: circuit.id, circuitListId: circuit.circuitListId, sectionId: circuit.sectionId, @@ -273,9 +234,7 @@ export class CircuitStructureProjectCommandRepository remark: circuit.remark, deviceRows: rows.map(toCircuitDeviceRowSnapshot), protectionDevice: protectionDevice ?? null, - }; - - assertCircuitsAreNotReferencedAsFeeders(database, projectId, [circuit.id]); + }); const result = database .delete(circuits) @@ -289,10 +248,7 @@ export class CircuitStructureProjectCommandRepository if (result.changes !== 1) { throw new Error("Circuit could not be deleted."); } - return { - forward: createCircuitDeleteProjectCommand(circuitId, expectedCircuitListId, externalObjects), - inverse: createCircuitInsertProjectCommand(circuitSnapshot, invertExternalObjectLinkTransitions(externalObjects)), - }; + return inverse; } private assertCircuitLocation( diff --git a/src/db/repositories/circuit.repository.ts b/src/db/repositories/circuit.repository.ts index 7d40fa1..ecbaba0 100644 --- a/src/db/repositories/circuit.repository.ts +++ b/src/db/repositories/circuit.repository.ts @@ -1,4 +1,4 @@ -import { asc, eq, inArray } from "drizzle-orm"; +import { asc, eq } from "drizzle-orm"; import type { AppDatabase } from "../database-context.js"; import { circuits } from "../schema/circuits.js"; @@ -14,15 +14,6 @@ export class CircuitRepository { .orderBy(asc(circuits.sortOrder), asc(circuits.equipmentIdentifier)); } - async listByCircuitLists(circuitListIds: string[]) { - if (circuitListIds.length === 0) return []; - return this.database - .select() - .from(circuits) - .where(inArray(circuits.circuitListId, circuitListIds)) - .orderBy(asc(circuits.sortOrder), asc(circuits.equipmentIdentifier)); - } - async listBySection(sectionId: string) { const db = this.database; return db diff --git a/src/db/repositories/distribution-board-component.repository.ts b/src/db/repositories/distribution-board-component.repository.ts index eedb4af..ab60603 100644 --- a/src/db/repositories/distribution-board-component.repository.ts +++ b/src/db/repositories/distribution-board-component.repository.ts @@ -19,18 +19,6 @@ export class DistributionBoardComponentRepository { ); } - async listByCircuitLists(circuitListIds: string[]) { - if (circuitListIds.length === 0) return []; - return this.database - .select() - .from(distributionBoardComponents) - .where(inArray(distributionBoardComponents.circuitListId, circuitListIds)) - .orderBy( - asc(distributionBoardComponents.sortOrder), - asc(distributionBoardComponents.id) - ); - } - async listProtectionByComponentIds(componentIds: string[]) { if (componentIds.length === 0) { return []; diff --git a/src/db/repositories/distribution-board-feeding-deletion-guard.persistence.ts b/src/db/repositories/distribution-board-feeding-deletion-guard.persistence.ts deleted file mode 100644 index 679f31e..0000000 --- a/src/db/repositories/distribution-board-feeding-deletion-guard.persistence.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { and, asc, eq, inArray } from "drizzle-orm"; -import type { AppDatabase } from "../database-context.js"; -import { distributionBoards } from "../schema/distribution-boards.js"; - -export function assertBoardsAreNotReferencedAsFeeders( - database: AppDatabase, - projectId: string, - distributionBoardIds: string[] -) { - if (distributionBoardIds.length === 0) return; - const dependent = database - .select({ - name: distributionBoards.name, - boardNumber: distributionBoards.boardNumber, - }) - .from(distributionBoards) - .where( - and( - eq(distributionBoards.projectId, projectId), - inArray( - distributionBoards.feedingDistributionBoardId, - [...new Set(distributionBoardIds)] - ) - ) - ) - .orderBy(asc(distributionBoards.boardNumber), asc(distributionBoards.name)) - .limit(1) - .get(); - if (dependent) throwFeedingReferenceError(dependent); -} - -export function assertCircuitsAreNotReferencedAsFeeders( - database: AppDatabase, - projectId: string, - circuitIds: string[] -) { - if (circuitIds.length === 0) return; - const dependent = database - .select({ - name: distributionBoards.name, - boardNumber: distributionBoards.boardNumber, - }) - .from(distributionBoards) - .where( - and( - eq(distributionBoards.projectId, projectId), - inArray( - distributionBoards.feedingCircuitId, - [...new Set(circuitIds)] - ) - ) - ) - .orderBy(asc(distributionBoards.boardNumber), asc(distributionBoards.name)) - .limit(1) - .get(); - if (dependent) throwFeedingReferenceError(dependent); -} - -function throwFeedingReferenceError(dependent: { - name: string; - boardNumber: string | null; -}): never { - const label = dependent.boardNumber ?? dependent.name; - throw new Error(`Speist ${label} – erst Einspeisung ändern.`); -} 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 f7003c5..db2cede 100644 --- a/src/db/repositories/distribution-board-structure-project-command.repository.ts +++ b/src/db/repositories/distribution-board-structure-project-command.repository.ts @@ -1,5 +1,4 @@ import { and, asc, eq, inArray } from "drizzle-orm"; -import { isDeepStrictEqual } from "node:util"; import { assertDistributionBoardDeleteProjectCommand, assertDistributionBoardInsertProjectCommand, @@ -18,20 +17,6 @@ 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, @@ -45,9 +30,6 @@ import { distributionBoards } from "../schema/distribution-boards.js"; 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 implements DistributionBoardStructureProjectCommandStore @@ -79,30 +61,6 @@ 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, @@ -290,9 +248,6 @@ export class DistributionBoardStructureProjectCommandRepository ); } - assertBoardsAreNotReferencedAsFeeders(database, projectId, [board.id]); - assertDistributionBoardHasNoExternalObjects(database, projectId, board.id); - const deleted = database .delete(distributionBoards) .where( @@ -370,16 +325,6 @@ export class DistributionBoardStructureProjectCommandRepository patch.supplyType ); } - this.assertFeedingReference(database, input.projectId, current.id, { - feedingDistributionBoardId: - patch.feedingDistributionBoardId === undefined - ? current.feedingDistributionBoardId - : patch.feedingDistributionBoardId, - feedingCircuitId: - patch.feedingCircuitId === undefined - ? current.feedingCircuitId - : patch.feedingCircuitId, - }); const inversePatch = Object.fromEntries( input.command.payload.changes.map((change) => [ change.field, @@ -388,8 +333,7 @@ export class DistributionBoardStructureProjectCommandRepository ) as DistributionBoardUpdatePatch; const inverse = createDistributionBoardUpdateProjectCommand( current.id, - inversePatch, - input.command.schemaVersion + inversePatch ); const updated = database .update(distributionBoards) @@ -408,135 +352,6 @@ 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, - distributionBoardId: string, - reference: { - feedingDistributionBoardId: string | null; - feedingCircuitId: string | null; - } - ) { - const { feedingDistributionBoardId, feedingCircuitId } = reference; - if (feedingDistributionBoardId === null) { - if (feedingCircuitId !== null) { - throw new Error( - "Ein speisender Stromkreis erfordert eine speisende Verteilung." - ); - } - return; - } - if (feedingDistributionBoardId === distributionBoardId) { - throw new Error("Eine Verteilung kann sich nicht selbst speisen."); - } - const projectBoards = database - .select({ - id: distributionBoards.id, - feedingDistributionBoardId: - distributionBoards.feedingDistributionBoardId, - }) - .from(distributionBoards) - .where(eq(distributionBoards.projectId, projectId)) - .all(); - const boardById = new Map(projectBoards.map((board) => [board.id, board])); - if (!boardById.has(feedingDistributionBoardId)) { - throw new Error( - "Die speisende Verteilung gehört nicht zum Projekt." - ); - } - const visited = new Set([distributionBoardId]); - let currentId: string | null = feedingDistributionBoardId; - while (currentId !== null) { - if (visited.has(currentId)) { - throw new Error("Die Einspeisungsverknüpfung würde einen Zyklus erzeugen."); - } - visited.add(currentId); - currentId = boardById.get(currentId)?.feedingDistributionBoardId ?? null; - } - if (feedingCircuitId === null) { - return; - } - const feedingCircuit = database - .select({ - projectId: circuitLists.projectId, - distributionBoardId: circuitLists.distributionBoardId, - }) - .from(circuits) - .innerJoin( - circuitLists, - eq(circuitLists.id, circuits.circuitListId) - ) - .where(eq(circuits.id, feedingCircuitId)) - .get(); - if ( - !feedingCircuit || - feedingCircuit.projectId !== projectId || - feedingCircuit.distributionBoardId !== feedingDistributionBoardId - ) { - throw new Error( - "Der speisende Stromkreis gehört nicht zur gewählten Verteilung." - ); - } - } } function assertSupplyTypeEnabled( @@ -577,20 +392,11 @@ function structureMatches( location, fedFrom, remark, - feedingDistributionBoardId, - feedingCircuitId, ...actualDistributionBoard } = actual.board; if ( simultaneityFactor !== 1 || - [ - boardNumber, - location, - fedFrom, - remark, - feedingDistributionBoardId, - feedingCircuitId, - ].some((value) => value !== null) || + [boardNumber, location, fedFrom, remark].some((value) => value !== null) || !sameRecord( expected.distributionBoard, actualDistributionBoard 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 b32fee5..6788dcc 100644 --- a/src/db/repositories/distribution-board-subtree-project-command.repository.ts +++ b/src/db/repositories/distribution-board-subtree-project-command.repository.ts @@ -32,8 +32,6 @@ import { projects } from "../schema/projects.js"; 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 @@ -84,10 +82,6 @@ export class DistributionBoardSubtreeProjectCommandRepository "Distribution-board subtree changed before deletion." ); } - assertBoardsAreNotReferencedAsFeeders(database, projectId, [ - current.distributionBoard.id, - ]); - assertDistributionBoardHasNoExternalObjects(database, projectId, current.distributionBoard.id); const deleted = database .delete(distributionBoards) .where( @@ -306,69 +300,6 @@ export class DistributionBoardSubtreeProjectCommandRepository ); } } - const feedingDistributionBoardId = - snapshot.distributionBoard.feedingDistributionBoardId; - const feedingCircuitId = snapshot.distributionBoard.feedingCircuitId; - if (feedingDistributionBoardId === null) { - if (feedingCircuitId !== null) { - throw new Error( - "Ein speisender Stromkreis erfordert eine speisende Verteilung." - ); - } - } else { - if (feedingDistributionBoardId === snapshot.distributionBoard.id) { - throw new Error("Eine Verteilung kann sich nicht selbst speisen."); - } - const projectBoards = database - .select({ - id: distributionBoards.id, - feedingDistributionBoardId: - distributionBoards.feedingDistributionBoardId, - }) - .from(distributionBoards) - .where(eq(distributionBoards.projectId, projectId)) - .all(); - const boardById = new Map(projectBoards.map((board) => [board.id, board])); - if (!boardById.has(feedingDistributionBoardId)) { - throw new Error( - "Die speisende Verteilung gehört nicht zum Projekt." - ); - } - const visited = new Set([snapshot.distributionBoard.id]); - let currentId: string | null = feedingDistributionBoardId; - while (currentId !== null) { - if (visited.has(currentId)) { - throw new Error( - "Die Einspeisungsverknüpfung würde einen Zyklus erzeugen." - ); - } - visited.add(currentId); - currentId = boardById.get(currentId)?.feedingDistributionBoardId ?? null; - } - if (feedingCircuitId !== null) { - const feedingCircuit = database - .select({ - projectId: circuitLists.projectId, - distributionBoardId: circuitLists.distributionBoardId, - }) - .from(circuits) - .innerJoin( - circuitLists, - eq(circuitLists.id, circuits.circuitListId) - ) - .where(eq(circuits.id, feedingCircuitId)) - .get(); - if ( - !feedingCircuit || - feedingCircuit.projectId !== projectId || - feedingCircuit.distributionBoardId !== feedingDistributionBoardId - ) { - throw new Error( - "Der speisende Stromkreis gehört nicht zur gewählten Verteilung." - ); - } - } - } const linkedProjectDeviceIds = uniqueStrings( snapshot.circuits.flatMap((circuit) => circuit.deviceRows.flatMap((row) => diff --git a/src/db/repositories/estimate-balance-project-command.repository.ts b/src/db/repositories/estimate-balance-project-command.repository.ts deleted file mode 100644 index b31ca78..0000000 --- a/src/db/repositories/estimate-balance-project-command.repository.ts +++ /dev/null @@ -1,132 +0,0 @@ -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 deleted file mode 100644 index 4d59aa6..0000000 --- a/src/db/repositories/estimate-balance.persistence.ts +++ /dev/null @@ -1,121 +0,0 @@ -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 deleted file mode 100644 index 4c70d27..0000000 --- a/src/db/repositories/estimate-balance.repository.ts +++ /dev/null @@ -1,60 +0,0 @@ -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/repositories/external-csv-configuration-project-command.repository.ts b/src/db/repositories/external-csv-configuration-project-command.repository.ts new file mode 100644 index 0000000..c7d7bf7 --- /dev/null +++ b/src/db/repositories/external-csv-configuration-project-command.repository.ts @@ -0,0 +1,105 @@ +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-model-configuration.repository.ts b/src/db/repositories/external-csv-configuration.repository.ts similarity index 51% rename from src/db/repositories/external-model-configuration.repository.ts rename to src/db/repositories/external-csv-configuration.repository.ts index 7cbacab..2b39a65 100644 --- a/src/db/repositories/external-model-configuration.repository.ts +++ b/src/db/repositories/external-csv-configuration.repository.ts @@ -1,11 +1,12 @@ import { eq } from "drizzle-orm"; -import type { ExternalModelConfigurationReader } from "../../domain/ports/external-model-configuration.reader.js"; +import type { ExternalCsvConfigurationReader } from "../../domain/ports/external-csv-configuration.reader.js"; import type { AppDatabase } from "../database-context.js"; -import { externalModelConfigurations } from "../schema/external-model-configurations.js"; +import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; import { projects } from "../schema/projects.js"; -export class ExternalModelConfigurationRepository - implements ExternalModelConfigurationReader { +export class ExternalCsvConfigurationRepository + implements ExternalCsvConfigurationReader +{ constructor(private readonly database: AppDatabase) {} getByProject(projectId: string) { @@ -14,11 +15,13 @@ export class ExternalModelConfigurationRepository .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(externalModelConfigurations) - .where(eq(externalModelConfigurations.projectId, projectId)) + .from(externalCsvConfigurations) + .where(eq(externalCsvConfigurations.projectId, projectId)) .get() ?? null; return { projectExists: true, configuration }; } diff --git a/src/db/repositories/external-export-batch.repository.ts b/src/db/repositories/external-export-batch.repository.ts deleted file mode 100644 index c8f7a7d..0000000 --- a/src/db/repositories/external-export-batch.repository.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { desc, eq } from "drizzle-orm"; -import type { AppDatabase } from "../database-context.js"; -import { externalExportBatches } from "../schema/external-export-batches.js"; - -export class ExternalExportBatchRepository { - constructor(private readonly database: AppDatabase) {} - - append(batch: typeof externalExportBatches.$inferInsert) { - this.database.insert(externalExportBatches).values(batch).run(); - return batch; - } - - listByProject(projectId: string) { - return this.database.select().from(externalExportBatches) - .where(eq(externalExportBatches.projectId, projectId)) - .orderBy(desc(externalExportBatches.exportedAtIso), desc(externalExportBatches.id)).all(); - } -} diff --git a/src/db/repositories/external-follow-up-import-project-command.repository.ts b/src/db/repositories/external-follow-up-import-project-command.repository.ts deleted file mode 100644 index e87e1af..0000000 --- a/src/db/repositories/external-follow-up-import-project-command.repository.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { createHash } from "node:crypto"; -import { and, eq, inArray } from "drizzle-orm"; -import { assertCircuitDeviceRowQuantity } from "../../domain/calculations/circuit-device-row-quantity.js"; -import { assertExternalFollowUpImportProjectCommand, invertExternalFollowUpImportProjectCommand } from "../../domain/models/external-follow-up-import-project-command.model.js"; -import type { ExternalFollowUpImportProjectCommandStore } from "../../domain/ports/external-follow-up-import-project-command.store.js"; -import type { CircuitDeviceRowSnapshot } from "../../domain/models/circuit-device-row-structure-project-command.model.js"; -import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; -import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; -import { externalModelStatesEqual } from "../../external-model/domain/external-model-state-comparison.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 { 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 { rooms } from "../schema/rooms.js"; -import { toCircuitDeviceRowSnapshot } from "./circuit-device-row-structure.persistence.js"; -import { ExternalModelStateRepository } from "./external-model-state.repository.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; -import { insertManyInBatches } from "./batched-insert.persistence.js"; - -export class ExternalFollowUpImportProjectCommandRepository implements ExternalFollowUpImportProjectCommandStore { - constructor(private readonly database: AppDatabase) {} - execute(input: Parameters[0]) { - assertExternalFollowUpImportProjectCommand(input.command); - return executeProjectCommandTransaction(this.database, input, (tx) => { - const currentState = new ExternalModelStateRepository(tx).getByProject(input.projectId); - const currentConfiguration = tx.select().from(externalModelConfigurations).where(eq(externalModelConfigurations.projectId, input.projectId)).get(); - if (!currentState.projectExists || !currentConfiguration || !externalModelStatesEqual(currentState.state, input.command.payload.expectedState) || !same(currentConfiguration, input.command.payload.expectedConfiguration)) throw new Error("Revit-Zustand oder Konfiguration wurde zwischenzeitlich geändert."); - const rowIds = input.command.payload.rows.map(({ expected }) => expected.id); - const currentRows = rowIds.length ? tx.select().from(circuitDeviceRows).where(inArray(circuitDeviceRows.id, rowIds)).all() : []; - if (currentRows.length !== rowIds.length) throw new Error("Eine Gerätezeile des Folgeimports wurde nicht gefunden."); - const transitionById = new Map(input.command.payload.rows.map((transition) => [transition.expected.id, transition])); - for (const row of currentRows) if (!same(toCircuitDeviceRowSnapshot(row), transitionById.get(row.id)!.expected)) throw new Error("Eine Gerätezeile wurde zwischenzeitlich geändert."); - validateTarget(tx, input.projectId, input.expectedRevision, input.source, input.command.payload.targetConfiguration.configuration, input.command.payload.expectedState, input.command.payload.targetState, input.command.payload.rows); - for (const transition of input.command.payload.rows) { - const result = tx.update(circuitDeviceRows).set({ quantity: transition.target.quantity }).where(and(eq(circuitDeviceRows.id, transition.expected.id), eq(circuitDeviceRows.quantity, transition.expected.quantity))).run(); - if (result.changes !== 1) throw new Error("Eine Gerätezeile wurde während des Folgeimports geändert."); - } - replaceConfiguration(tx, input.projectId, input.command.payload.targetConfiguration); - replaceState(tx, input.projectId, input.command.payload.targetState); - return invertExternalFollowUpImportProjectCommand(input.command); - }); - } -} - -function validateTarget(database: AppDatabase, projectId: string, expectedRevision: number, source: string, configuration: ExternalModelConfiguration, expectedState: ExternalModelStateSnapshot, target: ExternalModelStateSnapshot, rows: Array<{ expected: CircuitDeviceRowSnapshot; target: CircuitDeviceRowSnapshot }>) { - if (target.source?.projectId !== projectId) throw new Error("Der Revit-Folgeimport gehört zu einem anderen Projekt."); - const growing = target.importBatches.length > expectedState.importBatches.length; - const latest = growing ? target.importBatches.at(-1)! : expectedState.importBatches.at(-1)!; - if (source === "user" && (!growing || latest.appliedProjectRevision !== expectedRevision + 1)) throw new Error("Die Projektrevision des Folgeimports ist ungültig."); - if (growing) { - if (!same(latest.configurationSnapshot, configuration)) throw new Error("Die Konfigurationskopie des Folgeimports ist ungültig."); - const bytes = Buffer.from(latest.originalContentBase64!, "base64"); - if (bytes.toString("base64") !== latest.originalContentBase64 || createHash("sha256").update(bytes).digest("hex") !== latest.sha256) throw new Error("Die Prüfsumme des Folgeimports 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.deviceTypes.map((entry) => entry.id)); - for (const mapping of target.roomMappings) { if (mapping.roomId && !roomIds.has(mapping.roomId)) throw new Error("Eine Raumzuordnung verweist auf ein anderes Projekt."); if (mapping.defaultDistributionBoardId && !boardIds.has(mapping.defaultDistributionBoardId)) throw new Error("Ein Standardverteiler verweist auf ein anderes Projekt."); } - for (const object of target.objects) { if (!deviceTypeIds.has(object.deviceTypeId)) throw new Error("Ein Revit-Objekt verweist auf eine unbekannte Geräteart."); if (object.distributionBoardId && !boardIds.has(object.distributionBoardId)) throw new Error("Ein Revit-Objekt verweist auf einen fremden Verteiler."); if (object.linkedProjectDeviceId && !projectDeviceIds.has(object.linkedProjectDeviceId)) throw new Error("Ein Revit-Objekt verweist auf ein fremdes Projektgerät."); } - assertRows(database, projectId, target, rows); -} - -function assertRows(database: AppDatabase, projectId: string, target: ExternalModelStateSnapshot, rows: Array<{ expected: CircuitDeviceRowSnapshot; target: CircuitDeviceRowSnapshot }>) { - const linkedRowIds = [...new Set(target.objects.flatMap((object) => object.circuitDeviceRowId ? [object.circuitDeviceRowId] : []))]; - const rowsToLoad = [...new Set([...linkedRowIds, ...rows.map(({ expected }) => expected.id)])]; - if (!rowsToLoad.length) return; - const contexts = database.select({ row: circuitDeviceRows, projectId: circuitLists.projectId }).from(circuitDeviceRows).innerJoin(circuits, eq(circuits.id, circuitDeviceRows.circuitId)).innerJoin(circuitLists, eq(circuitLists.id, circuits.circuitListId)).where(inArray(circuitDeviceRows.id, rowsToLoad)).all(); - if (contexts.length !== rowsToLoad.length || contexts.some((entry) => entry.projectId !== projectId)) throw new Error("Eine Gerätezeile gehört zu einem anderen Projekt."); - const transitionById = new Map(rows.map((transition) => [transition.expected.id, transition])); - for (const context of contexts) { - const current = toCircuitDeviceRowSnapshot(context.row); - const effective = transitionById.get(current.id)?.target ?? current; - assertCircuitDeviceRowQuantity({ quantity: effective.quantity, manualQuantity: effective.manualQuantity ?? effective.quantity, externalObjects: target.objects.filter((object) => object.circuitDeviceRowId === effective.id).map((object) => ({ effectiveQuantity: object.planningValues.effectiveQuantity })) }); - } -} -function replaceConfiguration(database: AppDatabase, projectId: string, target: typeof externalModelConfigurations.$inferInsert) { database.delete(externalModelConfigurations).where(eq(externalModelConfigurations.projectId, projectId)).run(); 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(); insertManyInBatches(database, externalImportBatches, target.importBatches.map(({ originalContentBase64, ...batch }) => ({ ...batch, originalBytes: originalContentBase64 === null ? null : Buffer.from(originalContentBase64, "base64") }))); insertManyInBatches(database, externalRoomMappings, target.roomMappings); insertManyInBatches(database, externalModelObjects, target.objects); } -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/db/repositories/external-initial-import-project-command.repository.ts b/src/db/repositories/external-initial-import-project-command.repository.ts index 501cb10..1f2281e 100644 --- a/src/db/repositories/external-initial-import-project-command.repository.ts +++ b/src/db/repositories/external-initial-import-project-command.repository.ts @@ -1,89 +1,252 @@ -import { createHash } from "node:crypto"; +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 { 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 { 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 { externalModelStatesEqual } from "../../external-model/domain/external-model-state-comparison.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 { 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"; -import { insertManyInBatches } from "./batched-insert.persistence.js"; -export class ExternalInitialImportProjectCommandRepository implements ExternalInitialImportProjectCommandStore { +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 (!externalModelStatesEqual(payload.expectedState, currentStateResult.state) || !same(payload.expectedConfiguration, currentConfiguration)) { - throw new Error("Revit-Zustand oder Konfiguration wurde zwischenzeitlich geändert."); + 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."); } - 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 (!externalModelStatesEqual(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); + 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 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."); +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."); } - 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."); + 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 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; +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(); - insertManyInBatches(database, externalImportBatches, target.importBatches.map(({ originalContentBase64, ...batch }) => ({ ...batch, originalBytes: originalContentBase64 === null ? null : Buffer.from(originalContentBase64, "base64") }))); - insertManyInBatches(database, externalRoomMappings, target.roomMappings); - insertManyInBatches(database, externalModelObjects, target.objects); + 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("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); } +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 deleted file mode 100644 index 881cc8a..0000000 --- a/src/db/repositories/external-model-configuration-project-command.repository.ts +++ /dev/null @@ -1,79 +0,0 @@ -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-model-state.repository.ts b/src/db/repositories/external-model-state.repository.ts index c2adb7c..36079c9 100644 --- a/src/db/repositories/external-model-state.repository.ts +++ b/src/db/repositories/external-model-state.repository.ts @@ -55,10 +55,7 @@ export class ExternalModelStateRepository implements ExternalModelStateReader { .select() .from(externalModelObjects) .where(eq(externalModelObjects.sourceId, source.id)) - .orderBy( - asc(externalModelObjects.worksharingId), - asc(externalModelObjects.id) - ) + .orderBy(asc(externalModelObjects.ifcGuid), asc(externalModelObjects.id)) .all(); return { @@ -67,10 +64,7 @@ export class ExternalModelStateRepository implements ExternalModelStateReader { source, importBatches: batches.map(({ originalBytes, ...batch }) => ({ ...batch, - originalContentBase64: - originalBytes === null - ? null - : Buffer.from(originalBytes).toString("base64"), + originalContentBase64: 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 505481d..ddc9891 100644 --- a/src/db/repositories/external-object-assignment.persistence.ts +++ b/src/db/repositories/external-object-assignment.persistence.ts @@ -11,27 +11,6 @@ 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, @@ -72,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) => - scalarText(object.acceptedSourceValues.selectionMarker).trim() + object.acceptedSourceValues.selectionMarker.trim() ) ); if (markers.size > 1) { @@ -107,13 +86,7 @@ export function applyExternalObjectLinks( ) { for (const { expected, target } of transitions) { const updated = database.update(externalModelObjects) - .set({ - circuitDeviceRowId: target.circuitDeviceRowId, - distributionBoardId: target.distributionBoardId, - linkedProjectDeviceId: target.linkedProjectDeviceId, - planningValues: target.planningValues, - overriddenFields: target.overriddenFields, - }) + .set({ circuitDeviceRowId: target.circuitDeviceRowId }) .where(and( eq(externalModelObjects.id, expected.id), expected.circuitDeviceRowId === null @@ -145,17 +118,13 @@ function matchesRowPlanningValues( row.category === planning.category && row.connectionKind === planning.connectionKind && (planning.powerPerUnitW === null || row.powerPerUnit === planning.powerPerUnitW / 1000) && - row.simultaneityFactor === (planning.simultaneityFactor ?? 1) && + row.simultaneityFactor === planning.simultaneityFactor && 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/external-object-delete-missing-project-command.repository.ts b/src/db/repositories/external-object-delete-missing-project-command.repository.ts deleted file mode 100644 index 600c19a..0000000 --- a/src/db/repositories/external-object-delete-missing-project-command.repository.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { and, eq, inArray } from "drizzle-orm"; -import { assertCircuitDeviceRowQuantity } from "../../domain/calculations/circuit-device-row-quantity.js"; -import { assertExternalObjectDeleteMissingProjectCommand, invertExternalObjectDeleteMissingProjectCommand } from "../../domain/models/external-object-delete-missing-project-command.model.js"; -import type { ExternalObjectDeleteMissingProjectCommandStore } from "../../domain/ports/external-object-delete-missing-project-command.store.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 { externalModelObjects } from "../schema/external-model-objects.js"; -import { externalModelSources } from "../schema/external-model-sources.js"; -import { externalImportBatches } from "../schema/external-import-batches.js"; -import { externalRoomMappings } from "../schema/external-room-mappings.js"; -import { distributionBoards } from "../schema/distribution-boards.js"; -import { projectDevices } from "../schema/project-devices.js"; -import { toCircuitDeviceRowSnapshot } from "./circuit-device-row-structure.persistence.js"; -import { snapshotsEqual, toExternalObjectSnapshot } from "./external-object-assignment.persistence.js"; -import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; - -export class ExternalObjectDeleteMissingProjectCommandRepository implements ExternalObjectDeleteMissingProjectCommandStore { - constructor(private readonly database: AppDatabase) {} - execute(input: Parameters[0]) { - assertExternalObjectDeleteMissingProjectCommand(input.command); - return executeProjectCommandTransaction(this.database, input, (tx) => { - const rowById = new Map(input.command.payload.rows.map((transition) => [transition.expected.id, transition])); - const rowIds = [...rowById.keys()]; - const rowContexts = rowIds.length ? tx.select({ row: circuitDeviceRows, projectId: circuitLists.projectId }).from(circuitDeviceRows).innerJoin(circuits, eq(circuits.id, circuitDeviceRows.circuitId)).innerJoin(circuitLists, eq(circuitLists.id, circuits.circuitListId)).where(inArray(circuitDeviceRows.id, rowIds)).all() : []; - if (rowContexts.length !== rowIds.length || rowContexts.some((entry) => entry.projectId !== input.projectId || !snapshotsEqual(toCircuitDeviceRowSnapshot(entry.row), rowById.get(entry.row.id)!.expected))) throw new Error("Eine Gerätezeile wurde zwischenzeitlich geändert."); - const currentObjects = tx.select().from(externalModelObjects).where(eq(externalModelObjects.projectId, input.projectId)).all().map(toExternalObjectSnapshot); - const currentById = new Map(currentObjects.map((object) => [object.id, object])); - for (const transition of input.command.payload.objects) { - const current = currentById.get((transition.expected ?? transition.target)!.id) ?? null; - if (transition.expected === null ? current !== null : current === null || !snapshotsEqual(current, transition.expected)) throw new Error("Ein fehlendes Revit-Objekt wurde zwischenzeitlich geändert."); - } - const sourceIds = ids(tx.select({ id: externalModelSources.id }).from(externalModelSources).where(eq(externalModelSources.projectId, input.projectId)).all()); - const batchIds = ids(tx.select({ id: externalImportBatches.id }).from(externalImportBatches).where(eq(externalImportBatches.projectId, input.projectId)).all()); - const mappingIds = ids(tx.select({ id: externalRoomMappings.id }).from(externalRoomMappings).where(eq(externalRoomMappings.projectId, input.projectId)).all()); - const boardIds = ids(tx.select({ id: distributionBoards.id }).from(distributionBoards).where(eq(distributionBoards.projectId, input.projectId)).all()); - const deviceIds = ids(tx.select({ id: projectDevices.id }).from(projectDevices).where(eq(projectDevices.projectId, input.projectId)).all()); - for (const { target } of input.command.payload.objects) if (target && (target.projectId !== input.projectId || !sourceIds.has(target.sourceId) || !batchIds.has(target.lastSeenImportBatchId) || !batchIds.has(target.lastAcceptedImportBatchId) || (target.externalRoomMappingId !== null && !mappingIds.has(target.externalRoomMappingId)) || (target.distributionBoardId !== null && !boardIds.has(target.distributionBoardId)) || (target.linkedProjectDeviceId !== null && !deviceIds.has(target.linkedProjectDeviceId)))) throw new Error("Ein wiederhergestelltes Revit-Objekt verweist auf ein anderes Projekt."); - const targetById = new Map(currentObjects.map((object) => [object.id, object])); - for (const transition of input.command.payload.objects) { const id = (transition.expected ?? transition.target)!.id; if (transition.target) targetById.set(id, transition.target); else targetById.delete(id); } - for (const transition of input.command.payload.rows) assertCircuitDeviceRowQuantity({ quantity: transition.target.quantity, manualQuantity: transition.target.manualQuantity ?? transition.target.quantity, externalObjects: [...targetById.values()].filter((object) => object.circuitDeviceRowId === transition.target.id).map((object) => ({ effectiveQuantity: object.planningValues.effectiveQuantity })) }); - for (const transition of input.command.payload.rows) { - const result = tx.update(circuitDeviceRows).set({ quantity: transition.target.quantity }).where(and(eq(circuitDeviceRows.id, transition.expected.id), eq(circuitDeviceRows.quantity, transition.expected.quantity))).run(); - if (result.changes !== 1) throw new Error("Eine Gerätezeile wurde während des Löschens geändert."); - } - for (const transition of input.command.payload.objects) { - const object = transition.expected ?? transition.target!; - if (transition.target === null) { - const result = tx.delete(externalModelObjects).where(and(eq(externalModelObjects.id, object.id), eq(externalModelObjects.projectId, input.projectId))).run(); - if (result.changes !== 1) throw new Error("Ein fehlendes Revit-Objekt konnte nicht gelöscht werden."); - } else tx.insert(externalModelObjects).values(transition.target).run(); - } - return invertExternalObjectDeleteMissingProjectCommand(input.command); - }); - } -} - -function ids(entries: Array<{ id: string }>) { return new Set(entries.map((entry) => entry.id)); } diff --git a/src/db/repositories/external-object-deletion-guard.persistence.ts b/src/db/repositories/external-object-deletion-guard.persistence.ts deleted file mode 100644 index 45fdac7..0000000 --- a/src/db/repositories/external-object-deletion-guard.persistence.ts +++ /dev/null @@ -1,37 +0,0 @@ -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/external-object-new-circuit-project-command.repository.ts b/src/db/repositories/external-object-new-circuit-project-command.repository.ts index 7667a28..bea64ff 100644 --- a/src/db/repositories/external-object-new-circuit-project-command.repository.ts +++ b/src/db/repositories/external-object-new-circuit-project-command.repository.ts @@ -33,7 +33,6 @@ import { snapshotsEqual, } from "./external-object-assignment.persistence.js"; import { assertEquipmentIdentifierAvailable } from "./equipment-identifier-uniqueness.persistence.js"; -import { assertCircuitsAreNotReferencedAsFeeders } from "./distribution-board-feeding-deletion-guard.persistence.js"; export class ExternalObjectNewCircuitProjectCommandRepository implements ExternalObjectNewCircuitProjectCommandStore @@ -163,9 +162,6 @@ export class ExternalObjectNewCircuitProjectCommandRepository objects, "External object changed during new-circuit assignment." ); - assertCircuitsAreNotReferencedAsFeeders(database, projectId, [ - expectedCircuit.id, - ]); const deleted = database.delete(circuits).where(and( eq(circuits.id, expectedCircuit.id), eq(circuits.circuitListId, expectedCircuit.circuitListId) diff --git a/src/db/repositories/external-object-planning-project-command.repository.ts b/src/db/repositories/external-object-planning-project-command.repository.ts deleted file mode 100644 index e6b3b1f..0000000 --- a/src/db/repositories/external-object-planning-project-command.repository.ts +++ /dev/null @@ -1,29 +0,0 @@ -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/db/repositories/project-location-structure-project-command.repository.ts b/src/db/repositories/project-location-structure-project-command.repository.ts index 40a1743..7cbadde 100644 --- a/src/db/repositories/project-location-structure-project-command.repository.ts +++ b/src/db/repositories/project-location-structure-project-command.repository.ts @@ -1,35 +1,23 @@ import { and, eq } from "drizzle-orm"; import { - assertProjectBuildingDeleteProjectCommand, - assertProjectBuildingInsertProjectCommand, - assertProjectBuildingUpdateProjectCommand, assertProjectFloorDeleteProjectCommand, assertProjectFloorInsertProjectCommand, assertProjectFloorUpdateProjectCommand, assertProjectRoomDeleteProjectCommand, assertProjectRoomInsertProjectCommand, assertProjectRoomUpdateProjectCommand, - createProjectBuildingDeleteProjectCommand, - createProjectBuildingInsertProjectCommand, - createProjectBuildingUpdateProjectCommand, createProjectFloorDeleteProjectCommand, createProjectFloorInsertProjectCommand, createProjectFloorUpdateProjectCommand, createProjectRoomDeleteProjectCommand, createProjectRoomInsertProjectCommand, createProjectRoomUpdateProjectCommand, - projectBuildingDeleteCommandType, - projectBuildingInsertCommandType, - projectBuildingUpdateCommandType, projectFloorDeleteCommandType, projectFloorInsertCommandType, projectFloorUpdateCommandType, projectRoomDeleteCommandType, projectRoomInsertCommandType, projectRoomUpdateCommandType, - upgradeProjectFloorCommand, - upgradeProjectRoomCommand, - type ProjectBuildingSnapshot, type ProjectFloorSnapshot, type ProjectLocationStructureProjectCommand, type ProjectRoomSnapshot, @@ -39,14 +27,12 @@ import type { ProjectLocationStructureProjectCommandStore, } from "../../domain/ports/project-location-structure-project-command.store.js"; import type { AppDatabase } from "../database-context.js"; -import { buildings } from "../schema/buildings.js"; import { circuitDeviceRows } from "../schema/circuit-device-rows.js"; import { floors } from "../schema/floors.js"; 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 @@ -54,14 +40,11 @@ export class ProjectLocationStructureProjectCommandRepository constructor(private readonly database: AppDatabase) {} execute(input: ExecuteProjectLocationStructureCommandInput) { - // Forward and inverse are persisted with one schema version, so a - // version 1 floor command from older history is upgraded first. - const command = toCurrentCommandVersion(input.command); return executeProjectCommandTransaction( this.database, - { ...input, command }, + input, (tx) => - this.applyCommand(tx, input.projectId, command) + this.applyCommand(tx, input.projectId, input.command) ); } @@ -71,66 +54,40 @@ export class ProjectLocationStructureProjectCommandRepository command: ProjectLocationStructureProjectCommand ): ProjectLocationStructureProjectCommand { switch (command.type) { - case projectBuildingInsertCommandType: - assertProjectBuildingInsertProjectCommand(command); - return this.insertBuilding(database, projectId, command.payload.building); - case projectBuildingDeleteCommandType: - assertProjectBuildingDeleteProjectCommand(command); - return this.deleteBuilding(database, projectId, command.payload.building); - case projectBuildingUpdateCommandType: - assertProjectBuildingUpdateProjectCommand(command); - return this.updateBuilding( - database, - projectId, - command.payload.expected, - command.payload.target - ); - case projectFloorInsertCommandType: { + case projectFloorInsertCommandType: assertProjectFloorInsertProjectCommand(command); - const current = upgradeProjectFloorCommand(command); return this.insertFloor( database, projectId, - current.payload.floor + command.payload.floor ); - } - case projectFloorDeleteCommandType: { + case projectFloorDeleteCommandType: assertProjectFloorDeleteProjectCommand(command); - const current = upgradeProjectFloorCommand(command); return this.deleteFloor( database, projectId, - current.payload.floor + command.payload.floor ); - } - case projectFloorUpdateCommandType: { + case projectFloorUpdateCommandType: assertProjectFloorUpdateProjectCommand(command); - const current = upgradeProjectFloorCommand(command); - return this.updateFloor(database, projectId, current.payload.expected, current.payload.target); - } - case projectRoomInsertCommandType: { + return this.updateFloor(database, projectId, command.payload.expected, command.payload.target); + case projectRoomInsertCommandType: assertProjectRoomInsertProjectCommand(command); - const current = upgradeProjectRoomCommand(command); return this.insertRoom( database, projectId, - current.payload.room + command.payload.room ); - } - case projectRoomDeleteCommandType: { + case projectRoomDeleteCommandType: assertProjectRoomDeleteProjectCommand(command); - const current = upgradeProjectRoomCommand(command); return this.deleteRoom( database, projectId, - current.payload.room + command.payload.room ); - } - case projectRoomUpdateCommandType: { + case projectRoomUpdateCommandType: assertProjectRoomUpdateProjectCommand(command); - const current = upgradeProjectRoomCommand(command); - return this.updateRoom(database, projectId, current.payload.expected, current.payload.target); - } + return this.updateRoom(database, projectId, command.payload.expected, command.payload.target); } } @@ -143,7 +100,6 @@ export class ProjectLocationStructureProjectCommandRepository if (floor.projectId !== projectId) { throw new Error("Project-floor snapshot does not belong to project."); } - this.assertBuildingInProject(database, projectId, floor.buildingId); const existing = database .select({ id: floors.id }) .from(floors) @@ -211,104 +167,6 @@ export class ProjectLocationStructureProjectCommandRepository return createProjectFloorInsertProjectCommand(expected); } - private insertBuilding( - database: AppDatabase, - projectId: string, - building: ProjectBuildingSnapshot - ) { - this.assertProjectExists(database, projectId); - if (building.projectId !== projectId) { - throw new Error("Project-building snapshot does not belong to project."); - } - const existing = database - .select({ id: buildings.id }) - .from(buildings) - .where(eq(buildings.id, building.id)) - .get(); - if (existing) { - throw new Error("Project-building id already exists."); - } - database.insert(buildings).values(building).run(); - return createProjectBuildingDeleteProjectCommand(building); - } - - private deleteBuilding( - database: AppDatabase, - projectId: string, - expected: ProjectBuildingSnapshot - ) { - const persisted = database - .select() - .from(buildings) - .where(and(eq(buildings.id, expected.id), eq(buildings.projectId, projectId))) - .get(); - if (!persisted || !sameRecord(expected, persisted)) { - throw new Error("Project building changed before deletion."); - } - const referencedFloor = database - .select({ id: floors.id }) - .from(floors) - .where(eq(floors.buildingId, expected.id)) - .limit(1) - .get(); - if (referencedFloor) { - throw new Error( - "Das Gebäude kann nicht gelöscht werden, solange Etagen zugeordnet sind." - ); - } - const deleted = database - .delete(buildings) - .where(and(eq(buildings.id, expected.id), eq(buildings.projectId, projectId))) - .run(); - if (deleted.changes !== 1) { - throw new Error("Project building could not be deleted."); - } - return createProjectBuildingInsertProjectCommand(expected); - } - - private updateBuilding( - database: AppDatabase, - projectId: string, - expected: ProjectBuildingSnapshot, - target: ProjectBuildingSnapshot - ) { - const persisted = database - .select() - .from(buildings) - .where(and(eq(buildings.id, expected.id), eq(buildings.projectId, projectId))) - .get(); - if (!persisted || !sameRecord(expected, persisted)) { - throw new Error("Project building changed before update."); - } - const updated = database - .update(buildings) - .set({ name: target.name }) - .where(and(eq(buildings.id, expected.id), eq(buildings.projectId, projectId))) - .run(); - if (updated.changes !== 1) { - throw new Error("Das Gebäude konnte nicht aktualisiert werden."); - } - return createProjectBuildingUpdateProjectCommand(target, expected); - } - - private assertBuildingInProject( - database: AppDatabase, - projectId: string, - buildingId: string | null - ) { - if (buildingId === null) { - return; - } - const building = database - .select({ id: buildings.id }) - .from(buildings) - .where(and(eq(buildings.id, buildingId), eq(buildings.projectId, projectId))) - .get(); - if (!building) { - throw new Error("Project floor references a foreign building."); - } - } - private insertRoom( database: AppDatabase, projectId: string, @@ -359,10 +217,9 @@ export class ProjectLocationStructureProjectCommandRepository if (!persisted || !sameRecord(expected, persisted)) { throw new Error("Project floor changed before update."); } - this.assertBuildingInProject(database, projectId, target.buildingId); const updated = database .update(floors) - .set({ name: target.name, buildingId: target.buildingId }) + .set({ name: target.name }) .where(and(eq(floors.id, expected.id), eq(floors.projectId, projectId))) .run(); if (updated.changes !== 1) { @@ -401,7 +258,6 @@ export class ProjectLocationStructureProjectCommandRepository floorId: target.floorId, roomNumber: target.roomNumber, roomName: target.roomName, - areaM2: target.areaM2, }) .where(and(eq(rooms.id, expected.id), eq(rooms.projectId, projectId))) .run(); @@ -440,7 +296,6 @@ 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( @@ -471,33 +326,6 @@ export class ProjectLocationStructureProjectCommandRepository } } -function toCurrentCommandVersion( - command: ProjectLocationStructureProjectCommand -): ProjectLocationStructureProjectCommand { - switch (command.type) { - case projectFloorInsertCommandType: - assertProjectFloorInsertProjectCommand(command); - return upgradeProjectFloorCommand(command); - case projectFloorDeleteCommandType: - assertProjectFloorDeleteProjectCommand(command); - return upgradeProjectFloorCommand(command); - case projectFloorUpdateCommandType: - assertProjectFloorUpdateProjectCommand(command); - return upgradeProjectFloorCommand(command); - case projectRoomInsertCommandType: - assertProjectRoomInsertProjectCommand(command); - return upgradeProjectRoomCommand(command); - case projectRoomDeleteCommandType: - assertProjectRoomDeleteProjectCommand(command); - return upgradeProjectRoomCommand(command); - case projectRoomUpdateCommandType: - assertProjectRoomUpdateProjectCommand(command); - return upgradeProjectRoomCommand(command); - default: - return command; - } -} - function sameRecord( expected: object, actual: object diff --git a/src/db/repositories/project-snapshot.repository.ts b/src/db/repositories/project-snapshot.repository.ts index 7a7522a..5274fee 100644 --- a/src/db/repositories/project-snapshot.repository.ts +++ b/src/db/repositories/project-snapshot.repository.ts @@ -5,7 +5,6 @@ import { ProjectSnapshotNameConflictError } from "../../domain/errors/project-sn import { createProjectStateRestoreCommand } from "../../domain/models/project-state-restore-command.model.js"; import { deserializeProjectStateSnapshot, - isSupportedProjectStateSnapshotSchemaVersion, projectStateSnapshotSchemaVersion, } from "../../domain/models/project-state-snapshot.model.js"; import type { @@ -139,7 +138,7 @@ export class ProjectSnapshotRepository implements ProjectSnapshotStore { if (actualChecksum !== stored.payloadSha256) { throw new Error("Project snapshot checksum verification failed."); } - if (!isSupportedProjectStateSnapshotSchemaVersion(stored.schemaVersion)) { + if (stored.schemaVersion !== projectStateSnapshotSchemaVersion) { throw new Error("Project snapshot schema version is not supported."); } const targetState = deserializeProjectStateSnapshot(stored.payloadJson); diff --git a/src/db/repositories/project-state-restore-command.repository.ts b/src/db/repositories/project-state-restore-command.repository.ts index 2386bf6..cf6f9bc 100644 --- a/src/db/repositories/project-state-restore-command.repository.ts +++ b/src/db/repositories/project-state-restore-command.repository.ts @@ -3,8 +3,6 @@ import { ProjectStateConflictError } from "../../domain/errors/project-state-con import { assertProjectStateRestoreCommand, createProjectStateRestoreCommand, - createProjectTransferRestoreCommand, - projectStateRestoreCommandSchemaVersion, } from "../../domain/models/project-state-restore-command.model.js"; import { parseProjectStateSnapshot, @@ -15,8 +13,6 @@ import type { ProjectStateRestoreCommandStore, } from "../../domain/ports/project-state-restore-command.store.js"; import type { AppDatabase } from "../database-context.js"; -import { canonicalEstimateBalance } from "../../estimate-balance/domain/estimate-balance-command.model.js"; -import type { EstimateBalanceSnapshot } from "../../shared/estimate-balance/estimate-balance.js"; import { circuitDeviceRows } from "../schema/circuit-device-rows.js"; import { circuitLists } from "../schema/circuit-lists.js"; import { circuitProtectionDevices } from "../schema/circuit-protection-devices.js"; @@ -25,27 +21,20 @@ 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 { distributionBoards } from "../schema/distribution-boards.js"; -import { buildings } from "../schema/buildings.js"; import { floors } from "../schema/floors.js"; 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 { externalModelConfigurations } from "../schema/external-model-configurations.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 { estimateBalances } from "../schema/estimate-balances.js"; -import { - insertEstimateBalance, - readEstimateBalances, -} from "./estimate-balance.persistence.js"; import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js"; import { readProjectStateSnapshot, } from "./project-state-snapshot.persistence.js"; -import { insertManyInBatches } from "./batched-insert.persistence.js"; export class ProjectStateRestoreCommandRepository implements ProjectStateRestoreCommandStore @@ -76,39 +65,10 @@ export class ProjectStateRestoreCommandRepository if (!current) { throw new Error("Project not found."); } - const currentEstimateBalances = readEstimateBalances(tx, input.projectId); - const transferCommand = - input.command.schemaVersion === projectStateRestoreCommandSchemaVersion - ? input.command - : null; if ( current.payloadSha256 !== input.command.payload.expectedStateSha256 && - !matchesHistoryRestoreTarget( - tx, - input, - current.state, - currentEstimateBalances - ) - ) { - throw new ProjectStateConflictError( - input.projectId, - input.command.payload.expectedStateSha256, - current.payloadSha256 - ); - } - if ( - transferCommand && - canonicalEstimateBalances(currentEstimateBalances) !== - canonicalEstimateBalances( - transferCommand.payload.expectedEstimateBalances - ) && - !matchesHistoryRestoreTarget( - tx, - input, - current.state, - currentEstimateBalances - ) + !matchesHistoryRestoreTarget(tx, input, current.state) ) { throw new ProjectStateConflictError( input.projectId, @@ -121,28 +81,14 @@ export class ProjectStateRestoreCommandRepository input.command.payload.targetState ); replaceProjectState(tx, targetState); - if (transferCommand) { - replaceEstimateBalances( - tx, - input.projectId, - transferCommand.payload.targetEstimateBalances - ); - } const persistedTarget = readProjectStateSnapshot(tx, input.projectId); if (!persistedTarget) { throw new Error("Restored project could not be loaded."); } - const inverse = transferCommand - ? createProjectTransferRestoreCommand( - persistedTarget.payloadSha256, - current.state, - transferCommand.payload.targetEstimateBalances, - currentEstimateBalances - ) - : createProjectStateRestoreCommand( - persistedTarget.payloadSha256, - current.state - ); + const inverse = createProjectStateRestoreCommand( + persistedTarget.payloadSha256, + current.state + ); return inverse; } @@ -151,8 +97,7 @@ export class ProjectStateRestoreCommandRepository function matchesHistoryRestoreTarget( database: AppDatabase, input: ExecuteProjectStateRestoreCommandInput, - currentState: ProjectStateSnapshot, - currentEstimateBalances: EstimateBalanceSnapshot[] + currentState: ProjectStateSnapshot ) { if ( (input.source !== "undo" && input.source !== "redo") || @@ -176,45 +121,25 @@ function matchesHistoryRestoreTarget( input.source === "undo" ? changeSet.forwardPayloadJson : changeSet.inversePayloadJson; - const command = JSON.parse(serialized) as unknown; - assertProjectStateRestoreCommand(command); - const expectedState = parseProjectStateSnapshot(command.payload.targetState); - const stateMatches = - canonicalProjectState(expectedState) === - canonicalProjectState(currentState); - if (!stateMatches) { + const command = JSON.parse(serialized) as { + type?: unknown; + payload?: { targetState?: unknown }; + }; + if (command.type !== "project.restore-state") { return false; } - return command.schemaVersion !== projectStateRestoreCommandSchemaVersion || - canonicalEstimateBalances(command.payload.targetEstimateBalances) === - canonicalEstimateBalances(currentEstimateBalances); + const expectedState = parseProjectStateSnapshot( + command.payload?.targetState + ); + return ( + canonicalProjectState(expectedState) === + canonicalProjectState(currentState) + ); } catch { return false; } } -function canonicalEstimateBalances(balances: EstimateBalanceSnapshot[]) { - return JSON.stringify( - [...balances] - .sort((left, right) => left.id.localeCompare(right.id)) - .map((balance) => canonicalEstimateBalance(balance)) - ); -} - -function replaceEstimateBalances( - database: AppDatabase, - projectId: string, - balances: EstimateBalanceSnapshot[] -) { - database - .delete(estimateBalances) - .where(eq(estimateBalances.projectId, projectId)) - .run(); - for (const balance of balances) { - insertEstimateBalance(database, balance); - } -} - function canonicalProjectState(state: ProjectStateSnapshot) { return JSON.stringify({ ...state, @@ -239,10 +164,9 @@ function canonicalProjectState(state: ProjectStateSnapshot) { })) ), projectDevices: byId(state.projectDevices), - buildings: byId(state.buildings), floors: byId(state.floors), rooms: byId(state.rooms), - externalModelConfiguration: state.externalModelConfiguration, + externalCsvConfiguration: state.externalCsvConfiguration, externalModel: { source: state.externalModel.source, importBatches: byId(state.externalModel.importBatches), @@ -271,21 +195,13 @@ function replaceProjectState( database: AppDatabase, state: ProjectStateSnapshot ) { - database - .update(distributionBoards) - .set({ - feedingDistributionBoardId: null, - feedingCircuitId: null, - }) - .where(eq(distributionBoards.projectId, state.project.id)) - .run(); database .delete(externalModelSources) .where(eq(externalModelSources.projectId, state.project.id)) .run(); database - .delete(externalModelConfigurations) - .where(eq(externalModelConfigurations.projectId, state.project.id)) + .delete(externalCsvConfigurations) + .where(eq(externalCsvConfigurations.projectId, state.project.id)) .run(); database .delete(distributionBoards) @@ -303,10 +219,6 @@ function replaceProjectState( .delete(floors) .where(eq(floors.projectId, state.project.id)) .run(); - database - .delete(buildings) - .where(eq(buildings.projectId, state.project.id)) - .run(); database .update(projects) @@ -329,25 +241,16 @@ function replaceProjectState( .where(eq(projects.id, state.project.id)) .run(); - insertMany(database, buildings, state.buildings); insertMany(database, floors, state.floors); - if (state.externalModelConfiguration !== null) { + if (state.externalCsvConfiguration !== null) { database - .insert(externalModelConfigurations) - .values(state.externalModelConfiguration) + .insert(externalCsvConfigurations) + .values(state.externalCsvConfiguration) .run(); } insertMany(database, rooms, state.rooms); insertMany(database, projectDevices, state.projectDevices); - insertMany( - database, - distributionBoards, - state.distributionBoards.map((board) => ({ - ...board, - feedingDistributionBoardId: null, - feedingCircuitId: null, - })) - ); + insertMany(database, distributionBoards, state.distributionBoards); insertMany(database, circuitLists, state.circuitLists); insertMany(database, circuitSections, state.circuitSections); insertMany( @@ -358,7 +261,6 @@ function replaceProjectState( isReserve: circuit.isReserve ? 1 : 0, })) ); - restoreDistributionBoardFeedingReferences(database, state); insertMany( database, distributionBoardComponents, @@ -388,10 +290,7 @@ function replaceProjectState( state.externalModel.importBatches.map( ({ originalContentBase64, ...batch }) => ({ ...batch, - originalBytes: - originalContentBase64 === null - ? null - : Buffer.from(originalContentBase64, "base64"), + originalBytes: Buffer.from(originalContentBase64, "base64"), }) ) ); @@ -399,35 +298,16 @@ function replaceProjectState( insertMany(database, externalModelObjects, state.externalModel.objects); } -function restoreDistributionBoardFeedingReferences( - database: AppDatabase, - state: ProjectStateSnapshot -) { - for (const board of state.distributionBoards) { - if ( - board.feedingDistributionBoardId === null && - board.feedingCircuitId === null - ) { - continue; - } - const updated = database - .update(distributionBoards) - .set({ - feedingDistributionBoardId: board.feedingDistributionBoardId, - feedingCircuitId: board.feedingCircuitId, - }) - .where(eq(distributionBoards.id, board.id)) - .run(); - if (updated.changes !== 1) { - throw new Error("Distribution-board feeding reference could not be restored."); - } - } -} - function insertMany[0]>( database: AppDatabase, table: TTable, values: unknown[] ) { - insertManyInBatches(database, table, values); + if (values.length === 0) { + return; + } + database + .insert(table) + .values(values as never) + .run(); } diff --git a/src/db/repositories/project-state-snapshot.persistence.ts b/src/db/repositories/project-state-snapshot.persistence.ts index 431241b..84131e7 100644 --- a/src/db/repositories/project-state-snapshot.persistence.ts +++ b/src/db/repositories/project-state-snapshot.persistence.ts @@ -15,12 +15,11 @@ 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 { distributionBoards } from "../schema/distribution-boards.js"; -import { buildings } from "../schema/buildings.js"; 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 { externalModelConfigurations } from "../schema/external-model-configurations.js"; +import { externalCsvConfigurations } from "../schema/external-csv-configurations.js"; import { ExternalModelStateRepository } from "./external-model-state.repository.js"; export interface PersistedProjectStateSnapshot { @@ -66,10 +65,10 @@ export function readProjectStateSnapshot( .where(eq(distributionBoards.projectId, projectId)) .orderBy(asc(distributionBoards.name), asc(distributionBoards.id)) .all(); - const externalModelConfiguration = database + const externalCsvConfiguration = database .select() - .from(externalModelConfigurations) - .where(eq(externalModelConfigurations.projectId, projectId)) + .from(externalCsvConfigurations) + .where(eq(externalCsvConfigurations.projectId, projectId)) .get() ?? null; const externalModel = new ExternalModelStateRepository(database) .getByProject(projectId).state; @@ -220,12 +219,6 @@ export function readProjectStateSnapshot( .where(eq(projectDevices.projectId, projectId)) .orderBy(asc(projectDevices.displayName), asc(projectDevices.id)) .all(); - const buildingRows = database - .select() - .from(buildings) - .where(eq(buildings.projectId, projectId)) - .orderBy(asc(buildings.sortOrder), asc(buildings.id)) - .all(); const floorRows = database .select() .from(floors) @@ -266,7 +259,7 @@ export function readProjectStateSnapshot( projectEditor: project.projectEditor, }, distributionBoards: boardRows, - externalModelConfiguration, + externalCsvConfiguration, externalModel, circuitLists: listRows, circuitSections: sectionRows, @@ -280,7 +273,6 @@ export function readProjectStateSnapshot( deviceRows: deviceRowsByCircuit.get(circuit.id) ?? [], })), projectDevices: projectDeviceRows, - buildings: buildingRows, floors: floorRows, rooms: roomRows, }); diff --git a/src/db/repositories/project-transfer.repository.ts b/src/db/repositories/project-transfer.repository.ts index c203388..07a5067 100644 --- a/src/db/repositories/project-transfer.repository.ts +++ b/src/db/repositories/project-transfer.repository.ts @@ -3,11 +3,9 @@ import { eq } from "drizzle-orm"; import { createProjectTransferEnvelope, parseProjectTransferEnvelope, - remapEstimateBalances, remapProjectState, - serializeProjectTransferPayload, } from "../../domain/models/project-transfer.model.js"; -import { createProjectTransferRestoreCommand } from "../../domain/models/project-state-restore-command.model.js"; +import { createProjectStateRestoreCommand } from "../../domain/models/project-state-restore-command.model.js"; import type { ProjectTransferStore } from "../../domain/ports/project-transfer.store.js"; import type { AppDatabase } from "../database-context.js"; import { circuitDeviceRows } from "../schema/circuit-device-rows.js"; @@ -18,26 +16,20 @@ 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 { distributionBoards } from "../schema/distribution-boards.js"; -import { buildings } from "../schema/buildings.js"; 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 { externalModelConfigurations } from "../schema/external-model-configurations.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 { - insertEstimateBalance, - readEstimateBalances, -} from "./estimate-balance.persistence.js"; import { hashProjectStatePayload, readProjectStateSnapshot, } from "./project-state-snapshot.persistence.js"; import { serializeProjectStateSnapshot } from "../../domain/models/project-state-snapshot.model.js"; -import { insertManyInBatches } from "./batched-insert.persistence.js"; export class ProjectTransferRepository implements ProjectTransferStore { constructor(private readonly database: AppDatabase) {} @@ -47,15 +39,10 @@ export class ProjectTransferRepository implements ProjectTransferStore { if (!snapshot) { return null; } - const estimateBalances = readEstimateBalances(this.database, projectId); - const payloadSha256 = hashProjectStatePayload( - serializeProjectTransferPayload(snapshot.state, estimateBalances) - ); return createProjectTransferEnvelope( new Date().toISOString(), - payloadSha256, - snapshot.state, - estimateBalances + snapshot.payloadSha256, + snapshot.state ); } @@ -73,21 +60,10 @@ export class ProjectTransferRepository implements ProjectTransferStore { projectId, () => crypto.randomUUID() ); - const currentEstimateBalances = readEstimateBalances(this.database, projectId); - const targetEstimateBalances = - transfer.projectState.project.id === projectId - ? transfer.estimateBalances - : remapEstimateBalances( - transfer.estimateBalances, - projectId, - () => crypto.randomUUID() - ); return { - command: createProjectTransferRestoreCommand( + command: createProjectStateRestoreCommand( current.payloadSha256, - targetState, - currentEstimateBalances, - targetEstimateBalances + targetState ), }; } @@ -101,39 +77,20 @@ export class ProjectTransferRepository implements ProjectTransferStore { () => crypto.randomUUID(), `${transfer.projectState.project.name} (Kopie)` ); - const estimateBalances = remapEstimateBalances( - transfer.estimateBalances, - projectId, - () => crypto.randomUUID() - ); - this.database.transaction((tx) => { - insertProjectState(tx, state); - for (const balance of estimateBalances) { - insertEstimateBalance(tx, balance); - } - }); + this.database.transaction((tx) => insertProjectState(tx, state)); return { projectId, name: state.project.name }; } private parseVerified(value: unknown) { - const isLegacy = isPlainObject(value) && value.formatVersion === 1; - const rawPayloadSha256 = isPlainObject(value) && isPlainObject(value.projectState) - ? hashProjectStatePayload( - isLegacy - ? JSON.stringify(value.projectState) - : JSON.stringify({ - projectState: value.projectState, - estimateBalances: value.estimateBalances, - }) - ) - : null; + const rawPayloadSha256 = + isPlainObject(value) && + isPlainObject(value.projectState) + ? hashProjectStatePayload(JSON.stringify(value.projectState)) + : null; const transfer = parseProjectTransferEnvelope(value); - const payloadJson = isLegacy - ? serializeProjectStateSnapshot(transfer.projectState) - : serializeProjectTransferPayload( - transfer.projectState, - transfer.estimateBalances - ); + const payloadJson = serializeProjectStateSnapshot( + transfer.projectState + ); if ( hashProjectStatePayload(payloadJson) !== transfer.payloadSha256 && rawPayloadSha256 !== transfer.payloadSha256 @@ -164,25 +121,16 @@ function insertProjectState( .insert(projects) .values({ ...state.project, currentRevision: 0 }) .run(); - if (state.externalModelConfiguration !== null) { + if (state.externalCsvConfiguration !== null) { database - .insert(externalModelConfigurations) - .values(state.externalModelConfiguration) + .insert(externalCsvConfigurations) + .values(state.externalCsvConfiguration) .run(); } - insertMany(database, buildings, state.buildings); insertMany(database, floors, state.floors); insertMany(database, rooms, state.rooms); insertMany(database, projectDevices, state.projectDevices); - insertMany( - database, - distributionBoards, - state.distributionBoards.map((board) => ({ - ...board, - feedingDistributionBoardId: null, - feedingCircuitId: null, - })) - ); + insertMany(database, distributionBoards, state.distributionBoards); insertMany(database, circuitLists, state.circuitLists); insertMany(database, circuitSections, state.circuitSections); insertMany( @@ -193,25 +141,6 @@ function insertProjectState( isReserve: circuit.isReserve ? 1 : 0, })) ); - for (const board of state.distributionBoards) { - if ( - board.feedingDistributionBoardId === null && - board.feedingCircuitId === null - ) { - continue; - } - const updated = database - .update(distributionBoards) - .set({ - feedingDistributionBoardId: board.feedingDistributionBoardId, - feedingCircuitId: board.feedingCircuitId, - }) - .where(eq(distributionBoards.id, board.id)) - .run(); - if (updated.changes !== 1) { - throw new Error("Distribution-board feeding reference could not be imported."); - } - } insertMany( database, distributionBoardComponents, @@ -241,10 +170,7 @@ function insertProjectState( state.externalModel.importBatches.map( ({ originalContentBase64, ...batch }) => ({ ...batch, - originalBytes: - originalContentBase64 === null - ? null - : Buffer.from(originalContentBase64, "base64"), + originalBytes: Buffer.from(originalContentBase64, "base64"), }) ) ); @@ -257,5 +183,7 @@ function insertMany[0]>( table: TTable, values: unknown[] ) { - insertManyInBatches(database, table, values); + if (values.length > 0) { + database.insert(table).values(values as never).run(); + } } diff --git a/src/db/repositories/user.repository.ts b/src/db/repositories/user.repository.ts deleted file mode 100644 index 1fd55c7..0000000 --- a/src/db/repositories/user.repository.ts +++ /dev/null @@ -1,117 +0,0 @@ -import crypto from "node:crypto"; -import { and, asc, eq } from "drizzle-orm"; -import type { AppDatabase } from "../database-context.js"; -import { users } from "../schema/users.js"; -import { - LastActiveAdminStoreError, - UsernameAlreadyExistsStoreError, - type CreateUserAccount, - type UserStore, -} from "../../domain/ports/user.store.js"; -import type { UserRole } from "../../shared/constants/user-roles.js"; - -function isUniqueConstraintError(error: unknown): boolean { - return ( - error instanceof Error && - "code" in error && - (error as { code?: unknown }).code === "SQLITE_CONSTRAINT_UNIQUE" - ); -} - -export class UserRepository implements UserStore { - 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: CreateUserAccount) { - const db = this.database; - const id = crypto.randomUUID(); - try { - await db.insert(users).values({ - id, - username: input.username.trim().toLowerCase(), - name: input.name, - role: input.role, - passwordHash: input.passwordHash, - active: true, - mustChangePassword: true, - }); - } catch (error) { - if (isUniqueConstraintError(error)) throw new UsernameAlreadyExistsStoreError(); - throw error; - } - return this.findById(id); - } - - async updateRoleAndActive( - userId: string, - patch: { role?: UserRole; active?: boolean } - ) { - return this.database.transaction((tx) => { - const [target] = tx.select().from(users).where(eq(users.id, userId)).limit(1).all(); - if (!target) return null; - - const removesActiveAdmin = - target.role === "admin" && - target.active && - (patch.role === "user" || patch.active === false); - if (removesActiveAdmin) { - const activeAdmins = tx - .select({ id: users.id }) - .from(users) - .where(and(eq(users.role, "admin"), eq(users.active, true))) - .limit(2) - .all(); - if (activeAdmins.length <= 1) throw new LastActiveAdminStoreError(); - } - - tx.update(users) - .set({ - ...(patch.role !== undefined ? { role: patch.role } : {}), - ...(patch.active !== undefined ? { active: patch.active } : {}), - updatedAt: new Date(), - }) - .where(eq(users.id, userId)) - .run(); - return tx.select().from(users).where(eq(users.id, userId)).limit(1).all()[0] ?? null; - }); - } - - 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/buildings.ts b/src/db/schema/buildings.ts deleted file mode 100644 index 7d2fb78..0000000 --- a/src/db/schema/buildings.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import { projects } from "./projects.js"; - -export const buildings = sqliteTable("buildings", { - id: text("id").primaryKey(), - projectId: text("project_id") - .notNull() - .references(() => projects.id, { onDelete: "cascade" }), - name: text("name").notNull(), - sortOrder: integer("sort_order").notNull().default(0), -}); diff --git a/src/db/schema/cable-sizing-calculations.ts b/src/db/schema/cable-sizing-calculations.ts new file mode 100644 index 0000000..511fab3 --- /dev/null +++ b/src/db/schema/cable-sizing-calculations.ts @@ -0,0 +1,30 @@ +import { sql } from "drizzle-orm"; +import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { circuits } from "./circuits.js"; +import { projects } from "./projects.js"; + +// Audit log for the cable-sizing module (see docs/cable-sizing-module.md). +// Deliberately separate from the revision/command system: a calculation is +// not itself a project mutation, only applying its result via the existing +// circuit.update command is. circuitId/projectId are nullable and +// onDelete "set null" so a deleted circuit or project never blocks or +// cascades into losing the audit trail. +export const cableSizingCalculations = sqliteTable( + "cable_sizing_calculations", + { + id: text("id").primaryKey(), + projectId: text("project_id").references(() => projects.id, { onDelete: "set null" }), + circuitId: text("circuit_id").references(() => circuits.id, { onDelete: "set null" }), + equipmentIdentifier: text("equipment_identifier"), + input: text("input", { mode: "json" }).notNull(), + result: text("result", { mode: "json" }).notNull(), + appliedToCircuit: integer("applied_to_circuit").notNull().default(0), + createdAt: integer("created_at", { mode: "timestamp" }) + .notNull() + .default(sql`(unixepoch())`), + }, + (table) => [index("cable_sizing_calculations_circuit_id_idx").on(table.circuitId)] +); + +export type CableSizingCalculation = typeof cableSizingCalculations.$inferSelect; +export type NewCableSizingCalculation = typeof cableSizingCalculations.$inferInsert; diff --git a/src/db/schema/circuit-lists.ts b/src/db/schema/circuit-lists.ts index 2283aeb..0af5138 100644 --- a/src/db/schema/circuit-lists.ts +++ b/src/db/schema/circuit-lists.ts @@ -1,4 +1,4 @@ -import { sqliteTable, text, unique, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; +import { sqliteTable, text, unique } from "drizzle-orm/sqlite-core"; import { distributionBoards } from "./distribution-boards.js"; import { projects } from "./projects.js"; @@ -11,7 +11,7 @@ export const circuitLists = sqliteTable( .references(() => projects.id, { onDelete: "cascade" }), distributionBoardId: text("distribution_board_id") .notNull() - .references((): AnySQLiteColumn => distributionBoards.id, { onDelete: "cascade" }), + .references(() => distributionBoards.id, { onDelete: "cascade" }), name: text("name").notNull(), }, (table) => [unique("circuit_lists_distribution_board_id_unique").on(table.distributionBoardId)] diff --git a/src/db/schema/circuits.ts b/src/db/schema/circuits.ts index 15ef0e3..6e3ed3e 100644 --- a/src/db/schema/circuits.ts +++ b/src/db/schema/circuits.ts @@ -1,4 +1,4 @@ -import { index, integer, real, sqliteTable, text, unique, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; +import { index, integer, real, sqliteTable, text, unique } from "drizzle-orm/sqlite-core"; import { circuitLists } from "./circuit-lists.js"; import { circuitSections } from "./circuit-sections.js"; @@ -8,7 +8,7 @@ export const circuits = sqliteTable( id: text("id").primaryKey(), circuitListId: text("circuit_list_id") .notNull() - .references((): AnySQLiteColumn => circuitLists.id, { onDelete: "cascade" }), + .references(() => circuitLists.id, { onDelete: "cascade" }), sectionId: text("section_id") .notNull() .references(() => circuitSections.id, { onDelete: "cascade" }), diff --git a/src/db/schema/distribution-boards.ts b/src/db/schema/distribution-boards.ts index 60bbe4d..eb63486 100644 --- a/src/db/schema/distribution-boards.ts +++ b/src/db/schema/distribution-boards.ts @@ -1,44 +1,24 @@ -import { index, real, sqliteTable, text, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; -import { circuits } from "./circuits.js"; +import { real, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { floors } from "./floors.js"; import { projects } from "./projects.js"; import type { DistributionBoardSupplyType } from "../../shared/constants/distribution-board.js"; -export const distributionBoards = sqliteTable( - "distribution_boards", - { - id: text("id").primaryKey(), - projectId: text("project_id") - .notNull() - .references(() => projects.id, { onDelete: "cascade" }), - name: text("name").notNull(), - floorId: text("floor_id").references(() => floors.id, { - onDelete: "set null", - }), - supplyType: text("supply_type").$type(), - simultaneityFactor: real("simultaneity_factor") - .notNull() - .default(1), - boardNumber: text("board_number"), - location: text("location"), - fedFrom: text("fed_from"), - remark: text("remark"), - feedingDistributionBoardId: text("feeding_distribution_board_id").references( - (): AnySQLiteColumn => distributionBoards.id, - { onDelete: "restrict" } - ), - feedingCircuitId: text("feeding_circuit_id").references( - (): AnySQLiteColumn => circuits.id, - { onDelete: "restrict" } - ), - }, - (table) => [ - index("distribution_boards_feeding_board_idx").on( - table.feedingDistributionBoardId - ), - index("distribution_boards_feeding_circuit_idx").on( - table.feedingCircuitId - ), - ] -); +export const distributionBoards = sqliteTable("distribution_boards", { + id: text("id").primaryKey(), + projectId: text("project_id") + .notNull() + .references(() => projects.id, { onDelete: "cascade" }), + name: text("name").notNull(), + floorId: text("floor_id").references(() => floors.id, { + onDelete: "set null", + }), + supplyType: text("supply_type").$type(), + simultaneityFactor: real("simultaneity_factor") + .notNull() + .default(1), + boardNumber: text("board_number"), + location: text("location"), + fedFrom: text("fed_from"), + remark: text("remark"), +}); diff --git a/src/db/schema/estimate-balances.ts b/src/db/schema/estimate-balances.ts deleted file mode 100644 index 4425a03..0000000 --- a/src/db/schema/estimate-balances.ts +++ /dev/null @@ -1,60 +0,0 @@ -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"), - 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/db/schema/external-csv-configurations.ts b/src/db/schema/external-csv-configurations.ts new file mode 100644 index 0000000..2cbcd06 --- /dev/null +++ b/src/db/schema/external-csv-configurations.ts @@ -0,0 +1,22 @@ +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-export-batches.ts b/src/db/schema/external-export-batches.ts deleted file mode 100644 index 37e94d8..0000000 --- a/src/db/schema/external-export-batches.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; -import { projects } from "./projects.js"; - -export const externalExportScopes = ["all", "deviating", "selected"] as const; -export type ExternalExportScope = (typeof externalExportScopes)[number]; - -export const externalExportBatches = sqliteTable( - "external_export_batches", - { - id: text("id").primaryKey(), - projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), - projectRevision: integer("project_revision").notNull(), - importBatchId: text("import_batch_id").notNull(), - exportedAtIso: text("exported_at_iso").notNull(), - fileName: text("file_name").notNull(), - sha256: text("sha256").notNull(), - configurationSnapshot: text("configuration_snapshot", { mode: "json" }).$type().notNull(), - configurationSha256: text("configuration_sha256").notNull(), - scope: text("scope", { enum: externalExportScopes }).notNull(), - objectCount: integer("object_count").notNull(), - }, - (table) => [index("external_export_batches_project_exported_idx").on(table.projectId, table.exportedAtIso)] -); diff --git a/src/db/schema/external-import-batches.ts b/src/db/schema/external-import-batches.ts index 0919891..125077e 100644 --- a/src/db/schema/external-import-batches.ts +++ b/src/db/schema/external-import-batches.ts @@ -1,7 +1,9 @@ import { blob, index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; +import type { + ExternalCsvConfiguration, + ExternalCsvDocument, +} from "../../external-model/csv/external-csv-contracts.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"; @@ -19,13 +21,15 @@ export const externalImportBatches = sqliteTable( importedAtIso: text("imported_at_iso").notNull(), fileName: text("file_name").notNull(), sha256: text("sha256").notNull(), - objectCount: integer("object_count").notNull(), - appliedProjectRevision: integer("applied_project_revision"), + appliedProjectRevision: integer("applied_project_revision").notNull(), + configurationVersion: integer("configuration_version").notNull(), configurationSnapshot: text("configuration_snapshot", { mode: "json" }) - .$type(), - originalBytes: blob("original_bytes", { mode: "buffer" }), + .$type() + .notNull(), + originalBytes: blob("original_bytes", { mode: "buffer" }).notNull(), document: text("document", { mode: "json" }) - .$type(), + .$type() + .notNull(), }, (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 deleted file mode 100644 index e28ced7..0000000 --- a/src/db/schema/external-model-configurations.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 2de80cb..fbd50b7 100644 --- a/src/db/schema/external-model-objects.ts +++ b/src/db/schema/external-model-objects.ts @@ -23,9 +23,7 @@ export const externalModelObjects = sqliteTable( sourceId: text("source_id") .notNull() .references(() => externalModelSources.id, { onDelete: "cascade" }), - worksharingId: text("worksharing_id").notNull(), - ifcGuid: text("ifc_guid"), - deviceTypeId: text("device_type_id").notNull(), + ifcGuid: text("ifc_guid").notNull(), lastSeenImportBatchId: text("last_seen_import_batch_id") .notNull() .references(() => externalImportBatches.id, { onDelete: "restrict" }), @@ -64,27 +62,17 @@ export const externalModelObjects = sqliteTable( .default("present"), }, (table) => [ - uniqueIndex("external_model_objects_source_worksharing_id_unique").on( + uniqueIndex("external_model_objects_source_ifc_guid_unique").on( table.sourceId, - table.worksharingId + table.ifcGuid ), 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 7dfb3d1..a4f9ded 100644 --- a/src/db/schema/external-model-sources.ts +++ b/src/db/schema/external-model-sources.ts @@ -12,9 +12,12 @@ export const externalModelSources = sqliteTable( name: text("name").notNull(), sourceType: text("source_type", { enum: externalModelSourceTypes }) .notNull() - .default("revit_xlsx"), + .default("revit_csv"), }, (table) => [ - uniqueIndex("external_model_sources_project_unique").on(table.projectId), + uniqueIndex("external_model_sources_project_type_unique").on( + table.projectId, + table.sourceType + ), ] ); diff --git a/src/db/schema/floors.ts b/src/db/schema/floors.ts index bd50534..5c68753 100644 --- a/src/db/schema/floors.ts +++ b/src/db/schema/floors.ts @@ -1,5 +1,4 @@ import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; -import { buildings } from "./buildings.js"; import { projects } from "./projects.js"; export const floors = sqliteTable("floors", { @@ -9,9 +8,4 @@ export const floors = sqliteTable("floors", { .references(() => projects.id, { onDelete: "cascade" }), name: text("name").notNull(), sortOrder: integer("sort_order").notNull().default(0), - // Optional parent building. Floors created before buildings existed stay - // without one and are shown as "Ohne Gebäude". - buildingId: text("building_id").references(() => buildings.id, { - onDelete: "set null", - }), }); diff --git a/src/db/schema/rooms.ts b/src/db/schema/rooms.ts index 47988bd..271106d 100644 --- a/src/db/schema/rooms.ts +++ b/src/db/schema/rooms.ts @@ -1,4 +1,4 @@ -import { real, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { sqliteTable, text } from "drizzle-orm/sqlite-core"; import { floors } from "./floors.js"; import { projects } from "./projects.js"; @@ -10,6 +10,4 @@ export const rooms = sqliteTable("rooms", { floorId: text("floor_id").references(() => floors.id, { onDelete: "set null" }), roomNumber: text("room_number").notNull(), roomName: text("room_name").notNull(), - /** Optional net room area from the Revit room parameter "Fläche". */ - areaM2: real("area_m2"), }); diff --git a/src/db/schema/users.ts b/src/db/schema/users.ts deleted file mode 100644 index 7105fb4..0000000 --- a/src/db/schema/users.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { sql } from "drizzle-orm"; -import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; -import type { UserRole } from "../../shared/constants/user-roles.js"; - -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").$type().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/calculations/distribution-board-load-calculation.ts b/src/domain/calculations/distribution-board-load-calculation.ts deleted file mode 100644 index 4c7bad6..0000000 --- a/src/domain/calculations/distribution-board-load-calculation.ts +++ /dev/null @@ -1,217 +0,0 @@ -export interface DistributionBoardLoadBoardInput { - id: string; - name: string; - boardNumber: string | null; - simultaneityFactor: number; - feedingDistributionBoardId: string | null; - feedingCircuitId: string | null; -} - -export interface DistributionBoardLoadCircuitInput { - id: string; - distributionBoardId: string; - rows: Array<{ - activePowerKw: number; - cosPhi: number | null; - }>; -} - -export interface DownstreamDistributionBoardLoad { - distributionBoardId: string; - name: string; - boardNumber: string | null; - activePowerKw: number; - apparentPowerKva: number; - cosPhi: number; -} - -export interface CalculatedCircuitLoad { - circuitId: string; - deviceActivePowerKw: number; - deviceApparentPowerKva: number; - activePowerKw: number; - apparentPowerKva: number; - cosPhi: number; - downstreamBoards: DownstreamDistributionBoardLoad[]; -} - -export interface CalculatedDistributionBoardLoad { - distributionBoardId: string; - activePowerBeforeSimultaneityKw: number; - apparentPowerBeforeSimultaneityKva: number; - demandActivePowerKw: number; - demandApparentPowerKva: number; - cosPhi: number; -} - -export interface DistributionBoardLoadCalculation { - boards: Map; - circuits: Map; -} - -/** - * Calculates one project graph. A child board enters exactly one feeder - * circuit with its demand after the child's own board simultaneity factor. - * Board-only relations form a hierarchy but intentionally add no load. - */ -export function calculateDistributionBoardLoads(input: { - boards: DistributionBoardLoadBoardInput[]; - circuits: DistributionBoardLoadCircuitInput[]; -}): DistributionBoardLoadCalculation { - const boardById = new Map(input.boards.map((board) => [board.id, board])); - const circuitById = new Map(input.circuits.map((circuit) => [circuit.id, circuit])); - const circuitsByBoardId = groupBy( - input.circuits, - (circuit) => circuit.distributionBoardId - ); - const childrenByCircuitId = new Map(); - for (const board of input.boards) { - assertBoardInput(board, boardById, circuitById); - if (board.feedingCircuitId === null) continue; - const children = childrenByCircuitId.get(board.feedingCircuitId) ?? []; - children.push(board); - childrenByCircuitId.set(board.feedingCircuitId, children); - } - - const boards = new Map(); - const circuits = new Map(); - const activePath = new Set(); - - const calculateBoard = (boardId: string): CalculatedDistributionBoardLoad => { - const cached = boards.get(boardId); - if (cached) return cached; - if (activePath.has(boardId)) { - throw new Error("Distribution-board feeding graph contains a cycle."); - } - const board = boardById.get(boardId); - if (!board) throw new Error("Distribution board is missing from load graph."); - activePath.add(boardId); - - let activePowerBeforeSimultaneityKw = 0; - let apparentPowerBeforeSimultaneityKva = 0; - for (const circuit of circuitsByBoardId.get(boardId) ?? []) { - let deviceActivePowerKw = 0; - let deviceApparentPowerKva = 0; - for (const row of circuit.rows) { - assertNonNegativeFinite(row.activePowerKw, "row active power"); - const cosPhi = row.cosPhi ?? 1; - if (!Number.isFinite(cosPhi) || cosPhi <= 0 || cosPhi > 1) { - throw new Error("Row cos phi must be greater than zero and at most one."); - } - deviceActivePowerKw += row.activePowerKw; - deviceApparentPowerKva += row.activePowerKw / cosPhi; - } - const downstreamBoards = (childrenByCircuitId.get(circuit.id) ?? []) - .map((child) => { - const childLoad = calculateBoard(child.id); - return { - distributionBoardId: child.id, - name: child.name, - boardNumber: child.boardNumber, - activePowerKw: childLoad.demandActivePowerKw, - apparentPowerKva: childLoad.demandApparentPowerKva, - cosPhi: effectiveCosPhi( - childLoad.demandActivePowerKw, - childLoad.demandApparentPowerKva - ), - }; - }); - const activePowerKw = - deviceActivePowerKw + - downstreamBoards.reduce((sum, child) => sum + child.activePowerKw, 0); - const apparentPowerKva = - deviceApparentPowerKva + - downstreamBoards.reduce((sum, child) => sum + child.apparentPowerKva, 0); - circuits.set(circuit.id, { - circuitId: circuit.id, - deviceActivePowerKw, - deviceApparentPowerKva, - activePowerKw, - apparentPowerKva, - cosPhi: effectiveCosPhi(activePowerKw, apparentPowerKva), - downstreamBoards, - }); - activePowerBeforeSimultaneityKw += activePowerKw; - apparentPowerBeforeSimultaneityKva += apparentPowerKva; - } - - activePath.delete(boardId); - const result = { - distributionBoardId: boardId, - activePowerBeforeSimultaneityKw, - apparentPowerBeforeSimultaneityKva, - demandActivePowerKw: - activePowerBeforeSimultaneityKw * board.simultaneityFactor, - demandApparentPowerKva: - apparentPowerBeforeSimultaneityKva * board.simultaneityFactor, - cosPhi: effectiveCosPhi( - activePowerBeforeSimultaneityKw, - apparentPowerBeforeSimultaneityKva - ), - }; - boards.set(boardId, result); - return result; - }; - - for (const board of input.boards) calculateBoard(board.id); - return { boards, circuits }; -} - -function assertBoardInput( - board: DistributionBoardLoadBoardInput, - boardById: Map, - circuitById: Map -) { - if ( - !Number.isFinite(board.simultaneityFactor) || - board.simultaneityFactor < 0 || - board.simultaneityFactor > 1 - ) { - throw new Error("Board simultaneity factor must be between zero and one."); - } - if (board.feedingDistributionBoardId === board.id) { - throw new Error("Distribution board cannot feed itself."); - } - if ( - board.feedingDistributionBoardId !== null && - !boardById.has(board.feedingDistributionBoardId) - ) { - throw new Error("Feeding distribution board is missing from load graph."); - } - if ( - board.feedingCircuitId !== null && - board.feedingDistributionBoardId === null - ) { - throw new Error("Feeding circuit requires a feeding distribution board."); - } - if ( - board.feedingCircuitId !== null && - circuitById.get(board.feedingCircuitId)?.distributionBoardId !== - board.feedingDistributionBoardId - ) { - throw new Error("Feeding circuit belongs to another distribution board."); - } -} - -function effectiveCosPhi(activePowerKw: number, apparentPowerKva: number) { - return activePowerKw > 0 && apparentPowerKva > 0 - ? activePowerKw / apparentPowerKva - : 1; -} - -function assertNonNegativeFinite(value: number, label: string) { - if (!Number.isFinite(value) || value < 0) { - throw new Error(`${label} must be a non-negative finite number.`); - } -} - -function groupBy(values: T[], keyOf: (value: T) => string) { - const groups = new Map(); - for (const value of values) { - const key = keyOf(value); - const group = groups.get(key) ?? []; - group.push(value); - groups.set(key, group); - } - return groups; -} 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 ebba5ac..2464a27 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,11 +1,4 @@ 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; @@ -39,13 +32,11 @@ export interface CircuitDeviceRowSnapshot { export interface CircuitDeviceRowInsertCommandPayload { row: CircuitDeviceRowSnapshot; - externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeviceRowDeleteCommandPayload { rowId: string; expectedCircuitId: string; - externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeviceRowInsertProjectCommand @@ -65,8 +56,7 @@ export type CircuitDeviceRowStructureProjectCommand = | CircuitDeviceRowDeleteProjectCommand; export function createCircuitDeviceRowInsertProjectCommand( - row: CircuitDeviceRowSnapshot, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + row: CircuitDeviceRowSnapshot ): CircuitDeviceRowInsertProjectCommand { const normalizedRow = { ...row, @@ -75,7 +65,7 @@ export function createCircuitDeviceRowInsertProjectCommand( const command: CircuitDeviceRowInsertProjectCommand = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowInsertCommandType, - payload: { row: normalizedRow, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { row: normalizedRow }, }; assertCircuitDeviceRowInsertProjectCommand(command); return command; @@ -83,13 +73,12 @@ export function createCircuitDeviceRowInsertProjectCommand( export function createCircuitDeviceRowDeleteProjectCommand( rowId: string, - expectedCircuitId: string, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + expectedCircuitId: string ): CircuitDeviceRowDeleteProjectCommand { const command: CircuitDeviceRowDeleteProjectCommand = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowDeleteCommandType, - payload: { rowId, expectedCircuitId, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { rowId, expectedCircuitId }, }; assertCircuitDeviceRowDeleteProjectCommand(command); return command; @@ -154,7 +143,6 @@ export function assertCircuitDeviceRowInsertProjectCommand( throw new Error("row.cosPhi must be positive or null."); } } - assertExternalObjectLinkTransitions(command.payload.externalObjects); } export function assertCircuitDeviceRowDeleteProjectCommand( @@ -175,41 +163,6 @@ 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 4470cd2..a3e53b3 100644 --- a/src/domain/models/circuit-group-subtree-project-command.model.ts +++ b/src/domain/models/circuit-group-subtree-project-command.model.ts @@ -3,7 +3,6 @@ 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; @@ -13,7 +12,6 @@ export const circuitGroupSubtreeCommandSchemaVersion = 1 as const; interface Payload { snapshot: CircuitGroupSubtreeSnapshot; - externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitGroupDeleteSubtreeProjectCommand @@ -33,26 +31,24 @@ export type CircuitGroupSubtreeProjectCommand = | CircuitGroupRestoreSubtreeProjectCommand; export function createCircuitGroupDeleteSubtreeProjectCommand( - snapshot: CircuitGroupSubtreeSnapshot, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + snapshot: CircuitGroupSubtreeSnapshot ): CircuitGroupDeleteSubtreeProjectCommand { const command: CircuitGroupDeleteSubtreeProjectCommand = { schemaVersion: circuitGroupSubtreeCommandSchemaVersion, type: circuitGroupDeleteSubtreeCommandType, - payload: { snapshot, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { snapshot }, }; assertCircuitGroupDeleteSubtreeProjectCommand(command); return command; } export function createCircuitGroupRestoreSubtreeProjectCommand( - snapshot: CircuitGroupSubtreeSnapshot, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + snapshot: CircuitGroupSubtreeSnapshot ): CircuitGroupRestoreSubtreeProjectCommand { const command: CircuitGroupRestoreSubtreeProjectCommand = { schemaVersion: circuitGroupSubtreeCommandSchemaVersion, type: circuitGroupRestoreSubtreeCommandType, - payload: { snapshot, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { snapshot }, }; assertCircuitGroupRestoreSubtreeProjectCommand(command); return command; @@ -80,12 +76,11 @@ function assertCommand( command.schemaVersion !== circuitGroupSubtreeCommandSchemaVersion || command.type !== type || !isPlainObject(command.payload) || - Object.keys(command.payload).some((key) => key !== "snapshot" && key !== "externalObjects") + Object.keys(command.payload).length !== 1 ) { 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 292c776..5260c4b 100644 --- a/src/domain/models/circuit-structure-project-command.model.ts +++ b/src/domain/models/circuit-structure-project-command.model.ts @@ -3,8 +3,6 @@ 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 { @@ -39,13 +37,11 @@ export interface CircuitSnapshot { export interface CircuitInsertCommandPayload { circuit: CircuitSnapshot; - externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitDeleteCommandPayload { circuitId: string; expectedCircuitListId: string; - externalObjects?: ExternalObjectLinkSnapshotTransition[]; } export interface CircuitInsertProjectCommand @@ -65,13 +61,12 @@ export type CircuitStructureProjectCommand = | CircuitDeleteProjectCommand; export function createCircuitInsertProjectCommand( - circuit: CircuitSnapshot, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + circuit: CircuitSnapshot ): CircuitInsertProjectCommand { const command: CircuitInsertProjectCommand = { schemaVersion: circuitStructureCommandSchemaVersion, type: circuitInsertCommandType, - payload: { circuit, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { circuit }, }; assertCircuitInsertProjectCommand(command); return command; @@ -79,13 +74,12 @@ export function createCircuitInsertProjectCommand( export function createCircuitDeleteProjectCommand( circuitId: string, - expectedCircuitListId: string, - externalObjects?: ExternalObjectLinkSnapshotTransition[] + expectedCircuitListId: string ): CircuitDeleteProjectCommand { const command: CircuitDeleteProjectCommand = { schemaVersion: circuitStructureCommandSchemaVersion, type: circuitDeleteCommandType, - payload: { circuitId, expectedCircuitListId, ...(externalObjects?.length ? { externalObjects } : {}) }, + payload: { circuitId, expectedCircuitListId }, }; assertCircuitDeleteProjectCommand(command); return command; @@ -174,7 +168,6 @@ export function assertCircuitInsertProjectCommand( } rowIds.add(row.id); } - assertExternalObjectLinkTransitions(command.payload.externalObjects); } export function assertCircuitDeleteProjectCommand( @@ -194,7 +187,6 @@ 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 fd1bd2c..71fb743 100644 --- a/src/domain/models/circuit-tree.model.ts +++ b/src/domain/models/circuit-tree.model.ts @@ -20,7 +20,6 @@ export interface CircuitTreeDeviceRow { remark?: string; overriddenFields?: string; rowTotalPower: number; - externalObjectCount?: number; } export interface CircuitTreeCircuit { @@ -41,10 +40,7 @@ export interface CircuitTreeCircuit { isReserve: boolean; remark?: string; circuitTotalPower: number; - circuitApparentPower: number; - circuitCosPhi: number; deviceRows: CircuitTreeDeviceRow[]; - downstreamBoardLoads: CircuitTreeDownstreamBoardLoad[]; protectionDevice?: CircuitTreeProtectionDevice; } @@ -63,11 +59,6 @@ export interface CircuitTreeSectionBlock { export interface CircuitTreeResponse { circuitListId: string; - distributionBoardId: string; - distributionBoardName: string; - distributionBoardNumber?: string; - distributionBoardSupplyType?: DistributionBoardSupplyType; - feedingReference?: CircuitTreeFeedingReference; currentRevision: number; singlePhaseVoltageV: number; threePhaseVoltageV: number; @@ -79,36 +70,7 @@ export interface CircuitTreeResponse { footerComponents: CircuitTreeComponent[]; } -export interface CircuitTreeDownstreamBoardLoad { - distributionBoardId: string; - name: string; - boardNumber?: string; - supplyType?: DistributionBoardSupplyType; - activePowerKw: number; - apparentPowerKva: number; - cosPhi: number; -} - -export interface CircuitTreeFeedingReference { - distributionBoardId: string; - circuitListId: string; - distributionBoardName: string; - distributionBoardNumber?: string; - circuitId?: string; - circuitEquipmentIdentifier?: string; - circuitDisplayName?: string; - circuitCategory?: CircuitGroupCategory; -} - -export interface ProjectCircuitTreesResponse { - currentRevision: number; - trees: CircuitTreeResponse[]; -} - import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; -import type { - DistributionBoardSupplyType, -} from "../../shared/constants/distribution-board.js"; import type { DistributionBoardComponentPlacement, DistributionBoardComponentRole, 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 deleted file mode 100644 index a1fc035..0000000 --- a/src/domain/models/distribution-board-feeder-circuit-project-command.model.ts +++ /dev/null @@ -1,132 +0,0 @@ -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/models/distribution-board-project-command.model.ts b/src/domain/models/distribution-board-project-command.model.ts index 961cf53..2e917d0 100644 --- a/src/domain/models/distribution-board-project-command.model.ts +++ b/src/domain/models/distribution-board-project-command.model.ts @@ -9,18 +9,16 @@ import type { SerializedProjectCommand } from "./project-command.model.js"; export const distributionBoardUpdateCommandType = "distribution-board.update" as const; -// Version 2 adds logical feeding references. Version-1 commands remain -// executable and can only change the fields they originally knew. -export const distributionBoardUpdateCommandSchemaVersion = 2 as const; -const legacyDistributionBoardUpdateCommandSchemaVersion = 1 as const; +// The info-card fields were added additively to schema version 1: every +// previously stored command remains valid, and the inverse is still derived +// from the persisted row for exactly the changed fields. +export const distributionBoardUpdateCommandSchemaVersion = 1 as const; export interface DistributionBoardUpdateValues extends Record { floorId: string | null; supplyType: DistributionBoardSupplyType | null; simultaneityFactor: number; - feedingDistributionBoardId: string | null; - feedingCircuitId: string | null; } export type DistributionBoardUpdateField = @@ -43,20 +41,16 @@ export interface DistributionBoardUpdateCommandPayload { export interface DistributionBoardUpdateProjectCommand extends SerializedProjectCommand { - schemaVersion: - | typeof legacyDistributionBoardUpdateCommandSchemaVersion - | typeof distributionBoardUpdateCommandSchemaVersion; + schemaVersion: typeof distributionBoardUpdateCommandSchemaVersion; type: typeof distributionBoardUpdateCommandType; } export function createDistributionBoardUpdateProjectCommand( distributionBoardId: string, - patch: DistributionBoardUpdatePatch, - schemaVersion: DistributionBoardUpdateProjectCommand["schemaVersion"] = - distributionBoardUpdateCommandSchemaVersion + patch: DistributionBoardUpdatePatch ): DistributionBoardUpdateProjectCommand { const command: DistributionBoardUpdateProjectCommand = { - schemaVersion, + schemaVersion: distributionBoardUpdateCommandSchemaVersion, type: distributionBoardUpdateCommandType, payload: { distributionBoardId, @@ -74,8 +68,7 @@ export function assertDistributionBoardUpdateProjectCommand( command: SerializedProjectCommand ): asserts command is DistributionBoardUpdateProjectCommand { if ( - (command.schemaVersion !== legacyDistributionBoardUpdateCommandSchemaVersion && - command.schemaVersion !== distributionBoardUpdateCommandSchemaVersion) || + command.schemaVersion !== distributionBoardUpdateCommandSchemaVersion || command.type !== distributionBoardUpdateCommandType || !isPlainObject(command.payload) ) { @@ -100,12 +93,7 @@ export function assertDistributionBoardUpdateProjectCommand( (change.field !== "floorId" && change.field !== "supplyType" && change.field !== "simultaneityFactor" && - change.field !== "feedingDistributionBoardId" && - change.field !== "feedingCircuitId" && !isInfoField(change.field)) || - (command.schemaVersion === legacyDistributionBoardUpdateCommandSchemaVersion && - (change.field === "feedingDistributionBoardId" || - change.field === "feedingCircuitId")) || seen.has(change.field) ) { throw new Error( @@ -117,9 +105,7 @@ export function assertDistributionBoardUpdateProjectCommand( } else if (change.field === "floorId") { if ( change.value !== null && - (typeof change.value !== "string" || - !change.value.trim() || - change.value !== change.value.trim()) + (typeof change.value !== "string" || !change.value.trim()) ) { throw new Error("floorId must be a non-empty string or null."); } @@ -132,16 +118,6 @@ export function assertDistributionBoardUpdateProjectCommand( ) { throw new Error("supplyType is invalid."); } - } else if ( - change.field === "feedingDistributionBoardId" || - change.field === "feedingCircuitId" - ) { - if ( - change.value !== null && - (typeof change.value !== "string" || !change.value.trim()) - ) { - throw new Error(`${change.field} must be a non-empty string or null.`); - } } else if ( typeof change.value !== "number" || !Number.isFinite(change.value) || diff --git a/src/domain/models/distribution-board-subtree-snapshot.model.ts b/src/domain/models/distribution-board-subtree-snapshot.model.ts index 700a52b..a0269fc 100644 --- a/src/domain/models/distribution-board-subtree-snapshot.model.ts +++ b/src/domain/models/distribution-board-subtree-snapshot.model.ts @@ -74,8 +74,6 @@ export interface DistributionBoardSubtreeSnapshot { floorId: string | null; supplyType: DistributionBoardSupplyType | null; simultaneityFactor: number; - feedingDistributionBoardId: string | null; - feedingCircuitId: string | null; } & Record; circuitList: { id: string; @@ -186,9 +184,6 @@ export function normalizeDistributionBoardSubtreeSnapshot( for (const field of distributionBoardInfoFields) { board[field] = board[field] ?? null; } - board.feedingDistributionBoardId = - board.feedingDistributionBoardId ?? null; - board.feedingCircuitId = board.feedingCircuitId ?? null; return { ...snapshot, distributionBoard: board }; } @@ -232,18 +227,6 @@ export function assertDistributionBoardSubtreeSnapshot( assertNullableString(board[field], `distributionBoard.${field}`); } } - if (board.feedingDistributionBoardId !== undefined) { - assertNullableString( - board.feedingDistributionBoardId, - "distributionBoard.feedingDistributionBoardId" - ); - } - if (board.feedingCircuitId !== undefined) { - assertNullableString( - board.feedingCircuitId, - "distributionBoard.feedingCircuitId" - ); - } for (const field of [ "id", "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 new file mode 100644 index 0000000..bb87342 --- /dev/null +++ b/src/domain/models/external-csv-configuration-project-command.model.ts @@ -0,0 +1,94 @@ +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-follow-up-import-project-command.model.ts b/src/domain/models/external-follow-up-import-project-command.model.ts deleted file mode 100644 index f9581a2..0000000 --- a/src/domain/models/external-follow-up-import-project-command.model.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { assertExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration.js"; -import type { ExternalModelStateSnapshot } from "../../external-model/domain/external-model-contracts.js"; -import type { ExternalModelConfigurationSnapshot } from "./external-model-configuration-project-command.model.js"; -import { assertCircuitDeviceRowInsertProjectCommand, circuitDeviceRowInsertCommandType, circuitDeviceRowStructureCommandSchemaVersion, type CircuitDeviceRowSnapshot } from "./circuit-device-row-structure-project-command.model.js"; -import type { SerializedProjectCommand } from "./project-command.model.js"; -import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; - -export const externalFollowUpImportCommandType = "external-import.apply-follow-up" as const; -export const externalFollowUpImportCommandSchemaVersion = 1 as const; - -export interface ExternalFollowUpImportPayload { - expectedConfiguration: ExternalModelConfigurationSnapshot; - targetConfiguration: ExternalModelConfigurationSnapshot; - expectedState: ExternalModelStateSnapshot; - targetState: ExternalModelStateSnapshot; - rows: Array<{ expected: CircuitDeviceRowSnapshot; target: CircuitDeviceRowSnapshot }>; -} - -export interface ExternalFollowUpImportProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof externalFollowUpImportCommandSchemaVersion; - type: typeof externalFollowUpImportCommandType; -} - -export function createExternalFollowUpImportProjectCommand(payload: ExternalFollowUpImportPayload): ExternalFollowUpImportProjectCommand { - const command: ExternalFollowUpImportProjectCommand = { schemaVersion: 1, type: externalFollowUpImportCommandType, payload: { ...payload, rows: payload.rows.map(({ expected, target }) => ({ expected: normalizeRow(expected), target: normalizeRow(target) })) } }; - assertExternalFollowUpImportProjectCommand(command); - return command; -} - -export function invertExternalFollowUpImportProjectCommand(command: ExternalFollowUpImportProjectCommand) { - return createExternalFollowUpImportProjectCommand({ - expectedConfiguration: command.payload.targetConfiguration, - targetConfiguration: command.payload.expectedConfiguration, - expectedState: command.payload.targetState, - targetState: command.payload.expectedState, - rows: command.payload.rows.map(({ expected, target }) => ({ expected: target, target: expected })), - }); -} - -export function assertExternalFollowUpImportProjectCommand(command: SerializedProjectCommand): asserts command is ExternalFollowUpImportProjectCommand { - if (command.schemaVersion !== 1 || command.type !== externalFollowUpImportCommandType || !isRecord(command.payload)) throw new Error("Nicht unterstützter Revit-Folgeimport-Command."); - if (Object.keys(command.payload).sort().join(",") !== "expectedConfiguration,expectedState,rows,targetConfiguration,targetState" || !Array.isArray(command.payload.rows)) throw new Error("Der Revit-Folgeimport-Command ist unvollständig."); - const expectedConfiguration = parseConfiguration(command.payload.expectedConfiguration); - const targetConfiguration = parseConfiguration(command.payload.targetConfiguration); - if (expectedConfiguration.id !== targetConfiguration.id || expectedConfiguration.projectId !== targetConfiguration.projectId) throw new Error("Der Folgeimport darf die Konfigurationsidentität nicht ändern."); - const expectedState = parseExternalModelStateSnapshot(command.payload.expectedState); - const targetState = parseExternalModelStateSnapshot(command.payload.targetState); - if (!expectedState.source || !targetState.source || expectedState.source.id !== targetState.source.id || expectedState.source.projectId !== targetState.source.projectId) throw new Error("Der Folgeimport benötigt dieselbe Revit-Quelle auf beiden Seiten."); - const batchDelta = targetState.importBatches.length - expectedState.importBatches.length; - if (Math.abs(batchDelta) !== 1) throw new Error("Der Folgeimport muss genau einen Importbatch hinzufügen oder entfernen."); - const larger = batchDelta > 0 ? targetState : expectedState; - const smaller = batchDelta > 0 ? expectedState : targetState; - const largerConfiguration = batchDelta > 0 ? targetConfiguration : expectedConfiguration; - const addedBatch = larger.importBatches.at(-1)!; - if (addedBatch.importKind !== "follow_up" || addedBatch.configurationSnapshot === null || addedBatch.originalContentBase64 === null || addedBatch.document === null) throw new Error("Der Folgeimport-Batch ist unvollständig."); - if (canonical(addedBatch.configurationSnapshot) !== canonical(largerConfiguration.configuration)) throw new Error("Die Konfigurationskopie des Folgeimports stimmt nicht mit dem Ziel überein."); - if (larger.importBatches.length !== smaller.importBatches.length + 1 || smaller.importBatches.some((batch, index) => !sameBatchMetadata(batch, larger.importBatches[index]))) throw new Error("Der Folgeimport darf bestehende Importbatch-Metadaten nicht verändern."); - const largerObjectById = new Map(larger.objects.map((object) => [object.id, object])); - for (const object of smaller.objects) { - const next = largerObjectById.get(object.id); - if (!next || next.worksharingId !== object.worksharingId || next.sourceId !== object.sourceId || next.circuitDeviceRowId !== object.circuitDeviceRowId || next.linkedProjectDeviceId !== object.linkedProjectDeviceId) throw new Error("Der Folgeimport darf bestehende Objektidentitäten oder Links nicht verändern."); - } - const smallerIds = new Set(smaller.objects.map((object) => object.id)); - if (larger.objects.some((object) => !smallerIds.has(object.id) && (object.circuitDeviceRowId !== null || object.presenceStatus !== "present" || object.lastSeenImportBatchId !== addedBatch.id))) throw new Error("Neue Folgeimportobjekte müssen unverknüpft und vorhanden sein."); - if (larger.objects.filter((object) => object.presenceStatus === "present" && object.lastSeenImportBatchId === addedBatch.id).length !== addedBatch.objectCount) throw new Error("Die Objektzahl des Folgeimportbatches ist inkonsistent."); - const largerMappings = new Map(larger.roomMappings.map((mapping) => [mapping.id, mapping])); - if (smaller.roomMappings.some((mapping) => canonical(mapping) !== canonical(largerMappings.get(mapping.id)))) throw new Error("Der Folgeimport darf bestehende Raumzuordnungen nicht verändern."); - const rowIds = new Set(); - for (const transition of command.payload.rows) { - if (!isRecord(transition)) throw new Error("Ungültiger Gerätezeilenübergang im Folgeimport."); - const expected = parseRow(transition.expected); const target = parseRow(transition.target); - if (expected.id !== target.id || rowIds.has(expected.id) || expected.manualQuantity !== target.manualQuantity) throw new Error("Ungültige Gerätezeilenidentität im Folgeimport."); - const expectedRest = { ...expected, quantity: 0 }; const targetRest = { ...target, quantity: 0 }; - if (canonical(expectedRest) !== canonical(targetRest) || expected.quantity === target.quantity) throw new Error("Der Folgeimport darf an Gerätezeilen nur die Gesamtmenge ändern."); - rowIds.add(expected.id); - } -} - -function parseConfiguration(value: unknown): ExternalModelConfigurationSnapshot { if (!isRecord(value) || typeof value.id !== "string" || typeof value.projectId !== "string") throw new Error("Ungültige Revit-Konfiguration im Folgeimport."); assertExternalModelConfiguration(value.configuration); return value as unknown as ExternalModelConfigurationSnapshot; } -function normalizeRow(row: CircuitDeviceRowSnapshot): CircuitDeviceRowSnapshot { return { ...row, manualQuantity: row.manualQuantity ?? row.quantity }; } -function parseRow(value: unknown): CircuitDeviceRowSnapshot { const envelope = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowInsertCommandType, payload: { row: value } }; assertCircuitDeviceRowInsertProjectCommand(envelope); return envelope.payload.row; } -function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } -function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`; return JSON.stringify(value); } -function sameBatchMetadata(left: ExternalModelStateSnapshot["importBatches"][number], right: ExternalModelStateSnapshot["importBatches"][number] | undefined) { if (!right) return false; return left.id === right.id && left.projectId === right.projectId && left.sourceId === right.sourceId && left.importKind === right.importKind && left.importedAtIso === right.importedAtIso && left.fileName === right.fileName && left.sha256 === right.sha256 && left.objectCount === right.objectCount; } diff --git a/src/domain/models/external-initial-import-project-command.model.ts b/src/domain/models/external-initial-import-project-command.model.ts index c63ae43..2004cfc 100644 --- a/src/domain/models/external-initial-import-project-command.model.ts +++ b/src/domain/models/external-initial-import-project-command.model.ts @@ -1,34 +1,30 @@ 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 externalInitialImportCommandType = + "external-import.apply-initial" as const; export const externalInitialImportCommandSchemaVersion = 1 as const; export interface ExternalInitialImportPayload { - expectedConfiguration: ExternalModelConfigurationSnapshot | null; - targetConfiguration: ExternalModelConfigurationSnapshot | null; - expectedState: ExternalModelStateSnapshot; - targetState: ExternalModelStateSnapshot; + expected: ExternalModelStateSnapshot; + target: ExternalModelStateSnapshot; } -export interface ExternalInitialImportProjectCommand extends SerializedProjectCommand { +export interface ExternalInitialImportProjectCommand + extends SerializedProjectCommand { schemaVersion: typeof externalInitialImportCommandSchemaVersion; type: typeof externalInitialImportCommandType; } export function createExternalInitialImportProjectCommand( - expectedConfiguration: ExternalModelConfigurationSnapshot | null, - targetConfiguration: ExternalModelConfigurationSnapshot | null, - expectedState: ExternalModelStateSnapshot, - targetState: ExternalModelStateSnapshot + expected: ExternalModelStateSnapshot, + target: ExternalModelStateSnapshot ): ExternalInitialImportProjectCommand { const command: ExternalInitialImportProjectCommand = { schemaVersion: externalInitialImportCommandSchemaVersion, type: externalInitialImportCommandType, - payload: { expectedConfiguration, targetConfiguration, expectedState, targetState }, + payload: { expected, target }, }; assertExternalInitialImportProjectCommand(command); return command; @@ -37,21 +33,22 @@ export function createExternalInitialImportProjectCommand( 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."); + 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 keys = Object.keys(command.payload).sort().join(","); - if (keys !== "expectedConfiguration,expectedState,targetConfiguration,targetState") { - throw new Error("Der Revit-Erstimport-Command ist unvollständig."); + 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."); } - 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); + assertPopulatedInitialState(expectedIsEmpty ? target : expected); } export function createEmptyExternalModelState(): ExternalModelStateSnapshot { @@ -59,47 +56,79 @@ export function createEmptyExternalModelState(): ExternalModelStateSnapshot { } 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); + return ( + state.source === null && + state.importBatches.length === 0 && + state.roomMappings.length === 0 && + state.objects.length === 0 + ); } 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."); + 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 || batch.configurationSnapshot === null || batch.originalContentBase64 === null || batch.document === null || batch.objectCount !== state.objects.length) { - throw new Error("Der Erstimport-Batch ist unvollständig."); + 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); + 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 || roomKeys.has(mapping.normalizedSourceRoomKey)) throw new Error("Ungültige oder doppelte Quellraumzuordnung."); + 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); - const worksharingIds = new Set(); + 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("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."); + 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 }>) { +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("Doppelte ID im Revit-Erstimport."); ids.add(entry.id); } + 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); } + +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 deleted file mode 100644 index e606b6a..0000000 --- a/src/domain/models/external-model-configuration-project-command.model.ts +++ /dev/null @@ -1,88 +0,0 @@ -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/external-object-delete-missing-project-command.model.ts b/src/domain/models/external-object-delete-missing-project-command.model.ts deleted file mode 100644 index ddb7d63..0000000 --- a/src/domain/models/external-object-delete-missing-project-command.model.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { ExternalModelObjectSnapshot } from "../../external-model/domain/external-model-contracts.js"; -import type { SerializedProjectCommand } from "./project-command.model.js"; -import { parseExternalModelStateSnapshot } from "./project-state-snapshot.model.js"; -import { assertCircuitDeviceRowInsertProjectCommand, circuitDeviceRowInsertCommandType, circuitDeviceRowStructureCommandSchemaVersion, type CircuitDeviceRowSnapshot } from "./circuit-device-row-structure-project-command.model.js"; - -export const externalObjectDeleteMissingCommandType = "external-model-object.delete-missing" as const; -type ObjectTransition = { expected: ExternalModelObjectSnapshot | null; target: ExternalModelObjectSnapshot | null }; -export interface ExternalObjectDeleteMissingProjectCommand extends SerializedProjectCommand<{ objects: ObjectTransition[]; rows: Array<{ expected: CircuitDeviceRowSnapshot; target: CircuitDeviceRowSnapshot }> }> { - schemaVersion: 1; - type: typeof externalObjectDeleteMissingCommandType; -} - -export function createExternalObjectDeleteMissingProjectCommand(payload: ExternalObjectDeleteMissingProjectCommand["payload"]): ExternalObjectDeleteMissingProjectCommand { - const command: ExternalObjectDeleteMissingProjectCommand = { schemaVersion: 1, type: externalObjectDeleteMissingCommandType, payload }; - assertExternalObjectDeleteMissingProjectCommand(command); - return command; -} - -export function invertExternalObjectDeleteMissingProjectCommand(command: ExternalObjectDeleteMissingProjectCommand) { - return createExternalObjectDeleteMissingProjectCommand({ - objects: command.payload.objects.map(({ expected, target }) => ({ expected: target, target: expected })), - rows: command.payload.rows.map(({ expected, target }) => ({ expected: target, target: expected })), - }); -} - -export function assertExternalObjectDeleteMissingProjectCommand(command: SerializedProjectCommand): asserts command is ExternalObjectDeleteMissingProjectCommand { - if (command.schemaVersion !== 1 || command.type !== externalObjectDeleteMissingCommandType || !isRecord(command.payload) || !Array.isArray(command.payload.objects) || !Array.isArray(command.payload.rows) || command.payload.objects.length === 0) throw new Error("Nicht unterstützter Command zum Löschen fehlender Revit-Objekte."); - const objectIds = new Set(); - let deletion: boolean | null = null; - for (const transition of command.payload.objects) { - if (!isRecord(transition) || (transition.expected === null) === (transition.target === null)) throw new Error("Ungültiger Löschübergang für ein Revit-Objekt."); - const object = parseObject(transition.expected ?? transition.target); - if (object.presenceStatus !== "missing" || objectIds.has(object.id)) throw new Error("Nur eindeutig fehlende Revit-Objekte dürfen gelöscht werden."); - const nextDeletion = transition.target === null; - if (deletion !== null && deletion !== nextDeletion) throw new Error("Löschen und Wiederherstellen dürfen nicht gemischt werden."); - deletion = nextDeletion; - objectIds.add(object.id); - } - const affectedRowIds = new Set(command.payload.objects.flatMap(({ expected, target }) => (expected ?? target)!.circuitDeviceRowId ? [(expected ?? target)!.circuitDeviceRowId!] : [])); - const rowIds = new Set(); - for (const transition of command.payload.rows) { - if (!isRecord(transition)) throw new Error("Ungültiger Gerätezeilenübergang."); - const expected = parseRow(transition.expected); const target = parseRow(transition.target); - if (expected.id !== target.id || rowIds.has(expected.id) || expected.manualQuantity !== target.manualQuantity) throw new Error("Ungültige Gerätezeilenidentität."); - if (canonical({ ...expected, quantity: 0 }) !== canonical({ ...target, quantity: 0 }) || expected.quantity === target.quantity) throw new Error("Beim Löschen fehlender Objekte darf nur die Gesamtmenge geändert werden."); - rowIds.add(expected.id); - } - if (canonical([...affectedRowIds].sort()) !== canonical([...rowIds].sort())) throw new Error("Die Mengenübergänge der betroffenen Gerätezeilen sind unvollständig."); -} - -function parseObject(value: unknown) { return parseExternalModelStateSnapshot({ source: null, importBatches: [], roomMappings: [], objects: [value] }).objects[0]!; } -function parseRow(value: unknown) { const envelope = { schemaVersion: circuitDeviceRowStructureCommandSchemaVersion, type: circuitDeviceRowInsertCommandType, payload: { row: value } }; assertCircuitDeviceRowInsertProjectCommand(envelope); return envelope.payload.row; } -function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } -function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`; return JSON.stringify(value); } 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 e7a3e23..b34a449 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, distributionBoardId: null }; - const targetRest = { ...target, circuitDeviceRowId: null, distributionBoardId: null }; + const expectedRest = { ...expected, circuitDeviceRowId: null }; + const targetRest = { ...target, circuitDeviceRowId: 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 6bae039..d0416dd 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, distributionBoardId: null }; - const targetRest = { ...target, circuitDeviceRowId: null, distributionBoardId: null }; + const expectedRest = { ...expected, circuitDeviceRowId: null }; + const targetRest = { ...target, circuitDeviceRowId: 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-planning-project-command.model.ts b/src/domain/models/external-object-planning-project-command.model.ts deleted file mode 100644 index f31d126..0000000 --- a/src/domain/models/external-object-planning-project-command.model.ts +++ /dev/null @@ -1,30 +0,0 @@ -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/models/external-object-row-assignment-project-command.model.ts b/src/domain/models/external-object-row-assignment-project-command.model.ts index cb4ae97..a45fe31 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."); } - assertOnlyFieldsChanged( + assertOnlyFieldChanged( expected as unknown as Record, target as unknown as Record, - new Set(["circuitDeviceRowId", "distributionBoardId", "linkedProjectDeviceId", "planningValues", "overriddenFields"]), + "circuitDeviceRowId", "external object" ); if (expected.circuitDeviceRowId) affectedRowIds.add(expected.circuitDeviceRowId); @@ -161,22 +161,11 @@ 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 }; - for (const field of allowedFields) { - delete expectedRest[field]; - delete targetRest[field]; - } + delete expectedRest[allowedField]; + delete targetRest[allowedField]; if (canonicalJson(expectedRest) !== canonicalJson(targetRest)) { throw new Error(`Row assignment may only change the ${label} assignment state.`); } diff --git a/src/domain/models/project-location-structure-project-command.model.ts b/src/domain/models/project-location-structure-project-command.model.ts index 8580527..616add9 100644 --- a/src/domain/models/project-location-structure-project-command.model.ts +++ b/src/domain/models/project-location-structure-project-command.model.ts @@ -1,235 +1,101 @@ import crypto from "node:crypto"; import type { SerializedProjectCommand } from "./project-command.model.js"; -export const projectBuildingInsertCommandType = "project-building.insert" as const; -export const projectBuildingDeleteCommandType = "project-building.delete" as const; -export const projectBuildingUpdateCommandType = "project-building.update" as const; export const projectFloorInsertCommandType = "project-floor.insert" as const; export const projectFloorDeleteCommandType = "project-floor.delete" as const; export const projectFloorUpdateCommandType = "project-floor.update" as const; export const projectRoomInsertCommandType = "project-room.insert" as const; export const projectRoomDeleteCommandType = "project-room.delete" as const; export const projectRoomUpdateCommandType = "project-room.update" as const; -/** Building commands and legacy floor/room commands. */ export const projectLocationStructureCommandSchemaVersion = 1 as const; -/** - * Floor commands carry `buildingId` since version 2. Version 1 floor - * commands stay executable from persisted history: they were recorded before - * buildings existed, so they are upgraded with `buildingId = null`. - */ -export const projectFloorCommandSchemaVersion = 2 as const; -const legacyProjectFloorCommandSchemaVersion = 1 as const; -/** Room commands carry `areaM2` since version 2. */ -export const projectRoomCommandSchemaVersion = 2 as const; -const legacyProjectRoomCommandSchemaVersion = 1 as const; - -export interface ProjectBuildingSnapshot { - id: string; - projectId: string; - name: string; - sortOrder: number; -} export interface ProjectFloorSnapshot { id: string; projectId: string; name: string; sortOrder: number; - buildingId: string | null; } -export type LegacyProjectFloorSnapshot = Omit; - export interface ProjectRoomSnapshot { id: string; projectId: string; floorId: string | null; roomNumber: string; roomName: string; - areaM2: number | null; -} - -export type LegacyProjectRoomSnapshot = Omit; - -interface ProjectBuildingStructureCommandPayload { - building: ProjectBuildingSnapshot; } interface ProjectFloorStructureCommandPayload { floor: ProjectFloorSnapshot; } -interface LegacyProjectFloorStructureCommandPayload { - floor: LegacyProjectFloorSnapshot; -} - interface ProjectRoomStructureCommandPayload { room: ProjectRoomSnapshot; } -interface LegacyProjectRoomStructureCommandPayload { - room: LegacyProjectRoomSnapshot; -} - -interface ProjectBuildingUpdateCommandPayload { - expected: ProjectBuildingSnapshot; - target: ProjectBuildingSnapshot; -} - interface ProjectFloorUpdateCommandPayload { expected: ProjectFloorSnapshot; target: ProjectFloorSnapshot; } -interface LegacyProjectFloorUpdateCommandPayload { - expected: LegacyProjectFloorSnapshot; - target: LegacyProjectFloorSnapshot; -} - interface ProjectRoomUpdateCommandPayload { expected: ProjectRoomSnapshot; target: ProjectRoomSnapshot; } -interface LegacyProjectRoomUpdateCommandPayload { - expected: LegacyProjectRoomSnapshot; - target: LegacyProjectRoomSnapshot; -} - -export interface ProjectBuildingInsertProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof projectLocationStructureCommandSchemaVersion; - type: typeof projectBuildingInsertCommandType; -} - -export interface ProjectBuildingDeleteProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof projectLocationStructureCommandSchemaVersion; - type: typeof projectBuildingDeleteCommandType; -} - -export interface ProjectBuildingUpdateProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof projectLocationStructureCommandSchemaVersion; - type: typeof projectBuildingUpdateCommandType; -} - export interface ProjectFloorInsertProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectFloorCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectFloorInsertCommandType; } export interface ProjectFloorDeleteProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectFloorCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectFloorDeleteCommandType; } export interface ProjectFloorUpdateProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectFloorCommandSchemaVersion; - type: typeof projectFloorUpdateCommandType; -} - -export interface LegacyProjectFloorInsertProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectFloorCommandSchemaVersion; - type: typeof projectFloorInsertCommandType; -} - -export interface LegacyProjectFloorDeleteProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectFloorCommandSchemaVersion; - type: typeof projectFloorDeleteCommandType; -} - -export interface LegacyProjectFloorUpdateProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectFloorCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectFloorUpdateCommandType; } export interface ProjectRoomInsertProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectRoomCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectRoomInsertCommandType; } export interface ProjectRoomDeleteProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectRoomCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectRoomDeleteCommandType; } export interface ProjectRoomUpdateProjectCommand extends SerializedProjectCommand { - schemaVersion: typeof projectRoomCommandSchemaVersion; - type: typeof projectRoomUpdateCommandType; -} - -export interface LegacyProjectRoomInsertProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectRoomCommandSchemaVersion; - type: typeof projectRoomInsertCommandType; -} - -export interface LegacyProjectRoomDeleteProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectRoomCommandSchemaVersion; - type: typeof projectRoomDeleteCommandType; -} - -export interface LegacyProjectRoomUpdateProjectCommand - extends SerializedProjectCommand { - schemaVersion: typeof legacyProjectRoomCommandSchemaVersion; + schemaVersion: typeof projectLocationStructureCommandSchemaVersion; type: typeof projectRoomUpdateCommandType; } export type ProjectLocationStructureProjectCommand = - | ProjectBuildingInsertProjectCommand - | ProjectBuildingDeleteProjectCommand - | ProjectBuildingUpdateProjectCommand | ProjectFloorInsertProjectCommand | ProjectFloorDeleteProjectCommand | ProjectFloorUpdateProjectCommand - | LegacyProjectFloorInsertProjectCommand - | LegacyProjectFloorDeleteProjectCommand - | LegacyProjectFloorUpdateProjectCommand | ProjectRoomInsertProjectCommand | ProjectRoomDeleteProjectCommand - | ProjectRoomUpdateProjectCommand - | LegacyProjectRoomInsertProjectCommand - | LegacyProjectRoomDeleteProjectCommand - | LegacyProjectRoomUpdateProjectCommand; - -export function createProjectBuildingSnapshot( - projectId: string, - name: string, - sortOrder: number -): ProjectBuildingSnapshot { - const building: ProjectBuildingSnapshot = { - id: crypto.randomUUID(), - projectId, - name: name.trim(), - sortOrder, - }; - assertProjectBuildingSnapshot(building); - return building; -} + | ProjectRoomUpdateProjectCommand; export function createProjectFloorSnapshot( projectId: string, name: string, - sortOrder: number, - buildingId: string | null = null + sortOrder: number ): ProjectFloorSnapshot { const floor: ProjectFloorSnapshot = { id: crypto.randomUUID(), projectId, name: name.trim(), sortOrder, - buildingId: buildingId?.trim() || null, }; assertProjectFloorSnapshot(floor); return floor; @@ -241,7 +107,6 @@ export function createProjectRoomSnapshot( floorId?: string; roomNumber: string; roomName: string; - areaM2?: number | null; } ): ProjectRoomSnapshot { const room: ProjectRoomSnapshot = { @@ -250,52 +115,17 @@ export function createProjectRoomSnapshot( floorId: input.floorId?.trim() || null, roomNumber: input.roomNumber.trim(), roomName: input.roomName.trim(), - areaM2: input.areaM2 ?? null, }; assertProjectRoomSnapshot(room); return room; } -export function createProjectBuildingInsertProjectCommand( - building: ProjectBuildingSnapshot -): ProjectBuildingInsertProjectCommand { - assertProjectBuildingSnapshot(building); - return { - schemaVersion: projectLocationStructureCommandSchemaVersion, - type: projectBuildingInsertCommandType, - payload: { building }, - }; -} - -export function createProjectBuildingDeleteProjectCommand( - building: ProjectBuildingSnapshot -): ProjectBuildingDeleteProjectCommand { - assertProjectBuildingSnapshot(building); - return { - schemaVersion: projectLocationStructureCommandSchemaVersion, - type: projectBuildingDeleteCommandType, - payload: { building }, - }; -} - -export function createProjectBuildingUpdateProjectCommand( - expected: ProjectBuildingSnapshot, - target: ProjectBuildingSnapshot -): ProjectBuildingUpdateProjectCommand { - assertMatchingBuildingUpdate(expected, target); - return { - schemaVersion: projectLocationStructureCommandSchemaVersion, - type: projectBuildingUpdateCommandType, - payload: { expected, target }, - }; -} - export function createProjectFloorInsertProjectCommand( floor: ProjectFloorSnapshot ): ProjectFloorInsertProjectCommand { assertProjectFloorSnapshot(floor); return { - schemaVersion: projectFloorCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectFloorInsertCommandType, payload: { floor }, }; @@ -306,7 +136,7 @@ export function createProjectFloorDeleteProjectCommand( ): ProjectFloorDeleteProjectCommand { assertProjectFloorSnapshot(floor); return { - schemaVersion: projectFloorCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectFloorDeleteCommandType, payload: { floor }, }; @@ -317,7 +147,7 @@ export function createProjectRoomInsertProjectCommand( ): ProjectRoomInsertProjectCommand { assertProjectRoomSnapshot(room); return { - schemaVersion: projectRoomCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectRoomInsertCommandType, payload: { room }, }; @@ -328,7 +158,7 @@ export function createProjectRoomDeleteProjectCommand( ): ProjectRoomDeleteProjectCommand { assertProjectRoomSnapshot(room); return { - schemaVersion: projectRoomCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectRoomDeleteCommandType, payload: { room }, }; @@ -340,7 +170,7 @@ export function createProjectFloorUpdateProjectCommand( ): ProjectFloorUpdateProjectCommand { assertMatchingFloorUpdate(expected, target); return { - schemaVersion: projectFloorCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectFloorUpdateCommandType, payload: { expected, target }, }; @@ -352,49 +182,15 @@ export function createProjectRoomUpdateProjectCommand( ): ProjectRoomUpdateProjectCommand { assertMatchingRoomUpdate(expected, target); return { - schemaVersion: projectRoomCommandSchemaVersion, + schemaVersion: projectLocationStructureCommandSchemaVersion, type: projectRoomUpdateCommandType, payload: { expected, target }, }; } -export function assertProjectBuildingInsertProjectCommand( - command: SerializedProjectCommand -): asserts command is ProjectBuildingInsertProjectCommand { - assertProjectBuildingStructureProjectCommand( - command, - projectBuildingInsertCommandType - ); -} - -export function assertProjectBuildingDeleteProjectCommand( - command: SerializedProjectCommand -): asserts command is ProjectBuildingDeleteProjectCommand { - assertProjectBuildingStructureProjectCommand( - command, - projectBuildingDeleteCommandType - ); -} - -export function assertProjectBuildingUpdateProjectCommand( - command: SerializedProjectCommand -): asserts command is ProjectBuildingUpdateProjectCommand { - if ( - command.schemaVersion !== projectLocationStructureCommandSchemaVersion || - command.type !== projectBuildingUpdateCommandType || - !isPlainObject(command.payload) || - Object.keys(command.payload).length !== 2 - ) { - throw new Error("Unsupported project-building update command."); - } - assertMatchingBuildingUpdate(command.payload.expected, command.payload.target); -} - export function assertProjectFloorInsertProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectFloorInsertProjectCommand - | LegacyProjectFloorInsertProjectCommand { +): asserts command is ProjectFloorInsertProjectCommand { assertProjectFloorStructureProjectCommand( command, projectFloorInsertCommandType @@ -403,9 +199,7 @@ export function assertProjectFloorInsertProjectCommand( export function assertProjectFloorDeleteProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectFloorDeleteProjectCommand - | LegacyProjectFloorDeleteProjectCommand { +): asserts command is ProjectFloorDeleteProjectCommand { assertProjectFloorStructureProjectCommand( command, projectFloorDeleteCommandType @@ -414,9 +208,7 @@ export function assertProjectFloorDeleteProjectCommand( export function assertProjectRoomInsertProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectRoomInsertProjectCommand - | LegacyProjectRoomInsertProjectCommand { +): asserts command is ProjectRoomInsertProjectCommand { assertProjectRoomStructureProjectCommand( command, projectRoomInsertCommandType @@ -425,9 +217,7 @@ export function assertProjectRoomInsertProjectCommand( export function assertProjectRoomDeleteProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectRoomDeleteProjectCommand - | LegacyProjectRoomDeleteProjectCommand { +): asserts command is ProjectRoomDeleteProjectCommand { assertProjectRoomStructureProjectCommand( command, projectRoomDeleteCommandType @@ -436,161 +226,32 @@ export function assertProjectRoomDeleteProjectCommand( export function assertProjectFloorUpdateProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectFloorUpdateProjectCommand - | LegacyProjectFloorUpdateProjectCommand { +): asserts command is ProjectFloorUpdateProjectCommand { if ( + command.schemaVersion !== projectLocationStructureCommandSchemaVersion || command.type !== projectFloorUpdateCommandType || !isPlainObject(command.payload) || Object.keys(command.payload).length !== 2 ) { throw new Error("Unsupported project-floor update command."); } - if (command.schemaVersion === legacyProjectFloorCommandSchemaVersion) { - assertMatchingFloorUpdate( - upgradeLegacyFloorSnapshot(command.payload.expected), - upgradeLegacyFloorSnapshot(command.payload.target) - ); - return; - } - if (command.schemaVersion !== projectFloorCommandSchemaVersion) { - throw new Error("Unsupported project-floor update command."); - } assertMatchingFloorUpdate(command.payload.expected, command.payload.target); } export function assertProjectRoomUpdateProjectCommand( command: SerializedProjectCommand -): asserts command is - | ProjectRoomUpdateProjectCommand - | LegacyProjectRoomUpdateProjectCommand { +): asserts command is ProjectRoomUpdateProjectCommand { if ( + command.schemaVersion !== projectLocationStructureCommandSchemaVersion || command.type !== projectRoomUpdateCommandType || !isPlainObject(command.payload) || Object.keys(command.payload).length !== 2 ) { throw new Error("Unsupported project-room update command."); } - if (command.schemaVersion === legacyProjectRoomCommandSchemaVersion) { - assertMatchingRoomUpdate( - upgradeLegacyRoomSnapshot(command.payload.expected), - upgradeLegacyRoomSnapshot(command.payload.target) - ); - return; - } - if (command.schemaVersion !== projectRoomCommandSchemaVersion) { - throw new Error("Unsupported project-room update command."); - } assertMatchingRoomUpdate(command.payload.expected, command.payload.target); } -/** - * Upgrades a (validated) floor command of any supported version to the - * current version. Version 1 commands predate buildings; their floors had no - * building, so `buildingId` becomes null. - */ -export function upgradeProjectFloorCommand( - command: - | ProjectFloorInsertProjectCommand - | LegacyProjectFloorInsertProjectCommand -): ProjectFloorInsertProjectCommand; -export function upgradeProjectFloorCommand( - command: - | ProjectFloorDeleteProjectCommand - | LegacyProjectFloorDeleteProjectCommand -): ProjectFloorDeleteProjectCommand; -export function upgradeProjectFloorCommand( - command: - | ProjectFloorUpdateProjectCommand - | LegacyProjectFloorUpdateProjectCommand -): ProjectFloorUpdateProjectCommand; -export function upgradeProjectFloorCommand( - command: - | ProjectFloorInsertProjectCommand - | ProjectFloorDeleteProjectCommand - | ProjectFloorUpdateProjectCommand - | LegacyProjectFloorInsertProjectCommand - | LegacyProjectFloorDeleteProjectCommand - | LegacyProjectFloorUpdateProjectCommand -) { - if (command.schemaVersion === projectFloorCommandSchemaVersion) { - return command; - } - switch (command.type) { - case projectFloorInsertCommandType: - return createProjectFloorInsertProjectCommand( - upgradeLegacyFloorSnapshot(command.payload.floor) - ); - case projectFloorDeleteCommandType: - return createProjectFloorDeleteProjectCommand( - upgradeLegacyFloorSnapshot(command.payload.floor) - ); - case projectFloorUpdateCommandType: - return createProjectFloorUpdateProjectCommand( - upgradeLegacyFloorSnapshot(command.payload.expected), - upgradeLegacyFloorSnapshot(command.payload.target) - ); - } -} - -/** Upgrades persisted version-1 room commands with an empty area. */ -export function upgradeProjectRoomCommand( - command: - | ProjectRoomInsertProjectCommand - | LegacyProjectRoomInsertProjectCommand -): ProjectRoomInsertProjectCommand; -export function upgradeProjectRoomCommand( - command: - | ProjectRoomDeleteProjectCommand - | LegacyProjectRoomDeleteProjectCommand -): ProjectRoomDeleteProjectCommand; -export function upgradeProjectRoomCommand( - command: - | ProjectRoomUpdateProjectCommand - | LegacyProjectRoomUpdateProjectCommand -): ProjectRoomUpdateProjectCommand; -export function upgradeProjectRoomCommand( - command: - | ProjectRoomInsertProjectCommand - | ProjectRoomDeleteProjectCommand - | ProjectRoomUpdateProjectCommand - | LegacyProjectRoomInsertProjectCommand - | LegacyProjectRoomDeleteProjectCommand - | LegacyProjectRoomUpdateProjectCommand -) { - if (command.schemaVersion === projectRoomCommandSchemaVersion) { - return command; - } - switch (command.type) { - case projectRoomInsertCommandType: - return createProjectRoomInsertProjectCommand( - upgradeLegacyRoomSnapshot(command.payload.room) - ); - case projectRoomDeleteCommandType: - return createProjectRoomDeleteProjectCommand( - upgradeLegacyRoomSnapshot(command.payload.room) - ); - case projectRoomUpdateCommandType: - return createProjectRoomUpdateProjectCommand( - upgradeLegacyRoomSnapshot(command.payload.expected), - upgradeLegacyRoomSnapshot(command.payload.target) - ); - } -} - -function assertMatchingBuildingUpdate(expected: unknown, target: unknown) { - assertProjectBuildingSnapshot(expected); - assertProjectBuildingSnapshot(target); - if ( - expected.id !== target.id || - expected.projectId !== target.projectId || - expected.sortOrder !== target.sortOrder || - expected.name === target.name - ) { - throw new Error("Project-building update must change only the name."); - } -} - function assertMatchingFloorUpdate(expected: unknown, target: unknown) { assertProjectFloorSnapshot(expected); assertProjectFloorSnapshot(target); @@ -598,11 +259,9 @@ function assertMatchingFloorUpdate(expected: unknown, target: unknown) { expected.id !== target.id || expected.projectId !== target.projectId || expected.sortOrder !== target.sortOrder || - (expected.name === target.name && expected.buildingId === target.buildingId) + expected.name === target.name ) { - throw new Error( - "Project-floor update must change only the name or the building." - ); + throw new Error("Project-floor update must change only the name."); } } @@ -618,77 +277,27 @@ function assertMatchingRoomUpdate(expected: unknown, target: unknown) { } } -export function assertProjectBuildingSnapshot( - building: unknown -): asserts building is ProjectBuildingSnapshot { - if (!isPlainObject(building) || Object.keys(building).length !== 4) { - throw new Error("Project-building snapshot is invalid."); - } - assertNormalizedNonEmptyString(building.id, "building.id"); - assertNormalizedNonEmptyString(building.projectId, "building.projectId"); - assertNormalizedNonEmptyString(building.name, "building.name"); - assertSortOrder(building.sortOrder, "building.sortOrder"); -} - export function assertProjectFloorSnapshot( floor: unknown ): asserts floor is ProjectFloorSnapshot { - if (!isPlainObject(floor) || Object.keys(floor).length !== 5) { - throw new Error("Project-floor snapshot is invalid."); - } - assertLegacyFloorFields(floor); - if (floor.buildingId !== null) { - assertNormalizedNonEmptyString(floor.buildingId, "floor.buildingId"); - } -} - -function assertLegacyProjectFloorSnapshot( - floor: unknown -): asserts floor is LegacyProjectFloorSnapshot { if (!isPlainObject(floor) || Object.keys(floor).length !== 4) { throw new Error("Project-floor snapshot is invalid."); } - assertLegacyFloorFields(floor); -} - -function assertLegacyFloorFields(floor: Record) { assertNormalizedNonEmptyString(floor.id, "floor.id"); assertNormalizedNonEmptyString(floor.projectId, "floor.projectId"); assertNormalizedNonEmptyString(floor.name, "floor.name"); - assertSortOrder(floor.sortOrder, "floor.sortOrder"); -} - -function upgradeLegacyFloorSnapshot(floor: unknown): ProjectFloorSnapshot { - assertLegacyProjectFloorSnapshot(floor); - return { ...floor, buildingId: null }; + if ( + typeof floor.sortOrder !== "number" || + !Number.isSafeInteger(floor.sortOrder) || + floor.sortOrder < 0 + ) { + throw new Error("floor.sortOrder must be a non-negative integer."); + } } export function assertProjectRoomSnapshot( room: unknown ): asserts room is ProjectRoomSnapshot { - if (!isPlainObject(room) || Object.keys(room).length !== 6) { - throw new Error("Project-room snapshot is invalid."); - } - assertNormalizedNonEmptyString(room.id, "room.id"); - assertNormalizedNonEmptyString(room.projectId, "room.projectId"); - if (room.floorId !== null) { - assertNormalizedNonEmptyString(room.floorId, "room.floorId"); - } - assertNormalizedNonEmptyString(room.roomNumber, "room.roomNumber"); - assertNormalizedNonEmptyString(room.roomName, "room.roomName"); - if ( - room.areaM2 !== null && - (typeof room.areaM2 !== "number" || - !Number.isFinite(room.areaM2) || - room.areaM2 < 0) - ) { - throw new Error("room.areaM2 must be null or a non-negative finite number."); - } -} - -function assertLegacyProjectRoomSnapshot( - room: unknown -): asserts room is LegacyProjectRoomSnapshot { if (!isPlainObject(room) || Object.keys(room).length !== 5) { throw new Error("Project-room snapshot is invalid."); } @@ -701,28 +310,6 @@ function assertLegacyProjectRoomSnapshot( assertNormalizedNonEmptyString(room.roomName, "room.roomName"); } -function upgradeLegacyRoomSnapshot(room: unknown): ProjectRoomSnapshot { - assertLegacyProjectRoomSnapshot(room); - return { ...room, areaM2: null }; -} - -function assertProjectBuildingStructureProjectCommand( - command: SerializedProjectCommand, - expectedType: - | typeof projectBuildingInsertCommandType - | typeof projectBuildingDeleteCommandType -) { - if ( - command.schemaVersion !== projectLocationStructureCommandSchemaVersion || - command.type !== expectedType || - !isPlainObject(command.payload) || - Object.keys(command.payload).length !== 1 - ) { - throw new Error("Unsupported project-building structure command."); - } - assertProjectBuildingSnapshot(command.payload.building); -} - function assertProjectFloorStructureProjectCommand( command: SerializedProjectCommand, expectedType: @@ -730,19 +317,13 @@ function assertProjectFloorStructureProjectCommand( | typeof projectFloorDeleteCommandType ) { if ( + command.schemaVersion !== projectLocationStructureCommandSchemaVersion || command.type !== expectedType || !isPlainObject(command.payload) || Object.keys(command.payload).length !== 1 ) { throw new Error("Unsupported project-floor structure command."); } - if (command.schemaVersion === legacyProjectFloorCommandSchemaVersion) { - assertLegacyProjectFloorSnapshot(command.payload.floor); - return; - } - if (command.schemaVersion !== projectFloorCommandSchemaVersion) { - throw new Error("Unsupported project-floor structure command."); - } assertProjectFloorSnapshot(command.payload.floor); } @@ -753,32 +334,16 @@ function assertProjectRoomStructureProjectCommand( | typeof projectRoomDeleteCommandType ) { if ( + command.schemaVersion !== projectLocationStructureCommandSchemaVersion || command.type !== expectedType || !isPlainObject(command.payload) || Object.keys(command.payload).length !== 1 ) { throw new Error("Unsupported project-room structure command."); } - if (command.schemaVersion === legacyProjectRoomCommandSchemaVersion) { - assertLegacyProjectRoomSnapshot(command.payload.room); - return; - } - if (command.schemaVersion !== projectRoomCommandSchemaVersion) { - throw new Error("Unsupported project-room structure command."); - } assertProjectRoomSnapshot(command.payload.room); } -function assertSortOrder(value: unknown, field: string) { - if ( - typeof value !== "number" || - !Number.isSafeInteger(value) || - value < 0 - ) { - throw new Error(`${field} must be a non-negative integer.`); - } -} - function assertNormalizedNonEmptyString( value: unknown, field: string diff --git a/src/domain/models/project-state-restore-command.model.ts b/src/domain/models/project-state-restore-command.model.ts index 83b8405..14b876c 100644 --- a/src/domain/models/project-state-restore-command.model.ts +++ b/src/domain/models/project-state-restore-command.model.ts @@ -3,80 +3,32 @@ import { type ProjectStateSnapshot, } from "./project-state-snapshot.model.js"; import type { SerializedProjectCommand } from "./project-command.model.js"; -import { - parseEstimateBalanceSnapshot, -} from "../../estimate-balance/domain/estimate-balance-command.model.js"; -import type { EstimateBalanceSnapshot } from "../../shared/estimate-balance/estimate-balance.js"; export const projectStateRestoreCommandType = "project.restore-state"; -export const projectStateRestoreCommandSchemaVersion = 2 as const; -const snapshotRestoreCommandSchemaVersion = 1 as const; +export const projectStateRestoreCommandSchemaVersion = 1 as const; export interface ProjectStateRestoreCommandPayload { expectedStateSha256: string; targetState: ProjectStateSnapshot; } -export type SnapshotProjectStateRestoreCommand = SerializedProjectCommand< +export type ProjectStateRestoreCommand = SerializedProjectCommand< ProjectStateRestoreCommandPayload -> & { - schemaVersion: typeof snapshotRestoreCommandSchemaVersion; - type: typeof projectStateRestoreCommandType; -}; - -export interface ProjectTransferRestoreCommandPayload - extends ProjectStateRestoreCommandPayload { - expectedEstimateBalances: EstimateBalanceSnapshot[]; - targetEstimateBalances: EstimateBalanceSnapshot[]; -} - -export type ProjectTransferRestoreCommand = SerializedProjectCommand< - ProjectTransferRestoreCommandPayload > & { schemaVersion: typeof projectStateRestoreCommandSchemaVersion; type: typeof projectStateRestoreCommandType; }; -export type ProjectStateRestoreCommand = - | SnapshotProjectStateRestoreCommand - | ProjectTransferRestoreCommand; - export function createProjectStateRestoreCommand( expectedStateSha256: string, targetState: ProjectStateSnapshot ): ProjectStateRestoreCommand { - const command: SnapshotProjectStateRestoreCommand = { - schemaVersion: snapshotRestoreCommandSchemaVersion, - type: projectStateRestoreCommandType, - payload: { - expectedStateSha256, - targetState: parseProjectStateSnapshot(targetState), - }, - }; - assertProjectStateRestoreCommand(command); - return command; -} - -export function createProjectTransferRestoreCommand( - expectedStateSha256: string, - targetState: ProjectStateSnapshot, - expectedEstimateBalances: EstimateBalanceSnapshot[], - targetEstimateBalances: EstimateBalanceSnapshot[] -): ProjectTransferRestoreCommand { - const command: ProjectTransferRestoreCommand = { + const command: ProjectStateRestoreCommand = { schemaVersion: projectStateRestoreCommandSchemaVersion, type: projectStateRestoreCommandType, payload: { expectedStateSha256, targetState: parseProjectStateSnapshot(targetState), - expectedEstimateBalances: parseEstimateBalances( - expectedEstimateBalances, - targetState.project.id - ), - targetEstimateBalances: parseEstimateBalances( - targetEstimateBalances, - targetState.project.id - ), }, }; assertProjectStateRestoreCommand(command); @@ -90,7 +42,10 @@ export function assertProjectStateRestoreCommand( throw new Error("Project state restore command must be an object."); } const command = value as Partial; - if (command.type !== projectStateRestoreCommandType) { + if ( + command.type !== projectStateRestoreCommandType || + command.schemaVersion !== projectStateRestoreCommandSchemaVersion + ) { throw new Error("Unsupported project state restore command."); } if (!command.payload || typeof command.payload !== "object") { @@ -103,43 +58,5 @@ export function assertProjectStateRestoreCommand( ) { throw new Error("Expected project state checksum is invalid."); } - const targetState = parseProjectStateSnapshot(payload.targetState); - if (command.schemaVersion === snapshotRestoreCommandSchemaVersion) { - if (Object.keys(payload).length !== 2) { - throw new Error("Snapshot restore payload contains unknown fields."); - } - return; - } - if (command.schemaVersion !== projectStateRestoreCommandSchemaVersion) { - throw new Error("Unsupported project state restore command."); - } - const transferPayload = payload as Partial; - parseEstimateBalances( - transferPayload.expectedEstimateBalances, - targetState.project.id - ); - parseEstimateBalances( - transferPayload.targetEstimateBalances, - targetState.project.id - ); - if (Object.keys(payload).length !== 4) { - throw new Error("Project transfer restore payload contains unknown fields."); - } -} - -function parseEstimateBalances( - value: unknown, - projectId: string -): EstimateBalanceSnapshot[] { - if (!Array.isArray(value)) { - throw new Error("Project transfer estimate balances must be an array."); - } - const balances = value.map(parseEstimateBalanceSnapshot); - if (balances.some((balance) => balance.projectId !== projectId)) { - throw new Error("Project transfer estimate balance belongs to another project."); - } - if (new Set(balances.map((balance) => balance.id)).size !== balances.length) { - throw new Error("Project transfer contains duplicate estimate balances."); - } - return balances; + parseProjectStateSnapshot(payload.targetState); } diff --git a/src/domain/models/project-state-snapshot.model.ts b/src/domain/models/project-state-snapshot.model.ts index 2296bc1..623a069 100644 --- a/src/domain/models/project-state-snapshot.model.ts +++ b/src/domain/models/project-state-snapshot.model.ts @@ -28,10 +28,6 @@ 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, @@ -39,11 +35,7 @@ import { type ExternalModelStateSnapshot, } from "../../external-model/domain/external-model-contracts.js"; -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; +export const projectStateSnapshotSchemaVersion = 6 as const; const boardInfoProjectStateSnapshotSchemaVersion = 5 as const; const previousProjectStateSnapshotSchemaVersion = 4 as const; const externalModelProjectStateSnapshotSchemaVersion = 3 as const; @@ -118,7 +110,7 @@ const distributionBoardInfoValueSchema = (field: DistributionBoardInfoField) => .max(distributionBoardInfoFieldMaxLengths[field]) .nullable(); -const distributionBoardWithoutFeedingSchema = legacyDistributionBoardSchema +const distributionBoardSchema = legacyDistributionBoardSchema .extend({ boardNumber: distributionBoardInfoValueSchema("boardNumber"), location: distributionBoardInfoValueSchema("location"), @@ -127,13 +119,6 @@ const distributionBoardWithoutFeedingSchema = legacyDistributionBoardSchema }) .strict(); -const distributionBoardSchema = distributionBoardWithoutFeedingSchema - .extend({ - feedingDistributionBoardId: idSchema.nullable(), - feedingCircuitId: idSchema.nullable(), - }) - .strict(); - function withEmptyDistributionBoardInfo( boards: Array> ) { @@ -146,16 +131,6 @@ function withEmptyDistributionBoardInfo( })); } -function withEmptyDistributionBoardFeeding( - boards: Array> -) { - return boards.map((board) => ({ - ...board, - feedingDistributionBoardId: null, - feedingCircuitId: null, - })); -} - const circuitListSchema = z .object({ id: idSchema, @@ -262,7 +237,7 @@ const projectDeviceSchema = z }) .strict(); -const buildingSchema = z +const floorSchema = z .object({ id: idSchema, projectId: idSchema, @@ -271,20 +246,7 @@ const buildingSchema = z }) .strict(); -const legacyFloorSchema = z - .object({ - id: idSchema, - projectId: idSchema, - name: z.string().trim().min(1), - sortOrder: finiteNumberSchema, - }) - .strict(); - -const floorSchema = legacyFloorSchema - .extend({ buildingId: idSchema.nullable() }) - .strict(); - -const legacyRoomSchema = z +const roomSchema = z .object({ id: idSchema, projectId: idSchema, @@ -294,10 +256,6 @@ const legacyRoomSchema = z }) .strict(); -const roomSchema = legacyRoomSchema - .extend({ areaM2: finiteNumberSchema.nonnegative().nullable() }) - .strict(); - const distributionBoardComponentSchema = z .object({ id: idSchema, @@ -428,14 +386,14 @@ const externalCsvDocumentSchema = z.object({ }); }); -const legacyExternalModelSourceSchema = z.object({ +const externalModelSourceSchema = z.object({ id: idSchema, projectId: idSchema, name: z.string().trim().min(1), - sourceType: z.literal("revit_csv"), + sourceType: z.enum(externalModelSourceTypes), }).strict(); -const legacyExternalImportBatchSchema = z.object({ +const externalImportBatchSchema = z.object({ id: idSchema, projectId: idSchema, sourceId: idSchema, @@ -466,7 +424,7 @@ const externalRoomMappingSchema = z.object({ defaultDistributionBoardId: idSchema.nullable(), }).strict(); -const legacyExternalPlanningFieldNames = [ +const externalPlanningFieldNames = [ "displayName", "internalDeviceType", "category", @@ -479,7 +437,7 @@ const legacyExternalPlanningFieldNames = [ "remark", ] as const; -const legacyExternalModelObjectSchema = z.object({ +const externalModelObjectSchema = z.object({ id: idSchema, projectId: idSchema, sourceId: idSchema, @@ -509,170 +467,6 @@ const legacyExternalModelObjectSchema = 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 ), @@ -688,21 +482,7 @@ const externalModelStateSchema = z.object({ importBatches: z.array(externalImportBatchSchema), roomMappings: z.array(externalRoomMappingSchema), objects: z.array(externalModelObjectSchema), -}).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.", - }); - } -}); +}).strict(); export function parseExternalModelStateSnapshot( value: unknown @@ -710,27 +490,13 @@ export function parseExternalModelStateSnapshot( return externalModelStateSchema.parse(value); } -// Versions 1-6 have floors without a building and no building list. Versions -// 1-7 have rooms without an area. -const previousProjectStateSnapshotContents = { +const projectStateSnapshotContents = { circuitLists: z.array(circuitListSchema), circuitSections: z.array(circuitSectionSchema), circuits: z.array(circuitSchema), projectDevices: z.array(projectDeviceSchema), - floors: z.array(legacyFloorSchema), - rooms: z.array(legacyRoomSchema), - distributionBoardComponents: z.array(distributionBoardComponentSchema), - circuitProtectionDevices: z.array(circuitProtectionDeviceSchema), - distributionBoardComponentProtectionDevices: z.array( - componentProtectionDeviceSchema - ), -}; - -const buildingProjectStateSnapshotContents = { - ...previousProjectStateSnapshotContents, - buildings: z.array(buildingSchema), floors: z.array(floorSchema), - rooms: z.array(legacyRoomSchema), + rooms: z.array(roomSchema), distributionBoardComponents: z.array(distributionBoardComponentSchema), circuitProtectionDevices: z.array(circuitProtectionDeviceSchema), distributionBoardComponentProtectionDevices: z.array( @@ -738,74 +504,25 @@ const buildingProjectStateSnapshotContents = { ), }; -const projectStateSnapshotContents = { - ...buildingProjectStateSnapshotContents, - rooms: z.array(roomSchema), -}; - export const projectStateSnapshotSchema = z .object({ schemaVersion: z.literal(projectStateSnapshotSchemaVersion), project: projectSchema, distributionBoards: z.array(distributionBoardSchema), - externalModelConfiguration: externalModelConfigurationSnapshotSchema.nullable(), + externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.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: legacyExternalModelStateSchema, - ...projectStateSnapshotContents, - }) - .strict(); - -const buildingProjectStateSnapshotSchema = z - .object({ - schemaVersion: z.literal(buildingProjectStateSnapshotSchemaVersion), - project: projectSchema, - distributionBoards: z.array(distributionBoardWithoutFeedingSchema), - externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: legacyExternalModelStateSchema, - ...buildingProjectStateSnapshotContents, - }) - .strict(); - -const coverProjectStateSnapshotSchema = z - .object({ - schemaVersion: z.literal(coverProjectStateSnapshotSchemaVersion), - project: projectSchema, - distributionBoards: z.array(distributionBoardWithoutFeedingSchema), - externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: legacyExternalModelStateSchema, - ...previousProjectStateSnapshotContents, - }) - .strict(); - const boardInfoProjectStateSnapshotSchema = z .object({ schemaVersion: z.literal(boardInfoProjectStateSnapshotSchemaVersion), project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: legacyExternalModelStateSchema, - ...previousProjectStateSnapshotContents, + externalModel: externalModelStateSchema, + ...projectStateSnapshotContents, }) .strict(); @@ -815,8 +532,8 @@ const previousProjectStateSnapshotSchema = z project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - externalModel: legacyExternalModelStateSchema, - ...previousProjectStateSnapshotContents, + externalModel: externalModelStateSchema, + ...projectStateSnapshotContents, }) .strict(); @@ -826,7 +543,7 @@ const externalModelProjectStateSnapshotSchema = z project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), externalCsvConfiguration: externalCsvConfigurationSnapshotSchema.nullable(), - ...previousProjectStateSnapshotContents, + ...projectStateSnapshotContents, }) .strict(); @@ -835,7 +552,7 @@ const legacyProjectStateSnapshotSchema = z schemaVersion: z.literal(legacyProjectStateSnapshotSchemaVersion), project: publicBuildingProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), - ...previousProjectStateSnapshotContents, + ...projectStateSnapshotContents, }) .strict(); @@ -844,7 +561,7 @@ const baselineProjectStateSnapshotSchema = z schemaVersion: z.literal(baselineProjectStateSnapshotSchemaVersion), project: previousProjectSchema, distributionBoards: z.array(legacyDistributionBoardSchema), - ...previousProjectStateSnapshotContents, + ...projectStateSnapshotContents, }) .strict(); @@ -852,20 +569,6 @@ export type ProjectStateSnapshot = z.infer< typeof projectStateSnapshotSchema >; -/** - * Stored snapshots of every supported version can be restored: they are - * upgraded to the current version while parsing. - */ -export function isSupportedProjectStateSnapshotSchemaVersion( - schemaVersion: number -): boolean { - return ( - Number.isInteger(schemaVersion) && - schemaVersion >= baselineProjectStateSnapshotSchemaVersion && - schemaVersion <= projectStateSnapshotSchemaVersion - ); -} - export function parseProjectStateSnapshot( value: unknown ): ProjectStateSnapshot { @@ -878,97 +581,6 @@ 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 && - typeof roomArea === "object" && - !Array.isArray(roomArea) && - (roomArea as { schemaVersion?: unknown }).schemaVersion === - roomAreaProjectStateSnapshotSchemaVersion - ) { - const previous = roomAreaProjectStateSnapshotSchema.parse(roomArea); - return { - ...previous, - schemaVersion: legacyCsvProjectStateSnapshotSchemaVersion, - distributionBoards: withEmptyDistributionBoardFeeding( - previous.distributionBoards - ), - }; - } - return roomArea; -} - -function upgradeToRoomAreaProjectStateSnapshot(value: unknown): unknown { - const cover = upgradeToCoverProjectStateSnapshot(value); - if ( - cover !== null && - typeof cover === "object" && - !Array.isArray(cover) && - (cover as { schemaVersion?: unknown }).schemaVersion === - buildingProjectStateSnapshotSchemaVersion - ) { - const previous = buildingProjectStateSnapshotSchema.parse(cover); - return { - ...previous, - schemaVersion: roomAreaProjectStateSnapshotSchemaVersion, - rooms: previous.rooms.map((room) => ({ ...room, areaM2: null })), - }; - } - if ( - cover === null || - typeof cover !== "object" || - Array.isArray(cover) || - (cover as { schemaVersion?: unknown }).schemaVersion !== - coverProjectStateSnapshotSchemaVersion - ) { - return cover; - } - // Every supported version before 7 lacks buildings; its floors had no - // building. Build version 7 first so the room-area upgrade above remains a - // single exact transition. - const previous = coverProjectStateSnapshotSchema.parse(cover); - return upgradeToRoomAreaProjectStateSnapshot({ - ...previous, - schemaVersion: buildingProjectStateSnapshotSchemaVersion, - buildings: [], - floors: previous.floors.map((floor) => ({ ...floor, buildingId: null })), - }); -} - -function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { if ( value === null || typeof value !== "object" || @@ -985,7 +597,7 @@ function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { const previous = boardInfoProjectStateSnapshotSchema.parse(value); return { ...previous, - schemaVersion: coverProjectStateSnapshotSchemaVersion, + schemaVersion: projectStateSnapshotSchemaVersion, project: { ...previous.project, ...emptyProjectCoverValues }, distributionBoards: withEmptyDistributionBoardInfo( previous.distributionBoards @@ -996,7 +608,7 @@ function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { const previous = previousProjectStateSnapshotSchema.parse(value); return { ...previous, - schemaVersion: coverProjectStateSnapshotSchemaVersion, + schemaVersion: projectStateSnapshotSchemaVersion, project: { ...previous.project, ...emptyProjectCoverValues }, distributionBoards: withEmptyDistributionBoardInfo( previous.distributionBoards @@ -1007,7 +619,7 @@ function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { const previous = externalModelProjectStateSnapshotSchema.parse(value); return { ...previous, - schemaVersion: coverProjectStateSnapshotSchemaVersion, + schemaVersion: projectStateSnapshotSchemaVersion, project: { ...previous.project, ...emptyProjectCoverValues }, distributionBoards: withEmptyDistributionBoardInfo( previous.distributionBoards @@ -1019,7 +631,7 @@ function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { const legacy = legacyProjectStateSnapshotSchema.parse(value); return { ...legacy, - schemaVersion: coverProjectStateSnapshotSchemaVersion, + schemaVersion: projectStateSnapshotSchemaVersion, project: { ...legacy.project, ...emptyProjectCoverValues }, distributionBoards: withEmptyDistributionBoardInfo( legacy.distributionBoards @@ -1032,7 +644,7 @@ function upgradeToCoverProjectStateSnapshot(value: unknown): unknown { const baseline = baselineProjectStateSnapshotSchema.parse(value); return { ...baseline, - schemaVersion: coverProjectStateSnapshotSchemaVersion, + schemaVersion: projectStateSnapshotSchemaVersion, project: { ...baseline.project, isPublicBuilding: false, @@ -1057,20 +669,6 @@ 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 { @@ -1132,10 +730,10 @@ function assertProjectStateSnapshotRelations( ) { const projectId = snapshot.project.id; if ( - snapshot.externalModelConfiguration !== null && - snapshot.externalModelConfiguration.projectId !== projectId + snapshot.externalCsvConfiguration !== null && + snapshot.externalCsvConfiguration.projectId !== projectId ) { - throw new Error("Snapshot Revit-XLSX configuration belongs to a different project."); + throw new Error("Snapshot external CSV configuration belongs to a different project."); } const boardIds = uniqueIds( snapshot.distributionBoards, @@ -1153,7 +751,6 @@ function assertProjectStateSnapshotRelations( snapshot.projectDevices, "project device" ); - const buildingIds = uniqueIds(snapshot.buildings, "building"); const floorIds = uniqueIds(snapshot.floors, "floor"); const roomIds = uniqueIds(snapshot.rooms, "room"); const circuitIds = uniqueIds(snapshot.circuits, "circuit"); @@ -1164,15 +761,6 @@ function assertProjectStateSnapshotRelations( const sectionById = new Map( snapshot.circuitSections.map((entry) => [entry.id, entry]) ); - const boardById = new Map( - snapshot.distributionBoards.map((entry) => [entry.id, entry]) - ); - const circuitListById = new Map( - snapshot.circuitLists.map((entry) => [entry.id, entry]) - ); - const circuitById = new Map( - snapshot.circuits.map((entry) => [entry.id, entry]) - ); const componentById = new Map( snapshot.distributionBoardComponents.map((entry) => [ entry.id, @@ -1201,47 +789,6 @@ function assertProjectStateSnapshotRelations( "Snapshot distribution board uses a disabled supply type." ); } - if (board.feedingDistributionBoardId === board.id) { - throw new Error("Snapshot distribution board cannot feed itself."); - } - if (board.feedingDistributionBoardId !== null) { - assertReference( - boardIds, - board.feedingDistributionBoardId, - "feeding distribution board" - ); - } - if (board.feedingCircuitId !== null) { - if (board.feedingDistributionBoardId === null) { - throw new Error( - "Snapshot feeding circuit requires a feeding distribution board." - ); - } - assertReference(circuitIds, board.feedingCircuitId, "feeding circuit"); - const feedingCircuit = circuitById.get(board.feedingCircuitId); - const feedingList = feedingCircuit - ? circuitListById.get(feedingCircuit.circuitListId) - : undefined; - if ( - !feedingList || - feedingList.distributionBoardId !== board.feedingDistributionBoardId - ) { - throw new Error( - "Snapshot feeding circuit belongs to another distribution board." - ); - } - } - } - for (const board of snapshot.distributionBoards) { - const visited = new Set([board.id]); - let currentId = board.feedingDistributionBoardId; - while (currentId !== null) { - if (visited.has(currentId)) { - throw new Error("Snapshot distribution-board feeding graph contains a cycle."); - } - visited.add(currentId); - currentId = boardById.get(currentId)?.feedingDistributionBoardId ?? null; - } } for (const list of snapshot.circuitLists) { assertProjectOwnership(list.projectId, projectId, "circuit list"); @@ -1282,14 +829,8 @@ function assertProjectStateSnapshotRelations( ); } } - for (const building of snapshot.buildings) { - assertProjectOwnership(building.projectId, projectId, "building"); - } for (const floor of snapshot.floors) { assertProjectOwnership(floor.projectId, projectId, "floor"); - if (floor.buildingId !== null) { - assertReference(buildingIds, floor.buildingId, "floor building"); - } } for (const room of snapshot.rooms) { assertProjectOwnership(room.projectId, projectId, "room"); @@ -1476,12 +1017,6 @@ 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"); @@ -1517,23 +1052,17 @@ function assertExternalModelRelations( } } - const worksharingIds = new Set(); - const deviceTypeIds = new Set( - snapshot.externalModelConfiguration.configuration.deviceTypes.map( - (deviceType) => deviceType.id - ) - ); + const ifcGuids = new Set(); 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( - worksharingIds, - object.worksharingId, - "Snapshot contains duplicate external Worksharing-IDs." + ifcGuids, + object.ifcGuid, + "Snapshot contains duplicate external IFCGUIDs." ); - 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 e067896..3f28f51 100644 --- a/src/domain/models/project-transfer.model.ts +++ b/src/domain/models/project-transfer.model.ts @@ -3,12 +3,9 @@ import { projectStateSnapshotSchemaVersion, type ProjectStateSnapshot, } from "./project-state-snapshot.model.js"; -import { parseEstimateBalanceSnapshot } from "../../estimate-balance/domain/estimate-balance-command.model.js"; -import type { EstimateBalanceSnapshot } from "../../shared/estimate-balance/estimate-balance.js"; export const projectTransferFormat = "leistungsbilanz.project" as const; -export const projectTransferFormatVersion = 2 as const; -const legacyProjectTransferFormatVersion = 1 as const; +export const projectTransferFormatVersion = 1 as const; export interface ProjectTransferEnvelope { format: typeof projectTransferFormat; @@ -16,14 +13,12 @@ export interface ProjectTransferEnvelope { exportedAtIso: string; payloadSha256: string; projectState: ProjectStateSnapshot; - estimateBalances: EstimateBalanceSnapshot[]; } export function createProjectTransferEnvelope( exportedAtIso: string, payloadSha256: string, - projectState: ProjectStateSnapshot, - estimateBalances: EstimateBalanceSnapshot[] + projectState: ProjectStateSnapshot ): ProjectTransferEnvelope { return parseProjectTransferEnvelope({ format: projectTransferFormat, @@ -31,7 +26,6 @@ export function createProjectTransferEnvelope( exportedAtIso, payloadSha256, projectState, - estimateBalances, }); } @@ -43,8 +37,7 @@ export function parseProjectTransferEnvelope( } if ( value.format !== projectTransferFormat || - (value.formatVersion !== legacyProjectTransferFormatVersion && - value.formatVersion !== projectTransferFormatVersion) + value.formatVersion !== projectTransferFormatVersion ) { throw new Error("Project transfer format is not supported."); } @@ -64,13 +57,7 @@ export function parseProjectTransferEnvelope( if (projectState.schemaVersion !== projectStateSnapshotSchemaVersion) { throw new Error("Project transfer snapshot version is not supported."); } - const estimateBalances = - value.formatVersion === legacyProjectTransferFormatVersion - ? [] - : parseTransferEstimateBalances(value.estimateBalances, projectState.project.id); - const expectedFieldCount = - value.formatVersion === legacyProjectTransferFormatVersion ? 5 : 6; - if (Object.keys(value).length !== expectedFieldCount) { + if (Object.keys(value).length !== 5) { throw new Error("Project transfer file contains unknown fields."); } return { @@ -79,43 +66,9 @@ export function parseProjectTransferEnvelope( exportedAtIso: value.exportedAtIso, payloadSha256: value.payloadSha256, projectState, - estimateBalances, }; } -export function serializeProjectTransferPayload( - projectState: ProjectStateSnapshot, - estimateBalances: EstimateBalanceSnapshot[] -) { - const parsedState = parseProjectStateSnapshot(projectState); - return JSON.stringify({ - projectState: parsedState, - estimateBalances: parseTransferEstimateBalances( - estimateBalances, - parsedState.project.id - ), - }); -} - -export function remapEstimateBalances( - source: EstimateBalanceSnapshot[], - targetProjectId: string, - createId: () => string -): EstimateBalanceSnapshot[] { - return source.map((balance) => - parseEstimateBalanceSnapshot({ - ...balance, - id: createId(), - projectId: targetProjectId, - groups: balance.groups.map((group) => ({ - ...group, - id: createId(), - rows: group.rows.map((row) => ({ ...row, id: createId() })), - })), - }) - ); -} - export function remapProjectState( source: ProjectStateSnapshot, targetProjectId: string, @@ -131,7 +84,6 @@ export function remapProjectState( createId ); const deviceIds = idMap(source.projectDevices, createId); - const buildingIds = idMap(source.buildings, createId); const floorIds = idMap(source.floors, createId); const roomIds = idMap(source.rooms, createId); const rowIds = new Map( @@ -146,35 +98,16 @@ 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 }, - externalModelConfiguration: - source.externalModelConfiguration === null + externalCsvConfiguration: + source.externalCsvConfiguration === null ? null : { - ...source.externalModelConfiguration, + ...source.externalCsvConfiguration, id: createId(), projectId: targetProjectId, - configuration: remapExternalModelConfiguration( - source.externalModelConfiguration.configuration, - deviceTypeIds, - familyRuleIds - ), }, externalModel: { source: source.externalModel.source === null @@ -189,14 +122,6 @@ 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, @@ -217,7 +142,6 @@ export function remapProjectState( id: requiredId(externalObjectIds, object.id), projectId: targetProjectId, sourceId: externalSourceId!, - deviceTypeId: requiredId(deviceTypeIds, object.deviceTypeId), lastSeenImportBatchId: requiredId( externalBatchIds, object.lastSeenImportBatchId @@ -251,14 +175,6 @@ export function remapProjectState( ...board, id: requiredId(boardIds, board.id), projectId: targetProjectId, - feedingDistributionBoardId: - board.feedingDistributionBoardId === null - ? null - : requiredId(boardIds, board.feedingDistributionBoardId), - feedingCircuitId: - board.feedingCircuitId === null - ? null - : requiredId(circuitIds, board.feedingCircuitId), floorId: board.floorId === null ? null @@ -326,19 +242,10 @@ export function remapProjectState( id: requiredId(deviceIds, device.id), projectId: targetProjectId, })), - buildings: source.buildings.map((building) => ({ - ...building, - id: requiredId(buildingIds, building.id), - projectId: targetProjectId, - })), floors: source.floors.map((floor) => ({ ...floor, id: requiredId(floorIds, floor.id), projectId: targetProjectId, - buildingId: - floor.buildingId === null - ? null - : requiredId(buildingIds, floor.buildingId), })), rooms: source.rooms.map((room) => ({ ...room, @@ -350,36 +257,6 @@ 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 @@ -395,37 +272,6 @@ function requiredId(ids: ReadonlyMap, sourceId: string) { return targetId; } -function parseTransferEstimateBalances( - value: unknown, - projectId: string -): EstimateBalanceSnapshot[] { - if (!Array.isArray(value)) { - throw new Error("Project transfer estimate balances must be an array."); - } - const balances = value.map(parseEstimateBalanceSnapshot); - if (balances.some((balance) => balance.projectId !== projectId)) { - throw new Error("Project transfer estimate balance belongs to another project."); - } - assertUniqueIds(balances.map((balance) => balance.id), "estimate balance"); - assertUniqueIds( - balances.flatMap((balance) => balance.groups.map((group) => group.id)), - "estimate group" - ); - assertUniqueIds( - balances.flatMap((balance) => - balance.groups.flatMap((group) => group.rows.map((row) => row.id)) - ), - "estimate row" - ); - return balances; -} - -function assertUniqueIds(ids: string[], label: string) { - if (new Set(ids).size !== ids.length) { - throw new Error(`Project transfer contains a duplicate ${label} id.`); - } -} - 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 6dd8d8f..f0cb5c9 100644 --- a/src/domain/ports/distribution-board-structure-project-command.store.ts +++ b/src/domain/ports/distribution-board-structure-project-command.store.ts @@ -1,6 +1,5 @@ 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, @@ -36,15 +35,4 @@ export interface DistributionBoardStructureProjectCommandStore { revision: AppendedProjectRevision; inverse: DistributionBoardUpdateProjectCommand; }; - executeFeederCircuit( - input: Omit< - ExecuteDistributionBoardStructureCommandInput, - "command" - > & { - command: DistributionBoardFeederCircuitProjectCommand; - } - ): { - revision: AppendedProjectRevision; - inverse: DistributionBoardFeederCircuitProjectCommand; - }; } diff --git a/src/domain/ports/external-csv-configuration-project-command.store.ts b/src/domain/ports/external-csv-configuration-project-command.store.ts new file mode 100644 index 0000000..0bc74b4 --- /dev/null +++ b/src/domain/ports/external-csv-configuration-project-command.store.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000..a50144b --- /dev/null +++ b/src/domain/ports/external-csv-configuration.reader.ts @@ -0,0 +1,10 @@ +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-follow-up-import-project-command.store.ts b/src/domain/ports/external-follow-up-import-project-command.store.ts deleted file mode 100644 index d39efc9..0000000 --- a/src/domain/ports/external-follow-up-import-project-command.store.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { ExternalFollowUpImportProjectCommand } from "../models/external-follow-up-import-project-command.model.js"; -import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; - -export interface ExternalFollowUpImportProjectCommandStore { - execute(input: { projectId: string; expectedRevision: number; source: ProjectRevisionSource; description?: string; actorId?: string; historyTargetChangeSetId?: string; command: ExternalFollowUpImportProjectCommand }): { revision: AppendedProjectRevision; inverse: ExternalFollowUpImportProjectCommand }; -} diff --git a/src/domain/ports/external-initial-import-project-command.store.ts b/src/domain/ports/external-initial-import-project-command.store.ts index 411d3c3..db1917e 100644 --- a/src/domain/ports/external-initial-import-project-command.store.ts +++ b/src/domain/ports/external-initial-import-project-command.store.ts @@ -10,6 +10,10 @@ export interface ExecuteExternalInitialImportCommandInput { historyTargetChangeSetId?: string; command: ExternalInitialImportProjectCommand; } + export interface ExternalInitialImportProjectCommandStore { - execute(input: ExecuteExternalInitialImportCommandInput): { revision: AppendedProjectRevision; inverse: ExternalInitialImportProjectCommand }; + 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 deleted file mode 100644 index d6dce8c..0000000 --- a/src/domain/ports/external-model-configuration-project-command.store.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 1b54f77..0000000 --- a/src/domain/ports/external-model-configuration.reader.ts +++ /dev/null @@ -1,10 +0,0 @@ -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/ports/external-object-delete-missing-project-command.store.ts b/src/domain/ports/external-object-delete-missing-project-command.store.ts deleted file mode 100644 index d6f2e8f..0000000 --- a/src/domain/ports/external-object-delete-missing-project-command.store.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ExternalObjectDeleteMissingProjectCommand } from "../models/external-object-delete-missing-project-command.model.js"; -import type { AppendedProjectRevision, ProjectRevisionSource } from "./project-revision.store.js"; -export interface ExternalObjectDeleteMissingProjectCommandStore { execute(input: { projectId: string; expectedRevision: number; source: ProjectRevisionSource; description?: string; actorId?: string; historyTargetChangeSetId?: string; command: ExternalObjectDeleteMissingProjectCommand }): { revision: AppendedProjectRevision; inverse: ExternalObjectDeleteMissingProjectCommand }; } diff --git a/src/domain/ports/external-object-planning-project-command.store.ts b/src/domain/ports/external-object-planning-project-command.store.ts deleted file mode 100644 index 19c610b..0000000 --- a/src/domain/ports/external-object-planning-project-command.store.ts +++ /dev/null @@ -1,3 +0,0 @@ -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/ports/user.store.ts b/src/domain/ports/user.store.ts deleted file mode 100644 index 9b80023..0000000 --- a/src/domain/ports/user.store.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { UserRole } from "../../shared/constants/user-roles.js"; - -export interface UserAccount { - id: string; - username: string; - passwordHash: string; - name: string; - role: UserRole; - active: boolean; - mustChangePassword: boolean; - createdAt: Date; - updatedAt: Date; -} - -export interface CreateUserAccount { - username: string; - name: string; - role: UserRole; - passwordHash: string; -} - -export class UsernameAlreadyExistsStoreError extends Error {} -export class LastActiveAdminStoreError extends Error {} - -export interface UserStore { - list(): Promise; - count(): Promise; - findById(userId: string): Promise; - findByUsername(username: string): Promise; - create(input: CreateUserAccount): Promise; - updateRoleAndActive( - userId: string, - patch: { role?: UserRole; active?: boolean } - ): Promise; - setPassword( - userId: string, - passwordHash: string, - mustChangePassword: boolean - ): Promise; -} diff --git a/src/domain/services/project-command.service.ts b/src/domain/services/project-command.service.ts index 960ee64..bee31a3 100644 --- a/src/domain/services/project-command.service.ts +++ b/src/domain/services/project-command.service.ts @@ -45,11 +45,6 @@ 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, @@ -75,18 +70,12 @@ import { type SerializedProjectCommand, } from "../models/project-command.model.js"; import { - assertProjectBuildingDeleteProjectCommand, - assertProjectBuildingInsertProjectCommand, - assertProjectBuildingUpdateProjectCommand, assertProjectFloorDeleteProjectCommand, assertProjectFloorInsertProjectCommand, assertProjectFloorUpdateProjectCommand, assertProjectRoomDeleteProjectCommand, assertProjectRoomInsertProjectCommand, assertProjectRoomUpdateProjectCommand, - projectBuildingDeleteCommandType, - projectBuildingInsertCommandType, - projectBuildingUpdateCommandType, projectFloorDeleteCommandType, projectFloorInsertCommandType, projectFloorUpdateCommandType, @@ -173,21 +162,15 @@ 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 { - assertExternalModelConfigurationUpdateProjectCommand, - externalModelConfigurationUpdateCommandType, -} from "../models/external-model-configuration-project-command.model.js"; -import type { ExternalModelConfigurationProjectCommandStore } from "../ports/external-model-configuration-project-command.store.js"; + 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"; -import { assertExternalFollowUpImportProjectCommand, externalFollowUpImportCommandType } from "../models/external-follow-up-import-project-command.model.js"; -import type { ExternalFollowUpImportProjectCommandStore } from "../ports/external-follow-up-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 { assertExternalObjectDeleteMissingProjectCommand, externalObjectDeleteMissingCommandType } from "../models/external-object-delete-missing-project-command.model.js"; -import type { ExternalObjectDeleteMissingProjectCommandStore } from "../ports/external-object-delete-missing-project-command.store.js"; import { assertExternalObjectRowAssignmentProjectCommand, externalObjectRowAssignmentCommandType, @@ -205,15 +188,6 @@ 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; @@ -249,15 +223,11 @@ export class ProjectCommandService implements ProjectCommandExecutor { private readonly circuitGroupSubtreeStore: CircuitGroupSubtreeProjectCommandStore, private readonly circuitProtectionStore: CircuitProtectionProjectCommandStore, private readonly historyStore: ProjectHistoryStore, - private readonly externalModelConfigurationStore?: ExternalModelConfigurationProjectCommandStore, + private readonly externalCsvConfigurationStore?: ExternalCsvConfigurationProjectCommandStore, + private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore, private readonly externalObjectRowAssignmentStore?: ExternalObjectRowAssignmentProjectCommandStore, private readonly externalObjectNewRowStore?: ExternalObjectNewRowProjectCommandStore, - private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore, - private readonly estimateBalanceStore?: EstimateBalanceProjectCommandStore, - private readonly externalInitialImportStore?: ExternalInitialImportProjectCommandStore, - private readonly externalObjectPlanningStore?: ExternalObjectPlanningProjectCommandStore, - private readonly externalFollowUpImportStore?: ExternalFollowUpImportProjectCommandStore, - private readonly externalObjectDeleteMissingStore?: ExternalObjectDeleteMissingProjectCommandStore + private readonly externalObjectNewCircuitStore?: ExternalObjectNewCircuitProjectCommandStore ) {} executeUser( @@ -317,8 +287,6 @@ export class ProjectCommandService implements ProjectCommandExecutor { ); } - assertNoLegacyExternalCsvHistoryCommand(step.command); - return this.dispatch({ ...input, source: direction, @@ -434,14 +402,6 @@ 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 @@ -532,18 +492,6 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } - case projectBuildingInsertCommandType: { - assertProjectBuildingInsertProjectCommand(input.command); - return this.projectLocationStructureStore.execute({ ...input, command: input.command }).revision; - } - case projectBuildingDeleteCommandType: { - assertProjectBuildingDeleteProjectCommand(input.command); - return this.projectLocationStructureStore.execute({ ...input, command: input.command }).revision; - } - case projectBuildingUpdateCommandType: { - assertProjectBuildingUpdateProjectCommand(input.command); - return this.projectLocationStructureStore.execute({ ...input, command: input.command }).revision; - } case projectFloorInsertCommandType: { assertProjectFloorInsertProjectCommand(input.command); return this.projectLocationStructureStore.execute({ @@ -636,12 +584,12 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } - case externalModelConfigurationUpdateCommandType: { - assertExternalModelConfigurationUpdateProjectCommand(input.command); - if (!this.externalModelConfigurationStore) { - throw new Error("External model configuration store is not available."); + case externalCsvConfigurationUpdateCommandType: { + assertExternalCsvConfigurationUpdateProjectCommand(input.command); + if (!this.externalCsvConfigurationStore) { + throw new Error("External CSV configuration store is not available."); } - return this.externalModelConfigurationStore.execute({ + return this.externalCsvConfigurationStore.execute({ ...input, command: input.command, }).revision; @@ -656,21 +604,6 @@ export class ProjectCommandService implements ProjectCommandExecutor { command: input.command, }).revision; } - case externalFollowUpImportCommandType: { - assertExternalFollowUpImportProjectCommand(input.command); - if (!this.externalFollowUpImportStore) throw new Error("External follow-up import store is not available."); - return this.externalFollowUpImportStore.execute({ ...input, 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 externalObjectDeleteMissingCommandType: { - assertExternalObjectDeleteMissingProjectCommand(input.command); - if (!this.externalObjectDeleteMissingStore) throw new Error("External missing-object delete store is not available."); - return this.externalObjectDeleteMissingStore.execute({ ...input, command: input.command }).revision; - } case externalObjectRowAssignmentCommandType: { assertExternalObjectRowAssignmentProjectCommand(input.command); if (!this.externalObjectRowAssignmentStore) { @@ -703,24 +636,6 @@ 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({ @@ -746,16 +661,3 @@ 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/domain/services/user.service.ts b/src/domain/services/user.service.ts deleted file mode 100644 index 7ea2f0b..0000000 --- a/src/domain/services/user.service.ts +++ /dev/null @@ -1,156 +0,0 @@ -import type { UserRole } from "../../shared/constants/user-roles.js"; -import { createLogger } from "../../shared/logging/logger.js"; -import { - LastActiveAdminStoreError, - UsernameAlreadyExistsStoreError, - type UserStore, -} from "../ports/user.store.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 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."); - } -} - -export interface PasswordHasher { - hash(password: string): Promise; - verify(password: string, storedHash: string): Promise; -} - -export interface UserServiceOptions { - bootstrap: { username: string; password: string } | null; -} - -export class UserService { - private dummyHash: Promise | null = null; - - constructor( - private readonly repository: UserStore, - private readonly options: UserServiceOptions, - private readonly passwords: PasswordHasher - ) {} - - /** - * 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 { - // Warm the dummy hash at startup so even the first unknown-user login - // costs one scrypt run, not two. - await this.getDummyHash(); - const existingCount = await this.repository.count(); - if (existingCount > 0) return; - if (!this.options.bootstrap) { - logger.warn( - "no users exist and AUTH_BOOTSTRAP_USERNAME/AUTH_BOOTSTRAP_PASSWORT are not set - nobody can sign in" - ); - return; - } - const passwordHash = await this.passwords.hash(this.options.bootstrap.password); - await this.repository.create({ - username: this.options.bootstrap.username, - name: "Administrator", - role: "admin", - passwordHash, - }); - logger.info("bootstrap admin created", { - username: this.options.bootstrap.username, - }); - } - - async authenticate(username: string, password: string) { - const user = await this.repository.findByUsername(username); - // 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 this.passwords.verify(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 this.passwords.hash(input.initialPassword); - 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 (error instanceof UsernameAlreadyExistsStoreError) throw new UsernameTakenError(); - throw error; - } - } - - async updateRoleAndActive(userId: string, patch: { role?: UserRole; active?: boolean }) { - try { - return await this.repository.updateRoleAndActive(userId, patch); - } catch (error) { - if (error instanceof LastActiveAdminStoreError) throw new LastAdminError(); - throw error; - } - } - - /** Admin-triggered reset with a new start password; forces a change on next login. */ - async resetPassword(userId: string, newPassword: string) { - const passwordHash = await this.passwords.hash(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 this.passwords.verify(currentPassword, user.passwordHash); - if (!currentMatches) throw new WrongPasswordError(); - if (newPassword === currentPassword) throw new PasswordUnchangedError(); - const passwordHash = await this.passwords.hash(newPassword); - return this.repository.setPassword(userId, passwordHash, false); - } - - private getDummyHash(): Promise { - this.dummyHash ??= this.passwords.hash("dummy-password-for-constant-time-login"); - return this.dummyHash; - } -} diff --git a/src/estimate-balance/api/estimate-balance-request.schemas.ts b/src/estimate-balance/api/estimate-balance-request.schemas.ts deleted file mode 100644 index d1f1a5f..0000000 --- a/src/estimate-balance/api/estimate-balance-request.schemas.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index f1b0da8..0000000 --- a/src/estimate-balance/domain/estimate-balance-command.model.ts +++ /dev/null @@ -1,318 +0,0 @@ -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), - 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, - 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 deleted file mode 100644 index e5f7e04..0000000 --- a/src/estimate-balance/domain/estimate-balance-project-command.store.ts +++ /dev/null @@ -1,24 +0,0 @@ -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/external-model/application/external-circuit-list-objects.ts b/src/external-model/application/external-circuit-list-objects.ts new file mode 100644 index 0000000..43f57c5 --- /dev/null +++ b/src/external-model/application/external-circuit-list-objects.ts @@ -0,0 +1,88 @@ +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 new file mode 100644 index 0000000..57aa480 --- /dev/null +++ b/src/external-model/application/external-csv-preview.ts @@ -0,0 +1,91 @@ +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 new file mode 100644 index 0000000..bc916f8 --- /dev/null +++ b/src/external-model/application/external-initial-import-plan.ts @@ -0,0 +1,164 @@ +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 new file mode 100644 index 0000000..be0925e --- /dev/null +++ b/src/external-model/application/external-initial-import-target.ts @@ -0,0 +1,130 @@ +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/application/external-xlsx-follow-up-import.ts b/src/external-model/application/external-xlsx-follow-up-import.ts deleted file mode 100644 index 9e0293a..0000000 --- a/src/external-model/application/external-xlsx-follow-up-import.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; -import type { ExternalModelObjectSnapshot, ExternalModelObjectSourceValues, ExternalModelStateSnapshot } from "../domain/external-model-contracts.js"; -import type { ExternalXlsxReturnValues, ExternalXlsxScalar } from "../xlsx/external-xlsx-contracts.js"; -import { createExternalXlsxInitialImportPlan, type ExternalInitialImportCatalogs, type ExternalInitialImportPlan, type ExternalInitialImportProjectedObject } from "./external-xlsx-initial-import.js"; - -export const externalSourceDecisionFields = ["ifcGuid", "roomNumber", "roomName", "familyAndType", "selectionMarker", "socketCount", "sourceRemark"] as const; -export type ExternalSourceDecisionField = (typeof externalSourceDecisionFields)[number]; - -export interface ExternalFollowUpChange { - objectId: string; - worksharingId: string; - familyAndType: string; - changedFields: ExternalSourceDecisionField[]; - previousQuantity: number; - suggestedQuantity: number; - circuitDeviceRowId: string | null; -} - -export interface ExternalXlsxFollowUpPlan extends ExternalInitialImportPlan { - newObjectCount: number; - changedObjectCount: number; - unchangedObjectCount: number; - missingObjectCount: number; - returnDeviationCount: number; - newObjectWorksharingIds: string[]; - newSourceRoomKeys: string[]; - newFamilyAndTypes: string[]; - changes: ExternalFollowUpChange[]; - missingObjects: Array<{ objectId: string; worksharingId: string; familyAndType: string; circuitDeviceRowId: string | null }>; - returnDeviations: Array<{ objectId: string; worksharingId: string; fields: string[] }>; -} - -export async function createExternalXlsxFollowUpImportPlan(input: { - fileName: string; - bytes: Uint8Array; - configuration: ExternalModelConfiguration; - catalogs: ExternalInitialImportCatalogs; - currentState: ExternalModelStateSnapshot; - currentReturnValuesByObjectId: ReadonlyMap; -}): Promise<{ plan: ExternalXlsxFollowUpPlan; document: Awaited>["document"] }> { - if (!input.currentState.source || input.currentState.importBatches.length === 0) throw new Error("Für den Folgeimport fehlt ein bestehender Revit-Import."); - const parsed = await createExternalXlsxInitialImportPlan(input); - const existingByWorksharingId = new Map(input.currentState.objects.map((object) => [object.worksharingId, object])); - const incomingByWorksharingId = new Map(parsed.plan.objects.map((object) => [object.worksharingId, object])); - const newObjects: ExternalInitialImportProjectedObject[] = []; - const changes: ExternalFollowUpChange[] = []; - let unchangedObjectCount = 0; - const returnDeviations: ExternalXlsxFollowUpPlan["returnDeviations"] = []; - - for (const incoming of parsed.plan.objects) { - const existing = existingByWorksharingId.get(incoming.worksharingId); - if (!existing) { newObjects.push(incoming); continue; } - const changedFields = changedSourceFields(existing, incoming); - if (changedFields.length) { - changes.push({ - objectId: existing.id, - worksharingId: existing.worksharingId, - familyAndType: incoming.sourceValues.familyAndType, - changedFields, - previousQuantity: existing.planningValues.effectiveQuantity, - suggestedQuantity: incoming.suggestedPlanningValues.effectiveQuantity, - circuitDeviceRowId: existing.circuitDeviceRowId, - }); - } else unchangedObjectCount += 1; - const returnFields = changedReturnFields(input.currentReturnValuesByObjectId.get(existing.id), incoming.sourceValues); - if (returnFields.length) returnDeviations.push({ objectId: existing.id, worksharingId: existing.worksharingId, fields: returnFields }); - } - - const missingObjects = input.currentState.objects - .filter((object) => !incomingByWorksharingId.has(object.worksharingId)) - .map((object) => ({ objectId: object.id, worksharingId: object.worksharingId, familyAndType: object.acceptedSourceValues.familyAndType, circuitDeviceRowId: object.circuitDeviceRowId })); - const existingRoomKeys = new Set(input.currentState.roomMappings.map((mapping) => mapping.normalizedSourceRoomKey)); - const newSourceRoomKeys = parsed.plan.sourceRooms.map((room) => room.sourceRoomKey).filter((key) => !existingRoomKeys.has(key)); - const newFamilyAndTypes = [...new Set(newObjects.map((object) => object.sourceValues.familyAndType))].sort((a, b) => a.localeCompare(b, "de")); - return { - document: parsed.document, - plan: { - ...parsed.plan, - newObjectCount: newObjects.length, - changedObjectCount: changes.length, - unchangedObjectCount, - missingObjectCount: missingObjects.length, - returnDeviationCount: returnDeviations.length, - newObjectWorksharingIds: newObjects.map((object) => object.worksharingId), - newSourceRoomKeys, - newFamilyAndTypes, - changes, - missingObjects, - returnDeviations, - }, - }; -} - -function changedSourceFields(existing: ExternalModelObjectSnapshot, incoming: ExternalInitialImportProjectedObject) { - const fields: ExternalSourceDecisionField[] = []; - if (!sameScalar(existing.ifcGuid, incoming.ifcGuid)) fields.push("ifcGuid"); - for (const field of externalSourceDecisionFields.slice(1) as readonly (keyof ExternalModelObjectSourceValues)[]) { - if (!sameScalar(existing.acceptedSourceValues[field], incoming.sourceValues[field])) fields.push(field as ExternalSourceDecisionField); - } - return fields; -} - -function changedReturnFields(expected: ExternalXlsxReturnValues | undefined, incoming: ExternalModelObjectSourceValues) { - if (!expected) return []; - const fields = ["circuitCombined", "boardName", "circuitIdentifier", "designation", "electricalPowerW", "voltageV", "currentA"] as const; - return fields.filter((field) => !sameScalar(expected[field], incoming[field])); -} - -function sameScalar(left: ExternalXlsxScalar | undefined, right: ExternalXlsxScalar | undefined) { - return normalize(left) === normalize(right); -} - -function normalize(value: ExternalXlsxScalar | undefined): string | number | boolean { - if (value === null || value === undefined || value === "") return ""; - if (typeof value !== "string") return value; - const trimmed = value.trim(); - if (!trimmed) return ""; - const numeric = Number(trimmed.replace(",", ".")); - return Number.isFinite(numeric) ? numeric : trimmed; -} diff --git a/src/external-model/application/external-xlsx-follow-up-target.ts b/src/external-model/application/external-xlsx-follow-up-target.ts deleted file mode 100644 index db62b52..0000000 --- a/src/external-model/application/external-xlsx-follow-up-target.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type { CircuitDeviceRowSnapshot } from "../../domain/models/circuit-device-row-structure-project-command.model.js"; -import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; -import type { ExternalModelObjectSnapshot, ExternalModelObjectSourceValues, ExternalModelStateSnapshot } from "../domain/external-model-contracts.js"; -import type { ExternalXlsxDocument } from "../xlsx/external-xlsx-contracts.js"; -import type { ExternalFamilyProjectDeviceDecision, ExternalRoomDecision } from "./external-xlsx-initial-import-target.js"; -import type { ExternalSourceDecisionField, ExternalXlsxFollowUpPlan } from "./external-xlsx-follow-up-import.js"; - -export interface ExternalSourceChangeDecision { objectId: string; accept: boolean; } -export interface ExternalRowQuantityTransition { expected: CircuitDeviceRowSnapshot; target: CircuitDeviceRowSnapshot; } - -export function buildExternalXlsxFollowUpTarget(input: { - projectId: string; - expectedRevision: number; - importedAtIso: string; - configuration: ExternalModelConfiguration; - originalContentBase64: string; - document: ExternalXlsxDocument; - plan: ExternalXlsxFollowUpPlan; - currentState: ExternalModelStateSnapshot; - sourceChangeDecisions: ExternalSourceChangeDecision[]; - roomDecisions: ExternalRoomDecision[]; - familyProjectDeviceDecisions: ExternalFamilyProjectDeviceDecision[]; - objectsWithoutRoomDefaultDistributionBoardId: string | null; - rowsById: ReadonlyMap; - createId: () => string; -}): { targetState: ExternalModelStateSnapshot; rowTransitions: ExternalRowQuantityTransition[] } { - const source = input.currentState.source; - if (!source || source.projectId !== input.projectId) throw new Error("Für den Folgeimport fehlt die Revit-Quelle."); - const decisions = exactDecisionMap(input.plan.changes.map((change) => change.objectId), input.sourceChangeDecisions, (decision) => decision.objectId, "Quelländerung"); - const newRoomSet = new Set(input.plan.newSourceRoomKeys); - const roomDecisions = exactDecisionMap(input.plan.newSourceRoomKeys, input.roomDecisions, (decision) => decision.sourceRoomKey, "Quellraum"); - const newFamilySet = new Set(input.plan.newFamilyAndTypes); - const familyDecisions = exactDecisionMap(input.plan.newFamilyAndTypes, input.familyProjectDeviceDecisions, (decision) => decision.familyAndType, "Familie und Typ"); - const batchId = input.createId(); - const oldMappings = input.currentState.roomMappings.map((mapping) => ({ ...mapping })); - const mappingByKey = new Map(oldMappings.map((mapping) => [mapping.normalizedSourceRoomKey, mapping])); - const newObjectIds = new Set(input.plan.newObjectWorksharingIds); - const neededRoomKeys = new Set(input.plan.objects.filter((object) => newObjectIds.has(object.worksharingId)).map((object) => object.sourceRoomKey).filter((key): key is string => key !== null)); - for (const change of input.plan.changes) { - if (!decisions.get(change.objectId)!.accept || !change.changedFields.some((field) => field === "roomNumber" || field === "roomName")) continue; - const key = input.plan.objects.find((object) => object.worksharingId === change.worksharingId)?.sourceRoomKey; - if (key) neededRoomKeys.add(key); - } - for (const room of input.plan.sourceRooms.filter((candidate) => newRoomSet.has(candidate.sourceRoomKey) && neededRoomKeys.has(candidate.sourceRoomKey))) { - const decision = roomDecisions.get(room.sourceRoomKey)!; - const mapping = { id: input.createId(), projectId: input.projectId, sourceId: source.id, normalizedSourceRoomKey: room.sourceRoomKey, sourceFloorName: null, sourceRoomNumber: room.roomNumber, sourceRoomName: room.roomName, roomId: decision.roomId, defaultDistributionBoardId: decision.defaultDistributionBoardId }; - oldMappings.push(mapping); mappingByKey.set(mapping.normalizedSourceRoomKey, mapping); - } - const incomingById = new Map(input.plan.objects.map((object) => [object.worksharingId, object])); - const existingByWorksharingId = new Map(input.currentState.objects.map((object) => [object.worksharingId, object])); - const changedById = new Map(input.plan.changes.map((change) => [change.objectId, change])); - const quantityDeltaByRow = new Map(); - const objects: ExternalModelObjectSnapshot[] = []; - - for (const existing of input.currentState.objects) { - const incoming = incomingById.get(existing.worksharingId); - if (!incoming) { objects.push({ ...existing, presenceStatus: "missing" }); continue; } - const change = changedById.get(existing.id); - const accept = change ? decisions.get(existing.id)!.accept : false; - if (accept && incoming.issues.some((issue) => issue === "unknown-family-and-type" || issue === "invalid-quantity")) throw new Error("Eine akzeptierte Quelländerung besitzt keine gültige Familien- oder Mengenregel."); - const planningValues = { ...existing.planningValues }; - let deviceTypeId = existing.deviceTypeId; - let externalRoomMappingId = existing.externalRoomMappingId; - let distributionBoardId = existing.distributionBoardId; - let ifcGuid = existing.ifcGuid; - if (accept && change) { - const fields = new Set(change.changedFields); - if (fields.has("ifcGuid")) ifcGuid = incoming.ifcGuid; - if (fields.has("familyAndType")) { - const rule = input.configuration.familyTypeRules.find((candidate) => candidate.exactFamilyAndType === incoming.sourceValues.familyAndType); - if (!rule) throw new Error("Eine geänderte Familie ist nicht klassifiziert."); - deviceTypeId = rule.deviceTypeId; - const type = input.configuration.deviceTypes.find((candidate) => candidate.id === rule.deviceTypeId)!; - if (!existing.overriddenFields.includes("category")) planningValues.category = type.category; - } - if (fields.has("selectionMarker") && !existing.overriddenFields.includes("displayName")) planningValues.displayName = scalarText(incoming.sourceValues.selectionMarker) || incoming.sourceValues.familyAndType; - if (fields.has("sourceRemark") && !existing.overriddenFields.includes("remark")) planningValues.remark = scalarText(incoming.sourceValues.sourceRemark) || null; - if (fields.has("socketCount") && !existing.overriddenFields.includes("effectiveQuantity")) planningValues.effectiveQuantity = incoming.suggestedPlanningValues.effectiveQuantity; - if (fields.has("roomNumber") || fields.has("roomName")) { - const oldMapping = existing.externalRoomMappingId ? oldMappings.find((mapping) => mapping.id === existing.externalRoomMappingId) : null; - const nextMapping = incoming.sourceRoomKey ? mappingByKey.get(incoming.sourceRoomKey) ?? null : null; - externalRoomMappingId = nextMapping?.id ?? null; - if (!existing.circuitDeviceRowId && (existing.distributionBoardId === null || existing.distributionBoardId === oldMapping?.defaultDistributionBoardId)) distributionBoardId = nextMapping?.defaultDistributionBoardId ?? input.objectsWithoutRoomDefaultDistributionBoardId; - } - } - if (existing.circuitDeviceRowId && planningValues.effectiveQuantity !== existing.planningValues.effectiveQuantity) { - quantityDeltaByRow.set(existing.circuitDeviceRowId, (quantityDeltaByRow.get(existing.circuitDeviceRowId) ?? 0) + planningValues.effectiveQuantity - existing.planningValues.effectiveQuantity); - } - objects.push({ - ...existing, - ifcGuid, deviceTypeId, externalRoomMappingId, distributionBoardId, - lastSeenImportBatchId: batchId, - lastAcceptedImportBatchId: change && !accept ? existing.lastAcceptedImportBatchId : batchId, - acceptedSourceValues: mergeAcceptedSource(existing.acceptedSourceValues, incoming.sourceValues, accept), - planningValues, - presenceStatus: "present", - }); - } - - for (const incoming of input.plan.objects.filter((object) => !existingByWorksharingId.has(object.worksharingId))) { - if (incoming.issues.some((issue) => issue === "unknown-family-and-type" || issue === "invalid-quantity")) throw new Error("Ein neues Revit-Objekt besitzt keine gültige Familien- oder Mengenregel."); - const rule = input.configuration.familyTypeRules.find((candidate) => candidate.exactFamilyAndType === incoming.sourceValues.familyAndType); - if (!rule) throw new Error("Eine neue Familie ist nicht klassifiziert."); - const mapping = incoming.sourceRoomKey ? mappingByKey.get(incoming.sourceRoomKey) ?? null : null; - objects.push({ - id: input.createId(), projectId: input.projectId, sourceId: source.id, worksharingId: incoming.worksharingId, ifcGuid: incoming.ifcGuid, - deviceTypeId: rule.deviceTypeId, lastSeenImportBatchId: batchId, lastAcceptedImportBatchId: batchId, - acceptedSourceValues: incoming.sourceValues, planningValues: incoming.suggestedPlanningValues, overriddenFields: [], - externalRoomMappingId: mapping?.id ?? null, - distributionBoardId: mapping?.defaultDistributionBoardId ?? input.objectsWithoutRoomDefaultDistributionBoardId, - linkedProjectDeviceId: newFamilySet.has(incoming.sourceValues.familyAndType) ? familyDecisions.get(incoming.sourceValues.familyAndType)!.projectDeviceId : null, - circuitDeviceRowId: null, presenceStatus: "present", - }); - } - const rowTransitions = [...quantityDeltaByRow].map(([rowId, delta]) => { - const expected = input.rowsById.get(rowId); - if (!expected) throw new Error("Eine verknüpfte Gerätezeile wurde nicht gefunden."); - return { expected, target: { ...expected, quantity: expected.quantity + delta } }; - }); - const previousBatches = input.currentState.importBatches.map((batch) => ({ ...batch, appliedProjectRevision: null, configurationSnapshot: null, originalContentBase64: null, document: null })); - return { - targetState: { - source: { ...source }, - importBatches: [...previousBatches, { id: batchId, projectId: input.projectId, sourceId: source.id, importKind: "follow_up", importedAtIso: input.importedAtIso, fileName: input.plan.fileName, sha256: input.plan.sha256, objectCount: input.plan.objectCount, appliedProjectRevision: input.expectedRevision + 1, configurationSnapshot: input.configuration, originalContentBase64: input.originalContentBase64, document: input.document }], - roomMappings: oldMappings, - objects, - }, - rowTransitions, - }; -} - -const returnFields = new Set(["rowNumber", "circuitCombined", "boardName", "circuitIdentifier", "designation", "electricalPowerW", "voltageV", "currentA"]); -function mergeAcceptedSource(previous: ExternalModelObjectSourceValues, incoming: ExternalModelObjectSourceValues, acceptSourceChanges: boolean) { - if (acceptSourceChanges) return incoming; - return Object.fromEntries(Object.keys(previous).map((key) => [key, returnFields.has(key as keyof ExternalModelObjectSourceValues) ? incoming[key as keyof ExternalModelObjectSourceValues] : previous[key as keyof ExternalModelObjectSourceValues]])) as unknown as ExternalModelObjectSourceValues; -} -function scalarText(value: string | number | boolean | null) { return value === null ? "" : String(value).trim(); } -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-target.ts b/src/external-model/application/external-xlsx-initial-import-target.ts deleted file mode 100644 index 8a7fd27..0000000 --- a/src/external-model/application/external-xlsx-initial-import-target.ts +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index f89403c..0000000 --- a/src/external-model/application/external-xlsx-initial-import.ts +++ /dev/null @@ -1,246 +0,0 @@ -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/external-model/application/external-xlsx-return-projection.ts b/src/external-model/application/external-xlsx-return-projection.ts deleted file mode 100644 index a80125c..0000000 --- a/src/external-model/application/external-xlsx-return-projection.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { ExternalModelObjectSnapshot } from "../domain/external-model-contracts.js"; -import type { ExternalXlsxCircuitMode, ExternalXlsxReturnValues } from "../xlsx/external-xlsx-contracts.js"; -import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; - -export interface ExternalReturnRowContext { - rowId: string; - displayName: string; - powerPerUnitKw: number; - cosPhi: number | null; - phaseType: string | null; - category: CircuitGroupCategory | null; - circuitIdentifier: string; - circuitVoltageV: number | null; - distributionBoardName: string; -} - -export interface ExternalReturnProjection { - objectId: string; - worksharingId: string; - values: ExternalXlsxReturnValues; - differsFromImported: boolean; - warnings: string[]; -} - -export function getRevitBoardName(board: { name: string }) { - return board.name; -} - -export function projectExternalXlsxReturn(input: { - object: ExternalModelObjectSnapshot; - row: ExternalReturnRowContext | null; - circuitMode: ExternalXlsxCircuitMode; - singlePhaseVoltageV: number; - threePhaseVoltageV: number; -}): ExternalReturnProjection { - const { object, row } = input; - const planning = object.planningValues; - const warnings: string[] = []; - const category = row?.category ?? planning.category; - const phaseType = row?.phaseType ?? (category === "three_phase" ? "three_phase" : category ? "single_phase" : null); - const voltageV = row?.circuitVoltageV ?? defaultVoltage(category, input.singlePhaseVoltageV, input.threePhaseVoltageV); - const powerPerUnitW = row ? row.powerPerUnitKw * 1000 : planning.powerPerUnitW; - const electricalPowerW = powerPerUnitW === null - ? null - : roundNumber(planning.effectiveQuantity * powerPerUnitW, 6); - const cosPhi = row?.cosPhi ?? planning.cosPhi; - const currentA = calculateCurrent({ electricalPowerW, voltageV, cosPhi, phaseType }); - if (electricalPowerW === null) warnings.push("Elektrische Leistung ist nicht berechenbar."); - if (voltageV === null) warnings.push("Spannung ist nicht bestimmbar."); - if (currentA === null) warnings.push("Stromstärke ist nicht berechenbar."); - - const values: ExternalXlsxReturnValues = { - ...(input.circuitMode === "combined" - ? { circuitCombined: row ? `${getRevitBoardName({ name: row.distributionBoardName })}${row.circuitIdentifier}` : "" } - : { - boardName: row ? getRevitBoardName({ name: row.distributionBoardName }) : "", - circuitIdentifier: row?.circuitIdentifier ?? "", - }), - designation: row?.displayName ?? planning.displayName ?? "", - electricalPowerW, - voltageV, - currentA, - }; - const source = object.acceptedSourceValues; - const sourceValues: ExternalXlsxReturnValues = input.circuitMode === "combined" - ? { - circuitCombined: source.circuitCombined, - designation: source.designation, - electricalPowerW: source.electricalPowerW, - voltageV: source.voltageV, - currentA: source.currentA, - } - : { - boardName: source.boardName, - circuitIdentifier: source.circuitIdentifier, - designation: source.designation, - electricalPowerW: source.electricalPowerW, - voltageV: source.voltageV, - currentA: source.currentA, - }; - - return { - objectId: object.id, - worksharingId: object.worksharingId, - values, - differsFromImported: Object.keys(values).some((key) => - !sameScalar(values[key as keyof ExternalXlsxReturnValues], sourceValues[key as keyof ExternalXlsxReturnValues]) - ), - warnings, - }; -} - -function defaultVoltage(category: CircuitGroupCategory | null, singlePhase: number, threePhase: number) { - if (category === "three_phase") return threePhase; - if (category === "lighting" || category === "single_phase") return singlePhase; - return null; -} - -function calculateCurrent(input: { electricalPowerW: number | null; voltageV: number | null; cosPhi: number | null; phaseType: string | null }) { - if ( - input.electricalPowerW === null || - input.voltageV === null || input.voltageV <= 0 || - input.cosPhi === null || input.cosPhi <= 0 || - (input.phaseType !== "single_phase" && input.phaseType !== "three_phase") - ) return null; - const divisor = input.phaseType === "three_phase" - ? Math.sqrt(3) * input.voltageV * input.cosPhi - : input.voltageV * input.cosPhi; - return roundNumber(input.electricalPowerW / divisor, 2); -} - -function sameScalar(left: string | number | boolean | null | undefined, right: string | number | boolean | null | undefined) { - const normalizedLeft = normalizeScalar(left); - const normalizedRight = normalizeScalar(right); - if (typeof normalizedLeft === "number" && typeof normalizedRight === "number") { - return Math.abs(normalizedLeft - normalizedRight) < 1e-9; - } - return normalizedLeft === normalizedRight; -} - -function normalizeScalar(value: string | number | boolean | null | undefined): string | number | boolean { - if (value === null || value === undefined || value === "") return ""; - if (typeof value === "string") { - const trimmed = value.trim(); - if (!trimmed) return ""; - const numeric = Number(trimmed.replace(",", ".")); - return Number.isFinite(numeric) ? numeric : trimmed; - } - return value; -} - -function roundNumber(value: number, decimals: number) { - const factor = 10 ** decimals; - return Math.round((value + Number.EPSILON) * factor) / factor; -} diff --git a/src/external-model/configuration/external-model-configuration.ts b/src/external-model/configuration/external-model-configuration.ts deleted file mode 100644 index b3dc20e..0000000 --- a/src/external-model/configuration/external-model-configuration.ts +++ /dev/null @@ -1,246 +0,0 @@ -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 new file mode 100644 index 0000000..3446d24 --- /dev/null +++ b/src/external-model/csv/external-csv-transport.ts @@ -0,0 +1,356 @@ +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 95ab137..b06e2fb 100644 --- a/src/external-model/domain/external-model-contracts.ts +++ b/src/external-model/domain/external-model-contracts.ts @@ -1,11 +1,10 @@ import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; -import type { ExternalModelConfiguration } from "../configuration/external-model-configuration.js"; import type { - ExternalXlsxDocument, - ExternalXlsxScalar, -} from "../xlsx/external-xlsx-contracts.js"; + ExternalCsvConfiguration, + ExternalCsvDocument, +} from "../csv/external-csv-contracts.js"; -export const externalModelSourceTypes = ["revit_xlsx"] as const; +export const externalModelSourceTypes = ["revit_csv"] as const; export type ExternalModelSourceType = (typeof externalModelSourceTypes)[number]; export const externalImportKinds = ["initial", "follow_up"] as const; @@ -30,11 +29,11 @@ export interface ExternalImportBatchSnapshot { importedAtIso: string; fileName: string; sha256: string; - objectCount: number; - appliedProjectRevision: number | null; - configurationSnapshot: ExternalModelConfiguration | null; - originalContentBase64: string | null; - document: ExternalXlsxDocument | null; + appliedProjectRevision: number; + configurationVersion: number; + configurationSnapshot: ExternalCsvConfiguration; + originalContentBase64: string; + document: ExternalCsvDocument; } export interface ExternalRoomMappingSnapshot { @@ -51,28 +50,24 @@ export interface ExternalRoomMappingSnapshot { export interface ExternalModelObjectSourceValues { rowNumber: number; - roomNumber: ExternalXlsxScalar; - roomName: ExternalXlsxScalar; + roomNumber: string; + roomName: string; familyAndType: string; - selectionMarker: ExternalXlsxScalar; - socketCount: ExternalXlsxScalar; - sourceRemark: ExternalXlsxScalar; - circuitCombined: ExternalXlsxScalar; - boardName: ExternalXlsxScalar; - circuitIdentifier: ExternalXlsxScalar; - designation: ExternalXlsxScalar; - electricalPowerW: ExternalXlsxScalar; - voltageV: ExternalXlsxScalar; - currentA: ExternalXlsxScalar; + selectionMarker: string; + circuitIdentifier: string; + power: string; + quantity: string | null; + additionalSourceValues: Record; } export interface ExternalModelObjectPlanningValues { displayName: string | null; + internalDeviceType: string | null; category: CircuitGroupCategory | null; connectionKind: string | null; effectiveQuantity: number; powerPerUnitW: number | null; - simultaneityFactor: number | null; + simultaneityFactor: number; cosPhi: number | null; costGroup: string | null; remark: string | null; @@ -85,9 +80,7 @@ export interface ExternalModelObjectSnapshot { id: string; projectId: string; sourceId: string; - worksharingId: string; - ifcGuid: string | null; - deviceTypeId: string; + ifcGuid: 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 new file mode 100644 index 0000000..3085211 --- /dev/null +++ b/src/external-model/domain/external-model-matching.ts @@ -0,0 +1,147 @@ +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/external-model/domain/external-model-state-comparison.ts b/src/external-model/domain/external-model-state-comparison.ts deleted file mode 100644 index ff851f0..0000000 --- a/src/external-model/domain/external-model-state-comparison.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { ExternalModelStateSnapshot } from "./external-model-contracts.js"; - -export function externalModelStatesEqual(left: ExternalModelStateSnapshot, right: ExternalModelStateSnapshot) { - return canonical(normalize(left)) === canonical(normalize(right)); -} - -function normalize(state: ExternalModelStateSnapshot): ExternalModelStateSnapshot { - return { - ...state, - importBatches: [...state.importBatches].sort((left, right) => compareNullableNumber(left.appliedProjectRevision, right.appliedProjectRevision) || compareText(left.id, right.id)), - roomMappings: [...state.roomMappings].sort((left, right) => compareText(left.normalizedSourceRoomKey, right.normalizedSourceRoomKey) || compareText(left.id, right.id)), - objects: [...state.objects].sort((left, right) => compareText(left.worksharingId, right.worksharingId) || compareText(left.id, right.id)), - }; -} - -function compareNullableNumber(left: number | null, right: number | null) { - if (left === right) return 0; - if (left === null) return -1; - if (right === null) return 1; - return left - right; -} -function compareText(left: string, right: string) { return left < right ? -1 : left > right ? 1 : 0; } -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/external-model/xlsx/external-xlsx-contracts.ts b/src/external-model/xlsx/external-xlsx-contracts.ts deleted file mode 100644 index 94c7b45..0000000 --- a/src/external-model/xlsx/external-xlsx-contracts.ts +++ /dev/null @@ -1,153 +0,0 @@ -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 deleted file mode 100644 index 31cc707..0000000 --- a/src/external-model/xlsx/external-xlsx-transport.ts +++ /dev/null @@ -1,582 +0,0 @@ -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/src/frontend/components/AppShell.tsx b/src/frontend/components/AppShell.tsx index 77b7c78..bbfa0ae 100644 --- a/src/frontend/components/AppShell.tsx +++ b/src/frontend/components/AppShell.tsx @@ -4,14 +4,12 @@ import { useEffect, useState } from "react"; import { usePathname } from "next/navigation"; import { Sidebar } from "./Sidebar"; -// Every page shows the (collapsible) sidebar except the print view, which is -// a stand-alone document opened in its own tab and printed as PDF. -const PRINT_VIEW_PATTERN = /^\/projects\/[^/]+\/print(\/|$)/; +const PROJECT_AREA_PATTERN = /^\/projects(\/[^/]+)?$/; const SIDEBAR_COLLAPSED_STORAGE_KEY = "leistungsbilanz:sidebar-collapsed"; export function AppShell({ children }: { children: React.ReactNode }) { const pathname = usePathname(); - const showSidebar = !PRINT_VIEW_PATTERN.test(pathname ?? ""); + const showSidebar = PROJECT_AREA_PATTERN.test(pathname ?? ""); const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false); useEffect(() => { diff --git a/src/frontend/components/AuthProvider.tsx b/src/frontend/components/AuthProvider.tsx deleted file mode 100644 index 02ab833..0000000 --- a/src/frontend/components/AuthProvider.tsx +++ /dev/null @@ -1,61 +0,0 @@ -"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 deleted file mode 100644 index 23a2aeb..0000000 --- a/src/frontend/components/LoginGate.tsx +++ /dev/null @@ -1,179 +0,0 @@ -"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 e99b493..b3cbb4f 100644 --- a/src/frontend/components/Sidebar.tsx +++ b/src/frontend/components/Sidebar.tsx @@ -6,25 +6,15 @@ import { useEffect, useState } from "react"; import { listProjects } from "../utils/api"; import type { ProjectDto } from "../types"; import { ThemeToggle } from "./ThemeToggle"; -import { useAuth } from "./AuthProvider"; -import { getConfigEntry } from "../utils/config-access"; -// Anchors on the project overview page (/projects/[id]). const PROJECT_SECTIONS = [ { id: "verlauf", label: "Verlauf", icon: "↺" }, { id: "verteilungen", label: "Verteilungen", icon: "⌁" }, + { id: "etagen", label: "Etagen", icon: "▥" }, + { id: "raeume", label: "Räume", icon: "⌂" }, { id: "projektgeraete", label: "Projektgeräte", icon: "⚙" }, ] as const; -// 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). -const PROJECT_PATH_PATTERN = /^\/projects\/([^/]+)(\/.*)?$/; - interface SidebarProps { isCollapsed: boolean; onToggleCollapsed: () => void; @@ -32,16 +22,8 @@ interface SidebarProps { export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { const pathname = usePathname(); - const { user, isAdmin, logout } = useAuth(); - const configEntry = getConfigEntry(isAdmin); - const projectMatch = pathname?.match(PROJECT_PATH_PATTERN); + const projectMatch = pathname?.match(/^\/projects\/([^/]+)$/); const activeProjectId = projectMatch ? projectMatch[1] : null; - const projectSubPath = projectMatch?.[2] ?? ""; - // Section anchors only exist (and are observed) on the overview itself. - const overviewProjectId = - activeProjectId && (projectSubPath === "" || projectSubPath === "/") - ? activeProjectId - : null; const [projects, setProjects] = useState([]); const [activeSection, setActiveSection] = useState(null); @@ -60,7 +42,7 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { }, []); useEffect(() => { - if (!overviewProjectId) { + if (!activeProjectId) { setActiveSection(null); return; } @@ -87,7 +69,7 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) { elements.forEach((element) => observer.observe(element)); return () => observer.disconnect(); - }, [overviewProjectId]); + }, [activeProjectId]); return (
    ); diff --git a/src/frontend/components/ThemeToggle.tsx b/src/frontend/components/ThemeToggle.tsx index 2073a5e..355e0e2 100644 --- a/src/frontend/components/ThemeToggle.tsx +++ b/src/frontend/components/ThemeToggle.tsx @@ -48,17 +48,16 @@ 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. ); } diff --git a/src/frontend/components/cable-sizing-api.ts b/src/frontend/components/cable-sizing-api.ts index 73582b5..ee52aef 100644 --- a/src/frontend/components/cable-sizing-api.ts +++ b/src/frontend/components/cable-sizing-api.ts @@ -1,44 +1,71 @@ -// 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). +// Thin, self-contained fetch client for the cable-sizing module. Deliberately +// not merged into ../utils/api.ts to keep this module's frontend footprint a +// single new file rather than growing the existing shared API file - see +// docs/cable-sizing-module.md. import type { CableSizingAlert, CableSizingInput, CableSizingResult, + InsulationMaterial, + LayingMethod, } 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; - alerts: CableSizingAlert[]; -} - -export async function calculateCableSizing( - input: CableSizingInput -): Promise { - const response = await fetch("/api/cable-sizing/calculate", { - method: "POST", - headers: { - "Content-Type": "application/json", - [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, - }, - body: JSON.stringify(input), +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 details = await response.text(); try { const parsed = JSON.parse(details) as { error?: unknown }; - if (typeof parsed.error === "string") { - details = parsed.error; - } + 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; + return response.json() as Promise; +} + +export interface CalculateCableSizingResponse { + calculationId: string; + result: CableSizingResult; + alerts: CableSizingAlert[]; +} + +export function calculateCableSizing( + input: CableSizingInput, + context?: { projectId?: string; circuitId?: string; equipmentIdentifier?: string } +): Promise { + return request("/api/cable-sizing/calculate", { + method: "POST", + body: JSON.stringify({ ...input, context }), + }); +} + +export function markCableSizingCalculationApplied(calculationId: string): Promise { + return request(`/api/cable-sizing/calculations/${calculationId}/applied`, { + method: "POST", + }); +} + +export interface LayingMethodOption { + method: LayingMethod; + label: string; + dataVerified: boolean; +} + +export function listLayingMethods(): Promise { + return request("/api/cable-sizing/laying-methods"); +} + +export interface InsulationMaterialOption { + insulation: InsulationMaterial; + label: string; +} + +export function listInsulationMaterials(): Promise { + return request("/api/cable-sizing/insulation-materials"); } diff --git a/src/frontend/components/cable-sizing-defaults.ts b/src/frontend/components/cable-sizing-defaults.ts deleted file mode 100644 index 069c575..0000000 --- a/src/frontend/components/cable-sizing-defaults.ts +++ /dev/null @@ -1,57 +0,0 @@ -// 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 { - if (Number.isFinite(circuit.circuitCosPhi) && circuit.circuitCosPhi > 0) { - return Math.round(circuit.circuitCosPhi * 100) / 100; - } - 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 index b15de3b..36b204c 100644 --- a/src/frontend/components/cable-sizing-modal.tsx +++ b/src/frontend/components/cable-sizing-modal.tsx @@ -4,6 +4,8 @@ import { type FormEvent, useMemo, useState } from "react"; import { CONDUCTOR_MATERIALS, CROSS_SECTIONS_MM2, + GROUPING_LABELS, + GROUPING_OPTIONS, HARMONIC_NEUTRAL_LOAD_LABELS, HARMONIC_NEUTRAL_LOAD_OPTIONS, INSULATION_MATERIALS, @@ -12,9 +14,8 @@ import { LAYING_METHOD_GROUP, LAYING_METHOD_LABELS, PRACTICAL_MINIMUM_CROSS_SECTION_MM2, - REFERENCE_TEMPERATURE_C, - maxGroupingCircuits, - temperatureOptions, + TEMPERATURE_FACTOR_AIR, + TEMPERATURE_FACTOR_GROUND, type CableSizingAlert, type CableSizingInput, type CableSizingResult, @@ -26,19 +27,13 @@ import { } 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; + projectId: string; onClose: () => void; onApply: (patch: { cableCrossSection: string; @@ -47,8 +42,15 @@ interface CableSizingModalProps { }) => Promise; } +function temperatureOptions(method: LayingMethod) { + const table = + LAYING_METHOD_GROUP[method] === "air" ? TEMPERATURE_FACTOR_AIR : TEMPERATURE_FACTOR_GROUND; + return Object.keys(table).map(Number).sort((a, b) => a - b); +} + // 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. +// like "2.5 mm²" or "2,5". Returns null if nothing parseable is found - +// used only for the manual-entry sanity check below, never persisted. function parseCrossSectionMm2(text: string): number | null { const match = text.match(/([0-9]+(?:[.,][0-9]+)?)/); if (!match) return null; @@ -56,52 +58,38 @@ function parseCrossSectionMm2(text: string): number | null { 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, + projectId, 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 [cosPhi, setCosPhi] = useState(1); const [maxVoltageDropPercent, setMaxVoltageDropPercent] = useState(3); const [harmonicNeutralLoad, setHarmonicNeutralLoad] = useState("none"); const [lengthM, setLengthM] = useState(circuit.cableLength ?? 0); - const [phase, setPhase] = useState<1 | 3>(derivedPhase); + const [phase, setPhase] = useState<1 | 3>(circuit.voltage === 400 ? 3 : 1); - // Manual entry: applying never requires a calculation. Prefilled from the - // circuit so an existing cable specification is not lost. + // Manual override: applying this never requires a calculation. Prefilled + // from the circuit's current values so opening the modal on an already + // specified cable doesn't lose that data. const [manualCableType, setManualCableType] = useState(circuit.cableType ?? ""); const [manualCrossSection, setManualCrossSection] = useState(circuit.cableCrossSection ?? ""); const [calculating, setCalculating] = useState(false); + const [calculationId, setCalculationId] = useState(null); 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 groupingMaximum = maxGroupingCircuits(layingMethod); - const availableTemperatures = temperatureOptions(layingMethod, insulation); + const voltage = circuit.voltage ?? (phase === 1 ? 230 : 400); const input: CableSizingInput = useMemo( () => ({ @@ -118,7 +106,7 @@ export function CableSizingModal({ groupingCircuits, maxVoltageDropPercent, harmonicNeutralLoad, - existingProtection, + existingProtectionRatedCurrentA: circuit.protectionDevice?.ratedCurrentA, circuitCategory, }), [ @@ -134,8 +122,7 @@ export function CableSizingModal({ groupingCircuits, maxVoltageDropPercent, harmonicNeutralLoad, - existingProtection?.ratedCurrentA, - existingProtection?.kind, + circuit.protectionDevice?.ratedCurrentA, circuitCategory, ] ); @@ -146,47 +133,50 @@ export function CableSizingModal({ 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(", ")}).`; + return `${parsed} mm² ist kein Standard-Querschnitt (${CROSS_SECTIONS_MM2.join(", ")}).`; } if ( - result?.supported && + result?.dataVerified && 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²).`; + return `${parsed} mm² ist kleiner als die zuletzt berechnete Empfehlung (${result.recommendedCrossSectionMm2} mm²) - passt nicht zu Last${circuit.protectionDevice ? "/Sicherung" : ""} und Verlegeart.`; } 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 `${parsed} mm² liegt unter dem Praxis-Mindestquerschnitt für 1-phasige Stromkreise (${practicalMinimum} mm²).`; } return null; - }, [manualCrossSection, result, circuitCategory]); + }, [manualCrossSection, result, circuit.protectionDevice, 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]]; + function handleLayingMethodChange(method: LayingMethod) { + setLayingMethod(method); + const options = temperatureOptions(method); + const reference = LAYING_METHOD_GROUP[method] === "air" ? 30 : 20; setAmbientTemperatureC(options.includes(reference) ? reference : options[0]); + setResult(null); + setCalculationId(null); } async function handleCalculate() { setCalculating(true); setError(null); try { - const response = await calculateCableSizing(input); + const response = await calculateCableSizing(input, { + projectId, + circuitId: circuit.id, + equipmentIdentifier: circuit.equipmentIdentifier, + }); 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²`); + setCalculationId(response.calculationId); + // Calculating fills the manual field as a suggestion, but that field + // stays the single source of truth for what gets applied - the user + // can still edit it by hand before submitting. + if (response.result.dataVerified && response.result.recommendedCrossSectionMm2) { + setManualCrossSection(`${response.result.recommendedCrossSectionMm2} mm²`); } } catch (err) { setError(err instanceof Error ? err.message : "Berechnung fehlgeschlagen"); @@ -205,41 +195,31 @@ export function CableSizingModal({ }); } - const recommendedRow = result?.rows.find((row) => row.recommended); - return (
    { - setLengthM(Number(event.target.value)); - resetResult(); - }} + onChange={(event) => setLengthM(Number(event.target.value))} type="number" value={lengthM} /> - {lengthM === 0 ? ( -
    - Bei 0 m wird kein Spannungsfall angesetzt. -
    - ) : null}
    - +
    -
    +
    -
    +
    -
    +
    - { - setGroupingCircuits(Math.max(1, Math.round(Number(event.target.value) || 1))); - resetResult(); - }} - step={1} - type="number" + onChange={(event) => setGroupingCircuits(Number(event.target.value))} value={groupingCircuits} - /> -
    - Anzahl gemeinsam verlegter Stromkreise, einschließlich dieses - {layingMethod === "E" - ? "; ohne Angaben zur Kabelpritsche ist nur 1 zulässig." - : `; für diese Verlegeart sind bis ${groupingMaximum} tabelliert.`} -
    + > + {GROUPING_OPTIONS.map((grouping) => ( + + ))} +
    - {phase === 3 ? ( + {phase === 3 && (
    - ) : null} -
    + )} +
    { - setCosPhi(Math.min(1, Math.max(0.1, Number(event.target.value) || 1))); - resetResult(); - }} - step={0.01} - type="number" + min={0.6} + onChange={(event) => setCosPhi(Number(event.target.value))} + step={0.05} + type="range" value={cosPhi} /> -
    - Aus den Gerätezeilen: {formatNumber(derivedCosPhi, 2)} -
    + {cosPhi.toFixed(2)}
    -
    +
    { - setMaxVoltageDropPercent(Number(event.target.value) || 3); - resetResult(); - }} + max={5} + min={1} + onChange={(event) => setMaxVoltageDropPercent(Number(event.target.value))} step={0.5} - type="number" + type="range" 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"} -
    + {maxVoltageDropPercent.toFixed(1)} %
    @@ -463,66 +395,69 @@ export function CableSizingModal({ onClick={handleCalculate} type="button" > - {calculating ? "Berechnet …" : "Berechnen"} + {calculating ? "Berechnet…" : "Berechnen"} - {error ?

    {error}

    : null} + {error &&

    {error}

    } - {result ? ( + {result && !result.dataVerified && ( +
    + Für Verlegeart {layingMethod} mit Isolierstoff {insulation.toUpperCase()} liegen keine + geprüften Strombelastbarkeits-Tabellenwerte vor - keine Dimensionierung möglich. Bitte + eine andere Verlegeart/Isolierstoff-Kombination wählen. +
    + )} + + {result && result.dataVerified && (
    - {result.supported ? ( -
    -
    -
    Betriebsstrom IB
    -
    {formatNumber(result.operatingCurrentA, 1)} A
    +
    +
    +
    Betriebsstrom Ib
    +
    {result.operatingCurrentA.toFixed(1)} A
    +
    +
    +
    + Bemessungsstrom (für Querschnittswahl){circuit.protectionDevice ? " *" : ""}
    -
    -
    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` - : "–"} -
    +
    + {result.designCurrentA.toFixed(1)} A
    - ) : null} +
    +
    Empfohlener Querschnitt
    +
    + + {result.recommendedCrossSectionMm2 + ? `${result.recommendedCrossSectionMm2} mm²` + : "-"} + +
    +
    +
    +
    ΔU bei Empfehlung
    +
    + {result.voltageDropAtRecommendedPercent != null + ? `${result.voltageDropAtRecommendedPercent.toFixed(2)} %` + : "-"} +
    +
    +
    +
    Korrekturfaktor
    +
    {result.combinedDerationFactor.toFixed(2)}
    +
    +
    +
    Max. Länge (ΔU-Grenze)
    +
    + {result.rows.find((row) => row.recommended)?.maxLengthForVoltageDropM != null + ? `${result.rows + .find((row) => row.recommended)! + .maxLengthForVoltageDropM!.toFixed(0)} m` + : "-"} +
    +
    +
    {alerts.map((alert, index) => (
    ))} + {circuit.protectionDevice && ( +

    + * Bemessungsstrom = Maximum aus Betriebsstrom und vorhandener Sicherung + ({circuit.protectionDevice.ratedCurrentA} A) - die Sicherung löst erst bei ihrem + eigenen Bemessungsstrom aus, das Kabel muss also dafür ausgelegt sein, nicht nur + für die tatsächliche Last. +

    + )}
    - ) : null} + )}

    - Kabeltyp und Querschnitt direkt eingeben oder die Empfehlung übernehmen. - Beides landet in denselben Feldern und kann vor dem Übernehmen angepasst - werden. + Querschnitt manuell eingeben oder eine Berechnung oben übernehmen - beides schreibt in + dasselbe Feld, du kannst es vor dem Übernehmen frei anpassen.

    @@ -554,7 +496,7 @@ export function CableSizingModal({ className="form-control" id="cable-sizing-manual-type" onChange={(event) => setManualCableType(event.target.value)} - placeholder="z. B. NYM-J 3x2,5" + placeholder="z.B. NYM-J 3x1.5" value={manualCableType} />
    @@ -566,15 +508,15 @@ export function CableSizingModal({ className="form-control" id="cable-sizing-manual-cross-section" onChange={(event) => setManualCrossSection(event.target.value)} - placeholder="z. B. 4 mm²" + placeholder="z.B. 4 mm²" value={manualCrossSection} />
    - {manualCrossSectionWarning ? ( + {manualCrossSectionWarning && (
    {manualCrossSectionWarning}
    - ) : null} + )}
    ); diff --git a/src/frontend/components/circuit-tree-editor.tsx b/src/frontend/components/circuit-tree-editor.tsx index 5418922..d113b3b 100644 --- a/src/frontend/components/circuit-tree-editor.tsx +++ b/src/frontend/components/circuit-tree-editor.tsx @@ -1,32 +1,6 @@ "use client"; -import Link from "next/link"; import { DragEvent, KeyboardEvent, useEffect, useMemo, useRef, useState } from "react"; -import { - ArrowDown, - ArrowDown01, - ArrowUp, - Calculator, - Check, - Columns3, - FilterX, - FolderPlus, - Funnel, - ListOrdered, - ListPlus, - ListX, - PackagePlus, - PanelRightClose, - PanelRightOpen, - Pencil, - Plus, - Redo2, - ShieldPlus, - TableProperties, - Trash2, - Undo2, -} from "lucide-react"; -import { IconButton, IconButtonSeparator } from "./icon-button"; import { inferProjectDeviceSectionKey, isProjectDevicePlacementValid, @@ -102,7 +76,6 @@ import { type MutableDistributionBoardComponentRole, } from "../utils/distribution-board-component-editing"; import { loadCircuitEditorSnapshot } from "../utils/circuit-editor-history"; -import { createClientId } from "../utils/client-id"; import type { CellKey, ColumnDef, @@ -120,11 +93,6 @@ import { deleteCircuitGroupCommand, deleteCircuitGroupSubtreeCommand, deleteDistributionBoardComponentCommand, - assignExternalProjectObjectsToRow, - assignExternalProjectObjectsToNewRow, - assignExternalProjectObjectsToNewCircuit, - detachExternalProjectObjectsFromRow, - getExternalProjectObjects, getCircuitTree, getNextCircuitIdentifier, getProjectHistory, @@ -159,7 +127,6 @@ import type { ProjectCommandResultDto, ProjectDeviceDto, ProjectHistoryStateDto, - ExternalProjectObjectsDto, } from "../types"; import type { CircuitDeviceRowSnapshot, @@ -168,7 +135,6 @@ import type { CircuitSnapshot, } from "../../domain/models/circuit-structure-project-command.model"; import { DistributionBoardComponentModal } from "./distribution-board-component-modal"; -import { GzfPickerModal } from "./gzf-picker-modal"; import { CircuitGroupModal } from "./circuit-group-modal"; import { CircuitProtectionModal } from "./circuit-protection-modal"; import { CableSizingModal } from "./cable-sizing-modal"; @@ -281,24 +247,6 @@ function createValuesFromEditPatch( ); } -/** - * Header labels break only between words: hyphens become non-breaking and a - * trailing unit such as "[kW]" is always shown on its own second line, so - * header heights stay uniform. - */ -function renderColumnHeaderLabel(label: string) { - const match = /^(.*?)\s*(\[[^\]]+\])$/.exec(label); - const name = (match ? match[1] : label).replace(/-/g, "‑"); - return match ? ( - <> - {name} - {match[2]} - - ) : ( - name - ); -} - export function CircuitTreeEditor(props: { projectId: string; circuitListId: string }) { /* Circuit-tree editor invariant overview: @@ -329,16 +277,11 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str useState(null); const [circuitGroupEditorIntent, setCircuitGroupEditorIntent] = useState(null); - // GZF cell the AMEV picker writes to; null while the picker is closed. - const [gzfPickerCell, setGzfPickerCell] = useState(null); const [protectionEditorCircuit, setProtectionEditorCircuit] = useState(null); 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(""); @@ -390,26 +333,6 @@ 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; @@ -418,17 +341,13 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } setError(null); try { - const [{ tree, history }, external] = await Promise.all([ - loadCircuitEditorSnapshot( - () => getCircuitTree(projectId, circuitListId), - () => getProjectHistory(projectId) - ), - getExternalProjectObjects(projectId), - ]); + const { tree, history } = await loadCircuitEditorSnapshot( + () => getCircuitTree(projectId, circuitListId), + () => getProjectHistory(projectId) + ); projectRevisionRef.current = history.currentRevision; setHistoryState(history); setData(tree); - setExternalObjects(external); } catch (err) { setError(normalizeUiError(err)); } finally { @@ -1061,7 +980,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str defaultSortOrder: number ) { return buildCircuitDeviceRowInsertSnapshot({ - id: createClientId(), + id: crypto.randomUUID(), circuitId, values, defaultSortOrder, @@ -1085,7 +1004,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str ), data ); - const circuitId = createClientId(); + const circuitId = crypto.randomUUID(); const deviceRows = deviceRowValues.map((row, index) => createDeviceRowSnapshot(circuitId, row, (index + 1) * 10) ); @@ -1253,7 +1172,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str (section) => section.id === intent.sectionId )?.components ?? []; const snapshot = buildDistributionBoardComponentSnapshot({ - id: createClientId(), + id: crypto.randomUUID(), circuitListId, role: intent.role, sectionId: intent.sectionId, @@ -1318,7 +1237,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str projectId, getExpectedProjectRevision(), buildNewCircuitGroupSnapshot({ - id: createClientId(), + id: crypto.randomUUID(), circuitListId, category: values.category, displayName: values.displayName, @@ -1354,20 +1273,12 @@ 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 + externalWarning)) { + if (!confirm(warning)) { return; } await runCommand({ @@ -1500,7 +1411,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str return; } await runCommand({ - label: "Leitungsberechnung übernehmen", + label: "Kabel dimensionieren", redo: async () => { const result = await updateCircuitById( projectId, @@ -1807,7 +1718,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const currentDisplay = mode === "replaceWithTypedChar" && cell.cellKey !== "phaseType" ? typedChar ?? "" - : String(visibleCell.editValue ?? visibleCell.value ?? ""); + : String(visibleCell.value ?? ""); focusTokenRef.current += 1; setEditingCell({ ...cell, @@ -1946,26 +1857,22 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } // Commits the active editor input through command history so edits remain undoable. - // `target` commits a value for a cell without an open inline editor - // (AMEV GZF picker); the regular edit path passes no target. async function commitEdit( direction: SaveDirection = "stay", - draftOverride?: string, - target?: SelectedCell + draftOverride?: string ) { - const session = target ?? editingCell; - if (!session) { + if (!editingCell) { return; } - const row = findRow(session.rowKey); - const cell = row?.cells.find((entry) => entry.cellKey === session.cellKey); + const row = findRow(editingCell.rowKey); + const cell = row?.cells.find((entry) => entry.cellKey === editingCell.cellKey); if (!row || !cell || !cell.editable) { setEditingCell(null); return; } - const draft = draftOverride ?? editingCell?.draft ?? ""; + const draft = draftOverride ?? editingCell.draft; if ( - session.cellKey === "equipmentIdentifier" && + editingCell.cellKey === "equipmentIdentifier" && row.circuit && hasEquipmentIdentifierConflict(allCircuits, row.circuit.id, draft) ) { @@ -1973,7 +1880,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str return; } - let targetSelection: SelectedCell = { rowKey: session.rowKey, cellKey: session.cellKey }; + let targetSelection: SelectedCell = { rowKey: editingCell.rowKey, cellKey: editingCell.cellKey }; const nextSelectionIntent = () => { let selected = targetSelection; if (direction !== "stay") { @@ -1996,7 +1903,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str redo: async () => { const selection = await createFromPlaceholder( row.sectionId, - session.cellKey, + editingCell.cellKey, draft ); targetSelection = selection; @@ -2013,7 +1920,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const command: HistoryCommand = { label: "Stromkreisfeld bearbeiten", redo: async () => { - await patchCircuit(row.circuit!.id, session.cellKey, next); + await patchCircuit(row.circuit!.id, editingCell.cellKey, next); return nextSelectionIntent(); }, }; @@ -2027,7 +1934,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str const command: HistoryCommand = { label: "Gerätefeld bearbeiten", redo: async () => { - await patchDeviceRow(row.device!.id, session.cellKey, next); + await patchDeviceRow(row.device!.id, editingCell.cellKey, next); return nextSelectionIntent(); }, }; @@ -2042,7 +1949,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str label: "Gerätezeile im Reservestromkreis erstellen", redo: async () => { const editValues = createValuesFromEditPatch( - buildDeviceRowEditPatch(session.cellKey, next) + buildDeviceRowEditPatch(editingCell.cellKey, next) ); const snapshot = createDeviceRowSnapshot( row.circuit!.id, @@ -2062,7 +1969,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str snapshot, "Gerätezeile im Reservestromkreis erstellen" ); - targetSelection = { rowKey: `circuitCompact:${row.circuit!.id}`, cellKey: session.cellKey }; + targetSelection = { rowKey: `circuitCompact:${row.circuit!.id}`, cellKey: editingCell.cellKey }; return nextSelectionIntent(); }, }; @@ -2071,45 +1978,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } } - function isGzfPickerCell(target: SelectedCell | null): target is SelectedCell { - return Boolean( - target && - target.cellKey === "simultaneityFactor" && - findCell(target.rowKey, target.cellKey)?.editable - ); - } - - // Opens the AMEV simultaneity-factor table for one GZF cell. A running - // inline edit is discarded because the picked value replaces it. - function openGzfPicker(target: SelectedCell) { - if (isSaving || historyBusy || !isGzfPickerCell(target)) { - return; - } - setEditingCell(null); - setSelectedCell(target); - setGzfPickerCell(target); - } - - function closeGzfPicker() { - setGzfPickerCell(null); - focusGridWithoutScroll(); - } - - // Commits the picked mean value like a typed edit (undoable command). - function handleGzfPicked(value: number) { - const target = gzfPickerCell; - setGzfPickerCell(null); - if (!target) { - return; - } - // parseNumeric accepts only the German decimal comma. - const draft = value.toLocaleString("de-DE", { - maximumFractionDigits: 2, - useGrouping: false, - }); - void commitEdit("stay", draft, target); - } - // Cancels current edit session and restores grid keyboard focus. function cancelEdit() { if (!editingCell) { @@ -2919,15 +2787,11 @@ 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." + - externalWarning + "Abbrechen: anschließend entscheiden, ob stattdessen der gesamte Stromkreis gelöscht werden soll." ); if (!keepAsReserve) { const deleteCircuit = confirm( @@ -2939,7 +2803,7 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str } return; } - } else if (!confirm(`Gerätezeile „${rowSnapshot.displayName}“ löschen?${externalWarning}`)) { + } else if (!confirm(`Gerätezeile „${rowSnapshot.displayName}“ löschen?`)) { return; } await runCommand({ @@ -2962,18 +2826,11 @@ 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." + - externalWarning + "Bestehende Betriebsmittelkennzeichen werden nicht neu nummeriert." ) ) { return; @@ -3010,56 +2867,6 @@ 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) { @@ -3114,14 +2921,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str // - printable key starts overwrite edit (type-to-edit) // - Arrow/Tab move selectedCell when not editing function handleContainerKeyDown(event: KeyboardEvent) { - // The picker modal sits outside the grid; keep grid keys from acting behind it. - if (gzfPickerCell) { - if (event.key === "Escape") { - event.preventDefault(); - closeGzfPicker(); - } - return; - } if (editingCell) { if (event.key === "Tab") { event.preventDefault(); @@ -3189,11 +2988,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str moveHorizontal(-1); return; } - if (event.altKey && event.key === "ArrowDown" && isGzfPickerCell(selectedCell)) { - event.preventDefault(); - openGzfPicker(selectedCell); - return; - } if (event.key === "ArrowDown") { event.preventDefault(); moveVertical(1); @@ -3229,37 +3023,32 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str return (
    - void handleUndo()} - showLabel - /> - + Rückgängig + +
    + disabled={!historyState || historyState.redoDepth === 0 || historyBusy || isSaving} + > + Wiederholen + + + + {renderColumnSettingsMenu("col-empty")} +
    {renderActiveViewSummary()} {renderDistributionPowerSummary()} {error ? ( @@ -3361,9 +3150,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str onSave={handleSaveCircuitGroup} /> ) : null} - {gzfPickerCell ? ( - - ) : null} {protectionEditorCircuit ? ( setCableSizingEditorCircuit(null)} - singlePhaseVoltageV={data.singlePhaseVoltageV} - threePhaseVoltageV={data.threePhaseVoltageV} + onApply={handleApplyCableSizing} /> ) : null} - {data.feedingReference ? ( -
    - Gespeist von{" "} - - {data.feedingReference.distributionBoardNumber ?? - data.feedingReference.distributionBoardName} - {data.feedingReference.circuitEquipmentIdentifier ?? ""} - - {data.feedingReference.circuitId - ? null - : " (speisender Stromkreis noch nicht festgelegt)"} -
    - ) : null}
    - void handleUndo()} - showLabel + disabled={!historyState || historyState.undoDepth === 0 || historyBusy || isSaving} title={ historyState?.undoDepth ? `${historyState.undoDepth} Änderung(en) können rückgängig gemacht werden.` : undefined } - /> - + Rückgängig + + {isSortedView ? ( - void handleApplySortedOrder()} - showLabel + disabled={hasActiveFilters || isSaving || historyBusy} title={hasActiveFilters ? "Vor dem Übernehmen der Sortierung zuerst die Filter zurücksetzen." : undefined} - /> + > + Sortierung übernehmen + ) : null} - - - - + Spalten + + + + + {renderColumnSettingsMenu("col")}
    {renderActiveViewSummary()} @@ -3530,62 +3281,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str ) : null} {isSaving ?
    Wird gespeichert …
    : null}
    - {isRevitDrawerOpen ? ( - - ) : null} {isProjectDeviceDrawerOpen ? (
    {openFilterColumn === column.key ? ( @@ -4070,21 +3759,105 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str
    - void handleAddReserveCircuit(section.id)} + + + + + + + +
    {dropIntent?.kind === "new-circuit" && dropIntent.sectionId === section.id ? ( @@ -4244,13 +3930,9 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str key={row.rowKey} className={`${ row.rowType === "circuitSummary" - ? row.downstreamBoardLoad - ? "feeder-circuit-row" - : "summary-row" + ? "summary-row" : row.rowType === "deviceRow" ? "device-row" - : row.rowType === "downstreamBoardLoad" - ? "downstream-board-load-row" : row.rowType === "reserveCircuit" ? "empty-circuit-row" : row.rowType === "placeholder" @@ -4369,11 +4051,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str }`} onClick={() => setActiveSectionId(row.sectionId)} onDragOver={(event) => { - if (draggingExternalObjectIds.length > 0 && (row.device || row.circuit || row.rowType === "placeholder")) { - event.preventDefault(); - event.dataTransfer.dropEffect = "move"; - return; - } if (draggingCircuitCount > 0) { const valid = isCircuitDropTargetValid( row.sectionId @@ -4514,21 +4191,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str }); }} onDrop={(event) => { - if (draggingExternalObjectIds.length > 0 && row.device) { - event.preventDefault(); - void handleAssignExternalObjects(row.device.id, draggingExternalObjectIds); - return; - } - if (draggingExternalObjectIds.length > 0 && row.rowType === "placeholder") { - event.preventDefault(); - void handleAssignExternalObjectsToNewCircuit(row.sectionId, draggingExternalObjectIds); - return; - } - if (draggingExternalObjectIds.length > 0 && row.circuit) { - event.preventDefault(); - void handleAssignExternalObjectsToNewRow(row.circuit.id, draggingExternalObjectIds); - return; - } if (draggingCircuitCount > 0) { if (row.rowType === "placeholder") { void handleCircuitReorderDrop(event, { @@ -4620,10 +4282,15 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str row.circuit && row.rowType !== "deviceRow" ); + const isCableSizingTrigger = Boolean( + (column.key === "cableSummary" || column.key === "cableCrossSection") && + row.circuit && + row.rowType !== "deviceRow" + ); return ( { requestAnimationFrame(() => { const active = document.activeElement as HTMLElement | null; - if (active?.closest('[role="dialog"][aria-modal="true"]')) { - return; - } if (!active || !containerRef.current?.contains(active)) { setEditingCell(null); focusGridWithoutScroll(); @@ -4825,27 +4488,6 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str }); }} /> - ) : column.key === "simultaneityFactor" && - cell.editable && - isSelected ? ( - <> - - {formatCellValue(cell.value, column.key)} - ) : ( formatCellValue(cell.value, column.key) )} @@ -4876,65 +4518,30 @@ export function CircuitTreeEditor(props: { projectId: string; circuitListId: str : "" }`} > - {row.circuit && - (row.rowType === "circuitCompact" || - row.rowType === "circuitSummary" || - row.rowType === "reserveCircuit") ? ( + {row.circuit && row.rowType !== "deviceRow" ? ( <> - setCableSizingEditorCircuit(row.circuit!)} + + ) : null} {row.device ? ( - <> - {(row.device.externalObjectCount ?? 0) > 0 ? ( - - ) : null} - void handleDeleteDevice(row.device!.id)} - tabIndex={-1} - variant="danger" - /> - + ) : null} {dropIntent?.kind === "new-circuit" && row.rowType === "placeholder" && dropIntent.sectionId === row.sectionId ? ( diff --git a/src/frontend/components/distribution-board-info-card.tsx b/src/frontend/components/distribution-board-info-card.tsx index dcc4188..f2523f4 100644 --- a/src/frontend/components/distribution-board-info-card.tsx +++ b/src/frontend/components/distribution-board-info-card.tsx @@ -13,7 +13,7 @@ export type DistributionBoardInfoDraft = Record = { boardNumber: "z. B. UV 1.1", location: "z. B. Raum 003 Technik", - fedFrom: "z. B. HAK, Zähleranlage, Trafo oder NEA", + fedFrom: "z. B. HV 0.1 oder HAK / Zähleranlage", remark: "", }; @@ -98,8 +98,8 @@ export function DistributionBoardInfoCard({ )} {field === "fedFrom" ? (
    - Für externe Einspeisungen oder ergänzende Hinweise. Eine - speisende Projektverteilung wird oben logisch verknüpft. + Vorerst Freitext. Die logische Verknüpfung mit dem + speisenden Verteiler folgt.
    ) : null}
    diff --git a/src/frontend/components/filter-panel.tsx b/src/frontend/components/filter-panel.tsx deleted file mode 100644 index 9c9923b..0000000 --- a/src/frontend/components/filter-panel.tsx +++ /dev/null @@ -1,127 +0,0 @@ -"use client"; - -import { ChevronDown, ChevronRight, FilterX } from "lucide-react"; -import React, { useEffect, useId, useState, type ReactNode } from "react"; -import { IconButton } from "./icon-button"; - -function readCollapsed(storageKey: string) { - try { - return window.localStorage.getItem(storageKey) === "1"; - } catch { - return false; - } -} - -function writeCollapsed(storageKey: string, isCollapsed: boolean) { - try { - window.localStorage.setItem(storageKey, isCollapsed ? "1" : "0"); - } catch { - // Storage unavailable (private mode, blocked): keep the in-memory state. - } -} - -/** - * Collapsible filter area inside a card (PM app style): a small header row - * with toggle, label "Filter", a "Filter aktiv" badge while collapsed and the - * "x von y" count; below it the wrapping filter bar with a "Zurücksetzen" - * button while a filter is active. Only the bar collapses, never the card. - * The collapsed state is remembered per `storageKey` (default: expanded). - */ -export function CollapsibleFilterPanel({ - storageKey, - isFilterActive, - visibleCount, - totalCount, - onReset, - children, -}: { - storageKey: string; - isFilterActive: boolean; - visibleCount: number; - totalCount: number; - onReset: () => void; - children: ReactNode; -}) { - const [isCollapsed, setIsCollapsed] = useState(false); - const barId = useId(); - - useEffect(() => { - setIsCollapsed(readCollapsed(storageKey)); - }, [storageKey]); - - function toggleCollapsed() { - const next = !isCollapsed; - setIsCollapsed(next); - 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 ( -
    -
    - - {isCollapsed ? ( - <> - Filter - {isFilterActive ? Filter aktiv : null} - - ) : ( -
    - {children} - {isFilterActive ? ( - - ) : null} -
    - )} - - {visibleCount} von {totalCount} - -
    -
    - ); -} - -/** Search field for a filter bar. */ -export function FilterSearchField({ - label, - placeholder, - value, - onChange, -}: { - label: string; - placeholder: string; - value: string; - onChange: (value: string) => void; -}) { - return ( - - ); -} diff --git a/src/frontend/components/floor-select-options.tsx b/src/frontend/components/floor-select-options.tsx deleted file mode 100644 index bfaa2f6..0000000 --- a/src/frontend/components/floor-select-options.tsx +++ /dev/null @@ -1,49 +0,0 @@ -"use client"; - -import React from "react"; -import type { BuildingDto, FloorDto } from "../types"; -import { groupFloorsByBuilding } from "../utils/building-structure"; - -export type FloorOption = Pick & { - buildingId?: string | null; -}; - -interface FloorSelectOptionsProps { - buildings?: ReadonlyArray>; - floors: ReadonlyArray; -} - -/** - * Floor
    - ) : null} -
    - ); -} diff --git a/src/frontend/components/project-device-modal.tsx b/src/frontend/components/project-device-modal.tsx index 0d95223..27c24d0 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, type ReactNode, useState } from "react"; +import React, { FormEvent, useState } from "react"; import type { CreateProjectDeviceInput, GlobalDeviceDto, @@ -14,20 +14,10 @@ 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?: ProjectDeviceModalInitialValues; + initialValues?: Partial; isSaving: boolean; onClose: () => void; onImportGlobal: (globalDeviceId: string) => Promise; @@ -35,8 +25,6 @@ interface ProjectDeviceModalProps { } export function ProjectDeviceModal({ - context, - existingDevices = [], globalDevices, initialDevice, initialValues, @@ -48,11 +36,6 @@ 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 })); @@ -96,17 +79,6 @@ 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 ? (
    {error ? ( @@ -389,15 +381,14 @@ export function ProjectVersionHistory({ {formatDateTime(snapshot.createdAtIso)} -
    - setRestoreCandidate(snapshot)} - variant="danger" - /> -
    + ))} diff --git a/src/frontend/components/revit-csv-modal.tsx b/src/frontend/components/revit-csv-modal.tsx new file mode 100644 index 0000000..3602bd8 --- /dev/null +++ b/src/frontend/components/revit-csv-modal.tsx @@ -0,0 +1,666 @@ +"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-follow-up-import-wizard.tsx b/src/frontend/components/revit-follow-up-import-wizard.tsx deleted file mode 100644 index 8b561c5..0000000 --- a/src/frontend/components/revit-follow-up-import-wizard.tsx +++ /dev/null @@ -1,91 +0,0 @@ -"use client"; - -import { useState, type FormEvent } from "react"; -import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; -import type { ExternalFollowUpImportPlanDto, ProjectHistoryStateDto } from "../types"; -import { applyExternalFollowUpImport, planExternalFollowUpImport } from "../utils/api"; -import { createClientId } from "../utils/client-id"; -import { FormModal } from "./form-modal"; - -const steps = ["Vorschau", "Quelländerungen", "Neue Räume", "Familienregeln", "Projektgeräte", "Bestätigung"]; -const fieldLabels: Record = { ifcGuid: "IfcGUID", roomNumber: "Raumnummer", roomName: "Raumname", familyAndType: "Familie und Typ", selectionMarker: "Auswahlkenner", socketCount: "Anzahl", sourceRemark: "Bemerkung" }; - -export function RevitFollowUpImportWizard({ 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 [accepted, setAccepted] = useState>({}); - const [roomIds, setRoomIds] = useState>({}); - const [boardIds, setBoardIds] = useState>({}); - const [deviceIds, setDeviceIds] = useState>({}); - 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 planExternalFollowUpImport(projectId, nextFile, nextConfiguration, expectedRevision); - setPlan(loaded); - setAccepted((current) => Object.fromEntries(loaded.changes.map((change) => [change.objectId, current[change.objectId] ?? true]))); - setRoomIds((current) => Object.fromEntries(loaded.newSourceRoomKeys.map((key) => { const room = loaded.sourceRooms.find((candidate) => candidate.sourceRoomKey === key)!; return [key, current[key] ?? room.suggestedRoomId ?? ""]; }))); - setBoardIds((current) => Object.fromEntries(loaded.newSourceRoomKeys.map((key) => [key, current[key] ?? ""]))); - setDeviceIds((current) => Object.fromEntries(loaded.newFamilyAndTypes.map((family) => [family, current[family] ?? ""]))); - } catch (value) { setError(value instanceof Error ? value.message : "Folgeimport-Vorschau fehlgeschlagen."); setPlan(null); } - finally { setBusy(false); } - } - - async function addRule(familyAndType: string, category: "lighting" | "single_phase" | "three_phase", quantityRule: "one" | "socketCount", deviceTypeId?: string) { - if (!file) return; - const next = structuredClone(configuration); - const targetTypeId = deviceTypeId ?? createClientId(); - if (!deviceTypeId) next.deviceTypes.push({ id: targetTypeId, name: familyAndType, category, defaults: { powerPerUnitW: null, simultaneityFactor: 1, cosPhi: null, costGroup: null } }); - next.familyTypeRules.push({ id: createClientId(), exactFamilyAndType: familyAndType, deviceTypeId: targetTypeId, 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 applyExternalFollowUpImport(projectId, file, { - expectedRevision, expectedSha256: plan.sha256, configuration, objectsWithoutRoomDefaultDistributionBoardId: noRoomBoardId || null, - sourceChangeDecisions: plan.changes.map((change) => ({ objectId: change.objectId, accept: accepted[change.objectId] ?? false })), - roomDecisions: plan.newSourceRoomKeys.map((sourceRoomKey) => ({ sourceRoomKey, roomId: roomIds[sourceRoomKey] || null, defaultDistributionBoardId: boardIds[sourceRoomKey] || null })), - familyProjectDeviceDecisions: plan.newFamilyAndTypes.map((familyAndType) => ({ familyAndType, projectDeviceId: deviceIds[familyAndType] || null })), - }); - onImported({ history: result.history, objectCount: result.import.objectCount }); - } catch (value) { setError(value instanceof Error ? value.message : "Folgeimport fehlgeschlagen."); } - finally { setBusy(false); } - } - - const relevantUnknownFamilies = plan?.familyGroups.filter((family) => !family.classified && (plan.newFamilyAndTypes.includes(family.familyAndType) || plan.changes.some((change) => accepted[change.objectId] && change.familyAndType === family.familyAndType))) ?? []; - const relevantInvalidQuantity = plan?.objects.some((object) => object.issues.includes("invalid-quantity") && (plan.newObjectWorksharingIds.includes(object.worksharingId) || plan.changes.some((change) => change.worksharingId === object.worksharingId && accepted[change.objectId]))) ?? false; - const invalidQuantityFamilies = plan ? [...new Set(plan.objects.filter((object) => object.issues.includes("invalid-quantity") && (plan.newObjectWorksharingIds.includes(object.worksharingId) || plan.changes.some((change) => change.worksharingId === object.worksharingId && accepted[change.objectId]))).map((object) => object.sourceValues.familyAndType))] : []; - const blocked = !plan || relevantUnknownFamilies.length > 0 || relevantInvalidQuantity; - return void submit(event)} submitDisabled={blocked} submitLabel={step === steps.length - 1 ? "Folgeimport ü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.returnDeviationCount} Objekte enthalten Rückgabefelder, die in Revit noch nicht aktualisiert sind.
    {plan.warnings.length ?
    {plan.warnings.map((warning) =>
    {warning}
    )}
    : null} : null}
    : null} - {step === 1 && plan ?

    Nur fachliche Quelländerungen benötigen eine Entscheidung. Abweichende Rückgabefelder werden lediglich als „in Revit noch nicht aktualisiert“ gemeldet.

    {plan.changes.length ? plan.changes.map((change) => ) :
    Keine fachlichen Quelländerungen.
    }{plan.missingObjects.length ?
    {plan.missingObjects.length} fehlende Objekte werden markiert. Links und Mengen bleiben bestehen.
    : null}
    : null} - {step === 2 && plan ?

    Nur neue, tatsächlich übernommene Quellräume benötigen eine Zuordnung.

    {plan.newSourceRoomKeys.map((key) => { const room = plan.sourceRooms.find((candidate) => candidate.sourceRoomKey === key)!; return
    {room.roomNumber || "–"} {room.roomName}
    ; })}
    : null} - {step === 3 && plan ?

    Unbekannte Familien müssen nur für neue Objekte oder akzeptierte Familienänderungen klassifiziert werden.

    {relevantUnknownFamilies.map((family) =>
    {family.familyAndType}
    {configuration.deviceTypes.flatMap((type) => [, ])}
    )}{!relevantUnknownFamilies.length ?
    Alle benötigten Familien sind klassifiziert.
    : null}{relevantInvalidQuantity ?
    Mindestens eine übernommene Mengenangabe ist ungültig.{invalidQuantityFamilies.map((family) => )}
    : null}
    : null} - {step === 4 && plan ?

    Neue Revit-Objekte können familienweise mit einem vorhandenen Projektgerät verknüpft werden.

    {plan.newFamilyAndTypes.map((family) =>
    {family}
    )}
    : null} - {step === 5 && plan ?
    {plan.objectCount} Objekte im vollständigen Import.
    Neu: {plan.newObjectCount}, fachlich geändert: {plan.changedObjectCount}, fehlend: {plan.missingObjectCount}. Fehlende Objekte werden nicht gelöst oder gelöscht. Apply liest die Datei erneut; Undo und Redo verwenden ausschließlich die gespeicherten Zustände.
    : null} - {step > 0 ? : null} -
    ; -} - -function Count({ label, value }: { label: string; value: number }) { return
    {value}
    {label}
    ; } diff --git a/src/frontend/components/revit-initial-import-wizard.tsx b/src/frontend/components/revit-initial-import-wizard.tsx deleted file mode 100644 index 8a4fc4d..0000000 --- a/src/frontend/components/revit-initial-import-wizard.tsx +++ /dev/null @@ -1,106 +0,0 @@ -"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/components/revit-object-table-model.ts b/src/frontend/components/revit-object-table-model.ts deleted file mode 100644 index 2618ccc..0000000 --- a/src/frontend/components/revit-object-table-model.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { ExternalProjectObjectDto } from "../types"; - -export type RevitObjectSort = "family" | "room" | "worksharing"; - -export function filterAndSortRevitObjects( - objects: readonly ExternalProjectObjectDto[], - input: { search: string; boardFilter: string; assignmentFilter: string; sort: RevitObjectSort } -) { - const needle = input.search.trim().toLocaleLowerCase("de-DE"); - return objects.filter((object) => { - if (input.boardFilter !== "all" && (input.boardFilter === "none" ? object.distributionBoardId !== null : object.distributionBoardId !== input.boardFilter)) return false; - if (input.assignmentFilter === "unassigned" && object.circuitDeviceRowId !== null) return false; - if (input.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((leftObject, rightObject) => { - const left = input.sort === "family" ? leftObject.familyAndType : input.sort === "room" ? `${leftObject.sourceRoomNumber}\u0000${leftObject.sourceRoomName}` : leftObject.worksharingId; - const right = input.sort === "family" ? rightObject.familyAndType : input.sort === "room" ? `${rightObject.sourceRoomNumber}\u0000${rightObject.sourceRoomName}` : rightObject.worksharingId; - return left.localeCompare(right, "de", { numeric: true }) || leftObject.worksharingId.localeCompare(rightObject.worksharingId); - }); -} - -export function createVirtualRevitObjectWindow(rows: readonly T[], scrollTop: number, rowHeight: number, viewportHeight: number, overscan = 5) { - const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan); - return { first, rows: rows.slice(first, first + Math.ceil(viewportHeight / rowHeight) + overscan * 2) }; -} diff --git a/src/frontend/components/revit-object-table.tsx b/src/frontend/components/revit-object-table.tsx deleted file mode 100644 index 2ab56c9..0000000 --- a/src/frontend/components/revit-object-table.tsx +++ /dev/null @@ -1,108 +0,0 @@ -"use client"; - -import { useEffect, useMemo, useState } from "react"; -import type { ExternalProjectObjectsDto, ExternalReturnScopeDto } from "../types"; -import { createExternalReturnWorkbook, deleteMissingExternalProjectObjects, getExternalProjectObjects, updateExternalProjectObjects } from "../utils/api"; -import { createVirtualRevitObjectWindow, filterAndSortRevitObjects, type RevitObjectSort } from "./revit-object-table-model"; - -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"); - 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); - const [returnScope, setReturnScope] = useState("all"); - const [exporting, setExporting] = useState(false); - const [exportWarnings, setExportWarnings] = useState([]); - const [exportMessage, setExportMessage] = useState(null); - - 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 []; - return filterAndSortRevitObjects(data.objects, { search, boardFilter, assignmentFilter, sort }); - }, [data, search, boardFilter, assignmentFilter, sort]); - const { first, rows: visible } = createVirtualRevitObjectWindow(rows, scrollTop, rowHeight, viewportHeight); - const selectable = rows.filter((object) => object.circuitDeviceRowId === null); - const returnSelectable = rows.filter((object) => object.presenceStatus === "present"); - const selectedHasLinkedObject = data?.objects.some((object) => selected.has(object.id) && object.circuitDeviceRowId !== null) ?? false; - const selectedMissing = data?.objects.filter((object) => selected.has(object.id) && object.presenceStatus === "missing") ?? []; - const selectionContainsPresentObject = data?.objects.some((object) => selected.has(object.id) && object.presenceStatus === "present") ?? false; - - 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); } - } - - async function exportReturnWorkbook() { - if (!data || (returnScope === "selected" && selected.size === 0)) return; - setExporting(true); setError(null); setExportWarnings([]); setExportMessage(null); - try { - const result = await createExternalReturnWorkbook(projectId, data.currentRevision, returnScope, [...selected]); - downloadBase64(result.contentBase64, result.fileName); - setExportWarnings(result.warnings); - setExportMessage(`${result.objectCount} Revit-Objekte wurden in ${result.fileName} geschrieben.`); - } catch (value) { - setError(value instanceof Error ? value.message : "Rückgabe-Excel konnte nicht erstellt werden."); - } finally { - setExporting(false); - } - } - - async function deleteMissing() { - if (!data || selectedMissing.length === 0 || selectionContainsPresentObject) return; - if (!window.confirm(`${selectedMissing.length} fehlende Revit-Objekte wirklich löschen? Verknüpfte Mengen werden angepasst. Undo stellt Objekte, Links und Mengen wieder her.`)) return; - setSaving(true); setError(null); - try { const result = await deleteMissingExternalProjectObjects(projectId, data.currentRevision, selectedMissing.map((object) => object.id)); onRevision(result.history.currentRevision); setSelected(new Set()); await load(); } - catch (value) { setError(value instanceof Error ? value.message : "Fehlende Revit-Objekte konnten nicht gelöscht werden."); } - 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} -
    {exportMessage ?
    {exportMessage}
    : null}{exportWarnings.length ?
    Hinweise zur Rückgabe:
      {exportWarnings.map((warning) =>
    • {warning}
    • )}
    : null}
    -
    setScrollTop(event.currentTarget.scrollTop)}>
    {visible.map((object, index) => { const top = (first + index) * rowHeight; const linked = object.circuitDeviceRowId !== null; const missing = object.presenceStatus === "missing"; 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}
    {missing ? "fehlend" : linked ? "verknüpft" : "frei"}
    ; })}
    -
    {planningField ? : null}
    -
    ; -} - -function downloadBase64(contentBase64: string, fileName: string) { - const binary = atob(contentBase64); - const bytes = new Uint8Array(binary.length); - for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index); - const url = URL.createObjectURL(new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })); - const anchor = document.createElement("a"); - anchor.href = url; - anchor.download = fileName; - anchor.click(); - URL.revokeObjectURL(url); -} diff --git a/src/frontend/components/revit-xlsx-settings-modal.tsx b/src/frontend/components/revit-xlsx-settings-modal.tsx deleted file mode 100644 index 899c3ca..0000000 --- a/src/frontend/components/revit-xlsx-settings-modal.tsx +++ /dev/null @@ -1,46 +0,0 @@ -"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, isNewConfiguration = false, isSaving, onClose, onInspectSample, onSave }: { - configuration: ExternalModelConfiguration; - isNewConfiguration?: boolean; - 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/components/room-modal.tsx b/src/frontend/components/room-modal.tsx index b8a0ff0..e5648e0 100644 --- a/src/frontend/components/room-modal.tsx +++ b/src/frontend/components/room-modal.tsx @@ -1,18 +1,11 @@ "use client"; import React, { type FormEvent, useState } from "react"; -import type { BuildingDto, CreateRoomInput, RoomDto } from "../types"; -import { FloorSelectOptions, type FloorOption } from "./floor-select-options"; +import type { CreateRoomInput, FloorDto, RoomDto } from "../types"; import { FormModal } from "./form-modal"; -import { - formatOptionalRoomAreaInput, - parseRoomAreaInput, -} from "../utils/room-area"; interface RoomModalProps { - /** When given, the floor select groups floors by building. */ - buildings?: ReadonlyArray>; - floors: ReadonlyArray; + floors: FloorDto[]; initialRoom?: RoomDto; initialValues?: Partial; isSaving: boolean; @@ -22,7 +15,6 @@ interface RoomModalProps { } export function RoomModal({ - buildings, floors, initialRoom, initialValues, @@ -40,21 +32,14 @@ export function RoomModal({ const [floorId, setFloorId] = useState( initialRoom?.floorId ?? initialValues?.floorId ?? "" ); - const [areaText, setAreaText] = useState(() => - formatOptionalRoomAreaInput( - initialRoom ? initialRoom.areaM2 : initialValues?.areaM2 - ) - ); - const parsedArea = parseRoomAreaInput(areaText); async function handleSubmit(event: FormEvent) { event.preventDefault(); - if (!roomNumber.trim() || !roomName.trim() || !parsedArea.ok) return; + if (!roomNumber.trim() || !roomName.trim()) return; await onSave({ floorId: floorId || undefined, roomNumber: roomNumber.trim(), roomName: roomName.trim(), - areaM2: parsedArea.value, }); } @@ -63,7 +48,7 @@ export function RoomModal({ isSaving={isSaving} onClose={onClose} onSubmit={handleSubmit} - submitDisabled={!roomNumber.trim() || !roomName.trim() || !parsedArea.ok} + submitDisabled={!roomNumber.trim() || !roomName.trim()} submitLabel={initialRoom ? "Änderungen speichern" : "Raum anlegen"} title={initialRoom ? "Raum bearbeiten" : "Raum hinzufügen"} > @@ -98,30 +83,9 @@ export function RoomModal({ value={floorId} > - + {floors.map((floor) => )}
    -
    - - setAreaText(event.target.value)} - placeholder="z. B. 23,45" - type="text" - value={areaText} - /> -
    - {parsedArea.ok - ? "Optionale Netto-Raumfläche; Eingabe mit Dezimalkomma." - : parsedArea.error} -
    -
    {initialRoom && onDelete ? (
    diff --git a/src/frontend/estimate-balance/estimate-balance-create-modal.tsx b/src/frontend/estimate-balance/estimate-balance-create-modal.tsx deleted file mode 100644 index 6d8f123..0000000 --- a/src/frontend/estimate-balance/estimate-balance-create-modal.tsx +++ /dev/null @@ -1,162 +0,0 @@ -"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 deleted file mode 100644 index e2726d1..0000000 --- a/src/frontend/estimate-balance/estimate-balance-document.ts +++ /dev/null @@ -1,298 +0,0 @@ -// 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, - 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, - 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), - 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 deleted file mode 100644 index 85cddf3..0000000 --- a/src/frontend/estimate-balance/estimate-balance-format.ts +++ /dev/null @@ -1,122 +0,0 @@ -// 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 deleted file mode 100644 index 4bfa927..0000000 --- a/src/frontend/estimate-balance/estimate-balance-sheet.tsx +++ /dev/null @@ -1,684 +0,0 @@ -"use client"; - -import type { ReactNode } from "react"; -import { ArrowDown, ArrowUp, PackagePlus, 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, - formatGermanNumber, -} 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; - onTakeOverRow: (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 = 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, - 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" - printFormat={(current: number) => formatGermanNumber(current, 0, 3)} - onCommit={onCommit} - onValidityChange={(isValid) => onValidityChange(fieldKey, isValid)} - parse={(text) => parseGermanDecimal(text, range)} - value={value} - /> - ); -} - -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, - value, -}: { - ariaLabel: string; - disabled: boolean; - list?: string; - 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, - onTakeOverRow, - onValidityChange, - row, - rowIndex, -}: { - disabled: boolean; - group: EstimateGroupSnapshot; - onChange: EstimateBalanceUpdate; - onOpenGzfPicker: (groupId: string, rowId: string) => void; - onTakeOverRow: (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({ 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} - /> - - -
    - onTakeOverRow(group.id, row.id)} - variant="primary" - > - - 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, - onTakeOverRow, - 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 ( -
    - - {supplyOptions(balance).map((supply) => ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {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/MSR … - 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 deleted file mode 100644 index f7098b0..0000000 --- a/src/frontend/estimate-balance/estimate-comparison-table.tsx +++ /dev/null @@ -1,88 +0,0 @@ -"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 deleted file mode 100644 index 904fa2e..0000000 --- a/src/frontend/estimate-balance/estimate-draft-input.tsx +++ /dev/null @@ -1,112 +0,0 @@ -"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; - /** Printed text; defaults to the input text. */ - printFormat?: (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, - printFormat, - 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} - /> - - {printFormat ? printFormat(value) : error ? format(value) : text} - - - ); -} diff --git a/src/frontend/estimate-balance/estimate-group-modal.tsx b/src/frontend/estimate-balance/estimate-group-modal.tsx deleted file mode 100644 index 8d56308..0000000 --- a/src/frontend/estimate-balance/estimate-group-modal.tsx +++ /dev/null @@ -1,128 +0,0 @@ -"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/estimate-balance/estimate-print-header.tsx b/src/frontend/estimate-balance/estimate-print-header.tsx deleted file mode 100644 index 84ce3e9..0000000 --- a/src/frontend/estimate-balance/estimate-print-header.tsx +++ /dev/null @@ -1,104 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { documentLogoUrl, getDocumentBranding } from "../utils/api"; -import type { EstimateBalanceDto, OfficeProfileDto, ProjectDto } from "../types"; -import { formatIsoDateGerman } from "./estimate-balance-format"; - -interface EstimatePrintHeaderProps { - project: ProjectDto; - balance: EstimateBalanceDto; -} - -function cssString(value: string) { - return JSON.stringify(value.replace(/[<>\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 ( - <> - - - - ); -} diff --git a/src/frontend/estimate-balance/estimate-project-device-prefill.ts b/src/frontend/estimate-balance/estimate-project-device-prefill.ts deleted file mode 100644 index 4ef9b52..0000000 --- a/src/frontend/estimate-balance/estimate-project-device-prefill.ts +++ /dev/null @@ -1,51 +0,0 @@ -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/src/frontend/print/print-document-model.ts b/src/frontend/print/print-document-model.ts index d3e4724..c0df6b7 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; - /** Device-row demand plus downstream-board demand before this board's GZF. */ - powerBeforeBoardSimultaneityKw: number; + /** Σ row totals, i.e. with the device-row simultaneity factors. */ + devicePowerKw: number; simultaneityFactor: number; - /** Total active power with this board's simultaneity factor applied. */ + /** Device power with the board simultaneity factor applied. */ demandPowerKw: number; /** - * Design current from the apparent power including downstream boards. - * The selected feeder circuit determines whether one or three phases apply. + * Symmetrical three-phase design current from the apparent power + * S = Σ(row total / cos φ) × board GZF. A missing cos φ counts as 1. */ designCurrentA: number; } @@ -46,13 +46,8 @@ 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; @@ -60,13 +55,12 @@ export function summarizePrintBoard(input: { ...input, circuitCount, installedPowerKw, - powerBeforeBoardSimultaneityKw: tree.distributionBoardTotalPower, + devicePowerKw: tree.distributionBoardTotalPower, simultaneityFactor, demandPowerKw: tree.distributionBoardTotalPowerWithSimultaneityFactor, - designCurrentA: calculateDesignCurrent( - apparentPowerKva * simultaneityFactor, - tree - ), + designCurrentA: + (apparentPowerKva * simultaneityFactor * 1000) / + (Math.sqrt(3) * tree.threePhaseVoltageV), }; } @@ -74,33 +68,34 @@ 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( - revision: number, - summaries: readonly PrintBoardSummary[], - finalRevision: number -) { - if (finalRevision !== revision || summaries.some(({ tree }) => tree.currentRevision !== revision)) { - throw new Error("Das Projekt wurde während des Ladens geändert. Bitte die Seitenansicht neu laden."); - } -} - -export function buildBoardHierarchy( +/** + * 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( summaries: PrintBoardSummary[] ): PrintBoardHierarchyEntry[] { - const summaryById = new Map( - summaries.map((summary) => [summary.board.id, summary]) - ); + const normalize = (value: string | null) => + value?.trim().toLocaleLowerCase("de") || null; const parentById = new Map(); for (const summary of summaries) { - const parentId = summary.board.feedingDistributionBoardId; - parentById.set( - summary.board.id, - parentId && parentId !== summary.board.id && summaryById.has(parentId) - ? parentId - : null - ); + const fedFrom = normalize(summary.board.fedFrom); + const parent = fedFrom + ? summaries.find( + (candidate) => + candidate !== summary && + (normalize(candidate.board.boardNumber) === fedFrom || + normalize(candidate.board.name) === fedFrom) + ) + : undefined; + parentById.set(summary.board.id, parent?.board.id ?? null); } for (const summary of summaries) { const visited = new Set([summary.board.id]); @@ -119,12 +114,20 @@ export function buildBoardHierarchy( 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)); }; @@ -132,25 +135,6 @@ export function buildBoardHierarchy( 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, @@ -192,5 +176,5 @@ export function formatProtectionDevice( } export function formatCircuitCable(circuit: CircuitTreeCircuitDto): string | null { - return [circuit.cableType, circuit.cableCrossSection].filter(Boolean).join(" · ") || null; + return circuit.cableType || circuit.cableCrossSection || null; } diff --git a/src/frontend/print/print-document.css b/src/frontend/print/print-document.css index e814293..92b727f 100644 --- a/src/frontend/print/print-document.css +++ b/src/frontend/print/print-document.css @@ -1,6 +1,6 @@ -/* Print view (Seitenansicht) in the kbp corporate design. Colors are - derived from the kbp logo and presentation material; change them only - here. +/* Print view (Seitenansicht) in the provisional kbp corporate design. + Colors are derived from the kbp logo and presentation material and will be + replaced by the official CD specification; change them only here. All selectors are scoped to .print-view. The @page rules (format, margins, page numbers) are injected by the print page because they need project data. */ @@ -450,11 +450,6 @@ span.pd-tb-logo-image { .print-view { background: #fff !important; } - /* The dark theme sets color-scheme: dark on the root; Chrome then paints - the page margins dark. Printing always uses the light scheme. */ - html:has(.print-view) { - color-scheme: light !important; - } .pd-toolbar, .pd-sheet-footer { display: none !important; diff --git a/src/frontend/print/print-document.tsx b/src/frontend/print/print-document.tsx index a13d7e1..98a9df3 100644 --- a/src/frontend/print/print-document.tsx +++ b/src/frontend/print/print-document.tsx @@ -13,7 +13,6 @@ import { formatCircuitCable, formatCurrent, formatFactor, - formatFeedingReference, formatKilowatt, formatProtectionDevice, formatUnitPower, @@ -270,8 +269,8 @@ function OverviewSheet({ stand: string; }) { const roots = entries.filter((entry) => entry.parentBoardId === null); - // Root boards may still carry an external feed description such as - // "HAK / Zähleranlage"; logical board links determine the actual tree. + // 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"). const feedGroups = new Map(); for (const root of roots) { const feed = root.summary.board.fedFrom ?? ""; @@ -321,10 +320,11 @@ function OverviewSheet({ Nr.BezeichnungÖrtlichkeitEtageNetzGespeist von SK Pinst
    [kW] - P vor Vert.-GZF
    [kW] + PGeräte
    [kW] GZF
    Vert. - Pgl inkl. UV
    [kW] + Pgl
    [kW] IB
    [A] + Σ inkl.
    unterlagert [kW] @@ -340,45 +340,40 @@ function OverviewSheet({ {board.location ?? "–"} {entry.summary.floorName ?? "–"} {board.supplyType ?? "–"} - {formatFeedingReference(entry.summary)} + {board.fedFrom ?? "–"} {entry.summary.circuitCount} {formatKilowatt(entry.summary.installedPowerKw)} - {formatKilowatt(entry.summary.powerBeforeBoardSimultaneityKw)} + {formatKilowatt(entry.summary.devicePowerKw)} {formatFactor(entry.summary.simultaneityFactor)} {formatKilowatt(entry.summary.demandPowerKw)} {formatCurrent(entry.summary.designCurrentA)} + {formatKilowatt(entry.cumulatedDemandPowerKw)} ); })} - Summe der Einspeisungen + Summe aller Verteiler (ohne übergeordneten GZF) {formatKilowatt(sum((entry) => entry.summary.installedPowerKw))} - {formatKilowatt(sum((entry) => - entry.parentBoardId === null - ? entry.summary.powerBeforeBoardSimultaneityKw - : 0 - ))} + {formatKilowatt(sum((entry) => entry.summary.devicePowerKw))} + + {formatKilowatt(sum((entry) => entry.summary.demandPowerKw))} - {formatKilowatt(sum((entry) => - entry.parentBoardId === null ? entry.summary.demandPowerKw : 0 - ))}

    - 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. + Vorläufig: „Gespeist von“ ist noch ein Freitextfeld. Struktur und + „Σ inkl. unterlagert“ werden nur über gleichlautende Verteilernummern bzw. + -bezeichnungen zugeordnet und einfach addiert (kein übergeordneter GZF). Die fachliche + Verknüpfung und Summierung folgt.

    - 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 + 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

    @@ -408,7 +403,6 @@ function ComponentRow({ component }: { component: CircuitTreeComponentDto }) { function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { const rows = circuit.deviceRows; - const downstreamBoards = circuit.downstreamBoardLoads ?? []; const circuitCells = ( <> {formatProtectionDevice(circuit.protectionDevice) ?? } @@ -419,7 +413,7 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { {circuit.remark ?? ""} ); - if (rows.length === 0 && downstreamBoards.length === 0) { + if (rows.length === 0) { return ( {circuit.equipmentIdentifier} @@ -431,26 +425,7 @@ 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) { + if (rows.length === 1) { const row = rows[0]; const title = circuit.displayName ?? row.displayName; return ( @@ -492,16 +467,6 @@ function CircuitRows({ circuit }: { circuit: CircuitTreeCircuitDto }) { ))} - {downstreamBoards.map((load) => ( - - - Unterverteilung {load.boardNumber ?? load.name} - – - - {formatKilowatt(load.activePowerKw)} - Automatisch aus der verknüpften Verteilung - - ))} ); } @@ -535,7 +500,7 @@ function BoardPlanSheet({ rows={[ ["Örtlichkeit", [board.location, summary.floorName].filter(Boolean).join(" · ") || "–"], ["Netzart", board.supplyType ?? "–"], - ["Gespeist von", formatFeedingReference(summary)], + ["Gespeist von", board.fedFrom ?? "–"], [ <>Pgl, <> @@ -576,7 +541,7 @@ function BoardPlanSheet({ Summe Verteiler (Pinst {formatKilowatt(summary.installedPowerKw)} kW) - {formatKilowatt(summary.powerBeforeBoardSimultaneityKw)} + {formatKilowatt(summary.devicePowerKw)} diff --git a/src/frontend/types.ts b/src/frontend/types.ts index 78b8227..49bb77f 100644 --- a/src/frontend/types.ts +++ b/src/frontend/types.ts @@ -10,80 +10,59 @@ import type { ProtectionDeviceType, RcdType, } from "../shared/constants/protection-device"; -import type { ExternalModelConfiguration } from "../external-model/configuration/external-model-configuration"; +import type { + ExternalCsvConfiguration, + ExternalCsvDialect, +} from "../external-model/csv/external-csv-contracts"; +import type { createExternalInitialImportPlan } from "../external-model/application/external-initial-import-plan"; -export interface ExternalModelConfigurationSnapshotDto { +export interface ExternalCsvConfigurationSnapshotDto { id: string; projectId: string; - configuration: ExternalModelConfiguration; + configurationVersion: number; + configuration: ExternalCsvConfiguration; } -export interface ExternalInitialImportPlanDto { +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; - sha256: 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[]; - 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: 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<{ - 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 type ExternalInitialImportPlanDto = ReturnType< + typeof createExternalInitialImportPlan +>; + 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; @@ -95,15 +74,6 @@ export interface ApplyExternalInitialImportInput { }>; } -export interface ExternalInitialImportStatusDto { - imported: boolean; - sourceName: string | null; - objectCount: number; - missingObjectCount: number; - importedAtIso: string | null; - fileName: string | null; -} - export interface ExternalInitialImportResultDto extends ProjectCommandResultDto { import: { sourceId: string; @@ -112,72 +82,6 @@ export interface ExternalInitialImportResultDto extends ProjectCommandResultDto }; } -export interface ExternalFollowUpImportPlanDto extends ExternalInitialImportPlanDto { - newObjectCount: number; - changedObjectCount: number; - unchangedObjectCount: number; - missingObjectCount: number; - returnDeviationCount: number; - newObjectWorksharingIds: string[]; - newSourceRoomKeys: string[]; - newFamilyAndTypes: string[]; - changes: Array<{ objectId: string; worksharingId: string; familyAndType: string; changedFields: string[]; previousQuantity: number; suggestedQuantity: number; circuitDeviceRowId: string | null }>; - missingObjects: Array<{ objectId: string; worksharingId: string; familyAndType: string; circuitDeviceRowId: string | null }>; - returnDeviations: Array<{ objectId: string; worksharingId: string; fields: string[] }>; -} - -export interface ApplyExternalFollowUpImportInput { - expectedRevision: number; - expectedSha256: string; - configuration: ExternalModelConfiguration; - objectsWithoutRoomDefaultDistributionBoardId: string | null; - sourceChangeDecisions: Array<{ objectId: string; accept: boolean }>; - roomDecisions: Array<{ sourceRoomKey: string; roomId: string | null; defaultDistributionBoardId: string | null }>; - familyProjectDeviceDecisions: Array<{ familyAndType: string; projectDeviceId: string | null }>; -} - -export interface ExternalFollowUpImportResultDto extends ProjectCommandResultDto { - import: { importBatchId: string; objectCount: number; newObjectCount: number; changedObjectCount: number; missingObjectCount: number }; -} - -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 type ExternalReturnScopeDto = "all" | "deviating" | "selected"; - -export interface ExternalReturnWorkbookDto { - fileName: string; - contentBase64: string; - sha256: string; - objectCount: number; - warnings: string[]; -} - -export interface ExternalExportBatchDto { - id: string; - projectId: string; - projectRevision: number; - importBatchId: string; - exportedAtIso: string; - fileName: string; - sha256: string; - configurationSha256: string; - scope: ExternalReturnScopeDto; - objectCount: number; -} - export interface ProjectDto { id: string; name: string; @@ -291,8 +195,6 @@ export interface DistributionBoardDto extends DistributionBoardInfoDto { floorId: string | null; supplyType: DistributionBoardSupplyType | null; simultaneityFactor: number; - feedingDistributionBoardId: string | null; - feedingCircuitId: string | null; } export interface DocumentLogoMetadataDto { @@ -324,24 +226,11 @@ export interface CircuitListDto { name: string; } -export interface BuildingDto { - id: string; - projectId: string; - name: string; - sortOrder: number; -} - -export interface ProjectBuildingCommandResultDto - extends ProjectCommandResultDto { - building: BuildingDto; -} - export interface FloorDto { id: string; projectId: string; name: string; sortOrder: number; - buildingId: string | null; } export interface ProjectFloorCommandResultDto @@ -355,7 +244,6 @@ export interface RoomDto { floorId: string | null; roomNumber: string; roomName: string; - areaM2: number | null; } export interface GlobalDeviceDto { @@ -400,21 +288,14 @@ export interface ProjectDeviceCommandResultDto projectDevice: ProjectDeviceDto; } -export interface CreateBuildingInput { - name: string; -} - export interface CreateFloorInput { name: string; - /** Omitted = keep the current assignment on update; null = no building. */ - buildingId?: string | null; } export interface CreateRoomInput { floorId?: string; roomNumber: string; roomName: string; - areaM2: number | null; } export interface CreateGlobalDeviceInput { @@ -499,7 +380,6 @@ export interface CircuitTreeDeviceRowDto { remark?: string; overriddenFields?: string; rowTotalPower: number; - externalObjectCount?: number; } export interface CircuitTreeProtectionDeviceDto { @@ -541,10 +421,7 @@ export interface CircuitTreeCircuitDto { isReserve: boolean; remark?: string; circuitTotalPower: number; - circuitApparentPower: number; - circuitCosPhi: number; deviceRows: CircuitTreeDeviceRowDto[]; - downstreamBoardLoads: CircuitTreeDownstreamBoardLoadDto[]; protectionDevice?: CircuitTreeProtectionDeviceDto; } @@ -563,11 +440,6 @@ export interface CircuitTreeSectionDto { export interface CircuitTreeResponseDto { circuitListId: string; - distributionBoardId: string; - distributionBoardName: string; - distributionBoardNumber?: string; - distributionBoardSupplyType?: DistributionBoardSupplyType; - feedingReference?: CircuitTreeFeedingReferenceDto; currentRevision: number; singlePhaseVoltageV: number; threePhaseVoltageV: number; @@ -579,32 +451,6 @@ export interface CircuitTreeResponseDto { footerComponents: CircuitTreeComponentDto[]; } -export interface CircuitTreeDownstreamBoardLoadDto { - distributionBoardId: string; - name: string; - boardNumber?: string; - supplyType?: DistributionBoardSupplyType; - activePowerKw: number; - apparentPowerKva: number; - cosPhi: number; -} - -export interface CircuitTreeFeedingReferenceDto { - distributionBoardId: string; - circuitListId: string; - distributionBoardName: string; - distributionBoardNumber?: string; - circuitId?: string; - circuitEquipmentIdentifier?: string; - circuitDisplayName?: string; - circuitCategory?: CircuitGroupCategory; -} - -export interface ProjectCircuitTreesResponseDto { - currentRevision: number; - trees: CircuitTreeResponseDto[]; -} - export interface ExternalCircuitListObjectDto { id: string; ifcGuid: string; @@ -670,34 +516,3 @@ 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 a793a95..d55a915 100644 --- a/src/frontend/utils/api.ts +++ b/src/frontend/utils/api.ts @@ -1,11 +1,5 @@ -import { - WRITE_REQUEST_HEADER_NAME, - WRITE_REQUEST_HEADER_VALUE, -} from "../../shared/constants/request-security"; import type { - BuildingDto, CircuitListDto, - CreateBuildingInput, CreateFloorInput, CreateProjectDeviceInput, CreateRoomInput, @@ -23,7 +17,6 @@ import type { ProjectCommandResultDto, ProjectDeviceCommandResultDto, ProjectDeviceDto, - ProjectBuildingCommandResultDto, ProjectFloorCommandResultDto, ProjectHistoryStateDto, ProjectRevisionPageDto, @@ -37,25 +30,13 @@ import type { ProjectDto, RoomDto, CircuitTreeResponseDto, - ProjectCircuitTreesResponseDto, - ExternalModelConfigurationSnapshotDto, + ExternalCsvConfigurationSnapshotDto, + ExternalCsvPreviewDto, ExternalInitialImportPlanDto, - ExternalInitialImportResultDto, - ExternalFollowUpImportPlanDto, - ExternalFollowUpImportResultDto, - ApplyExternalFollowUpImportInput, - ExternalInitialImportStatusDto, ApplyExternalInitialImportInput, - ExternalProjectObjectsDto, - ExternalReturnScopeDto, - ExternalReturnWorkbookDto, - CreateEstimateBalanceInput, - EstimateBalanceCommandResultDto, - EstimateBalanceDto, - EstimateBalanceUpdateResultDto, - EstimateComparisonDto, + ExternalInitialImportResultDto, } from "../types"; -import type { ExternalModelConfiguration } from "../../external-model/configuration/external-model-configuration"; +import type { ExternalCsvConfiguration } from "../../external-model/csv/external-csv-contracts"; import type { ProjectDeviceSyncField } from "../../shared/constants/project-device-sync-fields"; import { createCircuitUpdateProjectCommand, @@ -103,36 +84,11 @@ 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, headers: { "Content-Type": "application/json", - [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, ...init?.headers, }, cache: "no-store", @@ -140,23 +96,15 @@ 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; code?: unknown }; + const parsed = JSON.parse(details) as { error?: 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 ApiRequestError( - details || `Anfrage fehlgeschlagen (Status ${response.status})`, - response.status, - code - ); + throw new Error(details || `Anfrage fehlgeschlagen (Status ${response.status})`); } if (response.status === 204) { @@ -174,136 +122,6 @@ 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 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) }), - }); -} - -export async function planExternalFollowUpImport(projectId: string, file: File, configuration: ExternalModelConfiguration, expectedRevision: number) { - return request(`/api/projects/${projectId}/external-model/follow-up-import/plan`, { - method: "POST", body: JSON.stringify({ fileName: file.name, contentBase64: await fileToBase64(file), configuration, expectedRevision }), - }); -} - -export async function applyExternalFollowUpImport(projectId: string, file: File, input: ApplyExternalFollowUpImportInput) { - return request(`/api/projects/${projectId}/external-model/follow-up-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 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 deleteMissingExternalProjectObjects(projectId: string, expectedRevision: number, objectIds: string[]) { - return request(`/api/projects/${projectId}/external-model/objects/delete-missing`, { method: "POST", body: JSON.stringify({ expectedRevision, objectIds, confirmed: true }) }); -} - -export function createExternalReturnWorkbook( - projectId: string, - expectedRevision: number, - scope: ExternalReturnScopeDto, - selectedObjectIds: string[] -) { - return request(`/api/projects/${projectId}/external-model/return-workbook`, { - method: "POST", - body: JSON.stringify({ expectedRevision, scope, selectedObjectIds }), - }); -} - -export function assignExternalProjectObjectsToRow(projectId: string, expectedRevision: number, objectIds: string[], rowId: string, confirmedConflictObjectIds: string[] = []) { - return request(`/api/projects/${projectId}/external-model/objects/assign-row`, { - method: "POST", - body: JSON.stringify({ expectedRevision, objectIds, rowId, confirmedConflictObjectIds }), - }); -} - -export function detachExternalProjectObjectsFromRow(projectId: string, expectedRevision: number, objectIds: string[]) { - return request(`/api/projects/${projectId}/external-model/objects/detach-row`, { - method: "POST", - body: JSON.stringify({ expectedRevision, objectIds }), - }); -} - -export function assignExternalProjectObjectsToNewRow(projectId: string, expectedRevision: number, objectIds: string[], circuitId: string) { - return request(`/api/projects/${projectId}/external-model/objects/assign-new-row`, { - method: "POST", body: JSON.stringify({ expectedRevision, objectIds, circuitId }), - }); -} - -export function assignExternalProjectObjectsToNewCircuit(projectId: string, expectedRevision: number, objectIds: string[], sectionId: string) { - return request(`/api/projects/${projectId}/external-model/objects/assign-new-circuit`, { - method: "POST", body: JSON.stringify({ expectedRevision, objectIds, sectionId }), - }); -} - export function getProjectHistory(projectId: string) { return request( `/api/projects/${projectId}/history` @@ -507,22 +325,14 @@ 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: UpdateDistributionBoardInput, + input: { + floorId: string | null; + supplyType: NonNullable; + simultaneityFactor: number; + } & Partial, expectedRevision: number ) { return request( @@ -534,41 +344,6 @@ 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() { @@ -605,6 +380,12 @@ 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 @@ -614,6 +395,57 @@ 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, @@ -651,12 +483,6 @@ export function getCircuitTree(projectId: string, circuitListId: string) { return request(`/api/projects/${projectId}/circuit-lists/${circuitListId}/tree`); } -export function getProjectCircuitTrees(projectId: string) { - return request( - `/api/projects/${projectId}/circuit-trees` - ); -} - export function insertDistributionBoardComponentCommand( projectId: string, expectedRevision: number, @@ -1055,61 +881,6 @@ export function renumberCircuitSectionCommand( ); } -export function listBuildings(projectId: string) { - return request(`/api/projects/${projectId}/buildings`); -} - -export function createBuilding( - projectId: string, - input: CreateBuildingInput, - expectedRevision: number -) { - return request( - `/api/projects/${projectId}/buildings`, - { - method: "POST", - body: JSON.stringify({ name: input.name, expectedRevision }), - } - ); -} - -export function updateBuilding( - projectId: string, - buildingId: string, - input: CreateBuildingInput, - expectedRevision: number -) { - return request( - `/api/projects/${projectId}/buildings/${buildingId}`, - { - method: "PUT", - body: JSON.stringify({ name: input.name, expectedRevision }), - } - ); -} - -export function deleteBuilding( - projectId: string, - buildingId: string, - expectedRevision: number -) { - return request( - `/api/projects/${projectId}/buildings/${buildingId}`, - { - method: "DELETE", - body: JSON.stringify({ expectedRevision }), - } - ); -} - -// buildingId is only sent when the caller passes it (string or null); -// an omitted buildingId keeps the current assignment on update. -function toFloorRequestBody(input: CreateFloorInput, expectedRevision: number) { - return input.buildingId === undefined - ? { name: input.name, expectedRevision } - : { name: input.name, buildingId: input.buildingId, expectedRevision }; -} - export function listFloors(projectId: string) { return request(`/api/projects/${projectId}/floors`); } @@ -1123,7 +894,7 @@ export function createFloor( `/api/projects/${projectId}/floors`, { method: "POST", - body: JSON.stringify(toFloorRequestBody(input, expectedRevision)), + body: JSON.stringify({ ...input, expectedRevision }), } ); } @@ -1136,7 +907,7 @@ export function updateFloor( ) { return request(`/api/projects/${projectId}/floors/${floorId}`, { method: "PUT", - body: JSON.stringify(toFloorRequestBody(input, expectedRevision)), + body: JSON.stringify({ ...input, expectedRevision }), }); } @@ -1306,66 +1077,3 @@ 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/auth-api.ts b/src/frontend/utils/auth-api.ts deleted file mode 100644 index a6f12b3..0000000 --- a/src/frontend/utils/auth-api.ts +++ /dev/null @@ -1,95 +0,0 @@ -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. - -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", - [WRITE_REQUEST_HEADER_NAME]: WRITE_REQUEST_HEADER_VALUE, - ...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/frontend/utils/building-structure.ts b/src/frontend/utils/building-structure.ts deleted file mode 100644 index 11c1a1e..0000000 --- a/src/frontend/utils/building-structure.ts +++ /dev/null @@ -1,350 +0,0 @@ -// Pure selection, filtering and grouping rules for the building structure -// view (Gebäude → Etagen → Räume) and grouped floor selects. -import type { BuildingDto, FloorDto, RoomDto } from "../types"; - -/** Selection key for "Alle" in the building and floor columns. */ -export const ALL_SELECTION = "__all__"; -/** Selection key for "Ohne Gebäude" / "Ohne Etage". */ -export const UNASSIGNED_SELECTION = "__unassigned__"; - -/** ALL_SELECTION, UNASSIGNED_SELECTION or a building/floor id. */ -export type StructureSelection = string; - -export const UNASSIGNED_BUILDING_LABEL = "Ohne Gebäude"; -export const UNASSIGNED_FLOOR_LABEL = "Ohne Etage"; - -type BuildingLike = Pick; -type FloorLike = Pick & { - buildingId?: string | null; -}; -type RoomLike = Pick; -type RoomAreaLike = Pick; - -export interface RoomAreaSummary { - areaM2: number; - roomCount: number; - missingAreaCount: number; -} - -export interface StructureAreaSummaries { - total: RoomAreaSummary; - byBuilding: Map; - byFloor: Map; -} - -export interface FloorGroup { - /** null for floors without (known) building. */ - buildingId: string | null; - label: string; - floors: TFloor[]; -} - -/** - * The building a floor belongs to, or null when it has none or references a - * building that is not (or no longer) loaded. - */ -export function resolveFloorBuildingId( - floor: FloorLike, - buildingIds: ReadonlySet -): string | null { - const buildingId = floor.buildingId ?? null; - return buildingId !== null && buildingIds.has(buildingId) - ? buildingId - : null; -} - -function toIdSet(entries: ReadonlyArray<{ id: string }>) { - return new Set(entries.map((entry) => entry.id)); -} - -export function hasFloorsWithoutBuilding( - floors: ReadonlyArray, - buildings: ReadonlyArray -): boolean { - const buildingIds = toIdSet(buildings); - return floors.some( - (floor) => resolveFloorBuildingId(floor, buildingIds) === null - ); -} - -export function hasRoomsWithoutFloor( - rooms: ReadonlyArray, - floors: ReadonlyArray -): boolean { - const floorIds = toIdSet(floors); - return rooms.some( - (room) => room.floorId === null || !floorIds.has(room.floorId) - ); -} - -/** - * Groups floors by building in building order; floors without a known - * building come last under "Ohne Gebäude". Empty groups are omitted and the - * floor order inside a group is preserved. - */ -export function groupFloorsByBuilding( - floors: ReadonlyArray, - buildings: ReadonlyArray -): FloorGroup[] { - const buildingIds = toIdSet(buildings); - const floorsByBuilding = new Map(); - for (const floor of floors) { - const buildingId = resolveFloorBuildingId(floor, buildingIds); - const group = floorsByBuilding.get(buildingId) ?? []; - group.push(floor); - floorsByBuilding.set(buildingId, group); - } - const groups: FloorGroup[] = []; - for (const building of buildings) { - const groupFloors = floorsByBuilding.get(building.id); - if (groupFloors?.length) { - groups.push({ - buildingId: building.id, - label: building.name, - floors: groupFloors, - }); - } - } - const unassigned = floorsByBuilding.get(null); - if (unassigned?.length) { - groups.push({ - buildingId: null, - label: UNASSIGNED_BUILDING_LABEL, - floors: unassigned, - }); - } - return groups; -} - -/** Floors shown in the floor column for a building selection. */ -export function filterFloorsByBuilding( - floors: ReadonlyArray, - buildings: ReadonlyArray, - buildingSelection: StructureSelection -): TFloor[] { - if (buildingSelection === ALL_SELECTION) { - return [...floors]; - } - const buildingIds = toIdSet(buildings); - const targetBuildingId = - buildingSelection === UNASSIGNED_SELECTION ? null : buildingSelection; - return floors.filter( - (floor) => resolveFloorBuildingId(floor, buildingIds) === targetBuildingId - ); -} - -/** - * "Ohne Etage" is offered only when rooms without floor exist and the - * building selection can contain them ("Alle" or "Ohne Gebäude"), because a - * room without floor has no building either. - */ -export function showsRoomsWithoutFloorEntry( - rooms: ReadonlyArray, - floors: ReadonlyArray, - buildingSelection: StructureSelection -): boolean { - return ( - (buildingSelection === ALL_SELECTION || - buildingSelection === UNASSIGNED_SELECTION) && - hasRoomsWithoutFloor(rooms, floors) - ); -} - -/** Rooms shown in the room column for the current selections. */ -export function filterRooms( - rooms: ReadonlyArray, - floors: ReadonlyArray, - buildings: ReadonlyArray, - buildingSelection: StructureSelection, - floorSelection: StructureSelection -): TRoom[] { - const floorIds = toIdSet(floors); - const isWithoutFloor = (room: RoomLike) => - room.floorId === null || !floorIds.has(room.floorId); - - if (floorSelection === UNASSIGNED_SELECTION) { - return showsRoomsWithoutFloorEntry(rooms, floors, buildingSelection) - ? rooms.filter(isWithoutFloor) - : []; - } - if (floorSelection !== ALL_SELECTION) { - return rooms.filter((room) => room.floorId === floorSelection); - } - if (buildingSelection === ALL_SELECTION) { - return [...rooms]; - } - const visibleFloorIds = toIdSet( - filterFloorsByBuilding(floors, buildings, buildingSelection) - ); - return rooms.filter( - (room) => - (room.floorId !== null && visibleFloorIds.has(room.floorId)) || - (buildingSelection === UNASSIGNED_SELECTION && isWithoutFloor(room)) - ); -} - -/** Falls back to "Alle" when a selected building vanished. */ -export function normalizeBuildingSelection( - selection: StructureSelection, - floors: ReadonlyArray, - buildings: ReadonlyArray -): StructureSelection { - if (selection === ALL_SELECTION) { - return selection; - } - if (selection === UNASSIGNED_SELECTION) { - return hasFloorsWithoutBuilding(floors, buildings) - ? selection - : ALL_SELECTION; - } - return buildings.some((building) => building.id === selection) - ? selection - : ALL_SELECTION; -} - -/** Falls back to "Alle" when a selected floor is no longer visible. */ -export function normalizeFloorSelection( - selection: StructureSelection, - rooms: ReadonlyArray, - floors: ReadonlyArray, - buildings: ReadonlyArray, - buildingSelection: StructureSelection -): StructureSelection { - if (selection === ALL_SELECTION) { - return selection; - } - if (selection === UNASSIGNED_SELECTION) { - return showsRoomsWithoutFloorEntry(rooms, floors, buildingSelection) - ? selection - : ALL_SELECTION; - } - return filterFloorsByBuilding(floors, buildings, buildingSelection).some( - (floor) => floor.id === selection - ) - ? selection - : ALL_SELECTION; -} - -/** Building preselected in the floor dialog ("" = Ohne Gebäude). */ -export function defaultBuildingIdForNewFloor( - buildingSelection: StructureSelection -): string { - return buildingSelection === ALL_SELECTION || - buildingSelection === UNASSIGNED_SELECTION - ? "" - : buildingSelection; -} - -/** Floor preselected in the room dialog ("" = Ohne Etage). */ -export function defaultFloorIdForNewRoom( - floorSelection: StructureSelection -): string { - return floorSelection === ALL_SELECTION || - floorSelection === UNASSIGNED_SELECTION - ? "" - : floorSelection; -} - -export function countFloorsByBuilding( - floors: ReadonlyArray, - buildings: ReadonlyArray -): Map { - const buildingIds = toIdSet(buildings); - const counts = new Map(); - for (const floor of floors) { - const buildingId = resolveFloorBuildingId(floor, buildingIds); - counts.set(buildingId, (counts.get(buildingId) ?? 0) + 1); - } - return counts; -} - -/** Room counts per floor id; rooms without known floor count under null. */ -export function countRoomsByFloor( - rooms: ReadonlyArray, - floors: ReadonlyArray -): Map { - const floorIds = toIdSet(floors); - const counts = new Map(); - for (const room of rooms) { - const floorId = - room.floorId !== null && floorIds.has(room.floorId) - ? room.floorId - : null; - counts.set(floorId, (counts.get(floorId) ?? 0) + 1); - } - return counts; -} - -/** - * Sums only known room areas and counts missing values separately. Rooms with - * no known floor/building are grouped under null for the corresponding UI - * entries "Ohne Etage" and "Ohne Gebäude". - */ -export function summarizeRoomAreas( - rooms: ReadonlyArray, - floors: ReadonlyArray, - buildings: ReadonlyArray -): StructureAreaSummaries { - const buildingIds = toIdSet(buildings); - const floorsById = new Map(floors.map((floor) => [floor.id, floor])); - const byBuilding = new Map(); - const byFloor = new Map(); - const total = emptyAreaSummary(); - - for (const room of rooms) { - const floor = room.floorId === null ? undefined : floorsById.get(room.floorId); - const floorId = floor?.id ?? null; - const buildingId = floor - ? resolveFloorBuildingId(floor, buildingIds) - : null; - addRoomArea(total, room.areaM2); - addRoomArea(summaryFor(byFloor, floorId), room.areaM2); - addRoomArea(summaryFor(byBuilding, buildingId), room.areaM2); - } - return { total, byBuilding, byFloor }; -} - -function emptyAreaSummary(): RoomAreaSummary { - return { areaM2: 0, roomCount: 0, missingAreaCount: 0 }; -} - -function summaryFor( - summaries: Map, - key: string | null -) { - const existing = summaries.get(key); - if (existing) return existing; - const created = emptyAreaSummary(); - summaries.set(key, created); - return created; -} - -function addRoomArea(summary: RoomAreaSummary, areaM2: number | null) { - summary.roomCount += 1; - if (areaM2 === null) { - summary.missingAreaCount += 1; - } else { - summary.areaM2 += areaM2; - } -} - -/** "EG · Haus A", "EG" (floor without building) or "Ohne Etage". */ -export function describeRoomLocation( - room: RoomLike, - floors: ReadonlyArray, - buildings: ReadonlyArray -): string { - const floor = - room.floorId === null - ? undefined - : floors.find((entry) => entry.id === room.floorId); - if (!floor) { - return UNASSIGNED_FLOOR_LABEL; - } - const buildingId = resolveFloorBuildingId(floor, toIdSet(buildings)); - const building = - buildingId === null - ? undefined - : buildings.find((entry) => entry.id === buildingId); - return building ? `${floor.name} · ${building.name}` : floor.name; -} diff --git a/src/frontend/utils/circuit-grid-model.ts b/src/frontend/utils/circuit-grid-model.ts index fafeca4..ba4be98 100644 --- a/src/frontend/utils/circuit-grid-model.ts +++ b/src/frontend/utils/circuit-grid-model.ts @@ -44,7 +44,6 @@ export type RowType = | "circuitCompact" | "circuitSummary" | "deviceRow" - | "downstreamBoardLoad" | "reserveCircuit" | "placeholder" | "footerComponent"; @@ -615,13 +614,8 @@ 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") { - if (circuitFieldKeys.has(key)) return "circuitField"; - if (deviceFieldKeys.has(key)) return "deviceField"; - } - if (rowType === "circuitCompact") { + if (rowType === "reserveCircuit" || 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 30e5ecf..fb2a846 100644 --- a/src/frontend/utils/circuit-grid-projection.ts +++ b/src/frontend/utils/circuit-grid-projection.ts @@ -2,7 +2,6 @@ import type { CircuitTreeCircuitDto, CircuitTreeComponentDto, CircuitTreeDeviceRowDto, - CircuitTreeDownstreamBoardLoadDto, CircuitTreeSectionDto, } from "../types.js"; import { buildCircuitStructureProjection } from "./circuit-structure-projection"; @@ -37,8 +36,6 @@ export interface VisibleGridCell { editable: boolean; kind: CellKind; value: GridValue; - /** Separate persisted value when the displayed value is derived. */ - editValue?: GridValue; } export interface VisibleGridRow { @@ -48,7 +45,6 @@ export interface VisibleGridRow { circuit?: CircuitTreeCircuitDto; device?: CircuitTreeDeviceRowDto; component?: CircuitTreeComponentDto; - downstreamBoardLoad?: CircuitTreeDownstreamBoardLoadDto; cells: VisibleGridCell[]; } @@ -130,64 +126,21 @@ function makeVisibleGridRow( rowType: RowType, sectionId: string, circuit?: CircuitTreeCircuitDto, - device?: CircuitTreeDeviceRowDto, - downstreamBoardLoad?: CircuitTreeDownstreamBoardLoadDto + device?: CircuitTreeDeviceRowDto ): 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 => { 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" - ? `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 === "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") { + if (rowType === "placeholder") { value = column.key === "equipmentIdentifier" ? "-frei-" : undefined; } else if (kind === "deviceField" && device) { value = getDeviceValue(device, column.key); @@ -210,18 +163,10 @@ function makeVisibleGridRow( value = circuit.voltage; } - return { cellKey: column.key, editable, kind, value, editValue }; + return { cellKey: column.key, editable, kind, value }; }); - return { - rowKey, - rowType, - sectionId, - circuit, - device, - downstreamBoardLoad, - cells, - }; + return { rowKey, rowType, sectionId, circuit, device, cells }; } export function buildVisibleGridRowsWithStructure( @@ -276,40 +221,15 @@ export function buildVisibleGridRowsWithStructure( } if (row.rowType === "circuitBlock") { const circuit = row.circuit; - const downstreamLoads = circuit.downstreamBoardLoads ?? []; - if (circuit.deviceRows.length === 0 && downstreamLoads.length === 0) { + if (circuit.deviceRows.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) { + } else if (circuit.deviceRows.length === 1) { 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/frontend/utils/client-id.ts b/src/frontend/utils/client-id.ts deleted file mode 100644 index f3804d5..0000000 --- a/src/frontend/utils/client-id.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Creates a random RFC 4122 version 4 UUID for new entities built in the - * browser. - * - * crypto.randomUUID() exists only in secure contexts (HTTPS or localhost). - * The app is also opened over plain HTTP from other machines in the LAN, where - * it is undefined, so fall back to crypto.getRandomValues(), which is - * available in every context. - */ -export function createClientId( - source: Pick & Partial> = crypto -): string { - if (typeof source.randomUUID === "function") { - return source.randomUUID(); - } - const bytes = source.getRandomValues(new Uint8Array(16)); - bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 - bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant - const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); - return [ - hex.slice(0, 8), - hex.slice(8, 12), - hex.slice(12, 16), - hex.slice(16, 20), - hex.slice(20), - ].join("-"); -} diff --git a/src/frontend/utils/config-access.ts b/src/frontend/utils/config-access.ts deleted file mode 100644 index 86dd2a2..0000000 --- a/src/frontend/utils/config-access.ts +++ /dev/null @@ -1,25 +0,0 @@ -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/frontend/utils/distribution-board-feeder-circuit.ts b/src/frontend/utils/distribution-board-feeder-circuit.ts deleted file mode 100644 index c2c7f43..0000000 --- a/src/frontend/utils/distribution-board-feeder-circuit.ts +++ /dev/null @@ -1,68 +0,0 @@ -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/overview-filters.ts b/src/frontend/utils/overview-filters.ts deleted file mode 100644 index 8757597..0000000 --- a/src/frontend/utils/overview-filters.ts +++ /dev/null @@ -1,249 +0,0 @@ -import type { - DistributionBoardDto, - FloorDto, - ProjectDeviceDto, -} from "../types"; - -/** - * Pure filter logic for the project overview cards (Verteilungen, - * Projektgeräte). Every multi-select filter uses the PM semantics: an empty - * selection means "Alle", otherwise a record must match one selected value. - * Records without a value are addressed through the dedicated "none" ids. - */ - -export interface FilterOption { - id: string; - label: string; -} - -/** Option id for boards without floor ("Ohne Etage"). */ -export const withoutFloorFilterId = "__without_floor__"; -/** Option id for boards without supply type ("Nicht festgelegt"). */ -export const withoutSupplyTypeFilterId = "__without_supply_type__"; -/** Option id for project devices without cost group ("Ohne Kostengruppe"). */ -export const withoutCostGroupFilterId = "__without_cost_group__"; - -export interface DistributionBoardFilters { - query: string; - floorIds: string[]; - supplyTypes: string[]; -} - -export interface ProjectDeviceFilters { - query: string; - categories: string[]; - phaseTypes: string[]; - costGroups: string[]; -} - -export const emptyDistributionBoardFilters: DistributionBoardFilters = { - query: "", - floorIds: [], - supplyTypes: [], -}; - -export const emptyProjectDeviceFilters: ProjectDeviceFilters = { - query: "", - categories: [], - phaseTypes: [], - costGroups: [], -}; - -export function normalizeFilterQuery(query: string) { - return query.trim().toLocaleLowerCase("de"); -} - -function matchesQuery( - normalizedQuery: string, - values: readonly (string | null | undefined)[] -) { - return ( - !normalizedQuery || - values.some((value) => - value?.toLocaleLowerCase("de").includes(normalizedQuery) - ) - ); -} - -function matchesSelection(selected: readonly string[], value: string) { - return selected.length === 0 || selected.includes(value); -} - -/** Adds or removes one value from a multi-select selection. */ -export function toggleFilterValue(selected: readonly string[], value: string) { - return selected.includes(value) - ? selected.filter((entry) => entry !== value) - : [...selected, value]; -} - -/** - * Drops selected values that are no longer offered (e.g. a deleted floor), so - * no invisible selection keeps hiding records. - */ -export function retainAvailableFilterValues( - selected: readonly string[], - options: readonly FilterOption[] -) { - const available = new Set(options.map((option) => option.id)); - return selected.filter((value) => available.has(value)); -} - -export function isDistributionBoardFilterActive( - filters: DistributionBoardFilters -) { - return ( - normalizeFilterQuery(filters.query) !== "" || - filters.floorIds.length > 0 || - filters.supplyTypes.length > 0 - ); -} - -export function isProjectDeviceFilterActive(filters: ProjectDeviceFilters) { - return ( - normalizeFilterQuery(filters.query) !== "" || - filters.categories.length > 0 || - filters.phaseTypes.length > 0 || - filters.costGroups.length > 0 - ); -} - -/** Floors in their configured order, followed by "Ohne Etage". */ -export function buildFloorFilterOptions( - floors: readonly FloorDto[] -): FilterOption[] { - return [ - ...[...floors] - .sort( - (left, right) => - left.sortOrder - right.sortOrder || - left.name.localeCompare(right.name, "de", { numeric: true }) - ) - .map((floor) => ({ id: floor.id, label: floor.name })), - { id: withoutFloorFilterId, label: "Ohne Etage" }, - ]; -} - -/** - * Supply types in catalog order: every enabled or used type, plus - * "Nicht festgelegt" when a board has no supply type. - */ -export function buildSupplyTypeFilterOptions( - catalog: readonly string[], - enabledSupplyTypes: readonly string[], - boards: readonly Pick[], - labels: Readonly> -): FilterOption[] { - const offered = new Set(enabledSupplyTypes); - let hasBoardWithoutSupplyType = false; - for (const board of boards) { - if (board.supplyType) { - offered.add(board.supplyType); - } else { - hasBoardWithoutSupplyType = true; - } - } - const options: FilterOption[] = catalog - .filter((supplyType) => offered.has(supplyType)) - .map((supplyType) => ({ - id: supplyType, - label: labels[supplyType] ?? supplyType, - })); - if (hasBoardWithoutSupplyType) { - options.push({ id: withoutSupplyTypeFilterId, label: "Nicht festgelegt" }); - } - return options; -} - -/** - * Board number and location come with the distribution-board info card - * (feature/print-view). They are optional here so the filter works with and - * without those fields and searches them as soon as the DTO carries them. - */ -export function filterDistributionBoards< - Board extends Pick & { - boardNumber?: string | null; - location?: string | null; - }, ->( - boards: readonly Board[], - filters: DistributionBoardFilters, - floorNameById: ReadonlyMap -): Board[] { - const query = normalizeFilterQuery(filters.query); - return boards.filter( - (board) => - matchesQuery(query, [ - board.name, - board.boardNumber, - board.location, - board.floorId ? floorNameById.get(board.floorId) : undefined, - ]) && - matchesSelection( - filters.floorIds, - board.floorId ?? withoutFloorFilterId - ) && - matchesSelection( - filters.supplyTypes, - board.supplyType ?? withoutSupplyTypeFilterId - ) - ); -} - -function getCostGroupFilterValue(costGroup: string | null) { - const trimmed = costGroup?.trim() ?? ""; - return trimmed || withoutCostGroupFilterId; -} - -/** Distinct cost groups in natural order, followed by "Ohne Kostengruppe". */ -export function buildCostGroupFilterOptions( - devices: readonly Pick[] -): FilterOption[] { - const costGroups = new Set(); - for (const device of devices) { - const value = getCostGroupFilterValue(device.costGroup); - if (value !== withoutCostGroupFilterId) { - costGroups.add(value); - } - } - return [ - ...[...costGroups] - .sort((left, right) => left.localeCompare(right, "de", { numeric: true })) - .map((costGroup) => ({ id: costGroup, label: costGroup })), - { id: withoutCostGroupFilterId, label: "Ohne Kostengruppe" }, - ]; -} - -export function filterProjectDevices< - Device extends Pick< - ProjectDeviceDto, - | "name" - | "displayName" - | "category" - | "phaseType" - | "connectionKind" - | "costGroup" - >, ->( - devices: readonly Device[], - filters: ProjectDeviceFilters, - categoryLabels: Readonly> = {} -): Device[] { - const query = normalizeFilterQuery(filters.query); - return devices.filter( - (device) => - matchesQuery(query, [ - device.name, - device.displayName, - device.category, - categoryLabels[device.category], - device.connectionKind, - device.costGroup, - ]) && - matchesSelection(filters.categories, device.category) && - matchesSelection(filters.phaseTypes, device.phaseType) && - matchesSelection( - filters.costGroups, - getCostGroupFilterValue(device.costGroup) - ) - ); -} diff --git a/src/frontend/utils/project-version-history.ts b/src/frontend/utils/project-version-history.ts index 2f1f35b..5685b29 100644 --- a/src/frontend/utils/project-version-history.ts +++ b/src/frontend/utils/project-version-history.ts @@ -32,10 +32,6 @@ 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", @@ -50,9 +46,6 @@ const commandTypeLabels: Record = { "circuit.move-group": "Stromkreis in andere Gruppe verschoben", "circuit-group.delete-subtree": "Stromkreisgruppe vollständig entfernt", "circuit-group.restore-subtree": "Stromkreisgruppe vollständig wiederhergestellt", - "project-building.insert": "Gebäude angelegt", - "project-building.update": "Gebäude bearbeitet", - "project-building.delete": "Gebäude entfernt", "project-floor.insert": "Geschoss angelegt", "project-floor.update": "Geschoss bearbeitet", "project-floor.delete": "Geschoss entfernt", @@ -62,10 +55,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-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": @@ -75,9 +65,6 @@ 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/frontend/utils/revit-xlsx-settings.ts b/src/frontend/utils/revit-xlsx-settings.ts deleted file mode 100644 index 6c05c14..0000000 --- a/src/frontend/utils/revit-xlsx-settings.ts +++ /dev/null @@ -1,17 +0,0 @@ -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/frontend/utils/room-area.ts b/src/frontend/utils/room-area.ts deleted file mode 100644 index fa54fd8..0000000 --- a/src/frontend/utils/room-area.ts +++ /dev/null @@ -1,30 +0,0 @@ -export type RoomAreaParseResult = - | { ok: true; value: number | null } - | { ok: false; error: string }; - -/** Parses an optional German decimal without rounding the stored value. */ -export function parseRoomAreaInput(text: string): RoomAreaParseResult { - const normalized = text.trim(); - if (!normalized) return { ok: true, value: null }; - if (!/^(?:\d+(?:,\d*)?|,\d+)$/.test(normalized)) { - return { - ok: false, - error: "Bitte eine nicht negative Zahl mit Komma eingeben.", - }; - } - const value = Number(normalized.replace(",", ".")); - return Number.isFinite(value) && value >= 0 - ? { ok: true, value } - : { ok: false, error: "Die Fläche muss mindestens 0 m² betragen." }; -} - -export function formatRoomArea(areaM2: number): string { - return areaM2.toLocaleString("de-DE", { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - }); -} - -export function formatOptionalRoomAreaInput(areaM2: number | null | undefined): string { - return areaM2 === null || areaM2 === undefined ? "" : formatRoomArea(areaM2); -} diff --git a/src/server/auth/auth-config.ts b/src/server/auth/auth-config.ts deleted file mode 100644 index c4c3b44..0000000 --- a/src/server/auth/auth-config.ts +++ /dev/null @@ -1,59 +0,0 @@ -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 - * 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 {} - -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 ?? ""; - 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, - sessionMaxAgeMs: maxDays * 24 * 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 deleted file mode 100644 index bafae03..0000000 --- a/src/server/auth/auth.middleware.ts +++ /dev/null @@ -1,156 +0,0 @@ -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 { 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; - 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: Pick, - 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, maxAgeMs: number) { - return { - httpOnly: true, - sameSite: "lax" as const, - secure: authConfig.cookieSecure, - path: "/", - maxAge: maxAgeMs, - }; -} - -/** 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 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) => { - if (SAFE_METHODS.has(req.method)) { - 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(); - 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, - users: Pick, - 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) setSessionCookie(res, authConfig, sessions, sessionId); - 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 deleted file mode 100644 index 344ff65..0000000 --- a/src/server/auth/cookie.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** 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; - // 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 deleted file mode 100644 index d81719b..0000000 --- a/src/server/auth/login-throttle.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 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/password.ts b/src/server/auth/password.ts deleted file mode 100644 index 97132af..0000000 --- a/src/server/auth/password.ts +++ /dev/null @@ -1,95 +0,0 @@ -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; -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 -// 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(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, - 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.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"); - 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/auth/sessions.ts b/src/server/auth/sessions.ts deleted file mode 100644 index 9ee1fe0..0000000 --- a/src/server/auth/sessions.ts +++ /dev/null @@ -1,105 +0,0 @@ -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 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, - createdAt: now, - expiresAt: Math.min(now + this.idleTtlMs, now + this.absoluteTtlMs), - }; - 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; - const now = this.now(); - if (this.isExpired(session, now)) { - this.sessions.delete(sessionId); - return undefined; - } - 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 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) { - this.sessions.delete(id); - } - } - } - - 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/application-repositories.ts b/src/server/composition/application-repositories.ts index 002a784..33881fd 100644 --- a/src/server/composition/application-repositories.ts +++ b/src/server/composition/application-repositories.ts @@ -6,18 +6,15 @@ import { CircuitRepository } from "../../db/repositories/circuit.repository.js"; import { CircuitProtectionDeviceRepository } from "../../db/repositories/circuit-protection-device.repository.js"; 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"; import { ProjectRepository } from "../../db/repositories/project.repository.js"; import { RoomRepository } from "../../db/repositories/room.repository.js"; -import { ExternalModelConfigurationRepository } from "../../db/repositories/external-model-configuration.repository.js"; +import { ExternalCsvConfigurationRepository } from "../../db/repositories/external-csv-configuration.repository.js"; import { ExternalModelStateRepository } from "../../db/repositories/external-model-state.repository.js"; -import { ExternalExportBatchRepository } from "../../db/repositories/external-export-batch.repository.js"; +import { CableSizingCalculationRepository } from "../../db/repositories/cable-sizing-calculation.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); @@ -30,16 +27,13 @@ export const distributionBoardComponentRepository = new DistributionBoardComponentRepository(db); 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); export const projectRepository = new ProjectRepository(db); export const roomRepository = new RoomRepository(db); -export const externalModelConfigurationRepository = - new ExternalModelConfigurationRepository(db); +export const externalCsvConfigurationRepository = + new ExternalCsvConfigurationRepository(db); export const externalModelStateRepository = new ExternalModelStateRepository(db); -export const externalExportBatchRepository = new ExternalExportBatchRepository(db); +export const cableSizingCalculationRepository = new CableSizingCalculationRepository(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 deleted file mode 100644 index 07b822b..0000000 --- a/src/server/composition/auth.ts +++ /dev/null @@ -1,16 +0,0 @@ -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"; -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, - { bootstrap: authConfig.bootstrap }, - { hash: hashPassword, verify: verifyPassword } -); diff --git a/src/server/composition/project-command-stores.ts b/src/server/composition/project-command-stores.ts index e2cc30a..79a4a9f 100644 --- a/src/server/composition/project-command-stores.ts +++ b/src/server/composition/project-command-stores.ts @@ -22,15 +22,11 @@ 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 { ExternalModelConfigurationProjectCommandRepository } from "../../db/repositories/external-model-configuration-project-command.repository.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 { ExternalFollowUpImportProjectCommandRepository } from "../../db/repositories/external-follow-up-import-project-command.repository.js"; -import { ExternalObjectPlanningProjectCommandRepository } from "../../db/repositories/external-object-planning-project-command.repository.js"; -import { ExternalObjectDeleteMissingProjectCommandRepository } from "../../db/repositories/external-object-delete-missing-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"; -import { EstimateBalanceProjectCommandRepository } from "../../db/repositories/estimate-balance-project-command.repository.js"; export const circuitProjectCommandStore = new CircuitProjectCommandRepository(db); export const circuitDeviceRowProjectCommandStore = @@ -74,24 +70,16 @@ export const projectSettingsProjectCommandStore = export const projectStateRestoreCommandStore = new ProjectStateRestoreCommandRepository(db); export const projectHistoryStore = new ProjectHistoryRepository(db); -export const externalModelConfigurationProjectCommandStore = - new ExternalModelConfigurationProjectCommandRepository(db); +export const externalCsvConfigurationProjectCommandStore = + new ExternalCsvConfigurationProjectCommandRepository(db); export const externalInitialImportProjectCommandStore = new ExternalInitialImportProjectCommandRepository(db); -export const externalFollowUpImportProjectCommandStore = - new ExternalFollowUpImportProjectCommandRepository(db); -export const externalObjectPlanningProjectCommandStore = - new ExternalObjectPlanningProjectCommandRepository(db); -export const externalObjectDeleteMissingProjectCommandStore = - new ExternalObjectDeleteMissingProjectCommandRepository(db); export const externalObjectRowAssignmentProjectCommandStore = new ExternalObjectRowAssignmentProjectCommandRepository(db); 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, @@ -115,13 +103,9 @@ export const projectCommandService = new ProjectCommandService( circuitGroupSubtreeProjectCommandStore, circuitProtectionProjectCommandStore, projectHistoryStore, - externalModelConfigurationProjectCommandStore, + externalCsvConfigurationProjectCommandStore, + externalInitialImportProjectCommandStore, externalObjectRowAssignmentProjectCommandStore, externalObjectNewRowProjectCommandStore, - externalObjectNewCircuitProjectCommandStore, - estimateBalanceProjectCommandStore, - externalInitialImportProjectCommandStore, - externalObjectPlanningProjectCommandStore, - externalFollowUpImportProjectCommandStore, - externalObjectDeleteMissingProjectCommandStore + externalObjectNewCircuitProjectCommandStore ); diff --git a/src/server/controllers/auth.controller.ts b/src/server/controllers/auth.controller.ts deleted file mode 100644 index 5eaf699..0000000 --- a/src/server/controllers/auth.controller.ts +++ /dev/null @@ -1,109 +0,0 @@ -import type { Request, Response } from "express"; -import { changePasswordSchema, loginSchema } from "../../shared/validation/auth.schemas.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"; - -export async function getAuthStatus(req: Request, res: Response) { - const identity = await identityFromRequest(req, sessionStore, userRepository); - const sessionId = sessionIdFromRequest(req); - if (identity && sessionId) setSessionCookie(res, authConfig, sessionStore, sessionId); - 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; - } - 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(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); - 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; - } - 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: "Das neue Passwort muss 8 bis 200 Zeichen lang sein." }); - return; - } - try { - await userService.changeOwnPassword( - identity.id, - parsed.data.currentPassword, - parsed.data.newPassword - ); - } catch (error) { - if (error instanceof WrongPasswordError || error instanceof PasswordUnchangedError) { - res.status(400).json({ error: error.message }); - return; - } - throw error; - } - // 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, 0), maxAge: undefined }); - res.json({ signedOut: true }); -} diff --git a/src/server/controllers/building.controller.ts b/src/server/controllers/building.controller.ts deleted file mode 100644 index 3a49120..0000000 --- a/src/server/controllers/building.controller.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type { Request, Response } from "express"; -import { - createProjectBuildingDeleteProjectCommand, - createProjectBuildingInsertProjectCommand, - createProjectBuildingSnapshot, - createProjectBuildingUpdateProjectCommand, -} from "../../domain/models/project-location-structure-project-command.model.js"; -import { - createBuildingSchema, - deleteProjectLocationSchema, - updateBuildingSchema, -} from "../../shared/validation/project-structure.schemas.js"; -import { projectCommandService } from "../composition/project-command-stores.js"; -import { buildingRepository } from "../composition/application-repositories.js"; -import { respondWithProjectCommandError } from "./project-command.controller.js"; - -export async function listBuildingsByProject(req: Request, res: Response) { - const { projectId } = req.params; - if (typeof projectId !== "string") { - return res.status(400).json({ error: "Invalid projectId" }); - } - - const result = await buildingRepository.listByProject(projectId); - return res.json(result); -} - -export async function createBuilding(req: Request, res: Response) { - const { projectId } = req.params; - if (typeof projectId !== "string") { - return res.status(400).json({ error: "Invalid projectId" }); - } - - const parsed = createBuildingSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - - const existingBuildings = await buildingRepository.listByProject(projectId); - const nextSortOrder = existingBuildings.length - ? Math.max(...existingBuildings.map((building) => building.sortOrder)) + 1 - : 0; - const building = createProjectBuildingSnapshot( - projectId, - parsed.data.name, - nextSortOrder - ); - try { - const result = projectCommandService.executeUser({ - projectId, - expectedRevision: parsed.data.expectedRevision, - description: "Gebäude anlegen", - command: createProjectBuildingInsertProjectCommand(building), - }); - return res.status(201).json({ ...result, building }); - } catch (error) { - return respondWithProjectCommandError(error, res); - } -} - -export async function updateBuilding(req: Request, res: Response) { - const { projectId, buildingId } = req.params; - if (typeof projectId !== "string" || typeof buildingId !== "string") { - return res.status(400).json({ error: "Invalid parameters" }); - } - const parsed = updateBuildingSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - const current = await buildingRepository.findById(projectId, buildingId); - if (!current) { - return res.status(404).json({ error: "Building not found" }); - } - const target = { ...current, name: parsed.data.name }; - try { - const result = projectCommandService.executeUser({ - projectId, - expectedRevision: parsed.data.expectedRevision, - description: "Gebäude bearbeiten", - command: createProjectBuildingUpdateProjectCommand(current, target), - }); - return res.json({ ...result, building: target }); - } catch (error) { - return respondWithProjectCommandError(error, res); - } -} - -export async function deleteBuilding(req: Request, res: Response) { - const { projectId, buildingId } = req.params; - if (typeof projectId !== "string" || typeof buildingId !== "string") { - return res.status(400).json({ error: "Invalid parameters" }); - } - const parsed = deleteProjectLocationSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ error: parsed.error.flatten() }); - } - const current = await buildingRepository.findById(projectId, buildingId); - if (!current) { - return res.status(404).json({ error: "Building not found" }); - } - try { - const result = projectCommandService.executeUser({ - projectId, - expectedRevision: parsed.data.expectedRevision, - description: "Gebäude löschen", - command: createProjectBuildingDeleteProjectCommand(current), - }); - return res.json(result); - } catch (error) { - return respondWithProjectCommandError(error, res); - } -} diff --git a/src/server/controllers/cable-sizing.controller.ts b/src/server/controllers/cable-sizing.controller.ts index 8c6124e..e0b628e 100644 --- a/src/server/controllers/cable-sizing.controller.ts +++ b/src/server/controllers/cable-sizing.controller.ts @@ -1,33 +1,74 @@ +import { randomUUID } from "node:crypto"; import type { Request, Response } from "express"; import { cableSizingRequestSchema } from "../../cable-sizing/domain/cable-sizing-contracts.js"; import { - buildCableSizingAlerts, calculateCableSizing, - INSULATION_MATERIALS, - INSULATION_MATERIAL_LABELS, + buildCableSizingAlerts, LAYING_METHODS, LAYING_METHOD_LABELS, + LAYING_METHOD_VERIFIED, + INSULATION_MATERIALS, + INSULATION_MATERIAL_LABELS, } from "../../cable-sizing/domain/cable-sizing-calculation.js"; +import { cableSizingCalculationRepository } from "../composition/application-repositories.js"; -// Stateless calculation: it neither reads nor writes project data. The -// planner applies a result through the existing circuit.update command, which -// keeps revisions and Undo/Redo intact. See docs/cable-sizing-module.md. -export function calculateCableSizingHandler(req: Request, res: Response) { +// Stateless calculation, not a project command: no expectedRevision, no +// circuit mutation here. The caller applies the result via the existing +// circuit.update command (POST /api/projects/:projectId/commands) if the +// user confirms it. See docs/cable-sizing-module.md. +export async function calculateCableSizingHandler(req: Request, res: Response) { const parsed = cableSizingRequestSchema.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: parsed.error.flatten() }); } - const result = calculateCableSizing(parsed.data); - return res.json({ result, alerts: buildCableSizingAlerts(parsed.data, result) }); + + const { context, ...input } = parsed.data; + const result = calculateCableSizing(input); + const alerts = buildCableSizingAlerts(input, result); + + let entry; + try { + entry = await cableSizingCalculationRepository.create({ + id: randomUUID(), + projectId: context?.projectId ?? null, + circuitId: context?.circuitId ?? null, + equipmentIdentifier: context?.equipmentIdentifier ?? null, + input, + result, + appliedToCircuit: 0, + }); + } catch (error) { + // context.circuitId/projectId are caller-supplied and only used for the + // audit-log entry, not the calculation itself - a stale or unknown id + // (e.g. a circuit deleted between page load and this request) should be + // a normal 400, not a raw 500 from the foreign-key constraint. + if ( + error && + typeof error === "object" && + "code" in error && + (error as { code?: string }).code === "SQLITE_CONSTRAINT_FOREIGNKEY" + ) { + return res + .status(400) + .json({ error: "Unknown context.projectId or context.circuitId" }); + } + throw error; + } + + return res.status(201).json({ calculationId: entry.id, result, alerts }); } -export function listLayingMethodsHandler(_req: Request, res: Response) { +export async function listLayingMethodsHandler(_req: Request, res: Response) { return res.json( - LAYING_METHODS.map((method) => ({ method, label: LAYING_METHOD_LABELS[method] })) + LAYING_METHODS.map((method) => ({ + method, + label: LAYING_METHOD_LABELS[method], + dataVerified: LAYING_METHOD_VERIFIED[method], + })) ); } -export function listInsulationMaterialsHandler(_req: Request, res: Response) { +export async function listInsulationMaterialsHandler(_req: Request, res: Response) { return res.json( INSULATION_MATERIALS.map((insulation) => ({ insulation, @@ -35,3 +76,24 @@ export function listInsulationMaterialsHandler(_req: Request, res: Response) { })) ); } + +export async function markCalculationAppliedHandler(req: Request, res: Response) { + const { calculationId } = req.params; + if (typeof calculationId !== "string") { + return res.status(400).json({ error: "Invalid calculationId" }); + } + const updated = await cableSizingCalculationRepository.markApplied(calculationId); + if (!updated) { + return res.status(404).json({ error: "Calculation not found" }); + } + return res.json(updated); +} + +export async function listCalculationsForCircuitHandler(req: Request, res: Response) { + const { circuitId } = req.params; + if (typeof circuitId !== "string") { + return res.status(400).json({ error: "Invalid circuitId" }); + } + const rows = await cableSizingCalculationRepository.listByCircuit(circuitId); + return res.json(rows); +} diff --git a/src/server/controllers/circuit-tree.controller.ts b/src/server/controllers/circuit-tree.controller.ts index d1fb7f6..b7c86bf 100644 --- a/src/server/controllers/circuit-tree.controller.ts +++ b/src/server/controllers/circuit-tree.controller.ts @@ -1,11 +1,13 @@ import type { Request, Response } from "express"; -import { calculateDistributionBoardLoads } from "../../domain/calculations/distribution-board-load-calculation.js"; -import { calculateRowTotalPower } from "../../domain/calculations/circuit-power-calculation.js"; -import type { - CircuitTreeProtectionDevice, - CircuitTreeResponse, - ProjectCircuitTreesResponse, -} from "../../domain/models/circuit-tree.model.js"; +import { + applyDistributionBoardSimultaneityFactor, + calculateCircuitTotalPower, + calculateDistributionBoardTotalPower, + calculateRowTotalPower, + calculateSectionTotalPower, +} from "../../domain/calculations/circuit-power-calculation.js"; +import type { CircuitTreeResponse } from "../../domain/models/circuit-tree.model.js"; +import type { CircuitTreeProtectionDevice } from "../../domain/models/circuit-tree.model.js"; import { circuitDeviceRowRepository, circuitListRepository, @@ -14,12 +16,13 @@ import { circuitSectionRepository, distributionBoardComponentRepository, distributionBoardRepository, - externalModelStateRepository, projectRepository, } from "../composition/application-repositories.js"; export function isMissingCircuitTreeSchemaError(error: unknown): boolean { - if (!(error instanceof Error)) return false; + if (!(error instanceof Error)) { + return false; + } return ( error.message.includes("no such table: circuit_sections") || error.message.includes("no such table: circuits") || @@ -34,154 +37,70 @@ export async function getCircuitTree(req: Request, res: Response) { if (typeof projectId !== "string" || typeof circuitListId !== "string") { return res.status(400).json({ error: "Invalid parameters" }); } + const list = await circuitListRepository.findById(projectId, circuitListId); - if (!list) return res.status(404).json({ error: "Circuit list not found" }); - - try { - const result = await buildProjectCircuitTrees(projectId); - if (!result) return res.status(404).json({ error: "Project not found" }); - const tree = result.trees.find((entry) => entry.circuitListId === circuitListId); - if (!tree) { - return res.status(404).json({ error: "Distribution board not found" }); - } - return res.json(tree); - } catch (error) { - if (isMissingCircuitTreeSchemaError(error)) { - const project = await projectRepository.findById(projectId); - const board = await distributionBoardRepository.findById( - projectId, - list.distributionBoardId - ); - if (!project || !board) { - return res.status(404).json({ error: "Project structure not found" }); - } - return res.json(emptyCircuitTree(project, board, circuitListId)); - } - throw error; + if (!list) { + return res.status(404).json({ error: "Circuit list not found" }); } -} - -export async function getProjectCircuitTrees(req: Request, res: Response) { - const { projectId } = req.params; - if (typeof projectId !== "string") { - return res.status(400).json({ error: "Invalid parameters" }); - } - try { - const result = await buildProjectCircuitTrees(projectId); - if (!result) return res.status(404).json({ error: "Project not found" }); - return res.json(result); - } catch (error) { - if (isMissingCircuitTreeSchemaError(error)) { - const project = await projectRepository.findById(projectId); - if (!project) return res.status(404).json({ error: "Project not found" }); - return res.json({ currentRevision: project.currentRevision, trees: [] }); - } - throw error; - } -} - -export async function buildProjectCircuitTrees( - projectId: string -): Promise { const project = await projectRepository.findById(projectId); - if (!project) return null; - const [lists, boards] = await Promise.all([ - circuitListRepository.listByProject(projectId), - distributionBoardRepository.listByProject(projectId), - ]); - const externalState = externalModelStateRepository.getByProject(projectId).state; - const externalCountByRowId = new Map(); - for (const object of externalState.objects) { - if (object.circuitDeviceRowId) { - externalCountByRowId.set(object.circuitDeviceRowId, (externalCountByRowId.get(object.circuitDeviceRowId) ?? 0) + 1); - } + if (!project) { + return res.status(404).json({ error: "Project not found" }); + } + const distributionBoard = + await distributionBoardRepository.findById( + projectId, + list.distributionBoardId + ); + if (!distributionBoard) { + return res.status(404).json({ + error: "Distribution board not found", + }); } - const listIds = lists.map((entry) => entry.id); - const [sections, circuits, components] = await Promise.all([ - circuitSectionRepository.listByCircuitLists(listIds), - circuitRepository.listByCircuitLists(listIds), - distributionBoardComponentRepository.listByCircuitLists(listIds), - ]); - const [rows, circuitProtections, componentProtections] = await Promise.all([ - circuitDeviceRowRepository.listByCircuitList(circuits.map((entry) => entry.id)), - circuitProtectionDeviceRepository.listByCircuitIds(circuits.map((entry) => entry.id)), - distributionBoardComponentRepository.listProtectionByComponentIds( - components.map((entry) => entry.id) - ), - ]); - 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); - const sectionsByListId = groupBy(sections, (section) => section.circuitListId); - const circuitsByListId = groupBy(circuits, (circuit) => circuit.circuitListId); - const componentsByListId = groupBy(components, (component) => component.circuitListId); - const circuitProtectionById = new Map( - circuitProtections.map((entry) => [entry.circuitId, entry]) - ); - const componentProtectionById = new Map( - componentProtections.map((entry) => [entry.componentId, entry]) - ); + try { + const sections = await circuitSectionRepository.listByCircuitList(circuitListId); + const circuits = await circuitRepository.listByCircuitList(circuitListId); + const rows = await circuitDeviceRowRepository.listByCircuitList(circuits.map((entry) => entry.id)); + const components = + await distributionBoardComponentRepository.listByCircuitList( + circuitListId + ); + const [circuitProtections, componentProtections] = + await Promise.all([ + circuitProtectionDeviceRepository.listByCircuitIds( + circuits.map((entry) => entry.id) + ), + distributionBoardComponentRepository.listProtectionByComponentIds( + components.map((entry) => entry.id) + ), + ]); - const loads = calculateDistributionBoardLoads({ - boards: boards.map((board) => ({ - id: board.id, - name: board.name, - boardNumber: board.boardNumber, - simultaneityFactor: board.simultaneityFactor, - feedingDistributionBoardId: board.feedingDistributionBoardId, - feedingCircuitId: board.feedingCircuitId, - })), - circuits: circuits.map((circuit) => { - const list = listById.get(circuit.circuitListId); - if (!list) throw new Error("Circuit list is missing from project tree."); - return { - id: circuit.id, - distributionBoardId: list.distributionBoardId, - rows: (rowsByCircuitId.get(circuit.id) ?? []).map((row) => ({ - activePowerKw: calculateRowTotalPower( - row.quantity, - row.powerPerUnit, - row.simultaneityFactor - ), - cosPhi: row.cosPhi, - })), - }; - }), - }); + const sectionById = new Map(sections.map((section) => [section.id, section])); + const rowsByCircuitId = new Map(); + const circuitProtectionById = new Map( + circuitProtections.map((entry) => [entry.circuitId, entry]) + ); + const componentProtectionById = new Map( + componentProtections.map((entry) => [entry.componentId, entry]) + ); + for (const row of rows) { + if (!rowsByCircuitId.has(row.circuitId)) { + rowsByCircuitId.set(row.circuitId, []); + } + rowsByCircuitId.get(row.circuitId)!.push(row); + } - const trees = lists.map((list): CircuitTreeResponse => { - const board = boardById.get(list.distributionBoardId); - if (!board) throw new Error("Distribution board is missing from project tree."); - const boardLoad = loads.boards.get(board.id); - if (!boardLoad) throw new Error("Distribution-board load is missing."); const tree: CircuitTreeResponse = { - circuitListId: list.id, - distributionBoardId: board.id, - distributionBoardName: board.name, - distributionBoardNumber: board.boardNumber ?? undefined, - distributionBoardSupplyType: board.supplyType ?? undefined, - feedingReference: resolveFeedingReference( - board, - boardById, - listByBoardId, - circuitById, - sectionById - ), + circuitListId, currentRevision: project.currentRevision, singlePhaseVoltageV: project.singlePhaseVoltageV, threePhaseVoltageV: project.threePhaseVoltageV, - distributionBoardSimultaneityFactor: board.simultaneityFactor, - distributionBoardTotalPower: boardLoad.activePowerBeforeSimultaneityKw, - distributionBoardTotalPowerWithSimultaneityFactor: - boardLoad.demandActivePowerKw, + distributionBoardSimultaneityFactor: + distributionBoard.simultaneityFactor, + distributionBoardTotalPower: 0, + distributionBoardTotalPowerWithSimultaneityFactor: 0, headerComponents: [], - sections: (sectionsByListId.get(list.id) ?? []).map((section) => ({ + sections: sections.map((section) => ({ id: section.id, key: section.key, displayName: section.displayName, @@ -196,8 +115,9 @@ export async function buildProjectCircuitTrees( footerComponents: [], }; const sectionBlocks = new Map(tree.sections.map((section) => [section.id, section])); - for (const component of componentsByListId.get(list.id) ?? []) { - const protection = componentProtectionById.get(component.id); + for (const component of components) { + const protection = + componentProtectionById.get(component.id); const dto = { id: component.id, circuitListId: component.circuitListId, @@ -207,18 +127,24 @@ export async function buildProjectCircuitTrees( role: component.role, placement: component.placement, sortOrder: component.sortOrder, - protectionDevice: protection ? toProtectionDeviceDto(protection) : undefined, + protectionDevice: protection + ? toProtectionDeviceDto(protection) + : undefined, }; - if (component.placement === "header") tree.headerComponents.push(dto); - else if (component.placement === "footer") tree.footerComponents.push(dto); - else if (component.sectionId !== null) { + if (component.placement === "header") { + tree.headerComponents.push(dto); + } else if (component.placement === "footer") { + tree.footerComponents.push(dto); + } else if (component.sectionId !== null) { sectionBlocks.get(component.sectionId)?.components.push(dto); } } - for (const circuit of circuitsByListId.get(list.id) ?? []) { - const block = sectionBlocks.get(circuit.sectionId); - if (!block) continue; + for (const circuit of circuits) { + const section = sectionById.get(circuit.sectionId); + if (!section || section.circuitListId !== circuit.circuitListId) { + continue; + } const deviceRows = (rowsByCircuitId.get(circuit.id) ?? []).map((row) => ({ id: row.id, linkedProjectDeviceId: row.linkedProjectDeviceId ?? undefined, @@ -240,17 +166,12 @@ export async function buildProjectCircuitTrees( cosPhi: row.cosPhi ?? undefined, remark: row.remark ?? undefined, overriddenFields: row.overriddenFields ?? undefined, - rowTotalPower: calculateRowTotalPower( - row.quantity, - row.powerPerUnit, - row.simultaneityFactor - ), - externalObjectCount: externalCountByRowId.get(row.id) ?? 0, + rowTotalPower: calculateRowTotalPower(row.quantity, row.powerPerUnit, row.simultaneityFactor), })); - const circuitLoad = loads.circuits.get(circuit.id); - if (!circuitLoad) throw new Error("Circuit load is missing."); + const circuitTotalPower = calculateCircuitTotalPower(deviceRows); const protection = circuitProtectionById.get(circuit.id); - block.circuits.push({ + + sectionBlocks.get(section.id)?.circuits.push({ id: circuit.id, circuitListId: circuit.circuitListId, sectionId: circuit.sectionId, @@ -265,97 +186,50 @@ export async function buildProjectCircuitTrees( voltage: circuit.voltage ?? undefined, controlRequirement: circuit.controlRequirement ?? undefined, status: circuit.status ?? undefined, - isReserve: - Boolean(circuit.isReserve) && - circuitLoad.downstreamBoards.length === 0, + isReserve: Boolean(circuit.isReserve), remark: circuit.remark ?? undefined, - circuitTotalPower: circuitLoad.activePowerKw, - circuitApparentPower: circuitLoad.apparentPowerKva, - circuitCosPhi: circuitLoad.cosPhi, + circuitTotalPower, deviceRows, - downstreamBoardLoads: circuitLoad.downstreamBoards - .map((load) => ({ - distributionBoardId: load.distributionBoardId, - name: load.name, - boardNumber: load.boardNumber ?? undefined, - supplyType: boardById.get(load.distributionBoardId)?.supplyType ?? undefined, - activePowerKw: load.activePowerKw, - apparentPowerKva: load.apparentPowerKva, - cosPhi: load.cosPhi, - })) - .sort((left, right) => - (left.boardNumber ?? left.name).localeCompare( - right.boardNumber ?? right.name, - "de" - ) - ), - protectionDevice: protection ? toProtectionDeviceDto(protection) : undefined, + protectionDevice: protection + ? toProtectionDeviceDto(protection) + : undefined, }); } + for (const section of tree.sections) { - section.sectionTotalPower = section.circuits.reduce( - (sum, circuit) => sum + circuit.circuitTotalPower, - 0 + section.sectionTotalPower = calculateSectionTotalPower( + section.circuits ); } - return tree; - }); + tree.distributionBoardTotalPower = + calculateDistributionBoardTotalPower(tree.sections); + tree.distributionBoardTotalPowerWithSimultaneityFactor = + applyDistributionBoardSimultaneityFactor( + tree.distributionBoardTotalPower, + tree.distributionBoardSimultaneityFactor + ); - return { currentRevision: project.currentRevision, trees }; -} - -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, - circuitEquipmentIdentifier: feedingCircuit?.equipmentIdentifier, - circuitDisplayName: feedingCircuit?.displayName ?? undefined, - circuitCategory: feedingCircuit - ? sectionById.get(feedingCircuit.sectionId)?.category ?? undefined - : undefined, - }; -} - -function emptyCircuitTree( - project: NonNullable>>, - board: NonNullable>>, - circuitListId: string -): CircuitTreeResponse & { warning: string } { - return { - circuitListId, - distributionBoardId: board.id, - distributionBoardName: board.name, - distributionBoardNumber: board.boardNumber ?? undefined, - distributionBoardSupplyType: board.supplyType ?? undefined, - currentRevision: project.currentRevision, - singlePhaseVoltageV: project.singlePhaseVoltageV, - threePhaseVoltageV: project.threePhaseVoltageV, - distributionBoardSimultaneityFactor: board.simultaneityFactor, - distributionBoardTotalPower: 0, - distributionBoardTotalPowerWithSimultaneityFactor: 0, - headerComponents: [], - sections: [], - footerComponents: [], - warning: - "Circuit-first tables are not available yet. Run database migrations (including 0008_circuit_first_model).", - }; + return res.json(tree); + } catch (error) { + if (isMissingCircuitTreeSchemaError(error)) { + return res.json({ + circuitListId, + currentRevision: project.currentRevision, + singlePhaseVoltageV: project.singlePhaseVoltageV, + threePhaseVoltageV: project.threePhaseVoltageV, + distributionBoardSimultaneityFactor: + distributionBoard.simultaneityFactor, + distributionBoardTotalPower: 0, + distributionBoardTotalPowerWithSimultaneityFactor: 0, + headerComponents: [], + sections: [], + footerComponents: [], + warning: + "Circuit-first tables are not available yet. Run database migrations (including 0008_circuit_first_model).", + }); + } + throw error; + } } function toProtectionDeviceDto(value: { @@ -369,20 +243,11 @@ function toProtectionDeviceDto(value: { return { type: value.type, ratedCurrentA: value.ratedCurrentA, - fuseUtilizationCategory: value.fuseUtilizationCategory ?? undefined, + fuseUtilizationCategory: + value.fuseUtilizationCategory ?? undefined, tripCharacteristic: value.tripCharacteristic ?? undefined, rcdType: value.rcdType ?? undefined, - ratedResidualCurrentMa: value.ratedResidualCurrentMa ?? undefined, + ratedResidualCurrentMa: + value.ratedResidualCurrentMa ?? undefined, }; } - -function groupBy(values: T[], keyOf: (value: T) => string) { - const groups = new Map(); - for (const value of values) { - const key = keyOf(value); - const group = groups.get(key) ?? []; - group.push(value); - groups.set(key, group); - } - return groups; -} diff --git a/src/server/controllers/distribution-board.controller.ts b/src/server/controllers/distribution-board.controller.ts index d2e9bb9..9ea713a 100644 --- a/src/server/controllers/distribution-board.controller.ts +++ b/src/server/controllers/distribution-board.controller.ts @@ -69,8 +69,6 @@ export async function createDistributionBoard(req: Request, res: Response) { location: null, fedFrom: null, remark: null, - feedingDistributionBoardId: null, - feedingCircuitId: null, }, }); } catch (error) { @@ -100,17 +98,6 @@ export async function updateDistributionBoard( .filter((field) => parsed.data[field] !== undefined) .map((field) => [field, parsed.data[field]]) ); - const feedingPatch = { - ...(parsed.data.feedingDistributionBoardId === undefined - ? {} - : { - feedingDistributionBoardId: - parsed.data.feedingDistributionBoardId, - }), - ...(parsed.data.feedingCircuitId === undefined - ? {} - : { feedingCircuitId: parsed.data.feedingCircuitId }), - }; try { const result = projectCommandService.executeUser({ projectId, @@ -123,7 +110,6 @@ export async function updateDistributionBoard( supplyType: parsed.data.supplyType, simultaneityFactor: parsed.data.simultaneityFactor, ...infoPatch, - ...feedingPatch, } ), }); diff --git a/src/server/controllers/estimate-balance.controller.ts b/src/server/controllers/estimate-balance.controller.ts deleted file mode 100644 index a22bcb1..0000000 --- a/src/server/controllers/estimate-balance.controller.ts +++ /dev/null @@ -1,180 +0,0 @@ -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/controllers/external-csv.controller.ts b/src/server/controllers/external-csv.controller.ts new file mode 100644 index 0000000..4862d9b --- /dev/null +++ b/src/server/controllers/external-csv.controller.ts @@ -0,0 +1,298 @@ +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/controllers/external-follow-up-import.controller.ts b/src/server/controllers/external-follow-up-import.controller.ts deleted file mode 100644 index 8e70c5b..0000000 --- a/src/server/controllers/external-follow-up-import.controller.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { Request, Response } from "express"; -import type { CircuitDeviceRowSnapshot } from "../../domain/models/circuit-device-row-structure-project-command.model.js"; -import { createExternalFollowUpImportProjectCommand } from "../../domain/models/external-follow-up-import-project-command.model.js"; -import { createExternalXlsxFollowUpImportPlan } from "../../external-model/application/external-xlsx-follow-up-import.js"; -import { buildExternalXlsxFollowUpTarget } from "../../external-model/application/external-xlsx-follow-up-target.js"; -import { projectExternalXlsxReturn, type ExternalReturnRowContext } from "../../external-model/application/external-xlsx-return-projection.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 { buildProjectCircuitTrees } from "./circuit-tree.controller.js"; -import { respondWithProjectCommandError } from "./project-command.controller.js"; - -export async function planExternalFollowUpImport(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const context = await loadContext(projectId, expectedRevision, req.body?.configuration); - const { plan } = await createExternalXlsxFollowUpImportPlan({ - fileName: requiredString(req.body?.fileName, "Dateiname"), bytes: decodeBase64(req.body?.contentBase64), configuration: context.configuration, - catalogs: await loadCatalogs(projectId), currentState: context.state, currentReturnValuesByObjectId: context.returnValues, - }); - return res.json(plan); - } catch (error) { return res.status(400).json({ error: error instanceof Error ? error.message : "Folgeimport-Vorschau fehlgeschlagen." }); } -} - -export async function applyExternalFollowUpImport(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const context = await loadContext(projectId, expectedRevision, req.body?.configuration); - const bytes = decodeBase64(req.body?.contentBase64); - const { plan, document } = await createExternalXlsxFollowUpImportPlan({ - fileName: requiredString(req.body?.fileName, "Dateiname"), bytes, configuration: context.configuration, - catalogs: await loadCatalogs(projectId), currentState: context.state, currentReturnValuesByObjectId: context.returnValues, - }); - 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 built = buildExternalXlsxFollowUpTarget({ - projectId, expectedRevision, importedAtIso: new Date().toISOString(), configuration: context.configuration, - originalContentBase64: String(req.body.contentBase64), document, plan, currentState: context.state, - sourceChangeDecisions: requireArray(req.body?.sourceChangeDecisions, "Quelländerungsentscheidungen"), - roomDecisions: requireArray(req.body?.roomDecisions, "Raumentscheidungen"), - familyProjectDeviceDecisions: requireArray(req.body?.familyProjectDeviceDecisions, "ProjectDevice-Entscheidungen"), - objectsWithoutRoomDefaultDistributionBoardId: nullableString(req.body?.objectsWithoutRoomDefaultDistributionBoardId, "Standardverteiler ohne Raum"), - rowsById: context.rowsById, createId: randomUUID, - }); - const targetConfiguration = { ...context.configurationSnapshot, configuration: context.configuration }; - const result = projectCommandService.executeUser({ - projectId, expectedRevision, description: `Revit-Folgeimport ${plan.fileName}`, - command: createExternalFollowUpImportProjectCommand({ expectedConfiguration: context.configurationSnapshot, targetConfiguration, expectedState: context.state, targetState: built.targetState, rows: built.rowTransitions }), - }); - return res.status(201).json({ ...result, import: { importBatchId: built.targetState.importBatches.at(-1)!.id, objectCount: plan.objectCount, newObjectCount: plan.newObjectCount, changedObjectCount: plan.changedObjectCount, missingObjectCount: plan.missingObjectCount } }); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -async function loadContext(projectId: string, expectedRevision: number, configurationValue: unknown) { - const [project, treeResult] = await Promise.all([projectRepository.findById(projectId), buildProjectCircuitTrees(projectId)]); - if (!project || !treeResult) throw new Error("Projekt nicht gefunden."); - if (project.currentRevision !== expectedRevision || treeResult.currentRevision !== expectedRevision) throw new Error("Der Folgeimportplan ist wegen einer neueren Projektrevision ungültig."); - const stored = externalModelConfigurationRepository.getByProject(projectId); - if (!stored.configuration) throw new Error("Für das Projekt ist keine Revit-XLSX-Konfiguration gespeichert."); - assertExternalModelConfiguration(configurationValue); - const stateResult = externalModelStateRepository.getByProject(projectId); - if (!stateResult.state.source) throw new Error("Für den Folgeimport fehlt ein bestehender Revit-Import."); - const rowContexts = createRowContexts(treeResult); - const returnValues = new Map(stateResult.state.objects.map((object) => [object.id, projectExternalXlsxReturn({ object, row: object.circuitDeviceRowId ? rowContexts.get(object.circuitDeviceRowId)?.returnContext ?? null : null, circuitMode: configurationValue.circuitMode, singlePhaseVoltageV: project.singlePhaseVoltageV, threePhaseVoltageV: project.threePhaseVoltageV }).values])); - return { configuration: configurationValue, configurationSnapshot: stored.configuration, state: stateResult.state, returnValues, rowsById: new Map([...rowContexts].map(([id, value]) => [id, value.snapshot])) }; -} - -function createRowContexts(treeResult: NonNullable>>) { - const result = new Map(); - for (const tree of treeResult.trees) for (const section of tree.sections) for (const circuit of section.circuits) for (const row of circuit.deviceRows) result.set(row.id, { - returnContext: { rowId: row.id, displayName: row.displayName, powerPerUnitKw: row.powerPerUnit, cosPhi: row.cosPhi ?? null, phaseType: row.phaseType ?? null, category: section.category ?? null, circuitIdentifier: circuit.equipmentIdentifier, circuitVoltageV: circuit.voltage ?? null, distributionBoardName: tree.distributionBoardName }, - snapshot: { id: row.id, circuitId: circuit.id, linkedProjectDeviceId: row.linkedProjectDeviceId ?? null, sortOrder: row.sortOrder, name: row.name, displayName: row.displayName, phaseType: row.phaseType ?? null, connectionKind: row.connectionKind ?? null, costGroup: row.costGroup ?? null, category: row.category ?? null, level: row.level ?? null, roomId: row.roomId ?? null, roomNumberSnapshot: row.roomNumberSnapshot ?? null, roomNameSnapshot: row.roomNameSnapshot ?? null, quantity: row.quantity, manualQuantity: row.manualQuantity, powerPerUnit: row.powerPerUnit, simultaneityFactor: row.simultaneityFactor, cosPhi: row.cosPhi ?? null, remark: row.remark ?? null, overriddenFields: row.overriddenFields ?? null }, - }); - return result; -} -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 parseExpectedRevision(value: unknown) { if (!Number.isSafeInteger(value) || (value as number) < 0) throw new Error("Ungültige Projektrevision."); return value as number; } -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/controllers/external-initial-import.controller.ts b/src/server/controllers/external-initial-import.controller.ts deleted file mode 100644 index 25eb284..0000000 --- a/src/server/controllers/external-initial-import.controller.ts +++ /dev/null @@ -1,68 +0,0 @@ -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: batch?.objectCount ?? result.state.objects.length, missingObjectCount: result.state.objects.filter((object) => object.presenceStatus === "missing").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/controllers/external-model-configuration.controller.ts b/src/server/controllers/external-model-configuration.controller.ts deleted file mode 100644 index 0a4166a..0000000 --- a/src/server/controllers/external-model-configuration.controller.ts +++ /dev/null @@ -1,60 +0,0 @@ -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/controllers/external-objects.controller.ts b/src/server/controllers/external-objects.controller.ts deleted file mode 100644 index a381faa..0000000 --- a/src/server/controllers/external-objects.controller.ts +++ /dev/null @@ -1,313 +0,0 @@ -import type { Request, Response } from "express"; -import { randomUUID } from "node:crypto"; -import { createExternalObjectPlanningUpdateProjectCommand } from "../../domain/models/external-object-planning-project-command.model.js"; -import { createExternalObjectDeleteMissingProjectCommand } from "../../domain/models/external-object-delete-missing-project-command.model.js"; -import { createExternalObjectRowAssignmentProjectCommand } from "../../domain/models/external-object-row-assignment-project-command.model.js"; -import type { CircuitDeviceRowSnapshot } from "../../domain/models/circuit-device-row-structure-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"; -import { buildProjectCircuitTrees } from "./circuit-tree.controller.js"; -import { createExternalObjectNewRowProjectCommand, externalObjectAssignToNewRowCommandType } from "../../domain/models/external-object-new-row-project-command.model.js"; -import { createExternalObjectNewCircuitProjectCommand, externalObjectAssignToNewCircuitCommandType } from "../../domain/models/external-object-new-circuit-project-command.model.js"; -import { createDefaultCircuitProtection } from "../../domain/services/protection-device-defaults.js"; -import { circuitNumberingService } from "../composition/circuit-numbering-service.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); } -} - -export async function deleteMissingExternalObjects(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const objectIds = parseObjectIds(req.body?.objectIds); - if (req.body?.confirmed !== true) throw new Error("Das Löschen fehlender Revit-Objekte muss bestätigt werden."); - const { state, projectExists } = externalModelStateRepository.getByProject(projectId); - if (!projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); - const byId = new Map(state.objects.map((object) => [object.id, object])); - const selected = objectIds.map((id) => { - const object = byId.get(id); - if (!object || object.presenceStatus !== "missing") throw new Error("Nur im letzten Import fehlende Revit-Objekte dürfen gelöscht werden."); - return object; - }); - const treeResult = await buildProjectCircuitTrees(projectId); - const quantitiesByRowId = new Map(); - for (const object of selected) if (object.circuitDeviceRowId) quantitiesByRowId.set(object.circuitDeviceRowId, (quantitiesByRowId.get(object.circuitDeviceRowId) ?? 0) + object.planningValues.effectiveQuantity); - const rows = [...quantitiesByRowId].map(([rowId, removedQuantity]) => { - const location = findRow(treeResult, rowId); - if (!location) throw new Error("Eine verknüpfte Gerätezeile wurde nicht gefunden."); - const expected = toRowSnapshot(location.row, location.circuitId); - return { expected, target: { ...expected, quantity: expected.quantity - removedQuantity } }; - }); - const result = projectCommandService.executeUser({ - projectId, - expectedRevision, - description: `${selected.length} fehlende Revit-Objekte gelöscht`, - command: createExternalObjectDeleteMissingProjectCommand({ objects: selected.map((expected) => ({ expected, target: null })), rows }), - }); - return res.json(result); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -export async function assignExternalObjectsToRow(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const objectIds = parseObjectIds(req.body?.objectIds); - const rowId = requiredId(req.body?.rowId, "Ungültige Gerätezeile."); - const confirmedConflictObjectIds = Array.isArray(req.body?.confirmedConflictObjectIds) - ? req.body.confirmedConflictObjectIds.map((value: unknown) => requiredId(value, "Ungültige Konfliktbestätigung.")) - : []; - const { state, projectExists } = externalModelStateRepository.getByProject(projectId); - if (!projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); - const treeResult = await buildProjectCircuitTrees(projectId); - const location = findRow(treeResult, rowId); - if (!location) throw new Error("Gerätezeile wurde nicht gefunden."); - const byId = new Map(state.objects.map((object) => [object.id, object])); - const selected = objectIds.map((id) => { - const object = byId.get(id); - if (!object) throw new Error("Ein Revit-Objekt wurde nicht gefunden."); - if (object.circuitDeviceRowId !== null) throw new Error("Ein Revit-Objekt ist bereits einer Gerätezeile zugeordnet."); - return object; - }); - const expectedRow = toRowSnapshot(location.row, location.circuitId); - const addedQuantity = selected.reduce((sum, object) => sum + object.planningValues.effectiveQuantity, 0); - const targetRow = { ...expectedRow, quantity: expectedRow.quantity + addedQuantity }; - const objects = selected.map((expected) => ({ - expected, - target: { ...expected, distributionBoardId: location.distributionBoardId, circuitDeviceRowId: rowId }, - })); - const result = projectCommandService.executeUser({ - projectId, - expectedRevision, - description: `${objects.length} Revit-Objekte zugeordnet`, - command: createExternalObjectRowAssignmentProjectCommand({ - rows: [{ expected: expectedRow, target: targetRow }], - objects, - confirmedConflictObjectIds, - }), - }); - return res.json(result); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -export async function detachExternalObjectsFromRow(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const objectIds = parseObjectIds(req.body?.objectIds); - const { state, projectExists } = externalModelStateRepository.getByProject(projectId); - if (!projectExists) return res.status(404).json({ error: "Projekt nicht gefunden." }); - const treeResult = await buildProjectCircuitTrees(projectId); - const byId = new Map(state.objects.map((object) => [object.id, object])); - const selected = objectIds.map((id) => { - const object = byId.get(id); - if (!object?.circuitDeviceRowId) throw new Error("Ein Revit-Objekt ist keiner Gerätezeile zugeordnet."); - return object; - }); - const rowIds = new Set(selected.map((object) => object.circuitDeviceRowId!)); - if (rowIds.size !== 1) throw new Error("Revit-Objekte können nur aus derselben Gerätezeile gemeinsam gelöst werden."); - const rowId = [...rowIds][0]!; - const location = findRow(treeResult, rowId); - if (!location) throw new Error("Gerätezeile wurde nicht gefunden."); - const expectedRow = toRowSnapshot(location.row, location.circuitId); - const removedQuantity = selected.reduce((sum, object) => sum + object.planningValues.effectiveQuantity, 0); - const targetRow = { ...expectedRow, quantity: expectedRow.quantity - removedQuantity }; - const copiedFields = ["displayName", "category", "connectionKind", "powerPerUnitW", "simultaneityFactor", "cosPhi", "costGroup", "remark"] as const; - const objects = selected.map((expected) => ({ - expected, - target: { - ...expected, - circuitDeviceRowId: null, - distributionBoardId: location.distributionBoardId, - linkedProjectDeviceId: expectedRow.linkedProjectDeviceId, - planningValues: { - ...expected.planningValues, - displayName: expectedRow.displayName, - category: location.category, - connectionKind: expectedRow.connectionKind, - powerPerUnitW: expectedRow.powerPerUnit * 1000, - simultaneityFactor: expectedRow.simultaneityFactor, - cosPhi: expectedRow.cosPhi, - costGroup: expectedRow.costGroup, - remark: expectedRow.remark, - }, - overriddenFields: [...new Set([...expected.overriddenFields, ...copiedFields])], - }, - })); - const result = projectCommandService.executeUser({ - projectId, - expectedRevision, - description: `${objects.length} Revit-Objekte gelöst`, - command: createExternalObjectRowAssignmentProjectCommand({ - rows: [{ expected: expectedRow, target: targetRow }], - objects, - confirmedConflictObjectIds: [], - }), - }); - return res.json(result); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -export async function assignExternalObjectsToNewRow(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const objectIds = parseObjectIds(req.body?.objectIds); - const circuitId = requiredId(req.body?.circuitId, "Ungültiger Stromkreis."); - const context = await loadAssignmentContext(projectId, objectIds); - const circuitLocation = context.treeResult?.trees.flatMap((tree) => tree.sections.flatMap((section) => section.circuits.map((circuit) => ({ tree, section, circuit })))).find((entry) => entry.circuit.id === circuitId); - if (!circuitLocation || !circuitLocation.section.category) throw new Error("Stromkreis wurde nicht gefunden."); - const row = buildExternalRow(context.objects, context.roomId, circuitId, Math.max(0, ...circuitLocation.circuit.deviceRows.map((entry) => entry.sortOrder)) + 10); - const transitions = context.objects.map((expected) => ({ expected, target: { ...expected, distributionBoardId: circuitLocation.tree.distributionBoardId, circuitDeviceRowId: row.id } })); - const result = projectCommandService.executeUser({ projectId, expectedRevision, description: `${transitions.length} Revit-Objekte als neue Gerätezeile zugeordnet`, command: createExternalObjectNewRowProjectCommand(externalObjectAssignToNewRowCommandType, { row, objects: transitions, confirmedConflictObjectIds: objectIds }) }); - return res.json(result); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -export async function assignExternalObjectsToNewCircuit(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const objectIds = parseObjectIds(req.body?.objectIds); - const sectionId = requiredId(req.body?.sectionId, "Ungültige Stromkreisgruppe."); - const context = await loadAssignmentContext(projectId, objectIds); - const sectionLocation = context.treeResult?.trees.flatMap((tree) => tree.sections.map((section) => ({ tree, section }))).find((entry) => entry.section.id === sectionId); - if (!sectionLocation?.section.category) throw new Error("Stromkreisgruppe wurde nicht gefunden."); - const circuitId = randomUUID(); - const row = buildExternalRow(context.objects, context.roomId, circuitId, 10); - const protection = createDefaultCircuitProtection(sectionLocation.section.category); - const circuit = { - id: circuitId, - circuitListId: sectionLocation.tree.circuitListId, - sectionId, - equipmentIdentifier: await circuitNumberingService.getNextIdentifier(sectionId), - displayName: null, - sortOrder: Math.max(0, ...sectionLocation.section.circuits.map((entry) => entry.sortOrder)) + 10, - cableType: null, cableCrossSection: null, cableLength: null, rcdAssignment: null, - terminalDesignation: null, - voltage: sectionLocation.section.category === "three_phase" ? sectionLocation.tree.threePhaseVoltageV : sectionLocation.tree.singlePhaseVoltageV, - controlRequirement: null, status: null, isReserve: false, remark: null, - deviceRows: [row], - protectionDevice: { - circuitId, - type: protection.type, - ratedCurrentA: protection.ratedCurrentA, - fuseUtilizationCategory: "fuseUtilizationCategory" in protection ? protection.fuseUtilizationCategory : null, - tripCharacteristic: "tripCharacteristic" in protection ? protection.tripCharacteristic : null, - rcdType: "rcdType" in protection ? protection.rcdType : null, - ratedResidualCurrentMa: "ratedResidualCurrentMa" in protection ? protection.ratedResidualCurrentMa : null, - }, - }; - const transitions = context.objects.map((expected) => ({ expected, target: { ...expected, distributionBoardId: sectionLocation.tree.distributionBoardId, circuitDeviceRowId: row.id } })); - const result = projectCommandService.executeUser({ projectId, expectedRevision, description: `${transitions.length} Revit-Objekte als neuen Stromkreis zugeordnet`, command: createExternalObjectNewCircuitProjectCommand(externalObjectAssignToNewCircuitCommandType, { circuit, objects: transitions, confirmedConflictObjectIds: objectIds }) }); - return res.json(result); - } catch (error) { return respondWithProjectCommandError(error, res); } -} - -async function loadAssignmentContext(projectId: string, objectIds: string[]) { - const { state, projectExists } = externalModelStateRepository.getByProject(projectId); - if (!projectExists) throw new Error("Projekt nicht gefunden."); - const byId = new Map(state.objects.map((object) => [object.id, object])); - const objects = objectIds.map((id) => { - const object = byId.get(id); - if (!object) throw new Error("Ein Revit-Objekt wurde nicht gefunden."); - if (object.circuitDeviceRowId !== null) throw new Error("Ein Revit-Objekt ist bereits zugeordnet."); - return object; - }); - const roomIds = new Set(objects.map((object) => object.externalRoomMappingId === null ? null : state.roomMappings.find((mapping) => mapping.id === object.externalRoomMappingId)?.roomId ?? null)); - if (roomIds.size !== 1) throw new Error("Revit-Objekte aus verschiedenen Räumen benötigen getrennte Gerätezeilen."); - return { objects, roomId: [...roomIds][0]!, treeResult: await buildProjectCircuitTrees(projectId) }; -} - -function buildExternalRow(objects: ReturnType["state"]["objects"], roomId: string | null, circuitId: string, sortOrder: number): CircuitDeviceRowSnapshot { - const first = objects[0]!; - const planning = first.planningValues; - const quantity = objects.reduce((sum, object) => sum + object.planningValues.effectiveQuantity, 0); - return { - id: randomUUID(), circuitId, linkedProjectDeviceId: first.linkedProjectDeviceId, - sortOrder, name: first.acceptedSourceValues.familyAndType, - displayName: planning.displayName ?? (scalarText(first.acceptedSourceValues.selectionMarker) || first.acceptedSourceValues.familyAndType), - phaseType: planning.category === "three_phase" ? "three_phase" : "single_phase", - connectionKind: planning.connectionKind, costGroup: planning.costGroup, - category: planning.category, level: null, - roomId, - roomNumberSnapshot: scalarText(first.acceptedSourceValues.roomNumber) || null, - roomNameSnapshot: scalarText(first.acceptedSourceValues.roomName) || null, - quantity, manualQuantity: 0, - powerPerUnit: (planning.powerPerUnitW ?? 0) / 1000, - simultaneityFactor: planning.simultaneityFactor ?? 1, - cosPhi: planning.cosPhi, remark: planning.remark, overriddenFields: null, - }; -} - -function parseExpectedRevision(value: unknown) { - if (!Number.isSafeInteger(value) || (value as number) < 0) throw new Error("Ungültige Projektrevision."); - return value as number; -} -function parseObjectIds(value: unknown): string[] { - if (!Array.isArray(value) || value.length === 0) throw new Error("Keine Revit-Objekte ausgewählt."); - const ids = value.map((entry) => requiredId(entry, "Ungültige Revit-Objekt-ID.")); - if (new Set(ids).size !== ids.length) throw new Error("Revit-Objekte sind doppelt ausgewählt."); - return ids; -} -function requiredId(value: unknown, message: string) { if (typeof value !== "string" || !value) throw new Error(message); return value; } -function findRow(result: Awaited>, rowId: string) { - if (!result) return null; - for (const tree of result.trees) for (const section of tree.sections) for (const circuit of section.circuits) { - const row = circuit.deviceRows.find((entry) => entry.id === rowId); - if (row) return { row, circuitId: circuit.id, distributionBoardId: tree.distributionBoardId, category: section.category ?? null }; - } - return null; -} -function toRowSnapshot(row: NonNullable>["row"], circuitId: string): CircuitDeviceRowSnapshot { - return { id: row.id, circuitId, linkedProjectDeviceId: row.linkedProjectDeviceId ?? null, sortOrder: row.sortOrder, name: row.name, displayName: row.displayName, phaseType: row.phaseType ?? null, connectionKind: row.connectionKind ?? null, costGroup: row.costGroup ?? null, category: row.category ?? null, level: row.level ?? null, roomId: row.roomId ?? null, roomNumberSnapshot: row.roomNumberSnapshot ?? null, roomNameSnapshot: row.roomNameSnapshot ?? null, quantity: row.quantity, manualQuantity: row.manualQuantity, powerPerUnit: row.powerPerUnit, simultaneityFactor: row.simultaneityFactor, cosPhi: row.cosPhi ?? null, remark: row.remark ?? null, overriddenFields: row.overriddenFields ?? null }; -} - -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/controllers/external-return-workbook.controller.ts b/src/server/controllers/external-return-workbook.controller.ts deleted file mode 100644 index 0db6d81..0000000 --- a/src/server/controllers/external-return-workbook.controller.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import type { Request, Response } from "express"; -import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js"; -import type { ExternalExportScope } from "../../db/schema/external-export-batches.js"; -import { projectExternalXlsxReturn, type ExternalReturnRowContext } from "../../external-model/application/external-xlsx-return-projection.js"; -import { createExternalXlsxReturn } from "../../external-model/xlsx/external-xlsx-transport.js"; -import { - externalExportBatchRepository, - externalModelStateRepository, - projectRepository, -} from "../composition/application-repositories.js"; -import { buildProjectCircuitTrees } from "./circuit-tree.controller.js"; - -const exportScopes = new Set(["all", "deviating", "selected"]); - -export async function createExternalReturnWorkbook(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - try { - const expectedRevision = parseExpectedRevision(req.body?.expectedRevision); - const scope = parseScope(req.body?.scope); - const selectedObjectIds = scope === "selected" ? parseSelectedIds(req.body?.selectedObjectIds) : []; - if (scope === "selected" && selectedObjectIds.length === 0) { - return res.status(400).json({ error: "Für die ausgewählte Rückgabe wurden keine Revit-Objekte markiert." }); - } - - const project = await projectRepository.findById(projectId); - if (!project) return res.status(404).json({ error: "Projekt nicht gefunden." }); - if (project.currentRevision !== expectedRevision) { - return res.status(409).json({ - error: "Die Rückgabe ist wegen einer neueren Projektrevision ungültig.", - code: "PROJECT_REVISION_CONFLICT", - expectedRevision, - currentRevision: project.currentRevision, - }); - } - - const { state } = externalModelStateRepository.getByProject(projectId); - const importBatch = state.importBatches.at(-1); - if (!importBatch?.originalContentBase64 || !importBatch.configurationSnapshot) { - return res.status(409).json({ - error: "Für die Rückgabe fehlt der letzte vollständige Revit-Import.", - code: "EXTERNAL_XLSX_IMPORT_REQUIRED", - }); - } - const treeResult = await buildProjectCircuitTrees(projectId); - if (!treeResult || treeResult.currentRevision !== expectedRevision) { - return res.status(409).json({ - error: "Die Rückgabe ist wegen einer neueren Projektrevision ungültig.", - code: "PROJECT_REVISION_CONFLICT", - }); - } - - const rowById = new Map(); - for (const tree of treeResult.trees) { - for (const section of tree.sections) { - for (const circuit of section.circuits) { - for (const row of circuit.deviceRows) { - rowById.set(row.id, { - rowId: row.id, - displayName: row.displayName, - powerPerUnitKw: row.powerPerUnit, - cosPhi: row.cosPhi ?? null, - phaseType: row.phaseType ?? null, - category: (section.category ?? null) as CircuitGroupCategory | null, - circuitIdentifier: circuit.equipmentIdentifier, - circuitVoltageV: circuit.voltage ?? null, - distributionBoardName: tree.distributionBoardName, - }); - } - } - } - } - - const projections = state.objects - .filter((object) => object.presenceStatus === "present" && object.lastSeenImportBatchId === importBatch.id) - .map((object) => projectExternalXlsxReturn({ - object, - row: object.circuitDeviceRowId ? rowById.get(object.circuitDeviceRowId) ?? null : null, - circuitMode: importBatch.configurationSnapshot!.circuitMode, - singlePhaseVoltageV: project.singlePhaseVoltageV, - threePhaseVoltageV: project.threePhaseVoltageV, - })); - const projectionById = new Map(projections.map((projection) => [projection.objectId, projection])); - for (const objectId of selectedObjectIds) { - if (!projectionById.has(objectId)) { - return res.status(400).json({ error: "Ein ausgewähltes Revit-Objekt gehört nicht zum letzten Import." }); - } - } - const selected = scope === "all" - ? projections - : scope === "deviating" - ? projections.filter((projection) => projection.differsFromImported) - : selectedObjectIds.map((id) => projectionById.get(id)!); - if (selected.length === 0) { - return res.status(400).json({ error: "Der gewählte Rückgabeumfang enthält keine Revit-Objekte." }); - } - - const result = await createExternalXlsxReturn({ - fileName: importBatch.fileName, - bytes: Buffer.from(importBatch.originalContentBase64, "base64"), - configuration: importBatch.configurationSnapshot, - selectedWorksharingIds: selected.map((projection) => projection.worksharingId), - updates: selected.map((projection) => ({ - worksharingId: projection.worksharingId, - values: projection.values, - })), - }); - const fileName = `${safeFileName(project.name)}_Revit-Rueckgabe_${new Date().toISOString().slice(0, 10)}.xlsx`; - const sha256 = hash(result.bytes); - const configurationSha256 = hash(Buffer.from(JSON.stringify(importBatch.configurationSnapshot), "utf8")); - const currentProject = await projectRepository.findById(projectId); - if (!currentProject || currentProject.currentRevision !== expectedRevision) { - return res.status(409).json({ - error: "Die Rückgabe ist wegen einer neueren Projektrevision ungültig.", - code: "PROJECT_REVISION_CONFLICT", - expectedRevision, - currentRevision: currentProject?.currentRevision ?? null, - }); - } - externalExportBatchRepository.append({ - id: randomUUID(), - projectId, - projectRevision: expectedRevision, - importBatchId: importBatch.id, - exportedAtIso: new Date().toISOString(), - fileName, - sha256, - configurationSnapshot: importBatch.configurationSnapshot, - configurationSha256, - scope, - objectCount: result.exportedObjectCount, - }); - - const projectionWarnings = selected.flatMap((projection) => - projection.warnings.map((warning) => `${projection.worksharingId}: ${warning}`) - ); - return res.json({ - fileName, - contentBase64: Buffer.from(result.bytes).toString("base64"), - sha256, - objectCount: result.exportedObjectCount, - warnings: [...new Set([...result.issues.map((issue) => issue.message), ...projectionWarnings])], - }); - } catch (error) { - return res.status(400).json({ error: error instanceof Error ? error.message : "Revit-Rückgabe fehlgeschlagen." }); - } -} - -export async function listExternalExportBatches(req: Request, res: Response) { - const projectId = String(req.params.projectId ?? ""); - const project = await projectRepository.findById(projectId); - if (!project) return res.status(404).json({ error: "Projekt nicht gefunden." }); - return res.json(externalExportBatchRepository.listByProject(projectId).map(({ configurationSnapshot: _configuration, ...batch }) => batch)); -} - -function parseExpectedRevision(value: unknown) { - if (!Number.isSafeInteger(value) || (value as number) < 0) throw new Error("Ungültige Projektrevision."); - return value as number; -} - -function parseScope(value: unknown): ExternalExportScope { - if (typeof value !== "string" || !exportScopes.has(value as ExternalExportScope)) throw new Error("Ungültiger Rückgabeumfang."); - return value as ExternalExportScope; -} - -function parseSelectedIds(value: unknown) { - if (value === undefined) return []; - if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string") || new Set(value).size !== value.length) { - throw new Error("Ungültige Objektauswahl."); - } - return value as string[]; -} - -function safeFileName(value: string) { - return value.trim().replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_") || "Projekt"; -} - -function hash(bytes: Uint8Array) { - return createHash("sha256").update(bytes).digest("hex"); -} diff --git a/src/server/controllers/floor.controller.ts b/src/server/controllers/floor.controller.ts index b000db3..085aa10 100644 --- a/src/server/controllers/floor.controller.ts +++ b/src/server/controllers/floor.controller.ts @@ -42,8 +42,7 @@ export async function createFloor(req: Request, res: Response) { const floor = createProjectFloorSnapshot( projectId, parsed.data.name, - nextSortOrder, - parsed.data.buildingId ?? null + nextSortOrder ); try { const result = projectCommandService.executeUser({ @@ -71,14 +70,7 @@ export async function updateFloor(req: Request, res: Response) { if (!current) { return res.status(404).json({ error: "Floor not found" }); } - const target = { - ...current, - name: parsed.data.name, - buildingId: - parsed.data.buildingId === undefined - ? current.buildingId - : parsed.data.buildingId, - }; + const target = { ...current, name: parsed.data.name }; try { const result = projectCommandService.executeUser({ projectId, diff --git a/src/server/controllers/room.controller.ts b/src/server/controllers/room.controller.ts index b65c42a..3e78628 100644 --- a/src/server/controllers/room.controller.ts +++ b/src/server/controllers/room.controller.ts @@ -67,7 +67,6 @@ export async function updateRoom(req: Request, res: Response) { floorId: parsed.data.floorId, roomNumber: parsed.data.roomNumber, roomName: parsed.data.roomName, - areaM2: parsed.data.areaM2 === undefined ? current.areaM2 : parsed.data.areaM2, }; try { const result = projectCommandService.executeUser({ diff --git a/src/server/controllers/user.controller.ts b/src/server/controllers/user.controller.ts deleted file mode 100644 index bdf8d0f..0000000 --- a/src/server/controllers/user.controller.ts +++ /dev/null @@ -1,121 +0,0 @@ -import type { Request, Response } from "express"; -import type { ZodError } from "zod"; -import { - createUserSchema, - resetPasswordSchema, - updateUserSchema, -} from "../../shared/validation/user.schemas.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. -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, - }; -} - -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)); -} - -export async function createUser(req: Request, res: Response) { - const parsed = createUserSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ error: firstIssue(parsed.error) }); - 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: firstIssue(parsed.error) }); - 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; - } - 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) { - 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: firstIssue(parsed.error) }); - 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); - // 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 9a65ce0..7b36c5f 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,19 +1,10 @@ import express from "express"; import { globalDeviceRouter } from "./routes/global-device.routes.js"; import { projectDeviceRouter } from "./routes/project-device.routes.js"; +import { cableSizingRouter } from "./routes/cable-sizing.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, - 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"; import { closeDefaultDatabase } from "../db/client.js"; @@ -23,7 +14,6 @@ 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) => { @@ -60,20 +50,10 @@ 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", requireSameOriginForWrites()); -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); app.use("/api/project-devices", projectDeviceRouter); +app.use("/api/cable-sizing", cableSizingRouter); app.use("/api/document-branding", documentBrandingRouter); app.use(errorMiddleware); @@ -97,48 +77,40 @@ setInterval(() => { }); }, heartbeatIntervalMs).unref(); -userService - .ensureBootstrapAdmin() - .catch((error) => { - logger.error("bootstrap admin setup failed", toErrorMeta(error)); +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"); process.exit(1); - }) - .then(() => { - const server = app.listen(port, () => { - logger.info("server started", { port }); - }); + }, shutdownTimeoutMs); + forceExit.unref(); - 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(); + server.close((error) => { + if (error) logger.error("http server close failed", toErrorMeta(error)); + try { + closeDefaultDatabase(); + } catch (closeError) { + logger.error("database close failed", toErrorMeta(closeError)); } - - process.on("SIGTERM", shutdown); - process.on("SIGINT", shutdown); + 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(); +} + +process.on("SIGTERM", shutdown); +process.on("SIGINT", shutdown); diff --git a/src/server/routes/auth.routes.ts b/src/server/routes/auth.routes.ts deleted file mode 100644 index ee1cdd1..0000000 --- a/src/server/routes/auth.routes.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/cable-sizing.routes.ts b/src/server/routes/cable-sizing.routes.ts index 485e9c1..ca67e2e 100644 --- a/src/server/routes/cable-sizing.routes.ts +++ b/src/server/routes/cable-sizing.routes.ts @@ -1,9 +1,19 @@ 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); +cableSizingRouter.get( + "/insulation-materials", + cableSizingController.listInsulationMaterialsHandler +); +cableSizingRouter.post( + "/calculations/:calculationId/applied", + cableSizingController.markCalculationAppliedHandler +); +cableSizingRouter.get( + "/circuits/:circuitId/calculations", + cableSizingController.listCalculationsForCircuitHandler +); diff --git a/src/server/routes/project.routes.ts b/src/server/routes/project.routes.ts index 5d83ee0..8801784 100644 --- a/src/server/routes/project.routes.ts +++ b/src/server/routes/project.routes.ts @@ -13,26 +13,9 @@ import { updateDistributionBoard, } from "../controllers/distribution-board.controller.js"; import { listCircuitListsByProject } from "../controllers/circuit-list.controller.js"; -import { - createBuilding, - deleteBuilding, - listBuildingsByProject, - updateBuilding, -} 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, - getProjectCircuitTrees, -} from "../controllers/circuit-tree.controller.js"; +import { getCircuitTree } from "../controllers/circuit-tree.controller.js"; import { getNextCircuitIdentifier } from "../controllers/circuit.controller.js"; import { getProjectHistory, @@ -54,18 +37,13 @@ import { importProjectTransferAsNewProject, } from "../controllers/project-transfer.controller.js"; import { - getExternalModelConfiguration, - detectExternalModelWorkbook, - updateExternalModelConfiguration, -} from "../controllers/external-model-configuration.controller.js"; -import { + getExternalCsvConfiguration, applyExternalInitialImport, - getExternalInitialImportStatus, + previewExternalCsv, planExternalInitialImport, -} from "../controllers/external-initial-import.controller.js"; -import { assignExternalObjectsToNewCircuit, assignExternalObjectsToNewRow, assignExternalObjectsToRow, deleteMissingExternalObjects, detachExternalObjectsFromRow, listExternalObjects, updateExternalObjects } from "../controllers/external-objects.controller.js"; -import { createExternalReturnWorkbook, listExternalExportBatches } from "../controllers/external-return-workbook.controller.js"; -import { applyExternalFollowUpImport, planExternalFollowUpImport } from "../controllers/external-follow-up-import.controller.js"; + updateExternalCsvConfiguration, + getExternalCircuitListObjects, +} from "../controllers/external-csv.controller.js"; export const projectRouter = Router(); @@ -75,6 +53,21 @@ 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); @@ -87,23 +80,6 @@ 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/external-model/import-status", getExternalInitialImportStatus); -projectRouter.post("/:projectId/external-model/initial-import/plan", planExternalInitialImport); -projectRouter.post("/:projectId/external-model/initial-import/apply", applyExternalInitialImport); -projectRouter.post("/:projectId/external-model/follow-up-import/plan", planExternalFollowUpImport); -projectRouter.post("/:projectId/external-model/follow-up-import/apply", applyExternalFollowUpImport); -projectRouter.get("/:projectId/external-model/objects", listExternalObjects); -projectRouter.put("/:projectId/external-model/objects", updateExternalObjects); -projectRouter.post("/:projectId/external-model/objects/delete-missing", deleteMissingExternalObjects); -projectRouter.post("/:projectId/external-model/objects/assign-row", assignExternalObjectsToRow); -projectRouter.post("/:projectId/external-model/objects/assign-new-row", assignExternalObjectsToNewRow); -projectRouter.post("/:projectId/external-model/objects/assign-new-circuit", assignExternalObjectsToNewCircuit); -projectRouter.post("/:projectId/external-model/objects/detach-row", detachExternalObjectsFromRow); -projectRouter.post("/:projectId/external-model/return-workbook", createExternalReturnWorkbook); -projectRouter.get("/:projectId/external-model/export-batches", listExternalExportBatches); projectRouter.get("/:projectId/distribution-boards", listDistributionBoardsByProject); projectRouter.post("/:projectId/distribution-boards", createDistributionBoard); projectRouter.post( @@ -119,16 +95,11 @@ projectRouter.delete( deleteDistributionBoard ); projectRouter.get("/:projectId/circuit-lists", listCircuitListsByProject); -projectRouter.get("/:projectId/circuit-trees", getProjectCircuitTrees); projectRouter.get("/:projectId/circuit-lists/:circuitListId/tree", getCircuitTree); projectRouter.get( "/:projectId/circuit-sections/:sectionId/next-identifier", getNextCircuitIdentifier ); -projectRouter.get("/:projectId/buildings", listBuildingsByProject); -projectRouter.post("/:projectId/buildings", createBuilding); -projectRouter.put("/:projectId/buildings/:buildingId", updateBuilding); -projectRouter.delete("/:projectId/buildings/:buildingId", deleteBuilding); projectRouter.get("/:projectId/floors", listFloorsByProject); projectRouter.post("/:projectId/floors", createFloor); projectRouter.put("/:projectId/floors/:floorId", updateFloor); @@ -137,12 +108,3 @@ 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/server/routes/user.routes.ts b/src/server/routes/user.routes.ts deleted file mode 100644 index a34699c..0000000 --- a/src/server/routes/user.routes.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/request-security.ts b/src/shared/constants/request-security.ts deleted file mode 100644 index f89ce10..0000000 --- a/src/shared/constants/request-security.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const WRITE_REQUEST_HEADER_NAME = "X-Leistungsbilanz-Request"; -export const WRITE_REQUEST_HEADER_VALUE = "1"; diff --git a/src/shared/constants/user-roles.ts b/src/shared/constants/user-roles.ts deleted file mode 100644 index f123d5f..0000000 --- a/src/shared/constants/user-roles.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/estimate-balance/estimate-balance.ts b/src/shared/estimate-balance/estimate-balance.ts deleted file mode 100644 index 63d3753..0000000 --- a/src/shared/estimate-balance/estimate-balance.ts +++ /dev/null @@ -1,314 +0,0 @@ -/** - * 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 "MSR" (free text). */ - supply: 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/src/shared/validation/auth.schemas.ts b/src/shared/validation/auth.schemas.ts deleted file mode 100644 index 7d95eec..0000000 --- a/src/shared/validation/auth.schemas.ts +++ /dev/null @@ -1,20 +0,0 @@ -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).max(MAX_USERNAME_LENGTH), - password: z.string().min(1).max(MAX_PASSWORD_LENGTH), - }) - .strict(); - -export const changePasswordSchema = z - .object({ - 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/external-csv.schemas.ts b/src/shared/validation/external-csv.schemas.ts new file mode 100644 index 0000000..cf99e66 --- /dev/null +++ b/src/shared/validation/external-csv.schemas.ts @@ -0,0 +1,40 @@ +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/src/shared/validation/project-structure.schemas.ts b/src/shared/validation/project-structure.schemas.ts index ede5152..143be0a 100644 --- a/src/shared/validation/project-structure.schemas.ts +++ b/src/shared/validation/project-structure.schemas.ts @@ -86,8 +86,6 @@ export const updateDistributionBoardSchema = z location: distributionBoardInfoValueSchema("location"), fedFrom: distributionBoardInfoValueSchema("fedFrom"), remark: distributionBoardInfoValueSchema("remark"), - feedingDistributionBoardId: z.string().trim().min(1).nullable().optional(), - feedingCircuitId: z.string().trim().min(1).nullable().optional(), }) .strict(); @@ -104,22 +102,10 @@ export const deleteDistributionBoardSchema = z }) .strict(); -export const createBuildingSchema = z - .object({ - expectedRevision: expectedProjectRevisionSchema, - name: z.string().trim().min(1).max(200), - }) - .strict(); - -export const updateBuildingSchema = createBuildingSchema; - -// A missing buildingId keeps the current value (older clients send only the -// name); null removes the floor from its building. export const createFloorSchema = z .object({ expectedRevision: expectedProjectRevisionSchema, name: z.string().trim().min(1).max(200), - buildingId: z.string().trim().min(1).nullable().optional(), }) .strict(); @@ -137,7 +123,6 @@ export const createRoomSchema = z floorId: z.string().trim().min(1).optional(), roomNumber: z.string().trim().min(1).max(50), roomName: z.string().trim().min(1).max(200), - areaM2: z.number().finite().nonnegative().nullable().optional(), }) .strict(); @@ -147,7 +132,6 @@ export const updateRoomSchema = z floorId: z.string().trim().min(1).nullable(), roomNumber: z.string().trim().min(1).max(50), roomName: z.string().trim().min(1).max(200), - areaM2: z.number().finite().nonnegative().nullable().optional(), }) .strict(); diff --git a/src/shared/validation/user.schemas.ts b/src/shared/validation/user.schemas.ts deleted file mode 100644 index cec4c5f..0000000 --- a/src/shared/validation/user.schemas.ts +++ /dev/null @@ -1,48 +0,0 @@ -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"; - -// 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() - .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(MAX_PASSWORD_LENGTH), - }) - .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(MAX_PASSWORD_LENGTH), - }) - .strict(); - -export type CreateUserInput = z.infer; -export type UpdateUserInput = z.infer; -export type ResetPasswordInput = z.infer; diff --git a/tests/authentication.test.ts b/tests/authentication.test.ts deleted file mode 100644 index e5c431d..0000000 --- a/tests/authentication.test.ts +++ /dev/null @@ -1,320 +0,0 @@ -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"; -import { - WRITE_REQUEST_HEADER_NAME, - WRITE_REQUEST_HEADER_VALUE, -} from "../src/shared/constants/request-security.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, - { bootstrap: config.bootstrap }, - { hash: hashPassword, verify: verifyPassword } - ), - }; -} - -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); - 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 - ); - }); -}); - -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, includeApplicationHeader = true) { - let status: number | undefined; - let passed = false; - const req = { - method, - 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) { - 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", false).passed, true); - assert.equal(run("POST", "same-origin").passed, true); - assert.equal(run("POST").passed, true, "scripts can send the explicit application header"); - }); - - 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 }); - }); -}); - -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("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({ - 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); - }); -}); diff --git a/tests/batched-insert.persistence.test.ts b/tests/batched-insert.persistence.test.ts deleted file mode 100644 index e7b2127..0000000 --- a/tests/batched-insert.persistence.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 { insertManyInBatches } from "../src/db/repositories/batched-insert.persistence.js"; -import { projects } from "../src/db/schema/projects.js"; - -describe("batched SQLite inserts", () => { - it("keeps every batch inside the caller transaction", () => { - const context = createDatabaseContext(":memory:"); - try { - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - const values = Array.from({ length: 401 }, (_, index) => ({ id: `project-${index}`, name: `Projekt ${index}` })); - values[400] = { id: "project-0", name: "Duplikat" }; - assert.throws(() => context.db.transaction((tx) => insertManyInBatches(tx, projects, values))); - assert.equal(context.db.select().from(projects).all().length, 0); - } finally { context.close(); } - }); -}); diff --git a/tests/building-structure-frontend-api.test.ts b/tests/building-structure-frontend-api.test.ts deleted file mode 100644 index 9e23150..0000000 --- a/tests/building-structure-frontend-api.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { - createBuilding, - createFloor, - deleteBuilding, - listBuildings, - updateBuilding, - updateFloor, -} from "../src/frontend/utils/api.js"; - -describe("building structure frontend API", () => { - it("sends building commands and optional floor building assignments", 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 === undefined ? undefined : JSON.parse(String(init.body)), - }); - return new Response(JSON.stringify([]), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - }; - try { - await listBuildings("project-1"); - await createBuilding("project-1", { name: "Haus A" }, 3); - await updateBuilding("project-1", "building-1", { name: "Haus B" }, 4); - await deleteBuilding("project-1", "building-1", 5); - await createFloor( - "project-1", - { name: "EG", buildingId: "building-1" }, - 6 - ); - await createFloor("project-1", { name: "Dach", buildingId: null }, 7); - await createFloor("project-1", { name: "UG", buildingId: undefined }, 8); - await updateFloor( - "project-1", - "floor-1", - { name: "1. OG", buildingId: null }, - 9 - ); - await updateFloor("project-1", "floor-1", { name: "2. OG" }, 10); - } finally { - globalThis.fetch = originalFetch; - } - - assert.deepEqual(requests, [ - { - url: "/api/projects/project-1/buildings", - method: "GET", - body: undefined, - }, - { - url: "/api/projects/project-1/buildings", - method: "POST", - body: { name: "Haus A", expectedRevision: 3 }, - }, - { - url: "/api/projects/project-1/buildings/building-1", - method: "PUT", - body: { name: "Haus B", expectedRevision: 4 }, - }, - { - url: "/api/projects/project-1/buildings/building-1", - method: "DELETE", - body: { expectedRevision: 5 }, - }, - { - url: "/api/projects/project-1/floors", - method: "POST", - body: { name: "EG", buildingId: "building-1", expectedRevision: 6 }, - }, - { - url: "/api/projects/project-1/floors", - method: "POST", - body: { name: "Dach", buildingId: null, expectedRevision: 7 }, - }, - { - url: "/api/projects/project-1/floors", - method: "POST", - body: { name: "UG", expectedRevision: 8 }, - }, - { - url: "/api/projects/project-1/floors/floor-1", - method: "PUT", - body: { name: "1. OG", buildingId: null, expectedRevision: 9 }, - }, - { - url: "/api/projects/project-1/floors/floor-1", - method: "PUT", - body: { name: "2. OG", expectedRevision: 10 }, - }, - ]); - const updateWithoutBuilding = requests[8].body as Record; - assert.equal("buildingId" in updateWithoutBuilding, false); - }); -}); diff --git a/tests/building-structure-view.test.ts b/tests/building-structure-view.test.ts deleted file mode 100644 index a024818..0000000 --- a/tests/building-structure-view.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import type { - BuildingDto, - FloorDto, - RoomDto, -} from "../src/frontend/types.js"; -import { - ALL_SELECTION, - UNASSIGNED_SELECTION, - countFloorsByBuilding, - countRoomsByFloor, - defaultBuildingIdForNewFloor, - defaultFloorIdForNewRoom, - describeRoomLocation, - filterFloorsByBuilding, - filterRooms, - groupFloorsByBuilding, - hasFloorsWithoutBuilding, - hasRoomsWithoutFloor, - normalizeBuildingSelection, - normalizeFloorSelection, - showsRoomsWithoutFloorEntry, - summarizeRoomAreas, -} from "../src/frontend/utils/building-structure.js"; - -function building(id: string, name: string, sortOrder: number): BuildingDto { - return { id, projectId: "project-1", name, sortOrder }; -} - -function floor( - id: string, - name: string, - buildingId: string | null, - sortOrder = 0 -): FloorDto { - return { id, projectId: "project-1", name, sortOrder, buildingId }; -} - -function room( - id: string, - floorId: string | null, - roomNumber = id, - areaM2: number | null = null -): RoomDto { - return { - id, - projectId: "project-1", - floorId, - roomNumber, - roomName: `Raum ${roomNumber}`, - areaM2, - }; -} - -const buildings = [building("b-a", "Haus A", 0), building("b-b", "Haus B", 1)]; -const floors = [ - floor("f-free", "Außenanlage", null, 0), - floor("f-a-eg", "EG", "b-a", 1), - floor("f-b-eg", "EG", "b-b", 2), - floor("f-a-og", "1. OG", "b-a", 3), - floor("f-orphan", "Keller", "b-deleted", 4), -]; -const rooms = [ - room("r-a-eg", "f-a-eg"), - room("r-a-og", "f-a-og"), - room("r-b-eg", "f-b-eg"), - room("r-free", "f-free"), - room("r-orphan-floor", "f-orphan"), - room("r-none", null), - room("r-missing-floor", "f-deleted"), -]; - -const ids = (entries: ReadonlyArray<{ id: string }>) => - entries.map((entry) => entry.id); - -describe("building structure view", () => { - it("groups floors in building order and puts unassigned floors last", () => { - const groups = groupFloorsByBuilding(floors, buildings); - assert.deepEqual( - groups.map((group) => ({ - buildingId: group.buildingId, - label: group.label, - floors: ids(group.floors), - })), - [ - { buildingId: "b-a", label: "Haus A", floors: ["f-a-eg", "f-a-og"] }, - { buildingId: "b-b", label: "Haus B", floors: ["f-b-eg"] }, - { - buildingId: null, - label: "Ohne Gebäude", - floors: ["f-free", "f-orphan"], - }, - ] - ); - }); - - it("omits empty groups", () => { - const groups = groupFloorsByBuilding( - [floor("f-1", "EG", "b-b")], - buildings - ); - assert.deepEqual( - groups.map((group) => group.buildingId), - ["b-b"] - ); - assert.deepEqual(groupFloorsByBuilding([], buildings), []); - }); - - it("filters floors by building selection", () => { - assert.deepEqual( - ids(filterFloorsByBuilding(floors, buildings, ALL_SELECTION)), - ids(floors) - ); - assert.deepEqual( - ids(filterFloorsByBuilding(floors, buildings, "b-a")), - ["f-a-eg", "f-a-og"] - ); - assert.deepEqual( - ids(filterFloorsByBuilding(floors, buildings, UNASSIGNED_SELECTION)), - ["f-free", "f-orphan"] - ); - }); - - it("detects floors without building and rooms without floor", () => { - assert.equal(hasFloorsWithoutBuilding(floors, buildings), true); - assert.equal( - hasFloorsWithoutBuilding([floor("f-1", "EG", "b-a")], buildings), - false - ); - assert.equal(hasRoomsWithoutFloor(rooms, floors), true); - assert.equal(hasRoomsWithoutFloor([room("r-1", "f-a-eg")], floors), false); - }); - - it("filters rooms for building and floor selections", () => { - assert.deepEqual( - ids(filterRooms(rooms, floors, buildings, ALL_SELECTION, ALL_SELECTION)), - ids(rooms) - ); - assert.deepEqual( - ids(filterRooms(rooms, floors, buildings, "b-a", ALL_SELECTION)), - ["r-a-eg", "r-a-og"] - ); - assert.deepEqual( - ids(filterRooms(rooms, floors, buildings, "b-a", "f-a-og")), - ["r-a-og"] - ); - assert.deepEqual( - ids(filterRooms(rooms, floors, buildings, ALL_SELECTION, "f-b-eg")), - ["r-b-eg"] - ); - assert.deepEqual( - ids( - filterRooms( - rooms, - floors, - buildings, - UNASSIGNED_SELECTION, - ALL_SELECTION - ) - ), - ["r-free", "r-orphan-floor", "r-none", "r-missing-floor"] - ); - assert.deepEqual( - ids( - filterRooms( - rooms, - floors, - buildings, - ALL_SELECTION, - UNASSIGNED_SELECTION - ) - ), - ["r-none", "r-missing-floor"] - ); - assert.deepEqual( - ids(filterRooms(rooms, floors, buildings, "b-a", UNASSIGNED_SELECTION)), - [] - ); - }); - - it("offers 'Ohne Etage' only where rooms without floor can belong", () => { - assert.equal(showsRoomsWithoutFloorEntry(rooms, floors, ALL_SELECTION), true); - assert.equal( - showsRoomsWithoutFloorEntry(rooms, floors, UNASSIGNED_SELECTION), - true - ); - assert.equal(showsRoomsWithoutFloorEntry(rooms, floors, "b-a"), false); - assert.equal( - showsRoomsWithoutFloorEntry([room("r-1", "f-a-eg")], floors, ALL_SELECTION), - false - ); - }); - - it("falls back to 'Alle' for vanished or hidden selections", () => { - assert.equal(normalizeBuildingSelection("b-a", floors, buildings), "b-a"); - assert.equal( - normalizeBuildingSelection("b-deleted", floors, buildings), - ALL_SELECTION - ); - assert.equal( - normalizeBuildingSelection(UNASSIGNED_SELECTION, floors, buildings), - UNASSIGNED_SELECTION - ); - assert.equal( - normalizeBuildingSelection( - UNASSIGNED_SELECTION, - [floor("f-1", "EG", "b-a")], - buildings - ), - ALL_SELECTION - ); - - assert.equal( - normalizeFloorSelection("f-a-og", rooms, floors, buildings, "b-a"), - "f-a-og" - ); - assert.equal( - normalizeFloorSelection("f-b-eg", rooms, floors, buildings, "b-a"), - ALL_SELECTION - ); - assert.equal( - normalizeFloorSelection("f-deleted", rooms, floors, buildings, ALL_SELECTION), - ALL_SELECTION - ); - assert.equal( - normalizeFloorSelection( - UNASSIGNED_SELECTION, - rooms, - floors, - buildings, - ALL_SELECTION - ), - UNASSIGNED_SELECTION - ); - assert.equal( - normalizeFloorSelection(UNASSIGNED_SELECTION, rooms, floors, buildings, "b-a"), - ALL_SELECTION - ); - }); - - it("preselects the selected building and floor for new entries", () => { - assert.equal(defaultBuildingIdForNewFloor("b-a"), "b-a"); - assert.equal(defaultBuildingIdForNewFloor(ALL_SELECTION), ""); - assert.equal(defaultBuildingIdForNewFloor(UNASSIGNED_SELECTION), ""); - assert.equal(defaultFloorIdForNewRoom("f-a-eg"), "f-a-eg"); - assert.equal(defaultFloorIdForNewRoom(ALL_SELECTION), ""); - assert.equal(defaultFloorIdForNewRoom(UNASSIGNED_SELECTION), ""); - }); - - it("counts floors per building and rooms per floor", () => { - assert.deepEqual( - [...countFloorsByBuilding(floors, buildings)], - [ - [null, 2], - ["b-a", 2], - ["b-b", 1], - ] - ); - assert.deepEqual( - [...countRoomsByFloor(rooms, floors)], - [ - ["f-a-eg", 1], - ["f-a-og", 1], - ["f-b-eg", 1], - ["f-free", 1], - ["f-orphan", 1], - [null, 2], - ] - ); - }); - - it("sums known areas and counts missing areas per floor and building", () => { - const areaRooms = [ - room("a", "f-a-eg", "a", 20.25), - room("b", "f-a-eg"), - room("c", "f-free", "c", 5.5), - room("d", null, "d", 3), - room("e", "f-deleted"), - ]; - const summaries = summarizeRoomAreas(areaRooms, floors, buildings); - - assert.deepEqual(summaries.total, { - areaM2: 28.75, - roomCount: 5, - missingAreaCount: 2, - }); - assert.deepEqual(summaries.byFloor.get("f-a-eg"), { - areaM2: 20.25, - roomCount: 2, - missingAreaCount: 1, - }); - assert.deepEqual(summaries.byFloor.get(null), { - areaM2: 3, - roomCount: 2, - missingAreaCount: 1, - }); - assert.deepEqual(summaries.byBuilding.get("b-a"), { - areaM2: 20.25, - roomCount: 2, - missingAreaCount: 1, - }); - assert.deepEqual(summaries.byBuilding.get(null), { - areaM2: 8.5, - roomCount: 3, - missingAreaCount: 1, - }); - }); - - it("describes a room location with floor and building", () => { - assert.equal( - describeRoomLocation(room("r", "f-a-og"), floors, buildings), - "1. OG · Haus A" - ); - assert.equal( - describeRoomLocation(room("r", "f-free"), floors, buildings), - "Außenanlage" - ); - assert.equal( - describeRoomLocation(room("r", "f-orphan"), floors, buildings), - "Keller" - ); - assert.equal( - describeRoomLocation(room("r", null), floors, buildings), - "Ohne Etage" - ); - }); -}); diff --git a/tests/cable-sizing-calculation.repository.test.ts b/tests/cable-sizing-calculation.repository.test.ts new file mode 100644 index 0000000..c5a2ac1 --- /dev/null +++ b/tests/cable-sizing-calculation.repository.test.ts @@ -0,0 +1,152 @@ +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 { CableSizingCalculationRepository } from "../src/db/repositories/cable-sizing-calculation.repository.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 { projects } from "../src/db/schema/projects.js"; +import { DistributionBoardFixtureRepository } from "./support/distribution-board-fixture.js"; + +function createRepository() { + const context = createDatabaseContext(":memory:"); + migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); + return new CableSizingCalculationRepository(context.db); +} + +function createRepositoryWithCircuits(): { + repository: CableSizingCalculationRepository; + context: DatabaseContext; + circuitOneId: string; + circuitTwoId: string; +} { + 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(); + const board = new DistributionBoardFixtureRepository(context.db).createWithCircuitListAndDefaultSections( + "project-1", + "UV-01" + ); + const circuitList = context.db + .select() + .from(circuitLists) + .where(eq(circuitLists.distributionBoardId, board.id)) + .get(); + if (!circuitList) { + throw new Error("fixture did not create a circuit list"); + } + const section = context.db + .select() + .from(circuitSections) + .where(eq(circuitSections.circuitListId, circuitList.id)) + .get(); + if (!section) { + throw new Error("fixture did not create a section"); + } + const circuitOneId = "circuit-1"; + const circuitTwoId = "circuit-2"; + context.db + .insert(circuits) + .values([ + { + id: circuitOneId, + circuitListId: section.circuitListId, + sectionId: section.id, + equipmentIdentifier: "-1F1.1", + }, + { + id: circuitTwoId, + circuitListId: section.circuitListId, + sectionId: section.id, + equipmentIdentifier: "-1F1.2", + }, + ]) + .run(); + return { + repository: new CableSizingCalculationRepository(context.db), + context, + circuitOneId, + circuitTwoId, + }; +} + +describe("CableSizingCalculationRepository", () => { + it("creates an entry with input/result JSON and defaults appliedToCircuit to false", () => { + const repository = createRepository(); + const entry = repository.create({ + id: "calc-1", + projectId: null, + circuitId: null, + equipmentIdentifier: "-1F1.1", + input: { layingMethod: "C" }, + result: { recommendedCrossSectionMm2: 4 }, + appliedToCircuit: 0, + }); + assert.equal(entry.id, "calc-1"); + assert.equal(entry.appliedToCircuit, 0); + assert.deepEqual(entry.input, { layingMethod: "C" }); + assert.deepEqual(entry.result, { recommendedCrossSectionMm2: 4 }); + }); + + it("lists entries by circuitId, most recent first", () => { + // createdAt defaults to SQLite's unixepoch() (second resolution), so two + // inserts in the same test can tie - pass explicit, distinct timestamps + // instead of racing the clock. circuitId has a real foreign key into + // circuits (foreign_keys = ON), so this needs actual circuit rows, not + // arbitrary strings. + const { repository, circuitOneId, circuitTwoId } = createRepositoryWithCircuits(); + repository.create({ + id: "calc-a", + projectId: null, + circuitId: circuitOneId, + equipmentIdentifier: null, + input: {}, + result: {}, + appliedToCircuit: 0, + createdAt: new Date(1000), + }); + repository.create({ + id: "calc-b", + projectId: null, + circuitId: circuitOneId, + equipmentIdentifier: null, + input: {}, + result: {}, + appliedToCircuit: 0, + createdAt: new Date(2000), + }); + repository.create({ + id: "calc-other-circuit", + projectId: null, + circuitId: circuitTwoId, + equipmentIdentifier: null, + input: {}, + result: {}, + appliedToCircuit: 0, + createdAt: new Date(3000), + }); + + const rows = repository.listByCircuit(circuitOneId); + assert.equal(rows.length, 2); + assert.equal(rows[0].id, "calc-b"); + assert.equal(rows[1].id, "calc-a"); + }); + + it("marks an entry as applied", () => { + const repository = createRepository(); + repository.create({ + id: "calc-1", + projectId: null, + circuitId: null, + equipmentIdentifier: null, + input: {}, + result: {}, + appliedToCircuit: 0, + }); + const updated = repository.markApplied("calc-1"); + assert.equal(updated?.appliedToCircuit, 1); + }); +}); diff --git a/tests/cable-sizing-calculation.test.ts b/tests/cable-sizing-calculation.test.ts index 53d81a1..89a935d 100644 --- a/tests/cable-sizing-calculation.test.ts +++ b/tests/cable-sizing-calculation.test.ts @@ -3,20 +3,9 @@ import { describe, it } from "node:test"; import { buildCableSizingAlerts, calculateCableSizing, - conventionalTrippingFactor, - CROSS_SECTIONS_MM2, - CURRENT_CAPACITY_A, - minimumIzForProtection, - temperatureOptions, + isCableSizingDataVerified, 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, @@ -34,298 +23,187 @@ const BASE_INPUT: CableSizingInput = { 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 (DIN VDE 0298-4:2023-06)", () => { - it("contains the checked PVC copper values", () => { - 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); - // 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); - // 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", "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 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); - }); - - 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)", () => { + it("matches the verified reference case (1~, 5 kW, 230 V, 30 m, method C, copper)", () => { const result = calculateCableSizing(BASE_INPUT); - assert.equal(result.supported, true); + assert.equal(result.dataVerified, 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 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: 11 }, grouped); - assert.ok(alerts.some((alert) => alert.text.includes("12 Stromkreise gerundet"))); + it("returns dataVerified: false and no numeric result for an unverified laying method", () => { + const result = calculateCableSizing({ ...BASE_INPUT, layingMethod: "A2" }); + assert.equal(result.dataVerified, false); + assert.equal(result.recommendedCrossSectionMm2, null); + assert.equal(result.rows.length, 0); + // The operating current itself does not depend on the capacity table + // and is still reported so the UI can show at least that much. + assert.ok(Math.abs(result.operatingCurrentA - 21.739) < 0.01); }); - 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("returns dataVerified: false for xlpe regardless of method", () => { + const result = calculateCableSizing({ ...BASE_INPUT, insulation: "xlpe" }); + assert.equal(result.dataVerified, false); }); - 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", () => { - 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, 25); - for (const row of result.rows.filter((row) => row.crossSectionMm2 < 25)) { - assert.equal(row.ratedCurrentA, null); - assert.equal(row.recommended, false); + it("isCableSizingDataVerified matches the six ported, verified methods only", () => { + for (const method of ["A1", "B2", "C", "E", "D1", "D2"] as const) { + assert.equal(isCableSizingDataVerified(method, "pvc"), true, method); + } + for (const method of ["A2", "B1", "F", "G"] as const) { + assert.equal(isCableSizingDataVerified(method, "pvc"), false, method); } }); - 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); + it("applies the 0.86 harmonic reduction factor only for three-phase + 15to33Percent", () => { + const threePhase: CableSizingInput = { + ...BASE_INPUT, + phase: 3, + mode: "current", + currentA: 10, + powerKw: undefined, + voltage: 400, + }; + const base = calculateCableSizing({ ...threePhase, harmonicNeutralLoad: "none" }); + const derated = calculateCableSizing({ + ...threePhase, + harmonicNeutralLoad: "15to33Percent", + }); + assert.equal(base.harmonicReductionApplied, false); + assert.equal(derated.harmonicReductionApplied, true); + assert.ok( + Math.abs(derated.combinedDerationFactor - base.combinedDerationFactor * 0.86) < 1e-9 + ); - // 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); + const singlePhaseWithHarmonics = calculateCableSizing({ + ...BASE_INPUT, + harmonicNeutralLoad: "15to33Percent", + }); + assert.equal(singlePhaseWithHarmonics.harmonicReductionApplied, false); }); - 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("uses max(operatingCurrentA, existingProtectionRatedCurrentA) as the design current for cross-section selection", () => { + // Load alone (21.7 A) would recommend 4 mm² (see the reference case + // above); a 32 A breaker on the same circuit must still be covered by + // the cable (In <= Iz), so the recommendation should grow accordingly. + const withoutBreaker = calculateCableSizing(BASE_INPUT); + const withBreaker = calculateCableSizing({ + ...BASE_INPUT, + existingProtectionRatedCurrentA: 32, + }); + assert.equal(withoutBreaker.designCurrentA, withoutBreaker.operatingCurrentA); + assert.equal(withBreaker.designCurrentA, 32); + assert.ok( + (withBreaker.recommendedCrossSectionMm2 ?? 0) >= + (withoutBreaker.recommendedCrossSectionMm2 ?? 0) + ); + assert.ok(withBreaker.protectionCoordination?.coordinated); }); - 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", () => { + it("reports an oversized breaker as the limiting factor when no cross-section can cover it", () => { const result = calculateCableSizing({ ...BASE_INPUT, - powerKw: 1, - lengthM: 5, - circuitCategory: "single_phase", + existingProtectionRatedCurrentA: 1000, }); - 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))); - }); + assert.equal(result.designCurrentA, 1000); + assert.equal(result.recommendedCrossSectionMm2, null); + // No cross-section satisfies the design current at all, so there is no + // "recommended but under-protected" case to flag - protectionCoordination + // is only meaningful once a recommendation exists. + assert.equal(result.protectionCoordination, null); - it("offers only tabulated temperatures", () => { - assert.deepEqual(temperatureOptions("C", "pvc").at(-1), 60); - assert.deepEqual(temperatureOptions("C", "xlpe").at(-1), 80); - assert.deepEqual(temperatureOptions("D", "pvc")[2], 20); + const alerts = buildCableSizingAlerts( + { ...BASE_INPUT, existingProtectionRatedCurrentA: 1000 }, + result + ); + assert.equal(alerts.length, 1); + assert.equal(alerts[0].kind, "critical"); + assert.ok(alerts[0].text.includes("Vorhandene Sicherung")); }); }); -describe("cable sizing request schema", () => { - it("accepts a complete request and rejects unknown or legacy fields", () => { - assert.equal(cableSizingRequestSchema.safeParse(BASE_INPUT).success, true); +describe("buildCableSizingAlerts", () => { + it("returns a single critical alert for an unverified combination, no numeric claims", () => { + const input: CableSizingInput = { ...BASE_INPUT, layingMethod: "G" }; + const result = calculateCableSizing(input); + const alerts = buildCableSizingAlerts(input, result); + assert.equal(alerts.length, 1); + assert.equal(alerts[0].kind, "critical"); + assert.ok(alerts[0].text.includes("keine geprüften")); + }); + + it("returns an ok alert plus a max-length info alert for a clean, unremarkable case", () => { + const input: CableSizingInput = { + ...BASE_INPUT, + mode: "current", + currentA: 15, + powerKw: undefined, + lengthM: 3, + }; + const result = calculateCableSizing(input); + const alerts = buildCableSizingAlerts(input, result); + assert.equal(alerts.length, 2); + assert.equal(alerts[0].kind, "ok"); + assert.equal(alerts[1].kind, "info"); + assert.ok(alerts[1].text.includes("Maximale Länge")); + }); +}); + +describe("maxLengthForVoltageDropM", () => { + it("is the inverse of the voltage-drop formula: recalculating at that length gives back the limit", () => { + const result = calculateCableSizing(BASE_INPUT); + const recommendedRow = result.rows.find((row) => row.recommended); + assert.ok(recommendedRow?.maxLengthForVoltageDropM != null); + + const atMaxLength = calculateCableSizing({ + ...BASE_INPUT, + lengthM: recommendedRow!.maxLengthForVoltageDropM!, + }); + const rowAtSameCrossSection = atMaxLength.rows.find( + (row) => row.crossSectionMm2 === recommendedRow!.crossSectionMm2 + ); + assert.ok( + Math.abs(rowAtSameCrossSection!.voltageDropPercent! - BASE_INPUT.maxVoltageDropPercent) < + 0.01 + ); + }); + + it("is null when there is no current flowing (division by zero guard)", () => { + const result = calculateCableSizing({ ...BASE_INPUT, mode: "current", currentA: 0, powerKw: undefined }); + assert.ok(result.rows.every((row) => row.maxLengthForVoltageDropM === null)); + }); +}); + +describe("practical minimum cross-section for single_phase circuits", () => { + it("raises a smaller calculated recommendation to 2.5 mm² for single_phase circuits", () => { + // 1 A load at 30 m would normally recommend 1.5 mm² by calculation alone. + const smallLoad: CableSizingInput = { ...BASE_INPUT, mode: "current", currentA: 1, powerKw: undefined }; + const withoutCategory = calculateCableSizing(smallLoad); + const withCategory = calculateCableSizing({ ...smallLoad, circuitCategory: "single_phase" }); + + assert.equal(withoutCategory.recommendedCrossSectionMm2, 1.5); + assert.equal(withoutCategory.practicalMinimumApplied, false); + assert.equal(withCategory.recommendedCrossSectionMm2, 2.5); + assert.equal(withCategory.practicalMinimumApplied, true); + }); + + it("never lowers a recommendation that already needs more than the practical minimum", () => { + const result = calculateCableSizing({ ...BASE_INPUT, circuitCategory: "single_phase" }); + assert.equal(result.recommendedCrossSectionMm2, 4); + assert.equal(result.practicalMinimumApplied, false); + }); + + it("does not apply to lighting or three_phase categories", () => { + const smallLoad: CableSizingInput = { ...BASE_INPUT, mode: "current", currentA: 1, powerKw: undefined }; assert.equal( - cableSizingRequestSchema.safeParse({ ...BASE_INPUT, existingProtection: { kind: "fuse", ratedCurrentA: 25 } }).success, - true + calculateCableSizing({ ...smallLoad, circuitCategory: "lighting" }).recommendedCrossSectionMm2, + 1.5 ); assert.equal( - cableSizingRequestSchema.safeParse({ ...BASE_INPUT, existingProtectionRatedCurrentA: 16 }).success, - false + calculateCableSizing({ ...smallLoad, circuitCategory: "three_phase" }).recommendedCrossSectionMm2, + 1.5 ); - 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); - }); -}); - -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), - 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, - 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("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); - 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); }); }); diff --git a/tests/circuit-device-row-move-project-command.repository.test.ts b/tests/circuit-device-row-move-project-command.repository.test.ts index 8975368..0569099 100644 --- a/tests/circuit-device-row-move-project-command.repository.test.ts +++ b/tests/circuit-device-row-move-project-command.repository.test.ts @@ -14,7 +14,6 @@ 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"; import { circuits } from "../src/db/schema/circuits.js"; -import { distributionBoards } from "../src/db/schema/distribution-boards.js"; import { projectRevisions } from "../src/db/schema/project-revisions.js"; import { projects } from "../src/db/schema/projects.js"; import { @@ -612,62 +611,6 @@ describe("circuit device-row move project-command repository", () => { } }); - it("blocks undo from removing a generated circuit used as a feeder", () => { - const fixture = createTestDatabase(); - try { - const store = new CircuitDeviceRowMoveProjectCommandRepository( - fixture.context.db - ); - const targetCircuit = createMoveTargetSnapshot(fixture); - const command = createCircuitDeviceRowMoveWithNewCircuitProjectCommand( - "create", - targetCircuit, - [{ - rowId: "row-1", - expectedCircuitId: "circuit-1", - expectedSortOrder: 10, - targetCircuitId: targetCircuit.id, - targetSortOrder: 10, - }] - ); - const moved = store.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command, - }); - const downstream = new DistributionBoardFixtureRepository( - fixture.context.db - ).createWithCircuitListAndDefaultSections("project-1", "UV-02"); - fixture.context.db - .update(distributionBoards) - .set({ - feedingDistributionBoardId: fixture.circuitListId, - feedingCircuitId: targetCircuit.id, - }) - .where(eq(distributionBoards.id, downstream.id)) - .run(); - - assert.throws( - () => store.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: moved.revision.changeSetId, - command: moved.inverse, - }), - /Speist UV-02 – erst Einspeisung ändern\./ - ); - assert.equal(getRow(fixture.context, "row-1")?.circuitId, targetCircuit.id); - assert.ok( - fixture.context.db.select().from(circuits) - .where(eq(circuits.id, targetCircuit.id)).get() - ); - } finally { - fixture.context.close(); - } - }); - it("rejects deletion when the created target changed outside history", () => { const fixture = createTestDatabase(); try { diff --git a/tests/circuit-grid-model.test.ts b/tests/circuit-grid-model.test.ts index 475d781..641a770 100644 --- a/tests/circuit-grid-model.test.ts +++ b/tests/circuit-grid-model.test.ts @@ -133,9 +133,7 @@ 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", "displayName"), "circuitField"); - assert.equal(getCellKind("reserveCircuit", "remark"), "circuitField"); - assert.equal(getCellKind("reserveCircuit", "powerPerUnit"), "deviceField"); + assert.equal(getCellKind("reserveCircuit", "remark"), "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 6551aee..952e3d6 100644 --- a/tests/circuit-grid-projection.test.ts +++ b/tests/circuit-grid-projection.test.ts @@ -47,10 +47,7 @@ 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: [], }; } @@ -179,91 +176,6 @@ describe("circuit grid projection", () => { ); }); - it("renders one linked downstream board as one compact editable circuit row", () => { - const feeder = { - ...reserveCircuit, - displayName: undefined, - 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", - "placeholder", - ]); - const loadRow = rows[1]; - assert.equal( - loadRow.cells.find((cell) => cell.cellKey === "displayName")?.value, - "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.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", () => { const protectedSections = sections.map((section) => ({ ...section, diff --git a/tests/circuit-group-subtree-project-command.repository.test.ts b/tests/circuit-group-subtree-project-command.repository.test.ts index 8494798..05d7dcc 100644 --- a/tests/circuit-group-subtree-project-command.repository.test.ts +++ b/tests/circuit-group-subtree-project-command.repository.test.ts @@ -16,7 +16,6 @@ import { circuitSections } from "../src/db/schema/circuit-sections.js"; import { circuits } from "../src/db/schema/circuits.js"; import { distributionBoardComponentProtectionDevices } from "../src/db/schema/distribution-board-component-protection-devices.js"; import { distributionBoardComponents } from "../src/db/schema/distribution-board-components.js"; -import { distributionBoards } from "../src/db/schema/distribution-boards.js"; import { projectRevisions } from "../src/db/schema/project-revisions.js"; import { projects } from "../src/db/schema/projects.js"; import { createCircuitGroupDeleteSubtreeProjectCommand } from "../src/domain/models/circuit-group-subtree-project-command.model.js"; @@ -229,45 +228,6 @@ describe("circuit-group subtree project command", () => { } }); - it("blocks deleting a group containing a feeding circuit", () => { - const context = createTestDatabase(); - try { - const list = context.db.select().from(circuitLists).get()!; - const downstream = new DistributionBoardFixtureRepository( - context.db - ).createWithCircuitListAndDefaultSections("project-1", "Unterverteiler"); - context.db - .update(distributionBoards) - .set({ - feedingDistributionBoardId: list.distributionBoardId, - feedingCircuitId: "subtree-circuit", - }) - .where(eq(distributionBoards.id, downstream.id)) - .run(); - const repository = - new CircuitGroupSubtreeProjectCommandRepository(context.db); - const groupId = context.db - .select() - .from(circuits) - .where(eq(circuits.id, "subtree-circuit")) - .get()!.sectionId; - const snapshot = repository.capture("project-1", groupId); - - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createCircuitGroupDeleteSubtreeProjectCommand(snapshot), - }), - /Speist Unterverteiler – erst Einspeisung ändern\./ - ); - assert.deepEqual(repository.capture("project-1", groupId), snapshot); - } finally { - context.close(); - } - }); - it("rolls back a cascaded deletion when history persistence fails", () => { const context = createTestDatabase(); try { diff --git a/tests/circuit-structure-project-command.repository.test.ts b/tests/circuit-structure-project-command.repository.test.ts index 8985ad0..4c05554 100644 --- a/tests/circuit-structure-project-command.repository.test.ts +++ b/tests/circuit-structure-project-command.repository.test.ts @@ -14,7 +14,6 @@ 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"; import { circuits } from "../src/db/schema/circuits.js"; -import { distributionBoards } from "../src/db/schema/distribution-boards.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"; @@ -443,48 +442,6 @@ describe("circuit structure project-command repository", () => { } }); - it("blocks deleting a circuit that feeds a distribution board", () => { - const fixture = createTestDatabase(); - try { - const downstream = new DistributionBoardFixtureRepository( - fixture.context.db - ).createWithCircuitListAndDefaultSections("project-1", "UV Unterverteiler"); - fixture.context.db - .update(distributionBoards) - .set({ - boardNumber: "UV-02", - feedingDistributionBoardId: fixture.circuitListId, - feedingCircuitId: "circuit-existing", - }) - .where(eq(distributionBoards.id, downstream.id)) - .run(); - - const store = new CircuitStructureProjectCommandRepository( - fixture.context.db - ); - assert.throws( - () => - store.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createCircuitDeleteProjectCommand( - "circuit-existing", - fixture.circuitListId - ), - }), - /Speist UV-02 – erst Einspeisung ändern\./ - ); - assert.ok(getCircuit(fixture.context, "circuit-existing")); - assert.equal( - fixture.context.db.select().from(projectRevisions).all().length, - 0 - ); - } finally { - fixture.context.close(); - } - }); - it("rolls back insert and delete for late history failures", () => { const fixture = createTestDatabase(); try { diff --git a/tests/circuit-tree.controller.test.ts b/tests/circuit-tree.controller.test.ts index ea20da2..7fcf884 100644 --- a/tests/circuit-tree.controller.test.ts +++ b/tests/circuit-tree.controller.test.ts @@ -38,15 +38,13 @@ describe("circuit tree controller", () => { it("returns header, grouped and footer components with both protection layers", async () => { const originals = { findList: circuitListRepository.findById, - listLists: circuitListRepository.listByProject, findProject: projectRepository.findById, findBoard: distributionBoardRepository.findById, - listBoards: distributionBoardRepository.listByProject, - listSections: circuitSectionRepository.listByCircuitLists, - listCircuits: circuitRepository.listByCircuitLists, + listSections: circuitSectionRepository.listByCircuitList, + listCircuits: circuitRepository.listByCircuitList, listRows: circuitDeviceRowRepository.listByCircuitList, listComponents: - distributionBoardComponentRepository.listByCircuitLists, + distributionBoardComponentRepository.listByCircuitList, listComponentProtection: distributionBoardComponentRepository.listProtectionByComponentIds, listCircuitProtection: @@ -59,13 +57,6 @@ describe("circuit tree controller", () => { distributionBoardId: "board-1", name: "UV-01", }) as never; - circuitListRepository.listByProject = async () => - [{ - id: "list-1", - projectId: "project-1", - distributionBoardId: "board-1", - name: "UV-01", - }] as never; projectRepository.findById = async () => ({ id: "project-1", @@ -75,19 +66,8 @@ describe("circuit tree controller", () => { threePhaseVoltageV: 400, }) as never; distributionBoardRepository.findById = async () => - ({ id: "board-1", name: "UV-01", simultaneityFactor: 0.8 }) as never; - distributionBoardRepository.listByProject = async () => - [{ - id: "board-1", - projectId: "project-1", - name: "UV-01", - boardNumber: "UV-01", - supplyType: "AV", - simultaneityFactor: 0.8, - feedingDistributionBoardId: null, - feedingCircuitId: null, - }] as never; - circuitSectionRepository.listByCircuitLists = async () => + ({ id: "board-1", simultaneityFactor: 0.8 }) as never; + circuitSectionRepository.listByCircuitList = async () => [ { id: "group-1", @@ -100,7 +80,7 @@ describe("circuit tree controller", () => { groupNumber: 1, }, ] as never; - circuitRepository.listByCircuitLists = async () => + circuitRepository.listByCircuitList = async () => [ { id: "circuit-1", @@ -110,19 +90,10 @@ describe("circuit tree controller", () => { displayName: "Licht", sortOrder: 10, isReserve: 0, - cableType: null, - cableCrossSection: null, - cableLength: null, - rcdAssignment: null, - terminalDesignation: null, - voltage: 230, - controlRequirement: null, - status: null, - remark: null, }, ] as never; circuitDeviceRowRepository.listByCircuitList = async () => []; - distributionBoardComponentRepository.listByCircuitLists = + distributionBoardComponentRepository.listByCircuitList = async () => [ { @@ -199,15 +170,13 @@ describe("circuit tree controller", () => { ); } finally { circuitListRepository.findById = originals.findList; - circuitListRepository.listByProject = originals.listLists; projectRepository.findById = originals.findProject; distributionBoardRepository.findById = originals.findBoard; - distributionBoardRepository.listByProject = originals.listBoards; - circuitSectionRepository.listByCircuitLists = + circuitSectionRepository.listByCircuitList = originals.listSections; - circuitRepository.listByCircuitLists = originals.listCircuits; + circuitRepository.listByCircuitList = originals.listCircuits; circuitDeviceRowRepository.listByCircuitList = originals.listRows; - distributionBoardComponentRepository.listByCircuitLists = + distributionBoardComponentRepository.listByCircuitList = originals.listComponents; distributionBoardComponentRepository.listProtectionByComponentIds = originals.listComponentProtection; diff --git a/tests/client-id.test.ts b/tests/client-id.test.ts deleted file mode 100644 index 95baa60..0000000 --- a/tests/client-id.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import assert from "node:assert/strict"; -import { webcrypto } from "node:crypto"; -import { describe, it } from "node:test"; -import { z } from "zod"; -import { createClientId } from "../src/frontend/utils/client-id.js"; - -const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; - -describe("client id", () => { - it("uses crypto.randomUUID when the context provides it", () => { - const id = createClientId({ - getRandomValues: () => { - throw new Error("fallback must not be used"); - }, - randomUUID: () => "11111111-2222-4333-8444-555555555555", - }); - assert.equal(id, "11111111-2222-4333-8444-555555555555"); - }); - - it("falls back to getRandomValues outside a secure context", () => { - const insecure = { - getRandomValues: webcrypto.getRandomValues.bind(webcrypto), - } as Pick; - const ids = new Set(); - for (let index = 0; index < 200; index += 1) { - const id = createClientId(insecure); - assert.match(id, uuidV4); - assert.equal(z.string().uuid().safeParse(id).success, true); - ids.add(id); - } - assert.equal(ids.size, 200); - }); - - it("sets version and variant bits regardless of the random bytes", () => { - const allOnes = { - getRandomValues: (array: T) => { - if (array instanceof Uint8Array) { - array.fill(0xff); - } - return array; - }, - } as Pick; - assert.equal(createClientId(allOnes), "ffffffff-ffff-4fff-bfff-ffffffffffff"); - }); -}); diff --git a/tests/config-access.test.ts b/tests/config-access.test.ts deleted file mode 100644 index 3fdc83d..0000000 --- a/tests/config-access.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -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/distribution-board-feeder-circuit-project-command.repository.test.ts b/tests/distribution-board-feeder-circuit-project-command.repository.test.ts deleted file mode 100644 index d4d2c26..0000000 --- a/tests/distribution-board-feeder-circuit-project-command.repository.test.ts +++ /dev/null @@ -1,240 +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 { 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 deleted file mode 100644 index fb143da..0000000 --- a/tests/distribution-board-feeder-circuit.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -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"], - ] - ); - }); -}); diff --git a/tests/distribution-board-load-calculation.test.ts b/tests/distribution-board-load-calculation.test.ts deleted file mode 100644 index f6c9a95..0000000 --- a/tests/distribution-board-load-calculation.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { calculateDistributionBoardLoads } from "../src/domain/calculations/distribution-board-load-calculation.js"; - -const board = ( - id: string, - simultaneityFactor: number, - feedingDistributionBoardId: string | null = null, - feedingCircuitId: string | null = null -) => ({ - id, - name: id, - boardNumber: id.toUpperCase(), - simultaneityFactor, - feedingDistributionBoardId, - feedingCircuitId, -}); - -describe("distribution-board load calculation", () => { - it("rolls recursive demand into the selected feeder circuit exactly once", () => { - const result = calculateDistributionBoardLoads({ - boards: [ - board("nshv", 0.8), - board("uv1", 0.5, "nshv", "nshv-out"), - board("uv2", 0.25, "uv1", "uv1-out"), - ], - circuits: [ - { id: "nshv-out", distributionBoardId: "nshv", rows: [{ activePowerKw: 2, cosPhi: 1 }] }, - { id: "uv1-out", distributionBoardId: "uv1", rows: [{ activePowerKw: 4, cosPhi: 0.8 }] }, - { id: "uv2-load", distributionBoardId: "uv2", rows: [{ activePowerKw: 8, cosPhi: 0.8 }] }, - ], - }); - - assert.deepEqual(result.boards.get("uv2"), { - distributionBoardId: "uv2", - activePowerBeforeSimultaneityKw: 8, - apparentPowerBeforeSimultaneityKva: 10, - demandActivePowerKw: 2, - demandApparentPowerKva: 2.5, - cosPhi: 0.8, - }); - assert.equal(result.circuits.get("uv1-out")?.activePowerKw, 6); - assert.equal(result.boards.get("uv1")?.demandActivePowerKw, 3); - assert.equal(result.circuits.get("nshv-out")?.activePowerKw, 5); - assert.equal(result.boards.get("nshv")?.demandActivePowerKw, 4); - assert.equal(result.circuits.get("nshv-out")?.downstreamBoards.length, 1); - }); - - it("combines apparent power for multiple child boards on one circuit", () => { - const result = calculateDistributionBoardLoads({ - boards: [board("main", 1), board("a", 1, "main", "out"), board("b", 1, "main", "out")], - circuits: [ - { id: "out", distributionBoardId: "main", rows: [] }, - { id: "a-load", distributionBoardId: "a", rows: [{ activePowerKw: 2, cosPhi: 0.5 }] }, - { id: "b-load", distributionBoardId: "b", rows: [{ activePowerKw: 2, cosPhi: 1 }] }, - ], - }); - const feeder = result.circuits.get("out")!; - assert.equal(feeder.activePowerKw, 4); - assert.equal(feeder.apparentPowerKva, 6); - assert.equal(feeder.cosPhi, 2 / 3); - assert.deepEqual(feeder.downstreamBoards.map((entry) => entry.distributionBoardId), ["a", "b"]); - }); - - it("keeps a board-only hierarchy relation out of load rollup", () => { - const result = calculateDistributionBoardLoads({ - boards: [board("main", 1), board("child", 1, "main", null)], - circuits: [ - { id: "main-load", distributionBoardId: "main", rows: [{ activePowerKw: 1, cosPhi: 1 }] }, - { id: "child-load", distributionBoardId: "child", rows: [{ activePowerKw: 5, cosPhi: 1 }] }, - ], - }); - assert.equal(result.boards.get("main")?.demandActivePowerKw, 1); - assert.equal(result.boards.get("child")?.demandActivePowerKw, 5); - }); - - it("rejects cycles defensively", () => { - assert.throws( - () => calculateDistributionBoardLoads({ - boards: [board("a", 1, "b", "b-out"), board("b", 1, "a", "a-out")], - circuits: [ - { id: "a-out", distributionBoardId: "a", rows: [] }, - { id: "b-out", distributionBoardId: "b", rows: [] }, - ], - }), - /cycle/ - ); - }); -}); diff --git a/tests/distribution-board-structure-project-command.repository.test.ts b/tests/distribution-board-structure-project-command.repository.test.ts index a02f005..f829edf 100644 --- a/tests/distribution-board-structure-project-command.repository.test.ts +++ b/tests/distribution-board-structure-project-command.repository.test.ts @@ -219,54 +219,6 @@ describe("distribution-board structure project command", () => { } }); - it("blocks undo from removing an empty board used as a feeder", () => { - const context = createTestDatabase(); - try { - const repository = - new DistributionBoardStructureProjectCommandRepository(context.db); - const upstream = createDistributionBoardStructureSnapshot( - "project-1", - "NSHV" - ); - const inserted = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createDistributionBoardInsertProjectCommand(upstream), - }); - const downstream = createDistributionBoardStructureSnapshot( - "project-1", - "UV-01" - ); - context.db.insert(distributionBoards).values({ - ...downstream.distributionBoard, - boardNumber: "UV-01", - feedingDistributionBoardId: upstream.distributionBoard.id, - }).run(); - context.db.insert(circuitLists).values(downstream.circuitList).run(); - context.db.insert(circuitSections).values(downstream.sections).run(); - context.db.insert(distributionBoardComponents) - .values(downstream.components).run(); - - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: inserted.revision.changeSetId, - command: inserted.inverse, - }), - /Speist UV-01 – erst Einspeisung ändern\./ - ); - assert.ok( - context.db.select().from(distributionBoards) - .where(eq(distributionBoards.id, upstream.distributionBoard.id)).get() - ); - } finally { - context.close(); - } - }); - it("allows only supply types enabled in the project", () => { const context = createTestDatabase(); try { @@ -539,159 +491,6 @@ describe("distribution-board structure project command", () => { } }); - it("links a feeding board and circuit while preserving version-1 updates", () => { - const context = createTestDatabase(); - try { - const repository = - new DistributionBoardStructureProjectCommandRepository(context.db); - const upstream = createDistributionBoardStructureSnapshot( - "project-1", - "NSHV", - { supplyType: "AV" } - ); - const downstream = createDistributionBoardStructureSnapshot( - "project-1", - "UV EG", - { supplyType: "AV" } - ); - repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createDistributionBoardInsertProjectCommand(upstream), - }); - repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "user", - command: createDistributionBoardInsertProjectCommand(downstream), - }); - context.db.insert(circuits).values([ - { - id: "feed-circuit", - circuitListId: upstream.circuitList.id, - sectionId: upstream.sections[2]!.id, - equipmentIdentifier: "-3F1.1", - sortOrder: 10, - }, - { - id: "downstream-circuit", - circuitListId: downstream.circuitList.id, - sectionId: downstream.sections[2]!.id, - equipmentIdentifier: "-3F1.1", - sortOrder: 10, - }, - ]).run(); - - const linked = repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 2, - source: "user", - command: createDistributionBoardUpdateProjectCommand( - downstream.distributionBoard.id, - { - feedingDistributionBoardId: upstream.distributionBoard.id, - feedingCircuitId: "feed-circuit", - } - ), - }); - assert.deepEqual( - context.db - .select({ - feedingDistributionBoardId: - distributionBoards.feedingDistributionBoardId, - feedingCircuitId: distributionBoards.feedingCircuitId, - }) - .from(distributionBoards) - .where(eq(distributionBoards.id, downstream.distributionBoard.id)) - .get(), - { - feedingDistributionBoardId: upstream.distributionBoard.id, - feedingCircuitId: "feed-circuit", - } - ); - - repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 3, - source: "undo", - historyTargetChangeSetId: new ProjectHistoryRepository( - context.db - ).getNextCommand("project-1", "undo")?.changeSetId, - command: linked.inverse, - }); - repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 4, - source: "user", - command: createDistributionBoardUpdateProjectCommand( - downstream.distributionBoard.id, - { - feedingDistributionBoardId: upstream.distributionBoard.id, - feedingCircuitId: null, - } - ), - }); - - assert.throws( - () => repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 5, - source: "user", - command: createDistributionBoardUpdateProjectCommand( - upstream.distributionBoard.id, - { - feedingDistributionBoardId: downstream.distributionBoard.id, - feedingCircuitId: null, - } - ), - }), - /Zyklus/ - ); - assert.throws( - () => repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 5, - source: "user", - command: createDistributionBoardUpdateProjectCommand( - downstream.distributionBoard.id, - { - feedingDistributionBoardId: upstream.distributionBoard.id, - feedingCircuitId: "downstream-circuit", - } - ), - }), - /gehört nicht zur gewählten Verteilung/ - ); - - repository.executeUpdate({ - projectId: "project-1", - expectedRevision: 5, - source: "user", - command: { - schemaVersion: 1, - type: "distribution-board.update", - payload: { - distributionBoardId: downstream.distributionBoard.id, - changes: [{ field: "boardNumber", value: "UV-01" }], - }, - }, - }); - const afterLegacyUpdate = context.db - .select() - .from(distributionBoards) - .where(eq(distributionBoards.id, downstream.distributionBoard.id)) - .get(); - assert.equal(afterLegacyUpdate?.boardNumber, "UV-01"); - assert.equal( - afterLegacyUpdate?.feedingDistributionBoardId, - upstream.distributionBoard.id - ); - } finally { - context.close(); - } - }); - it("sends distribution-board writes to the revision-safe API", async () => { const requests: Array<{ url: string; method: string; body: unknown }> = []; const originalFetch = globalThis.fetch; diff --git a/tests/distribution-board-subtree-project-command.repository.test.ts b/tests/distribution-board-subtree-project-command.repository.test.ts index 6508b9b..7975f2b 100644 --- a/tests/distribution-board-subtree-project-command.repository.test.ts +++ b/tests/distribution-board-subtree-project-command.repository.test.ts @@ -291,43 +291,6 @@ describe("distribution-board subtree project command", () => { } }); - it("blocks deleting a board subtree that feeds another board", () => { - const context = createTestDatabase(); - try { - const upstream = createPopulatedBoard(context); - const downstream = new DistributionBoardFixtureRepository( - context.db - ).createWithCircuitListAndDefaultSections("project-1", "Unterverteiler"); - context.db - .update(distributionBoards) - .set({ - boardNumber: "UV-03", - feedingDistributionBoardId: upstream.id, - }) - .where(eq(distributionBoards.id, downstream.id)) - .run(); - const repository = - new DistributionBoardSubtreeProjectCommandRepository(context.db); - const snapshot = repository.capture("project-1", upstream.id); - - assert.throws( - () => - repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: - createDistributionBoardDeleteSubtreeProjectCommand(snapshot), - }), - /Speist UV-03 – erst Einspeisung ändern\./ - ); - assert.deepEqual(repository.capture("project-1", upstream.id), snapshot); - assert.equal(context.db.select().from(projectRevisions).all().length, 0); - } finally { - context.close(); - } - }); - it("rolls back a cascaded deletion when history persistence fails", () => { const context = createTestDatabase(); try { diff --git a/tests/distribution-board-subtree.test.ts b/tests/distribution-board-subtree.test.ts index 6e48294..33d5318 100644 --- a/tests/distribution-board-subtree.test.ts +++ b/tests/distribution-board-subtree.test.ts @@ -19,8 +19,6 @@ function createSnapshot(): DistributionBoardSubtreeSnapshot { floorId: "floor-1", supplyType: "AV", simultaneityFactor: 0.8, - feedingDistributionBoardId: "board-upstream", - feedingCircuitId: "circuit-upstream", }, circuitList: { id: "list-1", @@ -159,11 +157,6 @@ describe("distribution-board subtree snapshot", () => { assert.equal(clone.distributionBoard.id, "new-1"); assert.equal(clone.circuitList.id, "new-1"); assert.equal(clone.distributionBoard.name, "UV 1 Kopie"); - assert.equal( - clone.distributionBoard.feedingDistributionBoardId, - "board-upstream" - ); - assert.equal(clone.distributionBoard.feedingCircuitId, "circuit-upstream"); assert.equal(clone.circuitList.name, "UV 1 Kopie Stromkreisliste"); assert.equal(clone.sections[0].id, "new-2"); assert.equal(clone.circuits[0].id, "new-3"); diff --git a/tests/estimate-balance-frontend.test.ts b/tests/estimate-balance-frontend.test.ts deleted file mode 100644 index 7604de2..0000000 --- a/tests/estimate-balance-frontend.test.ts +++ /dev/null @@ -1,482 +0,0 @@ -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 { createEstimateProjectDeviceInitialValues } from "../src/frontend/estimate-balance/estimate-project-device-prefill.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, - 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 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(); - 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 ", - 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, - remark: saveable.groups[0]!.rows[0]!.remark, - }, - { name: "Hebeanlage", supply: "ELT", 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 deleted file mode 100644 index 1463fe4..0000000 --- a/tests/estimate-balance.test.ts +++ /dev/null @@ -1,458 +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, - 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", - 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(); - } - }); -}); diff --git a/tests/external-circuit-list-objects.test.ts b/tests/external-circuit-list-objects.test.ts new file mode 100644 index 0000000..4552d58 --- /dev/null +++ b/tests/external-circuit-list-objects.test.ts @@ -0,0 +1,105 @@ +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 new file mode 100644 index 0000000..dfba2ae --- /dev/null +++ b/tests/external-csv-api-contract.test.ts @@ -0,0 +1,83 @@ +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 new file mode 100644 index 0000000..0186581 --- /dev/null +++ b/tests/external-csv-configuration-project-command.repository.test.ts @@ -0,0 +1,244 @@ +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 new file mode 100644 index 0000000..b786ebd --- /dev/null +++ b/tests/external-csv-preview.test.ts @@ -0,0 +1,56 @@ +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 new file mode 100644 index 0000000..11a44ac --- /dev/null +++ b/tests/external-csv-transport.test.ts @@ -0,0 +1,146 @@ +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-export-batch.repository.test.ts b/tests/external-export-batch.repository.test.ts deleted file mode 100644 index 50278b6..0000000 --- a/tests/external-export-batch.repository.test.ts +++ /dev/null @@ -1,40 +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 { ExternalExportBatchRepository } from "../src/db/repositories/external-export-batch.repository.js"; -import { projects } from "../src/db/schema/projects.js"; -import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.js"; - -describe("external export batch repository", () => { - it("appends immutable audit metadata without changing the project revision", () => { - const context = createDatabaseContext(":memory:"); - try { - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - context.db.insert(projects).values({ id: "project-1", name: "Projekt", currentRevision: 7 }).run(); - const repository = new ExternalExportBatchRepository(context.db); - const configuration = createDefaultExternalModelConfiguration(); - repository.append({ - id: "export-1", projectId: "project-1", projectRevision: 7, - importBatchId: "historical-import-without-foreign-key", exportedAtIso: "2026-09-30T10:00:00.000Z", - fileName: "Projekt_Revit-Rueckgabe_2026-09-30.xlsx", sha256: "a".repeat(64), - configurationSnapshot: configuration, configurationSha256: "b".repeat(64), scope: "all", objectCount: 4, - }); - configuration.columns.designation = "Nachträglich geändert"; - repository.append({ - id: "export-2", projectId: "project-1", projectRevision: 7, - importBatchId: "historical-import-without-foreign-key", exportedAtIso: "2026-09-30T11:00:00.000Z", - fileName: "Projekt_Revit-Rueckgabe_2026-09-30.xlsx", sha256: "c".repeat(64), - configurationSnapshot: configuration, configurationSha256: "d".repeat(64), scope: "selected", objectCount: 1, - }); - - const batches = repository.listByProject("project-1"); - assert.deepEqual(batches.map((batch) => batch.id), ["export-2", "export-1"]); - assert.notEqual(batches[0]!.configurationSnapshot.columns.designation, batches[1]!.configurationSnapshot.columns.designation); - assert.equal(context.db.select({ revision: projects.currentRevision }).from(projects).get()!.revision, 7); - } finally { - context.close(); - } - }); -}); diff --git a/tests/external-follow-up-import-project-command.repository.test.ts b/tests/external-follow-up-import-project-command.repository.test.ts deleted file mode 100644 index fcb6ae7..0000000 --- a/tests/external-follow-up-import-project-command.repository.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import path from "node:path"; -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import ExcelJS from "exceljs"; -import { eq } from "drizzle-orm"; -import { migrate } from "drizzle-orm/better-sqlite3/migrator"; -import { createDatabaseContext } from "../src/db/database-context.js"; -import { ExternalFollowUpImportProjectCommandRepository } from "../src/db/repositories/external-follow-up-import-project-command.repository.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 { toCircuitDeviceRowSnapshot } from "../src/db/repositories/circuit-device-row-structure.persistence.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 { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; -import { externalModelObjects } from "../src/db/schema/external-model-objects.js"; -import { projects } from "../src/db/schema/projects.js"; -import { createExternalFollowUpImportProjectCommand } from "../src/domain/models/external-follow-up-import-project-command.model.js"; -import { createExternalObjectDeleteMissingProjectCommand } from "../src/domain/models/external-object-delete-missing-project-command.model.js"; -import { ExternalObjectDeleteMissingProjectCommandRepository } from "../src/db/repositories/external-object-delete-missing-project-command.repository.js"; -import { createEmptyExternalModelState, createExternalInitialImportProjectCommand } from "../src/domain/models/external-initial-import-project-command.model.js"; -import { createExternalXlsxFollowUpImportPlan } from "../src/external-model/application/external-xlsx-follow-up-import.js"; -import { buildExternalXlsxFollowUpTarget } from "../src/external-model/application/external-xlsx-follow-up-target.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"; -const configuration = { ...createDefaultExternalModelConfiguration(), ...externalXlsxTestConfiguration, deviceTypes: [{ id: deviceTypeA, name: "Steckdose", category: "single_phase" as const, defaults: { powerPerUnitW: null, simultaneityFactor: 1, cosPhi: 0.9, costGroup: null } }, { id: deviceTypeB, name: "Leuchte", category: "lighting" as const, defaults: { powerPerUnitW: 40, simultaneityFactor: 1, 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 }] }; -const catalogs = { floors: [], rooms: [], distributionBoards: [], projectDevices: [] }; - -describe("external follow-up import project command", () => { - it("commits object and row quantities atomically and restores exact batches on undo and redo", async () => { - const context = createDatabaseContext(":memory:"); - try { - migrate(context.db, { migrationsFolder: path.resolve("src", "db", "migrations") }); - context.db.insert(projects).values({ id: "project-1", name: "Projekt" }).run(); - 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: "Liste" }).run(); - context.db.insert(circuitSections).values({ id: "section-1", circuitListId: "list-1", key: "single-1", displayName: "1-phasig", prefix: "-2F1.", sortOrder: 10, category: "single_phase", groupNumber: 1 }).run(); - context.db.insert(circuits).values({ id: "circuit-1", circuitListId: "list-1", sectionId: "section-1", equipmentIdentifier: "-2F1.1", sortOrder: 10, voltage: 230 }).run(); - context.db.insert(circuitDeviceRows).values({ id: "row-1", circuitId: "circuit-1", sortOrder: 10, name: "Steckdose", displayName: "Steckdose", phaseType: "single_phase", category: "single_phase", quantity: 3, manualQuantity: 1, powerPerUnit: 0.125, simultaneityFactor: 1, cosPhi: 0.9 }).run(); - const configurationSnapshot = { id: "config-1", projectId: "project-1", configuration }; - context.db.insert(externalModelConfigurations).values(configurationSnapshot).run(); - const initialBytes = await createRevitXlsxFixture(); - const initialParsed = await createExternalXlsxInitialImportPlan({ fileName: "initial.xlsx", bytes: initialBytes, configuration, catalogs }); - let sequence = 0; - const initialState = buildExternalXlsxInitialImportTarget({ projectId: "project-1", expectedRevision: 0, sourceName: "Revit", importedAtIso: "2026-09-30T08:00:00.000Z", configuration, originalContentBase64: Buffer.from(initialBytes).toString("base64"), document: initialParsed.document, plan: initialParsed.plan, roomDecisions: initialParsed.plan.sourceRooms.map((room) => ({ sourceRoomKey: room.sourceRoomKey, roomId: null, defaultDistributionBoardId: null })), familyProjectDeviceDecisions: initialParsed.plan.familyGroups.map((family) => ({ familyAndType: family.familyAndType, projectDeviceId: null })), objectsWithoutRoomDefaultDistributionBoardId: null, createId: () => `30000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}` }); - new ExternalInitialImportProjectCommandRepository(context.db).execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createExternalInitialImportProjectCommand(configurationSnapshot, configurationSnapshot, createEmptyExternalModelState(), initialState) }); - const importedFirst = new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects.find((object) => object.worksharingId === firstWorksharingId)!; - context.db.update(externalModelObjects).set({ circuitDeviceRowId: "row-1" }).where(eq(externalModelObjects.id, importedFirst.id)).run(); - - const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(initialBytes); workbook.worksheets[0]!.getCell(3, 6).value = 3; - const followBytes = new Uint8Array(await workbook.xlsx.writeBuffer()); - const current = new ExternalModelStateRepository(context.db).getByProject("project-1").state; - const returnValues = new Map(current.objects.map((object) => [object.id, { circuitCombined: object.acceptedSourceValues.circuitCombined, boardName: object.acceptedSourceValues.boardName, circuitIdentifier: object.acceptedSourceValues.circuitIdentifier, designation: object.acceptedSourceValues.designation, electricalPowerW: object.acceptedSourceValues.electricalPowerW, voltageV: object.acceptedSourceValues.voltageV, currentA: object.acceptedSourceValues.currentA }])); - const followParsed = await createExternalXlsxFollowUpImportPlan({ fileName: "follow.xlsx", bytes: followBytes, configuration, catalogs, currentState: current, currentReturnValuesByObjectId: returnValues }); - const expectedRow = toCircuitDeviceRowSnapshot(context.db.select().from(circuitDeviceRows).where(eq(circuitDeviceRows.id, "row-1")).get()!); - const built = buildExternalXlsxFollowUpTarget({ projectId: "project-1", expectedRevision: 1, importedAtIso: "2026-09-30T09:00:00.000Z", configuration, originalContentBase64: Buffer.from(followBytes).toString("base64"), document: followParsed.document, plan: followParsed.plan, currentState: current, sourceChangeDecisions: followParsed.plan.changes.map((change) => ({ objectId: change.objectId, accept: true })), roomDecisions: [], familyProjectDeviceDecisions: [], objectsWithoutRoomDefaultDistributionBoardId: null, rowsById: new Map([["row-1", expectedRow]]), createId: () => `40000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}` }); - built.targetState.objects.reverse(); - const repository = new ExternalFollowUpImportProjectCommandRepository(context.db); - const commandWithoutRequiredRowTransition = createExternalFollowUpImportProjectCommand({ expectedConfiguration: configurationSnapshot, targetConfiguration: configurationSnapshot, expectedState: current, targetState: built.targetState, rows: [] }); - assert.throws( - () => repository.execute({ projectId: "project-1", expectedRevision: 1, source: "user", command: commandWithoutRequiredRowTransition }), - /Materialized quantity 3 does not match manual and external quantity 4/, - ); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 3); - const applied = repository.execute({ projectId: "project-1", expectedRevision: 1, source: "user", command: createExternalFollowUpImportProjectCommand({ expectedConfiguration: configurationSnapshot, targetConfiguration: configurationSnapshot, expectedState: current, targetState: built.targetState, rows: built.rowTransitions }) }); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 4); - let state = new ExternalModelStateRepository(context.db).getByProject("project-1").state; - assert.equal(state.importBatches.length, 2); assert.equal(state.importBatches[0]!.document, null); assert.equal(state.objects.find((object) => object.worksharingId === firstWorksharingId)!.planningValues.effectiveQuantity, 3); - - const undone = repository.execute({ projectId: "project-1", expectedRevision: 2, source: "undo", historyTargetChangeSetId: applied.revision.changeSetId, command: applied.inverse }); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 3); - state = new ExternalModelStateRepository(context.db).getByProject("project-1").state; - assert.equal(state.importBatches.length, 1); assert.ok(state.importBatches[0]!.document); - repository.execute({ projectId: "project-1", expectedRevision: 3, source: "redo", historyTargetChangeSetId: applied.revision.changeSetId, command: undone.inverse }); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 4); - - context.db.update(externalModelObjects).set({ presenceStatus: "missing" }).where(eq(externalModelObjects.id, importedFirst.id)).run(); - const missingObject = new ExternalModelStateRepository(context.db).getByProject("project-1").state.objects.find((object) => object.id === importedFirst.id)!; - const rowBeforeDelete = toCircuitDeviceRowSnapshot(context.db.select().from(circuitDeviceRows).where(eq(circuitDeviceRows.id, "row-1")).get()!); - const deleteRepository = new ExternalObjectDeleteMissingProjectCommandRepository(context.db); - const deleted = deleteRepository.execute({ projectId: "project-1", expectedRevision: 4, source: "user", command: createExternalObjectDeleteMissingProjectCommand({ objects: [{ expected: missingObject, target: null }], rows: [{ expected: rowBeforeDelete, target: { ...rowBeforeDelete, quantity: 1 } }] }) }); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 1); - assert.equal(context.db.select().from(externalModelObjects).where(eq(externalModelObjects.id, importedFirst.id)).get(), undefined); - const foreignRestore = createExternalObjectDeleteMissingProjectCommand({ objects: [{ expected: null, target: { ...missingObject, projectId: "project-2" } }], rows: deleted.inverse.payload.rows }); - assert.throws(() => deleteRepository.execute({ projectId: "project-1", expectedRevision: 5, source: "user", command: foreignRestore }), /anderes Projekt/); - deleteRepository.execute({ projectId: "project-1", expectedRevision: 5, source: "undo", historyTargetChangeSetId: deleted.revision.changeSetId, command: deleted.inverse }); - assert.equal(context.db.select().from(circuitDeviceRows).get()!.quantity, 4); - assert.equal(context.db.select().from(externalModelObjects).where(eq(externalModelObjects.id, importedFirst.id)).get()!.circuitDeviceRowId, "row-1"); - } finally { context.close(); } - }); -}); - diff --git a/tests/external-initial-import-plan.test.ts b/tests/external-initial-import-plan.test.ts new file mode 100644 index 0000000..7fc1a43 --- /dev/null +++ b/tests/external-initial-import-plan.test.ts @@ -0,0 +1,149 @@ +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 new file mode 100644 index 0000000..b9acb83 --- /dev/null +++ b/tests/external-initial-import-project-command.repository.test.ts @@ -0,0 +1,297 @@ +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 deleted file mode 100644 index 7c1066a..0000000 --- a/tests/external-model-configuration.test.ts +++ /dev/null @@ -1,132 +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 { 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 new file mode 100644 index 0000000..08319ec --- /dev/null +++ b/tests/external-model-foundation.test.ts @@ -0,0 +1,431 @@ +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 deleted file mode 100644 index a4836ac..0000000 --- a/tests/external-model-xlsx-foundation.test.ts +++ /dev/null @@ -1,87 +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 { 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 547d60f..da8551e 100644 --- a/tests/external-object-row-assignment-project-command.repository.test.ts +++ b/tests/external-object-row-assignment-project-command.repository.test.ts @@ -7,9 +7,6 @@ import { createDatabaseContext, type AppDatabase } from "../src/db/database-cont import { ExternalObjectRowAssignmentProjectCommandRepository } from "../src/db/repositories/external-object-row-assignment-project-command.repository.js"; import { ExternalObjectNewRowProjectCommandRepository } from "../src/db/repositories/external-object-new-row-project-command.repository.js"; import { ExternalObjectNewCircuitProjectCommandRepository } from "../src/db/repositories/external-object-new-circuit-project-command.repository.js"; -import { CircuitDeviceRowStructureProjectCommandRepository } from "../src/db/repositories/circuit-device-row-structure-project-command.repository.js"; -import { CircuitStructureProjectCommandRepository } from "../src/db/repositories/circuit-structure-project-command.repository.js"; -import { CircuitGroupSubtreeProjectCommandRepository } from "../src/db/repositories/circuit-group-subtree-project-command.repository.js"; import { toCircuitDeviceRowSnapshot } from "../src/db/repositories/circuit-device-row-structure.persistence.js"; import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; import { circuitLists } from "../src/db/schema/circuit-lists.js"; @@ -34,10 +31,7 @@ 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 { createCircuitDeviceRowDeleteProjectCommand } from "../src/domain/models/circuit-device-row-structure-project-command.model.js"; -import { createCircuitDeleteProjectCommand } from "../src/domain/models/circuit-structure-project-command.model.js"; -import { createCircuitGroupDeleteSubtreeProjectCommand } from "../src/domain/models/circuit-group-subtree-project-command.model.js"; -import { assertDistributionBoardHasNoExternalObjects, assertRoomHasNoExternalObjects } from "../src/db/repositories/external-object-deletion-guard.persistence.js"; +import { externalCsvTestConfiguration } from "./fixtures/revit-csv-fixtures.js"; function createFixture(initialObjectRowId: string | null = "row-1") { const context = createDatabaseContext(":memory:"); @@ -69,16 +63,20 @@ function createFixture(initialObjectRowId: string | null = "row-1") { simultaneityFactor: 1, }).run(); } - database.insert(externalModelSources).values({ id: "source-1", projectId: "project-1", name: "Revit", sourceType: "revit_xlsx" }).run(); + database.insert(externalModelSources).values({ id: "source-1", projectId: "project-1", name: "Revit", sourceType: "revit_csv" }).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.xlsx", + fileName: "revit.csv", sha256: "a".repeat(64), - objectCount: 1, + appliedProjectRevision: 0, + configurationVersion: 1, + configurationSnapshot: externalCsvTestConfiguration, + originalBytes: Buffer.from("test"), + document: { delimiter: ";", encoding: "utf-8", headers: [], rows: [] }, }).run(); database.insert(externalRoomMappings).values({ id: "mapping-1", @@ -100,9 +98,7 @@ 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: { @@ -111,18 +107,14 @@ 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", - designation: null, - electricalPowerW: "120", - voltageV: 230, - currentA: null, + power: "120", + quantity: "2", + additionalSourceValues: {}, }, planningValues: { displayName: "Steckdose", + internalDeviceType: "socket", category: "single_phase", connectionKind: "socket", effectiveQuantity: 2, @@ -541,61 +533,6 @@ describe("external object new-circuit project command", () => { } }); - it("blocks history removal when the generated circuit became a feeder", () => { - const context = createFixture(null); - try { - const object = objectSnapshot(null); - const circuit = newExternalCircuit(context.db); - const command = createExternalObjectNewCircuitProjectCommand( - externalObjectAssignToNewCircuitCommandType, - { - circuit, - objects: [{ - expected: object, - target: { ...object, circuitDeviceRowId: "row-new" }, - }], - confirmedConflictObjectIds: [], - } - ); - const repository = new ExternalObjectNewCircuitProjectCommandRepository(context.db); - const inserted = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command, - }); - context.db.insert(distributionBoards).values({ - id: "board-2", - projectId: "project-1", - name: "Unterverteiler", - boardNumber: "UV-02", - feedingDistributionBoardId: "board-1", - feedingCircuitId: circuit.id, - }).run(); - - assert.throws( - () => repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: inserted.revision.changeSetId, - command: inserted.inverse, - }), - /Speist UV-02 – erst Einspeisung ändern\./ - ); - assert.ok( - context.db.select().from(circuits) - .where(eq(circuits.id, circuit.id)).get() - ); - assert.equal( - context.db.select().from(externalModelObjects).get()!.circuitDeviceRowId, - "row-new" - ); - } finally { - context.close(); - } - }); - it("rolls back the complete circuit subtree when history persistence fails", () => { const context = createFixture(null); try { @@ -633,63 +570,4 @@ describe("external object new-circuit project command", () => { context.close(); } }); - - it("detaches linked objects on row deletion and restores the exact link on undo", () => { - const context = createFixture(); - try { - const repository = new CircuitDeviceRowStructureProjectCommandRepository(context.db); - const deleted = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: createCircuitDeviceRowDeleteProjectCommand("row-1", "circuit-1"), - }); - assert.equal(context.db.select().from(externalModelObjects).get()!.circuitDeviceRowId, null); - assert.equal(context.db.select().from(circuitDeviceRows).where(eq(circuitDeviceRows.id, "row-1")).get(), undefined); - - repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: deleted.revision.changeSetId, - command: deleted.inverse, - }); - assert.equal(context.db.select().from(externalModelObjects).get()!.circuitDeviceRowId, "row-1"); - assert.ok(context.db.select().from(circuitDeviceRows).where(eq(circuitDeviceRows.id, "row-1")).get()); - } finally { - context.close(); - } - }); - - it("preserves external links through circuit and populated-group deletion undo", () => { - for (const kind of ["circuit", "group"] as const) { - const context = createFixture(); - try { - const repository = kind === "circuit" - ? new CircuitStructureProjectCommandRepository(context.db) - : new CircuitGroupSubtreeProjectCommandRepository(context.db); - const command = kind === "circuit" - ? createCircuitDeleteProjectCommand("circuit-1", "list-1") - : createCircuitGroupDeleteSubtreeProjectCommand( - (repository as CircuitGroupSubtreeProjectCommandRepository).capture("project-1", "section-1") - ); - const deleted = repository.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command } as never); - assert.equal(context.db.select().from(externalModelObjects).get()!.circuitDeviceRowId, null); - repository.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: deleted.revision.changeSetId, command: deleted.inverse } as never); - assert.equal(context.db.select().from(externalModelObjects).get()!.circuitDeviceRowId, "row-1"); - } finally { - context.close(); - } - } - }); - - it("blocks room and distribution-board deletion while external objects reference them", () => { - const context = createFixture(null); - try { - assert.throws(() => assertDistributionBoardHasNoExternalObjects(context.db, "project-1", "board-1"), /Revit-Objekte/); - assert.throws(() => assertRoomHasNoExternalObjects(context.db, "project-1", "room-1"), /Revit-Objekte/); - } finally { - context.close(); - } - }); }); diff --git a/tests/external-xlsx-follow-up-import.test.ts b/tests/external-xlsx-follow-up-import.test.ts deleted file mode 100644 index 70cb7d9..0000000 --- a/tests/external-xlsx-follow-up-import.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import ExcelJS from "exceljs"; -import { createExternalXlsxFollowUpImportPlan } from "../src/external-model/application/external-xlsx-follow-up-import.js"; -import { buildExternalXlsxFollowUpTarget } from "../src/external-model/application/external-xlsx-follow-up-target.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 type { ExternalXlsxReturnValues } from "../src/external-model/xlsx/external-xlsx-contracts.js"; -import { createRevitXlsxFixture, externalXlsxTestConfiguration, firstWorksharingId, secondWorksharingId } from "./fixtures/revit-xlsx-fixtures.js"; - -const deviceTypeA = "10000000-0000-4000-8000-000000000001"; -const deviceTypeB = "10000000-0000-4000-8000-000000000002"; -const newWorksharingId = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-00000003"; -const catalogs = { floors: [], rooms: [], distributionBoards: [], projectDevices: [] }; -const configuration = { ...createDefaultExternalModelConfiguration(), ...externalXlsxTestConfiguration, deviceTypes: [{ id: deviceTypeA, name: "Steckdose", category: "single_phase" as const, defaults: { powerPerUnitW: null, simultaneityFactor: 1, cosPhi: 0.9, costGroup: null } }, { id: deviceTypeB, name: "Leuchte", category: "lighting" as const, defaults: { powerPerUnitW: 40, simultaneityFactor: 1, 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 }] }; - -async function initialState() { - const bytes = await createRevitXlsxFixture(); - const { plan, document } = await createExternalXlsxInitialImportPlan({ fileName: "initial.xlsx", bytes, configuration, catalogs }); - let sequence = 0; - const state = buildExternalXlsxInitialImportTarget({ projectId: "project-1", expectedRevision: 0, sourceName: "Revit", importedAtIso: "2026-09-30T08: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 missing = structuredClone(state.objects[1]!); missing.id = "30000000-0000-4000-8000-999999999999"; missing.worksharingId = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-00000099"; - state.objects.push(missing); - return state; -} - -async function changedWorkbook(firstId = firstWorksharingId) { - const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(await createRevitXlsxFixture()); - const sheet = workbook.worksheets[0]!; - sheet.getCell(3, 1).value = firstId; sheet.getCell(3, 6).value = 3; - sheet.getCell(5, 1).value = newWorksharingId; sheet.getCell(5, 2).value = "Leuchte neu"; sheet.getCell(5, 5).value = "Leuchte: Decke"; sheet.getCell(5, 6).value = 1; - return new Uint8Array(await workbook.xlsx.writeBuffer()); -} - -function currentReturns(state: Awaited>) { - const map = new Map(); - for (const object of state.objects) map.set(object.id, { circuitCombined: object.acceptedSourceValues.circuitCombined, boardName: object.acceptedSourceValues.boardName, circuitIdentifier: object.acceptedSourceValues.circuitIdentifier, designation: object.acceptedSourceValues.designation, electricalPowerW: object.acceptedSourceValues.electricalPowerW, voltageV: object.acceptedSourceValues.voltageV, currentA: object.acceptedSourceValues.currentA }); - map.set(state.objects[0]!.id, { ...map.get(state.objects[0]!.id)!, designation: "Noch nicht in Revit" }); - return map; -} - -describe("Linear XLSX follow-up import", () => { - it("classifies new, changed, unchanged, missing and return-deviating objects with exact IDs", async () => { - const state = await initialState(); - const bytes = await changedWorkbook(); - const { plan } = await createExternalXlsxFollowUpImportPlan({ fileName: "follow-up.xlsx", bytes, configuration, catalogs, currentState: state, currentReturnValuesByObjectId: currentReturns(state) }); - assert.deepEqual({ new: plan.newObjectCount, changed: plan.changedObjectCount, unchanged: plan.unchangedObjectCount, missing: plan.missingObjectCount, returnDeviation: plan.returnDeviationCount }, { new: 1, changed: 1, unchanged: 1, missing: 1, returnDeviation: 1 }); - assert.deepEqual(plan.changes[0]!.changedFields, ["socketCount"]); - assert.equal(plan.missingObjects[0]!.worksharingId.endsWith("99"), true); - - const caseChanged = await createExternalXlsxFollowUpImportPlan({ fileName: "follow-up.xlsx", bytes: await changedWorkbook(firstWorksharingId.toLowerCase()), configuration, catalogs, currentState: state, currentReturnValuesByObjectId: currentReturns(state) }); - assert.equal(caseChanged.plan.newObjectCount, 2); - assert.equal(caseChanged.plan.missingObjectCount, 2); - }); - - it("updates accepted quantities and row totals while preserving missing links and compacting old batches", async () => { - const state = await initialState(); - const first = state.objects.find((object) => object.worksharingId === firstWorksharingId)!; - first.circuitDeviceRowId = "row-1"; - const bytes = await changedWorkbook(); - const { plan, document } = await createExternalXlsxFollowUpImportPlan({ fileName: "follow-up.xlsx", bytes, configuration, catalogs, currentState: state, currentReturnValuesByObjectId: currentReturns(state) }); - let sequence = 0; - const row = { id: "row-1", circuitId: "circuit-1", linkedProjectDeviceId: null, sortOrder: 10, name: "Steckdose", displayName: "Steckdose", phaseType: "single_phase", connectionKind: null, costGroup: null, category: "single_phase", level: null, roomId: null, roomNumberSnapshot: null, roomNameSnapshot: null, quantity: 3, manualQuantity: 1, powerPerUnit: 0.125, simultaneityFactor: 1, cosPhi: 0.9, remark: null, overriddenFields: null }; - const built = buildExternalXlsxFollowUpTarget({ projectId: "project-1", expectedRevision: 1, importedAtIso: "2026-09-30T09:00:00.000Z", configuration, originalContentBase64: Buffer.from(bytes).toString("base64"), document, plan, currentState: state, sourceChangeDecisions: plan.changes.map((change) => ({ objectId: change.objectId, accept: true })), roomDecisions: plan.newSourceRoomKeys.map((sourceRoomKey) => ({ sourceRoomKey, roomId: null, defaultDistributionBoardId: null })), familyProjectDeviceDecisions: plan.newFamilyAndTypes.map((familyAndType) => ({ familyAndType, projectDeviceId: null })), objectsWithoutRoomDefaultDistributionBoardId: null, rowsById: new Map([[row.id, row]]), createId: () => `40000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}` }); - assert.equal(built.rowTransitions[0]!.target.quantity, 4); - assert.equal(built.targetState.objects.find((object) => object.id === first.id)!.planningValues.effectiveQuantity, 3); - const missing = built.targetState.objects.find((object) => object.worksharingId.endsWith("99"))!; - assert.equal(missing.presenceStatus, "missing"); - assert.equal(missing.circuitDeviceRowId, null); - assert.equal(built.targetState.importBatches[0]!.originalContentBase64, null); - assert.ok(built.targetState.importBatches[1]!.originalContentBase64); - - const rejected = buildExternalXlsxFollowUpTarget({ projectId: "project-1", expectedRevision: 1, importedAtIso: "2026-09-30T09:00:00.000Z", configuration, originalContentBase64: Buffer.from(bytes).toString("base64"), document, plan, currentState: state, sourceChangeDecisions: plan.changes.map((change) => ({ objectId: change.objectId, accept: false })), roomDecisions: plan.newSourceRoomKeys.map((sourceRoomKey) => ({ sourceRoomKey, roomId: null, defaultDistributionBoardId: null })), familyProjectDeviceDecisions: plan.newFamilyAndTypes.map((familyAndType) => ({ familyAndType, projectDeviceId: null })), objectsWithoutRoomDefaultDistributionBoardId: null, rowsById: new Map([[row.id, row]]), createId: () => `50000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}` }); - const rejectedObject = rejected.targetState.objects.find((object) => object.id === first.id)!; - assert.equal(rejectedObject.planningValues.effectiveQuantity, first.planningValues.effectiveQuantity); - assert.equal(rejectedObject.lastAcceptedImportBatchId, first.lastAcceptedImportBatchId); - assert.notEqual(rejectedObject.lastSeenImportBatchId, first.lastSeenImportBatchId); - assert.equal(rejected.rowTransitions.length, 0); - }); -}); - diff --git a/tests/external-xlsx-initial-import.test.ts b/tests/external-xlsx-initial-import.test.ts deleted file mode 100644 index df17e23..0000000 --- a/tests/external-xlsx-initial-import.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 { 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"; -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")}` }); - target.objects.reverse(); - 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 }); - 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/external-xlsx-return-projection.test.ts b/tests/external-xlsx-return-projection.test.ts deleted file mode 100644 index 10c1980..0000000 --- a/tests/external-xlsx-return-projection.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { projectExternalXlsxReturn } from "../src/external-model/application/external-xlsx-return-projection.js"; -import type { ExternalModelObjectSnapshot } from "../src/external-model/domain/external-model-contracts.js"; - -function object(): ExternalModelObjectSnapshot { - return { - id: "object-1", projectId: "project-1", sourceId: "source-1", - worksharingId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee-ffffffff", ifcGuid: null, - deviceTypeId: "type-1", lastSeenImportBatchId: "batch-1", lastAcceptedImportBatchId: "batch-1", - acceptedSourceValues: { rowNumber: 2, roomNumber: "101", roomName: "Büro", familyAndType: "Steckdose", selectionMarker: "SD", socketCount: 2, sourceRemark: null, circuitCombined: "UV 1-2F1.1", boardName: "UV 1", circuitIdentifier: "-2F1.1", designation: "Steckdose", electricalPowerW: "240", voltageV: 230, currentA: "1,16" }, - planningValues: { displayName: "Steckdose", category: "single_phase", connectionKind: "socket", effectiveQuantity: 2, powerPerUnitW: 120, simultaneityFactor: 1, cosPhi: 0.9, costGroup: null, remark: null }, - overriddenFields: [], externalRoomMappingId: null, distributionBoardId: "board-1", linkedProjectDeviceId: null, circuitDeviceRowId: "row-1", presenceStatus: "present", - }; -} - -describe("external XLSX return projection", () => { - it("projects typed row values and compares normalized imported scalars", () => { - const result = projectExternalXlsxReturn({ object: object(), circuitMode: "combined", singlePhaseVoltageV: 230, threePhaseVoltageV: 400, row: { rowId: "row-1", displayName: "Steckdose", powerPerUnitKw: 0.12, cosPhi: 0.9, phaseType: "single_phase", category: "single_phase", circuitIdentifier: "-2F1.1", circuitVoltageV: 230, distributionBoardName: "UV 1" } }); - assert.deepEqual(result.values, { circuitCombined: "UV 1-2F1.1", designation: "Steckdose", electricalPowerW: 240, voltageV: 230, currentA: 1.16 }); - assert.equal(result.differsFromImported, false); - assert.deepEqual(result.warnings, []); - }); - - it("uses object planning without a row and leaves an uncomputable current empty", () => { - const input = object(); input.circuitDeviceRowId = null; input.planningValues.cosPhi = null; - const result = projectExternalXlsxReturn({ object: input, row: null, circuitMode: "separate", singlePhaseVoltageV: 230, threePhaseVoltageV: 400 }); - assert.equal(result.values.boardName, ""); - assert.equal(result.values.circuitIdentifier, ""); - assert.equal(result.values.electricalPowerW, 240); - assert.equal(result.values.currentA, null); - assert.equal(result.differsFromImported, true); - assert.match(result.warnings.join(" "), /Stromstärke/); - }); - - it("uses three-phase current and object-specific effective quantity", () => { - const input = object(); input.planningValues.category = "three_phase"; input.planningValues.effectiveQuantity = 3; - const result = projectExternalXlsxReturn({ object: input, row: null, circuitMode: "combined", singlePhaseVoltageV: 230, threePhaseVoltageV: 400 }); - assert.equal(result.values.electricalPowerW, 360); - assert.equal(result.values.voltageV, 400); - assert.equal(result.values.currentA, 0.58); - }); -}); diff --git a/tests/external-xlsx-transport.test.ts b/tests/external-xlsx-transport.test.ts deleted file mode 100644 index 32cd784..0000000 --- a/tests/external-xlsx-transport.test.ts +++ /dev/null @@ -1,267 +0,0 @@ -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 deleted file mode 100644 index a4afd7f..0000000 --- a/tests/fixtures/revit-xlsx-fixtures.ts +++ /dev/null @@ -1,160 +0,0 @@ -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()); -} - -export async function createLargeRevitXlsxFixture(objectCount: number) { - const workbook = new ExcelJS.Workbook(); - const worksheet = workbook.addWorksheet("Linear Export"); - worksheet.addRow([ - "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", - ]); - worksheet.addRow([]); - for (let index = 0; index < objectCount; index += 1) { - const suffix = String(index + 1).padStart(8, "0"); - worksheet.addRow([ - `AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE-${suffix}`, - `Steckdose ${index + 1}`, - String(100 + (index % 250)), - `Raum ${index % 250}`, - "Steckdose: Standard", - (index % 4) + 1, - null, null, null, null, null, null, null, null, - `IFC-${suffix}`, - ]); - } - 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; - }); -} diff --git a/tests/linear-xlsx-external-model-migration.test.ts b/tests/linear-xlsx-external-model-migration.test.ts deleted file mode 100644 index 6bfc8bf..0000000 --- a/tests/linear-xlsx-external-model-migration.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -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/overview-filters.test.ts b/tests/overview-filters.test.ts deleted file mode 100644 index 84c5807..0000000 --- a/tests/overview-filters.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { - buildCostGroupFilterOptions, - buildFloorFilterOptions, - buildSupplyTypeFilterOptions, - emptyDistributionBoardFilters, - emptyProjectDeviceFilters, - filterDistributionBoards, - filterProjectDevices, - isDistributionBoardFilterActive, - isProjectDeviceFilterActive, - retainAvailableFilterValues, - toggleFilterValue, - withoutCostGroupFilterId, - withoutFloorFilterId, - withoutSupplyTypeFilterId, -} from "../src/frontend/utils/overview-filters.js"; -import type { - DistributionBoardDto, - FloorDto, - ProjectDeviceDto, -} from "../src/frontend/types.js"; - -type TestBoard = Pick< - DistributionBoardDto, - "id" | "name" | "floorId" | "supplyType" ->; - -function board( - id: string, - name: string, - floorId: string | null, - supplyType: DistributionBoardDto["supplyType"] -): TestBoard { - return { id, name, floorId, supplyType }; -} - -function device( - id: string, - overrides: Partial -): ProjectDeviceDto { - return { - id, - projectId: "project-1", - name: `device-${id}`, - displayName: `Gerät ${id}`, - phaseType: "single_phase", - connectionKind: null, - costGroup: null, - category: "single_phase", - quantity: 1, - powerPerUnit: 1, - simultaneityFactor: 1, - totalPower: 1, - cosPhi: null, - remark: null, - voltageV: null, - ...overrides, - }; -} - -const floors: FloorDto[] = [ - { id: "floor-og", projectId: "project-1", name: "1. OG", sortOrder: 2 }, - { id: "floor-eg", projectId: "project-1", name: "EG", sortOrder: 1 }, -]; -const floorNameById = new Map(floors.map((floor) => [floor.id, floor.name])); - -const boards = [ - board("b1", "UV-EG-01", "floor-eg", "AV"), - board("b2", "UV-OG-01", "floor-og", "SV"), - board("b3", "HV", null, "AV"), - board("b4", "SiBe-Zentrale", null, null), -]; - -describe("overview filters: distribution boards", () => { - it("returns every board without an active filter", () => { - assert.equal(isDistributionBoardFilterActive(emptyDistributionBoardFilters), false); - assert.deepEqual( - filterDistributionBoards(boards, emptyDistributionBoardFilters, floorNameById), - boards - ); - }); - - it("also searches board number and location when the boards carry them", () => { - const withInfo = [ - { ...boards[0]!, boardNumber: "UV 0.1", location: "Raum 003 Technik" }, - { ...boards[1]!, boardNumber: null, location: null }, - ]; - assert.deepEqual( - filterDistributionBoards( - withInfo, - { ...emptyDistributionBoardFilters, query: "uv 0.1" }, - floorNameById - ).map((entry) => entry.id), - [withInfo[0]!.id] - ); - assert.deepEqual( - filterDistributionBoards( - withInfo, - { ...emptyDistributionBoardFilters, query: "technik" }, - floorNameById - ).map((entry) => entry.id), - [withInfo[0]!.id] - ); - }); - - it("searches board and floor names case-insensitively and ignores blank queries", () => { - const byFloorName = filterDistributionBoards( - boards, - { ...emptyDistributionBoardFilters, query: " og " }, - floorNameById - ); - assert.deepEqual(byFloorName.map((entry) => entry.id), ["b2"]); - const byBoardName = filterDistributionBoards( - boards, - { ...emptyDistributionBoardFilters, query: "sibe" }, - floorNameById - ); - assert.deepEqual(byBoardName.map((entry) => entry.id), ["b4"]); - assert.equal( - isDistributionBoardFilterActive({ ...emptyDistributionBoardFilters, query: " " }), - false - ); - }); - - it("filters floors with the dedicated option for boards without floor", () => { - const result = filterDistributionBoards( - boards, - { ...emptyDistributionBoardFilters, floorIds: ["floor-eg", withoutFloorFilterId] }, - floorNameById - ); - assert.deepEqual(result.map((entry) => entry.id), ["b1", "b3", "b4"]); - }); - - it("combines supply type with the other criteria", () => { - const filters = { - query: "", - floorIds: [withoutFloorFilterId], - supplyTypes: ["AV"], - }; - assert.equal(isDistributionBoardFilterActive(filters), true); - assert.deepEqual( - filterDistributionBoards(boards, filters, floorNameById).map((entry) => entry.id), - ["b3"] - ); - assert.deepEqual( - filterDistributionBoards( - boards, - { ...emptyDistributionBoardFilters, supplyTypes: [withoutSupplyTypeFilterId] }, - floorNameById - ).map((entry) => entry.id), - ["b4"] - ); - }); - - it("offers floors in configured order followed by 'Ohne Etage'", () => { - assert.deepEqual(buildFloorFilterOptions(floors), [ - { id: "floor-eg", label: "EG" }, - { id: "floor-og", label: "1. OG" }, - { id: withoutFloorFilterId, label: "Ohne Etage" }, - ]); - }); - - it("offers enabled and used supply types in catalog order", () => { - const options = buildSupplyTypeFilterOptions( - ["AV", "SV", "EV", "USV"], - ["USV", "AV"], - boards, - { AV: "AV – Allgemein", SV: "SV – Sicherheit" } - ); - assert.deepEqual(options, [ - { id: "AV", label: "AV – Allgemein" }, - { id: "SV", label: "SV – Sicherheit" }, - { id: "USV", label: "USV" }, - { id: withoutSupplyTypeFilterId, label: "Nicht festgelegt" }, - ]); - }); -}); - -describe("overview filters: project devices", () => { - const devices = [ - device("d1", { - displayName: "Steckdose Büro", - costGroup: "444", - connectionKind: "Steckdose", - }), - device("d2", { - displayName: "Durchlauferhitzer", - phaseType: "three_phase", - category: "three_phase", - costGroup: " 445 ", - }), - device("d3", { - displayName: "Downlight", - category: "lighting", - costGroup: " ", - }), - device("d4", { displayName: "Kaffeemaschine", costGroup: null }), - ]; - - it("searches names, connection kind, cost group and the German category label", () => { - assert.deepEqual( - filterProjectDevices(devices, { ...emptyProjectDeviceFilters, query: "STECK" }).map( - (entry) => entry.id - ), - ["d1"] - ); - assert.deepEqual( - filterProjectDevices( - devices, - { ...emptyProjectDeviceFilters, query: "beleucht" }, - { lighting: "Beleuchtung" } - ).map((entry) => entry.id), - ["d3"] - ); - }); - - it("filters category, phase type and cost group together", () => { - const filters = { - query: "", - categories: ["single_phase", "three_phase"], - phaseTypes: ["three_phase"], - costGroups: ["445"], - }; - assert.equal(isProjectDeviceFilterActive(filters), true); - assert.deepEqual( - filterProjectDevices(devices, filters).map((entry) => entry.id), - ["d2"] - ); - }); - - it("treats blank cost groups as 'Ohne Kostengruppe'", () => { - assert.deepEqual( - filterProjectDevices(devices, { - ...emptyProjectDeviceFilters, - costGroups: [withoutCostGroupFilterId], - }).map((entry) => entry.id), - ["d3", "d4"] - ); - assert.deepEqual(buildCostGroupFilterOptions(devices), [ - { id: "444", label: "444" }, - { id: "445", label: "445" }, - { id: withoutCostGroupFilterId, label: "Ohne Kostengruppe" }, - ]); - }); - - it("returns an empty list when the filters hide every device", () => { - assert.deepEqual( - filterProjectDevices(devices, { ...emptyProjectDeviceFilters, query: "gibt es nicht" }), - [] - ); - assert.equal(isProjectDeviceFilterActive(emptyProjectDeviceFilters), false); - }); -}); - -describe("overview filters: selection helpers", () => { - it("toggles values without mutating the selection", () => { - const selected = ["a"]; - assert.deepEqual(toggleFilterValue(selected, "b"), ["a", "b"]); - assert.deepEqual(toggleFilterValue(selected, "a"), []); - assert.deepEqual(selected, ["a"]); - }); - - it("drops selected values that are no longer offered", () => { - assert.deepEqual( - retainAvailableFilterValues(["floor-eg", "deleted-floor"], buildFloorFilterOptions(floors)), - ["floor-eg"] - ); - }); -}); diff --git a/tests/print-document-model.test.ts b/tests/print-document-model.test.ts index ba91c3e..a5165e8 100644 --- a/tests/print-document-model.test.ts +++ b/tests/print-document-model.test.ts @@ -1,10 +1,7 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { - assertPrintRevisionConsistency, - buildBoardHierarchy, - formatFeedingReference, - formatCircuitCable, + buildPreliminaryBoardHierarchy, formatProtectionDevice, summarizePrintBoard, } from "../src/frontend/print/print-document-model.js"; @@ -28,8 +25,6 @@ function board( location: null, fedFrom: null, remark: null, - feedingDistributionBoardId: null, - feedingCircuitId: null, ...info, }; } @@ -55,8 +50,6 @@ 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, @@ -84,13 +77,7 @@ function tree( sortOrder: 1, isReserve: false, circuitTotalPower: total, - circuitApparentPower: deviceRows.reduce( - (sum, row) => sum + row.rowTotalPower / (row.cosPhi || 1), - 0 - ), - circuitCosPhi: 1, deviceRows, - downstreamBoardLoads: [], }, ], }, @@ -112,34 +99,6 @@ function summary( } describe("print document model", () => { - it("rejects mixed project revisions instead of printing mislabeled data", () => { - const summaries = [summary("uv", {}, 1)]; - assert.doesNotThrow(() => assertPrintRevisionConsistency(1, summaries, 1)); - assert.throws(() => assertPrintRevisionConsistency(0, summaries, 0), /neu laden/); - assert.throws(() => assertPrintRevisionConsistency(1, summaries, 2), /neu laden/); - assert.throws(() => assertPrintRevisionConsistency(1, [], 2), /neu laden/); - }); - - it("prints both cable type and cross-section without hiding either value", () => { - const circuit = tree([]).sections[0].circuits[0]; - assert.equal(formatCircuitCable({ ...circuit, cableType: "NYM-J", cableCrossSection: "3x2,5" }), "NYM-J · 3x2,5"); - assert.equal(formatCircuitCable({ ...circuit, cableType: "NYM-J" }), "NYM-J"); - assert.equal(formatCircuitCable({ ...circuit, cableCrossSection: "3x2,5" }), "3x2,5"); - assert.equal(formatCircuitCable(circuit), null); - }); - - 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 = buildBoardHierarchy(ordered); - assert.ok(entries.every((entry) => entry.parentBoardId === null)); - } - }); - it("derives installed, device and demand power and the design current", () => { const result = summarizePrintBoard({ board: board("uv"), @@ -155,39 +114,17 @@ describe("print document model", () => { }); assert.equal(result.circuitCount, 1); assert.equal(result.installedPowerKw, 14); - assert.equal(result.powerBeforeBoardSimultaneityKw, 10); + assert.equal(result.devicePowerKw, 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("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([ + it("nests boards by matching free-text feed and sums downstream demand", () => { + const entries = buildPreliminaryBoardHierarchy([ summary("hv", { boardNumber: "HV 0.1", fedFrom: "HAK" }, 10), - summary("uv-a", { boardNumber: "UV 1.1", feedingDistributionBoardId: "hv" }, 4), - summary("uv-b", { boardNumber: "UV 1.2", feedingDistributionBoardId: "uv-a" }, 2), + 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-c", { name: "UV-C", fedFrom: "unbekannt" }, 1), ]); assert.deepEqual( @@ -195,37 +132,28 @@ describe("print document model", () => { entry.summary.board.id, entry.depth, entry.parentBoardId, + entry.cumulatedDemandPowerKw, ]), [ - ["hv", 0, null], - ["uv-a", 1, "hv"], - ["uv-b", 2, "uv-a"], - ["uv-c", 0, null], + ["hv", 0, null, 16], + ["uv-a", 1, "hv", 6], + ["uv-b", 2, "uv-a", 2], + ["uv-c", 0, null, 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), + 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), ]); assert.equal(entries.length, 2); assert.ok(entries.some((entry) => entry.parentBoardId === null)); - }); - - 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"); + assert.equal( + entries.reduce((sum, entry) => sum + (entry.depth === 0 ? entry.cumulatedDemandPowerKw : 0), 0), + 2 + ); }); it("formats protection devices for the plan table", () => { diff --git a/tests/print-view-migration.test.ts b/tests/print-view-migration.test.ts deleted file mode 100644 index 343de70..0000000 --- a/tests/print-view-migration.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import assert from "node:assert/strict"; -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import { it } from "node:test"; -import { migrate } from "drizzle-orm/better-sqlite3/migrator"; -import { createDatabaseContext } from "../src/db/database-context.js"; - -it("upgrades a populated pre-print database through the current schema without changing existing records", async () => { - const source = path.resolve("src/db/migrations"); - const staging = mkdtempSync(path.join(tmpdir(), "leistungsbilanz-print-migration-")); - const journal = JSON.parse(readFileSync(path.join(source, "meta/_journal.json"), "utf8")); - journal.entries = journal.entries.filter((entry: { idx: number }) => entry.idx <= 6); - mkdirSync(path.join(staging, "meta")); - const files = [path.join(staging, "meta/_journal.json")]; - writeFileSync(files[0], JSON.stringify(journal)); - for (const entry of journal.entries) { - const file = path.join(staging, `${entry.tag}.sql`); - copyFileSync(path.join(source, `${entry.tag}.sql`), file); - files.push(file); - } - const context = createDatabaseContext(":memory:"); - try { - migrate(context.db, { migrationsFolder: staging }); - context.sqlite.exec(` - INSERT INTO projects (id, name, current_revision) VALUES ('p', 'Existing project', 17); - INSERT INTO distribution_boards (id, project_id, name, simultaneity_factor) - VALUES ('b', 'p', 'Existing board', 0.7); - INSERT INTO floors (id, project_id, name, sort_order) - VALUES ('f', 'p', 'Existing floor', 3); - INSERT INTO rooms (id, project_id, floor_id, room_number, room_name) - VALUES ('r', 'p', 'f', '101', 'Existing room'); - `); - const oldProject = context.sqlite.prepare("SELECT * FROM projects").get() as Record; - const oldBoard = context.sqlite.prepare("SELECT * FROM distribution_boards").get() as Record; - const oldFloor = context.sqlite.prepare("SELECT * FROM floors").get() as Record; - const oldRoom = context.sqlite.prepare("SELECT * FROM rooms").get() as Record; - const backup = path.join(staging, "before-print.db"); - files.push(backup); - await context.sqlite.backup(backup); - - migrate(context.db, { migrationsFolder: source }); - const project = context.sqlite.prepare("SELECT * FROM projects").get() as Record; - const board = context.sqlite.prepare("SELECT * FROM distribution_boards").get() as Record; - const floor = context.sqlite.prepare("SELECT * FROM floors").get() as Record; - const room = context.sqlite.prepare("SELECT * FROM rooms").get() as Record; - for (const [key, value] of Object.entries(oldProject)) assert.deepEqual(project[key], value); - for (const [key, value] of Object.entries(oldBoard)) assert.deepEqual(board[key], value); - for (const [key, value] of Object.entries(oldFloor)) assert.deepEqual(floor[key], value); - for (const [key, value] of Object.entries(oldRoom)) assert.deepEqual(room[key], value); - for (const field of ["site_address", "work_stage", "project_lead", "project_editor"]) assert.equal(project[field], null); - for (const field of ["board_number", "location", "fed_from", "remark"]) assert.equal(board[field], null); - assert.equal(board.feeding_distribution_board_id, null); - assert.equal(board.feeding_circuit_id, null); - assert.equal(floor.building_id, null); - assert.equal(room.area_m2, null); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM buildings").get()!.count, 0); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM document_branding_assets").get()!.count, 0); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM document_branding_settings").get()!.count, 0); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM estimate_balances").get()!.count, 0); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM estimate_groups").get()!.count, 0); - assert.equal(context.sqlite.prepare("SELECT count(*) AS count FROM estimate_rows").get()!.count, 0); - assert.deepEqual(context.sqlite.pragma("foreign_key_check"), []); - assert.equal(context.sqlite.pragma("integrity_check", { simple: true }), "ok"); - migrate(context.db, { migrationsFolder: source }); - assert.deepEqual(context.sqlite.prepare("SELECT * FROM projects").get(), project); - } finally { - context.close(); - for (const file of files) unlinkSync(file); - rmdirSync(path.join(staging, "meta")); - rmdirSync(staging); - } -}); diff --git a/tests/project-building-structure.test.ts b/tests/project-building-structure.test.ts deleted file mode 100644 index 2c9ccdf..0000000 --- a/tests/project-building-structure.test.ts +++ /dev/null @@ -1,305 +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 { ProjectHistoryRepository } from "../src/db/repositories/project-history.repository.js"; -import { ProjectLocationStructureProjectCommandRepository } from "../src/db/repositories/project-location-structure-project-command.repository.js"; -import { buildings } from "../src/db/schema/buildings.js"; -import { floors } from "../src/db/schema/floors.js"; -import { projects } from "../src/db/schema/projects.js"; -import { - assertProjectFloorInsertProjectCommand, - createProjectBuildingDeleteProjectCommand, - createProjectBuildingInsertProjectCommand, - createProjectBuildingSnapshot, - createProjectBuildingUpdateProjectCommand, - createProjectFloorInsertProjectCommand, - createProjectFloorSnapshot, - createProjectFloorUpdateProjectCommand, - projectFloorCommandSchemaVersion, - type ProjectLocationStructureProjectCommand, -} from "../src/domain/models/project-location-structure-project-command.model.js"; -import { - createBuildingSchema, - createFloorSchema, - updateFloorSchema, -} from "../src/shared/validation/project-structure.schemas.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" }, - { id: "project-2", name: "Foreign project" }, - ]) - .run(); - return context; -} - -/** Executes a user command and returns a runner for its undo and redo. */ -function createRunner(context: DatabaseContext) { - const repository = new ProjectLocationStructureProjectCommandRepository( - context.db - ); - const history = new ProjectHistoryRepository(context.db); - let revision = 0; - const run = ( - command: ProjectLocationStructureProjectCommand, - source: "user" | "undo" | "redo" = "user" - ) => { - const step = - source === "user" ? null : history.getNextCommand("project-1", source); - if (source !== "user") { - assert.ok(step); - } - const result = repository.execute({ - projectId: "project-1", - expectedRevision: revision, - source, - historyTargetChangeSetId: step?.changeSetId, - command, - }); - revision += 1; - return result; - }; - return { repository, run }; -} - -function getBuilding(context: DatabaseContext, id: string) { - return context.db.select().from(buildings).where(eq(buildings.id, id)).get(); -} - -function getFloor(context: DatabaseContext, id: string) { - return context.db.select().from(floors).where(eq(floors.id, id)).get(); -} - -describe("project building structure", () => { - it("creates, renames and deletes buildings with persisted undo and redo", () => { - const context = createTestDatabase(); - try { - const { run } = createRunner(context); - const building = createProjectBuildingSnapshot("project-1", " Haus A ", 0); - assert.equal(building.name, "Haus A"); - - const insert = createProjectBuildingInsertProjectCommand(building); - const inserted = run(insert); - assert.deepEqual(getBuilding(context, building.id), building); - - const renamed = { ...building, name: "Haus B" }; - const update = createProjectBuildingUpdateProjectCommand(building, renamed); - const updated = run(update); - assert.equal(getBuilding(context, building.id)?.name, "Haus B"); - - run(updated.inverse, "undo"); - assert.deepEqual(getBuilding(context, building.id), building); - run(inserted.inverse, "undo"); - assert.equal(getBuilding(context, building.id), undefined); - run(insert, "redo"); - run(update, "redo"); - assert.deepEqual(getBuilding(context, building.id), renamed); - - const deleted = run(createProjectBuildingDeleteProjectCommand(renamed)); - assert.equal(getBuilding(context, building.id), undefined); - run(deleted.inverse, "undo"); - assert.deepEqual(getBuilding(context, building.id), renamed); - } finally { - context.close(); - } - }); - - it("assigns floors to buildings and blocks deleting a building in use", () => { - const context = createTestDatabase(); - try { - const { run } = createRunner(context); - const houseA = createProjectBuildingSnapshot("project-1", "Haus A", 0); - const houseB = createProjectBuildingSnapshot("project-1", "Haus B", 1); - run(createProjectBuildingInsertProjectCommand(houseA)); - run(createProjectBuildingInsertProjectCommand(houseB)); - - const floor = createProjectFloorSnapshot("project-1", "EG", 0, houseA.id); - const floorInsert = createProjectFloorInsertProjectCommand(floor); - assert.equal(floorInsert.schemaVersion, projectFloorCommandSchemaVersion); - run(floorInsert); - assert.deepEqual(getFloor(context, floor.id), floor); - - const moved = { ...floor, buildingId: houseB.id }; - const moveCommand = createProjectFloorUpdateProjectCommand(floor, moved); - const movedResult = run(moveCommand); - assert.equal(getFloor(context, floor.id)?.buildingId, houseB.id); - - assert.throws( - () => run(createProjectBuildingDeleteProjectCommand(houseB)), - /solange Etagen zugeordnet/ - ); - assert.ok(getBuilding(context, houseB.id)); - - run(movedResult.inverse, "undo"); - assert.equal(getFloor(context, floor.id)?.buildingId, houseA.id); - run(moveCommand, "redo"); - assert.equal(getFloor(context, floor.id)?.buildingId, houseB.id); - - const unassigned = { ...moved, buildingId: null }; - run(createProjectFloorUpdateProjectCommand(moved, unassigned)); - assert.equal(getFloor(context, floor.id)?.buildingId, null); - run(createProjectBuildingDeleteProjectCommand(houseB)); - assert.equal(getBuilding(context, houseB.id), undefined); - } finally { - context.close(); - } - }); - - it("rejects floors that reference a missing or foreign building", () => { - const context = createTestDatabase(); - try { - const { run } = createRunner(context); - context.db - .insert(buildings) - .values({ id: "foreign", projectId: "project-2", name: "Fremd", sortOrder: 0 }) - .run(); - assert.throws( - () => - run( - createProjectFloorInsertProjectCommand( - createProjectFloorSnapshot("project-1", "EG", 0, "foreign") - ) - ), - /foreign building/ - ); - assert.throws( - () => - run( - createProjectFloorInsertProjectCommand( - createProjectFloorSnapshot("project-1", "EG", 0, "missing") - ) - ), - /foreign building/ - ); - assert.equal(context.db.select().from(floors).all().length, 0); - - const floor = createProjectFloorSnapshot("project-1", "EG", 0); - run(createProjectFloorInsertProjectCommand(floor)); - assert.throws( - () => - run( - createProjectFloorUpdateProjectCommand(floor, { - ...floor, - buildingId: "foreign", - }) - ), - /foreign building/ - ); - assert.throws( - () => createProjectFloorUpdateProjectCommand(floor, { ...floor }), - /only the name or the building/ - ); - assert.throws( - () => - createProjectFloorUpdateProjectCommand(floor, { - ...floor, - sortOrder: 5, - name: "Erdgeschoss", - }), - /only the name or the building/ - ); - } finally { - context.close(); - } - }); - - it("executes version 1 floor commands recorded before buildings existed", () => { - const context = createTestDatabase(); - try { - const { run } = createRunner(context); - const legacyFloor = { - id: "floor-legacy", - projectId: "project-1", - name: "EG", - sortOrder: 0, - }; - const legacyInsert = { - schemaVersion: 1 as const, - type: "project-floor.insert" as const, - payload: { floor: legacyFloor }, - }; - assertProjectFloorInsertProjectCommand(legacyInsert); - const inserted = run(legacyInsert); - assert.deepEqual(getFloor(context, legacyFloor.id), { - ...legacyFloor, - buildingId: null, - }); - // The inverse is always written in the current version. - assert.equal(inserted.inverse.schemaVersion, projectFloorCommandSchemaVersion); - - const legacyUpdate = { - schemaVersion: 1 as const, - type: "project-floor.update" as const, - payload: { - expected: legacyFloor, - target: { ...legacyFloor, name: "Erdgeschoss" }, - }, - }; - const updated = run(legacyUpdate); - assert.equal(getFloor(context, legacyFloor.id)?.name, "Erdgeschoss"); - run(updated.inverse, "undo"); - assert.equal(getFloor(context, legacyFloor.id)?.name, "EG"); - - // A version 1 snapshot must not carry buildingId, a version 2 one must. - assert.throws(() => - assertProjectFloorInsertProjectCommand({ - schemaVersion: 1, - type: "project-floor.insert", - payload: { floor: { ...legacyFloor, buildingId: null } }, - }) - ); - assert.throws(() => - assertProjectFloorInsertProjectCommand({ - schemaVersion: 2, - type: "project-floor.insert", - payload: { floor: legacyFloor }, - }) - ); - } finally { - context.close(); - } - }); - - it("validates building and floor requests", () => { - assert.equal( - createBuildingSchema.safeParse({ expectedRevision: 0, name: "Haus A" }).success, - true - ); - assert.equal( - createBuildingSchema.safeParse({ expectedRevision: 0, name: " " }).success, - false - ); - assert.equal( - createBuildingSchema.safeParse({ - expectedRevision: 0, - name: "Haus A", - sortOrder: 1, - }).success, - false - ); - for (const buildingId of [undefined, null, "building-1"]) { - assert.equal( - createFloorSchema.safeParse({ expectedRevision: 0, name: "EG", buildingId }) - .success, - true - ); - } - assert.equal( - updateFloorSchema.safeParse({ expectedRevision: 0, name: "EG", buildingId: "" }) - .success, - false - ); - }); -}); diff --git a/tests/project-command.service.test.ts b/tests/project-command.service.test.ts index ac6d887..861edcd 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 { ExternalModelConfigurationProjectCommandRepository } from "../src/db/repositories/external-model-configuration-project-command.repository.js"; +import { ExternalCsvConfigurationProjectCommandRepository } from "../src/db/repositories/external-csv-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"; @@ -41,10 +41,9 @@ import { projectChangeSets } from "../src/db/schema/project-change-sets.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 { buildings } from "../src/db/schema/buildings.js"; import { floors } from "../src/db/schema/floors.js"; import { rooms } from "../src/db/schema/rooms.js"; -import { externalModelConfigurations } from "../src/db/schema/external-model-configurations.js"; +import { externalCsvConfigurations } from "../src/db/schema/external-csv-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"; @@ -79,8 +78,6 @@ import { createDistributionBoardComponentUpdateProjectCommand, } from "../src/domain/models/distribution-board-component-structure-project-command.model.js"; import { - createProjectBuildingInsertProjectCommand, - createProjectBuildingSnapshot, createProjectFloorInsertProjectCommand, createProjectFloorSnapshot, createProjectRoomInsertProjectCommand, @@ -90,8 +87,9 @@ 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 { createExternalModelConfigurationUpdateProjectCommand } from "../src/domain/models/external-model-configuration-project-command.model.js"; -import { createDefaultExternalModelConfiguration } from "../src/external-model/configuration/external-model-configuration.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 { ProjectCommandService } from "../src/domain/services/project-command.service.js"; function createTestDatabase(): DatabaseContext { @@ -165,7 +163,7 @@ function createService(context: DatabaseContext) { new CircuitGroupSubtreeProjectCommandRepository(context.db), new CircuitProtectionProjectCommandRepository(context.db), new ProjectHistoryRepository(context.db), - new ExternalModelConfigurationProjectCommandRepository(context.db) + new ExternalCsvConfigurationProjectCommandRepository(context.db) ); } @@ -1126,62 +1124,31 @@ describe("project command service", () => { } }); - it("dispatches external XLSX configuration updates through persistent history", () => { + it("dispatches external CSV configuration updates through persistent history", () => { const context = createTestDatabase(); try { const service = createService(context); const target = { id: "external-config-1", projectId: "project-1", - configuration: createDefaultExternalModelConfiguration(), + configurationVersion: 1, + configuration: createDefaultExternalCsvConfiguration(externalCsvTestColumns), }; const updated = service.executeUser({ projectId: "project-1", expectedRevision: 0, - command: createExternalModelConfigurationUpdateProjectCommand(null, target), + command: createExternalCsvConfigurationUpdateProjectCommand(null, target), }); assert.equal(updated.history.currentRevision, 1); - assert.equal(context.db.select().from(externalModelConfigurations).all().length, 1); + assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 1); const undone = service.undo({ projectId: "project-1", expectedRevision: 1 }); assert.equal(undone.history.currentRevision, 2); - assert.equal(context.db.select().from(externalModelConfigurations).all().length, 0); + assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 0); const redone = service.redo({ projectId: "project-1", expectedRevision: 2 }); assert.equal(redone.history.currentRevision, 3); - 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); + assert.equal(context.db.select().from(externalCsvConfigurations).all().length, 1); } finally { context.close(); } @@ -1643,43 +1610,6 @@ describe("project command service", () => { } }); - it("dispatches building commands and floor assignments with persisted inverses", () => { - const context = createTestDatabase(); - try { - const service = createService(context); - const building = createProjectBuildingSnapshot("project-1", "Haus A", 0); - service.executeUser({ - projectId: "project-1", - expectedRevision: 0, - command: createProjectBuildingInsertProjectCommand(building), - }); - const floor = createProjectFloorSnapshot("project-1", "EG", 0, building.id); - const created = service.executeUser({ - projectId: "project-1", - expectedRevision: 1, - command: createProjectFloorInsertProjectCommand(floor), - }); - assert.equal(created.history.currentRevision, 2); - assert.equal( - context.db.select().from(floors).where(eq(floors.id, floor.id)).get() - ?.buildingId, - building.id - ); - - createService(context).undo({ projectId: "project-1", expectedRevision: 2 }); - createService(context).undo({ projectId: "project-1", expectedRevision: 3 }); - assert.equal(context.db.select().from(buildings).all().length, 0); - createService(context).redo({ projectId: "project-1", expectedRevision: 4 }); - createService(context).redo({ projectId: "project-1", expectedRevision: 5 }); - assert.deepEqual( - context.db.select().from(floors).where(eq(floors.id, floor.id)).get(), - floor - ); - } finally { - context.close(); - } - }); - it("dispatches floor and room setup with their persisted inverses", () => { const context = createTestDatabase(); try { 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 f5e7a60..593a7f6 100644 --- a/tests/project-device-row-sync-project-command.repository.test.ts +++ b/tests/project-device-row-sync-project-command.repository.test.ts @@ -19,6 +19,7 @@ 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, @@ -177,7 +178,7 @@ function linkExternalObject( id: "source-1", projectId: "project-1", name: "Revit", - sourceType: "revit_xlsx", + sourceType: "revit_csv", }) .run(); context.db @@ -188,9 +189,13 @@ function linkExternalObject( sourceId: "source-1", importKind: "initial", importedAtIso: "2026-08-02T16:00:00.000Z", - fileName: "revit.xlsx", + fileName: "revit.csv", sha256: "a".repeat(64), - objectCount: 1, + appliedProjectRevision: 0, + configurationVersion: 1, + configurationSnapshot: externalCsvTestConfiguration, + originalBytes: Buffer.from("test"), + document: { delimiter: ";", encoding: "utf-8", headers: [], rows: [] }, }) .run(); context.db @@ -199,9 +204,7 @@ 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: { @@ -210,18 +213,14 @@ function linkExternalObject( roomName: "Büro", familyAndType: "Leuchte: Standard", selectionMarker: "Leuchte", - socketCount: String(effectiveQuantity), - sourceRemark: null, - circuitCombined: "-1F1", - boardName: "UV 1", circuitIdentifier: "-1F1", - designation: null, - electricalPowerW: "30", - voltageV: 230, - currentA: null, + power: "30", + quantity: String(effectiveQuantity), + additionalSourceValues: {}, }, planningValues: { displayName: "Leuchte", + internalDeviceType: "luminaire", category: "single_phase", connectionKind: "fixed", effectiveQuantity, diff --git a/tests/project-location-structure-project-command.repository.test.ts b/tests/project-location-structure-project-command.repository.test.ts index 03f70f9..6378965 100644 --- a/tests/project-location-structure-project-command.repository.test.ts +++ b/tests/project-location-structure-project-command.repository.test.ts @@ -22,11 +22,6 @@ import { createProjectRoomInsertProjectCommand, createProjectRoomSnapshot, createProjectRoomUpdateProjectCommand, - projectRoomCommandSchemaVersion, - projectRoomDeleteCommandType, - projectRoomUpdateCommandType, - type LegacyProjectRoomDeleteProjectCommand, - type LegacyProjectRoomUpdateProjectCommand, } from "../src/domain/models/project-location-structure-project-command.model.js"; import { createFloor, @@ -71,12 +66,10 @@ describe("project-location structure project command", () => { floorId: floor.id, roomNumber: " 001 ", roomName: " Technik ", - areaM2: 23.456, }); assert.equal(floor.name, "EG"); assert.equal(room.roomNumber, "001"); assert.equal(room.roomName, "Technik"); - assert.equal(room.areaM2, 23.456); assert.throws( () => createProjectFloorInsertProjectCommand({ @@ -120,7 +113,6 @@ describe("project-location structure project command", () => { floorId: "floor-1", roomNumber: "001", roomName: "Technik", - areaM2: 23.456, }, 8 ); @@ -128,7 +120,7 @@ describe("project-location structure project command", () => { await updateRoom( "project-1", "room-1", - { roomNumber: "101", roomName: "Büro", areaM2: null }, + { roomNumber: "101", roomName: "Büro" }, 10 ); await deleteFloor("project-1", "floor-1", 11); @@ -149,7 +141,6 @@ describe("project-location structure project command", () => { floorId: "floor-1", roomNumber: "001", roomName: "Technik", - areaM2: 23.456, expectedRevision: 8, }, }, @@ -164,7 +155,6 @@ describe("project-location structure project command", () => { body: { roomNumber: "101", roomName: "Büro", - areaM2: null, floorId: null, expectedRevision: 10, }, @@ -209,7 +199,6 @@ describe("project-location structure project command", () => { floorId: null, roomNumber: "002", roomName: "Lager", - areaM2: 48.125, }; const roomCommand = createProjectRoomUpdateProjectCommand(room, updatedRoom); const roomResult = repository.execute({ @@ -438,64 +427,6 @@ describe("project-location structure project command", () => { } }); - it("upgrades version-1 room commands without overwriting a newer area", () => { - const context = createTestDatabase(); - try { - const repository = new ProjectLocationStructureProjectCommandRepository(context.db); - const history = new ProjectHistoryRepository(context.db); - const room = createProjectRoomSnapshot("project-1", { - roomNumber: "001", - roomName: "Technik", - }); - context.db.insert(rooms).values(room).run(); - const { areaM2: _expectedArea, ...legacyExpected } = room; - const legacyTarget = { ...legacyExpected, roomName: "Technik alt" }; - const legacyUpdate: LegacyProjectRoomUpdateProjectCommand = { - schemaVersion: 1, - type: projectRoomUpdateCommandType, - payload: { expected: legacyExpected, target: legacyTarget }, - }; - - const updated = repository.execute({ - projectId: "project-1", - expectedRevision: 0, - source: "user", - command: legacyUpdate, - }); - assert.equal(updated.inverse.schemaVersion, projectRoomCommandSchemaVersion); - assert.equal(context.db.select().from(rooms).get()?.areaM2, null); - - const undo = history.getNextCommand("project-1", "undo"); - assert.ok(undo); - repository.execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: undo.changeSetId, - command: updated.inverse, - }); - context.db.update(rooms).set({ areaM2: 12.5 }).where(eq(rooms.id, room.id)).run(); - const legacyDelete: LegacyProjectRoomDeleteProjectCommand = { - schemaVersion: 1, - type: projectRoomDeleteCommandType, - payload: { room: legacyExpected }, - }; - assert.throws( - () => - repository.execute({ - projectId: "project-1", - expectedRevision: 2, - source: "user", - command: legacyDelete, - }), - /changed before deletion/ - ); - assert.equal(context.db.select().from(rooms).get()?.areaM2, 12.5); - } finally { - context.close(); - } - }); - it("rejects foreign, stale and changed locations without partial writes", () => { const context = createTestDatabase(); try { diff --git a/tests/project-snapshot.repository.test.ts b/tests/project-snapshot.repository.test.ts index b85485c..b062c68 100644 --- a/tests/project-snapshot.repository.test.ts +++ b/tests/project-snapshot.repository.test.ts @@ -11,13 +11,7 @@ import { import { DistributionBoardFixtureRepository } from "./support/distribution-board-fixture.js"; import { ProjectSnapshotRepository } from "../src/db/repositories/project-snapshot.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 { - deleteEstimateBalance, - insertEstimateBalance, - readEstimateBalances, -} from "../src/db/repositories/estimate-balance.persistence.js"; import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; import { circuitLists } from "../src/db/schema/circuit-lists.js"; import { circuitProtectionDevices } from "../src/db/schema/circuit-protection-devices.js"; @@ -26,7 +20,6 @@ import { circuits } from "../src/db/schema/circuits.js"; import { distributionBoardComponentProtectionDevices } from "../src/db/schema/distribution-board-component-protection-devices.js"; import { distributionBoardComponents } from "../src/db/schema/distribution-board-components.js"; import { distributionBoards } from "../src/db/schema/distribution-boards.js"; -import { buildings } from "../src/db/schema/buildings.js"; import { floors } from "../src/db/schema/floors.js"; import { projectDevices } from "../src/db/schema/project-devices.js"; import { projectSnapshots } from "../src/db/schema/project-snapshots.js"; @@ -34,48 +27,8 @@ import { projects } from "../src/db/schema/projects.js"; import { rooms } from "../src/db/schema/rooms.js"; import { deserializeProjectStateSnapshot } from "../src/domain/models/project-state-snapshot.model.js"; import { projectStateSnapshotSchemaVersion } from "../src/domain/models/project-state-snapshot.model.js"; -import { createProjectStateRestoreCommand } from "../src/domain/models/project-state-restore-command.model.js"; import { ProjectRevisionConflictError } from "../src/domain/errors/project-revision-conflict.error.js"; import { ProjectSnapshotNameConflictError } from "../src/domain/errors/project-snapshot-name-conflict.error.js"; -import { parseEstimateBalanceSnapshot } from "../src/estimate-balance/domain/estimate-balance-command.model.js"; - -function estimateBalance(projectId: string, suffix = "") { - return parseEstimateBalanceSnapshot({ - id: `estimate${suffix}`, - projectId, - name: `Vorplanung${suffix}`, - workStage: "LPH 2", - dateIso: "2026-09-27", - reserveAvPercent: 10, - reserveSvPercent: 5, - sortOrder: 0, - groups: [ - { - id: `estimate-group${suffix}`, - costGroup: "440", - title: "Starkstromanlagen", - editor: "Planung", - sortOrder: 0, - rows: [ - { - id: `estimate-row${suffix}`, - sortOrder: 0, - supply: "ELT", - name: "Beleuchtung", - quantity: 100, - unit: "area", - connection: "fixed", - powerPerUnitW: 12, - simultaneityFactor: 0.8, - cosPhi: 0.95, - safetySupply: false, - remark: null, - }, - ], - }, - ], - }); -} function createTestDatabase(): DatabaseContext { const context = createDatabaseContext(":memory:"); @@ -106,15 +59,6 @@ function createTestDatabase(): DatabaseContext { .where(eq(circuitSections.circuitListId, list.id)) .get(); assert.ok(section); - context.db - .insert(buildings) - .values({ - id: "building-1", - projectId: "project-1", - name: "Haus A", - sortOrder: 0, - }) - .run(); context.db .insert(floors) .values({ @@ -122,7 +66,6 @@ function createTestDatabase(): DatabaseContext { projectId: "project-1", name: "EG", sortOrder: 10, - buildingId: "building-1", }) .run(); context.db @@ -142,7 +85,6 @@ function createTestDatabase(): DatabaseContext { floorId: "floor-1", roomNumber: "001", roomName: "Technik", - areaM2: 31.75, }) .run(); context.db @@ -306,9 +248,7 @@ describe("project snapshot repository", () => { "device-1" ); assert.equal(state.projectDevices.length, 1); - assert.equal(state.buildings.length, 1); assert.equal(state.floors.length, 1); - assert.equal(state.floors[0].buildingId, "building-1"); assert.equal(state.rooms.length, 1); assert.deepEqual(repository.listByProject("project-1"), [ created, @@ -437,127 +377,15 @@ describe("project snapshot repository", () => { context.close(); } }); - - it("restores snapshots stored with an older supported schema version", () => { - const context = createTestDatabase(); - try { - const repository = new ProjectSnapshotRepository(context.db); - const snapshot = repository.createNamed({ - projectId: "project-1", - expectedRevision: 0, - name: "Vor dem Update", - }); - assert.ok(snapshot); - // Rewrite the stored payload into the previous (version 5) shape, as it - // exists for snapshots created before the current version. - const payload = JSON.parse( - context.db - .select({ payloadJson: projectSnapshots.payloadJson }) - .from(projectSnapshots) - .where(eq(projectSnapshots.id, snapshot.id)) - .get()!.payloadJson - ) as { - schemaVersion: number; - project: Record; - distributionBoards: Array>; - buildings?: unknown; - floors: Array>; - 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; - } - for (const room of payload.rooms) { - delete room.areaM2; - } - for (const field of ["siteAddress", "workStage", "projectLead", "projectEditor"]) { - delete payload.project[field]; - } - for (const board of payload.distributionBoards) { - for (const field of [ - "boardNumber", - "location", - "fedFrom", - "remark", - "feedingDistributionBoardId", - "feedingCircuitId", - ]) { - delete board[field]; - } - } - const payloadJson = JSON.stringify(payload); - context.db - .update(projectSnapshots) - .set({ - schemaVersion: 5, - payloadJson, - payloadSha256: crypto - .createHash("sha256") - .update(payloadJson) - .digest("hex"), - }) - .where(eq(projectSnapshots.id, snapshot.id)) - .run(); - - const prepared = repository.prepareRestore("project-1", snapshot.id); - assert.ok(prepared); - const targetState = prepared.command.payload.targetState; - assert.equal(targetState.schemaVersion, projectStateSnapshotSchemaVersion); - assert.ok(targetState.distributionBoards.length > 0); - assert.ok( - targetState.distributionBoards.every( - (board) => board.boardNumber === null && board.fedFrom === null - ) - ); - // Version 5 predates buildings: the upgraded state has none. - assert.deepEqual(targetState.buildings, []); - assert.ok(targetState.floors.every((floor) => floor.buildingId === null)); - } finally { - context.close(); - } - }); }); describe("portable project transfer", () => { - it("keeps estimate balances outside normal snapshot restore", () => { - const context = createTestDatabase(); - try { - insertEstimateBalance(context.db, estimateBalance("project-1")); - const current = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(current); - new ProjectStateRestoreCommandRepository(context.db).execute({ - projectId: "project-1", - expectedRevision: 0, - source: "restore", - command: createProjectStateRestoreCommand(current.payloadSha256, { - ...current.state, - project: { ...current.state.project, name: "Restored project" }, - }), - }); - assert.deepEqual( - readEstimateBalances(context.db, "project-1").map((entry) => entry.id), - ["estimate"] - ); - } finally { - context.close(); - } - }); - it("exports and atomically duplicates a complete project with new ids", () => { const context = createTestDatabase(); try { - context.db.update(projects).set({ siteAddress: "Musterstraße 1", workStage: "LPH 5", projectLead: "Planung", projectEditor: "Test" }).where(eq(projects.id, "project-1")).run(); - context.db.update(distributionBoards).set({ boardNumber: "UV-01", location: "Technik", fedFrom: "HAK", remark: "Prüfstand" }).where(eq(distributionBoards.projectId, "project-1")).run(); - insertEstimateBalance(context.db, estimateBalance("project-1")); const repository = new ProjectTransferRepository(context.db); const transfer = repository.exportProject("project-1"); assert.ok(transfer); - assert.equal(transfer.formatVersion, 2); - assert.equal(transfer.estimateBalances.length, 1); const duplicate = repository.importDuplicate(transfer); assert.notEqual(duplicate.projectId, "project-1"); assert.equal(duplicate.name, "Snapshot-Projekt (Kopie)"); @@ -570,13 +398,6 @@ describe("portable project transfer", () => { assert.ok(source); assert.ok(copied); assert.equal(copied.currentRevision, 0); - assert.equal(copied.state.project.siteAddress, source.state.project.siteAddress); - assert.equal(copied.state.project.workStage, "LPH 5"); - assert.equal(copied.state.project.projectLead, "Planung"); - assert.equal(copied.state.project.projectEditor, "Test"); - for (const field of ["boardNumber", "location", "fedFrom", "remark"] as const) { - assert.equal(copied.state.distributionBoards[0][field], source.state.distributionBoards[0][field]); - } assert.equal(copied.state.circuits.length, source.state.circuits.length); assert.notEqual( copied.state.circuits[0].id, @@ -611,16 +432,10 @@ describe("portable project transfer", () => { copied.state.circuits[0].deviceRows[0].roomId, copied.state.rooms[0].id ); - assert.equal(copied.state.rooms[0].areaM2, 31.75); assert.equal( copied.state.distributionBoards[0].floorId, copied.state.floors[0].id ); - assert.notEqual(copied.state.buildings[0].id, "building-1"); - assert.equal( - copied.state.floors[0].buildingId, - copied.state.buildings[0].id - ); assert.equal( copied.state.distributionBoards[0].supplyType, "SV" @@ -629,18 +444,6 @@ describe("portable project transfer", () => { copied.state.distributionBoards[0].simultaneityFactor, 0.65 ); - const copiedBalances = readEstimateBalances(context.db, duplicate.projectId); - assert.equal(copiedBalances.length, 1); - assert.notEqual(copiedBalances[0].id, transfer.estimateBalances[0].id); - assert.notEqual( - copiedBalances[0].groups[0].id, - transfer.estimateBalances[0].groups[0].id - ); - assert.notEqual( - copiedBalances[0].groups[0].rows[0].id, - transfer.estimateBalances[0].groups[0].rows[0].id - ); - assert.equal(copiedBalances[0].groups[0].rows[0].name, "Beleuchtung"); } finally { context.close(); } @@ -666,14 +469,6 @@ describe("portable project transfer", () => { }), /checksum verification failed/ ); - assert.throws( - () => - repository.importDuplicate({ - ...transfer, - estimateBalances: [estimateBalance("project-1", "-tampered")], - }), - /checksum verification failed/ - ); assert.equal( context.db.select().from(projects).all().length, 1 @@ -683,79 +478,15 @@ describe("portable project transfer", () => { } }); - it("imports legacy transfer version 1 with no estimate balances", () => { - const context = createTestDatabase(); - try { - const snapshot = readProjectStateSnapshot(context.db, "project-1"); - assert.ok(snapshot); - const legacyTransfer = { - format: "leistungsbilanz.project", - formatVersion: 1, - exportedAtIso: "2026-09-27T12:00:00.000Z", - payloadSha256: snapshot.payloadSha256, - projectState: snapshot.state, - }; - const duplicate = new ProjectTransferRepository(context.db).importDuplicate( - legacyTransfer - ); - assert.deepEqual( - readEstimateBalances(context.db, duplicate.projectId), - [] - ); - } finally { - context.close(); - } - }); - - it("replaces exported estimate balances atomically and restores them on undo", () => { - const context = createTestDatabase(); - try { - insertEstimateBalance(context.db, estimateBalance("project-1")); - const transferRepository = new ProjectTransferRepository(context.db); - const transfer = transferRepository.exportProject("project-1"); - assert.ok(transfer); - - deleteEstimateBalance(context.db, "project-1", "estimate"); - insertEstimateBalance(context.db, estimateBalance("project-1", "-changed")); - const prepared = transferRepository.prepareReplace("project-1", transfer); - assert.ok(prepared); - const restored = new ProjectStateRestoreCommandRepository(context.db).execute({ - projectId: "project-1", - expectedRevision: 0, - source: "restore", - command: prepared.command, - }); - assert.deepEqual( - readEstimateBalances(context.db, "project-1").map((entry) => entry.id), - ["estimate"] - ); - - new ProjectStateRestoreCommandRepository(context.db).execute({ - projectId: "project-1", - expectedRevision: 1, - source: "undo", - historyTargetChangeSetId: restored.revision.changeSetId, - command: restored.inverse, - }); - assert.deepEqual( - readEstimateBalances(context.db, "project-1").map((entry) => entry.id), - ["estimate-changed"] - ); - } finally { - context.close(); - } - }); - it("rolls back a duplicate when a late project-state insert fails", () => { const context = createTestDatabase(); try { - insertEstimateBalance(context.db, estimateBalance("project-1")); const repository = new ProjectTransferRepository(context.db); const transfer = repository.exportProject("project-1"); assert.ok(transfer); context.sqlite.exec(` - CREATE TRIGGER fail_imported_estimate_row - BEFORE INSERT ON estimate_rows + CREATE TRIGGER fail_imported_device_row + BEFORE INSERT ON circuit_device_rows BEGIN SELECT RAISE(ABORT, 'forced project transfer failure'); END; diff --git a/tests/project-state-restore-command.repository.test.ts b/tests/project-state-restore-command.repository.test.ts index b093f9e..fff87e0 100644 --- a/tests/project-state-restore-command.repository.test.ts +++ b/tests/project-state-restore-command.repository.test.ts @@ -39,7 +39,6 @@ import { circuitSections } from "../src/db/schema/circuit-sections.js"; import { circuits } from "../src/db/schema/circuits.js"; import { distributionBoardComponentProtectionDevices } from "../src/db/schema/distribution-board-component-protection-devices.js"; import { distributionBoardComponents } from "../src/db/schema/distribution-board-components.js"; -import { distributionBoards } from "../src/db/schema/distribution-boards.js"; import { floors } from "../src/db/schema/floors.js"; import { projectDevices } from "../src/db/schema/project-devices.js"; import { projectRevisions } from "../src/db/schema/project-revisions.js"; @@ -96,7 +95,6 @@ function createTestDatabase(): DatabaseContext { floorId: "floor-1", roomNumber: "001", roomName: "Technik", - areaM2: 31.75, }) .run(); context.db @@ -342,8 +340,6 @@ describe("project state restore command", () => { it("restores a complete snapshot as a revision and supports undo and redo", () => { const context = createTestDatabase(); try { - context.db.update(projects).set({ siteAddress: "Originaladresse", workStage: "LPH 3", projectLead: "Leitung", projectEditor: "Bearbeitung" }).where(eq(projects.id, "project-1")).run(); - context.db.update(distributionBoards).set({ boardNumber: "UV-01", location: "EG", fedFrom: "HAK", remark: "Original" }).where(eq(distributionBoards.projectId, "project-1")).run(); const snapshots = new ProjectSnapshotRepository(context.db); const snapshot = snapshots.createNamed({ projectId: "project-1", @@ -355,8 +351,6 @@ describe("project state restore command", () => { assert.ok(original); changeCompleteProjectState(context); - context.db.update(projects).set({ siteAddress: "Neue Adresse", workStage: "LPH 5", projectLead: null, projectEditor: null }).where(eq(projects.id, "project-1")).run(); - context.db.update(distributionBoards).set({ boardNumber: "UV-02", location: "OG", fedFrom: "HV", remark: null }).where(eq(distributionBoards.projectId, "project-1")).run(); const changed = readProjectStateSnapshot(context.db, "project-1"); assert.ok(changed); assert.notEqual(changed.payloadSha256, original.payloadSha256); diff --git a/tests/project-state-snapshot.test.ts b/tests/project-state-snapshot.test.ts index 1ae460f..04d4901 100644 --- a/tests/project-state-snapshot.test.ts +++ b/tests/project-state-snapshot.test.ts @@ -6,42 +6,12 @@ import { projectStateSnapshotSchemaVersion, serializeProjectStateSnapshot, } 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; - } - return snapshot; -} - -/** Removes the fields introduced by snapshot schema version 7. */ -function withoutVersionSevenFields< - T extends { floors: object[]; distributionBoards: object[] }, ->(snapshot: T): T { - withoutVersionNineFields(snapshot); - delete (snapshot as Record).buildings; - for (const floor of snapshot.floors) { - delete (floor as Record).buildingId; - } - return snapshot; -} - -/** Removes the fields introduced by snapshot schema versions 6 and 7. */ +/** Removes the fields introduced by snapshot schema version 6. */ function withoutVersionSixFields< - T extends { project: object; distributionBoards: object[]; floors: object[] }, + T extends { project: object; distributionBoards: object[] }, >(snapshot: T): T { - withoutVersionSevenFields(snapshot); const project = snapshot.project as Record; for (const field of ["siteAddress", "workStage", "projectLead", "projectEditor"]) { delete project[field]; @@ -82,7 +52,7 @@ function minimalSnapshot() { projectEditor: null as string | null, }, distributionBoards: [], - externalModelConfiguration: null, + externalCsvConfiguration: null, externalModel: { source: null, importBatches: [], @@ -96,27 +66,8 @@ function minimalSnapshot() { distributionBoardComponentProtectionDevices: [], circuits: [], projectDevices: [], - buildings: [] as Array<{ - id: string; - projectId: string; - name: string; - sortOrder: number; - }>, - floors: [] as Array<{ - id: string; - projectId: string; - name: string; - sortOrder: number; - buildingId: string | null; - }>, - rooms: [] as Array<{ - id: string; - projectId: string; - floorId: string | null; - roomNumber: string; - roomName: string; - areaM2: number | null; - }>, + floors: [], + rooms: [], }; } @@ -135,8 +86,6 @@ function protectedSnapshot() { location: "Raum 003 Technik" as string | null, fedFrom: "HV 0.1" as string | null, remark: null as string | null, - feedingDistributionBoardId: null as string | null, - feedingCircuitId: null as string | null, }, ], circuitLists: [ @@ -226,101 +175,10 @@ describe("project state snapshot model", () => { ); }); - it("upgrades snapshot version 8 with empty feeding references", () => { - const previous = withoutVersionNineFields(protectedSnapshot()); - previous.schemaVersion = 8 as typeof previous.schemaVersion; - - const upgraded = parseProjectStateSnapshot(previous); - - assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal( - upgraded.distributionBoards[0]?.feedingDistributionBoardId, - null - ); - assert.equal(upgraded.distributionBoards[0]?.feedingCircuitId, null); - }); - - it("validates logical feeding references and cycles", () => { - const linked = protectedSnapshot(); - linked.distributionBoards.push({ - id: "board-2", - projectId: "project-1", - name: "UV 2", - floorId: null, - supplyType: null, - simultaneityFactor: 1, - boardNumber: "UV 2.1", - location: null, - fedFrom: null, - remark: null, - feedingDistributionBoardId: "board-1", - feedingCircuitId: "circuit-1", - }); - linked.circuitLists.push({ - id: "list-2", - projectId: "project-1", - distributionBoardId: "board-2", - name: "UV 2 Stromkreisliste", - }); - linked.circuitSections.push({ - id: "section-2", - circuitListId: "list-2", - key: "three_phase", - displayName: "Dreiphasig 1", - prefix: "-3F1.", - sortOrder: 10, - category: "three_phase", - groupNumber: 1, - }); - const parsed = parseProjectStateSnapshot(linked); - assert.equal(parsed.distributionBoards[1]?.feedingCircuitId, "circuit-1"); - let nextId = 0; - const remapped = remapProjectState( - parsed, - "project-copy", - () => `copy-${++nextId}` - ); - const remappedUpstream = remapped.distributionBoards.find( - (board) => board.name === "UV 1" - ); - const remappedDownstream = remapped.distributionBoards.find( - (board) => board.name === "UV 2" - ); - assert.ok(remappedUpstream); - assert.ok(remappedDownstream); - assert.equal( - remappedDownstream.feedingDistributionBoardId, - remappedUpstream.id - ); - assert.notEqual(remappedDownstream.feedingCircuitId, "circuit-1"); - assert.ok( - remapped.circuits.some( - (circuit) => circuit.id === remappedDownstream.feedingCircuitId - ) - ); - - const missingBoard = structuredClone(linked); - missingBoard.distributionBoards[1]!.feedingDistributionBoardId = null; - assert.throws( - () => parseProjectStateSnapshot(missingBoard), - /requires a feeding distribution board/ - ); - - const cycle = structuredClone(linked); - cycle.distributionBoards[0]!.feedingDistributionBoardId = "board-2"; - cycle.distributionBoards[0]!.feedingCircuitId = null; - cycle.distributionBoards[1]!.feedingCircuitId = null; - assert.throws( - () => parseProjectStateSnapshot(cycle), - /contains a cycle/ - ); - }); - it("upgrades the supported baseline snapshot with a safe building default", () => { 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; @@ -328,7 +186,7 @@ describe("project state snapshot model", () => { assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); assert.equal(upgraded.project.isPublicBuilding, false); - assert.equal(upgraded.externalModelConfiguration, null); + assert.equal(upgraded.externalCsvConfiguration, null); }); it("upgrades snapshot version 2 with an empty external CSV configuration", () => { @@ -340,7 +198,7 @@ describe("project state snapshot model", () => { const upgraded = parseProjectStateSnapshot(previous); assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(upgraded.externalModelConfiguration, null); + assert.equal(upgraded.externalCsvConfiguration, null); assert.deepEqual(upgraded.externalModel, { source: null, importBatches: [], @@ -357,7 +215,7 @@ describe("project state snapshot model", () => { const upgraded = parseProjectStateSnapshot(previous); assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(upgraded.externalModelConfiguration, null); + assert.equal(upgraded.externalCsvConfiguration, null); assert.deepEqual(upgraded.externalModel, { source: null, importBatches: [], @@ -366,28 +224,6 @@ 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; @@ -470,10 +306,7 @@ describe("project state snapshot model", () => { delete (outdated.project as Record).description; assert.throws(() => parseProjectStateSnapshot(outdated)); assert.throws(() => - parseProjectStateSnapshot({ - ...minimalSnapshot(), - schemaVersion: projectStateSnapshotSchemaVersion + 1, - }) + parseProjectStateSnapshot({ ...minimalSnapshot(), schemaVersion: 7 }) ); }); @@ -522,119 +355,12 @@ describe("project state snapshot model", () => { projectId: "project-2", name: "EG", sortOrder: 10, - buildingId: null, }); assert.throws( () => parseProjectStateSnapshot(wrongOwner), /floor belongs to a different project/ ); }); - - it("keeps buildings and validates floor building references", () => { - const snapshot = minimalSnapshot(); - snapshot.buildings.push({ - id: "building-1", - projectId: "project-1", - name: "Haus A", - sortOrder: 0, - }); - snapshot.floors.push( - { - id: "floor-1", - projectId: "project-1", - name: "EG", - sortOrder: 0, - buildingId: "building-1", - }, - { - id: "floor-2", - projectId: "project-1", - name: "Keller", - sortOrder: 1, - buildingId: null, - } - ); - const parsed = deserializeProjectStateSnapshot( - serializeProjectStateSnapshot(parseProjectStateSnapshot(snapshot)) - ); - assert.deepEqual(parsed.buildings, snapshot.buildings); - assert.deepEqual( - parsed.floors.map((floor) => floor.buildingId), - ["building-1", null] - ); - - const unknownBuilding = structuredClone(snapshot); - unknownBuilding.floors[0]!.buildingId = "building-x"; - assert.throws( - () => parseProjectStateSnapshot(unknownBuilding), - /floor building/ - ); - - const foreignBuilding = structuredClone(snapshot); - foreignBuilding.buildings[0]!.projectId = "project-2"; - assert.throws( - () => parseProjectStateSnapshot(foreignBuilding), - /building belongs to a different project/ - ); - - const floorWithoutBuildingField = structuredClone(snapshot); - delete (floorWithoutBuildingField.floors[1] as Record) - .buildingId; - assert.throws(() => parseProjectStateSnapshot(floorWithoutBuildingField)); - }); - - it("keeps room areas and upgrades snapshot version 7 with an empty area", () => { - const current = minimalSnapshot(); - current.rooms.push({ - id: "room-1", - projectId: "project-1", - floorId: null, - roomNumber: "001", - roomName: "Technik", - areaM2: 23.456, - }); - assert.equal(parseProjectStateSnapshot(current).rooms[0]?.areaM2, 23.456); - - 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); - assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.equal(upgraded.rooms[0]?.areaM2, null); - }); - - it("upgrades snapshot version 6 without buildings", () => { - const snapshot = minimalSnapshot(); - snapshot.floors.push({ - id: "floor-1", - projectId: "project-1", - name: "EG", - sortOrder: 0, - buildingId: null, - }); - const previous = withoutVersionSevenFields(structuredClone(snapshot)); - previous.schemaVersion = 6 as typeof previous.schemaVersion; - - const upgraded = parseProjectStateSnapshot(previous); - - assert.equal(upgraded.schemaVersion, projectStateSnapshotSchemaVersion); - assert.deepEqual(upgraded.buildings, []); - assert.deepEqual(upgraded.floors, [ - { - id: "floor-1", - projectId: "project-1", - name: "EG", - sortOrder: 0, - buildingId: null, - }, - ]); - // Version 6 cover values survive the upgrade. - assert.equal(upgraded.project.workStage, "LPH 5"); - - const mislabeled = structuredClone(snapshot); - mislabeled.schemaVersion = 6 as typeof mislabeled.schemaVersion; - assert.throws(() => parseProjectStateSnapshot(mislabeled)); - }); }); describe("named project snapshot request", () => { diff --git a/tests/project-version-history.test.ts b/tests/project-version-history.test.ts index 4e85d41..59a2aac 100644 --- a/tests/project-version-history.test.ts +++ b/tests/project-version-history.test.ts @@ -3,11 +3,7 @@ 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 { - hasExistingProjectDeviceName, - isProjectDeviceNumberInRange, - ProjectDeviceModal, -} from "../src/frontend/components/project-device-modal.js"; +import { ProjectDeviceModal } from "../src/frontend/components/project-device-modal.js"; import { ProjectSettingsModal } from "../src/frontend/components/project-settings-modal.js"; import type { ProjectRevisionSummaryDto, @@ -328,42 +324,6 @@ 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, /