-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1099 lines (954 loc) · 39.8 KB
/
Copy pathapp.js
File metadata and controls
1099 lines (954 loc) · 39.8 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
// Configuration
const DATA_URL = 'cdf_efk_data.json';
// --- TPF (Transparence du financement de la vie politique) ---
const TPF_THEME_PATTERN = /financement\s+(de(s)?\s+(la\s+vie\s+politique|parti|campagne)|politique|électoral)|transparence\s+(du\s+financement|de\s+la\s+vie\s+politique)|politikfinanzierung|parteienfinanzierung|kampagnenfinanzierung|transparenzvorschrift|financement.*campagne.*extraordinaire/i;
function detectTPF(item) {
if (!item.date) return false;
const year = parseInt(item.date.substring(0, 4), 10);
if (year < 2020) return false;
const textToSearch = [
item.title || '', item.title_de || '', item.title_it || '',
item.text || '', item.text_de || ''
].join(' ');
return TPF_THEME_PATTERN.test(textToSearch);
}
function getTPFBadge(item) {
if (!detectTPF(item)) return '';
return '<span class="badge badge-theme badge-theme-tpf">TPF</span>';
}
const EXCEL_URL = 'Objets_parlementaires_CDF_EFK.xlsx';
const INITIAL_ITEMS = 10;
const ITEMS_PER_LOAD = 10;
// State
let allData = [];
let filteredData = [];
let displayedCount = 0;
let newIds = []; // IDs des vrais nouveaux objets
let sessionsData = []; // Données des sessions parlementaires
let sortDescending = true; // true = récent en premier, false = ancien en premier
let businessRapportsMap = {}; // Index rapports CDF par business_number
// DOM Elements
const searchInput = document.getElementById('searchInput');
const clearButton = document.getElementById('clearSearch');
const resultsContainer = document.getElementById('results');
const resultsCount = document.getElementById('resultsCount');
const lastUpdate = document.getElementById('lastUpdate');
const downloadBtn = document.getElementById('downloadBtn');
const resetFiltersBtn = document.getElementById('resetFilters');
const showNewUpdatesBtn = document.getElementById('showNewUpdates');
// Initialize
document.addEventListener('DOMContentLoaded', init);
async function loadRapportsForObjects() {
try {
const [manuelsResp, sessionResp] = await Promise.all([
fetch('rapports_manuels.json').catch(() => null),
fetch('session_rapports_export.json').catch(() => null)
]);
if (manuelsResp) {
const manuels = await manuelsResp.json();
if (manuels?.mappings?.by_object) {
for (const [id, r] of Object.entries(manuels.mappings.by_object)) {
businessRapportsMap[id] = { pa: r.pa, title: r.title, url: r.url, match_type: 'manual' };
}
}
}
if (sessionResp) {
const session = await sessionResp.json();
if (session?.mappings?.by_object) {
for (const [id, r] of Object.entries(session.mappings.by_object)) {
if (!businessRapportsMap[id]) {
businessRapportsMap[id] = { pa: r.pa, title: r.title, url: r.url, match_type: 'session_matcher' };
}
}
}
}
} catch (e) {
console.warn('Rapports non chargés:', e);
}
}
function getRapportBadgeHtml(shortId) {
if (!shortId) return '';
const rapport = businessRapportsMap[shortId];
if (!rapport) return '';
const pa = rapport.pa ? `PA ${rapport.pa}` : 'Rapport CDF';
const tooltip = rapport.title || 'Rapport du CDF lié';
return `<a href="${rapport.url}" target="_blank" class="card-rapport" title="${tooltip}" onclick="event.stopPropagation();">📄 ${pa}</a>`;
}
async function init() {
showLoading();
try {
// Charger les rapports CDF
await loadRapportsForObjects();
// Charger les données des sessions
const sessionsResponse = await fetch('sessions.json');
const sessionsJson = await sessionsResponse.json();
sessionsData = sessionsJson.sessions || [];
const response = await fetch(DATA_URL);
const json = await response.json();
allData = json.items || [];
// Convertir new_ids en tableau si c'est une string
let rawNewIds = json.meta?.new_ids || [];
if (typeof rawNewIds === 'string') {
newIds = rawNewIds.split(',').map(id => id.trim()).filter(id => id);
} else {
newIds = rawNewIds;
}
// Display last update
if (json.meta && json.meta.updated) {
const date = new Date(json.meta.updated);
lastUpdate.textContent = `Mise à jour: ${date.toLocaleDateString('fr-CH')}`;
}
// Display session summary if available
displaySessionSummary(json.session_summary);
// Populate year, party, department and tags filters
populateYearFilter();
populatePartyFilter();
populateDepartmentFilter();
populateTagsFilter();
// Initialize dropdown filters
initDropdownFilters();
// Check for search parameter in URL
const urlParams = new URLSearchParams(window.location.search);
const searchParam = urlParams.get('search');
if (searchParam) {
searchInput.value = searchParam;
}
// Check for filter parameters from stats page
const filterParty = urlParams.get('filter_party');
const filterType = urlParams.get('filter_type');
const filterYear = urlParams.get('filter_year');
const filterSession = urlParams.get('filter_session');
const filterCouncil = urlParams.get('filter_council');
const filterDept = urlParams.get('filter_dept');
const filterLegislature = urlParams.get('filter_legislature');
const filterTags = urlParams.get('filter_tags');
const filterMention = urlParams.get('filter_mention');
if (filterParty) {
applyFilterFromUrl('partyDropdown', filterParty);
}
if (filterType) {
applyFilterFromUrl('typeDropdown', filterType);
}
if (filterYear) {
applyFilterFromUrl('yearDropdown', filterYear);
}
if (filterCouncil) {
applyFilterFromUrl('councilDropdown', filterCouncil);
}
if (filterDept) {
applyFilterFromUrl('departmentDropdown', filterDept);
}
if (filterLegislature) {
applyFilterFromUrl('legislatureDropdown', filterLegislature);
}
if (filterTags) {
applyFilterFromUrl('tagsDropdown', filterTags);
}
if (filterMention) {
applyFilterFromUrl('mentionDropdown', filterMention);
}
// Store session filter for use in applyFilters
window.sessionFilter = filterSession || null;
// Initial display
filteredData = [...allData];
applyFilters();
// Setup event listeners
setupEventListeners();
} catch (error) {
console.error('Error loading data:', error);
showError('Erreur lors du chargement des données');
}
}
function displaySessionSummary(summary) {
if (!summary) return;
// Check if we should display the summary (before next session starts)
const today = new Date();
const displayUntil = summary.display_until ? new Date(summary.display_until) : null;
if (displayUntil && today >= displayUntil) {
return; // Don't display after next session starts
}
const container = document.getElementById('sessionSummary');
const titleEl = document.getElementById('summaryTitle');
const textEl = document.getElementById('summaryText');
const listEl = document.getElementById('summaryInterventions');
if (!container || !titleEl || !textEl || !listEl) return;
titleEl.textContent = summary.title_fr;
textEl.innerHTML = summary.text_fr + (summary.themes_fr ? '<br><br><strong>Thèmes abordés :</strong> ' + escapeHtml(summary.themes_fr) : '');
// Build interventions list
if (summary.interventions && summary.interventions.shortId) {
const items = summary.interventions.shortId.map((id, i) => {
const title = summary.interventions.title[i] || '';
const author = summary.interventions.author[i] || '';
const party = translateParty(summary.interventions.party[i] || '');
const type = summary.interventions.type[i] || '';
const url = summary.interventions.url_fr[i] || '#';
const isCommission = ['Commissions', 'Kommissionen', 'Commissioni'].includes(party);
const authorWithParty = (party && !isCommission) ? `${author} (${party})` : author;
return `<li><a href="${url}" target="_blank">${id}</a> – ${type} – ${escapeHtml(title.substring(0, 60))}${title.length > 60 ? '...' : ''} – <em>${escapeHtml(authorWithParty)}</em></li>`;
});
listEl.innerHTML = items.join('');
}
container.style.display = 'block';
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text || '';
return div.innerHTML;
}
function getSessionTypeFromDate(dateStr) {
if (!dateStr || !sessionsData.length) {
return 'autre';
}
for (const session of sessionsData) {
if (dateStr >= session.start && dateStr <= session.end) {
const parts = session.id.split('-');
if (parts.length >= 2) {
const sessionType = parts[1];
if (sessionType.startsWith('speciale')) return 'speciale';
if (sessionType === 'printemps') return 'printemps';
if (sessionType === 'ete') return 'ete';
if (sessionType === 'automne') return 'automne';
if (sessionType === 'hiver') return 'hiver';
}
return 'autre';
}
}
return 'autre';
}
function translateParty(party) {
const translations = {
'Al': 'VERT-E-S',
'PSS': 'PS',
'M-E': 'Le Centre',
'PDC': 'Le Centre',
'PBD': 'Le Centre',
'CSPO': 'Le Centre',
'CVP': 'Le Centre',
'BDP': 'Le Centre',
'AI': 'VERT-E-S'
};
return translations[party] || party;
}
function translateAuthor(author) {
if (!author) return '';
const translations = {
'Sicherheitspolitische Kommission Nationalrat-Nationalrat': 'CPS-N',
'Sicherheitspolitische Kommission Nationalrat': 'CPS-N',
'Sicherheitspolitische Kommission Ständerat': 'CPS-E',
'FDP-Liberale Fraktion': 'Groupe libéral-radical',
'Grüne Fraktion': 'Groupe des VERT-E-S',
'Sozialdemokratische Fraktion': 'Groupe socialiste',
'SVP-Fraktion': 'Groupe de l\'Union démocratique du centre',
'Fraktion der Schweizerischen Volkspartei': 'Groupe de l\'Union démocratique du centre',
'Fraktion der Mitte': 'Groupe du Centre',
'Die Mitte-Fraktion. Die Mitte. EVP.': 'Groupe du Centre',
'Grünliberale Fraktion': 'Groupe vert\'libéral'
};
return translations[author] || author;
}
function getPartyFromAuthor(author) {
if (!author) return null;
if (author.includes('FDP') || author.includes('PLR') || author.includes('libéral-radical')) return 'PLR';
if (author.includes('Grünliberale') || author.includes('vert\'libéral')) return 'pvl';
if (author.includes('SVP') || author.includes('UDC') || author.includes('Schweizerischen Volkspartei') || author.includes('Union démocratique')) return 'UDC';
if (author.includes('SP ') || author.includes('PS ') || author.includes('socialiste') || author.includes('Sozialdemokratische')) return 'PSS';
if (author.includes('Grüne') || author.includes('Verts') || author.includes('VERT')) return 'VERT-E-S';
if (author.includes('Mitte') || author.includes('Centre') || author.includes('EVP')) return 'Le Centre';
return null;
}
function updateLangSwitcherLinks() {
const searchValue = searchInput.value.trim();
const langLinks = document.querySelectorAll('.lang-switcher a');
langLinks.forEach(link => {
const href = link.getAttribute('href').split('?')[0];
if (searchValue) {
link.setAttribute('href', `${href}?search=${encodeURIComponent(searchValue)}`);
} else {
link.setAttribute('href', href);
}
});
}
function setupEventListeners() {
searchInput.addEventListener('input', () => {
debounce(applyFilters, 300)();
updateLangSwitcherLinks();
});
clearButton.addEventListener('click', clearSearch);
// Download Excel button
if (downloadBtn) {
downloadBtn.addEventListener('click', downloadFilteredData);
}
// Sort order button
const sortOrderBtn = document.getElementById('sortOrderBtn');
if (sortOrderBtn) {
sortOrderBtn.addEventListener('click', toggleSortOrder);
}
// Update lang switcher on load
updateLangSwitcherLinks();
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && searchInput.value) {
clearSearch();
}
if (e.key === '/' && document.activeElement !== searchInput) {
e.preventDefault();
searchInput.focus();
}
});
}
function populateYearFilter() {
const yearMenu = document.getElementById('yearMenu');
const years = [...new Set(allData.map(item => item.date?.substring(0, 4)).filter(Boolean))];
if (!years.includes('2026')) years.push('2026');
years.sort((a, b) => b - a);
// Add "Tous" option (checked by default)
const allLabel = document.createElement('label');
allLabel.className = 'select-all';
allLabel.innerHTML = `<input type="checkbox" data-select-all checked> Tous`;
yearMenu.appendChild(allLabel);
years.forEach(year => {
const label = document.createElement('label');
label.innerHTML = `<input type="checkbox" value="${year}"> ${year}`;
yearMenu.appendChild(label);
});
}
function populatePartyFilter() {
const partyMenu = document.getElementById('partyMenu');
const translatedParties = [...new Set(allData.map(item => translateParty(item.party)).filter(Boolean))];
translatedParties.sort((a, b) => a.localeCompare(b, 'fr'));
// Add "Tous" option (checked by default)
const allLabel = document.createElement('label');
allLabel.className = 'select-all';
allLabel.innerHTML = `<input type="checkbox" data-select-all checked> Tous`;
partyMenu.appendChild(allLabel);
translatedParties.forEach(party => {
const label = document.createElement('label');
label.innerHTML = `<input type="checkbox" value="${party}"> ${party}`;
partyMenu.appendChild(label);
});
}
function translateDepartment(deptDE) {
const translations = {
'EFD': 'DFF',
'EDI': 'DFI',
'UVEK': 'DETEC',
'VBS': 'DDPS',
'EJPD': 'DFJP',
'EDA': 'DFAE',
'WBF': 'DEFR',
'BK': 'ChF',
'BGer': 'TF',
'Parl': 'Parl',
'VBV': 'AF',
'AB-BA': 'AS-MPC'
};
return translations[deptDE] || deptDE;
}
function populateDepartmentFilter() {
const deptMenu = document.getElementById('departmentMenu');
if (!deptMenu) return;
const departments = [...new Set(allData.map(item => item.department).filter(Boolean))];
departments.sort((a, b) => translateDepartment(a).localeCompare(translateDepartment(b), 'fr'));
// Add "Tous" option (checked by default)
const allLabel = document.createElement('label');
allLabel.className = 'select-all';
allLabel.innerHTML = `<input type="checkbox" data-select-all checked> Tous`;
deptMenu.appendChild(allLabel);
departments.forEach(dept => {
const label = document.createElement('label');
const deptFR = translateDepartment(dept);
label.innerHTML = `<input type="checkbox" value="${dept}"> ${deptFR}`;
deptMenu.appendChild(label);
});
}
function populateTagsFilter() {
const tagsMenu = document.getElementById('tagsMenu');
if (!tagsMenu) return;
// Extraire tous les tags uniques (séparés par |)
const allTags = new Set();
allData.forEach(item => {
if (item.tags) {
item.tags.split('|').forEach(tag => {
if (tag.trim()) allTags.add(tag.trim());
});
}
// Ajouter le tag TPF si détecté
if (detectTPF(item)) allTags.add('TPF');
});
const tagsArray = [...allTags].sort((a, b) => a.localeCompare(b, 'fr'));
// Add "Tous" option (checked by default)
const allLabel = document.createElement('label');
allLabel.className = 'select-all';
allLabel.innerHTML = `<input type="checkbox" data-select-all checked> Tous`;
tagsMenu.appendChild(allLabel);
tagsArray.forEach(tag => {
const label = document.createElement('label');
label.innerHTML = `<input type="checkbox" value="${tag}"> ${tag}`;
tagsMenu.appendChild(label);
});
}
function getCheckedValues(dropdownId) {
const dropdown = document.getElementById(dropdownId);
if (!dropdown) return [];
const checkboxes = dropdown.querySelectorAll('input[type="checkbox"]:checked:not([data-select-all])');
return Array.from(checkboxes).map(cb => cb.value).filter(v => v);
}
function updateFilterCount(dropdownId) {
const dropdown = document.getElementById(dropdownId);
if (!dropdown) return;
const countSpan = dropdown.querySelector('.filter-count');
if (!countSpan) return;
const checkboxes = dropdown.querySelectorAll('input[type="checkbox"]:not([data-select-all]):checked');
if (checkboxes.length > 0) {
// Récupérer les labels des filtres sélectionnés
const selectedLabels = Array.from(checkboxes).map(cb => {
const label = cb.parentElement.textContent.trim();
return label;
});
if (selectedLabels.length === 1) {
countSpan.textContent = `: ${selectedLabels[0]}`;
} else if (selectedLabels.length <= 2) {
countSpan.textContent = `: ${selectedLabels.join(', ')}`;
} else {
countSpan.textContent = `: ${selectedLabels[0]} +${selectedLabels.length - 1}`;
}
} else {
countSpan.textContent = '';
}
}
function initDropdownFilters() {
const dropdowns = document.querySelectorAll('.filter-dropdown');
// Toggle dropdown on button click
dropdowns.forEach(dropdown => {
const btn = dropdown.querySelector('.filter-btn');
btn.addEventListener('click', (e) => {
e.stopPropagation();
// Close other dropdowns
dropdowns.forEach(d => {
if (d !== dropdown) d.classList.remove('open');
});
dropdown.classList.toggle('open');
});
// Handle checkbox changes
const checkboxes = dropdown.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(cb => {
cb.addEventListener('change', (e) => {
const isSelectAll = e.target.hasAttribute('data-select-all');
if (isSelectAll && e.target.checked) {
// Uncheck all other checkboxes
dropdown.querySelectorAll('input[type="checkbox"]:not([data-select-all])').forEach(other => {
other.checked = false;
});
} else if (!isSelectAll && e.target.checked) {
// Uncheck "Tous" when selecting specific option
const selectAll = dropdown.querySelector('input[data-select-all]');
if (selectAll) selectAll.checked = false;
}
updateFilterCount(dropdown.id);
applyFilters();
});
});
});
// Close dropdowns when clicking outside
document.addEventListener('click', () => {
dropdowns.forEach(d => d.classList.remove('open'));
});
// Prevent closing when clicking inside menu
document.querySelectorAll('.filter-menu').forEach(menu => {
menu.addEventListener('click', e => e.stopPropagation());
});
// Reset filters button
if (resetFiltersBtn) {
resetFiltersBtn.addEventListener('click', resetAllFilters);
}
// Show new updates button
if (showNewUpdatesBtn) {
showNewUpdatesBtn.addEventListener('click', toggleNewUpdatesFilter);
}
}
function toggleNewUpdatesFilter() {
window.newUpdatesFilter = !window.newUpdatesFilter;
if (window.newUpdatesFilter) {
showNewUpdatesBtn.classList.add('active');
} else {
showNewUpdatesBtn.classList.remove('active');
}
applyFilters();
}
function resetAllFilters() {
document.querySelectorAll('.filter-dropdown input[type="checkbox"]').forEach(cb => {
cb.checked = false;
});
// Recheck "Tous" by default
document.querySelectorAll('.filter-dropdown input[data-select-all]').forEach(cb => {
cb.checked = true;
});
document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
updateFilterCount(dropdown.id);
});
searchInput.value = '';
// Clear session filter
window.sessionFilter = null;
// Clear new updates filter
window.newUpdatesFilter = false;
if (showNewUpdatesBtn) {
showNewUpdatesBtn.classList.remove('active');
}
// Clear URL parameters
if (window.history.replaceState) {
window.history.replaceState({}, document.title, window.location.pathname);
}
applyFilters();
}
function applyFilterFromUrl(dropdownId, filterValue) {
const dropdown = document.getElementById(dropdownId);
if (!dropdown) return;
// Support multiple values separated by comma
const filterValues = filterValue.split(',').map(v => v.trim());
// Uncheck "Tous"
const selectAll = dropdown.querySelector('input[data-select-all]');
if (selectAll) selectAll.checked = false;
// Check the matching checkboxes
const checkboxes = dropdown.querySelectorAll('input[type="checkbox"]:not([data-select-all])');
checkboxes.forEach(cb => {
if (filterValues.includes(cb.value)) {
cb.checked = true;
}
});
updateFilterCount(dropdownId);
}
function applyFilters() {
const searchTerm = searchInput.value.toLowerCase().trim();
const typeValues = getCheckedValues('typeDropdown');
const councilValues = getCheckedValues('councilDropdown');
const yearValues = getCheckedValues('yearDropdown');
const partyValues = getCheckedValues('partyDropdown');
const departmentValues = getCheckedValues('departmentDropdown');
const tagsValues = getCheckedValues('tagsDropdown');
const legislatureValues = getCheckedValues('legislatureDropdown');
const mentionValues = getCheckedValues('mentionDropdown');
filteredData = allData.filter(item => {
// Text search avec word boundaries
if (searchTerm) {
const searchFields = [
item.shortId,
item.title,
item.title_de,
item.author,
item.type,
item.status,
item.text, // Texte de l'objet
item.text_de // Texte allemand
].filter(Boolean).join(' ');
if (!searchWholeWord(searchFields, searchTerm)) {
return false;
}
}
// Type filter (multiple)
if (typeValues.length > 0 && !typeValues.includes(item.type)) {
return false;
}
// Council filter (multiple)
if (councilValues.length > 0 && !councilValues.includes(item.council)) {
return false;
}
// Year filter (multiple)
if (yearValues.length > 0) {
const itemYear = item.date?.substring(0, 4);
if (!yearValues.includes(itemYear)) {
return false;
}
}
// Session filter (from URL) - utilise les dates exactes des sessions
if (window.sessionFilter && item.date) {
const itemSessionType = getSessionTypeFromDate(item.date);
if (itemSessionType !== window.sessionFilter) {
return false;
}
}
// New updates filter (< 4 jours, cohérent avec la bande verte)
if (window.newUpdatesFilter) {
const now = new Date();
const fourDaysAgo = new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000);
const itemDateStr = item.date_maj || item.date || '';
const itemDate = itemDateStr ? new Date(itemDateStr + 'T12:00:00') : null;
const isRecent = itemDate ? itemDate >= fourDaysAgo : false;
if (!isRecent) {
return false;
}
}
// Party filter (multiple)
if (partyValues.length > 0) {
const itemParty = translateParty(item.party) || getPartyFromAuthor(item.author);
if (!partyValues.includes(itemParty)) {
return false;
}
}
// Department filter (multiple)
if (departmentValues.length > 0) {
const itemDept = item.department || 'none';
if (!departmentValues.includes(itemDept)) {
return false;
}
}
// Tags filter (multiple) - un objet passe si au moins un de ses tags est sélectionné
if (tagsValues.length > 0) {
const itemTags = item.tags ? item.tags.split('|').map(t => t.trim()) : [];
// Ajouter le tag TPF dynamiquement si détecté
if (detectTPF(item)) itemTags.push('TPF');
const hasMatchingTag = itemTags.some(tag => tagsValues.includes(tag));
if (!hasMatchingTag) {
return false;
}
}
// Legislature filter (multiple)
if (legislatureValues.length > 0) {
const itemLegislature = getLegislature(item.date);
if (!legislatureValues.includes(itemLegislature)) {
return false;
}
}
// Mention filter (qui cite le CDF)
if (mentionValues.length > 0) {
const mentionMap = {
'elu': 'Élu',
'cf': 'Conseil fédéral',
'both': 'Élu & Conseil fédéral'
};
const itemMention = item.mention || '';
const matchesMention = mentionValues.some(v => mentionMap[v] === itemMention);
if (!matchesMention) {
return false;
}
}
return true;
});
// Trier par date, puis par date_maj, puis par numéro
filteredData.sort((a, b) => {
const dateA = a.date || '';
const dateB = b.date || '';
if (dateA !== dateB) {
return sortDescending ? dateB.localeCompare(dateA) : dateA.localeCompare(dateB);
}
// Même date: MAJ récente/ancienne selon l'ordre
const majA = a.date_maj || '';
const majB = b.date_maj || '';
if (majA !== majB) {
return sortDescending ? majB.localeCompare(majA) : majA.localeCompare(majB);
}
// Même date et MAJ: trier par numéro
return sortDescending ? (b.shortId || '').localeCompare(a.shortId || '') : (a.shortId || '').localeCompare(b.shortId || '');
});
currentPage = 1;
renderResults();
updateURL();
}
function updateURL() {
const params = new URLSearchParams();
// Search term
const searchTerm = searchInput.value.trim();
if (searchTerm) params.set('search', searchTerm);
// Year filter
const yearValues = getCheckedValues('yearDropdown');
if (yearValues && yearValues.length > 0) {
params.set('filter_year', yearValues.join(','));
}
if (window.sessionFilter) params.set('filter_session', window.sessionFilter);
const typeValues = getCheckedValues('typeDropdown');
if (typeValues && typeValues.length > 0) {
params.set('filter_type', typeValues.join(','));
}
const councilValues = getCheckedValues('councilDropdown');
if (councilValues && councilValues.length > 0) {
params.set('filter_council', councilValues.join(','));
}
const partyValues = getCheckedValues('partyDropdown');
if (partyValues && partyValues.length > 0) {
params.set('filter_party', partyValues.join(','));
}
const departmentValues = getCheckedValues('departmentDropdown');
if (departmentValues && departmentValues.length > 0) {
params.set('filter_department', departmentValues.join(','));
}
const legislatureValues = getCheckedValues('legislatureDropdown');
if (legislatureValues && legislatureValues.length > 0) {
params.set('filter_legislature', legislatureValues.join(','));
}
if (window.newUpdatesFilter) params.set('nouveautes', '1');
// Update URL without reload
const newUrl = params.toString() ? `${window.location.pathname}?${params.toString()}` : window.location.pathname;
window.history.replaceState({}, document.title, newUrl);
}
function clearSearch() {
searchInput.value = '';
typeFilter.value = '';
councilFilter.value = '';
yearFilter.value = '';
partyFilter.value = '';
searchInput.focus();
applyFilters();
}
function toggleSortOrder() {
sortDescending = !sortDescending;
const btn = document.getElementById('sortOrderBtn');
if (btn) {
btn.textContent = sortDescending ? '↓ Récent' : '↑ Ancien';
}
applyFilters();
}
function renderResults(loadMore = false) {
// Update count
resultsCount.textContent = `${filteredData.length} intervention${filteredData.length !== 1 ? 's' : ''} trouvée${filteredData.length !== 1 ? 's' : ''}`;
if (filteredData.length === 0) {
resultsContainer.innerHTML = `
<div class="empty-state">
<h3>Aucun résultat</h3>
<p>Essayez de modifier vos critères de recherche</p>
</div>
`;
displayedCount = 0;
return;
}
const searchTerm = searchInput.value.toLowerCase().trim();
if (!loadMore) {
displayedCount = Math.min(INITIAL_ITEMS, filteredData.length);
resultsContainer.innerHTML = '';
} else {
displayedCount = Math.min(displayedCount + ITEMS_PER_LOAD, filteredData.length);
// Remove old show more button
const oldBtn = document.getElementById('showMoreBtn');
if (oldBtn) oldBtn.remove();
}
const itemsToShow = filteredData.slice(0, displayedCount);
resultsContainer.innerHTML = itemsToShow.map(item => createCard(item, searchTerm)).join('');
// Add "Show more" button if there are more items
if (displayedCount < filteredData.length) {
const remaining = filteredData.length - displayedCount;
resultsContainer.innerHTML += `
<div class="show-more-container">
<button id="showMoreBtn" class="btn-show-more">Afficher plus (${remaining} restant${remaining > 1 ? 's' : ''})</button>
</div>
`;
document.getElementById('showMoreBtn').addEventListener('click', () => renderResults(true));
}
}
function getMentionEmojis(mention) {
if (!mention) return { emojis: '🧑', tooltip: "L'auteur cite le CDF" };
const hasElu = mention.includes('Élu');
const hasCF = mention.includes('Conseil fédéral');
if (hasElu && hasCF) {
return { emojis: '🧑 🏛️', tooltip: "L'auteur et le Conseil fédéral citent le CDF" };
} else if (hasCF) {
return { emojis: '🏛️', tooltip: "Le Conseil fédéral cite le CDF" };
} else {
return { emojis: '🧑', tooltip: "L'auteur cite le CDF" };
}
}
function translateType(type) {
const translations = {
'Interpellation': 'Interpellation',
'Ip.': 'Ip.',
'Dringliche Interpellation': 'Interpellation urgente',
'D.Ip.': 'Ip. urg.',
'Motion': 'Motion',
'Mo.': 'Mo.',
'Fragestunde': 'Heure des questions',
'Fra.': 'Heure des questions',
'Geschäft des Bundesrates': 'Objet du Conseil fédéral',
'Postulat': 'Postulat',
'Po.': 'Po.',
'Anfrage': 'Question',
'A.': 'Question',
'Parlamentarische Initiative': 'Initiative parlementaire',
'Pa.Iv.': 'Iv. pa.',
'Pa. Iv.': 'Iv. pa.',
'Geschäft des Parlaments': 'Objet du Parlement'
};
return translations[type] || type;
}
function isTitleMissing(title) {
if (!title) return true;
const missing = ['titre suit', 'titel folgt', 'titolo segue', ''];
return missing.includes(title.toLowerCase().trim());
}
function isRecentlyUpdated(dateStr, days) {
if (!dateStr) return false;
const date = new Date(dateStr);
const now = new Date();
const diffTime = now - date;
const diffDays = diffTime / (1000 * 60 * 60 * 24);
return diffDays <= days;
}
function createCard(item, searchTerm) {
const frMissing = isTitleMissing(item.title);
const displayTitle = frMissing && item.title_de ? item.title_de : (item.title || item.title_de);
const title = highlightText(displayTitle, searchTerm);
const langWarning = frMissing && item.title_de ? '<span class="lang-warning">🌐 Uniquement en allemand</span>' : '';
const authorName = translateAuthor(item.author || '');
const partyFR = translateParty(item.party || '');
const isCommissionParty = ['Commissions', 'Kommissionen', 'Commissioni'].includes(partyFR);
const authorWithParty = (partyFR && !isCommissionParty) ? `${authorName} (${partyFR})` : authorName;
const author = highlightText(authorWithParty, searchTerm);
// Bande verte si mise à jour < 4 jours
const now = new Date();
const fourDaysAgo = new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000);
const itemDateStr = item.date_maj || item.date || '';
const itemDate = itemDateStr ? new Date(itemDateStr + 'T12:00:00') : null;
const isRecent = itemDate ? itemDate >= fourDaysAgo : false;
// Si date_maj_langs est défini, n'afficher la barre verte que si 'fr' est inclus
const langRestriction = item.date_maj_langs;
const isNew = isRecent && (!langRestriction || langRestriction.split(',').includes('fr'));
const shortId = highlightText(item.shortId, searchTerm);
const date = item.date ? new Date(item.date).toLocaleDateString('fr-CH') : '';
const dateMaj = item.date_maj ? new Date(item.date_maj).toLocaleDateString('fr-CH') : '';
// Afficher 🔄 si date de mise à jour existe et différente de la date de dépôt
const showDateMaj = dateMaj && dateMaj !== date;
const url = item.url_fr || item.url_de;
const mentionData = getMentionEmojis(item.mention);
// Status badge color
let statusClass = 'badge-status';
if (item.status?.includes('Erledigt') || item.status?.includes('Liquidé')) {
statusClass += ' badge-done';
}
return `
<article class="card${isNew ? ' card-new' : ''}">
<div class="card-header">
<span class="card-id">${shortId}</span>
<div class="card-badges">
<span class="badge badge-type">${translateType(item.type)}</span>
<span class="badge badge-council">${item.council === 'NR' ? 'CN' : 'CE'}</span>
<span class="badge badge-mention" title="${mentionData.tooltip}">${mentionData.emojis}</span>
${getTPFBadge(item)}
${getRapportBadgeHtml(shortId)}
</div>
</div>
<h3 class="card-title">
<a href="${url}" target="_blank" rel="noopener">${title}</a>
</h3>
${langWarning}
<div class="card-meta">
<span>👤 ${author}</span>
<span>📅 ${date}${showDateMaj ? ` · 🔄 ${dateMaj}` : ''}</span>
</div>
${item.status ? `<div style="margin-top: 0.5rem;"><span class="badge ${statusClass}">${getStatusFR(item.status)}</span></div>` : ''}
</article>
`;
}
function createPagination(totalPages) {
return `
<div class="pagination">
<button id="prevPage" ${currentPage === 1 ? 'disabled' : ''}>← Précédent</button>
<span>Page ${currentPage} / ${totalPages}</span>
<button id="nextPage" ${currentPage === totalPages ? 'disabled' : ''}>Suivant →</button>
</div>
`;
}
function setupPaginationListeners() {
const prevBtn = document.getElementById('prevPage');
const nextBtn = document.getElementById('nextPage');
if (prevBtn) {
prevBtn.addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderResults();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
});
}
if (nextBtn) {
nextBtn.addEventListener('click', () => {
const totalPages = Math.ceil(filteredData.length / ITEMS_PER_PAGE);
if (currentPage < totalPages) {
currentPage++;
renderResults();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
});
}
}