The name search ignored the legal form, so "Huber GmbH & Co KG" (public contracts) was given the register number of "Huber GmbH" in Ebenfurth and thereby linked to that company's managing director. Fixed on the server by moving the number and the officer role to an organisation of their own. Commons register ids reuse firmenbuch_number(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
395 lines
20 KiB
Python
395 lines
20 KiB
Python
"""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 ""
|
|
|
|
|
|
PARTNERSHIP = re.compile(r"\b(kg|og|kommanditgesellschaft|offene gesellschaft|co\.?\s*kg)\b", re.IGNORECASE)
|
|
|
|
|
|
def is_partnership(name: str) -> bool:
|
|
"""KG / OG / GmbH & Co KG: a different legal entity from the GmbH of the same name (often its general partner)."""
|
|
return bool(PARTNERSHIP.search(name))
|
|
|
|
|
|
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, but a
|
|
partnership never matches a corporation: 'Huber GmbH & Co KG' is not 'Huber GmbH')."""
|
|
target = normalize_org_name(name)
|
|
same = [h for h in hits if h["fn"] and normalize_org_name(h["name"]) == target
|
|
and is_partnership(h["name"]) == is_partnership(name)]
|
|
current = [h for h in same if not h["status"]] or same
|
|
return current[0] if len(current) == 1 else None
|
|
|
|
|
|
# -- 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
|