Add buildings above floors and a building structure page

Projects with several buildings could not be structured: floors and rooms
hung directly off the project. Floors can now belong to a building
(migration 0009: table buildings, nullable floors.building_id). Rooms and
distribution boards keep their floor; their building follows from it.
Existing floors stay without a building.

Buildings use the location-structure command store with
project-building.insert/.update/.delete, inverses and persistent Undo/Redo;
deleting a building with assigned floors is rejected. Floor commands carry
buildingId since command version 2. Version 1 floor commands from existing
history predate buildings and are upgraded with buildingId = null before
they are executed and persisted, so forward and inverse keep one version.

Project snapshot schema 7 stores buildings and floor.buildingId; versions
1-6 are upgraded without buildings. Restore and portable transfer include
buildings, and the transfer remaps building ids.

Buildings, floors and rooms move from the project overview to their own
page /projects/:id/struktur with three columns (Gebäude -> Etagen -> Räume)
that filter each other, and a sidebar entry. Floor selects in the board and
room dialogs are grouped by building. Unchanged dialogs close without a
command. Details in docs/building-structure.md; see issue #6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Grovy311 2026-09-26 12:52:34 +02:00
parent 7692699ee2
commit cd89c4a499
42 changed files with 5883 additions and 373 deletions

View file

@ -7,14 +7,21 @@ import { listProjects } from "../utils/api";
import type { ProjectDto } from "../types";
import { ThemeToggle } from "./ThemeToggle";
// 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]/<segment>).
const PROJECT_ROUTES = [
{ segment: "struktur", label: "Gebäudestruktur", 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;
@ -22,8 +29,14 @@ interface SidebarProps {
export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
const pathname = usePathname();
const projectMatch = pathname?.match(/^\/projects\/([^/]+)$/);
const projectMatch = pathname?.match(PROJECT_PATH_PATTERN);
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<ProjectDto[]>([]);
const [activeSection, setActiveSection] = useState<string | null>(null);
@ -42,7 +55,7 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
}, []);
useEffect(() => {
if (!activeProjectId) {
if (!overviewProjectId) {
setActiveSection(null);
return;
}
@ -69,7 +82,7 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
elements.forEach((element) => observer.observe(element));
return () => observer.disconnect();
}, [activeProjectId]);
}, [overviewProjectId]);
return (
<aside className={isCollapsed ? "sidebar sidebar-collapsed" : "sidebar"}>
@ -122,17 +135,46 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
{activeProjectId && (
<>
<div className="sidebar-section-label">In diesem Projekt</div>
{PROJECT_SECTIONS.map(({ id, label, icon }) => (
<a
key={id}
href={`#${id}`}
className={activeSection === id ? "sidebar-link active" : "sidebar-link"}
title={label}
>
<span className="sidebar-icon">{icon}</span>
<span className="sidebar-label">{label}</span>
</a>
))}
{PROJECT_SECTIONS.map(({ id, label, icon }) =>
overviewProjectId ? (
<a
key={id}
href={`#${id}`}
className={activeSection === id ? "sidebar-link active" : "sidebar-link"}
title={label}
>
<span className="sidebar-icon">{icon}</span>
<span className="sidebar-label">{label}</span>
</a>
) : (
<Link
key={id}
href={`/projects/${activeProjectId}#${id}`}
className="sidebar-link"
title={label}
>
<span className="sidebar-icon">{icon}</span>
<span className="sidebar-label">{label}</span>
</Link>
)
)}
{PROJECT_ROUTES.map(({ segment, label, icon }) => {
const href = `/projects/${activeProjectId}/${segment}`;
const isActive =
pathname === href || Boolean(pathname?.startsWith(`${href}/`));
return (
<Link
key={segment}
href={href}
aria-current={isActive ? "page" : undefined}
className={isActive ? "sidebar-link active" : "sidebar-link"}
title={label}
>
<span className="sidebar-icon">{icon}</span>
<span className="sidebar-label">{label}</span>
</Link>
);
})}
</>
)}
</nav>

View file

@ -0,0 +1,49 @@
"use client";
import React from "react";
import type { BuildingDto, FloorDto } from "../types";
import { groupFloorsByBuilding } from "../utils/building-structure";
export type FloorOption = Pick<FloorDto, "id" | "name"> & {
buildingId?: string | null;
};
interface FloorSelectOptionsProps {
buildings?: ReadonlyArray<Pick<BuildingDto, "id" | "name">>;
floors: ReadonlyArray<FloorOption>;
}
/**
* Floor <option>s for a <select>, grouped by building via <optgroup> as soon
* as the project has buildings. The caller renders its own empty option
* ("Ohne Etage") before these.
*/
export function FloorSelectOptions({
buildings = [],
floors,
}: FloorSelectOptionsProps) {
if (!buildings.length) {
return (
<>
{floors.map((floor) => (
<option key={floor.id} value={floor.id}>
{floor.name}
</option>
))}
</>
);
}
return (
<>
{groupFloorsByBuilding(floors, buildings).map((group) => (
<optgroup key={group.buildingId ?? "unassigned"} label={group.label}>
{group.floors.map((floor) => (
<option key={floor.id} value={floor.id}>
{floor.name}
</option>
))}
</optgroup>
))}
</>
);
}

View file

@ -1,11 +1,14 @@
"use client";
import React, { type FormEvent, useState } from "react";
import type { CreateRoomInput, FloorDto, RoomDto } from "../types";
import type { BuildingDto, CreateRoomInput, RoomDto } from "../types";
import { FloorSelectOptions, type FloorOption } from "./floor-select-options";
import { FormModal } from "./form-modal";
interface RoomModalProps {
floors: FloorDto[];
/** When given, the floor select groups floors by building. */
buildings?: ReadonlyArray<Pick<BuildingDto, "id" | "name">>;
floors: ReadonlyArray<FloorOption>;
initialRoom?: RoomDto;
initialValues?: Partial<CreateRoomInput>;
isSaving: boolean;
@ -15,6 +18,7 @@ interface RoomModalProps {
}
export function RoomModal({
buildings,
floors,
initialRoom,
initialValues,
@ -83,7 +87,7 @@ export function RoomModal({
value={floorId}
>
<option value="">Ohne Etage</option>
{floors.map((floor) => <option key={floor.id} value={floor.id}>{floor.name}</option>)}
<FloorSelectOptions buildings={buildings} floors={floors} />
</select>
</div>
</div>

View file

@ -226,11 +226,24 @@ 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
@ -288,8 +301,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 {

View file

@ -1,5 +1,7 @@
import type {
BuildingDto,
CircuitListDto,
CreateBuildingInput,
CreateFloorInput,
CreateProjectDeviceInput,
CreateRoomInput,
@ -17,6 +19,7 @@ import type {
ProjectCommandResultDto,
ProjectDeviceCommandResultDto,
ProjectDeviceDto,
ProjectBuildingCommandResultDto,
ProjectFloorCommandResultDto,
ProjectHistoryStateDto,
ProjectRevisionPageDto,
@ -881,6 +884,61 @@ export function renumberCircuitSectionCommand(
);
}
export function listBuildings(projectId: string) {
return request<BuildingDto[]>(`/api/projects/${projectId}/buildings`);
}
export function createBuilding(
projectId: string,
input: CreateBuildingInput,
expectedRevision: number
) {
return request<ProjectBuildingCommandResultDto>(
`/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<ProjectBuildingCommandResultDto>(
`/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<ProjectCommandResultDto>(
`/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<FloorDto[]>(`/api/projects/${projectId}/floors`);
}
@ -894,7 +952,7 @@ export function createFloor(
`/api/projects/${projectId}/floors`,
{
method: "POST",
body: JSON.stringify({ ...input, expectedRevision }),
body: JSON.stringify(toFloorRequestBody(input, expectedRevision)),
}
);
}
@ -907,7 +965,7 @@ export function updateFloor(
) {
return request<ProjectFloorCommandResultDto>(`/api/projects/${projectId}/floors/${floorId}`, {
method: "PUT",
body: JSON.stringify({ ...input, expectedRevision }),
body: JSON.stringify(toFloorRequestBody(input, expectedRevision)),
});
}

View file

@ -0,0 +1,284 @@
// 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<BuildingDto, "id" | "name">;
type FloorLike = Pick<FloorDto, "id" | "name"> & {
buildingId?: string | null;
};
type RoomLike = Pick<RoomDto, "floorId">;
export interface FloorGroup<TFloor extends FloorLike = FloorLike> {
/** 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>
): 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<FloorLike>,
buildings: ReadonlyArray<BuildingLike>
): boolean {
const buildingIds = toIdSet(buildings);
return floors.some(
(floor) => resolveFloorBuildingId(floor, buildingIds) === null
);
}
export function hasRoomsWithoutFloor(
rooms: ReadonlyArray<RoomLike>,
floors: ReadonlyArray<FloorLike>
): 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<TFloor extends FloorLike>(
floors: ReadonlyArray<TFloor>,
buildings: ReadonlyArray<BuildingLike>
): FloorGroup<TFloor>[] {
const buildingIds = toIdSet(buildings);
const floorsByBuilding = new Map<string | null, TFloor[]>();
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<TFloor>[] = [];
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<TFloor extends FloorLike>(
floors: ReadonlyArray<TFloor>,
buildings: ReadonlyArray<BuildingLike>,
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<RoomLike>,
floors: ReadonlyArray<FloorLike>,
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<TRoom extends RoomLike>(
rooms: ReadonlyArray<TRoom>,
floors: ReadonlyArray<FloorLike>,
buildings: ReadonlyArray<BuildingLike>,
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<FloorLike>,
buildings: ReadonlyArray<BuildingLike>
): 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<RoomLike>,
floors: ReadonlyArray<FloorLike>,
buildings: ReadonlyArray<BuildingLike>,
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<FloorLike>,
buildings: ReadonlyArray<BuildingLike>
): Map<string | null, number> {
const buildingIds = toIdSet(buildings);
const counts = new Map<string | null, number>();
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<RoomLike>,
floors: ReadonlyArray<FloorLike>
): Map<string | null, number> {
const floorIds = toIdSet(floors);
const counts = new Map<string | null, number>();
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;
}
/** "EG · Haus A", "EG" (floor without building) or "Ohne Etage". */
export function describeRoomLocation(
room: RoomLike,
floors: ReadonlyArray<FloorLike>,
buildings: ReadonlyArray<BuildingLike>
): 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;
}

View file

@ -46,6 +46,9 @@ const commandTypeLabels: Record<string, string> = {
"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",