662 lines
39 KiB
Python
662 lines
39 KiB
Python
"""
|
|
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, 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, Dict, Any
|
|
from datetime import datetime, timezone
|
|
from sqlalchemy import or_, func
|
|
|
|
from app.models.building import Building
|
|
from app.models.classroom import Classroom
|
|
from app.models.academic_term import AcademicTerm
|
|
from app.models.career import Career
|
|
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.institutional_benefit import InstitutionalBenefit
|
|
from app import db
|
|
from app.models.user import User
|
|
from app.services.gradebook_service import GradebookService
|
|
from app.services.weather_service import WeatherService
|
|
|
|
|
|
SPANISH_WEEKDAYS = {
|
|
0: "Lunes",
|
|
1: "Martes",
|
|
2: "Miércoles",
|
|
3: "Jueves",
|
|
4: "Viernes",
|
|
5: "Sábado",
|
|
6: "Domingo"
|
|
}
|
|
|
|
|
|
class LiveContextService:
|
|
"""Extrae un resumen conciso de entidades reales del sistema para enriquecer el System Prompt."""
|
|
|
|
@classmethod
|
|
def resolve_user(
|
|
cls,
|
|
user_id: Optional[str] = None,
|
|
user_email: Optional[str] = None,
|
|
user_name: Optional[str] = None
|
|
) -> Optional[User]:
|
|
"""Localiza el usuario autenticado en la base de datos por ID, email o nombre."""
|
|
try:
|
|
if user_id:
|
|
clean_id = user_id.replace("usr_", "").strip()
|
|
if clean_id.isdigit():
|
|
u = User.query.filter_by(id=int(clean_id)).first()
|
|
if u:
|
|
return u
|
|
|
|
if user_email and user_email.strip():
|
|
clean_email = user_email.strip().lower()
|
|
u = User.query.filter(func.lower(User.email) == clean_email).first()
|
|
if u:
|
|
return u
|
|
|
|
if user_name and user_name.strip() and len(user_name.strip()) >= 3:
|
|
clean_name = user_name.strip().lower()
|
|
u = User.query.filter(
|
|
or_(
|
|
func.lower(User.name).like(f"%{clean_name}%"),
|
|
func.lower(User.first_name).like(f"%{clean_name}%")
|
|
)
|
|
).first()
|
|
if u:
|
|
return u
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
@classmethod
|
|
def get_system_snapshot(
|
|
cls,
|
|
role: str = "alumno",
|
|
user_id: Optional[str] = None,
|
|
user_email: Optional[str] = None,
|
|
user_name: Optional[str] = None,
|
|
query: Optional[str] = None
|
|
) -> str:
|
|
"""
|
|
Retorna un bloque de texto formateado con las entidades reales de la base de datos,
|
|
personalizado según el usuario autenticado, su rol y su consulta.
|
|
"""
|
|
lines = []
|
|
normalized_role = (role or "alumno").strip().lower()
|
|
if "admin" in normalized_role:
|
|
effective_role = "admin"
|
|
elif "bedelia" in normalized_role:
|
|
effective_role = "bedelia"
|
|
elif "docent" in normalized_role or "prof" in normalized_role:
|
|
effective_role = "docente"
|
|
else:
|
|
effective_role = "alumno"
|
|
|
|
now = datetime.now()
|
|
start_of_day = datetime(now.year, now.month, now.day, 0, 0, 0)
|
|
end_of_day = datetime(now.year, now.month, now.day, 23, 59, 59)
|
|
|
|
# ---------------------------------------------------------
|
|
# 1. CONTEXTO INSTITUCIONAL Y ESTRUCTURA ACADÉMICA GLOBAL
|
|
# ---------------------------------------------------------
|
|
try:
|
|
# Ciclos Lectivos
|
|
terms = AcademicTerm.query.filter_by(is_active=True).order_by(AcademicTerm.year.desc()).all()
|
|
if terms:
|
|
term_strs = []
|
|
for t in terms:
|
|
curr_tag = " [VIGENTE ACTUALMENTE]" if getattr(t, 'is_current', False) else ""
|
|
term_strs.append(f"{t.name} (Código: {t.code}){curr_tag}")
|
|
lines.append("CICLO LECTIVO: " + " | ".join(term_strs))
|
|
|
|
# Carreras Activas
|
|
careers = Career.query.all()
|
|
if careers:
|
|
career_strs = [f"{c.name} ({c.code})" if c.code else c.name for c in careers]
|
|
lines.append(f"CARRERAS ACTIVAS ({len(careers)}): " + ", ".join(career_strs))
|
|
|
|
# Sedes y Edificios
|
|
buildings = Building.query.filter_by(is_active=True).all()
|
|
if buildings:
|
|
b_strs = []
|
|
for b in buildings:
|
|
cnt = getattr(b, 'classrooms_count', 0)
|
|
addr = f", {b.address}" if b.address else ""
|
|
b_strs.append(f"{b.name} ({b.code or 'Sede'}{addr} - {cnt} aulas)")
|
|
lines.append("SEDES ACTIVAS: " + " | ".join(b_strs))
|
|
|
|
# Aulas Totales
|
|
total_rooms = Classroom.query.filter_by(is_active=True).count()
|
|
if total_rooms > 0:
|
|
lines.append(f"TOTAL DE AULAS DISPONIBLES: {total_rooms} aulas activas (presenciales y virtuales)")
|
|
|
|
except Exception as e:
|
|
lines.append(f"ESTADO GLOBAL: Información general parcialmente cargada ({str(e)}).")
|
|
|
|
# ---------------------------------------------------------
|
|
# 2. LOCALIZACIÓN DEL USUARIO AUTENTICADO
|
|
# ---------------------------------------------------------
|
|
target_user = cls.resolve_user(user_id=user_id, user_email=user_email, user_name=user_name)
|
|
if target_user:
|
|
lines.append(
|
|
f"\nUSUARIO IDENTIFICADO EN SISTEMA: {target_user.name} ({target_user.email}) | "
|
|
f"Rol: {target_user.get_institutional_role().upper()} | DNI: {target_user.document_number or 'S/D'}"
|
|
)
|
|
elif user_name:
|
|
lines.append(f"\nUSUARIO SESIÓN: {user_name} (Rol aparente: {effective_role.upper()})")
|
|
|
|
# ---------------------------------------------------------
|
|
# 3. INFORMACIÓN ESPECÍFICA SEGÚN EL ROL DEL USUARIO
|
|
# ---------------------------------------------------------
|
|
try:
|
|
if effective_role == "alumno":
|
|
lines.append("\n--- DATOS DE CURSADA DEL ALUMNO ---")
|
|
if target_user:
|
|
# Materias en las que está inscripto
|
|
enrollments = (
|
|
StudentEnrollment.query
|
|
.filter_by(student_id=target_user.id, status='activo')
|
|
.all()
|
|
)
|
|
comm_ids = []
|
|
subj_ids = []
|
|
if enrollments:
|
|
lines.append(f"MATERIAS INSCRIPTAS ({len(enrollments)}):")
|
|
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'
|
|
shift = f"Turno {comm.shift}" if comm.shift else ""
|
|
t_name = comm.teacher_name
|
|
lines.append(f"- {subj_name} [{subj_code}] - Comisión {comm.code} ({sched} - {shift}) | Docente: {t_name}")
|
|
|
|
# ---------------------------------------------
|
|
# 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
|
|
.filter(
|
|
Reservation.commission_id.in_(comm_ids),
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status != 'CANCELLED'
|
|
)
|
|
.order_by(Reservation.start_time.asc())
|
|
.all()
|
|
)
|
|
if today_reservations:
|
|
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("\nCLASES DE HOY: No tienes clases presenciales ni virtuales programadas para el día de hoy.")
|
|
|
|
# ---------------------------------------------
|
|
# HITOS EVALUATIVOS Y EXÁMENES PROGRAMADOS
|
|
# ---------------------------------------------
|
|
try:
|
|
if subj_ids:
|
|
milestones = (
|
|
AcademicMilestone.query
|
|
.filter(
|
|
AcademicMilestone.subject_id.in_(subj_ids),
|
|
AcademicMilestone.is_active == True
|
|
)
|
|
.order_by(AcademicMilestone.date.asc())
|
|
.all()
|
|
)
|
|
if milestones:
|
|
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")
|
|
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 o tus notas, indica la materia o comisión para consultar.")
|
|
|
|
elif effective_role == "docente":
|
|
lines.append("\n--- DATOS ACADÉMICOS DEL DOCENTE ---")
|
|
if target_user:
|
|
# Comisiones a cargo
|
|
taught_commissions = (
|
|
Commission.query
|
|
.filter(
|
|
or_(
|
|
Commission.teacher_id == target_user.id,
|
|
Commission.id.in_(
|
|
CommissionTeacher.query
|
|
.with_entities(CommissionTeacher.commission_id)
|
|
.filter_by(user_id=target_user.id)
|
|
)
|
|
),
|
|
Commission.active == True
|
|
)
|
|
.all()
|
|
)
|
|
if taught_commissions:
|
|
lines.append(f"COMISIONES A TU CARGO ({len(taught_commissions)}):")
|
|
t_comm_ids = []
|
|
for tc in taught_commissions:
|
|
t_comm_ids.append(tc.id)
|
|
subj_name = tc.subject.name if tc.subject else 'Sin materia'
|
|
shift = f"Turno {tc.shift}" if tc.shift else ""
|
|
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}")
|
|
|
|
# ---------------------------------------------
|
|
# 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
|
|
.filter(
|
|
Reservation.commission_id.in_(t_comm_ids),
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status != 'CANCELLED'
|
|
)
|
|
.order_by(Reservation.start_time.asc())
|
|
.all()
|
|
)
|
|
if doc_res_today:
|
|
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("\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.")
|
|
|
|
elif effective_role in ("bedelia", "admin"):
|
|
is_admin = effective_role == "admin"
|
|
header_title = "GOBIERNO Y ESTADÍSTICAS DEL SISTEMA" if is_admin else "BALANCE OPERATIVO DE BEDELÍA"
|
|
lines.append(f"\n--- {header_title} ---")
|
|
try:
|
|
# Totales de usuarios
|
|
total_users = User.query.filter_by(is_active=True).count()
|
|
alumnos_cnt = User.query.filter(User.is_active == True, func.lower(User.role).like('%alumn%')).count()
|
|
docentes_cnt = User.query.filter(User.is_active == True, func.lower(User.role).like('%docent%')).count()
|
|
bedelia_cnt = User.query.filter(User.is_active == True, func.lower(User.role).like('%bedel%')).count()
|
|
admin_cnt = User.query.filter(User.is_active == True, func.lower(User.role).like('%admin%')).count()
|
|
|
|
lines.append(
|
|
f"USUARIOS ACTIVOS ({total_users}): {alumnos_cnt} Alumnos | {docentes_cnt} Docentes | "
|
|
f"{bedelia_cnt} Bedelía | {admin_cnt} Administradores"
|
|
)
|
|
|
|
# Comisiones y Asignaciones
|
|
active_comms = Commission.query.filter_by(active=True).all()
|
|
unassigned_teacher = [c for c in active_comms if not c.teacher_id and (not c.teachers or len(c.teachers) == 0)]
|
|
unassigned_teacher_cnt = len(unassigned_teacher)
|
|
|
|
# Cuál es la comisión que más alumnos tiene
|
|
enr_counts = (
|
|
db.session.query(StudentEnrollment.commission_id, func.count(StudentEnrollment.id))
|
|
.filter_by(status='activo')
|
|
.group_by(StudentEnrollment.commission_id)
|
|
.order_by(func.count(StudentEnrollment.id).desc())
|
|
.all()
|
|
)
|
|
top_comm_str = "No hay comisiones con alumnos inscriptos actualmente."
|
|
if enr_counts:
|
|
top_cid, top_qty = enr_counts[0]
|
|
top_c = Commission.query.get(top_cid)
|
|
if top_c:
|
|
subj_n = top_c.subject.name if top_c.subject else top_c.code
|
|
top_comm_str = f"{subj_n} (Comisión {top_c.code}) con {top_qty} alumnos inscriptos"
|
|
elif active_comms:
|
|
top_c = max(active_comms, key=lambda c: (c.current_students or 0), default=None)
|
|
if top_c:
|
|
subj_n = top_c.subject.name if top_c.subject else top_c.code
|
|
top_comm_str = f"{subj_n} (Comisión {top_c.code}) con {top_c.current_students or 0} alumnos"
|
|
|
|
lines.append(f"- Comisiones activas: {len(active_comms)}")
|
|
lines.append(f"- Comisiones sin docente asignado: {unassigned_teacher_cnt}")
|
|
if unassigned_teacher:
|
|
sample_un = [f"{c.subject.name if c.subject else c.code} ({c.code})" for c in unassigned_teacher[:3]]
|
|
lines.append(f" (Sin docente asignado: {', '.join(sample_un)})")
|
|
lines.append(f"- Comisión con más alumnos: {top_comm_str}")
|
|
|
|
# Reservas
|
|
total_res_today = (
|
|
Reservation.query
|
|
.filter(
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status != 'CANCELLED'
|
|
)
|
|
.count()
|
|
)
|
|
pending_res_list = (
|
|
Reservation.query
|
|
.filter(Reservation.status == 'PENDING')
|
|
.order_by(Reservation.start_time.asc())
|
|
.limit(5)
|
|
.all()
|
|
)
|
|
pending_cnt = Reservation.query.filter(Reservation.status == 'PENDING').count()
|
|
lines.append(f"- Reservas programadas para hoy: {total_res_today}")
|
|
lines.append(f"- Reservas pendientes de confirmación: {pending_cnt}")
|
|
if pending_res_list:
|
|
lines.append("DETALLE DE RESERVAS PENDIENTES:")
|
|
for pr in pending_res_list:
|
|
p_date = pr.start_time.strftime("%d/%m/%Y")
|
|
p_time = f"{pr.start_time.strftime('%H:%M')} a {pr.end_time.strftime('%H:%M')}"
|
|
solicitor = pr.user.name if pr.user else "Docente"
|
|
room_desc = pr.classroom.location_display if pr.classroom else "Aula solicitada"
|
|
lines.append(f"• ID {pr.id}: {pr.subject_name} ({p_date} {p_time} hs en {room_desc}) - Solicitó: {solicitor}")
|
|
|
|
lines.append(
|
|
f"TOTALES ACADÉMICOS: {Career.query.count()} Carreras | "
|
|
f"{Subject.query.filter_by(is_active=True).count()} Asignaturas | "
|
|
f"{len(active_comms)} Comisiones | "
|
|
f"{Classroom.query.filter_by(is_active=True).count()} Aulas"
|
|
)
|
|
except Exception as e:
|
|
lines.append(f"ESTADÍSTICAS OPERATIVAS: Consulta parcial ({str(e)}).")
|
|
|
|
except Exception as e:
|
|
lines.append(f"DETALLE DE ROL: Error consultando datos específicos ({str(e)}).")
|
|
|
|
# ---------------------------------------------------------
|
|
# 4. BÚSQUEDA DINÁMICA POR PALABRAS CLAVE EN LA CONSULTA
|
|
# ---------------------------------------------------------
|
|
if query and len(query.strip()) >= 3:
|
|
try:
|
|
q_lower = query.lower()
|
|
|
|
# A. Consulta de Clima, Ubicación o Cómo llegar a la Universidad
|
|
weather_keywords = [
|
|
'clima', 'temperatura', 'tiempo', 'llueve', 'lluvia', 'frio', 'calor',
|
|
'grados', 'caba', 'pronostico', 'llegar', 'donde queda', 'ubicacion',
|
|
'direccion', 'como llego', 'maps', 'mapa', 'tardo', 'distancia'
|
|
]
|
|
if any(w in q_lower for w in weather_keywords):
|
|
w_info = WeatherService.get_university_weather()
|
|
lines.append("\nCLIMA ACTUAL Y UBICACIÓN DE UNICABA:")
|
|
lines.append(f"• Sede Central: {w_info['campus']} ({w_info['address']})")
|
|
lines.append(f"• Clima actual en CABA: {w_info['summary']}")
|
|
lines.append(f"• Cómo llegar en Google Maps: [Calcular ruta a UniCABA]({w_info['maps_url']})")
|
|
lines.append("• Transporte público cercano: Subte B (Estación Florida), Subte D (Estación 9 de Julio / Diagonal Norte), Metrobus 9 de Julio.")
|
|
|
|
tokens = [
|
|
w for w in re.findall(r'[a-zA-Z0-9áéíóúñÁÉÍÓÚÑ]+', q_lower)
|
|
if len(w) >= 3 and w not in {
|
|
'donde', 'como', 'cuando', 'para', 'hola', 'buenas', 'cursar',
|
|
'materia', 'materias', 'clase', 'clases', 'aula', 'aulas', 'que', 'cual',
|
|
'esta', 'estan', 'unos', 'algunos', 'ellos', 'tiene'
|
|
}
|
|
]
|
|
|
|
# B. Búsqueda de Docentes / Profesores por Nombre
|
|
teacher_keywords = ['profesor', 'profesores', 'docente', 'docentes', 'llama', 'nombre', 'sergio']
|
|
if any(w in q_lower for w in teacher_keywords) or any(len(tok) >= 4 for tok in tokens):
|
|
all_docentes = User.query.filter(User.is_active == True, func.lower(User.role).like('%docent%')).all()
|
|
meaningful_tokens = [
|
|
tok for tok in tokens
|
|
if tok not in {'profesor', 'profesores', 'docente', 'docentes', 'llamado', 'alguno', 'estan', 'registrados', 'cuantos', 'cual', 'quien', 'nombre'}
|
|
]
|
|
if meaningful_tokens:
|
|
found_teachers = []
|
|
for d in all_docentes:
|
|
d_full = f"{d.name or ''} {d.first_name or ''} {d.last_name or ''}".lower()
|
|
if any(mt in d_full for mt in meaningful_tokens):
|
|
found_teachers.append(d)
|
|
if found_teachers:
|
|
lines.append("\nDOCENTES COINCIDENTES ENCONTRADOS:")
|
|
for fd in found_teachers[:5]:
|
|
c_list = [c.code for c in fd.taught_commissions if c.active]
|
|
c_str = f"Comisiones: {', '.join(c_list)}" if c_list else "Sin comisiones activas"
|
|
lines.append(f"• {fd.name} ({fd.email}) | {c_str}")
|
|
elif any(len(mt) >= 4 for mt in meaningful_tokens):
|
|
searched_name = meaningful_tokens[0].capitalize()
|
|
lines.append(f"\nBÚSQUEDA DE DOCENTES: No se encontraron profesores registrados con el nombre '{searched_name}' entre los {len(all_docentes)} docentes activos.")
|
|
|
|
# C. Búsqueda de Asignaturas
|
|
if tokens:
|
|
search_filter = or_(
|
|
*[Subject.name.ilike(f"%{tok}%") for tok in tokens],
|
|
*[Subject.code.ilike(f"%{tok}%") for tok in tokens]
|
|
)
|
|
matched_subjects = (
|
|
Subject.query
|
|
.filter(Subject.is_active == True, search_filter)
|
|
.limit(4)
|
|
.all()
|
|
)
|
|
if matched_subjects:
|
|
lines.append("\nASIGNATURAS COINCIDENTES CON LA CONSULTA:")
|
|
for s in matched_subjects:
|
|
c_names = s.career_obj.name if s.career_obj else "Carrera General"
|
|
lines.append(f"• {s.name} (Código: {s.code} | {c_names}):")
|
|
if s.commissions:
|
|
for sc in s.commissions[:2]:
|
|
t_str = f"Prof: {sc.teacher_name}" if sc.teacher else "Docente a designar"
|
|
lines.append(f" - Comisión {sc.code}: {sc.schedule or 'Horario a confirmar'} ({t_str})")
|
|
|
|
# D. Búsqueda de Aulas
|
|
classroom_tokens = [w for w in tokens if w.isdigit() or 'lab' in w or 'virtual' in w]
|
|
if classroom_tokens:
|
|
c_filter = or_(*[Classroom.code.ilike(f"%{tok}%") for tok in classroom_tokens])
|
|
matched_rooms = Classroom.query.filter(Classroom.is_active == True, c_filter).limit(3).all()
|
|
if matched_rooms:
|
|
lines.append("\nAULAS COINCIDENTES:")
|
|
for rm in matched_rooms:
|
|
cap = rm.capacity_display
|
|
lines.append(f"• Aula {rm.code_display} (Piso: {rm.floor_display}, Capacidad: {cap})")
|
|
|
|
# E. Búsqueda de Convenios y Beneficios Institucionales
|
|
benefit_keywords = [
|
|
'convenio', 'convenios', 'beneficio', 'beneficios', 'descuento', 'descuentos',
|
|
'promocion', 'promociones', 'promo', 'cafeteria', 'cafe', 'comida', 'almuerzo',
|
|
'libreria', 'fotocopia', 'deporte', 'gimnasio', 'salud', 'cupon'
|
|
]
|
|
if any(bk in q_lower for bk in benefit_keywords):
|
|
from datetime import date
|
|
today_b = date.today()
|
|
active_b = (
|
|
InstitutionalBenefit.query
|
|
.filter(
|
|
InstitutionalBenefit.is_active.is_(True),
|
|
InstitutionalBenefit.valid_from <= today_b,
|
|
or_(
|
|
InstitutionalBenefit.valid_until.is_(None),
|
|
InstitutionalBenefit.valid_until >= today_b
|
|
)
|
|
)
|
|
.order_by(InstitutionalBenefit.title.asc())
|
|
.limit(8)
|
|
.all()
|
|
)
|
|
matching_b = [b for b in active_b if b.applies_to_role(role)]
|
|
if matching_b:
|
|
lines.append("\nCONVENIOS Y BENEFICIOS INSTITUCIONALES ACTIVOS:")
|
|
for ben in matching_b:
|
|
bld_str = f"en {ben.building.name}" if ben.building else "en Todas las Sedes"
|
|
coupon_str = f" | Código Cupón: {ben.coupon_code}" if ben.coupon_code else ""
|
|
lines.append(f"• {ben.title}: {ben.discount_label} en {ben.partner_name} ({ben.category} {bld_str}){coupon_str}. {ben.description or ''}")
|
|
else:
|
|
lines.append("\nCONVENIOS Y BENEFICIOS: No se encontraron promociones activas registradas para la consulta.")
|
|
except Exception:
|
|
pass
|
|
|
|
return "\n".join(lines)
|