Repository navigation
Expand file tree
/
Copy pathCodigo.js
More file actions
2345 lines (2058 loc) · 91.4 KB
/
Copy pathCodigo.js
File metadata and controls
2345 lines (2058 loc) · 91.4 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
/**
* ═══════════════════════════════════════════════════════════
* CÓDIGO PRINCIPAL - ORQUESTADOR INTEGRADO V3.0
* Integra funcionalidad de matriz + seguimiento + PDF
* ═══════════════════════════════════════════════════════════
*/
// ══════════════════════════════════════════════════════════
// ✅ FUNCIÓN CRÍTICA: INCLUDE PARA PLANTILLAS HTML
// DEBE SER LA PRIMERA FUNCIÓN — SIN ELLA LA APP NO CARGA
// ══════════════════════════════════════════════════════════
function include(filename) {
try {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
} catch (e) {
console.error(`❌ include() falló para '${filename}': ${e.message}`);
// Retorna HTML de error visible en la página para identificar el archivo faltante
return `<!-- ERROR: No se pudo incluir '${filename}': ${e.message} -->
<div style="background:#c0392b;color:#fff;padding:10px;font-family:sans-serif;">
❌ Archivo faltante: <strong>${filename}.html</strong>
</div>`;
}
}
// ══════════════════════════════════════════════════════════
// ✅ FUNCIÓN: parseDateRobust (requerida por verificacion.gs)
// ══════════════════════════════════════════════════════════
function parseDateRobust(value) {
try {
if (!value) return null;
if (value instanceof Date && !isNaN(value)) return value;
const str = String(value).trim();
if (!str || str === 'null' || str === 'undefined') return null;
// Formato DD/MM/YYYY
const dmy = str.match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})$/);
if (dmy) return new Date(+dmy[3], +dmy[2]-1, +dmy[1]);
// Formato YYYY-MM-DD
const iso = str.match(/^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})$/);
if (iso) return new Date(+iso[1], +iso[2]-1, +iso[3]);
const d = new Date(value);
return isNaN(d) ? null : d;
} catch (e) {
return null;
}
}
// ══════════════════════════════════════════════════════════
// ✅ FUNCIÓN: saveFollowupData (llamada desde el HTML del PAC)
// ══════════════════════════════════════════════════════════
function saveFollowupData(dataJson) {
try {
const userEmail = Session.getActiveUser().getEmail();
// ✅ SEC-P1: validación de autorización server-side (no confiar solo en la UI)
const gestorPermisos = new GestorPermisos();
const rolUsuario = gestorPermisos.obtenerRol(userEmail);
const rolesAutorizados = [getConfig('ROLES.EDITOR'), getConfig('ROLES.ADMIN')];
if (!rolUsuario || rolesAutorizados.indexOf(rolUsuario) === -1) {
console.warn(`⚠️ Acceso denegado a saveFollowupData para ${userEmail} (rol: ${rolUsuario || 'ninguno'})`);
return { success: false, error: 'No tiene permisos para registrar seguimiento. Se requiere rol Editor o Administrador.' };
}
const data = typeof dataJson === 'string' ? JSON.parse(dataJson) : dataJson;
const formObject = {
rt: data['RT'] || data['rt'] || '',
estadoPredial: data['ESTADO PREDIAL']|| data['estadoPredial'] || '',
estadoAjustado: data['ESTADO PREDIAL AJUSTADO'] || data['estadoAjustado'] || '',
disp: data['PREDIOS DISPONIBLES (INCLUYE CESIONES)'] || data['disp'] || '',
estadoRt: data['ESTADO RT'] || data['estadoRt'] || '',
estadoTitulos: data['ESTADO ESTUDIO DE TITULOS'] || data['estadoTitulos'] || '',
estadoTasacion: data['ESTADO TASACIÓN']|| data['estadoTasacion']|| '',
estadoAvaluo: data['ESTADO AVALUO'] || data['estadoAvaluo'] || '',
fechaAvaluo: data['FECHA AVALUO'] || data['fechaAvaluo'] || '',
situaciones: data['SITUACIONES ESPECIALES'] || data['situaciones'] || '',
observaciones: data['OBSERVACIONES'] || data['observaciones'] || ''
};
if (!formObject.rt) return { success: false, error: 'RT es requerido' };
const result = saveTrackingData(formObject, userEmail);
return { success: result.status === 'success', message: result.message, error: result.status !== 'success' ? result.message : null };
} catch (e) {
console.error('Error en saveFollowupData: ' + e.message);
return { success: false, error: e.message };
}
}
// ✅ PUNTO DE ENTRADA - CON VALIDACIÓN DE CONFIG
function doGet(e) {
try {
// 0️⃣ NUEVO: VERIFICAR MODO MANTENIMIENTO DINÁMICO
const enMantenimiento = PropertiesService.getScriptProperties().getProperty('MODO_MANTENIMIENTO') === 'true';
if (enMantenimiento || (CONFIG.MANTENIMIENTO && CONFIG.MANTENIMIENTO.ACTIVO)) {
const htmlMantenimiento = `
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sistema en Mantenimiento</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;800&display=swap" rel="stylesheet">
<style>
body { background-color: #ecf0f1; font-family: 'Inter', sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; color: #333; }
.maint-container { background: white; padding: 50px 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); text-align: center; max-width: 550px; border-top: 5px solid #f39c12; width: 90%; }
h1 { color: #2c3e50; font-weight: 800; margin-top: 20px; font-size: 2rem; }
p { color: #555; font-size: 1.05rem; line-height: 1.6; margin-bottom: 25px; }
.contact { background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #3498db; text-align: left; }
.contact strong { color: #2c3e50; display: block; margin-bottom: 8px; }
.contact a { color: #3498db; text-decoration: none; font-weight: bold; word-break: break-all; }
.contact a:hover { text-decoration: underline; }
.icon-spin { animation: spin 4s linear infinite; color: #f39c12; font-size: 4rem; }
@keyframes spin { 100% { transform: rotate(360deg); } }
</style>
</head>
<body>
<div class="maint-container">
<i class="fas fa-cog icon-spin"></i>
<h1>Actualización en Curso</h1>
<p>${CONFIG.MANTENIMIENTO.MENSAJE}</p>
<div class="contact">
<strong><i class="fas fa-headset"></i> ¿Requieres información urgente?</strong>
Comunícate con nuestro equipo técnico:<br>
<a href="mailto:fabian.montanez@idu.gov.co">fabian.montanez@idu.gov.co</a><br>
<a href="mailto:sistemasdtdp@idu.gov.co">sistemasdtdp@idu.gov.co</a>
</div>
</div>
</body>
</html>
`;
return HtmlService.createHtmlOutput(htmlMantenimiento)
.setTitle('Sistema en Mantenimiento')
.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
// 1️⃣ VALIDAR CONFIGURACIÓN PRIMERO
try {
validateConfig();
console.log('✅ Configuración validada en doGet');
} catch (configError) {
console.error(`❌ Error de configuración: ${configError.message}`);
return HtmlService.createHtmlOutput(`
<div style="font-family:sans-serif; text-align:center; margin-top:50px;">
<h2 style="color:#c0392b">⚠️ Error de Configuración</h2>
<p>El sistema no está correctamente configurado.</p>
<p><strong>Error:</strong> ${configError.message}</p>
<p>Contacta al administrador.</p>
</div>
`);
}
// 2️⃣ OBTENER USUARIO
// ✅ CONC-FE-05-hotfix: fallback defensivo — getEmail() ya devuelve string
// por contrato de la API (nunca null/undefined), pero el || '' deja el
// invariante explícito para quien lea/toque este valor más adelante.
const userEmail = Session.getActiveUser().getEmail() || '';
console.log(`👤 Usuario: ${userEmail}`);
// 3️⃣ OBTENER ROL (CON MANEJO DE ERRORES)
let role = null;
try {
const gestorPermisos = new GestorPermisos();
role = gestorPermisos.obtenerRol(userEmail);
console.log(`👥 Rol: ${role}`);
} catch (permError) {
console.warn(`⚠️ Error obteniendo rol: ${permError.message}`);
role = getConfig('ROLES.LECTOR');
}
// 4️⃣ VALIDAR ACCESO
if (!role) {
return HtmlService.createHtmlOutput(`
<div style="font-family:sans-serif; text-align:center; margin-top:50px;">
<h2 style="color:#c0392b">⛔ Acceso Denegado</h2>
<p>El usuario <b>${userEmail}</b> no tiene permisos registrados.</p>
<p>Contacta al administrador.</p>
</div>
`);
}
// 5️⃣ REGISTRAR INGRESO
try {
const auditoria = new GestorAuditoria();
auditoria.registrarAccion(userEmail, 'Ingreso al Tablero', `Rol: ${role}`);
console.log('✅ Ingreso registrado en auditoría');
} catch (auditError) {
console.warn(`⚠️ Error registrando ingreso: ${auditError.message}`);
}
// 6️⃣ CARGAR PLANTILLA
try {
const template = HtmlService.createTemplateFromFile('Index');
template.currentUser = userEmail;
template.currentRole = role;
// ✅ CONC-FE-05-hotfix3: modo seguro GAS. Generamos un literal JS válido
// en el backend para evitar que el motor de plantillas falle al evaluar
// expresiones complejas dentro de <?!= ... ?>.
template.userEmail = userEmail;
template.safeUserEmailJS = JSON.stringify(userEmail || '');
return template.evaluate()
.setTitle('Tablero de Gestión Predial - Enterprise Modular')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.addMetaTag('viewport', 'width=device-width, initial-scale=1');
} catch (templateError) {
console.error(`❌ Error cargando plantilla: ${templateError.message}`);
return HtmlService.createHtmlOutput(`
<div style="font-family:sans-serif; text-align:center; margin-top:50px;">
<h2 style="color:#c0392b">❌ Error al cargar la interfaz</h2>
<p>${templateError.message}</p>
</div>
`);
}
} catch (e) {
console.error(`❌ Error crítico en doGet: ${e.message}`);
console.error(`📍 Stack: ${e.stack}`);
return HtmlService.createHtmlOutput(`
<div style="font-family:sans-serif; text-align:center; margin-top:50px;">
<h2 style="color:#c0392b">❌ Error al cargar</h2>
<p>${e.message}</p>
<p style="font-size: 0.8rem; color: #999;">Revisa los logs de ejecución</p>
</div>
`);
}
}
/**
* ✅ OBTIENE TIMELINE DE SEGUIMIENTO POR RT CON FILTROS CRONOLÓGICOS
*/
function getRtFollowupTimeline(rt, filterType = 'ALL') {
try {
console.log(`📅 Obteniendo timeline para RT: ${rt}, Filtro: ${filterType}`);
const timeline = [];
const today = new Date();
let startDate = null;
// Determinar rango de fechas según filtro
switch(filterType) {
case 'LAST_MONTH':
startDate = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
break;
case 'LAST_3_MONTHS':
startDate = new Date(today.getFullYear(), today.getMonth() - 3, today.getDate());
break;
case 'LAST_6_MONTHS':
startDate = new Date(today.getFullYear(), today.getMonth() - 6, today.getDate());
break;
case 'LAST_YEAR':
startDate = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate());
break;
case 'ALL':
default:
startDate = new Date(2000, 0, 1);
}
const dataFilesIds = getDataFilesIds();
dataFilesIds.forEach(id => {
try {
const ss = SpreadsheetApp.openById(id);
let wsSeg = ss.getSheetByName(getConfig('SHEETS.SEGUIMIENTO'));
if (!wsSeg) return;
const data = wsSeg.getDataRange().getValues();
const headers = data[0].map(h => h.toString().toUpperCase().trim());
const rtIdx = headers.findIndex(h => h.includes("RT"));
const fechaIdx = headers.findIndex(h => h.includes("FECHA"));
const obsIdx = headers.findIndex(h => h.includes("OBSERVACIONES"));
const estadoIdx = headers.findIndex(h => h.includes("ESTADO") && !h.includes("AJUSTADO"));
const dispIdx = headers.findIndex(h => h.includes("DISPONIBILIDAD"));
if (rtIdx === -1) return;
for (let i = 1; i < data.length; i++) {
if (String(data[i][rtIdx]).trim() === String(rt).trim()) {
// Parsear fecha
let fechaObj = null;
if (fechaIdx > -1 && data[i][fechaIdx]) {
fechaObj = new Date(data[i][fechaIdx]);
}
// Filtrar por rango de fechas
if (fechaObj && fechaObj >= startDate && fechaObj <= today) {
timeline.push({
fecha: fechaObj.toISOString().split('T')[0],
fechaCompleta: fechaObj.toLocaleString('es-CO'),
estado: estadoIdx > -1 ? data[i][estadoIdx] : '-',
disponibilidad: dispIdx > -1 ? data[i][dispIdx] : '-',
observaciones: obsIdx > -1 ? cleanTextUpper(data[i][obsIdx]) : '-',
usuario: data[i][headers.findIndex(h => h.includes("USUARIO"))] || '-'
});
}
}
}
} catch(e) {
console.error("Error leyendo seguimiento: " + e.message);
}
});
// Ordenar cronológicamente (más reciente primero)
timeline.sort((a, b) => new Date(b.fecha) - new Date(a.fecha));
console.log(`✅ Timeline generado: ${timeline.length} registros`);
return JSON.stringify({
rt: rt,
filterType: filterType,
totalRecords: timeline.length,
timeline: timeline
});
} catch (e) {
console.error(`Error en getRtFollowupTimeline: ${e.message}`);
return JSON.stringify({
error: e.message,
timeline: []
});
}
}
/**
* ✅ OBTIENE DATOS DEL DASHBOARD + SEGUIMIENTO (VERSIÓN COMPATIBLE V3)
*/
/**
* ✅ OBTIENE DATOS DEL DASHBOARD (FILTRADOS DESDE EL SERVIDOR PARA TODOS)
*/
function getDashboardData() {
try {
console.log('🔍 Iniciando getDashboardData...');
console.time('dashboard:total');
const enMantenimiento = PropertiesService.getScriptProperties().getProperty('MODO_MANTENIMIENTO') === 'true';
if (enMantenimiento) {
console.log('⛔ Petición bloqueada: Sistema en mantenimiento');
console.timeEnd('dashboard:total');
return { success: false, mantenimiento: true, message: "Sistema en mantenimiento" };
}
// ✅ SPRINT5-FASE-C: se resuelve el rol ANTES del caché a propósito. CACHE_KEY_DASHBOARD
// (cache_backend.js) es una clave FIJA compartida por TODOS los usuarios — correcto para
// Admin/Editor/Lector (mismo dataset para todos, ver docstring "clave fija" en ese archivo),
// pero un agujero de seguridad real para Articulador/Gestor: sin este guard, el filtro RBAC
// de más abajo se calcularía correctamente pero jamás se ejecutaría si otro usuario ya
// dejó una respuesta completa en caché — un Articulador vería el dataset de un Admin
// durante los 30 minutos de TTL. Por eso Articulador/Gestor se excluyen explícitamente
// del caché compartido (ni leen ni escriben en él), a costa de recalcular en cada carga.
const currentUserEmailRBAC = (Session.getActiveUser().getEmail() || '').trim().toLowerCase();
const rolUsuarioRBAC = getUserRole(currentUserEmailRBAC) || getConfig('ROLES.LECTOR');
const esArticuladorRBAC = rolUsuarioRBAC === getConfig('ROLES.ARTICULADOR');
const esGestorRBAC = rolUsuarioRBAC === getConfig('ROLES.GESTOR');
const requiereFiltroRBAC = esArticuladorRBAC || esGestorRBAC;
const colArticuladorRBAC = getConfig('COLUMNS.ARTICULADOR_JURIDICO', '').toUpperCase().trim();
const colGestorRBAC = getConfig('COLUMNS.GESTOR_JURIDICO', '').toUpperCase().trim();
const colRTRBAC = getConfig('COLUMNS.RT', '').toUpperCase().trim();
// ✅ SPRINT6-DESACOPLE [CONC-BE-12]: Datos es 100% lectura — el valor EFECTIVO de
// Articulador/Gestor por RT sale de fusionar con ASIGNACIONES_EQUIPOS (la capa que sí se
// escribe). _leerAsignacionesEquipos()/_fusionarAsignacionesConMatriz() viven en
// gestion_equipos_backend.js pero son globales a propósito (mismo scope GAS compartido).
const asignacionesMapRBAC = _leerAsignacionesEquipos();
const cache = CacheService.getScriptCache();
if (!requiereFiltroRBAC) {
console.time('dashboard:cacheRead');
const cached = getDashboardCachePayload(cache);
console.timeEnd('dashboard:cacheRead');
if (cached) {
try {
const cachedResponse = JSON.parse(cached);
cachedResponse.user = Session.getActiveUser().getEmail();
console.timeEnd('dashboard:total');
return cachedResponse;
} catch (e) {
console.warn('⚠️ Caché de dashboard corrupto, recalculando: ' + e.message);
}
}
}
const allRecords = [];
const allProyectosSet = new Set();
let headers = [];
let headersFound = false;
const seguimientoRecords = [];
const dataFilesIds = getDataFilesIds();
let filtroActivo = null;
try {
const gestorFiltro = new GestorFiltroMatriz();
filtroActivo = gestorFiltro.obtenerFiltroActivo();
} catch (e) {}
let proyectosVisibles = { todos: true, proyectos: [], excluidos: [] };
if (filtroActivo) {
if (filtroActivo.proyectosIncluidos && filtroActivo.proyectosIncluidos.length > 0) {
proyectosVisibles = { todos: false, proyectos: filtroActivo.proyectosIncluidos, excluidos: [] };
} else if (filtroActivo.proyectosExcluidos && filtroActivo.proyectosExcluidos.length > 0) {
proyectosVisibles = { todos: false, proyectos: [], excluidos: filtroActivo.proyectosExcluidos };
}
}
console.time('dashboard:sheetRead');
dataFilesIds.forEach((id) => {
try {
const ss = SpreadsheetApp.openById(id);
const ws = ss.getSheetByName(getConfig('SHEETS.DATOS', 'Datos'));
if (!ws) return;
const lastRow = ws.getLastRow();
const lastCol = ws.getLastColumn();
if (lastRow < 2 || lastCol < 1) return;
const data = ws.getRange(1, 1, lastRow, lastCol).getDisplayValues();
const usableRows = data.filter(row => row && row.some(cell => String(cell || '').trim() !== ''));
if (usableRows.length <= 1) return;
if (!headersFound) {
headers = usableRows[0].map(h => String(h || '').toUpperCase().trim());
headersFound = true;
}
const proyectoIndex = headers.findIndex(h => h.includes('PROYECTO'));
// ✅ SPRINT5-FASE-C: índices de las columnas de responsables para el filtro RBAC.
const idxArticuladorRBAC = headers.indexOf(colArticuladorRBAC);
const idxGestorRBAC = headers.indexOf(colGestorRBAC);
const idxRTRBAC = headers.indexOf(colRTRBAC);
// Un Gestor ve TODOS los RTs del/los Articulador(es) bajo los que él mismo aparece
// asignado como Gestor — se deriva de la vista FUSIONADA (Datos + ASIGNACIONES_EQUIPOS),
// no solo de Datos crudo. Pre-pasada barata en memoria (mismo usableRows ya leído).
let articuladoresPermitidosGestorRBAC = null;
if (esGestorRBAC && idxGestorRBAC >= 0 && idxArticuladorRBAC >= 0) {
articuladoresPermitidosGestorRBAC = new Set();
for (let k = 1; k < usableRows.length; k++) {
const rtPrepass = idxRTRBAC >= 0 ? String(usableRows[k][idxRTRBAC] || '').trim() : '';
const fusionPrepass = _fusionarAsignacionesConMatriz(
rtPrepass, usableRows[k][idxArticuladorRBAC], usableRows[k][idxGestorRBAC], asignacionesMapRBAC
);
if (fusionPrepass.gestorEmail.toLowerCase() === currentUserEmailRBAC && fusionPrepass.articuladorEmail) {
articuladoresPermitidosGestorRBAC.add(fusionPrepass.articuladorEmail.toLowerCase());
}
}
}
for (let i = 1; i < usableRows.length; i++) {
const row = usableRows[i];
const proyecto = String(row[proyectoIndex] || '').trim();
if (proyecto) {
allProyectosSet.add(proyecto);
}
let incluirRegistro = true;
if (!proyectosVisibles.todos) {
if (proyectosVisibles.proyectos.length > 0) {
incluirRegistro = proyectosVisibles.proyectos.includes(proyecto);
} else if (proyectosVisibles.excluidos.length > 0) {
incluirRegistro = !proyectosVisibles.excluidos.includes(proyecto);
}
}
if (!incluirRegistro) continue;
// ✅ SPRINT6-DESACOPLE: el valor EFECTIVO de Articulador/Gestor para esta fila sale
// de fusionar Datos (crudo) con ASIGNACIONES_EQUIPOS (overlay) — una sola vez por
// fila, reutilizado tanto para el filtro RBAC de abajo como para lo que se manda
// al cliente (así la Matriz también refleja reasignaciones hechas desde el árbol,
// no solo el módulo de Equipos).
const rtFilaRBAC = idxRTRBAC >= 0 ? String(row[idxRTRBAC] || '').trim() : '';
const fusionRBAC = (idxArticuladorRBAC >= 0)
? _fusionarAsignacionesConMatriz(rtFilaRBAC, row[idxArticuladorRBAC], row[idxGestorRBAC], asignacionesMapRBAC)
: null;
// ✅ SPRINT5-FASE-C: recorte por jerarquía RBAC (Articulador/Gestor). Una fila cuyo
// valor efectivo todavía es el nombre libre sin migrar simplemente no es visible
// para Articulador/Gestor hasta que se homologe/asigne — es el incentivo esperado.
if (requiereFiltroRBAC && fusionRBAC) {
let visiblePorRBAC = false;
if (esArticuladorRBAC) {
visiblePorRBAC = fusionRBAC.articuladorEmail.toLowerCase() === currentUserEmailRBAC;
} else if (esGestorRBAC) {
visiblePorRBAC = (fusionRBAC.gestorEmail.toLowerCase() === currentUserEmailRBAC) ||
(articuladoresPermitidosGestorRBAC && articuladoresPermitidosGestorRBAC.has(fusionRBAC.articuladorEmail.toLowerCase()));
}
if (!visiblePorRBAC) continue;
}
const rowObject = { _FILE_ID: id };
for (let j = 0; j < headers.length; j++) {
const cellVal = row[j];
const colName = headers[j];
if (colName.includes('VALOR') || colName.includes('PAGADO') || colName.includes('ESTIMADO') || colName.includes('SALDO')) {
rowObject[colName] = parseMoneyRobust(cellVal);
} else {
rowObject[colName] = cellVal || '';
}
}
// ✅ SPRINT6-DESACOPLE: sobreescribe con el valor EFECTIVO (Datos + overlay) lo que
// se manda al cliente — la Matriz general también debe ver reasignaciones hechas
// desde el árbol de Equipos, no solo el módulo de Equipos mismo.
if (fusionRBAC) {
rowObject[colArticuladorRBAC] = fusionRBAC.articuladorEmail;
rowObject[colGestorRBAC] = fusionRBAC.gestorEmail;
}
allRecords.push(rowObject);
}
const wsSeg = ss.getSheetByName(getConfig('SHEETS.SEGUIMIENTO', 'Seguimiento'));
if (wsSeg) {
const segLastRow = wsSeg.getLastRow();
const segLastCol = wsSeg.getLastColumn();
if (segLastRow > 1 && segLastCol > 0) {
const segData = wsSeg.getRange(1, 1, segLastRow, segLastCol).getDisplayValues();
const segUsableRows = segData.filter(row => row && row.some(cell => String(cell || '').trim() !== ''));
if (segUsableRows.length > 1) {
const segHeaders = segUsableRows[0].map(h => String(h || '').toUpperCase().trim());
for (let i = 1; i < segUsableRows.length; i++) {
const segRow = {};
for (let j = 0; j < segHeaders.length; j++) segRow[segHeaders[j]] = segUsableRows[i][j] || '';
if (segRow['RT']) seguimientoRecords.push(segRow);
}
}
}
}
} catch (e) {
console.error(`❌ Error archivo ${id}:`, e.message);
}
});
console.timeEnd('dashboard:sheetRead');
const alertasResumen = evaluarAlertasDataset(allRecords);
console.time('dashboard:serialize');
const cacheableResponse = {
success: true,
records: JSON.stringify(allRecords),
columns: JSON.stringify(headers),
seguimiento: JSON.stringify(seguimientoRecords),
allProyectos: JSON.stringify(Array.from(allProyectosSet).sort()),
filtroMatrizActivo: JSON.stringify(filtroActivo || {}),
alertasResumen: JSON.stringify(alertasResumen)
};
// ✅ SPRINT5-FASE-C: Articulador/Gestor nunca escriben en el caché compartido — su respuesta
// ya viene recortada por RBAC, y si se guardara ahí, el próximo Admin/Editor/Lector que
// pegara en el mismo TTL de 30 min recibiría por error el subconjunto recortado en vez del
// dataset completo (fuga en la dirección opuesta a la que ya se cerró en la lectura).
if (!requiereFiltroRBAC) {
try {
const serializedResponse = JSON.stringify(cacheableResponse);
const writeInfo = putDashboardCachePayload(cache, serializedResponse, 1800);
console.log('✅ Cache dashboard actualizado: ' + writeInfo.payloadSize + ' chars en ' + writeInfo.chunkCount + ' chunk(s)');
} catch (e) {
console.warn('⚠️ No se pudo cachear getDashboardData (posible overflow 100KB de CacheService): ' + e.message);
}
}
console.timeEnd('dashboard:serialize');
cacheableResponse.user = Session.getActiveUser().getEmail();
console.timeEnd('dashboard:total');
return cacheableResponse;
} catch (e) {
console.error('❌ Error crítico en getDashboardData:', e.message);
console.timeEnd('dashboard:total');
return {
success: false,
message: e.message,
records: '[]',
columns: '[]',
seguimiento: '[]',
allProyectos: '[]',
alertasResumen: JSON.stringify({
success: false,
totalAlertas: 0,
severidades: { CRITICA: 0, ALERTA: 0, ADVERTENCIA: 0, INFO: 0 },
proyectosImpactados: 0,
rtImpactados: 0,
alertas: [],
error: e.message
})
};
}
}
/**
* ✅ GUARDA Y ACTIVA EL FILTRO RÁPIDO PARA TODOS LOS USUARIOS
*/
function guardarYActivarFiltroManual(proyectosIncluidos, usuario) {
try {
const gestor = new GestorFiltroMatriz();
const todos = gestor.obtenerTodos();
// Buscar si ya existe el registro del filtro rápido
let filtroAdhoc = todos.find(f => f.nombre === 'FILTRO MANUAL VISTA RÁPIDA');
if (filtroAdhoc) {
// Actualizar y activar
gestor.actualizarFiltro(filtroAdhoc.id, 'FILTRO MANUAL VISTA RÁPIDA', 'Filtro rápido temporal aplicado por el administrador', proyectosIncluidos, [], usuario);
return gestor.activarFiltro(filtroAdhoc.id, usuario);
} else {
// Crear y activar
const res = gestor.crearFiltro('FILTRO MANUAL VISTA RÁPIDA', 'Filtro rápido temporal aplicado por el administrador', proyectosIncluidos, [], usuario);
if (res.success) {
return gestor.activarFiltro(res.id, usuario);
}
return res;
}
} catch(e) {
return { success: false, error: e.message };
}
}
/**
* ✅ PARSING ROBUSTO DE NÚMEROS (INTEGRADO DEL CÓDIGO 1)
*/
function parseMoneyRobust(cellValue) {
if (!cellValue) return 0;
let str = String(cellValue).trim();
if (!isNaN(str) && str !== '') return parseFloat(str);
str = str.replace(/[^\d.,]/g, '');
if (!str) return 0;
const lastCommaPos = str.lastIndexOf(',');
const lastDotPos = str.lastIndexOf('.');
let normalized = str;
if (lastCommaPos > lastDotPos) {
normalized = str.replace(/\./g, '').replace(',', '.');
} else if (lastDotPos > lastCommaPos) {
normalized = str.replace(/,/g, '');
} else if (lastCommaPos === -1 && lastDotPos === -1) {
normalized = str;
} else if (lastCommaPos >= 0 && lastDotPos === -1) {
normalized = str.replace(/,/g, '');
}
const result = parseFloat(normalized);
return isNaN(result) ? 0 : result;
}
/**
* ✅ OBTIENE LISTAS DESPLEGABLES UNIFICADAS (V1 + V2)
*/
function getDropdownLists() {
try {
let uniqueLists = {
estadoPredial: new Set(),
estadoAjustado: new Set(),
disp: new Set(),
estadoRt: new Set(),
estadoTitulos: new Set(),
estadoTasacion: new Set(),
estadoAvaluo: new Set(),
situaciones: new Set()
};
const dataFilesIds = getDataFilesIds();
dataFilesIds.forEach(id => {
try {
const ss = SpreadsheetApp.openById(id);
const ws = ss.getSheetByName(getConfig('SHEETS.DATOS'));
if(!ws) return;
const data = ws.getDataRange().getValues();
if(data.length < 2) return;
const headers = data[0].map(h => h.toString().toUpperCase().trim());
const addUnique = (keywords, setObj) => {
if (typeof keywords === 'string') keywords = [keywords];
const idx = headers.findIndex(h =>
keywords.some(k => h.includes(k))
);
if (idx > -1) {
data.slice(1).forEach(r => {
if(r[idx]) setObj.add(String(r[idx]).trim());
});
}
};
addUnique(["ESTADO PREDIAL"], uniqueLists.estadoPredial);
addUnique(["AJUSTADO"], uniqueLists.estadoAjustado);
addUnique(["DISPONIBLE"], uniqueLists.disp);
addUnique(["ESTADO RT"], uniqueLists.estadoRt);
addUnique(["TITULOS"], uniqueLists.estadoTitulos);
addUnique(["TASACI"], uniqueLists.estadoTasacion);
addUnique(["ESTADO AVALUO"], uniqueLists.estadoAvaluo);
addUnique(["SITUACION"], uniqueLists.situaciones);
} catch(e) {
console.error(`Error procesando listas: ${e.message}`);
}
});
return JSON.stringify({
estadoPredial: [...uniqueLists.estadoPredial].sort(),
estadoAjustado: [...uniqueLists.estadoAjustado].sort(),
disp: [...uniqueLists.disp].sort(),
estadoRt: [...uniqueLists.estadoRt].sort(),
estadoTitulos: [...uniqueLists.estadoTitulos].sort(),
estadoTasacion: [...uniqueLists.estadoTasacion].sort(),
estadoAvaluo: [...uniqueLists.estadoAvaluo].sort(),
situaciones: [...uniqueLists.situaciones].sort()
});
} catch (e) {
console.error(`Error en getDropdownLists: ${e.message}`);
return JSON.stringify({});
}
}
/**
* ═══════════════════════════════════════════════════════════
* FUNCIONES DE SEGUIMIENTO (V2 - ORQUESTADAS + V1)
* ═══════════════════════════════════════════════════════════
*/
/**
* ✅ GUARDA SEGUIMIENTO MANTENIENDO ESTRUCTURA ORIGINAL (INTEGRADO)
*/
function saveTrackingData(formObject, userEmail) {
const lock = LockService.getScriptLock();
try {
lock.waitLock(30000);
const timestamp = new Date();
let targetFileId = null;
let targetRowIndex = -1;
const dataFilesIds = getDataFilesIds();
// 1. BUSCAR RT EN LAS BASES (lectura)
for (const id of dataFilesIds) {
try {
const ss = SpreadsheetApp.openById(id);
const ws = ss.getSheetByName(getConfig('SHEETS.DATOS'));
if(!ws) continue;
const data = ws.getDataRange().getValues();
if (!data || data.length < 2) continue;
const headers = data[0].map(h => String(h).toUpperCase().trim());
const rtIndex = headers.indexOf('RT');
if (rtIndex === -1) continue;
for (let i = 1; i < data.length; i++) {
if (String(data[i][rtIndex]).trim() === String(formObject.rt).trim()) {
targetFileId = id;
targetRowIndex = i + 1;
break;
}
}
if (targetFileId) break;
} catch (err) {
console.error('Error buscando RT en archivo ' + id + ': ' + err.message);
}
}
if (!targetFileId || targetRowIndex === -1) {
throw new Error(`El RT ${formObject.rt} no fue encontrado en las bases conectadas.`);
}
// PRINCIPAL (matriz bajo nuestro control)
const principalId = getConfig('DATA_FILES.PRINCIPAL');
const gestorPrincipal = new GestorDatos(principalId);
// Asegurar hoja Seguimiento en la matriz principal
let wsSegPrincipal = gestorPrincipal.getSheet(getConfig('SHEETS.SEGUIMIENTO'));
if (!wsSegPrincipal) {
// crear hoja si no existe (GestorDatos.getSheet lanzará si no existe)
try {
gestorPrincipal.ss.insertSheet(getConfig('SHEETS.SEGUIMIENTO'));
wsSegPrincipal = gestorPrincipal.getSheet(getConfig('SHEETS.SEGUIMIENTO'));
wsSegPrincipal.appendRow([
'FECHA_REGISTRO','RT','ESTADO_PREDIAL','ESTADO_AJUSTADO',
'DISPONIBILIDAD','ESTADO_RT','TITULOS','TASACION','AVALUO',
'FECHA_AVALUO','SITUACIONES','OBSERVACIONES','USUARIO',
'CAMBIOS_DETECTADOS','ORIGEN_FILEID'
]);
} catch (e) {
// si falla por permisos u otro motivo, continuar y loggear
console.error('No se pudo crear hoja SEGUIMIENTO en matriz principal: ' + e.message);
}
}
// Obtener wsDatos del archivo donde se encontró el RT (solo para lectura)
const foundSS = SpreadsheetApp.openById(targetFileId);
const wsDatosFound = foundSS.getSheetByName(getConfig('SHEETS.DATOS'));
// 2. GUARDAR EN HISTÓRICO (AUDITORÍA) y en hoja Seguimiento PRINCIPAL (siempre)
const cambios = detectarCambios(formObject, wsDatosFound, targetRowIndex);
const rowDataHistory = [
timestamp,
formObject.rt,
formObject.estadoPredial,
formObject.estadoAjustado,
formObject.disp,
formObject.estadoRt,
formObject.estadoTitulos,
formObject.estadoTasacion,
formObject.estadoAvaluo,
formObject.fechaAvaluo || '',
formObject.situaciones,
cleanTextUpper(formObject.observaciones),
userEmail,
cambios.join(' | '),
targetFileId
];
try {
gestorPrincipal.agregarFila(getConfig('SHEETS.SEGUIMIENTO'), rowDataHistory);
} catch (e) {
// fallback: intentar appendRow directo
try {
const ss = SpreadsheetApp.openById(principalId);
const s = ss.getSheetByName(getConfig('SHEETS.SEGUIMIENTO'));
if (s) s.appendRow(rowDataHistory);
} catch (err) {
console.error('No se pudo registrar seguimiento: ' + err.message);
}
}
// 3. ACTUALIZAR HOJA "DATOS": Solo si la fila se encontró EN NUESTRA MATRIZ PRINCIPAL
if (targetFileId === principalId) {
try {
const sheetDatos = gestorPrincipal.getSheet(getConfig('SHEETS.DATOS'));
const lastCol = sheetDatos.getLastColumn();
const headers = sheetDatos.getRange(1, 1, 1, lastCol).getValues()[0].map(h => String(h).toUpperCase().trim());
const currentRow = sheetDatos.getRange(targetRowIndex, 1, 1, lastCol).getValues()[0];
const colMap = mapearColumnasFlexible(headers);
// Construir fila actualizada en memoria
const updatedRow = currentRow.slice();
const setIf = (colKey, val) => {
const idx = colMap[colKey];
if (idx > -1) updatedRow[idx] = (val === undefined || val === null) ? '' : val;
};
setIf('ESTADO PREDIAL', formObject.estadoPredial);
setIf('ESTADO PREDIAL AJUSTADO', formObject.estadoAjustado);
setIf('PREDIOS DISPONIBLES', formObject.disp);
setIf('ESTADO RT', formObject.estadoRt);
setIf('ESTADO ESTUDIO DE TITULOS', formObject.estadoTitulos);
setIf('ESTADO TASACIÓN', formObject.estadoTasacion);
setIf('ESTADO AVALUO', formObject.estadoAvaluo);
setIf('FECHA AVALUO', formObject.fechaAvaluo);
setIf('SITUACIONES ESPECIALES', formObject.situaciones);
setIf('OBSERVACIONES', cleanTextUpper(formObject.observaciones));
// Escritura en batch usando GestorDatos.actualizarRango
gestorPrincipal.actualizarRango(
getConfig('SHEETS.DATOS'),
targetRowIndex,
1,
[updatedRow]
);
} catch (e) {
console.error('Error actualizando DATOS en matriz principal: ' + e.message);
}
} else {
pac_log('saveTrackingData: RT encontrado en archivo externo. Escrituras dirigidas exclusivamente a la matriz principal.', 'ADVERTENCIA');
}
// 4. REGISTRAR EN AUDITORÍA MODULAR (EN MATRIZ PRINCIPAL)
try {
const auditoria = new GestorAuditoria(principalId);
auditoria.registrarAccion(
userEmail,
'Actualizar RT',
`RT: ${formObject.rt}, Cambios: ${cambios.length}, origen: ${targetFileId}`
);
} catch (audError) {
console.warn('⚠️ Error registrando auditoría: ' + audError.message);
}
// ✅ FASE 8 (perf, restaurado): invalida el caché del tablero — este RT cambió
// Seguimiento y/o Datos.
invalidateDataCache();
return {
status: 'success',
message: `✅ Seguimiento guardado en matriz principal para RT: ${formObject.rt}`,
cambios: cambios.length,
detalles: cambios,
origen: targetFileId
};
} catch (e) {
console.error(`Error en saveTrackingData: ${e.message}`);
return {
status: 'error',
message: e.message,
stack: e.stack
};
} finally {
try { lock.releaseLock(); } catch (er) {}
}
}
/**
* ✅ MAPEO FLEXIBLE DE COLUMNAS (DEL CÓDIGO 1)
*/
function mapearColumnasFlexible(headers) {
const findCol = (keywords) => {
if (typeof keywords === 'string') keywords = [keywords];
return headers.findIndex(h =>
keywords.some(k => h.includes(k.toUpperCase()))
);
};
return {
"ESTADO PREDIAL": findCol(["ESTADO PREDIAL"]),
"ESTADO PREDIAL AJUSTADO": findCol(["AJUSTADO"]),
"PREDIOS DISPONIBLES": findCol(["DISPONIBLE"]),
"ESTADO RT": findCol(["ESTADO RT"]),
"ESTADO ESTUDIO DE TITULOS": findCol(["TITULOS", "ESTUDIO"]),
"ESTADO TASACIÓN": findCol(["TASACI"]),
"ESTADO AVALUO": findCol(["AVALUO"]),
"FECHA AVALUO": findCol(["FECHA AVALUO"]),
"SITUACIONES ESPECIALES": findCol(["SITUACION"]),
"OBSERVACIONES": findCol(["OBSERVACIONES"])
};
}
/**
* ✅ DETECTA CAMBIOS PARA AUDITORÍA (DEL CÓDIGO 1)
*/
function detectarCambios(formObj, wsDatos, rowIndex) {
const cambios = [];
const headers = wsDatos.getRange(1, 1, 1, wsDatos.getLastColumn())
.getValues()[0].map(h => h.toString().toUpperCase().trim());
const colMap = mapearColumnasFlexible(headers);
const getValorActual = (colIdx) => {
if(colIdx < 0) return null;
return wsDatos.getRange(rowIndex, colIdx + 1).getValue();
};
const registrarCambio = (campo, nuevo) => {
const anterior = getValorActual(colMap[campo]);
if (String(anterior) !== String(nuevo)) {
cambios.push(`${campo}: "${anterior}" → "${nuevo}"`);
}
};
registrarCambio("ESTADO PREDIAL", formObj.estadoPredial);
registrarCambio("ESTADO PREDIAL AJUSTADO", formObj.estadoAjustado);
registrarCambio("PREDIOS DISPONIBLES", formObj.disp);
registrarCambio("ESTADO RT", formObj.estadoRt);
registrarCambio("ESTADO ESTUDIO DE TITULOS", formObj.estadoTitulos);
registrarCambio("ESTADO TASACIÓN", formObj.estadoTasacion);
registrarCambio("ESTADO AVALUO", formObj.estadoAvaluo);
return cambios;
}
/**
* ✅ OBTIENE HISTORIAL DE UN RT (INTEGRADO)
*/
function getRtHistory(rt) {
const historial = [];
const dataFilesIds = getDataFilesIds();
dataFilesIds.forEach(id => {
try {
const ss = SpreadsheetApp.openById(id);
let wsSeg = ss.getSheetByName(getConfig('SHEETS.SEGUIMIENTO'));
if (!wsSeg) return;
const data = wsSeg.getDataRange().getValues();
const headers = data[0];
const rtIdx = headers.findIndex(h =>
String(h).toUpperCase().includes("RT")
);
if (rtIdx === -1) return;
for (let i = 1; i < data.length; i++) {
if (String(data[i][rtIdx]).trim() === String(rt).trim()) {
historial.push({
fecha: data[i][0],
rt: data[i][1],
estado: data[i][3],
disponibilidad: data[i][4],
observaciones: data[i][11],
usuario: data[i][12],
cambios: data[i][13]
});