diff --git a/CHANGELOG.md b/CHANGELOG.md index 2df36d6..add0a53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,18 @@ 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.8.13] - 2026-10-26 +### Added +- **Métricas y Contadores Rápidos de Usuarios por Rol (`/admin/users_list`)**: + - Incorporadas tarjetas KPI interactivas en la cabecera de la vista de usuarios: Total global de usuarios registrados, Administradores, Bedelía, Docentes y Alumnos matriculados, con estados activos e inactivos. + - Al hacer clic en cualquiera de las tarjetas de rol, se filtra instantáneamente el padrón por dicho rol institucional. + - Añadida barra de paginación superior en la cabecera de la tabla mostrando el rango exacto de usuarios renderizados (`Página X de Y · Mostrando Z de N usuarios`) y controles rápidos de navegación previa y siguiente. +- **Filtro Resiliente por Rol en Backend FastAPI**: + - `get_users` en `/api/v1/admin/users` ahora acepta `role` tanto numérico (ID de rol) como textual (ej. `Docente`, `Alumno`, `Admin`), insensible a mayúsculas, y retorna `role_counts` estructurado con la distribución total institucional. +### Fixed +- **Limpieza de Diagnósticos de Tipos en Pyright**: + - Removidas llamadas redundantes a `str()` sobre parámetros ya tipados como cadenas en `academic.py`, `classrooms.py` y `reservations.py`, asegurando 0 errores y 0 advertencias en el Language Server. + ## [3.8.12] - 2026-10-26 ### Fixed - **Dashboard Layout y Estructura Visual (`frontend/views/dashboard/dashadm.html`)**: diff --git a/MEMORY.md b/MEMORY.md index 7ca7f7f..77a9e4d 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,11 +9,11 @@ Memoria del proyecto entre sesiones para la rama `dev`. - Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables. - Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación. - Reinicialización segura del sistema con contraseña de Administrador. -- **Sprint Activo: Paginación DB, Corrección de Layout de Dashboard y Resiliencia de Asignaturas/Comisiones — v3.8.12**: - - **Corrección de Layout del Dashboard (`dashadm.html`)**: Removidos 3 tags `` extra en el panel de percentiles que provocaban el desbordamiento de la sección de módulos de gestión y la tendencia de ocupación al fondo de la pantalla. - - **Resiliencia en Asignaturas y Comisiones**: Solucionado el error HTTP 422 en FastAPI (`list_subjects` y `list_commissions`) cuando los formularios o peticiones envían strings vacíos en parámetros de filtrado numéricos (`career_id`, `subject_id`). Depurado el BFF en Express para no propagar parámetros vacíos. - - **Paginación Server-Side y Optimización DB (Spec 008)**: Paginación server-side implementada para usuarios, logs de auditoría, asignaturas y comisiones. Endpoint `/api/v1/users/teachers` para listas de selección de docentes. - - **Versión Consolidada**: `v3.8.12`. +- **Sprint Activo: Contadores por Rol y Paginación Reforzada en Usuarios — v3.8.13**: + - **Métricas y Contadores por Rol en Usuarios (`users_list`)**: Tarjetas KPI en cabecera con total global, administradores, bedeles, docentes y alumnos, con filtro rápido al hacer clic. Doble barra de paginación (superior e inferior) con indicador de rango (`Página X de Y · Mostrando Z de N usuarios`). + - **Filtro Resiliente en FastAPI**: `get_users` acepta rol numérico o textual y retorna `role_counts` estructurado. + - **Cero Diagnósticos en Pyright**: Eliminadas llamadas `str()` redundantes en routers FastAPI. + - **Versión Consolidada**: `v3.8.13`. ## Decisiones (y por qué) - **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 57987fa..afd6488 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -7,7 +7,7 @@ from typing import Any from database import db, get_db, engine, SessionLocal, session from config.config import Config -__version__ = "3.8.12" +__version__ = "3.8.13" class DummyContext: def __enter__(self): diff --git a/backend/routers/academic.py b/backend/routers/academic.py index e50963f..030ea4c 100644 --- a/backend/routers/academic.py +++ b/backend/routers/academic.py @@ -161,7 +161,7 @@ def list_subjects( Subject.careers.any(Career.name.ilike(f'%{s_clean}%')) ) ) - parsed_career_id = int(career_id.strip()) if career_id and str(career_id).strip().isdigit() else None + parsed_career_id = int(career_id.strip()) if career_id and career_id.strip().isdigit() else None if parsed_career_id: query = query.filter(or_(Subject.career_id == parsed_career_id, Subject.careers.any(Career.id == parsed_career_id))) if active == 'true': @@ -428,8 +428,8 @@ def list_commissions( Subject.code.ilike(f'%{s_clean}%') ) ) - parsed_subject_id = int(subject_id.strip()) if subject_id and str(subject_id).strip().isdigit() else None - parsed_career_id = int(career_id.strip()) if career_id and str(career_id).strip().isdigit() else None + parsed_subject_id = int(subject_id.strip()) if subject_id and subject_id.strip().isdigit() else None + parsed_career_id = int(career_id.strip()) if career_id and career_id.strip().isdigit() else None if parsed_subject_id: query = query.filter(Commission.subject_id == parsed_subject_id) if parsed_career_id: diff --git a/backend/routers/admin.py b/backend/routers/admin.py index 9306463..0758f9a 100644 --- a/backend/routers/admin.py +++ b/backend/routers/admin.py @@ -32,7 +32,7 @@ admin_router = APIRouter(prefix="/api/v1", tags=["Administration & Settings"]) @admin_router.get("/admin/users") def get_users( search: Optional[str] = Query(None), - role_id: Optional[int] = Query(None, alias="role"), + role_filter: Optional[str] = Query(None, alias="role"), status_filter: Optional[str] = Query(None, alias="status"), page: int = Query(1, ge=1), per_page: int = Query(25, ge=1, le=200), @@ -53,8 +53,15 @@ def get_users( User.last_name.ilike(f'%{s_clean}%') ) ) - if role_id: - query = query.filter(User.role_id == role_id) + if role_filter and role_filter.strip(): + rf = role_filter.strip() + if rf.isdigit(): + rid = int(rf) + query = query.filter(or_(User.role_id == rid, User.role == rf)) + else: + rf_lower = rf.lower() + query = query.filter(or_(func.lower(User.role) == rf_lower, User.role.ilike(f'%{rf}%'))) + if status_filter == 'active': query = query.filter(User.is_active == True) elif status_filter == 'inactive': @@ -64,6 +71,37 @@ def get_users( roles = Role.query.order_by(Role.name.asc()).all() roles_data = [{'id': r.id, 'name': r.name} for r in roles] + # Métricas agregadas de usuarios para contadores en la vista + total_users_count = db.session.query(func.count(User.id)).scalar() or 0 + active_users_count = db.session.query(func.count(User.id)).filter(User.is_active == True).scalar() or 0 + inactive_users_count = db.session.query(func.count(User.id)).filter(User.is_active == False).scalar() or 0 + + admin_count = db.session.query(func.count(User.id)).filter( + or_(User.role_id == 1, func.lower(User.role) == 'admin') + ).scalar() or 0 + + bedelia_count = db.session.query(func.count(User.id)).filter( + or_(User.role_id == 7, func.lower(User.role) == 'bedelia') + ).scalar() or 0 + + docente_count = db.session.query(func.count(User.id)).filter( + or_(User.role_id == 2, func.lower(User.role).in_(['docente', 'profesor'])) + ).scalar() or 0 + + alumno_count = db.session.query(func.count(User.id)).filter( + or_(User.role_id == 6, func.lower(User.role).in_(['alumno', 'estudiante'])) + ).scalar() or 0 + + role_counts = { + 'total': total_users_count, + 'active': active_users_count, + 'inactive': inactive_users_count, + 'admin': admin_count, + 'bedelia': bedelia_count, + 'docente': docente_count, + 'alumno': alumno_count + } + if all_records: users = query.order_by(User.id.asc()).limit(1000).all() pages = 1 @@ -92,7 +130,8 @@ def get_users( 'has_next': page < pages, 'users': users_data, 'roles': roles_data, - 'document_types': DOCUMENT_TYPES + 'document_types': DOCUMENT_TYPES, + 'role_counts': role_counts } diff --git a/backend/routers/classrooms.py b/backend/routers/classrooms.py index 30d1b55..6c65f25 100644 --- a/backend/routers/classrooms.py +++ b/backend/routers/classrooms.py @@ -31,7 +31,7 @@ def list_classrooms( mode_str = (mode or '').lower() only_virtual = mode_str == 'virtual' only_physical = mode_str == 'physical' - parsed_building_id = int(building_id.strip()) if building_id and str(building_id).strip().isdigit() else None + parsed_building_id = int(building_id.strip()) if building_id and building_id.strip().isdigit() else None classrooms = classroom_service.list_classrooms( building_id=parsed_building_id, diff --git a/backend/routers/reservations.py b/backend/routers/reservations.py index 86b2e3b..e9d0bb6 100644 --- a/backend/routers/reservations.py +++ b/backend/routers/reservations.py @@ -45,7 +45,7 @@ def list_reservations( raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de end_date (debe ser YYYY-MM-DD).") is_hide_virtual = str(hide_virtual).lower() in ['1', 'true'] - parsed_classroom_id = int(classroom_id.strip()) if classroom_id and str(classroom_id).strip().isdigit() else None + parsed_classroom_id = int(classroom_id.strip()) if classroom_id and classroom_id.strip().isdigit() else None reservations = reservation_service.list_reservations( start_dt, end_dt, diff --git a/backend/setup.py b/backend/setup.py index 56ed1d3..20892ea 100644 --- a/backend/setup.py +++ b/backend/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name="edu-space-admin", - version="3.8.12", + version="3.8.13", description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)", author="Edu-Space Development Team", author_email="admin@edu-space.com", diff --git a/backend/tests/test_pagination_db.py b/backend/tests/test_pagination_db.py index 939a1cf..61c673d 100644 --- a/backend/tests/test_pagination_db.py +++ b/backend/tests/test_pagination_db.py @@ -61,6 +61,12 @@ def test_users_pagination_defaults(test_admin_headers, init_database): assert data["pages"] >= 2 assert data["has_next"] is True assert data["has_prev"] is False + assert "role_counts" in data + assert data["role_counts"]["total"] >= 30 + assert "admin" in data["role_counts"] + assert "docente" in data["role_counts"] + assert "alumno" in data["role_counts"] + assert "bedelia" in data["role_counts"] # 2. Segunda página res2 = client.get("/api/v1/users?page=2&per_page=10", headers=test_admin_headers) diff --git a/frontend/package.json b/frontend/package.json index 7b85367..f31e8aa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.8.12", + "version": "3.8.13", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/src/app.js b/frontend/src/app.js index 611b2e4..687f0ff 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), { }); // Versiones institucionales del sistema -const APP_VERSION = '3.8.12'; -const FRONTEND_VERSION = '3.8.12'; -const BACKEND_VERSION = '3.8.12'; +const APP_VERSION = '3.8.13'; +const FRONTEND_VERSION = '3.8.13'; +const BACKEND_VERSION = '3.8.13'; env.addGlobal('app_version', APP_VERSION); env.addGlobal('frontend_version', FRONTEND_VERSION); diff --git a/frontend/src/routes/admin.js b/frontend/src/routes/admin.js index be60acc..0aa8e89 100644 --- a/frontend/src/routes/admin.js +++ b/frontend/src/routes/admin.js @@ -436,6 +436,15 @@ const handleUsersList = async (req, res) => { let roles = [...MOCK_ROLES]; let document_types = []; let total = 0; + let role_counts = { + total: 0, + active: 0, + inactive: 0, + admin: 0, + bedelia: 0, + docente: 0, + alumno: 0 + }; try { const resp = await req.apiClient.get('/admin/users', { @@ -452,6 +461,9 @@ const handleUsersList = async (req, res) => { roles = resp.data.roles || roles; document_types = resp.data.document_types || []; total = resp.data.total !== undefined ? resp.data.total : users.length; + if (resp.data.role_counts) { + role_counts = resp.data.role_counts; + } } } catch (apiErr) { console.warn('Users list API notice:', apiErr.message); @@ -468,6 +480,7 @@ const handleUsersList = async (req, res) => { role_filter, status_filter, pagination, + role_counts, msg, error }); diff --git a/frontend/views/admin/users/list.html b/frontend/views/admin/users/list.html index 5448581..7f5934f 100644 --- a/frontend/views/admin/users/list.html +++ b/frontend/views/admin/users/list.html @@ -39,6 +39,121 @@ {% endif %} + +