1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const BASE = 'https://oda.ft.dk/api';
18
19
20
21
22
23
24
25
26
27
28export const MAX_TOP = 100;
29
30
31export const CASE_TYPES = {
32 1: 'UMF-del',
33 2: 'Forespørgsel',
34 3: 'Lovforslag',
35 4: 'Alm. del',
36 5: 'Beslutningsforslag',
37 6: 'Rådsmøde',
38 7: 'Kommissionsforslag',
39 8: 'Aktstykke',
40 9: 'Forslag til vedtagelse',
41 10: '§ 20-spørgsmål',
42 11: 'Redegørelse',
43 12: 'Indkaldelse af stedfortræder',
44 13: 'Statsrevisorerne',
45};
46
47
48function odataString(value) {
49 return `'${String(value).replace(/'/g, "''")}'`;
50}
51
52
53export function odataDateTime(value) {
54 const raw = String(value).trim();
55 const dateOnly = raw.match(/^(\d{4}-\d{2}-\d{2})$/);
56
57
58 const stamp = dateOnly
59 ? `${dateOnly[1]}T00:00:00`
60 : raw.replace(/\.\d+/, '').replace(/(Z|[+-]\d{2}:\d{2})$/, '');
61 if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(stamp)) {
62 throw new Error(`Cannot read "${value}" as a date. Use YYYY-MM-DD.`);
63 }
64 return `datetime'${stamp}'`;
65}
66
67export function daysAgoIso(days) {
68 return new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
69}
70
71
72function intList(values, field) {
73 const ints = (values ?? [])
74 .map((v) => Number(v))
75 .filter((v) => Number.isInteger(v) && v >= 0);
76 if (!ints.length) return null;
77 return `(${ints.map((v) => `${field} eq ${v}`).join(' or ')})`;
78}
79
80
81
82
83export function buildCaseFilter({
84 updatedSince = null,
85 updatedUntil = null,
86 caseTypeIds = [],
87 statusIds = [],
88 periodIds = [],
89 titleContains = null,
90} = {}) {
91 const clauses = [];
92
93 if (updatedSince) clauses.push(`opdateringsdato gt ${odataDateTime(updatedSince)}`);
94 if (updatedUntil) clauses.push(`opdateringsdato lt ${odataDateTime(updatedUntil)}`);
95
96 const types = intList(caseTypeIds, 'typeid');
97 if (types) clauses.push(types);
98
99 const statuses = intList(statusIds, 'statusid');
100 if (statuses) clauses.push(statuses);
101
102 const periods = intList(periodIds, 'periodeid');
103 if (periods) clauses.push(periods);
104
105 if (titleContains) {
106 clauses.push(`substringof(${odataString(titleContains)}, titel)`);
107 }
108
109 return clauses.join(' and ');
110}
111
112
113export function toIso(value) {
114 if (!value) return null;
115 const match = String(value).match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
116 if (match) return `${match[1]}T${match[2]}Z`;
117 const dateOnly = String(value).match(/^(\d{4}-\d{2}-\d{2})/);
118 return dateOnly ? dateOnly[1] : String(value);
119}
120
121function cleanText(value) {
122 if (value == null) return null;
123 const text = String(value).replace(/\s+/g, ' ').trim();
124 return text.length ? text : null;
125}
126
127
128
129
130
131export function normalizeCase(row, { includeDocuments = false, maxDocuments = 20 } = {}) {
132 const out = {
133 caseId: row.id ?? null,
134 caseNumber: cleanText(row.nummer),
135 title: cleanText(row.titel),
136 shortTitle: cleanText(row.titelkort),
137 typeId: row.typeid ?? null,
138 typeName: cleanText(row.Sagstype?.type) ?? CASE_TYPES[row.typeid] ?? null,
139 statusId: row.statusid ?? null,
140 statusName: cleanText(row.Sagsstatus?.status) ?? null,
141 categoryId: row.kategoriid ?? null,
142 periodId: row.periodeid ?? null,
143 summary: cleanText(row.resume),
144 voteConclusion: cleanText(row.afstemningskonklusion),
145 decision: cleanText(row.afgørelse),
146 decisionDate: toIso(row.afgørelsesdato),
147 lawNumber: cleanText(row.lovnummer),
148 lawNumberDate: toIso(row.lovnummerdato),
149 updatedAt: toIso(row.opdateringsdato),
150 retsinformationUrl: cleanText(row.retsinformationsurl),
151
152 odaUrl: row.id == null ? null : `${BASE}/Sag(${row.id})`,
153 };
154
155 if (includeDocuments) {
156 const links = Array.isArray(row.SagDokument) ? row.SagDokument : [];
157 out.documents = links
158 .slice(0, maxDocuments)
159 .map((link) => {
160 const doc = link.Dokument ?? {};
161 return {
162 documentId: doc.id ?? link.dokumentid ?? null,
163 title: cleanText(doc.titel),
164 typeId: doc.typeid ?? null,
165 date: toIso(doc.dato),
166 receivedDate: toIso(doc.modtagelsesdato),
167 releasedDate: toIso(doc.frigivelsesdato ?? link.frigivelsesdato),
168 questionTitle: cleanText(doc.spørgsmålstitel),
169 questionText: cleanText(doc.spørgsmålsordlyd),
170 attachmentNumber: link.bilagsnummer ?? null,
171 roleId: link.rolleid ?? null,
172 odaUrl: doc.id == null ? null : `${BASE}/Dokument(${doc.id})`,
173 };
174 })
175 .filter((d) => d.documentId != null);
176 out.documentCount = out.documents.length;
177 }
178
179 return out;
180}
181
182
183
184
185
186export async function fetchCases({
187 filter = '',
188 top = 50,
189 skip = 0,
190 orderBy = 'opdateringsdato desc',
191 includeDocuments = false,
192 withCount = false,
193 log = console,
194 fetchImpl = fetch,
195 maxAttempts = 4,
196} = {}) {
197 const params = new URLSearchParams();
198 if (filter) params.set('$filter', filter);
199
200
201 params.set('$top', String(Math.min(top, MAX_TOP)));
202 if (skip) params.set('$skip', String(skip));
203 params.set('$orderby', orderBy);
204 params.set('$format', 'json');
205 if (withCount) params.set('$inlinecount', 'allpages');
206
207 const expand = ['Sagstype', 'Sagsstatus'];
208 if (includeDocuments) expand.push('SagDokument/Dokument');
209 params.set('$expand', expand.join(','));
210
211 const url = `${BASE}/Sag?${params.toString()}`;
212
213 let lastError;
214 for (let attempt = 1; attempt <= maxAttempts; attempt++) {
215 try {
216 const res = await fetchImpl(url, { headers: { accept: 'application/json' } });
217
218 if (res.status === 429 || res.status >= 500) {
219 throw new Error(`oda.ft.dk responded ${res.status}`);
220 }
221 if (!res.ok) {
222 const detail = await res.text().catch(() => '');
223 throw Object.assign(
224 new Error(
225 `oda.ft.dk rejected the request (${res.status}): ${detail.slice(0, 400)}`,
226 ),
227 { fatal: true },
228 );
229 }
230
231 const body = await res.json();
232 return {
233 rows: body.value ?? [],
234 total: body['odata.count'] == null ? null : Number(body['odata.count']),
235 url,
236 };
237 } catch (err) {
238 if (err.fatal || attempt === maxAttempts) throw err;
239 lastError = err;
240 const waitMs = 800 * 2 ** (attempt - 1);
241 log.warning?.(`Request to oda.ft.dk failed (${err.message}). Retrying in ${waitMs}ms.`);
242 await new Promise((resolve) => setTimeout(resolve, waitMs));
243 }
244 }
245 throw lastError;
246}
247
248export { BASE as ODA_BASE };