from flask import Blueprint, jsonify, request, g from app.utils.jwt_decorators import jwt_required from app.models.classroom import Classroom from app.models.subject import Subject from app.models.user import User from app.models.reservation import Reservation from app.models.audit_log import AuditLog from app.services.audit_service import AuditService from datetime import datetime, timedelta from sqlalchemy import func from app import db from app.models.milestone import AcademicMilestone from app.models.subject import Commission from app.models.setting import SystemSetting api_dashboard_bp = Blueprint('api_dashboard', __name__, url_prefix='/api/v1/dashboard') def serialize_reservation(r): subject_name = (r.commission.subject.name if (r.commission and r.commission.subject) else r.purpose) or 'Actividad Académica' subject_code = (r.commission.subject.code if (r.commission and r.commission.subject) else '') classroom_code = r.classroom.code if r.classroom else 'Sin Aula' is_virtual = ('virtual' in classroom_code.lower()) or (getattr(r.classroom, 'is_virtual', False) if r.classroom else False) return { 'id': r.id, 'start_time': r.start_time.strftime('%H:%M') if r.start_time else '', 'end_time': r.end_time.strftime('%H:%M') if r.end_time else '', 'date_display': r.start_time.strftime('%d/%m') if r.start_time else '', 'classroom': { 'id': r.classroom_id, 'code': classroom_code, 'is_virtual': is_virtual, 'location_display': getattr(r.classroom, 'location_display', f'Sede Central · {classroom_code}') if r.classroom else 'Sin Aula' }, 'subject_name': subject_name, 'subject_code': subject_code, 'shift': r.shift or 'Mañana', 'commission': { 'id': r.commission_id, 'code': r.commission.code if r.commission else 'COM-1' }, 'status': str(r.status.value if hasattr(r.status, 'value') else r.status), 'user': { 'id': r.user_id, 'name': r.user.name if r.user else 'Docente' }, 'virtual_link': r.virtual_link or ('https://meet.google.com/edu-space-' + classroom_code.lower().replace(' ', '-') if is_virtual else '') } def serialize_milestone(m): return { 'id': m.id, 'title': m.title, 'materia_codigo': m.materia_codigo, 'subject_name': m.subject.name if (hasattr(m, 'subject') and m.subject) else m.materia_codigo, 'date': m.date.strftime('%d/%m/%Y') if m.date else '', 'type_obj': { 'name': m.type_obj.name if m.type_obj else 'Evaluación', 'color': m.type_obj.color if m.type_obj else '#0d6efd' }, 'classroom': m.classroom or 'Sede Central', 'link': m.link or '', 'notes': m.notes or '' } @api_dashboard_bp.route('/stats', methods=['GET']) @jwt_required def get_stats(): """Retorna estadísticas clave y datos operativos para el Dashboard.""" today = datetime.utcnow().date() try: total_classrooms = Classroom.query.filter_by(is_active=True).count() total_subjects = Subject.query.filter_by(is_active=True).count() total_users = User.query.filter_by(is_active=True).count() # Aulas presenciales y virtuales all_active_classrooms = Classroom.query.filter_by(is_active=True).all() virtual_classrooms_list = [ c for c in all_active_classrooms if getattr(c, 'is_virtual', False) or 'virtual' in (c.building or '').lower() or 'virtual' in (c.code or '').lower() ] virtual_classrooms = len(virtual_classrooms_list) physical_classrooms_list = [ c for c in all_active_classrooms if c not in virtual_classrooms_list ] total_physical_count = len(physical_classrooms_list) physical_classrooms = total_physical_count physical_ids = set(c.id for c in physical_classrooms_list) # 1. Asignación General del Cuatrimestre / Cronograma assigned_all_ids = set( r[0] for r in db.session.query(Reservation.classroom_id) .filter(Reservation.classroom_id.isnot(None)).distinct().all() ) assigned_physical_ids = physical_ids.intersection(assigned_all_ids) assigned_classrooms = len(assigned_physical_ids) unassigned_classrooms = max(0, total_physical_count - assigned_classrooms) assigned_pct = round((assigned_classrooms / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0 unassigned_pct = round(100.0 - assigned_pct, 1) if total_physical_count > 0 else 0.0 # 2. Asignación Operativa del Día de Hoy assigned_today_ids = set( r[0] for r in db.session.query(Reservation.classroom_id).filter( Reservation.classroom_id.isnot(None), func.date(Reservation.start_time) == today ).distinct().all() ) assigned_today_physical_ids = physical_ids.intersection(assigned_today_ids) assigned_today_count = len(assigned_today_physical_ids) unassigned_today_count = max(0, total_physical_count - assigned_today_count) assigned_today_pct = round((assigned_today_count / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0 unassigned_today_pct = round(100.0 - assigned_today_pct, 1) if total_physical_count > 0 else 0.0 today_reservations_q = Reservation.query.filter( func.date(Reservation.start_time) == today ).order_by(Reservation.start_time.asc()).all() today_reservations = len(today_reservations_q) pending_reservations_q = Reservation.query.filter( Reservation.status == 'PENDING' ).order_by(Reservation.start_time.asc()).all() pending_count = len(pending_reservations_q) upcoming_reservations_q = Reservation.query.filter( Reservation.start_time >= datetime.utcnow() ).order_by(Reservation.start_time.asc()).limit(10).all() milestones_q = AcademicMilestone.query.filter( AcademicMilestone.is_active == True ).order_by(AcademicMilestone.date.asc()).limit(10).all() recent_audits = AuditLog.query.order_by(AuditLog.created_at.desc()).limit(6).all() audit_data = [{ 'created_at': a.created_at.strftime('%Y-%m-%d %H:%M') if a.created_at else None, 'action_type': getattr(a, 'action', getattr(a, 'action_type', 'AUDIT')), 'ip_address': a.ip_address, 'user_email': getattr(a, 'user_email', None) or (getattr(a.user, 'email', 'System') if hasattr(a, 'user') else 'System') } for a in recent_audits] occupancy_rate = min(100, int((today_reservations / max(1, physical_classrooms * 3)) * 100)) if physical_classrooms > 0 else 0 pending_reservations = [serialize_reservation(r) for r in pending_reservations_q] today_schedule_list = [serialize_reservation(r) for r in today_reservations_q] upcoming_reservations = [serialize_reservation(r) for r in upcoming_reservations_q] milestones = [serialize_milestone(m) for m in milestones_q] jwt_user = getattr(g, 'jwt_user', None) user_id = getattr(jwt_user, 'id', None) my_today_count = 0 my_total_reservations = 0 my_today_classes = [] if user_id: my_today_q = Reservation.query.filter( Reservation.user_id == user_id, func.date(Reservation.start_time) == today, Reservation.status != 'CANCELLED' ).order_by(Reservation.start_time.asc()).all() my_today_count = len(my_today_q) my_today_classes = [serialize_reservation(r) for r in my_today_q] my_total_reservations = Reservation.query.filter( Reservation.user_id == user_id, Reservation.status.in_(['CONFIRMED', 'PENDING']) ).count() else: my_today_count = today_reservations my_total_reservations = len(today_reservations_q) my_today_classes = today_schedule_list[:5] # ---- Bedelía: Filtros completos de Aulas y Comisiones por Día (Hoy), Mañana, Semana y Mes ---- import calendar today_dt = datetime.utcnow() tomorrow_dt = today_dt + timedelta(days=1) tomorrow_start = tomorrow_dt.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow_end = tomorrow_dt.replace(hour=23, minute=59, second=59, microsecond=0) week_start = today_dt - timedelta(days=today_dt.weekday()) # Lunes week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0) week_end = week_start + timedelta(days=6, hours=23, minutes=59, seconds=59) month_start = today_dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_day = calendar.monthrange(today_dt.year, today_dt.month)[1] month_end = today_dt.replace(day=last_day, hour=23, minute=59, second=59, microsecond=0) # Etiquetas legibles de fecha en español dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'] meses_esp = ['', 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'] weekday_name = dias_esp[today_dt.weekday()] month_name = meses_esp[today_dt.month] tomorrow_weekday_name = dias_esp[tomorrow_dt.weekday()] tomorrow_month_name = meses_esp[tomorrow_dt.month] date_labels = { 'today': f"Hoy · {weekday_name} {today_dt.strftime('%d/%m/%Y')}", 'today_short': f"{weekday_name} {today_dt.strftime('%d/%m')}", 'today_full': f"{weekday_name}, {today_dt.day} de {month_name} de {today_dt.year}", 'tomorrow': f"Mañana · {tomorrow_weekday_name} {tomorrow_dt.strftime('%d/%m/%Y')}", 'tomorrow_short': f"{tomorrow_weekday_name} {tomorrow_dt.strftime('%d/%m')}", 'tomorrow_full': f"{tomorrow_weekday_name}, {tomorrow_dt.day} de {tomorrow_month_name} de {tomorrow_dt.year}", 'week': f"Semana del {week_start.strftime('%d/%m')} al {week_end.strftime('%d/%m/%Y')}", 'week_full': f"Semana del {week_start.strftime('%d/%m/%Y')} al {week_end.strftime('%d/%m/%Y')}", 'month': f"Mes de {month_name} {today_dt.year} ({month_start.strftime('%d/%m')} al {month_end.strftime('%d/%m/%Y')})", 'month_full': f"{month_name} de {today_dt.year}" } # Reservas por período tomorrow_reservations_q = Reservation.query.filter( Reservation.start_time >= tomorrow_start, Reservation.start_time <= tomorrow_end ).order_by(Reservation.start_time.asc()).all() tomorrow_schedule_list = [serialize_reservation(r) for r in tomorrow_reservations_q] week_reservations_q = Reservation.query.filter( Reservation.start_time >= week_start, Reservation.start_time <= week_end ).order_by(Reservation.start_time.asc()).all() week_schedule_list = [serialize_reservation(r) for r in week_reservations_q] month_reservations_q = Reservation.query.filter( Reservation.start_time >= month_start, Reservation.start_time <= month_end ).order_by(Reservation.start_time.asc()).all() # Mapas de reservas por aula en cada período res_map_classroom_today = {} for r in today_reservations_q: if r.classroom_id: res_map_classroom_today.setdefault(r.classroom_id, []).append(r) res_map_classroom_tomorrow = {} for r in tomorrow_reservations_q: if r.classroom_id: res_map_classroom_tomorrow.setdefault(r.classroom_id, []).append(r) res_map_classroom_week = {} for r in week_reservations_q: if r.classroom_id: res_map_classroom_week.setdefault(r.classroom_id, []).append(r) res_map_classroom_month = {} for r in month_reservations_q: if r.classroom_id: res_map_classroom_month.setdefault(r.classroom_id, []).append(r) # Mapas de reservas por comisión en cada período res_map_comm_today = {} for r in today_reservations_q: if r.commission_id: res_map_comm_today.setdefault(r.commission_id, []).append(r) res_map_comm_tomorrow = {} for r in tomorrow_reservations_q: if r.commission_id: res_map_comm_tomorrow.setdefault(r.commission_id, []).append(r) res_map_comm_week = {} for r in week_reservations_q: if r.commission_id: res_map_comm_week.setdefault(r.commission_id, []).append(r) res_map_comm_month = {} for r in month_reservations_q: if r.commission_id: res_map_comm_month.setdefault(r.commission_id, []).append(r) all_active_commissions = Commission.query.filter_by(active=True).all() total_active_commissions = len(all_active_commissions) # Helper para serializar aula con info contextual def build_classroom_item(c, res_list): r_first = res_list[0] if res_list else None assigned_summary = '' if r_first: subj = (r_first.commission.subject.name if (r_first.commission and r_first.commission.subject) else r_first.purpose) or 'Clase' assigned_summary = f"{subj} ({r_first.start_time.strftime('%H:%M')} - {r_first.end_time.strftime('%H:%M')} hs)" return { 'id': c.id, 'code': c.code, 'building': c.building or 'Sede Central', 'floor': c.floor or '', 'capacity': c.capacity or 0, 'is_virtual': getattr(c, 'is_virtual', False) or 'virtual' in (c.building or '').lower() or 'virtual' in (c.code or '').lower(), 'res_count': len(res_list), 'assigned_summary': assigned_summary } # Helper para serializar comisión con info contextual def build_comm_item(comm, res_list): has_v_link = bool(comm.virtual_link and comm.virtual_link.strip()) r_first = res_list[0] if res_list else None assigned_room = '' assigned_time = '' if r_first: assigned_room = r_first.classroom.code if r_first.classroom else 'Aula Virtual' assigned_time = f"{r_first.start_time.strftime('%H:%M')} - {r_first.end_time.strftime('%H:%M')} hs" return { 'id': comm.id, 'code': comm.code, 'full_code': comm.get_full_code(), 'subject_name': comm.subject.name if comm.subject else 'Sin materia', 'subject_code': comm.subject.code if comm.subject else '', 'teacher_name': comm.teacher_name or 'Sin docente', 'schedule': comm.schedule or 'Sin horario', 'shift': comm.shift or 'Sin turno', 'max_students': comm.max_students or 0, 'current_students': comm.current_students or 0, 'virtual_link': comm.virtual_link or '', 'has_virtual_link': has_v_link, 'res_count': len(res_list), 'assigned_room': assigned_room, 'assigned_time': assigned_time } # Construcción de Aulas Asignadas vs Sin Asignar para cada período (sobre aulas físicas) # 1. Hoy classrooms_assigned_today = [build_classroom_item(c, res_map_classroom_today[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_today] classrooms_unassigned_today = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_today] # 2. Mañana classrooms_assigned_tomorrow = [build_classroom_item(c, res_map_classroom_tomorrow[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_tomorrow] classrooms_unassigned_tomorrow = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_tomorrow] # 3. Semana classrooms_assigned_week = [build_classroom_item(c, res_map_classroom_week[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_week] classrooms_unassigned_week = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_week] # 4. Mes classrooms_assigned_month = [build_classroom_item(c, res_map_classroom_month[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_month] classrooms_unassigned_month = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_month] # Construcción de Comisiones Asignadas vs Sin Asignar para cada período # 1. Hoy commissions_assigned_today = [build_comm_item(comm, res_map_comm_today[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_today] commissions_unassigned_today = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_today] # 2. Mañana commissions_assigned_tomorrow = [build_comm_item(comm, res_map_comm_tomorrow[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_tomorrow] commissions_unassigned_tomorrow = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_tomorrow] # 3. Semana commissions_assigned_week = [build_comm_item(comm, res_map_comm_week[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_week] commissions_unassigned_week = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_week] # 4. Mes commissions_assigned_month = [build_comm_item(comm, res_map_comm_month[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_month] commissions_unassigned_month = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_month] # Identificar comisiones en modalidad virtual (por enlace Meet/Teams/Zoom o asignadas a Campus Virtual) virtual_room_ids = set(c.id for c in virtual_classrooms_list) comm_ids_virtual = set() for comm in all_active_commissions: if comm.virtual_link and comm.virtual_link.strip(): comm_ids_virtual.add(comm.id) if virtual_room_ids: comm_in_virtual_res = set( r[0] for r in db.session.query(Reservation.commission_id).filter( Reservation.classroom_id.in_(virtual_room_ids), Reservation.commission_id.isnot(None) ).distinct().all() ) comm_ids_virtual.update(comm_in_virtual_res) virtual_rooms_data = [] for comm in all_active_commissions: if comm.id in comm_ids_virtual: res_today = res_map_comm_today.get(comm.id, []) res_tomorrow = res_map_comm_tomorrow.get(comm.id, []) res_week = res_map_comm_week.get(comm.id, []) res_month = res_map_comm_month.get(comm.id, []) v_link = comm.virtual_link or (res_today[0].virtual_link if res_today and res_today[0].virtual_link else '') virtual_rooms_data.append({ 'id': comm.id, 'commission_id': comm.id, 'code': comm.code, 'full_code': comm.get_full_code(), 'subject_name': comm.subject.name if comm.subject else 'Sin materia', 'subject_code': comm.subject.code if comm.subject else '', 'career_name': comm.subject.career.name if (comm.subject and comm.subject.career) else 'UniCABA', 'teacher_name': comm.teacher_name or 'Docente a confirmar', 'schedule': comm.schedule or 'Horario regular', 'shift': comm.shift or 'Tarde', 'max_students': comm.max_students or 35, 'capacity': comm.max_students or 35, 'virtual_link': v_link, 'is_virtual': True, 'building': 'Campus Virtual', 'floor': 'Remoto ∞', 'today_classes': len(res_today), 'tomorrow_classes': len(res_tomorrow), 'week_classes': len(res_week), 'month_classes': len(res_month), 'res_count': len(res_month), 'is_active_today': len(res_today) > 0, 'is_active_tomorrow': len(res_tomorrow) > 0, 'assigned_summary': f"{comm.subject.name if comm.subject else 'Clase Virtual'} ({comm.schedule or 'Remoto'})" }) # Las salas virtuales disponibles corresponden a las salas de comisiones virtuales activas o catálogo virtual if virtual_rooms_data: virtual_classrooms = len(virtual_rooms_data) # Comisiones huérfanas generales (sin ninguna reserva histórica ni link virtual) comm_ids_with_any_res = set( r[0] for r in db.session.query(Reservation.commission_id).filter( Reservation.commission_id.isnot(None) ).distinct().all() ) unassigned_commissions_general = [ build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in comm_ids_with_any_res and not (comm.virtual_link and comm.virtual_link.strip()) ] # Compatibilidad hacia atrás para vistas existentes available_classrooms_today = classrooms_unassigned_today available_classrooms_tomorrow = classrooms_unassigned_tomorrow available_classrooms_week = classrooms_unassigned_week available_classrooms_month = classrooms_unassigned_month unassigned_commissions_tomorrow = commissions_unassigned_tomorrow unassigned_commissions_week = commissions_unassigned_week unassigned_commissions_month = commissions_unassigned_month # Diccionario unificado filter_stats filter_stats = { 'date_labels': date_labels, 'today': { 'label': date_labels['today'], 'date_short': date_labels['today_short'], 'date_full': date_labels['today_full'], 'classrooms': { 'assigned': classrooms_assigned_today, 'unassigned': classrooms_unassigned_today, 'assigned_count': len(classrooms_assigned_today), 'unassigned_count': len(classrooms_unassigned_today), 'assigned_pct': round((len(classrooms_assigned_today) / max(1, total_physical_count)) * 100, 1), 'unassigned_pct': round((len(classrooms_unassigned_today) / max(1, total_physical_count)) * 100, 1), 'total': total_physical_count }, 'commissions': { 'assigned': commissions_assigned_today, 'unassigned': commissions_unassigned_today, 'assigned_count': len(commissions_assigned_today), 'unassigned_count': len(commissions_unassigned_today), 'assigned_pct': round((len(commissions_assigned_today) / max(1, total_active_commissions)) * 100, 1), 'unassigned_pct': round((len(commissions_unassigned_today) / max(1, total_active_commissions)) * 100, 1), 'total': total_active_commissions } }, 'tomorrow': { 'label': date_labels['tomorrow'], 'date_short': date_labels['tomorrow_short'], 'date_full': date_labels['tomorrow_full'], 'classrooms': { 'assigned': classrooms_assigned_tomorrow, 'unassigned': classrooms_unassigned_tomorrow, 'assigned_count': len(classrooms_assigned_tomorrow), 'unassigned_count': len(classrooms_unassigned_tomorrow), 'assigned_pct': round((len(classrooms_assigned_tomorrow) / max(1, total_physical_count)) * 100, 1), 'unassigned_pct': round((len(classrooms_unassigned_tomorrow) / max(1, total_physical_count)) * 100, 1), 'total': total_physical_count }, 'commissions': { 'assigned': commissions_assigned_tomorrow, 'unassigned': commissions_unassigned_tomorrow, 'assigned_count': len(commissions_assigned_tomorrow), 'unassigned_count': len(commissions_unassigned_tomorrow), 'assigned_pct': round((len(commissions_assigned_tomorrow) / max(1, total_active_commissions)) * 100, 1), 'unassigned_pct': round((len(commissions_unassigned_tomorrow) / max(1, total_active_commissions)) * 100, 1), 'total': total_active_commissions } }, 'week': { 'label': date_labels['week'], 'date_short': date_labels['week'], 'date_full': date_labels['week_full'], 'classrooms': { 'assigned': classrooms_assigned_week, 'unassigned': classrooms_unassigned_week, 'assigned_count': len(classrooms_assigned_week), 'unassigned_count': len(classrooms_unassigned_week), 'assigned_pct': round((len(classrooms_assigned_week) / max(1, total_physical_count)) * 100, 1), 'unassigned_pct': round((len(classrooms_unassigned_week) / max(1, total_physical_count)) * 100, 1), 'total': total_physical_count }, 'commissions': { 'assigned': commissions_assigned_week, 'unassigned': commissions_unassigned_week, 'assigned_count': len(commissions_assigned_week), 'unassigned_count': len(commissions_unassigned_week), 'assigned_pct': round((len(commissions_assigned_week) / max(1, total_active_commissions)) * 100, 1), 'unassigned_pct': round((len(commissions_unassigned_week) / max(1, total_active_commissions)) * 100, 1), 'total': total_active_commissions } }, 'month': { 'label': date_labels['month'], 'date_short': date_labels['month'], 'date_full': date_labels['month_full'], 'classrooms': { 'assigned': classrooms_assigned_month, 'unassigned': classrooms_unassigned_month, 'assigned_count': len(classrooms_assigned_month), 'unassigned_count': len(classrooms_unassigned_month), 'assigned_pct': round((len(classrooms_assigned_month) / max(1, total_physical_count)) * 100, 1), 'unassigned_pct': round((len(classrooms_unassigned_month) / max(1, total_physical_count)) * 100, 1), 'total': total_physical_count }, 'commissions': { 'assigned': commissions_assigned_month, 'unassigned': commissions_unassigned_month, 'assigned_count': len(commissions_assigned_month), 'unassigned_count': len(commissions_unassigned_month), 'assigned_pct': round((len(commissions_assigned_month) / max(1, total_active_commissions)) * 100, 1), 'unassigned_pct': round((len(commissions_unassigned_month) / max(1, total_active_commissions)) * 100, 1), 'total': total_active_commissions } }, 'virtual_rooms': virtual_rooms_data, 'virtual_rooms_count': len(virtual_rooms_data) } except Exception as e: print(f"Error fetching stats: {e}") total_classrooms = 0 total_subjects = 0 total_users = 0 today_reservations = 0 pending_count = 0 physical_classrooms = 0 virtual_classrooms = 0 occupancy_rate = 0 assigned_classrooms = 0 assigned_pct = 0.0 unassigned_classrooms = 0 unassigned_pct = 0.0 assigned_today_count = 0 assigned_today_pct = 0.0 unassigned_today_count = 0 unassigned_today_pct = 0.0 audit_data = [] pending_reservations = [] today_schedule_list = [] week_schedule_list = [] upcoming_reservations = [] unassigned_commissions_week = [] unassigned_commissions_month = [] unassigned_commissions_general = [] available_classrooms_today = [] available_classrooms_week = [] available_classrooms_month = [] total_active_commissions = 0 milestones = [] # Mocked monthly data for chart since complex SQL group by month might differ based on dialect (SQLite vs Postgres) monthly_data = [ {"month": "Ene", "reservations": 120}, {"month": "Feb", "reservations": 180}, {"month": "Mar", "reservations": 250}, {"month": "Abr", "reservations": 220}, {"month": "May", "reservations": 300}, {"month": "Jun", "reservations": 310}, {"month": "Jul", "reservations": 200}, {"month": "Ago", "reservations": 350}, {"month": "Sep", "reservations": 420}, {"month": "Oct", "reservations": 480}, {"month": "Nov", "reservations": 520}, {"month": "Dic", "reservations": 210} ] return jsonify({ 'status': 'success', 'stats': { 'total_classrooms': total_classrooms, 'active_subjects': total_subjects, 'total_active_users': total_users, 'today_reservations': today_reservations, 'pending_count': pending_count, 'physical_classrooms': physical_classrooms, 'virtual_classrooms': virtual_classrooms, 'occupancy_rate': occupancy_rate, 'assigned_classrooms': assigned_classrooms, 'assigned_classrooms_pct': assigned_pct, 'unassigned_classrooms': unassigned_classrooms, 'unassigned_classrooms_pct': unassigned_pct, 'assigned_today_classrooms': assigned_today_count, 'assigned_today_pct': assigned_today_pct, 'unassigned_today_classrooms': unassigned_today_count, 'unassigned_today_pct': unassigned_today_pct, 'total_active_commissions': total_active_commissions, 'tomorrow_reservations': len(tomorrow_reservations_q) if 'tomorrow_reservations_q' in locals() else 0, 'my_today_count': my_today_count, 'my_total_reservations': my_total_reservations, 'virtual_rooms_count': virtual_classrooms }, 'audit_logs': audit_data, 'monthly_data': monthly_data, 'pending_reservations': pending_reservations, 'today_schedule_list': today_schedule_list, 'my_today_classes': my_today_classes, 'tomorrow_schedule_list': tomorrow_schedule_list if 'tomorrow_schedule_list' in locals() else [], 'week_schedule_list': week_schedule_list, 'upcoming_reservations': upcoming_reservations, 'milestones': milestones, 'filter_stats': filter_stats if 'filter_stats' in locals() else {}, 'date_labels': date_labels if 'date_labels' in locals() else {}, 'ui': { 'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True] }, 'bedelia': { 'unassigned_commissions_tomorrow': unassigned_commissions_tomorrow if 'unassigned_commissions_tomorrow' in locals() else [], 'unassigned_commissions_week': unassigned_commissions_week, 'unassigned_commissions_month': unassigned_commissions_month, 'unassigned_commissions_general': unassigned_commissions_general, 'available_classrooms_today': available_classrooms_today, 'available_classrooms_tomorrow': available_classrooms_tomorrow if 'available_classrooms_tomorrow' in locals() else [], 'available_classrooms_week': available_classrooms_week, 'available_classrooms_month': available_classrooms_month, 'virtual_rooms': virtual_rooms_data, 'virtual_rooms_count': len(virtual_rooms_data) } }), 200 @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 y entidades.""" from app.services.sheets_importer import GoogleSheetsImporter try: data = request.get_json(silent=True) or {} custom_url = data.get('sheets_url') or data.get('base_url') 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, import_careers=import_careers, import_subjects=import_subjects, import_commissions=import_commissions, import_classrooms=import_classrooms, import_reservations=import_reservations, selected_rows=selected_rows ) user_info = getattr(g, 'current_user', {}) or {} user_email = user_info.get('email') if isinstance(user_info, dict) else getattr(user_info, 'email', None) AuditService.log( action='SHEETS_IMPORT', module='import', user_email=user_email, ip_address=request.remote_addr, details={ 'stats': stats, 'filter_career': filter_career, 'filter_subject': filter_subject, 'filter_day': filter_day, 'filter_days': filter_days, 'single_date_only': single_date_only, 'manual_date': manual_date }, status='success' ) return jsonify({ 'status': 'success', 'stats': stats, 'source_url': importer.base_url }), 200 except Exception as e: user_info = getattr(g, 'current_user', {}) or {} user_email = user_info.get('email') if isinstance(user_info, dict) else getattr(user_info, 'email', None) AuditService.log( action='SHEETS_IMPORT_ERROR', module='import', user_email=user_email, ip_address=request.remote_addr, details={ 'error': str(e), 'filter_career': filter_career, 'filter_subject': filter_subject, 'filter_day': filter_day }, status='failed' ) return jsonify({ 'status': 'error', 'message': str(e) }), 500 @api_dashboard_bp.route('/sheets-inspect', methods=['GET', 'POST']) @jwt_required def inspect_google_sheets(): """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( 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, 'source_url': importer.base_url }), 200 except Exception as e: return jsonify({ 'status': 'error', 'message': str(e) }), 500