"""Documents of a source that are inserted into a container again. The same document in different Vorgänge stays allowed. This module only finds where a document is already present around the target, so the dialog can warn and the user can decide. Levels (account preference `duplicate_check`): - here: bound directly to the target. - inside: also what the target shows: Teilvorgänge of a Vorgang, the linked Vorgänge of an Akte. - around: also where the target lies: its Vorgang, the Akten it is linked to, the parent Akte. Only elements the actor may read are reported. A hit outside the actor's rights does not exist here. """ from __future__ import annotations from uuid import UUID from app.access.policy import ( Ctx, case_rights, element_rights, get_case, get_matter, matter_rights, ) from app.core.errors import Problem LEVELS = {"off": (), "here": ("here",), "inside": ("here", "inside"), "around": ("here", "inside", "around")} _ORDER = {"here": 0, "inside": 1, "around": 2} def _stored_connector(row: dict) -> str | None: if row["connector_id"] is not None: return str(row["connector_id"]) stored = (row["detail"] or {}).get("connector_id") return str(stored) if stored else None def _candidates(conn, source: str, external_id: str, connector_id: str | None) -> list[dict]: """Elements for the same document. `certain` is False when only one side knows the connection.""" rows = conn.execute( """ SELECT e.id, e.title, e.owner_subject_id, er.connector_id, er.detail FROM external_references er JOIN elements e ON e.id = er.element_id WHERE er.source = %s AND er.external_id = %s AND e.deleted_at IS NULL """, (source, external_id.strip()[:200]), ).fetchall() found = [] for row in rows: stored = _stored_connector(row) if stored is not None and connector_id is not None and stored != connector_id: continue found.append(row | {"certain": stored == connector_id}) return found def _children(conn, matter_id: UUID) -> list[UUID]: rows = conn.execute("SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL", (matter_id,)).fetchall() return [row["id"] for row in rows] def _zones(conn, target: Ctx) -> dict[str, list[Ctx]]: inside: list[Ctx] = [] around: list[Ctx] = [] if target.kind == "matter": inside = [Ctx("matter", child) for child in _children(conn, target.id)] matter = get_matter(conn, target.id) anchors = [target.id] if matter is not None and matter["parent_matter_id"] is not None: around.append(Ctx("matter", matter["parent_matter_id"])) anchors.append(matter["parent_matter_id"]) links = conn.execute("SELECT DISTINCT case_id FROM matter_case_links WHERE matter_id = ANY(%s)", (anchors,)).fetchall() around += [Ctx("case", row["case_id"]) for row in links] else: links = conn.execute("SELECT matter_id FROM matter_case_links WHERE case_id = %s", (target.id,)).fetchall() for row in links: inside.append(Ctx("matter", row["matter_id"])) inside += [Ctx("matter", child) for child in _children(conn, row["matter_id"])] case = get_case(conn, target.id) if case is not None and case["parent_case_id"] is not None: around.append(Ctx("case", case["parent_case_id"])) return {"here": [target], "inside": inside, "around": around} def _blocked(conn, case_id: UUID, element_id: UUID) -> bool: row = conn.execute( """ SELECT 1 FROM case_link_blocks b JOIN matter_case_links l ON l.id = b.link_id WHERE l.case_id = %s AND b.element_id = %s """, (case_id, element_id), ).fetchone() return row is not None def _title_if_readable(conn, actor: UUID, container: Ctx) -> str | None: if container.kind == "case": case = get_case(conn, container.id) return case["title"] if case is not None and case_rights(conn, actor, case).read else None matter = get_matter(conn, container.id) return matter["title"] if matter is not None and matter_rights(conn, actor, matter, None).read else None def find_existing( conn, actor: UUID, source: str, external_id: str, connector_id: str | None, target: Ctx, rights_context: Ctx | None, level: str, ) -> list[dict]: """Matches of one document at the chosen level, readable by the actor, nearest zone first.""" zones = LEVELS.get(level, ()) if not zones: return [] candidates = _candidates(conn, source, external_id, connector_id) if not candidates: return [] layout = _zones(conn, target) by_element: dict[UUID, dict] = {} for candidate in candidates: bindings = conn.execute( "SELECT b.context_kind, b.context_id, c.title AS chapter FROM bindings b LEFT JOIN chapters c ON c.id = b.chapter_id WHERE b.element_id = %s", (candidate["id"],), ).fetchall() for zone in zones: for container in layout[zone]: hit = next((b for b in bindings if b["context_kind"] == container.kind and b["context_id"] == container.id), None) if hit is None: continue if target.kind == "case" and zone == "inside" and _blocked(conn, target.id, candidate["id"]): continue seen_in = [container] if zone == "around" else [c for c in (target, rights_context) if c is not None] rights = [element_rights(conn, actor, candidate, ctx) for ctx in seen_in] if not any(r.read for r in rights): continue match = { "element_id": str(candidate["id"]), "title": candidate["title"], "where": zone, "certain": candidate["certain"], "chapter": hit["chapter"] if zone == "here" else None, "container": { "kind": container.kind, "title": _title_if_readable(conn, actor, container) if zone != "here" else None, }, "can_bind": any(r.share for r in rights), } known = by_element.get(candidate["id"]) if known is None or _ORDER[zone] < _ORDER[known["where"]]: by_element[candidate["id"]] = match return sorted(by_element.values(), key=lambda item: (_ORDER[item["where"]], item["title"])) def already_present(matches: list[dict]) -> Problem: where = {"here": "hier", "inside": "in diesem Bestand", "around": "im Umfeld"}[matches[0]["where"]] return Problem( 409, "Bereits vorhanden", f"Dieses Dokument ist {where} schon vorhanden. Füge es nur dann erneut ein, wenn das gewollt ist.", "already_present", )