reports: user articles that embed claims under a database seal and link each other

- /berichte lists published reports; /berichte/<slug> renders a report: Markdown subset built as React
  elements (no raw HTML), [[angabe:ID]] embeds the claim card under a seal (green 'Amtliche Daten' when a
  source is official), [text](angabe:ID|bericht:slug|person:slug|org:slug) links inline, [[bericht:slug]]
  embeds another report; a box says how many claims the text rests on; backlinks between reports.
- /berichte/verfassen (login at the proxy): own reports, editor with a picker that finds claims, reports and
  persons and inserts their codes; draft / published / withdrawn; every save kept in report_revision.
- Claim pages show the embed code, 'use in a new report' and the reports citing the claim.
- API: GET /api/v1/reports, /reports/{slug} (references resolved like permalinks, merged claims follow the
  survivor); POST/PUT for the web app with POLITRACK_AUTHOR_TOKEN on behalf of the proxy user. The web app
  trusts Remote-User only with X-Politrack-Proxy = POLITRACK_PROXY_SECRET.
- Migration 0011 (report, report_revision, report_reference, app_user.display_name); docs: data model,
  deployment (sign-in setup), design system, roadmap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
simonandClaude Opus 5.5 committed 2026-11-20 10:19:50 +01:00
1 parent f2d72fe464
commit 9f0e2fc115
32 files changed
+1974 -21

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
-- Reports: articles written by signed-in users that embed and link claims (and other reports) from the database.
-- The text is the author's; the embedded claims keep their own evidence, so readers can tell the two apart.
ALTER TABLE app_user ADD COLUMN display_name TEXT;
ALTER TABLE app_user ADD COLUMN last_seen_at TIMESTAMPTZ;
COMMENT ON COLUMN app_user.external_subject IS 'User name from the reverse-proxy login (Authelia Remote-User).';
COMMENT ON COLUMN app_user.display_name IS 'Name shown as the author of reports (Authelia Remote-Name), updated at every write.';
CREATE TABLE report (
id SERIAL PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
lede TEXT,
body TEXT NOT NULL,
lang TEXT NOT NULL DEFAULT 'de' CHECK (lang IN ('de', 'en')),
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'withdrawn')),
author_id INT NOT NULL REFERENCES app_user(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
COMMENT ON TABLE report IS 'User-written articles. body is Markdown with references: [[angabe:ID]] embeds a claim, [[bericht:slug]] another report; [text](angabe:ID|bericht:slug|person:slug|org:slug) link inline.';
COMMENT ON COLUMN report.slug IS 'Permanent URL key, fixed at creation so that links from other reports keep working.';
COMMENT ON COLUMN report.status IS 'draft: only the author sees it. published: listed. withdrawn: unlisted, the page stays and says so.';
COMMENT ON COLUMN report.published_at IS 'First publication; later edits only change updated_at (and add a revision).';
CREATE INDEX report_list_idx ON report (status, published_at DESC);
CREATE INDEX report_author_idx ON report (author_id, updated_at DESC);
CREATE TABLE report_revision (
id BIGSERIAL PRIMARY KEY,
report_id INT NOT NULL REFERENCES report(id) ON DELETE CASCADE,
title TEXT NOT NULL,
lede TEXT,
body TEXT NOT NULL,
status TEXT NOT NULL,
edited_by INT NOT NULL REFERENCES app_user(id),
edited_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE report_revision IS 'Every saved version of a report (also the first), so that changes after publication stay traceable.';
CREATE INDEX report_revision_idx ON report_revision (report_id, edited_at DESC);
CREATE TABLE report_reference (
report_id INT NOT NULL REFERENCES report(id) ON DELETE CASCADE,
ref_type TEXT NOT NULL CHECK (ref_type IN ('claim', 'report', 'person', 'organization')),
ref_key TEXT NOT NULL,
embedded BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (report_id, ref_type, ref_key)
);
COMMENT ON TABLE report_reference IS 'References parsed from the current body at every save: drives "used in reports" on claim, person and report pages.';
COMMENT ON COLUMN report_reference.ref_key IS 'Claim id, report slug, person slug or organisation slug, as written in the body.';
COMMENT ON COLUMN report_reference.embedded IS 'TRUE for a block embed ([[...]]), FALSE for an inline link.';
CREATE INDEX report_reference_target_idx ON report_reference (ref_type, ref_key);
+71 -1
View File
@@ -6,9 +6,11 @@ Conventions: every list endpoint takes limit/offset; claim-like endpoints take t
from __future__ import annotations
import hmac
from collections.abc import Iterator
from datetime import date
from typing import Annotated
from urllib.parse import unquote
from fastapi import Depends, FastAPI, Header, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
@@ -28,7 +30,7 @@ app = FastAPI(
docs_url="/api/docs",
openapi_url="/api/openapi.json",
)
app.add_middleware(CORSMiddleware, allow_origins=get_settings().api_cors_origins, allow_methods=["GET", "POST"],
app.add_middleware(CORSMiddleware, allow_origins=get_settings().api_cors_origins, allow_methods=["GET", "POST", "PUT"],
allow_headers=["*"])
@@ -255,6 +257,74 @@ def get_search(conn: DB, sources: Sources, q: Annotated[str, Query(min_length=2)
return queries.search(conn, q, sources=sources, since=since, until=until, limit=limit)
# -- reports ----------------------------------------------------------------------------------------------------------
# Reading is public (published reports). Writing: the web app calls with Authorization: Bearer POLITRACK_AUTHOR_TOKEN
# and the signed-in user in X-Politrack-User (Authelia Remote-User), -User-Name and -User-Email (percent-encoded)
# and -User-Groups (comma-separated).
def report_viewer(
authorization: Annotated[str | None, Header()] = None,
x_politrack_user: Annotated[str | None, Header()] = None,
x_politrack_user_name: Annotated[str | None, Header()] = None,
x_politrack_user_email: Annotated[str | None, Header()] = None,
x_politrack_user_groups: Annotated[str | None, Header()] = None,
) -> queries.Viewer | None:
settings = get_settings()
token = settings.author_token
if not token or not x_politrack_user or not hmac.compare_digest(authorization or "", f"Bearer {token}"):
return None
groups = [g.strip() for g in unquote(x_politrack_user_groups or "").split(",") if g.strip()]
return queries.Viewer(subject=unquote(x_politrack_user), name=unquote(x_politrack_user_name or "") or None,
email=unquote(x_politrack_user_email or "") or None, groups=groups,
editor=bool(set(groups) & set(settings.report_editor_groups)))
ReportViewer = Annotated[queries.Viewer | None, Depends(report_viewer)]
def require_author(viewer: ReportViewer) -> queries.Viewer:
if viewer is None:
raise HTTPException(401, "sign-in required")
return viewer
@app.get("/api/v1/reports", response_model=list[s.ReportListItem])
def get_reports(conn: DB, viewer: ReportViewer, mine: bool = False, claim: int | None = None, person: str | None = None,
org: str | None = None, report: str | None = None, q: str | None = None, limit: Limit = 30,
offset: Offset = 0):
"""Published reports written by users, newest first. Filter by a referenced claim, person, organisation or report.
Reports are opinion pieces: the embedded claims carry the evidence, the text around them is the author's."""
if mine and viewer is None:
raise HTTPException(401, "sign-in required")
return queries.list_reports(conn, viewer=viewer, mine=mine, claim_id=claim, person=person, organization=org,
report=report, q=q, limit=limit, offset=offset)
@app.get("/api/v1/reports/{slug}", response_model=s.ReportDetail)
def get_report(slug: str, conn: DB, viewer: ReportViewer):
"""A report with its body (Markdown with [[angabe:ID]] embeds) and every referenced claim, report, person and
organisation resolved, plus the reports that link to it."""
return not_found(queries.get_report(conn, slug, viewer), "report")
@app.post("/api/v1/reports", response_model=s.ReportSaved, include_in_schema=False)
def post_report(data: s.ReportInput, conn: DB, viewer: Annotated[queries.Viewer, Depends(require_author)]):
try:
return {"slug": queries.create_report(conn, viewer, **data.model_dump())}
except queries.ReportError as error:
raise HTTPException(400, str(error)) from error
@app.put("/api/v1/reports/{slug}", response_model=s.ReportSaved, include_in_schema=False)
def put_report(slug: str, data: s.ReportInput, conn: DB, viewer: Annotated[queries.Viewer, Depends(require_author)]):
try:
if not queries.update_report(conn, viewer, slug, **data.model_dump()):
raise HTTPException(404, "report not found or not yours")
except queries.ReportError as error:
raise HTTPException(400, str(error)) from error
return {"slug": slug}
# -- admin (POLITRACK_ADMIN_TOKEN) ------------------------------------------------------------------
def require_admin(authorization: Annotated[str | None, Header()] = None) -> str:
+52
View File
@@ -533,3 +533,55 @@ class PendingClaim(Model):
occurred_at: datetime | None = None
full_name: str | None = None
evidence: list[dict[str, Any]] | None = None
# -- reports --------------------------------------------------------------------------------------------------------
class ReportListItem(Model):
slug: str
title: str
lede: str | None = None
lang: Literal["de", "en"]
status: Literal["draft", "published", "withdrawn"]
author_name: str
created_at: datetime
updated_at: datetime
published_at: datetime | None = None
claim_count: int
official_claim_count: int
revision_count: int
class NamedRef(Model):
slug: str
name: str
kind: str | None = None
class ReportReferences(Model):
claims: list[Claim]
claim_aliases: dict[str, int] = {}
missing_claims: list[int] = []
reports: list[ReportListItem]
persons: list[NamedRef]
organizations: list[NamedRef]
class ReportDetail(ReportListItem):
body: str
can_edit: bool
is_author: bool
references: ReportReferences
backlinks: list[ReportListItem]
class ReportInput(BaseModel):
title: str
lede: str | None = None
body: str
lang: Literal["de", "en"] = "de"
status: Literal["draft", "published", "withdrawn"] = "draft"
class ReportSaved(Model):
slug: str
+4
View File
@@ -42,6 +42,10 @@ class Settings(BaseSettings):
api_cors_origins: list[str] = ["http://localhost:3000"]
# Bearer token for moderation/admin endpoints. Empty = disabled (use the CLI).
admin_token: str | None = None
# Shared secret of the web app for writing reports on behalf of a signed-in user. Empty = reports are read-only.
author_token: str | None = None
# Members of these login groups (Authelia Remote-Groups) may edit and withdraw any report.
report_editor_groups: list[str] = ["admins"]
@lru_cache
+11 -1
View File
@@ -14,11 +14,21 @@ from politrack.queries.common import SourceFilter
from politrack.queries.money import list_money, money_summary, social_feed, wiki_edits
from politrack.queries.organizations import get_organization, get_party, list_organizations, list_parties
from politrack.queries.people import former_overview, get_person, list_persons, person_network
from politrack.queries.reports import (
ReportError,
Viewer,
create_report,
get_report,
list_reports,
resolve_references,
update_report,
)
from politrack.queries.search import search
from politrack.queries.votes import list_votes, person_votes, vote_detail
__all__ = [
"SourceFilter", "calendar", "former_overview", "get_organization", "get_party", "get_person", "list_claims",
"ReportError", "SourceFilter", "Viewer", "calendar", "create_report", "get_report", "list_reports",
"resolve_references", "update_report", "former_overview", "get_organization", "get_party", "get_person", "list_claims",
"list_money", "list_organizations", "list_parties", "list_persons", "list_sources", "list_topics", "list_votes",
"money_summary", "pending_claims", "recent_runs", "person_network", "person_votes", "search", "set_review", "social_feed",
"source_freshness", "stats", "timeline_histogram", "vote_detail", "wiki_edits",
+4 -2
View File
@@ -22,6 +22,7 @@ def list_claims(
until: date | None = None,
q: str | None = None,
claim_id: int | None = None,
claim_ids: list[int] | None = None,
include_pending: bool = False,
limit: int = 50,
offset: int = 0,
@@ -29,7 +30,7 @@ def list_claims(
source_sql, params = sources.sql("s")
params.update({
"person": person, "party": party, "organization": organization, "claim_types": claim_types, "topics": topics, "since": since,
"until": until, "q": q, "claim_id": claim_id, "limit": limit, "offset": offset, "include_pending": include_pending,
"until": until, "q": q, "claim_id": claim_id, "claim_ids": claim_ids, "limit": limit, "offset": offset, "include_pending": include_pending,
})
return conn.execute(
f"""
@@ -62,7 +63,7 @@ def list_claims(
WHERE e.claim_id = c.id AND {source_sql}
) ev
WHERE ev.evidence IS NOT NULL AND {VISIBLE}
AND (%(claim_id)s::bigint IS NOT NULL OR {NOT_PART_VOTE})
AND (%(claim_id)s::bigint IS NOT NULL OR %(claim_ids)s::bigint[] IS NOT NULL OR {NOT_PART_VOTE})
AND (%(person)s::text IS NULL OR p.slug = %(person)s OR cpp.slug = %(person)s)
AND (%(party)s::text IS NULL OR o.slug = %(party)s
OR c.counterpart_org_id = (SELECT id FROM organization WHERE slug = %(party)s))
@@ -76,6 +77,7 @@ def list_claims(
AND (%(until)s::date IS NULL OR COALESCE(c.occurred_at::date, c.valid_from) <= %(until)s)
AND (%(q)s::text IS NULL OR c.summary_de ILIKE '%%' || %(q)s || '%%')
AND (%(claim_id)s::bigint IS NULL OR c.id = %(claim_id)s)
AND (%(claim_ids)s::bigint[] IS NULL OR c.id = ANY(%(claim_ids)s))
ORDER BY COALESCE(c.occurred_at, c.valid_from::timestamptz, c.created_at) DESC, c.id DESC
LIMIT %(limit)s OFFSET %(offset)s
""",
+268
View File
@@ -0,0 +1,268 @@
"""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 WHERE x.report_id = r.id AND x.ref_type = 'claim') AS claim_count,
(SELECT count(*) FROM report_reference x WHERE x.report_id = r.id AND x.ref_type = 'claim' 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 = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) 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
+31
View File
@@ -0,0 +1,31 @@
"""Reference syntax of user reports (the web app's ReportBody renders the same syntax)."""
from politrack.queries.reports import parse_references
BODY = """## Spenden 2017
[[angabe:123]]
Die Spende ist in [dieser Angabe](angabe:456) belegt, siehe auch [den Bericht](bericht:spenden-2017-2)
und [Pierer](person:stefan-pierer) bei der [ÖVP](org:oevp).
[[Bericht: wahlkampf-2017 ]]
[[angabe:123]] mitten im Satz ist keine Einbettung, [kaputt](angabe:abc) und [[angabe:x]] auch nicht.
[[claim:789]]
"""
def test_references_are_parsed_once_with_embedding_winning():
refs = parse_references(BODY)
assert refs == [
("claim", "123", True), ("report", "wahlkampf-2017", True), ("claim", "789", True),
("claim", "456", False), ("report", "spenden-2017-2", False), ("person", "stefan-pierer", False),
("organization", "oevp", False),
]
def test_inline_reference_to_an_embedded_claim_stays_embedded():
assert parse_references("[[angabe:5]]\n\nWie [oben](angabe:5) gezeigt") == [("claim", "5", True)]
def test_invalid_keys_are_ignored():
assert parse_references("[x](person:Hans Wurst) [y](bericht:../admin) [z](angabe:12a)") == []