Compare commits

...
8 Commits
Author SHA1 Message Date
simonandClaude Opus 5.5 1395dc2840 normalize_org_name keeps a partnership marker: a GmbH & Co KG no longer matches the GmbH
'Huber GmbH & Co KG' -> 'huber kg', 'Porsche Austria GmbH & Co OG' -> 'porsche austria og' (also &CoKG, KEG,
OHG), 'Huber GmbH' -> 'huber'. Alias matching treated the partnership and its general partner (different legal
entities) as one organisation. New legal_form_class(); firmenbuch.is_partnership uses it. Existing aliases are
recomputed and the merged organisations split by a one-off script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:20:42 +01:00
simonandClaude Opus 5.5 c61cb31e4a firmenbuch: a partnership (KG, OG, GmbH & Co KG) no longer matches the GmbH of the same name
The name search ignored the legal form, so "Huber GmbH & Co KG" (public contracts) was given the register number of
"Huber GmbH" in Ebenfurth and thereby linked to that company's managing director. Fixed on the server by moving the
number and the officer role to an organisation of their own. Commons register ids reuse firmenbuch_number().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:40:48 +01:00
simonandClaude Opus 5.5 b761517386 images: portraits and logos from Wikimedia Commons with author and licence
New adapter wikimedia.images: Wikidata P18 for people without an official photo, P154 logos for parties and
organisations matched by Wikidata id, Firmenbuch (P5285) or ZVR number (P6279). Licence data from the Commons
file page goes into image_credit (keyed by image URL); official Parliament/EP photos are never replaced.
Web: logos on party cards, party, organisation and organisation-list pages, credit lines under portraits and
logos, image proxy allows upload.wikimedia.org.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:35:27 +01:00
simonandClaude Opus 5.5 5640ed653b parlament: a written question's addressed minister is no longer recorded as asking it
The list row's "Personen" names the askers and the minister the question is addressed to. Persons who answered
the linked answer (or, for unanswered questions, any answer in the same period) are now left out of the askers.
(Test in the following commit, tests/test_parsers.py.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:35:27 +01:00
simonandClaude Opus 5.5 0c8b38a6b4 reports: count only claims that exist and are published
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:33:14 +01:00
simonandClaude Opus 5.5 8e16c01634 resolver: an organisation name shared by several records no longer creates another one
When an alias matched more than one organisation, the lookup gave up and the loader created a new record,
which made the name match three next time. A reparse of rtr.medientransparenz (2026-11-20) turned this into
41 duplicate organisations and 3,600 duplicate money flows. pick_org now chooses the exact name, then the same
kind, then the oldest record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:35:01 +01:00
simonandClaude Opus 5.5 9f0e2fc115 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>
2026-11-20 10:19:50 +01:00
simonandClaude Opus 5.5 f2d72fe464 fixes: immunity outcomes without political connection, ORF fee rows, dropped WKStA investigations
- parlament.items (parser 3): a committee finding of no connection to the political activity
  (Art. 57 Abs. 3 B-VG) means prosecution may proceed; it was left at 'requested'. Authority and
  case number no longer run into the following sentence on older reports.
- rtr.medientransparenz (parser 2): notice type 31 is the ORF's licence-fee income under section 31
  ORF-G, not a payment to an organisation named after the paragraph.
- enrich.legal: 'Einstellung der Ermittlungen' is proceedings_dropped, not an investigation.
- reparse -p kinds=a,b replays only responses of these request kinds (no stale sweep then).
- migration 0010 removes the wrong ORF rows and organisations and re-queues the affected headlines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:03:11 +01:00
60 changed files with 2708 additions and 56 deletions

No files matched your search

+5
View File
@@ -31,6 +31,11 @@ POLITRACK_API_CORS_ORIGINS=["http://localhost:3000"]
# Moderation endpoints (/api/v1/review, /api/v1/admin/runs). Leave empty to moderate via the CLI only.
# POLITRACK_ADMIN_TOKEN=
# Reports written by signed-in users (docs/deployment-unraid.md, "Reports and sign-in"). Both empty = read-only.
# POLITRACK_AUTHOR_TOKEN= shared by web and api (e.g. openssl rand -hex 32)
# POLITRACK_PROXY_SECRET= the reverse proxy sends it as X-Politrack-Proxy (e.g. openssl rand -hex 32)
# POLITRACK_REPORT_EDITOR_GROUPS=["admins"] login groups that may edit and withdraw any report
# Nightly database dumps (backup service). Ideally on a different disk or share than DATA_DIR.
# BACKUP_DIR=/mnt/user/backups/politrack
# BACKUP_KEEP_DAYS=14
@@ -0,0 +1,28 @@
-- Data fixes that go with parser changes of November 2026.
-- 1. RTR notice type 31 (§ 31 ORF-G) is the ORF's licence-fee income. It was stored as a "payment" from the ORF to
-- an organisation named after the legal basis. rtr.medientransparenz (parser_version 2) now emits it as ORF income;
-- `politrack reparse rtr.medientransparenz -p kinds=quartal` recreates the rows.
DELETE FROM claim c USING money_flow mf
WHERE mf.claim_id = c.id AND c.created_by = 'rtr.medientransparenz' AND mf.kind = 'other'
AND mf.payee_name ~ '§ 31 Abs\. [0-9]+ ORF-G';
DELETE FROM alias WHERE entity_type = 'organization'
AND entity_id IN (SELECT id FROM organization WHERE name ~ '^(Programmentgelt|Abgeltung) gemäß § 31 Abs\. [0-9]+ ORF-G$');
DELETE FROM identifier WHERE entity_type = 'organization'
AND entity_id IN (SELECT id FROM organization WHERE name ~ '^(Programmentgelt|Abgeltung) gemäß § 31 Abs\. [0-9]+ ORF-G$');
DELETE FROM organization o
WHERE o.name ~ '^(Programmentgelt|Abgeltung) gemäß § 31 Abs\. [0-9]+ ORF-G$'
AND NOT EXISTS (SELECT 1 FROM claim c WHERE c.organization_id = o.id OR c.counterpart_org_id = o.id)
AND NOT EXISTS (SELECT 1 FROM money_flow m WHERE m.payer_org_id = o.id OR m.payee_org_id = o.id);
-- 2. enrich.legal read "Einstellung der Ermittlungen" (proceedings dropped) as an investigation. Drop those unreviewed
-- proposals and let the enricher look at the headlines again.
DELETE FROM claim c
WHERE c.created_by = 'enrich.legal' AND c.review_status = 'pending'
AND EXISTS (SELECT 1 FROM claim_evidence e JOIN document d ON d.id = e.document_id
WHERE e.claim_id = c.id AND d.title ~* 'Einstellung(en)?\M.{0,40}(Verfahren|Ermittlung)');
UPDATE claim c SET data = c.data - 'legal_checked'
WHERE c.claim_type = 'media_mention' AND c.data ? 'legal_checked'
AND EXISTS (SELECT 1 FROM claim_evidence e JOIN document d ON d.id = e.document_id
WHERE e.claim_id = c.id AND d.title ~* 'Einstellung(en)?\M.{0,40}(Verfahren|Ermittlung)');
+52
View File
@@ -0,0 +1,52 @@
-- Reports: articles written by signed-in users that embed and link claims (and other reports) from the database.
-- The text is the author's; the embedded claims keep their own evidence, so readers can tell the two apart.
ALTER TABLE app_user ADD COLUMN display_name TEXT;
ALTER TABLE app_user ADD COLUMN last_seen_at TIMESTAMPTZ;
COMMENT ON COLUMN app_user.external_subject IS 'User name from the reverse-proxy login (Authelia Remote-User).';
COMMENT ON COLUMN app_user.display_name IS 'Name shown as the author of reports (Authelia Remote-Name), updated at every write.';
CREATE TABLE report (
id SERIAL PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
lede TEXT,
body TEXT NOT NULL,
lang TEXT NOT NULL DEFAULT 'de' CHECK (lang IN ('de', 'en')),
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'withdrawn')),
author_id INT NOT NULL REFERENCES app_user(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
COMMENT ON TABLE report IS 'User-written articles. body is Markdown with references: [[angabe:ID]] embeds a claim, [[bericht:slug]] another report; [text](angabe:ID|bericht:slug|person:slug|org:slug) link inline.';
COMMENT ON COLUMN report.slug IS 'Permanent URL key, fixed at creation so that links from other reports keep working.';
COMMENT ON COLUMN report.status IS 'draft: only the author sees it. published: listed. withdrawn: unlisted, the page stays and says so.';
COMMENT ON COLUMN report.published_at IS 'First publication; later edits only change updated_at (and add a revision).';
CREATE INDEX report_list_idx ON report (status, published_at DESC);
CREATE INDEX report_author_idx ON report (author_id, updated_at DESC);
CREATE TABLE report_revision (
id BIGSERIAL PRIMARY KEY,
report_id INT NOT NULL REFERENCES report(id) ON DELETE CASCADE,
title TEXT NOT NULL,
lede TEXT,
body TEXT NOT NULL,
status TEXT NOT NULL,
edited_by INT NOT NULL REFERENCES app_user(id),
edited_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE report_revision IS 'Every saved version of a report (also the first), so that changes after publication stay traceable.';
CREATE INDEX report_revision_idx ON report_revision (report_id, edited_at DESC);
CREATE TABLE report_reference (
report_id INT NOT NULL REFERENCES report(id) ON DELETE CASCADE,
ref_type TEXT NOT NULL CHECK (ref_type IN ('claim', 'report', 'person', 'organization')),
ref_key TEXT NOT NULL,
embedded BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (report_id, ref_type, ref_key)
);
COMMENT ON TABLE report_reference IS 'References parsed from the current body at every save: drives "used in reports" on claim, person and report pages.';
COMMENT ON COLUMN report_reference.ref_key IS 'Claim id, report slug, person slug or organisation slug, as written in the body.';
COMMENT ON COLUMN report_reference.embedded IS 'TRUE for a block embed ([[...]]), FALSE for an inline link.';
CREATE INDEX report_reference_target_idx ON report_reference (ref_type, ref_key);
+13
View File
@@ -0,0 +1,13 @@
-- Portraits and logos from Wikimedia Commons (via Wikidata P18 / P154). The image itself sits in person.photo_url or
-- organization.logo_url; official photos (Parliament, European Parliament) take precedence and are never replaced.
-- The licence data is keyed by the image URL, so the credit always belongs to the image that is actually shown.
CREATE TABLE image_credit (
url TEXT PRIMARY KEY,
page_url TEXT, -- file description page on Commons
credit TEXT, -- author / attribution as plain text
license TEXT, -- short name, e.g. "CC BY-SA 4.0"
license_url TEXT,
source_slug TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE image_credit IS 'Licence and attribution for third-party images in person.photo_url / organization.logo_url (Wikimedia Commons). No row = official photo of the source (Parliament, EP).';
+71 -1
View File
@@ -6,9 +6,11 @@ Conventions: every list endpoint takes limit/offset; claim-like endpoints take t
from __future__ import annotations
import hmac
from collections.abc import Iterator
from datetime import date
from typing import Annotated
from urllib.parse import unquote
from fastapi import Depends, FastAPI, Header, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
@@ -28,7 +30,7 @@ app = FastAPI(
docs_url="/api/docs",
openapi_url="/api/openapi.json",
)
app.add_middleware(CORSMiddleware, allow_origins=get_settings().api_cors_origins, allow_methods=["GET", "POST"],
app.add_middleware(CORSMiddleware, allow_origins=get_settings().api_cors_origins, allow_methods=["GET", "POST", "PUT"],
allow_headers=["*"])
@@ -255,6 +257,74 @@ def get_search(conn: DB, sources: Sources, q: Annotated[str, Query(min_length=2)
return queries.search(conn, q, sources=sources, since=since, until=until, limit=limit)
# -- reports ----------------------------------------------------------------------------------------------------------
# Reading is public (published reports). Writing: the web app calls with Authorization: Bearer POLITRACK_AUTHOR_TOKEN
# and the signed-in user in X-Politrack-User (Authelia Remote-User), -User-Name and -User-Email (percent-encoded)
# and -User-Groups (comma-separated).
def report_viewer(
authorization: Annotated[str | None, Header()] = None,
x_politrack_user: Annotated[str | None, Header()] = None,
x_politrack_user_name: Annotated[str | None, Header()] = None,
x_politrack_user_email: Annotated[str | None, Header()] = None,
x_politrack_user_groups: Annotated[str | None, Header()] = None,
) -> queries.Viewer | None:
settings = get_settings()
token = settings.author_token
if not token or not x_politrack_user or not hmac.compare_digest(authorization or "", f"Bearer {token}"):
return None
groups = [g.strip() for g in unquote(x_politrack_user_groups or "").split(",") if g.strip()]
return queries.Viewer(subject=unquote(x_politrack_user), name=unquote(x_politrack_user_name or "") or None,
email=unquote(x_politrack_user_email or "") or None, groups=groups,
editor=bool(set(groups) & set(settings.report_editor_groups)))
ReportViewer = Annotated[queries.Viewer | None, Depends(report_viewer)]
def require_author(viewer: ReportViewer) -> queries.Viewer:
if viewer is None:
raise HTTPException(401, "sign-in required")
return viewer
@app.get("/api/v1/reports", response_model=list[s.ReportListItem])
def get_reports(conn: DB, viewer: ReportViewer, mine: bool = False, claim: int | None = None, person: str | None = None,
org: str | None = None, report: str | None = None, q: str | None = None, limit: Limit = 30,
offset: Offset = 0):
"""Published reports written by users, newest first. Filter by a referenced claim, person, organisation or report.
Reports are opinion pieces: the embedded claims carry the evidence, the text around them is the author's."""
if mine and viewer is None:
raise HTTPException(401, "sign-in required")
return queries.list_reports(conn, viewer=viewer, mine=mine, claim_id=claim, person=person, organization=org,
report=report, q=q, limit=limit, offset=offset)
@app.get("/api/v1/reports/{slug}", response_model=s.ReportDetail)
def get_report(slug: str, conn: DB, viewer: ReportViewer):
"""A report with its body (Markdown with [[angabe:ID]] embeds) and every referenced claim, report, person and
organisation resolved, plus the reports that link to it."""
return not_found(queries.get_report(conn, slug, viewer), "report")
@app.post("/api/v1/reports", response_model=s.ReportSaved, include_in_schema=False)
def post_report(data: s.ReportInput, conn: DB, viewer: Annotated[queries.Viewer, Depends(require_author)]):
try:
return {"slug": queries.create_report(conn, viewer, **data.model_dump())}
except queries.ReportError as error:
raise HTTPException(400, str(error)) from error
@app.put("/api/v1/reports/{slug}", response_model=s.ReportSaved, include_in_schema=False)
def put_report(slug: str, data: s.ReportInput, conn: DB, viewer: Annotated[queries.Viewer, Depends(require_author)]):
try:
if not queries.update_report(conn, viewer, slug, **data.model_dump()):
raise HTTPException(404, "report not found or not yours")
except queries.ReportError as error:
raise HTTPException(400, str(error)) from error
return {"slug": slug}
# -- admin (POLITRACK_ADMIN_TOKEN) ------------------------------------------------------------------
def require_admin(authorization: Annotated[str | None, Header()] = None) -> str:
+66
View File
@@ -163,6 +163,10 @@ class PersonDetail(Model):
birth_date: date | None = None
death_date: date | None = None
photo_url: str | None = None
photo_credit: str | None = None
photo_license: str | None = None
photo_license_url: str | None = None
photo_page_url: str | None = None
wikidata_qid: str | None = None
parlament_pad: str | None = None
ep_id: str | None = None
@@ -264,6 +268,10 @@ class PartyDetail(Model):
short_name: str | None = None
color: str | None = None
logo_url: str | None = None
logo_credit: str | None = None
logo_license: str | None = None
logo_license_url: str | None = None
logo_page_url: str | None = None
kind: str
members: list[PartyMember]
former_members: list[FormerMember]
@@ -279,6 +287,7 @@ class OrganizationListItem(Model):
name: str
short_name: str | None = None
kind: str
logo_url: str | None = None
paid: float | None = None
received: float | None = None
@@ -317,6 +326,11 @@ class OrganizationDetail(Model):
parent_slug: str | None = None
parent_name: str | None = None
identifiers: dict[str, str] | None = None
logo_url: str | None = None
logo_credit: str | None = None
logo_license: str | None = None
logo_license_url: str | None = None
logo_page_url: str | None = None
money: list[OrgMoney]
counterparties: list[Counterparty]
people: list[OrgPerson]
@@ -533,3 +547,55 @@ class PendingClaim(Model):
occurred_at: datetime | None = None
full_name: str | None = None
evidence: list[dict[str, Any]] | None = None
# -- reports --------------------------------------------------------------------------------------------------------
class ReportListItem(Model):
slug: str
title: str
lede: str | None = None
lang: Literal["de", "en"]
status: Literal["draft", "published", "withdrawn"]
author_name: str
created_at: datetime
updated_at: datetime
published_at: datetime | None = None
claim_count: int
official_claim_count: int
revision_count: int
class NamedRef(Model):
slug: str
name: str
kind: str | None = None
class ReportReferences(Model):
claims: list[Claim]
claim_aliases: dict[str, int] = {}
missing_claims: list[int] = []
reports: list[ReportListItem]
persons: list[NamedRef]
organizations: list[NamedRef]
class ReportDetail(ReportListItem):
body: str
can_edit: bool
is_author: bool
references: ReportReferences
backlinks: list[ReportListItem]
class ReportInput(BaseModel):
title: str
lede: str | None = None
body: str
lang: Literal["de", "en"] = "de"
status: Literal["draft", "published", "withdrawn"] = "draft"
class ReportSaved(Model):
slug: str
+4
View File
@@ -42,6 +42,10 @@ class Settings(BaseSettings):
api_cors_origins: list[str] = ["http://localhost:3000"]
# Bearer token for moderation/admin endpoints. Empty = disabled (use the CLI).
admin_token: str | None = None
# Shared secret of the web app for writing reports on behalf of a signed-in user. Empty = reports are read-only.
author_token: str | None = None
# Members of these login groups (Authelia Remote-Groups) may edit and withdraw any report.
report_editor_groups: list[str] = ["admins"]
@lru_cache
+30
View File
@@ -25,6 +25,7 @@ from politrack.core.records import (
Document,
Event,
Evidence,
Image,
Legal,
Money,
OrgRecord,
@@ -82,6 +83,8 @@ class Loader:
return self.post_removed(record)
if isinstance(record, ArchiveCopy):
return self.archive_copy(record)
if isinstance(record, Image):
return self.image(record)
raise TypeError(f"unknown record type {type(record).__name__}")
# -- documents --------------------------------------------------------------------
@@ -244,6 +247,33 @@ class Loader:
self.ctx.stats["social_accounts"] += 1
return row["id"]
def image(self, rec: Image) -> int | None:
"""Portrait or logo from Commons: only where no official image exists (or a Commons one is replaced)."""
third_party = "(col IS NULL OR col LIKE 'https://upload.wikimedia.org/%%')"
if rec.role == "photo":
entity_id = self.resolver.person(rec.person)
table, col = "person", "photo_url"
else:
entity_id = self.resolver.org(rec.org, create=False)
table, col = "organization", "logo_url"
if entity_id is None:
self.ctx.stats["images_unresolved"] += 1
return None
self.conn.execute(
"""INSERT INTO image_credit (url, page_url, credit, license, license_url, source_slug)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (url) DO UPDATE SET page_url = EXCLUDED.page_url, credit = EXCLUDED.credit,
license = EXCLUDED.license, license_url = EXCLUDED.license_url, updated_at = now()""",
(rec.url, rec.page_url, rec.credit, rec.license, rec.license_url, self.ctx.spec.slug),
)
updated = self.conn.execute(
f"UPDATE {table} SET {col} = %s WHERE id = %s AND {third_party.replace('col', col)} "
f"AND {col} IS DISTINCT FROM %s",
(rec.url, entity_id, rec.url),
).rowcount
self.ctx.stats["images_set" if updated else "images_kept"] += 1
return entity_id
# -- standalone facets ------------------------------------------------------------
def vote_event(self, rec: VoteEvent) -> int:
+16 -1
View File
@@ -121,6 +121,20 @@ class SocialAccount:
verified: bool = False # True only for official sources (parliament profile, official website)
@dataclass
class Image:
"""A portrait (person) or logo (organization) from a freely licensed source, with its attribution. Fills the
entity's photo_url / logo_url only if it has no official image."""
url: str # the image (thumbnail) shown on the site
role: Literal["photo", "logo"]
page_url: str | None = None # description page with the full licence information
credit: str | None = None
license: str | None = None
license_url: str | None = None
person: PersonRef | None = None
org: OrgRef | None = None
# --------------------------------------------------------------------------------------------
# Facets (structured payload of a claim)
# --------------------------------------------------------------------------------------------
@@ -273,7 +287,8 @@ class ArchiveCopy:
archive_url: str
Record = Union[PersonRecord, OrgRecord, SocialAccount, VoteEvent, Event, Claim, Document, PostRemoved, ArchiveCopy]
Record = Union[PersonRecord, OrgRecord, SocialAccount, VoteEvent, Event, Claim, Document, PostRemoved, ArchiveCopy,
Image]
def to_jsonable(obj: Any) -> Any:
+16 -1
View File
@@ -30,6 +30,13 @@ OFFICE_FILLER = re.compile(r"\b(der republik osterreich|der bundesrepublik oster
r"\(osterreich\)")
def pick_org(candidates: list[dict], label: str, kind: str | None) -> int:
"""Tie-break between organisations sharing an alias: the exact name first, then the same kind, then the oldest."""
exact = normalize(label)
return min(candidates, key=lambda o: (normalize(o["name"] or "") != exact, bool(kind) and o["kind"] != kind,
o["id"]))["id"]
def name_parts(name: str) -> tuple[str, str]:
"""'Mag. Chiara-Sophia Glawogger' -> ('chiara', 'glawogger'): first given name and surname, normalised."""
tokens = normalize(strip_titles(name)).replace(",", " ").split()
@@ -293,16 +300,24 @@ class Resolver:
row = self.conn.execute("SELECT id FROM organization WHERE slug = %s", (ref.slug,)).fetchone()
if row:
return row["id"]
ambiguous: set[int] = set()
for label in (ref.short_name, ref.name):
if not label:
continue
for norm in {normalize(label), normalize_org_name(label)} - {""}:
for norm in sorted({normalize(label), normalize_org_name(label)} - {""}):
rows = self.conn.execute(
"SELECT DISTINCT entity_id FROM alias WHERE entity_type = 'organization' AND alias_norm = %s",
(norm,),
).fetchall()
if len(rows) == 1:
return rows[0]["entity_id"]
ambiguous.update(r["entity_id"] for r in rows)
if ambiguous:
# Several organisations share the name ("Tiroler Tageszeitung" / "Tiroler Tageszeitung GmbH"). Creating
# another one would only add a third; pick one deterministically instead.
candidates = self.conn.execute("SELECT id, name, kind FROM organization WHERE id = ANY(%s)",
(sorted(ambiguous),)).fetchall()
return pick_org(candidates, ref.name or ref.short_name or "", ref.kind)
return None
def _org_create(self, ref: OrgRef) -> int:
+6 -1
View File
@@ -155,6 +155,11 @@ def _reparse(adapter: Adapter, ctx: RunContext, conn: Connection) -> None:
loader = Loader(conn, ctx)
started = conn.execute("SELECT now() AS t").fetchone()["t"]
rows = archive.latest_stored(conn, adapter.name)
# -p kinds=a,b reparses only responses of these request kinds (e.g. one parser of a large adapter). Claims
# of the other kinds are not reproduced then, so the stale-claim sweep is skipped.
kinds = {k for k in str(ctx.params.get("kinds", "")).split(",") if k}
if kinds:
rows = [r for r in rows if (r["request"] or {}).get("kind", "default") in kinds]
ctx.log.info("reparsing %s archived responses", len(rows))
# Parse list/index responses before detail responses: records referencing others (vote positions ->
# vote events) are emitted by the parent's parse() in order, so the original order is preserved
@@ -173,7 +178,7 @@ def _reparse(adapter: Adapter, ctx: RunContext, conn: Connection) -> None:
tdm_reserved=row["tdm_reserved"], from_archive=True)
ctx.stats["responses"] += 1
_parse_and_load(adapter, ctx, conn, loader, resp) # follow-ups are archived separately
if not ctx.stats.get("errors") and not ctx.stats.get("missing_blobs"):
if not kinds and not ctx.stats.get("errors") and not ctx.stats.get("missing_blobs"):
_sweep_stale_claims(adapter, ctx, conn, started)
+3 -1
View File
@@ -26,7 +26,9 @@ STAGES = [
r"schuldig gesprochen|Schuldspruch|\bverurteilt\b)", re.I)),
("acquitted", re.compile(r"\b(freigesprochen|Freispruch)\b", re.I)),
("diversion", re.compile(r"\bDiversion\b", re.I)),
("proceedings_dropped", re.compile(r"\b(Verfahren|Ermittlungen)\b.*\beingestellt\b|\beingestellt\b.*\bVerfahren\b", re.I)),
# "Einstellung(en) der Ermittlungen gegen ..." as well as "Verfahren eingestellt"
("proceedings_dropped", re.compile(r"\b(Verfahren|Ermittlungen)\b.*\beingestellt\b|\beingestellt\b.*\bVerfahren\b|"
r"\bEinstellung(en)?\b.{0,40}\b(Verfahrens?|Ermittlung(en|sverfahren)?)\b", re.I)),
("trial", re.compile(r"\b(Prozess|Strafprozess|vor Gericht|Prozessauftakt|Hauptverhandlung)\b", re.I)),
("indicted", re.compile(r"\b(angeklagt|Anklage|Strafantrag)\b", re.I)),
("investigation", re.compile(r"\b(ermittelt|Ermittlungen|Ermittlungsverfahren|Beschuldigte[rn]?|Hausdurchsuchung|"
+11 -1
View File
@@ -14,11 +14,21 @@ from politrack.queries.common import SourceFilter
from politrack.queries.money import list_money, money_summary, social_feed, wiki_edits
from politrack.queries.organizations import get_organization, get_party, list_organizations, list_parties
from politrack.queries.people import former_overview, get_person, list_persons, person_network
from politrack.queries.reports import (
ReportError,
Viewer,
create_report,
get_report,
list_reports,
resolve_references,
update_report,
)
from politrack.queries.search import search
from politrack.queries.votes import list_votes, person_votes, vote_detail
__all__ = [
"SourceFilter", "calendar", "former_overview", "get_organization", "get_party", "get_person", "list_claims",
"ReportError", "SourceFilter", "Viewer", "calendar", "create_report", "get_report", "list_reports",
"resolve_references", "update_report", "former_overview", "get_organization", "get_party", "get_person", "list_claims",
"list_money", "list_organizations", "list_parties", "list_persons", "list_sources", "list_topics", "list_votes",
"money_summary", "pending_claims", "recent_runs", "person_network", "person_votes", "search", "set_review", "social_feed",
"source_freshness", "stats", "timeline_histogram", "vote_detail", "wiki_edits",
+4 -2
View File
@@ -22,6 +22,7 @@ def list_claims(
until: date | None = None,
q: str | None = None,
claim_id: int | None = None,
claim_ids: list[int] | None = None,
include_pending: bool = False,
limit: int = 50,
offset: int = 0,
@@ -29,7 +30,7 @@ def list_claims(
source_sql, params = sources.sql("s")
params.update({
"person": person, "party": party, "organization": organization, "claim_types": claim_types, "topics": topics, "since": since,
"until": until, "q": q, "claim_id": claim_id, "limit": limit, "offset": offset, "include_pending": include_pending,
"until": until, "q": q, "claim_id": claim_id, "claim_ids": claim_ids, "limit": limit, "offset": offset, "include_pending": include_pending,
})
return conn.execute(
f"""
@@ -62,7 +63,7 @@ def list_claims(
WHERE e.claim_id = c.id AND {source_sql}
) ev
WHERE ev.evidence IS NOT NULL AND {VISIBLE}
AND (%(claim_id)s::bigint IS NOT NULL OR {NOT_PART_VOTE})
AND (%(claim_id)s::bigint IS NOT NULL OR %(claim_ids)s::bigint[] IS NOT NULL OR {NOT_PART_VOTE})
AND (%(person)s::text IS NULL OR p.slug = %(person)s OR cpp.slug = %(person)s)
AND (%(party)s::text IS NULL OR o.slug = %(party)s
OR c.counterpart_org_id = (SELECT id FROM organization WHERE slug = %(party)s))
@@ -76,6 +77,7 @@ def list_claims(
AND (%(until)s::date IS NULL OR COALESCE(c.occurred_at::date, c.valid_from) <= %(until)s)
AND (%(q)s::text IS NULL OR c.summary_de ILIKE '%%' || %(q)s || '%%')
AND (%(claim_id)s::bigint IS NULL OR c.id = %(claim_id)s)
AND (%(claim_ids)s::bigint[] IS NULL OR c.id = ANY(%(claim_ids)s))
ORDER BY COALESCE(c.occurred_at, c.valid_from::timestamptz, c.created_at) DESC, c.id DESC
LIMIT %(limit)s OFFSET %(offset)s
""",
+9 -4
View File
@@ -30,7 +30,9 @@ def list_parties(conn: Connection) -> list[dict]:
def get_party(conn: Connection, slug: str) -> dict | None:
party = conn.execute(
"SELECT id, slug, name, short_name, color, logo_url, kind FROM organization WHERE slug = %s", (slug,)
"""SELECT o.id, o.slug, o.name, o.short_name, o.color, o.logo_url, o.kind, ic.credit AS logo_credit,
ic.license AS logo_license, ic.license_url AS logo_license_url, ic.page_url AS logo_page_url
FROM organization o LEFT JOIN image_credit ic ON ic.url = o.logo_url WHERE o.slug = %s""", (slug,)
).fetchone()
if not party:
return None
@@ -105,7 +107,7 @@ def list_organizations(conn: Connection, *, q: str | None = None, kind: str | No
offset: int = 0) -> list[dict]:
return conn.execute(
"""
SELECT o.slug, o.name, o.short_name, o.kind,
SELECT o.slug, o.name, o.short_name, o.kind, o.logo_url,
(SELECT sum(amount) FROM money_flow WHERE payer_org_id = o.id) AS paid,
(SELECT sum(amount) FROM money_flow WHERE payee_org_id = o.id) AS received
FROM organization o
@@ -125,8 +127,11 @@ def get_organization(conn: Connection, slug: str) -> dict | None:
org = conn.execute(
"""SELECT o.id, o.slug, o.name, o.short_name, o.kind, parent.slug AS parent_slug, parent.name AS parent_name,
(SELECT jsonb_object_agg(i.scheme, i.value) FROM identifier i
WHERE i.entity_type = 'organization' AND i.entity_id = o.id) AS identifiers
FROM organization o LEFT JOIN organization parent ON parent.id = o.parent_id WHERE o.slug = %s""",
WHERE i.entity_type = 'organization' AND i.entity_id = o.id) AS identifiers,
o.logo_url, ic.credit AS logo_credit, ic.license AS logo_license, ic.license_url AS logo_license_url,
ic.page_url AS logo_page_url
FROM organization o LEFT JOIN organization parent ON parent.id = o.parent_id
LEFT JOIN image_credit ic ON ic.url = o.logo_url WHERE o.slug = %s""",
(slug,),
).fetchone()
if not org:
+4 -1
View File
@@ -40,8 +40,11 @@ def get_person(conn: Connection, slug: str) -> dict | None:
"""
SELECT p.id, p.slug, p.full_name, p.given_name, p.family_name, p.honorific_prefix, p.birth_date, p.death_date,
p.photo_url, pi.wikidata_qid, pi.parlament_pad, pi.ep_id, p.summary_de, p.summary_en, ps.status,
ps.verified AS status_verified, ps.last_office_end
ps.verified AS status_verified, ps.last_office_end,
ic.credit AS photo_credit, ic.license AS photo_license, ic.license_url AS photo_license_url,
ic.page_url AS photo_page_url
FROM person p JOIN person_status ps ON ps.person_id = p.id JOIN person_identifier pi ON pi.person_id = p.id
LEFT JOIN image_credit ic ON ic.url = p.photo_url
WHERE p.slug = %s
""",
(slug,),
+270
View File
@@ -0,0 +1,270 @@
"""Reports: user-written articles that embed claims and link other reports.
Body syntax (Markdown subset, rendered by the web app's ReportBody):
[[angabe:123]] on a line of its own: the claim as a card, with its evidence
[[bericht:some-slug]] on a line of its own: a card linking another report
[text](angabe:123) inline link to a claim; also bericht:slug, person:slug, org:slug
English aliases (claim:, report:, organization:) work too. References are parsed at every save into
report_reference, which drives "used in reports" on claim, person and report pages.
Writes happen only through the API's author endpoints, which the web app calls with POLITRACK_AUTHOR_TOKEN on
behalf of a user signed in at the reverse proxy (Authelia).
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
from psycopg import Connection
from politrack.queries.claims import list_claims
from politrack.queries.common import SourceFilter
from politrack.text import make_slug
REF_TYPES = {"angabe": "claim", "claim": "claim", "bericht": "report", "report": "report", "person": "person",
"org": "organization", "organisation": "organization", "organization": "organization"}
_NAMES = "|".join(REF_TYPES)
BLOCK_REF = re.compile(rf"^[ \t]*\[\[({_NAMES})\s*:\s*([^\]\s]+)\s*\]\][ \t]*$", re.IGNORECASE | re.MULTILINE)
INLINE_REF = re.compile(rf"\[([^\]\n]+)\]\(({_NAMES}):([^)\s]+)\)", re.IGNORECASE)
MAX_BODY = 100_000
@dataclass
class Viewer:
"""The signed-in user on whose behalf the web app calls (from the X-Politrack-User* headers)."""
subject: str
name: str | None = None
email: str | None = None
groups: list[str] = field(default_factory=list)
editor: bool = False
def parse_references(body: str) -> list[tuple[str, str, bool]]:
"""(ref_type, key, embedded) for every valid reference in the body, without duplicates (embedding wins)."""
refs: dict[tuple[str, str], bool] = {}
for m in BLOCK_REF.finditer(body):
ref_type, key = REF_TYPES[m.group(1).lower()], m.group(2)
if _valid(ref_type, key):
refs[(ref_type, key)] = True
for m in INLINE_REF.finditer(body):
ref_type, key = REF_TYPES[m.group(2).lower()], m.group(3)
if _valid(ref_type, key):
refs.setdefault((ref_type, key), False)
return [(t, k, e) for (t, k), e in refs.items()]
def _valid(ref_type: str, key: str) -> bool:
return key.isdigit() if ref_type == "claim" else bool(re.fullmatch(r"[a-z0-9][a-z0-9-]{0,200}", key))
# -- users ----------------------------------------------------------------------------------------------------------
def upsert_user(conn: Connection, viewer: Viewer) -> int:
row = conn.execute(
"""INSERT INTO app_user (external_subject, email, display_name, last_seen_at) VALUES (%s, %s, %s, now())
ON CONFLICT (external_subject) DO UPDATE SET email = COALESCE(EXCLUDED.email, app_user.email),
display_name = COALESCE(EXCLUDED.display_name, app_user.display_name), last_seen_at = now()
RETURNING id""",
(viewer.subject, viewer.email, viewer.name),
).fetchone()
return row["id"]
# -- reading ----------------------------------------------------------------------------------------------------------
LIST_COLUMNS = """
r.slug, r.title, r.lede, r.lang, r.status, r.created_at, r.updated_at, r.published_at,
COALESCE(u.display_name, 'Unbekannt') AS author_name,
(SELECT count(*) FROM report_reference x JOIN claim c ON c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END)
WHERE x.report_id = r.id AND x.ref_type = 'claim' AND c.review_status = 'published') AS claim_count,
(SELECT count(*) FROM report_reference x JOIN claim c ON c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END)
WHERE x.report_id = r.id AND x.ref_type = 'claim' AND c.review_status = 'published' AND EXISTS (
SELECT 1 FROM claim_evidence e JOIN document d ON d.id = e.document_id JOIN source s ON s.id = d.source_id
WHERE e.claim_id = c.id AND s.kind = 'official')) AS official_claim_count,
(SELECT count(*) FROM report_revision v WHERE v.report_id = r.id) AS revision_count
"""
def list_reports(conn: Connection, *, viewer: Viewer | None = None, mine: bool = False, claim_id: int | None = None,
person: str | None = None, organization: str | None = None, report: str | None = None,
q: str | None = None, limit: int = 30, offset: int = 0) -> list[dict]:
"""Published reports, newest first. mine=True: all of the viewer's own reports (drafts too).
claim_id / person / organization / report: only reports referencing that claim, person, organisation or report."""
params = {"subject": viewer.subject if viewer else None, "mine": mine, "q": q, "limit": limit, "offset": offset,
"claim": str(claim_id) if claim_id is not None else None, "person": person, "org": organization,
"report": report}
return conn.execute(
f"""
SELECT {LIST_COLUMNS}
FROM report r JOIN app_user u ON u.id = r.author_id
WHERE (CASE WHEN %(mine)s THEN u.external_subject = %(subject)s ELSE r.status = 'published' END)
AND (%(claim)s::text IS NULL OR EXISTS (SELECT 1 FROM report_reference x WHERE x.report_id = r.id
AND x.ref_type = 'claim' AND x.ref_key = %(claim)s))
AND (%(person)s::text IS NULL OR EXISTS (
SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND (
(x.ref_type = 'person' AND x.ref_key = %(person)s) OR
(x.ref_type = 'claim' AND EXISTS (SELECT 1 FROM claim c JOIN person p ON p.id IN (c.person_id, c.counterpart_person_id)
WHERE c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) AND p.slug = %(person)s)))))
AND (%(org)s::text IS NULL OR EXISTS (
SELECT 1 FROM report_reference x WHERE x.report_id = r.id AND (
(x.ref_type = 'organization' AND x.ref_key = %(org)s) OR
(x.ref_type = 'claim' AND EXISTS (SELECT 1 FROM claim c JOIN organization o ON o.id IN (c.organization_id, c.counterpart_org_id)
WHERE c.id = (CASE WHEN x.ref_type = 'claim' THEN x.ref_key::bigint END) AND o.slug = %(org)s)))))
AND (%(report)s::text IS NULL OR EXISTS (SELECT 1 FROM report_reference x WHERE x.report_id = r.id
AND x.ref_type = 'report' AND x.ref_key = %(report)s))
AND (%(q)s::text IS NULL OR r.title ILIKE '%%' || %(q)s || '%%' OR r.lede ILIKE '%%' || %(q)s || '%%')
ORDER BY COALESCE(r.published_at, r.updated_at) DESC, r.id DESC
LIMIT %(limit)s OFFSET %(offset)s
""",
params,
).fetchall()
def get_report(conn: Connection, slug: str, viewer: Viewer | None = None) -> dict | None:
"""A report with everything needed to render it. Drafts only for their author (or an editor)."""
row = conn.execute(
f"""SELECT r.id, r.body, u.external_subject AS author_subject, {LIST_COLUMNS}
FROM report r JOIN app_user u ON u.id = r.author_id WHERE r.slug = %s""",
(slug,),
).fetchone()
if not row:
return None
own = bool(viewer and (viewer.subject == row["author_subject"] or viewer.editor))
if row["status"] == "draft" and not own:
return None
report = dict(row)
report.pop("id")
author_subject = report.pop("author_subject")
report["can_edit"] = own
report["is_author"] = bool(viewer and viewer.subject == author_subject)
report["references"] = resolve_references(conn, report["body"])
report["backlinks"] = list_reports(conn, report=slug, limit=50)
if report["status"] == "withdrawn" and not own:
report["body"], report["references"] = "", resolve_references(conn, "")
return report
def resolve_references(conn: Connection, body: str) -> dict[str, Any]:
"""Look up everything the body references. Claims are shown like permalinks (no visitor filter); a claim merged
into another one resolves to the survivor; hidden or deleted claims are listed in missing_claims."""
refs = parse_references(body)
claim_ids = [int(k) for t, k, _ in refs if t == "claim"]
survivors = _follow_merges(conn, claim_ids)
found = {c["id"]: c for c in list_claims(conn, sources=SourceFilter(), claim_ids=sorted(set(survivors.values())),
limit=max(1, len(survivors)))} if survivors else {}
claims, missing, aliases = [], [], {}
for cid in claim_ids:
survivor = survivors.get(cid)
if survivor in found:
if survivor != cid:
aliases[str(cid)] = survivor
if found[survivor] not in claims:
claims.append(found[survivor])
else:
missing.append(cid)
report_slugs = [k for t, k, _ in refs if t == "report"]
reports = conn.execute(
f"""SELECT {LIST_COLUMNS} FROM report r JOIN app_user u ON u.id = r.author_id
WHERE r.slug = ANY(%s) AND r.status <> 'draft'""",
(report_slugs,),
).fetchall() if report_slugs else []
persons = conn.execute("SELECT slug, full_name AS name FROM person WHERE slug = ANY(%s)",
([k for t, k, _ in refs if t == "person"],)).fetchall()
orgs = conn.execute("SELECT slug, COALESCE(short_name, name) AS name, kind FROM organization WHERE slug = ANY(%s)",
([k for t, k, _ in refs if t == "organization"],)).fetchall()
return {"claims": claims, "claim_aliases": aliases, "missing_claims": missing, "reports": reports,
"persons": persons, "organizations": orgs}
def _follow_merges(conn: Connection, claim_ids: list[int]) -> dict[int, int]:
"""claim id -> id of the claim it was merged into (itself if not merged). Unknown ids are left out."""
if not claim_ids:
return {}
rows = {r["id"]: r["merged_into"] for r in conn.execute(
"""WITH RECURSIVE chain AS (
SELECT id, merged_into FROM claim WHERE id = ANY(%s)
UNION SELECT c.id, c.merged_into FROM claim c JOIN chain ON c.id = chain.merged_into)
SELECT id, merged_into FROM chain""", (claim_ids,)).fetchall()}
result = {}
for cid in claim_ids:
current, hops = cid, 0
while current in rows and rows[current] is not None and hops < 10:
current, hops = rows[current], hops + 1
if current in rows:
result[cid] = current
return result
# -- writing ----------------------------------------------------------------------------------------------------------
class ReportError(ValueError):
pass
def _check(title: str, body: str) -> None:
if not 3 <= len(title.strip()) <= 200:
raise ReportError("title must be 3-200 characters")
if len(body) > MAX_BODY:
raise ReportError(f"body is longer than {MAX_BODY} characters")
RESERVED_SLUGS = {"verfassen", "neu"} # web routes under /berichte/
def _unique_slug(conn: Connection, title: str) -> str:
base = make_slug(title)[:80].strip("-") or "bericht"
if base in RESERVED_SLUGS:
base = f"{base}-bericht"
slug, n = base, 1
while conn.execute("SELECT 1 FROM report WHERE slug = %s", (slug,)).fetchone():
n += 1
slug = f"{base}-{n}"
return slug
def _save_references(conn: Connection, report_id: int, body: str) -> None:
conn.execute("DELETE FROM report_reference WHERE report_id = %s", (report_id,))
for ref_type, key, embedded in parse_references(body):
conn.execute("INSERT INTO report_reference (report_id, ref_type, ref_key, embedded) VALUES (%s, %s, %s, %s)",
(report_id, ref_type, key, embedded))
def create_report(conn: Connection, viewer: Viewer, *, title: str, lede: str | None, body: str, lang: str,
status: str) -> str:
_check(title, body)
user_id = upsert_user(conn, viewer)
slug = _unique_slug(conn, title)
report_id = conn.execute(
"""INSERT INTO report (slug, title, lede, body, lang, status, author_id, published_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, CASE WHEN %s = 'published' THEN now() END) RETURNING id""",
(slug, title.strip(), (lede or "").strip() or None, body, lang, status, user_id, status),
).fetchone()["id"]
_save_references(conn, report_id, body)
conn.execute("""INSERT INTO report_revision (report_id, title, lede, body, status, edited_by)
SELECT id, title, lede, body, status, %s FROM report WHERE id = %s""", (user_id, report_id))
conn.commit()
return slug
def update_report(conn: Connection, viewer: Viewer, slug: str, *, title: str, lede: str | None, body: str, lang: str,
status: str) -> bool:
"""False if the report doesn't exist or the viewer may not edit it."""
_check(title, body)
row = conn.execute("""SELECT r.id, u.external_subject FROM report r JOIN app_user u ON u.id = r.author_id
WHERE r.slug = %s FOR UPDATE OF r""", (slug,)).fetchone()
if not row or (row["external_subject"] != viewer.subject and not viewer.editor):
return False
user_id = upsert_user(conn, viewer)
conn.execute(
"""UPDATE report SET title = %s, lede = %s, body = %s, lang = %s, status = %s, updated_at = now(),
published_at = COALESCE(published_at, CASE WHEN %s = 'published' THEN now() END)
WHERE id = %s""",
(title.strip(), (lede or "").strip() or None, body, lang, status, status, row["id"]),
)
_save_references(conn, row["id"], body)
conn.execute("""INSERT INTO report_revision (report_id, title, lede, body, status, edited_by)
SELECT id, title, lede, body, status, %s FROM report WHERE id = %s""", (user_id, row["id"]))
conn.commit()
return True
+10 -3
View File
@@ -37,7 +37,7 @@ from politrack.core import (
)
from politrack.core.records import Claim, Evidence, OrgRecord, OrgRef, PersonRef
from politrack.core.spec import DERIVED
from politrack.text import firmenbuch_number, format_eur_de, normalize_org_name
from politrack.text import firmenbuch_number, format_eur_de, legal_form_class, normalize_org_name
URL = "https://justizonline.gv.at/jop/api/at.gv.justiz.fbw/ws"
NS = "ns://firmenbuch.justiz.gv.at/Abfrage/"
@@ -203,10 +203,17 @@ def search_term(name: str) -> str:
return term if len(term) >= 3 else ""
def is_partnership(name: str) -> bool:
"""KG / OG / GmbH & Co KG: a different legal entity from the GmbH of the same name (often its general partner)."""
return legal_form_class(name) in {"kg", "og"}
def unique_match(name: str, hits: list[dict[str, Any]]) -> dict[str, Any] | None:
"""The one current register entry with the same name (legal form, case and punctuation ignored)."""
"""The one current register entry with the same name (legal form, case and punctuation ignored, but a
partnership never matches a corporation: 'Huber GmbH & Co KG' is not 'Huber GmbH')."""
target = normalize_org_name(name)
same = [h for h in hits if h["fn"] and normalize_org_name(h["name"]) == target]
same = [h for h in hits if h["fn"] and normalize_org_name(h["name"]) == target
and is_partnership(h["name"]) == is_partnership(name)]
current = [h for h in same if not h["status"]] or same
return current[0] if len(current) == 1 else None
@@ -170,8 +170,9 @@ STGB_OFFENSES = {
def parse_immunity_report(text: str) -> dict[str, Any]:
authority = re.search(r"Ersuchen (?:der|des) (.+?),\s*(?:do\.|GZ|Zl)", text)
case_ref = re.search(r"\bGZ\.?\s*([^,]+?),", text)
# "Ersuchen der Staatsanwaltschaft Wien, do. GZ. 501 St 68/24k, um ..." or "... Wien (GZ 25 St 407/08i) um ..."
authority = re.search(r"Ersuchen (?:der|des) ([^,()]{3,90}?)\s*(?:,|\(|\bum\b)", text)
case_ref = re.search(r"\b(?:GZ|Zl)\.?:?\s*([^,()]{3,60}?)\s*[,)]", text)
# "wegen des Verdachtes einer strafbaren Handlung nach § 283 Abs. 1 Z 1 und Z 2, Abs. 2 StGB"
offense = re.search(r"wegen[^§]{0,90}?(§§? ?\d+.{0,120}?\b(?:StGB|VerbotsG|FinStrG|[A-Z][A-Za-z]*G)\b)", text)
offense_text = offense.group(1).strip() if offense else None
@@ -183,12 +184,16 @@ def parse_immunity_report(text: str) -> dict[str, Any]:
recommendation = None
if decision:
recommendation = "refuse" if (decision.group(1) or decision.group(2)) else "consent"
elif re.search(r"festgestellt, dass kein Zusammenhang", text):
# Art. 57 Abs. 3 B-VG: without a connection to the political activity, immunity does not apply and the
# authority may prosecute without the Nationalrat's consent.
recommendation = "no_connection"
connection = None
if re.search(r"\bkein Zusammenhang\b", text):
connection = False
elif re.search(r"\bein Zusammenhang\b", text):
connection = True
quote = re.search(r"Als Ergebnis seiner Beratungen.*?(?:zugestimmt|nicht zugestimmt)\s*\.", text)
quote = re.search(r"Als Ergebnis seiner Beratungen.*?(?:zugestimmt|kein Zusammenhang\b.{0,300}?\bbesteht)\s*\.", text)
return {
"authority": authority.group(1).strip() if authority else None,
"case_ref": case_ref.group(1).strip() if case_ref else None,
+46 -7
View File
@@ -50,13 +50,35 @@ WITNESS_TITLES = re.compile(r"^(?:(?:Oberstaatsanwalt|Staatsanwalt|Sektionschef(
r"Vizekanzler|Präsident(?:in)?)\s+)+")
ANSWERED_BY = re.compile(r"beantwortet durch (\d+/AB)")
def row_pads(row: dict) -> list[str]:
pads = row.get("Personen") or "[]"
pads = json.loads(pads) if isinstance(pads, str) else pads
return [str(p).strip() for p in pads if str(p).strip()]
def question_answerers(rows: list[dict]) -> dict[str, set[str]]:
"""Answer number ("1479/AB") -> persons who answered it; "*" -> everyone who answered any question in the list
(members of the government, used for questions not answered yet)."""
out: dict[str, set[str]] = {"*": set()}
for row in rows:
if row.get("ITYP") == "AB" and row.get("Nummer"):
pads = set(row_pads(row))
out.setdefault(row["Nummer"], set()).update(pads)
out["*"].update(pads)
return out
@register
class ParlamentItems(Adapter):
spec = SPEC
name = "parlament.items"
description = "Votes (faction + roll call), immunity requests, written questions, U-committee hearings"
schedule = "45 3 * * *"
parser_version = 2
parser_version = 4 # 3: immunity reports finding no political connection, cleaner authority and case number
# 4: a written question's addressed minister is no longer recorded as asking it
def start(self, ctx: RunContext) -> Iterator[Request]:
for gp in ctx.params.get("periods") or get_settings().parlament_periods:
@@ -76,7 +98,9 @@ class ParlamentItems(Adapter):
# -- list ---------------------------------------------------------------------------
def parse_items(self, ctx: RunContext, response: Response) -> Iterator[Any]:
for row in list_rows(response.json()):
rows = list_rows(response.json())
answerers = question_answerers(rows)
for row in rows:
path, subject, kind = row.get("HIS_URL"), row.get("Betreff") or "", row.get("ITYP")
if not path:
continue
@@ -88,15 +112,19 @@ class ParlamentItems(Adapter):
yield detail_request(path, kind="immunity",
meta={"title": subject, "date": row.get("Datum"), "status": row.get("Status")})
if kind in ("J", "AB"):
yield from self.question_claims(row, path)
yield from self.question_claims(row, path, answerers)
if kind == "KOMM" and HEARING.search(subject):
yield detail_request(path, kind="hearing", meta={"title": subject, "date": row.get("Datum")})
def question_claims(self, row: dict, path: str) -> Iterator[Claim]:
pads = row.get("Personen") or "[]"
pads = json.loads(pads) if isinstance(pads, str) else pads
def question_claims(self, row: dict, path: str, answerers: dict[str, set[str]] | None = None) -> Iterator[Claim]:
pads = row_pads(row)
subject = row.get("Betreff") or ""
is_question = row.get("ITYP") == "J"
if is_question and answerers:
# "Personen" of a question also lists the minister it is addressed to: not an asker.
answer = ANSWERED_BY.search(subject)
addressed = answerers.get(answer.group(1), set()) if answer else answerers.get("*", set())
pads = [p for p in pads if str(p).strip() not in addressed]
asked = parse_date(row.get("Datum"))
topics = tuple(json.loads(row.get("THEMEN") or "[]")) if isinstance(row.get("THEMEN"), str) else ()
for pad in pads:
@@ -232,12 +260,23 @@ class ParlamentItems(Adapter):
name = re.sub(r"^.*?(Abgeordneten zum Nationalrat|Mitglied(es)? des Bundesrates)\s*(Klubobmann|Klubobfrau)?",
"", title).strip()
decided = str(meta.get("status")) == "5"
recommendation = details["recommendation"] or ""
stage = {"consent": "immunity_waived" if decided else "immunity_waiver_requested",
"no_connection": "immunity_waived" if decided else "immunity_waiver_requested",
"refuse": "immunity_refused" if decided else "immunity_waiver_requested"}.get(
details["recommendation"] or "", "immunity_waiver_requested")
recommendation, "immunity_waiver_requested")
stage_de = {"immunity_waived": "Nationalrat stimmte der behördlichen Verfolgung zu (Immunität aufgehoben)",
"immunity_refused": "Nationalrat verweigerte die Zustimmung zur behördlichen Verfolgung",
"immunity_waiver_requested": "Ersuchen um Aufhebung der Immunität"}[stage]
if recommendation == "no_connection":
# Art. 57 Abs. 3 B-VG: no connection to the political activity -> no immunity, prosecution may proceed.
stage_de = ("Nationalrat stellte fest: kein Zusammenhang mit der politischen Tätigkeit, behördliche "
"Verfolgung zulässig" if decided else
"Ersuchen um Zustimmung zur behördlichen Verfolgung (Ausschuss empfiehlt: kein Zusammenhang "
"mit der politischen Tätigkeit, Verfolgung zulässig)")
elif stage == "immunity_waiver_requested" and recommendation:
stage_de += {"consent": " (Ausschuss empfiehlt Zustimmung)",
"refuse": " (Ausschuss empfiehlt, nicht zuzustimmen)"}[recommendation]
offense = details["offense"]
requested = parse_date(meta.get("date"))
yield Claim(
+25
View File
@@ -33,6 +33,9 @@ SPEC = SourceSpec(
"no use for defamatory/discriminatory purposes.",
)
KIND = {2: "government_ad", 4: "subsidy"}
# Notice type 31 (until 2023): the ORF reports what it received under § 31 ORF-G (licence fee "Programmentgelt",
# compensation under Abs. 11). The "medium" column then holds the legal basis, not a recipient.
ORF_FEE_REPORT = 31
def half_years(since_year: int) -> list[str]:
@@ -52,6 +55,7 @@ class MediaTransparency(Adapter):
description = "Government advertising and media subsidies per public body and media owner"
schedule = "0 4 * * 2"
queue = "bulk"
parser_version = 2 # 2: § 31 ORF-G fee reports are the ORF's income, not payments to a medium
def start(self, ctx: RunContext) -> Iterator[Request]:
for period in half_years(int(ctx.params.get("since_year", 2024))):
@@ -61,6 +65,23 @@ class MediaTransparency(Adapter):
yield Request(url=f"{API}/mt-bekanntgabe.json", params={"quartal": period, "size": PAGE_SIZE, "page": 0},
kind="quartal", meta={"period": period})
@staticmethod
def orf_fee(row: dict[str, Any], amount: float, label: str, period: str) -> Claim:
orf_name = (row.get("rechtstraeger") or "Österreichischer Rundfunk").strip().strip('"')
basis = (row.get("mediumMedieninhaber") or row.get("medium") or "§ 31 ORF-G").strip()
orf = OrgRef(name=orf_name, kind="media")
return Claim(
claim_type="money_flow", org=orf,
summary_de=f"{orf_name}: Einnahmen aus {basis}, {format_eur_de(amount)} € ({label})",
summary_en=f"{orf_name}: income under {basis} (licence fee), EUR {amount:,.2f} ({label})",
data={"legal_basis": basis, "period": label},
evidence=[Evidence(url=f"{API}/mt-bekanntgabe.json?quartal={period}", doc_type="dataset_row",
title=f"Medientransparenz {label}: {orf_name}", quote=f"{orf_name}: {basis}: {amount} €")],
topics=("Information und Medien",),
facet=Money(kind="other", amount=amount, payee=orf, payee_name=orf_name, payer_name=basis, period=label,
reference=basis, category="orf_fee"),
)
def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]:
rows = response.json().get("data") or []
params = response.request.params or {}
@@ -74,6 +95,10 @@ class MediaTransparency(Adapter):
amount = row.get("euro")
if row.get("leermeldung") or amount is None or float(amount) < min_euro:
continue
if row.get("bekanntgabe") == ORF_FEE_REPORT:
if float(amount) > 0:
yield self.orf_fee(row, float(amount), label, period)
continue
kind = KIND.get(row.get("bekanntgabe"), "other")
payer_name = (row.get("rechtstraeger") or "").strip().strip('"')
owner = (row.get("medieninhaber") or row.get("mediumMedieninhaber") or "").strip()
+173
View File
@@ -0,0 +1,173 @@
"""Portraits and logos from Wikimedia Commons, found through Wikidata.
Persons: Wikidata P18 (image) for everyone with a Wikidata id and no official photo (Parliament and European
Parliament photos always take precedence; the loader never replaces them).
Organizations: Wikidata P154 (logo image), matched through the Wikidata id, the Firmenbuch number (P5285) or the
ZVR number (P6279). Matching is by identifier only, never by name.
Every image comes with its author and licence from the Commons file page (extmetadata); the site shows that credit
next to the image. Commons only hosts freely licensed files; logos can still be protected trademarks, which is fine
for identifying the organization.
Flow: SPARQL (Wikidata ids -> file names) -> Commons API imageinfo in batches of 50 (thumbnail URL + licence).
"""
from __future__ import annotations
import json
import re
from collections.abc import Iterator
from typing import Any
from urllib.parse import unquote
from psycopg import Connection
from politrack.core import Adapter, Request, Response, RunContext, SourceSpec, register
from politrack.core.records import Image, OrgRef, PersonRef
from politrack.sources.wikidata import SPARQL, sparql
from politrack.text import firmenbuch_number, html_to_text
COMMONS_API = "https://commons.wikimedia.org/w/api.php"
THUMB_WIDTH = 330 # one of Wikimedia's standard thumbnail steps (cached at the edge)
BATCH = 300
FILE_BATCH = 50
SPEC = SourceSpec(
slug="wikimedia-commons",
name="Wikimedia Commons (Porträts und Logos)",
kind="aggregator",
homepage="https://commons.wikimedia.org",
license="Freie Lizenzen je Datei (CC BY, CC BY-SA, gemeinfrei); Urheber und Lizenz werden angezeigt",
access="api",
trust=60,
min_interval=1.0,
robots_exempt=(SPARQL, COMMONS_API),
tos_notes="Wikidata SPARQL and the Commons MediaWiki API with a descriptive User-Agent, sequential requests "
"(API etiquette; robots.txt disallows /w/ for crawlers, not API clients). Images are shown through the "
"site's image proxy with author and licence of each file.",
)
PERSON_QUERY = """
SELECT ?item ?img WHERE { VALUES ?item { %(items)s } ?item wdt:P18 ?img . }
"""
ORG_QUERY = """
SELECT ?item ?img WHERE { VALUES ?item { %(items)s } ?item wdt:P154 ?img . }
"""
# Logos of all items with an Austrian register number; the loader keeps those whose number we know.
REGISTER_QUERY = """
SELECT ?item ?id ?img WHERE { ?item wdt:%(prop)s ?id ; wdt:P154 ?img . }
"""
REGISTERS = {"firmenbuch": "P5285", "zvr": "P6279"}
def register_id(scheme: str, value: str) -> str | None:
"""Wikidata's register number in our identifier format: Firmenbuch '520909 v' / 'FN 58358x' -> '520909v',
ZVR digits only."""
if scheme == "firmenbuch":
return firmenbuch_number(value)
value = re.sub(r"\D", "", value)
return value.lstrip("0") or None
def file_title(commons_url: str) -> str:
"""http://commons.wikimedia.org/wiki/Special:FilePath/Foo%20bar.jpg -> 'File:Foo bar.jpg'"""
name = unquote(commons_url.rsplit("/", 1)[-1]).replace("_", " ")
return f"File:{name}"
def item_qid(binding: dict) -> str:
return binding["item"]["value"].rsplit("/", 1)[-1]
def wikidata_ids(conn: Connection, entity_type: str, where: str) -> list[str]:
rows = conn.execute(
f"""SELECT DISTINCT i.value FROM identifier i WHERE i.entity_type = %s AND i.scheme = 'wikidata'
AND i.value ~ '^Q[0-9]+$' AND {where} ORDER BY i.value""", (entity_type,)).fetchall()
return [r["value"] for r in rows]
def plain(meta: dict, key: str, limit: int = 200) -> str | None:
value = html_to_text((meta.get(key) or {}).get("value") or "").strip()
return value[:limit] if value else None
@register
class CommonsImages(Adapter):
spec = SPEC
name = "wikimedia.images"
description = "Portraits (Wikidata P18) and logos (P154) from Wikimedia Commons, with author and licence"
schedule = "30 5 * * 0"
queue = "scrape"
def start(self, ctx: RunContext) -> Iterator[Request]:
if ctx.conn is None:
return
persons = wikidata_ids(ctx.conn, "person", """EXISTS (SELECT 1 FROM person p WHERE p.id = i.entity_id
AND (p.photo_url IS NULL OR p.photo_url LIKE 'https://upload.wikimedia.org/%%'))""")
orgs = wikidata_ids(ctx.conn, "organization", "TRUE")
ctx.stats["persons_checked"], ctx.stats["orgs_checked"] = len(persons), len(orgs)
for i in range(0, len(persons), BATCH):
items = " ".join(f"wd:{q}" for q in persons[i:i + BATCH])
yield sparql(PERSON_QUERY % {"items": items}, kind="person_images")
for i in range(0, len(orgs), BATCH):
items = " ".join(f"wd:{q}" for q in orgs[i:i + BATCH])
yield sparql(ORG_QUERY % {"items": items}, kind="org_logos")
for scheme, prop in REGISTERS.items():
yield sparql(REGISTER_QUERY % {"prop": prop}, kind="register_logos", meta={"scheme": scheme})
def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]:
kind = response.request.kind
if kind == "files":
yield from self.parse_files(ctx, response)
return
bindings = json.loads(response.text, strict=False)["results"]["bindings"]
targets: dict[str, list[dict]] = {}
seen: set[str] = set()
for b in sorted(bindings, key=lambda b: (item_qid(b), b["img"]["value"])):
qid = item_qid(b)
if qid in seen: # several images: the first one (stable order)
continue
seen.add(qid)
if kind == "person_images":
target = {"role": "photo", "ids": {"wikidata": qid}}
elif kind == "org_logos":
target = {"role": "logo", "ids": {"wikidata": qid}}
else:
scheme = response.meta["scheme"]
value = register_id(scheme, b["id"]["value"])
if not value:
continue
target = {"role": "logo", "ids": {scheme: value, "wikidata": qid}}
targets.setdefault(file_title(b["img"]["value"]), []).append(target)
titles = sorted(targets)
for i in range(0, len(titles), FILE_BATCH):
chunk = titles[i:i + FILE_BATCH]
yield Request(
url=COMMONS_API, kind="files", conditional=False,
params={"action": "query", "prop": "imageinfo", "iiprop": "url|extmetadata",
"iiurlwidth": THUMB_WIDTH, "iiextmetadatafilter": "Artist|Credit|LicenseShortName|LicenseUrl",
"titles": "|".join(chunk), "format": "json", "formatversion": 2},
meta={"targets": {t: targets[t] for t in chunk}},
)
def parse_files(self, ctx: RunContext, response: Response) -> Iterator[Image]:
query = response.json().get("query") or {}
renamed = {n["to"]: n["from"] for n in query.get("normalized") or []}
targets = response.meta.get("targets") or {}
for page in query.get("pages") or []:
info = (page.get("imageinfo") or [None])[0]
wanted = targets.get(renamed.get(page.get("title"), page.get("title")))
if not info or not wanted:
ctx.stats["files_missing"] += 1
continue
url = info.get("thumburl") or info.get("url")
if not url or not url.startswith("https://upload.wikimedia.org/"):
continue
meta = info.get("extmetadata") or {}
credit = plain(meta, "Artist") or plain(meta, "Credit")
for target in wanted:
person = PersonRef(ids=target["ids"]) if target["role"] == "photo" else None
org = OrgRef(ids=target["ids"], create=False) if target["role"] == "logo" else None
yield Image(url=url, role=target["role"], page_url=info.get("descriptionurl"), credit=credit,
license=plain(meta, "LicenseShortName", 80), license_url=plain(meta, "LicenseUrl", 300),
person=person, org=org)
+29 -1
View File
@@ -49,17 +49,45 @@ LEGAL_FORMS = re.compile(
)
# Partnerships (KG, OG, GmbH & Co KG) are separate legal entities from the corporation of the same name, which is
# often their general partner. KEG and OHG/OEG are the pre-2007 names of KG and OG (same entity, renamed by the UGB).
PARTNERSHIP_FORMS = re.compile(
r"\b(?:(?P<kg>kommanditgesellschaft|kommandit-erwerbsgesellschaft|keg|kg|cokg)"
r"|(?P<og>offene\s+(?:handels|erwerbs)?gesellschaft|ohg|oeg|og))\b"
)
CORPORATE_FORMS = re.compile(
r"\b(gmbh|gesmbh|mbh|g\.m\.b\.h|m\.?\s?b\.?\s?h|ag|aktiengesellschaft|se|e\.?\s?gen|egen|eg|ltd|inc|llc|plc)\b"
)
def legal_form_class(name: str) -> str | None:
"""'kg' or 'og' for a partnership (also 'GmbH & Co KG'), 'corp' for a corporation (GmbH, AG, SE, eGen ...),
None when the name carries no legal form."""
text = normalize(name)
m = PARTNERSHIP_FORMS.search(text)
if m:
return "kg" if m.group("kg") else "og"
return "corp" if CORPORATE_FORMS.search(text) else None
def normalize_org_name(name: str) -> str:
"""'HYPO TIROL BANK AG' == 'Hypo Tirol Bank Aktiengesellschaft' -> 'hypo tirol bank'.
Lowercase, strip accents, quotes, punctuation and legal-form suffixes, so the same company is
recognised across sources (side-job lists, procurement notices, donation lists, ad reports).
A partnership keeps a marker: 'Huber GmbH & Co KG' -> 'huber kg', 'Maier OG' -> 'maier og', so it never
matches 'Huber GmbH' -> 'huber'.
"""
text = normalize(name)
partnership = PARTNERSHIP_FORMS.search(text)
text = re.sub(r"[\"'„“”»«]", "", text)
text = LEGAL_FORMS.sub(" ", text)
text = PARTNERSHIP_FORMS.sub(" ", text)
text = re.sub(r"[^\w\s-]", " ", text)
return re.sub(r"\s+", " ", text).strip(" -")
text = re.sub(r"\s+", " ", text).strip(" -&")
if partnership and text:
text += " kg" if partnership.group("kg") else " og"
return text
def firmenbuch_number(value: str | None) -> str | None:
+24 -1
View File
@@ -7,7 +7,7 @@ from politrack.core.adapter import Request, redact_url
from politrack.core.records import Claim, Evidence, Money, OrgRef, to_jsonable
from politrack.openapi_ts import to_typescript, ts_type
from politrack.sources.bundesregierung import ITEM, german_date, offices, period_start
from politrack.text import format_eur_de, normalize_org_name
from politrack.text import format_eur_de, legal_form_class, normalize_org_name
def test_request_fingerprint_ignores_meta_and_headers():
@@ -50,6 +50,18 @@ def test_normalize_org_name():
assert normalize_org_name("Muster Bau Gesellschaft m.b.H.") == "muster bau"
def test_partnership_keeps_its_marker():
# A GmbH & Co KG is a different legal entity from the GmbH of the same name.
kg = {normalize_org_name(n) for n in ("Huber GmbH & Co KG", "Huber Ges.m.b.H. & Co. KG.", "Huber GmbH&CoKG",
"Huber KG", "HUBER GMBH & CO KEG")}
assert kg == {"huber kg"}
assert normalize_org_name("Huber GmbH") == "huber"
assert normalize_org_name("Porsche Austria GmbH & Co OG") == normalize_org_name("Porsche Austria GmbH & Co. OHG")
assert normalize_org_name("Porsche Austria GmbH & Co OG") == "porsche austria og"
assert [legal_form_class(n) for n in ("Huber GmbH & Co KG", "Maier OG", "Huber GmbH", "Hypo AG", "Rotfuchs")] \
== ["kg", "og", "corp", "corp", None]
def test_format_eur_de():
assert format_eur_de(1234567.8) == "1.234.567,80"
assert format_eur_de("n/a") == "n/a"
@@ -127,3 +139,14 @@ def test_office_portfolios_for_colloquial_labels():
economy = office_key("Bundesminister für Wirtschaft, Energie und Tourismus")
climate = office_key("Federal Minister for Climate Action, Environment, Energy, Mobility, Innovation and Technology")
assert lead_portfolio(economy) == "wirtschaft" and lead_portfolio(economy) not in portfolios(climate)
def test_ambiguous_organisation_names_resolve_to_one_existing_record():
from politrack.core.resolve import pick_org
twins = [{"id": 1292, "name": "Tiroler Tageszeitung GmbH", "kind": "company"},
{"id": 10562, "name": "Tiroler Tageszeitung", "kind": "media"},
{"id": 37042, "name": "Tiroler Tageszeitung", "kind": "media"}]
assert pick_org(twins, "Tiroler Tageszeitung", "media") == 10562 # exact name, then the oldest
assert pick_org(twins, "Tiroler Tageszeitung GmbH", None) == 1292
assert pick_org([{"id": 5, "name": "A GmbH", "kind": "company"}, {"id": 3, "name": "A AG", "kind": "public_body"}],
"A", "public_body") == 3
+35
View File
@@ -135,3 +135,38 @@ def test_event_records_use_the_date_from_the_sentence():
claim = next(r for r in records if isinstance(r, Claim))
assert event.starts_at == claim.occurred_at == date(2026, 11, 11)
assert claim.data["date_precision"] == "day"
IMMUNITY_NO_CONNECTION = (
"Bericht des Immunitätsausschusses über das Ersuchen der Staatsanwaltschaft Wien, do. GZ. 501 St 68/24k, um "
"Zustimmung zur behördlichen Verfolgung des Abgeordneten zum Nationalrat Mag. Dr. Martin Graf gemäß Art. 57 Abs. 3 "
"B-VG Die Staatsanwaltschaft Wien ersucht ... wegen des Verdachtes einer strafbaren Handlung nach § 3g Abs. 1 und "
"Abs. 2 VerbotsG. ... Als Ergebnis seiner Beratungen stellt der Immunitätsausschuss somit den Antrag , der Nationalrat "
"wolle beschließen: In Behandlung des Ersuchens der Staatsanwaltschaft Wien (GZ 501 St 68/24k) um Zustimmung ... wird "
"im Sinne des Art. 57 Abs. 3 B‑VG festgestellt, dass kein Zusammenhang zwischen der inkriminierten Handlung und der "
"politischen Tätigkeit des Abgeordneten zum Nationalrat Mag. Dr. Martin Graf besteht. Wien, 2024 12 11"
)
def test_immunity_without_political_connection_allows_prosecution():
r = parse_immunity_report(IMMUNITY_NO_CONNECTION)
assert r["recommendation"] == "no_connection" and r["political_connection"] is False
assert r["offense"] == "§ 3g Abs. 1 und Abs. 2 VerbotsG"
assert r["quote"].endswith("Martin Graf besteht.")
def test_immunity_authority_and_case_number_in_brackets():
# older reports: "Ersuchen der Staatsanwaltschaft Wien (GZ 25 St 407/08i) um Zustimmung ..."
r = parse_immunity_report("Bericht über das Ersuchen der Staatsanwaltschaft Wien (GZ 25 St 407/08i) um Zustimmung zur "
"behördlichen Verfolgung des Abgeordneten Mag. Dr. Martin Graf Die Staatsanwaltschaft Wien "
"ersucht mit Schreiben vom 29. Jänner 2009, GZ 25 St 407/08i, um Zustimmung")
assert (r["authority"], r["case_ref"]) == ("Staatsanwaltschaft Wien", "25 St 407/08i")
r = parse_immunity_report("Ersuchen des Magistrats der Stadt Wien (GZ. MBA/210000025592/2021) um Zustimmung")
assert (r["authority"], r["case_ref"]) == ("Magistrats der Stadt Wien", "MBA/210000025592/2021")
def test_dropped_investigation_is_not_an_investigation():
assert classify("Verfahrenskomplex CASAG / Anzeige wegen Falschaussage: Einstellung von Ermittlungen gegen Thomas "
"Schmid") == "proceedings_dropped"
assert classify("Einstellungen der Ermittlungen gegen zwei Beschuldigte") == "proceedings_dropped"
assert classify("Causa Inserate: Weitere Ermittlungen") == "investigation"
+8
View File
@@ -118,3 +118,11 @@ def test_faults_and_requests():
assert "X-API-KEY" not in repr(a.describe()) # the token is never archived
assert b"&amp;" in F.envelope("SucheFirmaRequest", "SUCHEFIRMAREQUEST", {"FIRMENWORTLAUT": "A & B"})
assert Request(url="x").fingerprint == Request(url="x", data=None).fingerprint
def test_partnership_never_matches_the_corporation_of_the_same_name():
hits = [{"fn": "226399s", "name": "Huber GmbH", "seat": "Ebenfurth", "status": None, "legal_form": None}]
assert F.unique_match("Huber GmbH & Co KG", hits) is None
assert F.unique_match("Huber GmbH", hits)["fn"] == "226399s"
kg = [{"fn": "1k", "name": "Huber GmbH & Co KG", "seat": "Wels", "status": None, "legal_form": None}]
assert F.unique_match("Huber GmbH & Co. KG", kg)["fn"] == "1k"
+42
View File
@@ -235,3 +235,45 @@ def test_speech_segments_end_at_next_ru_anchor_or_chair():
assert seg["RU_1"].startswith("Abgeordnete Anna Eins (Grüne): Erste Rede.") and "Vorsitz" not in seg["RU_1"]
assert seg["RU_2"].startswith("Abgeordneter Bernd Zwei (SPÖ): Zweite Rede.")
assert "RU_2" in seg and len(seg["RU_2"]) < 200_000 # the rest of the session protocol is not one speech
def test_orf_fee_report_is_orf_income_not_a_payment_to_a_medium():
from politrack.sources.rtr import MediaTransparency
claim = MediaTransparency.orf_fee({"rechtstraeger": "Österreichischer Rundfunk", "bekanntgabe": 31,
"mediumMedieninhaber": "Programmentgelt gemäß § 31 Abs. 1 ORF-G"},
176200000.0, "2023-Q3", "20233")
assert claim.org.name == "Österreichischer Rundfunk" and claim.counterpart_org is None
assert claim.facet.payee.name == "Österreichischer Rundfunk" and claim.facet.payer is None
assert claim.facet.payer_name == "Programmentgelt gemäß § 31 Abs. 1 ORF-G" and claim.facet.category == "orf_fee"
assert claim.summary_de == ("Österreichischer Rundfunk: Einnahmen aus Programmentgelt gemäß § 31 Abs. 1 ORF-G, "
"176.200.000,00 € (2023-Q3)")
def test_written_question_addressee_is_not_an_asker():
from politrack.sources.parlament.items import ParlamentItems, question_answerers
rows = [
{"ITYP": "J", "Nummer": "1495/J", "Betreff": "Thema - beantwortet durch 1479/AB (SPÖ)",
"Personen": '["2337","35520"]', "Datum": "07.08.2018"},
{"ITYP": "J", "Nummer": "1600/J", "Betreff": "Offen", "Personen": '["2337","35520"]', "Datum": "01.09.2018"},
{"ITYP": "AB", "Nummer": "1479/AB", "Betreff": "Thema", "Personen": '["35520"]', "Datum": "07.10.2018"},
]
answerers = question_answerers(rows)
adapter = ParlamentItems.__new__(ParlamentItems)
askers = [c.person.ids["parlament"] for c in adapter.question_claims(rows[0], "/gegenstand/XXVI/J/1495", answerers)]
assert askers == ["2337"]
unanswered = [c.person.ids["parlament"] for c in adapter.question_claims(rows[1], "/gegenstand/XXVI/J/1600", answerers)]
assert unanswered == ["2337"]
answer = [c.person.ids["parlament"] for c in adapter.question_claims(rows[2], "/gegenstand/XXVI/AB/1479", answerers)]
assert answer == ["35520"]
def test_commons_register_ids_and_titles():
from politrack.sources.wikimedia import file_title, register_id
assert register_id("firmenbuch", "520909 v") == "520909v"
assert register_id("firmenbuch", "FN 58358x") == "58358x"
assert register_id("firmenbuch", "HRB 704943") is None
assert register_id("zvr", "ZVR 0303258961") == "303258961"
assert file_title("http://commons.wikimedia.org/wiki/Special:FilePath/B%C3%B6sendorfer_logo.svg") == \
"File:Bösendorfer logo.svg"
+31
View File
@@ -0,0 +1,31 @@
"""Reference syntax of user reports (the web app's ReportBody renders the same syntax)."""
from politrack.queries.reports import parse_references
BODY = """## Spenden 2017
[[angabe:123]]
Die Spende ist in [dieser Angabe](angabe:456) belegt, siehe auch [den Bericht](bericht:spenden-2017-2)
und [Pierer](person:stefan-pierer) bei der [ÖVP](org:oevp).
[[Bericht: wahlkampf-2017 ]]
[[angabe:123]] mitten im Satz ist keine Einbettung, [kaputt](angabe:abc) und [[angabe:x]] auch nicht.
[[claim:789]]
"""
def test_references_are_parsed_once_with_embedding_winning():
refs = parse_references(BODY)
assert refs == [
("claim", "123", True), ("report", "wahlkampf-2017", True), ("claim", "789", True),
("claim", "456", False), ("report", "spenden-2017-2", False), ("person", "stefan-pierer", False),
("organization", "oevp", False),
]
def test_inline_reference_to_an_embedded_claim_stays_embedded():
assert parse_references("[[angabe:5]]\n\nWie [oben](angabe:5) gezeigt") == [("claim", "5", True)]
def test_invalid_keys_are_ignored():
assert parse_references("[x](person:Hans Wurst) [y](bericht:../admin) [z](angabe:12a)") == []
+3
View File
@@ -110,6 +110,9 @@ services:
POLITRACK_LEGAL_ADDRESS: ${POLITRACK_LEGAL_ADDRESS:-}
POLITRACK_LEGAL_EMAIL: ${POLITRACK_LEGAL_EMAIL:-}
POLITRACK_CORRECTIONS_EMAIL: ${POLITRACK_CORRECTIONS_EMAIL:-}
# Reports: sign-in from the reverse proxy (see docs/deployment-unraid.md, "Reports and sign-in").
POLITRACK_AUTHOR_TOKEN: ${POLITRACK_AUTHOR_TOKEN:-}
POLITRACK_PROXY_SECRET: ${POLITRACK_PROXY_SECRET:-}
ports:
- "${WEB_PORT:-3000}:3000"
depends_on:
+13 -1
View File
@@ -18,6 +18,7 @@ organization ─┘ ╱ │ ╲ role, vote_position(→vo
social_account │ event_participant(→event), statement, legal_proceeding
chunk (text + embedding for RAG)
run, state, app_user operations
app_user ──< report ──< report_reference (→ claim, report, person, organization), report_revision
```
## Entities
@@ -28,6 +29,7 @@ run, state, app_user operations
| `organization` | `kind`: party, parliamentary_group, parliament, government, ministry, state_government, municipality, public_body, company, ngo, media, lobby, court, authority, eu_institution, other. `parent_id` for hierarchies. |
| `identifier` | `(entity_type, entity_id, scheme, value)`, unique per (entity_type, scheme, value). |
| `alias` | alternative names (with/without titles, short names, party abbreviations) used by the resolver and the linker. |
| `image_credit` | author, licence and Commons file page for a third-party image, keyed by its URL, which sits in `person.photo_url` / `organization.logo_url`. No row means an official photo (Parliament, EP); those are never replaced by Commons images. |
| `social_account` | person *or* organisation, `platform`, `url`, `verified` (official source) and `source_slug`. |
### Identifier schemes
@@ -117,4 +119,14 @@ across outlets (independence for corroboration).
`fetch_log` (every HTTP fetch: request, status, sha256, stored body, parse state), `run` (every adapter /
enricher run with stats and errors), `state` (adapter cursors), `chunk` (text chunks + pgvector
embeddings), `app_user` (reviewers).
embeddings), `app_user` (reviewers and report authors, from the proxy login).
## Reports
User-written articles (`report`, migration 0011). `body` is Markdown with references: `[[angabe:ID]]` on its own
line embeds a claim, `[[bericht:slug]]` another report; `[text](angabe:ID)`, `(bericht:slug)`, `(person:slug)` and
`(org:slug)` link inline. At every save the references are parsed into `report_reference` (drives "used in reports"
on claim pages and the backlinks between reports) and the version is copied to `report_revision`. Slugs are fixed at
creation. `status`: `draft` (author only), `published`, `withdrawn` (unlisted, the page says so). Embedded claims
are resolved like permalinks: no visitor filter, merged claims resolve to the survivor, hidden ones are reported as
missing. Writes only via the API's author endpoints (`POLITRACK_AUTHOR_TOKEN`, see deployment-unraid.md).
+26
View File
@@ -90,6 +90,32 @@ bge-m3 runs fine on CPU for this data volume. With an NVIDIA GPU, add a device r
VPN-only, or protect them with SSO or an API key at the proxy.
* Read [legal.md](legal.md) before going public (Impressum, privacy policy, §7b MedienG).
## Reports and sign-in
Anyone can read published reports; writing (`/berichte/verfassen…`) needs a login at the reverse proxy. The proxy
authenticates (Authelia, Authentik …) and passes `Remote-User`, `Remote-Name`, `Remote-Email` and `Remote-Groups`
to the `web` container. The web app trusts these headers only when the request also carries
`X-Politrack-Proxy: $POLITRACK_PROXY_SECRET`, which only the proxy sets, so a request straight to the web port
can't pretend to be someone. The web app then calls the API's write endpoints with
`Authorization: Bearer $POLITRACK_AUTHOR_TOKEN` (read by both `web` and `api` from `.env`).
1. Put `POLITRACK_AUTHOR_TOKEN` and `POLITRACK_PROXY_SECRET` (random, e.g. `openssl rand -hex 32`) into `.env` and
`docker compose up -d web api`.
2. SWAG: in the site's `location /` after the Authelia includes, add
`proxy_set_header X-Politrack-Proxy "<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
* `docker compose exec api politrack status` – recent runs with stats and errors (table `run`).
+17 -1
View File
@@ -27,7 +27,8 @@ All five stylesheets are imported once, in order, by `src/app/[locale]/layout.ts
* **Only tokens** for colour, spacing, radius and type. The exceptions are deliberate: party colours
(from the data), platform brand colours, and the favicon.
* **Server first.** Pages and most components are async server components. Client components exist only
where the browser must act: `ThemeSwitcher`, `LocaleSwitcher`, `NavLink`, `SettingsForm`, the error page.
where the browser must act: `ThemeSwitcher`, `LocaleSwitcher`, `NavLink`, `SettingsForm`, `ReportEditor`,
the error page.
* **No JavaScript needed** for navigation, filters, tabs, disclosures or the mobile menu: links, GET forms,
`<details>` and one checkbox toggle.
@@ -176,6 +177,21 @@ same mark as the favicon.
| `SocialFeed` | `SocialFeed.tsx` | post cards, no embeds |
| `SearchForm` | `SearchForm.tsx` | the big search field (optional date range) |
| `SettingsForm` (client) | `SettingsForm.tsx` | "Meine Filter" |
| `ReportBody`, `ClaimEmbed` | `ReportBody.tsx` | a report's text (Markdown subset, built as React elements, never raw HTML); embedded claim card under its database seal |
| `ReportCard`, `ReportList` | `ReportCard.tsx` | a report in lists and embedded in other reports: author, date, how many claims (official) it rests on |
| `ReportEditor` (client) | `ReportEditor.tsx` | title, summary, body and the reference picker (claims, reports, persons) |
### Reports
A report mixes the author's text with facts from the database, and the reader must always see which is which:
* Embedded claims (`[[angabe:ID]]`) are the full `ClaimCard` inside `.claim-embed`, under a seal: green shield
"Amtliche Daten" when a source is official (`source.kind = 'official'`), accent "Aus der Datenbank" otherwise.
* Inline references (`[text](angabe:ID)`) are tinted the same way and end with the seal icon; links to reports,
persons and organisations are ordinary links. A reference that no longer resolves is struck through, never
silently dropped.
* The `.report-basis` box under the header says how many claims the report rests on and that the text around
them is the author's. The list page carries the same disclaimer as a notice.
### The claim card
+4 -1
View File
@@ -75,7 +75,10 @@ Next.js frontend (de/en), Docker Compose for Unraid.
- [ ] Review queue for editors in the web UI (today `politrack review`)
- [ ] Community link submissions and a corrections/right-of-reply form
- [ ] Alerts (e-mail/RSS) for followed politicians
- [ ] Optional accounts via reverse-proxy SSO using `app_user`
- [x] Accounts via reverse-proxy SSO using `app_user` (2026-11-20, for reports; see deployment-unraid.md)
- [x] Reports: user articles embedding claims with a database seal, linking each other (`/berichte`, 2026-11-20)
- [ ] Reports, next: charts and money tables as embeds (`[[geld:…]]`), revision history page, comments/right of
reply, editor review before publication if the instance goes public, MCP tool for reading reports
- [ ] Partnerships: MeineAbgeordneten, Parteispenden.at, APA (OTS full-text licence)
- [ ] Map view of trips and appearances
- [ ] Semantic search with embeddings (`POLITRACK_OLLAMA_URL`): parked by the owner on 2026-11-09, full-text search only for now
+1
View File
@@ -69,6 +69,7 @@ Status: ✅ implemented (adapter name in `code`) · 🟡 planned · ⛔ delibera
| Source | Data | Access | Terms | Status |
|---|---|---|---|---|
| Wikidata | positions incl. Landtage and mayors, party membership, careers, birth dates, **social-media handles**, ids | SPARQL | CC0 | ✅ `wikidata.politicians` |
| Wikimedia Commons | portraits (Wikidata P18) for people without an official photo; party and company logos (P154), matched by Wikidata id, Firmenbuch number (P5285) or ZVR number (P6279) only | SPARQL + Commons API (imageinfo/extmetadata) | free licence per file; author and licence shown next to the image | ✅ `wikimedia.images` (weekly; Parliament/EP photos take precedence) |
| GDELT DOC 2.0 | article metadata for politicians' names, attributed to the original outlets | API, ≤ 1 request / 5 s | free | ✅ `gdelt.coverage` (supplement; thin for Austrian outlets) |
| HowTheyVote.eu | EP roll-call votes | CSV dump on GitHub (robots.txt blocks its download path), API | ODbL 1.0 (share-alike) | ⛔ not needed: `europarl.votes` takes the same votes from the EP under CC BY 4.0 |
| OpenSanctions | PEP cross-references | bulk JSON | CC BY-NC 4.0 | 🟡 non-commercial only |
+108 -5
View File
@@ -18,7 +18,8 @@
"social": "Social Media",
"wikipedia": "Wikipedia-Bearbeitungen",
"imprint": "Impressum",
"privacy": "Datenschutz"
"privacy": "Datenschutz",
"reports": "Berichte"
},
"Imprint": {
"title": "Impressum",
@@ -46,8 +47,8 @@
"visitors": "Politrack verwendet keine Werbung, kein Tracking und keine Skripte, Schriften oder Einbettungen von Dritten. Beim Abruf fallen technisch notwendige Zugriffsdaten an (IP-Adresse, Zeitpunkt, aufgerufene Seite), die nur so lange gespeichert werden, wie es für den sicheren Betrieb nötig ist.",
"cookiesHeading": "Cookies",
"cookies": "Wir speichern nur deine eigenen Einstellungen in Cookies: Quellen- und Themenfilter sowie das Farbschema. Sie dienen keiner Nachverfolgung.",
"imagesHeading": "Porträts",
"images": "Porträts laden wir über unseren eigenen Server, sodass deine IP-Adresse nicht an das Parlament oder andere Quellen übermittelt wird. Links zu externen Quellen öffnest du selbst; dort gelten die Bestimmungen der jeweiligen Betreiber.",
"imagesHeading": "Porträts und Logos",
"images": "Porträts und Logos laden wir über unseren eigenen Server, sodass deine IP-Adresse nicht an das Parlament, Wikimedia Commons oder andere Quellen übermittelt wird. Links zu externen Quellen öffnest du selbst; dort gelten die Bestimmungen der jeweiligen Betreiber.",
"subjectsHeading": "Daten über Politikerinnen und Politiker",
"subjects": "Politrack verarbeitet personenbezogene Daten ausschließlich zur öffentlichen Rolle von Personen: Funktionen, Abstimmungen, öffentliche Aussagen und Auftritte, gemeldete Nebentätigkeiten, Parteispenden und öffentlich bekannte Verfahren. Private Spender werden nur so genannt, wie es die amtliche Veröffentlichung vorsieht.",
"basisHeading": "Rechtsgrundlage",
@@ -159,7 +160,7 @@
},
"showPartVotes": "Auch Änderungsanträge und Teilabstimmungen anzeigen",
"hidePartVotes": "Nur Abstimmungen über ganze Texte anzeigen",
"factionVoteNote":"Im Nationalrat wird meist per Aufstehen abgestimmt; offiziell protokolliert ist dann nur das Stimmverhalten der Fraktion. Bei namentlichen Abstimmungen zeigen wir die eigene Stimme – und ob sie von der Fraktion abweicht.",
"factionVoteNote": "Im Nationalrat wird meist per Aufstehen abgestimmt; offiziell protokolliert ist dann nur das Stimmverhalten der Fraktion. Bei namentlichen Abstimmungen zeigen wir die eigene Stimme – und ob sie von der Fraktion abweicht.",
"roleCorroborated": "mehrfach belegt",
"unverified": "laut Wikidata – nicht amtlich bestätigt",
"accountUnverified": "Laut Wikidata – nicht amtlich bestätigt",
@@ -642,6 +643,108 @@
"crumb": "Angabe #{id}",
"cite": "Zitieren",
"citation": "Politrack: „{summary}“. Angabe #{id}, abgerufen am {date}. {url}",
"filtersIgnored": "Diese Seite zeigt die Angabe mit allen Quellen – unabhängig von deinen Filtern, damit ein geteilter Link für alle gleich aussieht."
"filtersIgnored": "Diese Seite zeigt die Angabe mit allen Quellen – unabhängig von deinen Filtern, damit ein geteilter Link für alle gleich aussieht.",
"inReports": "In Berichten",
"embedHint": "In einem Bericht einbetten mit",
"newReport": "In neuem Bericht verwenden"
},
"Reports": {
"title": "Berichte",
"eyebrow": "Bericht",
"intro": "Analysen und Zusammenhänge, geschrieben von Nutzer:innen. Jede eingebettete Angabe kommt direkt aus der Datenbank, mit ihren Belegen.",
"disclaimer": "Berichte geben die Sicht ihrer Autor:innen wieder. Belegt sind nur die markierten Angaben aus der Datenbank – Schlussfolgerungen daraus sind Meinung.",
"write": "Bericht verfassen",
"search": "Suche",
"searchPlaceholder": "Titel oder Vorspann …",
"none": "Noch keine Berichte.",
"byline": "Von {author}, {date}",
"edited": "zuletzt bearbeitet {date}",
"edit": "Bearbeiten",
"draftNotice": "Entwurf: nur du siehst diesen Bericht.",
"withdrawnNotice": "Dieser Bericht wurde von seinen Autor:innen zurückgezogen.",
"basisLabel": "Grundlage des Berichts",
"basis": "{claims, plural, =0 {Keine Angaben aus der Datenbank} one {Stützt sich auf # Angabe aus der Datenbank} other {Stützt sich auf # Angaben aus der Datenbank}}{official, plural, =0 {} other {, davon # aus amtlichen Quellen}}.",
"basisExplain": "Angaben mit dem Siegel sind von Politrack belegt und verlinken auf ihre Quellen. Der Text dazwischen stammt von {author}.",
"backlinks": "Berichte, die hierauf verweisen",
"status": {
"draft": "Entwurf",
"published": "Veröffentlicht",
"withdrawn": "Zurückgezogen"
},
"sealOfficial": "Amtliche Daten",
"sealDatabase": "Aus der Datenbank",
"sealDetail": "Angabe Nr. {id} · {sources}",
"refClaim": "Angabe Nr. {id} aus der Politrack-Datenbank",
"refClaimOfficial": "Angabe Nr. {id} aus der Politrack-Datenbank, belegt durch eine amtliche Quelle",
"refReport": "Bericht: {title}",
"refMissing": "Verweis nicht (mehr) verfügbar",
"claimMissing": "Angabe Nr. {id} ist nicht verfügbar (ausgeblendet, in Prüfung oder gelöscht).",
"reportMissing": "Der verlinkte Bericht ist nicht verfügbar."
},
"ReportEditor": {
"reports": "Berichte",
"mine": "Meine Berichte",
"mineIntro": "Angemeldet als {name}. Entwürfe siehst nur du.",
"mineNone": "Du hast noch keine Berichte geschrieben.",
"new": "Neuer Bericht",
"newIntro": "Verbinde Angaben aus der Datenbank zu einer Geschichte. Speichere zuerst als Entwurf – darunter erscheint dann die Vorschau.",
"editTitle": "Bericht bearbeiten",
"view": "Zum Bericht",
"signInNeeded": "Zum Schreiben musst du angemeldet sein. Öffne Politrack über die Adresse mit Anmeldung (nicht über die direkte LAN-Adresse des Servers).",
"title": "Titel",
"lede": "Vorspann",
"ledeHint": "Ein, zwei Sätze: worum geht es?",
"body": "Text",
"text": "Text",
"heading": "Überschrift",
"list": "Liste",
"quote": "Zitat",
"syntax": "Wie verweise ich auf Angaben?",
"helpEmbed": "in einer eigenen Zeile: bettet die Angabe Nr. 123 mit ihren Belegen ein",
"helpLink": "verlinkt die Angabe im Fließtext (mit Siegel)",
"helpReport": "bettet einen anderen Bericht ein bzw. verlinkt ihn",
"helpOther": "verlinkt eine Person, Organisation oder Webseite",
"helpFormat": "Überschrift, fett, kursiv, Liste, Zitat",
"lang": "Sprache",
"status": "Status",
"statusDraft": "Entwurf (nur für mich)",
"statusPublished": "Veröffentlicht",
"statusWithdrawn": "Zurückgezogen",
"responsibility": "Du schreibst unter deinem Namen. Bleib fair: Verbindungen sind keine Vorwürfe, und bei Verfahren gilt die Unschuldsvermutung. Jede gespeicherte Fassung wird aufbewahrt.",
"save": "Speichern",
"saving": "Speichert …",
"saved": "Gespeichert.",
"preview": "Vorschau",
"previewHint": "So sieht die zuletzt gespeicherte Fassung aus.",
"missingClaims": "Diese Angaben gibt es nicht oder sie sind nicht öffentlich: {ids}",
"pickerTitle": "Angaben finden",
"pickerType": "Was suchen?",
"type": {
"claim": "Angaben",
"report": "Berichte",
"person": "Personen"
},
"pickerPlaceholder": "Stichwort, Name oder Nr. …",
"pickerSearch": "Suchen",
"pickerNone": "Nichts gefunden.",
"pickerHint": "„Einbetten“ fügt die Karte an der Cursorposition ein, „Als Link“ verlinkt den markierten Text.",
"embed": "Einbetten",
"asLink": "Als Link",
"official": "amtlich",
"errorSignIn": "Du bist nicht (mehr) angemeldet. Lade die Seite neu.",
"errorNotYours": "Diesen Bericht kannst du nicht bearbeiten.",
"errorInvalid": "Nicht gespeichert: {detail}",
"errorUnknown": "Nicht gespeichert – bitte später noch einmal versuchen."
},
"Images": {
"official": {
"parlament": "Foto: Parlament Österreich",
"europarl": "Foto: Europäisches Parlament"
},
"commons": "Bild: {credit}",
"commonsNoCredit": "Bild: Wikimedia Commons",
"license": "Lizenz",
"source": "Quelle",
"logoAlt": "Logo von {name}"
}
}
+108 -5
View File
@@ -18,7 +18,8 @@
"social": "Social media",
"wikipedia": "Wikipedia edits",
"imprint": "Legal notice",
"privacy": "Privacy"
"privacy": "Privacy",
"reports": "Reports"
},
"Home": {
"headline": "Austrian politics – traceable.",
@@ -124,7 +125,7 @@
},
"showPartVotes": "Also show amendments and part votes",
"hidePartVotes": "Show votes on whole texts only",
"factionVoteNote":"The National Council mostly votes by standing up; then only each faction's vote is recorded. For roll-call votes we show the person's own vote – and whether it differs from their faction.",
"factionVoteNote": "The National Council mostly votes by standing up; then only each faction's vote is recorded. For roll-call votes we show the person's own vote – and whether it differs from their faction.",
"roleCorroborated": "corroborated",
"unverified": "per Wikidata – not officially confirmed",
"accountUnverified": "According to Wikidata – not officially confirmed",
@@ -621,8 +622,8 @@
"visitors": "Politrack uses no advertising, no tracking and no third-party scripts, fonts or embeds. Serving a page produces technically necessary access data (IP address, time, page requested), kept only as long as needed to run the site securely.",
"cookiesHeading": "Cookies",
"cookies": "Cookies only store your own settings: source and topic filters and the colour scheme. They are not used for tracking.",
"imagesHeading": "Portraits",
"images": "Portraits are loaded through our own server, so your IP address is not passed to the parliament or other sources. External source links are yours to open; the operators' own terms apply there.",
"imagesHeading": "Portraits and logos",
"images": "Portraits and logos are loaded through our own server, so your IP address is not passed on to Parliament, Wikimedia Commons or other sources. Links to external sources are opened by you; the respective operator's terms apply there.",
"subjectsHeading": "Data about politicians",
"subjects": "Politrack processes personal data only about people's public role: offices, votes, public statements and appearances, declared side jobs, party donations and publicly known proceedings. Private donors are named only as the official publication names them.",
"basisHeading": "Legal basis",
@@ -642,6 +643,108 @@
"crumb": "Fact #{id}",
"cite": "Cite",
"citation": "Politrack: “{summary}”. Fact #{id}, retrieved {date}. {url}",
"filtersIgnored": "This page shows the fact with all its sources – regardless of your filters, so a shared link looks the same for everyone."
"filtersIgnored": "This page shows the fact with all its sources – regardless of your filters, so a shared link looks the same for everyone.",
"inReports": "In reports",
"embedHint": "Embed it in a report with",
"newReport": "Use in a new report"
},
"Reports": {
"title": "Reports",
"eyebrow": "Report",
"intro": "Analyses and connections written by users. Every embedded fact comes straight from the database, with its sources.",
"disclaimer": "Reports reflect their authors' views. Only the marked facts from the database are backed by sources – conclusions drawn from them are opinion.",
"write": "Write a report",
"search": "Search",
"searchPlaceholder": "Title or summary …",
"none": "No reports yet.",
"byline": "By {author}, {date}",
"edited": "last edited {date}",
"edit": "Edit",
"draftNotice": "Draft: only you can see this report.",
"withdrawnNotice": "This report has been withdrawn by its author.",
"basisLabel": "What this report is based on",
"basis": "{claims, plural, =0 {No facts from the database} one {Based on # fact from the database} other {Based on # facts from the database}}{official, plural, =0 {} other {, # of them from official sources}}.",
"basisExplain": "Facts with the seal are backed by Politrack and link to their sources. The text around them is by {author}.",
"backlinks": "Reports linking here",
"status": {
"draft": "Draft",
"published": "Published",
"withdrawn": "Withdrawn"
},
"sealOfficial": "Official data",
"sealDatabase": "From the database",
"sealDetail": "Fact no. {id} · {sources}",
"refClaim": "Fact no. {id} from the Politrack database",
"refClaimOfficial": "Fact no. {id} from the Politrack database, backed by an official source",
"refReport": "Report: {title}",
"refMissing": "Reference not (or no longer) available",
"claimMissing": "Fact no. {id} is not available (hidden, under review or deleted).",
"reportMissing": "The linked report is not available."
},
"ReportEditor": {
"reports": "Reports",
"mine": "My reports",
"mineIntro": "Signed in as {name}. Only you can see drafts.",
"mineNone": "You haven't written any reports yet.",
"new": "New report",
"newIntro": "Connect facts from the database into a story. Save as a draft first – the preview then appears below.",
"editTitle": "Edit report",
"view": "View report",
"signInNeeded": "You need to be signed in to write. Open Politrack via its address with login (not the server's direct LAN address).",
"title": "Title",
"lede": "Summary",
"ledeHint": "One or two sentences: what is it about?",
"body": "Text",
"text": "text",
"heading": "Heading",
"list": "List",
"quote": "Quote",
"syntax": "How do I reference facts?",
"helpEmbed": "on a line of its own: embeds fact no. 123 with its sources",
"helpLink": "links the fact inline (with seal)",
"helpReport": "embeds or links another report",
"helpOther": "links a person, organisation or web page",
"helpFormat": "heading, bold, italic, list, quote",
"lang": "Language",
"status": "Status",
"statusDraft": "Draft (only me)",
"statusPublished": "Published",
"statusWithdrawn": "Withdrawn",
"responsibility": "You write under your own name. Be fair: connections are not accusations, and the presumption of innocence applies to proceedings. Every saved version is kept.",
"save": "Save",
"saving": "Saving …",
"saved": "Saved.",
"preview": "Preview",
"previewHint": "This is how the last saved version looks.",
"missingClaims": "These facts don't exist or aren't public: {ids}",
"pickerTitle": "Find facts",
"pickerType": "Search for",
"type": {
"claim": "Facts",
"report": "Reports",
"person": "People"
},
"pickerPlaceholder": "Keyword, name or no. …",
"pickerSearch": "Search",
"pickerNone": "Nothing found.",
"pickerHint": "\"Embed\" inserts the card at the cursor, \"As link\" links the selected text.",
"embed": "Embed",
"asLink": "As link",
"official": "official",
"errorSignIn": "You are not (or no longer) signed in. Reload the page.",
"errorNotYours": "You can't edit this report.",
"errorInvalid": "Not saved: {detail}",
"errorUnknown": "Not saved – please try again later."
},
"Images": {
"official": {
"parlament": "Photo: Austrian Parliament",
"europarl": "Photo: European Parliament"
},
"commons": "Image: {credit}",
"commonsNoCredit": "Image: Wikimedia Commons",
"license": "Licence",
"source": "Source",
"logoAlt": "Logo of {name}"
}
}
+10 -1
View File
@@ -3,9 +3,11 @@ import {headers} from 'next/headers';
import {notFound} from 'next/navigation';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {ClaimCard} from '@/components/ClaimList';
import {Icon} from '@/components/Icon';
import {Notice} from '@/components/Notice';
import {Breadcrumbs, type Crumb, SectionHead} from '@/components/PageHeader';
import {getPathname} from '@/i18n/navigation';
import {ReportList} from '@/components/ReportCard';
import {getPathname, Link} from '@/i18n/navigation';
import {api, NotFoundError, type Claim} from '@/lib/api';
import {formatDate} from '@/lib/format';
@@ -35,6 +37,7 @@ export default async function ClaimPage({params}: Props) {
const t = await getTranslations('ClaimPage');
const claim = await loadClaim(id);
const summary = locale === 'en' && claim.summary_en ? claim.summary_en : claim.summary_de;
const reports = await api.reports({claim: claim.id, limit: 20}).catch(() => []);
const h = await headers();
const host = h.get('x-forwarded-host') ?? h.get('host') ?? 'localhost';
@@ -58,6 +61,12 @@ export default async function ClaimPage({params}: Props) {
<p className="citation">{t('citation', {summary, id: String(claim.id), date: today, url})}</p>
<Notice tone="note">{t('filtersIgnored')}</Notice>
</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>
);
}
@@ -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>
);
}
+46
View File
@@ -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')} />
</>
);
}
@@ -7,6 +7,7 @@ import {ExternalLink} from '@/components/ExternalLink';
import {MoneyTable} from '@/components/MoneyTable';
import {Notice} from '@/components/Notice';
import {Breadcrumbs, SectionHead} from '@/components/PageHeader';
import {ImageCredit, Logo} from '@/components/ImageCredit';
import {Link, redirect} from '@/i18n/navigation';
import {api, NotFoundError, type Counterparty, type OrganizationDetail} from '@/lib/api';
import {formatMoneyCompact, formatNumber} from '@/lib/format';
@@ -83,6 +84,15 @@ export default async function OrganizationPage({params}: Props) {
</p>
) : null}
</div>
{org.logo_url && (
<figure className="page-header-logo">
<Logo name={org.name} src={org.logo_url} size="lg" />
<figcaption>
<ImageCredit url={org.logo_url} credit={org.logo_credit} license={org.logo_license}
licenseUrl={org.logo_license_url} pageUrl={org.logo_page_url} />
</figcaption>
</figure>
)}
</header>
<div className="layout-aside">
+7 -1
View File
@@ -2,6 +2,7 @@ import type {Metadata} from 'next';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {countActive, Field, FilterBar} from '@/components/FilterBar';
import {EmptyState} from '@/components/Notice';
import {Logo} from '@/components/ImageCredit';
import {PageHeader} from '@/components/PageHeader';
import {Pagination} from '@/components/Pagination';
import {Link} from '@/i18n/navigation';
@@ -59,7 +60,12 @@ export default async function OrganizationsPage({params, searchParams}: Props) {
<tbody>
{orgs.map((org) => (
<tr key={org.slug}>
<td data-label={t('name')}><Link href={`/organisationen/${org.slug}`}>{org.name}</Link></td>
<td data-label={t('name')}>
<span className="org-name">
<Logo name={org.name} src={org.logo_url} size="sm" />
<Link href={`/organisationen/${org.slug}`}>{org.name}</Link>
</span>
</td>
<td data-label={t('kindLabel')}><span className="badge">{t(`kind.${org.kind}` as 'kind.other')}</span></td>
<td data-label={t('paid')} className="num">{amount(org.paid)}</td>
<td data-label={t('received')} className="num">{amount(org.received)}</td>
@@ -5,6 +5,7 @@ import {ProportionBar, StatGrid} from '@/components/charts';
import {ClaimList} from '@/components/ClaimList';
import {Notice} from '@/components/Notice';
import {Breadcrumbs, SectionHead} from '@/components/PageHeader';
import {ImageCredit, Logo} from '@/components/ImageCredit';
import {SocialFeed} from '@/components/SocialFeed';
import {VoteLegend, VoteList} from '@/components/VoteList';
import {Link} from '@/i18n/navigation';
@@ -62,6 +63,15 @@ export default async function PartyPage({params}: Props) {
<h1>{party.short_name ?? party.name}</h1>
{party.short_name && <p className="lede">{party.name}</p>}
</div>
{party.logo_url && (
<figure className="page-header-logo">
<Logo name={party.name} src={party.logo_url} size="lg" />
<figcaption>
<ImageCredit url={party.logo_url} credit={party.logo_credit} license={party.logo_license}
licenseUrl={party.logo_license_url} pageUrl={party.logo_page_url} />
</figcaption>
</figure>
)}
</header>
<StatGrid
+2
View File
@@ -1,6 +1,7 @@
import type {Metadata} from 'next';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {PageHeader} from '@/components/PageHeader';
import {Logo} from '@/components/ImageCredit';
import {Link} from '@/i18n/navigation';
import {api} from '@/lib/api';
import {partyStyle} from '@/lib/format';
@@ -26,6 +27,7 @@ export default async function PartiesPage({params}: {params: Promise<{locale: st
{parties.map((party) => (
<li key={party.slug}>
<Link href={`/parteien/${party.slug}`} className="card-link party-card" style={partyStyle(party.color)}>
<Logo name={party.name} src={party.logo_url} size="sm" />
<span className="card-link-title">{party.short_name ?? party.name}</span>
{party.short_name && <span className="muted small">{party.name}</span>}
<span className="small">
@@ -2,6 +2,7 @@ import type {Metadata} from 'next';
import {notFound} from 'next/navigation';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {Avatar} from '@/components/Avatar';
import {ImageCredit} from '@/components/ImageCredit';
import {PartyTag, platformName, StatusBadge} from '@/components/badges';
import {StatGrid, type Stat} from '@/components/charts';
import {ClaimList} from '@/components/ClaimList';
@@ -89,7 +90,13 @@ export default async function PersonPage({params, searchParams}: Props) {
<article>
<Breadcrumbs items={[{label: tp('title'), href: '/personen'}, {label: person.full_name}]} />
<header className="profile-head">
<Avatar name={person.full_name} src={person.photo_url} size="lg" />
<figure className="profile-photo">
<Avatar name={person.full_name} src={person.photo_url} size="lg" />
<figcaption>
<ImageCredit url={person.photo_url} credit={person.photo_credit} license={person.photo_license}
licenseUrl={person.photo_license_url} pageUrl={person.photo_page_url} />
</figcaption>
</figure>
<div>
<div className="cluster">
<StatusBadge status={person.status} verified={person.status_verified} />
+2 -2
View File
@@ -1,8 +1,8 @@
// Image proxy for portraits, so that visitors' IP addresses don't reach the publishers.
// Image proxy for portraits and logos, so that visitors' IP addresses don't reach the publishers.
// Only raster images from the hosts below: anything else would turn this into an open proxy.
import type {NextRequest} from 'next/server';
const ALLOWED_HOSTS = new Set(['www.parlament.gv.at', 'www.europarl.europa.eu']);
const ALLOWED_HOSTS = new Set(['www.parlament.gv.at', 'www.europarl.europa.eu', 'upload.wikimedia.org']);
const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
const MAX_BYTES = 5 * 1024 * 1024;
const MAX_REDIRECTS = 3;
+35
View File
@@ -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'}});
}
+6 -3
View File
@@ -1,13 +1,16 @@
import {initials} from '@/lib/format';
/** Third-party images (portraits, logos) go through our own image proxy (app/api/img), so that visitors' IP
* addresses don't reach the publishers. */
export const proxied = (src: string) => `/api/img?u=${encodeURIComponent(src)}`;
/**
* Portrait or initials. Portraits go through our own image proxy (app/api/img), so that visitors' IP addresses
* don't reach third parties. Decorative (alt=""), because the name is always printed next to it.
* Portrait or initials. Decorative (alt=""), because the name is always printed next to it.
*/
export function Avatar({name, src, size = 'md'}: {name: string; src?: string | null; size?: 'md' | 'lg'}) {
const className = size === 'lg' ? 'avatar avatar--lg' : 'avatar';
if (src) {
return <img src={`/api/img?u=${encodeURIComponent(src)}`} alt="" className={className} loading="lazy" decoding="async" />;
return <img src={proxied(src)} alt="" className={className} loading="lazy" decoding="async" />;
}
return <span className={className} aria-hidden="true">{initials(name)}</span>;
}
+51
View File
@@ -0,0 +1,51 @@
import {getTranslations} from 'next-intl/server';
import {proxied} from '@/components/Avatar';
/** Organization or party logo on a light tile (logos are drawn for light backgrounds, also in dark mode). */
export async function Logo({name, src, size = 'md'}: {name: string; src?: string | null; size?: 'sm' | 'md' | 'lg'}) {
if (!src) return null;
const t = await getTranslations('Images');
return (
<span className={`logo-tile logo-tile--${size}`}>
<img src={proxied(src)} alt={t('logoAlt', {name})} loading="lazy" decoding="async" />
</span>
);
}
export type ImageCreditData = {
url?: string | null;
credit?: string | null;
license?: string | null;
licenseUrl?: string | null;
pageUrl?: string | null;
};
function hostOf(url: string): string {
try {
return new URL(url).hostname;
} catch {
return '';
}
}
/** Attribution under a portrait or logo: author and licence for Commons files, the publisher for official photos. */
export async function ImageCredit({url, credit, license, licenseUrl, pageUrl}: ImageCreditData) {
if (!url) return null;
const t = await getTranslations('Images');
const host = hostOf(url);
if (host === 'www.parlament.gv.at') return <p className="image-credit">{t('official.parlament')}</p>;
if (host === 'www.europarl.europa.eu') return <p className="image-credit">{t('official.europarl')}</p>;
if (host !== 'upload.wikimedia.org') return null;
const label = credit ? t('commons', {credit}) : t('commonsNoCredit');
return (
<p className="image-credit">
{pageUrl ? <a href={pageUrl} rel="noopener noreferrer" target="_blank">{label}</a> : label}
{license && (
<>
{' · '}
{licenseUrl ? <a href={licenseUrl} rel="license noopener noreferrer" target="_blank">{license}</a> : license}
</>
)}
</p>
);
}
+210
View File
@@ -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>
);
}
+41
View File
@@ -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>
);
}
+167
View File
@@ -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>&gt; …</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>
);
}
+3 -2
View File
@@ -14,6 +14,7 @@ const ITEMS = {
social: {href: '/social', key: 'social', icon: 'message'},
wikipedia: {href: '/wikipedia', key: 'wikipedia', icon: 'pencil'},
former: {href: '/ehemalige', key: 'former', icon: 'history'},
reports: {href: '/berichte', key: 'reports', icon: 'news'},
method: {href: '/methodik', key: 'method', icon: 'book'},
settings: {href: '/einstellungen', key: 'settings', icon: 'sliders'},
search: {href: '/suche', key: 'search', icon: 'search'},
@@ -22,11 +23,11 @@ const ITEMS = {
} satisfies Record<string, NavItem>;
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[]}[] = [
{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: 'about', items: [ITEMS.method, ITEMS.settings, ITEMS.search, ITEMS.imprint, ITEMS.privacy]}
];
+66
View File
@@ -179,6 +179,12 @@ export type MoneySummaryRow = {
count: number;
};
export type NamedRef = {
slug: string;
name: string;
kind: string | null;
};
export type Network = {
organizations: NetworkOrg[];
};
@@ -217,6 +223,11 @@ export type OrganizationDetail = {
parent_slug: string | null;
parent_name: string | null;
identifiers: Record<string, string> | null;
logo_url: string | null;
logo_credit: string | null;
logo_license: string | null;
logo_license_url: string | null;
logo_page_url: string | null;
money: OrgMoney[];
counterparties: Counterparty[];
people: OrgPerson[];
@@ -227,6 +238,7 @@ export type OrganizationListItem = {
name: string;
short_name: string | null;
kind: string;
logo_url: string | null;
paid: number | null;
received: number | null;
};
@@ -252,6 +264,10 @@ export type PartyDetail = {
short_name: string | null;
color: string | null;
logo_url: string | null;
logo_credit: string | null;
logo_license: string | null;
logo_license_url: string | null;
logo_page_url: string | null;
kind: string;
members: PartyMember[];
former_members: FormerMember[];
@@ -293,6 +309,10 @@ export type PersonDetail = {
birth_date: string | null;
death_date: string | null;
photo_url: string | null;
photo_credit: string | null;
photo_license: string | null;
photo_license_url: string | null;
photo_page_url: string | null;
wikidata_qid: string | null;
parlament_pad: string | null;
ep_id: string | null;
@@ -341,6 +361,50 @@ export type RelatedOrg = {
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 = {
role: string;
level: string;
@@ -512,6 +576,8 @@ export type Paths = {
'/api/v1/persons/{slug}': PersonDetail;
'/api/v1/persons/{slug}/network': Network;
'/api/v1/persons/{slug}/votes': PersonVote[];
'/api/v1/reports': ReportListItem[];
'/api/v1/reports/{slug}': ReportDetail;
'/api/v1/search': SearchHit[];
'/api/v1/social': SocialPost[];
'/api/v1/sources': Source[];
+42 -5
View File
@@ -4,14 +4,18 @@
import {cookies} from 'next/headers';
import type * as T from './api-types';
import {PREFS_COOKIE, parsePrefs, type Prefs} from './prefs';
import {getViewer, viewerHeaders} from './viewer';
export type {
CalendarData, CalendarEvent, Claim, Counterparty, Evidence, FormerPerson, MoneyFacet, MoneyFlow, MoneySummaryRow,
Network, NetworkOrg, OrganizationDetail, OrganizationListItem, Party, PartyDetail, PartyRef, PersonDetail,
PersonListItem, PersonVote, Role, SearchHit, SocialPost, Source, Stats, TimelineBucket, Topic, VoteDetail, VoteItem,
WikiEdit
PersonListItem, PersonVote, ReportDetail, ReportListItem, ReportReferences, Role, SearchHit, SocialPost, Source, Stats,
TimelineBucket, Topic, VoteDetail, VoteItem, WikiEdit
} 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 ClaimType = T.Claim['claim_type'];
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>;
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);
for (const [key, value] of Object.entries(params)) {
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));
}
}
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.ok) throw new Error(`API ${res.status} for ${url}`);
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 {}
/** 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. */
async function withPrefs(params: Params, useTopics = true): Promise<Params> {
const prefs = await getPrefs();
@@ -98,5 +128,12 @@ export const api = {
wikiEdits: (params: Params) => get<T.WikiEdit[]>('/api/v1/wiki-edits', params),
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)
};
+42
View File
@@ -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(','))
};
}
+371
View File
@@ -2132,3 +2132,374 @@ input[type='checkbox'].switch:checked::before {
from { 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);
}
/* ---------- portraits and logos: credit lines, logo tiles ---------- */
.profile-photo, .page-header-logo {
margin: 0;
display: flex;
flex-direction: column;
gap: var(--space-1);
max-width: 11rem;
}
.image-credit {
margin: 0;
font-size: var(--text-xs, 0.75rem);
line-height: 1.35;
color: var(--ink-3);
overflow-wrap: anywhere;
}
.image-credit a {
color: inherit;
}
/* Logos are designed for light backgrounds, so the tile stays white in dark mode too. */
.logo-tile {
--size: 2rem;
display: inline-grid;
place-items: center;
flex: none;
width: calc(var(--size) * 1.6);
height: var(--size);
padding: 3px;
background: #ffffff;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.logo-tile img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.logo-tile--sm { --size: 1.75rem; }
.logo-tile--lg { --size: 5rem; padding: var(--space-2); }
.party-card .logo-tile {
align-self: flex-start;
}
.org-name {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}