feat(dashboard): add day week month filtering for assigned and unassigned classrooms and commissions with clear dates

This commit is contained in:
2026-10-07 19:39:34 -03:00
parent b6d7d8842e
commit c834fcdbc6
3 changed files with 937 additions and 330 deletions
+225 -85
View File
@@ -150,119 +150,238 @@ def get_stats():
upcoming_reservations = [serialize_reservation(r) for r in upcoming_reservations_q]
milestones = [serialize_milestone(m) for m in milestones_q]
# ---- Bedelía: Comisiones sin aula asignada (semana, mes y general) ----
# ---- Bedelía: Filtros completos de Aulas y Comisiones por Día, Semana y Mes ----
import calendar
# Calcular rango de semana actual (lunes a domingo)
today_dt = datetime.utcnow()
week_start = today_dt - timedelta(days=today_dt.weekday()) # lunes
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)
# Reservas de la semana actual completa para Bedelía
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]
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}",
'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
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]
# Calcular rango del mes actual
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)
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_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_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)
# Comisiones activas totales
all_active_commissions = Commission.query.filter_by(active=True).all()
total_active_commissions = len(all_active_commissions)
# IDs de comisiones que SÍ tienen reserva en la semana
comm_ids_with_res_week = set(
r[0] for r in db.session.query(Reservation.commission_id).filter(
Reservation.commission_id.isnot(None),
Reservation.start_time >= week_start,
Reservation.start_time <= week_end
).distinct().all()
)
# IDs de comisiones que SÍ tienen reserva en el mes
comm_ids_with_res_month = set(
r[0] for r in db.session.query(Reservation.commission_id).filter(
Reservation.commission_id.isnot(None),
Reservation.start_time >= month_start,
Reservation.start_time <= month_end
).distinct().all()
)
# IDs de comisiones que tienen AL MENOS una reserva en general
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()
)
# 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
}
unassigned_commissions_week = []
unassigned_commissions_month = []
unassigned_commissions_general = []
for comm in all_active_commissions:
# 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())
comm_data = {
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,
'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,
'current_students': comm.current_students,
'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
'has_virtual_link': has_v_link,
'res_count': len(res_list),
'assigned_room': assigned_room,
'assigned_time': assigned_time
}
if comm.id not in comm_ids_with_res_week:
unassigned_commissions_week.append(comm_data)
if comm.id not in comm_ids_with_res_month:
unassigned_commissions_month.append(comm_data)
if comm.id not in comm_ids_with_any_res and not has_v_link:
unassigned_commissions_general.append(comm_data)
# ---- Bedelía: Aulas disponibles (sin reservas) hoy, semana y mes ----
classroom_ids_used_today = 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()
)
classroom_ids_used_week = set(
r[0] for r in db.session.query(Reservation.classroom_id).filter(
Reservation.classroom_id.isnot(None),
Reservation.start_time >= week_start,
Reservation.start_time <= week_end
).distinct().all()
)
classroom_ids_used_month = set(
r[0] for r in db.session.query(Reservation.classroom_id).filter(
Reservation.classroom_id.isnot(None),
Reservation.start_time >= month_start,
Reservation.start_time <= month_end
).distinct().all()
)
# 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. 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]
# 3. 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]
available_classrooms_today = []
available_classrooms_week = []
available_classrooms_month = []
for c in all_active_classrooms:
c_data = {
'id': c.id,
'code': c.code,
'building': c.building or 'Sin edificio',
'floor': c.floor or '',
'capacity': c.capacity,
'is_virtual': getattr(c, 'is_virtual', False) or 'virtual' in (c.building or '').lower() or 'virtual' in (c.code or '').lower()
# 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. 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]
# 3. 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]
# 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_week = classrooms_unassigned_week
available_classrooms_month = classrooms_unassigned_month
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
}
},
'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
}
}
}
if c.id not in classroom_ids_used_today:
available_classrooms_today.append(c_data)
if c.id not in classroom_ids_used_week:
available_classrooms_week.append(c_data)
if c.id not in classroom_ids_used_month:
available_classrooms_month.append(c_data)
except Exception as e:
print(f"Error fetching stats: {e}")
@@ -295,6 +414,21 @@ 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 = [
@@ -331,7 +465,9 @@ 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
'total_active_commissions': total_active_commissions,
'date_labels': date_labels,
'filter_stats': filter_stats
},
'audit_logs': audit_data,
'monthly_data': monthly_data,
@@ -340,10 +476,14 @@ 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,
+23 -2
View File
@@ -71,6 +71,19 @@ router.get('/', async (req, res) => {
// Bedelía-specific data
const bedeliaData = apiData.bedelia || {};
// Filter stats (today, week, month) & date labels for classrooms and commissions
const filter_stats = apiData.filter_stats || backendStats.filter_stats || bedeliaData.filter_stats || {
date_labels: {
today: 'Hoy',
week: 'Esta Semana',
month: 'Este Mes'
},
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 } }
};
const date_labels = apiData.date_labels || backendStats.date_labels || filter_stats.date_labels || {};
// Consolidated and role-specific stats
const stats = {
total_classrooms,
@@ -93,13 +106,17 @@ router.get('/', async (req, res) => {
my_total_reservations: 8,
virtual_rooms_count: virtual_classrooms_count,
today_classes_count: apiTodaySchedule ? Math.min(4, apiTodaySchedule.length) : 2,
milestones_count: apiMilestones ? apiMilestones.length : 3
milestones_count: apiMilestones ? apiMilestones.length : 3,
filter_stats,
date_labels
};
let role_data = {};
if (role === 'admin') {
role_data = {
filter_stats,
date_labels,
recent_audits: audit_logs.length > 0 ? audit_logs : [
{ created_at: '2026-09-18 21:15', action_type: 'UPDATE_PERMISSION', user_email: 'admin@edu-space.com', ip_address: '127.0.0.1' },
{ created_at: '2026-09-18 20:30', action_type: 'CREATE_COMMISSION', user_email: 'admin@edu-space.com', ip_address: '127.0.0.1' },
@@ -109,6 +126,8 @@ router.get('/', async (req, res) => {
} else if (role === 'bedelia') {
const apiWeekSchedule = Array.isArray(apiData.week_schedule_list) ? apiData.week_schedule_list : [];
role_data = {
filter_stats,
date_labels,
pending_reservations: apiPending || [],
today_schedule_list: apiTodaySchedule || [],
week_schedule_list: apiWeekSchedule,
@@ -173,7 +192,9 @@ router.get('/', async (req, res) => {
role_data,
monthly_data,
audit_logs,
upcoming_reservations
upcoming_reservations,
filter_stats,
date_labels
});
});
File diff suppressed because it is too large Load Diff