feat(sheets): refactor google sheets importer with granular entities and interactive preview grid v3.4.3

This commit is contained in:
2026-10-07 22:51:41 -03:00
parent e1c2c6e8c6
commit 22c545e2df
12 changed files with 1001 additions and 195 deletions
+18
View File
@@ -11,6 +11,24 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
## [3.4.3] - 2026-10-07
### Añadido & Refactorizado (Sincronización Google Sheets)
- **Selección Granular de Entidades a Importar:**
- Adopción del patrón visual de tarjetas checkbox (idéntico a la Herramienta de Reinicio y Purga Académica) con accesos rápidos "Marcar Todo" y "Desmarcar Todo".
- Toggles individuales para Asignaciones de aulas (`import_reservations`), Aulas físicas y virtuales (`import_classrooms`), Comisiones de cursada (`import_commissions`), Asignaturas / Materias (`import_subjects`) y Carreras académicas (`import_careers`).
- **Selector de Días de la Semana con Checkboxes Múltiples:**
- Sistema de checkboxes para procesar concurrentemente múltiples días de la semana (Lunes a Sábado) con selectores rápidos ("Todos", "Lun a Vie", "Limpiar").
- **Grilla de Previsualización Interactiva e Inspección Previa:**
- El botón "Inspeccionar Sheet Online" no importa directamente; extrae y presenta una grilla interactiva completa (`preview_rows`) de registros online.
- Selección por fila mediante checkboxes individuales y checkbox maestro superior.
- Modificación manual inline de fechas de cursada por fila mediante Datepicker (`<input type="date">`) y aplicador de fecha masiva a seleccionados.
- Resaltado visual con badges de alerta y error ante registros incompletos o aulas no reconocidas.
- Buscador en vivo multi-criterio y paginación fluida (25 filas por página) para evitar bloqueos del navegador.
- Modal de confirmación previa con desglose exacto de filas y entidades antes de iniciar la sincronización.
- **Backend & BFF Endpoints:**
- `POST /api/v1/dashboard/sheets-inspect` retorna metadatos y `preview_rows` con inferencia de fechas, estados de validación y carreras compartidas.
- `POST /api/v1/dashboard/sync-sheets` procesa opcionalmente `selected_rows` con fechas editadas respetando la granularidad de entidades activadas.
## [3.4.2] - 2026-10-07
### Corregido & Mejorado (UX/UI)
- **Agrupación Cronológica de Reservas en Cartelera del Día (`/schedule/today_schedule`):**
+21 -2
View File
@@ -99,7 +99,26 @@ Memoria del proyecto entre sesiones para la rama `dev`.
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
- Versión incrementada a `v3.4.2` en Frontend y Backend.
- Despliegue inmediato al servidor institucional `10.0.0.217` y verificación en caliente.
- **Sprint Importador Google Sheets: Selección Granular y Grilla Interactiva (v3.4.3)**:
- **Selección Granular de Entidades (Tarjetas Checkbox)**:
- Réplica del diseño visual de la Herramienta de Purga con botones "Marcar Todo" y "Desmarcar Todo".
- Toggles individuales para Asignaciones de aulas (`import_reservations`), Aulas físicas y virtuales (`import_classrooms`), Comisiones (`import_commissions`), Asignaturas (`import_subjects`) y Carreras (`import_careers`).
- **Selector de Días de la Semana con Checkboxes Múltiples**:
- Reemplazo del selector simple por checkboxes individuales para Lunes a Sábado con accesos rápidos ("Todos", "Lun a Vie", "Limpiar").
- **Grilla de Previsualización Interactiva e Inspección Previa**:
- El botón "Inspeccionar Sheet Online" no importa directamente; extrae y presenta una grilla interactiva completa (`preview_rows`) de registros online.
- Selección individual por fila y checkbox maestro superior.
- Modificación manual inline de fechas de cursada por fila mediante Datepicker (`<input type="date">`) y aplicador de fecha masiva a seleccionados.
- Resaltado visual con badges de alerta y error ante registros incompletos o aulas no reconocidas.
- Buscador en vivo multi-criterio y paginación fluida (25 filas por página) para evitar bloqueos del navegador.
- Modal de confirmación previa con desglose exacto de filas y entidades antes de iniciar la sincronización.
- **Backend y BFF REST**:
- `sheets_importer.py` ampliado para retornar `preview_rows` y procesar `selected_rows` con granularidad de entidades.
- Endpoints `POST /api/v1/dashboard/sheets-inspect` y `POST /api/v1/dashboard/sync-sheets`.
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
- Versión incrementada a `v3.4.3` en Frontend y Backend.
- Despliegue y verificación en caliente en el servidor institucional `10.0.0.217` (`https://eduspace.oemspot.com.ar`).
## Próximos pasos
1. Continuar con los objetivos de la Fase 6 del Roadmap institucional.
2. Monitoreo continuo de la experiencia de usuario en Bedelía y Cartelera del Día.
1. Continuar con los objetivos de la Fase 6 del Roadmap institucional (Docker-compose productivo, Nginx con SSL y automatización de workers continuos Moodle).
2. Monitoreo continuo de la experiencia de usuario en Bedelía, Cartelera del Día y Sincronización Académica.
+1 -1
View File
@@ -2,7 +2,7 @@
## Gestión de Espacios Áulicos, Asignación de Comisiones y Operatoria de Bedelía
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
**Versión:** 3.4.2 (Sprint UX/UI: Agrupación Cronológica de Reservas y Formato Limpio de Fechas)
**Versión:** 3.4.3 (Refactorización del Importador Google Sheets: Selección Granular y Grilla Interactiva)
**Fecha de Actualización:** 07 de Octubre de 2026
**Rama Base:** `dev`
+1 -1
View File
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
from config.config import Config
# Initialize extensions
__version__ = "3.4.2"
__version__ = "3.4.3"
db = SQLAlchemy()
migrate = Migrate()
cors = CORS()
+32 -4
View File
@@ -530,7 +530,7 @@ def get_stats():
@api_dashboard_bp.route('/sync-sheets', methods=['POST'])
@jwt_required
def sync_google_sheets():
"""Ejecuta la sincronización real con las hojas de cálculo de Google Sheets con soporte de filtros."""
"""Ejecuta la sincronización real con las hojas de cálculo de Google Sheets con soporte de filtros y entidades."""
from app.services.sheets_importer import GoogleSheetsImporter
try:
data = request.get_json(silent=True) or {}
@@ -538,16 +538,32 @@ def sync_google_sheets():
filter_career = data.get('filter_career')
filter_subject = data.get('filter_subject')
filter_day = data.get('filter_day')
filter_days = data.get('filter_days')
manual_date = data.get('manual_date')
single_date_only = bool(data.get('single_date_only', False))
# Opciones granulares de entidades
import_careers = data.get('import_careers', True)
import_subjects = data.get('import_subjects', True)
import_commissions = data.get('import_commissions', True)
import_classrooms = data.get('import_classrooms', True)
import_reservations = data.get('import_reservations', True)
selected_rows = data.get('selected_rows')
importer = GoogleSheetsImporter(base_url=custom_url)
stats = importer.sync(
filter_career=filter_career,
filter_subject=filter_subject,
filter_day=filter_day,
filter_days=filter_days,
manual_date=manual_date,
single_date_only=single_date_only
single_date_only=single_date_only,
import_careers=import_careers,
import_subjects=import_subjects,
import_commissions=import_commissions,
import_classrooms=import_classrooms,
import_reservations=import_reservations,
selected_rows=selected_rows
)
return jsonify({
'status': 'success',
@@ -563,13 +579,25 @@ def sync_google_sheets():
@api_dashboard_bp.route('/sheets-inspect', methods=['GET', 'POST'])
@jwt_required
def inspect_google_sheets():
"""Devuelve metadatos, carreras y materias del Google Sheet online para filtros interactivos."""
"""Devuelve metadatos, carreras, materias y previsualización de registros según los filtros aplicados."""
from app.services.sheets_importer import GoogleSheetsImporter
try:
data = request.get_json(silent=True) or {}
custom_url = data.get('sheets_url') or request.args.get('sheets_url')
filter_career = data.get('filter_career') or request.args.get('filter_career')
filter_subject = data.get('filter_subject') or request.args.get('filter_subject')
filter_day = data.get('filter_day') or request.args.get('filter_day')
filter_days = data.get('filter_days') or request.args.get('filter_days')
manual_date = data.get('manual_date') or request.args.get('manual_date')
importer = GoogleSheetsImporter(base_url=custom_url)
metadata = importer.inspect_sheet_content()
metadata = importer.inspect_sheet_content(
filter_career=filter_career,
filter_subject=filter_subject,
filter_day=filter_day,
filter_days=filter_days,
manual_date=manual_date
)
return jsonify({
'status': 'success',
'metadata': metadata,
+1 -1
View File
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
"info": {
"title": "Edu-Space REST API",
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
"version": "3.4.2"
"version": "3.4.3"
},
"servers": [
{
+180 -25
View File
@@ -352,21 +352,55 @@ class GoogleSheetsImporter:
except Exception:
return None, None
def inspect_sheet_content(self):
def inspect_sheet_content(self, filter_career=None, filter_subject=None, filter_day=None, filter_days=None, manual_date=None):
"""
Descarga e inspecciona las hojas del Sheet online para extraer:
- Días disponibles con cantidad de filas
- Carreras únicas
- Materias únicas con sus códigos, nombres y carreras
- Grilla de pre-visualización interactiva (preview_rows) según los filtros aplicados
"""
sheets_to_process = self.get_sheets_config()
days_info = []
careers_set = set()
subjects_map = {}
total_rows = 0
preview_rows = []
# Normalizar días seleccionados
allowed_days = None
if filter_days:
if isinstance(filter_days, str):
allowed_days = [normalize_day_name(d) for d in filter_days.split(',') if d.strip()]
elif isinstance(filter_days, (list, set)):
allowed_days = [normalize_day_name(d) for d in filter_days if d]
elif filter_day:
nd = normalize_day_name(filter_day)
if nd and nd.upper() not in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
allowed_days = [nd]
# Normalizar fecha manual para fecha inferida base
manual_dt = None
if manual_date:
try:
if isinstance(manual_date, (datetime, date)):
manual_dt = manual_date if isinstance(manual_date, date) else manual_date.date()
elif isinstance(manual_date, str) and manual_date.strip():
manual_dt = datetime.strptime(manual_date.strip(), '%Y-%m-%d').date()
except Exception:
pass
# Referencia de semana base: lunes 5 de octubre de 2026 (semana activa del 2° cuatrimestre)
ref_monday = date(2026, 10, 5)
if manual_dt:
ref_monday = manual_dt - timedelta(days=manual_dt.weekday())
row_counter = 0
for sheet_cfg in sheets_to_process:
day_name = sheet_cfg['name']
norm_day = normalize_day_name(day_name)
day_idx = sheet_cfg.get('day_idx', 0)
try:
csv_data = self.fetch_sheet_csv(sheet_cfg['gid'])
rows = self.parse_sheet_rows(csv_data, day_name)
@@ -374,10 +408,15 @@ class GoogleSheetsImporter:
days_info.append({
'name': day_name,
'gid': sheet_cfg['gid'],
'day_idx': sheet_cfg['day_idx'],
'day_idx': day_idx,
'rows_count': len(rows),
'status': 'OK'
})
# Si este día no está entre los permitidos, no lo agregamos a preview_rows
if allowed_days and norm_day not in allowed_days:
continue
for r in rows:
carreras = parse_careers_list(r.get('carrera', ''))
for c in carreras:
@@ -394,11 +433,67 @@ class GoogleSheetsImporter:
'careers': carreras,
'day': day_name
}
# Evaluar coincidencia de filtros de Carrera y Materia para la pre-visualización
if filter_career:
fc = filter_career.strip().upper()
match_c = any(fc in c.upper() or c.upper() in fc for c in carreras) or (fc in r.get('carrera', '').upper())
if not match_c:
continue
if filter_subject:
fs = filter_subject.strip().upper()
sub_codes = parse_subject_codes(code)
match_s = (fs in code.upper()) or (fs in name.upper()) or any(fs in sc.upper() for sc in sub_codes)
if not match_s:
continue
row_counter += 1
aula_raw = r.get('aula', '').strip()
room_info = self.normalize_room(aula_raw)
is_virtual = bool(room_info and ('VIRTUAL' in room_info.get('code', '').upper() or room_info.get('building') == 'Campus Virtual'))
# Calcular fecha tentativa
target_date = ref_monday + timedelta(days=day_idx)
if manual_dt and norm_day == normalize_day_name(['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'][manual_dt.weekday()]):
target_date = manual_dt
# Validaciones
is_valid = True
has_warning = False
warning_msg = None
if not code or not name:
is_valid = False
warning_msg = "Falta código o nombre de asignatura"
elif not room_info or not aula_raw or any(x in aula_raw.upper() for x in ['FERIADO', 'SIN ACTIVIDAD', 'CONSULTAR']):
has_warning = True
warning_msg = f"Aula pendiente o sin asignar ({aula_raw or 'Vacía'})"
preview_rows.append({
'id': row_counter,
'dia': norm_day,
'day_idx': day_idx,
'codigo': code,
'asignatura': name,
'aula': aula_raw or (room_info['code'] if room_info else 'Sin Aula'),
'aula_normalizada': room_info['code'] if room_info else 'Sin Aula',
'is_virtual': is_virtual,
'carrera': r.get('carrera', 'General'),
'carreras_list': carreras,
'horario': r.get('horario', ''),
'turno': r.get('turno', 'Mañana'),
'inferred_date': target_date.strftime('%Y-%m-%d'),
'is_valid': is_valid,
'has_warning': has_warning,
'warning_msg': warning_msg
})
except Exception as e:
days_info.append({
'name': day_name,
'gid': sheet_cfg['gid'],
'day_idx': sheet_cfg.get('day_idx', 0),
'day_idx': day_idx,
'rows_count': 0,
'status': 'Error',
'error': str(e)
@@ -406,19 +501,28 @@ class GoogleSheetsImporter:
return {
'total_rows': total_rows,
'matching_rows': len(preview_rows),
'days': days_info,
'careers': sorted(list(careers_set)),
'subjects': sorted(list(subjects_map.values()), key=lambda x: x['code'])
'subjects': sorted(list(subjects_map.values()), key=lambda x: x['code']),
'preview_rows': preview_rows
}
def sync(self, filter_career=None, filter_subject=None, filter_day=None, manual_date=None, single_date_only=False):
def sync(self, filter_career=None, filter_subject=None, filter_day=None, filter_days=None, manual_date=None, single_date_only=False, import_careers=True, import_subjects=True, import_commissions=True, import_classrooms=True, import_reservations=True, selected_rows=None):
"""
Proceso principal de sincronización con soporte de filtros y fechas manuales:
Proceso principal de sincronización con soporte de filtros, entidades granulares y filas seleccionadas:
:param filter_career: Filtrar por carrera específica (ej. 'DATOS (CCC)')
:param filter_subject: Filtrar por código o nombre de materia (ej. 'ASIG00113')
:param filter_day: Filtrar por día específico ('Lunes'..'Sábado' o 'ALL')
:param filter_days: Lista o cadena de días específicos (ej. ['Lunes', 'Martes'])
:param manual_date: Fecha manual específica (YYYY-MM-DD o objeto date)
:param single_date_only: Si es True y hay manual_date, crea reserva solo para esa fecha puntual
:param import_careers: Booleano para importar/crear carreras
:param import_subjects: Booleano para importar/crear asignaturas
:param import_commissions: Booleano para importar/crear comisiones
:param import_classrooms: Booleano para importar/crear aulas
:param import_reservations: Booleano para importar/crear reservas
:param selected_rows: Lista de filas específicas pre-seleccionadas desde la grilla interactiva
"""
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
@@ -430,19 +534,26 @@ class GoogleSheetsImporter:
manual_dt = manual_date if isinstance(manual_date, date) else manual_date.date()
elif isinstance(manual_date, str) and manual_date.strip():
manual_dt = datetime.strptime(manual_date.strip(), '%Y-%m-%d').date()
except Exception as e:
except Exception:
pass
# Normalizar día filtro si fue provisto
norm_filter_day = normalize_day_name(filter_day) if filter_day else None
if norm_filter_day and norm_filter_day.upper() in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
norm_filter_day = None
# Normalizar días permitidos
allowed_days = None
if filter_days:
if isinstance(filter_days, str):
allowed_days = [normalize_day_name(d) for d in filter_days.split(',') if d.strip()]
elif isinstance(filter_days, (list, set)):
allowed_days = [normalize_day_name(d) for d in filter_days if d]
elif filter_day:
nd = normalize_day_name(filter_day)
if nd and nd.upper() not in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
allowed_days = [nd]
# Si el usuario no especificó filter_day pero ingresó fecha manual puntual, inferir día
if not norm_filter_day and manual_dt and single_date_only:
# Si el usuario no especificó días pero ingresó fecha manual puntual, inferir día
if not allowed_days and manual_dt and single_date_only:
manual_w = manual_dt.weekday()
if manual_w < 6:
norm_filter_day = dias_esp[manual_w]
allowed_days = [dias_esp[manual_w]]
stats = {
'total_rows_processed': 0,
@@ -461,18 +572,35 @@ class GoogleSheetsImporter:
'filters_applied': {
'career': filter_career.strip() if filter_career else None,
'subject': filter_subject.strip() if filter_subject else None,
'day': norm_filter_day or 'Todos los Días',
'days': allowed_days or ['Todos los Días'],
'manual_date': manual_dt.strftime('%Y-%m-%d') if manual_dt else None,
'single_date_only': bool(single_date_only and manual_dt)
'single_date_only': bool(single_date_only and manual_dt),
'entities': {
'careers': bool(import_careers),
'subjects': bool(import_subjects),
'commissions': bool(import_commissions),
'classrooms': bool(import_classrooms),
'reservations': bool(import_reservations)
}
}
}
all_raw_records = []
sheets_to_process = self.get_sheets_config()
# Filtrar pestañas si se especificó un día específico
if norm_filter_day:
sheets_to_process = [s for s in sheets_to_process if normalize_day_name(s['name']) == norm_filter_day]
if selected_rows and isinstance(selected_rows, list) and len(selected_rows) > 0:
# Modo grilla interactiva: se procesan las filas explícitamente seleccionadas por el usuario
for r in selected_rows:
d_name = r.get('dia') or 'Lunes'
d_idx = map_day_to_idx(d_name)
all_raw_records.append((r, d_idx))
if d_name not in stats['by_day']:
stats['by_day'][d_name] = {'rows_count': 0, 'status': 'OK'}
stats['by_day'][d_name]['rows_count'] += 1
else:
# Modo descarga general desde Google Sheets
sheets_to_process = self.get_sheets_config()
if allowed_days:
sheets_to_process = [s for s in sheets_to_process if normalize_day_name(s['name']) in allowed_days]
for sheet_cfg in sheets_to_process:
day_name = sheet_cfg['name']
@@ -581,12 +709,14 @@ class GoogleSheetsImporter:
career = careers_cache.get(c_key)
if not career:
career = Career.query.filter(Career.name.ilike(c_name)).first()
if not career:
if not career and import_careers:
career = Career(name=c_name)
db.session.add(career)
db.session.flush()
stats['careers_created'] += 1
if career:
careers_cache[c_key] = career
if career:
career_objs.append(career)
primary_career = career_objs[0] if career_objs else None
@@ -599,6 +729,7 @@ class GoogleSheetsImporter:
classroom = classrooms_cache.get(room_key)
b_entity = buildings_cache.get(room_info['building'].upper())
if not classroom:
if import_classrooms:
classroom = Classroom(
building=room_info['building'],
building_id=b_entity.id if b_entity else None,
@@ -613,6 +744,9 @@ class GoogleSheetsImporter:
classrooms_cache[room_key] = classroom
stats['classrooms_created'] += 1
else:
classroom = Classroom.query.filter_by(code=room_info['code']).first()
else:
if import_classrooms:
classroom.capacity = max(classroom.capacity, room_info['capacity'])
if not classroom.building_id and b_entity:
classroom.building_id = b_entity.id
@@ -638,6 +772,7 @@ class GoogleSheetsImporter:
department_str = ", ".join([c.name for c in career_objs]) if career_objs else (primary_career.name if primary_career else 'General')
if not subject:
if import_subjects:
subject = Subject(
code=codigo,
name=asignatura,
@@ -646,11 +781,13 @@ class GoogleSheetsImporter:
credits=4,
is_active=True
)
if career_objs:
subject.careers = career_objs
db.session.add(subject)
db.session.flush()
stats['subjects_created'] += 1
else:
if import_subjects:
if subject.name != asignatura:
subject.name = asignatura
stats['subjects_updated'] += 1
@@ -662,12 +799,15 @@ class GoogleSheetsImporter:
subject.career_id = primary_career.id
subject.department = ", ".join([c.name for c in subject.careers]) if subject.careers else department_str
# Registrar en caché con código completo y con subcódigos individuales
# Registrar en caché con código completo y con subcódigos individuales si existe
if subject:
subjects_cache[subject_key] = subject
for sc in sub_codes:
subjects_cache[sc.upper()] = subject
# 4. Upsert Commission
commission = None
if subject:
comm_code = 'C1'
if '-E' in codigo:
comm_code = codigo.split('-')[-1]
@@ -682,6 +822,7 @@ class GoogleSheetsImporter:
).first()
if not commission:
if import_commissions:
commission = Commission(
subject_id=subject.id,
code=comm_code,
@@ -698,6 +839,7 @@ class GoogleSheetsImporter:
db.session.flush()
stats['commissions_created'] += 1
else:
if import_commissions:
commission.schedule = f"{dia} {horario_raw}"
commission.shift = turno
if classroom:
@@ -707,7 +849,7 @@ class GoogleSheetsImporter:
t_start, t_end = self.parse_time_range(horario_raw)
effective_day_idx = day_idx if day_idx is not None else (manual_dt.weekday() if manual_dt else 0)
if classroom and t_start and t_end:
if import_reservations and classroom and subject and commission and t_start and t_end:
is_room_virtual = bool(classroom.is_virtual or 'VIRTUAL' in (classroom.code or '').upper())
v_link = None
@@ -718,9 +860,22 @@ class GoogleSheetsImporter:
if not commission.virtual_link:
commission.virtual_link = v_link
# Determinar fechas a generar: puntual o 16 semanas
# Determinar fechas a generar: específica de la fila (datepicker), puntual o 16 semanas
dates_to_generate = []
if single_date_only and manual_dt:
row_specific_date = None
raw_row_date = rec.get('date') or rec.get('inferred_date')
if raw_row_date:
try:
if isinstance(raw_row_date, (datetime, date)):
row_specific_date = raw_row_date if isinstance(raw_row_date, date) else raw_row_date.date()
elif isinstance(raw_row_date, str) and raw_row_date.strip():
row_specific_date = datetime.strptime(raw_row_date.strip(), '%Y-%m-%d').date()
except Exception:
pass
if row_specific_date:
dates_to_generate = [row_specific_date]
elif single_date_only and manual_dt:
dates_to_generate = [manual_dt]
else:
dates_to_generate = [base_monday + timedelta(days=effective_day_idx, weeks=w) for w in range(weeks_to_generate)]
+1 -1
View File
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name="edu-space-admin",
version="3.4.2",
version="3.4.3",
description="Administrative interface for Edu-Space Classroom Management System",
author="Edu-Space Development Team",
author_email="admin@edu-space.com",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "3.4.2",
"version": "3.4.3",
"description": "",
"main": "index.js",
"scripts": {
+3 -3
View File
@@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
});
// Versiones institucionales del sistema
const APP_VERSION = '3.4.2';
const FRONTEND_VERSION = '3.4.2';
const BACKEND_VERSION = '3.4.2';
const APP_VERSION = '3.4.3';
const FRONTEND_VERSION = '3.4.3';
const BACKEND_VERSION = '3.4.3';
env.addGlobal('app_version', APP_VERSION);
env.addGlobal('frontend_version', FRONTEND_VERSION);
+27 -3
View File
@@ -91,10 +91,28 @@ const handleGoogleSheetsImport = async (req, res, justSynced = false) => {
if (req.body.filter_career) syncPayload.filter_career = req.body.filter_career.trim();
if (req.body.filter_subject) syncPayload.filter_subject = req.body.filter_subject.trim();
if (req.body.filter_day) syncPayload.filter_day = req.body.filter_day.trim();
if (req.body.filter_days) {
syncPayload.filter_days = Array.isArray(req.body.filter_days) ? req.body.filter_days : [req.body.filter_days];
}
if (req.body.manual_date) syncPayload.manual_date = req.body.manual_date.trim();
if (req.body.single_date_only === 'true' || req.body.single_date_only === true || req.body.single_date_only === 'on') {
syncPayload.single_date_only = true;
}
// Toggles granulares de entidades
syncPayload.import_careers = req.body.import_careers === 'true' || req.body.import_careers === true || req.body.import_careers === 'on';
syncPayload.import_subjects = req.body.import_subjects === 'true' || req.body.import_subjects === true || req.body.import_subjects === 'on';
syncPayload.import_commissions = req.body.import_commissions === 'true' || req.body.import_commissions === true || req.body.import_commissions === 'on';
syncPayload.import_classrooms = req.body.import_classrooms === 'true' || req.body.import_classrooms === true || req.body.import_classrooms === 'on';
syncPayload.import_reservations = req.body.import_reservations === 'true' || req.body.import_reservations === true || req.body.import_reservations === 'on';
// Filas preseleccionadas desde la grilla interactiva
if (req.body.selected_rows_json) {
try {
syncPayload.selected_rows = JSON.parse(req.body.selected_rows_json);
} catch (e) {
console.warn('Could not parse selected_rows_json:', e.message);
}
}
}
const syncRes = await req.apiClient.post('/dashboard/sync-sheets', syncPayload, { timeout: 90000 });
if (syncRes.data && syncRes.data.stats) {
@@ -143,6 +161,7 @@ const handleGoogleSheetsImport = async (req, res, justSynced = false) => {
filter_career: req.body?.filter_career || '',
filter_subject: req.body?.filter_subject || '',
filter_day: req.body?.filter_day || '',
filter_days: req.body?.filter_days || ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
manual_date: req.body?.manual_date || '',
single_date_only: req.body?.single_date_only === 'true' || req.body?.single_date_only === 'on',
flash_msg: flashMsg,
@@ -161,10 +180,15 @@ router.post(['/google_sheets_import', '/import'], (req, res) => handleGoogleShee
router.post('/sheets_inspect', async (req, res) => {
try {
const payload = {};
if (req.body && req.body.sheets_url) {
payload.sheets_url = req.body.sheets_url;
if (req.body) {
if (req.body.sheets_url) payload.sheets_url = req.body.sheets_url;
if (req.body.filter_career) payload.filter_career = req.body.filter_career;
if (req.body.filter_subject) payload.filter_subject = req.body.filter_subject;
if (req.body.filter_day) payload.filter_day = req.body.filter_day;
if (req.body.filter_days) payload.filter_days = req.body.filter_days;
if (req.body.manual_date) payload.manual_date = req.body.manual_date;
}
const resp = await req.apiClient.post('/dashboard/sheets-inspect', payload, { timeout: 35000 });
const resp = await req.apiClient.post('/dashboard/sheets-inspect', payload, { timeout: 45000 });
res.json(resp.data);
} catch (err) {
console.error('Error inspecting sheets in BFF:', err.response?.data || err.message);
+618 -56
View File
@@ -168,29 +168,107 @@
</div>
</div>
<form method="POST" id="syncForm" action="/admin/google_sheets_import" onsubmit="startSync()">
<form method="POST" id="syncForm" action="/admin/google_sheets_import">
<input type="hidden" name="sheets_url" id="syncSheetsUrl" value="{{ sheets_config.active_url }}">
<input type="hidden" name="selected_rows_json" id="selected_rows_json" value="">
<div class="row g-3 mb-4">
<!-- 1. Filtro por Día -->
<div class="col-md-6 col-lg-3">
<label for="filter_day" class="form-label fw-semibold small">
<i class="bi bi-calendar3 me-1 text-primary"></i>Día de Cursada:
<!-- 1. Selección Granular de Entidades a Sincronizar (Estilo Tarjetas Checkbox) -->
<div class="mb-4">
<div class="d-flex flex-wrap justify-content-between align-items-center mb-2 gap-2">
<label class="form-label fw-bold small text-uppercase text-secondary mb-0">
<i class="bi bi-check2-square text-success me-1"></i>1. Entidades a Importar / Sincronizar:
</label>
<select name="filter_day" id="filter_day" class="form-select form-select-sm">
<option value="" {% if not filter_day or filter_day == 'ALL' %}selected{% endif %}>Todos los Días (Lunes a Sábado)</option>
<option value="Lunes" {% if filter_day == 'Lunes' %}selected{% endif %}>Lunes</option>
<option value="Martes" {% if filter_day == 'Martes' %}selected{% endif %}>Martes</option>
<option value="Miércoles" {% if filter_day == 'Miércoles' or filter_day == 'Miercoles' %}selected{% endif %}>Miércoles</option>
<option value="Jueves" {% if filter_day == 'Jueves' %}selected{% endif %}>Jueves</option>
<option value="Viernes" {% if filter_day == 'Viernes' %}selected{% endif %}>Viernes</option>
<option value="Sábado" {% if filter_day == 'Sábado' or filter_day == 'Sabado' %}selected{% endif %}>Sábado</option>
</select>
<div class="form-text small">Procesa solo la pestaña del día indicado.</div>
<div class="btn-group btn-group-sm" role="group">
<button type="button" class="btn btn-outline-secondary py-0 px-2" onclick="toggleImportEntities(true)">
<i class="bi bi-check-all me-1"></i>Marcar Todo
</button>
<button type="button" class="btn btn-outline-secondary py-0 px-2" onclick="toggleImportEntities(false)">
<i class="bi bi-dash-square me-1"></i>Desmarcar Todo
</button>
</div>
</div>
<div class="row g-2">
<div class="col-sm-6 col-lg">
<div class="form-check p-2 border rounded bg-body-tertiary h-100 shadow-sm-sm">
<input class="form-check-input ms-1 me-2 import-entity-chk" type="checkbox" name="import_reservations" id="chk_import_reservations" value="true" checked>
<label class="form-check-label fw-semibold small" for="chk_import_reservations">
<i class="bi bi-calendar-check text-danger me-1"></i>Asignaciones (Reservas)
<small class="d-block text-muted fw-normal">Clases y horarios en calendario.</small>
</label>
</div>
</div>
<div class="col-sm-6 col-lg">
<div class="form-check p-2 border rounded bg-body-tertiary h-100 shadow-sm-sm">
<input class="form-check-input ms-1 me-2 import-entity-chk" type="checkbox" name="import_classrooms" id="chk_import_classrooms" value="true" checked>
<label class="form-check-label fw-semibold small" for="chk_import_classrooms">
<i class="bi bi-door-open text-success me-1"></i>Aulas Físicas y Virtuales
<small class="d-block text-muted fw-normal">Aulas presenciales y Zoom/PB.</small>
</label>
</div>
</div>
<div class="col-sm-6 col-lg">
<div class="form-check p-2 border rounded bg-body-tertiary h-100 shadow-sm-sm">
<input class="form-check-input ms-1 me-2 import-entity-chk" type="checkbox" name="import_commissions" id="chk_import_commissions" value="true" checked>
<label class="form-check-label fw-semibold small" for="chk_import_commissions">
<i class="bi bi-diagram-3 text-warning me-1"></i>Comisiones de Cursada
<small class="d-block text-muted fw-normal">Turnos y comisiones académicas.</small>
</label>
</div>
</div>
<div class="col-sm-6 col-lg">
<div class="form-check p-2 border rounded bg-body-tertiary h-100 shadow-sm-sm">
<input class="form-check-input ms-1 me-2 import-entity-chk" type="checkbox" name="import_subjects" id="chk_import_subjects" value="true" checked>
<label class="form-check-label fw-semibold small" for="chk_import_subjects">
<i class="bi bi-book text-info me-1"></i>Asignaturas / Materias
<small class="d-block text-muted fw-normal">Catálogo de materias curriculares.</small>
</label>
</div>
</div>
<div class="col-sm-6 col-lg">
<div class="form-check p-2 border rounded bg-body-tertiary h-100 shadow-sm-sm">
<input class="form-check-input ms-1 me-2 import-entity-chk" type="checkbox" name="import_careers" id="chk_import_careers" value="true" checked>
<label class="form-check-label fw-semibold small" for="chk_import_careers">
<i class="bi bi-mortarboard text-primary me-1"></i>Carreras Académicas
<small class="d-block text-muted fw-normal">Planes de estudio y carreras.</small>
</label>
</div>
</div>
</div>
</div>
<!-- 2. Filtro por Carrera -->
<div class="col-md-6 col-lg-3">
<!-- 2. Selección de Días de la Semana (Checkboxes Múltiples) -->
<div class="mb-4">
<div class="p-3 border rounded bg-body-tertiary">
<div class="d-flex flex-wrap justify-content-between align-items-center mb-2 gap-2">
<label class="form-label fw-bold small text-uppercase text-secondary mb-0">
<i class="bi bi-calendar3 text-primary me-1"></i>2. Días de la Semana a Procesar:
</label>
<div class="btn-group btn-group-sm" role="group">
<button type="button" class="btn btn-outline-primary py-0 px-2" onclick="setDaysSelection('all')">Todos</button>
<button type="button" class="btn btn-outline-secondary py-0 px-2" onclick="setDaysSelection('workdays')">Lun a Vie</button>
<button type="button" class="btn btn-outline-secondary py-0 px-2" onclick="setDaysSelection('none')">Limpiar</button>
</div>
</div>
<div class="d-flex flex-wrap gap-2" id="daysCheckboxesContainer">
{% set all_days = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'] %}
{% for d in all_days %}
<div class="form-check form-check-inline border rounded px-3 py-1 bg-white shadow-sm mb-0">
<input class="form-check-input filter-day-chk" type="checkbox" name="filter_days" id="day_chk_{{ loop.index }}" value="{{ d }}"
{% if not filter_days or (d in filter_days) or (filter_day and (filter_day == d or filter_day == 'ALL')) %}checked{% endif %}>
<label class="form-check-label small fw-semibold cursor-pointer" for="day_chk_{{ loop.index }}">{{ d }}</label>
</div>
{% endfor %}
</div>
<div class="form-text small mt-1">
<i class="bi bi-info-circle me-1"></i>Tilde uno o varios días específicos. Al inspeccionar o sincronizar se consultarán exclusivamente las pestañas seleccionadas.
</div>
</div>
</div>
<!-- 3. Filtros Específicos y Control de Fecha -->
<div class="row g-3 mb-4">
<!-- Filtro por Carrera -->
<div class="col-md-4">
<label for="filter_career" class="form-label fw-semibold small">
<i class="bi bi-mortarboard me-1 text-primary"></i>Carrera Académica:
</label>
@@ -202,11 +280,11 @@
<option value="{{ c.name if c.name else c }}"></option>
{% endfor %}
</datalist>
<div class="form-text small">Coincidencia exacta o compartida.</div>
<div class="form-text small">Coincidencia en materia principal o compartida.</div>
</div>
<!-- 3. Filtro por Materia -->
<div class="col-md-6 col-lg-3">
<!-- Filtro por Materia -->
<div class="col-md-4">
<label for="filter_subject" class="form-label fw-semibold small">
<i class="bi bi-book me-1 text-primary"></i>Materia / Asignatura:
</label>
@@ -218,33 +296,36 @@
<option value="{{ s.code }} - {{ s.name }}"></option>
{% endfor %}
</datalist>
<div class="form-text small">Busca por código o nombre de materia.</div>
<div class="form-text small">Busca por código o nombre curricular.</div>
</div>
<!-- 4. Fecha Manual y Control Puntual -->
<div class="col-md-6 col-lg-3">
<!-- Fecha Manual y Control Puntual -->
<div class="col-md-4">
<label for="manual_date" class="form-label fw-semibold small">
<i class="bi bi-calendar-event me-1 text-danger"></i>Fecha Manual (Corrección):
<i class="bi bi-calendar-event me-1 text-danger"></i>Fecha Manual Sugerida:
</label>
<input type="date" name="manual_date" id="manual_date" class="form-control form-control-sm"
value="{{ manual_date }}">
<div class="form-text small">Asigna/fuerza una fecha si falta en el Sheet.</div>
<div class="form-text small">Fecha por defecto para registros sin fecha inferida.</div>
</div>
</div>
<!-- Opciones adicionales de Fecha Manual -->
<!-- Opciones de Cursada y Acciones Principales -->
<div class="p-3 bg-body-tertiary rounded border mb-4">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" role="switch" id="single_date_only" name="single_date_only" value="true" {% if single_date_only %}checked{% endif %}>
<label class="form-check-label fw-semibold small" for="single_date_only">
<i class="bi bi-pin-angle-fill text-warning me-1"></i>Importar ÚNICAMENTE para esta fecha puntual
<i class="bi bi-pin-angle-fill text-warning me-1"></i>Importar ÚNICAMENTE para fecha puntual
</label>
<span class="d-block text-muted small">Crea 1 sola asignación/reserva en el calendario en lugar del cuatrimestre regular (16 semanas). Requiere indicar Fecha Manual.</span>
<span class="d-block text-muted small">Crea 1 sola asignación por fila en lugar del cuatrimestre regular (16 semanas).</span>
</div>
<div class="d-flex gap-2">
<button type="submit" id="syncBtn" class="btn btn-success px-4 py-2 shadow-sm fw-semibold">
<i class="bi bi-arrow-repeat me-2"></i>Iniciar Sincronización
<button type="button" class="btn btn-outline-primary px-3 shadow-sm fw-semibold" id="btnInspectSheet" onclick="inspectOnlineSheets()">
<i class="bi bi-search me-1"></i><span id="inspectBtnText">Inspeccionar Sheet Online</span>
</button>
<button type="button" id="syncBtn" class="btn btn-success px-4 shadow-sm fw-semibold" onclick="openSyncConfirmModal()">
<i class="bi bi-arrow-repeat me-1"></i>Iniciar Sincronización
</button>
</div>
</div>
@@ -256,6 +337,93 @@
<strong>Conectando a Google Sheets y sincronizando registros según filtros seleccionados...</strong>
</div>
<!-- 4. Grilla de Inspección Previa (Pre-visualización Interactiva) -->
<div id="previewSection" class="card border border-primary border-opacity-25 shadow-sm mb-4 d-none">
<div class="card-header bg-primary bg-opacity-10 py-3 d-flex flex-wrap justify-content-between align-items-center gap-2">
<div>
<h6 class="mb-0 fw-bold text-primary">
<i class="bi bi-table me-2"></i>Grilla de Inspección Previa (Previsualización Interactiva)
</h6>
<small class="text-muted">Revise, deseleccione filas individuales y ajuste las fechas de cursada antes de confirmar la subida.</small>
</div>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-white text-dark border">
Total detectado: <strong id="previewTotalCount">0</strong>
</span>
<span class="badge bg-success text-white">
Seleccionados: <strong id="previewSelectedCount">0</strong>
</span>
</div>
</div>
<div class="card-body p-3">
<!-- Barra de Controles de la Grilla -->
<div class="row g-2 align-items-center mb-3">
<div class="col-md-5">
<div class="input-group input-group-sm">
<span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
<input type="text" id="previewSearchInput" class="form-control" placeholder="Buscar por código, materia, carrera o aula..." oninput="onPreviewSearch()">
</div>
</div>
<div class="col-md-4">
<div class="input-group input-group-sm">
<span class="input-group-text bg-white small"><i class="bi bi-calendar-event me-1"></i>Fecha masiva:</span>
<input type="date" id="bulkDateInput" class="form-control">
<button type="button" class="btn btn-outline-secondary" onclick="applyBulkDate()" title="Aplica esta fecha a todos los registros seleccionados">
Aplicar
</button>
</div>
</div>
<div class="col-md-3 text-end">
<div class="btn-group btn-group-sm" role="group">
<button type="button" class="btn btn-outline-secondary" onclick="toggleSelectAllFiltered(true)">Marcar Todos</button>
<button type="button" class="btn btn-outline-secondary" onclick="toggleSelectAllFiltered(false)">Desmarcar</button>
</div>
</div>
</div>
<!-- Tabla de Previsualización -->
<div class="table-responsive border rounded mb-3" style="max-height: 520px; overflow-y: auto;">
<table class="table table-hover table-striped align-middle mb-0 small" id="previewTable">
<thead class="table-light sticky-top shadow-sm">
<tr>
<th class="text-center" style="width: 40px;">
<input class="form-check-input" type="checkbox" id="chkSelectAllPreview" onchange="toggleMasterPreviewCheckbox(this.checked)" checked title="Seleccionar/Deseleccionar todos">
</th>
<th style="width: 50px;">#</th>
<th style="width: 100px;">Día</th>
<th style="width: 110px;">Turno / Horario</th>
<th>Código & Asignatura</th>
<th>Carrera(s)</th>
<th style="width: 150px;">Aula Detectada</th>
<th style="width: 175px;">Fecha Cursada (Editable)</th>
<th style="width: 130px;">Estado</th>
</tr>
</thead>
<tbody id="previewTableBody">
<!-- Poblado dinámicamente con JavaScript -->
</tbody>
</table>
</div>
<!-- Paginación y Resumen -->
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
<div class="small text-muted" id="previewPaginationInfo">
Mostrando registros 1-25
</div>
<nav aria-label="Navegación de previsualización">
<ul class="pagination pagination-sm mb-0" id="previewPaginationNav">
<!-- Botones de paginación generados por JS -->
</ul>
</nav>
<div>
<button type="button" class="btn btn-sm btn-success px-3 shadow-sm fw-semibold" onclick="openSyncConfirmModal()">
<i class="bi bi-arrow-repeat me-1"></i>Confirmar Sincronización (<span id="previewSelectedCountBtn">0</span>)
</button>
</div>
</div>
</div>
</div>
<!-- Etiquetas de Días cubiertos en cartelera -->
<div class="d-flex flex-wrap align-items-center gap-1 pt-2 border-top">
<span class="small text-muted me-2">Hojas de cursada configuradas:</span>
@@ -600,32 +768,79 @@
</div>
</div>
</div>
<!-- Modal: Confirmación de Sincronización Académica -->
<div class="modal fade" id="syncConfirmModal" tabindex="-1" aria-labelledby="syncConfirmModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-0 shadow-lg">
<div class="modal-header bg-success text-white py-3">
<h5 class="modal-title h6 fw-bold" id="syncConfirmModalLabel">
<i class="bi bi-cloud-arrow-up-fill me-2"></i>Confirmar Sincronización Académica
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4">
<p class="mb-2 text-body">
¿Desea iniciar el procesamiento y sincronización de datos con el siguiente alcance?
</p>
<div class="p-3 bg-body-tertiary border rounded mb-3 small" id="syncConfirmDetails">
<!-- Poblado dinámicamente -->
</div>
<div class="alert alert-info small mb-0 d-flex gap-2 align-items-start">
<i class="bi bi-info-circle-fill fs-5 text-info flex-shrink-0"></i>
<div>
<strong>Nota:</strong> Los registros se validarán contra la matriz de disponibilidad. Las fechas editadas en la grilla se aplicarán a cada asignación individual.
</div>
</div>
</div>
<div class="modal-footer bg-body-tertiary border-top py-2">
<button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-success btn-sm px-4 fw-semibold" id="btnDoSyncConfirm" onclick="confirmSyncSubmission()">
<i class="bi bi-check2-circle me-1"></i>Sí, Iniciar Sincronización
</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script>
function startSync() {
const btn = document.getElementById('syncBtn');
const spinner = document.getElementById('syncSpinner');
const urlInput = document.getElementById('google_sheets_url');
const syncUrlInput = document.getElementById('syncSheetsUrl');
// Variables globales para el manejo de la previsualización interactiva
window.inspectedRows = [];
window.previewCurrentPage = 1;
window.previewPageSize = 25;
window.previewSearchTerm = '';
if (urlInput && syncUrlInput) {
syncUrlInput.value = urlInput.value.trim();
// Gestión de Entidades
function toggleImportEntities(checked) {
document.querySelectorAll('.import-entity-chk').forEach(el => el.checked = checked);
}
if (btn) {
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status"></span>Sincronizando con Google Sheets...';
}
if (spinner) {
spinner.classList.remove('d-none');
// Gestión de Días de la Semana
function setDaysSelection(mode) {
const chks = document.querySelectorAll('.filter-day-chk');
chks.forEach(el => {
if (mode === 'all') {
el.checked = true;
} else if (mode === 'none') {
el.checked = false;
} else if (mode === 'workdays') {
el.checked = (el.value !== 'Sábado' && el.value !== 'Sabado');
}
});
}
function getSelectedDays() {
const selected = [];
document.querySelectorAll('.filter-day-chk:checked').forEach(el => {
selected.push(el.value);
});
return selected;
}
// Limpieza de Filtros
function clearFilters() {
const d = document.getElementById('filter_day');
if (d) d.value = '';
const c = document.getElementById('filter_career');
if (c) c.value = '';
const s = document.getElementById('filter_subject');
@@ -634,22 +849,40 @@
if (m) m.value = '';
const single = document.getElementById('single_date_only');
if (single) single.checked = false;
setDaysSelection('all');
}
// Restaurar URL oficial
function restoreDefaultUrl() {
const defaultUrl = "{{ sheets_config.default_url }}";
const input = document.getElementById('google_sheets_url');
if (input && defaultUrl) {
input.value = defaultUrl;
}
}
// Inspección Online del Sheet
async function inspectOnlineSheets() {
const btn = document.getElementById('btnInspectSheet');
const btnText = document.getElementById('inspectBtnText');
const alertBox = document.getElementById('inspectAlert');
const alertMsg = document.getElementById('inspectAlertMsg');
const urlInput = document.getElementById('google_sheets_url');
const previewSec = document.getElementById('previewSection');
if (btn) btn.disabled = true;
if (btnText) btnText.innerText = 'Inspeccionando...';
try {
const selectedDays = getSelectedDays();
const payload = {
sheets_url: urlInput ? urlInput.value.trim() : ''
sheets_url: urlInput ? urlInput.value.trim() : '',
filter_career: (document.getElementById('filter_career')?.value || '').trim(),
filter_subject: (document.getElementById('filter_subject')?.value || '').trim(),
filter_days: selectedDays,
manual_date: (document.getElementById('manual_date')?.value || '').trim()
};
const resp = await fetch('/admin/sheets_inspect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -659,7 +892,8 @@
if (data.status === 'success' && data.metadata) {
const meta = data.metadata;
// Poblar datalists dinámicamente con carreras del Sheet online
// Actualizar datalist de Carreras
const careersList = document.getElementById('careersDataList');
if (careersList && meta.careers) {
careersList.innerHTML = '';
@@ -670,7 +904,7 @@
});
}
// Poblar datalists dinámicamente con materias del Sheet online
// Actualizar datalist de Materias
const subjectsList = document.getElementById('subjectsDataList');
if (subjectsList && meta.subjects) {
subjectsList.innerHTML = '';
@@ -681,11 +915,33 @@
});
}
// Cargar filas en memoria para la grilla interactiva
const rawRows = meta.preview_rows || [];
window.inspectedRows = rawRows.map(function(r) {
return Object.assign({}, r, {
selected: r.is_valid !== false,
date: r.inferred_date || document.getElementById('manual_date')?.value || ''
});
});
// Mostrar Alert resumen
if (alertBox && alertMsg) {
alertBox.className = 'alert alert-success border-0 shadow-sm mb-4';
alertMsg.innerHTML = '<strong>Inspección completada con éxito:</strong> Se detectaron <strong>' + (meta.total_rows || 0) + ' filas</strong>, <strong>' + (meta.careers ? meta.careers.length : 0) + ' carreras</strong> y <strong>' + (meta.subjects ? meta.subjects.length : 0) + ' materias</strong> disponibles en el Sheet online. Las sugerencias se han cargado en los campos de filtro.';
alertMsg.innerHTML = '<strong>Inspección completada con éxito:</strong> Se detectaron <strong>' +
(meta.total_rows || 0) + ' filas procesables</strong>, <strong>' +
(meta.careers ? meta.careers.length : 0) + ' carreras</strong> y <strong>' +
(meta.subjects ? meta.subjects.length : 0) + ' materias</strong> en los días seleccionados (' +
(selectedDays.join(', ') || 'Todos') + '). Revise los registros en la grilla inferior.';
alertBox.classList.remove('d-none');
}
// Desplegar y renderizar la grilla
if (previewSec) {
previewSec.classList.remove('d-none');
window.previewCurrentPage = 1;
renderPreview();
previewSec.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
} else {
throw new Error(data.message || 'No se pudieron extraer datos del Sheet online.');
}
@@ -701,14 +957,320 @@
}
}
function restoreDefaultUrl() {
const defaultUrl = "{{ sheets_config.default_url }}";
const input = document.getElementById('google_sheets_url');
if (input && defaultUrl) {
input.value = defaultUrl;
// Filtro de búsqueda en la grilla
function onPreviewSearch() {
const inp = document.getElementById('previewSearchInput');
window.previewSearchTerm = (inp ? inp.value : '').toLowerCase().trim();
window.previewCurrentPage = 1;
renderPreview();
}
function getFilteredRows() {
if (!window.previewSearchTerm) {
return window.inspectedRows;
}
const term = window.previewSearchTerm;
return window.inspectedRows.filter(function(r) {
const str = [
r.dia || '',
r.codigo || '',
r.asignatura || '',
r.carrera || '',
(r.carreras_list || []).join(' '),
r.aula || '',
r.horario || '',
r.turno || ''
].join(' ').toLowerCase();
return str.indexOf(term) !== -1;
});
}
// Renderizado dinámico de la Grilla Interactiva
function renderPreview() {
const tbody = document.getElementById('previewTableBody');
if (!tbody) return;
const filtered = getFilteredRows();
const totalFiltered = filtered.length;
const totalAll = window.inspectedRows.length;
const selectedCount = window.inspectedRows.filter(r => r.selected).length;
// Actualizar contadores
const totalCountEl = document.getElementById('previewTotalCount');
const selCountEl = document.getElementById('previewSelectedCount');
const selCountBtnEl = document.getElementById('previewSelectedCountBtn');
if (totalCountEl) totalCountEl.innerText = totalAll;
if (selCountEl) selCountEl.innerText = selectedCount;
if (selCountBtnEl) selCountBtnEl.innerText = selectedCount;
// Paginación
const totalPages = Math.max(1, Math.ceil(totalFiltered / window.previewPageSize));
if (window.previewCurrentPage > totalPages) window.previewCurrentPage = totalPages;
const startIdx = (window.previewCurrentPage - 1) * window.previewPageSize;
const pageRows = filtered.slice(startIdx, startIdx + window.previewPageSize);
if (pageRows.length === 0) {
tbody.innerHTML = '<tr><td colspan="9" class="text-center py-4 text-muted">' +
'<i class="bi bi-search fs-3 d-block mb-1 text-secondary"></i>' +
'No se encontraron registros que coincidan con la búsqueda.</td></tr>';
renderPreviewPagination(totalFiltered, totalPages);
return;
}
let html = '';
pageRows.forEach(function(row, idx) {
const globalIdx = startIdx + idx + 1;
const isInvalid = (row.is_valid === false);
const hasWarning = (row.has_warning === true);
const rowClass = isInvalid ? 'table-danger' : (hasWarning ? 'table-warning' : '');
// Badge de Aula
let aulaBadge = '';
if (row.is_virtual) {
aulaBadge = '<span class="badge bg-info-subtle text-info border border-info-subtle"><i class="bi bi-camera-video me-1"></i>' + (row.aula || 'Virtual') + '</span>';
} else if (row.aula) {
aulaBadge = '<span class="badge bg-secondary-subtle text-secondary border"><i class="bi bi-door-open me-1"></i>' + row.aula + '</span>';
} else {
aulaBadge = '<span class="badge bg-warning-subtle text-warning border border-warning-subtle"><i class="bi bi-question-circle me-1"></i>Sin Aula</span>';
}
// Badge de Estado
let estadoBadge = '';
if (isInvalid) {
estadoBadge = '<span class="badge bg-danger text-white"><i class="bi bi-x-circle me-1"></i>Inválido</span>';
} else if (hasWarning) {
estadoBadge = '<span class="badge bg-warning-subtle text-dark border border-warning-subtle" title="' + (row.warning_msg || 'Advertencia') + '"><i class="bi bi-exclamation-triangle me-1"></i>' + (row.warning_msg || 'Alerta') + '</span>';
} else {
estadoBadge = '<span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check-circle me-1"></i>Listo</span>';
}
// Carrera format
const carText = (row.carreras_list && row.carreras_list.length > 0) ? row.carreras_list.join(', ') : (row.carrera || 'General');
html += '<tr class="' + rowClass + '">' +
'<td class="text-center">' +
'<input class="form-check-input preview-row-chk" type="checkbox" ' +
(row.selected ? 'checked' : '') + ' ' +
(isInvalid ? 'disabled' : '') + ' ' +
'onchange="toggleRowSelection(\'' + row.id + '\', this.checked)">' +
'</td>' +
'<td class="text-muted font-monospace">' + globalIdx + '</td>' +
'<td><span class="badge bg-primary-subtle text-primary border border-primary-subtle">' + (row.dia || '-') + '</span></td>' +
'<td><div class="fw-semibold">' + (row.turno || '') + '</div><small class="text-muted">' + (row.horario || '') + '</small></td>' +
'<td>' +
'<div class="fw-bold text-dark">' + (row.codigo || '') + '</div>' +
'<div class="small text-secondary text-truncate" style="max-width: 220px;" title="' + (row.asignatura || '') + '">' + (row.asignatura || '') + '</div>' +
'</td>' +
'<td><small class="text-muted d-block text-truncate" style="max-width: 160px;" title="' + carText + '">' + carText + '</small></td>' +
'<td>' + aulaBadge + '</td>' +
'<td>' +
'<input type="date" class="form-control form-control-sm font-monospace" ' +
'value="' + (row.date || row.inferred_date || '') + '" ' +
'onchange="updateRowDate(\'' + row.id + '\', this.value)">' +
'</td>' +
'<td>' + estadoBadge + '</td>' +
'</tr>';
});
tbody.innerHTML = html;
renderPreviewPagination(totalFiltered, totalPages);
// Actualizar checkbox maestro
const masterChk = document.getElementById('chkSelectAllPreview');
if (masterChk) {
const visibleSelectable = pageRows.filter(r => r.is_valid !== false);
masterChk.checked = visibleSelectable.length > 0 && visibleSelectable.every(r => r.selected);
}
}
// Paginación visual
function renderPreviewPagination(totalFiltered, totalPages) {
const infoEl = document.getElementById('previewPaginationInfo');
const navEl = document.getElementById('previewPaginationNav');
if (!infoEl || !navEl) return;
const startIdx = totalFiltered === 0 ? 0 : (window.previewCurrentPage - 1) * window.previewPageSize + 1;
const endIdx = Math.min(window.previewCurrentPage * window.previewPageSize, totalFiltered);
infoEl.innerHTML = 'Mostrando registros <strong>' + startIdx + '</strong> - <strong>' + endIdx + '</strong> de <strong>' + totalFiltered + '</strong>';
let navHtml = '';
navHtml += '<li class="page-item ' + (window.previewCurrentPage === 1 ? 'disabled' : '') + '">' +
'<button class="page-link py-1 px-2" onclick="goToPreviewPage(' + (window.previewCurrentPage - 1) + ')">&laquo;</button>' +
'</li>';
let startP = Math.max(1, window.previewCurrentPage - 2);
let endP = Math.min(totalPages, startP + 4);
if (endP - startP < 4) startP = Math.max(1, endP - 4);
for (let p = startP; p <= endP; p++) {
navHtml += '<li class="page-item ' + (p === window.previewCurrentPage ? 'active' : '') + '">' +
'<button class="page-link py-1 px-2" onclick="goToPreviewPage(' + p + ')">' + p + '</button>' +
'</li>';
}
navHtml += '<li class="page-item ' + (window.previewCurrentPage === totalPages ? 'disabled' : '') + '">' +
'<button class="page-link py-1 px-2" onclick="goToPreviewPage(' + (window.previewCurrentPage + 1) + ')">&raquo;</button>' +
'</li>';
navEl.innerHTML = navHtml;
}
function goToPreviewPage(page) {
const filtered = getFilteredRows();
const totalPages = Math.max(1, Math.ceil(filtered.length / window.previewPageSize));
if (page < 1 || page > totalPages) return;
window.previewCurrentPage = page;
renderPreview();
}
// Edición Inline de Fechas en la Grilla
function updateRowDate(rowId, newDate) {
const row = window.inspectedRows.find(r => r.id === rowId);
if (row) {
row.date = newDate;
row.inferred_date = newDate;
}
}
// Toggle individual de selección de fila
function toggleRowSelection(rowId, checked) {
const row = window.inspectedRows.find(r => r.id === rowId);
if (row) {
row.selected = checked;
}
const selCount = window.inspectedRows.filter(r => r.selected).length;
const selCountEl = document.getElementById('previewSelectedCount');
const selCountBtnEl = document.getElementById('previewSelectedCountBtn');
if (selCountEl) selCountEl.innerText = selCount;
if (selCountBtnEl) selCountBtnEl.innerText = selCount;
}
// Checkbox Maestro de la Grilla
function toggleMasterPreviewCheckbox(checked) {
const filtered = getFilteredRows();
filtered.forEach(function(r) {
if (r.is_valid !== false) {
r.selected = checked;
}
});
renderPreview();
}
function toggleSelectAllFiltered(checked) {
const filtered = getFilteredRows();
filtered.forEach(function(r) {
if (r.is_valid !== false) {
r.selected = checked;
}
});
renderPreview();
}
// Aplicar Fecha Masiva a todas las filas seleccionadas
function applyBulkDate() {
const bulkInput = document.getElementById('bulkDateInput');
const val = bulkInput ? bulkInput.value : '';
if (!val) {
alert('Por favor ingrese una fecha válida en el campo de Fecha masiva.');
return;
}
let updatedCount = 0;
window.inspectedRows.forEach(function(r) {
if (r.selected) {
r.date = val;
r.inferred_date = val;
updatedCount++;
}
});
renderPreview();
alert('Se aplicó la fecha ' + val + ' a ' + updatedCount + ' fila(s) seleccionada(s).');
}
// Modal de Confirmación de Sincronización
function openSyncConfirmModal() {
const hasInspected = (window.inspectedRows && window.inspectedRows.length > 0);
const selCount = hasInspected ? window.inspectedRows.filter(r => r.selected).length : null;
if (hasInspected && selCount === 0) {
alert('Atención: Tiene 0 filas seleccionadas en la grilla de previsualización. Seleccione al menos una fila para sincronizar.');
return;
}
// Resumen de entidades marcadas
const chkRes = document.getElementById('chk_import_reservations')?.checked;
const chkCls = document.getElementById('chk_import_classrooms')?.checked;
const chkCom = document.getElementById('chk_import_commissions')?.checked;
const chkSub = document.getElementById('chk_import_subjects')?.checked;
const chkCar = document.getElementById('chk_import_careers')?.checked;
const detailsEl = document.getElementById('syncConfirmDetails');
if (detailsEl) {
let html = '<ul class="list-unstyled mb-0">';
if (hasInspected) {
html += '<li class="mb-1"><i class="bi bi-check2-circle text-success me-2"></i><strong>' + selCount + ' registros específicos seleccionados</strong> desde la grilla interactiva.</li>';
} else {
html += '<li class="mb-1"><i class="bi bi-layers text-primary me-2"></i>Sincronización completa de las pestañas de días seleccionadas.</li>';
}
html += '<li class="mt-2 text-muted fw-semibold">Entidades a crear / sincronizar:</li>';
if (chkRes) html += '<li class="ms-3"><i class="bi bi-calendar-check text-danger me-2"></i>Asignaciones de aulas (Reservas en Calendario)</li>';
if (chkCls) html += '<li class="ms-3"><i class="bi bi-door-open text-success me-2"></i>Aulas físicas y virtuales</li>';
if (chkCom) html += '<li class="ms-3"><i class="bi bi-diagram-3 text-warning me-2"></i>Comisiones de cursada</li>';
if (chkSub) html += '<li class="ms-3"><i class="bi bi-book text-info me-2"></i>Asignaturas / Materias</li>';
if (chkCar) html += '<li class="ms-3"><i class="bi bi-mortarboard text-primary me-2"></i>Carreras Académicas</li>';
const days = getSelectedDays();
html += '<li class="mt-2 text-muted fw-semibold">Días de cursada: ' + (days.length > 0 ? days.join(', ') : 'Ninguno seleccionado') + '</li>';
html += '</ul>';
detailsEl.innerHTML = html;
}
const modalEl = document.getElementById('syncConfirmModal');
if (modalEl && typeof bootstrap !== 'undefined' && bootstrap.Modal) {
try {
const modal = new bootstrap.Modal(modalEl);
modal.show();
return;
} catch (e) {
console.warn('Bootstrap modal error, fallback:', e);
}
}
if (confirm("¿Confirma iniciar la sincronización de las entidades seleccionadas?")) {
confirmSyncSubmission();
}
}
function confirmSyncSubmission() {
const btnConfirm = document.getElementById('btnDoSyncConfirm');
if (btnConfirm) {
btnConfirm.disabled = true;
btnConfirm.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Iniciando...';
}
// Si se inspeccionó previamente, serializar las filas seleccionadas
const hiddenSelectedRows = document.getElementById('selected_rows_json');
if (hiddenSelectedRows && window.inspectedRows && window.inspectedRows.length > 0) {
const selectedOnly = window.inspectedRows.filter(r => r.selected);
hiddenSelectedRows.value = JSON.stringify(selectedOnly);
}
const urlInput = document.getElementById('google_sheets_url');
const syncUrlInput = document.getElementById('syncSheetsUrl');
if (urlInput && syncUrlInput) {
syncUrlInput.value = urlInput.value.trim();
}
const spinner = document.getElementById('syncSpinner');
if (spinner) spinner.classList.remove('d-none');
const form = document.getElementById('syncForm');
if (form) {
form.submit();
}
}
// Modal de Purga
function toggleSelectAll(checked) {
document.getElementById('chk_reservations').checked = checked;
document.getElementById('chk_classrooms').checked = checked;