Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2172 lines (2152 loc) · 138 KB
/
Copy pathscript.js
File metadata and controls
2172 lines (2152 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The explorer page (index.html): loading, filters, table, record panel, review notes and exports.
// Scoring and records come from the engine files loaded before it (tools/engine.cjs).
'use strict';
function startExplorer() {
const body = document.querySelector('#contracts');
const status = document.querySelector('#status');
const fileHelp = document.querySelector('#file-help');
const controls = Object.fromEntries(['filter-country', 'date-from', 'date-to', 'filter-buyer', 'filter-supplier', 'filter-procedure', 'search', 'minimum', 'flagged', 'official', 'adjudicated', 'investigation', 'indicator', 'legal', 'notice-context', 'assessment', 'sort', 'sector', 'project', 'group-by', 'min-score', 'review', 'verification'].map(id => [id, document.getElementById(id)]));
const datasetSelect = document.querySelector('#dataset');
// datasets.js; South Korea's coverage is relative to its host.
const datasets = Object.fromEntries(Object.entries(globalThis.DATASETS).map(([key, d]) =>
[key, d.remote === 'korea' ? { ...d, coverage: `${KOREA_BASE}/${d.coverage}` } : d]));
let datasetMetadata = {};
function renderDatasetDates(key) {
const dates = document.querySelector('#dataset-dates');
const notes = document.querySelector('#dataset-date-notes');
const metadata = globalThis.DatasetMetadata.formatEntries(key, datasetMetadata);
dates.replaceChildren(); notes.replaceChildren();
for (const field of metadata.fields) {
dates.append(element('dt', field.label), element('dd', field.value));
}
for (const note of metadata.notes) notes.append(element('li', note));
notes.hidden = metadata.notes.length === 0;
}
// Dataset-level provenance, so anyone can repeat the collection or check a row at its source.
function renderSources(selected) {
const panel = document.querySelector('#dataset-sources');
const body = document.querySelector('#sources-body');
body.replaceChildren();
panel.hidden = !selected.sources;
if (!selected.sources) return;
const s = selected.sources;
body.append(element('p', `Publisher: ${s.publisher}. Licence: ${s.licence}.`));
const list = element('ul');
for (const [label, url] of s.links) {
if (/API|schema|licence|legal notice|reuse terms|dedication/i.test(label)) continue;
const item = element('li'); item.append(sourceLink(url, label)); list.append(item);
}
const coverage = element('li'); const coverageLink = element('a', 'Extraction details (JSON)'); coverageLink.href = selected.coverage; coverage.append(coverageLink); list.append(coverage);
const documentation = element('li'); const documentationLink = element('a', 'Source documentation'); documentationLink.href = 'docs/data-sources.md'; documentation.append(documentationLink); list.append(documentation);
body.append(list);
// Open APIs (data.go.kr): what this view shows, then what the research behind its indicators reads.
if (s.apis) {
for (const [role, heading] of [['site', 'Open APIs shown on this site'], ['research', 'Open APIs used in the research behind the indicators']]) {
const apis = s.apis.filter(a => a[0] === role);
if (!apis.length) continue;
body.append(element('h4', heading));
const apiList = element('ul', '', 'source-apis');
for (const [, name, id, use] of apis) {
const item = element('li');
item.append(sourceLink(`https://www.data.go.kr/data/${id}/openapi.do`, `${name} (${id})`), ' — ', element('span', use));
apiList.append(item);
}
body.append(apiList);
}
}
if (s.attribution) body.append(element('p', s.attribution, 'attribution'));
}
const provenance = { verified: 'Documented · public source', unverified: 'To verify · research lead', synthetic: 'Fictional · pedagogical comparison' };
const uiLocale = typeof i18nLocale === 'function' ? i18nLocale() : 'en-IE';
const money = new Intl.NumberFormat(uiLocale, { style: 'currency', currency: 'EUR', maximumFractionDigits: 2 });
const moneyCop = new Intl.NumberFormat(uiLocale, { style: 'currency', currency: 'COP', maximumFractionDigits: 0 });
const moneyPyg = new Intl.NumberFormat(uiLocale, { style: 'currency', currency: 'PYG', maximumFractionDigits: 0 });
const otherMoney = new Map();
// Local files may declare any ISO currency; amounts are never converted.
const moneyFor = c => {
if (!recordCurrency(c)) return { format: amount => `${new Intl.NumberFormat('en-IE').format(amount)} (currency unknown)` };
if (!c.assessmentMode && c.dataFamily === 'secop2') return moneyCop;
if (!c.assessmentMode && c.dataFamily === 'dncp') return moneyPyg;
if (!/^[A-Z]{3}$/.test(c.currency || '') || c.currency === 'EUR') return money;
if (!otherMoney.has(c.currency)) otherMoney.set(c.currency, new Intl.NumberFormat(uiLocale, { style: 'currency', currency: c.currency, maximumFractionDigits: 2 }));
return otherMoney.get(c.currency);
};
const dateFormat = new Intl.DateTimeFormat(uiLocale === 'en-IE' ? 'en-GB' : uiLocale, { timeZone: 'UTC', day: 'numeric', month: 'short', year: 'numeric' });
let contracts = [];
let boampDecpLinks = [];
let publicLinkEvidence = [];
let publicLinkResolutions = null;
let supplierProceedings = new Map();
const FRENCH_LINK_DATASETS = new Set(['decp', 'boamp', 'tours', 'consultations']);
let linkEvidenceStarted = false;
// South Korea: load the ranked subset, or a chosen buyer's shards.
let koreaBuyer = '', koreaMeta = null, koreaBuyers = null, koreaTop = null;
const koreaPicker = document.querySelector('#korea-picker');
// The institution box (under the province rows) and the type filter (in the advanced filters) show with the picker.
function setKoreaPicker(on) {
koreaPicker.hidden = !on;
document.querySelector('#korea-search-wrap').hidden = !on;
document.querySelector('#korea-type-filter').hidden = !on;
if (!on) document.querySelector('#korea-results').hidden = true;
}
const koreaSearch = document.querySelector('#korea-search');
const koreaResults = document.querySelector('#korea-results');
const koreaJson = (path, signal) => {
const url = `${KOREA_BASE}/${path}`;
return (!signal && globalThis.takeDataset?.(url)) || fetch(url, { signal, cache: 'no-store' }).then(response => {
if (!response.ok) throw Object.assign(new Error(`${url}: HTTP ${response.status}`), { status: response.status });
return response.json();
});
};
function koreaIndex() {
if (!koreaBuyers) koreaBuyers = Promise.all([koreaJson('meta.json'), koreaJson('buyers.json')]).then(([meta, buyers]) => {
koreaMeta = meta;
return buyers;
}).catch(error => { koreaBuyers = null; throw error; });
return koreaBuyers;
}
function koreaShard(n, signal) {
return koreaJson(`s/${String(n).padStart(4, '0')}.json`, signal);
}
const koreaKey = text => String(text || '').toLowerCase().replace(/\s+/g, '');
// Province and city as rows (city appears once a province is chosen); institution type, with its kinds indented
// under it, as one dropdown next to the institution search. All choices combine; each list counts contracts under
// the other choices. buyer[6] is [province, city, kind, ward] or null. Province, city and ward (구 of a big city)
// are where the requesting institution (수요기관) is: buyer[7], when present, splits the buyer's contracts as
// [[province, city, ward, n], ...] (PPS buys for institutions everywhere); otherwise all of them are at buyer[6].
const koreaFacet = { type: '', sub: '', region: '', city: '', ward: '' };
const koreaFacetValue = { type: b => b[2] || 'Other', sub: b => b[6]?.[2] || 'Other' };
const koreaPlaceValue = { region: p => p?.[0] || 'Unknown', city: p => p?.[1] || 'Other', ward: p => p?.[2] || 'Other' };
const koreaPlaces = b => b[7] || [[b[6]?.[0] ?? null, b[6]?.[1] ?? null, b[6]?.[3] ?? null, b[3]]];
const koreaParent = { sub: 'type', city: 'region', ward: 'city' };
const koreaClear = key => { for (const [child, p] of Object.entries(koreaParent)) if (p === key) { koreaFacet[child] = ''; koreaClear(child); } };
const KOREA_ROWS = { region: ['#korea-region', 'Province'], city: ['#korea-city', 'City or district'], ward: ['#korea-ward', 'Ward'] };
const koreaTypeSelect = document.querySelector('#korea-type');
const SEP = '\u001f';
const skipped = (k, skip) => Array.isArray(skip) ? skip.includes(k) : k === skip;
const koreaInPlace = (p, skip) => Object.keys(koreaPlaceValue).every(k => skipped(k, skip) || !koreaFacet[k] || koreaPlaceValue[k](p) === koreaFacet[k]);
// Contracts of buyer b under the current choices (except those in skip); 0 when the buyer is out.
const koreaCount = (b, skip) => Object.keys(koreaFacetValue).every(k => skipped(k, skip) || !koreaFacet[k] || koreaFacetValue[k](b) === koreaFacet[k])
? koreaPlaces(b).reduce((n, p) => n + (koreaInPlace(p, skip) ? p[3] : 0), 0) : 0;
const koreaMatches = (b, skip) => koreaCount(b, skip) > 0;
// A record's place: its requesting institution's when that lies elsewhere, else its buyer's.
const koreaRecordInPlace = (record, buyer) => koreaInPlace(record.demandPlace || [buyer[6]?.[0], buyer[6]?.[1], buyer[6]?.[3]]);
let koreaFacetBuyers = [];
function koreaFacetChanged() {
showKoreaResults(koreaFacetBuyers);
// The nationwide view follows the choices: the highest-scored contracts within the selection.
if (!koreaBuyer) loadDataset();
}
koreaTypeSelect.addEventListener('change', () => {
[koreaFacet.type, koreaFacet.sub = ''] = koreaTypeSelect.value.split(SEP);
koreaFacetChanged();
});
const KOREA_SVG = 'http://www.w3.org/2000/svg';
const svgNode = (tag, attrs = {}, parent) => {
const node = document.createElementNS(KOREA_SVG, tag);
for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
if (parent) parent.append(node);
return node;
};
// Bounding box of an M/L/Z path (build-korea-map.py), used for the parent map's zoom locator frame.
function shapeBBox(d) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const m of String(d || '').matchAll(/(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)/g)) {
const x = Number(m[1]), y = Number(m[2]);
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
return minX <= maxX ? { x: minX, y: minY, w: maxX - minX, h: maxY - minY } : null;
}
const koreaMapState = new WeakMap();
const koreaMapBoxes = {};
function formatMapArea(r, n, ko) {
const label = ko ? r.name : (r.en && r.en !== r.name ? `${r.en} (${r.name})` : r.name);
const unit = typeof i18nTranslate === 'function' ? i18nTranslate('contracts') : 'contracts';
return `${label} · ${n.toLocaleString('en')} ${unit}`;
}
function setMapHover(box, value) {
const state = koreaMapState.get(box);
if (!state) return;
const prev = state.hover || '';
if (prev === (value || '')) return;
state.hover = value || '';
const { svg, key, areas, labels, byName, totals, readout } = state;
const toggle = (name, on) => {
if (!name) return;
for (const el of svg.querySelectorAll(`[data-value="${CSS.escape(name)}"]`)) el.classList.toggle('is-hover', on);
const nav = document.querySelector(KOREA_ROWS[key][0]);
const btn = nav?.querySelector(`button[data-value="${CSS.escape(name)}"]`);
if (btn) btn.classList.toggle('is-hover', on);
};
toggle(prev, false);
toggle(state.hover, true);
if (state.hover) {
const g = areas.querySelector(`g.area[data-value="${CSS.escape(state.hover)}"]`);
if (g) areas.append(g);
const t = labels.querySelector(`text.name[data-value="${CSS.escape(state.hover)}"]`);
if (t) labels.append(t);
} else if (koreaFacet[key]) {
const sel = areas.querySelector(`g.area[data-value="${CSS.escape(koreaFacet[key])}"]`);
if (sel) areas.append(sel);
}
updateMapReadout(box);
}
function updateMapReadout(box) {
const state = koreaMapState.get(box);
if (!state) return;
const { key, byName, totals, readout, hover } = state;
const ko = document.documentElement.lang === 'ko';
const active = hover || koreaFacet[key] || '';
const r = active && byName.get(active);
readout.classList.toggle('is-hover', Boolean(hover && r));
readout.textContent = r ? formatMapArea(r, totals.get(active) || 0, ko) : '';
}
// Tight viewBox around all rendered shapes and island dots (trims blank sea margins left by dropped islets).
function tightViewBox(fallback, shapes) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
const grow = (x, y) => {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
};
for (const r of shapes) {
const b = shapeBBox(r.d);
if (b) { grow(b.x, b.y); grow(b.x + b.w, b.y + b.h); }
if (r.x !== undefined && r.y !== undefined) { grow(r.x - 18, r.y - 10); grow(r.x + 18, r.y + 10); }
for (const i of r.islands || []) { grow(i.cx - 24, i.cy - 6); grow(i.cx + 6, i.cy + 18); }
}
if (!(minX < maxX && minY < maxY)) return fallback;
const pad = 8;
const x = minX - pad, y = minY - pad, w = maxX - minX + pad * 2, h = maxY - minY + pad * 2;
return `${x.toFixed(1)} ${y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`;
}
// Highlight the zoomed child map's area with a framing box on its parent map and separate parent vs active panels.
function updateKoreaMapChrome() {
const visible = [koreaMapBox, koreaDistrictBox, koreaWardBox].filter(b => !b.hidden);
for (const b of [koreaMapBox, koreaDistrictBox, koreaWardBox]) {
b.classList.toggle('is-parent', !b.hidden && b !== visible.at(-1));
b.classList.toggle('is-active', !b.hidden && b === visible.at(-1));
}
const drawLocator = (box, targetName) => {
const state = koreaMapState.get(box);
if (!state) return;
state.locator.replaceChildren();
const r = targetName && state.byName.get(targetName);
const bbox = r && shapeBBox(r.d);
if (!bbox) return;
const [vx, vy, vw, vh] = state.viewBox.split(/\s+/).map(Number);
const pad = Math.max(5, Math.min(vw, vh) * 0.015);
const minSize = Math.min(vw, vh) * 0.075;
let w = Math.max(bbox.w + pad * 2, minSize);
let h = Math.max(bbox.h + pad * 2, minSize);
const cx = bbox.x + bbox.w / 2, cy = bbox.y + bbox.h / 2;
let x = cx - w / 2, y = cy - h / 2;
if (x < vx + 3) x = vx + 3;
if (y < vy + 3) y = vy + 3;
if (x + w > vx + vw - 3) { x = Math.max(vx + 3, vx + vw - 3 - w); w = Math.min(w, vw - 6); }
if (y + h > vy + vh - 3) { y = Math.max(vy + 3, vy + vh - 3 - h); h = Math.min(h, vh - 6); }
const attrs = { x: x.toFixed(1), y: y.toFixed(1), width: w.toFixed(1), height: h.toFixed(1), rx: '3' };
svgNode('rect', { ...attrs, class: 'locator-halo' }, state.locator);
svgNode('rect', { ...attrs, class: 'locator-box' }, state.locator);
};
drawLocator(koreaMapBox, !koreaDistrictBox.hidden ? koreaFacet.region : '');
drawLocator(koreaDistrictBox, !koreaWardBox.hidden ? koreaFacet.city : '');
}
// A clickable area (shape or label) that toggles koreaFacet[key] = value and syncs hover across shape, label and list.
function mapClickable(box, node, key, value, focusable) {
node.dataset.value = value;
const choose = () => {
koreaFacet[key] = koreaFacet[key] === value ? '' : value;
koreaClear(key);
koreaFacetChanged();
};
node.addEventListener('click', choose);
node.addEventListener('pointerenter', () => setMapHover(box, value));
node.addEventListener('pointerleave', () => {
if (koreaMapState.get(box)?.hover === value) setMapHover(box, '');
});
if (focusable) {
node.setAttribute('role', 'button');
node.setAttribute('tabindex', '0');
node.addEventListener('focus', () => setMapHover(box, value));
node.addEventListener('blur', () => {
if (koreaMapState.get(box)?.hover === value) setMapHover(box, '');
});
node.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); choose(); } });
}
return node;
}
// Shapes [{name, en, short?, d, x, y, ax?, ay?, islands?}] as clickable groups with labels above them; then
// highlight, density shading, live readout, locator square and label language are refreshed on every call.
function drawMap(box, viewBox, shapes, key, totals, { mapId = viewBox, title = '', clearKey = '' } = {}) {
let state = koreaMapState.get(box);
if (!state || state.mapId !== mapId) {
const head = element('figcaption', null, 'korea-map-head');
const titleWrap = element('span', null, 'korea-map-title-wrap');
const titleEl = element('span', '', 'korea-map-title');
const clearBtn = element('button', typeof i18nTranslate === 'function' ? i18nTranslate('Clear') : 'Clear', 'korea-map-clear');
clearBtn.type = 'button';
clearBtn.addEventListener('click', () => {
const k = box.dataset.clearKey;
if (!k || !koreaFacet[k]) return;
koreaFacet[k] = '';
koreaClear(k);
koreaFacetChanged();
});
titleWrap.append(titleEl, clearBtn);
const readout = element('span', '', 'korea-map-readout');
readout.setAttribute('aria-live', 'polite');
head.append(titleWrap, readout);
const canvas = element('div', null, 'korea-map-canvas');
const tight = tightViewBox(viewBox, shapes);
const [, , tw, th] = tight.split(/\s+/).map(Number);
const svg = svgNode('svg', { viewBox: tight, role: 'group' });
svg.dataset.view = tight;
if (tw > 0 && th > 0) svg.style.aspectRatio = `${tw} / ${th}`;
svg.addEventListener('pointerleave', () => setMapHover(box, ''));
const areas = svgNode('g', { class: 'areas' }, svg);
const locator = svgNode('g', { class: 'locator', 'aria-hidden': 'true' }, svg);
const labels = svgNode('g', { class: 'labels' }, svg);
for (const r of shapes) {
const g = mapClickable(box, svgNode('g', { class: 'area' }, areas), key, r.name, true);
svgNode('title', {}, g);
svgNode('path', { d: r.d }, g);
if (r.ax !== undefined) { // small region labelled beside it
svgNode('line', { x1: r.ax, y1: r.ay, x2: r.x, y2: r.y + (r.y > r.ay ? -7 : 7) }, labels);
svgNode('circle', { cx: r.ax, cy: r.ay, r: 2.2 }, labels);
}
mapClickable(box, svgNode('text', { x: r.x, y: r.y, class: 'name' }, labels), key, r.name);
for (const i of r.islands || []) { // islets under a pixel (Dokdo): a dot and a small label
svgNode('circle', { cx: i.cx, cy: i.cy, r: 2.2 }, labels);
const t = mapClickable(box, svgNode('text', { x: i.cx - 5, y: i.cy + 12, class: 'island' }, labels), key, r.name);
t.dataset.en = i.en;
t.dataset.short = i.short;
}
}
canvas.append(svg);
box.replaceChildren(head, canvas);
state = { mapId, viewBox: tight, key, svg, areas, locator, labels, titleEl, clearBtn, readout, hover: '' };
koreaMapState.set(box, state);
}
const ko = document.documentElement.lang === 'ko';
const byName = new Map(shapes.map(r => [r.name, r]));
state.byName = byName;
state.totals = totals;
state.titleEl.textContent = title;
box.dataset.clearKey = clearKey;
state.clearBtn.hidden = !clearKey || !koreaFacet[clearKey];
const maxTotal = Math.max(0, ...shapes.map(r => totals.get(r.name) || 0));
let selectedArea = null;
for (const g of state.areas.querySelectorAll('g.area')) {
const name = g.dataset.value, r = byName.get(name), n = totals.get(name) || 0;
const isOn = koreaFacet[key] === name;
g.classList.toggle('on', isOn);
g.classList.toggle('empty', maxTotal > 0 && n === 0);
g.style.setProperty('--heat', n > 0 && maxTotal > 0 ? (0.05 + 0.13 * Math.log1p(n) / Math.log1p(maxTotal)).toFixed(3) : '0');
g.setAttribute('aria-pressed', String(isOn));
const text = `${name}${r.en && r.en !== name ? ` (${r.en})` : ''} · ${n.toLocaleString('en')} contracts`;
g.setAttribute('aria-label', text);
g.querySelector('title').textContent = text;
if (isOn) selectedArea = g;
}
if (selectedArea) state.areas.append(selectedArea);
for (const t of state.labels.querySelectorAll('text.name')) {
const r = byName.get(t.dataset.value);
t.textContent = ko ? (r.short || r.name) : (r.en || r.name);
}
for (const t of state.labels.querySelectorAll('text.island')) t.textContent = ko ? t.dataset.short : t.dataset.en;
updateMapReadout(box);
box.hidden = false;
updateKoreaMapChrome();
}
// Province map (assets/korea-provinces.json); once a province is chosen, its cities and districts beside it
// (assets/korea-districts.json, loaded on the first choice). Both from tools/build-korea-map.py.
const koreaMapBox = document.querySelector('#korea-map');
const koreaDistrictBox = document.querySelector('#korea-district-map');
const koreaWardBox = document.querySelector('#korea-ward-map');
koreaMapBoxes.region = koreaMapBox;
koreaMapBoxes.city = koreaDistrictBox;
koreaMapBoxes.ward = koreaWardBox;
const loadJson = path => (globalThis.takeDataset?.(path) || fetch(path).then(r => r.ok ? r.json() : null)).catch(() => null);
let koreaMap = null, koreaDistricts = null;
let koreaMapData = null, koreaDistrictData = null;
const koreaMapTitle = (name, en) => document.documentElement.lang === 'ko' ? name : (en && en !== name ? en : name);
function renderKoreaMap(totals) {
koreaMap ||= loadJson('assets/korea-provinces.json').then(m => (koreaMapData = m));
koreaMap.then(map => {
if (!map) return;
const title = typeof i18nTranslate === 'function' ? i18nTranslate('Province') : 'Province';
drawMap(koreaMapBox, map.viewBox, map.regions, 'region', totals, { mapId: 'provinces', title, clearKey: 'region' });
});
}
// Wards of the chosen city, for cities divided into 구 (수원시, 창원시, …).
function renderKoreaWardMap(totals) {
const { region: province, city } = koreaFacet;
if (!province || !city) { koreaWardBox.hidden = true; updateKoreaMapChrome(); return; }
koreaDistricts ||= loadJson('assets/korea-districts.json').then(d => (koreaDistrictData = d));
koreaDistricts.then(all => {
const map = all?.[province]?.wards?.[city];
if (!map || koreaFacet.city !== city) { koreaWardBox.hidden = !map || !koreaFacet.city; updateKoreaMapChrome(); return; }
const cityInfo = all?.[province]?.cities?.find(c => c.name === city);
drawMap(koreaWardBox, map.viewBox, map.cities, 'ward', totals, {
mapId: `${province}/${city}`, title: koreaMapTitle(city, cityInfo?.en), clearKey: 'city'
});
});
}
function renderKoreaDistrictMap(totals) {
const province = koreaFacet.region;
if (!province) { koreaDistrictBox.hidden = true; updateKoreaMapChrome(); return; }
koreaDistricts ||= loadJson('assets/korea-districts.json').then(d => (koreaDistrictData = d));
koreaDistricts.then(all => {
const map = all?.[province];
if (!map || koreaFacet.region !== province) { koreaDistrictBox.hidden = !map || !koreaFacet.region; updateKoreaMapChrome(); return; }
const provInfo = koreaMapData?.regions?.find(r => r.name === province);
drawMap(koreaDistrictBox, map.viewBox, map.cities, 'city', totals, {
mapId: province, title: koreaMapTitle(province, provInfo?.en), clearKey: 'region'
});
});
}
function renderKoreaFacets(buyers) {
koreaFacetBuyers = buyers;
for (const [key, [selector, label]] of Object.entries(KOREA_ROWS)) {
const row = document.querySelector(selector);
const parent = koreaParent[key];
const totals = new Map();
if (!parent || koreaFacet[parent]) for (const b of buyers) if (koreaMatches(b, key)) {
for (const p of koreaPlaces(b)) if (koreaInPlace(p, key)) {
const v = koreaPlaceValue[key](p);
totals.set(v, (totals.get(v) || 0) + p[3]);
}
}
row.hidden = Boolean(parent) && !koreaFacet[parent];
const mapBox = koreaMapBoxes[key];
const button = (value, text, count) => {
const item = element('button', text, value === koreaFacet[key] ? 'on' : '');
item.type = 'button';
if (value) {
item.dataset.value = value;
item.addEventListener('pointerenter', () => setMapHover(mapBox, value));
item.addEventListener('pointerleave', () => {
if (koreaMapState.get(mapBox)?.hover === value) setMapHover(mapBox, '');
});
}
if (count !== undefined) item.append(element('span', count.toLocaleString('en'), 'muted'));
item.addEventListener('click', () => {
koreaFacet[key] = value === koreaFacet[key] ? '' : value;
koreaClear(key);
koreaFacetChanged();
});
return item;
};
row.replaceChildren(element('span', label, 'facet-label'), button('', 'All'), ...[...totals].sort((a, b) => b[1] - a[1]).map(([v, n]) => button(v, v, n)));
if (key === 'region') renderKoreaMap(totals);
if (key === 'city') renderKoreaDistrictMap(totals);
if (key === 'ward') renderKoreaWardMap(totals);
}
// Types, each followed by its kinds, counted under the province and city choices.
const types = new Map();
for (const b of buyers) {
const n = koreaCount(b, ['type', 'sub']);
if (!n) continue;
const t = koreaFacetValue.type(b), k = koreaFacetValue.sub(b);
if (!types.has(t)) types.set(t, { n: 0, kinds: new Map() });
const entry = types.get(t);
entry.n += n;
entry.kinds.set(k, (entry.kinds.get(k) || 0) + n);
}
const options = [['', 'All types']];
for (const [t, { n, kinds }] of [...types].sort((a, b) => b[1].n - a[1].n)) {
options.push([t, `${t} · ${n.toLocaleString('en')}`]);
if (kinds.size > 1) for (const [k, m] of [...kinds].sort((a, b) => b[1] - a[1])) options.push([t + SEP + k, `\u00a0\u00a0\u00a0↳ ${k} · ${m.toLocaleString('en')}`]);
}
fillSelect(koreaTypeSelect, options);
koreaTypeSelect.value = koreaFacet.sub ? koreaFacet.type + SEP + koreaFacet.sub : koreaFacet.type;
}
function showKoreaResults(buyers) {
renderKoreaFacets(buyers);
const wanted = koreaKey(koreaSearch.value);
// The list appears only while typing a name that is not the chosen institution's.
koreaResults.hidden = !wanted || (koreaBuyer && koreaSearch.value === buyers.find(b => b[0] === koreaBuyer)?.[1]);
const found = [];
for (const b of buyers) {
if (koreaMatches(b) && (!wanted || koreaKey(b[1]).includes(wanted) || b[0].startsWith(wanted))) found.push(b);
if (found.length >= 30) break;
}
koreaResults.replaceChildren(...found.map(b => {
const item = element('li');
const short = koreaFacet.region && b[1].startsWith(koreaFacet.region + ' ') ? b[1].slice(koreaFacet.region.length + 1) : b[1];
const button = element('button', `${short} · ${koreaCount(b).toLocaleString('en')} contracts`, 'link-button');
button.type = 'button';
button.addEventListener('click', () => chooseKoreaBuyer(b[0]));
item.append(button);
return item;
}));
if (!found.length) koreaResults.append(element('li', 'No contracting institution matches.', 'muted'));
}
function chooseKoreaBuyer(code) {
koreaBuyer = code;
if (!code) koreaSearch.value = '';
pendingView = null;
loadDataset();
}
koreaSearch.addEventListener('input', () => {
if (!koreaSearch.value.trim() && koreaBuyer) { chooseKoreaBuyer(''); return; }
koreaIndex().then(showKoreaResults).catch(() => {});
});
async function loadKorea(version) {
setKoreaPicker(true);
const buyers = await koreaIndex();
if (version !== loadVersion) return;
showKoreaResults(buyers);
const buyer = koreaBuyer && buyers.find(b => b[0] === koreaBuyer);
if (!buyer) {
koreaBuyer = '';
try {
koreaTop ||= koreaJson('top.json').catch(error => { koreaTop = null; throw error; });
const top = await koreaTop;
if (version !== loadVersion) return;
const chosen = Object.values(koreaFacet).some(Boolean) ? buyers.filter(b => koreaMatches(b)) : buyers;
const records = chosen.flatMap(b => koreaRecords(koreaMeta, top, b).filter(r => koreaRecordInPlace(r, b)));
const scope = Object.values(koreaFacet).filter(Boolean).join(' · ');
document.querySelector('#dataset-note').textContent = scope
? `${scope}: ${records.length.toLocaleString('en')} of the ${top.count.toLocaleString('en')} highest-scored contracts nationwide; choose an institution to see all of its contracts.`
: `The ${top.count.toLocaleString('en')} highest-scored of all ${koreaMeta.contracts.toLocaleString('en')} contracts; choose an institution to see all of its contracts.`;
accept(records);
} catch (error) {
if (version !== loadVersion) return;
if (error.status !== 404) throw error;
accept([]);
status.textContent = 'Choose a contracting institution.';
}
return;
}
koreaSearch.value = buyer[1];
status.textContent = `Loading ${buyer[3]} contracts of ${buyer[1]}…`;
const shards = await Promise.all(koreaParts(buyer).map(n => koreaShard(n)));
if (version !== loadVersion) return;
const records = shards.flatMap(shard => koreaRecords(koreaMeta, shard, buyer));
const here = records.filter(r => koreaRecordInPlace(r, buyer));
if (here.length < records.length) {
const scope = [koreaFacet.region, koreaFacet.city, koreaFacet.ward].filter(Boolean).join(' · ');
document.querySelector('#dataset-note').textContent = `${scope}: ${here.length.toLocaleString('en')} of the ${records.length.toLocaleString('en')} contracts of ${buyer[1]}, those requested by institutions there. Choose All provinces to see every one.`;
}
accept(here);
}
// First-page preview (prefetch.js, tools/build-first-pages.cjs): the default view's top rows,
// shown read-only until the full dataset is in. Filters, sorting, export and the record panel
// would act on 50 rows only, so they stay locked.
let previewing = false, previewTotal = 0;
const lockedBefore = new Map();
function setPreviewLock(on) {
previewing = on;
const elements = [...Object.values(controls), document.querySelector('#sort-field'), document.querySelector('#sort-direction'), ...document.querySelectorAll('.sort-header, #clear-filters')];
for (const el of elements) {
if (on) { lockedBefore.set(el, el.disabled); el.disabled = true; }
else if (lockedBefore.has(el)) el.disabled = lockedBefore.get(el);
}
if (!on) lockedBefore.clear();
document.querySelector('.table-wrap').inert = on;
document.querySelector('#results').setAttribute('aria-busy', String(on));
}
// Optional: never delays the records; badges appear when it arrives. A missing or invalid file shows none.
fetch('data/supplier-proceedings.json').then(response => {
if (!response.ok) throw new Error('Supplier proceedings unavailable');
return response.json();
}).then(data => {
supplierProceedings = validateSupplierProceedings(data);
if (loaded && !usingLocalFile) {
render();
const record = openId && contracts.find(c => c.id === openId);
if (record) renderDetail(record);
}
}).catch(error => console.warn('Supplier proceedings not shown:', error.message));
// Notes repeated on many rows describe the dataset, not a record: shown once under “Scope and limits”.
let sharedNotes = new Set();
const fieldNotes = document.querySelector('#field-notes');
let loaded = false;
let loadVersion = 0;
let page = 0;
let pageSize = 50;
let pageRowsForCopy = [];
let totalResultsForCopy = 0;
let rowsForExport = [];
let usingLocalFile = false;
let localFileName = '';
let localFileIdentity = '';
const defaultDataset = datasetSelect.options[0].value;
const initialView = hashToViewState(location.hash);
if (Object.hasOwn(datasets, initialView.dataset)) datasetSelect.value = initialView.dataset;
let pendingView = location.hash ? initialView : null;
const datasetSelection = setupDatasetSelection(document.querySelector('#country'), datasetSelect, () => {
pendingView = null;
loadDataset();
});
// These new navigation labels live here because the shared dictionaries are generated
// separately. Existing country names and cohort labels use the normal i18n observer.
const selectionLabels = { en: ['Country', 'Source / cohort'], fr: ['Pays', 'Source / cohorte'], es: ['País', 'Fuente / cohorte'], ko: ['국가', '출처 / 코호트'] };
const selectionLanguage = uiLocale.slice(0, 2);
const [countryLabel, sourceLabel] = selectionLabels[selectionLanguage] || selectionLabels.en;
document.querySelector('#country-label').textContent = countryLabel;
document.querySelector('#source-label').textContent = sourceLabel;
// The full label joins the country and the selected source/cohort.
const datasetLabel = () => {
const option = datasetSelect.selectedOptions[0], country = option.dataset.country;
return `${typeof i18nTranslate === 'function' ? i18nTranslate(country) : country} · ${option.textContent.replace(/^\s*[\u{1F1E6}-\u{1F1FF}]{2}/u, '').trim()}`;
};
let currentDatasetLabel = datasetLabel();
const pageSizeSelect = document.querySelector('#page-size');
const copyPage = document.querySelector('#copy-page');
const copyStatus = document.querySelector('#copy-status');
const exportCsv = document.querySelector('#export-csv');
const exportJson = document.querySelector('#export-json');
const pagination = document.querySelector('#pagination');
const previous = document.querySelector('#previous');
const next = document.querySelector('#next');
const viewport = document.querySelector('.table-wrap');
const projectPanel = document.querySelector('#project-panel');
const detailPanel = document.querySelector('#detail-panel');
const detailBody = document.querySelector('#detail-body');
const filterPanel = document.querySelector('#advanced-filters');
let projectCatalog = new Map();
// The record shown in the side panel; kept in the link as open=<id>.
let openId = '';
let pendingOpen = '';
let visibleRows = [];
let signalCounts = new Map();
const indicatorLabels = new Map([...controls.indicator.options].map(option => [option.value, option.textContent]));
for (const [id, label] of Object.entries(INDICATOR_KINDS)) if (!indicatorLabels.has(id)) indicatorLabels.set(id, label);
// Filters: a collapsible sidebar on wide screens (choice remembered in this browser), folded on narrow ones.
const FILTERS_STORE = 'contract-signals-filters';
const wideScreen = matchMedia('(min-width: 1001px)');
const sidebarWanted = () => { try { return localStorage.getItem(FILTERS_STORE) === 'open'; } catch { return false; } };
// The label stays the same open or closed; only the arrow turns, like the Dataset and Sources toggles.
filterPanel.open = wideScreen.matches && sidebarWanted();
wideScreen.addEventListener('change', () => { filterPanel.open = wideScreen.matches && sidebarWanted(); });
filterPanel.addEventListener('toggle', () => {
if (wideScreen.matches) try { localStorage.setItem(FILTERS_STORE, filterPanel.open ? 'open' : 'closed'); } catch { /* Storage blocked: the choice lasts for this visit. */ }
});
// Colour theme: automatic (system), light or dark, remembered in this browser only.
const THEME_STORE = 'contract-signals-theme';
const themeSelect = document.querySelector('#theme');
themeSelect.value = ['light', 'dark'].includes(document.documentElement.dataset.theme) ? document.documentElement.dataset.theme : 'auto';
themeSelect.addEventListener('change', () => {
const theme = themeSelect.value;
if (theme === 'auto') delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = theme;
try { if (theme === 'auto') localStorage.removeItem(THEME_STORE); else localStorage.setItem(THEME_STORE, theme); } catch { /* Storage blocked: the choice lasts for this visit. */ }
});
// Review marks and notes: a reviewer's own working notes, stored only in this browser.
// They never change the index and are not part of the shareable link.
const REVIEW_STORE = 'contract-signals-review-v1';
const REVIEW_STATUSES = { 'follow-up': 'Follow up', referred: 'Referred', reviewed: 'Reviewed' };
let reviews = {};
let reviewStorageWorks = true;
try { const saved = JSON.parse(localStorage.getItem(REVIEW_STORE) || '{}'); if (saved && typeof saved === 'object' && !Array.isArray(saved)) reviews = saved; } catch { reviewStorageWorks = false; }
let reviewsVersion = 0, selectionMemo = null;
function saveReviews() {
reviewsVersion++;
try { localStorage.setItem(REVIEW_STORE, JSON.stringify(reviews)); reviewStorageWorks = true; } catch { reviewStorageWorks = false; }
}
const reviewScope = () => usingLocalFile ? `local:${localFileIdentity}` : datasetSelect.value;
const reviewKey = c => `${reviewScope()}|${c.id}`;
const reviewOf = c => reviews[reviewKey(c)] || null;
function setReview(c, patch) {
const key = reviewKey(c);
const entry = { ...(reviews[key] || {}), ...patch, updatedAt: new Date().toISOString() };
if (!entry.status && !entry.note?.trim()) delete reviews[key]; else reviews[key] = entry;
saveReviews();
renderReviewSummary();
}
function reviewMatch(c) {
const wanted = controls.review.value;
if (!wanted) return true;
const mark = reviewOf(c)?.status || '';
return wanted === '@none' ? !mark : wanted === '@any' ? Boolean(mark) : mark === wanted;
}
function reviewCounts() {
const prefix = reviewScope() + '|';
const counts = { total: 0 };
for (const [key, entry] of Object.entries(reviews)) if (key.startsWith(prefix) && entry.status) { counts.total++; counts[entry.status] = (counts[entry.status] || 0) + 1; }
return counts;
}
function renderReviewSummary() {
const counts = reviewCounts();
document.querySelector('#review-filters').hidden = !counts.total && !controls.review.value;
document.querySelector('#review-summary').textContent = !reviewStorageWorks ? 'This browser blocks storage: marks last until the page is closed.' :
counts.total ? `In this dataset: ${Object.entries(REVIEW_STATUSES).map(([id, label]) => `${counts[id] || 0} ${label.toLowerCase()}`).join(' · ')}.` : 'None in this dataset yet.';
}
function fillSelect(select, options) {
const previousValue = select.value;
select.replaceChildren(...options.map(([value, label]) => { const option = element('option', label); option.value = value; return option; }));
select.value = options.some(([value]) => value === previousValue) ? previousValue : '';
}
function applyView(view) {
for (const [, id, fallback] of VIEW_FIELDS) {
if (id === 'open-record') { pendingOpen = view[id]; continue; }
if (id === 'korea-buyer') { koreaBuyer = view[id] || ''; continue; }
if (id === 'indicator' && view[id] && indicatorLabels.has(view[id]) && ![...controls[id].options].some(o => o.value === view[id])) {
const option = element('option', indicatorLabels.get(view[id])); option.value = view[id]; controls[id].append(option);
}
controls[id].value = view[id];
if (controls[id].tagName === 'SELECT' && controls[id].selectedIndex === -1) controls[id].value = fallback;
}
for (const id of VIEW_FLAGS) controls[id].checked = view[id];
pageSize = view.pageSize;
pageSizeSelect.value = String(pageSize);
page = view.page - 1;
}
function currentView() {
const view = { dataset: usingLocalFile || datasetSelect.value === defaultDataset ? '' : datasetSelect.value, page: page + 1, pageSize };
for (const [, id] of VIEW_FIELDS) view[id] = id === 'open-record' ? openId : id === 'korea-buyer' ? (datasetSelect.value === 'korea' && !usingLocalFile ? koreaBuyer : '') : controls[id].value;
for (const id of VIEW_FLAGS) view[id] = controls[id].checked;
return view;
}
// replaceState keeps the link current without adding a history entry per keystroke.
function writeView() {
const hash = viewStateToHash(currentView());
if (hash === location.hash) return;
try { history.replaceState(null, '', hash || location.pathname + location.search); } catch { /* Some file:// contexts refuse history updates. */ }
}
const FILTER_VALUES = ['filter-country', 'date-from', 'date-to', 'filter-buyer', 'filter-supplier', 'filter-procedure', 'minimum', 'sector', 'group-by', 'project', 'assessment', 'min-score', 'indicator', 'notice-context', 'legal', 'review', 'verification'];
function clearFilters() {
for (const id of FILTER_VALUES) controls[id].value = '';
controls['min-score'].value = '0';
for (const id of VIEW_FLAGS) controls[id].checked = false;
}
function refresh() { page = 0; render(); viewport.scrollTop = 0; }
function showProject(id) {
controls.search.value = '';
clearFilters();
controls.project.value = id;
controls['group-by'].value = id ? 'project' : '';
refresh();
}
let activeProfile = null;
const profilePanel = document.querySelector('#profile-panel');
function openProfile(c, role) {
const key = profileKey(c, role);
activeProfile = key ? buildProfile(contracts, role, key) : null;
page = 0;
render();
profilePanel.scrollIntoView({ block: 'start' });
}
function renderProfilePanel() {
profilePanel.replaceChildren();
profilePanel.hidden = !activeProfile;
if (!activeProfile) return;
const p = activeProfile;
const pct = (a, b) => b ? `${Math.round(a / b * 100)} %` : '—';
profilePanel.append(element('h2', `${p.role === 'buyer' ? 'Buyer' : 'Supplier'} profile · ${p.name || '—'}`),
element('p', `${p.contracts} contract(s)${p.firstDate ? ` · ${p.firstDate} → ${p.lastDate}` : ''} · ${p.assessed} assessed · ${p.flagged} with a signal (${pct(p.flagged, p.assessed)}). The table below now shows only these contracts. Compared with the ${p.scopeSize} records of the same dataset; amounts are never summed.`));
const table = element('table', null, 'profile-table');
const head = element('tr');
head.append(element('th', 'Indicator'), element('th', `This ${p.role}`), element('th', 'Whole dataset'));
table.append(head);
for (const kind of Object.keys(INDICATOR_KINDS)) {
const mine = p.kinds[kind], all = p.baseline[kind];
if (!mine && !all) continue;
const tr = element('tr');
tr.append(element('td', INDICATOR_KINDS[kind]), element('td', mine ? `${mine.signals} / ${mine.evaluated} evaluated (${pct(mine.signals, mine.evaluated)})` : 'not evaluated'),
element('td', all ? `${pct(all.signals, all.evaluated)} of ${all.evaluated} evaluated` : '—'));
table.append(tr);
}
profilePanel.append(table);
profilePanel.append(element('h3', p.role === 'buyer' ? 'Main suppliers' : 'Main buyers'));
const list = element('ol');
for (const cp of p.counterparts) list.append(element('li', `${cp.name} · ${cp.contracts} contract(s), ${cp.flagged} with a signal`));
profilePanel.append(list);
const money = Object.entries(p.currencies).map(([cur, v]) => `${v.contracts} with an amount in ${cur} (largest ${v.largest.toLocaleString('en-IE')} ${cur})`).join('; ');
if (money) profilePanel.append(element('p', `Declared amounts: ${money}. Not summed: declared amounts are not payments, and ceilings and amendments would double count.`));
profilePanel.append(element('p', 'A profile describes published declarations and heuristic signals only; a high rate is a reason to read the sources, not a finding.'));
const close = element('button', 'Close profile and show all contracts');
close.type = 'button';
close.addEventListener('click', () => { activeProfile = null; page = 0; render(); });
profilePanel.append(close);
}
function renderProjectPanel() {
projectPanel.replaceChildren();
const project = projectCatalog.get(controls.project.value);
projectPanel.hidden = !project;
if (!project) return;
projectPanel.append(element('h2', project.title), element('p', project.basis));
projectPanel.append(sourceLink(project.source, 'Public reference notice of the dossier'));
const list = element('ol', null, 'evidence-list');
(project.evidence || []).forEach(evidence => {
const item = element('li');
item.append(sourceLink(evidence.source, `${evidence.date} — ${evidence.label}`), element('span', ` · ${evidence.type}. ${evidence.description}`));
list.append(item);
});
projectPanel.append(list, element('p', 'These documentary elements earn no additional points and do not constitute an official finding. No project amount or score is summed.'));
const clear = element('button', 'Back to all records', 'clear-group');
clear.type = 'button';
clear.addEventListener('click', () => showProject(''));
projectPanel.append(clear);
}
// Indicator list: only the checks this dataset runs, most frequent first, each with its count.
function computeOverview() {
const officialCount = contracts.filter(c => c.officialFinding === true).length;
signalCounts = new Map();
const present = new Set();
// Counted per shared indicator kind, the value the filter matches (one row per kind).
for (const c of contracts) {
const kinds = new Set();
for (const r of getAssessment(c).checks) {
const kind = indicatorKind(r.id);
if (!kind) continue;
if (r.status !== 'not-applicable') present.add(kind);
if (r.status === 'signal') kinds.add(kind);
}
for (const kind of kinds) signalCounts.set(kind, (signalCounts.get(kind) || 0) + 1);
}
if (officialCount) { present.add('official-finding'); signalCounts.set('official-finding', officialCount); }
// Only offer context filters supported by the full loaded dataset, not the current results.
const availableNotices = new Set();
const availableLegal = new Set();
const availableVerification = new Set(contracts.map(c => c.verification?.status).filter(Boolean));
for (const c of contracts) {
const e = c.noticeEvidence;
if (e) {
if (e.procedureDescription || e.justifications.some(j => j.text)) availableNotices.add('explanation');
if (e.awardCriteria.length) availableNotices.add('criteria');
if (e.kind === 'correction') availableNotices.add('correction');
if (e.ted.length) availableNotices.add('ted');
}
if (declaredWithoutCompetition(c)) availableLegal.add('direct');
for (const citation of getLegalContext(c)) { availableLegal.add('cited'); availableLegal.add(citation.article); }
if (c.complaints?.length) availableLegal.add('py-complaint');
if (c.secop2PublicCounterparty?.labelled) availableLegal.add('co-public');
if (softwareMaintenanceContext(c)) availableLegal.add('fr-software');
}
for (const [id, available] of [['notice-context', availableNotices], ['legal', availableLegal], ['verification', availableVerification]]) {
for (const option of controls[id].options) option.hidden = Boolean(option.value && !available.has(option.value));
controls[id].closest('label').dataset.available = String(available.size > 0);
}
for (const [id, available] of [['official', officialCount > 0], ['adjudicated', contracts.some(hasAdjudicatedCorruption)], ['investigation', contracts.some(hasReportedInvestigation)]]) {
controls[id].closest('label').dataset.available = String(available);
}
const activeIndicator = pendingView?.indicator || controls.indicator.value;
if (activeIndicator && indicatorLabels.has(activeIndicator)) present.add(activeIndicator);
const options = [...indicatorLabels].filter(([id]) => id && present.has(id)).sort((a, b) => (signalCounts.get(b[0]) || 0) - (signalCounts.get(a[0]) || 0));
const tr = typeof i18nTranslate === 'function' ? i18nTranslate : text => text;
fillSelect(controls.indicator, [['', 'All indicators'], ...options.map(([id, label]) => [id, `${tr(label)} · ${signalCounts.get(id) || 0}`])]);
}
// Full-width rows must span only the visible columns: on phones six columns are hidden,
// and a colspan of 9 would create phantom columns that squeeze the subject.
function visibleColumnCount() {
return [...document.querySelectorAll('.main-table > thead th')].filter(th => getComputedStyle(th).display !== 'none').length || 9;
}
matchMedia('(max-width: 760px)').addEventListener('change', () => { if (loaded) render(); });
const formatDate = c => c.date ? dateFormat.format(new Date(c.date)) : c.noticeEvidence ? c.publicationDate || '—' : '—';
// Sources that disagree are shown as the full range of their published amounts, never one pick.
const formatAmount = c => Array.isArray(c.verification?.amountRange) ? c.verification.amountRange.map(a => moneyFor(c).format(a)).join(' – ') : c.amount == null ? '—' : c.amount === 0 ? 'declared 0 (likely undisclosed)' : ({ 'at-least': '≥ ', 'more-than': '> ', approximate: '≈ ' }[c.amountQualifier] || '') + moneyFor(c).format(c.amount);
// In the table a range takes two lines (low, then “– high”), so it never runs into the next column.
function amountCell(c) {
const range = c.verification?.amountRange;
if (!Array.isArray(range)) return element('td', formatAmount(c), 'numeric col-amount');
const cell = element('td', null, 'numeric amount-range col-amount');
cell.title = 'Sources disagree on the amount: range of the published values';
// Whole units keep each line inside narrow columns; the record panel keeps the exact amounts.
const options = moneyFor(c).resolvedOptions();
const whole = new Intl.NumberFormat(options.locale, { style: 'currency', currency: options.currency, maximumFractionDigits: 0, minimumFractionDigits: 0 });
cell.append(element('span', whole.format(range[0])), element('span', `– ${whole.format(range[1])}`));
return cell;
}
// Procedure as published, and whether it is competitive or direct where the data says so.
function procedureCell(c) {
const cell = element('td', null, 'col-procedure');
const name = (c.dataFamily === 'koneps' ? c.procedureMethod : c.procedure) || '';
cell.append(element('span', name, 'procedure-name'));
cell.title = name;
// KONEPS methods: 수의계약 (negotiated with one firm) is direct; the 경쟁 methods are competitive.
const korean = c.dataFamily === 'koneps' && c.procedureMethod ? (/수의/.test(c.procedureMethod) ? true : /경쟁/.test(c.procedureMethod) ? false : null) : null;
const direct = c.directAward ?? c.procedureDirect ?? korean;
if (direct === true || direct === false) cell.append(element('small', direct ? 'direct award' : 'competitive', 'provenance'));
return cell;
}
// A name kept to one short line; the whole of it is in the tooltip and the record panel.
function clipped(text, full) {
const span = element('span', text, 'clip');
span.title = full;
return span;
}
// Months up to 2 years, years from there.
function durationParts(months) {
return months < 24 ? [`${months} `, element('span', 'months')] : [`${Number((months / 12).toFixed(1)).toLocaleString(uiLocale)} `, element('span', 'years')];
}
function durationSpan(months) {
const span = element('span');
span.append(...durationParts(months));
return span;
}
// One column whose content depends on the country: the figure its data adds that the shared columns lack.
// Always three decimals, as KONEPS publishes them: floors such as 87.995 % are exact legal rates, and a winning
// ratio a few thousandths above its floor is what the floor checks look at, so rounding would hide both.
const percent = v => `${Number(v).toLocaleString('en', { minimumFractionDigits: 3, maximumFractionDigits: 3 })} %`;
const EXTRA_COLUMNS = {
koneps: { header: 'Bid ratio', title: 'Winning bid as a % of the reserve price (예정가격); below it, the lower award limit (낙찰하한율). From the bid opening (개찰결과).',
value: c => c.winnerRate == null ? null : [percent(c.winnerRate), c.lowerRate == null ? null : `floor ${percent(c.lowerRate)}`] },
decp: { header: 'Duration', title: 'Declared duration; below it, the declared amount change where the published history allows it.',
value: c => { const e = getAmountEvolution(c); return [c.durationMonths == null ? null : durationSpan(c.durationMonths), e.status === 'available' ? `${e.percentage >= 0 ? '+' : ''}${e.percentage.toFixed(1)} % amount` : null]; } },
prozorro: { header: 'Changes', title: 'Published contract changes (Prozorro)', value: c => !c.contractChanges ? null : [String(c.contractChanges), c.contractChangeTypes?.length ? c.contractChangeTypes.join(', ') : null] },
secop2: { header: 'Days added', title: 'Days added to the contract term (SECOP II)', value: c => !c.daysAdded ? null : [String(c.daysAdded)] },
dncp: { header: 'Amendments', title: 'Published contract amendments (DNCP)', value: c => !c.amendmentCount ? null : [String(c.amendmentCount)] },
};
EXTRA_COLUMNS.boamp = EXTRA_COLUMNS.decp;
let extraColumn = null;
function syncExtraColumn() {
// The dataset's main source decides (France mixes DECP with a few audit dossiers).
const counts = new Map();
for (const c of contracts) counts.set(c.dataFamily, (counts.get(c.dataFamily) || 0) + 1);
const main = [...counts].sort((a, b) => b[1] - a[1])[0]?.[0];
extraColumn = EXTRA_COLUMNS[main] || null;
if (extraColumn && !contracts.some(c => extraColumn.value(c)?.some(Boolean))) extraColumn = null;
// A column appears only if this dataset has something to put in it.
const table = document.querySelector('.main-table');
table.classList.toggle('no-sector', !contracts.some(c => getSector(c).code !== 'unknown'));
table.classList.toggle('no-offers', !contracts.some(c => c.offers != null));
table.classList.toggle('no-procedure', !contracts.some(c => c.procedure || c.procedureMethod));
// Paraguay publishes the start of the contract period, not the signature: said once, in the header.
const dateHeader = document.querySelector('.main-table th[data-sort-key="date"]');
dateHeader.querySelector('button').textContent = main === 'dncp' ? 'Period start' : 'Date';
dateHeader.title = main === 'dncp' ? 'Contract-period start · not signature' : '';
const th = document.querySelector('.main-table th.col-extra');
th.textContent = extraColumn?.header || '';
th.title = extraColumn?.title || '';
th.closest('table').classList.toggle('no-extra', !extraColumn);
}
function extraCell(c) {
const cell = element('td', null, 'numeric col-extra');
const [first, ...rest] = (extraColumn && extraColumn.value(c)) || [];
cell.append(first ?? '');
for (const line of rest) if (line) cell.append(element('small', line, 'provenance'));
return cell;
}
function scoreChip(c) {
const breakdown = getScoreBreakdown(c);
const level = scoreLevel(breakdown.score, hasIncompleteData(c), breakdown.assessment.signals, breakdown.assessment.weighted);
const partly = breakdown.partlyChecked;
const chip = element('span', formatIndex(breakdown), `score-chip level-${partly ? 'unknown' : level.id}`);
chip.title = partly ? `Nothing found in the checks that could run; no ${breakdown.unchecked.join(', ')} check could run on this record, so no index is shown.`
: `${level.label}: how much more frequent such records are among proven cases than among the same buyers’ other contracts. Not a probability.`;
return chip;
}
function selectionOptions() {
return { country: controls['filter-country'].value, dateFrom: controls['date-from'].value, dateTo: controls['date-to'].value, buyer: controls['filter-buyer'].value, supplier: controls['filter-supplier'].value, procedure: controls['filter-procedure'].value, search: controls.search.value, minimum: Math.max(0, Number(controls.minimum.value) || 0), minScore: Number(controls['min-score'].value) || 0, flagged: controls.flagged.checked, official: controls.official.checked, adjudicated: controls.adjudicated.checked, investigation: controls.investigation.checked, indicator: controls.indicator.value, legal: controls.legal.value, noticeContext: controls['notice-context'].value, assessment: controls.assessment.value, sector: controls.sector.value, project: controls.project.value, verification: controls.verification.value, sort: controls.sort.value };
}
function render() {
syncSortHeaders();
if (!loaded) return;
// An active filter from a shared URL remains visible even when it matches no records.
for (const id of ['notice-context', 'legal', 'verification', 'official', 'adjudicated', 'investigation']) {
const control = controls[id];
const active = control.type === 'checkbox' ? control.checked : Boolean(control.value);
control.closest('label').hidden = control.closest('label').dataset.available !== 'true' && !active;
if (active) {
if (control.selectedOptions) control.selectedOptions[0].hidden = false;
}
}
document.querySelector('.context-filters').hidden = [...document.querySelectorAll('.context-filters > label')].every(label => label.hidden);
// Selection, sorting and grouping depend only on the controls, the records and review marks:
// page changes and re-renders reuse them.
const options = selectionOptions();
const selectionKey = JSON.stringify([options, controls.review.value, controls['group-by'].value, reviewsVersion]);
if (!selectionMemo || selectionMemo.records !== contracts || selectionMemo.profile !== activeProfile || selectionMemo.key !== selectionKey) {
const pool = activeProfile ? contracts.filter(c => activeProfile.ids.has(c.id)) : contracts;
const filtered = selectContracts(controls.review.value ? pool.filter(reviewMatch) : pool, options);
selectionMemo = { records: contracts, profile: activeProfile, key: selectionKey, arrangement: arrangeGroups(filtered, controls['group-by'].value) };
}
const arrangement = selectionMemo.arrangement;
const visible = arrangement.rows;
visibleRows = visible;
renderProjectPanel();
renderProfilePanel();
const pageCount = Math.max(1, Math.ceil(visible.length / pageSize));
page = Math.min(page, pageCount - 1);
const pageRows = visible.slice(page * pageSize, (page + 1) * pageSize);
pageRowsForCopy = pageRows;
totalResultsForCopy = visible.length;
rowsForExport = visible;
const fragment = document.createDocumentFragment();
pageRows.forEach((c, index) => {
const indicators = getIndicators(c);
if (controls['group-by'].value) {
const info = groupInfo(c, controls['group-by'].value);
const preceding = visible[page * pageSize + index - 1];
if (index === 0 || groupInfo(preceding, controls['group-by'].value).key !== info.key) {
const group = arrangement.groups.get(info.key);
const header = element('tr', null, 'group-row');
const headerCell = element('td', `${group.label} · ${group.contracts.length} filtered result(s)${index === 0 && preceding && groupInfo(preceding, controls['group-by'].value).key === info.key ? ' · continued' : ''}`);
headerCell.colSpan = visibleColumnCount();
if (controls['group-by'].value === 'project' && c.project) {
const link = element('button', 'Open the dossier and its sources', 'group-link');
link.type = 'button';
link.addEventListener('click', () => showProject(c.project.id));
headerCell.append(element('span', ' · '), link);
}
header.append(headerCell);
fragment.append(header);
}
}
const row = element('tr', null, 'contract-row');
row.dataset.id = c.id;