Unterscheide Eingang und Ausgang an der Einbindung und ermoegliche Umbenennen, Archivieren, Loeschen und Verschieben.
Deploy Development / deploy (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 1m4s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 8s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 18:30:26 +02:00
1 parent 20625b4596
commit ad6240a5da
27 files changed
+1191 -88

No files matched your search

+100
View File
@@ -43,6 +43,11 @@ from app.api.schemas import (
CaseLinkIn,
CasePatch,
ChapterDateIn,
ChapterDeleteIn,
ChapterTitleIn,
CommunicationIn,
MatterMoveIn,
RecordDeleteIn,
ChapterIn,
ChapterOrderIn,
CrossLinkIn,
@@ -100,8 +105,11 @@ from app.ops import (
create_matter,
create_note,
create_task,
delete_case,
delete_chapter,
delete_cross_link,
delete_element,
delete_matter,
detach_binding,
fulfill_deadline,
grant_access,
@@ -118,9 +126,12 @@ from app.ops import (
patch_task,
revoke_grant,
move_binding_chapter,
move_matter,
reorder_bindings,
rename_chapter,
reorder_chapters,
set_chapter_date,
set_communication_direction,
set_content_order,
set_exception,
unlink_matter_case,
@@ -688,6 +699,92 @@ def post_matter_chapter_order(
return {"version": version}
@router.patch("/api/v1/chapters/{chapter_id}/title")
def patch_chapter_title(
chapter_id: UUID,
body: ChapterTitleIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
version = rename_chapter(
conn, principal.account_id, chapter_id, body.expected_version, body.title, _ctx_model(body.context)
)
return {"version": version, "title": body.title}
@router.post("/api/v1/chapters/{chapter_id}/delete")
def post_delete_chapter(
chapter_id: UUID,
body: ChapterDeleteIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
version = delete_chapter(
conn, principal.account_id, chapter_id, body.expected_version, _ctx_model(body.context)
)
return {"version": version}
@router.post("/api/v1/cases/{case_id}/delete")
def post_delete_case(
case_id: UUID,
body: RecordDeleteIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
delete_case(conn, principal.account_id, case_id, body.expected_version)
return {"ok": True}
@router.post("/api/v1/matters/{matter_id}/delete")
def post_delete_matter(
matter_id: UUID,
body: RecordDeleteIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
delete_matter(conn, principal.account_id, matter_id, body.expected_version, _ctx_model(body.context))
return {"ok": True}
@router.post("/api/v1/matters/{matter_id}/move")
def post_move_matter(
matter_id: UUID,
body: MatterMoveIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
matter = move_matter(
conn,
principal.account_id,
matter_id,
body.expected_version,
_ctx_model(body.context),
body.case_id,
body.parent_matter_id,
body.clear_parent,
)
return matter_summary(conn, principal.account_id, matter)
@router.patch("/api/v1/bindings/{binding_id}/communication")
def patch_communication(
binding_id: UUID,
body: CommunicationIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
element = set_communication_direction(
conn,
principal.account_id,
binding_id,
body.expected_version,
body.direction,
_ctx_model(body.context),
)
return {"version": element["version"], "direction": body.direction}
@router.patch("/api/v1/chapters/{chapter_id}")
def patch_chapter_date(
chapter_id: UUID,
@@ -799,6 +896,7 @@ def post_note(body: NoteIn, principal: Principal = Depends(get_principal), conn:
body.dates.document_on if body.dates else None,
body.dates.sent_on if body.dates else None,
body.dates.received_on if body.dates else None,
body.communication_direction,
)
element = created["element"]
return _created(
@@ -899,6 +997,7 @@ def post_file(
document_on: str | None = Form(default=None),
sent_on: str | None = Form(default=None),
received_on: str | None = Form(default=None),
communication_direction: str | None = Form(default=None),
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
@@ -928,6 +1027,7 @@ def post_file(
settings.media_root,
settings.upload_max_bytes,
request.state.cleanup_files,
communication_direction if communication_direction in {"in", "out"} else None,
)
return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]})
+31
View File
@@ -93,6 +93,36 @@ class ChapterDateIn(APIModel):
context: ContextIn | None = None
class ChapterTitleIn(APIModel):
expected_version: int = Field(ge=1)
title: str = Field(min_length=1, max_length=200)
context: ContextIn | None = None
class ChapterDeleteIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn | None = None
class RecordDeleteIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn | None = None
class MatterMoveIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn | None = None
case_id: UUID | None = None
parent_matter_id: UUID | None = None
clear_parent: bool = False
class CommunicationIn(APIModel):
expected_version: int = Field(ge=1)
direction: Literal["in", "out"] | None = None
context: ContextIn | None = None
class MatterIn(APIModel):
title: str = Field(min_length=1, max_length=200)
parent_matter_id: UUID | None = None
@@ -146,6 +176,7 @@ class NoteIn(APIModel):
placement: ContextIn | None = None
chapter_id: UUID | None = None
dates: DatesIn | None = None
communication_direction: Literal["in", "out"] | None = None
class ContentOrderIn(APIModel):
+6 -1
View File
@@ -1,4 +1,4 @@
"""Bounded note documents. Only paragraph text is stored."""
"""Bounded note documents. Paragraphs or one Markdown block are stored."""
from __future__ import annotations
@@ -9,6 +9,11 @@ def clean_document(document: dict) -> dict:
blocks = document.get("blocks")
if not isinstance(blocks, list) or len(blocks) > 400:
raise unprocessable("Die Notiz hat kein gültiges Dokument.")
if len(blocks) == 1 and isinstance(blocks[0], dict) and blocks[0].get("type") == "markdown":
text = blocks[0].get("text")
if not isinstance(text, str) or len(text) > 100_000:
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
return {"version": 1, "blocks": [{"type": "markdown", "text": text}]}
clean = []
for block in blocks:
if not isinstance(block, dict) or set(block) - {"type", "text"}:
+169 -2
View File
@@ -257,6 +257,152 @@ def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_i
return row
def _binding_in_page(conn, binding: dict, context: Ctx) -> bool:
if binding["context_kind"] == context.kind and binding["context_id"] == context.id:
return True
if context.kind != "case" or binding["context_kind"] != "matter":
return False
current = binding["context_id"]
seen: set[UUID] = set()
while current and current not in seen:
seen.add(current)
link = conn.execute(
"SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
(current, context.id),
).fetchone()
if link is not None:
return True
parent = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone()
current = parent["parent_matter_id"] if parent else None
return False
def set_communication_direction(conn, actor: UUID, binding_id: UUID, expected: int, direction: str | None, context: Ctx | None) -> dict:
row = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
if row is None:
raise not_found()
page = context or Ctx(row["context_kind"], row["context_id"])
if context is not None and not _binding_in_page(conn, row, context):
raise not_found()
element, rights = require_element(conn, actor, row["element_id"], page, "edit")
if not rights.edit:
raise forbidden()
bump_version(conn, "elements", element["id"], expected)
store_direction(conn, row["id"], direction, True)
audit(conn, actor, element["home_scope_id"], "communication_direction", "element", element["id"], page)
return get_element(conn, element["id"])
def _chapter_container(conn, actor: UUID, chapter_id: UUID, context: Ctx | None):
chapter = conn.execute("SELECT * FROM chapters WHERE id = %s", (chapter_id,)).fetchone()
if chapter is None:
raise not_found()
if chapter["case_id"]:
container, _rights = require_case(conn, actor, chapter["case_id"], "edit")
kind = "case"
else:
container, _rights = require_matter(conn, actor, chapter["matter_id"], context, "edit")
kind = "matter"
return chapter, container, kind
def rename_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, title: str, context: Ctx | None) -> int:
chapter, container, kind = _chapter_container(conn, actor, chapter_id, context)
version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected)
conn.execute("UPDATE chapters SET title = %s WHERE id = %s", (title.strip(), chapter["id"]))
audit(conn, actor, container["home_scope_id"], "chapter_renamed", kind, container["id"], context)
return version
def delete_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, context: Ctx | None) -> int:
chapter, container, kind = _chapter_container(conn, actor, chapter_id, context)
version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected)
conn.execute("UPDATE bindings SET chapter_id = NULL WHERE chapter_id = %s", (chapter["id"],))
conn.execute("DELETE FROM chapters WHERE id = %s", (chapter["id"],))
audit(conn, actor, container["home_scope_id"], "chapter_deleted", kind, container["id"], context)
return version
def delete_case(conn, actor: UUID, case_id: UUID, expected: int) -> None:
case, rights = require_case(conn, actor, case_id, "edit")
if not rights.edit:
raise forbidden()
children = conn.execute(
"SELECT id FROM cases WHERE parent_case_id = %s AND deleted_at IS NULL",
(case_id,),
).fetchall()
links = conn.execute("SELECT id FROM matter_case_links WHERE case_id = %s", (case_id,)).fetchall()
if children or links:
raise unprocessable("Diese Akte enthält noch Unterakten oder Vorgänge. Verschiebe oder lösche sie zuerst.")
bump_version(conn, "cases", case_id, expected)
conn.execute("UPDATE cases SET deleted_at = now(), updated_at = now() WHERE id = %s", (case_id,))
audit(conn, actor, case["home_scope_id"], "case_deleted", "case", case_id, None)
def delete_matter(conn, actor: UUID, matter_id: UUID, expected: int, context: Ctx | None) -> None:
matter, _rights = require_matter(conn, actor, matter_id, context, "edit")
children = conn.execute(
"SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL",
(matter_id,),
).fetchall()
if children:
raise unprocessable("Dieser Vorgang enthält noch Teilvorgänge. Verschiebe oder lösche sie zuerst.")
bump_version(conn, "matters", matter_id, expected)
conn.execute("UPDATE matters SET deleted_at = now(), updated_at = now() WHERE id = %s", (matter_id,))
audit(conn, actor, matter["home_scope_id"], "matter_deleted", "matter", matter_id, context)
def _matter_parent_chain(conn, matter_id: UUID) -> set[UUID]:
seen: set[UUID] = set()
current = matter_id
while current and current not in seen:
seen.add(current)
row = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone()
current = row["parent_matter_id"] if row else None
return seen
def move_matter(
conn,
actor: UUID,
matter_id: UUID,
expected: int,
context: Ctx | None,
case_id: UUID | None,
parent_matter_id: UUID | None,
clear_parent: bool,
) -> dict:
matter, _rights = require_matter(conn, actor, matter_id, context, "edit")
if case_id is None and parent_matter_id is None and not clear_parent:
raise unprocessable("Es fehlt ein Ziel.")
bump_version(conn, "matters", matter_id, expected)
if clear_parent:
conn.execute("UPDATE matters SET parent_matter_id = NULL WHERE id = %s", (matter_id,))
if parent_matter_id is not None:
if parent_matter_id == matter_id or matter_id in _matter_parent_chain(conn, parent_matter_id):
raise unprocessable("Ein Vorgang kann nicht in sich selbst oder in einen eigenen Teilvorgang verschoben werden.")
parent_context = Ctx("case", case_id) if case_id is not None else context
parent, _parent_rights = require_matter(conn, actor, parent_matter_id, parent_context, "edit")
if parent["home_scope_id"] != matter["home_scope_id"]:
raise unprocessable("Der Zielvorgang liegt in einem anderen Datenraum.")
conn.execute("UPDATE matters SET parent_matter_id = %s WHERE id = %s", (parent_matter_id, matter_id))
if case_id is not None:
require_case(conn, actor, case_id, "edit")
exists = conn.execute(
"SELECT id FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
(matter_id, case_id),
).fetchone()
if exists is None:
link_matter_to_case(conn, actor, matter_id, case_id, context)
if context is not None and context.kind == "case" and context.id != case_id:
conn.execute(
"DELETE FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
(matter_id, context.id),
)
audit(conn, actor, matter["home_scope_id"], "matter_moved", "matter", matter_id, context)
return get_matter(conn, matter_id)
def patch_matter(conn, actor: UUID, matter_id: UUID, expected: int, title: str | None, status: str | None, context: Ctx | None) -> dict:
if title is None and status is None:
raise unprocessable("Es fehlt eine Änderung.")
@@ -519,6 +665,21 @@ def record_dates(conn, actor: UUID, scope_id: UUID, element_id: UUID, context: C
audit(conn, actor, scope_id, "correspondence_recorded", "element", element_id, context)
def store_direction(conn, binding_id: UUID, direction: str | None, explicit: bool) -> None:
if not explicit:
return
if direction not in (None, "in", "out"):
raise unprocessable("Die Richtung ist ungültig.")
conn.execute(
"""
UPDATE bindings
SET communication_direction = %s, direction_explicit = true
WHERE id = %s
""",
(direction, binding_id),
)
def create_note(
conn,
actor: UUID,
@@ -531,6 +692,7 @@ def create_note(
document_on: date | None = None,
sent_on: date | None = None,
received_on: date | None = None,
communication_direction: str | None = None,
) -> dict:
document = clean_document(document)
target, rights_context = _placement(context, placement)
@@ -541,6 +703,7 @@ def create_note(
(element["id"], Json(document)),
)
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
store_direction(conn, binding["id"], communication_direction, communication_direction in ("in", "out"))
audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target)
if document_on is not None or sent_on is not None or received_on is not None:
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
@@ -619,7 +782,7 @@ def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx
return row
def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None) -> dict:
def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None, communication_direction: str | None = None) -> dict:
target, rights_context = _placement(context, placement)
require_container_edit(conn, actor, target, rights_context)
element = _new_element(conn, actor, scope_id, title, "external_ref")
@@ -628,12 +791,15 @@ def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str,
(element["id"], source, external_id.strip()[:200], Json(detail or {})),
)
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
adopted = (detail or {}).get("direction") if source == "imap" else None
chosen = communication_direction if communication_direction in ("in", "out") else adopted if adopted in ("in", "out") else None
store_direction(conn, binding["id"], chosen, chosen in ("in", "out"))
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
audit(conn, actor, scope_id, "external_ref_added", "element", element["id"], rights_context or target)
return element | {"binding_id": binding["id"]}
def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path]) -> dict:
def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path], communication_direction: str | None = None) -> dict:
if not data or len(data) > max_bytes:
raise unprocessable("Die Datei ist leer oder zu groß.")
content_type = sniff(data)
@@ -671,6 +837,7 @@ def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, da
(element["id"], asset_id),
)
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
store_direction(conn, binding["id"], communication_direction, communication_direction in ("in", "out"))
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
audit(conn, actor, scope_id, "file_added", "element", element["id"], rights_context or target)
return element | {"binding_id": binding["id"], "asset_id": asset_id}
+35 -16
View File
@@ -195,12 +195,13 @@ def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict
return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]}
def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict | None:
element = get_element(conn, element_id)
if element is None or not element_rights(conn, actor, element, context).read:
return None
dates = _dates(conn, element)
direction = None
def communication_from_row(conn, binding: dict, element: dict) -> dict:
"""Explicit binding direction wins. An adopted mailbox direction may prefill. Dates never do."""
stored = binding.get("communication_direction")
stored = stored if stored in ("in", "out") else None
if binding.get("direction_explicit"):
return {"direction": stored, "explicit": True}
source = None
if element["kind"] == "external_ref":
ref = conn.execute(
"SELECT source, detail FROM external_references WHERE element_id = %s",
@@ -208,12 +209,28 @@ def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict |
).fetchone()
detail = (ref["detail"] or {}) if ref is not None and ref["source"] == "imap" else {}
if detail.get("direction") in ("in", "out"):
direction = detail["direction"]
if direction is None:
if dates["sent_on"] and not dates["received_on"]:
direction = "out"
elif dates["received_on"] and not dates["sent_on"]:
direction = "in"
source = detail["direction"]
return {"direction": source, "explicit": False}
def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx, container: Ctx) -> dict | None:
element = get_element(conn, element_id)
if element is None or not element_rights(conn, actor, element, context).read:
return None
dates = _dates(conn, element)
row = conn.execute(
"""
SELECT communication_direction, direction_explicit
FROM bindings
WHERE element_id = %s AND context_kind = %s AND context_id = %s
""",
(element["id"], container.kind, container.id),
).fetchone()
direction = communication_from_row(
conn,
row or {"communication_direction": None, "direction_explicit": False},
element,
)["direction"]
return {
"id": str(element["id"]),
"title": element["title"],
@@ -222,7 +239,7 @@ def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict |
}
def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dict) -> None:
def _attach_references(conn, actor: UUID, element: dict, context: Ctx, container: Ctx, body: dict) -> None:
refers = []
for row in conn.execute(
"""
@@ -233,7 +250,7 @@ def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dic
""",
(element["id"],),
).fetchall():
view = _reference_view(conn, actor, row["refers_to_element_id"], context)
view = _reference_view(conn, actor, row["refers_to_element_id"], context, container)
if view is not None:
refers.append(view)
replies = []
@@ -246,7 +263,7 @@ def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dic
""",
(element["id"],),
).fetchall():
view = _reference_view(conn, actor, row["element_id"], context)
view = _reference_view(conn, actor, row["element_id"], context, container)
if view is not None:
replies.append(view)
if refers:
@@ -263,13 +280,15 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No
if not rights.read:
return None
body = _element_body(conn, element)
_attach_references(conn, actor, element, context, body)
container = Ctx(binding["context_kind"], binding["context_id"])
_attach_references(conn, actor, element, context, container, body)
payload = {
"id": str(binding["id"]),
"position": binding["position"],
"chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None,
"rights": rights.as_dict(),
"annotations": _annotations(conn, binding["id"]),
"communication": communication_from_row(conn, binding, element),
"element": body,
}
if element["owner_subject_id"] == actor:
+59 -6
View File
@@ -508,8 +508,8 @@ def _fetch_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict:
raw = _literal(fetched)
if status != "OK" or raw is None:
raise unprocessable("Die Nachricht lässt sich nicht lesen.")
if len(raw) > 1_500_000:
raise unprocessable("Die Nachricht ist zu groß für die Vorschau.")
if len(raw) > 8_000_000:
return _oversized_message(client, uid, mailbox)
message = BytesParser().parsebytes(raw)
subject = _decode(message.get("Subject")) or "(ohne Betreff)"
return {
@@ -522,7 +522,8 @@ def _fetch_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict:
"direction": _direction(mailbox),
"document_on": _mail_date(message.get("Date")),
"attachments": _message_attachments(message),
"text": _message_text(message),
"text": (_text := _message_text(message))[:200_000],
"text_truncated": len(_text) > 200_000,
}
@@ -532,9 +533,61 @@ _SENT_FOLDER = re.compile(
)
def _direction(mailbox: str) -> str:
_INBOX_FOLDER = re.compile(
r"(^|/)(inbox|posteingang|eingang)($|/)",
re.IGNORECASE,
)
def _direction(mailbox: str) -> str | None:
"""Sent folders are outgoing, an inbox is incoming. Other folder names prove nothing."""
folded = mailbox.casefold().replace("\\", "/")
return "out" if _SENT_FOLDER.search(folded) else "in"
if _SENT_FOLDER.search(folded):
return "out"
if _INBOX_FOLDER.search(folded):
return "in"
return None
def _oversized_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict:
header = _fetch_header(client, uid, mailbox) or {}
text = _partial_text(client, uid)
if not header and not text:
raise unprocessable("Die Nachricht lässt sich nicht lesen.")
return {
"uid": uid,
"mailbox": mailbox,
"title": header.get("title") or "(ohne Betreff)",
"message_from": header.get("message_from") or "",
"message_to": header.get("message_to") or "",
"message_cc": header.get("message_cc") or "",
"direction": header.get("direction", _direction(mailbox)),
"document_on": header.get("document_on"),
"attachments": header.get("attachments") or [],
"text": text,
"text_truncated": True,
}
def _partial_text(client: imaplib.IMAP4, uid: int) -> str:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[TEXT]<0.200000>)")
except imaplib.IMAP4.error:
return ""
if status != "OK":
return ""
raw = _literal(fetched)
if not raw:
return ""
sample = raw[:200_000]
try:
message = BytesParser().parsebytes(b"Subject: x\r\n\r\n" + sample)
text = _message_text(message)
except Exception:
text = ""
if not text:
text = sample.decode("utf-8", errors="replace")
return text.strip()[:200_000]
def _literal(fetched) -> bytes | None:
@@ -598,7 +651,7 @@ def _message_text(message) -> str:
text = "\n".join(chunk for chunk in plain if chunk).strip()
if not text:
text = "\n".join(chunk for chunk in html if chunk).strip()
return text[:8000]
return text
def _part_text(part) -> str:
@@ -0,0 +1,7 @@
ALTER TABLE bindings
ADD COLUMN communication_direction text,
ADD COLUMN direction_explicit boolean NOT NULL DEFAULT false;
ALTER TABLE bindings
ADD CONSTRAINT bindings_communication_direction
CHECK (communication_direction IS NULL OR communication_direction IN ('in', 'out'));
+192
View File
@@ -0,0 +1,192 @@
"""Communication direction lives on the binding and is never inferred from dates."""
from __future__ import annotations
from tests.support import Actor, bind_to, case_of, document, matter_of, register
def _matter(actor: Actor, matter_id: str) -> dict:
return actor.request("GET", f"/api/v1/matters/{matter_id}")
def _binding(detail: dict, title: str) -> dict:
return next(item for item in detail["bindings"] if item["element"]["title"] == title)
def _note(actor: Actor, matter_id: str, title: str, direction: str | None = None, **dates) -> dict:
body = {
"title": title,
"document": document(title),
"context": {"kind": "matter", "id": matter_id},
}
if dates:
body["dates"] = dates
if direction in ("in", "out"):
body["communication_direction"] = direction
return actor.request("POST", "/api/v1/notes", json=body, status=201)
def test_dates_do_not_invent_a_direction_and_explicit_choice_survives(client, db):
ada = Actor(client, "ada-richtung@example.test", "Ada Richtung")
ben = Actor(client, "ben-richtung@example.test", "Ben Richtung")
register(db, ada.email, ada.name)
register(db, ben.email, ben.name)
ada.login()
matter = matter_of(ada, "Kautionsabrechnung")
_note(ada, matter["id"], "Beide Daten", document_on="2026-10-12", sent_on="2026-10-01", received_on="2026-10-12")
_note(ada, matter["id"], "Telefon Eingang", "in")
_note(ada, matter["id"], "Telefon Ausgang", "out")
_note(ada, matter["id"], "Gedankenprotokoll")
ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": "Scan ohne Richtung",
"source": "paperless",
"external_id": "scan-42",
"context": {"kind": "matter", "id": matter["id"]},
"detail": {"open_url": "https://example.test/scan-42"},
},
status=201,
)
ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": "Mail der Verwaltung",
"source": "imap",
"external_id": "<verwaltung@example.test>",
"context": {"kind": "matter", "id": matter["id"]},
"detail": {
"direction": "in",
"message_from": "Hausverwaltung Mueller",
"mailbox": "INBOX",
},
},
status=201,
)
shown = _matter(ada, matter["id"])
both = _binding(shown, "Beide Daten")
assert both["communication"] == {"direction": None, "explicit": False}
assert both["element"]["dates"]["sent_on"] == "2026-10-01"
assert both["element"]["dates"]["received_on"] == "2026-10-12"
assert _binding(shown, "Telefon Eingang")["communication"]["direction"] == "in"
assert _binding(shown, "Telefon Ausgang")["communication"]["direction"] == "out"
assert _binding(shown, "Gedankenprotokoll")["communication"]["direction"] is None
assert _binding(shown, "Scan ohne Richtung")["communication"]["direction"] is None
mail = _binding(shown, "Mail der Verwaltung")
assert mail["communication"] == {"direction": "in", "explicit": True}
ada.request(
"PATCH",
f"/api/v1/bindings/{mail['id']}/communication",
json={"expected_version": mail["element"]["version"], "direction": None, "context": {"kind": "matter", "id": matter["id"]}},
)
cleared = _binding(_matter(ada, matter["id"]), "Mail der Verwaltung")
assert cleared["communication"] == {"direction": None, "explicit": True}
ada.request(
"PATCH",
f"/api/v1/bindings/{both['id']}/communication",
json={"expected_version": both["element"]["version"], "direction": "out", "context": {"kind": "matter", "id": matter["id"]}},
)
chosen = _binding(_matter(ada, matter["id"]), "Beide Daten")
assert chosen["communication"] == {"direction": "out", "explicit": True}
ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/grants",
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False},
status=201,
)
ben.login()
visible = _binding(_matter(ben, matter["id"]), "Beide Daten")
assert visible["communication"]["direction"] == "out"
ben.request(
"PATCH",
f"/api/v1/bindings/{visible['id']}/communication",
json={"expected_version": visible["element"]["version"], "direction": "in", "context": {"kind": "matter", "id": matter["id"]}},
status=403,
)
def test_a_second_binding_keeps_its_own_direction(client, db):
ada = Actor(client, "ada-bindung@example.test", "Ada Bindung")
register(db, ada.email, ada.name)
ada.login()
first = case_of(ada, "Erste Akte")
second = case_of(ada, "Zweite Akte")
created = ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Gemeinsame Notiz",
"document": {"version": 1, "blocks": [{"type": "markdown", "text": "# Anruf\n\n**Eingang**"}]},
"context": {"kind": "case", "id": first["id"]},
"communication_direction": "in",
},
status=201,
)
bind_to(ada, created["id"], first["id"], second["id"])
left = ada.request("GET", f"/api/v1/cases/{first['id']}")
right = ada.request("GET", f"/api/v1/cases/{second['id']}")
left_binding = next(item for item in left["bindings"] if item["element"]["title"] == "Gemeinsame Notiz")
right_binding = next(item for item in right["bindings"] if item["element"]["title"] == "Gemeinsame Notiz")
assert left_binding["communication"]["direction"] == "in"
assert right_binding["communication"]["direction"] is None
assert left_binding["element"]["document"]["blocks"][0]["type"] == "markdown"
ada.request(
"PATCH",
f"/api/v1/bindings/{right_binding['id']}/communication",
json={"expected_version": right_binding["element"]["version"], "direction": "out", "context": {"kind": "case", "id": second["id"]}},
)
left_again = ada.request("GET", f"/api/v1/cases/{first['id']}")
right_again = ada.request("GET", f"/api/v1/cases/{second['id']}")
assert next(item for item in left_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "in"
assert next(item for item in right_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "out"
def test_chapter_and_matter_can_be_renamed_and_moved(client, db):
ada = Actor(client, "ada-struktur@example.test", "Ada Struktur")
register(db, ada.email, ada.name)
ada.login()
case = case_of(ada, "Vermietung")
other = case_of(ada, "Ferienhaus")
matter = matter_of(ada, "Nebenkosten")
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
parent = matter_of(ada, "Wohnung")
ada.request("POST", f"/api/v1/matters/{parent['id']}/case-links", json={"case_id": other["id"]}, status=201)
chapter = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Schreiben"},
status=201,
)
detail = _matter(ada, matter["id"])
ada.request(
"PATCH",
f"/api/v1/chapters/{chapter['id']}/title",
json={"expected_version": detail["version"], "title": "Korrespondenz", "context": {"kind": "case", "id": case["id"]}},
)
current = _matter(ada, matter["id"])
assert current["chapters"][0]["title"] == "Korrespondenz"
ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/move",
json={
"expected_version": current["version"],
"context": {"kind": "case", "id": case["id"]},
"case_id": other["id"],
"parent_matter_id": parent["id"],
},
)
moved = _matter(ada, matter["id"])
assert moved["parent_matter_id"] == parent["id"]
assert any(item["case_id"] == other["id"] for item in moved["placements"])
assert all(item["case_id"] != case["id"] for item in moved["placements"])
ada.request(
"POST",
f"/api/v1/cases/{case['id']}/delete",
json={"expected_version": ada.request("GET", f"/api/v1/cases/{case['id']}")["version"]},
)
ada.request("GET", f"/api/v1/cases/{case['id']}", status=404)
+46
View File
@@ -149,6 +149,12 @@ def test_folder_pages_newest_first_and_search_stays_inside(client, db, monkeypat
assert preview["direction"] == "in"
assert preview["message_to"] == "Gegenseite <gegen@example.test>"
assert "Einwendung" in preview["text"]
other = ada.request(
"GET",
"/api/v1/sources/imap/messages",
params={"connector_id": account, "mailbox": "&AMQ-nderungen"},
)
assert other["items"][0]["direction"] is None
assert preview["attachments"][0]["filename"] == "einwendung.pdf"
ada.request(
"GET",
@@ -169,3 +175,43 @@ def test_foreign_mailbox_stays_hidden(client, db, monkeypatch):
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)
class HugeIMAP(FakeIMAP):
def uid(self, command, *args):
spec = " ".join(str(part) for part in args[1:]) if len(args) > 1 else ""
if command == "FETCH" and "BODY.PEEK[]" in spec:
return "OK", [(b"rfc822", b"x" * 8_000_001)]
if "BODY.PEEK[TEXT]" in spec:
return "OK", [(b"text", "Kurzer Auszug der grossen Nachricht.".encode())]
return super().uid(command, *args)
def test_oversized_message_still_returns_text(client, db, monkeypatch):
ada = Actor(client, "ada-huge@example.test", "Ada Gross")
register(db, ada.email, ada.name)
ada.login()
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", HugeIMAP)
account = ada.request(
"POST",
"/api/v1/connectors",
json={
"kind": "imap",
"name": "Gross",
"host": "imap.example.test",
"port": 993,
"username": "ada@example.test",
"password": "Postfach-Geheim",
"security": "ssl",
},
status=201,
)["id"]
preview = ada.request(
"GET",
"/api/v1/sources/imap/message",
params={"connector_id": account, "mailbox": "INBOX", "uid": 2},
)
assert "Kurzer Auszug" in preview["text"]
assert preview["text_truncated"] is True
assert preview["direction"] == "in"
assert preview["message_from"]
+15 -15
View File
@@ -5,18 +5,16 @@ from __future__ import annotations
from tests.support import Actor, document, register
def _note(actor: Actor, title: str, matter_id: str, **dates) -> None:
actor.request(
"POST",
"/api/v1/notes",
json={
"title": title,
"document": document(title),
"context": {"kind": "matter", "id": matter_id},
"dates": dates,
},
status=201,
)
def _note(actor: Actor, title: str, matter_id: str, direction: str | None = None, **dates) -> None:
body = {
"title": title,
"document": document(title),
"context": {"kind": "matter", "id": matter_id},
"dates": dates,
}
if direction in ("in", "out"):
body["communication_direction"] = direction
actor.request("POST", "/api/v1/notes", json=body, status=201)
def _by_title(detail: dict) -> dict:
@@ -30,9 +28,9 @@ def test_reply_names_its_letter_and_leaves_the_gap(client, db):
register(db, ben.email, ben.name)
ada.login()
matter = ada.request("POST", "/api/v1/matters", json={"title": "Schriftwechsel"}, status=201)
_note(ada, "Anschreiben", matter["id"], document_on="2026-03-12", received_on="2026-03-12")
_note(ada, "Zwischennachricht", matter["id"], document_on="2026-04-02", received_on="2026-04-02")
_note(ada, "Antwort", matter["id"], document_on="2026-05-18", sent_on="2026-05-18")
_note(ada, "Anschreiben", matter["id"], "in", document_on="2026-03-12", received_on="2026-03-12")
_note(ada, "Zwischennachricht", matter["id"], document_on="2026-04-02", received_on="2026-04-02", sent_on="2026-04-02")
_note(ada, "Antwort", matter["id"], "out", document_on="2026-05-18", sent_on="2026-05-18")
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
ada.request(
"PATCH",
@@ -80,6 +78,8 @@ def test_reply_names_its_letter_and_leaves_the_gap(client, db):
]
assert linked["Anschreiben"]["referred_by"][0]["title"] == "Antwort"
assert linked["Anschreiben"]["referred_by"][0]["direction"] == "out"
gap = next(item for item in shown["bindings"] if item["element"]["title"] == "Zwischennachricht")
assert gap["communication"]["direction"] is None
assert "refers_to" not in linked["Zwischennachricht"]
assert "referred_by" not in linked["Zwischennachricht"]
ada.request(