fix(academic): commission subjects and shared careers mapping, role-based scoping and gradebook milestones (v3.8.20)
This commit is contained in:
+104
-2
@@ -409,13 +409,40 @@ def list_commissions(
|
||||
career_id: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
active: Optional[str] = Query(None),
|
||||
teacher_id: Optional[int] = Query(None),
|
||||
student_id: Optional[int] = Query(None),
|
||||
mine: Optional[bool] = 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 búsqueda, carrera, materia, turno y paginación."""
|
||||
"""Lista las comisiones académicas con soporte para filtros de búsqueda, carrera, materia, turno, docente/alumno y paginación."""
|
||||
query = Commission.query
|
||||
joined_subject = False
|
||||
user_role = (getattr(current_user, 'role', '') or '').lower()
|
||||
|
||||
# Si se solicita mine=True o si se proveen filtros específicos de usuario
|
||||
effective_teacher_id = teacher_id
|
||||
effective_student_id = student_id
|
||||
if mine:
|
||||
if user_role == 'docente':
|
||||
effective_teacher_id = int(getattr(current_user, 'id'))
|
||||
elif user_role == 'alumno':
|
||||
effective_student_id = int(getattr(current_user, 'id'))
|
||||
|
||||
if effective_teacher_id:
|
||||
query = query.filter(
|
||||
or_(
|
||||
Commission.teacher_id == effective_teacher_id,
|
||||
Commission.teachers_association.any(CommissionTeacher.user_id == effective_teacher_id)
|
||||
)
|
||||
)
|
||||
|
||||
if effective_student_id:
|
||||
query = query.filter(
|
||||
Commission.enrollments.any(StudentEnrollment.student_id == effective_student_id)
|
||||
)
|
||||
|
||||
if search and search.strip():
|
||||
s_clean = search.strip().lower()
|
||||
query = query.outerjoin(Subject, Commission.subject_id == Subject.id)
|
||||
@@ -460,6 +487,10 @@ def list_commissions(
|
||||
has_next = False
|
||||
commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).all()
|
||||
|
||||
all_subjects = Subject.query.filter_by(is_active=True).order_by(Subject.name.asc()).all()
|
||||
all_careers = Career.query.order_by(Career.name.asc()).all()
|
||||
all_terms = AcademicTerm.query.filter_by(is_active=True).order_by(AcademicTerm.year.desc()).all()
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'total': total,
|
||||
@@ -468,7 +499,10 @@ def list_commissions(
|
||||
'pages': pages,
|
||||
'has_prev': has_prev,
|
||||
'has_next': has_next,
|
||||
'commissions': [c.to_dict() for c in commissions]
|
||||
'commissions': [c.to_dict() for c in commissions],
|
||||
'subjects': [s.to_dict() for s in all_subjects],
|
||||
'careers': [car.to_dict() for car in all_careers],
|
||||
'academic_terms': [t.to_dict() for t in all_terms]
|
||||
}
|
||||
|
||||
|
||||
@@ -1190,6 +1224,74 @@ async def reopen_commission_gradebook(
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@academic_router.get("/commissions/{id}/milestones")
|
||||
def list_commission_milestones(
|
||||
id: int,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista todos los hitos evaluativos de una comisión."""
|
||||
comm = Commission.query.get(id)
|
||||
if not comm:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Comisión no encontrada.")
|
||||
milestones = AcademicMilestone.query.filter_by(commission_id=id, is_active=True).order_by(AcademicMilestone.date.asc()).all()
|
||||
return {'status': 'success', 'milestones': [m.to_dict() for m in milestones]}
|
||||
|
||||
|
||||
@academic_router.post("/commissions/{id}/milestones", status_code=status.HTTP_201_CREATED)
|
||||
async def create_commission_milestone(
|
||||
id: int,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA", "DOCENTE"]))
|
||||
):
|
||||
"""Crea un nuevo hito evaluativo (examen, parcial, TP) para la comisión."""
|
||||
data = await get_request_payload(request)
|
||||
milestone_type_id = data.get('milestone_type_id')
|
||||
title = data.get('title', '')
|
||||
date_str = data.get('date', '')
|
||||
notes = data.get('notes', '')
|
||||
|
||||
if not milestone_type_id or not date_str:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="milestone_type_id y date son obligatorios.")
|
||||
|
||||
try:
|
||||
if 'T' in date_str:
|
||||
date_val = datetime.fromisoformat(date_str)
|
||||
else:
|
||||
date_val = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
except Exception:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato de fecha inválido (use YYYY-MM-DD o ISO).")
|
||||
|
||||
try:
|
||||
m = GradebookService.create_milestone(
|
||||
commission_id=id,
|
||||
milestone_type_id=int(milestone_type_id),
|
||||
title=title,
|
||||
date_val=date_val,
|
||||
notes=notes
|
||||
)
|
||||
return {'status': 'success', 'message': 'Hito evaluativo programado exitosamente.', 'milestone': m.to_dict()}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@academic_router.delete("/commissions/{id}/milestones/{milestone_id}")
|
||||
def delete_commission_milestone(
|
||||
id: int,
|
||||
milestone_id: int,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA", "DOCENTE"]))
|
||||
):
|
||||
"""Elimina un hito evaluativo programado si el acta aún está abierta."""
|
||||
try:
|
||||
GradebookService.delete_milestone(commission_id=id, milestone_id=milestone_id)
|
||||
return {'status': 'success', 'message': 'Hito evaluativo eliminado exitosamente.'}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
# =========================================================
|
||||
# MILESTONE TYPES CRUD
|
||||
# =========================================================
|
||||
|
||||
@@ -5,6 +5,7 @@ Provides endpoints for listing, retrieving, creating, updating and toggling clas
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
@@ -60,11 +61,48 @@ def list_classrooms(
|
||||
|
||||
|
||||
@classrooms_router.get("/virtual-rooms")
|
||||
def get_virtual_rooms(current_user: User = Depends(get_current_user)):
|
||||
"""Retorna el catálogo consolidado de salas virtuales operativas en el Campus Virtual."""
|
||||
def get_virtual_rooms(
|
||||
teacher_id: Optional[int] = Query(None),
|
||||
student_id: Optional[int] = Query(None),
|
||||
mine: Optional[bool] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Retorna el catálogo consolidado de salas virtuales operativas en el Campus Virtual con scoping por rol."""
|
||||
user_role = (getattr(current_user, 'role', '') or '').lower()
|
||||
user_id = getattr(current_user, 'id', None)
|
||||
|
||||
# Scoping automático por rol
|
||||
target_teacher_id = teacher_id
|
||||
target_student_id = student_id
|
||||
if mine or (mine is None and user_role == 'docente'):
|
||||
target_teacher_id = user_id
|
||||
elif mine or (mine is None and user_role in ['alumno', 'estudiante']):
|
||||
target_student_id = user_id
|
||||
|
||||
stats = dashboard_service.get_stats(current_user=current_user)
|
||||
vrooms = stats.get('bedelia', {}).get('virtual_rooms', [])
|
||||
|
||||
if target_teacher_id:
|
||||
from app.models.commission import Commission, CommissionTeacher
|
||||
my_comm_ids = set(
|
||||
c.id for c in Commission.query.filter(
|
||||
or_(
|
||||
Commission.teacher_id == target_teacher_id,
|
||||
Commission.teachers_association.any(CommissionTeacher.user_id == target_teacher_id)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
vrooms = [r for r in vrooms if r.get('commission_id') in my_comm_ids or r.get('id') in my_comm_ids]
|
||||
elif target_student_id:
|
||||
from app.models.academic import StudentEnrollment
|
||||
enrolled_comm_ids = set(
|
||||
e.commission_id for e in StudentEnrollment.query.filter(
|
||||
StudentEnrollment.student_id == target_student_id,
|
||||
StudentEnrollment.status.in_(['active', 'regular', 'enrolled', 'promoted'])
|
||||
).all()
|
||||
)
|
||||
vrooms = [r for r in vrooms if r.get('commission_id') in enrolled_comm_ids or r.get('id') in enrolled_comm_ids]
|
||||
|
||||
today_cnt = sum(r.get('today_classes', 0) for r in vrooms)
|
||||
week_cnt = sum(r.get('week_classes', 0) for r in vrooms)
|
||||
month_cnt = sum(r.get('month_classes', 0) for r in vrooms)
|
||||
|
||||
@@ -36,6 +36,9 @@ def list_reservations(
|
||||
floor: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
teacher_id: Optional[int] = Query(None),
|
||||
student_id: Optional[int] = Query(None),
|
||||
mine: Optional[bool] = Query(None),
|
||||
limit: int = Query(1000, le=5000),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
@@ -44,6 +47,16 @@ def list_reservations(
|
||||
effective_end = (date_to or end_date or "").strip()
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Scoping de rol o usuario específico
|
||||
user_role = (getattr(current_user, 'role', '') or '').lower()
|
||||
effective_teacher_id = teacher_id
|
||||
effective_student_id = student_id
|
||||
if mine:
|
||||
if user_role == 'docente':
|
||||
effective_teacher_id = int(getattr(current_user, 'id'))
|
||||
elif user_role == 'alumno':
|
||||
effective_student_id = int(getattr(current_user, 'id'))
|
||||
|
||||
# Resolución inteligente de rangos según scope o filtros
|
||||
if scope == 'month' and not effective_start and not effective_end:
|
||||
start_dt = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
@@ -84,6 +97,8 @@ def list_reservations(
|
||||
floor=floor,
|
||||
shift=shift,
|
||||
search=search,
|
||||
teacher_id=effective_teacher_id,
|
||||
student_id=effective_student_id,
|
||||
limit=limit
|
||||
)
|
||||
result = []
|
||||
|
||||
Reference in New Issue
Block a user