diff --git a/backend/app/api/library.py b/backend/app/api/library.py index 3ec8c23..800d025 100644 --- a/backend/app/api/library.py +++ b/backend/app/api/library.py @@ -8,11 +8,12 @@ from fastapi import APIRouter, Depends from fastapi.responses import JSONResponse from psycopg import Connection +from app.access.policy import parse_query_context, require_case, require_matter from app.access.roles import room_role from app.api.deps import Principal, get_conn, get_principal from app.api.schemas import BatchShareIn from app.core.errors import forbidden -from app.library import case_items, matter_items, room_contents, room_effect +from app.library import case_items, case_outline, matter_items, matter_outline, room_contents, room_effect from app.ops import share_with_room router = APIRouter() @@ -97,3 +98,22 @@ def share_many( "access": body.access, "effect": room_effect(conn, room_id, principal.account_id, body.access), } + + +@router.get("/api/v1/cases/{case_id}/outline") +def case_outline_view(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + case, _rights = require_case(conn, principal.account_id, case_id, "read") + return JSONResponse(case_outline(conn, principal.account_id, case), headers=_NO_STORE) + + +@router.get("/api/v1/matters/{matter_id}/outline") +def matter_outline_view( + matter_id: UUID, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + context = parse_query_context(context_kind, context_id) + matter, _rights = require_matter(conn, principal.account_id, matter_id, context, "read") + return JSONResponse(matter_outline(conn, principal.account_id, matter, context), headers=_NO_STORE) diff --git a/backend/app/library.py b/backend/app/library.py index 87e3d32..10622d6 100644 --- a/backend/app/library.py +++ b/backend/app/library.py @@ -20,7 +20,7 @@ from app.access.policy import ( matter_rights, room_name, ) -from app.present import case_summary, matter_summary +from app.present import _chapters, _matter_tree, case_summary, matter_summary def shared_rooms(conn, kind: str, resource_id: UUID) -> list[dict]: @@ -124,3 +124,47 @@ def room_effect(conn, room_id: UUID, actor: UUID, access: str) -> list[dict]: } ) return effect + + +def case_outline(conn, actor: UUID, case: dict) -> dict: + """What the navigation tree shows below a case. Only readable entries; no bindings or texts.""" + chapters = _chapters(conn, "case", case["id"], case.get("content_order") or "position", case.get("content_order_dir") or "asc") + subcases = [] + for row in conn.execute( + "SELECT * FROM cases WHERE parent_case_id = %s AND deleted_at IS NULL ORDER BY title, id", + (case["id"],), + ).fetchall(): + if case_rights(conn, actor, row).read: + subcases.append({"id": str(row["id"]), "title": row["title"], "status": row["record_status"]}) + linked = [] + for link in conn.execute( + """ + SELECT m.* FROM matter_case_links l JOIN matters m ON m.id = l.matter_id + WHERE l.case_id = %s AND m.deleted_at IS NULL ORDER BY m.title, m.id + """, + (case["id"],), + ).fetchall(): + if matter_rights(conn, actor, link, Ctx("case", case["id"])).read: + linked.append(link) + return { + "kind": "case", + "id": str(case["id"]), + "chapters": chapters, + "subcases": subcases, + "matters": _matter_tree(conn, actor, case["id"], linked), + } + + +def matter_outline(conn, actor: UUID, matter: dict, context: Ctx | None) -> dict: + """What the navigation tree shows below a matter: its chapters and its readable Teilvorgänge.""" + chapters = _chapters( + conn, "matter", matter["id"], matter.get("content_order") or "position", matter.get("content_order_dir") or "asc" + ) + children = [] + for row in conn.execute( + "SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id", + (matter["id"],), + ).fetchall(): + if matter_rights(conn, actor, row, context).read: + children.append({"id": str(row["id"]), "title": row["title"], "status": row["record_status"]}) + return {"kind": "matter", "id": str(matter["id"]), "chapters": chapters, "submatters": children} diff --git a/backend/tests/test_library.py b/backend/tests/test_library.py index f11742a..7efe443 100644 --- a/backend/tests/test_library.py +++ b/backend/tests/test_library.py @@ -152,3 +152,52 @@ def _id(owner: Actor, person: Actor) -> str: with psycopg.connect(get_settings().dsn(), row_factory=psycopg.rows.dict_row) as conn: return str(conn.execute("SELECT id FROM auth_accounts WHERE email = %s", (person.email,)).fetchone()["id"]) + + +def test_the_outline_lists_only_what_the_person_may_read(world): + ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"] + case = ada.request("POST", "/api/v1/cases", json={"title": "Gliederung"}, status=201) + ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Schriftverkehr"}, status=201) + sub = ada.request( + "POST", "/api/v1/cases", + json={"title": "Unterakte", "parent_case_id": case["id"], "rights_mode": "inherit_parent"}, status=201, + ) + open_matter = matter_of(ada, "Offener Vorgang") + hidden_matter = matter_of(ada, "Verborgener Vorgang") + child = ada.request("POST", "/api/v1/matters", json={"title": "Teilvorgang", "parent_matter_id": open_matter["id"]}, status=201) + ada.request("POST", f"/api/v1/matters/{open_matter['id']}/chapters", json={"title": "Belege"}, status=201) + _link(ada, open_matter["id"], case["id"]) + _link(ada, hidden_matter["id"], case["id"]) + _share(ada, "cases", case["id"], room) + ada.request( + "PUT", "/api/v1/exceptions", + json={"resource_kind": "matter", "resource_id": hidden_matter["id"], "context": {"kind": "case", "id": case["id"]}, "remove_read": True}, + ) + + mine = ada.request("GET", f"/api/v1/cases/{case['id']}/outline") + assert [c["title"] for c in mine["chapters"]] == ["Schriftverkehr"] + assert [c["title"] for c in mine["subcases"]] == ["Unterakte"] + # An exception in the case context hides the matter there for everyone, the owner included. + assert {m["title"] for m in mine["matters"]} == {"Offener Vorgang"} + seen = ben.request("GET", f"/api/v1/cases/{case['id']}/outline") + assert {m["title"] for m in seen["matters"]} == {"Offener Vorgang"} + assert [c["title"] for c in seen["matters"][0]["children"]] == ["Teilvorgang"] + assert sub["id"] in [c["id"] for c in seen["subcases"]] + + matter = ada.request("GET", f"/api/v1/matters/{open_matter['id']}/outline") + assert [c["title"] for c in matter["chapters"]] == ["Belege"] + assert [c["title"] for c in matter["submatters"]] == ["Teilvorgang"] + in_case = ben.request( + "GET", f"/api/v1/matters/{open_matter['id']}/outline", + params={"context_kind": "case", "context_id": case["id"]}, + ) + assert [c["title"] for c in in_case["submatters"]] == ["Teilvorgang"] + ben.request("GET", f"/api/v1/matters/{open_matter['id']}/outline", status=404) + assert child["title"] == "Teilvorgang" + + unknown = "00000000-0000-4000-8000-000000000000" + seen_status = dan.request("GET", f"/api/v1/cases/{case['id']}/outline", status=404) + missing = dan.request("GET", f"/api/v1/cases/{unknown}/outline", status=404) + assert seen_status["detail"] == missing["detail"] + dan.request("GET", f"/api/v1/matters/{open_matter['id']}/outline", status=404) + assert cem.request("GET", f"/api/v1/cases/{case['id']}/outline")["id"] == case["id"] diff --git a/docs/architecture/API_REFERENZ.md b/docs/architecture/API_REFERENZ.md index b16110d..c1cf502 100644 --- a/docs/architecture/API_REFERENZ.md +++ b/docs/architecture/API_REFERENZ.md @@ -75,6 +75,7 @@ Legende Spalte „Auth“: **–** öffentlich, **S** gültige Session, **S+R** | GET | `/api/v1/rooms/overview` | S+R | Räume der Person als Kacheln: Rolle, Eigentümer, Zahl der Mitglieder und der lesbaren Akten und Vorgänge; Mitgliedernamen nur für Verwalter | | GET | `/api/v1/rooms/{id}/contents` | S+R, Mitglied | Akten und Vorgänge, die mit dem Raum geteilt und für die Person lesbar sind, mit Zählern | | POST | `/api/v1/rooms/{id}/shares` | S+R, Mitglied | mehrere eigene Einträge auf einmal mit dem Raum teilen (alle oder keiner); Antwort nennt die Wirkung je Mitglied | +| GET | `/api/v1/cases/{id}/outline`, `/api/v1/matters/{id}/outline` | S+R | Struktur für den Navigationsbaum: Kapitel, Unterakten und Vorgänge bzw. Teilvorgänge, nur aus Lesbarem; für Vorgänge optional `context_kind=case&context_id=` | | GET | `/api/v1/team` | S+R, Hauptnutzer | Personen in den eigenen Räumen mit Rolle je Raum; `mine` = selbst eingeladen | | PATCH | `/api/v1/team/{id}` | S+R, Hauptnutzer | `status` eines selbst eingeladenen Mitarbeiters; fremde und unbekannte ID: 403 | | POST | `/api/v1/team/{id}/password-reset` | S+R, Hauptnutzer | Einmal-Passwort für einen selbst eingeladenen Mitarbeiter | diff --git a/docs/architecture/BENUTZERVERWALTUNG.md b/docs/architecture/BENUTZERVERWALTUNG.md index 2ed6ea4..b5208f0 100644 --- a/docs/architecture/BENUTZERVERWALTUNG.md +++ b/docs/architecture/BENUTZERVERWALTUNG.md @@ -85,3 +85,12 @@ MFA (später optional für alle Konten), Leerlaufablauf und Rotation der Sitzung ### Vorbereitung Subscription `backend/app/access/limits.py` ist die einzige Stelle für Grenzen. `ensure_can_create_room(conn, owner_id)` läuft beim Anlegen eines Raums, `ensure_can_add_member(conn, owner_id, room_id)` beim Aufnehmen, Einladen und Annehmen einer Einladung. Heute lassen beide alles zu. Das Kontingentsubjekt ist der Eigentümer des Raums, ein Hauptnutzer, wie der Verein bei Shinkan (Entitlements-Blueprint). Vorgesehene Messgrößen: aktive Mitarbeiter je Hauptnutzer und je Raum, aus der Datenbank gezählt. Der Betreiber setzt den Plan. Zahlungsdienst und Tarife gehören nicht in diese Stufe. Offene Entscheidung: Ein Mitarbeiter, den ein zweiter Hauptnutzer als bestehendes Konto aufnimmt, zählt beim Raum-Eigentümer; die Zuständigkeit bei Grenzen klärt das Tarifkonzept. + +### Ein Navigationsbaum für Ablage, Akten und Vorgänge (seit 23.10.2026) + +Der Baum „Meine Ablage“ steht links auf den Listenseiten und auf den Seiten von Akte und Vorgang. Die frühere Spalte „Struktur“ ist darin aufgegangen. + +- **Aufklappen mit Fokus:** Ein Klick auf eine Akte oder einen Vorgang öffnet ihn und klappt seine Struktur auf. Der Pfad dorthin bleibt offen, die aktuelle Zeile (auch ein Kapitel) ist hervorgehoben. Nach dem Neuladen der Seite stimmt der Fokus wieder. +- **Unter einer Akte:** Überblick, „Direkt in dieser Akte“, Kapitel mit Unterkapiteln, Unterakten und die Vorgänge der Akte. **Unter einem Vorgang:** „Alle Inhalte“, Kapitel, Teilvorgänge. „Neues Kapitel“ und die Pfeile zum Verschieben stehen im Baum, solange der Eintrag offen ist. +- **Direkt von Vorgang zu Vorgang:** Ein Vorgang erscheint unter jeder Akte, in der er liegt, und unter „Vorgänge“. Ein Klick unter einer Akte öffnet ihn in diesem Aktenkontext, unter „Vorgänge“ ohne Akte. Die frühere Auswahl des Handlungskontexts entfällt. Querverweise und weitere Akten stehen unter dem Titel des Vorgangs. +- **Nachladen:** Die Wurzeln kommen aus `/cases` und `/matters`, die Struktur eines Knotens aus `GET /cases/{id}/outline` und `GET /matters/{id}/outline`, einmal beim Aufklappen. Die Antworten enthalten nur Lesbares (keine Inhalte). Ändert sich der offene Eintrag (Kapitel, Unterakte, Vorgang), lädt der Baum seine Struktur neu. diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 18ddd75..b81fe3b 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -136,9 +136,9 @@ export function App() { } /> } /> } /> + } /> + } /> - } /> - } /> } /> } /> } /> diff --git a/frontend/src/library/LibraryLayout.jsx b/frontend/src/library/LibraryLayout.jsx index 623521a..e5622b6 100644 --- a/frontend/src/library/LibraryLayout.jsx +++ b/frontend/src/library/LibraryLayout.jsx @@ -1,11 +1,11 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react"; -import { NavLink, Outlet, useLocation, useSearchParams } from "react-router-dom"; +import { Outlet, useLocation } from "react-router-dom"; import { api } from "../api.js"; -import { SHARE_DRAG_TYPE, isEmployee, parseShareDrag, shareTargets } from "../admin/admin-core.js"; +import { isEmployee, shareTargets } from "../admin/admin-core.js"; import { ErrorNote } from "../pages/widgets.jsx"; import { SessionContext } from "../session.js"; -import { effectText, folderTree } from "./library-core.js"; -import { MiniIcon } from "./MiniIcon.jsx"; +import { effectText } from "./library-core.js"; +import { NavTree } from "./NavTree.jsx"; export const LibraryContext = createContext(null); @@ -15,129 +15,33 @@ export function useLibrary() { const PLURAL = { case: "cases", matter: "matters" }; -function TreeNodes({ nodes, children, hrefFor, parentKey, current, openIds, toggle }) { - return ( -
    - {nodes.map((node) => { - const kids = children.get(node.id) || []; - const open = openIds.has(node.id); - const selected = current === node.id; - return ( -
  • -
    - {kids.length ? ( - - ) : } - - - {node.title} - -
    - {open && kids.length ? ( - - ) : null} -
  • - ); - })} -
- ); +const outlineKey = (kind, id, contextId = "") => `${kind}:${id}:${contextId || ""}`; + +// A detail page tells the tree which entry is open and what can be done there. +// `actions` are read when a row is clicked, so they may close over the latest state. +export function useLibraryFocus(focus, actions) { + const library = useLibrary(); + const signature = JSON.stringify(focus || null); + useEffect(() => { + library?.setFocus(focus || null); + return () => library?.setFocus(null); + }, [signature]); + if (library) library.actionsRef.current = actions || {}; } -function TreeSection({ to, label, items, parentKey, folder, active }) { - const { roots, children } = folderTree(items || [], parentKey); - const [openIds, setOpenIds] = useState(() => new Set()); - const byId = new Map((items || []).map((item) => [item.id, item])); - // The path to the selected folder stays open. - const path = new Set(); - for (let node = byId.get(folder); node; node = node[parentKey] ? byId.get(node[parentKey]) : null) path.add(node[parentKey]); - const shown = new Set([...openIds, ...path]); - const toggle = (id) => - setOpenIds((current) => { - const next = new Set(current); - if (next.has(id)) next.delete(id); - else next.add(id); - return next; - }); - return ( -
- - {label} - {(items || []).length} - - `${to}?ordner=${node.id}`} - current={active ? folder : ""} - openIds={shown} - toggle={toggle} - /> -
- ); -} - -function LibraryTree({ cases, matters, rooms, onDropOnRoom, employee }) { - const location = useLocation(); - const [params] = useSearchParams(); - const folder = params.get("ordner") || ""; - const [over, setOver] = useState(""); - return ( - - ); -} - -// Frame of the library: folder tree on the left, tiles on the right, one place for data and messages. +// Frame of the library: one navigation tree on the left, the page on the right. export function LibraryLayout() { const { session } = useContext(SessionContext); const employee = isEmployee(session); const [data, setData] = useState({ cases: null, matters: null, rooms: null }); + const [outlines, setOutlines] = useState(() => new Map()); + const [focus, setFocus] = useState(null); const [error, setError] = useState(""); const [message, setMessage] = useState(""); const [treeOpen, setTreeOpen] = useState(false); const timer = useRef(null); + const actionsRef = useRef({}); + const pending = useRef(new Set()); const location = useLocation(); const reload = useCallback(async () => { @@ -155,8 +59,34 @@ export function LibraryLayout() { useEffect(() => { reload(); + setOutlines(new Map()); }, [reload, session.scope.id]); + // Outlines come on demand and stay in memory. `force` fetches again after a change. + const loadOutline = useCallback(async (kind, id, contextId = "", force = false) => { + const key = outlineKey(kind, id, contextId); + if (pending.current.has(key)) return; + if (!force && outlines.has(key)) return; + pending.current.add(key); + try { + const query = kind === "matter" && contextId ? `?context_kind=case&context_id=${contextId}` : ""; + const outline = await api(`/api/v1/${PLURAL[kind]}/${id}/outline${query}`); + setOutlines((current) => new Map(current).set(key, outline)); + } catch { + setOutlines((current) => new Map(current).set(key, { chapters: [], subcases: [], matters: [], submatters: [] })); + } finally { + pending.current.delete(key); + } + }, [outlines]); + + // The open entry changed (a chapter added, a matter moved): fetch its outline and the lists again. + const stamp = focus?.stamp || ""; + useEffect(() => { + if (!focus) return; + loadOutline(focus.kind, focus.id, focus.contextId || "", true); + reload(); + }, [stamp]); + useEffect(() => { setTreeOpen(false); }, [location.pathname, location.search]); @@ -195,6 +125,11 @@ export function LibraryLayout() { notify, share, unshare, + focus, + setFocus, + outlines, + loadOutline, + actionsRef, dropOnRoom: (payload, room) => share(payload.kind, { id: payload.id, title: payload.title }, room), targets: shareTargets(session.rooms), employee, @@ -207,7 +142,7 @@ export function LibraryLayout() { {treeOpen ? "Ordner ausblenden" : "Ordner anzeigen"}
diff --git a/frontend/src/library/MiniIcon.jsx b/frontend/src/library/MiniIcon.jsx index 01d7786..835951e 100644 --- a/frontend/src/library/MiniIcon.jsx +++ b/frontend/src/library/MiniIcon.jsx @@ -9,6 +9,13 @@ export function MiniIcon({ kind }) { ); } + if (kind === "plus") { + return ( + + + + ); + } if (kind === "chapter") { return ( diff --git a/frontend/src/library/NavTree.jsx b/frontend/src/library/NavTree.jsx new file mode 100644 index 0000000..054ecf2 --- /dev/null +++ b/frontend/src/library/NavTree.jsx @@ -0,0 +1,274 @@ +import { useEffect, useState } from "react"; +import { Link, NavLink } from "react-router-dom"; +import { SHARE_DRAG_TYPE, parseShareDrag } from "../admin/admin-core.js"; +import { useLibrary } from "./LibraryLayout.jsx"; +import { MiniIcon } from "./MiniIcon.jsx"; +import { + caseHref, + caseKey, + chapterTree, + focusKeys, + folderTree, + matterHref, + matterKey, + rowState, +} from "./library-core.js"; + +// One row of the navigation tree. A row with `load` fetches its outline when it opens. +function Row({ node, tree }) { + const library = useLibrary(); + const open = tree.isOpen(node.key); + const expandable = Boolean(node.expandable); + + useEffect(() => { + if (open && node.load) library.loadOutline(node.load.kind, node.load.id, node.load.contextId); + }, [open, node.key]); + + const className = `library-tree__link${node.current ? " is-current" : ""}${node.ancestor ? " is-ancestor" : ""}`; + const inner = ( + <> + + {node.title} + {node.count !== undefined ? {node.count} : null} + + ); + return ( +
  • +
    + {expandable ? ( + + ) :
    + {open && node.children ? : null} +
  • + ); +} + +function List({ nodes, tree }) { + if (!nodes.length) return null; + return ( +
      + {nodes.map((node) => )} +
    + ); +} + +// Builds the node descriptions from the lists, the loaded outlines and the focus of the page. +function buildNodes({ cases, matters, library, isOpen }) { + const { focus, outlines } = library; + const caseTree = folderTree(cases || [], "parent_case_id"); + const matterTreeAll = folderTree(matters || [], "parent_matter_id"); + + const chapterNodes = (tree, base, owner, ownerKind, contextId) => + tree.map(({ chapter, first, last, children }) => { + const state = rowState(focus, ownerKind, owner, contextId); + const href = ownerKind === "case" ? caseHref(owner, { kapitel: chapter.id }) : matterHref(owner, contextId, { kapitel: chapter.id }); + return { + key: `k:${chapter.id}:${contextId || ""}`, + icon: "chapter", + title: chapter.title, + href, + current: state.here && state.chapter === chapter.id, + expandable: children.length > 0, + moves: state.here && focus.canReorder ? { id: chapter.id, first, last } : null, + children: () => chapterNodes(children, base, owner, ownerKind, contextId), + }; + }); + + const addChapter = (owner, ownerKind, contextId) => { + const state = rowState(focus, ownerKind, owner, contextId); + if (!state.here || !focus.canEdit) return []; + return [{ + key: `add:${owner}:${contextId || ""}`, + icon: "plus", + title: state.chapter ? "Neues Unterkapitel" : "Neues Kapitel", + className: "library-tree__add", + onClick: () => library.actionsRef.current.addChapter?.(state.chapter), + }]; + }; + + function matterNode(item, contextId, subs) { + const key = matterKey(item.id, contextId); + const state = rowState(focus, "matter", item.id, contextId); + return { + key, + icon: "matter", + title: item.title, + href: matterHref(item.id, contextId), + current: state.whole && !isOpen(key), + ancestor: state.here, + expandable: true, + load: { kind: "matter", id: item.id, contextId }, + children: () => { + const outline = outlines.get(`matter:${item.id}:${contextId || ""}`); + if (!outline) return [{ key: `${key}:loading`, icon: "contents", title: "Wird geladen …", className: "library-tree__hint", onClick: () => {} }]; + const submatters = (outline.submatters || []).map((child) => matterNode(child, contextId, null)); + return [ + { key: `${key}:all`, icon: "contents", title: "Alle Inhalte", href: matterHref(item.id, contextId), current: state.whole }, + ...chapterNodes(chapterTree(outline.chapters || []), "", item.id, "matter", contextId), + ...submatters, + ...addChapter(item.id, "matter", contextId), + ]; + }, + }; + } + + function caseNode(item) { + const key = caseKey(item.id); + const state = rowState(focus, "case", item.id); + const kids = caseTree.children.get(item.id) || []; + return { + key, + icon: "case", + title: item.title, + href: caseHref(item.id), + current: state.whole && !isOpen(key), + ancestor: state.here, + expandable: true, + load: { kind: "case", id: item.id }, + children: () => { + const outline = outlines.get(`case:${item.id}:`); + if (!outline) return [{ key: `${key}:loading`, icon: "contents", title: "Wird geladen …", className: "library-tree__hint", onClick: () => {} }]; + const hasParts = (outline.subcases || []).length > 0 || (outline.matters || []).length > 0; + const rows = []; + if (hasParts) rows.push({ key: `${key}:over`, icon: "contents", title: "Überblick", href: caseHref(item.id, { bereich: "ueberblick" }), current: state.overview }); + rows.push({ key: `${key}:direct`, icon: "contents", title: "Direkt in dieser Akte", href: caseHref(item.id), current: state.whole }); + rows.push(...chapterNodes(chapterTree(outline.chapters || []), "", item.id, "case", "")); + rows.push(...kids.map(caseNode)); + rows.push(...(outline.matters || []).map((matter) => matterNode(matter, item.id, matter.children))); + rows.push(...addChapter(item.id, "case", "")); + return rows; + }, + }; + } + + return { + cases: caseTree.roots.map(caseNode), + matters: matterTreeAll.roots.map((item) => matterNode(item, "", null)), + }; +} + +function Section({ id, icon, label, count, nodes, tree, to }) { + const open = tree.isOpen(id); + return ( +
    +
    + + `library-tree__root${isActive ? " is-current" : ""}`}> + {label} + {count} + +
    + {open ? : null} +
    + ); +} + +export function NavTree({ cases, matters, rooms, employee, onDropOnRoom }) { + const library = useLibrary(); + const [opened, setOpened] = useState(() => new Set(["sec:cases", "sec:matters"])); + const [closed, setClosed] = useState(() => new Set()); + const [over, setOver] = useState(""); + const auto = focusKeys(library.focus, cases || [], matters || []); + + const tree = { + isOpen: (key) => { + if (closed.has(key)) return false; + return opened.has(key) || auto.has(key); + }, + toggle: (key) => { + const currently = tree.isOpen(key); + setOpened((current) => { + const next = new Set(current); + if (currently) next.delete(key); + else next.add(key); + return next; + }); + setClosed((current) => { + const next = new Set(current); + if (currently) next.add(key); + else next.delete(key); + return next; + }); + }, + }; + + // A new focus opens its path again, even if the person closed it before. + const focusId = library.focus ? `${library.focus.kind}:${library.focus.id}:${library.focus.contextId || ""}` : ""; + useEffect(() => { + if (!focusId) return; + setClosed((current) => { + const next = new Set(current); + for (const key of auto) next.delete(key); + return next; + }); + }, [focusId]); + + const nodes = buildNodes({ cases, matters, library, isOpen: tree.isOpen }); + + return ( + + ); +} + diff --git a/frontend/src/library/library-core.js b/frontend/src/library/library-core.js index 2b09e29..c94790e 100644 --- a/frontend/src/library/library-core.js +++ b/frontend/src/library/library-core.js @@ -104,3 +104,87 @@ export function addable(items, roomId) { export function roleHint(role) { return roleLabel(role); } + +// ---- Navigation tree: keys, the path that opens for the focused entry, chapters and links ---- + +export const caseKey = (id) => `c:${id}`; +export const matterKey = (id, contextId = "") => (contextId ? `m:${id}@${contextId}` : `m:${id}`); + +// Keys of all nodes that open so that the focused entry is visible: its sections, parents and itself. +export function focusKeys(focus, cases = [], matters = []) { + const keys = new Set(); + if (!focus) return keys; + const caseById = new Map(cases.map((item) => [item.id, item])); + const matterById = new Map(matters.map((item) => [item.id, item])); + const addCaseChain = (caseId) => { + keys.add("sec:cases"); + keys.add(caseKey(caseId)); + const seen = new Set(); + let current = caseById.get(caseId); + while (current && !seen.has(current.id)) { + seen.add(current.id); + keys.add(caseKey(current.id)); + current = current.parent_case_id ? caseById.get(current.parent_case_id) : null; + } + }; + if (focus.kind === "case") { + addCaseChain(focus.id); + } else if (focus.kind === "matter") { + const context = focus.contextId || ""; + if (context) addCaseChain(context); + else keys.add("sec:matters"); + keys.add(matterKey(focus.id, context)); + const seen = new Set(); + let current = matterById.get(focus.id); + while (current && current.parent_matter_id && !seen.has(current.id)) { + seen.add(current.id); + keys.add(matterKey(current.parent_matter_id, context)); + current = matterById.get(current.parent_matter_id); + } + } + return keys; +} + +// Chapters of one container as a tree. Each node knows its siblings for the move arrows. +export function chapterTree(chapters = [], parentId = "") { + const siblings = chapters.filter((chapter) => (chapter.parent_chapter_id || "") === parentId); + return siblings.map((chapter, index) => ({ + chapter, + first: index === 0, + last: index === siblings.length - 1, + children: chapterTree(chapters, chapter.id), + })); +} + +export function caseHref(id, extra = {}) { + const query = new URLSearchParams(extra).toString(); + return `/cases/${id}${query ? `?${query}` : ""}`; +} + +export function matterHref(id, contextId = "", extra = {}) { + const query = new URLSearchParams({ ...(contextId ? { context_kind: "case", context_id: contextId } : {}), ...extra }).toString(); + return `/matters/${id}${query ? `?${query}` : ""}`; +} + +// Which row is the current one for the focus. The container row is current only when nothing below it is selected. +export function rowState(focus, kind, id, contextId = "") { + const here = Boolean(focus) && focus.kind === kind && focus.id === id && (kind === "case" || (focus.contextId || "") === (contextId || "")); + return { + here, + chapter: here ? focus.chapterId || "" : "", + overview: here && kind === "case" ? Boolean(focus.overview) : false, + whole: here && !focus.chapterId && !focus.overview, + }; +} + +// A short signature of what the tree shows below an entry. A change reloads that outline. +export function outlineSignature(record) { + if (!record) return ""; + const chapters = (record.chapters || []).map((chapter) => `${chapter.id}:${chapter.title}:${chapter.position}:${chapter.parent_chapter_id || ""}`).join("|"); + const subcases = (record.subcases || []).map((item) => item.id).join(","); + const matters = []; + const walk = (nodes) => (nodes || []).forEach((node) => { matters.push(node.id); walk(node.children); }); + walk(record.matters); + const submatters = (record.submatters || []).map((item) => item.id).join(","); + return [record.id, record.title, chapters, subcases, matters.join(","), submatters].join("#"); +} diff --git a/frontend/src/library/library-core.test.mjs b/frontend/src/library/library-core.test.mjs index 6eaa9db..92c8701 100644 --- a/frontend/src/library/library-core.test.mjs +++ b/frontend/src/library/library-core.test.mjs @@ -61,3 +61,69 @@ test("only own entries that are not yet in the room can be added", () => { assert.deepEqual(addable(cases, "r1").map((c) => c.id), ["b", "d"]); assert.deepEqual(addable(cases, "r2").map((c) => c.id), ["a", "b", "d"]); }); + +import { caseHref, caseKey, chapterTree, focusKeys, matterHref, matterKey, outlineSignature, rowState } from "./library-core.js"; + +const allCases = [ + { id: "a", parent_case_id: null }, + { id: "b", parent_case_id: "a" }, +]; +const allMatters = [ + { id: "m1", parent_matter_id: null }, + { id: "m2", parent_matter_id: "m1" }, +]; + +test("the focus opens the path to a case, its parents and its section", () => { + assert.deepEqual([...focusKeys({ kind: "case", id: "b" }, allCases, allMatters)].sort(), ["c:a", "c:b", "sec:cases"]); + assert.equal(focusKeys(null, allCases, allMatters).size, 0); +}); + +test("a matter opens under its case context or under the matters section", () => { + const inCase = focusKeys({ kind: "matter", id: "m2", contextId: "b" }, allCases, allMatters); + assert.deepEqual([...inCase].sort(), ["c:a", "c:b", "m:m1@b", "m:m2@b", "sec:cases"]); + const alone = focusKeys({ kind: "matter", id: "m2", contextId: "" }, allCases, allMatters); + assert.deepEqual([...alone].sort(), ["m:m1", "m:m2", "sec:matters"]); + assert.equal(matterKey("x", "c"), "m:x@c"); + assert.equal(matterKey("x"), "m:x"); + assert.equal(caseKey("x"), "c:x"); +}); + +test("chapters become a tree that knows its first and last sibling", () => { + const chapters = [ + { id: "1", parent_chapter_id: null }, + { id: "2", parent_chapter_id: "1" }, + { id: "3", parent_chapter_id: "1" }, + { id: "4", parent_chapter_id: null }, + ]; + const tree = chapterTree(chapters); + assert.deepEqual(tree.map((n) => [n.chapter.id, n.first, n.last]), [["1", true, false], ["4", false, true]]); + assert.deepEqual(tree[0].children.map((n) => [n.chapter.id, n.first, n.last]), [["2", true, false], ["3", false, true]]); +}); + +test("links keep the case context of a matter", () => { + assert.equal(caseHref("a"), "/cases/a"); + assert.equal(caseHref("a", { kapitel: "k" }), "/cases/a?kapitel=k"); + assert.equal(matterHref("m", "a"), "/matters/m?context_kind=case&context_id=a"); + assert.equal(matterHref("m", "a", { kapitel: "k" }), "/matters/m?context_kind=case&context_id=a&kapitel=k"); + assert.equal(matterHref("m"), "/matters/m"); +}); + +test("a row is current only for its own context", () => { + const focus = { kind: "matter", id: "m", contextId: "a", chapterId: "" }; + assert.equal(rowState(focus, "matter", "m", "a").whole, true); + assert.equal(rowState(focus, "matter", "m", "b").here, false); + assert.equal(rowState(focus, "matter", "m", "").here, false); + assert.equal(rowState({ kind: "case", id: "a", overview: true }, "case", "a").overview, true); + assert.equal(rowState({ kind: "case", id: "a", chapterId: "k" }, "case", "a").whole, false); + assert.equal(rowState(null, "case", "a").here, false); +}); + +test("the outline signature changes with chapters, subcases and matters", () => { + const base = { id: "a", title: "T", chapters: [{ id: "1", title: "K", position: 1 }], subcases: [{ id: "s" }], matters: [{ id: "m", children: [{ id: "n", children: [] }] }] }; + const same = outlineSignature(base); + assert.equal(outlineSignature({ ...base }), same); + assert.notEqual(outlineSignature({ ...base, chapters: [...base.chapters, { id: "2", title: "L", position: 2 }] }), same); + assert.notEqual(outlineSignature({ ...base, subcases: [] }), same); + assert.notEqual(outlineSignature({ ...base, matters: [] }), same); + assert.equal(outlineSignature(null), ""); +}); diff --git a/frontend/src/library/library.css b/frontend/src/library/library.css index bea84ce..4c16e14 100644 --- a/frontend/src/library/library.css +++ b/frontend/src/library/library.css @@ -103,3 +103,17 @@ a.button.quiet { background: var(--surface2); border: 1px solid var(--border2); .mini-icon--room { color: var(--kind-room); } .library-tree__toggle { font-size: 14px; } .mark, .chip-popover .popover__button { display: inline-flex; align-items: center; gap: 5px; } + +/* Navigation tree below the entries */ +.library-tree__link.is-ancestor { font-weight: 700; } +.library-tree__add .library-tree__link, .library-tree__add button { color: var(--accent-dark); font-weight: 600; } +.library-tree__hint .library-tree__link { color: var(--text2); font-style: italic; } +.library-tree__moves { display: inline-flex; gap: 0; flex: none; } +.library-tree__moves button { min-height: 26px; width: 24px; padding: 0; font-size: 13px; background: transparent; color: var(--text2); border-radius: 6px; } +.library-tree__moves button:hover:not(:disabled) { background: var(--accent-light); color: var(--accent-dark); } +.library-tree button.library-tree__link { background: transparent; border: 0; justify-content: flex-start; text-align: left; width: 100%; } +.library__main .workspace { min-height: calc(100vh - 80px); } +.library__main > .page, .library__main > .workspace { max-width: none; } +.library-tree__list { min-width: 0; } +.library-tree__section > .library-tree__row > .library-tree__root { flex: 1; } +.mini-icon--plus { color: var(--accent-dark); } diff --git a/frontend/src/pages/Cases.jsx b/frontend/src/pages/Cases.jsx index 8bb8fd3..3958560 100644 --- a/frontend/src/pages/Cases.jsx +++ b/frontend/src/pages/Cases.jsx @@ -11,106 +11,11 @@ import { RoomShare } from "../admin/RoomShare.jsx"; import { writableRooms } from "../admin/admin-core.js"; import { ContentBoard, DateField, DirectionChoice, MarkdownEditor, ObjectMenu, OrderChoice, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, saveChapterOrder, writeSelection } from "./content.jsx"; import { ReadingPane } from "./ReadingPane.jsx"; -import { StructureNavigator, Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx"; +import { Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx"; +import { useLibraryFocus } from "../library/LibraryLayout.jsx"; +import { outlineSignature } from "../library/library-core.js"; import { NavIcon } from "./icons.jsx"; -function OutlineLink({ kind, title, to }) { - return ( - - {kind} - {title} - - ); -} - -function matterChapters(record, matterId) { - return (record.contained || []).find((item) => item.matter_id === matterId)?.chapters || []; -} - -function ChapterLinks({ chapters, scopeId, scope, chapterId, onChapter }) { - if (!chapters.length) return null; - return ( -
      - {chapters.map((chapter) => ( -
    • - -
    • - ))} -
    - ); -} - -function MatterBranch({ matter, caseId, scope, chapterId, record, onScope, onChapter }) { - const selected = scope === matter.id && !chapterId; - return ( -
  • -
    - - Öffnen -
    - - {matter.children?.length ? ( -
      - {matter.children.map((child) => ( - - ))} -
    - ) : null} -
  • - ); -} - -function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) { - const hasParent = Boolean(record.parent_case_id && record.parent_title); - return ( - - ); -} - function matterOrigin(group) { const kind = group.kind_label === "Teilvorgang" ? "Teilvorgang" : "Vorgang"; const parent = group.parent_title ? ` · Vorgang ${group.parent_title}` : ""; @@ -146,59 +51,6 @@ function mergedCaseItems(record, direction, caseId) { return [...dated, ...undated]; } -function matterNode(matter, caseId) { - const query = `?context_kind=case&context_id=${caseId}`; - return { - id: matter.id, - title: matter.title, - kind: matter.kind_label || "Vorgang", - href: `/matters/${matter.id}${query}`, - current: false, - children: (matter.children || []).map((child) => matterNode(child, caseId)), - }; -} - -function caseNodes(record, parentRecord) { - const self = { - id: record.id, - title: record.title, - kind: record.kind_label || "Akte", - href: null, - current: true, - children: [ - ...(record.subcases || []).map((item) => ({ - id: item.id, - title: item.title, - kind: "Unterakte", - href: `/cases/${item.id}`, - current: false, - children: [], - })), - ...(record.matters || []).map((matter) => matterNode(matter, record.id)), - ], - }; - if (!parentRecord) return [self]; - const siblings = (parentRecord.subcases || []).map((item) => (item.id === record.id ? self : { - id: item.id, - title: item.title, - kind: "Unterakte", - href: `/cases/${item.id}`, - current: false, - children: [], - })); - return [{ - id: parentRecord.id, - title: parentRecord.title, - kind: "Akte", - href: `/cases/${parentRecord.id}`, - current: false, - children: [ - ...(siblings.length ? siblings : [self]), - ...(parentRecord.matters || []).map((matter) => matterNode(matter, parentRecord.id)), - ], - }]; -} - export function CaseDetail() { const { id } = useParams(); const navigate = useNavigate(); @@ -208,7 +60,6 @@ export function CaseDetail() { const chapterId = overview ? "" : (params.get("kapitel") || ""); const entryId = params.get("eintrag") || ""; const [record, setRecord] = useState(null); - const [parentTree, setParentTree] = useState(null); const [error, setError] = useState(""); const [modal, setModal] = useState(""); const [chapterParentId, setChapterParentId] = useState(""); @@ -269,7 +120,6 @@ export function CaseDetail() { setModal(""); setDateDir("asc"); setStructureOpen(false); - setParentTree(null); api(`/api/v1/cases/${id}`).then((detail) => { if (!alive) return; pendingChapter.current = ""; @@ -280,19 +130,6 @@ export function CaseDetail() { return () => { alive = false; }; }, [id]); - useEffect(() => { - if (!record || record.id !== id || !record.parent_case_id) return undefined; - let alive = true; - api(`/api/v1/cases/${record.parent_case_id}`).then((parent) => { - if (alive) setParentTree(parent); - }).catch(() => { - if (alive) setParentTree(null); - }); - return () => { - alive = false; - }; - }, [record, id]); - useEffect(() => { if (!record || record.id !== id) return; const matterId = rawScope && !["all", "ueberblick", "direkt", "direct"].includes(rawScope) ? rawScope : ""; @@ -385,6 +222,25 @@ export function CaseDetail() { } } + useLibraryFocus( + record && record.id === id + ? { + kind: "case", + id, + chapterId: overview ? "" : chapterId, + overview, + canEdit: Boolean(record.rights?.edit), + canReorder: Boolean(record.rights?.edit) && (record.chapters || []).length > 1, + stamp: outlineSignature(record), + } + : null, + { addChapter: (parentId) => openChapter(parentId), moveChapter }, + ); + + useEffect(() => { + setView("contents"); + }, [chapterId, overview]); + if (error && !record) return
    ; if (!record) return

    Akte wird geladen …

    ; @@ -396,10 +252,6 @@ export function CaseDetail() { count: (record.bindings || []).filter((item) => item.chapter_id === chapter.id).length, })); const merged = mergedCaseItems(record, dateDir, id); - const contexts = [ - ...(parentTree ? [{ id: parentTree.id, label: parentTree.title }] : []), - { id: record.id, label: record.title }, - ]; const entry = overview ? null : ((record.bindings || []).find((item) => item.id === entryId) || null); const hasContained = Boolean(record.contained?.length); @@ -411,29 +263,6 @@ export function CaseDetail() { setStructureOpen={setStructureOpen} hasEntry={Boolean(entry) && !overview} listRef={listRef} - nav={( - { if (next !== id) navigate(`/cases/${next}`); }) : null} - nodes={caseNodes(record, parentTree)} - allLabel="Direkt in dieser Akte" - chapters={chapters} - chapterId={overview ? "" : chapterId} - allCount={(record.bindings || []).length} - overview={hasContained ? { active: overview, count: merged.length, onSelect: showOverview } : null} - chapterHeading={`Kapitel in ${record.title}`} - onChapter={chooseChapter} - onAddChapter={canEdit ? () => openChapter(chapterId) : null} - onAddRootChapter={canEdit ? () => openChapter("") : null} - canAddChapter={canEdit} - onMoveChapter={moveChapter} - canReorder={canEdit && chapters.length > 1} - links={[]} - onNavigate={() => setStructureOpen(false)} - onClose={width < 1500 ? () => setStructureOpen(false) : null} - /> - )} reader={entry ? (
    - {width < 1500 ? : null} {canEdit ? (
    - {width < 1500 ? : null} {canEdit ? (