From 9f0e2fc11511638d01444143cc22f3b2cfb8fe55 Mon Sep 17 00:00:00 2001 From: Simon Diesenreiter Date: Fri, 20 Nov 2026 10:19:50 +0100 Subject: [PATCH] reports: user articles that embed claims under a database seal and link each other - /berichte lists published reports; /berichte/ 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 --- .env.example | 5 + backend/migrations/0011_reports.sql | 52 +++ backend/politrack/api/main.py | 72 +++- backend/politrack/api/schemas.py | 52 +++ backend/politrack/config.py | 4 + backend/politrack/queries/__init__.py | 12 +- backend/politrack/queries/claims.py | 6 +- backend/politrack/queries/reports.py | 268 +++++++++++++++ backend/tests/test_reports.py | 31 ++ docker-compose.yml | 3 + docs/data-model.md | 13 +- docs/deployment-unraid.md | 26 ++ docs/design/design-system.md | 18 +- docs/roadmap.md | 5 +- web/messages/de.json | 98 +++++- web/messages/en.json | 98 +++++- web/src/app/[locale]/angaben/[id]/page.tsx | 11 +- web/src/app/[locale]/berichte/[slug]/page.tsx | 78 +++++ web/src/app/[locale]/berichte/page.tsx | 46 +++ .../berichte/verfassen/[slug]/page.tsx | 59 ++++ .../[locale]/berichte/verfassen/actions.ts | 46 +++ .../[locale]/berichte/verfassen/neu/page.tsx | 35 ++ .../app/[locale]/berichte/verfassen/page.tsx | 42 +++ web/src/app/api/referenz-suche/route.ts | 35 ++ web/src/components/ReportBody.tsx | 210 ++++++++++++ web/src/components/ReportCard.tsx | 41 +++ web/src/components/ReportEditor.tsx | 167 +++++++++ web/src/components/nav.ts | 5 +- web/src/lib/api-types.ts | 52 +++ web/src/lib/api.ts | 47 ++- web/src/lib/viewer.ts | 42 +++ web/src/styles/components.css | 316 ++++++++++++++++++ 32 files changed, 1974 insertions(+), 21 deletions(-) create mode 100644 backend/migrations/0011_reports.sql create mode 100644 backend/politrack/queries/reports.py create mode 100644 backend/tests/test_reports.py create mode 100644 web/src/app/[locale]/berichte/[slug]/page.tsx create mode 100644 web/src/app/[locale]/berichte/page.tsx create mode 100644 web/src/app/[locale]/berichte/verfassen/[slug]/page.tsx create mode 100644 web/src/app/[locale]/berichte/verfassen/actions.ts create mode 100644 web/src/app/[locale]/berichte/verfassen/neu/page.tsx create mode 100644 web/src/app/[locale]/berichte/verfassen/page.tsx create mode 100644 web/src/app/api/referenz-suche/route.ts create mode 100644 web/src/components/ReportBody.tsx create mode 100644 web/src/components/ReportCard.tsx create mode 100644 web/src/components/ReportEditor.tsx create mode 100644 web/src/lib/viewer.ts diff --git a/.env.example b/.env.example index a133baf..36ba332 100644 --- a/.env.example +++ b/.env.example @@ -31,6 +31,11 @@ POLITRACK_API_CORS_ORIGINS=["http://localhost:3000"] # Moderation endpoints (/api/v1/review, /api/v1/admin/runs). Leave empty to moderate via the CLI only. # POLITRACK_ADMIN_TOKEN= +# Reports written by signed-in users (docs/deployment-unraid.md, "Reports and sign-in"). Both empty = read-only. +# POLITRACK_AUTHOR_TOKEN= shared by web and api (e.g. openssl rand -hex 32) +# POLITRACK_PROXY_SECRET= the reverse proxy sends it as X-Politrack-Proxy (e.g. openssl rand -hex 32) +# POLITRACK_REPORT_EDITOR_GROUPS=["admins"] login groups that may edit and withdraw any report + # Nightly database dumps (backup service). Ideally on a different disk or share than DATA_DIR. # BACKUP_DIR=/mnt/user/backups/politrack # BACKUP_KEEP_DAYS=14 diff --git a/backend/migrations/0011_reports.sql b/backend/migrations/0011_reports.sql new file mode 100644 index 0000000..dac3334 --- /dev/null +++ b/backend/migrations/0011_reports.sql @@ -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); diff --git a/backend/politrack/api/main.py b/backend/politrack/api/main.py index 1f6e9a2..b949d0f 100644 --- a/backend/politrack/api/main.py +++ b/backend/politrack/api/main.py @@ -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: diff --git a/backend/politrack/api/schemas.py b/backend/politrack/api/schemas.py index e10282e..d962dc0 100644 --- a/backend/politrack/api/schemas.py +++ b/backend/politrack/api/schemas.py @@ -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 diff --git a/backend/politrack/config.py b/backend/politrack/config.py index d5cdb9e..07f5cc9 100644 --- a/backend/politrack/config.py +++ b/backend/politrack/config.py @@ -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 diff --git a/backend/politrack/queries/__init__.py b/backend/politrack/queries/__init__.py index 2dba341..8dd9b1f 100644 --- a/backend/politrack/queries/__init__.py +++ b/backend/politrack/queries/__init__.py @@ -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", diff --git a/backend/politrack/queries/claims.py b/backend/politrack/queries/claims.py index 09c1905..5552a61 100644 --- a/backend/politrack/queries/claims.py +++ b/backend/politrack/queries/claims.py @@ -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 """, diff --git a/backend/politrack/queries/reports.py b/backend/politrack/queries/reports.py new file mode 100644 index 0000000..044b5ef --- /dev/null +++ b/backend/politrack/queries/reports.py @@ -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 diff --git a/backend/tests/test_reports.py b/backend/tests/test_reports.py new file mode 100644 index 0000000..f52bb4b --- /dev/null +++ b/backend/tests/test_reports.py @@ -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)") == [] diff --git a/docker-compose.yml b/docker-compose.yml index edfb80f..793c376 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -110,6 +110,9 @@ services: POLITRACK_LEGAL_ADDRESS: ${POLITRACK_LEGAL_ADDRESS:-} POLITRACK_LEGAL_EMAIL: ${POLITRACK_LEGAL_EMAIL:-} POLITRACK_CORRECTIONS_EMAIL: ${POLITRACK_CORRECTIONS_EMAIL:-} + # Reports: sign-in from the reverse proxy (see docs/deployment-unraid.md, "Reports and sign-in"). + POLITRACK_AUTHOR_TOKEN: ${POLITRACK_AUTHOR_TOKEN:-} + POLITRACK_PROXY_SECRET: ${POLITRACK_PROXY_SECRET:-} ports: - "${WEB_PORT:-3000}:3000" depends_on: diff --git a/docs/data-model.md b/docs/data-model.md index 5e30a94..8086cde 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -18,6 +18,7 @@ organization ─┘ ╱ │ ╲ role, vote_position(→vo social_account │ event_participant(→event), statement, legal_proceeding chunk (text + embedding for RAG) run, state, app_user operations +app_user ──< report ──< report_reference (→ claim, report, person, organization), report_revision ``` ## Entities @@ -117,4 +118,14 @@ across outlets (independence for corroboration). `fetch_log` (every HTTP fetch: request, status, sha256, stored body, parse state), `run` (every adapter / enricher run with stats and errors), `state` (adapter cursors), `chunk` (text chunks + pgvector -embeddings), `app_user` (reviewers). +embeddings), `app_user` (reviewers and report authors, from the proxy login). + +## Reports + +User-written articles (`report`, migration 0011). `body` is Markdown with references: `[[angabe:ID]]` on its own +line embeds a claim, `[[bericht:slug]]` another report; `[text](angabe:ID)`, `(bericht:slug)`, `(person:slug)` and +`(org:slug)` link inline. At every save the references are parsed into `report_reference` (drives "used in reports" +on claim pages and the backlinks between reports) and the version is copied to `report_revision`. Slugs are fixed at +creation. `status`: `draft` (author only), `published`, `withdrawn` (unlisted, the page says so). Embedded claims +are resolved like permalinks: no visitor filter, merged claims resolve to the survivor, hidden ones are reported as +missing. Writes only via the API's author endpoints (`POLITRACK_AUTHOR_TOKEN`, see deployment-unraid.md). diff --git a/docs/deployment-unraid.md b/docs/deployment-unraid.md index 936d86a..d22785f 100644 --- a/docs/deployment-unraid.md +++ b/docs/deployment-unraid.md @@ -90,6 +90,32 @@ bge-m3 runs fine on CPU for this data volume. With an NVIDIA GPU, add a device r VPN-only, or protect them with SSO or an API key at the proxy. * Read [legal.md](legal.md) before going public (Impressum, privacy policy, §7b MedienG). +## Reports and sign-in + +Anyone can read published reports; writing (`/berichte/verfassen…`) needs a login at the reverse proxy. The proxy +authenticates (Authelia, Authentik …) and passes `Remote-User`, `Remote-Name`, `Remote-Email` and `Remote-Groups` +to the `web` container. The web app trusts these headers only when the request also carries +`X-Politrack-Proxy: $POLITRACK_PROXY_SECRET`, which only the proxy sets, so a request straight to the web port +can't pretend to be someone. The web app then calls the API's write endpoints with +`Authorization: Bearer $POLITRACK_AUTHOR_TOKEN` (read by both `web` and `api` from `.env`). + +1. Put `POLITRACK_AUTHOR_TOKEN` and `POLITRACK_PROXY_SECRET` (random, e.g. `openssl rand -hex 32`) into `.env` and + `docker compose up -d web api`. +2. SWAG: in the site's `location /` after the Authelia includes, add + `proxy_set_header X-Politrack-Proxy "";` and reload nginx. The SWAG Authelia include already sets + the `Remote-*` headers (empty when nobody is signed in, which also overwrites forged ones). +3. Authelia: if the site bypasses the login on the LAN, add a rule *before* the bypass that requires a login for + the write paths, e.g. + ```yaml + - domain: 'politrack.example.org' + resources: ['^/(en/)?berichte/verfassen([/?].*)?$'] + policy: 'one_factor' + ``` + Pages behind a bypass rule see nobody as signed in (no edit buttons there); the write pages always do. + +Members of `POLITRACK_REPORT_EDITOR_GROUPS` (default `["admins"]`) may edit and withdraw any report. Every saved +version stays in `report_revision`. + ## Monitoring * `docker compose exec api politrack status` – recent runs with stats and errors (table `run`). diff --git a/docs/design/design-system.md b/docs/design/design-system.md index ae769bd..cee209d 100644 --- a/docs/design/design-system.md +++ b/docs/design/design-system.md @@ -27,7 +27,8 @@ All five stylesheets are imported once, in order, by `src/app/[locale]/layout.ts * **Only tokens** for colour, spacing, radius and type. The exceptions are deliberate: party colours (from the data), platform brand colours, and the favicon. * **Server first.** Pages and most components are async server components. Client components exist only - where the browser must act: `ThemeSwitcher`, `LocaleSwitcher`, `NavLink`, `SettingsForm`, the error page. + where the browser must act: `ThemeSwitcher`, `LocaleSwitcher`, `NavLink`, `SettingsForm`, `ReportEditor`, + the error page. * **No JavaScript needed** for navigation, filters, tabs, disclosures or the mobile menu: links, GET forms, `
` and one checkbox toggle. @@ -176,6 +177,21 @@ same mark as the favicon. | `SocialFeed` | `SocialFeed.tsx` | post cards, no embeds | | `SearchForm` | `SearchForm.tsx` | the big search field (optional date range) | | `SettingsForm` (client) | `SettingsForm.tsx` | "Meine Filter" | +| `ReportBody`, `ClaimEmbed` | `ReportBody.tsx` | a report's text (Markdown subset, built as React elements, never raw HTML); embedded claim card under its database seal | +| `ReportCard`, `ReportList` | `ReportCard.tsx` | a report in lists and embedded in other reports: author, date, how many claims (official) it rests on | +| `ReportEditor` (client) | `ReportEditor.tsx` | title, summary, body and the reference picker (claims, reports, persons) | + +### Reports + +A report mixes the author's text with facts from the database, and the reader must always see which is which: + +* Embedded claims (`[[angabe:ID]]`) are the full `ClaimCard` inside `.claim-embed`, under a seal: green shield + "Amtliche Daten" when a source is official (`source.kind = 'official'`), accent "Aus der Datenbank" otherwise. +* Inline references (`[text](angabe:ID)`) are tinted the same way and end with the seal icon; links to reports, + persons and organisations are ordinary links. A reference that no longer resolves is struck through, never + silently dropped. +* The `.report-basis` box under the header says how many claims the report rests on and that the text around + them is the author's. The list page carries the same disclaimer as a notice. ### The claim card diff --git a/docs/roadmap.md b/docs/roadmap.md index 3532085..c3abc58 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -75,7 +75,10 @@ Next.js frontend (de/en), Docker Compose for Unraid. - [ ] Review queue for editors in the web UI (today `politrack review`) - [ ] Community link submissions and a corrections/right-of-reply form - [ ] Alerts (e-mail/RSS) for followed politicians -- [ ] Optional accounts via reverse-proxy SSO using `app_user` +- [x] Accounts via reverse-proxy SSO using `app_user` (2026-11-20, for reports; see deployment-unraid.md) +- [x] Reports: user articles embedding claims with a database seal, linking each other (`/berichte`, 2026-11-20) +- [ ] Reports, next: charts and money tables as embeds (`[[geld:…]]`), revision history page, comments/right of + reply, editor review before publication if the instance goes public, MCP tool for reading reports - [ ] Partnerships: MeineAbgeordneten, Parteispenden.at, APA (OTS full-text licence) - [ ] Map view of trips and appearances - [ ] Semantic search with embeddings (`POLITRACK_OLLAMA_URL`): parked by the owner on 2026-11-09, full-text search only for now diff --git a/web/messages/de.json b/web/messages/de.json index d85d1cd..d7e3f7a 100644 --- a/web/messages/de.json +++ b/web/messages/de.json @@ -18,7 +18,8 @@ "social": "Social Media", "wikipedia": "Wikipedia-Bearbeitungen", "imprint": "Impressum", - "privacy": "Datenschutz" + "privacy": "Datenschutz", + "reports": "Berichte" }, "Imprint": { "title": "Impressum", @@ -159,7 +160,7 @@ }, "showPartVotes": "Auch Änderungsanträge und Teilabstimmungen anzeigen", "hidePartVotes": "Nur Abstimmungen über ganze Texte anzeigen", - "factionVoteNote":"Im Nationalrat wird meist per Aufstehen abgestimmt; offiziell protokolliert ist dann nur das Stimmverhalten der Fraktion. Bei namentlichen Abstimmungen zeigen wir die eigene Stimme – und ob sie von der Fraktion abweicht.", + "factionVoteNote": "Im Nationalrat wird meist per Aufstehen abgestimmt; offiziell protokolliert ist dann nur das Stimmverhalten der Fraktion. Bei namentlichen Abstimmungen zeigen wir die eigene Stimme – und ob sie von der Fraktion abweicht.", "roleCorroborated": "mehrfach belegt", "unverified": "laut Wikidata – nicht amtlich bestätigt", "accountUnverified": "Laut Wikidata – nicht amtlich bestätigt", @@ -642,6 +643,97 @@ "crumb": "Angabe #{id}", "cite": "Zitieren", "citation": "Politrack: „{summary}“. Angabe #{id}, abgerufen am {date}. {url}", - "filtersIgnored": "Diese Seite zeigt die Angabe mit allen Quellen – unabhängig von deinen Filtern, damit ein geteilter Link für alle gleich aussieht." + "filtersIgnored": "Diese Seite zeigt die Angabe mit allen Quellen – unabhängig von deinen Filtern, damit ein geteilter Link für alle gleich aussieht.", + "inReports": "In Berichten", + "embedHint": "In einem Bericht einbetten mit", + "newReport": "In neuem Bericht verwenden" + }, + "Reports": { + "title": "Berichte", + "eyebrow": "Bericht", + "intro": "Analysen und Zusammenhänge, geschrieben von Nutzer:innen. Jede eingebettete Angabe kommt direkt aus der Datenbank, mit ihren Belegen.", + "disclaimer": "Berichte geben die Sicht ihrer Autor:innen wieder. Belegt sind nur die markierten Angaben aus der Datenbank – Schlussfolgerungen daraus sind Meinung.", + "write": "Bericht verfassen", + "search": "Suche", + "searchPlaceholder": "Titel oder Vorspann …", + "none": "Noch keine Berichte.", + "byline": "Von {author}, {date}", + "edited": "zuletzt bearbeitet {date}", + "edit": "Bearbeiten", + "draftNotice": "Entwurf: nur du siehst diesen Bericht.", + "withdrawnNotice": "Dieser Bericht wurde von seinen Autor:innen zurückgezogen.", + "basisLabel": "Grundlage des Berichts", + "basis": "{claims, plural, =0 {Keine Angaben aus der Datenbank} one {Stützt sich auf # Angabe aus der Datenbank} other {Stützt sich auf # Angaben aus der Datenbank}}{official, plural, =0 {} other {, davon # aus amtlichen Quellen}}.", + "basisExplain": "Angaben mit dem Siegel sind von Politrack belegt und verlinken auf ihre Quellen. Der Text dazwischen stammt von {author}.", + "backlinks": "Berichte, die hierauf verweisen", + "status": { + "draft": "Entwurf", + "published": "Veröffentlicht", + "withdrawn": "Zurückgezogen" + }, + "sealOfficial": "Amtliche Daten", + "sealDatabase": "Aus der Datenbank", + "sealDetail": "Angabe Nr. {id} · {sources}", + "refClaim": "Angabe Nr. {id} aus der Politrack-Datenbank", + "refClaimOfficial": "Angabe Nr. {id} aus der Politrack-Datenbank, belegt durch eine amtliche Quelle", + "refReport": "Bericht: {title}", + "refMissing": "Verweis nicht (mehr) verfügbar", + "claimMissing": "Angabe Nr. {id} ist nicht verfügbar (ausgeblendet, in Prüfung oder gelöscht).", + "reportMissing": "Der verlinkte Bericht ist nicht verfügbar." + }, + "ReportEditor": { + "reports": "Berichte", + "mine": "Meine Berichte", + "mineIntro": "Angemeldet als {name}. Entwürfe siehst nur du.", + "mineNone": "Du hast noch keine Berichte geschrieben.", + "new": "Neuer Bericht", + "newIntro": "Verbinde Angaben aus der Datenbank zu einer Geschichte. Speichere zuerst als Entwurf – darunter erscheint dann die Vorschau.", + "editTitle": "Bericht bearbeiten", + "view": "Zum Bericht", + "signInNeeded": "Zum Schreiben musst du angemeldet sein. Öffne Politrack über die Adresse mit Anmeldung (nicht über die direkte LAN-Adresse des Servers).", + "title": "Titel", + "lede": "Vorspann", + "ledeHint": "Ein, zwei Sätze: worum geht es?", + "body": "Text", + "text": "Text", + "heading": "Überschrift", + "list": "Liste", + "quote": "Zitat", + "syntax": "Wie verweise ich auf Angaben?", + "helpEmbed": "in einer eigenen Zeile: bettet die Angabe Nr. 123 mit ihren Belegen ein", + "helpLink": "verlinkt die Angabe im Fließtext (mit Siegel)", + "helpReport": "bettet einen anderen Bericht ein bzw. verlinkt ihn", + "helpOther": "verlinkt eine Person, Organisation oder Webseite", + "helpFormat": "Überschrift, fett, kursiv, Liste, Zitat", + "lang": "Sprache", + "status": "Status", + "statusDraft": "Entwurf (nur für mich)", + "statusPublished": "Veröffentlicht", + "statusWithdrawn": "Zurückgezogen", + "responsibility": "Du schreibst unter deinem Namen. Bleib fair: Verbindungen sind keine Vorwürfe, und bei Verfahren gilt die Unschuldsvermutung. Jede gespeicherte Fassung wird aufbewahrt.", + "save": "Speichern", + "saving": "Speichert …", + "saved": "Gespeichert.", + "preview": "Vorschau", + "previewHint": "So sieht die zuletzt gespeicherte Fassung aus.", + "missingClaims": "Diese Angaben gibt es nicht oder sie sind nicht öffentlich: {ids}", + "pickerTitle": "Angaben finden", + "pickerType": "Was suchen?", + "type": { + "claim": "Angaben", + "report": "Berichte", + "person": "Personen" + }, + "pickerPlaceholder": "Stichwort, Name oder Nr. …", + "pickerSearch": "Suchen", + "pickerNone": "Nichts gefunden.", + "pickerHint": "„Einbetten“ fügt die Karte an der Cursorposition ein, „Als Link“ verlinkt den markierten Text.", + "embed": "Einbetten", + "asLink": "Als Link", + "official": "amtlich", + "errorSignIn": "Du bist nicht (mehr) angemeldet. Lade die Seite neu.", + "errorNotYours": "Diesen Bericht kannst du nicht bearbeiten.", + "errorInvalid": "Nicht gespeichert: {detail}", + "errorUnknown": "Nicht gespeichert – bitte später noch einmal versuchen." } } diff --git a/web/messages/en.json b/web/messages/en.json index a712649..c020c67 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -18,7 +18,8 @@ "social": "Social media", "wikipedia": "Wikipedia edits", "imprint": "Legal notice", - "privacy": "Privacy" + "privacy": "Privacy", + "reports": "Reports" }, "Home": { "headline": "Austrian politics – traceable.", @@ -124,7 +125,7 @@ }, "showPartVotes": "Also show amendments and part votes", "hidePartVotes": "Show votes on whole texts only", - "factionVoteNote":"The National Council mostly votes by standing up; then only each faction's vote is recorded. For roll-call votes we show the person's own vote – and whether it differs from their faction.", + "factionVoteNote": "The National Council mostly votes by standing up; then only each faction's vote is recorded. For roll-call votes we show the person's own vote – and whether it differs from their faction.", "roleCorroborated": "corroborated", "unverified": "per Wikidata – not officially confirmed", "accountUnverified": "According to Wikidata – not officially confirmed", @@ -642,6 +643,97 @@ "crumb": "Fact #{id}", "cite": "Cite", "citation": "Politrack: “{summary}”. Fact #{id}, retrieved {date}. {url}", - "filtersIgnored": "This page shows the fact with all its sources – regardless of your filters, so a shared link looks the same for everyone." + "filtersIgnored": "This page shows the fact with all its sources – regardless of your filters, so a shared link looks the same for everyone.", + "inReports": "In reports", + "embedHint": "Embed it in a report with", + "newReport": "Use in a new report" + }, + "Reports": { + "title": "Reports", + "eyebrow": "Report", + "intro": "Analyses and connections written by users. Every embedded fact comes straight from the database, with its sources.", + "disclaimer": "Reports reflect their authors' views. Only the marked facts from the database are backed by sources – conclusions drawn from them are opinion.", + "write": "Write a report", + "search": "Search", + "searchPlaceholder": "Title or summary …", + "none": "No reports yet.", + "byline": "By {author}, {date}", + "edited": "last edited {date}", + "edit": "Edit", + "draftNotice": "Draft: only you can see this report.", + "withdrawnNotice": "This report has been withdrawn by its author.", + "basisLabel": "What this report is based on", + "basis": "{claims, plural, =0 {No facts from the database} one {Based on # fact from the database} other {Based on # facts from the database}}{official, plural, =0 {} other {, # of them from official sources}}.", + "basisExplain": "Facts with the seal are backed by Politrack and link to their sources. The text around them is by {author}.", + "backlinks": "Reports linking here", + "status": { + "draft": "Draft", + "published": "Published", + "withdrawn": "Withdrawn" + }, + "sealOfficial": "Official data", + "sealDatabase": "From the database", + "sealDetail": "Fact no. {id} · {sources}", + "refClaim": "Fact no. {id} from the Politrack database", + "refClaimOfficial": "Fact no. {id} from the Politrack database, backed by an official source", + "refReport": "Report: {title}", + "refMissing": "Reference not (or no longer) available", + "claimMissing": "Fact no. {id} is not available (hidden, under review or deleted).", + "reportMissing": "The linked report is not available." + }, + "ReportEditor": { + "reports": "Reports", + "mine": "My reports", + "mineIntro": "Signed in as {name}. Only you can see drafts.", + "mineNone": "You haven't written any reports yet.", + "new": "New report", + "newIntro": "Connect facts from the database into a story. Save as a draft first – the preview then appears below.", + "editTitle": "Edit report", + "view": "View report", + "signInNeeded": "You need to be signed in to write. Open Politrack via its address with login (not the server's direct LAN address).", + "title": "Title", + "lede": "Summary", + "ledeHint": "One or two sentences: what is it about?", + "body": "Text", + "text": "text", + "heading": "Heading", + "list": "List", + "quote": "Quote", + "syntax": "How do I reference facts?", + "helpEmbed": "on a line of its own: embeds fact no. 123 with its sources", + "helpLink": "links the fact inline (with seal)", + "helpReport": "embeds or links another report", + "helpOther": "links a person, organisation or web page", + "helpFormat": "heading, bold, italic, list, quote", + "lang": "Language", + "status": "Status", + "statusDraft": "Draft (only me)", + "statusPublished": "Published", + "statusWithdrawn": "Withdrawn", + "responsibility": "You write under your own name. Be fair: connections are not accusations, and the presumption of innocence applies to proceedings. Every saved version is kept.", + "save": "Save", + "saving": "Saving …", + "saved": "Saved.", + "preview": "Preview", + "previewHint": "This is how the last saved version looks.", + "missingClaims": "These facts don't exist or aren't public: {ids}", + "pickerTitle": "Find facts", + "pickerType": "Search for", + "type": { + "claim": "Facts", + "report": "Reports", + "person": "People" + }, + "pickerPlaceholder": "Keyword, name or no. …", + "pickerSearch": "Search", + "pickerNone": "Nothing found.", + "pickerHint": "\"Embed\" inserts the card at the cursor, \"As link\" links the selected text.", + "embed": "Embed", + "asLink": "As link", + "official": "official", + "errorSignIn": "You are not (or no longer) signed in. Reload the page.", + "errorNotYours": "You can't edit this report.", + "errorInvalid": "Not saved: {detail}", + "errorUnknown": "Not saved – please try again later." } } diff --git a/web/src/app/[locale]/angaben/[id]/page.tsx b/web/src/app/[locale]/angaben/[id]/page.tsx index 02c9341..f66e9db 100644 --- a/web/src/app/[locale]/angaben/[id]/page.tsx +++ b/web/src/app/[locale]/angaben/[id]/page.tsx @@ -3,9 +3,11 @@ import {headers} from 'next/headers'; import {notFound} from 'next/navigation'; import {getTranslations, setRequestLocale} from 'next-intl/server'; import {ClaimCard} from '@/components/ClaimList'; +import {Icon} from '@/components/Icon'; import {Notice} from '@/components/Notice'; import {Breadcrumbs, type Crumb, SectionHead} from '@/components/PageHeader'; -import {getPathname} from '@/i18n/navigation'; +import {ReportList} from '@/components/ReportCard'; +import {getPathname, Link} from '@/i18n/navigation'; import {api, NotFoundError, type Claim} from '@/lib/api'; import {formatDate} from '@/lib/format'; @@ -35,6 +37,7 @@ export default async function ClaimPage({params}: Props) { const t = await getTranslations('ClaimPage'); const claim = await loadClaim(id); const summary = locale === 'en' && claim.summary_en ? claim.summary_en : claim.summary_de; + const reports = await api.reports({claim: claim.id, limit: 20}).catch(() => []); const h = await headers(); const host = h.get('x-forwarded-host') ?? h.get('host') ?? 'localhost'; @@ -58,6 +61,12 @@ export default async function ClaimPage({params}: Props) {

{t('citation', {summary, id: String(claim.id), date: today, url})}

{t('filtersIgnored')} +
+ +

{t('embedHint')} [[angabe:{claim.id}]]

+

{t('newReport')}

+ {reports.length > 0 && } +
); } diff --git a/web/src/app/[locale]/berichte/[slug]/page.tsx b/web/src/app/[locale]/berichte/[slug]/page.tsx new file mode 100644 index 0000000..4fe33bb --- /dev/null +++ b/web/src/app/[locale]/berichte/[slug]/page.tsx @@ -0,0 +1,78 @@ +import type {Metadata} from 'next'; +import {notFound} from 'next/navigation'; +import {getTranslations, setRequestLocale} from 'next-intl/server'; +import {Icon} from '@/components/Icon'; +import {Notice} from '@/components/Notice'; +import {PageHeader, SectionHead} from '@/components/PageHeader'; +import {ReportBody} from '@/components/ReportBody'; +import {ReportList} from '@/components/ReportCard'; +import {Link} from '@/i18n/navigation'; +import {api, NotFoundError, type ReportDetail} from '@/lib/api'; +import {formatDate} from '@/lib/format'; + +type Props = {params: Promise<{locale: string; slug: string}>}; + +async function loadReport(slug: string): Promise { + if (!/^[a-z0-9][a-z0-9-]{0,200}$/.test(slug)) notFound(); + try { + return await api.report(slug); + } catch (error) { + if (error instanceof NotFoundError) notFound(); + throw error; + } +} + +export async function generateMetadata({params}: Props): Promise { + const {slug} = await params; + const report = await loadReport(slug); + return {title: report.title, description: report.lede ?? undefined}; +} + +export default async function ReportPage({params}: Props) { + const {locale, slug} = await params; + setRequestLocale(locale); + const t = await getTranslations('Reports'); + const report = await loadReport(slug); + const lang = report.lang !== locale ? report.lang : undefined; + const published = report.published_at ?? report.created_at; + const edited = report.revision_count > 1 && report.updated_at.slice(0, 10) !== published.slice(0, 10); + + return ( +
+ {report.title}} + lede={report.lede ? {report.lede} : undefined} + meta={<> + {t('byline', {author: report.author_name, date: formatDate(published, locale)})} + {edited && <> · {t('edited', {date: formatDate(report.updated_at, locale)})}} + } + actions={report.can_edit ? ( + {t('edit')} + ) : undefined} + /> + {report.status === 'draft' && {t('draftNotice')}} + {report.status === 'withdrawn' && {t('withdrawnNotice')}} + + + +
+ +
+ + {report.backlinks.length > 0 && ( +
+ + +
+ )} +
+ ); +} diff --git a/web/src/app/[locale]/berichte/page.tsx b/web/src/app/[locale]/berichte/page.tsx new file mode 100644 index 0000000..c5aa1dc --- /dev/null +++ b/web/src/app/[locale]/berichte/page.tsx @@ -0,0 +1,46 @@ +import type {Metadata} from 'next'; +import {getTranslations, setRequestLocale} from 'next-intl/server'; +import {countActive, Field, FilterBar} from '@/components/FilterBar'; +import {Icon} from '@/components/Icon'; +import {Notice} from '@/components/Notice'; +import {PageHeader} from '@/components/PageHeader'; +import {Pagination} from '@/components/Pagination'; +import {ReportList} from '@/components/ReportCard'; +import {Link} from '@/i18n/navigation'; +import {api} from '@/lib/api'; + +const PAGE = 30; + +type Props = { + params: Promise<{locale: string}>; + searchParams: Promise<{q?: string; page?: string}>; +}; + +export async function generateMetadata({params}: Props): Promise { + const {locale} = await params; + const t = await getTranslations({locale, namespace: 'Reports'}); + return {title: t('title')}; +} + +/** All published reports, newest first. */ +export default async function ReportsPage({params, searchParams}: Props) { + const {locale} = await params; + setRequestLocale(locale); + const sp = await searchParams; + const t = await getTranslations('Reports'); + const page = Math.max(1, Number(sp.page) || 1); + const reports = await api.reports({q: sp.q, limit: PAGE, offset: (page - 1) * PAGE}); + + return ( + <> + {t('write')}} /> + {t('disclaimer')} + + + + + + + ); +} diff --git a/web/src/app/[locale]/berichte/verfassen/[slug]/page.tsx b/web/src/app/[locale]/berichte/verfassen/[slug]/page.tsx new file mode 100644 index 0000000..647c335 --- /dev/null +++ b/web/src/app/[locale]/berichte/verfassen/[slug]/page.tsx @@ -0,0 +1,59 @@ +import type {Metadata} from 'next'; +import {notFound} from 'next/navigation'; +import {getTranslations, setRequestLocale} from 'next-intl/server'; +import {Icon} from '@/components/Icon'; +import {Notice} from '@/components/Notice'; +import {PageHeader, SectionHead} from '@/components/PageHeader'; +import {ReportBody} from '@/components/ReportBody'; +import {ReportEditor} from '@/components/ReportEditor'; +import {Link} from '@/i18n/navigation'; +import {api, NotFoundError} from '@/lib/api'; +import {getViewer} from '@/lib/viewer'; +import {updateReportAction} from '../actions'; + +type Props = {params: Promise<{locale: string; slug: string}>}; + +export async function generateMetadata({params}: Props): Promise { + const {locale} = await params; + const t = await getTranslations({locale, namespace: 'ReportEditor'}); + return {title: t('editTitle'), robots: {index: false}}; +} + +/** Edit a report, with the saved version rendered below as the preview. */ +export default async function EditReportPage({params}: Props) { + const {locale, slug} = await params; + setRequestLocale(locale); + const t = await getTranslations('ReportEditor'); + const crumbs = [{label: t('reports'), href: '/berichte'}, {label: t('mine'), href: '/berichte/verfassen'}, {label: t('editTitle')}]; + if (!(await getViewer())) { + return <>{t('signInNeeded')}; + } + if (!/^[a-z0-9][a-z0-9-]{0,200}$/.test(slug)) notFound(); + const report = await api.report(slug).catch((error) => { + if (error instanceof NotFoundError) notFound(); + throw error; + }); + if (!report.can_edit) return <>{t('errorNotYours')}; + const missing = report.references.missing_claims; + + return ( + <> + {t('view')} + : undefined} /> + +
+ +

{t('previewHint')}

+ {missing.length > 0 && {t('missingClaims', {ids: missing.join(', ')})}} +
+

{report.title}

+ {report.lede &&

{report.lede}

} + +
+
+ + ); +} diff --git a/web/src/app/[locale]/berichte/verfassen/actions.ts b/web/src/app/[locale]/berichte/verfassen/actions.ts new file mode 100644 index 0000000..86d66dd --- /dev/null +++ b/web/src/app/[locale]/berichte/verfassen/actions.ts @@ -0,0 +1,46 @@ +'use server'; + +// Saving reports. Runs on the server with the signed-in viewer (see lib/viewer.ts); the API checks ownership again. +import {revalidatePath} from 'next/cache'; +import {getLocale, getTranslations} from 'next-intl/server'; +import type {EditorState} from '@/components/ReportEditor'; +import {redirect} from '@/i18n/navigation'; +import {api, WriteError, type ReportInput} from '@/lib/api'; + +function readForm(form: FormData): ReportInput { + const text = (name: string) => String(form.get(name) ?? ''); + const lang = text('lang') === 'en' ? 'en' : 'de'; + const status = (['draft', 'published', 'withdrawn'] as const).find((s) => s === text('status')) ?? 'draft'; + return {title: text('title').trim(), lede: text('lede').trim() || null, body: text('body'), lang, status}; +} + +async function failure(error: unknown): Promise { + const t = await getTranslations('ReportEditor'); + if (error instanceof WriteError) { + if (error.status === 401) return {error: t('errorSignIn')}; + if (error.status === 404) return {error: t('errorNotYours')}; + return {error: t('errorInvalid', {detail: error.message})}; + } + return {error: t('errorUnknown')}; +} + +export async function createReportAction(_state: EditorState, form: FormData): Promise { + let slug: string; + try { + slug = (await api.createReport(readForm(form))).slug; + } catch (error) { + return failure(error); + } + redirect({href: `/berichte/verfassen/${slug}`, locale: await getLocale()}); + return {saved: true}; +} + +export async function updateReportAction(slug: string, _state: EditorState, form: FormData): Promise { + try { + await api.updateReport(slug, readForm(form)); + } catch (error) { + return failure(error); + } + revalidatePath('/[locale]/berichte', 'layout'); + return {saved: true}; +} diff --git a/web/src/app/[locale]/berichte/verfassen/neu/page.tsx b/web/src/app/[locale]/berichte/verfassen/neu/page.tsx new file mode 100644 index 0000000..a94d596 --- /dev/null +++ b/web/src/app/[locale]/berichte/verfassen/neu/page.tsx @@ -0,0 +1,35 @@ +import type {Metadata} from 'next'; +import {getTranslations, setRequestLocale} from 'next-intl/server'; +import {Notice} from '@/components/Notice'; +import {PageHeader} from '@/components/PageHeader'; +import {ReportEditor} from '@/components/ReportEditor'; +import {getViewer} from '@/lib/viewer'; +import {createReportAction} from '../actions'; + +type Props = {params: Promise<{locale: string}>; searchParams: Promise<{angabe?: string}>}; + +export async function generateMetadata({params}: Props): Promise { + const {locale} = await params; + const t = await getTranslations({locale, namespace: 'ReportEditor'}); + return {title: t('new'), robots: {index: false}}; +} + +/** A new report. ?angabe=123 starts the body with that claim embedded ("use in a report" on claim pages). */ +export default async function NewReportPage({params, searchParams}: Props) { + const {locale} = await params; + setRequestLocale(locale); + const sp = await searchParams; + const t = await getTranslations('ReportEditor'); + const crumbs = [{label: t('reports'), href: '/berichte'}, {label: t('mine'), href: '/berichte/verfassen'}, {label: t('new')}]; + if (!(await getViewer())) { + return <>{t('signInNeeded')}; + } + const start = sp.angabe && /^\d+$/.test(sp.angabe) ? `[[angabe:${sp.angabe}]]\n\n` : ''; + return ( + <> + + + + ); +} diff --git a/web/src/app/[locale]/berichte/verfassen/page.tsx b/web/src/app/[locale]/berichte/verfassen/page.tsx new file mode 100644 index 0000000..a4f42dd --- /dev/null +++ b/web/src/app/[locale]/berichte/verfassen/page.tsx @@ -0,0 +1,42 @@ +import type {Metadata} from 'next'; +import {getTranslations, setRequestLocale} from 'next-intl/server'; +import {Icon} from '@/components/Icon'; +import {Notice} from '@/components/Notice'; +import {PageHeader} from '@/components/PageHeader'; +import {ReportList} from '@/components/ReportCard'; +import {Link} from '@/i18n/navigation'; +import {api} from '@/lib/api'; +import {getViewer} from '@/lib/viewer'; + +type Props = {params: Promise<{locale: string}>}; + +export async function generateMetadata({params}: Props): Promise { + const {locale} = await params; + const t = await getTranslations({locale, namespace: 'ReportEditor'}); + return {title: t('mine'), robots: {index: false}}; +} + +/** The signed-in user's own reports (drafts included). Behind the proxy login, see docs/deployment-unraid.md. */ +export default async function MyReportsPage({params}: Props) { + const {locale} = await params; + setRequestLocale(locale); + const t = await getTranslations('ReportEditor'); + const viewer = await getViewer(); + if (!viewer) { + return ( + <> + + {t('signInNeeded')} + + ); + } + const reports = await api.reports({mine: true, limit: 200}); + return ( + <> + {t('new')}} /> + `/berichte/verfassen/${r.slug}`} empty={t('mineNone')} /> + + ); +} diff --git a/web/src/app/api/referenz-suche/route.ts b/web/src/app/api/referenz-suche/route.ts new file mode 100644 index 0000000..1695d4d --- /dev/null +++ b/web/src/app/api/referenz-suche/route.ts @@ -0,0 +1,35 @@ +// Search for the report editor's reference picker: claims, reports or persons matching a text. +// Read-only and limited to what the public pages show anyway. +import type {NextRequest} from 'next/server'; +import {api} from '@/lib/api'; + +export type ReferenceHit = {code: string; link: string; label: string; detail: string; official?: boolean}; + +export async function GET(request: NextRequest): Promise { + const q = (request.nextUrl.searchParams.get('q') ?? '').trim().slice(0, 200); + const type = request.nextUrl.searchParams.get('type') ?? 'claim'; + if (q.length < 2) return Response.json([]); + let hits: ReferenceHit[] = []; + try { + if (type === 'report') { + hits = (await api.reports({q, limit: 10})).map((r) => ({ + code: `[[bericht:${r.slug}]]`, link: `bericht:${r.slug}`, label: r.title, detail: r.author_name + })); + } else if (type === 'person') { + hits = (await api.persons({q, limit: 10, status: 'all'})).map((p) => ({ + code: `[${p.full_name}](person:${p.slug})`, link: `person:${p.slug}`, label: p.full_name, detail: p.slug + })); + } else { + const byId = /^\d+$/.test(q) ? await api.claim(q).then((c) => [c], () => []) : []; + const found = byId.length ? byId : await api.claims({q, limit: 12}); + hits = found.map((c) => ({ + code: `[[angabe:${c.id}]]`, link: `angabe:${c.id}`, label: c.summary_de, + detail: [`Nr. ${c.id}`, c.person_name, (c.occurred_at ?? c.valid_from ?? '').slice(0, 10)].filter(Boolean).join(' · '), + official: c.evidence.some((ev) => ev.source_kind === 'official') + })); + } + } catch { + return Response.json([], {status: 502}); + } + return Response.json(hits, {headers: {'Cache-Control': 'no-store'}}); +} diff --git a/web/src/components/ReportBody.tsx b/web/src/components/ReportBody.tsx new file mode 100644 index 0000000..a8986a3 --- /dev/null +++ b/web/src/components/ReportBody.tsx @@ -0,0 +1,210 @@ +// Renders a report body: a small Markdown subset plus database references (backend: politrack/queries/reports.py). +// Builds React elements directly - no HTML from the author ever reaches the page, so a report can't inject markup. +// +// ## Heading / ### Subheading paragraphs separated by blank lines - list / 1. list > quote --- +// **bold** *italic* [text](https://...) +// [[angabe:123]] [[bericht:slug]] on a line of their own: claim card / report card +// [text](angabe:123) (bericht:slug) (person:slug) (org:slug) inline links, marked as database references +import type {ReactNode} from 'react'; +import {getTranslations} from 'next-intl/server'; +import {Link} from '@/i18n/navigation'; +import type {Claim, ReportReferences} from '@/lib/api'; +import {ClaimCard} from './ClaimList'; +import {ExternalLink} from './ExternalLink'; +import {Icon} from './Icon'; +import {ReportCard} from './ReportCard'; + +const REF_TYPES: Record = { + angabe: 'claim', claim: 'claim', bericht: 'report', report: 'report', person: 'person', + org: 'organization', organisation: 'organization', organization: 'organization' +}; +const NAMES = Object.keys(REF_TYPES).join('|'); +const BLOCK_REF = new RegExp(`^\\s*\\[\\[(${NAMES})\\s*:\\s*([^\\]\\s]+)\\s*\\]\\]\\s*$`, 'i'); +const INLINE = /\[([^\]\n]+)\]\(([^)\s]+)\)|\*\*([^*\n]+)\*\*|\*([^*\s][^*\n]*)\*|_([^_\s][^_\n]*)_/; + +type Block = + | {kind: 'h2' | 'h3' | 'p' | 'quote'; text: string} + | {kind: 'ul' | 'ol'; items: string[]} + | {kind: 'hr'} + | {kind: 'embed'; type: 'claim' | 'report' | 'person' | 'organization'; key: string}; + +export function parseBlocks(body: string): Block[] { + const blocks: Block[] = []; + let para: string[] = []; + let list: {kind: 'ul' | 'ol'; items: string[]} | null = null; + let quote: string[] = []; + const flush = () => { + if (para.length) blocks.push({kind: 'p', text: para.join(' ')}); + if (list) blocks.push(list); + if (quote.length) blocks.push({kind: 'quote', text: quote.join(' ')}); + para = []; + list = null; + quote = []; + }; + for (const raw of body.replace(/\r\n?/g, '\n').split('\n')) { + const line = raw.trimEnd(); + const ref = BLOCK_REF.exec(line); + let m: RegExpExecArray | null; + if (!line.trim()) { + flush(); + } else if (ref) { + flush(); + blocks.push({kind: 'embed', type: REF_TYPES[ref[1].toLowerCase()], key: ref[2]}); + } else if ((m = /^(#{1,3})\s+(.+)$/.exec(line))) { + flush(); + blocks.push({kind: m[1].length === 3 ? 'h3' : 'h2', text: m[2]}); + } else if (/^\s*(-{3,}|\*{3,})\s*$/.test(line)) { + flush(); + blocks.push({kind: 'hr'}); + } else if ((m = /^\s*[-*]\s+(.+)$/.exec(line)) || (m = /^\s*\d+[.)]\s+(.+)$/.exec(line))) { + const kind = /^\s*\d/.test(line) ? 'ol' : 'ul'; + if (para.length || quote.length || (list && list.kind !== kind)) flush(); + list ??= {kind, items: []}; + list.items.push(m[1]); + } else if ((m = /^\s*>\s?(.*)$/.exec(line))) { + if (para.length || list) flush(); + quote.push(m[1]); + } else if (list && /^\s{2,}\S/.test(raw)) { + list.items[list.items.length - 1] += ` ${line.trim()}`; + } else { + if (list || quote.length) flush(); + para.push(line.trim()); + } + } + flush(); + return blocks; +} + +export function isOfficial(claim: Claim): boolean { + return claim.evidence.some((ev) => ev.source_kind === 'official'); +} + +type Lookup = { + claim: (key: string) => Claim | undefined; + refs: ReportReferences; + t: Translate; +}; +type Translate = (key: string, values?: Record) => string; + +function lookup(refs: ReportReferences, t: Lookup['t']): Lookup { + const claims = new Map(refs.claims.map((c) => [String(c.id), c])); + return { + claim: (key) => claims.get(String(refs.claim_aliases[key] ?? key)), + refs, + t + }; +} + +function inline(text: string, ctx: Lookup, prefix = 'i'): ReactNode[] { + const out: ReactNode[] = []; + let rest = text; + let n = 0; + while (rest) { + const m = INLINE.exec(rest); + if (!m) { + out.push(rest); + break; + } + if (m.index > 0) out.push(rest.slice(0, m.index)); + const key = `${prefix}-${n++}`; + if (m[1] !== undefined) out.push(); + else if (m[3] !== undefined) out.push({inline(m[3], ctx, key)}); + else out.push({inline(m[4] ?? m[5], ctx, key)}); + rest = rest.slice(m.index + m[0].length); + } + return out; +} + +function RefLink({label, target, ctx, prefix}: {label: string; target: string; ctx: Lookup; prefix: string}) { + const {t, refs} = ctx; + const text = inline(label, ctx, prefix); + const colon = target.indexOf(':'); + const scheme = colon > 0 ? target.slice(0, colon).toLowerCase() : ''; + const key = target.slice(colon + 1); + if (scheme === 'https' || scheme === 'http') return {text}; + const type = REF_TYPES[scheme]; + const missing = {text}; + if (type === 'claim') { + const claim = ctx.claim(key); + if (!claim) return missing; + const official = isOfficial(claim); + return ( + + {text} + + ); + } + if (type === 'report') { + const report = refs.reports.find((r) => r.slug === key); + return report ? {text} : missing; + } + if (type === 'person') { + return refs.persons.some((p) => p.slug === key) ? {text} : missing; + } + if (type === 'organization') { + const org = refs.organizations.find((o) => o.slug === key); + if (!org) return missing; + return {text}; + } + return <>{text}; +} + +/** A claim inside a report: the full claim card under a seal that says it comes from the database. */ +export async function ClaimEmbed({claim}: {claim: Claim}) { + const t = await getTranslations('Reports'); + const official = isOfficial(claim); + const sources = [...new Set(claim.evidence.filter((ev) => !official || ev.source_kind === 'official') + .map((ev) => ev.source_name ?? ev.source))].slice(0, 3).join(', '); + return ( +
+
+ + + {t(official ? 'sealOfficial' : 'sealDatabase')} + {' · '}{t('sealDetail', {id: String(claim.id), sources})} + +
+ +
+ ); +} + +export async function ReportBody({body, references}: {body: string; references: ReportReferences}) { + const tr = await getTranslations('Reports'); + const t: Translate = (key, values) => tr(key as 'refMissing', values); + const ctx = lookup(references, t); + const blocks = parseBlocks(body); + return ( +
+ {blocks.map((block, i) => { + const key = `b${i}`; + switch (block.kind) { + case 'h2': return

{inline(block.text, ctx, key)}

; + case 'h3': return

{inline(block.text, ctx, key)}

; + case 'p': return

{inline(block.text, ctx, key)}

; + case 'quote': return

{inline(block.text, ctx, key)}

; + case 'hr': return
; + case 'ul': + case 'ol': { + const items = block.items.map((item, j) =>
  • {inline(item, ctx, `${key}-${j}`)}
  • ); + return block.kind === 'ul' ?
      {items}
    :
      {items}
    ; + } + case 'embed': { + if (block.type === 'claim') { + const claim = ctx.claim(block.key); + return claim ? + :

    {t('claimMissing', {id: block.key})}

    ; + } + if (block.type === 'report') { + const report = references.reports.find((r) => r.slug === block.key); + return report ?
    + :

    {t('reportMissing')}

    ; + } + return

    ; + } + } + })} +
    + ); +} diff --git a/web/src/components/ReportCard.tsx b/web/src/components/ReportCard.tsx new file mode 100644 index 0000000..af883fe --- /dev/null +++ b/web/src/components/ReportCard.tsx @@ -0,0 +1,41 @@ +import {getLocale, getTranslations} from 'next-intl/server'; +import {Link} from '@/i18n/navigation'; +import type {ReportListItem} from '@/lib/api'; +import {formatDate} from '@/lib/format'; +import {Icon} from './Icon'; +import {EmptyState} from './Notice'; + +/** A report in a list or embedded in another report: title, lede, author, date and how much rests on the database. */ +export async function ReportCard({report, href}: {report: ReportListItem; href?: string}) { + const t = await getTranslations('Reports'); + const locale = await getLocale(); + const when = report.published_at ?? report.updated_at; + return ( +
    +

    + + {report.author_name} + + {report.status !== 'published' && {t(`status.${report.status}` as 'status.draft')}} +

    +

    + {report.title} +

    + {report.lede &&

    {report.lede}

    } +

    + + {t('basis', {claims: report.claim_count, official: report.official_claim_count})} +

    +
    + ); +} + +export async function ReportList({reports, hrefFor, empty}: {reports: ReportListItem[]; hrefFor?: (r: ReportListItem) => string; empty?: string}) { + const t = await getTranslations('Reports'); + if (!reports.length) return {empty ?? t('none')}; + return ( +
      + {reports.map((report) =>
    • )} +
    + ); +} diff --git a/web/src/components/ReportEditor.tsx b/web/src/components/ReportEditor.tsx new file mode 100644 index 0000000..ba0ceb8 --- /dev/null +++ b/web/src/components/ReportEditor.tsx @@ -0,0 +1,167 @@ +'use client'; + +// The report editor: title, lede, Markdown body and a picker that finds claims, reports and persons and inserts +// their reference code at the cursor. Saving goes through a server action (signed-in users only). +import {type FormEvent, useActionState, useRef, useState} from 'react'; +import {useTranslations} from 'next-intl'; +import type {ReportInput} from '@/lib/api'; +import {Icon} from './Icon'; + +export type EditorState = {error?: string; saved?: boolean}; +type Hit = {code: string; link: string; label: string; detail: string; official?: boolean}; +type SearchType = 'claim' | 'report' | 'person'; + +export function ReportEditor({action, initial, isNew}: { + action: (state: EditorState, form: FormData) => Promise; + initial: ReportInput; + isNew: boolean; +}) { + const t = useTranslations('ReportEditor'); + const [state, formAction, pending] = useActionState(action, {}); + const body = useRef(null); + const [q, setQ] = useState(''); + const [type, setType] = useState('claim'); + const [hits, setHits] = useState(null); + const [searching, setSearching] = useState(false); + + function insert(text: string, block: boolean) { + const el = body.current; + if (!el) return; + const {selectionStart: start, selectionEnd: end, value} = el; + let snippet = text; + if (block) { + const before = value.slice(0, start); + snippet = `${before && !before.endsWith('\n\n') ? (before.endsWith('\n') ? '\n' : '\n\n') : ''}${text}\n\n`; + } + el.setRangeText(snippet, start, end, 'end'); + el.focus(); + } + + function insertLink(hit: Hit) { + const el = body.current; + if (!el) return; + const selected = el.value.slice(el.selectionStart, el.selectionEnd).trim(); + insert(`[${selected || hit.label.slice(0, 80)}](${hit.link})`, false); + } + + function wrap(marker: string) { + const el = body.current; + if (!el) return; + const {selectionStart: start, selectionEnd: end, value} = el; + el.setRangeText(`${marker}${value.slice(start, end) || t('text')}${marker}`, start, end, 'select'); + el.focus(); + } + + async function search(event?: FormEvent) { + event?.preventDefault(); + if (q.trim().length < 2) return; + setSearching(true); + try { + const res = await fetch(`/api/referenz-suche?type=${type}&q=${encodeURIComponent(q.trim())}`); + setHits(res.ok ? await res.json() : []); + } finally { + setSearching(false); + } + } + + return ( +
    +
    + +