542 lines
31 KiB
Python
542 lines
31 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.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:
|
|
"""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 = str(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 == "bedelia":
|
|
lines.append("\n--- BALANCE OPERATIVO DE BEDELÍA (HOY) ---")
|
|
total_res_today = (
|
|
Reservation.query
|
|
.filter(
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status != 'CANCELLED'
|
|
)
|
|
.count()
|
|
)
|
|
pending_res = (
|
|
Reservation.query
|
|
.filter(Reservation.status == 'PENDING')
|
|
.count()
|
|
)
|
|
active_commissions_cnt = Commission.query.filter_by(active=True).count()
|
|
total_subjects_cnt = Subject.query.filter_by(is_active=True).count()
|
|
|
|
lines.append(f"- Reservas programadas para hoy: {total_res_today}")
|
|
lines.append(f"- Reservas pendientes de confirmación: {pending_res}")
|
|
lines.append(f"- Comisiones activas en el sistema: {active_commissions_cnt}")
|
|
lines.append(f"- Asignaturas activas: {total_subjects_cnt}")
|
|
|
|
elif effective_role == "admin":
|
|
lines.append("\n--- GOBIERNO Y ESTADÍSTICAS DEL SISTEMA ---")
|
|
try:
|
|
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"
|
|
)
|
|
lines.append(
|
|
f"TOTALES ACADÉMICOS: {Career.query.count()} Carreras | "
|
|
f"{Subject.query.filter_by(is_active=True).count()} Asignaturas | "
|
|
f"{Commission.query.filter_by(active=True).count()} Comisiones | "
|
|
f"{Classroom.query.filter_by(is_active=True).count()} Aulas"
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
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:
|
|
tokens = [
|
|
w for w in re.findall(r'[a-zA-Z0-9áéíóúñÁÉÍÓÚÑ]+', query.lower())
|
|
if len(w) >= 3 and w not in {
|
|
'donde', 'como', 'cuando', 'para', 'hola', 'buenas', 'cursar',
|
|
'materia', 'materias', 'clase', 'clases', 'aula', 'aulas', 'que', 'cual'
|
|
}
|
|
]
|
|
if tokens:
|
|
# Buscar asignaturas coincidentes
|
|
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})")
|
|
|
|
# Buscar aulas coincidentes si se menciona un código o número
|
|
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})")
|
|
except Exception:
|
|
pass
|
|
|
|
return "\n".join(lines)
|