"""Reports: user-written articles that embed claims and link other reports. Body syntax (Markdown subset, rendered by the web app's ReportBody): [[angabe:123]] on a line of its own: the claim as a card, with its evidence [[bericht:some-slug]] on a line of its own: a card linking another report [text](angabe:123) inline link to a claim; also bericht:slug, person:slug, org:slug English aliases (claim:, report:, organization:) work too. References are parsed at every save into report_reference, which drives "used in reports" on claim, person and report pages. Writes happen only through the API's author endpoints, which the web app calls with POLITRACK_AUTHOR_TOKEN on behalf of a user signed in at the reverse proxy (Authelia). """ from __future__ import annotations import re from dataclasses import dataclass, field from typing import Any from psycopg import Connection from politrack.queries.claims import list_claims from politrack.queries.common import SourceFilter from politrack.text import make_slug REF_TYPES = {"angabe": "claim", "claim": "claim", "bericht": "report", "report": "report", "person": "person", "org": "organization", "organisation": "organization", "organization": "organization"} _NAMES = "|".join(REF_TYPES) BLOCK_REF = re.compile(rf"^[ \t]*\[\[({_NAMES})\s*:\s*([^\]\s]+)\s*\]\][ \t]*$", re.IGNORECASE | re.MULTILINE) INLINE_REF = re.compile(rf"\[([^\]\n]+)\]\(({_NAMES}):([^)\s]+)\)", re.IGNORECASE) MAX_BODY = 100_000 @dataclass class Viewer: """The signed-in user on whose behalf the web app calls (from the X-Politrack-User* headers).""" subject: str name: str | None = None email: str | None = None groups: list[str] = field(default_factory=list) editor: bool = False def parse_references(body: str) -> list[tuple[str, str, bool]]: """(ref_type, key, embedded) for every valid reference in the body, without duplicates (embedding wins).""" refs: dict[tuple[str, str], bool] = {} for m in BLOCK_REF.finditer(body): ref_type, key = REF_TYPES[m.group(1).lower()], m.group(2) if _valid(ref_type, key): refs[(ref_type, key)] = True for m in INLINE_REF.finditer(body): ref_type, key = REF_TYPES[m.group(2).lower()], m.group(3) if _valid(ref_type, key): refs.setdefault((ref_type, key), False) return [(t, k, e) for (t, k), e in refs.items()] def _valid(ref_type: str, key: str) -> bool: return key.isdigit() if ref_type == "claim" else bool(re.fullmatch(r"[a-z0-9][a-z0-9-]{0,200}", key)) # -- users ---------------------------------------------------------------------------------------------------------- def upsert_user(conn: Connection, viewer: Viewer) -> int: row = conn.execute( """INSERT INTO app_user (external_subject, email, display_name, last_seen_at) VALUES (%s, %s, %s, now()) ON CONFLICT (external_subject) DO UPDATE SET email = COALESCE(EXCLUDED.email, app_user.email), display_name = COALESCE(EXCLUDED.display_name, app_user.display_name), last_seen_at = now() RETURNING id""", (viewer.subject, viewer.email, viewer.name), ).fetchone() return row["id"] # -- reading ---------------------------------------------------------------------------------------------------------- LIST_COLUMNS = """ r.slug, r.title, r.lede, r.lang, r.status, r.created_at, r.updated_at, r.published_at, COALESCE(u.display_name, 'Unbekannt') AS author_name, (SELECT count(*) FROM report_reference x JOIN claim c ON c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) WHERE x.report_id = r.id AND x.ref_type = 'claim' AND c.review_status = 'published') AS claim_count, (SELECT count(*) FROM report_reference x JOIN claim c ON c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) WHERE x.report_id = r.id AND x.ref_type = 'claim' AND c.review_status = 'published' AND EXISTS ( SELECT 1 FROM claim_evidence e JOIN document d ON d.id = e.document_id JOIN source s ON s.id = d.source_id WHERE e.claim_id = c.id AND s.kind = 'official')) AS official_claim_count, (SELECT count(*) FROM report_revision v WHERE v.report_id = r.id) AS revision_count """ def list_reports(conn: Connection, *, viewer: Viewer | None = None, mine: bool = False, claim_id: int | None = None, person: str | None = None, organization: str | None = None, report: str | None = None, q: str | None = None, limit: int = 30, offset: int = 0) -> list[dict]: """Published reports, newest first. mine=True: all of the viewer's own reports (drafts too). claim_id / person / organization / report: only reports referencing that claim, person, organisation or report.""" params = {"subject": viewer.subject if viewer else None, "mine": mine, "q": q, "limit": limit, "offset": offset, "claim": str(claim_id) if claim_id is not None else None, "person": person, "org": organization, "report": report} return conn.execute( f""" SELECT {LIST_COLUMNS} FROM report r JOIN app_user u ON u.id = r.author_id WHERE (CASE WHEN %(mine)s THEN u.external_subject = %(subject)s ELSE r.status = 'published' END) AND (%(claim)s::text IS NULL OR EXISTS (SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND x.ref_type = 'claim' AND x.ref_key = %(claim)s)) AND (%(person)s::text IS NULL OR EXISTS ( SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND ( (x.ref_type = 'person' AND x.ref_key = %(person)s) OR (x.ref_type = 'claim' AND EXISTS (SELECT 1 FROM claim c JOIN person p ON p.id IN (c.person_id, c.counterpart_person_id) WHERE c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) AND p.slug = %(person)s))))) AND (%(org)s::text IS NULL OR EXISTS ( SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND ( (x.ref_type = 'organization' AND x.ref_key = %(org)s) OR (x.ref_type = 'claim' AND EXISTS (SELECT 1 FROM claim c JOIN organization o ON o.id IN (c.organization_id, c.counterpart_org_id) WHERE c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) AND o.slug = %(org)s))))) AND (%(report)s::text IS NULL OR EXISTS (SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND x.ref_type = 'report' AND x.ref_key = %(report)s)) AND (%(q)s::text IS NULL OR r.title ILIKE '%%' || %(q)s || '%%' OR r.lede ILIKE '%%' || %(q)s || '%%') ORDER BY COALESCE(r.published_at, r.updated_at) DESC, r.id DESC LIMIT %(limit)s OFFSET %(offset)s """, params, ).fetchall() def get_report(conn: Connection, slug: str, viewer: Viewer | None = None) -> dict | None: """A report with everything needed to render it. Drafts only for their author (or an editor).""" row = conn.execute( f"""SELECT r.id, r.body, u.external_subject AS author_subject, {LIST_COLUMNS} FROM report r JOIN app_user u ON u.id = r.author_id WHERE r.slug = %s""", (slug,), ).fetchone() if not row: return None own = bool(viewer and (viewer.subject == row["author_subject"] or viewer.editor)) if row["status"] == "draft" and not own: return None report = dict(row) report.pop("id") author_subject = report.pop("author_subject") report["can_edit"] = own report["is_author"] = bool(viewer and viewer.subject == author_subject) report["references"] = resolve_references(conn, report["body"]) report["backlinks"] = list_reports(conn, report=slug, limit=50) if report["status"] == "withdrawn" and not own: report["body"], report["references"] = "", resolve_references(conn, "") return report def resolve_references(conn: Connection, body: str) -> dict[str, Any]: """Look up everything the body references. Claims are shown like permalinks (no visitor filter); a claim merged into another one resolves to the survivor; hidden or deleted claims are listed in missing_claims.""" refs = parse_references(body) claim_ids = [int(k) for t, k, _ in refs if t == "claim"] survivors = _follow_merges(conn, claim_ids) found = {c["id"]: c for c in list_claims(conn, sources=SourceFilter(), claim_ids=sorted(set(survivors.values())), limit=max(1, len(survivors)))} if survivors else {} claims, missing, aliases = [], [], {} for cid in claim_ids: survivor = survivors.get(cid) if survivor in found: if survivor != cid: aliases[str(cid)] = survivor if found[survivor] not in claims: claims.append(found[survivor]) else: missing.append(cid) report_slugs = [k for t, k, _ in refs if t == "report"] reports = conn.execute( f"""SELECT {LIST_COLUMNS} FROM report r JOIN app_user u ON u.id = r.author_id WHERE r.slug = ANY(%s) AND r.status <> 'draft'""", (report_slugs,), ).fetchall() if report_slugs else [] persons = conn.execute("SELECT slug, full_name AS name FROM person WHERE slug = ANY(%s)", ([k for t, k, _ in refs if t == "person"],)).fetchall() orgs = conn.execute("SELECT slug, COALESCE(short_name, name) AS name, kind FROM organization WHERE slug = ANY(%s)", ([k for t, k, _ in refs if t == "organization"],)).fetchall() return {"claims": claims, "claim_aliases": aliases, "missing_claims": missing, "reports": reports, "persons": persons, "organizations": orgs} def _follow_merges(conn: Connection, claim_ids: list[int]) -> dict[int, int]: """claim id -> id of the claim it was merged into (itself if not merged). Unknown ids are left out.""" if not claim_ids: return {} rows = {r["id"]: r["merged_into"] for r in conn.execute( """WITH RECURSIVE chain AS ( SELECT id, merged_into FROM claim WHERE id = ANY(%s) UNION SELECT c.id, c.merged_into FROM claim c JOIN chain ON c.id = chain.merged_into) SELECT id, merged_into FROM chain""", (claim_ids,)).fetchall()} result = {} for cid in claim_ids: current, hops = cid, 0 while current in rows and rows[current] is not None and hops < 10: current, hops = rows[current], hops + 1 if current in rows: result[cid] = current return result # -- writing ---------------------------------------------------------------------------------------------------------- class ReportError(ValueError): pass def _check(title: str, body: str) -> None: if not 3 <= len(title.strip()) <= 200: raise ReportError("title must be 3-200 characters") if len(body) > MAX_BODY: raise ReportError(f"body is longer than {MAX_BODY} characters") RESERVED_SLUGS = {"verfassen", "neu"} # web routes under /berichte/ def _unique_slug(conn: Connection, title: str) -> str: base = make_slug(title)[:80].strip("-") or "bericht" if base in RESERVED_SLUGS: base = f"{base}-bericht" slug, n = base, 1 while conn.execute("SELECT 1 FROM report WHERE slug = %s", (slug,)).fetchone(): n += 1 slug = f"{base}-{n}" return slug def _save_references(conn: Connection, report_id: int, body: str) -> None: conn.execute("DELETE FROM report_reference WHERE report_id = %s", (report_id,)) for ref_type, key, embedded in parse_references(body): conn.execute("INSERT INTO report_reference (report_id, ref_type, ref_key, embedded) VALUES (%s, %s, %s, %s)", (report_id, ref_type, key, embedded)) def create_report(conn: Connection, viewer: Viewer, *, title: str, lede: str | None, body: str, lang: str, status: str) -> str: _check(title, body) user_id = upsert_user(conn, viewer) slug = _unique_slug(conn, title) report_id = conn.execute( """INSERT INTO report (slug, title, lede, body, lang, status, author_id, published_at) VALUES (%s, %s, %s, %s, %s, %s, %s, CASE WHEN %s = 'published' THEN now() END) RETURNING id""", (slug, title.strip(), (lede or "").strip() or None, body, lang, status, user_id, status), ).fetchone()["id"] _save_references(conn, report_id, body) conn.execute("""INSERT INTO report_revision (report_id, title, lede, body, status, edited_by) SELECT id, title, lede, body, status, %s FROM report WHERE id = %s""", (user_id, report_id)) conn.commit() return slug def update_report(conn: Connection, viewer: Viewer, slug: str, *, title: str, lede: str | None, body: str, lang: str, status: str) -> bool: """False if the report doesn't exist or the viewer may not edit it.""" _check(title, body) row = conn.execute("""SELECT r.id, u.external_subject FROM report r JOIN app_user u ON u.id = r.author_id WHERE r.slug = %s FOR UPDATE OF r""", (slug,)).fetchone() if not row or (row["external_subject"] != viewer.subject and not viewer.editor): return False user_id = upsert_user(conn, viewer) conn.execute( """UPDATE report SET title = %s, lede = %s, body = %s, lang = %s, status = %s, updated_at = now(), published_at = COALESCE(published_at, CASE WHEN %s = 'published' THEN now() END) WHERE id = %s""", (title.strip(), (lede or "").strip() or None, body, lang, status, status, row["id"]), ) _save_references(conn, row["id"], body) conn.execute("""INSERT INTO report_revision (report_id, title, lede, body, status, edited_by) SELECT id, title, lede, body, status, %s FROM report WHERE id = %s""", (user_id, row["id"])) conn.commit() return True