diff --git a/backend/app/routes/api/dashboard.py b/backend/app/routes/api/dashboard.py index 38e81ff..8ba396c 100644 --- a/backend/app/routes/api/dashboard.py +++ b/backend/app/routes/api/dashboard.py @@ -414,21 +414,6 @@ def get_stats(): available_classrooms_month = [] total_active_commissions = 0 milestones = [] - date_labels = { - 'today': 'Hoy', - 'today_short': 'Hoy', - 'today_full': 'Hoy', - 'week': 'Esta Semana', - 'week_full': 'Esta Semana', - 'month': 'Este Mes', - 'month_full': 'Este Mes' - } - filter_stats = { - 'date_labels': date_labels, - 'today': {'label': 'Hoy', 'classrooms': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}, 'commissions': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}}, - 'week': {'label': 'Esta Semana', 'classrooms': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}, 'commissions': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}}, - 'month': {'label': 'Este Mes', 'classrooms': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}, 'commissions': {'assigned': [], 'unassigned': [], 'assigned_count': 0, 'unassigned_count': 0, 'assigned_pct': 0, 'unassigned_pct': 0, 'total': 0}} - } # Mocked monthly data for chart since complex SQL group by month might differ based on dialect (SQLite vs Postgres) monthly_data = [ @@ -465,9 +450,7 @@ def get_stats(): 'assigned_today_pct': assigned_today_pct, 'unassigned_today_classrooms': unassigned_today_count, 'unassigned_today_pct': unassigned_today_pct, - 'total_active_commissions': total_active_commissions, - 'date_labels': date_labels, - 'filter_stats': filter_stats + 'total_active_commissions': total_active_commissions }, 'audit_logs': audit_data, 'monthly_data': monthly_data, @@ -476,14 +459,10 @@ def get_stats(): 'week_schedule_list': week_schedule_list, 'upcoming_reservations': upcoming_reservations, 'milestones': milestones, - 'filter_stats': filter_stats, - 'date_labels': date_labels, 'ui': { 'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True] }, 'bedelia': { - 'filter_stats': filter_stats, - 'date_labels': date_labels, 'unassigned_commissions_week': unassigned_commissions_week, 'unassigned_commissions_month': unassigned_commissions_month, 'unassigned_commissions_general': unassigned_commissions_general, diff --git a/backend/app/services/sheets_importer.py b/backend/app/services/sheets_importer.py index e747865..fa657b2 100644 --- a/backend/app/services/sheets_importer.py +++ b/backend/app/services/sheets_importer.py @@ -48,6 +48,21 @@ CANONICAL_CAREERS = { 'POSG. INCLUSIVAS': 'POSG. INCLUSIVAS', } +def normalize_day_name(day_str): + """Normaliza cualquier variante de día a su nombre canónico en español (Lunes..Sábado)""" + if not day_str: + return '' + d = day_str.strip().lower() + d = d.replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u') + if 'lun' in d: return 'Lunes' + if 'mar' in d: return 'Martes' + if 'mie' in d: return 'Miércoles' + if 'jue' in d: return 'Jueves' + if 'vie' in d: return 'Viernes' + if 'sab' in d: return 'Sábado' + if 'dom' in d: return 'Domingo' + return day_str.strip() + def map_day_to_idx(day_str): """Mapea el nombre del día (o prefijo) a su índice numérico 0..6 (Lunes=0)""" d = (day_str or '').lower() @@ -337,16 +352,101 @@ class GoogleSheetsImporter: except Exception: return None, None - def sync(self): + def inspect_sheet_content(self): """ - Proceso principal de sincronización: - 1. Descarga las 6 hojas de cálculo semanales (Lunes a Sábado). - 2. Normaliza carreras individuales y asignaturas compartidas (Many-to-Many). - 3. Upserts Aulas, Carreras, Asignaturas, Comisiones. - 4. Genera Reservas en el calendario para el semestre académico. + 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 """ + sheets_to_process = self.get_sheets_config() + days_info = [] + careers_set = set() + subjects_map = {} + total_rows = 0 + + for sheet_cfg in sheets_to_process: + day_name = sheet_cfg['name'] + try: + csv_data = self.fetch_sheet_csv(sheet_cfg['gid']) + rows = self.parse_sheet_rows(csv_data, day_name) + total_rows += len(rows) + days_info.append({ + 'name': day_name, + 'gid': sheet_cfg['gid'], + 'day_idx': sheet_cfg['day_idx'], + 'rows_count': len(rows), + 'status': 'OK' + }) + for r in rows: + carreras = parse_careers_list(r.get('carrera', '')) + for c in carreras: + if c and c != 'General': + careers_set.add(c) + + code = r.get('codigo', '').strip() + name = r.get('asignatura', '').strip() + if code and name: + if code not in subjects_map: + subjects_map[code] = { + 'code': code, + 'name': name, + 'careers': carreras, + 'day': day_name + } + except Exception as e: + days_info.append({ + 'name': day_name, + 'gid': sheet_cfg['gid'], + 'day_idx': sheet_cfg.get('day_idx', 0), + 'rows_count': 0, + 'status': 'Error', + 'error': str(e) + }) + + return { + 'total_rows': total_rows, + 'days': days_info, + 'careers': sorted(list(careers_set)), + 'subjects': sorted(list(subjects_map.values()), key=lambda x: x['code']) + } + + def sync(self, filter_career=None, filter_subject=None, filter_day=None, manual_date=None, single_date_only=False): + """ + Proceso principal de sincronización con soporte de filtros y fechas manuales: + :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 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 + """ + dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'] + + # Normalizar fecha manual si fue provista + 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 as e: + 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 + + # 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: + manual_w = manual_dt.weekday() + if manual_w < 6: + norm_filter_day = dias_esp[manual_w] + stats = { 'total_rows_processed': 0, + 'matching_rows': 0, 'careers_created': 0, 'careers_updated': 0, 'classrooms_created': 0, @@ -357,11 +457,23 @@ class GoogleSheetsImporter: 'reservations_created': 0, 'by_day': {}, 'errors': [], - 'sample_records': [] + 'sample_records': [], + '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', + 'manual_date': manual_dt.strftime('%Y-%m-%d') if manual_dt else None, + 'single_date_only': bool(single_date_only and manual_dt) + } } 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] + for sheet_cfg in sheets_to_process: day_name = sheet_cfg['name'] try: @@ -424,9 +536,11 @@ class GoogleSheetsImporter: classrooms_cache = {(c.building.strip().upper(), c.code.strip().upper()): c for c in Classroom.query.all()} subjects_cache = {s.code.strip().upper(): s for s in Subject.query.all()} - # Calculate current semester dates (anchored on academic year 2026) + # Calculate semester dates (anchored on academic year 2026 or manual date base) base_monday = date(2026, 8, 31) - weeks_to_generate = 16 # Generar reservas para 16 semanas (cuatrimestre completo Ago - Dic 2026) + if manual_dt and not single_date_only: + base_monday = manual_dt - timedelta(days=manual_dt.weekday()) + weeks_to_generate = 16 # Generar reservas para 16 semanas for rec, day_idx in all_raw_records: try: @@ -435,11 +549,32 @@ class GoogleSheetsImporter: aula_raw = rec['aula'] carrera_raw = rec['carrera'].strip() horario_raw = rec['horario'] - dia = rec['dia'] + dia = rec['dia'] or (dias_esp[manual_dt.weekday()] if manual_dt else 'Lunes') turno = rec.get('turno', 'Mañana') - # 1. Upsert Careers (Desglosar carreras múltiples normalizadas) + # Si el registro no traía día pero hay fecha manual, asignar día de la fecha + if day_idx is None and manual_dt: + day_idx = manual_dt.weekday() + + # --- FILTRO 1: Filtrar por Carrera si fue especificada --- carreras_list = parse_careers_list(carrera_raw) + if filter_career: + fc = filter_career.strip().upper() + match_c = any(fc in c.upper() or c.upper() in fc for c in carreras_list) or (fc in carrera_raw.upper()) + if not match_c: + continue + + # --- FILTRO 2: Filtrar por Materia si fue especificada --- + sub_codes = parse_subject_codes(codigo) + if filter_subject: + fs = filter_subject.strip().upper() + match_s = (fs in codigo.upper()) or (fs in asignatura.upper()) or any(fs in sc.upper() for sc in sub_codes) + if not match_s: + continue + + stats['matching_rows'] += 1 + + # 1. Upsert Careers (Desglosar carreras múltiples normalizadas) career_objs = [] for c_name in carreras_list: c_key = c_name.upper() @@ -484,7 +619,6 @@ class GoogleSheetsImporter: # 3. Upsert Subject (Soporte Many-to-Many con múltiples carreras y subcódigos) subject_key = codigo.upper() - sub_codes = parse_subject_codes(codigo) subject = subjects_cache.get(subject_key) if not subject: for sc in sub_codes: @@ -571,7 +705,9 @@ class GoogleSheetsImporter: # 5. Generar Reservas de Calendario t_start, t_end = self.parse_time_range(horario_raw) - if classroom and t_start and t_end and day_idx is not None: + 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: is_room_virtual = bool(classroom.is_virtual or 'VIRTUAL' in (classroom.code or '').upper()) v_link = None @@ -582,8 +718,14 @@ class GoogleSheetsImporter: if not commission.virtual_link: commission.virtual_link = v_link - for w in range(weeks_to_generate): - class_date = base_monday + timedelta(days=day_idx, weeks=w) + # Determinar fechas a generar: puntual o 16 semanas + dates_to_generate = [] + if 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)] + + for class_date in dates_to_generate: dt_start = datetime.combine(class_date, t_start) dt_end = datetime.combine(class_date, t_end) @@ -602,6 +744,8 @@ class GoogleSheetsImporter: ).first() c_desc = ", ".join([c.name for c in career_objs]) if career_objs else 'General' + note_suffix = f" [Fecha asignada: {class_date.strftime('%d/%m/%Y')}]" if (manual_dt and single_date_only) else "" + note_text = f"Clase {'puntual ' if (single_date_only and manual_dt) else 'semanal '}{dia} ({turno}) - Carreras: {c_desc}{note_suffix}" if not existing_res: res = Reservation( @@ -615,13 +759,13 @@ class GoogleSheetsImporter: expected_attendees=min(classroom.capacity, 30) if not is_room_virtual else 35, shift=turno, virtual_link=v_link, - notes=f"Clase semanal {dia} ({turno}) - Carreras: {c_desc}" + notes=note_text ) db.session.add(res) stats['reservations_created'] += 1 else: existing_res.shift = turno - existing_res.notes = f"Clase semanal {dia} ({turno}) - Carreras: {c_desc}" + existing_res.notes = note_text if is_room_virtual and not existing_res.virtual_link: existing_res.virtual_link = v_link diff --git a/frontend/src/routes/admin.js b/frontend/src/routes/admin.js index dad7f91..1b8688e 100644 --- a/frontend/src/routes/admin.js +++ b/frontend/src/routes/admin.js @@ -107,7 +107,7 @@ const handleGoogleSheetsImport = async (req, res, justSynced = false) => { recentSubjects = (sR.value.data?.subjects || []).slice(0, 15); } if (cmR.status === 'fulfilled') metrics.total_commissions = cmR.value.data?.commissions?.length || 0; - } catch (e) {} + } catch (e) { } } catch (err) { console.error('Backend sync-sheets API error:', err.response?.data || err.message); syncError = err.response?.data?.message || err.message; @@ -276,9 +276,9 @@ router.get(['/occupancy_metrics', '/occupancy-metrics', '/metrics/occupancy'], h const MOCK_ROLES = [ { id: 1, name: 'Administrador', description: 'Acceso total al sistema', user_count: 2, is_system: true, permissions: { classrooms: 'read_write', schedule: 'read_write', admin: 'read_write', buildings: 'read_write' } }, - { id: 2, name: 'Bedel', description: 'Gestión de reservas y aulas', user_count: 5, is_system: false, permissions: { classrooms: 'read_write', schedule: 'read_write', admin: 'read', buildings: 'read' } }, - { id: 3, name: 'Docente', description: 'Visualización de horarios', user_count: 18, is_system: false, permissions: { classrooms: 'read', schedule: 'read', admin: 'none', buildings: 'read' } }, - { id: 4, name: 'Invitado', description: 'Solo lectura', user_count: 3, is_system: false, permissions: { classrooms: 'read', schedule: 'none', admin: 'none', buildings: 'none' } } + { id: 2, name: 'Bedel', description: 'Gestión de reservas y aulas', user_count: 5, is_system: false, permissions: { classrooms: 'read_write', schedule: 'read_write', admin: 'read', buildings: 'read' } }, + { id: 3, name: 'Docente', description: 'Visualización de horarios', user_count: 18, is_system: false, permissions: { classrooms: 'read', schedule: 'read', admin: 'none', buildings: 'read' } }, + { id: 4, name: 'Invitado', description: 'Solo lectura', user_count: 3, is_system: false, permissions: { classrooms: 'read', schedule: 'none', admin: 'none', buildings: 'none' } } ]; const MOCK_USERS = [ @@ -349,7 +349,7 @@ const handleUsersList = async (req, res) => { if (role_filter) { filtered = filtered.filter(u => String(u.role_id) === String(role_filter)); } - if (status_filter === 'active') filtered = filtered.filter(u => u.is_active); + if (status_filter === 'active') filtered = filtered.filter(u => u.is_active); if (status_filter === 'inactive') filtered = filtered.filter(u => !u.is_active); res.render('admin/users/list', { @@ -388,10 +388,10 @@ const handleUserAdd = async (req, res) => { }); } catch (err) { console.error('Error in user add:', err.message); - res.render('admin/users/form', { - title: 'Nuevo Usuario — Edu-Space Admin', - user: null, - roles: MOCK_ROLES, + res.render('admin/users/form', { + title: 'Nuevo Usuario — Edu-Space Admin', + user: null, + roles: MOCK_ROLES, document_types: [], error: req.query.error || null, msg: null @@ -431,25 +431,25 @@ const handleUserEdit = async (req, res) => { }); } catch (err) { console.error('Error in user edit:', err.message); - res.render('admin/users/form', { - title: 'Editar Usuario — Edu-Space Admin', - user: MOCK_USERS[0], - roles: MOCK_ROLES, + res.render('admin/users/form', { + title: 'Editar Usuario — Edu-Space Admin', + user: MOCK_USERS[0], + roles: MOCK_ROLES, document_types: [], error: 'No se pudo cargar la información del usuario.', - msg: null + msg: null }); } }; const handleUserSave = async (req, res) => { const userId = req.params.id || req.body.id; - const { + const { name, first_name, last_name, email, personal_email, password, role_id, is_active, - phone, address, document_type, document_number + phone, address, document_type, document_number } = req.body; - const payload = { + const payload = { first_name: (first_name || '').trim(), last_name: (last_name || '').trim(), name: (name || `${first_name || ''} ${last_name || ''}`).trim(), @@ -518,12 +518,12 @@ router.post(['/users/:id/password', '/users/password', '/user_password', '/user_ // ─── 4. ROLES ───────────────────────────────────────────────────────────────── const MODULES = [ - { id: 'classrooms', name: 'Aulas', icon: 'bi-door-open' }, - { id: 'schedule', name: 'Horarios', icon: 'bi-calendar3' }, - { id: 'buildings', name: 'Edificios', icon: 'bi-buildings' }, - { id: 'admin', name: 'Admin', icon: 'bi-shield-lock' }, - { id: 'users', name: 'Usuarios', icon: 'bi-people' }, - { id: 'reports', name: 'Reportes', icon: 'bi-graph-up' } + { id: 'classrooms', name: 'Aulas', icon: 'bi-door-open' }, + { id: 'schedule', name: 'Horarios', icon: 'bi-calendar3' }, + { id: 'buildings', name: 'Edificios', icon: 'bi-buildings' }, + { id: 'admin', name: 'Admin', icon: 'bi-shield-lock' }, + { id: 'users', name: 'Usuarios', icon: 'bi-people' }, + { id: 'reports', name: 'Reportes', icon: 'bi-graph-up' } ]; const handleRolesList = async (req, res) => { @@ -879,7 +879,7 @@ const handleCommissionsList = async (req, res) => { try { const carRes = await req.apiClient.get('/careers'); careers = carRes.data?.careers || []; - } catch (carErr) {} + } catch (carErr) { } } // Si por alguna razón no vinieron academic_terms en commissions, intentar fallback @@ -887,7 +887,7 @@ const handleCommissionsList = async (req, res) => { try { const termsRes = await req.apiClient.get('/academic-terms'); academic_terms = termsRes.data?.terms || termsRes.data?.academic_terms || []; - } catch (tErr) {} + } catch (tErr) { } } if (uRes.status === 'fulfilled' && uRes.value.data) { diff --git a/frontend/views/admin/import.html b/frontend/views/admin/import.html index 1ea4f00..9edd44d 100644 --- a/frontend/views/admin/import.html +++ b/frontend/views/admin/import.html @@ -8,9 +8,11 @@

- Google Sheets Academic Sync & Gestión de Datos + Google Sheets Academic Sync & Gestión de + Datos

-

Extrae, normaliza y sincroniza carreras, aulas, comisiones y cronogramas de cursada desde Google Sheets con soporte de configuración dinámica y reinicio de entorno.

+

Extrae, normaliza y sincroniza carreras, aulas, comisiones y cronogramas de + cursada desde Google Sheets con soporte de configuración dinámica y reinicio de entorno.

@@ -24,33 +26,33 @@ {% if flash_msg %} -