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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user