Firmenbuch (JustizOnline HVD): register numbers and politicians' company functions
- firmenbuch.search: register number for companies linked to people/parties, only for one current register entry with the same name - firmenbuch.extracts: current extracts; officers/shareholders who are politicians in the database (exact birth date + name, new person hint birth_date) become company_role claims; nobody else is stored, raw responses are not archived, addresses never read; the register's daily change list triggers re-extracts - enrich.firmenbuch closes roles a newer extract no longer lists - Request.data (raw body, part of the fingerprint); SOAP faults are not retried - firmenbuch_number drops leading zeros; migration 0009 adds company_role and aligns stored numbers; internal politrack_org ids are no longer stored as identifiers - company_role in API types, MCP docs, person money tab, connections, labels Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
68be25a953
commit
10c677ca70
30 files changed
+597
-20
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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';
|
||||
@@ -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"]
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"<r:{k}>{escape('' if v is None else str(v))}</r:{k}>" for k, v in fields.items())
|
||||
return (f'<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:r="{NS}{service}">'
|
||||
f"<soap:Header/><soap:Body><r:{root}>{body}</r:{root}></soap:Body></soap:Envelope>").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
|
||||
@@ -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:
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
{
|
||||
"__type__": "Request",
|
||||
"conditional": true,
|
||||
"data": null,
|
||||
"headers": null,
|
||||
"json": null,
|
||||
"kind": "decisions",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
{
|
||||
"__type__": "Request",
|
||||
"conditional": true,
|
||||
"data": null,
|
||||
"headers": null,
|
||||
"json": null,
|
||||
"kind": "immunity_report",
|
||||
|
||||
@@ -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": [
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
{
|
||||
"__type__": "Request",
|
||||
"conditional": false,
|
||||
"data": null,
|
||||
"headers": null,
|
||||
"json": null,
|
||||
"kind": "wayback",
|
||||
|
||||
@@ -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"""<env:Envelope {NSDECL}><env:Header/><env:Body>
|
||||
<ns6:AUSZUG_V2_RESPONSE ns6:FNR="306527 a" ns6:STICHTAG="2026-11-18" ns6:UMFANG="Kurzinformation">
|
||||
<ns6:FIRMA>
|
||||
<ns6:FI_DKZ02 ns6:AUFRECHT="false" ns6:VNR="000"><ns6:BEZEICHNUNG>Alter Name GmbH</ns6:BEZEICHNUNG></ns6:FI_DKZ02>
|
||||
<ns6:FI_DKZ02 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:BEZEICHNUNG>25 PersonaldienstleistungsgesmbH</ns6:BEZEICHNUNG>
|
||||
</ns6:FI_DKZ02>
|
||||
<ns6:FI_DKZ03 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:STRASSE>Musterstraße</ns6:STRASSE><ns6:PLZ>1</ns6:PLZ>
|
||||
</ns6:FI_DKZ03>
|
||||
<ns6:FI_DKZ06 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:SITZ>Salzburg</ns6:SITZ></ns6:FI_DKZ06>
|
||||
<ns6:FI_DKZ07 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:RECHTSFORM><ns6:CODE>GES</ns6:CODE>
|
||||
<ns6:TEXT>Gesellschaft mit beschränkter Haftung</ns6:TEXT></ns6:RECHTSFORM></ns6:FI_DKZ07>
|
||||
</ns6:FIRMA>
|
||||
<ns6:FUN ns6:FKEN="GF" ns6:FKENTEXT="GESCHÄFTSFÜHRER/IN (handelsrechtlich)" ns6:PNR=" A">
|
||||
<ns6:FU_DKZ10 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:DATVON>20080215</ns6:DATVON>
|
||||
<ns6:TEXT>vertritt seit 15.02.2008 selbständig</ns6:TEXT></ns6:FU_DKZ10></ns6:FUN>
|
||||
<ns6:FUN ns6:FKEN="GF" ns6:FKENTEXT="GESCHÄFTSFÜHRER/IN (handelsrechtlich)" ns6:PNR=" C">
|
||||
<ns6:FU_DKZ10 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:DATVON>20080215</ns6:DATVON>
|
||||
<ns6:TEXT>vertritt seit 15.02.2008 selbständig</ns6:TEXT></ns6:FU_DKZ10></ns6:FUN>
|
||||
<ns6:FUN ns6:FKEN="GS" ns6:FKENTEXT="GESELLSCHAFTER/IN" ns6:PNR=" D">
|
||||
<ns6:FU_DKZ10 ns6:AUFRECHT="true" ns6:VNR="002"><ns6:KAPITAL>35000</ns6:KAPITAL><ns6:WHR>EUR</ns6:WHR>
|
||||
</ns6:FU_DKZ10></ns6:FUN>
|
||||
<ns6:FUN ns6:FKEN="PR" ns6:FKENTEXT="PROKURIST/IN" ns6:PNR=" E">
|
||||
<ns6:FU_DKZ10 ns6:AUFRECHT="false" ns6:VNR="001"><ns6:DATVON>20090101</ns6:DATVON></ns6:FU_DKZ10></ns6:FUN>
|
||||
<ns6:PER ns6:PNR=" A"><ns6:PE_DKZ02 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:VORNAME>Max</ns6:VORNAME>
|
||||
<ns6:NACHNAME>Muster</ns6:NACHNAME><ns6:GEBURTSDATUM>19700101</ns6:GEBURTSDATUM></ns6:PE_DKZ02></ns6:PER>
|
||||
<ns6:PER ns6:PNR=" C"><ns6:PE_DKZ02 ns6:AUFRECHT="true" ns6:VNR="003"><ns6:VORNAME>Tanja</ns6:VORNAME>
|
||||
<ns6:NACHNAME>Graf</ns6:NACHNAME><ns6:GEBURTSDATUM>19750507</ns6:GEBURTSDATUM></ns6:PE_DKZ02></ns6:PER>
|
||||
<ns6:PER ns6:PNR=" D"><ns6:PE_DKZ02 ns6:AUFRECHT="true" ns6:VNR="002">
|
||||
<ns6:BEZEICHNUNG>Muster Holding GmbH</ns6:BEZEICHNUNG></ns6:PE_DKZ02></ns6:PER>
|
||||
<ns6:PER ns6:PNR=" E"><ns6:PE_DKZ02 ns6:AUFRECHT="true" ns6:VNR="001"><ns6:VORNAME>Eva</ns6:VORNAME>
|
||||
<ns6:NACHNAME>Ehemalig</ns6:NACHNAME><ns6:GEBURTSDATUM>19800202</ns6:GEBURTSDATUM></ns6:PE_DKZ02></ns6:PER>
|
||||
</ns6:AUSZUG_V2_RESPONSE></env:Body></env:Envelope>""".encode()
|
||||
|
||||
SEARCH = f"""<env:Envelope {NSDECL}><env:Header/><env:Body><ns14:SUCHEFIRMARESPONSE>
|
||||
<ns14:ERGEBNIS><ns14:FNR>068616g</ns14:FNR><ns14:STATUS/><ns14:NAME>Salzburger Parkgaragen Gesellschaft</ns14:NAME>
|
||||
<ns14:NAME>m.b.H.</ns14:NAME><ns14:SITZ>Salzburg</ns14:SITZ><ns14:RECHTSFORM><ns14:CODE>GES</ns14:CODE>
|
||||
<ns14:TEXT>Gesellschaft mit beschränkter Haftung</ns14:TEXT></ns14:RECHTSFORM></ns14:ERGEBNIS>
|
||||
<ns14:ERGEBNIS><ns14:FNR>1a</ns14:FNR><ns14:STATUS>gelöscht</ns14:STATUS>
|
||||
<ns14:NAME>Salzburger Parkgaragen Gesellschaft m.b.H.</ns14:NAME></ns14:ERGEBNIS>
|
||||
<ns14:ERGEBNIS><ns14:FNR>2b</ns14:FNR><ns14:STATUS/><ns14:NAME>Salzburger Parkgaragen Betriebs GmbH</ns14:NAME>
|
||||
</ns14:ERGEBNIS></ns14:SUCHEFIRMARESPONSE></env:Body></env:Envelope>""".encode()
|
||||
|
||||
FAULT = b"""<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Body><env:Fault>
|
||||
<env:Code><env:Value>env:Receiver</env:Value></env:Code><env:Reason>
|
||||
<env:Text xml:lang="de-AT">Der Parameter "UMFANG" fehlt oder ist ung\xc3\xbcltig</env:Text></env:Reason>
|
||||
</env:Fault></env:Body></env:Envelope>"""
|
||||
|
||||
|
||||
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"<r:FNR>306527a</r:FNR>" 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
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -37,7 +37,7 @@ run, state, app_user operations
|
||||
| `parlament` | person | Parliament person id (PAD) – `parlament.gv.at/person/<id>` |
|
||||
| `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) |
|
||||
|
||||
@@ -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/<slug>?tab=money`, `/api/v1/persons/<slug>/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**.
|
||||
+2
-1
@@ -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**
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<string, ClaimType[]>;
|
||||
|
||||
@@ -111,6 +111,7 @@ const DETAILS: Partial<Record<ClaimType, Renderer[]>> = {
|
||||
money_flow: [money],
|
||||
party_finance: [partyFinance, money],
|
||||
side_job: [counterpart, money],
|
||||
company_role: [counterpart],
|
||||
career: [counterpart],
|
||||
meeting: [counterpart],
|
||||
lobbying: [counterpart],
|
||||
|
||||
@@ -27,7 +27,8 @@ const TYPE_ICONS: Partial<Record<ClaimType, IconName>> = {
|
||||
declaration: 'document',
|
||||
ownership: 'link',
|
||||
affiliation: 'link',
|
||||
election_result: 'vote'
|
||||
election_result: 'vote',
|
||||
company_role: 'briefcase'
|
||||
};
|
||||
|
||||
export async function TypeLabel({type}: {type: ClaimType}) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user