feat(ai-chat): enable student grades, next in-person class, teacher student grades and milestones (v3.8.32)
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
LiveContextService - Proveedor de contexto en tiempo real para UdeCi (SDD-010 / SDD-011).
|
||||
Consulta las entidades relacionales persistidas en base de datos (Sedes, Aulas, Ciclos Lectivos,
|
||||
Carreras, Asignaturas, Comisiones, Inscripciones y Reservas) para suministrar a UdeCi conocimiento
|
||||
fidedigno del estado del sistema, adaptado rigurosamente al usuario autenticado y su rol institucional.
|
||||
Carreras, Asignaturas, Comisiones, Inscripciones, Calificaciones, Hitos y Reservas) para suministrar
|
||||
a UdeCi conocimiento fidedigno del estado del sistema, adaptado rigurosamente al usuario autenticado y su rol institucional.
|
||||
"""
|
||||
import re
|
||||
from typing import Optional, List
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import or_, func
|
||||
|
||||
@@ -17,7 +17,20 @@ from app.models.subject import Subject, Commission, CommissionTeacher
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.milestone import AcademicMilestone, MilestoneType
|
||||
from app.models.grade import MilestoneGrade
|
||||
from app.models.user import User
|
||||
from app.services.gradebook_service import GradebookService
|
||||
|
||||
|
||||
SPANISH_WEEKDAYS = {
|
||||
0: "Lunes",
|
||||
1: "Martes",
|
||||
2: "Miércoles",
|
||||
3: "Jueves",
|
||||
4: "Viernes",
|
||||
5: "Sábado",
|
||||
6: "Domingo"
|
||||
}
|
||||
|
||||
|
||||
class LiveContextService:
|
||||
@@ -149,13 +162,16 @@ class LiveContextService:
|
||||
.filter_by(student_id=target_user.id, status='activo')
|
||||
.all()
|
||||
)
|
||||
comm_ids = []
|
||||
subj_ids = []
|
||||
if enrollments:
|
||||
lines.append(f"MATERIAS INSCRIPTAS ({len(enrollments)}):")
|
||||
comm_ids = []
|
||||
for en in enrollments:
|
||||
comm = en.commission
|
||||
if comm:
|
||||
comm_ids.append(comm.id)
|
||||
if comm.subject_id:
|
||||
subj_ids.append(comm.subject_id)
|
||||
subj_name = comm.subject.name if comm.subject else 'Sin Asignatura'
|
||||
subj_code = comm.subject.code if comm.subject else ''
|
||||
sched = comm.schedule or 'Horario por coordinar'
|
||||
@@ -163,7 +179,94 @@ class LiveContextService:
|
||||
t_name = comm.teacher_name
|
||||
lines.append(f"- {subj_name} [{subj_code}] - Comisión {comm.code} ({sched} - {shift}) | Docente: {t_name}")
|
||||
|
||||
# Clases de hoy para el alumno
|
||||
# ---------------------------------------------
|
||||
# NOTAS Y CALIFICACIONES DEL ALUMNO (GRADEBOOK)
|
||||
# ---------------------------------------------
|
||||
try:
|
||||
student_grades = GradebookService.get_student_grades(target_user.id)
|
||||
if student_grades:
|
||||
lines.append("\nCALIFICACIONES Y ESTADO ACADÉMICO:")
|
||||
for sg in student_grades:
|
||||
s_name = sg.get('subject_name', 'Materia')
|
||||
s_code = sg.get('subject_code', '')
|
||||
c_code = sg.get('commission_code', '')
|
||||
cond = sg.get('condition', 'En curso')
|
||||
avg = sg.get('average_score')
|
||||
avg_str = f"Promedio: {avg}" if avg is not None else "Sin promedio aún"
|
||||
lines.append(f"• {s_name} ({s_code} - Com. {c_code}): Condición {cond} ({avg_str})")
|
||||
|
||||
m_list = sg.get('milestones', [])
|
||||
if m_list:
|
||||
for m in m_list:
|
||||
m_title = m.get('milestone_title') or m.get('milestone_type') or 'Evaluación'
|
||||
m_score = m.get('display_score', '-')
|
||||
m_date = m.get('milestone_date', '')
|
||||
date_part = f" [{m_date}]" if m_date else ""
|
||||
feedback_part = f" - Devolución: {m['feedback']}" if m.get('feedback') else ""
|
||||
lines.append(f" - {m_title}{date_part}: Nota: {m_score}{feedback_part}")
|
||||
else:
|
||||
lines.append(" - No registra evaluaciones cargadas aún.")
|
||||
else:
|
||||
lines.append("\nCALIFICACIONES: Aún no tienes calificaciones registradas en el Libro de Calificaciones.")
|
||||
except Exception as e_grades:
|
||||
lines.append(f"\nCALIFICACIONES: Consulta de notas no disponible ({str(e_grades)}).")
|
||||
|
||||
# ---------------------------------------------
|
||||
# PRÓXIMA CLASE PRESENCIAL DEL ALUMNO
|
||||
# ---------------------------------------------
|
||||
if comm_ids:
|
||||
try:
|
||||
future_presencials = (
|
||||
Reservation.query
|
||||
.filter(
|
||||
Reservation.commission_id.in_(comm_ids),
|
||||
Reservation.start_time >= now,
|
||||
Reservation.status != 'CANCELLED'
|
||||
)
|
||||
.join(Classroom, Reservation.classroom_id == Classroom.id)
|
||||
.filter(
|
||||
~Classroom.code.ilike('%VIRTUAL%'),
|
||||
~Classroom.building.ilike('%VIRTUAL%')
|
||||
)
|
||||
.order_by(Reservation.start_time.asc())
|
||||
.limit(3)
|
||||
.all()
|
||||
)
|
||||
if future_presencials:
|
||||
next_p = future_presencials[0]
|
||||
weekday = SPANISH_WEEKDAYS.get(next_p.start_time.weekday(), "Día")
|
||||
p_date = next_p.start_time.strftime("%d/%m/%Y")
|
||||
st_time = next_p.start_time.strftime("%H:%M")
|
||||
et_time = next_p.end_time.strftime("%H:%M")
|
||||
p_room = next_p.classroom.location_display if next_p.classroom else "Aula física confirmada"
|
||||
comm_code = next_p.commission.code if next_p.commission else ""
|
||||
|
||||
lines.append("\nPRÓXIMA CLASE PRESENCIAL:")
|
||||
lines.append(
|
||||
f"👉 Tu próxima clase presencial es de {next_p.subject_name} (Comisión {comm_code}) "
|
||||
f"el {weekday} {p_date} de {st_time} a {et_time} hs en {p_room}."
|
||||
)
|
||||
if len(future_presencials) > 1:
|
||||
lines.append("Siguientes clases presenciales agendadas:")
|
||||
for fp in future_presencials[1:]:
|
||||
w_name = SPANISH_WEEKDAYS.get(fp.start_time.weekday(), "")
|
||||
lines.append(
|
||||
f"- {fp.subject_name}: {w_name} {fp.start_time.strftime('%d/%m')} "
|
||||
f"({fp.start_time.strftime('%H:%M')} a {fp.end_time.strftime('%H:%M')} hs) "
|
||||
f"en {fp.classroom.code_display}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
"\nPRÓXIMA CLASE PRESENCIAL: No registras clases presenciales programadas en el "
|
||||
"calendario inmediato (tus materias se dictan en modalidad virtual / Google Meet "
|
||||
"o aún no tienen aula física agendada para fechas futuras)."
|
||||
)
|
||||
except Exception as e_pres:
|
||||
lines.append(f"\nPRÓXIMA CLASE PRESENCIAL: Detalle temporalmente no disponible ({str(e_pres)}).")
|
||||
|
||||
# ---------------------------------------------
|
||||
# CLASES DE HOY PARA EL ALUMNO
|
||||
# ---------------------------------------------
|
||||
if comm_ids:
|
||||
today_reservations = (
|
||||
Reservation.query
|
||||
@@ -177,41 +280,43 @@ class LiveContextService:
|
||||
.all()
|
||||
)
|
||||
if today_reservations:
|
||||
lines.append("CLASES PROGRAMADAS PARA HOY:")
|
||||
lines.append("\nCLASES PROGRAMADAS PARA HOY:")
|
||||
for res in today_reservations:
|
||||
st = res.start_time.strftime("%H:%M")
|
||||
et = res.end_time.strftime("%H:%M")
|
||||
room_str = res.classroom.location_display if res.classroom else "Aula por confirmar"
|
||||
lines.append(f"👉 HOY cursas: {res.subject_name} en {room_str} de {st} a {et} hs.")
|
||||
else:
|
||||
lines.append("CLASES DE HOY: No tienes clases presenciales ni virtuales programadas para el día de hoy.")
|
||||
lines.append("\nCLASES DE HOY: No tienes clases presenciales ni virtuales programadas para el día de hoy.")
|
||||
|
||||
# Hitos y exámenes próximos
|
||||
# ---------------------------------------------
|
||||
# HITOS EVALUATIVOS Y EXÁMENES PROGRAMADOS
|
||||
# ---------------------------------------------
|
||||
try:
|
||||
subj_ids = [e.commission.subject_id for e in enrollments if e.commission and e.commission.subject_id]
|
||||
if subj_ids:
|
||||
milestones = (
|
||||
AcademicMilestone.query
|
||||
.filter(
|
||||
AcademicMilestone.subject_id.in_(subj_ids),
|
||||
AcademicMilestone.date >= start_of_day
|
||||
AcademicMilestone.is_active == True
|
||||
)
|
||||
.order_by(AcademicMilestone.date.asc())
|
||||
.limit(5)
|
||||
.all()
|
||||
)
|
||||
if milestones:
|
||||
lines.append("PRÓXIMOS HITOS / EVALUACIONES:")
|
||||
lines.append("\nHITOS EVALUATIVOS Y EXÁMENES PROGRAMADOS:")
|
||||
for m in milestones:
|
||||
m_date = m.date.strftime("%d/%m/%Y %H:%M")
|
||||
t_title = m.type_obj.name if m.type_obj else (m.title or "Hito")
|
||||
lines.append(f"- {m.materia_codigo}: {t_title} el {m_date}")
|
||||
place = m.classroom or m.link or "Aula regular"
|
||||
tag = "[PRÓXIMO]" if m.date >= now else "[FINALIZADO]"
|
||||
lines.append(f"- {m.materia_codigo}: {t_title} el {m_date} hs ({place}) {tag}")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
lines.append("MATERIAS: No registras materias inscriptas activas en este cuatrimestre.")
|
||||
else:
|
||||
lines.append("NOTA ALUMNO: Si buscas en qué aula cursas, indica la materia o comisión para consultar el aula asignada.")
|
||||
lines.append("NOTA ALUMNO: Si buscas en qué aula cursas o tus notas, indica la materia o comisión para consultar.")
|
||||
|
||||
elif effective_role == "docente":
|
||||
lines.append("\n--- DATOS ACADÉMICOS DEL DOCENTE ---")
|
||||
@@ -242,7 +347,77 @@ class LiveContextService:
|
||||
acta_status = "Acta Cerrada" if tc.grades_closed else "Acta Abierta (Carga de Notas Habilitada)"
|
||||
lines.append(f"- {subj_name} (Comisión {tc.code}): {tc.schedule or 'Sin horario'} - {shift} | {tc.current_students} alumnos | Estado: {acta_status}")
|
||||
|
||||
# Clases de hoy del docente
|
||||
# ---------------------------------------------
|
||||
# NOTAS DE ALUMNOS POR COMISIÓN (GRADEBOOK)
|
||||
# ---------------------------------------------
|
||||
lines.append("\nNOTAS Y CALIFICACIONES DE TUS ALUMNOS (LIBRO DE CALIFICACIONES):")
|
||||
for tc in taught_commissions:
|
||||
try:
|
||||
gb = GradebookService.get_commission_gradebook(tc.id)
|
||||
students = gb.get('students', [])
|
||||
ms_cols = gb.get('milestone_columns', [])
|
||||
subj_title = tc.subject.name if tc.subject else f"Comisión {tc.code}"
|
||||
|
||||
if students:
|
||||
graded_count = sum(1 for s in students if s.get('graded_count', 0) > 0)
|
||||
avg_all = [s['average_score'] for s in students if s.get('average_score') is not None]
|
||||
comm_avg = round(sum(avg_all) / len(avg_all), 2) if avg_all else "S/C"
|
||||
lines.append(
|
||||
f"• {subj_title} (Comisión {tc.code}): {len(students)} alumnos inscriptos | "
|
||||
f"{graded_count} con notas cargadas | Promedio de comisión: {comm_avg}"
|
||||
)
|
||||
|
||||
# Detalle de alumnos y notas
|
||||
for st in students[:15]: # Muestra representativa o completa
|
||||
st_name = st.get('name') or st.get('student_name', 'Alumno')
|
||||
st_cond = st.get('condition', 'Sin Calificar')
|
||||
st_avg = st.get('average_score')
|
||||
avg_display = f"Prom: {st_avg}" if st_avg is not None else "Sin prom."
|
||||
|
||||
# Notas de cada hito
|
||||
scores_list = []
|
||||
g_list = st.get('grades_list', [])
|
||||
for gl in g_list:
|
||||
m_name = next((mc['title'] for mc in ms_cols if mc['id'] == gl['milestone_id']), 'Eval')
|
||||
scores_list.append(f"{m_name}: {gl['display_score']}")
|
||||
scores_str = " | ".join(scores_list) if scores_list else "Sin notas"
|
||||
lines.append(f" - {st_name}: {scores_str} ({avg_display} - {st_cond})")
|
||||
else:
|
||||
lines.append(f"• {subj_title} (Comisión {tc.code}): Sin alumnos inscriptos actualmente.")
|
||||
except Exception as e_gb:
|
||||
lines.append(f"• Comisión {tc.code}: Detalle de calificaciones no disponible ({str(e_gb)}).")
|
||||
|
||||
# ---------------------------------------------
|
||||
# HITOS EVALUATIVOS DE LAS MATERIAS DEL DOCENTE
|
||||
# ---------------------------------------------
|
||||
try:
|
||||
t_milestones = (
|
||||
AcademicMilestone.query
|
||||
.filter(
|
||||
AcademicMilestone.commission_id.in_(t_comm_ids),
|
||||
AcademicMilestone.is_active == True
|
||||
)
|
||||
.order_by(AcademicMilestone.date.asc())
|
||||
.all()
|
||||
)
|
||||
if t_milestones:
|
||||
lines.append("\nHITOS EVALUATIVOS Y FECHAS DE EXAMEN PROGRAMADOS:")
|
||||
for tm in t_milestones:
|
||||
tm_date = tm.date.strftime("%d/%m/%Y %H:%M")
|
||||
tm_tipo = tm.type_obj.name if tm.type_obj else (tm.title or "Hito")
|
||||
c_name = tm.commission.code if tm.commission else ""
|
||||
loc = tm.classroom or tm.link or "Aula regular"
|
||||
tag = "[PRÓXIMO]" if tm.date >= now else "[FINALIZADO]"
|
||||
temario = f" - Temario/Notas: {tm.notes}" if tm.notes else ""
|
||||
lines.append(f"- Comisión {c_name} | {tm_tipo} ({tm_date} hs en {loc}){temario} {tag}")
|
||||
else:
|
||||
lines.append("\nHITOS EVALUATIVOS: No tienes exámenes ni TPs programados para tus comisiones.")
|
||||
except Exception as e_m:
|
||||
lines.append(f"\nHITOS EVALUATIVOS: Consulta no disponible ({str(e_m)}).")
|
||||
|
||||
# ---------------------------------------------
|
||||
# CLASES DE HOY DEL DOCENTE
|
||||
# ---------------------------------------------
|
||||
if t_comm_ids:
|
||||
doc_res_today = (
|
||||
Reservation.query
|
||||
@@ -256,14 +431,14 @@ class LiveContextService:
|
||||
.all()
|
||||
)
|
||||
if doc_res_today:
|
||||
lines.append("TUS CLASES DE HOY:")
|
||||
lines.append("\nTUS CLASES DE HOY:")
|
||||
for r in doc_res_today:
|
||||
st = r.start_time.strftime("%H:%M")
|
||||
et = r.end_time.strftime("%H:%M")
|
||||
room_str = r.classroom.location_display if r.classroom else "Aula a confirmar"
|
||||
lines.append(f"👉 Dictas: {r.subject_name} en {room_str} ({st} a {et} hs) - Esperados: {r.expected_attendees}")
|
||||
else:
|
||||
lines.append("CLASES DE HOY: No tienes reservas de aulas registradas para hoy.")
|
||||
lines.append("\nCLASES DE HOY: No tienes reservas de aulas registradas para hoy.")
|
||||
else:
|
||||
lines.append("COMISIONES: No registras comisiones asignadas como docente titular ni adjunto en el ciclo actual.")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user