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:
1 parent
f2d72fe464
commit
9f0e2fc115
32 files changed
+1974
-21
No files matched your search
@@ -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.
|
# Moderation endpoints (/api/v1/review, /api/v1/admin/runs). Leave empty to moderate via the CLI only.
|
||||||
# POLITRACK_ADMIN_TOKEN=
|
# 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.
|
# Nightly database dumps (backup service). Ideally on a different disk or share than DATA_DIR.
|
||||||
# BACKUP_DIR=/mnt/user/backups/politrack
|
# BACKUP_DIR=/mnt/user/backups/politrack
|
||||||
# BACKUP_KEEP_DAYS=14
|
# BACKUP_KEEP_DAYS=14
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -6,9 +6,11 @@ Conventions: every list endpoint takes limit/offset; claim-like endpoints take t
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hmac
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
from urllib.parse import unquote
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI, Header, HTTPException, Query
|
from fastapi import Depends, FastAPI, Header, HTTPException, Query
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
@@ -28,7 +30,7 @@ app = FastAPI(
|
|||||||
docs_url="/api/docs",
|
docs_url="/api/docs",
|
||||||
openapi_url="/api/openapi.json",
|
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=["*"])
|
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)
|
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) ------------------------------------------------------------------
|
# -- admin (POLITRACK_ADMIN_TOKEN) ------------------------------------------------------------------
|
||||||
|
|
||||||
def require_admin(authorization: Annotated[str | None, Header()] = None) -> str:
|
def require_admin(authorization: Annotated[str | None, Header()] = None) -> str:
|
||||||
|
|||||||
@@ -533,3 +533,55 @@ class PendingClaim(Model):
|
|||||||
occurred_at: datetime | None = None
|
occurred_at: datetime | None = None
|
||||||
full_name: str | None = None
|
full_name: str | None = None
|
||||||
evidence: list[dict[str, Any]] | 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
|
||||||
@@ -42,6 +42,10 @@ class Settings(BaseSettings):
|
|||||||
api_cors_origins: list[str] = ["http://localhost:3000"]
|
api_cors_origins: list[str] = ["http://localhost:3000"]
|
||||||
# Bearer token for moderation/admin endpoints. Empty = disabled (use the CLI).
|
# Bearer token for moderation/admin endpoints. Empty = disabled (use the CLI).
|
||||||
admin_token: str | None = None
|
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
|
@lru_cache
|
||||||
|
|||||||
@@ -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.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.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.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.search import search
|
||||||
from politrack.queries.votes import list_votes, person_votes, vote_detail
|
from politrack.queries.votes import list_votes, person_votes, vote_detail
|
||||||
|
|
||||||
__all__ = [
|
__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",
|
"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",
|
"money_summary", "pending_claims", "recent_runs", "person_network", "person_votes", "search", "set_review", "social_feed",
|
||||||
"source_freshness", "stats", "timeline_histogram", "vote_detail", "wiki_edits",
|
"source_freshness", "stats", "timeline_histogram", "vote_detail", "wiki_edits",
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ def list_claims(
|
|||||||
until: date | None = None,
|
until: date | None = None,
|
||||||
q: str | None = None,
|
q: str | None = None,
|
||||||
claim_id: int | None = None,
|
claim_id: int | None = None,
|
||||||
|
claim_ids: list[int] | None = None,
|
||||||
include_pending: bool = False,
|
include_pending: bool = False,
|
||||||
limit: int = 50,
|
limit: int = 50,
|
||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
@@ -29,7 +30,7 @@ def list_claims(
|
|||||||
source_sql, params = sources.sql("s")
|
source_sql, params = sources.sql("s")
|
||||||
params.update({
|
params.update({
|
||||||
"person": person, "party": party, "organization": organization, "claim_types": claim_types, "topics": topics, "since": since,
|
"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(
|
return conn.execute(
|
||||||
f"""
|
f"""
|
||||||
@@ -62,7 +63,7 @@ def list_claims(
|
|||||||
WHERE e.claim_id = c.id AND {source_sql}
|
WHERE e.claim_id = c.id AND {source_sql}
|
||||||
) ev
|
) ev
|
||||||
WHERE ev.evidence IS NOT NULL AND {VISIBLE}
|
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 (%(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
|
AND (%(party)s::text IS NULL OR o.slug = %(party)s
|
||||||
OR c.counterpart_org_id = (SELECT id FROM organization WHERE 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 (%(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 (%(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_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
|
ORDER BY COALESCE(c.occurred_at, c.valid_from::timestamptz, c.created_at) DESC, c.id DESC
|
||||||
LIMIT %(limit)s OFFSET %(offset)s
|
LIMIT %(limit)s OFFSET %(offset)s
|
||||||
""",
|
""",
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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)") == []
|
||||||
@@ -110,6 +110,9 @@ services:
|
|||||||
POLITRACK_LEGAL_ADDRESS: ${POLITRACK_LEGAL_ADDRESS:-}
|
POLITRACK_LEGAL_ADDRESS: ${POLITRACK_LEGAL_ADDRESS:-}
|
||||||
POLITRACK_LEGAL_EMAIL: ${POLITRACK_LEGAL_EMAIL:-}
|
POLITRACK_LEGAL_EMAIL: ${POLITRACK_LEGAL_EMAIL:-}
|
||||||
POLITRACK_CORRECTIONS_EMAIL: ${POLITRACK_CORRECTIONS_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:
|
ports:
|
||||||
- "${WEB_PORT:-3000}:3000"
|
- "${WEB_PORT:-3000}:3000"
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
+12
-1
@@ -18,6 +18,7 @@ organization ─┘ ╱ │ ╲ role, vote_position(→vo
|
|||||||
social_account │ event_participant(→event), statement, legal_proceeding
|
social_account │ event_participant(→event), statement, legal_proceeding
|
||||||
chunk (text + embedding for RAG)
|
chunk (text + embedding for RAG)
|
||||||
run, state, app_user operations
|
run, state, app_user operations
|
||||||
|
app_user ──< report ──< report_reference (→ claim, report, person, organization), report_revision
|
||||||
```
|
```
|
||||||
|
|
||||||
## Entities
|
## 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 /
|
`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
|
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).
|
||||||
@@ -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.
|
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).
|
* 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 "<the secret>";` 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
|
## Monitoring
|
||||||
|
|
||||||
* `docker compose exec api politrack status` – recent runs with stats and errors (table `run`).
|
* `docker compose exec api politrack status` – recent runs with stats and errors (table `run`).
|
||||||
|
|||||||
@@ -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
|
* **Only tokens** for colour, spacing, radius and type. The exceptions are deliberate: party colours
|
||||||
(from the data), platform brand colours, and the favicon.
|
(from the data), platform brand colours, and the favicon.
|
||||||
* **Server first.** Pages and most components are async server components. Client components exist only
|
* **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,
|
* **No JavaScript needed** for navigation, filters, tabs, disclosures or the mobile menu: links, GET forms,
|
||||||
`<details>` and one checkbox toggle.
|
`<details>` and one checkbox toggle.
|
||||||
|
|
||||||
@@ -176,6 +177,21 @@ same mark as the favicon.
|
|||||||
| `SocialFeed` | `SocialFeed.tsx` | post cards, no embeds |
|
| `SocialFeed` | `SocialFeed.tsx` | post cards, no embeds |
|
||||||
| `SearchForm` | `SearchForm.tsx` | the big search field (optional date range) |
|
| `SearchForm` | `SearchForm.tsx` | the big search field (optional date range) |
|
||||||
| `SettingsForm` (client) | `SettingsForm.tsx` | "Meine Filter" |
|
| `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
|
### The claim card
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -75,7 +75,10 @@ Next.js frontend (de/en), Docker Compose for Unraid.
|
|||||||
- [ ] Review queue for editors in the web UI (today `politrack review`)
|
- [ ] Review queue for editors in the web UI (today `politrack review`)
|
||||||
- [ ] Community link submissions and a corrections/right-of-reply form
|
- [ ] Community link submissions and a corrections/right-of-reply form
|
||||||
- [ ] Alerts (e-mail/RSS) for followed politicians
|
- [ ] 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)
|
- [ ] Partnerships: MeineAbgeordneten, Parteispenden.at, APA (OTS full-text licence)
|
||||||
- [ ] Map view of trips and appearances
|
- [ ] 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
|
- [ ] Semantic search with embeddings (`POLITRACK_OLLAMA_URL`): parked by the owner on 2026-11-09, full-text search only for now
|
||||||
|
|||||||
+95
-3
@@ -18,7 +18,8 @@
|
|||||||
"social": "Social Media",
|
"social": "Social Media",
|
||||||
"wikipedia": "Wikipedia-Bearbeitungen",
|
"wikipedia": "Wikipedia-Bearbeitungen",
|
||||||
"imprint": "Impressum",
|
"imprint": "Impressum",
|
||||||
"privacy": "Datenschutz"
|
"privacy": "Datenschutz",
|
||||||
|
"reports": "Berichte"
|
||||||
},
|
},
|
||||||
"Imprint": {
|
"Imprint": {
|
||||||
"title": "Impressum",
|
"title": "Impressum",
|
||||||
@@ -159,7 +160,7 @@
|
|||||||
},
|
},
|
||||||
"showPartVotes": "Auch Änderungsanträge und Teilabstimmungen anzeigen",
|
"showPartVotes": "Auch Änderungsanträge und Teilabstimmungen anzeigen",
|
||||||
"hidePartVotes": "Nur Abstimmungen über ganze Texte 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",
|
"roleCorroborated": "mehrfach belegt",
|
||||||
"unverified": "laut Wikidata – nicht amtlich bestätigt",
|
"unverified": "laut Wikidata – nicht amtlich bestätigt",
|
||||||
"accountUnverified": "Laut Wikidata – nicht amtlich bestätigt",
|
"accountUnverified": "Laut Wikidata – nicht amtlich bestätigt",
|
||||||
@@ -642,6 +643,97 @@
|
|||||||
"crumb": "Angabe #{id}",
|
"crumb": "Angabe #{id}",
|
||||||
"cite": "Zitieren",
|
"cite": "Zitieren",
|
||||||
"citation": "Politrack: „{summary}“. Angabe #{id}, abgerufen am {date}. {url}",
|
"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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+95
-3
@@ -18,7 +18,8 @@
|
|||||||
"social": "Social media",
|
"social": "Social media",
|
||||||
"wikipedia": "Wikipedia edits",
|
"wikipedia": "Wikipedia edits",
|
||||||
"imprint": "Legal notice",
|
"imprint": "Legal notice",
|
||||||
"privacy": "Privacy"
|
"privacy": "Privacy",
|
||||||
|
"reports": "Reports"
|
||||||
},
|
},
|
||||||
"Home": {
|
"Home": {
|
||||||
"headline": "Austrian politics – traceable.",
|
"headline": "Austrian politics – traceable.",
|
||||||
@@ -124,7 +125,7 @@
|
|||||||
},
|
},
|
||||||
"showPartVotes": "Also show amendments and part votes",
|
"showPartVotes": "Also show amendments and part votes",
|
||||||
"hidePartVotes": "Show votes on whole texts only",
|
"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",
|
"roleCorroborated": "corroborated",
|
||||||
"unverified": "per Wikidata – not officially confirmed",
|
"unverified": "per Wikidata – not officially confirmed",
|
||||||
"accountUnverified": "According to Wikidata – not officially confirmed",
|
"accountUnverified": "According to Wikidata – not officially confirmed",
|
||||||
@@ -642,6 +643,97 @@
|
|||||||
"crumb": "Fact #{id}",
|
"crumb": "Fact #{id}",
|
||||||
"cite": "Cite",
|
"cite": "Cite",
|
||||||
"citation": "Politrack: “{summary}”. Fact #{id}, retrieved {date}. {url}",
|
"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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,11 @@ import {headers} from 'next/headers';
|
|||||||
import {notFound} from 'next/navigation';
|
import {notFound} from 'next/navigation';
|
||||||
import {getTranslations, setRequestLocale} from 'next-intl/server';
|
import {getTranslations, setRequestLocale} from 'next-intl/server';
|
||||||
import {ClaimCard} from '@/components/ClaimList';
|
import {ClaimCard} from '@/components/ClaimList';
|
||||||
|
import {Icon} from '@/components/Icon';
|
||||||
import {Notice} from '@/components/Notice';
|
import {Notice} from '@/components/Notice';
|
||||||
import {Breadcrumbs, type Crumb, SectionHead} from '@/components/PageHeader';
|
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 {api, NotFoundError, type Claim} from '@/lib/api';
|
||||||
import {formatDate} from '@/lib/format';
|
import {formatDate} from '@/lib/format';
|
||||||
|
|
||||||
@@ -35,6 +37,7 @@ export default async function ClaimPage({params}: Props) {
|
|||||||
const t = await getTranslations('ClaimPage');
|
const t = await getTranslations('ClaimPage');
|
||||||
const claim = await loadClaim(id);
|
const claim = await loadClaim(id);
|
||||||
const summary = locale === 'en' && claim.summary_en ? claim.summary_en : claim.summary_de;
|
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 h = await headers();
|
||||||
const host = h.get('x-forwarded-host') ?? h.get('host') ?? 'localhost';
|
const host = h.get('x-forwarded-host') ?? h.get('host') ?? 'localhost';
|
||||||
@@ -58,6 +61,12 @@ export default async function ClaimPage({params}: Props) {
|
|||||||
<p className="citation">{t('citation', {summary, id: String(claim.id), date: today, url})}</p>
|
<p className="citation">{t('citation', {summary, id: String(claim.id), date: today, url})}</p>
|
||||||
<Notice tone="note">{t('filtersIgnored')}</Notice>
|
<Notice tone="note">{t('filtersIgnored')}</Notice>
|
||||||
</section>
|
</section>
|
||||||
|
<section className="section" aria-labelledby="in-reports">
|
||||||
|
<SectionHead id="in-reports" title={t('inReports')} />
|
||||||
|
<p>{t('embedHint')} <code className="embed-code">[[angabe:{claim.id}]]</code></p>
|
||||||
|
<p><Link href={`/berichte/verfassen/neu?angabe=${claim.id}`} className="button secondary"><Icon name="pencil" /> {t('newReport')}</Link></p>
|
||||||
|
{reports.length > 0 && <ReportList reports={reports} />}
|
||||||
|
</section>
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -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<ReportDetail> {
|
||||||
|
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<Metadata> {
|
||||||
|
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 (
|
||||||
|
<article className="report">
|
||||||
|
<PageHeader
|
||||||
|
crumbs={[{label: t('title'), href: '/berichte'}, {label: report.title}]}
|
||||||
|
eyebrow={t('eyebrow')}
|
||||||
|
title={<span lang={lang}>{report.title}</span>}
|
||||||
|
lede={report.lede ? <span lang={lang}>{report.lede}</span> : 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 ? (
|
||||||
|
<Link href={`/berichte/verfassen/${report.slug}`} className="button secondary"><Icon name="pencil" /> {t('edit')}</Link>
|
||||||
|
) : undefined}
|
||||||
|
/>
|
||||||
|
{report.status === 'draft' && <Notice tone="caution">{t('draftNotice')}</Notice>}
|
||||||
|
{report.status === 'withdrawn' && <Notice tone="caution">{t('withdrawnNotice')}</Notice>}
|
||||||
|
|
||||||
|
<aside className="report-basis" aria-label={t('basisLabel')}>
|
||||||
|
<Icon name="shield" />
|
||||||
|
<p>
|
||||||
|
<strong>{t('basis', {claims: report.claim_count, official: report.official_claim_count})}</strong>{' '}
|
||||||
|
{t('basisExplain', {author: report.author_name})}
|
||||||
|
</p>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div lang={lang}>
|
||||||
|
<ReportBody body={report.body} references={report.references} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{report.backlinks.length > 0 && (
|
||||||
|
<section className="section" aria-labelledby="backlinks">
|
||||||
|
<SectionHead id="backlinks" title={t('backlinks')} />
|
||||||
|
<ReportList reports={report.backlinks} />
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Metadata> {
|
||||||
|
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 (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('title')} lede={t('intro')}
|
||||||
|
actions={<Link href="/berichte/verfassen" className="button"><Icon name="pencil" /> {t('write')}</Link>} />
|
||||||
|
<Notice tone="info">{t('disclaimer')}</Notice>
|
||||||
|
<FilterBar id="reports" active={countActive(sp.q)} resetHref="/berichte">
|
||||||
|
<Field label={t('search')} wide><input type="search" name="q" defaultValue={sp.q} placeholder={t('searchPlaceholder')} /></Field>
|
||||||
|
</FilterBar>
|
||||||
|
<ReportList reports={reports} />
|
||||||
|
<Pagination pathname="/berichte" query={sp} page={page} hasNext={reports.length === PAGE} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Metadata> {
|
||||||
|
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 <><PageHeader title={t('editTitle')} crumbs={crumbs} /><Notice tone="caution">{t('signInNeeded')}</Notice></>;
|
||||||
|
}
|
||||||
|
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 <><PageHeader title={t('editTitle')} crumbs={crumbs} /><Notice tone="caution">{t('errorNotYours')}</Notice></>;
|
||||||
|
const missing = report.references.missing_claims;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('editTitle')} crumbs={crumbs}
|
||||||
|
actions={report.status !== 'draft'
|
||||||
|
? <Link href={`/berichte/${report.slug}`} className="button secondary"><Icon name="arrow-right" /> {t('view')}</Link>
|
||||||
|
: undefined} />
|
||||||
|
<ReportEditor action={updateReportAction.bind(null, report.slug)} isNew={false}
|
||||||
|
initial={{title: report.title, lede: report.lede, body: report.body, lang: report.lang, status: report.status}} />
|
||||||
|
<section className="section report-preview" aria-labelledby="preview">
|
||||||
|
<SectionHead id="preview" title={t('preview')} />
|
||||||
|
<p className="small">{t('previewHint')}</p>
|
||||||
|
{missing.length > 0 && <Notice tone="caution">{t('missingClaims', {ids: missing.join(', ')})}</Notice>}
|
||||||
|
<article className="report">
|
||||||
|
<h1 className="report-preview-title">{report.title}</h1>
|
||||||
|
{report.lede && <p className="lede">{report.lede}</p>}
|
||||||
|
<ReportBody body={report.body} references={report.references} />
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<EditorState> {
|
||||||
|
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<EditorState> {
|
||||||
|
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<EditorState> {
|
||||||
|
try {
|
||||||
|
await api.updateReport(slug, readForm(form));
|
||||||
|
} catch (error) {
|
||||||
|
return failure(error);
|
||||||
|
}
|
||||||
|
revalidatePath('/[locale]/berichte', 'layout');
|
||||||
|
return {saved: true};
|
||||||
|
}
|
||||||
@@ -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<Metadata> {
|
||||||
|
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 <><PageHeader title={t('new')} crumbs={crumbs} /><Notice tone="caution">{t('signInNeeded')}</Notice></>;
|
||||||
|
}
|
||||||
|
const start = sp.angabe && /^\d+$/.test(sp.angabe) ? `[[angabe:${sp.angabe}]]\n\n` : '';
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('new')} lede={t('newIntro')} crumbs={crumbs} />
|
||||||
|
<ReportEditor action={createReportAction} isNew
|
||||||
|
initial={{title: '', lede: null, body: start, lang: locale === 'en' ? 'en' : 'de', status: 'draft'}} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Metadata> {
|
||||||
|
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 (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('mine')} crumbs={[{label: t('reports'), href: '/berichte'}, {label: t('mine')}]} />
|
||||||
|
<Notice tone="caution">{t('signInNeeded')}</Notice>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const reports = await api.reports({mine: true, limit: 200});
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('mine')} lede={t('mineIntro', {name: viewer.name})}
|
||||||
|
crumbs={[{label: t('reports'), href: '/berichte'}, {label: t('mine')}]}
|
||||||
|
actions={<Link href="/berichte/verfassen/neu" className="button"><Icon name="pencil" /> {t('new')}</Link>} />
|
||||||
|
<ReportList reports={reports} hrefFor={(r) => `/berichte/verfassen/${r.slug}`} empty={t('mineNone')} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Response> {
|
||||||
|
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'}});
|
||||||
|
}
|
||||||
@@ -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<string, 'claim' | 'report' | 'person' | 'organization'> = {
|
||||||
|
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, string>) => 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(<RefLink key={key} label={m[1]} target={m[2]} ctx={ctx} prefix={key} />);
|
||||||
|
else if (m[3] !== undefined) out.push(<strong key={key}>{inline(m[3], ctx, key)}</strong>);
|
||||||
|
else out.push(<em key={key}>{inline(m[4] ?? m[5], ctx, key)}</em>);
|
||||||
|
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 <ExternalLink href={target}>{text}</ExternalLink>;
|
||||||
|
const type = REF_TYPES[scheme];
|
||||||
|
const missing = <span className="ref ref--missing" title={t('refMissing')}>{text}</span>;
|
||||||
|
if (type === 'claim') {
|
||||||
|
const claim = ctx.claim(key);
|
||||||
|
if (!claim) return missing;
|
||||||
|
const official = isOfficial(claim);
|
||||||
|
return (
|
||||||
|
<Link href={`/angaben/${claim.id}`} className={`ref ref--claim${official ? ' is-official' : ''}`}
|
||||||
|
title={t(official ? 'refClaimOfficial' : 'refClaim', {id: String(claim.id)})}>
|
||||||
|
{text}<Icon name={official ? 'shield' : 'checks'} />
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (type === 'report') {
|
||||||
|
const report = refs.reports.find((r) => r.slug === key);
|
||||||
|
return report ? <Link href={`/berichte/${key}`} className="ref ref--report" title={t('refReport', {title: report.title})}>{text}</Link> : missing;
|
||||||
|
}
|
||||||
|
if (type === 'person') {
|
||||||
|
return refs.persons.some((p) => p.slug === key) ? <Link href={`/personen/${key}`} className="ref">{text}</Link> : missing;
|
||||||
|
}
|
||||||
|
if (type === 'organization') {
|
||||||
|
const org = refs.organizations.find((o) => o.slug === key);
|
||||||
|
if (!org) return missing;
|
||||||
|
return <Link href={`/${org.kind === 'party' ? 'parteien' : 'organisationen'}/${key}`} className="ref">{text}</Link>;
|
||||||
|
}
|
||||||
|
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 (
|
||||||
|
<figure className={`claim-embed${official ? ' is-official' : ''}`}>
|
||||||
|
<figcaption className="claim-embed-seal">
|
||||||
|
<Icon name={official ? 'shield' : 'checks'} />
|
||||||
|
<span>
|
||||||
|
<strong>{t(official ? 'sealOfficial' : 'sealDatabase')}</strong>
|
||||||
|
{' · '}{t('sealDetail', {id: String(claim.id), sources})}
|
||||||
|
</span>
|
||||||
|
</figcaption>
|
||||||
|
<ClaimCard claim={claim} />
|
||||||
|
</figure>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<div className="report-body">
|
||||||
|
{blocks.map((block, i) => {
|
||||||
|
const key = `b${i}`;
|
||||||
|
switch (block.kind) {
|
||||||
|
case 'h2': return <h2 key={key}>{inline(block.text, ctx, key)}</h2>;
|
||||||
|
case 'h3': return <h3 key={key}>{inline(block.text, ctx, key)}</h3>;
|
||||||
|
case 'p': return <p key={key}>{inline(block.text, ctx, key)}</p>;
|
||||||
|
case 'quote': return <blockquote key={key}><p>{inline(block.text, ctx, key)}</p></blockquote>;
|
||||||
|
case 'hr': return <hr key={key} />;
|
||||||
|
case 'ul':
|
||||||
|
case 'ol': {
|
||||||
|
const items = block.items.map((item, j) => <li key={j}>{inline(item, ctx, `${key}-${j}`)}</li>);
|
||||||
|
return block.kind === 'ul' ? <ul key={key}>{items}</ul> : <ol key={key}>{items}</ol>;
|
||||||
|
}
|
||||||
|
case 'embed': {
|
||||||
|
if (block.type === 'claim') {
|
||||||
|
const claim = ctx.claim(block.key);
|
||||||
|
return claim ? <ClaimEmbed key={key} claim={claim} />
|
||||||
|
: <p key={key} className="ref-missing-block"><Icon name="alert" /> {t('claimMissing', {id: block.key})}</p>;
|
||||||
|
}
|
||||||
|
if (block.type === 'report') {
|
||||||
|
const report = references.reports.find((r) => r.slug === block.key);
|
||||||
|
return report ? <div key={key} className="report-embed"><ReportCard report={report} /></div>
|
||||||
|
: <p key={key} className="ref-missing-block"><Icon name="alert" /> {t('reportMissing')}</p>;
|
||||||
|
}
|
||||||
|
return <p key={key}><RefLink label={block.key} target={`${block.type === 'person' ? 'person' : 'org'}:${block.key}`} ctx={ctx} prefix={key} /></p>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<article className="report-card card">
|
||||||
|
<p className="report-card-meta">
|
||||||
|
<Icon name="news" />
|
||||||
|
<span>{report.author_name}</span>
|
||||||
|
<time dateTime={when}>{formatDate(when, locale)}</time>
|
||||||
|
{report.status !== 'published' && <span className="badge badge--caution">{t(`status.${report.status}` as 'status.draft')}</span>}
|
||||||
|
</p>
|
||||||
|
<h3 className="report-card-title">
|
||||||
|
<Link href={href ?? `/berichte/${report.slug}`} lang={report.lang !== locale ? report.lang : undefined}>{report.title}</Link>
|
||||||
|
</h3>
|
||||||
|
{report.lede && <p className="report-card-lede" lang={report.lang !== locale ? report.lang : undefined}>{report.lede}</p>}
|
||||||
|
<p className="report-card-basis">
|
||||||
|
<Icon name="shield" />
|
||||||
|
{t('basis', {claims: report.claim_count, official: report.official_claim_count})}
|
||||||
|
</p>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ReportList({reports, hrefFor, empty}: {reports: ReportListItem[]; hrefFor?: (r: ReportListItem) => string; empty?: string}) {
|
||||||
|
const t = await getTranslations('Reports');
|
||||||
|
if (!reports.length) return <EmptyState icon="news">{empty ?? t('none')}</EmptyState>;
|
||||||
|
return (
|
||||||
|
<ul className="report-list">
|
||||||
|
{reports.map((report) => <li key={report.slug}><ReportCard report={report} href={hrefFor?.(report)} /></li>)}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<EditorState>;
|
||||||
|
initial: ReportInput;
|
||||||
|
isNew: boolean;
|
||||||
|
}) {
|
||||||
|
const t = useTranslations('ReportEditor');
|
||||||
|
const [state, formAction, pending] = useActionState(action, {});
|
||||||
|
const body = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const [q, setQ] = useState('');
|
||||||
|
const [type, setType] = useState<SearchType>('claim');
|
||||||
|
const [hits, setHits] = useState<Hit[] | null>(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 (
|
||||||
|
<div className="report-editor">
|
||||||
|
<form action={formAction} className="report-editor-form stack">
|
||||||
|
<label className="field field--wide">
|
||||||
|
<span className="field-label">{t('title')}</span>
|
||||||
|
<input name="title" required minLength={3} maxLength={200} defaultValue={initial.title} />
|
||||||
|
</label>
|
||||||
|
<label className="field field--wide">
|
||||||
|
<span className="field-label">{t('lede')}</span>
|
||||||
|
<textarea name="lede" rows={2} maxLength={500} defaultValue={initial.lede ?? ''} placeholder={t('ledeHint')} />
|
||||||
|
</label>
|
||||||
|
<div className="field field--wide">
|
||||||
|
<span className="field-label" id="body-label">{t('body')}</span>
|
||||||
|
<div className="report-editor-toolbar cluster" role="toolbar" aria-labelledby="body-label">
|
||||||
|
<button type="button" className="ghost" onClick={() => insert('## ', true)}>{t('heading')}</button>
|
||||||
|
<button type="button" className="ghost" onClick={() => wrap('**')}><strong>B</strong></button>
|
||||||
|
<button type="button" className="ghost" onClick={() => wrap('*')}><em>I</em></button>
|
||||||
|
<button type="button" className="ghost" onClick={() => insert('- ', true)}>{t('list')}</button>
|
||||||
|
<button type="button" className="ghost" onClick={() => insert('> ', true)}>{t('quote')}</button>
|
||||||
|
</div>
|
||||||
|
<textarea ref={body} name="body" rows={22} maxLength={100000} defaultValue={initial.body}
|
||||||
|
aria-labelledby="body-label" className="report-editor-body" spellCheck />
|
||||||
|
<details className="report-editor-help">
|
||||||
|
<summary><Icon name="info" /> {t('syntax')}</summary>
|
||||||
|
<ul>
|
||||||
|
<li><code>[[angabe:123]]</code> {t('helpEmbed')}</li>
|
||||||
|
<li><code>[Text](angabe:123)</code> {t('helpLink')}</li>
|
||||||
|
<li><code>[[bericht:slug]]</code>, <code>[Text](bericht:slug)</code> {t('helpReport')}</li>
|
||||||
|
<li><code>[Text](person:slug)</code>, <code>[Text](org:slug)</code>, <code>[Text](https://…)</code> {t('helpOther')}</li>
|
||||||
|
<li><code>## …</code>, <code>**…**</code>, <code>*…*</code>, <code>- …</code>, <code>> …</code> {t('helpFormat')}</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
<div className="cluster report-editor-meta">
|
||||||
|
<label className="field">
|
||||||
|
<span className="field-label">{t('lang')}</span>
|
||||||
|
<select name="lang" defaultValue={initial.lang}>
|
||||||
|
<option value="de">Deutsch</option>
|
||||||
|
<option value="en">English</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span className="field-label">{t('status')}</span>
|
||||||
|
<select name="status" defaultValue={initial.status}>
|
||||||
|
<option value="draft">{t('statusDraft')}</option>
|
||||||
|
<option value="published">{t('statusPublished')}</option>
|
||||||
|
{!isNew && <option value="withdrawn">{t('statusWithdrawn')}</option>}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p className="small">{t('responsibility')}</p>
|
||||||
|
{state.error && <p className="form-error" role="alert"><Icon name="alert" /> {state.error}</p>}
|
||||||
|
{state.saved && <p className="form-ok" role="status"><Icon name="check" /> {t('saved')}</p>}
|
||||||
|
<div className="cluster">
|
||||||
|
<button type="submit" disabled={pending}>{pending ? t('saving') : t('save')}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<aside className="report-picker card" aria-labelledby="picker-title">
|
||||||
|
<h2 id="picker-title" className="report-picker-title"><Icon name="search" /> {t('pickerTitle')}</h2>
|
||||||
|
<form onSubmit={search} className="stack">
|
||||||
|
<div className="chip-toggles" role="radiogroup" aria-label={t('pickerType')}>
|
||||||
|
{(['claim', 'report', 'person'] as const).map((value) => (
|
||||||
|
<label key={value} className="chip-toggle">
|
||||||
|
<input type="radio" className="visually-hidden" name="picker-type" value={value} checked={type === value}
|
||||||
|
onChange={() => { setType(value); setHits(null); }} />
|
||||||
|
{t(`type.${value}`)}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="cluster">
|
||||||
|
<input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t('pickerPlaceholder')}
|
||||||
|
aria-label={t('pickerTitle')} />
|
||||||
|
<button type="submit" className="secondary" disabled={searching}>{t('pickerSearch')}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{hits && hits.length === 0 && <p className="small">{t('pickerNone')}</p>}
|
||||||
|
{hits && hits.length > 0 && (
|
||||||
|
<ul className="report-picker-hits">
|
||||||
|
{hits.map((hit) => (
|
||||||
|
<li key={hit.code}>
|
||||||
|
<p className="report-picker-label">
|
||||||
|
{hit.official && <span className="badge badge--positive"><Icon name="shield" /> {t('official')}</span>}
|
||||||
|
{hit.label}
|
||||||
|
</p>
|
||||||
|
<p className="small">{hit.detail}</p>
|
||||||
|
<div className="cluster">
|
||||||
|
{type !== 'person' && (
|
||||||
|
<button type="button" className="secondary" onClick={() => insert(hit.code, true)}>{t('embed')}</button>
|
||||||
|
)}
|
||||||
|
<button type="button" className="ghost" onClick={() => insertLink(hit)}>{t('asLink')}</button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
<p className="small">{t('pickerHint')}</p>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ const ITEMS = {
|
|||||||
social: {href: '/social', key: 'social', icon: 'message'},
|
social: {href: '/social', key: 'social', icon: 'message'},
|
||||||
wikipedia: {href: '/wikipedia', key: 'wikipedia', icon: 'pencil'},
|
wikipedia: {href: '/wikipedia', key: 'wikipedia', icon: 'pencil'},
|
||||||
former: {href: '/ehemalige', key: 'former', icon: 'history'},
|
former: {href: '/ehemalige', key: 'former', icon: 'history'},
|
||||||
|
reports: {href: '/berichte', key: 'reports', icon: 'news'},
|
||||||
method: {href: '/methodik', key: 'method', icon: 'book'},
|
method: {href: '/methodik', key: 'method', icon: 'book'},
|
||||||
settings: {href: '/einstellungen', key: 'settings', icon: 'sliders'},
|
settings: {href: '/einstellungen', key: 'settings', icon: 'sliders'},
|
||||||
search: {href: '/suche', key: 'search', icon: 'search'},
|
search: {href: '/suche', key: 'search', icon: 'search'},
|
||||||
@@ -22,11 +23,11 @@ const ITEMS = {
|
|||||||
} satisfies Record<string, NavItem>;
|
} satisfies Record<string, NavItem>;
|
||||||
|
|
||||||
export const PRIMARY_NAV: NavItem[] = [ITEMS.persons, ITEMS.parties, ITEMS.votes, ITEMS.money, ITEMS.organizations, ITEMS.calendar];
|
export const PRIMARY_NAV: NavItem[] = [ITEMS.persons, ITEMS.parties, ITEMS.votes, ITEMS.money, ITEMS.organizations, ITEMS.calendar];
|
||||||
export const MORE_NAV: NavItem[] = [ITEMS.social, ITEMS.wikipedia, ITEMS.former, ITEMS.method];
|
export const MORE_NAV: NavItem[] = [ITEMS.reports, ITEMS.social, ITEMS.wikipedia, ITEMS.former, ITEMS.method];
|
||||||
|
|
||||||
export const NAV_GROUPS: {key: string; items: NavItem[]}[] = [
|
export const NAV_GROUPS: {key: string; items: NavItem[]}[] = [
|
||||||
{key: 'people', items: [ITEMS.persons, ITEMS.parties, ITEMS.former]},
|
{key: 'people', items: [ITEMS.persons, ITEMS.parties, ITEMS.former]},
|
||||||
{key: 'decisions', items: [ITEMS.votes, ITEMS.calendar, ITEMS.social]},
|
{key: 'decisions', items: [ITEMS.votes, ITEMS.calendar, ITEMS.social, ITEMS.reports]},
|
||||||
{key: 'influence', items: [ITEMS.money, ITEMS.organizations, ITEMS.wikipedia]},
|
{key: 'influence', items: [ITEMS.money, ITEMS.organizations, ITEMS.wikipedia]},
|
||||||
{key: 'about', items: [ITEMS.method, ITEMS.settings, ITEMS.search, ITEMS.imprint, ITEMS.privacy]}
|
{key: 'about', items: [ITEMS.method, ITEMS.settings, ITEMS.search, ITEMS.imprint, ITEMS.privacy]}
|
||||||
];
|
];
|
||||||
@@ -179,6 +179,12 @@ export type MoneySummaryRow = {
|
|||||||
count: number;
|
count: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type NamedRef = {
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
kind: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
export type Network = {
|
export type Network = {
|
||||||
organizations: NetworkOrg[];
|
organizations: NetworkOrg[];
|
||||||
};
|
};
|
||||||
@@ -341,6 +347,50 @@ export type RelatedOrg = {
|
|||||||
kind: string;
|
kind: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ReportDetail = {
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
lede: string | null;
|
||||||
|
lang: 'de' | 'en';
|
||||||
|
status: 'draft' | 'published' | 'withdrawn';
|
||||||
|
author_name: string;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
published_at: string | null;
|
||||||
|
claim_count: number;
|
||||||
|
official_claim_count: number;
|
||||||
|
revision_count: number;
|
||||||
|
body: string;
|
||||||
|
can_edit: boolean;
|
||||||
|
is_author: boolean;
|
||||||
|
references: ReportReferences;
|
||||||
|
backlinks: ReportListItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ReportListItem = {
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
lede: string | null;
|
||||||
|
lang: 'de' | 'en';
|
||||||
|
status: 'draft' | 'published' | 'withdrawn';
|
||||||
|
author_name: string;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
published_at: string | null;
|
||||||
|
claim_count: number;
|
||||||
|
official_claim_count: number;
|
||||||
|
revision_count: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ReportReferences = {
|
||||||
|
claims: Claim[];
|
||||||
|
claim_aliases: Record<string, number>;
|
||||||
|
missing_claims: number[];
|
||||||
|
reports: ReportListItem[];
|
||||||
|
persons: NamedRef[];
|
||||||
|
organizations: NamedRef[];
|
||||||
|
};
|
||||||
|
|
||||||
export type Role = {
|
export type Role = {
|
||||||
role: string;
|
role: string;
|
||||||
level: string;
|
level: string;
|
||||||
@@ -512,6 +562,8 @@ export type Paths = {
|
|||||||
'/api/v1/persons/{slug}': PersonDetail;
|
'/api/v1/persons/{slug}': PersonDetail;
|
||||||
'/api/v1/persons/{slug}/network': Network;
|
'/api/v1/persons/{slug}/network': Network;
|
||||||
'/api/v1/persons/{slug}/votes': PersonVote[];
|
'/api/v1/persons/{slug}/votes': PersonVote[];
|
||||||
|
'/api/v1/reports': ReportListItem[];
|
||||||
|
'/api/v1/reports/{slug}': ReportDetail;
|
||||||
'/api/v1/search': SearchHit[];
|
'/api/v1/search': SearchHit[];
|
||||||
'/api/v1/social': SocialPost[];
|
'/api/v1/social': SocialPost[];
|
||||||
'/api/v1/sources': Source[];
|
'/api/v1/sources': Source[];
|
||||||
|
|||||||
+42
-5
@@ -4,14 +4,18 @@
|
|||||||
import {cookies} from 'next/headers';
|
import {cookies} from 'next/headers';
|
||||||
import type * as T from './api-types';
|
import type * as T from './api-types';
|
||||||
import {PREFS_COOKIE, parsePrefs, type Prefs} from './prefs';
|
import {PREFS_COOKIE, parsePrefs, type Prefs} from './prefs';
|
||||||
|
import {getViewer, viewerHeaders} from './viewer';
|
||||||
|
|
||||||
export type {
|
export type {
|
||||||
CalendarData, CalendarEvent, Claim, Counterparty, Evidence, FormerPerson, MoneyFacet, MoneyFlow, MoneySummaryRow,
|
CalendarData, CalendarEvent, Claim, Counterparty, Evidence, FormerPerson, MoneyFacet, MoneyFlow, MoneySummaryRow,
|
||||||
Network, NetworkOrg, OrganizationDetail, OrganizationListItem, Party, PartyDetail, PartyRef, PersonDetail,
|
Network, NetworkOrg, OrganizationDetail, OrganizationListItem, Party, PartyDetail, PartyRef, PersonDetail,
|
||||||
PersonListItem, PersonVote, Role, SearchHit, SocialPost, Source, Stats, TimelineBucket, Topic, VoteDetail, VoteItem,
|
PersonListItem, PersonVote, ReportDetail, ReportListItem, ReportReferences, Role, SearchHit, SocialPost, Source, Stats,
|
||||||
WikiEdit
|
TimelineBucket, Topic, VoteDetail, VoteItem, WikiEdit
|
||||||
} from './api-types';
|
} from './api-types';
|
||||||
|
|
||||||
|
/** What the report editor sends (write endpoints are not in the public schema). */
|
||||||
|
export type ReportInput = {title: string; lede: string | null; body: string; lang: 'de' | 'en'; status: 'draft' | 'published' | 'withdrawn'};
|
||||||
|
|
||||||
export type Person = T.PersonDetail;
|
export type Person = T.PersonDetail;
|
||||||
export type ClaimType = T.Claim['claim_type'];
|
export type ClaimType = T.Claim['claim_type'];
|
||||||
export type PersonStatus = T.PersonDetail['status'];
|
export type PersonStatus = T.PersonDetail['status'];
|
||||||
@@ -30,7 +34,7 @@ export async function getPrefs(): Promise<Prefs> {
|
|||||||
|
|
||||||
type Params = Record<string, string | number | boolean | string[] | undefined | null>;
|
type Params = Record<string, string | number | boolean | string[] | undefined | null>;
|
||||||
|
|
||||||
async function get<R>(path: string, params: Params = {}): Promise<R> {
|
async function get<R>(path: string, params: Params = {}, extraHeaders: Record<string, string> = {}): Promise<R> {
|
||||||
const url = new URL(path, API);
|
const url = new URL(path, API);
|
||||||
for (const [key, value] of Object.entries(params)) {
|
for (const [key, value] of Object.entries(params)) {
|
||||||
if (value === undefined || value === null || value === '') continue;
|
if (value === undefined || value === null || value === '') continue;
|
||||||
@@ -40,7 +44,7 @@ async function get<R>(path: string, params: Params = {}): Promise<R> {
|
|||||||
url.searchParams.set(key, String(value));
|
url.searchParams.set(key, String(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const res = await fetch(url, {cache: 'no-store'});
|
const res = await fetch(url, {cache: 'no-store', headers: extraHeaders});
|
||||||
if (res.status === 404) throw new NotFoundError(path);
|
if (res.status === 404) throw new NotFoundError(path);
|
||||||
if (!res.ok) throw new Error(`API ${res.status} for ${url}`);
|
if (!res.ok) throw new Error(`API ${res.status} for ${url}`);
|
||||||
return res.json() as Promise<R>;
|
return res.json() as Promise<R>;
|
||||||
@@ -48,6 +52,32 @@ async function get<R>(path: string, params: Params = {}): Promise<R> {
|
|||||||
|
|
||||||
export class NotFoundError extends Error {}
|
export class NotFoundError extends Error {}
|
||||||
|
|
||||||
|
/** A write rejected by the API (400: invalid input, 401: not signed in, 404: not yours). */
|
||||||
|
export class WriteError extends Error {
|
||||||
|
constructor(public status: number, message: string) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes as the signed-in viewer. */
|
||||||
|
async function send<R>(method: 'POST' | 'PUT', path: string, body: unknown): Promise<R> {
|
||||||
|
const viewer = await getViewer();
|
||||||
|
if (!viewer) throw new WriteError(401, 'sign-in required');
|
||||||
|
const res = await fetch(new URL(path, API), {
|
||||||
|
method, cache: 'no-store', body: JSON.stringify(body),
|
||||||
|
headers: {'Content-Type': 'application/json', ...viewerHeaders(viewer)}
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const detail = await res.json().then((j: {detail?: unknown}) => String(j.detail ?? ''), () => '');
|
||||||
|
throw new WriteError(res.status, detail || `API ${res.status}`);
|
||||||
|
}
|
||||||
|
return res.json() as Promise<R>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function asViewer(): Promise<Record<string, string>> {
|
||||||
|
return viewerHeaders(await getViewer());
|
||||||
|
}
|
||||||
|
|
||||||
/** Adds the visitor's source filter (and topic filter, if wanted) from the preferences cookie. */
|
/** Adds the visitor's source filter (and topic filter, if wanted) from the preferences cookie. */
|
||||||
async function withPrefs(params: Params, useTopics = true): Promise<Params> {
|
async function withPrefs(params: Params, useTopics = true): Promise<Params> {
|
||||||
const prefs = await getPrefs();
|
const prefs = await getPrefs();
|
||||||
@@ -98,5 +128,12 @@ export const api = {
|
|||||||
wikiEdits: (params: Params) => get<T.WikiEdit[]>('/api/v1/wiki-edits', params),
|
wikiEdits: (params: Params) => get<T.WikiEdit[]>('/api/v1/wiki-edits', params),
|
||||||
|
|
||||||
search: async (q: string, since?: string, until?: string) =>
|
search: async (q: string, since?: string, until?: string) =>
|
||||||
get<T.SearchHit[]>('/api/v1/search', await withPrefs({q, since, until}, false))
|
get<T.SearchHit[]>('/api/v1/search', await withPrefs({q, since, until}, false)),
|
||||||
|
|
||||||
|
/** Published reports (mine: the viewer's own, drafts included). Not filtered by the visitor's sources. */
|
||||||
|
reports: async (params: Params) => get<T.ReportListItem[]>('/api/v1/reports', params, await asViewer()),
|
||||||
|
/** One report; drafts only for their author. */
|
||||||
|
report: async (slug: string) => get<T.ReportDetail>(`/api/v1/reports/${enc(slug)}`, {}, await asViewer()),
|
||||||
|
createReport: (input: ReportInput) => send<{slug: string}>('POST', '/api/v1/reports', input),
|
||||||
|
updateReport: (slug: string, input: ReportInput) => send<{slug: string}>('PUT', `/api/v1/reports/${enc(slug)}`, input)
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Who is signed in: the reverse proxy (SWAG + Authelia) passes the login as Remote-User/-Name/-Email/-Groups.
|
||||||
|
// Those headers are trusted only together with X-Politrack-Proxy = POLITRACK_PROXY_SECRET, which only the proxy
|
||||||
|
// sets: a request that reaches the web container directly (LAN port) can't claim to be someone. Without the
|
||||||
|
// secret configured, nobody is signed in and reports are read-only.
|
||||||
|
import {headers} from 'next/headers';
|
||||||
|
|
||||||
|
export type Viewer = {subject: string; name: string; email: string | null; groups: string[]};
|
||||||
|
|
||||||
|
function same(a: string, b: string): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
let diff = 0;
|
||||||
|
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||||
|
return diff === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getViewer(): Promise<Viewer | null> {
|
||||||
|
const secret = process.env.POLITRACK_PROXY_SECRET;
|
||||||
|
if (!secret || !process.env.POLITRACK_AUTHOR_TOKEN) return null;
|
||||||
|
const h = await headers();
|
||||||
|
if (!same(h.get('x-politrack-proxy') ?? '', secret)) return null;
|
||||||
|
const subject = h.get('remote-user')?.trim();
|
||||||
|
if (!subject) return null;
|
||||||
|
return {
|
||||||
|
subject,
|
||||||
|
name: h.get('remote-name')?.trim() || subject,
|
||||||
|
email: h.get('remote-email')?.trim() || null,
|
||||||
|
groups: (h.get('remote-groups') ?? '').split(',').map((g) => g.trim()).filter(Boolean)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Headers for API calls on behalf of the viewer (values percent-encoded: names may contain umlauts). */
|
||||||
|
export function viewerHeaders(viewer: Viewer | null): Record<string, string> {
|
||||||
|
const token = process.env.POLITRACK_AUTHOR_TOKEN;
|
||||||
|
if (!viewer || !token) return {};
|
||||||
|
return {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'X-Politrack-User': encodeURIComponent(viewer.subject),
|
||||||
|
'X-Politrack-User-Name': encodeURIComponent(viewer.name),
|
||||||
|
'X-Politrack-User-Email': encodeURIComponent(viewer.email ?? ''),
|
||||||
|
'X-Politrack-User-Groups': encodeURIComponent(viewer.groups.join(','))
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -2132,3 +2132,319 @@ input[type='checkbox'].switch:checked::before {
|
|||||||
from { background-position: 100% 0; }
|
from { background-position: 100% 0; }
|
||||||
to { background-position: -100% 0; }
|
to { background-position: -100% 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- reports (user articles with embedded claims) ---------- */
|
||||||
|
|
||||||
|
.report-list {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-3);
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-meta, .report-card-basis {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0;
|
||||||
|
color: var(--ink-3);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-title {
|
||||||
|
margin: var(--space-2) 0 var(--space-1);
|
||||||
|
font-size: var(--text-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-title a {
|
||||||
|
color: var(--ink);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-title a:hover {
|
||||||
|
color: var(--accent);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-lede {
|
||||||
|
margin: 0 0 var(--space-2);
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-card-basis .icon {
|
||||||
|
color: var(--positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report {
|
||||||
|
max-width: var(--prose-max);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-basis {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: var(--space-3);
|
||||||
|
margin: 0 0 var(--space-6);
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
border-left: 4px solid var(--positive);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--positive-soft);
|
||||||
|
color: var(--ink-2);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-basis > .icon {
|
||||||
|
flex: none;
|
||||||
|
width: 1.25rem;
|
||||||
|
height: 1.25rem;
|
||||||
|
margin-top: 0.1rem;
|
||||||
|
color: var(--positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-basis p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-body {
|
||||||
|
font-size: var(--text-md);
|
||||||
|
line-height: 1.65;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-body h2 {
|
||||||
|
margin-top: var(--space-7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-body h3 {
|
||||||
|
margin-top: var(--space-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-body blockquote {
|
||||||
|
margin-inline: 0;
|
||||||
|
padding-left: var(--space-4);
|
||||||
|
border-left: 3px solid var(--line-strong);
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-body hr {
|
||||||
|
margin: var(--space-6) 0;
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A database reference in the author's text: underlined with a seal, so it never looks like plain prose. */
|
||||||
|
.ref {
|
||||||
|
text-decoration-thickness: 1px;
|
||||||
|
text-underline-offset: 0.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref--claim {
|
||||||
|
padding: 0 0.15em;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent-ink);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref--claim.is-official {
|
||||||
|
background: var(--positive-soft);
|
||||||
|
color: var(--positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref--claim:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref--claim .icon {
|
||||||
|
width: 0.85em;
|
||||||
|
height: 0.85em;
|
||||||
|
margin-left: 0.2em;
|
||||||
|
vertical-align: -0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref--missing {
|
||||||
|
color: var(--ink-3);
|
||||||
|
text-decoration: line-through dotted;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ref-missing-block {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
border: 1px dashed var(--line-strong);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--ink-3);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* An embedded claim: the regular claim card under a seal saying where it comes from. */
|
||||||
|
.claim-embed {
|
||||||
|
margin: var(--space-5) 0;
|
||||||
|
border: 2px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
||||||
|
border-radius: calc(var(--radius-lg) + 2px);
|
||||||
|
background: var(--accent-soft);
|
||||||
|
font-size: var(--text-base);
|
||||||
|
line-height: var(--leading);
|
||||||
|
}
|
||||||
|
|
||||||
|
.claim-embed.is-official {
|
||||||
|
border-color: color-mix(in srgb, var(--positive) 45%, transparent);
|
||||||
|
background: var(--positive-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.claim-embed-seal {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding: var(--space-2) var(--space-4);
|
||||||
|
color: var(--accent-ink);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.claim-embed.is-official .claim-embed-seal {
|
||||||
|
color: var(--positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
.claim-embed-seal .icon {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.claim-embed > .claim {
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
border-radius: 0 0 var(--radius-lg) var(--radius-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-embed {
|
||||||
|
margin: var(--space-5) 0;
|
||||||
|
font-size: var(--text-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.embed-code {
|
||||||
|
padding: 0.1em 0.4em;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--surface-2);
|
||||||
|
user-select: all;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Editor: form on the left, reference picker on the right (stacked on phones). */
|
||||||
|
.report-editor {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: var(--space-5);
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 60rem) {
|
||||||
|
.report-editor {
|
||||||
|
grid-template-columns: minmax(0, 2fr) minmax(16rem, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker {
|
||||||
|
position: sticky;
|
||||||
|
top: calc(var(--header-h) + var(--space-4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-body {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 24rem;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-form textarea[name='lede'] {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-toolbar {
|
||||||
|
gap: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-toolbar button {
|
||||||
|
min-height: 2rem;
|
||||||
|
padding: 0.2rem 0.6rem;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-help {
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-help ul {
|
||||||
|
margin: var(--space-2) 0 0;
|
||||||
|
padding-left: var(--space-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-editor-meta .field {
|
||||||
|
flex: 0 1 14rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-error, .form-ok {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-error {
|
||||||
|
color: var(--negative);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-ok {
|
||||||
|
color: var(--positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0 0 var(--space-3);
|
||||||
|
font-size: var(--text-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker input[type='search'] {
|
||||||
|
flex: 1 1 10rem;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-hits {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-3);
|
||||||
|
max-height: 60vh;
|
||||||
|
margin: var(--space-3) 0;
|
||||||
|
padding: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-hits li {
|
||||||
|
padding-bottom: var(--space-3);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-hits p {
|
||||||
|
margin: 0 0 var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-label .badge {
|
||||||
|
margin-right: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-picker-hits button {
|
||||||
|
min-height: 2rem;
|
||||||
|
padding: 0.2rem 0.6rem;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-preview {
|
||||||
|
padding-top: var(--space-5);
|
||||||
|
border-top: 2px dashed var(--line-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-preview-title {
|
||||||
|
margin-top: var(--space-4);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user