fix: corregir layout de dashboard, resiliencia en filtros de asignaturas y paginacion de bd (v3.8.12)
This commit is contained in:
@@ -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.11"
|
||||
__version__ = "3.8.12"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -15,12 +15,12 @@ class User(db.Model):
|
||||
password_hash = db.Column(db.String(255), nullable=False)
|
||||
name = db.Column(db.String(100), nullable=False)
|
||||
role = db.Column(db.String(50), nullable=False)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False, index=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
last_login = db.Column(db.DateTime)
|
||||
preferred_language = db.Column(db.String(10), default=None, nullable=True)
|
||||
theme_preference = db.Column(db.String(10), default='auto', nullable=False)
|
||||
role_id = db.Column(db.Integer, db.ForeignKey('roles.id', ondelete='SET NULL'), nullable=True)
|
||||
role_id = db.Column(db.Integer, db.ForeignKey('roles.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
# Extended personal, contact and identity document fields
|
||||
first_name = db.Column(db.String(100), nullable=True)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from typing import Optional, List
|
||||
from datetime import datetime, date, time
|
||||
from sqlalchemy.orm import joinedload
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy import and_, or_, func, not_
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.user import User
|
||||
from app.repositories.base_repository import BaseRepository
|
||||
from app import db
|
||||
|
||||
@@ -31,8 +33,13 @@ class ReservationRepository(BaseRepository[Reservation]):
|
||||
return query.all()
|
||||
|
||||
def get_by_date_range(self, start_dt: datetime, end_dt: datetime,
|
||||
classroom_id: Optional[int] = None) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de una ventana temporal con carga ansiosa de relaciones."""
|
||||
classroom_id: Optional[int] = None,
|
||||
is_hide_virtual: bool = False,
|
||||
floor: Optional[str] = None,
|
||||
shift: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
limit: int = 1000) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de una ventana temporal con carga ansiosa y filtros en SQL."""
|
||||
query = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission),
|
||||
@@ -46,7 +53,38 @@ class ReservationRepository(BaseRepository[Reservation]):
|
||||
if classroom_id:
|
||||
query = query.filter(Reservation.classroom_id == classroom_id)
|
||||
|
||||
return query.order_by(Reservation.start_time.asc()).all()
|
||||
if is_hide_virtual:
|
||||
query = query.outerjoin(Classroom, Reservation.classroom_id == Classroom.id).filter(
|
||||
or_(
|
||||
Classroom.id.is_(None),
|
||||
and_(
|
||||
not_(Classroom.code.ilike('%VIRTUAL%')),
|
||||
not_(Classroom.building.ilike('%VIRTUAL%'))
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if floor:
|
||||
query = query.join(Classroom, Reservation.classroom_id == Classroom.id).filter(
|
||||
func.lower(Classroom.floor) == floor.strip().lower()
|
||||
)
|
||||
|
||||
if shift:
|
||||
query = query.filter(Reservation.shift.ilike(f'%{shift.strip()}%'))
|
||||
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
query = query.outerjoin(Classroom, Reservation.classroom_id == Classroom.id)\
|
||||
.outerjoin(User, Reservation.user_id == User.id)\
|
||||
.filter(
|
||||
or_(
|
||||
Reservation.purpose.ilike(f'%{s_clean}%'),
|
||||
Classroom.code.ilike(f'%{s_clean}%'),
|
||||
User.name.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
|
||||
return query.order_by(Reservation.start_time.asc()).limit(limit).all()
|
||||
|
||||
def get_by_teacher(self, teacher_id: int) -> List[Reservation]:
|
||||
"""Obtiene reservas asignadas a un docente."""
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Optional, List, Dict, Any
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
import json
|
||||
from sqlalchemy import or_
|
||||
from app import db
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.models.user import User
|
||||
@@ -94,7 +95,42 @@ class AuditService:
|
||||
|
||||
return query.order_by(AuditLog.created_at.desc()).limit(limit).all()
|
||||
|
||||
@staticmethod
|
||||
def get_paginated_logs(
|
||||
module: Optional[str] = None,
|
||||
action: Optional[str] = None,
|
||||
user_id: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
page: int = 1,
|
||||
per_page: int = 25
|
||||
) -> Tuple[List[AuditLog], int]:
|
||||
"""Recupera eventos de auditoría con filtros SQL, búsqueda y paginación server-side."""
|
||||
query = AuditLog.query
|
||||
|
||||
if module:
|
||||
query = query.filter(AuditLog.module == module)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action)
|
||||
if user_id:
|
||||
query = query.filter(AuditLog.user_id == user_id)
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.details.ilike(f'%{s_clean}%'),
|
||||
AuditLog.user_email.ilike(f'%{s_clean}%'),
|
||||
AuditLog.action.ilike(f'%{s_clean}%'),
|
||||
AuditLog.module.ilike(f'%{s_clean}%'),
|
||||
AuditLog.ip_address.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
logs = query.order_by(AuditLog.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all()
|
||||
return logs, total
|
||||
|
||||
@staticmethod
|
||||
def get_recent_logs(limit: int = 50, module: Optional[str] = None,
|
||||
action: Optional[str] = None) -> List[AuditLog]:
|
||||
return AuditService.get_logs(module=module, action=action, limit=limit)
|
||||
|
||||
|
||||
@@ -21,9 +21,22 @@ class ReservationService:
|
||||
return self.reservation_repo.get_by_id(reservation_id)
|
||||
|
||||
def list_reservations(self, start_dt: datetime, end_dt: datetime,
|
||||
classroom_id: Optional[int] = None) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de un rango temporal."""
|
||||
return self.reservation_repo.get_by_date_range(start_dt, end_dt, classroom_id=classroom_id)
|
||||
classroom_id: Optional[int] = None,
|
||||
is_hide_virtual: bool = False,
|
||||
floor: Optional[str] = None,
|
||||
shift: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
limit: int = 1000) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de un rango temporal con filtros SQL."""
|
||||
return self.reservation_repo.get_by_date_range(
|
||||
start_dt, end_dt,
|
||||
classroom_id=classroom_id,
|
||||
is_hide_virtual=is_hide_virtual,
|
||||
floor=floor,
|
||||
shift=shift,
|
||||
search=search,
|
||||
limit=limit
|
||||
)
|
||||
|
||||
def check_conflicts(self, classroom_id: int, start_time: datetime, end_time: datetime,
|
||||
exclude_id: Optional[int] = None) -> List[Reservation]:
|
||||
|
||||
+80
-19
@@ -6,6 +6,7 @@ from typing import Optional, List, Dict, Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
from sqlalchemy import func, or_
|
||||
from datetime import datetime, timezone
|
||||
import math
|
||||
|
||||
from app import db
|
||||
from app.models.career import Career
|
||||
@@ -142,13 +143,15 @@ def delete_career(
|
||||
@academic_router.get("/subjects")
|
||||
def list_subjects(
|
||||
search: Optional[str] = Query(None),
|
||||
career_id: Optional[int] = Query(None),
|
||||
career_id: Optional[str] = Query(None),
|
||||
active: Optional[str] = Query(None),
|
||||
page: Optional[int] = Query(None, ge=1),
|
||||
per_page: Optional[int] = Query(None, ge=1, le=200),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista las asignaturas con filtros opcionales de búsqueda, carrera y estado."""
|
||||
"""Lista las asignaturas con filtros opcionales de búsqueda, carrera, estado y paginación."""
|
||||
query = Subject.query
|
||||
if search:
|
||||
if search and search.strip():
|
||||
s_clean = search.strip().lower()
|
||||
query = query.filter(
|
||||
or_(
|
||||
@@ -158,16 +161,30 @@ def list_subjects(
|
||||
Subject.careers.any(Career.name.ilike(f'%{s_clean}%'))
|
||||
)
|
||||
)
|
||||
if career_id:
|
||||
query = query.filter(or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id)))
|
||||
parsed_career_id = int(career_id.strip()) if career_id and str(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':
|
||||
query = query.filter(Subject.is_active == True)
|
||||
elif active == 'false':
|
||||
query = query.filter(Subject.is_active == False)
|
||||
|
||||
subjects = query.order_by(Subject.id.asc()).all()
|
||||
total = query.count()
|
||||
careers = Career.query.order_by(Career.name.asc()).all()
|
||||
|
||||
if page and per_page:
|
||||
pages = math.ceil(total / per_page) if total > 0 else 1
|
||||
subjects = query.order_by(Subject.id.asc()).offset((page - 1) * per_page).limit(per_page).all()
|
||||
has_prev = page > 1
|
||||
has_next = page < pages
|
||||
else:
|
||||
pages = 1
|
||||
page = 1
|
||||
per_page = total or 1
|
||||
has_prev = False
|
||||
has_next = False
|
||||
subjects = query.order_by(Subject.id.asc()).all()
|
||||
|
||||
subjects_data = []
|
||||
for s in subjects:
|
||||
d = s.to_dict()
|
||||
@@ -184,7 +201,12 @@ def list_subjects(
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': len(subjects_data),
|
||||
'total': total,
|
||||
'page': page,
|
||||
'per_page': per_page,
|
||||
'pages': pages,
|
||||
'has_prev': has_prev,
|
||||
'has_next': has_next,
|
||||
'subjects': subjects_data,
|
||||
'careers': [c.to_dict() for c in careers]
|
||||
}
|
||||
@@ -382,31 +404,70 @@ def delete_subject(
|
||||
|
||||
@academic_router.get("/commissions")
|
||||
def list_commissions(
|
||||
subject_id: Optional[int] = Query(None),
|
||||
career_id: Optional[int] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
subject_id: Optional[str] = Query(None),
|
||||
career_id: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
active: Optional[str] = Query(None),
|
||||
page: Optional[int] = Query(None, ge=1),
|
||||
per_page: Optional[int] = Query(None, ge=1, le=200),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista las comisiones académicas con soporte para filtros de carrera, materia y turno."""
|
||||
"""Lista las comisiones académicas con soporte para filtros de búsqueda, carrera, materia, turno y paginación."""
|
||||
query = Commission.query
|
||||
if subject_id:
|
||||
query = query.filter(Commission.subject_id == subject_id)
|
||||
if career_id:
|
||||
query = query.join(Subject, Commission.subject_id == Subject.id).filter(
|
||||
or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id))
|
||||
joined_subject = False
|
||||
if search and search.strip():
|
||||
s_clean = search.strip().lower()
|
||||
query = query.outerjoin(Subject, Commission.subject_id == Subject.id)
|
||||
joined_subject = True
|
||||
query = query.filter(
|
||||
or_(
|
||||
Commission.code.ilike(f'%{s_clean}%'),
|
||||
Commission.schedule.ilike(f'%{s_clean}%'),
|
||||
Subject.name.ilike(f'%{s_clean}%'),
|
||||
Subject.code.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
if shift:
|
||||
query = query.filter(Commission.shift == shift)
|
||||
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
|
||||
if parsed_subject_id:
|
||||
query = query.filter(Commission.subject_id == parsed_subject_id)
|
||||
if parsed_career_id:
|
||||
if not joined_subject:
|
||||
query = query.join(Subject, Commission.subject_id == Subject.id)
|
||||
joined_subject = True
|
||||
query = query.filter(
|
||||
or_(Subject.career_id == parsed_career_id, Subject.careers.any(Career.id == parsed_career_id))
|
||||
)
|
||||
if shift and shift.strip():
|
||||
query = query.filter(Commission.shift == shift.strip())
|
||||
if active == 'true':
|
||||
query = query.filter(Commission.active == True)
|
||||
elif active == 'false':
|
||||
query = query.filter(Commission.active == False)
|
||||
|
||||
commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).all()
|
||||
total = query.count()
|
||||
if page and per_page:
|
||||
pages = math.ceil(total / per_page) if total > 0 else 1
|
||||
commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).offset((page - 1) * per_page).limit(per_page).all()
|
||||
has_prev = page > 1
|
||||
has_next = page < pages
|
||||
else:
|
||||
pages = 1
|
||||
page = 1
|
||||
per_page = total or 1
|
||||
has_prev = False
|
||||
has_next = False
|
||||
commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).all()
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': len(commissions),
|
||||
'total': total,
|
||||
'page': page,
|
||||
'per_page': per_page,
|
||||
'pages': pages,
|
||||
'has_prev': has_prev,
|
||||
'has_next': has_next,
|
||||
'commissions': [c.to_dict() for c in commissions]
|
||||
}
|
||||
|
||||
|
||||
+88
-12
@@ -7,6 +7,7 @@ from typing import Optional, List, Dict, Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
from sqlalchemy import func, or_
|
||||
from datetime import datetime, timezone
|
||||
import math
|
||||
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
@@ -33,9 +34,12 @@ def get_users(
|
||||
search: Optional[str] = Query(None),
|
||||
role_id: Optional[int] = 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),
|
||||
all_records: bool = Query(False, alias="all"),
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""Lista usuarios del sistema con filtros de búsqueda y rol."""
|
||||
"""Lista usuarios del sistema con filtros de búsqueda, rol y paginación server-side."""
|
||||
query = User.query
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
@@ -56,8 +60,18 @@ def get_users(
|
||||
elif status_filter == 'inactive':
|
||||
query = query.filter(User.is_active == False)
|
||||
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
total = query.count()
|
||||
roles = Role.query.order_by(Role.name.asc()).all()
|
||||
roles_data = [{'id': r.id, 'name': r.name} for r in roles]
|
||||
|
||||
if all_records:
|
||||
users = query.order_by(User.id.asc()).limit(1000).all()
|
||||
pages = 1
|
||||
page = 1
|
||||
per_page = total or 1
|
||||
else:
|
||||
pages = math.ceil(total / per_page) if total > 0 else 1
|
||||
users = query.order_by(User.id.asc()).offset((page - 1) * per_page).limit(per_page).all()
|
||||
|
||||
users_data = []
|
||||
for u in users:
|
||||
@@ -68,17 +82,63 @@ def get_users(
|
||||
} if u.role_obj else {'id': 1, 'name': u.role or 'Admin'}
|
||||
users_data.append(d)
|
||||
|
||||
roles_data = [{'id': r.id, 'name': r.name} for r in roles]
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': len(users_data),
|
||||
'total': total,
|
||||
'page': page,
|
||||
'per_page': per_page,
|
||||
'pages': pages,
|
||||
'has_prev': page > 1,
|
||||
'has_next': page < pages,
|
||||
'users': users_data,
|
||||
'roles': roles_data,
|
||||
'document_types': DOCUMENT_TYPES
|
||||
}
|
||||
|
||||
|
||||
@admin_router.get("/users/teachers")
|
||||
@admin_router.get("/admin/users/teachers")
|
||||
def get_teachers(
|
||||
search: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Retorna una lista ligera de docentes activos para selectores y comisiones."""
|
||||
query = User.query.filter(User.is_active == True)
|
||||
query = query.filter(
|
||||
or_(
|
||||
User.role.ilike('%docent%'),
|
||||
User.role.ilike('%prof%'),
|
||||
User.role.ilike('%bedel%'),
|
||||
User.role.ilike('%admin%')
|
||||
)
|
||||
)
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
query = query.filter(
|
||||
or_(
|
||||
User.name.ilike(f'%{s_clean}%'),
|
||||
User.email.ilike(f'%{s_clean}%'),
|
||||
User.document_number.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
teachers = query.order_by(User.name.asc()).all()
|
||||
teachers_data = [
|
||||
{
|
||||
'id': t.id,
|
||||
'name': t.name,
|
||||
'email': t.email,
|
||||
'document_number': t.document_number,
|
||||
'role': t.role
|
||||
}
|
||||
for t in teachers
|
||||
]
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': len(teachers_data),
|
||||
'teachers': teachers_data
|
||||
}
|
||||
|
||||
|
||||
@admin_router.post("/users", status_code=status.HTTP_201_CREATED)
|
||||
@admin_router.post("/admin/users", status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(
|
||||
@@ -601,25 +661,41 @@ def get_audit_logs(
|
||||
module: Optional[str] = Query(None),
|
||||
action: Optional[str] = Query(None),
|
||||
user_id: Optional[int] = Query(None),
|
||||
limit: int = Query(50),
|
||||
search: Optional[str] = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
per_page: int = Query(25, ge=1, le=100),
|
||||
limit: Optional[int] = Query(None),
|
||||
current_user: User = Depends(require_roles(["ADMIN"]))
|
||||
):
|
||||
"""Consulta la bitácora inmutable de auditoría del sistema."""
|
||||
logs = AuditService.get_logs(module=module, action=action, user_id=user_id, limit=limit)
|
||||
"""Consulta la bitácora inmutable de auditoría del sistema con paginación server-side."""
|
||||
actual_per_page = limit if (limit and not per_page) else per_page
|
||||
logs, total = AuditService.get_paginated_logs(
|
||||
module=module,
|
||||
action=action,
|
||||
user_id=user_id,
|
||||
search=search,
|
||||
page=page,
|
||||
per_page=actual_per_page
|
||||
)
|
||||
pages = math.ceil(total / actual_per_page) if total > 0 else 1
|
||||
|
||||
distinct_modules = [m[0] for m in db.session.query(AuditLog.module).distinct().all() if m[0]]
|
||||
distinct_actions = [a[0] for a in db.session.query(AuditLog.action).distinct().all() if a[0]]
|
||||
all_modules = sorted(list(set(distinct_modules + ['auth', 'admin', 'reservations', 'classrooms', 'buildings', 'academic', 'moodle'])))
|
||||
all_actions = sorted(list(set(distinct_actions + ['LOGIN', 'LOGIN_FAILED', 'LOGOUT', 'CREATE', 'UPDATE', 'DELETE', 'IMPERSONATE_START', 'IMPERSONATE_END'])))
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': len(logs),
|
||||
'total': total,
|
||||
'logs': [log.to_dict() for log in logs],
|
||||
'modules': all_modules,
|
||||
'actions': all_actions,
|
||||
'pagination': {
|
||||
'page': 1,
|
||||
'per_page': limit,
|
||||
'total': len(logs)
|
||||
'page': page,
|
||||
'per_page': actual_per_page,
|
||||
'total': total,
|
||||
'pages': pages,
|
||||
'has_prev': page > 1,
|
||||
'has_next': page < pages
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ dashboard_service = DashboardService()
|
||||
|
||||
@classrooms_router.get("")
|
||||
def list_classrooms(
|
||||
building_id: Optional[int] = Query(None),
|
||||
building_id: Optional[str] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
mode: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
@@ -31,9 +31,10 @@ 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
|
||||
|
||||
classrooms = classroom_service.list_classrooms(
|
||||
building_id=building_id,
|
||||
building_id=parsed_building_id,
|
||||
floor=floor,
|
||||
only_virtual=only_virtual,
|
||||
only_physical=only_physical
|
||||
|
||||
@@ -24,14 +24,15 @@ reservation_service = ReservationService()
|
||||
def list_reservations(
|
||||
start_date: Optional[str] = Query(None),
|
||||
end_date: Optional[str] = Query(None),
|
||||
classroom_id: Optional[int] = Query(None),
|
||||
classroom_id: Optional[str] = Query(None),
|
||||
hide_virtual: Optional[str] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
limit: int = Query(1000, le=5000),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Consulta de reservas por rango de fechas y/o aula."""
|
||||
"""Consulta de reservas por rango de fechas y/o aula con filtros en SQL."""
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
try:
|
||||
start_dt = datetime.strptime(start_date, '%Y-%m-%d') if start_date else now.replace(hour=0, minute=0, second=0)
|
||||
@@ -44,27 +45,22 @@ 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
|
||||
|
||||
reservations = reservation_service.list_reservations(start_dt, end_dt, classroom_id=classroom_id)
|
||||
reservations = reservation_service.list_reservations(
|
||||
start_dt, end_dt,
|
||||
classroom_id=parsed_classroom_id,
|
||||
is_hide_virtual=is_hide_virtual,
|
||||
floor=floor,
|
||||
shift=shift,
|
||||
search=search,
|
||||
limit=limit
|
||||
)
|
||||
result = []
|
||||
for r in reservations:
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
if is_hide_virtual and is_virt:
|
||||
continue
|
||||
if floor and r.classroom and str(r.classroom.floor).strip().lower() != floor.strip().lower():
|
||||
continue
|
||||
if shift and r.shift and shift.lower() not in r.shift.lower():
|
||||
continue
|
||||
r_user: Any = getattr(r, 'user', None)
|
||||
u_name = (getattr(r_user, 'name', '') or '').lower() if r_user else ''
|
||||
if search:
|
||||
s_lower = search.lower()
|
||||
subj_n = (r.subject_name or '').lower()
|
||||
subj_c = (r.subject_code or '').lower()
|
||||
c_name = (r.classroom.code if r.classroom else '').lower()
|
||||
if s_lower not in subj_n and s_lower not in subj_c and s_lower not in c_name and s_lower not in u_name:
|
||||
continue
|
||||
|
||||
is_virt = bool(r.is_virtual or (r.classroom and getattr(r.classroom, 'is_virtual', False)))
|
||||
user_dict = {
|
||||
'id': getattr(r_user, 'id', None),
|
||||
'name': getattr(r_user, 'name', None),
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.11",
|
||||
version="3.8.12",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
Test suite for Server-Side Pagination and DB Optimizations.
|
||||
Validates pagination contracts, SQL filtering, and lightweight teacher projection.
|
||||
"""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.models.subject import Subject, Commission
|
||||
from app.models.career import Career
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.services.audit_service import AuditService
|
||||
from app.services.jwt_service import JWTService
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_admin_headers(init_database):
|
||||
admin = User.query.filter_by(email="admin_pag_test@unicaba.edu.ar").first()
|
||||
if not admin:
|
||||
admin = User(
|
||||
name="Admin Paginacion",
|
||||
email="admin_pag_test@unicaba.edu.ar",
|
||||
password_hash=generate_password_hash("EduSpace2026!"),
|
||||
role="ADMIN",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(admin)
|
||||
init_database.session.commit()
|
||||
tokens = JWTService.generate_tokens(admin)
|
||||
return {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
|
||||
def test_users_pagination_defaults(test_admin_headers, init_database):
|
||||
client = TestClient(app)
|
||||
# Crear varios usuarios si no existen
|
||||
for i in range(1, 30):
|
||||
email = f"pag_user_{i}@unicaba.edu.ar"
|
||||
if not User.query.filter_by(email=email).first():
|
||||
u = User(
|
||||
name=f"Usuario Paginado {i}",
|
||||
email=email,
|
||||
password_hash=generate_password_hash("pass"),
|
||||
role="ALUMNO",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(u)
|
||||
init_database.session.commit()
|
||||
|
||||
# 1. Paginación por defecto (page=1, per_page=25)
|
||||
res = client.get("/api/v1/users", headers=test_admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["status"] == "success"
|
||||
assert "total" in data
|
||||
assert data["page"] == 1
|
||||
assert data["per_page"] == 25
|
||||
assert "pages" in data
|
||||
assert len(data["users"]) <= 25
|
||||
assert data["pages"] >= 2
|
||||
assert data["has_next"] is True
|
||||
assert data["has_prev"] is False
|
||||
|
||||
# 2. Segunda página
|
||||
res2 = client.get("/api/v1/users?page=2&per_page=10", headers=test_admin_headers)
|
||||
assert res2.status_code == 200
|
||||
data2 = res2.json()
|
||||
assert data2["page"] == 2
|
||||
assert data2["per_page"] == 10
|
||||
assert len(data2["users"]) == 10
|
||||
assert data2["has_prev"] is True
|
||||
|
||||
|
||||
def test_users_teachers_endpoint(test_admin_headers, init_database):
|
||||
client = TestClient(app)
|
||||
# Crear docente específico
|
||||
teacher = User.query.filter_by(email="profesor_pag_test@unicaba.edu.ar").first()
|
||||
if not teacher:
|
||||
teacher = User(
|
||||
name="Profesor Paginado",
|
||||
email="profesor_pag_test@unicaba.edu.ar",
|
||||
password_hash=generate_password_hash("pass"),
|
||||
role="DOCENTE",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(teacher)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.get("/api/v1/users/teachers", headers=test_admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["status"] == "success"
|
||||
assert "teachers" in data
|
||||
assert any(t["email"] == "profesor_pag_test@unicaba.edu.ar" for t in data["teachers"])
|
||||
# Verificar que sólo expone campos seguros
|
||||
first = data["teachers"][0]
|
||||
assert "id" in first
|
||||
assert "name" in first
|
||||
assert "email" in first
|
||||
assert "password_hash" not in first
|
||||
|
||||
|
||||
def test_audit_logs_pagination_and_search(test_admin_headers, init_database):
|
||||
client = TestClient(app)
|
||||
# Generar eventos de auditoría
|
||||
AuditService.log("LOGIN", "auth", details="Prueba de paginacion audit 1", user_email="admin_pag_test@unicaba.edu.ar")
|
||||
AuditService.log("CREATE", "classrooms", details="Prueba de paginacion audit 2", user_email="admin_pag_test@unicaba.edu.ar")
|
||||
AuditService.log("UPDATE", "academic", details="Materia actualizada para test", user_email="admin_pag_test@unicaba.edu.ar")
|
||||
|
||||
res = client.get("/api/v1/audit-logs?page=1&per_page=2", headers=test_admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["status"] == "success"
|
||||
assert "pagination" in data
|
||||
pag = data["pagination"]
|
||||
assert pag["page"] == 1
|
||||
assert pag["per_page"] == 2
|
||||
assert pag["total"] >= 3
|
||||
assert pag["pages"] >= 2
|
||||
assert len(data["logs"]) == 2
|
||||
|
||||
# Búsqueda por texto en SQL
|
||||
res_search = client.get("/api/v1/audit-logs?search=Materia+actualizada", headers=test_admin_headers)
|
||||
assert res_search.status_code == 200
|
||||
data_search = res_search.json()
|
||||
assert len(data_search["logs"]) >= 1
|
||||
assert any("actualizada" in (l.get("details") or "") for l in data_search["logs"])
|
||||
|
||||
|
||||
def test_subjects_pagination(test_admin_headers, init_database):
|
||||
client = TestClient(app)
|
||||
# Crear carrera y asignaturas
|
||||
car = Career.query.filter_by(code="CAR-PAG").first()
|
||||
if not car:
|
||||
car = Career(name="Carrera Paginacion", code="CAR-PAG")
|
||||
init_database.session.add(car)
|
||||
init_database.session.commit()
|
||||
|
||||
for i in range(1, 6):
|
||||
code = f"SUBJ-PAG-{i}"
|
||||
if not Subject.query.filter_by(code=code).first():
|
||||
s = Subject(name=f"Asignatura Paginada {i}", code=code, career_id=car.id, is_active=True)
|
||||
init_database.session.add(s)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.get("/api/v1/subjects?page=1&per_page=3", headers=test_admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["page"] == 1
|
||||
assert data["per_page"] == 3
|
||||
assert len(data["subjects"]) == 3
|
||||
assert data["total"] >= 5
|
||||
assert data["has_next"] is True
|
||||
|
||||
|
||||
def test_commissions_pagination(test_admin_headers, init_database):
|
||||
client = TestClient(app)
|
||||
# Crear comisiones
|
||||
subj = Subject.query.filter_by(code="SUBJ-PAG-1").first()
|
||||
if subj:
|
||||
for i in range(1, 4):
|
||||
code = f"COMM-PAG-{i}"
|
||||
if not Commission.query.filter_by(code=code, subject_id=subj.id).first():
|
||||
c = Commission(code=code, subject_id=subj.id, shift="Mañana", active=True)
|
||||
init_database.session.add(c)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.get("/api/v1/commissions?page=1&per_page=2", headers=test_admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["page"] == 1
|
||||
assert data["per_page"] == 2
|
||||
assert len(data["commissions"]) <= 2
|
||||
assert "total" in data
|
||||
|
||||
|
||||
def test_empty_query_params_resilience(test_admin_headers, init_database):
|
||||
"""Verifica que query parameters vacíos no causen error 422 Unprocessable Entity."""
|
||||
client = TestClient(app)
|
||||
res_subj = client.get("/api/v1/subjects?career_id=&active=&search=", headers=test_admin_headers)
|
||||
assert res_subj.status_code == 200
|
||||
assert "subjects" in res_subj.json()
|
||||
|
||||
res_comm = client.get("/api/v1/commissions?subject_id=&career_id=&shift=&active=&search=", headers=test_admin_headers)
|
||||
assert res_comm.status_code == 200
|
||||
assert "commissions" in res_comm.json()
|
||||
|
||||
res_resv = client.get("/api/v1/reservations?classroom_id=&floor=&shift=&search=&hide_virtual=false", headers=test_admin_headers)
|
||||
assert res_resv.status_code == 200
|
||||
assert "reservations" in res_resv.json()
|
||||
|
||||
Reference in New Issue
Block a user