diff --git a/.env.example b/.env.example index 9d2bb1d..a133baf 100644 --- a/.env.example +++ b/.env.example @@ -45,6 +45,8 @@ POLITRACK_AD_ARCHIVE_SINCE=2023-01-01 # Optional credentials. Adapters that need them skip themselves when unset. # YouTube Data API v3 key (free quota): https://console.cloud.google.com/apis/library/youtube.googleapis.com # POLITRACK_YOUTUBE_API_KEY= +# JustizOnline Firmenbuch high-value-dataset web service token (free, request it at justizonline.gv.at) +# POLITRACK_JUSTIZ_HVD_API_KEY= # Meta Ad Library API token (requires identity confirmation): https://www.facebook.com/ads/library/api # POLITRACK_META_AD_LIBRARY_TOKEN= # X API v2 bearer token (paid tier with read access). Without it no X posts are collected. diff --git a/backend/migrations/0009_company_roles.sql b/backend/migrations/0009_company_roles.sql new file mode 100644 index 0000000..72876ce --- /dev/null +++ b/backend/migrations/0009_company_roles.sql @@ -0,0 +1,17 @@ +-- Company register (Firmenbuch HVD): functions of politicians in companies (managing director, authorised +-- signatory, board member, shareholder ...), as their own claim type so that they never count as political office. +ALTER TABLE claim DROP CONSTRAINT claim_claim_type_check; +ALTER TABLE claim ADD CONSTRAINT claim_claim_type_check CHECK (claim_type IN ( + 'role', 'vote', 'donation', 'money_flow', 'statement', 'appearance', 'meeting', 'travel', + 'side_job', 'legal_proceeding', 'lobbying', 'media_mention', 'career', + 'parliamentary_question', 'government_decision', 'wiki_edit', 'declaration', 'ownership', + 'affiliation', 'party_finance', 'election_result', 'company_role', 'other')); +COMMENT ON COLUMN claim.claim_type IS 'Kind of fact. election_result: a party''s result in a region (counterpart = the elected body) or a candidate''s preference votes (person, counterpart = party). company_role: a person''s function in a company according to the Firmenbuch (counterpart = the company; data.function, data.fn).'; + +-- Firmenbuch numbers are now stored without leading zeros ('068616g' -> '68616g'), as text.firmenbuch_number does. +DELETE FROM identifier a +WHERE a.scheme = 'firmenbuch' AND a.value ~ '^0' + AND EXISTS (SELECT 1 FROM identifier b WHERE b.entity_type = a.entity_type AND b.scheme = 'firmenbuch' + AND b.value = regexp_replace(a.value, '^0+', '')); +UPDATE identifier SET value = regexp_replace(value, '^0+', '') +WHERE scheme = 'firmenbuch' AND value ~ '^0'; diff --git a/backend/politrack/api/schemas.py b/backend/politrack/api/schemas.py index 81cc19c..e10282e 100644 --- a/backend/politrack/api/schemas.py +++ b/backend/politrack/api/schemas.py @@ -11,7 +11,7 @@ from pydantic import BaseModel, ConfigDict ClaimType = Literal["role", "vote", "donation", "money_flow", "statement", "appearance", "meeting", "travel", "side_job", "legal_proceeding", "lobbying", "media_mention", "career", "parliamentary_question", "government_decision", "wiki_edit", "declaration", "ownership", "affiliation", "party_finance", - "election_result", "other"] + "election_result", "company_role", "other"] PersonStatus = Literal["active", "former", "party_member", "deceased"] diff --git a/backend/politrack/config.py b/backend/politrack/config.py index 075b6d4..d5cdb9e 100644 --- a/backend/politrack/config.py +++ b/backend/politrack/config.py @@ -33,6 +33,7 @@ class Settings(BaseSettings): youtube_api_key: str | None = None meta_ad_library_token: str | None = None x_bearer_token: str | None = None + justiz_hvd_api_key: str | None = None # JustizOnline Firmenbuch HVD web service (firmenbuch.* adapters) # Bulk sources: how far back to backfill on the first run procurement_since: str = "2024-01-01" diff --git a/backend/politrack/core/adapter.py b/backend/politrack/core/adapter.py index 6699948..efd5e40 100644 --- a/backend/politrack/core/adapter.py +++ b/backend/politrack/core/adapter.py @@ -50,14 +50,18 @@ class Request: method: str = "GET" params: dict[str, Any] | None = None json: Any = None - headers: dict[str, str] | None = None + data: bytes | None = None # raw request body (e.g. a SOAP envelope); part of the fingerprint + headers: dict[str, str] | None = None # never archived (may carry API keys) meta: dict[str, Any] = field(default_factory=dict, compare=False, hash=False) conditional: bool = True # send If-None-Match / If-Modified-Since skip_unchanged: bool = True # body + parser_version unchanged: follow-ups only @property def fingerprint(self) -> str: - raw = json.dumps([self.method, self.url, self.params or {}, self.json], sort_keys=True, default=str) + parts: list[Any] = [self.method, self.url, self.params or {}, self.json] + if self.data is not None: + parts.append(self.data.decode("utf-8", "replace")) + raw = json.dumps(parts, sort_keys=True, default=str) return hashlib.sha256(raw.encode()).hexdigest()[:32] def describe(self) -> dict[str, Any]: diff --git a/backend/politrack/core/fetch.py b/backend/politrack/core/fetch.py index ccbcd13..e1bb01b 100644 --- a/backend/politrack/core/fetch.py +++ b/backend/politrack/core/fetch.py @@ -30,6 +30,11 @@ log = logging.getLogger(__name__) RETRY_STATUS = {429, 500, 502, 503, 504} +def is_soap_fault(resp: httpx.Response) -> bool: + """A SOAP service answers a bad request with HTTP 500 and a Fault body; retrying can't change the answer.""" + return resp.status_code == 500 and b"Fault>" in resp.content[:4000] + + class Disallowed(Exception): """robots.txt forbids fetching this URL.""" @@ -121,14 +126,15 @@ class Fetcher: for attempt in range(attempts): self._throttle(req.url, spec) try: - resp = self.client.request(req.method, req.url, params=req.params, json=req.json, headers=headers) + resp = self.client.request(req.method, req.url, params=req.params, json=req.json, content=req.data, + headers=headers) except httpx.TransportError as exc: if attempt == attempts - 1: raise log.warning("transport error %s (%s), retrying", req.url, exc) time.sleep(min(5 * 2 ** attempt, 120)) continue - if resp.status_code in RETRY_STATUS and attempt < attempts - 1: + if resp.status_code in RETRY_STATUS and attempt < attempts - 1 and not is_soap_fault(resp): retry_after = resp.headers.get("Retry-After", "") time.sleep(min(float(retry_after) if retry_after.isdigit() else 5 * 2 ** attempt, 300)) continue diff --git a/backend/politrack/core/resolve.py b/backend/politrack/core/resolve.py index d342a96..4be3eed 100644 --- a/backend/politrack/core/resolve.py +++ b/backend/politrack/core/resolve.py @@ -9,6 +9,8 @@ Hint strategies for persons (documented in docs/data-model.md): office + on holder of an office title on a date (Council of Ministers minutes) birth_year exact name and year of birth (candidate lists); add no_name_match so that a name alone never matches when the year doesn't + birth_date exact date of birth and the same name or a variant of it (company register officers); + with no_name_match, people who are not in the database are never matched or created """ from __future__ import annotations @@ -197,6 +199,11 @@ class Resolver: (normalize(strip_titles(ref.name)), int(hints["birth_year"])), ).fetchall() return rows[0]["id"] if len(rows) == 1 else None + if "birth_date" in hints and ref.name: + rows = self.conn.execute("SELECT id, full_name FROM person WHERE birth_date = %s", + (hints["birth_date"],)).fetchall() + hits = {r["id"] for r in rows if variant_of(ref.name, r["full_name"])} + return hits.pop() if len(hits) == 1 else None return None def office_holder(self, office: str, on: date | None) -> int | None: @@ -325,7 +332,7 @@ class Resolver: def _add_org_ids(self, org_id: int, ref: OrgRef) -> None: for scheme, value in ref.ids.items(): - if value: + if value and scheme != "politrack_org": # internal lookup id, not an external identifier self.conn.execute( "INSERT INTO identifier (entity_type, entity_id, scheme, value) VALUES ('organization', %s, %s, %s) " "ON CONFLICT DO NOTHING", diff --git a/backend/politrack/mcp_server.py b/backend/politrack/mcp_server.py index ded0493..bf71885 100644 --- a/backend/politrack/mcp_server.py +++ b/backend/politrack/mcp_server.py @@ -116,7 +116,7 @@ def list_claims( """Claims about a person/party/organisation, newest first. claim_types: role, vote, donation, money_flow, statement, appearance, meeting, travel, side_job, legal_proceeding, lobbying, media_mention, career, parliamentary_question, government_decision, wiki_edit, declaration, ownership, affiliation, party_finance, - election_result. + election_result, company_role (functions in companies according to the Firmenbuch). Dates as YYYY-MM-DD.""" with connection() as conn: return _dump(queries.list_claims( diff --git a/backend/politrack/queries/organizations.py b/backend/politrack/queries/organizations.py index 7ff269b..9f07f81 100644 --- a/backend/politrack/queries/organizations.py +++ b/backend/politrack/queries/organizations.py @@ -160,7 +160,7 @@ def get_organization(conn: Connection, slug: str) -> dict | None: SELECT DISTINCT ON (p.id, c.claim_type) p.slug, p.full_name, c.claim_type AS via, c.summary_de FROM claim c JOIN person p ON p.id = c.person_id WHERE c.counterpart_org_id = %(id)s AND c.merged_into IS NULL AND c.review_status = 'published' - AND c.claim_type IN ('side_job', 'career', 'meeting', 'role', 'lobbying') + AND c.claim_type IN ('side_job', 'company_role', 'career', 'meeting', 'role', 'lobbying') ORDER BY p.id, c.claim_type LIMIT 100 """, {"id": oid}, diff --git a/backend/politrack/queries/people.py b/backend/politrack/queries/people.py index 32e1627..c55cc0c 100644 --- a/backend/politrack/queries/people.py +++ b/backend/politrack/queries/people.py @@ -126,7 +126,7 @@ def person_network(conn: Connection, slug: str) -> dict: FROM claim c WHERE c.person_id = %(pid)s AND c.counterpart_org_id IS NOT NULL AND c.merged_into IS NULL AND c.review_status = 'published' - AND c.claim_type IN ('side_job', 'career', 'meeting', 'role', 'lobbying') + AND c.claim_type IN ('side_job', 'company_role', 'career', 'meeting', 'role', 'lobbying') GROUP BY 1, 2 UNION SELECT r.party_id, 'party', NULL FROM role r WHERE r.person_id = %(pid)s AND r.party_id IS NOT NULL diff --git a/backend/politrack/sources/firmenbuch.py b/backend/politrack/sources/firmenbuch.py new file mode 100644 index 0000000..3bb1d37 --- /dev/null +++ b/backend/politrack/sources/firmenbuch.py @@ -0,0 +1,384 @@ +"""Austrian company register (Firmenbuch) through the free JustizOnline high-value-dataset web service (SOAP 1.2, +personal API token in POLITRACK_JUSTIZ_HVD_API_KEY; the adapters skip themselves without it). + + firmenbuch.search Companies the data names without a register number (side-job employers, party holdings and + affiliations): company search by name; the number is recorded only when exactly one current + register entry has the same name (legal form and punctuation ignored). + firmenbuch.extracts Current extract ("Kurzinformation") of every company with a register number: the official + name becomes an alias of the company, and officers and shareholders who are politicians in + the database become `company_role` claims. The daily change list of the register + (VERAENDERUNGENFIRMA) tells which extracted companies to fetch again. + enrich.firmenbuch Closes company roles that a newer extract of the same company no longer lists. + +Privacy: extracts name private individuals with birth date and address. A person is matched only by exact birth +date plus the same name (or a variant of it) among persons already in the database, and never created; everyone +else is dropped in the Loader. Raw responses are not archived (keep_raw=False) and addresses are never read. +""" + +from __future__ import annotations + +import re +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from datetime import date, datetime, timedelta +from typing import Any +from xml.sax.saxutils import escape + +from politrack.config import get_settings +from politrack.core import ( + Adapter, + Enricher, + Request, + Response, + RunContext, + SourceSpec, + register, + register_spec, +) +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 + +URL = "https://justizonline.gv.at/jop/api/at.gv.justiz.fbw/ws" +NS = "ns://firmenbuch.justiz.gv.at/Abfrage/" +SPEC = register_spec(SourceSpec( + slug="firmenbuch", name="Firmenbuch (JustizOnline HVD)", kind="official", homepage="https://justizonline.gv.at", + license="High-value dataset (EU Implementing Regulation 2023/138)", access="api", trust=95, min_interval=2.0, + store_fulltext=False, keep_raw=False, + tos_notes="Free HVD web service of the Austrian company register (personal API token, HTTP 429 when the load " + "limit is exceeded). Extracts contain private individuals' birth dates and addresses: raw responses " + "are not archived; only officers who are politicians already in the database (exact birth date and " + "name) are stored, and addresses never.")) + +# Functions (FKEN) in English; everything else uses the register's German label +FUNCTIONS_EN = { + "GF": "managing director", "PR": "authorised signatory (Prokurist)", "VS": "member of the management board", + "VV": "chair of the management board", "AR": "member of the supervisory board", + "AV": "chair of the supervisory board", "AS": "deputy chair of the supervisory board", "GS": "shareholder", + "KOM": "limited partner", "KP": "limited partner", "UG": "general partner", "IH": "owner", "LI": "liquidator", +} +# Words that end the name part of a company name (search term = what comes before) +LEGAL_FORM = re.compile( + r"\s(?:GmbH|Ges\.?\s?m\.?\s?b\.?\s?H\.?|Gesellschaft\s+m\.?\s?b\.?\s?H\.?|Gesellschaft mit beschränkter Haftung|" + r"AG|Aktiengesellschaft|KG|OG|OHG|KEG|OEG|e\.\s?U\.?|SE|eGen|reg\.?\s?Gen|Genossenschaft|& Co|Privatstiftung|" + r"Holding)\b.*$", re.IGNORECASE) + + +def fn_display(fn: str) -> str: + """'306527a' -> '306527 a', as the register writes it.""" + return f"{fn[:-1]} {fn[-1]}" + + +def envelope(service: str, root: str, fields: dict[str, Any]) -> bytes: + """SOAP 1.2 request; `service` is the namespace suffix (e.g. 'v2/AuszugRequest').""" + body = "".join(f"{escape('' if v is None else str(v))}" for k, v in fields.items()) + return (f'' + f"{body}").encode() + + +def soap_request(kind: str, service: str, root: str, fields: dict[str, Any], meta: dict[str, Any]) -> Request: + return Request(url=URL, kind=kind, method="POST", data=envelope(service, root, fields), meta=meta, + headers={"Content-Type": "application/soap+xml;charset=UTF-8", + "X-API-KEY": get_settings().justiz_hvd_api_key or ""}, + conditional=False, skip_unchanged=False) + + +# -- XML helpers (namespace prefixes differ per response; compare local names) ------------------------------------- + +def _local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _attr(el: ET.Element, name: str) -> str | None: + return next((v for k, v in el.attrib.items() if _local(k) == name), None) + + +def _kids(el: ET.Element, name: str) -> list[ET.Element]: + return [c for c in el if _local(c.tag) == name] + + +def _find(el: ET.Element, name: str) -> ET.Element | None: + return next((c for c in el.iter() if _local(c.tag) == name), None) + + +def _text(el: ET.Element | None, name: str) -> str | None: + found = _find(el, name) if el is not None else None + text = (found.text or "").strip() if found is not None else "" + return text or None + + +def _current(el: ET.Element, name: str) -> ET.Element | None: + """The current (AUFRECHT) entry of a register field; the newest one (highest VNR) if several.""" + entries = [c for c in _kids(el, name) if _attr(c, "AUFRECHT") != "false"] + return max(entries, key=lambda c: _attr(c, "VNR") or "") if entries else None + + +def _ymd(value: str | None) -> date | None: + """'20080215' or '2008-02-15' -> date.""" + digits = re.sub(r"\D", "", value or "") + try: + return datetime.strptime(digits, "%Y%m%d").date() if len(digits) == 8 else None + except ValueError: + return None + + +def soap_body(body: bytes) -> ET.Element: + root = ET.fromstring(body) + fault = _find(root, "Fault") + if fault is not None: + raise SoapFault(_text(fault, "Text") or "SOAP fault") + found = _find(root, "Body") + if found is None or not len(found): + raise SoapFault("empty SOAP body") + return found[0] + + +class SoapFault(Exception): + pass + + +# -- parsers (pure) ------------------------------------------------------------------------------------------------ + +def parse_extract(body: bytes) -> dict[str, Any]: + """Company and its current functions. Addresses (FI_DKZ03, PE_DKZ03) are never read.""" + resp = soap_body(body) + fn = firmenbuch_number(_attr(resp, "FNR")) + firma = _find(resp, "FIRMA") + name_el = _current(firma, "FI_DKZ02") if firma is not None else None + name = " ".join(t.text.strip() for t in _kids(name_el, "BEZEICHNUNG") if t.text) if name_el is not None else "" + seat_el = _current(firma, "FI_DKZ06") if firma is not None else None + form_el = _current(firma, "FI_DKZ07") if firma is not None else None + persons: dict[str, dict[str, Any]] = {} + for per in _kids(resp, "PER"): + entry = _current(per, "PE_DKZ02") + if entry is None: + continue + given, surname = _text(entry, "VORNAME"), _text(entry, "NACHNAME") + persons[(_attr(per, "PNR") or "").strip()] = { + "given": given, "surname": surname, "birth_date": _ymd(_text(entry, "GEBURTSDATUM")), + "organization": None if surname else (_text(entry, "BEZEICHNUNG") or _text(entry, "NAME_FORMATIERT")), + } + functions = [] + for fun in _kids(resp, "FUN"): + pnr = (_attr(fun, "PNR") or "").strip() + entry = _current(fun, "FU_DKZ10") + if entry is None or pnr not in persons: + continue + capital = _text(entry, "KAPITAL") + functions.append({ + "pnr": pnr, "code": _attr(fun, "FKEN") or "", "label": function_label(_attr(fun, "FKENTEXT") or ""), + "since": _ymd(_text(entry, "DATVON")), "until": _ymd(_text(entry, "DATBIS")), + "detail": " ".join(t.text.strip() for t in _kids(entry, "TEXT") if t.text) or None, + "capital": float(capital) if capital else None, "currency": _text(entry, "WHR"), + **persons[pnr], + }) + return {"fn": fn, "name": name, "seat": _text(seat_el, "SITZ"), "legal_form": _text(form_el, "TEXT"), + "as_of": _attr(resp, "STICHTAG"), "functions": functions} + + +def function_label(text: str) -> str: + """'GESCHÄFTSFÜHRER/IN (handelsrechtlich)' -> 'Geschäftsführer/in (handelsrechtlich)'.""" + return " ".join(w.capitalize() if w.isupper() else w for w in text.split()) + + +def parse_search(body: bytes) -> list[dict[str, Any]]: + resp = soap_body(body) + out = [] + for hit in _kids(resp, "ERGEBNIS"): + name = " ".join(t.text.strip() for t in _kids(hit, "NAME") if t.text) + out.append({"fn": firmenbuch_number(_text(hit, "FNR")), "name": name, "seat": _text(hit, "SITZ"), + "status": _text(hit, "STATUS"), "legal_form": _text(_find(hit, "RECHTSFORM"), "TEXT")}) + return out + + +def parse_changes(body: bytes) -> set[str]: + resp = soap_body(body) + return {fn for fn in (firmenbuch_number(_text(v, "FNR")) for v in _kids(resp, "VERAENDERUNG")) if fn} + + +def search_term(name: str) -> str: + """'Salzburger Parkgaragen Gesellschaft m.b.H.' -> 'Salzburger Parkgaragen' (the register's search matches + words of the company name; the legal form is written in many ways).""" + term = LEGAL_FORM.sub("", " " + re.sub(r"[\"'„“”»«]", "", name)).strip(" ,.-&") + return term if len(term) >= 3 else "" + + +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).""" + target = normalize_org_name(name) + same = [h for h in hits if h["fn"] and normalize_org_name(h["name"]) == target] + current = [h for h in same if not h["status"]] or same + return current[0] if len(current) == 1 else None + + +# -- adapters ------------------------------------------------------------------------------------------------------ + +def _fetched(conn, adapter: str, kind: str, key: str, ok_only: bool = True) -> set[str]: + rows = conn.execute( + f"""SELECT DISTINCT request->'meta'->>'{key}' AS v FROM fetch_log + WHERE adapter = %s AND request->>'kind' = %s {"AND status = 200" if ok_only else ""}""", + (adapter, kind)).fetchall() + return {r["v"] for r in rows if r["v"]} + + +@register +class FirmenbuchSearch(Adapter): + spec = SPEC + name = "firmenbuch.search" + description = "Find register numbers of companies named in side jobs and party reports (Firmenbuch search)" + schedule = "10 3 * * *" + queue = "bulk" + + def start(self, ctx: RunContext) -> Iterator[Request]: + if ctx.conn is None or not get_settings().justiz_hvd_api_key: + ctx.stats["no_api_key"] += 1 + return + scope = ctx.params.get("scope", "linked") # linked: companies linked to a person or party; all: every company + linked = "" if scope == "all" else """AND EXISTS (SELECT 1 FROM claim c WHERE c.counterpart_org_id = o.id + AND c.claim_type IN ('side_job', 'ownership', 'affiliation', 'career'))""" + rows = ctx.conn.execute( + f"""SELECT o.id, o.name FROM organization o + WHERE o.kind IN ('company', 'other', 'media') + AND NOT EXISTS (SELECT 1 FROM identifier i WHERE i.entity_type = 'organization' + AND i.entity_id = o.id AND i.scheme = 'firmenbuch') {linked} + ORDER BY o.id""").fetchall() + searched = _fetched(ctx.conn, self.name, "search", "org_id", ok_only=False) + todo = [r for r in rows if str(r["id"]) not in searched and search_term(r["name"])] + ctx.stats["pending"] = len(todo) + for row in todo[: int(ctx.params.get("max_searches", 300))]: + yield soap_request("search", "SucheFirmaRequest", "SUCHEFIRMAREQUEST", { + "FIRMENWORTLAUT": search_term(row["name"]), "EXAKTESUCHE": "false", "SUCHBEREICH": 1, + "GERICHT": "", "RECHTSFORM": "", "RECHTSEIGENSCHAFT": "", "ORTNR": ""}, + meta={"org_id": str(row["id"]), "name": row["name"]}) + + def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]: + try: + hits = parse_search(response.body) + except SoapFault as exc: + ctx.stats["soap_faults"] += 1 + ctx.log.info("search %s: %s", response.request.meta["name"], exc) + return + match = unique_match(response.request.meta["name"], hits) + if match is None: + ctx.stats["no_unique_match" if hits else "not_found"] += 1 + return + ctx.stats["matched"] += 1 + yield OrgRecord(ref=OrgRef(ids={"politrack_org": response.request.meta["org_id"], "firmenbuch": match["fn"]}, + create=False), aliases=(match["name"],)) + + +@register +class FirmenbuchExtracts(Adapter): + spec = SPEC + name = "firmenbuch.extracts" + description = "Company register extracts: official names, and politicians' functions in companies" + schedule = "40 3 * * *" + queue = "bulk" + CHANGE_DAYS = 14 # how far back the change list is read when runs were missed + + def start(self, ctx: RunContext) -> Iterator[Request]: + if ctx.conn is None or not get_settings().justiz_hvd_api_key: + ctx.stats["no_api_key"] += 1 + return + today = date.today() + tracked = {r["value"] for r in ctx.conn.execute( + "SELECT value FROM identifier WHERE entity_type = 'organization' AND scheme = 'firmenbuch'").fetchall()} + done = _fetched(ctx.conn, self.name, "extract", "fn") & tracked + failed = {r["v"] for r in ctx.conn.execute( + """SELECT DISTINCT request->'meta'->>'fn' AS v FROM fetch_log WHERE adapter = %s + AND request->>'kind' = 'extract' AND status >= 400 AND fetched_at > now() - interval '30 days'""", + (self.name,)).fetchall()} + wanted = [ctx.params["fn"]] if ctx.params.get("fn") else sorted(tracked - done - failed) + if ctx.params.get("refresh") == "all": + wanted = sorted(tracked - failed) + ctx.stats["pending"] = len(wanted) + for fn in wanted[: int(ctx.params.get("max_extracts", 600))]: + yield self.extract(fn, today) + # Changes of the days since the last run: companies extracted before are fetched again + last = ctx.state.get("changes_until") + first = max(date.fromisoformat(last) + timedelta(days=1) if last else today - timedelta(days=1), + today - timedelta(days=self.CHANGE_DAYS)) + day = first + while done and day < today: + yield soap_request("changes", "VeraenderungenFirmaRequest", "VERAENDERUNGENFIRMAREQUEST", + {"VON": day.isoformat(), "BIS": day.isoformat()}, + meta={"day": day.isoformat(), "tracked": sorted(done)}) + day += timedelta(days=1) + ctx.state.set("changes_until", (today - timedelta(days=1)).isoformat()) + + @staticmethod + def extract(fn: str, on: date) -> Request: + return soap_request("extract", "v2/AuszugRequest", "AUSZUG_V2_REQUEST", + {"FNR": fn, "STICHTAG": on.isoformat(), "UMFANG": "Kurzinformation"}, meta={"fn": fn}) + + def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]: + kind = response.request.kind + try: + if kind == "changes": + changed = parse_changes(response.body) & set(response.request.meta["tracked"]) + ctx.stats["changed_companies"] += len(changed) + for fn in sorted(changed): + yield self.extract(fn, date.today()) + return + company = parse_extract(response.body) + except SoapFault as exc: + ctx.stats["soap_faults"] += 1 + ctx.log.info("%s %s: %s", kind, response.request.meta.get("fn") or response.request.meta.get("day"), exc) + return + yield from self.records(ctx, company, response.request.meta["fn"]) + + def records(self, ctx: RunContext, company: dict[str, Any], fn: str) -> Iterator[Any]: + name = company["name"] or f"FN {fn_display(fn)}" + org = OrgRef(ids={"firmenbuch": fn}, name=company["name"] or None, kind="company", create=False) + if company["name"]: + yield OrgRecord(ref=org, aliases=(company["name"],)) + evidence_title = f"Firmenbuch: {name} (FN {fn_display(fn)}), Stichtag {company['as_of'] or ''}".strip() + for f in company["functions"]: + if f["organization"]: + ctx.stats["officers_not_persons"] += 1 # e.g. a holding company as shareholder + continue + if not (f["given"] and f["surname"] and f["birth_date"]): + ctx.stats["officers_incomplete"] += 1 + continue + person_name = f"{f['given']} {f['surname']}" + label_en = FUNCTIONS_EN.get(f["code"], f["label"]) + share = "" + if f["capital"] and f["code"] in {"GS", "KOM", "KP"}: + share = f" (Stammeinlage {f['currency'] or 'EUR'} {format_eur_de(f['capital'])})" + yield Claim( + claim_type="company_role", person=PersonRef(name=person_name, hints={ + "birth_date": f["birth_date"], "no_name_match": True}), + counterpart_org=org, valid_from=f["since"], valid_to=f["until"], + summary_de=f"{person_name}: {f['label']} bei {name}{share}", + summary_en=f"{person_name}: {label_en} of {name}", + data={"fn": fn, "function": f["code"], "function_label": f["label"], "detail": f["detail"], + "capital": f["capital"], "currency": f["currency"], "legal_form": company["legal_form"], + "seat": company["seat"], "as_of": company["as_of"]}, + evidence=[Evidence(url=f"{URL}#FN{fn}", doc_type="register_entry", title=evidence_title, + locator=f"FN {fn_display(fn)} {f['code']} {f['pnr']}")], + key=("firmenbuch", fn, f["code"], f["pnr"]), + ) + + +@register +class FirmenbuchStatus(Enricher): + """The extract lists current functions only: a company role that a newer extract of the same company no longer + lists has ended (end date = date of that extract).""" + + spec = DERIVED + name = "enrich.firmenbuch" + description = "Close company roles that the latest Firmenbuch extract no longer lists" + schedule = "30 6 * * *" + + def run(self, ctx: RunContext) -> None: + closed = ctx.conn.execute( + """WITH latest AS ( + SELECT request->'meta'->>'fn' AS fn, max(fetched_at) AS fetched_at FROM fetch_log + WHERE adapter = 'firmenbuch.extracts' AND request->>'kind' = 'extract' AND status = 200 + GROUP BY 1) + UPDATE claim c SET valid_to = l.fetched_at::date, updated_at = now(), + data = c.data || '{"ended": "no longer listed in the register extract"}'::jsonb + FROM latest l + WHERE c.created_by = 'firmenbuch.extracts' AND c.claim_type = 'company_role' AND c.valid_to IS NULL + AND c.data->>'fn' = l.fn AND c.updated_at < l.fetched_at - interval '1 hour'""").rowcount + ctx.stats["closed"] = closed diff --git a/backend/politrack/text.py b/backend/politrack/text.py index 6e53324..0fed641 100644 --- a/backend/politrack/text.py +++ b/backend/politrack/text.py @@ -63,9 +63,10 @@ def normalize_org_name(name: str) -> str: def firmenbuch_number(value: str | None) -> str | None: - """'FN 306527 a', 'FN306527a', '306527a' -> '306527a' (Austrian company register number, normalised).""" + """'FN 306527 a', 'FN306527a', '306527a', '068616g' -> '306527a', '68616g' (Austrian company register number, + normalised: no leading zeros, lower-case check letter).""" m = re.fullmatch(r"\s*(?:FN\s*)?(\d{1,6})\s?([a-zA-Z])\s*", value or "", re.IGNORECASE) - return f"{m.group(1)}{m.group(2).lower()}" if m else None + return f"{int(m.group(1))}{m.group(2).lower()}" if m and int(m.group(1)) else None def format_eur_de(amount: object) -> str: diff --git a/backend/tests/fixtures/europarl.meps/meps.expected.json b/backend/tests/fixtures/europarl.meps/meps.expected.json index 1ba8842..e108f7f 100644 --- a/backend/tests/fixtures/europarl.meps/meps.expected.json +++ b/backend/tests/fixtures/europarl.meps/meps.expected.json @@ -27,6 +27,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -45,6 +46,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -89,6 +91,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -107,6 +110,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -151,6 +155,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -169,6 +174,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -213,6 +219,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -231,6 +238,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -275,6 +283,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -293,6 +302,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -337,6 +347,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -355,6 +366,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -399,6 +411,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -417,6 +430,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", @@ -461,6 +475,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "mep", @@ -479,6 +494,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "declarations", diff --git a/backend/tests/fixtures/europarl.votes/meetings.expected.json b/backend/tests/fixtures/europarl.votes/meetings.expected.json index fe2a5ab..6fa6313 100644 --- a/backend/tests/fixtures/europarl.votes/meetings.expected.json +++ b/backend/tests/fixtures/europarl.votes/meetings.expected.json @@ -2,6 +2,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "results", @@ -22,6 +23,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "results", diff --git a/backend/tests/fixtures/europarl.votes/results.expected.json b/backend/tests/fixtures/europarl.votes/results.expected.json index 26f0c97..da70d92 100644 --- a/backend/tests/fixtures/europarl.votes/results.expected.json +++ b/backend/tests/fixtures/europarl.votes/results.expected.json @@ -2,6 +2,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "decisions", diff --git a/backend/tests/fixtures/parlament.items/immunity.expected.json b/backend/tests/fixtures/parlament.items/immunity.expected.json index 0e56ac3..cca3c0f 100644 --- a/backend/tests/fixtures/parlament.items/immunity.expected.json +++ b/backend/tests/fixtures/parlament.items/immunity.expected.json @@ -2,6 +2,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": null, "kind": "immunity_report", diff --git a/backend/tests/fixtures/parlament.persons/person_detail.expected.json b/backend/tests/fixtures/parlament.persons/person_detail.expected.json index 04e93f4..388081b 100644 --- a/backend/tests/fixtures/parlament.persons/person_detail.expected.json +++ b/backend/tests/fixtures/parlament.persons/person_detail.expected.json @@ -663,6 +663,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": { "PAD_INTERN": [ @@ -682,6 +683,7 @@ { "__type__": "Request", "conditional": true, + "data": null, "headers": null, "json": { "PAD_INTERN": [ diff --git a/backend/tests/fixtures/social.x_deletions/lookup.expected.json b/backend/tests/fixtures/social.x_deletions/lookup.expected.json index 95ed66b..730eac7 100644 --- a/backend/tests/fixtures/social.x_deletions/lookup.expected.json +++ b/backend/tests/fixtures/social.x_deletions/lookup.expected.json @@ -9,6 +9,7 @@ { "__type__": "Request", "conditional": false, + "data": null, "headers": null, "json": null, "kind": "wayback", diff --git a/backend/tests/test_firmenbuch.py b/backend/tests/test_firmenbuch.py new file mode 100644 index 0000000..cd50d81 --- /dev/null +++ b/backend/tests/test_firmenbuch.py @@ -0,0 +1,120 @@ +"""Firmenbuch HVD parsers, on responses shaped like the real service (November 2026). The private co-director of +the real extract is replaced by a fictional person and the address is removed.""" + +from datetime import date + +import pytest + +from politrack.core import RunContext +from politrack.core.adapter import Request, StateStore +from politrack.sources import firmenbuch as F +from politrack.text import firmenbuch_number + +NSDECL = ('xmlns:env="http://www.w3.org/2003/05/soap-envelope" ' + 'xmlns:ns6="ns://firmenbuch.justiz.gv.at/Abfrage/v2/AuszugResponse" ' + 'xmlns:ns14="ns://firmenbuch.justiz.gv.at/Abfrage/SucheFirmaResponse" ' + 'xmlns:ns9="ns://firmenbuch.justiz.gv.at/Abfrage/VeraenderungenFirmaResponse"') + +EXTRACT = f""" + + + Alter Name GmbH + 25 PersonaldienstleistungsgesmbH + + Musterstraße1 + + Salzburg + GES + Gesellschaft mit beschränkter Haftung + + + 20080215 + vertritt seit 15.02.2008 selbständig + + 20080215 + vertritt seit 15.02.2008 selbständig + + 35000EUR + + + 20090101 + Max + Muster19700101 + Tanja + Graf19750507 + + Muster Holding GmbH + Eva + Ehemalig19800202 +""".encode() + +SEARCH = f""" +068616gSalzburger Parkgaragen Gesellschaft +m.b.H.SalzburgGES +Gesellschaft mit beschränkter Haftung +1agelöscht +Salzburger Parkgaragen Gesellschaft m.b.H. +2bSalzburger Parkgaragen Betriebs GmbH +""".encode() + +FAULT = b""" +env:Receiver +Der Parameter "UMFANG" fehlt oder ist ung\xc3\xbcltig +""" + + +def test_register_numbers_are_normalised_without_leading_zeros(): + assert firmenbuch_number("068616g") == firmenbuch_number("FN 68616 G") == "68616g" + assert firmenbuch_number("0a") is None + assert F.fn_display("306527a") == "306527 a" + + +def test_extract_reads_current_functions_but_no_addresses(): + company = F.parse_extract(EXTRACT) + assert (company["fn"], company["name"], company["seat"], company["legal_form"], company["as_of"]) == ( + "306527a", "25 PersonaldienstleistungsgesmbH", "Salzburg", "Gesellschaft mit beschränkter Haftung", "2026-11-18") + assert "Musterstraße" not in repr(company) + funcs = {f["pnr"]: f for f in company["functions"]} + assert set(funcs) == {"A", "C", "D"} # E's function has ended (AUFRECHT=false) + assert (funcs["C"]["given"], funcs["C"]["surname"], funcs["C"]["birth_date"], funcs["C"]["since"]) == ( + "Tanja", "Graf", date(1975, 5, 7), date(2008, 2, 15)) + assert funcs["C"]["label"] == "Geschäftsführer/in (handelsrechtlich)" + assert funcs["D"]["organization"] == "Muster Holding GmbH" and funcs["D"]["capital"] == 35000.0 + + +def test_extract_records_match_people_only_by_birth_date(): + ctx = RunContext(adapter="firmenbuch.extracts", spec=F.SPEC, state=StateStore(None, "firmenbuch.extracts")) + records = list(F.FirmenbuchExtracts().records(ctx, F.parse_extract(EXTRACT), "306527a")) + claims = [r for r in records if getattr(r, "claim_type", None) == "company_role"] + assert len(claims) == 2 and ctx.stats["officers_not_persons"] == 1 + graf = next(c for c in claims if c.person.name == "Tanja Graf") + assert graf.person.hints == {"birth_date": date(1975, 5, 7), "no_name_match": True} + assert graf.summary_de == "Tanja Graf: Geschäftsführer/in (handelsrechtlich) bei 25 PersonaldienstleistungsgesmbH" + assert graf.summary_en == "Tanja Graf: managing director of 25 PersonaldienstleistungsgesmbH" + assert graf.key == ("firmenbuch", "306527a", "GF", "C") and graf.valid_from == date(2008, 2, 15) + assert graf.counterpart_org.ids == {"firmenbuch": "306527a"} and not graf.counterpart_org.create + + +def test_search_accepts_only_one_current_entry_with_the_same_name(): + hits = F.parse_search(SEARCH) + assert hits[0] == {"fn": "68616g", "name": "Salzburger Parkgaragen Gesellschaft m.b.H.", "seat": "Salzburg", + "status": None, "legal_form": "Gesellschaft mit beschränkter Haftung"} + assert F.unique_match("Salzburger Parkgaragen Gesellschaft m.b.H", hits)["fn"] == "68616g" # deleted one ignored + assert F.unique_match("Salzburger Parkgaragen", hits)["fn"] == "68616g" # declarations often omit the legal form + twins = hits + [{"fn": "3c", "name": "Salzburger Parkgaragen GmbH", "seat": "Hallein", "status": None, + "legal_form": None}] + assert F.unique_match("Salzburger Parkgaragen GmbH", twins) is None # two current companies: never guess + assert F.search_term("Salzburger Parkgaragen Gesellschaft m.b.H.") == "Salzburger Parkgaragen" + assert F.search_term("„Wiener Städtische“ Versicherung AG Vienna Insurance Group") == "Wiener Städtische Versicherung" + assert F.search_term("AG") == "" + + +def test_faults_and_requests(): + with pytest.raises(F.SoapFault, match="UMFANG"): + F.parse_extract(FAULT) + a = F.FirmenbuchExtracts.extract("306527a", date(2026, 11, 18)) + b = F.FirmenbuchExtracts.extract("68616g", date(2026, 11, 18)) + assert a.method == "POST" and b"306527a" in a.data and a.fingerprint != b.fingerprint + assert "X-API-KEY" not in repr(a.describe()) # the token is never archived + assert b"&" in F.envelope("SucheFirmaRequest", "SUCHEFIRMAREQUEST", {"FIRMENWORTLAUT": "A & B"}) + assert Request(url="x").fingerprint == Request(url="x", data=None).fingerprint diff --git a/docs/contributing/adapters.md b/docs/contributing/adapters.md index 2940720..30a99f8 100644 --- a/docs/contributing/adapters.md +++ b/docs/contributing/adapters.md @@ -193,6 +193,8 @@ PersonRef(ids={"wikidata": "Q78869"}, name="Alexander Van der Bellen") PersonRef(name="Leonore Gewessler") # exact alias match (titles stripped) PersonRef(hints={"surname_in_body": "nationalrat", "on": date(2024, 3, 1)}, name="Kickl") # roll calls PersonRef(hints={"office": "Bundesministerin für Justiz", "on": date(2025, 6, 17)}) # office holder +PersonRef(name="Tanja Graf", hints={"birth_date": date(1975, 5, 7), "no_name_match": True}) # register entries: + # known persons only, never anyone else OrgRef(slug="oevp") # seeded organisations OrgRef(ids={"firmenbuch": "123456a"}, name="Muster GmbH", kind="company") # created if unknown OrgRef(name="ÖVP", kind="party", create=False) # match only, never create diff --git a/docs/data-model.md b/docs/data-model.md index 25b38e8..5e30a94 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -37,7 +37,7 @@ run, state, app_user operations | `parlament` | person | Parliament person id (PAD) – `parlament.gv.at/person/` | | `wikidata` | person, org | Wikidata QID | | `ep` | person | European Parliament MEP id | -| `firmenbuch` | org | Austrian company register number (FN), normalised `306527a` (`text.firmenbuch_number`) – from side-job declarations, procurement, party holdings | +| `firmenbuch` | org | Austrian company register number (FN), normalised `306527a` without leading zeros (`text.firmenbuch_number`) – from side-job declarations, procurement, party holdings and the register search (`firmenbuch.search`) | | `zvr` | org | Austrian association register number (ZVR) – from party reports (affiliated organisations) | | `uid` | org | VAT id (ATU…) | | `rtr` | org | legal entity id in the RTR media-transparency data | @@ -59,6 +59,7 @@ counterpart (`counterpart_person_id`, `counterpart_org_id`), time (`occurred_at` | `donation` | `money_flow` | Rechnungshof donation lists, party reports | | `money_flow` | `money_flow` | procurement, RTR media transparency, party funding, political ads | | `side_job` | – (`data`, counterpart org) | parliament declarations | +| `company_role` | – (`data.function`, `data.fn`, counterpart = company) | Firmenbuch extracts (`firmenbuch.extracts`); ended when a newer extract no longer lists it (`enrich.firmenbuch`) | | `statement` | `statement` (context, platform, url, excerpt) | speeches, social posts | | `appearance`, `meeting`, `travel` | `event_participant` → `event` | calendar, hearings, Council of Ministers, `enrich.events`, EC meetings | | `legal_proceeding` | `legal_proceeding` (stage, offense, authority) | immunity reports, `enrich.legal` (reviewed) | diff --git a/docs/investigative-data.md b/docs/investigative-data.md index 4374936..bc72cb9 100644 --- a/docs/investigative-data.md +++ b/docs/investigative-data.md @@ -15,7 +15,7 @@ value per effort. "Status" refers to this project: ✅ done · 🟡 next · ⛔ | **EU agricultural subsidies** per recipient | EU-mandated transparency database (AMA) | Farmer-politicians and their associations | 🟡 | | COVID aid (COFAG) large recipients | Published lists | Companies close to parties that received aid | 🟡 | | Political **ad spending** online | Meta Ad Library API (verified developer account), Google Political Ads Transparency (public BigQuery dataset) | Spend per party/politician, targeting, timing before elections | ✅ `ads.google` (public bundle), `ads.meta` (token) | -| Company roles (management, supervisory boards, shareholdings) | Firmenbuch (fee per query; the status of free EU "high-value dataset" access in Austria is unclear) | Revolving door, conflicts of interest, donor networks | 🔍 (until free bulk access is confirmed) | +| Company roles (management, supervisory boards, shareholdings) | Firmenbuch, free JustizOnline high-value-dataset service (API token) | Revolving door, conflicts of interest, donor networks | ✅ `firmenbuch.extracts` (functions of persons already in the database) | | Land register (*Grundbuch*) | Fee per query | Property deals involving politicians | 🔍 | ## 2. Influence & access @@ -66,4 +66,5 @@ value per effort. "Status" refers to this project: ✅ done · 🟡 next · ⛔ * **Corroboration**: the same fact from independent sources is merged and shown as confirmed: ✅ * **Follow the money**: per person, the organisations they are connected to (side jobs, careers, party, meetings) and those organisations' donations, contracts, ads and funding: ✅ (`/personen/?tab=money`, `/api/v1/persons//network`) * **Organisation pages**: money paid/received by kind, top counterparties, connected people: ✅ -* Next: a visual **network graph** and company roles (Firmenbuch – no free bulk access yet). +* **Company roles** from the Firmenbuch (`company_role`), also listed as connections: ✅ +* Next: a visual **network graph**. diff --git a/docs/roadmap.md b/docs/roadmap.md index c88c87d..3532085 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -64,7 +64,8 @@ Next.js frontend (de/en), Docker Compose for Unraid. **Quality** - [ ] Golden fixtures for every adapter (the framework and first cases are in place) -- [ ] Entity resolution for donors/companies via Firmenbuch numbers from procurement notices +- [x] Firmenbuch (HVD): register numbers for named companies, politicians' company functions (`firmenbuch.*`, 2026-11) +- [ ] Shareholders that are companies (holding chains) and donor/company resolution beyond exact names - [ ] Wayback Machine archiving of evidence URLs (`document.archive_url`) **Product** diff --git a/docs/sources.md b/docs/sources.md index 2767589..7cf11ca 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -60,7 +60,8 @@ Status: ✅ implemented (adapter name in `code`) · 🟡 planned · ⛔ delibera | AMA farm subsidies, EU state-aid register (TAM) | subsidy recipients | search interfaces | – | 🟡 not implemented yet (bulk access and terms still to be checked) | | Election results, preference votes | party results for Austria and the states; candidates' preference votes (only candidates who resolve to a known politician) | BMI XLSX (Bundeswahlbehörde) | official works; CC BY 4.0 on data.gv.at | ✅ `bmi.elections` (NR 2024, NR 2019, EU 2024); 🟡 earlier elections, NR 2019 state lists, Landtag and municipal elections | | Insolvency notices (Ediktsdatei) | companies tied to politicians | Justiz web application | terms to be checked before automating | 🟡 | -| Firmenbuch, Grundbuch, beneficial owners (WiEReG) | company roles, property | paid clearing houses; WiEReG public access restricted since the 2022 CJEU ruling | – | ⛔ cost and legal limits | +| Firmenbuch (company register) | register numbers of named companies; politicians' functions in companies (managing director, authorised signatory, board, shareholder) with start date and capital | JustizOnline high-value-dataset SOAP service (free, personal API token `POLITRACK_JUSTIZ_HVD_API_KEY`) | HVD (EU Implementing Regulation 2023/138) | ✅ `firmenbuch.search`, `firmenbuch.extracts`, `enrich.firmenbuch`. Officers are matched only by exact birth date and name among persons already known; private individuals are never stored and raw responses are not archived | +| Grundbuch, beneficial owners (WiEReG) | property, beneficial ownership | paid clearing houses; WiEReG public access restricted since the 2022 CJEU ruling | – | ⛔ cost and legal limits | | Criminal record (*Strafregister*) | – | not public | – | ⛔ does not exist publicly | ## NGOs & aggregators diff --git a/web/messages/de.json b/web/messages/de.json index 1b93b0f..d85d1cd 100644 --- a/web/messages/de.json +++ b/web/messages/de.json @@ -276,6 +276,7 @@ "meeting": "Treffen", "travel": "Reise", "side_job": "Nebentätigkeit", + "company_role": "Firmenbuch", "legal_proceeding": "Verfahren", "lobbying": "Lobbying", "media_mention": "Medienbericht", @@ -569,6 +570,7 @@ "received": "erhalten", "via": { "side_job": "Nebentätigkeit", + "company_role": "Firmenbuch", "career": "Werdegang", "meeting": "Treffen", "role": "Funktion", diff --git a/web/messages/en.json b/web/messages/en.json index 33ed5dd..a712649 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -241,6 +241,7 @@ "meeting": "Meeting", "travel": "Travel", "side_job": "Side job", + "company_role": "Company register", "legal_proceeding": "Proceedings", "lobbying": "Lobbying", "media_mention": "Media report", @@ -534,6 +535,7 @@ "received": "received", "via": { "side_job": "side job", + "company_role": "company register", "career": "career", "meeting": "meeting", "role": "office", diff --git a/web/src/app/[locale]/personen/[slug]/page.tsx b/web/src/app/[locale]/personen/[slug]/page.tsx index de5ddae..e41aba8 100644 --- a/web/src/app/[locale]/personen/[slug]/page.tsx +++ b/web/src/app/[locale]/personen/[slug]/page.tsx @@ -23,13 +23,13 @@ import {isCurrent, roleLabel} from '@/lib/roles'; // Claim types per tab (also used for the tab counts); tabs with their own component are listed in CUSTOM_TABS. const TABS = { overview: ['statement', 'vote', 'donation', 'side_job', 'media_mention', 'meeting', 'travel', 'legal_proceeding', - 'career', 'government_decision', 'declaration', 'election_result'], + 'career', 'government_decision', 'declaration', 'election_result', 'company_role'], timeline: [], votes: ['vote'], travel: ['travel', 'meeting', 'appearance', 'government_decision'], statements: ['statement', 'parliamentary_question'], social: [], - money: ['side_job', 'donation', 'money_flow', 'lobbying', 'declaration', 'ownership'], + money: ['side_job', 'company_role', 'donation', 'money_flow', 'lobbying', 'declaration', 'ownership'], media: ['media_mention', 'career', 'wiki_edit'], legal: ['legal_proceeding'] } satisfies Record; diff --git a/web/src/components/ClaimDetails.tsx b/web/src/components/ClaimDetails.tsx index e7edea1..50eba84 100644 --- a/web/src/components/ClaimDetails.tsx +++ b/web/src/components/ClaimDetails.tsx @@ -111,6 +111,7 @@ const DETAILS: Partial> = { money_flow: [money], party_finance: [partyFinance, money], side_job: [counterpart, money], + company_role: [counterpart], career: [counterpart], meeting: [counterpart], lobbying: [counterpart], diff --git a/web/src/components/badges.tsx b/web/src/components/badges.tsx index fb2ed0d..4d88a7e 100644 --- a/web/src/components/badges.tsx +++ b/web/src/components/badges.tsx @@ -27,7 +27,8 @@ const TYPE_ICONS: Partial> = { declaration: 'document', ownership: 'link', affiliation: 'link', - election_result: 'vote' + election_result: 'vote', + company_role: 'briefcase' }; export async function TypeLabel({type}: {type: ClaimType}) { diff --git a/web/src/lib/api-types.ts b/web/src/lib/api-types.ts index de91c70..b0a0eee 100644 --- a/web/src/lib/api-types.ts +++ b/web/src/lib/api-types.ts @@ -22,7 +22,7 @@ export type CalendarEvent = { export type Claim = { id: number; - claim_type: 'role' | 'vote' | 'donation' | 'money_flow' | 'statement' | 'appearance' | 'meeting' | 'travel' | 'side_job' | 'legal_proceeding' | 'lobbying' | 'media_mention' | 'career' | 'parliamentary_question' | 'government_decision' | 'wiki_edit' | 'declaration' | 'ownership' | 'affiliation' | 'party_finance' | 'election_result' | 'other'; + claim_type: 'role' | 'vote' | 'donation' | 'money_flow' | 'statement' | 'appearance' | 'meeting' | 'travel' | 'side_job' | 'legal_proceeding' | 'lobbying' | 'media_mention' | 'career' | 'parliamentary_question' | 'government_decision' | 'wiki_edit' | 'declaration' | 'ownership' | 'affiliation' | 'party_finance' | 'election_result' | 'company_role' | 'other'; summary_de: string; summary_en: string | null; occurred_at: string | null;