1"""Danish Annual Reports (CVR Regnskaber) — Apify Actor.
2
3Returns the index of published annual reports (regnskaber) for Danish companies
4from the official Erhvervsstyrelsen distribution endpoint. For each filing it
5returns the accounting period, publication timestamp, document type, and direct
6links to the PDF and machine-readable XBRL documents.
7
8This reads only stable, top-level index fields (it does NOT parse figures out of
9the XBRL), so it is robust and maintenance-free. No API key required.
10"""
11
12from __future__ import annotations
13
14import re
15
16import httpx
17try:
18 from . import _tier_prices
19except ImportError:
20 import _tier_prices
21from apify import Actor
22
23SEARCH_URL = "http://distribution.virk.dk/offentliggoerelser/_search"
24MAX_SIZE = 3000
25DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
26
27
28def _get(d, *path):
29 """Safe nested getter; returns None if any step is missing."""
30 cur = d
31 for key in path:
32 if not isinstance(cur, dict):
33 return None
34 cur = cur.get(key)
35 return cur
36
37
38def transform(source: dict) -> dict:
39 """Flatten one offentliggoerelse (_source) into a clean filing record.
40
41 Field paths confirmed against the official endpoint and two independent
42 open-source clients (cvrminer, XBRL-AI).
43 """
44 period = _get(source, "regnskab", "regnskabsperiode") or {}
45
46 pdf_url = None
47 xml_url = None
48 doc_type = None
49 for dok in source.get("dokumenter") or []:
50 if not isinstance(dok, dict):
51 continue
52 mime = dok.get("dokumentMimeType")
53 if mime == "application/pdf" and not pdf_url:
54 pdf_url = dok.get("dokumentUrl")
55 doc_type = doc_type or dok.get("dokumentType")
56 elif mime == "application/xml" and not xml_url:
57 xml_url = dok.get("dokumentUrl")
58 doc_type = doc_type or dok.get("dokumentType")
59
60 return {
61 "cvrNumber": source.get("cvrNummer"),
62 "offentliggoerelsestype": source.get("offentliggoerelsestype"),
63 "documentType": doc_type,
64 "periodStart": period.get("startDato"),
65 "periodEnd": period.get("slutDato"),
66 "publishedAt": source.get("offentliggoerelsesTidspunkt"),
67 "lastUpdated": source.get("sidstOpdateret"),
68 "isCorrection": source.get("omgoerelse"),
69 "regNumber": source.get("regNummer"),
70 "caseNumber": source.get("sagsNummer"),
71 "loadId": source.get("indlaesningsId"),
72 "loadedAt": source.get("indlaesningsTidspunkt"),
73 "pdfUrl": pdf_url,
74 "xbrlUrl": xml_url,
75 }
76
77
78def build_query(actor_input: dict):
79 """Build the ElasticSearch query body and resolved size."""
80 must = []
81
82 cvr = actor_input.get("cvrNumber")
83 if cvr is not None and str(cvr).strip():
84 digits = "".join(ch for ch in str(cvr) if ch.isdigit())
85 if digits:
86 must.append({"term": {"cvrNummer": int(digits)}})
87
88 from_date = (actor_input.get("fromDate") or "").strip()
89 to_date = (actor_input.get("toDate") or "").strip()
90 if from_date or to_date:
91
92
93
94 rng = {}
95 if from_date:
96 rng["gte"] = from_date
97 if to_date:
98 rng["lte"] = to_date
99 must.append({"range": {"offentliggoerelsesTidspunkt": rng}})
100
101 max_items = actor_input.get("maxItems") or 100
102 try:
103 max_items = int(max_items)
104 except (ValueError, TypeError):
105 max_items = 100
106 max_items = max(1, min(max_items, MAX_SIZE))
107
108
109 must.append({"term": {"offentliggoerelsestype": "regnskab"}})
110
111 body = {
112 "query": {"bool": {"must": must}},
113 "size": max_items,
114 "sort": [{"offentliggoerelsesTidspunkt": {"order": "desc"}}],
115 }
116 return body, max_items
117
118
119async def main() -> None:
120 async with Actor:
121 actor_input = await Actor.get_input() or {}
122
123 if not (actor_input.get("cvrNumber") or actor_input.get("fromDate") or actor_input.get("toDate")):
124
125 actor_input = {**actor_input, "cvrNumber": "24256790"}
126
127 for field in ("fromDate", "toDate"):
128 value = (actor_input.get(field) or "").strip()
129 if value and not DATE_RE.match(value):
130 await Actor.fail(status_message=f"{field} must be a date like 2026-11-20 (got '{value}').")
131 return
132
133 body, max_items = build_query(actor_input)
134 Actor.log.info(f"Querying annual reports (cvr={actor_input.get('cvrNumber')}, "
135 f"from={actor_input.get('fromDate')}, to={actor_input.get('toDate')}, size={max_items}).")
136
137 headers = {
138 "Accept": "application/json; charset=utf-8",
139 "Content-Type": "application/json",
140 "User-Agent": "apify-danish-annual-reports (+https://apify.com)",
141 }
142
143 hits = []
144 try:
145 async with httpx.AsyncClient(timeout=60, headers=headers) as client:
146 resp = await client.post(SEARCH_URL, json=body)
147 resp.raise_for_status()
148 data = resp.json()
149 hits = _get(data, "hits", "hits") or []
150 total = _get(data, "hits", "total")
151 Actor.log.info(f"Found {total if total is not None else len(hits)} matching filings; processing {len(hits)}.")
152 except httpx.HTTPStatusError as exc:
153 Actor.log.error(f"Erhvervsstyrelsen endpoint returned HTTP {exc.response.status_code}.")
154 except Exception as exc:
155 Actor.log.error(f"Failed to fetch annual reports: {exc}")
156
157 count = 0
158 for hit in hits:
159 source = hit.get("_source") if isinstance(hit, dict) else None
160 if not isinstance(source, dict):
161 continue
162 await Actor.push_data(transform(source))
163 count += 1
164
165 Actor.log.info(f"Done. Returned {count} filing(s).")