fix(academic): commission subjects and shared careers mapping, role-based scoping and gradebook milestones (v3.8.20)
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.19"
|
||||
__version__ = "3.8.20"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -189,6 +189,8 @@ class Commission(db.Model):
|
||||
return {
|
||||
'id': self.id,
|
||||
'subject_id': self.subject_id,
|
||||
'subject_name': self.subject.name if self.subject else 'Sin materia',
|
||||
'subject_code': self.subject.code if self.subject else '',
|
||||
'career_id': self.career_id,
|
||||
'career_name': self.career_name,
|
||||
'career_names': self.career_names,
|
||||
|
||||
@@ -40,6 +40,8 @@ class ReservationRepository(BaseRepository[Reservation]):
|
||||
floor: Optional[str] = None,
|
||||
shift: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
teacher_id: Optional[int] = None,
|
||||
student_id: Optional[int] = None,
|
||||
limit: int = 1000) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de una ventana temporal con carga ansiosa y filtros en SQL."""
|
||||
query = Reservation.query.options(
|
||||
@@ -51,6 +53,29 @@ class ReservationRepository(BaseRepository[Reservation]):
|
||||
Reservation.start_time <= end_dt
|
||||
)
|
||||
|
||||
if teacher_id:
|
||||
from app.models.subject import Commission, CommissionTeacher
|
||||
teacher_comm_ids = db.session.query(Commission.id).filter(
|
||||
or_(
|
||||
Commission.teacher_id == teacher_id,
|
||||
Commission.teachers_association.any(CommissionTeacher.user_id == teacher_id)
|
||||
)
|
||||
).subquery()
|
||||
query = query.filter(
|
||||
or_(
|
||||
Reservation.user_id == teacher_id,
|
||||
Reservation.commission_id.in_(teacher_comm_ids)
|
||||
)
|
||||
)
|
||||
|
||||
if student_id:
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
student_comm_ids = db.session.query(StudentEnrollment.commission_id).filter_by(
|
||||
student_id=student_id,
|
||||
status='activo'
|
||||
).subquery()
|
||||
query = query.filter(Reservation.commission_id.in_(student_comm_ids))
|
||||
|
||||
if status and status.strip() and status.strip().lower() != 'all':
|
||||
s_val = status.strip()
|
||||
query = query.filter(Reservation.status == s_val)
|
||||
|
||||
@@ -97,13 +97,22 @@ class GradebookService:
|
||||
condition = 'Pendiente'
|
||||
condition_badge = 'bg-warning text-dark'
|
||||
|
||||
# Mapa indexado por milestone_id para acceso directo en Nunjucks
|
||||
grades_by_m = {g['milestone_id']: g for g in student_grades}
|
||||
|
||||
rows.append({
|
||||
'id': student.id,
|
||||
'name': student.name,
|
||||
'email': student.email,
|
||||
'dni': getattr(student, 'document_number', None) or f'LEG-{student.id}',
|
||||
'enrollment_id': enr.id,
|
||||
'student_id': student.id,
|
||||
'student_name': student.name,
|
||||
'student_email': student.email,
|
||||
'enrollment_status': enr.status,
|
||||
'grades': student_grades,
|
||||
'grades': grades_by_m,
|
||||
'grades_list': student_grades,
|
||||
'average': avg_score,
|
||||
'average_score': avg_score,
|
||||
'graded_count': graded_count,
|
||||
'total_milestones': total_milestones,
|
||||
@@ -111,9 +120,20 @@ class GradebookService:
|
||||
'condition_badge': condition_badge
|
||||
})
|
||||
|
||||
milestone_columns = [
|
||||
{
|
||||
'id': m.id,
|
||||
'title': m.title or m.tipo,
|
||||
'tipo': m.tipo,
|
||||
'date': m.date.strftime('%d/%m/%Y') if m.date else '',
|
||||
'color': m.color
|
||||
} for m in milestones
|
||||
]
|
||||
|
||||
return {
|
||||
'commission': comm.to_dict(),
|
||||
'milestones': [m.to_dict() for m in milestones],
|
||||
'milestone_columns': milestone_columns,
|
||||
'students': rows,
|
||||
'is_closed': bool(comm.grades_closed),
|
||||
'acta_number': comm.acta_number,
|
||||
@@ -326,8 +346,14 @@ class GradebookService:
|
||||
has_failed = False
|
||||
for m in milestones:
|
||||
g = grades_by_milestone.get(m.id)
|
||||
m_date_str = m.date.strftime('%d/%m/%Y') if m.date else ''
|
||||
if g:
|
||||
ms_results.append(g.to_dict())
|
||||
ms_dict = g.to_dict()
|
||||
ms_dict['milestone_title'] = m.title or m.tipo
|
||||
ms_dict['milestone_date'] = m_date_str
|
||||
ms_dict['milestone_type'] = m.tipo
|
||||
ms_dict['milestone_color'] = m.color
|
||||
ms_results.append(ms_dict)
|
||||
if g.is_absent:
|
||||
has_failed = True
|
||||
elif g.score is not None:
|
||||
@@ -338,6 +364,7 @@ class GradebookService:
|
||||
ms_results.append({
|
||||
'milestone_id': m.id,
|
||||
'milestone_title': m.title or m.tipo,
|
||||
'milestone_date': m_date_str,
|
||||
'milestone_type': m.tipo,
|
||||
'milestone_color': m.color,
|
||||
'display_score': '-',
|
||||
@@ -350,31 +377,53 @@ class GradebookService:
|
||||
|
||||
if not grades:
|
||||
condition = 'Cursando'
|
||||
academic_cond = 'PENDIENTE'
|
||||
condition_badge = 'bg-secondary'
|
||||
elif has_failed:
|
||||
condition = 'Desaprobado'
|
||||
academic_cond = 'LIBRE'
|
||||
condition_badge = 'bg-danger'
|
||||
elif avg_score is not None and avg_score >= 7.0 and len(grades) == len(milestones):
|
||||
condition = 'Promociona'
|
||||
academic_cond = 'PROMOCIONADO'
|
||||
condition_badge = 'bg-success'
|
||||
elif avg_score is not None and avg_score >= 4.0:
|
||||
condition = 'Regular'
|
||||
academic_cond = 'REGULAR'
|
||||
condition_badge = 'bg-primary'
|
||||
else:
|
||||
condition = 'En curso'
|
||||
academic_cond = 'PENDIENTE'
|
||||
condition_badge = 'bg-info text-dark'
|
||||
|
||||
results.append({
|
||||
'enrollment_id': enr.id,
|
||||
'commission_id': comm.id,
|
||||
'commission_code': comm.get_full_code(),
|
||||
'commission': {
|
||||
'id': comm.id,
|
||||
'code': comm.get_full_code(),
|
||||
'semester': comm.semester,
|
||||
'year': comm.year,
|
||||
'shift': comm.shift,
|
||||
'virtual_link': comm.virtual_link
|
||||
},
|
||||
'subject': {
|
||||
'id': comm.subject.id if comm.subject else None,
|
||||
'name': comm.subject.name if comm.subject else 'Materia',
|
||||
'code': comm.subject.code if comm.subject else '',
|
||||
'career': getattr(comm, 'career_names', None) or (comm.subject.career_obj.name if (comm.subject and comm.subject.career_obj) else 'General')
|
||||
},
|
||||
'subject_name': comm.subject.name if comm.subject else 'Materia',
|
||||
'subject_code': comm.subject.code if comm.subject else '',
|
||||
'semester': comm.semester,
|
||||
'year': comm.year,
|
||||
'teacher_name': comm.teacher_name,
|
||||
'milestones': ms_results,
|
||||
'grades': ms_results,
|
||||
'average': avg_score,
|
||||
'average_score': avg_score,
|
||||
'academic_condition': academic_cond,
|
||||
'condition': condition,
|
||||
'condition_badge': condition_badge,
|
||||
'is_acta_closed': bool(comm.grades_closed),
|
||||
@@ -383,6 +432,61 @@ class GradebookService:
|
||||
|
||||
return results
|
||||
|
||||
@classmethod
|
||||
def create_milestone(
|
||||
cls,
|
||||
commission_id: int,
|
||||
milestone_type_id: int,
|
||||
title: str,
|
||||
date_val: datetime,
|
||||
notes: str = '',
|
||||
classroom: str = '',
|
||||
link: str = ''
|
||||
) -> AcademicMilestone:
|
||||
"""Crea un nuevo hito evaluativo (examen, parcial, TP) para una comisión."""
|
||||
comm = Commission.query.get(commission_id)
|
||||
if not comm:
|
||||
raise ValueError(f'Comisión {commission_id} no encontrada.')
|
||||
if comm.grades_closed:
|
||||
raise ValueError('No se pueden agregar hitos a un acta cerrada.')
|
||||
|
||||
m_type = MilestoneType.query.get(milestone_type_id)
|
||||
if not m_type:
|
||||
raise ValueError(f'Tipo de evaluación {milestone_type_id} no encontrado.')
|
||||
|
||||
milestone = AcademicMilestone(
|
||||
title=title.strip() if title else m_type.name,
|
||||
materia_codigo=comm.subject.code if comm.subject else 'ASIG',
|
||||
subject_id=comm.subject_id,
|
||||
commission_id=comm.id,
|
||||
milestone_type_id=m_type.id,
|
||||
date=date_val,
|
||||
classroom=classroom or (comm.virtual_link if comm.virtual_link else None),
|
||||
link=link or comm.virtual_link,
|
||||
notes=notes.strip() if notes else '',
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(milestone)
|
||||
db.session.commit()
|
||||
return milestone
|
||||
|
||||
@classmethod
|
||||
def delete_milestone(cls, commission_id: int, milestone_id: int) -> bool:
|
||||
"""Elimina un hito evaluativo de una comisión si el acta no está cerrada."""
|
||||
comm = Commission.query.get(commission_id)
|
||||
if not comm:
|
||||
raise ValueError(f'Comisión {commission_id} no encontrada.')
|
||||
if comm.grades_closed:
|
||||
raise ValueError('No se pueden eliminar hitos de un acta cerrada.')
|
||||
|
||||
milestone = AcademicMilestone.query.filter_by(id=milestone_id, commission_id=comm.id).first()
|
||||
if not milestone:
|
||||
raise ValueError(f'Hito {milestone_id} no encontrado en la comisión.')
|
||||
|
||||
db.session.delete(milestone)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def get_student_upcoming_milestones(cls, student_id: int, limit: int = 5) -> List[Dict[str, Any]]:
|
||||
"""Obtiene las próximas evaluaciones con cálculo de cuenta regresiva para el dashboard."""
|
||||
|
||||
@@ -28,6 +28,8 @@ class ReservationService:
|
||||
floor: Optional[str] = None,
|
||||
shift: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
teacher_id: Optional[int] = None,
|
||||
student_id: Optional[int] = None,
|
||||
limit: int = 1000) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de un rango temporal con filtros SQL."""
|
||||
return self.reservation_repo.get_by_date_range(
|
||||
@@ -39,6 +41,8 @@ class ReservationService:
|
||||
floor=floor,
|
||||
shift=shift,
|
||||
search=search,
|
||||
teacher_id=teacher_id,
|
||||
student_id=student_id,
|
||||
limit=limit
|
||||
)
|
||||
|
||||
|
||||
+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 = []
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.19",
|
||||
version="3.8.20",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
Reference in New Issue
Block a user