-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2727 lines (2339 loc) · 101 KB
/
Copy pathapp.js
File metadata and controls
2727 lines (2339 loc) · 101 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
// Configuración
const CONFIG = {
// Lista de proxies CORS (se usará el primero que funcione).
CORS_PROXIES: [
'https://renfe-proxy.vvictor-97.workers.dev/?url=', // Cloudflare Worker — prioritario
'https://api.allorigins.win/raw?url=', // Fallback 1
'https://api.codetabs.com/v1/proxy?quest=', // Fallback 2
'https://corsproxy.io/?', // Fallback 3
'https://thingproxy.freeboard.io/fetch/', // Fallback 4
'' // Sin proxy
],
CURRENT_PROXY_INDEX: 0,
POLL_INTERVAL: 15000, // 15 segundos
API_TIMEOUT: 30000, // 30 segundos antes de que el estado cambie a desconectado
FLEET_URL: 'https://tiempo-real.largorecorrido.renfe.com/renfe-visor/flotaLD.json',
ROUTES_URL: 'https://tiempo-real.largorecorrido.renfe.com/renfe-visor/trenesConEstacionesLD.json',
STATIONS_URL: './estaciones.geojson', // Archivo local estático (las estaciones no cambian)
ON_TIME_THRESHOLD: 5 // Margen de tolerancia en minutos para considerar un tren "a tiempo"
};
// Train type mapping (códigos de producto de Renfe)
const TRAIN_TYPES = {
1: 'Largo Recorrido',
2: 'AVE',
3: 'Avant',
4: 'Talgo',
5: 'Altaria',
6: 'Euromed',
7: 'Diurno',
8: 'Estrella',
9: 'Tren Hotel',
10: 'Trenhotel',
11: 'Alvia',
12: 'Arco',
13: 'Intercity',
14: 'Talgo 200',
15: 'MD',
16: 'Media Distancia',
17: 'Cercanías',
18: 'Regional',
19: 'Regional Express',
20: 'Alaris',
25: 'AVE TGV',
28: 'AVLO',
29: 'Trenhotel Lusitania'
};
const TRAIN_TYPE_COLORS = {
'AVE': '#e74c3c',
'Avant': '#3498db',
'Talgo': '#2ecc71',
'Diurno': '#f39c12',
'Estrella': '#9b59b6',
'Tren Hotel': '#1abc9c',
'Alvia': '#e67e22',
'Intercity': '#34495e',
'Media Distancia': '#16a085',
'Regional': '#27ae60',
'Regional Express': '#2980b9',
'AVE TGV': '#c0392b',
'AVLO': '#8e44ad',
'Largo Recorrido': '#95a5a6',
'Altaria': '#d35400',
'Euromed': '#2c3e50',
'Trenhotel': '#16a085',
'Arco': '#7f8c8d',
'Talgo 200': '#27ae60',
'MD': '#16a085',
'Cercanías': '#95a5a6',
'Alaris': '#e67e22',
'Trenhotel Lusitania': '#1abc9c'
};
// Global state
const state = {
fleetData: [],
routesData: [],
stationsData: null,
stationMap: {}, // Map of station codes to names
timeSeriesData: [],
watchedTrains: new Set(),
lastFetchTime: null,
pollInterval: null,
mapMode: 'heatmap', // 'heatmap' or 'markers'
map: null,
charts: {},
previousDelays: {}, // For notification tracking
initialLoadComplete: false,
dashboardMode: 'live', // 'live' or 'historical'
currentHistoricalDate: null,
liveDataCache: null, // Cache para restaurar datos en vivo
timeseriesMode: 'live', // 'live' or 'historical'
currentTimeseriesDate: null
};
// ============================================================================
// DATA FETCHING
// ============================================================================
async function fetchDataWithFallback(url) {
let lastError = null;
// Probar cada proxy en orden (siempre empezar desde el preferido)
for (let i = 0; i < CONFIG.CORS_PROXIES.length; i++) {
// Intentar primero con el proxy preferido, luego el resto
const proxyIndex = (CONFIG.CURRENT_PROXY_INDEX + i) % CONFIG.CORS_PROXIES.length;
const proxy = CONFIG.CORS_PROXIES[proxyIndex];
try {
const urlWithCache = url + (url.includes('?') ? '&' : '?') + 'v=' + Date.now();
const fullUrl = proxy
? proxy + encodeURIComponent(urlWithCache)
: urlWithCache;
console.log(`Intentando con proxy ${proxyIndex + 1}/${CONFIG.CORS_PROXIES.length}:`, fullUrl.substring(0, 100) + '...');
const response = await fetch(fullUrl, {
signal: AbortSignal.timeout(6000) // 6 segundos por proxy
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// Éxito! Guardar este proxy como el preferido
if (CONFIG.CURRENT_PROXY_INDEX !== proxyIndex) {
console.log(`🔄 Cambiando proxy preferido a: ${CONFIG.CORS_PROXIES[proxyIndex] || 'directo'}`);
CONFIG.CURRENT_PROXY_INDEX = proxyIndex;
}
console.log(`✅ Proxy ${proxyIndex + 1} funcionando. Datos obtenidos: ${Array.isArray(data) ? data.length : Object.keys(data).length} elementos`);
return data;
} catch (error) {
lastError = error;
console.warn(`❌ Proxy ${proxyIndex + 1} (${CONFIG.CORS_PROXIES[proxyIndex] || 'directo'}) falló:`, error.message);
// Intentar con el siguiente proxy
continue;
}
}
// Si ningún proxy funcionó, resetear el índice para reintentar desde el principio la próxima vez
console.error('⚠️ Todos los proxies fallaron. Se reintentará desde el principio en la próxima actualización.');
CONFIG.CURRENT_PROXY_INDEX = 0;
throw new Error(`Todos los proxies fallaron. Último error: ${lastError?.message || 'Desconocido'}`);
}
async function updateData() {
// Si estamos en modo histórico, no actualizar datos en vivo
if (state.dashboardMode === 'historical') {
console.log('🕒 Modo histórico activo, omitiendo actualización en vivo');
return;
}
try {
console.log('Iniciando actualización de datos...');
const [fleetData, routesData] = await Promise.all([
fetchDataWithFallback(CONFIG.FLEET_URL),
fetchDataWithFallback(CONFIG.ROUTES_URL)
]);
// La API de Renfe devuelve objetos con estructura {fechaActualizacion: "...", trenes: [...]}
// Extraer el array de la propiedad 'trenes'
const actualFleetData = Array.isArray(fleetData) ? fleetData : (fleetData?.trenes || []);
const actualRoutesData = Array.isArray(routesData) ? routesData : (routesData?.trenes || []);
console.log('✅ Datos obtenidos:', {
trenes: actualFleetData.length,
rutas: actualRoutesData.length,
actualizacion: fleetData?.fechaActualizacion || 'N/D'
});
state.fleetData = actualFleetData;
state.routesData = actualRoutesData;
state.lastFetchTime = Date.now();
updateStatusIndicator(true);
updateLastUpdateTime();
processTimeSeriesData();
updateAllSections();
checkWatchedTrains();
// Hide loading overlay on first successful load
if (!state.initialLoadComplete) {
state.initialLoadComplete = true;
setTimeout(() => {
const overlay = document.getElementById('loadingOverlay');
if (overlay) {
overlay.classList.add('hidden');
setTimeout(() => overlay.remove(), 500);
}
}, 500);
}
} catch (error) {
console.error('Error al obtener datos:', error);
updateStatusIndicator(false);
// Ocultar el overlay aunque falle la carga inicial
if (!state.initialLoadComplete) {
state.initialLoadComplete = true;
const overlay = document.getElementById('loadingOverlay');
if (overlay) {
const loadingText = overlay.querySelector('.loading-text');
if (loadingText) loadingText.textContent = 'Sin conexión con Renfe. Reintentando…';
setTimeout(() => {
overlay.classList.add('hidden');
setTimeout(() => overlay.remove(), 500);
}, 2000);
}
}
}
}
async function loadStationsData() {
try {
// Archivo local, no necesita proxy CORS
const response = await fetch(CONFIG.STATIONS_URL);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const geojson = await response.json();
state.stationsData = geojson;
// Create station code to name mapping for faster lookups
state.stationMap = {};
if (geojson.features) {
geojson.features.forEach(feature => {
const code = feature.properties.CODIGO;
const name = feature.properties.NOMBRE;
if (code && name) {
state.stationMap[code] = name;
}
});
}
console.log('✅ Estaciones cargadas desde archivo local:', Object.keys(state.stationMap).length, 'estaciones');
} catch (error) {
console.error('Failed to load stations:', error);
}
}
// Helper function to get proper corridor name
function getCorridorName(train) {
const corridor = train.desCorridor || '';
// If corridor looks like a code (LMDxxxx or similar), construct from origin/destination
if (!corridor || corridor.match(/^[A-Z]{2,3}\d+/)) {
const originCode = parseInt(train.codOrigen);
const destCode = parseInt(train.codDestino);
if (state.stationMap && originCode && destCode) {
const originName = state.stationMap[originCode];
const destName = state.stationMap[destCode];
if (originName && destName) {
return `${originName} - ${destName}`;
}
}
// Fallback if we can't find the stations
return corridor || 'Ruta no disponible';
}
return corridor;
}
let consecutiveFailures = 0;
function updateStatusIndicator(success) {
const dot = document.getElementById('statusDot');
const text = document.getElementById('statusText');
if (success) {
consecutiveFailures = 0;
dot.className = 'status-dot live';
text.textContent = 'EN VIVO';
} else {
consecutiveFailures++;
// Solo muestra DESCONECTADO tras 3 fallos consecutivos (evita alarmas falsas)
if (consecutiveFailures >= 3) {
dot.className = 'status-dot offline';
text.textContent = 'DESCONECTADO';
}
}
}
function updateLastUpdateTime() {
const elem = document.getElementById('lastUpdate');
if (state.lastFetchTime) {
const date = new Date(state.lastFetchTime);
elem.textContent = `Última actualización: ${date.toLocaleTimeString('es-ES')}`;
}
}
function startPolling() {
updateData(); // Initial fetch
state.pollInterval = setInterval(updateData, CONFIG.POLL_INTERVAL);
// Check if data is stale
setInterval(() => {
if (state.lastFetchTime && Date.now() - state.lastFetchTime > CONFIG.API_TIMEOUT) {
updateStatusIndicator(false);
}
}, 5000);
}
// ============================================================================
// TIME SERIES DATA PROCESSING
// ============================================================================
function processTimeSeriesData() {
if (!state.fleetData || state.fleetData.length === 0) {
console.warn('⚠️ No hay datos de trenes para procesar series temporales');
return;
}
const timestamp = state.lastFetchTime;
// Calculate overall average delay
const delays = state.fleetData.map(t => parseInt(t.ultRetraso || 0));
const avgDelay = delays.length > 0 ? delays.reduce((a, b) => a + b, 0) / delays.length : 0;
// Calculate average delay per train type
const delaysByType = {};
state.fleetData.forEach(train => {
const type = TRAIN_TYPES[train.codProduct] || 'Unknown';
if (!delaysByType[type]) delaysByType[type] = [];
delaysByType[type].push(parseInt(train.ultRetraso || 0));
});
const dataPoint = {
timestamp,
avgDelay,
byType: {}
};
Object.keys(delaysByType).forEach(type => {
const avg = delaysByType[type].reduce((a, b) => a + b, 0) / delaysByType[type].length;
dataPoint.byType[type] = avg;
});
state.timeSeriesData.push(dataPoint);
console.log('📊 Serie temporal agregada:', {
puntos: state.timeSeriesData.length,
retrasoPromedio: avgDelay.toFixed(1),
tiposUnicos: Object.keys(delaysByType).length
});
// Keep only last 500 points (about 2 hours at 15s intervals)
if (state.timeSeriesData.length > 500) {
state.timeSeriesData = state.timeSeriesData.slice(-500);
}
// Persist to localStorage
try {
localStorage.setItem('renfe_timeseries', JSON.stringify(state.timeSeriesData));
} catch (e) {
console.warn('Failed to save to localStorage:', e);
}
}
function loadTimeSeriesFromStorage() {
try {
const data = localStorage.getItem('renfe_timeseries');
if (data) {
state.timeSeriesData = JSON.parse(data);
// Filtrar datos inválidos (sin byType o formato incorrecto)
state.timeSeriesData = state.timeSeriesData.filter(d =>
d && d.byType && typeof d.byType === 'object'
);
// Migración: Eliminar datos con tipos "Unknown" antiguos
// Si hay muchos "Unknown", probablemente son datos viejos con códigos no mapeados
const unknownCount = state.timeSeriesData.filter(d =>
Object.keys(d.byType).includes('Unknown')
).length;
// Si más del 10% de los datos tienen "Unknown", limpiar el historial
if (unknownCount > state.timeSeriesData.length * 0.1) {
console.log('🔄 Limpiando datos históricos con tipos no mapeados');
state.timeSeriesData = [];
localStorage.removeItem('renfe_timeseries');
}
}
} catch (e) {
console.warn('Failed to load from localStorage:', e);
state.timeSeriesData = [];
localStorage.removeItem('renfe_timeseries');
}
}
// ============================================================================
// SECTION 1: LIVE PUNCTUALITY DASHBOARD
// ============================================================================
function updatePunctualityDashboard() {
const trains = state.fleetData;
const delays = trains.map(t => parseInt(t.ultRetraso || 0));
// Summary cards
document.getElementById('totalTrains').textContent = trains.length;
// Subtítulo del primer KPI: trenes con retraso
const delayedCount = delays.filter(d => d > CONFIG.ON_TIME_THRESHOLD).length;
const subtitle = document.getElementById('trainsSubtitle');
if (subtitle) {
subtitle.textContent = delayedCount > 0
? `${delayedCount} con retraso · ${trains.length - delayedCount} a tiempo`
: 'Todos a tiempo';
subtitle.className = 'card-subtitle' + (delayedCount > 0 ? ' has-delays' : ' all-on-time');
}
// Título dinámico de la pestaña
document.title = delayedCount > 0
? `🔴 Renfetraso · ${delayedCount} retrasados`
: '✅ Renfetraso · Monitor de Puntualidad';
// Un tren se considera "a tiempo" si tiene menos de CONFIG.ON_TIME_THRESHOLD minutos de retraso
const onTime = delays.filter(d => d <= CONFIG.ON_TIME_THRESHOLD).length;
const onTimePercent = trains.length > 0 ? ((onTime / trains.length) * 100).toFixed(1) : 0;
document.getElementById('onTimePercent').textContent = onTimePercent + '%';
const avgDelay = delays.length > 0 ? (delays.reduce((a, b) => a + b, 0) / delays.length).toFixed(1) : 0;
document.getElementById('avgDelay').textContent = avgDelay;
const maxDelay = delays.length > 0 ? Math.max(...delays) : 0;
document.getElementById('maxDelay').textContent = maxDelay;
// Top 5 most delayed trains
updateTopDelayedTrains(trains);
// Delay distribution chart
updateDelayDistributionChart(delays);
// Delay by type chart
updateDelayByTypeChart(trains);
// Delay by corridor chart
updateDelayByCorridorChart(trains);
}
function updateTopDelayedTrains(trains) {
const container = document.getElementById('topDelayedTrains');
// Sort by delay descending and take top 5
// Only show trains with delays > ON_TIME_THRESHOLD
const topDelayed = trains
.filter(t => parseInt(t.ultRetraso || 0) > CONFIG.ON_TIME_THRESHOLD)
.sort((a, b) => parseInt(b.ultRetraso || 0) - parseInt(a.ultRetraso || 0))
.slice(0, 5);
if (topDelayed.length === 0) {
container.innerHTML = '<div class="no-data"><span class="material-symbols-outlined">check_circle</span> ¡Todos los trenes están a tiempo!</div>';
return;
}
container.innerHTML = topDelayed.map((train, index) => {
const delay = parseInt(train.ultRetraso || 0);
const ranks = ['#1', '#2', '#3', '#4', '#5'];
const rankColors = ['#FFD700', '#C0C0C0', '#CD7F32', '#3498db', '#3498db'];
return `
<div class="top-delayed-item">
<div class="delayed-rank" style="color: ${rankColors[index]}">${ranks[index]}</div>
<div class="delayed-info">
<div class="delayed-train-id">Tren ${train.codComercial}</div>
<div class="delayed-corridor">${getCorridorName(train)}</div>
</div>
<div class="delayed-type">${TRAIN_TYPES[train.codProduct] || 'Desconocido'}</div>
<div class="delayed-time">+${delay} min</div>
</div>
`;
}).join('');
}
function updateDelayDistributionChart(delays) {
const ranges = {
'0 min': 0,
'1-5': 0,
'6-15': 0,
'16-30': 0,
'31-60': 0,
'60+': 0
};
delays.forEach(d => {
if (d === 0) ranges['0 min']++;
else if (d <= 5) ranges['1-5']++;
else if (d <= 15) ranges['6-15']++;
else if (d <= 30) ranges['16-30']++;
else if (d <= 60) ranges['31-60']++;
else ranges['60+']++;
});
const ctx = document.getElementById('delayDistChart');
if (state.charts.delayDist) {
state.charts.delayDist.data.datasets[0].data = Object.values(ranges);
state.charts.delayDist.update();
} else {
const existingChart = Chart.getChart(ctx);
if (existingChart) existingChart.destroy();
state.charts.delayDist = new Chart(ctx, {
type: 'bar',
data: {
labels: Object.keys(ranges),
datasets: [{
label: 'Número de Trenes',
data: Object.values(ranges),
backgroundColor: ['#2ecc71', '#f1c40f', '#e67e22', '#e74c3c', '#c0392b', '#8b0000']
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: { display: false }
},
scales: {
y: { beginAtZero: true }
}
}
});
}
}
function updateDelayByTypeChart(trains) {
const delaysByType = {};
trains.forEach(train => {
const type = TRAIN_TYPES[train.codProduct] || 'Unknown';
if (!delaysByType[type]) delaysByType[type] = [];
delaysByType[type].push(parseInt(train.ultRetraso || 0));
});
const labels = Object.keys(delaysByType);
const avgDelays = labels.map(type => {
const delays = delaysByType[type];
return (delays.reduce((a, b) => a + b, 0) / delays.length).toFixed(1);
});
const colors = labels.map(type => TRAIN_TYPE_COLORS[type] || '#95a5a6');
const ctx = document.getElementById('delayByTypeChart');
const wrapper = ctx.closest('.delay-type-chart-wrapper');
const rowHeight = window.innerWidth < 480 ? 36 : 32;
const chartHeight = Math.max(240, labels.length * rowHeight);
wrapper.style.height = chartHeight + 'px';
if (state.charts.delayByType) {
state.charts.delayByType.data.labels = labels;
state.charts.delayByType.data.datasets[0].data = avgDelays;
state.charts.delayByType.data.datasets[0].backgroundColor = colors;
state.charts.delayByType.update();
} else {
const existingChart = Chart.getChart(ctx);
if (existingChart) existingChart.destroy();
state.charts.delayByType = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [{
label: 'Retraso Promedio (min)',
data: avgDelays,
backgroundColor: colors
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
title: (items) => labels[items[0].dataIndex]
}
}
},
scales: {
x: { beginAtZero: true },
y: {
ticks: {
font: { size: 12 },
callback: function(val, index) {
const label = labels[index] || String(val);
return label.length > 15 ? label.slice(0, 14) + '…' : label;
}
}
}
}
}
});
}
}
function updateDelayByCorridorChart(trains) {
const delaysByCorridor = {};
trains.forEach(train => {
const corridor = getCorridorName(train);
if (!delaysByCorridor[corridor]) delaysByCorridor[corridor] = [];
delaysByCorridor[corridor].push(parseInt(train.ultRetraso || 0));
});
const corridorAvgs = Object.entries(delaysByCorridor).map(([corridor, delays]) => ({
corridor,
avg: delays.reduce((a, b) => a + b, 0) / delays.length
}));
corridorAvgs.sort((a, b) => b.avg - a.avg);
const top10 = corridorAvgs.slice(0, 10);
const labels = top10.map(c => c.corridor);
const data = top10.map(c => c.avg.toFixed(1));
const ctx = document.getElementById('delayByCorridorChart');
if (state.charts.delayByCorridor) {
state.charts.delayByCorridor.data.labels = labels;
state.charts.delayByCorridor.data.datasets[0].data = data;
state.charts.delayByCorridor.update();
} else {
const existingChart = Chart.getChart(ctx);
if (existingChart) existingChart.destroy();
state.charts.delayByCorridor = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [{
label: 'Retraso Promedio (min)',
data,
backgroundColor: '#e74c3c'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
plugins: {
legend: { display: false }
},
scales: {
x: { beginAtZero: true },
y: {
ticks: { autoSkip: false },
afterFit: function(scale) {
scale.width = 220;
}
}
}
}
});
}
}
// ============================================================================
// SECTION 2: DELAY TIME SERIES
// ============================================================================
function updateTimeSeries() {
if (state.timeSeriesData.length === 0) return;
const typeToggles = document.getElementById('typeToggles');
const allTypes = new Set();
state.timeSeriesData.forEach(dp => {
if (dp.byType && typeof dp.byType === 'object') {
Object.keys(dp.byType).forEach(type => allTypes.add(type));
}
});
// Add new type toggles (supports types appearing after first update)
const existingTypes = new Set(
Array.from(typeToggles.querySelectorAll('.type-toggle')).map(cb => cb.dataset.type)
);
Array.from(allTypes).sort().forEach(type => {
if (!existingTypes.has(type)) {
const label = document.createElement('label');
label.innerHTML = `<input type="checkbox" class="type-toggle" data-type="${type}" checked> ${type}`;
typeToggles.appendChild(label);
label.querySelector('input').addEventListener('change', updateTimeSeriesChart);
}
});
updateTimeSeriesChart();
}
function updateTimeSeriesChart() {
const enabledTypes = Array.from(document.querySelectorAll('.type-toggle:checked'))
.map(cb => cb.dataset.type);
const datasets = enabledTypes.map(type => {
const data = state.timeSeriesData
.filter(dp => dp && dp.byType)
.map(dp => ({
x: dp.timestamp,
y: dp.byType[type] || 0
}));
return {
label: type,
data,
borderColor: TRAIN_TYPE_COLORS[type] || '#95a5a6',
backgroundColor: TRAIN_TYPE_COLORS[type] || '#95a5a6',
borderWidth: 2,
pointRadius: 0,
tension: 0.1
};
});
const ctx = document.getElementById('timeSeriesChart');
if (state.charts.timeSeries) {
state.charts.timeSeries.data.datasets = datasets;
state.charts.timeSeries.update();
} else {
// Destruir cualquier chart existente en este canvas
const existingChart = Chart.getChart(ctx);
if (existingChart) {
existingChart.destroy();
}
const isMobile = window.innerWidth < 768;
state.charts.timeSeries = new Chart(ctx, {
type: 'line',
data: { datasets },
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
type: 'time',
time: { unit: 'minute' },
title: { display: !isMobile, text: 'Tiempo' },
ticks: {
maxTicksLimit: isMobile ? 5 : 10,
maxRotation: isMobile ? 45 : 0,
minRotation: 0,
font: { size: isMobile ? 10 : 12 }
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: isMobile ? 'Retraso (min)' : 'Retraso Promedio (min)',
font: { size: isMobile ? 10 : 12 }
},
ticks: { font: { size: isMobile ? 10 : 12 } }
}
},
plugins: {
legend: {
position: 'bottom',
labels: {
boxWidth: isMobile ? 12 : 20,
font: { size: isMobile ? 10 : 12 },
padding: isMobile ? 8 : 10
}
}
}
}
});
}
// Update stats
updateTimeSeriesStats(enabledTypes);
}
function updateTimeSeriesStats(enabledTypes) {
const statsDiv = document.getElementById('timeSeriesStats');
const n = state.timeSeriesData.length;
if (n === 0) {
statsDiv.innerHTML = '<p class="ts-no-data">Sin datos históricos aún — espera unos segundos...</p>';
return;
}
const minutes = n > 1
? Math.round((state.timeSeriesData[n - 1].timestamp - state.timeSeriesData[0].timestamp) / 60000)
: 0;
const cards = enabledTypes.map(type => {
const values = state.timeSeriesData
.filter(dp => dp && dp.byType)
.map(dp => dp.byType[type] || 0);
if (values.length === 0 || values.every(v => v === 0)) return null;
const current = values[values.length - 1];
const prev = values.length > 1 ? values[values.length - 2] : current;
const min = Math.min(...values);
const max = Math.max(...values);
const avg = values.reduce((a, b) => a + b, 0) / values.length;
const delta = current - prev;
const trendIcon = delta > 0.1 ? '↑' : delta < -0.1 ? '↓' : '→';
const trendClass = delta > 0.1 ? 'trend-up' : delta < -0.1 ? 'trend-down' : 'trend-flat';
const valueClass = current <= 5 ? 'good' : current <= 15 ? 'warn' : 'bad';
return `
<div class="ts-stat-card">
<div class="ts-stat-type">${type}</div>
<div class="ts-stat-current ${valueClass}">
${current.toFixed(1)}<span class="ts-stat-unit"> min</span>
<span class="ts-trend ${trendClass}">${trendIcon}</span>
</div>
<div class="ts-stat-meta">
<span title="Mínimo de la sesión"><span class="meta-label">mín</span> ${min.toFixed(1)}</span>
<span title="Promedio de la sesión"><span class="meta-label">prom</span> ${avg.toFixed(1)}</span>
<span title="Máximo de la sesión"><span class="meta-label">máx</span> ${max.toFixed(1)}</span>
</div>
</div>`;
}).filter(c => c !== null);
statsDiv.innerHTML = `
<div class="ts-stats-header">
<span><strong>${n}</strong> lecturas · <strong>${minutes}</strong> min de historial</span>
</div>
<div class="ts-stats-grid">${cards.join('')}</div>`;
}
// ============================================================================
// SECTION 3: TRAFFIC DENSITY MAP
// ============================================================================
function initMap() {
state.map = new maplibregl.Map({
container: 'mapContainer',
style: {
version: 8,
sources: {
'osm': {
type: 'raster',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256,
attribution: '© OpenStreetMap contributors'
}
},
layers: [{
id: 'osm',
type: 'raster',
source: 'osm',
minzoom: 0,
maxzoom: 19
}]
},
center: [-3.7038, 40.4168], // Madrid
zoom: 6
});
state.map.on('load', () => {
updateMap();
});
document.getElementById('toggleMapMode').addEventListener('click', () => {
state.mapMode = state.mapMode === 'heatmap' ? 'markers' : 'heatmap';
document.getElementById('toggleMapMode').textContent =
state.mapMode === 'heatmap' ? 'Cambiar a Marcadores' : 'Cambiar a Mapa de Calor';
updateMap();
});
// Layer toggle controls
document.getElementById('showHighSpeed').addEventListener('change', updateMap);
document.getElementById('showConventional').addEventListener('change', updateMap);
}
function updateMap() {
if (!state.map || !state.map.loaded()) return;
// Remove existing layers and sources
if (state.map.getLayer('trains-heat')) state.map.removeLayer('trains-heat');
if (state.map.getLayer('trains-markers')) state.map.removeLayer('trains-markers');
if (state.map.getSource('trains')) state.map.removeSource('trains');
// Get layer visibility settings
const showHighSpeed = document.getElementById('showHighSpeed')?.checked ?? true;
const showConventional = document.getElementById('showConventional')?.checked ?? true;
// High-speed train types (AVE, AVLO, AVE TGV)
const highSpeedTypes = ['AVE', 'AVLO', 'AVE TGV'];
const features = state.fleetData
.filter(t => {
if (!t.latitud || !t.longitud) return false;
const trainType = TRAIN_TYPES[t.codProduct] || '';
const isHighSpeed = highSpeedTypes.includes(trainType);
// Filter based on layer selection
if (isHighSpeed && !showHighSpeed) return false;
if (!isHighSpeed && !showConventional) return false;
return true;
})
.map(train => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [parseFloat(train.longitud), parseFloat(train.latitud)]
},
properties: {
trainId: train.codComercial,
type: TRAIN_TYPES[train.codProduct] || 'Unknown',
corridor: getCorridorName(train),
delay: parseInt(train.ultRetraso || 0),
time: train.time,
mat: train.mat || '',
delayColor: getDelayColor(parseInt(train.ultRetraso || 0)),
isHighSpeed: highSpeedTypes.includes(TRAIN_TYPES[train.codProduct] || '')
}
}));
state.map.addSource('trains', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features
}
});
if (state.mapMode === 'heatmap') {
state.map.addLayer({
id: 'trains-heat',
type: 'heatmap',
source: 'trains',
paint: {
'heatmap-weight': 1,
'heatmap-intensity': 1,
'heatmap-radius': 20,
'heatmap-opacity': 0.8
}
});
} else {
state.map.addLayer({
id: 'trains-markers',
type: 'circle',
source: 'trains',
paint: {
// Radius: larger for high-speed trains
'circle-radius': [
'case',
['get', 'isHighSpeed'], 8,
6
],
'circle-color': ['get', 'delayColor'],
// Stroke width: thicker for high-speed
'circle-stroke-width': [
'case',
['get', 'isHighSpeed'], 2,
1
],
'circle-stroke-color': [
'case',
['get', 'isHighSpeed'], '#e74c3c',
'#3498db'
],
'circle-opacity': 0.9
}
});
// Add click handler for popups
state.map.on('click', 'trains-markers', (e) => {
const props = e.features[0].properties;
const delayClass = props.delay === 0 ? 'on-time' : props.delay <= 30 ? 'minor-delay' : 'major-delay';
const delayIcon = props.delay === 0 ? 'check_circle' : props.delay <= 15 ? 'warning' : 'error';
const html = `
<div class="map-popup">
<div class="popup-header">
<strong><span class="material-symbols-outlined ${delayClass}">${delayIcon}</span> Tren ${props.trainId}</strong>
<span class="popup-type">${props.type}</span>
</div>
<div class="popup-body">
<div class="popup-row">
<span class="popup-label"><span class="material-symbols-outlined">route</span> Ruta:</span>
<span>${props.corridor}</span>
</div>
<div class="popup-row ${delayClass}">
<span class="popup-label"><span class="material-symbols-outlined">schedule</span> Retraso:</span>
<span><strong>${props.delay} min</strong></span>
</div>
<div class="popup-row">
<span class="popup-label"><span class="material-symbols-outlined">location_on</span> Última ubicación:</span>
<span>${new Date(props.time * 1000).toLocaleTimeString('es-ES')}</span>
</div>
${props.mat ? `<div class="popup-row">
<span class="popup-label"><span class="material-symbols-outlined">directions_railway</span> Material:</span>
<span>${props.mat}</span>
</div>` : ''}
</div>
</div>
`;
new maplibregl.Popup({ className: 'enhanced-popup' })
.setLngLat(e.lngLat)
.setHTML(html)
.addTo(state.map);