Lass E-Mails ueber die Faecher finden und halte Kapitel sowie das Menue in der Akte an ihrem Ort.
Deploy Development / deploy (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 1m1s
Test Suite / smoke-dev (push) Successful in 1s
Test Suite / frontend-build (push) Successful in 5s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 10:59:03 +02:00
1 parent 3465ed57f6
commit 67d48378c9
11 files changed
+696 -160

No files matched your search

+15 -1
View File
@@ -17,6 +17,7 @@ from app.ops import create_external
from app.sources import (
clean_base_url,
delete_connector,
imap_mailboxes,
imap_messages,
list_connectors,
paperless_content,
@@ -88,14 +89,27 @@ def search_paperless(q: str = "", principal: Principal = Depends(get_principal),
return {"items": paperless_documents(conn, principal.account_id, q.strip())}
@router.get("/api/v1/sources/imap/mailboxes")
def list_mailboxes(
connector_id: UUID,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return {"items": imap_mailboxes(conn, principal.account_id, connector_id)}
@router.get("/api/v1/sources/imap/messages")
def search_mail(
connector_id: UUID,
q: str = "",
mailbox: str = "",
before: int | None = None,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return {"items": imap_messages(conn, principal.account_id, connector_id, q.strip())}
if before is not None and before < 1:
raise unprocessable("Die Seitenangabe ist ungültig.")
return imap_messages(conn, principal.account_id, connector_id, q.strip(), mailbox.strip(), before)
@router.post("/api/v1/sources/link", status_code=201)
+49 -28
View File
@@ -358,6 +358,32 @@ def matter_placements(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -
return items
def _contained_group(conn, actor: UUID, matter: dict, context: Ctx) -> dict | None:
matter_right = matter_rights(conn, actor, matter, context)
if not matter_right.read:
return None
return {
"matter_id": str(matter["id"]),
"title": matter["title"],
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
"version": matter["version"],
"rights": matter_right.as_dict(),
"chapters": _chapters(conn, "matter", matter["id"]),
"content_order": matter.get("content_order") or "position",
"content_order_dir": matter.get("content_order_dir") or "asc",
"bindings": _ordered_bindings(
conn,
actor,
"matter",
matter["id"],
context,
matter.get("content_order") or "position",
matter.get("content_order_dir") or "asc",
),
}
def _matter_node(row: dict) -> dict:
return {
"id": str(row["id"]),
@@ -461,7 +487,8 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
conn, actor, "case", case["id"], context, payload["content_order"], payload["content_order_dir"]
)
contained = []
for link in conn.execute(
seen_matters: set[UUID] = set()
linked_matters = conn.execute(
"""
SELECT m.*
FROM matter_case_links l
@@ -470,33 +497,27 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
ORDER BY m.title, m.id
""",
(case["id"],),
).fetchall():
matter_right = matter_rights(conn, actor, link, context)
if not matter_right.read:
continue
items = _ordered_bindings(
conn,
actor,
"matter",
link["id"],
context,
link.get("content_order") or "position",
link.get("content_order_dir") or "asc",
)
if not items:
continue
contained.append(
{
"matter_id": str(link["id"]),
"title": link["title"],
"version": link["version"],
"rights": matter_right.as_dict(),
"chapters": _chapters(conn, "matter", link["id"]),
"content_order": link.get("content_order") or "position",
"content_order_dir": link.get("content_order_dir") or "asc",
"bindings": items,
}
)
).fetchall()
for link in linked_matters:
block = [link]
if not link["parent_matter_id"]:
block.extend(
conn.execute(
"""
SELECT * FROM matters
WHERE parent_matter_id = %s AND deleted_at IS NULL
ORDER BY title, id
""",
(link["id"],),
).fetchall()
)
for matter in block:
if matter["id"] in seen_matters:
continue
seen_matters.add(matter["id"])
group = _contained_group(conn, actor, matter, context)
if group is not None:
contained.append(group)
payload["contained"] = contained
payload["tasks"] = []
payload["deadlines"] = []
+189 -38
View File
@@ -2,11 +2,14 @@
from __future__ import annotations
import base64
import imaplib
import json
import re
import ssl
from email.header import decode_header
from email.parser import BytesParser
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse
@@ -107,11 +110,37 @@ def paperless_documents(conn, owner_id: UUID, query: str) -> list[dict]:
return items
def imap_messages(conn, owner_id: UUID, connector_id: UUID, query: str) -> list[dict]:
def imap_mailboxes(conn, owner_id: UUID, connector_id: UUID) -> list[dict]:
row = _owned(conn, owner_id, connector_id)
if row["kind"] != "imap":
raise unprocessable("Das ist kein E-Mail-Konto.")
return _imap_list(row["settings"], row["secret"], query)
client = _imap_login(row["settings"], row["secret"])
try:
return _imap_mailboxes(client)
finally:
_imap_logout(client)
def imap_messages(
conn,
owner_id: UUID,
connector_id: UUID,
query: str,
mailbox: str,
before: int | None,
) -> dict:
row = _owned(conn, owner_id, connector_id)
if row["kind"] != "imap":
raise unprocessable("Das ist kein E-Mail-Konto.")
if any(char in mailbox for char in "\r\n\x00"):
raise unprocessable("Der Fachname ist ungültig.")
if len(query) > 200:
raise unprocessable("Die Suche ist zu lang.")
client = _imap_login(row["settings"], row["secret"])
try:
return _imap_page(client, mailbox, query, before)
finally:
_imap_logout(client)
def _owned(conn, owner_id: UUID, connector_id: UUID) -> dict:
@@ -329,43 +358,165 @@ def _imap_login(settings: dict, secret: str) -> imaplib.IMAP4:
raise unprocessable("Das Postfach ist nicht erreichbar.") from exc
def _imap_list(settings: dict, secret: str, query: str) -> list[dict]:
client = _imap_login(settings, secret)
PAGE_SIZE = 30
_LIST_LINE = re.compile(
r'^\((?P<flags>[^)]*)\)\s+(?P<delim>"(?:\\.|[^"])*"|NIL)\s+(?P<name>"(?:\\.|[^"])*"|\S+)\s*$'
)
def _imap_logout(client: imaplib.IMAP4) -> None:
try:
mailbox = settings.get("mailbox") or "INBOX"
status, _ = client.select(mailbox, readonly=True)
if status != "OK":
raise unprocessable("Das Postfach enthält dieses Fach nicht.")
status, data = client.search(None, "ALL")
if status != "OK" or not data or not data[0]:
return []
ids = data[0].split()[-25:]
needle = query.strip().lower()
items = []
for mid in reversed(ids):
status, fetched = client.fetch(mid, "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE MESSAGE-ID)])")
if status != "OK" or not fetched or not isinstance(fetched[0], tuple):
continue
header = BytesParser().parsebytes(fetched[0][1])
subject = _decode(header.get("Subject")) or "(ohne Betreff)"
sender = _decode(header.get("From"))
if needle and needle not in subject.lower() and needle not in sender.lower():
continue
message_id = (header.get("Message-ID") or f"uid:{mid.decode()}").strip()
items.append(
{
"id": message_id[:200],
"title": subject[:200],
"message_from": sender[:200],
"date": _decode(header.get("Date"))[:80],
}
)
return items
finally:
try:
client.logout()
except imaplib.IMAP4.error:
pass
client.logout()
except imaplib.IMAP4.error:
pass
def _imap_mailboxes(client: imaplib.IMAP4) -> list[dict]:
try:
status, data = client.list()
except imaplib.IMAP4.error as exc:
raise unprocessable("Die Fächer konnten nicht gelesen werden.") from exc
if status != "OK":
raise unprocessable("Die Fächer konnten nicht gelesen werden.")
items = []
seen: set[str] = set()
for raw in data or []:
parsed = _parse_list_line(raw)
if parsed is None or parsed["name"] in seen:
continue
seen.add(parsed["name"])
items.append(parsed)
items.sort(key=lambda item: (0 if item["name"].upper() == "INBOX" else 1, item["label"].casefold()))
return items
def _imap_page(client: imaplib.IMAP4, mailbox: str, query: str, before: int | None) -> dict:
folders = _imap_mailboxes(client)
chosen = mailbox or "INBOX"
match = next((item for item in folders if item["name"] == chosen), None)
if match is None or not match["selectable"]:
raise unprocessable("Dieses Fach gibt es in dem Konto nicht.")
try:
status, _ = client.select(chosen, readonly=True)
except imaplib.IMAP4.error as exc:
raise unprocessable("Dieses Fach lässt sich nicht öffnen.") from exc
if status != "OK":
raise unprocessable("Dieses Fach lässt sich nicht öffnen.")
status, data = _uid_search(client, query)
if status != "OK" or not data or not data[0]:
return {"mailbox": chosen, "items": [], "next_before": None}
uids = sorted(int(part) for part in data[0].split() if part.isdigit())
if before is not None:
uids = [uid for uid in uids if uid < before]
page = uids[-PAGE_SIZE:]
next_before = page[0] if len(uids) > PAGE_SIZE else None
items = []
for uid in reversed(page):
item = _fetch_header(client, uid, chosen)
if item is not None:
items.append(item)
return {"mailbox": chosen, "items": items, "next_before": next_before}
def _uid_search(client: imaplib.IMAP4, query: str):
needle = " ".join(query.split())
if not needle:
return client.uid("SEARCH", None, "ALL")
quoted = '"' + needle.replace("\\", "\\\\").replace('"', '\\"') + '"'
try:
if needle.isascii():
return client.uid("SEARCH", None, "OR", "SUBJECT", quoted, "FROM", quoted)
encoded = quoted.encode("utf-8")
return client.uid("SEARCH", "CHARSET", "UTF-8", "OR", "SUBJECT", encoded, "FROM", encoded)
except imaplib.IMAP4.error as exc:
raise unprocessable("Das Postfach kann diese Suche nicht ausführen. Blättere im Fach oder kürze den Suchtext.") from exc
def _fetch_header(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict | None:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE MESSAGE-ID)])")
except imaplib.IMAP4.error:
return None
if status != "OK" or not fetched or not isinstance(fetched[0], tuple):
return None
header = BytesParser().parsebytes(fetched[0][1])
subject = _decode(header.get("Subject")) or "(ohne Betreff)"
sender = _decode(header.get("From"))
message_id = (header.get("Message-ID") or f"uid:{mailbox}:{uid}").strip()
return {
"id": message_id[:200],
"uid": uid,
"title": subject[:200],
"message_from": sender[:200],
"document_on": _mail_date(header.get("Date")),
}
def _parse_list_line(raw) -> dict | None:
if not isinstance(raw, (bytes, str)) or not raw:
return None
text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
match = _LIST_LINE.match(text.strip())
if match is None:
return None
flags = {flag.lstrip("\\").casefold() for flag in match.group("flags").split() if flag}
delimiter = _unquote(match.group("delim"))
name = _unquote(match.group("name"))
if not name:
return None
label = "Posteingang" if name.upper() == "INBOX" else _decode_utf7(name)
depth = 0 if not delimiter or name.upper() == "INBOX" else name.count(delimiter)
return {
"name": name,
"label": label,
"delimiter": delimiter,
"depth": depth,
"selectable": "noselect" not in flags,
}
def _unquote(token: str) -> str:
if token == "NIL":
return ""
if len(token) >= 2 and token.startswith('"') and token.endswith('"'):
return token[1:-1].replace(r"\"", '"').replace(r"\\", "\\")
return token
def _decode_utf7(value: str) -> str:
if "&" not in value:
return value
parts: list[str] = []
index = 0
while index < len(value):
if value[index] != "&":
parts.append(value[index])
index += 1
continue
end = value.find("-", index)
if end < 0:
parts.append(value[index:])
break
if end == index + 1:
parts.append("&")
else:
chunk = value[index + 1:end].replace(",", "/")
padding = "=" * ((4 - len(chunk) % 4) % 4)
try:
parts.append(base64.b64decode(chunk + padding).decode("utf-16-be"))
except (ValueError, UnicodeDecodeError):
parts.append(value[index:end + 1])
index = end + 1
return "".join(parts)
def _mail_date(value: str | None) -> str | None:
if not value:
return None
try:
return parsedate_to_datetime(value).date().isoformat()
except (TypeError, ValueError, OverflowError):
return None
def _decode(value: str | None) -> str:
+131
View File
@@ -0,0 +1,131 @@
"""IMAP folders are browsed; search stays inside the open folder."""
from __future__ import annotations
import app.sources as sources
from tests.support import Actor, register
class FakeIMAP:
selects: list[str] = []
def __init__(self, *args, **kwargs):
pass
def login(self, username, secret):
assert secret == "Postfach-Geheim"
return "OK", [b"logged"]
def list(self):
return "OK", [
b'(\\HasNoChildren) "/" "INBOX"',
b'(\\HasNoChildren) "/" "&AMQ-nderungen"',
b'(\\Noselect \\HasChildren) "/" "[Gmail]"',
b'(\\HasNoChildren) "/" "[Gmail]/Gesendet"',
]
def select(self, mailbox, readonly=False):
assert readonly is True
FakeIMAP.selects.append(mailbox)
return "OK", [b"5"]
def uid(self, command, *args):
if command == "SEARCH":
if any(isinstance(arg, str) and "Einwendung" in arg for arg in args):
return "OK", [b"2"]
return "OK", [b"1 2 3 4 5"]
uid = int(args[0])
header = (
f"From: Ada Beispiel <ada@example.test>\r\n"
f"Subject: Nachricht {uid}\r\n"
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
f"Message-ID: <{uid}@example.test>\r\n"
).encode()
return "OK", [(b"body", header), b")"]
def logout(self):
return "BYE", [b""]
def _account(monkeypatch, actor: Actor) -> str:
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", FakeIMAP)
created = actor.request(
"POST",
"/api/v1/connectors",
json={
"kind": "imap",
"name": "Kanzlei",
"host": "imap.example.test",
"port": 993,
"username": "ada@example.test",
"password": "Postfach-Geheim",
"security": "ssl",
},
status=201,
)
return created["id"]
def test_mailboxes_are_named_and_inbox_comes_first(client, db, monkeypatch):
ada = Actor(client, "ada-mail@example.test", "Ada Post")
register(db, ada.email, ada.name)
ada.login()
account = _account(monkeypatch, ada)
listed = ada.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": account})
assert [item["label"] for item in listed["items"]] == ["Posteingang", "[Gmail]", "[Gmail]/Gesendet", "Änderungen"]
gmail = next(item for item in listed["items"] if item["name"] == "[Gmail]")
sent = next(item for item in listed["items"] if item["name"] == "[Gmail]/Gesendet")
assert gmail["selectable"] is False
assert sent["selectable"] is True
assert sent["depth"] == 1
def test_folder_pages_newest_first_and_search_stays_inside(client, db, monkeypatch):
ada = Actor(client, "ada-page@example.test", "Ada Seite")
register(db, ada.email, ada.name)
ada.login()
account = _account(monkeypatch, ada)
monkeypatch.setattr(sources, "PAGE_SIZE", 2)
FakeIMAP.selects = []
first = ada.request(
"GET",
"/api/v1/sources/imap/messages",
params={"connector_id": account, "mailbox": "[Gmail]/Gesendet"},
)
assert first["mailbox"] == "[Gmail]/Gesendet"
assert [item["title"] for item in first["items"]] == ["Nachricht 5", "Nachricht 4"]
assert first["items"][0]["document_on"] == "2024-05-02"
assert first["items"][0]["message_from"] == "Ada Beispiel <ada@example.test>"
assert first["next_before"] == 4
older = ada.request(
"GET",
"/api/v1/sources/imap/messages",
params={"connector_id": account, "mailbox": "[Gmail]/Gesendet", "before": first["next_before"]},
)
assert [item["title"] for item in older["items"]] == ["Nachricht 3", "Nachricht 2"]
found = ada.request(
"GET",
"/api/v1/sources/imap/messages",
params={"connector_id": account, "mailbox": "INBOX", "q": "Einwendung"},
)
assert [item["title"] for item in found["items"]] == ["Nachricht 2"]
assert found["next_before"] is None
ada.request(
"GET",
"/api/v1/sources/imap/messages",
params={"connector_id": account, "mailbox": "Geheim"},
status=422,
)
assert "Geheim" not in FakeIMAP.selects
def test_foreign_mailbox_stays_hidden(client, db, monkeypatch):
ada = Actor(client, "ada-own@example.test", "Ada Eigen")
ben = Actor(client, "ben-own@example.test", "Ben Fremd")
register(db, ada.email, ada.name)
register(db, ben.email, ben.name)
ada.login()
account = _account(monkeypatch, ada)
ben.login()
ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": account}, status=404)
ben.request("GET", "/api/v1/sources/imap/messages", params={"connector_id": account}, status=404)
+15
View File
@@ -396,6 +396,21 @@ def test_teilvorgang_keeps_its_parent_in_the_trail(client, db):
assert rows["Prüfung"]["kind_label"] == "Teilvorgang"
assert rows["Prüfung"]["parent_title"] == "Hauptvorgang"
assert rows["Hauptvorgang"]["kind_label"] == "Vorgang"
chapter = ada.request(
"POST",
f"/api/v1/matters/{child['id']}/chapters?context_kind=case&context_id={case['id']}",
json={"title": "Schriftverkehr"},
status=201,
)
_note(ada, "Einwendung", child, document_on="2024-05-02")
case_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
assert [item["title"] for item in case_view["matters"]] == ["Hauptvorgang"]
assert case_view["matters"][0]["children"][0]["title"] == "Prüfung"
contained = {item["title"]: item for item in case_view["contained"]}
assert contained["Prüfung"]["kind_label"] == "Teilvorgang"
assert contained["Prüfung"]["parent_title"] == "Hauptvorgang"
assert contained["Prüfung"]["chapters"][0]["id"] == chapter["id"]
assert contained["Prüfung"]["bindings"][0]["element"]["title"] == "Einwendung"
_PNG = bytes.fromhex(
+1 -1
View File
@@ -474,7 +474,7 @@ Die genaue Darstellung vollständig gesperrter Verweise ist durch Weglassen ents
| Element `external_ref` | bleiben in Paperless oder einer späteren Quelle | Tsumugu hält Quelle, externe ID, Anzeigetitel und die synchronisierten Felder | Tsumugu löscht die Referenz und die eigenen Beziehungen. Das Quelldokument bleibt. |
| Element `note` / `correspondence` | kein Medienobjekt, Text in `note_bodies` | fachliche Daten in Tsumugu | wie andere Elemente |
Erster Dateischnitt, Vorschlag der registrierten Profile: JPEG, PNG, WebP und PDF als Anhang. Größen und Quarantäne folgen den Defaults des Datei-Blueprints und dürfen im Produktprofil begründet angepasst werden. Video, Audio und E-Mail-Import sind nicht im MVP. Ein IMAP-Verweis kann später ein weiteres `external_ref` werden; im MVP gibt es dafür keinen Abruf.
Erster Dateischnitt, Vorschlag der registrierten Profile: JPEG, PNG, WebP und PDF als Anhang. Größen und Quarantäne folgen den Defaults des Datei-Blueprints und dürfen im Produktprofil begründet angepasst werden. Video, Audio und ein vollständiger E-Mail-Import sind nicht im MVP. Ein verbundenes IMAP-Konto wird über seine Fächer geblättert; die Suche ist nur ein Zusatz im geöffneten Fach. Der Verweis speichert Betreff, Absender und Datum, nicht die Nachricht.
Upload startet nur bei Bearbeitungsrecht am Zielkontext. Der Download nutzt den Readplan: Sessioncookie, geprüfter Scope, lesbare Einbindung, lesbares Asset, aktuelle Revision. Kein öffentlicher `/media`-Mount und keine Session in der URL.
+68 -41
View File
@@ -104,6 +104,53 @@ function OutlineLink({ kind, title, to }) {
);
}
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 (
<ul>
{chapters.map((chapter) => (
<li key={chapter.id}>
<button
type="button"
className={scope === scopeId && chapterId === chapter.id ? "hierarchy__row is-current" : "hierarchy__row"}
onClick={() => onChapter(scopeId, chapter.id)}
>
<span className="hierarchy__kind">Kapitel</span>
<strong>{chapter.title}</strong>
</button>
</li>
))}
</ul>
);
}
function MatterBranch({ matter, caseId, scope, chapterId, record, onScope, onChapter }) {
const selected = scope === matter.id && !chapterId;
return (
<li>
<div className="hierarchy__line">
<button type="button" className={selected ? "hierarchy__row is-current" : "hierarchy__row"} onClick={() => onScope(matter.id)}>
<span className="hierarchy__kind">{matter.kind_label || "Vorgang"}</span>
<strong>{matter.title}</strong>
</button>
<Link className="hierarchy__open" to={`/matters/${matter.id}?context_kind=case&context_id=${caseId}`}>Öffnen</Link>
</div>
<ChapterLinks chapters={matterChapters(record, matter.id)} scopeId={matter.id} scope={scope} chapterId={chapterId} onChapter={onChapter} />
{matter.children?.length ? (
<ul>
{matter.children.map((child) => (
<MatterBranch key={child.id} matter={child} caseId={caseId} scope={scope} chapterId={chapterId} record={record} onScope={onScope} onChapter={onChapter} />
))}
</ul>
) : null}
</li>
);
}
function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) {
const hasParent = Boolean(record.parent_case_id && record.parent_title);
return (
@@ -111,6 +158,7 @@ function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) {
<h2>Gliederung</h2>
<button type="button" className={scope === "all" ? "" : "quiet"} onClick={() => onScope("all")}>Alle Inhalte</button>
<button type="button" className={scope === "direct" && !chapterId ? "" : "quiet"} onClick={() => onScope("direct")}>Direkt in dieser Akte</button>
<ChapterLinks chapters={record.chapters || []} scopeId="direct" scope={scope} chapterId={chapterId} onChapter={onChapter} />
{hasParent ? (
<p className="hierarchy__parent">Übergeordnet: <Link to={`/cases/${record.parent_case_id}`}>Akte {record.parent_title}</Link></p>
) : null}
@@ -129,40 +177,7 @@ function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) {
<h3>Vorgänge</h3>
<ul className="hierarchy">
{record.matters.map((matter) => (
<li key={matter.id}>
<button type="button" className={scope === matter.id ? "hierarchy__row" : "hierarchy__row quiet"} onClick={() => onScope(matter.id)}>
<span className="hierarchy__kind">{matter.kind_label || "Vorgang"}</span>
<strong>{matter.title}</strong>
</button>
<Link className="muted" to={`/matters/${matter.id}?context_kind=case&context_id=${caseId}`}>Öffnen</Link>
{matter.children?.length ? (
<ul>
{matter.children.map((child) => (
<li key={child.id}>
<button type="button" className={scope === child.id ? "hierarchy__row" : "hierarchy__row quiet"} onClick={() => onScope(child.id)}>
<span className="hierarchy__kind">Teilvorgang</span>
<strong>{child.title}</strong>
</button>
</li>
))}
</ul>
) : null}
</li>
))}
</ul>
</>
) : null}
{scope === "direct" && record.chapters?.length ? (
<>
<h3>Kapitel</h3>
<ul className="hierarchy">
{record.chapters.map((chapter) => (
<li key={chapter.id}>
<button type="button" className={chapterId === chapter.id ? "hierarchy__row" : "hierarchy__row quiet"} onClick={() => onChapter(chapter.id)}>
<span className="hierarchy__kind">Kapitel</span>
<strong>{chapter.title}</strong>
</button>
</li>
<MatterBranch key={matter.id} matter={matter} caseId={caseId} scope={scope} chapterId={chapterId} record={record} onScope={onScope} onChapter={onChapter} />
))}
</ul>
</>
@@ -171,16 +186,27 @@ function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) {
);
}
function matterOrigin(group) {
const kind = group.kind_label === "Teilvorgang" ? "Teilvorgang" : "Vorgang";
const parent = group.parent_title ? ` · Vorgang ${group.parent_title}` : "";
return `Aus ${kind} ${group.title}${parent}`;
}
function chapterOrigin(base, chapters, chapterId) {
const title = (chapters || []).find((chapter) => chapter.id === chapterId)?.title;
return title ? `${base} · Kapitel ${title}` : base;
}
function mergedCaseItems(record, direction, caseId) {
const rows = [
...(record.bindings || []).map((binding) => ({
...binding,
origin: "Direkt in dieser Akte",
origin: chapterOrigin("Direkt in dieser Akte", record.chapters, binding.chapter_id),
readerHref: `/cases/${caseId}/items/${binding.id}`,
})),
...(record.contained || []).flatMap((group) => (group.bindings || []).map((binding) => ({
...binding,
origin: `Aus Vorgang ${group.title}`,
origin: chapterOrigin(matterOrigin(group), group.chapters, binding.chapter_id),
readerHref: `/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${caseId}`,
}))),
];
@@ -239,7 +265,7 @@ export function CaseDetail() {
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("matter")}>Vorgang anlegen und zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("assign")}>Vorhandenen Vorgang zuordnen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("subcase")}>Unterakte anlegen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("chapter")}>Kapitel anlegen</button> : null}
{record.rights.edit ? <button type="button" className="quiet" onClick={() => setModal("chapter")}>{group ? "Kapitel in diesem Vorgang anlegen" : "Kapitel anlegen"}</button> : null}
{record.rights.share || record.is_owner ? <button type="button" className="quiet" onClick={() => setModal("share")}>Teilen</button> : null}
</ObjectMenu>
</div>
@@ -255,7 +281,7 @@ export function CaseDetail() {
scope={scope}
chapterId={chapterId}
onScope={(next) => { setScope(next); setChapterId(""); setView("contents"); setOutlineOpen(false); }}
onChapter={(next) => { setChapterId(next); setScope("direct"); setView("contents"); setOutlineOpen(false); }}
onChapter={(nextScope, nextChapter) => { setScope(nextScope); setChapterId(nextChapter); setView("contents"); setOutlineOpen(false); }}
/>
</div>
</aside>
@@ -295,6 +321,7 @@ export function CaseDetail() {
context={context}
containerKind="matter"
containerId={group.matter_id}
onlyChapter={chapterId}
onChange={load}
itemHref={(binding) => `/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${id}`}
/>
@@ -340,14 +367,14 @@ export function CaseDetail() {
<Modal open={modal === "paperless"} title="Aus Paperless" onClose={() => setModal("")}>
<PaperlessPicker context={context} placement={addPlacement} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "mail"} title="E-Mail verbinden" onClose={() => setModal("")}>
<Modal open={modal === "mail"} title="E-Mail verbinden" wide onClose={() => setModal("")}>
<MailPicker context={context} placement={addPlacement} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "subcase"} title="Unterakte anlegen" onClose={() => setModal("")}>
<NewSubcase parentId={id} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "chapter"} title="Kapitel anlegen" onClose={() => setModal("")}>
<ChapterForm path={`/api/v1/cases/${id}/chapters`} onChange={() => { setModal(""); load(); }} />
<Modal open={modal === "chapter"} title={group ? "Kapitel im Vorgang" : "Kapitel anlegen"} onClose={() => setModal("")}>
<ChapterForm path={group ? `/api/v1/matters/${group.matter_id}/chapters?context_kind=case&context_id=${id}` : `/api/v1/cases/${id}/chapters`} onChange={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "share"} title="Teilen" onClose={() => setModal("")}>
<ShareBox path={`/api/v1/cases/${id}/grants`} grants={record.grants || []} onChange={load} />
+1 -1
View File
@@ -254,7 +254,7 @@ export function MatterDetail() {
<Modal open={modal === "paperless"} title="Aus Paperless" onClose={() => setModal("")}>
<PaperlessPicker context={rightsContext} placement={placement} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "mail"} title="E-Mail verbinden" onClose={() => setModal("")}>
<Modal open={modal === "mail"} title="E-Mail verbinden" wide onClose={() => setModal("")}>
<MailPicker context={rightsContext} placement={placement} onDone={() => { setModal(""); load(); }} />
</Modal>
<Modal open={modal === "submatter"} title="Teilvorgang anlegen" onClose={() => setModal("")}>
+138 -26
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api } from "../api.js";
import { formatDate } from "./content.jsx";
import { ErrorNote } from "./widgets.jsx";
export function Sources() {
@@ -197,8 +198,13 @@ export function PaperlessPicker({ context, placement, onDone }) {
export function MailPicker({ context, placement, onDone }) {
const [accounts, setAccounts] = useState([]);
const [accountId, setAccountId] = useState("");
const [folders, setFolders] = useState([]);
const [mailbox, setMailbox] = useState("");
const [draft, setDraft] = useState("");
const [query, setQuery] = useState("");
const [items, setItems] = useState([]);
const [nextBefore, setNextBefore] = useState(null);
const [loading, setLoading] = useState("");
const [error, setError] = useState("");
useEffect(() => {
@@ -211,18 +217,94 @@ export function MailPicker({ context, placement, onDone }) {
.catch((err) => setError(err.message));
}, []);
useEffect(() => {
if (!accountId) return undefined;
let alive = true;
setFolders([]);
setMailbox("");
setItems([]);
setError("");
setLoading("Fächer werden gelesen …");
api(`/api/v1/sources/imap/mailboxes?connector_id=${accountId}`)
.then((data) => {
if (!alive) return;
const list = data.items || [];
setFolders(list);
const preferred = list.find((item) => item.selectable && item.name.toUpperCase() === "INBOX")
|| list.find((item) => item.selectable);
setMailbox(preferred ? preferred.name : "");
if (!preferred) setLoading("");
})
.catch((err) => {
if (!alive) return;
setLoading("");
setError(err.message);
});
return () => {
alive = false;
};
}, [accountId]);
useEffect(() => {
if (!accountId || !mailbox) return undefined;
let alive = true;
setQuery("");
setDraft("");
setItems([]);
setNextBefore(null);
setError("");
setLoading("Nachrichten werden gelesen …");
const params = new URLSearchParams({ connector_id: accountId, mailbox });
api(`/api/v1/sources/imap/messages?${params}`)
.then((data) => {
if (!alive) return;
setItems(data.items || []);
setNextBefore(data.next_before ?? null);
setLoading("");
})
.catch((err) => {
if (!alive) return;
setLoading("");
setError(err.message);
});
return () => {
alive = false;
};
}, [accountId, mailbox]);
async function search(event) {
event.preventDefault();
if (!accountId) {
setError("Lege zuerst ein E-Mail-Konto unter Quellen an.");
return;
}
if (!accountId || !mailbox) return;
setError("");
setLoading("Nachrichten werden gelesen …");
const params = new URLSearchParams({ connector_id: accountId, mailbox });
if (draft.trim()) params.set("q", draft.trim());
try {
const data = await api(`/api/v1/sources/imap/messages?connector_id=${accountId}&q=${encodeURIComponent(query)}`);
setItems(data.items);
const data = await api(`/api/v1/sources/imap/messages?${params}`);
setQuery(draft.trim());
setItems(data.items || []);
setNextBefore(data.next_before ?? null);
} catch (err) {
setError(err.message);
} finally {
setLoading("");
}
}
async function older() {
if (!nextBefore) return;
setError("");
setLoading("Ältere Nachrichten werden gelesen …");
const params = new URLSearchParams({ connector_id: accountId, mailbox, before: String(nextBefore) });
if (query) params.set("q", query);
try {
const data = await api(`/api/v1/sources/imap/messages?${params}`);
setItems((current) => [...current, ...(data.items || [])]);
setNextBefore(data.next_before ?? null);
} catch (err) {
setError(err.message);
} finally {
setLoading("");
}
}
@@ -237,6 +319,7 @@ export function MailPicker({ context, placement, onDone }) {
external_id: item.id,
context,
...(placement ? { placement } : {}),
...(item.document_on ? { dates: { document_on: item.document_on, sent_on: null, received_on: null } } : {}),
...(item.message_from ? { detail: { message_from: item.message_from } } : {}),
},
});
@@ -248,28 +331,57 @@ export function MailPicker({ context, placement, onDone }) {
return (
<div className="stack">
<form onSubmit={search} className="stack">
<label>
Konto
<select value={accountId} onChange={(event) => setAccountId(event.target.value)}>
{accounts.length ? null : <option value="">Kein Konto</option>}
{accounts.map((item) => (
<option key={item.id} value={item.id}>{item.name}</option>
<label>
Konto
<select value={accountId} onChange={(event) => setAccountId(event.target.value)}>
{accounts.length ? null : <option value="">Kein Konto</option>}
{accounts.map((item) => (
<option key={item.id} value={item.id}>{item.name}</option>
))}
</select>
</label>
{!accounts.length ? <p className="muted">Lege zuerst ein E-Mail-Konto unter <Link to="/sources">Quellen</Link> an.</p> : null}
<div className="mailbox">
<nav className="mailbox__folders" aria-label="Fächer">
{folders.map((folder) => (
folder.selectable ? (
<button
key={folder.name}
type="button"
className={folder.name === mailbox ? "" : "quiet"}
style={{ paddingLeft: 12 + folder.depth * 14 }}
aria-current={folder.name === mailbox ? "true" : undefined}
onClick={() => setMailbox(folder.name)}
>
{folder.label}
</button>
) : (
<span key={folder.name} className="mailbox__group" style={{ paddingLeft: 12 + folder.depth * 14 }}>{folder.label}</span>
)
))}
</nav>
<div className="mailbox__messages">
<form onSubmit={search} className="inline">
<input value={draft} onChange={(event) => setDraft(event.target.value)} placeholder="Im gewählten Fach suchen" aria-label="Im gewählten Fach suchen" />
<button type="submit" className="quiet" disabled={!mailbox || !!loading}>Suchen</button>
</form>
<ErrorNote error={error} />
{accountId && !loading && !mailbox && !error ? <p className="muted">Dieses Konto hat keine lesbaren Fächer.</p> : null}
{loading ? <p className="muted">{loading}</p> : null}
{!loading && mailbox && !items.length ? (
<p className="muted">{query ? "In diesem Fach gibt es dazu keine Nachricht." : "In diesem Fach gibt es keine Nachricht."}</p>
) : null}
<div className="mail-list">
{items.map((item) => (
<button key={`${mailbox}:${item.uid || item.id}`} type="button" className="mail-row" onClick={() => link(item)}>
<span>{formatDate(item.document_on)}</span>
<strong>{item.title}</strong>
<span>{item.message_from || "Ohne Absender"}</span>
</button>
))}
</select>
</label>
<div className="inline">
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Betreff oder Absender" />
<button type="submit">Abrufen</button>
</div>
{nextBefore ? <button type="button" className="quiet" onClick={older} disabled={!!loading}>Ältere laden</button> : null}
</div>
</form>
<ErrorNote error={error} />
<div className="stack">
{items.map((item) => (
<button key={item.id} type="button" className="quiet" onClick={() => link(item)}>
{item.title}{item.message_from ? ` · ${item.message_from}` : ""}
</button>
))}
</div>
</div>
);
+37 -20
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, fetchFile, fetchPaperless } from "../api.js";
import { Modal } from "./Modal.jsx";
import { ErrorNote } from "./widgets.jsx";
export function formatDate(value) {
@@ -103,11 +104,15 @@ function sectionsOf(chapters, bindings) {
loose.push(binding);
}
}
const sections = (chapters || [])
.filter((chapter) => (buckets.get(chapter.id) || []).length)
.map((chapter) => ({ id: chapter.id, title: chapter.title, items: buckets.get(chapter.id) }));
if (loose.length || !sections.length) {
sections.push({ id: "loose", title: sections.length ? "Ohne Kapitel" : "", items: loose });
const sections = (chapters || []).map((chapter) => ({
id: chapter.id,
title: chapter.title,
items: buckets.get(chapter.id) || [],
}));
if (sections.length && loose.length) {
sections.push({ id: "loose", title: "Ohne Kapitel", items: loose });
} else if (!sections.length) {
sections.push({ id: "loose", title: "", items: loose });
}
return sections;
}
@@ -138,16 +143,23 @@ export function Placements({ items }) {
}
export function ObjectMenu({ view, onView, children }) {
const [open, setOpen] = useState(false);
function choose(next) {
setOpen(false);
onView(next);
}
return (
<details className="object-menu">
<summary>Menü</summary>
<div className="stack">
<button type="button" className={view === "course" ? "" : "quiet"} onClick={() => onView("course")}>Fachlicher Verlauf</button>
<button type="button" className={view === "audit" ? "" : "quiet"} onClick={() => onView("audit")}>Änderungsprotokoll</button>
<button type="button" className={view === "links" ? "" : "quiet"} onClick={() => onView("links")}>Zuordnungen</button>
{children}
</div>
</details>
<>
<button type="button" className="quiet" onClick={() => setOpen(true)}>Menü</button>
<Modal open={open} title="Menü" onClose={() => setOpen(false)}>
<div className="menu-list" onClick={() => setOpen(false)}>
<button type="button" className={view === "course" ? "" : "quiet"} onClick={() => choose("course")}>Fachlicher Verlauf</button>
<button type="button" className={view === "audit" ? "" : "quiet"} onClick={() => choose("audit")}>Änderungsprotokoll</button>
<button type="button" className={view === "links" ? "" : "quiet"} onClick={() => choose("links")}>Zuordnungen</button>
{children}
</div>
</Modal>
</>
);
}
@@ -421,7 +433,7 @@ export function ContentBoard({
)}
{pending ? <p className="muted">Ordnung wird gespeichert …</p> : null}
<ErrorNote error={error} />
{source.length ? (
{source.length || chapters.length ? (
visibleSections.map((section) => (
<section
key={section.id}
@@ -431,6 +443,7 @@ export function ContentBoard({
onDrop={(event) => onDrop(event, section.id)}
>
{section.title ? <h3 className="chapter-title">{section.title}</h3> : null}
{section.title && !section.items.length ? <p className="muted">Noch nichts in diesem Kapitel.</p> : null}
<ol className="preview-list">
{section.items.map((binding, index) => {
const element = binding.element;
@@ -450,7 +463,7 @@ export function ContentBoard({
onDragStart={(event) => onDragStart(event, binding.id, section.id)}
onDragEnd={cancel}
>
Ziehen
<span className="handle__grip" aria-hidden="true" />
</button>
) : null}
<Thumb element={element} context={context} />
@@ -460,11 +473,15 @@ export function ContentBoard({
{text ? <span className="preview-row__text">{text}</span> : null}
{binding.origin ? <span className="preview-row__origin">{binding.origin}{binding.shared ? " · weitere Einbindung" : ""}</span> : null}
</Link>
{canSort && custom ? (
{canSort && (custom || chapters.length) ? (
<details className="row-menu">
<summary>Ordnen</summary>
<button type="button" aria-label={`${element.title} nach oben`} disabled={pending || index === 0} onClick={() => move(binding.id, -1)}>Nach oben</button>
<button type="button" aria-label={`${element.title} nach unten`} disabled={pending || index === section.items.length - 1} onClick={() => move(binding.id, 1)}>Nach unten</button>
<summary>{custom ? "Ordnen" : "Einordnen"}</summary>
{custom ? (
<>
<button type="button" aria-label={`${element.title} nach oben`} disabled={pending || index === 0} onClick={() => move(binding.id, -1)}>Nach oben</button>
<button type="button" aria-label={`${element.title} nach unten`} disabled={pending || index === section.items.length - 1} onClick={() => move(binding.id, 1)}>Nach unten</button>
</>
) : null}
{chapters.length ? (
<label>
In Kapitel einordnen
+52 -4
View File
@@ -410,7 +410,11 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
.trail__sep { color: var(--text3); }
.hierarchy { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 4px; }
.hierarchy ul { list-style: none; margin: 0; padding: 2px 0 2px 14px; border-left: 2px solid var(--border); display: grid; gap: 4px; }
.hierarchy__row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: baseline; min-height: 44px; padding: 4px 0; text-decoration: none; color: inherit; }
.hierarchy__line { display: flex; align-items: center; gap: 8px; }
.hierarchy__line .hierarchy__row { flex: 1; }
.hierarchy__open { flex: 0 0 auto; font-size: 13px; }
.hierarchy__row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: baseline; min-height: 36px; padding: 4px 8px; text-decoration: none; color: inherit; border-radius: 8px; }
.hierarchy__row.is-current { background: var(--accent-light); }
.hierarchy__kind { min-width: 7.2rem; color: var(--accent-dark); font-size: 12px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; }
.hierarchy__parent { margin-bottom: 8px; }
.order-bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
@@ -517,12 +521,53 @@ button.hierarchy__row { width: 100%; border: 0; background: transparent; text-al
color: var(--text2);
}
.thumb--pdf { pointer-events: none; }
.handle { min-width: 44px; min-height: 44px; cursor: grab; touch-action: none; }
.handle {
width: 28px;
min-width: 28px;
min-height: 44px;
padding: 0;
background: transparent;
color: var(--text3);
cursor: grab;
touch-action: none;
}
.handle:hover, .handle:focus-visible { background: var(--surface2); }
.handle__grip {
width: 10px;
height: 16px;
background-image: radial-gradient(currentColor 1.15px, transparent 1.25px);
background-size: 5px 5px;
}
.insert-line { height: 4px; background: var(--accent); border-radius: 2px; list-style: none; margin: 2px 0; }
.row-menu, .object-menu { font-size: 14px; }
.object-menu .stack, .row-menu { display: grid; gap: 6px; padding-top: 6px; }
.row-menu { font-size: 14px; }
.row-menu, .menu-list { display: grid; gap: 8px; }
.menu-list button { width: 100%; justify-content: flex-start; }
.placements { margin: 4px 0 0; overflow-wrap: anywhere; }
.reader-preview { display: block; max-width: 100%; height: auto; border: 1px solid var(--border); }
.mailbox { display: grid; grid-template-columns: minmax(9rem, 14rem) minmax(0, 1fr); gap: 16px; align-items: start; }
.mailbox__folders { display: grid; gap: 6px; align-content: start; }
.mailbox__folders button { justify-content: flex-start; text-align: left; width: 100%; }
.mailbox__group { min-height: 32px; display: flex; align-items: center; color: var(--text3); font-size: 13px; font-weight: 650; }
.mailbox__messages { display: grid; gap: 10px; min-width: 0; }
.mail-list { display: grid; }
.mail-row {
display: grid;
grid-template-columns: 6.5rem minmax(0, 1fr);
gap: 2px 12px;
width: 100%;
min-height: 58px;
padding: 8px 10px;
border: 0;
border-top: 1px solid var(--border);
border-radius: 0;
background: transparent;
color: inherit;
text-align: left;
font-weight: 500;
}
.mail-row strong { grid-column: 2; grid-row: 1; overflow-wrap: anywhere; }
.mail-row span:first-child { grid-column: 1; grid-row: 1 / span 2; color: var(--text2); font-size: 13px; }
.mail-row span:last-child { grid-column: 2; color: var(--text2); font-size: 13px; overflow-wrap: anywhere; }
@media (min-width: 900px) {
.record-layout { grid-template-columns: 240px minmax(0, 1fr); }
@@ -532,6 +577,9 @@ button.hierarchy__row { width: 100%; border: 0; background: transparent; text-al
.outline__body { display: none; }
.outline.is-open .outline__body { display: block; }
.outline__toggle { display: inline-flex; margin-bottom: 8px; }
.mailbox { grid-template-columns: 1fr; }
.mailbox__folders { grid-auto-flow: column; grid-auto-columns: max-content; overflow-x: auto; padding-bottom: 4px; }
.mailbox__folders button, .mailbox__group { width: auto; }
}
@media (prefers-color-scheme: dark) {