Compare commits
129
Commits
1e6f493358
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8f2984c82 | ||
|
|
3c61d4fc8e | ||
|
|
60036370a0 | ||
|
|
71480ee309 | ||
|
|
845f6e160e | ||
|
|
b10fc14152 | ||
|
|
aa61c19910 | ||
|
|
1ce6ca0ea5 | ||
|
|
b752493a74 | ||
|
|
19495e96b4 | ||
|
|
1477780df0 | ||
|
|
9f21442bed | ||
|
|
4668117c35 | ||
|
|
3dbd22cc3c | ||
|
|
e84a236d54 | ||
|
|
2d1fefa856 | ||
|
|
54c221e20e | ||
|
|
aaf8281e86 | ||
|
|
1fc653dce8 | ||
|
|
63a90f06ad | ||
|
|
470a326ca6 | ||
|
|
58d94f28d1 | ||
|
|
e5e6bfa094 | ||
|
|
e45eb972dd | ||
|
|
bd88dfdd19 | ||
|
|
939878c4a8 | ||
|
|
d56b2570d1 | ||
|
|
6ff2031b6b | ||
|
|
f7a549ff1f | ||
|
|
c59ff1897f | ||
|
|
32fdd7dbfe | ||
|
|
da7c96d083 | ||
|
|
96d8618157 | ||
|
|
7668c3d92f | ||
|
|
737ddf44a8 | ||
|
|
bf5b7c3ae7 | ||
|
|
a5b014efbe | ||
|
|
fb46de5f28 | ||
|
|
4125f7f7bd | ||
|
|
502865e45b | ||
|
|
52dc3aece0 | ||
|
|
619767ef1b | ||
|
|
173cdaa952 | ||
|
|
3dbe075eb0 | ||
|
|
9f1ac6d670 | ||
|
|
a692c9ce67 | ||
|
|
e4aa832b6e | ||
|
|
6e0ab7faaa | ||
|
|
91ea4bbfc7 | ||
|
|
6bf2a72d08 | ||
|
|
67a1cb14a0 | ||
|
|
85f320d96e | ||
|
|
71a0ac5d11 | ||
|
|
f022cf9bc6 | ||
|
|
bbaab0b1d7 | ||
|
|
452ff8098a | ||
|
|
e89f1b0457 | ||
|
|
7da12d90cc | ||
|
|
213997abeb | ||
|
|
0d93e2c5b7 | ||
|
|
836e605697 | ||
|
|
85fa1b389f | ||
|
|
c14ab0d49f | ||
|
|
4dd3e30698 | ||
|
|
8b4b478744 | ||
|
|
eb3d71d20d | ||
|
|
eff5ed5ce0 | ||
|
|
5ed62d5d30 | ||
|
|
ae071d7f72 | ||
|
|
263e0a17a6 | ||
|
|
ae329c4c36 | ||
|
|
738d210a75 | ||
|
|
6057b6d206 | ||
|
|
9ad70d69e9 | ||
|
|
0b9fee0d66 | ||
|
|
44f4811171 | ||
|
|
37c21e1cd8 | ||
|
|
5057d648c9 | ||
|
|
76647e228b | ||
|
|
e1cc2d1212 | ||
|
|
6d43b2fd66 | ||
|
|
940119edc4 | ||
|
|
ac1e94b927 | ||
|
|
1560bc2a67 | ||
|
|
1e6faa1301 | ||
|
|
cf368036a6 | ||
|
|
fe5acb6119 | ||
|
|
06306c372a | ||
|
|
b2a4f878d8 | ||
|
|
6b0d0bbc77 | ||
|
|
6cb75722f2 | ||
|
|
0828c93edd | ||
|
|
0ca5688b47 | ||
|
|
39c80f573b | ||
|
|
94009ec552 | ||
|
|
be5da21649 | ||
|
|
1edd81516a | ||
|
|
47c21dd25a | ||
|
|
5161460440 | ||
|
|
ea9991e795 | ||
|
|
368dc71b14 | ||
|
|
25039efdeb | ||
|
|
f2d0179154 | ||
|
|
f95711d77b | ||
|
|
22c545e2df | ||
|
|
e1c2c6e8c6 | ||
|
|
ec7a8ac7d4 | ||
|
|
f82e1c414c | ||
|
|
62de55bea8 | ||
|
|
21812ef02e | ||
|
|
03078e3178 | ||
|
|
cb77ba57de | ||
|
|
be3ec3fd89 | ||
|
|
fcd752cda8 | ||
|
|
576a7c0dd2 | ||
|
|
6eef71bc7e | ||
|
|
c834fcdbc6 | ||
|
|
b6d7d8842e | ||
|
|
b935509e54 | ||
|
|
ff6480f591 | ||
|
|
5764203232 | ||
|
|
a60a7cdc78 | ||
|
|
14bf7169c2 | ||
|
|
b7f790eed1 | ||
|
|
eb239ddb21 | ||
|
|
29a2da3297 | ||
|
|
fc94ca82fe | ||
|
|
e38572c93d | ||
|
|
8dc055cd1e |
@@ -0,0 +1,84 @@
|
||||
---
|
||||
name: deploy
|
||||
description: Procedimiento innegociable de bump semántico de versión, git push y despliegue continuo en producción (LXC 10.0.0.217) utilizando .credenciales.
|
||||
---
|
||||
|
||||
# Skill: Despliegue Continuo, Bump de Versión y Git Push
|
||||
|
||||
Esta skill define el protocolo obligatorio para consolidar, versionar, publicar y desplegar cambios en **admin-edu-space**.
|
||||
|
||||
---
|
||||
|
||||
## Principio Rector (Principios 9 y 10 de la Constitución)
|
||||
Toda tarea concluida que modifique funcionalidad, corrija errores o altere la interfaz debe:
|
||||
0. **Tolerancia Cero a Errores en Código (`@[current_problems]`):** Es mandatorio verificar y resolver al 100% cualquier error de linter, compilación, imports o advertencias críticas antes de compilar o empaquetar. Nunca dar una tarea por terminada si hay errores en el código.
|
||||
1. **Subir la versión semántica** de forma coordinada.
|
||||
2. **Ejecutar `git push`** al repositorio remoto en la rama activa (`dev` y `main`).
|
||||
3. **Desplegar inmediatamente en producción** en el servidor institucional utilizando las credenciales registradas en `.credenciales`.
|
||||
|
||||
---
|
||||
|
||||
## Paso 0: Verificación de Código Limpio (Zero Errors)
|
||||
Antes de proceder con el bump de versión:
|
||||
- Inspeccionar y limpiar todos los problemas reportados en `@[current_problems]`.
|
||||
- Ejecutar suite de pruebas: `cd backend && .\venv\Scripts\python.exe -m pytest tests -v`.
|
||||
- Verificar que el compilador no reporte errores de sintaxis ni de tipos: `py_compile`.
|
||||
|
||||
---
|
||||
|
||||
## Paso 1: Bump Semántico de Versión
|
||||
Incrementar la versión siguiendo SemVer (`X.Y.Z`) en todos los descriptores del proyecto:
|
||||
- `frontend/package.json` (`"version": "X.Y.Z"`)
|
||||
- `frontend/src/app.js` (`APP_VERSION`, `FRONTEND_VERSION`, `BACKEND_VERSION`)
|
||||
- `backend/app/__init__.py` (`__version__ = "X.Y.Z"`)
|
||||
- `backend/setup.py` (`version="X.Y.Z"`)
|
||||
- `backend/app/routes/api/openapi.py` (`"version": "X.Y.Z"`)
|
||||
- `CHANGELOG.md` (Nueva sección `## [X.Y.Z] - YYYY-MM-DD`)
|
||||
- `MEMORY.md` (Registrar hito del sprint)
|
||||
|
||||
---
|
||||
|
||||
## Paso 2: Git Commit y Push
|
||||
Ejecutar la suite de pruebas (`python -m pytest tests -v` en `backend`). Si está 100% en verde:
|
||||
```powershell
|
||||
git add .
|
||||
git commit -m "feat/fix: descripción del cambio (vX.Y.Z)"
|
||||
git push origin dev
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Paso 3: Despliegue en Servidor de Producción (LXC Edu-Admin-Space)
|
||||
Consultar el archivo `.credenciales` en la raíz del proyecto para obtener la IP, usuario y contraseña del host:
|
||||
- **Host / IP:** `10.0.0.217` (LXC Debian Edu-Admin-Space)
|
||||
- **Dominio Público:** `https://eduspace.oemspot.com.ar`
|
||||
- **Usuario SSH:** `root`
|
||||
- **Acceso:** Credenciales de `.credenciales`
|
||||
|
||||
### Comandos de Despliegue Remoto:
|
||||
1. Conectar vía SSH y sincronizar repositorio en el servidor:
|
||||
```bash
|
||||
ssh root@10.0.0.217 "cd /opt/admin-edu-space && git fetch && git checkout dev && git pull origin dev"
|
||||
```
|
||||
2. Si hubo cambios en dependencias o esquema:
|
||||
```bash
|
||||
ssh root@10.0.0.217 "cd /opt/admin-edu-space/backend && ./venv/bin/pip install -r requirements.txt && ./venv/bin/flask db upgrade"
|
||||
ssh root@10.0.0.217 "cd /opt/admin-edu-space/frontend && npm install"
|
||||
```
|
||||
3. Reiniciar servicios systemd del Backend y Frontend:
|
||||
```bash
|
||||
ssh root@10.0.0.217 "systemctl restart admin-edu-space-backend admin-edu-space-frontend"
|
||||
```
|
||||
4. Verificar estado del servicio:
|
||||
```bash
|
||||
ssh root@10.0.0.217 "systemctl status admin-edu-space-backend --no-pager"
|
||||
ssh root@10.0.0.217 "systemctl status admin-edu-space-frontend --no-pager"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Paso 4: Verificación de Disponibilidad en Vivo (Smoke Test)
|
||||
Comprobar que el endpoint público responde HTTP 200 con la nueva versión:
|
||||
- Backend version: `https://eduspace.oemspot.com.ar/api/v1/version` o `http://10.0.0.217:5000/api/v1/version`
|
||||
- Frontend version: `https://eduspace.oemspot.com.ar/version`
|
||||
- Pantalla de login accesible: HTTP 200 en `https://eduspace.oemspot.com.ar/login`
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
name: moodle-replicator
|
||||
description: Procedimiento y script de automatización para exportar participantes, materias y carreras desde Moodle Producción UniCABA y replicarlos en el Moodle Local (10.0.0.207) con DNI y credenciales mockeadas.
|
||||
---
|
||||
|
||||
# Skill: Replicador de Datos de Moodle Producción a Local
|
||||
|
||||
## Propósito
|
||||
Automatizar la extracción de participantes (estudiantes y docentes), asignaturas y carreras desde el campus virtual institucional de UniCABA en producción (`https://campus.udelaciudad.edu.ar/`) y replicar su estructura y usuarios en el entorno de pruebas local de Moodle (`http://10.0.0.207/moodle`), permitiendo validar la integración y concurrencia con **Admin Edu Space**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Mapeo Oficial de Entidades (16 Cursos de la Carrera)
|
||||
|
||||
| Entidad | Nombre Oficial | ID Producción | ID Local |
|
||||
| :--- | :--- | :---: | :---: |
|
||||
| **Carrera** | Mi carrera - Lic. en Tecnologías Digitales (CCC) | `922` | `19` |
|
||||
| **Escuela** | Escuela de Tecnología e Industrias Digitales | `187` | `3` |
|
||||
| **Materia 1/2025** | ASIG00120 - Gestión de Sistemas de Información_1/2025 | `3218` | `4` |
|
||||
| **Materia 1/2025** | ASIG00121 - Análisis de Datos I - TEC.DIG._1/2025 | `3220` | `5` |
|
||||
| **Materia 1/2025** | ASIG00122 - Taller: Gestión de Proyectos Digitales - E1_1/2025 | `3221` | `6` |
|
||||
| **Materia 1/2025** | ASIG00215 - Marketing Digital - OPTATIVA -1/2025 | `3665` | `7` |
|
||||
| **Materia 2/2025** | ASIG00123 - Administración de Negocios Digitales_2/2025 | `3945` | `8` |
|
||||
| **Materia 2/2025** | ASIG00124 - Sistemas Digitales_2/2025 | `3944` | `9` |
|
||||
| **Materia 2/2025** | ASIG00125 - Taller: Emprendedurismo en Innovación Digital_2/2025 | `3943` | `10` |
|
||||
| **Materia 2/2025** | ASIG00205 - Gestión del Talento Humano en la Industria digital-2/2025 | `3933` | `11` |
|
||||
| **Materia 1/2026** | ASIG00121 - Análisis de Datos I - TEC.DIG._1/2026 | `4565` | `12` |
|
||||
| **Materia 1/2026** | ASIG00123 - Administración de Negocios Digitales_1/2026 | `4569` | `13` |
|
||||
| **Materia 1/2026** | ASIG00125 - Taller: Emprendedurismo en Innovación Digital_1/2026 | `4571` | `14` |
|
||||
| **Materia 1/2026** | ASIG00296 - Gestión de Redes Informáticas - Equipo 1_1/2026 | `4582` | `15` |
|
||||
| **Materia 2/2026** | ASIG00124 - Sistemas Digitales_2/2026 | `5311` | `16` |
|
||||
| **Materia 2/2026** | ASIG00126 - Seguridad de la Información_2/2026 | `5313` | `17` |
|
||||
| **Materia 2/2026** | ASIG00127 - Programación de Vanguardia - E1_2/2026 | `5314` | `18` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Reglas de Negocio, User-Agent y Mocking
|
||||
|
||||
1. **User-Agent y Credenciales en Producción**:
|
||||
- Cabecera HTTP fija: `User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)`.
|
||||
- Obtenidas exclusivamente de `.credenciales` (sección `Login Moodle del Campus UniCABA en producción`).
|
||||
- Flujo de dos pasos: `GET /login/index.php` para extraer `logintoken` pre-sesión -> `POST` de credenciales manteniendo la cookie `MoodleSession`.
|
||||
|
||||
2. **Descarga Directa de Participantes**:
|
||||
- Invocación al endpoint de exportación `/user/action_redir.php` con `bulkchange.php?operation=download_participants&dataformat=json` pasando los checkboxes de usuarios extraídos con `perpage=5000`.
|
||||
- Fusión con los datos de rol extraídos de la tabla HTML para distinguir `Profesor Universidad` (`editingteacher`, ID 3) de `Estudiante Universidad` (`student`, ID 5).
|
||||
|
||||
3. **Generación Determinística de DNI**:
|
||||
- Para todo participante que no posea DNI explícito: `DNI = 90 + ID_Moodle_6_digitos` (ej. `moodle_id=12740` -> `90012740`).
|
||||
- **Regla de Acceso Local**: `username = DNI` y `password = DNI`.
|
||||
- Si el usuario cuenta con DNI real conocido (ej. Carlos Tello: `34247025`), se preserva su DNI real.
|
||||
|
||||
4. **Alta y Matriculación en Moodle Local**:
|
||||
- Consumo de la REST API institucional en `http://10.0.0.207/moodle/webservice/rest/server.php`.
|
||||
- Funciones: `core_user_create_users` y `enrol_manual_enrol_users`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Comandos de Ejecución
|
||||
|
||||
### Modo Simulación (Dry-Run):
|
||||
```powershell
|
||||
.\backend\venv\Scripts\python.exe scripts/moodle_replicator.py --dry-run
|
||||
```
|
||||
|
||||
### Exportar y Guardar en Archivo JSON:
|
||||
```powershell
|
||||
.\backend\venv\Scripts\python.exe scripts/moodle_replicator.py --export-json participantes_moodle.json --dry-run
|
||||
```
|
||||
|
||||
### Ejecutar Replicación Completa en Moodle Local:
|
||||
```powershell
|
||||
.\backend\venv\Scripts\python.exe scripts/moodle_replicator.py
|
||||
```
|
||||
|
||||
### Replicar Curso Específico:
|
||||
```powershell
|
||||
.\backend\venv\Scripts\python.exe scripts/moodle_replicator.py --course 5311
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Verificación en Moodle Local
|
||||
Para verificar que los usuarios fueron importados y matriculados correctamente:
|
||||
```powershell
|
||||
plink.exe -ssh -batch -pw "Unicaba2026*" root@10.0.0.207 "mysql -u moodleuser -p'MoodlePass2026!Segura' moodle -e 'SELECT c.fullname, COUNT(ue.id) as matriculados FROM mdl_course c JOIN mdl_enrol e ON e.courseid=c.id JOIN mdl_user_enrolments ue ON ue.enrolid=e.id WHERE c.id IN (16,17,18,19) GROUP BY c.id;'"
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
name: sdd
|
||||
description: Flujo de desarrollo guiado por especificaciones (Spec-Driven Development) basado en los principios de ingeniería de software con IA y sintaxis EARS.
|
||||
---
|
||||
|
||||
# Skill: Spec-Driven Development (SDD)
|
||||
|
||||
Esta skill define el arnés metodológico innegociable para implementar, refactorizar o validar funcionalidades en **admin-edu-space**.
|
||||
|
||||
## Principio Fundamental
|
||||
**La especificación manda**: Ninguna línea de código de negocio se escribe si no está precedida por una especificación aprobada (`spec.md`), un plan técnico (`plan.md`) y una lista de tareas atómicas (`tasks.md`).
|
||||
|
||||
---
|
||||
|
||||
## Flujo de Trabajo (7 Pasos)
|
||||
|
||||
```
|
||||
1. Constitución (docs/constitution.md)
|
||||
↓
|
||||
2. Especificación (specs/NNN-nombre/spec.md)
|
||||
↓
|
||||
3. Clarificación (Revisión QA - detección de ambigüedades)
|
||||
↓
|
||||
4. Planificación (specs/NNN-nombre/plan.md)
|
||||
↓
|
||||
5. Desglose de Tareas (specs/NNN-nombre/tasks.md)
|
||||
↓
|
||||
6. Implementación (Tarea por tarea, Test-First)
|
||||
↓
|
||||
7. Validación (RF por RF + Criterios de Finalización)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sintaxis EARS (Easy Approach to Requirements Syntax)
|
||||
Todo Requisito Funcional (RF) debe redactarse usando exclusivamente una de las 5 estructuras EARS en español:
|
||||
|
||||
1. **Ubicuo (Comportamiento permanente)**:
|
||||
> `EL SISTEMA <comportamiento permanente>.`
|
||||
> *Ejemplo:* EL SISTEMA registrará en `AuditLog` toda modificación de asignación de aula.
|
||||
|
||||
2. **Basado en Eventos (Disparado por una acción)**:
|
||||
> `CUANDO <evento>, EL SISTEMA <respuesta>.`
|
||||
> *Ejemplo:* CUANDO el usuario confirme una reserva con conflicto físico, EL SISTEMA bloqueará la operación y retornará un error HTTP 409 con el detalle de la superposición.
|
||||
|
||||
3. **Basado en Estados (Activo mientras se cumpla una condición)**:
|
||||
> `MIENTRAS <estado>, EL SISTEMA <respuesta>.`
|
||||
> *Ejemplo:* MIENTRAS una comisión posea co-docencia activa registrada, EL SISTEMA permitirá la superposición horaria del docente auxiliar.
|
||||
|
||||
4. **No Deseado / Excepciones (Manejo de errores y límites)**:
|
||||
> `SI <condición no deseada>, ENTONCES EL SISTEMA <respuesta>.`
|
||||
> *Ejemplo:* SI la matrícula de la comisión supera el aforo máximo del aula, ENTONCES EL SISTEMA impedirá el guardado y alertará al operador de Bedelía.
|
||||
|
||||
5. **Opcional (Funcionalidad dependiente de configuración o rol)**:
|
||||
> `DONDE <característica opcional>, EL SISTEMA <respuesta>.`
|
||||
> *Ejemplo:* DONDE el usuario posea rol Bedelia o Admin, EL SISTEMA habilitará el botón de reasignación directa de aulas libres.
|
||||
|
||||
---
|
||||
|
||||
## Reglas de Ejecución para Agentes
|
||||
1. **No inventar**: Si falta información o un caso de uso no está cubierto, detenerse y marcar `[NECESITA ACLARACIÓN]`.
|
||||
2. **Tareas pequeñas**: Cada tarea en `tasks.md` debe tener una duración estimada de 20-30 minutos y contar con su criterio *"Hecho cuando:"*.
|
||||
3. **Test-First**: En la lógica de backend, escribir primero el test en rojo antes de tocar el código de la solución.
|
||||
4. **Validación RF por RF**: Al finalizar, verificar cada RF de la especificación contra los tests y la interfaz gráfica.
|
||||
5. **Tolerancia Cero a Errores de Código (`@[current_problems]`) (Principio 10 de la Constitución)**: Es estrictamente inadmisible declarar una tarea o spec como completada si persisten errores en la terminal o problemas de diagnóstico. Todos los errores de importación, narrowing de tipos, NoneType y linter deben ser resueltos antes de dar el veredicto de aprobación.
|
||||
6. **Diseño Modular y Contratos Fuertes (Principio 11 de la Constitución)**: Toda nueva API o endpoint debe dividirse en 4 capas desacopladas (`main.py`, `routers/`, `schemas/`, `storage.py`), usar `Pydantic` (`BaseModel` + `Field`) para validar bodies y query params con tipado estricto, levantar `HTTPException` controladas (404/422/400) sin retornar `null` ante fallos, y documentarse automáticamente en Swagger UI (`/docs`). Las integraciones con modelos de lenguaje (LLMs) deben implementarse con clientes asíncronos `httpx`, timeouts generosos (600s), formato estándar de roles e integrarse con la pestaña de IA en Configuración Global.
|
||||
7. **Memoria**: Al completar cada fase o entrega, actualizar `MEMORY.md`.
|
||||
8. **Bump de Versión, Git Push y Despliegue en Producción (Skill `deploy`)**: Conforme al Principio 9 de la Constitución, incrementar versión semántica (`package.json`, `app.js`, `__init__.py`, `CHANGELOG.md`), ejecutar `git push origin dev` al repositorio remoto y desplegar en producción al servidor institucional LXC (`10.0.0.217`) utilizando las credenciales de `.credenciales`.
|
||||
+234
-227
@@ -1,227 +1,234 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
.idea
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Examples
|
||||
example/
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
#poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
#pdm.lock
|
||||
#pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
#pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Node.js / Frontend
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
frontend/.env
|
||||
|
||||
legacy_admin-edu-space/
|
||||
.vscode/
|
||||
.schemathesis/
|
||||
|
||||
AlumnosLS
|
||||
prerrequisitos
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
.idea
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Examples
|
||||
example/
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
#poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
#pdm.lock
|
||||
#pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
#pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Node.js / Frontend
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
frontend/.env
|
||||
|
||||
legacy_admin-edu-space/
|
||||
.vscode/
|
||||
.schemathesis/
|
||||
|
||||
AlumnosLS
|
||||
apuntes
|
||||
|
||||
.credentials
|
||||
.credenciales
|
||||
participantes_export.json
|
||||
*export.json
|
||||
scratch/
|
||||
␍
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: Coordinador general del proyecto Admin Edu-Space. Dirige el flujo SDD orquestando al planificador, implementador y revisor sin tocar código directamente.
|
||||
mode: primary
|
||||
---
|
||||
|
||||
Eres el Agente Coordinador (Coordinator) de **admin-edu-space**.
|
||||
Tu misión es guiar el avance hacia la entrega del MVP de Bedelía asegurando el cumplimiento de `docs/constitution.md` y `AGENTS.md`.
|
||||
|
||||
## Flujo de Trabajo
|
||||
1. **Spec**: Delegar en `@planner` la redacción de `specs/NNN-nombre/spec.md`.
|
||||
2. **Clarificación**: Delegar en `@reviewer` la revisión QA para eliminar ambigüedades.
|
||||
3. **Plan y Tareas**: Delegar en `@planner` la confección de `plan.md` y `tasks.md`.
|
||||
4. **Implementación**: Delegar en `@implementer` una tarea atómica a la vez.
|
||||
5. **Validación**: Delegar en `@reviewer` la validación RF por RF.
|
||||
6. **Despliegue y Memoria**: Verificar tests en verde (`pytest tests -v`), asegurar cero errores en `@[current_problems]` (Principio 10: no es admisible dar una tarea o hito por completado con errores), validar estándares del Principio 11 (arquitectura modular, contratos Pydantic e IA asíncrona), actualizar `MEMORY.md` y cumplir con el Principio 9 de la Constitución (bump, git push y despliegue continuo).
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: Agente implementador de Admin Edu-Space. Ejecuta tareas atómicas individuales guiado por el plan y con enfoque Test-First.
|
||||
mode: subagent
|
||||
---
|
||||
|
||||
Eres el Agente Implementador (Implementer) de **admin-edu-space**.
|
||||
Tu misión es ejecutar UNA tarea específica de `tasks.md` sin rediseñar el plan ni añadir alcance no solicitado.
|
||||
|
||||
## Reglas
|
||||
- Lee la tarea asignada, `plan.md`, `docs/constitution.md` y `AGENTS.md`.
|
||||
- Enfoque **Test-First**: si tocas lógica de negocio, crea o ajusta primero la prueba automatizada en `backend/tests/`.
|
||||
- Ejecuta las pruebas (`python -m pytest tests -v` en backend) y asegura 100% de éxito.
|
||||
- **Principio 10 (Tolerancia Cero)**: Repara activamente todos los problemas reportados en la terminal o Language Server (`@[current_problems]`). Es estrictamente inadmisible decir que una tarea está terminada o completada si hay errores o fallos en el código.
|
||||
- **Principio 11 (Arquitectura de APIs y LLMs)**: Diseña APIs modulares (`main.py`, `routers/`, `schemas/`, `storage.py`), utiliza Pydantic (`BaseModel` + `Field`) para validar bodies y query params tipados, responde con códigos de estado HTTP explícitos (201/200/204/404/422), levanta `HTTPException` descriptivas sin retornar `null` en fallos y utiliza `httpx` asíncrono con timeouts generosos (600s) para llamadas a modelos de lenguaje (LLMs).
|
||||
- Marca la tarea con `[x]` en `tasks.md` al terminar únicamente si no hay ningún error y detén tu ejecución para supervisión.
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: Agente planificador SDD de Admin Edu-Space. Redacta especificaciones EARS, planes técnicos y tareas atómicas. No escribe código de aplicación.
|
||||
mode: subagent
|
||||
---
|
||||
|
||||
Eres el Agente Planificador (Planner) de **admin-edu-space**.
|
||||
Tu objetivo es redactar especificaciones precisas, arquitecturas limpias y listas de tareas sin tocar el código fuente del backend ni del frontend.
|
||||
|
||||
## Reglas
|
||||
- Lee siempre `docs/constitution.md`, `AGENTS.md` y `MEMORY.md`.
|
||||
- Escribe las especificaciones en `specs/NNN-nombre/spec.md` con sintaxis EARS en español.
|
||||
- Nunca incluyas nombres de archivos ni detalles de base de datos en `spec.md` (van en `plan.md`).
|
||||
- Define criterios de aceptación verificables y delimita claramente el **Fuera de Alcance**.
|
||||
- En `plan.md`, estructura siempre el diseño técnico bajo las 4 capas del Principio 11 (`main.py`, `routers/`, `schemas/`, `storage.py`), definiendo contratos Pydantic (`BaseModel` con `Field`), códigos de estado HTTP semánticos (201, 204, 404, 422), y para módulos de IA prever clientes `httpx` asíncronos con timeouts generosos (600s) y la pestaña correspondiente en Configuración Global.
|
||||
- En `tasks.md`, desglosa tareas en bloques atómicos de 20 a 30 minutos con `[ ]` y criterio *"Hecho cuando:"*.
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
description: Agente revisor y auditor QA de Admin Edu-Space. Clarifica especificaciones y valida implementaciones RF por RF sin modificar archivos.
|
||||
mode: subagent
|
||||
---
|
||||
|
||||
Eres el Agente Revisor (Reviewer) de **admin-edu-space**.
|
||||
Tu misión es actuar como QA profesional y auditor de calidad, garantizando que el software cumpla la especificación al 100%.
|
||||
|
||||
## Tareas
|
||||
1. **En Clarificación de Spec**: Busca ambigüedades, contradicciones, lagunas en casos límite o choques con `docs/constitution.md`.
|
||||
2. **En Validación de Implementación**:
|
||||
- Revisa los cambios (`git diff`).
|
||||
- Verifica activamente que no existan errores ni problemas en la terminal o Language Server (`@[current_problems]`). Si persisten errores de sintaxis, imports, tipos o `NoneType`, emitir obligatoriamente `VEREDICTO: CAMBIOS NECESARIOS`.
|
||||
- Verifica el cumplimiento del **Principio 11**: arquitectura modular (`routers/`, `schemas/`, `storage.py`), validación con Pydantic `BaseModel` + `Field`, uso estricto de códigos HTTP (201/200/204/404/422), manejo controlado de excepciones (`HTTPException`) sin retornar `null` ante fallos, y uso de `httpx` asíncrono con timeouts generosos (600s) en integraciones con LLMs.
|
||||
- Ejecuta las pruebas automatizadas (`python -m pytest tests -v`).
|
||||
- Recorre cada RF de la especificación y emite un veredicto formal:
|
||||
- `VEREDICTO: APROBADO` (solo admisible si pruebas pasan al 100%, cero problemas en `@[current_problems]` y cumplimiento estricto de la Constitución).
|
||||
- `VEREDICTO: CAMBIOS NECESARIOS` (con lista numerada de archivo:línea, incumplimiento y corrección esperada).
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
description: Bump de versión, commit, git push y despliegue a producción usando .credenciales
|
||||
agent: coordinator
|
||||
---
|
||||
Ejecuta el protocolo innegociable de despliegue continuo (Skill `deploy` y Principio 9):
|
||||
|
||||
1. Comprueba que la suite de pruebas esté en verde: `cd backend && pytest tests -v`.
|
||||
2. Incrementa el número de versión semántica en:
|
||||
- `frontend/package.json`
|
||||
- `frontend/src/app.js`
|
||||
- `backend/app/__init__.py`
|
||||
- `backend/setup.py`
|
||||
- `backend/app/routes/api/openapi.py`
|
||||
- `CHANGELOG.md`
|
||||
- `MEMORY.md`
|
||||
3. Ejecuta `git add .`, `git commit` y `git push origin dev` al repositorio remoto.
|
||||
4. Conéctate vía SSH al servidor de producción utilizando los datos del archivo `.credenciales`:
|
||||
- Host LXC: `10.0.0.217`
|
||||
- Usuario: `root`
|
||||
5. Ejecuta en el servidor:
|
||||
- `cd /opt/admin-edu-space && git pull origin dev`
|
||||
- `systemctl restart admin-edu-space-backend admin-edu-space-frontend`
|
||||
6. Verifica que `https://eduspace.oemspot.com.ar/version` responda HTTP 200 con la versión recién publicada.
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
description: SDD · Genera el plan técnico a partir de una spec aprobada
|
||||
---
|
||||
Lee `docs/constitution.md`, `AGENTS.md` y `specs/$1/spec.md`. NO escribas código.
|
||||
|
||||
Genera `specs/$1/plan.md` con:
|
||||
1. Archivos que se crean o modifican y responsabilidad de cada uno.
|
||||
2. Contratos de API (endpoints REST `/api/v1/`, métodos, payload JSON, códigos HTTP).
|
||||
3. Componentes de UI / Vistas Nunjucks afectadas.
|
||||
4. Decisiones técnicas justificadas (y la alternativa descartada).
|
||||
5. Estrategia de tests automatizados (`pytest tests -v`).
|
||||
6. Mapeo de qué Requisito Funcional (RF) cubre cada parte.
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
description: SDD · Genera o entrevista para crear una nueva spec (uso /sdd-spec 001-nombre idea)
|
||||
---
|
||||
NO escribas código en ningún momento. Lee `docs/constitution.md`, `AGENTS.md` y `MEMORY.md`, y utiliza la skill `sdd`.
|
||||
|
||||
Carpeta de la spec: `specs/$1/`
|
||||
Idea inicial: $ARGUMENTS
|
||||
|
||||
Tu trabajo:
|
||||
1. Haz preguntas de UNA en UNA para eliminar ambigüedades (casos límite, errores, qué queda fuera de alcance para el MVP). Máximo 5 preguntas.
|
||||
2. Genera `specs/$1/spec.md` siguiendo la plantilla de SDD, con requisitos funcionales en notación EARS en español y "Estado: borrador".
|
||||
3. Describe exclusivamente el QUÉ y el POR QUÉ: nada de nombres de archivo, modelos ni arquitectura (eso va en el plan).
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
description: SDD · Genera las tareas atómicas a partir de spec.md y plan.md
|
||||
---
|
||||
A partir de `specs/$1/spec.md` y `specs/$1/plan.md`, genera `specs/$1/tasks.md`:
|
||||
1. Tareas pequeñas y atómicas (máximo 20-30 minutos cada una).
|
||||
2. Ordenadas por dependencia lógica (Backend / Datos primero, luego Frontend BFF / UI, luego Tests y Validación).
|
||||
3. Cada tarea debe indicar qué RFs cubre y una línea `"Hecho cuando:"` verificable.
|
||||
4. Utiliza checkboxes `[ ]`.
|
||||
Vendored
+4
-2
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}\\venv\\Scripts\\python.exe",
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}\\backend\\venv\\Scripts\\python.exe",
|
||||
"python.analysis.extraPaths": [
|
||||
"${workspaceFolder}\\venv\\Lib\\site-packages"
|
||||
"${workspaceFolder}\\backend",
|
||||
"${workspaceFolder}\\scripts",
|
||||
"${workspaceFolder}\\backend\\venv\\Lib\\site-packages"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# AGENTS.md - admin-edu-space (Rama dev / MVP)
|
||||
Plataforma web de gestión de espacios áulicos, sincronización académica y asignación de cursadas para UniCABA, diseñada para reemplazar el uso de planillas Excel en Bedelía, orquestar calendarios en tiempo real y conectarse con Moodle 4.1 y Google Workspace.
|
||||
|
||||
## Stack y Estructura
|
||||
- **Arquitectura**: Desacoplada (Backend Core REST API + Frontend BFF).
|
||||
- **Backend Core**: Python 3.12/3.14, FastAPI 0.115+ (100% Nativo ASGI puro con Uvicorn, routers modulares y OpenAPI /docs), SQLAlchemy ORM 2.0, PostgreSQL 15 / SQLite, Pydantic v2 DTOs (`BaseModel`), PyJWT (HS256 stateless).
|
||||
- **Frontend BFF**: Node.js v20+, Express.js, motor de plantillas Nunjucks, cliente Axios con interceptores de autorización Bearer, Bootstrap 5 + Vanilla CSS.
|
||||
- **Integraciones Clave**:
|
||||
- Google OAuth 2.0 para autenticación institucional restringida a `@unicaba.edu.ar`.
|
||||
- Moodle 4.1 REST API (`core_webservice_*`, `enrol_*`) con cola asíncrona resiliente (`MoodleSyncTask`), reintentos exponenciales, Dead Letter Queue (DLQ), capa de caché híbrida (`CacheService` en Redis / memoria) y resolución transparente de IDs de usuario en `update_users`.
|
||||
- Motor de Notificaciones SMTP dinámico (`EmailService`) con credenciales cifradas con Fernet en base de datos.
|
||||
- Importador oficial de Google Sheets (`sheets_importer.py`) para ingesta masiva inicial.
|
||||
- **Entorno de Ejecución**: Contenedores Linux LXC en Proxmox con Nginx como proxy inverso y terminación SSL (entorno productivo institucional: `eduspace.oemspot.com.ar`).
|
||||
|
||||
## Comandos de Desarrollo y Verificación
|
||||
- **Levantar Backend (FastAPI / ASGI :5000)**:
|
||||
```powershell
|
||||
cd backend
|
||||
.\venv\Scripts\activate
|
||||
uvicorn main:app --host 0.0.0.0 --port 5000 --reload
|
||||
```
|
||||
- **Levantar Frontend BFF (Express :3000)**:
|
||||
```powershell
|
||||
cd frontend
|
||||
npm run dev
|
||||
```
|
||||
- **Ejecutar Suite de Pruebas Automatizadas (Backend)**:
|
||||
```powershell
|
||||
cd backend
|
||||
.\venv\Scripts\activate
|
||||
pytest tests -v
|
||||
```
|
||||
- **Auditoría Automatizada de Seguridad (SAST / SCA / DAST)**:
|
||||
```powershell
|
||||
.\security_audit.bat --no-pause
|
||||
```
|
||||
|
||||
## Convenciones de Desarrollo y Buenas Prácticas de APIs
|
||||
- Nombres de variables, funciones, clases, tablas, endpoints y commits estrictamente en **inglés**.
|
||||
- Los endpoints de la API deben seguir estándares RESTful puros bajo `/api/v1/` retornando exclusivamente JSON.
|
||||
- Interfaz gráfica de usuario, etiquetas de formularios, mensajes de error y documentación operativa exclusivamente en **español**.
|
||||
- **Arquitectura Modular en 4 Capas (Separación Estricta de Responsabilidades)**:
|
||||
- `main.py`: Inicialización de la aplicación y registro de routers. No colocar lógica de negocio en el archivo principal ni en el frontend.
|
||||
- `routers/`: Endpoints agrupados por dominio utilizando `APIRouter` (o Blueprints) con prefijos comunes (`prefix="/products"`, `prefix="/llm"`) y etiquetas (`tags=["..."]`) para una documentación limpia en Swagger UI.
|
||||
- `schemas/` (`schemas.py`): Modelos de datos y validaciones con `Pydantic` (`BaseModel`).
|
||||
- `storage.py` (o capa de persistencia `models/`): Centralización del acceso a datos y base de datos.
|
||||
- **Validación de Datos con Pydantic y Tipado Fuerte**:
|
||||
- Heredar de `BaseModel` para el cuerpo (body) de las peticiones.
|
||||
- Uso mandatorio de `Field` para restricciones de negocio: `min_length`, `max_length`, `gt=0`, `ge=0`, etc.
|
||||
- Manejo de parámetros: Path Parameters obligatorios en la URL y Query Parameters opcionales con defaults tipados (`limit: int = 10`).
|
||||
- Validación y captura automática: ante datos inválidos responder con código `422 Unprocessable Entity` detallando el atributo exacto y la falla.
|
||||
- **Códigos de Estado HTTP y Manejo de Excepciones**:
|
||||
- Códigos de estado HTTP semánticos: `201 Created` en POST exitosos, `200 OK` en lecturas/actualizaciones, `204 No Content` en eliminaciones sin cuerpo.
|
||||
- Prohibido retornar `null` o respuestas vacías ante fallos lógicos: levantar siempre excepciones controladas (`HTTPException`) con código adecuado (ej. `404 Not Found` con `detail="Recurso no encontrado"`, `400 Bad Request`, `409 Conflict`).
|
||||
- **Documentación Interactiva Automática**:
|
||||
- Contratos OpenAPI expuestos en `/docs` (Swagger UI) listos para pruebas en vivo (*Try it out*) y visualización de esquemas.
|
||||
|
||||
## Reglas de Dominio y Trampas Conocidas
|
||||
- **Reemplazo del Excel de Bedelía**: La gestión operativa diaria debe realizarse en la app a través del circuito secuencial de 9 pasos (Sedes -> Aulas -> Ciclos Lectivos -> Carreras -> Asignaturas -> Comisiones -> Profesores -> Alumnos -> Reservas). Las comisiones heredan y exponen la Carrera de la asignatura para trazabilidad por plan de estudios. Las hojas de cálculo son únicamente para importación masiva de datos iniciales.
|
||||
- **Asignaturas Compartidas entre Carreras**: Una asignatura puede pertenecer a más de una carrera mediante la tabla asociativa relacional `subject_careers` (Many-to-Many), preservando `career_id` principal por compatibilidad. Las comisiones y asignaturas exponen todas las carreras asociadas en UI y filtros de búsqueda.
|
||||
- **Sincronización con Moodle**: Prohibido hacer peticiones directas y síncronas bloqueantes a Moodle dentro de los controladores de usuario. Utilizar siempre `CacheService` para lecturas y encolar en `MoodleSyncTask` para escrituras.
|
||||
- **Matriz de Conflictos de Reservas**: Una reserva no puede guardarse si genera superposición física de aula presencial, sobrepasa el aforo máximo o solapa al docente (salvo excepción justificada por co-docencia activa).
|
||||
- **Restricción Diaria de Alumnos**: Un alumno no puede matricularse en dos materias regulares en el mismo día, a menos que sea un curso corto (`is_short_course`) o posea autorización expresa de Bedelía (`allow_same_day_exception`).
|
||||
- **Autenticación**: Los flujos de acceso pasan por tokens JWT transportados en cookies seguras `HttpOnly`.
|
||||
- **Integración Asíncrona con Modelos de IA Locales (LLMs) y Asistente en la App**:
|
||||
- **Pestaña en Configuración Global**: Incluir una pestaña específica en la Configuración Global de la app para gestionar la integración con modelos de IA (servidor/URL, modelo seleccionado, tokens y timeout), sentando las bases para el futuro asistente virtual que guiará al usuario en la plataforma.
|
||||
- **Cliente HTTP Asíncrono no Bloqueante (`httpx`)**: Toda llamada a servidores de inferencia locales (Ollama, llama.cpp, vLLM) o APIs de IA debe realizarse de forma asíncrona (`httpx.AsyncClient` con `async def` / `await`) para no bloquear el hilo de ejecución principal ni degradar la concurrencia.
|
||||
- **Timeouts Generosos**: Fijar un tiempo de espera (`timeout`) amplio (mínimo 600 segundos en entornos locales) previendo la carga de modelos en VRAM o inferencias de prompts extensos.
|
||||
- **Estructura de Roles Estándar**: Formatear el payload JSON enviando el modelo y los mensajes con roles explícitos (`role: "system" | "user" | "assistant"`, `content: prompt`).
|
||||
|
||||
## Metodología SDD (Spec-Driven Development) y Arnés de Agentes
|
||||
- **La especificación manda**: Ninguna feature se codifica sin su carpeta `specs/NNN-nombre/` conteniendo `spec.md` (requisitos en sintaxis **EARS** en español: Ubicuo, Eventos, Estado, No Deseado, Opcional), `plan.md` y `tasks.md` (skill `.agents/skills/sdd/SKILL.md`).
|
||||
- **Flujo de Roles**:
|
||||
- `Coordinator`: Conduce la interacción con el usuario y orquesta a los subagentes sin tocar código.
|
||||
- `Planner`: Redacta specs, planes y tareas atómicas (20-30 min) con criterios verificables "Hecho cuando:".
|
||||
- `Implementer`: Ejecuta tareas una a una con enfoque Test-First (`backend/tests/`).
|
||||
- `Reviewer`: Clarifica specs como QA y valida la implementación emitiendo veredicto formal (`VEREDICTO: APROBADO / CAMBIOS NECESARIOS`).
|
||||
|
||||
## Despliegue en Producción y Git Push (Innegociable por Principio 9)
|
||||
- Al completar cualquier tarea o hito verificado:
|
||||
1. Incrementar versión semántica (`package.json`, `app.js`, `__init__.py`, `setup.py`, `openapi.py`).
|
||||
2. Registrar cambios en `CHANGELOG.md` y `MEMORY.md`.
|
||||
3. Ejecutar `git add .`, commit y **`git push origin dev`** al repositorio remoto.
|
||||
4. Desplegar inmediatamente en producción al servidor institucional LXC (`10.0.0.217` / `https://eduspace.oemspot.com.ar`) utilizando los accesos del archivo `.credenciales`, reiniciando los servicios `admin-edu-space-backend` y `admin-edu-space-frontend`, y verificando HTTP 200 en `/version`.
|
||||
|
||||
## Límites
|
||||
- **SIEMPRE**: Lee `docs/constitution.md` y la especificación activa (`specs/`) antes de proponer o modificar código.
|
||||
- **SIEMPRE (Principio 10 - Tolerancia Cero)**: Repara activamente todos los problemas y errores reportados en la terminal / Language Server (`@[current_problems]`). **Es estrictamente inadmisible decir que una tarea está terminada o completada si hay errores o problemas en el código.**
|
||||
- **SIEMPRE (Principio 11 - Contratos Fuertes e IA)**: Implementar endpoints desacoplados en routers modulares, validar payloads con Pydantic `BaseModel` y `Field`, retornar códigos de estado HTTP semánticos (201, 204, 404, 422), exponer contratos en OpenAPI `/docs` y emplear `httpx` asíncrono con timeouts generosos (600s) para integraciones con LLMs.
|
||||
- **SIEMPRE**: Al finalizar la tarea (con cero problemas en el código), realizar bump de versión, `git push origin dev` y despliegue a producción con `.credenciales` (Skill `.agents/skills/deploy/SKILL.md`).
|
||||
- **PREGUNTA ANTES DE**: Añadir nuevas dependencias a `requirements.txt` o `package.json`, alterar el esquema relacional de la base de datos o cambiar la estrategia de caché.
|
||||
- **NUNCA**: Expongas contraseñas, tokens de Moodle, secretos de API o el contenido del archivo `.credenciales` en el código fuente, commits o logs públicos.
|
||||
|
||||
## Memoria
|
||||
- Al empezar, lee `MEMORY.md` para conocer el estado actual de la rama y los objetivos del sprint.
|
||||
- Al terminar cualquier tarea, actualízalo resumiendo las decisiones tomadas y los siguientes pasos.
|
||||
+1218
-2
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,327 @@
|
||||
# MEMORY.md - admin-edu-space
|
||||
Memoria del proyecto entre sesiones para la rama `dev`.
|
||||
|
||||
## Estado actual
|
||||
- Fases 0 a 5.1 del Roadmap completadas y estabilizadas:
|
||||
- Arquitectura desacoplada: Backend Core FastAPI ASGI REST API (:5000) + Frontend BFF Node.js/Express (:3000).
|
||||
- Cobertura 100% ABM: Sedes/Edificios, Aulas (físicas/virtuales), Ciclos Lectivos, Carreras, Materias, Comisiones y Reservas.
|
||||
- Matriz integral de conflictos (físico, docente con co-docencia, aforo y restricción diaria del alumno).
|
||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
||||
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||
- **Sprint Activo: Optimización de Apoyo al Orador en Diapositivas PPTX y Web HTML (v3.8.58)**:
|
||||
- **Rediseño Visual Orientado a Presentación Oral**: Diapositivas limpias con 3 puntos clave contundentes (15pt), capturas de pantalla a gran escala (hero visual) y métricas KPI destacadas.
|
||||
- **Notas del Orador Integradas**: Explicaciones técnicas completas embebidas en las notas de PowerPoint (slide.notes_slide) y en el cajón web (tecla N) para el presentador Carlos Facundo Tello.
|
||||
- **Sincronización Total**: PPTX y HTML regenerados, tests 100% aprobados y desplegado en producción.
|
||||
- **Presentación PowerPoint Widescreen (PRESENTACION_EJECUTIVA_DIAPOSITIVAS.pptx)**: Generación de 14 diapositivas profesionales 16:9 con estética obsidian/slate, métricas y capturas de producción incrustadas.
|
||||
- **Presentación Ejecutiva Web Interactiva (PRESENTACION_EJECUTIVA.html)**: Motor web interactivo con controles de teclado, modo pantalla completa (F), notas de orador (N) y lightbox de capturas.
|
||||
- **Paquete Académico Oficial para la Cátedra**: Memoria técnica de 426 líneas (INFORME_TECNICO_PROYECTO_FINAL.md), guía para el evaluador (GUIA_DEMOSTRACION_Y_EVALUACION_DOCENTE.md), evidencias ágiles (MINUTAS_Y_EVIDENCIAS_GESTION_AGIL.md) y galería (GALERIA_DE_CAPTURAS.md).
|
||||
- **Eliminación Total de Fondos Gráficos Invasivos**: Se retiraron `bg_course-card.png`, `square_course_name.png` y `mini_logo_icon.png` de la consola de recepción, dejando la UI limpia, sobria, sin recuadros recortados y con máxima nitidez.
|
||||
- **Corrección Crítica en Resolución de DNI (Bug de Interceptación por Puntos)**: Se solucionó el problema donde cualquier entrada con dos puntos (ej. `34.247.025` o fechas de emisión/nacimiento `09.02.89` en códigos de barras Renaper) era catalogada como JWT y abortaba con error de firma. Ahora se exige estructura Base64URL pura y en caso de error continúa con la resolución de DNI.
|
||||
- **Soporte de Prefijos y Caracteres**: Manejo universal de prefijos `DNI:`, delimitadores `;` y protección de la letra `Ñ` en apellidos y nombres.
|
||||
- **Versión Consolidada**: 3.8.57.
|
||||
|
||||
## Decisiones (y por qué)
|
||||
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
||||
- **Asociación Explícita de Carreras**: Toda Asignatura se vincula a su Carrera y toda Comisión hereda y expone la Carrera, permitiendo filtros y búsquedas específicas por titulación.
|
||||
- **Importador de Google Sheets Preservado**: Se conserva como ingestor inicial masivo sin fricción para no interrumpir el flujo actual del personal.
|
||||
- **Guía Operativa por Rol**: Documentar explícitamente el procedimiento para Bedelía, Docentes y Alumnos para facilitar la adopción inmediata.
|
||||
|
||||
## Aprendizajes y errores a evitar
|
||||
- **Colisiones Virtuales**: En aulas virtuales no debe aplicarse colisión física horaria; múltiples comisiones pueden cursar simultáneamente con enlaces independientes.
|
||||
- **Manejo de Estados Vacíos (Empty States)**: Proteger siempre las vistas de plantillas en Nunjucks contra colecciones vacías para evitar errores 500 cuando se reinicializa la base.
|
||||
- **Seguridad de Secretos**: Mantener `.credenciales` y `.env` estrictamente fuera del índice de Git.
|
||||
|
||||
- **Depuración de Mocks en Dashboard**: Se eliminaron los arrays estáticos de fallback (`upcoming_reservations`, `today_schedule_list`, etc.) en `frontend/src/routes/dashboard.js` que mostraban asignaturas ficticias ("Matemática Discreta", "Sistemas Operativos", "Ingeniería de Software") en ausencia de datos reales.
|
||||
- **Resolución de Error 500 en Aulas Presenciales y Virtuales**: Se reparó el balance de etiquetas de Nunjucks en `frontend/views/classrooms/list.html` y se reubicaron los modales de eliminación en el bloque físico. Validado con HTTP 200 en `/classrooms/list_classrooms?view_mode=physical` y `view_mode=virtual`.
|
||||
- **Estandarización de Versiones (v3.4.0)**: Expuesto en Backend (`/api/v1/version`), Frontend BFF (`/version`), badges en el pie de página de la barra lateral (`sidebar-footer`) y en la pantalla de inicio de sesión (`login.html`).
|
||||
- **Materias Compartidas en Múltiples Carreras (Many-to-Many)**: Se creó la tabla `subject_careers` en la base de datos relacional para asociar una materia a múltiples carreras simultáneamente (ej: IOT en DATOS, TEC. DIG y VIDEOJUEGOS, o Teoría y Práctica en PROF PROF y CIENCIAS), manteniendo `career_id` principal por retrocompatibilidad.
|
||||
- **Normalización del Importador de Google Sheets**: `sheets_importer.py` descubre dinámicamente las 6 pestañas semanales (Lunes a Sábado), desglosa y mapea de forma canónica las carreras separadas por guion (`-`), soporta códigos combinados (`/`) y desglosa métricas por día de cursada (`by_day`).
|
||||
- **Reactivación de Bedelía en Producción**: Activada la cuenta `bedelia@edu-space.com` para trabajo operativo institucional continuo.
|
||||
|
||||
- **Corrección de Vistas de Bedelía (Reservas de Hoy, Semana, Aulas Libres y Comisiones Sin Aula)**:
|
||||
- **Causa Raíz de Reservas Vacías**: `sheets_importer.py` generaba reservas únicamente para `weeks_to_generate = 4` a partir del 31 de agosto de 2026 (finalizando el 26 de septiembre). En la fecha actual de octubre de 2026 (`2026-10-07`), la base de datos tenía 0 reservas para el día y la semana. Se amplió a `weeks_to_generate = 16` cubriendo todo el 2° cuatrimestre regular (hasta el 19 de diciembre de 2026), generando **2464 reservas totales**, **34 clases para hoy** y **154 clases para la semana actual**.
|
||||
- **Fecha Dinámica en Cartelera**: Se corrigió `handleTodaySchedule` en `frontend/src/routes/schedule.js` que tenía hardcodeado `2026-09-18` como fecha por defecto, reemplazándolo por la fecha actual ISO (`new Date().toISOString().split('T')[0]`) y añadiendo navegación interactiva entre días (`prev_date`, `next_date`, y botón "Hoy").
|
||||
- **Panel Operativo de Cartelera & Agenda en Dashboard**: Se incorporó en el Dashboard de Bedelía la sección "Cartelera Operativa & Agenda de Clases" con tabs dinámicos para alternar entre "Clases de Hoy" y "Esta Semana", visualizando horario, aula física o sala virtual (con enlace directo a Meet), materia, comisión, turno y docente.
|
||||
- **Aulas Disponibles por Período**: Se agregó el selector interactivo "Hoy" (con 18 aulas libres detectadas para el día), "Esta Semana" y "Este Mes" en el panel `#bedelia-available-classrooms`, permitiendo asignar aulas libres con un clic.
|
||||
- **Comisiones Sin Aula Física ni Virtual**: Se agregó el tab "Sin Aula Física ni Virtual (General)" en `#bedelia-unassigned-commissions` para identificar comisiones sin asignación de espacio, y se añadió la columna "Espacio / Aula" con filtro rápido `unassigned_room=true` en `/admin/commissions_list`.
|
||||
- **Filtrado Temporal de Aulas y Comisiones (Día, Semana y Mes)**:
|
||||
- **Requerimiento**: Poder filtrar tanto **Aulas Asignadas** vs **Aulas Sin Asignar (Libres)** como **Comisiones Asignadas** vs **Comisiones Sin Asignar** por **Día**, **Semana** y **Mes**, con la opción de **Día por defecto** y aclarando la **fecha explícita** para fácil identificación de todos los usuarios.
|
||||
- **Backend (`dashboard.py`)**: Se calculan estructuras `filter_stats` para los tres períodos (`today`, `week`, `month`) con métricas precisas (counts, porcentajes) y diccionarios legibles `date_labels` en español ("Hoy · Miércoles 07/10/2026", "Semana del 05/10 al 11/10/2026", "Mes de Octubre 2026").
|
||||
- **Frontend BFF & UI (`dashboard.js`, `dashboard.html`)**:
|
||||
- **Panel de Percentiles**: Switcher interactivo `[ Día (Hoy) ]` (activo por defecto), `[ Semana ]` y `[ Mes ]` con badge explícito de fecha y barras reactivas.
|
||||
- **Panel de Comisiones**: Switcher `[ Día (Hoy) ]`, `[ Semana ]`, `[ Mes ]` con badge de fecha explícita, más pestañas para conmutar entre "Comisiones Asignadas (Con Aula)" y "Comisiones Sin Asignar (Pendientes)" con acciones directas para asignar espacio.
|
||||
- **Panel de Aulas**: Switcher `[ Día (Hoy) ]`, `[ Semana ]`, `[ Mes ]` con badge de fecha explícita, más pestañas para conmutar entre "Aulas Sin Asignar (Libres)" y "Aulas Asignadas (En Uso)" con acceso directo a cartelera o asignación inmediata.
|
||||
- **Validación en Producción**: Desplegado en `https://eduspace.oemspot.com.ar` y verificado con éxito (HTTP 200 en login de Bedelía y renderizado exacto de datos reales).
|
||||
|
||||
- **Evolución del Importador de Google Sheets (Filtros por Carrera, Materia, Día y Fecha Manual)**:
|
||||
- **Requerimiento**: Permitir filtrar qué Carrera, qué Materia y qué Día importar desde el Google Sheet online de UniCABA, como así también agregar la fecha manualmente para corregir o evitar errores si el Sheet no tiene la fecha o se requiere asignar una clase puntual en el calendario.
|
||||
- **Backend (`sheets_importer.py` & `dashboard.py`)**:
|
||||
- Se implementó `inspect_sheet_content()` que descarga e inspecciona las 6 hojas del Sheet online en ~7s, descubriendo de forma dinámica todas las Carreras únicas (18 carreras detectadas) y Materias únicas (206 materias detectadas).
|
||||
- Se agregaron los parámetros `filter_career`, `filter_subject`, `filter_day`, `manual_date` y `single_date_only` al método `sync(...)`.
|
||||
- Normalización robusta de días con `normalize_day_name(...)` insensible a acentos y mayúsculas.
|
||||
- Soporte de coincidencia parcial y sensible a carreras compuestas (ej: `DATOS (CCC)` coincide con asignaturas compartidas con `TEC. DIG.` y `VIDEOJUEGOS`).
|
||||
- Soporte de asignación de fecha puntual manual (`single_date_only=True`), creando 1 única reserva para esa fecha exacta en vez de las 16 semanas regulares, o tomando la fecha manual como base del cuatrimestre.
|
||||
- Nuevo endpoint REST `GET/POST /api/v1/dashboard/sheets-inspect` y actualización de `/api/v1/dashboard/sync-sheets`.
|
||||
- **Frontend BFF & UI (`admin.js` & `import.html`)**:
|
||||
- Panel interactivo "Sincronización Académica con Filtros Avanzados y Control de Fecha".
|
||||
- Selectores dinámicos de Día (Todos, Lunes, Martes, etc.), inputs con autocompletado `<datalist>` para Carreras y Materias.
|
||||
- Selector interactivo de Fecha Manual (`type="date"`) con switch toggle para "Importar ÚNICAMENTE para esta fecha puntual".
|
||||
- Botón "Inspeccionar Sheet Online" con llamada AJAX a `/admin/sheets_inspect` que carga en vivo las carreras y materias descubiertas.
|
||||
- Tarjeta de informe detallado post-sincronización con badges temáticos de "Filtros Activos", número de "Filas Coincidentes" vs totales, y modo de generación.
|
||||
- **Validación en Producción**:
|
||||
- Pruebas automatizadas de backend: 49 tests aprobados en pytest (100% passed).
|
||||
- Desplegado en producción institucional (`https://eduspace.oemspot.com.ar`).
|
||||
- Verificación online con `bedelia@edu-space.com`: HTTP 200 en `/admin/google_sheets_import`, endpoint `/admin/sheets_inspect` retornando 239 filas y 18 carreras, y sincronización filtrada con éxito (ej. Martes + DATOS procesando exactamente sus 3 filas coincidentes).
|
||||
|
||||
- **Sprint v3.4.1: Corrección de Bug en Import Sheet, Aulas Virtuales en Bedelía, Modularización de Vistas y Reglas de Workflow**:
|
||||
- **Fix Bug Google Sheets Import (`Error loading Google Sheets sync view`)**:
|
||||
- **Causa Raíz**: `availableCareers` y `availableSubjects` se declaraban únicamente dentro de un bloque condicional en `admin.js`, provocando `ReferenceError: availableCareers is not defined` en peticiones GET normales.
|
||||
- **Solución**: Se declararon e inicializaron a nivel de función `handleGoogleSheetsImport` tanto en la consulta inicial de `Promise.allSettled` como en el refresh posterior a la sincronización.
|
||||
- **Fix Bug Aulas Virtuales en Dashboard de Bedelía**:
|
||||
- **Causa Raíz**: El conteo `virtual_classrooms` en `dashboard.py` calculaba `len(virtual_classrooms_list)` sobre la tabla relacional `classrooms`, que solo contiene 1 registro genérico (`id: 331, code: 'VIRTUAL', building: 'Campus Virtual'`).
|
||||
- **Solución**: Se actualizó la lógica para calcular las salas virtuales a partir de las comisiones activas con modalidad virtual (Google Meet/Teams/Zoom) o reservas en Campus Virtual, reportando las 101 salas virtuales activas. Se incorporó el arreglo `virtual_rooms` en `role_data` de Bedelía y se agregó la pestaña *"Salas Virtuales (Campus Virtual)"* con 127 enlaces a Google Meet en el panel de Aulas (`dashbede.html`).
|
||||
- **Modularización de la Arquitectura de Vistas (`dashboard.html` como Layout Padre)**:
|
||||
- Se dividió el archivo monolítico `dashboard.html` de más de 2300 líneas en 4 componentes/subvistas según el rol del usuario:
|
||||
- `dashadm.html` (Administrador)
|
||||
- `dashbede.html` (Bedelía)
|
||||
- `dashprof.html` (Docente / Profesor)
|
||||
- `dashalum.html` (Alumno / Estudiante)
|
||||
- `dashboard.html` actúa ahora como layout/plantilla padre limpia que inyecta la subvista correspondiente mediante `{% include %}` de Nunjucks.
|
||||
- **Actualización de Reglas en `docs/constitution.md` (Principio 9)**:
|
||||
- Se agregó el Principio 9 innegociable:
|
||||
1) Siempre actualizar y guardar el control de la nueva versión semántica al momento de compilar.
|
||||
2) Al finalizar la compilación, siempre subir y desplegar la nueva versión al servidor institucional de producción.
|
||||
- **Despliegue y Verificación en Producción**:
|
||||
- Versionado elevado a `v3.4.1`.
|
||||
- Desplegado exitosamente en el servidor LXC `10.0.0.217` (`https://eduspace.oemspot.com.ar`).
|
||||
- Verificación HTTP 200 en `/version`, login admin, `/admin/google_sheets_import`, dashboards modularizados de los 4 roles y cuenta institucional de Bedelía.
|
||||
- **Sprint UX/UI: Agrupación Cronológica de Reservas y Formato Limpio de Fechas (v3.4.2)**:
|
||||
- **Problema 1: Duplicación de Reservas por Hora en Cartelera**:
|
||||
- En `/schedule/today_schedule`, un bucle fijo `for (let hour = 7; hour <= 21; hour++)` insertaba la misma reserva en cada bloque horario de 1 hora que abarcaba la materia (ej. Marketing Digital de 08:00 a 11:00 hs aparecía repetida a las 8, 9 y 10).
|
||||
- **Solución**: Se eliminó la clonación artificial y se introdujo la agrupación nativa por franja horaria real de cursada (`grouped_slots`, ej. `08:00 - 11:00 hs`, `18:30 - 21:00 hs`). Cada reserva aparece agrupada exactamente UNA SOLA VEZ en su bloque horario correspondiente con turno, duración, aula, cupo y enlace a Meet/Zoom.
|
||||
- **Problema 2: Formato ISO Crudo en Listado de Reservas**:
|
||||
- En `/schedule/list_reservations` (tabla y tarjetas) se mostraban strings crudos con 'T' y segundos (`2026-10-08T08:00:00 - 2026-10-08T11:00:00 hs`).
|
||||
- **Solución**: Se enriquecieron todas las reservas con la función `formatReservationDates` y nuevos filtros Nunjucks (`format_date_human`, `format_time`, `format_time_range`), mostrando fecha limpia (`Jueves 08/10/2026` / `08/10/2026`) y horario amigable (`08:00 - 11:00 hs`).
|
||||
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||
- Versión incrementada a `v3.4.2` en Frontend y Backend.
|
||||
- Despliegue inmediato al servidor institucional `10.0.0.217` y verificación en caliente.
|
||||
- **Sprint Importador Google Sheets: Selección Granular y Grilla Interactiva (v3.4.3)**:
|
||||
- **Selección Granular de Entidades (Tarjetas Checkbox)**:
|
||||
- Réplica del diseño visual de la Herramienta de Purga con botones "Marcar Todo" y "Desmarcar Todo".
|
||||
- Toggles individuales para Asignaciones de aulas (`import_reservations`), Aulas físicas y virtuales (`import_classrooms`), Comisiones (`import_commissions`), Asignaturas (`import_subjects`) y Carreras (`import_careers`).
|
||||
- **Selector de Días de la Semana con Checkboxes Múltiples**:
|
||||
- Reemplazo del selector simple por checkboxes individuales para Lunes a Sábado con accesos rápidos ("Todos", "Lun a Vie", "Limpiar").
|
||||
- **Grilla de Previsualización Interactiva e Inspección Previa**:
|
||||
- El botón "Inspeccionar Sheet Online" no importa directamente; extrae y presenta una grilla interactiva completa (`preview_rows`) de registros online.
|
||||
- Selección individual por fila y checkbox maestro superior.
|
||||
- Modificación manual inline de fechas de cursada por fila mediante Datepicker (`<input type="date">`) y aplicador de fecha masiva a seleccionados.
|
||||
- Resaltado visual con badges de alerta y error ante registros incompletos o aulas no reconocidas.
|
||||
- Buscador en vivo multi-criterio y paginación fluida (25 filas por página) para evitar bloqueos del navegador.
|
||||
- Modal de confirmación previa con desglose exacto de filas y entidades antes de iniciar la sincronización.
|
||||
- **Backend y BFF REST**:
|
||||
- `sheets_importer.py` ampliado para retornar `preview_rows` y procesar `selected_rows` con granularidad de entidades.
|
||||
- Endpoints `POST /api/v1/dashboard/sheets-inspect` y `POST /api/v1/dashboard/sync-sheets`.
|
||||
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||
- Versión incrementada a `v3.4.3` en Frontend y Backend.
|
||||
- Despliegue y verificación en caliente en el servidor institucional `10.0.0.217` (`https://eduspace.oemspot.com.ar`).
|
||||
|
||||
- **Sprint Dashboard Bedelía: Filtro Temporal "Mañana" en Switchers y Cartelera (v3.4.4)**:
|
||||
- **Requerimiento**: Agregar "Mañana" en el filtro actual del dashboard que decía "Día (Hoy) / Semana / Mes".
|
||||
- **Implementación**:
|
||||
- **Backend API (`backend/app/routes/api/dashboard.py`)**: Cálculo de `tomorrow_dt` (00:00:00 a 23:59:59), agregando estadísticas en `filter_stats['tomorrow']` para percentiles de aulas físicas y comisiones asignadas/sin asignar, y `tomorrow_schedule_list` para la agenda de clases.
|
||||
- **Frontend BFF & Vistas (`frontend/views/dashboard/dashbede.html`, `dashbede.html`, `dashadm.html`, `dashboard.html`)**:
|
||||
- Switcher de percentiles: botón "Mañana" con actualización dinámica de percentiles de ocupación de aulas físicas.
|
||||
- Switcher de comisiones: botón "Mañana" y bloques `#commBlock-tomorrow-unassigned` y `#commBlock-tomorrow-assigned`.
|
||||
- Switcher de aulas físicas: botón "Mañana" y bloques `#classBlock-tomorrow-unassigned` (aulas libres con botón "Asignar") y `#classBlock-tomorrow-assigned` (aulas en uso).
|
||||
- Cartelera Operativa & Agenda de Clases: botón "Clases de Mañana" y tabla `#bedeliaScheduleTomorrow` mostrando asignaturas, comisiones, docentes y enlaces para mañana.
|
||||
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||
- Versión incrementada a `v3.4.4` en Frontend y Backend.
|
||||
- Despliegue al servidor institucional `10.0.0.217` (`https://eduspace.oemspot.com.ar`) y verificación en caliente.
|
||||
|
||||
- **Sprint Optimizador de Aulas IA: Corrección de Permisos y Carga de Comisiones (v3.4.5)**:
|
||||
- **Problema Reportado**: AI Room Reservation Optimizer no mostraba comisiones y los indicadores de Available Classrooms, Active Commissions y Existing Reservations quedaban en `--`.
|
||||
- **Causa Raíz Identificada**:
|
||||
- En `backend/app/routes/genetic_algorithm.py` las rutas `@genetic_bp.route('/commissions')`, `/algorithm-status`, `/preview-optimization`, `/optimize` y `/apply-optimization` exigían de forma estricta `g.jwt_user.role in ['ADMIN', 'teacher']` o `g.jwt_user.role in ['ADMIN']`.
|
||||
- Al ingresar como Bedelía (`role == 'Bedelia'`), Docentes o Administradores con rol en minúsculas, el backend devolvía `403 Forbidden`, bloqueando la llamada AJAX y dejando la interfaz vacía con `--`.
|
||||
- En el Frontend BFF, la ruta `/genetic_optimizer` no requería `requireAuth` ni pasaba datos de sesión de usuario a la plantilla.
|
||||
- **Solución Implementada**:
|
||||
- Creación del helper `check_optimizer_permission(user, requires_write)` en `backend/app/routes/genetic_algorithm.py` habilitando acceso a `admin`, `administrador`, `bedelia`, `docente`/`teacher` y permisos RBAC en 'optimizer'.
|
||||
- `GET /api/genetic/commissions` ahora enriquece los objetos con `subject_name`, `subject_code`, `career_name`, `schedule` y `shift`.
|
||||
- `frontend/views/genetic_optimizer.html`: Traducido íntegramente a español institucional ("Optimizador Inteligente de Asignación de Aulas (IA)"), tarjetas de comisiones con badges, buscador en vivo multi-criterio y manejo de errores visual.
|
||||
- `frontend/public/js/genetic-algorithm.js`: Traducción de alertas, modales y tablas de resultados.
|
||||
- `frontend/src/app.js`: Protección con `requireAuth` e inyección de sesión a la vista.
|
||||
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||
- Versión incrementada a `v3.4.5` en Frontend y Backend.
|
||||
- Despliegue inmediato al servidor institucional `10.0.0.217` y verificación en caliente HTTP 200.
|
||||
|
||||
- **Sprint v3.4.6: Corrección Integral de Reservas, Pisos Dinámicos, Fechas Humanas y Filtro de Carreras**:
|
||||
- **Incidencias Resueltas**:
|
||||
1. `/schedule/add_reservation` y `/schedule/edit`: Corregido error de serialización JSON que rompía el selector en cascada Edificio -> Piso -> Aula al seleccionar "Edificio Central". Inyección segura sin entities y matching resiliente de pisos físicos y virtuales.
|
||||
2. `/schedule/calendar_view`: Limpieza de datos hardcodeados/mockeados (`Arquitectura de Software ARQ-101`, `COM-A`, `Licenciatura en Sistemas`). El feed y filtros ahora consumen asignaturas, carreras y comisiones reales de la BD.
|
||||
3. `sheets_importer.py`: Eliminada la autogeneración no deseada de enlaces de Google Meet / Zoom (`meet.google.com/edu-...`) en reservas importadas cuando la celda original está vacía (ej. `#9797 ASIG00215 - Marketing Digital`).
|
||||
4. `/classrooms/view_classroom`: Formateadas fechas y horarios a español legible (ej. `Viernes 04/09/2026 · 18:30 a 21:30 hs`) eliminando formato ISO repetido y ampliando rango a todo el semestre 2026.
|
||||
5. `/buildings/list_buildings` y `/buildings/view/:id`: Corregida la ficha de edificio que mostraba "No hay aulas asignadas a este edificio" a pesar de tener 6 aulas físicas asociadas (`floors_list` y `classrooms_by_floor`), corregido el contador de "Pisos Presenciales" (4 pisos) y soporte completo de niveles dinámicos alfanuméricos (PB, EP, Subsuelo, etc.).
|
||||
6. `/admin/commissions_list`: Corregido `UnboundLocalError` en `backend/app/routes/api/admin.py` por importación interna tardía de `Career`, que arrojaba HTTP 500 al filtrar por `career_id=180, 181, 182`.
|
||||
- **Sprint v3.4.8: Registro de Auditoría Institucional y Trazabilidad Operativa**:
|
||||
- **Incidencias y Mejoras**:
|
||||
1. `/api/v1/admin/audit-logs`: Implementación del endpoint RESTful con paginación, filtros por módulo (`auth`, `reservations`, `classrooms`, `buildings`, `optimizer`, `admin`, etc.), acción (`LOGIN`, `LOGIN_FAILED`, `CREATE`, `UPDATE`, `DELETE`, `CONFIRM`, etc.) y búsqueda multi-campo.
|
||||
2. Modelo `AuditLog`: Agregado método `to_dict()` para serialización JSON segura e ISO.
|
||||
3. `AuditService`: Soporte de parámetros explícitos `user_id` y `user_email` para registrar eventos cuando el usuario no está autenticado o el intento de acceso falla.
|
||||
4. `/api/v1/auth/`: Instrumentada la captura de inicios de sesión (`LOGIN`), Google OAuth (`LOGIN_GOOGLE`), Moodle delegado (`LOGIN_MOODLE`), fallos de inicio de sesión (`LOGIN_FAILED`), accesos bloqueados (`LOGIN_BLOCKED`), cierres de sesión (`LOGOUT`) y cambios de contraseña institucional (`PASSWORD_CHANGE`).
|
||||
5. `/api/v1/reservations`: Auditoría de creación (`CREATE`), edición (`UPDATE`), cancelación (`CANCEL`), borrado permanente (`DELETE`) y confirmación oficial (`CONFIRM`).
|
||||
6. `/api/v1/classrooms` y `/api/v1/buildings`: Auditoría de altas, modificaciones, alternancia de estado activo/inactivo (`TOGGLE`) y bajas.
|
||||
7. Optimizador Genético IA: Auditoría de ejecuciones (`OPTIMIZE_RUN`) y aplicación de asignaciones masivas en base de datos (`OPTIMIZE_APPLY`).
|
||||
8. Frontend BFF (`/admin/audit_logs`): Conexión del BFF con la REST API, badges temáticos e intuitivos, filtros rápidos por categorías, visor modal para detalles extensos o JSON, y paginador dinámico nativo que preserva parámetros de consulta.
|
||||
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||
- Versión incrementada a `v3.4.8` en Frontend y Backend.
|
||||
|
||||
- **Sprint v3.4.9: Solución de Límite de Payload en Importador de Sheets & Diagnóstico Transparente de Incidentes**:
|
||||
- **Incidencias y Mejoras**:
|
||||
1. `frontend/src/app.js`: Elevado límite de `express.json` y `express.urlencoded` de 100 KB por defecto a 50 MB (`{ limit: '50mb' }`), resolviendo el error `PayloadTooLargeError: request entity too large: expected 154166, length 154166, limit 102400` que provocaba HTTP 500 al enviar la matriz de filas preseleccionadas en `/admin/google_sheets_import`.
|
||||
2. Manejo de Incidentes y Diagnóstico Transparente: Reemplazo total de la pantalla genérica de error por una interfaz estructurada con código de ticket único (`INC-YYYYMMDD-XXXX`), diagnóstico descriptivo clasificado, sección técnica de diagnóstico colapsable (Ruta, Timestamp, Usuario actuante, IP, Stack trace), botón para copiar reporte a soporte IT y enlace directo a la Auditoría Institucional.
|
||||
3. `backend/app/routes/api/admin.py`: Nuevo endpoint `/api/v1/admin/log-error` para registrar incidentes técnicos no controlados del frontend directamente en `AuditLog` (`action='SYSTEM_ERROR'`, `module='system'`).
|
||||
4. `backend/app/routes/api/dashboard.py`: Instrumentada auditoría completa en `sync_google_sheets` para registrar tanto importaciones exitosas (`SHEETS_IMPORT`) como fallos (`SHEETS_IMPORT_ERROR`) con desglose de estadísticas y excepciones.
|
||||
- **Sprint v3.5.0: Cierre Formal del MVP de Bedelía & Adopción del Arnés SDD / IA**:
|
||||
- **Metodología y Arnés de Ingeniería con IA (Apuntes Día 1, 2 y 3)**:
|
||||
1. Creación de la Skill de SDD (`.agents/skills/sdd/SKILL.md`) con las plantillas de `spec.md`, `plan.md`, `tasks.md` y sintaxis formal **EARS** en español.
|
||||
2. Creación de comandos reutilizables de agentes en `.opencode/commands/` (`sdd-spec`, `sdd-plan`, `sdd-tasks`).
|
||||
3. Definición de roles de subagentes en `.opencode/agents/`: Coordinator, Planner, Implementer, Reviewer (QA).
|
||||
4. Integración del arnés en `AGENTS.md`.
|
||||
- **Diagnóstico y Cierre de Brecha del MVP**:
|
||||
- Se identificó la causa raíz de la percepción de "estar lejos": el *Scope Creep* sin especificación formal de cierre y la falta de exportación/impresión de carteleras que forzaba a Bedelía a recurrir al Excel para imprimir o compartir partes con portería y docentes.
|
||||
- Se formalizó la primera especificación oficial del proyecto en `specs/001-cierre-mvp-bedelia/` (`spec.md`, `plan.md`, `tasks.md`), delimitando de forma estricta los Requisitos Funcionales en **EARS** y estableciendo un perímetro cerrado de **Fuera de Alcance**.
|
||||
- **Implementación Técnica**:
|
||||
1. `frontend/src/routes/schedule.js`: Endpoint `/schedule/export_csv` con codificación UTF-8 BOM (`\uFEFF`) y delimitadores `;` para apertura nativa e inmediata en Microsoft Excel en español.
|
||||
2. `frontend/views/schedule/today.html`: Botones directos `[ Excel / CSV ]` e `[ Imprimir ]`, acompañados de estilos CSS `@media print` que formatean la grilla de asignaciones en hoja A4 limpia con membrete institucional oficial de UniCABA.
|
||||
3. `frontend/views/dashboard/dashbede.html`: Accesos rápidos en el Launchpad operativo de Bedelía para descargar la planilla del día e imprimir en 1 clic.
|
||||
- **Calidad y Bump Semántico (Principio 9)**:
|
||||
- 52 pruebas de backend ejecutadas con 100% de éxito en pytest (`52 passed`).
|
||||
- Versión incrementada a `v3.5.0` en `package.json`, `app.js`, `__init__.py`, `setup.py` y `openapi.py`.
|
||||
|
||||
- **Sprint v3.5.1: Exportación y Replicación Moodle Producción a Local con Usuarios y Emails Reales**:
|
||||
- **Especificación SDD (`specs/002-moodle-export-sync/`)**: Creados `spec.md` (6 RF en EARS), `plan.md` y `tasks.md` (todas las tareas completadas).
|
||||
- **Extracción Híbrida y Concurrente con Emails Reales**:
|
||||
- `scripts/moodle_replicator.py` se autentica en `https://campus.udelaciudad.edu.ar/` con `logintoken` dinámico.
|
||||
- Obtiene la nómina masiva estructurada vía `/user/action_redir.php` (`download_participants&dataformat=json`).
|
||||
- Consulta de forma concurrente (ThreadPool con 10 workers) los perfiles de los usuarios (`user/view.php`) extrayendo sus correos personales y reales (`@gmail.com`, `@hotmail.com`, etc.), eliminando cualquier generación de emails inventados.
|
||||
- Normalización fonética/ortográfica sin acentos (`normalize_name`) para vincular con 100% de precisión docentes y estudiantes entre HTML y JSON.
|
||||
- **Reglas de Acceso y DNI Determinístico**:
|
||||
- DNI de 8 dígitos determinístico derivado del ID de Moodle (`90{moodle_id:06d}`), asignado idénticamente como `username` y `password` para pruebas locales.
|
||||
- Preservado el DNI y correo real de Carlos Tello (`34247025`, `carlostellocba@gmail.com`).
|
||||
- **Carga en Moodle Local (`10.0.0.207`)**:
|
||||
- Creación y actualización de usuarios mediante Moodle REST API (`core_user_create_users`, `core_user_update_users`).
|
||||
- 504 matriculaciones completadas exitosamente en los 4 cursos oficiales:
|
||||
* Carrera Lic. en Tecnologías Digitales (CCC): ID Prod 922 -> ID Local 19 (194 alumnos).
|
||||
* ASIG00124 - Sistemas Digitales_2/2026: ID Prod 5311 -> ID Local 16 (131 alumnos y 2 profesores).
|
||||
* ASIG00126 - Seguridad de la Información_2/2026: ID Prod 5313 -> ID Local 17 (138 alumnos y 2 profesores).
|
||||
* ASIG00127 - Programación de Vanguardia - E1_2/2026: ID Prod 5314 -> ID Local 18 (41 alumnos y 2 profesores).
|
||||
- Desactivada la política restrictiva de contraseñas (`passwordpolicy=0`) en el entorno de pruebas local para permitir contraseñas numéricas idénticas al DNI.
|
||||
- Verificación exitosa de login de estudiante en `http://10.0.0.207/moodle/login/index.php`.
|
||||
- **Skill de Automatización**: Creada `.agents/skills/moodle-replicator/SKILL.md` con manual operativo y comandos CLI.
|
||||
|
||||
- **Sprint v3.5.2: Replicación Completa de 16 Cursos, User-Agent Mozilla/5.0 y Fix de Credenciales**:
|
||||
- **Catálogo Completo de la Carrera (16 Cursos)**:
|
||||
- Se identificaron y replicaron la totalidad de las 15 materias de la Licenciatura en Tecnologías Digitales (1/2025, 2/2025, 1/2026 y 2/2026) más el curso de la carrera (Local 19).
|
||||
- Resuelto el caso de alumnos como `90010202` (Carlos Guillermo Terzano): ahora cuenta con sus 6 materias reales cursadas (Local 4, 5, 8, 9, 10, 11) además de la carrera.
|
||||
- Carlos Tello (`34247025`) matriculado en las 15 asignaturas y la carrera.
|
||||
- Más de 1.100 matriculaciones procesadas y validadas con 100% de éxito.
|
||||
- **Identificación y Asignación de Todos los Docentes**:
|
||||
- Extraídos y asignados todos los profesores reales con rol `editingteacher` (ID 3) y correos institucionales `@udelaciudad.edu.ar`.
|
||||
- **Cabecera HTTP y User-Agent**:
|
||||
- Forzado estrictamente el encabezado `User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)` en todas las solicitudes al campus para evitar alertas por `python-requests`.
|
||||
- **Sincronización de Contraseña Local (Fix 34247025)**:
|
||||
- Se corrigió la contraseña del usuario `34247025` restableciéndola a `34247025` idéntica al DNI en Moodle local. Verificado inicio de sesión exitoso.
|
||||
|
||||
- **Sprint v3.5.3: Importación de Roles Moodle-App, Limpieza Total de Admin y Purga de Cursos**:
|
||||
- **Sincronización RBAC de Roles Moodle a PostgreSQL de la App (`classrooms_db`)**:
|
||||
- Desarrollado `scripts/import_moodle_to_app.py` y bandera `--sync-app` en `moodle_replicator.py`.
|
||||
- Mapeo unívoco: Moodle `editingteacher` -> App `Docente` (`role_id=2`), Moodle `student` -> App `Alumno` (`role_id=6`).
|
||||
- Importados **653 usuarios únicos** (15 Docentes y 640 Alumnos) a la base de datos de producción con contraseñas PBKDF2 coincidentes con el DNI, habilitando de inmediato la asignación de comisiones, reservas e inscripciones.
|
||||
- **Desmatriculación de Cuenta Admin en Moodle Local (`10.0.0.207`)**:
|
||||
- Removidas todas las matriculaciones de `admin` en cursos académicos y generales (quedando con 0 enrolments).
|
||||
- **Sprint v3.5.4: Conexión Moodle API, Login Delegado y Sincronización Moodle -> Edu Space**:
|
||||
- **Habilitación de Web Services para Tokens de Usuario en Moodle Local (`10.0.0.207`)**:
|
||||
- Asignada la capability `moodle/webservice:createtoken` al rol 7 (`user` / usuario autenticado) en `mdl_role_capabilities`.
|
||||
- Habilitado `enablemobilewebservice = 1` y servicio `moodle_mobile_app` (`enabled = 1`).
|
||||
- Verificada la emisión de tokens exitosa para usuarios individuales (incluyendo `34247025`) tanto contra `moodle_api` como contra `moodle_mobile_app`.
|
||||
- **Conexión de Admin Edu Space con Moodle Local**:
|
||||
- Configurado el token `810428346d3601c68a37a315fcba8d4391629f46` de `moodle_api` en `system_settings` de `classrooms_db`.
|
||||
- Habilitada `auth_moodle_enabled = 'true'` y `moodle_server_url = 'http://10.0.0.207/moodle'`.
|
||||
- Adaptado el endpoint de autenticación `/api/v1/auth/moodle` para autenticar con `moodle_api` (con fallback a `moodle_mobile_app`) y hacer matching de cuenta local por número de documento (DNI).
|
||||
- **Sincronización Bidireccional Moodle -> Edu Space**:
|
||||
- Agregado el endpoint administrativo `POST /api/v1/admin/moodle/sync-from-moodle`.
|
||||
- Incorporados los métodos `get_courses()`, `get_categories()` y `sync_from_moodle_to_app()` en `MoodleClient`.
|
||||
- **Sprint v3.5.5: Autenticación por API Key para Moodle, Purga de Tareas y Hardening**:
|
||||
- **Purga de Tareas de Sincronización Residuales**:
|
||||
- Eliminadas las 6 tareas pendientes residuales de prueba (#1 a #6) en la tabla `moodle_sync_tasks` de `classrooms_db` en `10.0.0.217`, dejando la cola limpia en 0 registros.
|
||||
- **Ampliación de Funciones Web Services en Moodle Local (`10.0.0.207`)**:
|
||||
- Asignadas al servicio `moodle_api` las funciones `enrol_manual_unenrol_users`, `core_enrol_unenrol_user_enrolment`, `core_role_assign_roles` y `core_role_unassign_roles`, completando el catálogo a 15 funciones esenciales.
|
||||
- **Seguridad por Restricción de Red (IP Restriction)**:
|
||||
- Fijada la restricción de red `iprestriction = '10.0.0.0/24'` en `mdl_external_tokens`, asegurando que solo el tráfico interno institucional pueda utilizar los tokens de Moodle.
|
||||
- **Autenticación por API Key Institucional en Admin Edu Space**:
|
||||
- Creado mecanismo para autenticar endpoints de sincronización (`/settings/moodle/sync` y `/moodle/sync-from-moodle`) mediante `X-API-Key` institucional de 64 caracteres hex.
|
||||
- Generada y almacenada la clave API institucional cifrada con Fernet en `system_settings` (`classrooms_db`).
|
||||
- Agregados endpoints para consulta y regeneración de clave API (`/api/v1/admin/settings/moodle/api-key`).
|
||||
|
||||
- **Sprint v3.5.6: Principio 10 de Tolerancia Cero a Errores de Código, Robustez en SystemSetting y Replicador**:
|
||||
- **Principio 10 de la Constitución**:
|
||||
- Incorporada regla mandatoria en `docs/constitution.md`, `AGENTS.md`, `.agents/skills/sdd/SKILL.md`, `.agents/skills/deploy/SKILL.md` y `.opencode/agents/` (`coordinator.md`, `implementer.md`, `reviewer.md`).
|
||||
- Es estrictamente inadmisible declarar una tarea o sprint como terminado o completado si persisten errores en el código o en el analizador de la IDE (`@[current_problems]`).
|
||||
- **Reparación de Tipos en Replicador Moodle**:
|
||||
- Ajustado casteo a entero `int(course_meta['local_id'])` y `int(u.get('role_id', 5))` en `scripts/moodle_replicator.py`.
|
||||
- **Robustez Híbrida en `SystemSetting`**:
|
||||
- Implementado descriptor híbrido `_hybrid_setting_method` para `get_decrypted_value` y `get_masked_value`, permitiendo indistintamente la invocación como método de clase o de instancia sin errores de argumentos.
|
||||
- **Resolución de Condición de Carrera en Tests de SQLite**:
|
||||
- Añadida espera activa de finalización de workers en `test_05_api_async_job_submission_and_polling` para evitar bloqueos de base de datos en `tearDown()`.
|
||||
- **Validación Automatizada**:
|
||||
- 52/52 tests pasando en verde al 100% (`pytest tests -v`).
|
||||
|
||||
- **Sprint v3.5.7: Principio 11 de la Constitución — Estándares Modernos de APIs (FastAPI/Pydantic) e Integración con Modelos de IA (LLMs)**:
|
||||
- **Arquitectura Modular en 4 Capas**:
|
||||
- Desacople estricto: `main.py` (bootstrap/registro), `routers/` (endpoints agrupados por dominio con prefijos y tags para Swagger), `schemas/` (contratos con Pydantic `BaseModel`), `storage.py` (acceso a persistencia). Prohibida la lógica de negocio en el frontend o en archivos monolíticos.
|
||||
- **Tipado Fuerte y Validación Pydantic**:
|
||||
- Uso obligatorio de `Field` para validaciones declarativas (`min_length`, `max_length`, `gt`, `ge`, regex).
|
||||
- Distinción estricta de Path Parameters (obligatorios) y Query Parameters (opcionales tipados con defaults).
|
||||
- Manejo y respuesta automática de error `422 Unprocessable Entity` detallando el campo exacto.
|
||||
- **Semántica HTTP y Excepciones Controladas**:
|
||||
- Uso de códigos de estado HTTP semánticos (`201 Created` en POST, `200 OK`, `204 No Content`).
|
||||
- Prohibido retornar `null` o respuestas vacías ante fallos: levantar `HTTPException` controladas con detalle descriptivo (404, 400, 409).
|
||||
- **Documentación Interactiva Automática**:
|
||||
- Contratos OpenAPI expuestos en `/docs` (Swagger UI) con capacidades de prueba en vivo (*Try it out*).
|
||||
- **Integración Asíncrona con Modelos de IA Locales (LLMs) & Asistente Virtual**:
|
||||
- **Pestaña en Configuración Global**: Planificada en `ROADMAP.md` y UI administrativa para configurar URL del servidor local (Ollama, llama.cpp), modelo, token y timeout para el futuro asistente virtual de la app.
|
||||
- **Cliente Asíncrono no Bloqueante**: Uso mandatorio de `httpx.AsyncClient` con `async def` / `await` para inferencias concurrentes sin bloquear el servidor.
|
||||
- **Timeout Generoso**: Configurar timeout de 600 segundos previendo carga de modelos en VRAM o prompts extensos.
|
||||
- **Formato Estándar de Roles**: Historial estructurado bajo `role: "system" | "user" | "assistant"` y `content: prompt`.
|
||||
- **Actualización Documental Completa**:
|
||||
- Sincronizados `docs/constitution.md` (Principio 11), `AGENTS.md`, `.agents/skills/sdd/SKILL.md`, `.opencode/agents/` (`coordinator.md`, `planner.md`, `implementer.md`, `reviewer.md`), `ROADMAP.md` (Fase 7) y `MEMORY.md`.
|
||||
|
||||
- **Sprint v3.6.0: Migración Completa de Flask API a FastAPI ASGI (Principio 11)**:
|
||||
- **Reemplazo Arquitectónico**:
|
||||
- Backend Core migrado a FastAPI con arquitectura de 4 capas: `backend/main.py` (FastAPI bootstrap), `backend/routers/` (APIRouters modulares por dominio), `backend/schemas/` (Pydantic v2 BaseModels con validación declarativa) y `backend/database.py` (persistencia relacional).
|
||||
- Módulos migrados a FastAPI: `version`, `auth`, `classrooms`, `reservations`, `students`, `dashboard`, `optimizer` y `genetic`.
|
||||
- Documentación interactiva OpenAPI v3 expuesta nativamente en `/docs` (Swagger UI) y `/redoc`.
|
||||
- Puente de retrocompatibilidad y cero regresión implementado mediante `a2wsgi` para asegurar interoperabilidad fluida con Gunicorn, Uvicorn y el frontend BFF Express.js.
|
||||
- **Calidad y Verificación**:
|
||||
- 57 tests automatizados ejecutados y aprobados al 100% en pytest (`57 passed`).
|
||||
- Cero errores en linter, tipos y compilación estática (`@[current_problems]`).
|
||||
- **Despliegue Continuo**:
|
||||
- Bump semántico a `v3.6.0`.
|
||||
- Actualización remota y reinicio de servicios en el servidor LXC `10.0.0.217` (`https://eduspace.oemspot.com.ar`).
|
||||
|
||||
|
||||
- **Consolidación General y Actualización Documental al 04/11/2026 (v3.8.56)**:
|
||||
- **Arquitectura 100% FastAPI ASGI**: Erradicación definitiva de cualquier componente Flask legacy; FastAPI 0.115+ con Uvicorn, OpenAPI (/docs, /redoc), Pydantic v2 y SQLAlchemy 2.0 nativo.
|
||||
- **Copiloto Institucional UdeCi & RAG Embebido (Specs 009 & 010)**: Integración asíncrona no bloqueante (httpx 600s) con LLMs locales (Qwen 30B / Llama.cpp / Ollama), base de conocimiento vectorial institucional (KnowledgeChunk), inyección profunda de contexto en tiempo real de PostgreSQL (LiveContextService), prompt security perimetral y UX adaptativa (bottom-sheet en móviles / dock en desktop).
|
||||
- **Servidor MCP Institucional & Spotlight Didáctico (Spec 011)**: Endpoints Model Context Protocol bajo /api/v1/mcp y asistente interactivo guiado (GuideService).
|
||||
- **Consola de Recepción, Multi-Serial COM y Reconocimiento Universal de DNI (Spec 013)**: Web Serial API para hasta 4 lectores serie simultáneos con auto-reconexión plug-and-play, buffer de 380ms para códigos de alta densidad, parser universal de DNI argentino (Renaper 2026 QR+JWT, 2012 PDF417, 2009 F/M, Mi Argentina y número directo), normalización de teclado español, feedback auditivo (Web Audio API) y bitácora de acceso inmutable.
|
||||
- **Credencial Digital QR Dinámica Anti-Captura (Spec 012)**: Auto-rotación del código QR cada 3 segundos, ventana estricta de gracia de 6 segundos contra capturas de pantalla, disponible en modal global, vista de perfil y carnet universitario completo.
|
||||
- **Módulo de Beneficios y Convenios (Spec 012)**: ABM y catálogo de descuentos para la comunidad UniCABA con permisos RBAC dedicados.
|
||||
- **Suite de Pruebas Automatizadas**: 131 de 131 pruebas ejecutadas y superadas con éxito (100% passed en pytest).
|
||||
- **Sincronización Total de Documentación**: README.md y CHANGELOG.md completamente actualizados al día de hoy.
|
||||
|
||||
## Próximos pasos
|
||||
1. Monitorear los endpoints ASGI en producción bajo concurrencia operativa.
|
||||
2. Implementar la pestaña de Asistente IA en la Configuración Global administrativa (`ROADMAP.md` Fase 7).
|
||||
3. Continuar con el roadmap hacia la Fase 6 de hardening y orquestación de servicios en Docker.
|
||||
@@ -1,273 +1,449 @@
|
||||
# Panel de Administración Edu-Space (UniCABA)
|
||||
|
||||
Plataforma integral de gestión áulica, asignación de espacios, control de horarios, seguimiento académico y reservas para la **Universidad de la Ciudad de Buenos Aires (UniCABA)**.
|
||||
Plataforma web integral de gestión de espacios áulicos, orquestación académica, control de accesos físicos, seguimiento pedagógico y asistencia inteligente para la **Universidad de la Ciudad de Buenos Aires (UniCABA)**. Diseñada para reemplazar el uso de planillas Excel en Bedelía, sincronizar calendarios en tiempo real, validar identidades mediante credenciales digitales y hardware serial, y conectarse fluidamente con **Moodle 4.1**, **Google Workspace** y servidores de **Inteligencia Artificial (LLMs)**.
|
||||
|
||||
El proyecto se basa en una arquitectura **desacoplada (Frontend / Backend)** en formato monorepo.
|
||||
El proyecto se basa en una arquitectura **desacoplada (Backend Core REST API + Frontend BFF)** en formato monorepo de alto rendimiento.
|
||||
|
||||
**Versión Actual:** `3.1.0` (Fases 0 a 5 completadas, Fase 5.1 Bedelía UX & ABMs finalizada)
|
||||
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
|
||||
**Versión Actual:** `3.8.56` (Consolidada — FastAPI ASGI Pura, Control de Acceso QR / DNI, Multi-Serial COM, Asistente RAG UdeCi, Servidor MCP y Beneficios)
|
||||
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
|
||||
**Entorno de Producción:** [https://eduspace.oemspot.com.ar](https://eduspace.oemspot.com.ar) (Servidor LXC Proxmox `10.0.0.217`)
|
||||
**Suite de Pruebas Automatizadas:** 131/131 pruebas superadas (100% passed en `pytest`)
|
||||
|
||||
---
|
||||
|
||||
## 🗺️ Estado del Roadmap MVP
|
||||
## 🗺️ Estado del Roadmap & Fases del Sistema
|
||||
|
||||
```
|
||||
Fase 0: Desacople y Arquitectura Base [████████████████████] 100% (Completado)
|
||||
Fase 1: Paridad Legacy y Estabilización [████████████████████] 100% (Completado)
|
||||
Fase 2: Co-docencia y Matriz Conflictos [████████████████████] 100% (Completado)
|
||||
Fase 3: Hitos Evaluativos y Calificaciones[████████████████████] 100% (Completado)
|
||||
Fase 4: UI/UX Drag & Drop e Impersonación[████████████████████] 100% (Completado)
|
||||
Fase 5: Integración Auth, Email & Moodle [████████████████████] 100% (Completado)
|
||||
Fase 5.1: Bedelía UX, ABMs y Purga Datos [████████████████████] 100% (Completado)
|
||||
Fase 6: Despliegue Producción e Infraest.[███████░░░░░░░░░░░░░] 35% (En Curso)
|
||||
```text
|
||||
Fase 0: Desacople y Arquitectura Base [████████████████████] 100% (Completado)
|
||||
Fase 1: Paridad Legacy y Estabilización [████████████████████] 100% (Completado)
|
||||
Fase 2: Co-docencia y Matriz de Conflictos Integral [████████████████████] 100% (Completado)
|
||||
Fase 3: Hitos Evaluativos, Gradebook y Actas [████████████████████] 100% (Completado)
|
||||
Fase 4: UI/UX Drag & Drop e Impersonación Segura [████████████████████] 100% (Completado)
|
||||
Fase 5: Integración Auth (Google/Moodle/Local/Emerg.) [████████████████████] 100% (Completado)
|
||||
Fase 5.1: Bedelía UX, Circuito 9 Pasos y Reset Seguro [████████████████████] 100% (Completado)
|
||||
Fase 6: Despliegue Producción Proxmox LXC (Nginx/SSL) [████████████████████] 100% (Completado v3.5.0)
|
||||
Fase 7: Asistente IA UdeCi, RAG Embebido y MCP Server [████████████████████] 100% (Completado v3.8.25-28)
|
||||
Módulo: Recepción, Multi-Serial COM y DNI Renaper [████████████████████] 100% (Completado v3.8.50-56)
|
||||
Módulo: Credencial Digital QR Anti-Captura & Perfil [████████████████████] 100% (Completado v3.8.45-54)
|
||||
Módulo: Convenios y Beneficios Institucionales [████████████████████] 100% (Completado v3.8.39-44)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏛️ Sede Institucional y Ubicaciones
|
||||
* **Sede Central UniCABA:** Tte. Gral. Juan Domingo Perón 802, Ciudad Autónoma de Buenos Aires (CABA) — Aulas de grado, auditorio principal y laboratorios distribuidos desde Planta Baja (Piso 0) hasta el 4.° Piso.
|
||||
* **Campus Virtual:** Espacio áulico digital integrado (Microsoft Teams / Moodle) configurado con **capacidad ilimitada ($\infty$)**.
|
||||
|
||||
* **Sede Central UniCABA:** Tte. Gral. Juan Domingo Perón 802, Ciudad Autónoma de Buenos Aires (CABA) — Aulas de grado, auditorio principal y laboratorios distribuidos desde Planta Baja (Piso 0 / PB) hasta el 4.° Piso.
|
||||
* **Campus Virtual:** Espacio áulico digital integrado (Google Meet / Microsoft Teams / Moodle) configurado con **capacidad ilimitada ($\infty$)** y sin restricciones de colisión física.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Arquitectura del Proyecto (Monorepo)
|
||||
## 🏗️ Arquitectura del Proyecto (Monorepo Desacoplado)
|
||||
|
||||
El repositorio implementa un patrón desacoplado en formato monorepo compuesto por la **Core API (Backend)**, la capa de mediación y vistas **BFF (Frontend)**, herramientas unificadas de despliegue, auditoría automatizada y flujos de CI/CD:
|
||||
El repositorio implementa un patrón desacoplado en 4 capas estrictas compuesto por la **Core REST API (FastAPI ASGI)**, la capa de mediación y vistas **BFF (Node.js / Express)**, herramientas unificadas de despliegue, scripts de replicación y pipelines de integración continua:
|
||||
|
||||
```text
|
||||
/
|
||||
├── backend/ # Capa Core API (Python 3.10+ / Flask / SQLAlchemy)
|
||||
│ ├── app/ # Lógica de negocio y arquitectura desacoplada
|
||||
│ │ ├── models/ # Modelos ORM (User, Role, Classroom, Reservation, etc.)
|
||||
│ │ ├── routes/api/ # Endpoints REST JSON v1 (/auth, /classrooms, /admin, etc.)
|
||||
│ │ ├── schemas/ # DTOs y validación de contratos (Pydantic v2)
|
||||
│ │ ├── services/ # Servicios de dominio (JWT, Email SMTP, Moodle, Queue)
|
||||
│ │ └── security/ # Pipeline de filtros y validación stateless de JWT
|
||||
│ ├── tests/ # Suite activa de pruebas unitarias y de integración (pytest)
|
||||
│ ├── init_db.py # Inicializador idempotente de esquema, roles RBAC y semillas
|
||||
│ ├── backup_db.sh # Generador automatizado de backups para PostgreSQL
|
||||
│ ├── classrooms_db.sql # Snapshot integral de base de datos para despliegue
|
||||
│ ├── wsgi.py # Entrada WSGI para ejecución con Gunicorn
|
||||
│ └── requirements.txt # Dependencias Python auditadas (0 vulnerabilidades / CVEs)
|
||||
├── backend/ # Capa Core API (Python 3.12+ / FastAPI ASGI / SQLAlchemy 2.0)
|
||||
│ ├── main.py # Inicializador FastAPI ASGI, docs OpenAPI (/docs, /redoc), CORS
|
||||
│ ├── database.py # Motor relacional SQLAlchemy 2.0 (SessionLocal, get_db)
|
||||
│ ├── routers/ # Endpoints REST modulares por dominio (/api/v1/)
|
||||
│ │ ├── auth.py # Autenticación JWT, Google OAuth, Moodle delegado y perfil
|
||||
│ │ ├── version.py # Endpoints públicos /version y /health
|
||||
│ │ ├── classrooms.py # ABM y catálogo de aulas físicas y virtuales
|
||||
│ │ ├── buildings.py # Gestión de sedes, edificios y pisos dinámicos
|
||||
│ │ ├── reservations.py # Asignación de espacios, cartelera y validación Drag & Drop
|
||||
│ │ ├── academic.py # Carreras, asignaturas multi-carrera y comisiones
|
||||
│ │ ├── admin.py # Gestión institucional, usuarios, roles RBAC y auditoría
|
||||
│ │ ├── students.py # Inscripciones y consulta académica del alumno
|
||||
│ │ ├── dashboard.py # Agregaciones, percentiles y sincronización Sheets
|
||||
│ │ ├── optimizer.py # Algoritmo genético predictivo de optimización áulica
|
||||
│ │ ├── ai_chat.py # Endpoints del asistente UdeCi, inferencia y contexto en vivo
|
||||
│ │ ├── mcp.py # Servidor Model Context Protocol institucional
|
||||
│ │ ├── benefits.py # Catálogo y ABM de convenios y beneficios
|
||||
│ │ └── reception.py # Consola de recepción, escaneo QR y validación de DNI
|
||||
│ ├── schemas/ # DTOs y validación de contratos (Pydantic v2 BaseModel)
|
||||
│ ├── app/ # Lógica de dominio y persistencia
|
||||
│ │ ├── models/ # Modelos ORM puros SQLAlchemy 2.0 (User, Role, Reservation, etc.)
|
||||
│ │ └── services/ # Servicios de dominio especializados:
|
||||
│ │ ├── argentine_dni_parser.py # Parser universal de DNI (Renaper 2026/2012/2009/MiArg)
|
||||
│ │ ├── qr_security_service.py # Generación y validación de QR dinámico anti-captura
|
||||
│ │ ├── live_context_service.py # Inyección de contexto real de BD en prompts IA
|
||||
│ │ ├── rag_service.py # Recuperación semántica sobre normativas de UniCABA
|
||||
│ │ ├── prompt_security.py # Blindaje anti-jailbreak e inyecciones de prompt
|
||||
│ │ ├── guide_service.py # Asistencia interactiva guiada (Spotlights en UI)
|
||||
│ │ ├── sheets_importer.py # Importador multi-carrera y por rango de Google Sheets
|
||||
│ │ ├── moodle_client.py # Cliente HTTP REST para Moodle 4.1 Web Services
|
||||
│ │ ├── moodle_queue_service.py # Cola asíncrona resiliente y Dead Letter Queue (DLQ)
|
||||
│ │ ├── email_service.py # Notificaciones SMTP con credenciales cifradas (Fernet)
|
||||
│ │ ├── gradebook_service.py # Matriz de calificaciones y actas inmutables
|
||||
│ │ ├── optimizer_service.py # Optimizador heurístico basado en algoritmo genético
|
||||
│ │ ├── weather_service.py # Widget meteorológico del campus en CABA
|
||||
│ │ └── audit_service.py # Trazabilidad y registro inmutable de auditoría
|
||||
│ ├── tests/ # Suite de 131 pruebas automatizadas unitarias y de integración
|
||||
│ ├── init_db.py # Inicializador idempotente de esquema, roles RBAC y semillas
|
||||
│ ├── classrooms_db.sql # Snapshot integral de base de datos para despliegue
|
||||
│ └── requirements.txt # Dependencias auditadas (FastAPI, Uvicorn, SQLAlchemy 2.0, Pydantic)
|
||||
│
|
||||
├── frontend/ # Backend-For-Frontend BFF (Node.js 20 LTS / Express)
|
||||
│ ├── src/ # Capa servidora de mediación web
|
||||
│ │ ├── app.js # Servidor Express, seguridad Helmet, rate-limiting
|
||||
│ │ ├── controllers/ # Controladores de orquestación y mediación
|
||||
│ │ ├── middlewares/ # Sesión por Cookie HttpOnly, JWT injection y RBAC
|
||||
│ │ ├── routes/ # Enrutamiento web (auth, schedule, classrooms, admin)
|
||||
│ │ └── services/ # Cliente Axios centralizado hacia Flask API
|
||||
│ ├── views/ # Plantillas y componentes dinámicos en Nunjucks (.html)
|
||||
│ │ ├── admin/ # Paneles de gestión institucional y configuración
|
||||
│ │ ├── classrooms/ # Catálogo de aulas y visualización de sedes
|
||||
│ │ ├── schedule/ # Cronograma de comisiones, reservas y calendario
|
||||
│ │ ├── my_subjects/ # Libreta de calificaciones, hitos evaluativos y cursada
|
||||
│ │ └── partials/ # Componentes reutilizables, modales y navegación
|
||||
│ ├── public/ # Assets estáticos (CSS responsive 720p/1080p, JS cliente)
|
||||
│ └── package.json # Dependencias y manifiesto de Node.js
|
||||
├── frontend/ # Backend-For-Frontend BFF (Node.js 20 LTS / Express 5)
|
||||
│ ├── src/ # Capa servidora de mediación web
|
||||
│ │ ├── app.js # Servidor Express, Helmet, rate-limit, cookies HttpOnly
|
||||
│ │ ├── middlewares/ # JWT injection, sesión HttpOnly, RBAC y control de acceso
|
||||
│ │ └── routes/ # Enrutamiento web (auth, schedule, classrooms, admin, reception)
|
||||
│ ├── views/ # Plantillas dinámicas en Nunjucks (.html)
|
||||
│ │ ├── admin/ # Paneles de gestión institucional, auditoría e importador
|
||||
│ │ ├── classrooms/ # Catálogo de aulas físicas y virtuales
|
||||
│ │ ├── schedule/ # Cronograma de comisiones, reservas, cartelera y calendario
|
||||
│ │ ├── dashboard/ # Dashboards modularizados por rol (admin, bedelia, prof, alum)
|
||||
│ │ ├── reception/ # Consola de recepción y escaneo de credenciales
|
||||
│ │ ├── credential/ # Carnet universitario digital completo y modal interactivo
|
||||
│ │ ├── benefits/ # Portal de convenios y beneficios institucionales
|
||||
│ │ └── partials/ # Asistente UdeCi, spotlights, navegación y modales globales
|
||||
│ ├── public/ # Assets estáticos (Bootstrap 5, Vanilla CSS, JS cliente)
|
||||
│ │ ├── js/serial-scanner.js # Módulo Web Serial API para hasta 4 lectores COM concurrentes
|
||||
│ │ ├── js/qrcode.min.js # Generador local autónomo de códigos QR
|
||||
│ │ └── css/ # Temas Claro / Oscuro de alto contraste (WCAG AA)
|
||||
│ └── package.json # Dependencias y manifiesto de Node.js
|
||||
│
|
||||
├── install.sh # Instalador nativo unificado para Linux / Proxmox LXC
|
||||
├── security_audit.bat # Suite automatizada de auditoría (SAST, SCA, DAST)
|
||||
├── .gitea/workflows/ # Pipelines de integración continua (CI/CD en Gitea)
|
||||
├── docs/ # Especificaciones técnicas, auditorías y changelogs
|
||||
├── ROADMAP_MVP.md # Plan de evolución, estadios y fases del proyecto
|
||||
├── SECURITY_AUDIT_REPORT.md # Informe formal de auditoría y hardening
|
||||
└── README.md # Documentación general y guía operativa
|
||||
├── specs/ # Especificaciones formales SDD (Specs 001 a 013 en EARS)
|
||||
├── scripts/ # Automatizaciones (moodle_replicator.py, importador RBAC)
|
||||
├── install.sh # Instalador desatendido unificado para Linux / Proxmox LXC
|
||||
├── security_audit.bat # Suite automatizada de auditoría de seguridad (SAST, SCA, DAST)
|
||||
├── AGENTS.md # Directivas de ingeniería de software, arquitectura y límites
|
||||
├── docs/constitution.md # Principios de desarrollo de software innegociables
|
||||
└── README.md # Documentación general y manual técnico del sistema
|
||||
```
|
||||
|
||||
### 🐍 Backend Core API (Python + Flask)
|
||||
- Funciona exclusivamente como una **REST API** que expone endpoints bajo `/api/v1/` retornando **JSON**.
|
||||
- Encargado de la persistencia de datos (SQLAlchemy / PostgreSQL o SQLite), lógica de negocio, servicio de tokens JWT (Access & Refresh), matriz RBAC, y algoritmos de optimización heurística (Módulo Predictivo).
|
||||
- **Prohibido** retornar HTML o utilizar Jinja2/`render_template` en este entorno.
|
||||
### ⚡ Backend Core API (Python 3.12+ / FastAPI / SQLAlchemy 2.0)
|
||||
- **100% Nativo ASGI puro** ejecutado con **Uvicorn**, con arquitectura desacoplada en 4 capas eliminando cualquier rastro de frameworks monolíticos legacy.
|
||||
- Expone contratos RESTful bajo `/api/v1/` retornando exclusivamente **JSON**.
|
||||
- Validación estricta de payloads con **Pydantic v2** (`BaseModel`, `Field`) respondiendo automáticamente con códigos `422 Unprocessable Entity` detallando campos exactos.
|
||||
- Documentación interactiva autogenerada en vivo en `/docs` (Swagger UI), `/redoc` y contratos OpenAPI v3 en `/openapi.json`.
|
||||
- Persistencia optimizada con **SQLAlchemy 2.0** sobre PostgreSQL 15 (en producción) y SQLite (en suites de pruebas).
|
||||
- Autenticación mediante tokens **PyJWT** (HS256) stateless con Access Tokens, Refresh Tokens y tokens dinámicos anti-captura.
|
||||
- Cifrado simétrico de datos sensibles en reposo mediante **Fernet** (`cryptography`).
|
||||
- Inferencia asíncrona no bloqueante hacia servidores de IA locales o remotos empleando **`httpx.AsyncClient`** con timeouts generosos (600 segundos).
|
||||
|
||||
### 🟢 Frontend BFF (Node.js + Express)
|
||||
- Aplicación Backend-For-Frontend que renderiza las vistas para el cliente mediante **Nunjucks**.
|
||||
- Gestiona la sesión segura del usuario almacenando el token JWT recibido de Flask en una **Cookie HttpOnly**.
|
||||
- Actúa como proxy de conexión con el Backend de Python empleando **Axios** (inyectando el Bearer token interceptado).
|
||||
- Blindado con **Helmet** (cabeceras de seguridad HTTP) y **express-rate-limit** para mitigar ataques de fuerza bruta.
|
||||
- Interfaz adaptativa y responsive diseñada para pantallas estándar argentinas (720p, 1366x768 y 1080p) con gráficos dinámicos (**Chart.js**).
|
||||
### 🟢 Frontend BFF (Node.js 20+ LTS / Express 5)
|
||||
- Servidor de mediación Backend-For-Frontend que renderiza interfaces del lado del servidor mediante **Nunjucks**.
|
||||
- Gestiona sesiones seguras almacenando el JWT en cookies `HttpOnly`, `SameSite=Lax` y `Secure` en producción.
|
||||
- Cliente **Axios** centralizado con interceptores que inyectan de forma transparente el Bearer token en cada solicitud a la FastAPI.
|
||||
- Blindaje perimetral con **Helmet** (cabeceras de seguridad HTTP) y **express-rate-limit** para protección contra ataques de fuerza bruta.
|
||||
- Soporte para hardware local en navegadores Chromium mediante la **Web Serial API** (`navigator.serial`) para control de accesos sin depender del foco del cursor.
|
||||
- Interfaz adaptativa diseñada para pantallas estándar argentinas (720p, 1366x768, 1080p y móviles) con soporte integral de **Modo Oscuro / Alto Contraste (WCAG AA)** y componentes reactivos en **Chart.js** y **FullCalendar**.
|
||||
|
||||
---
|
||||
|
||||
## 🤖 Asistente Virtual Inteligente "UdeCi" & RAG Embebido (Specs 009 & 010)
|
||||
|
||||
La plataforma cuenta con un copiloto de inteligencia artificial institucional integrado denominado **UdeCi** (*Universidad de la Ciudad*), accesible desde cualquier punto de la aplicación:
|
||||
|
||||
```text
|
||||
[ Usuario / Pregunta ] ──► [ Prompt Security & Anti-Jailbreak ] ──► [ Live Context DB (PostgreSQL) ]
|
||||
│
|
||||
[ Inferencia Asíncrona (httpx 600s) ] ◄── [ RAG Vectorial (Normativas) ] ◄────┘
|
||||
(Llama.cpp / Ollama / Qwen)
|
||||
│
|
||||
▼
|
||||
[ Respuesta Estructurada ] ──► [ UI Móvil (Bottom-Sheet) / Desktop Dock ] ──► [ Acciones & Quick Chips ]
|
||||
```
|
||||
|
||||
### 1. Inferencia Asíncrona no Bloqueante con Modelos de IA Locales
|
||||
* Integración nativa con servidores de inferencia OpenAI-compatibles (tales como **llama.cpp**, **Ollama** o **vLLM**) ejecutando modelos como *Qwen 2.5 / 3 Coder 30B*.
|
||||
* Peticiones ejecutadas de forma 100% asíncrona (`async def` con `httpx.AsyncClient`) con timeout de **600 segundos** para permitir la carga fluida de tensores en VRAM e inferencias de prompts extensos sin degradar la concurrencia del servidor.
|
||||
* Pestaña dedicada en la **Configuración Global** (`/admin/settings` -> *Asistente IA*) para parametrizar URL del servidor, modelo, temperatura, max tokens y botón para verificar conexión en caliente.
|
||||
|
||||
### 2. Arquitectura RAG Embebida (`KnowledgeChunk`)
|
||||
* Almacena normativas institucionales, estatutos de UniCABA, reglamentos de correlatividades, calendarios académicos, regímenes de regularidad y contactos oficiales en la tabla relacional `knowledge_chunks`.
|
||||
* Motor semántico con ranking de relevancia basado en frecuencia inversa de documentos (TF-IDF) y filtrado estricto por roles (`ADMIN`, `BEDELIA`, `DOCENTE`, `ALUMNO`, `PUBLIC`).
|
||||
* Respuestas precisas sobre dónde recuperar contraseñas de Moodle (`https://campus.udelaciudad.edu.ar/login/forgot_password.php`), cómo ingresar con Google Workspace o cómo tramitar equivalencias.
|
||||
|
||||
### 3. Inyección de Contexto en Vivo Profundo (`LiveContextService`)
|
||||
* Consulta la base de datos PostgreSQL en tiempo real según la identidad y rol del usuario autenticado:
|
||||
* **Alumnos:** Aula física y piso asignado para el día de hoy, materias en las que está inscripto, docentes de su comisión, porcentaje de asistencia y **calificaciones con estricta privacidad** (un alumno jamás puede consultar notas de otros pares).
|
||||
* **Docentes:** Comisiones asignadas a su cargo, aulas donde dicta clase hoy, cantidad de alumnos inscriptos y estado de cierre de actas de su cátedra.
|
||||
* **Bedelía / Admin:** Aulas libres hoy por piso, comisiones pendientes de asignación de aula física y porcentaje global de ocupación de la sede.
|
||||
|
||||
### 4. Seguridad de Prompts y Blindaje Perimetral (`prompt_security.py`)
|
||||
* Filtro declarativo contra técnicas de *Jailbreak*, inyecciones de prompt (*Prompt Injection*), bypass de roles y extracción de directivas de sistema.
|
||||
* Neutralización automática de tokens especiales de inferencia (`<|im_start|>`, `<|system|>`, etc.) y prohibición explícita de revelar credenciales de base de datos o secretos de API.
|
||||
|
||||
### 5. Experiencia de Usuario Adaptativa y Ergonómica
|
||||
* **Móviles:** Ventana desplegable estilo *bottom-sheet* (inspirada en la UX de Mercado Libre) con acople automático al teclado virtual en pantalla, backdrop con aislamiento de scroll y botón de repliegue rápido.
|
||||
* **Escritorio:** Widget flotante dockeable con selector de tamaño, sugerencias rápidas contextuales (*Quick Chips*) y renderizado de texto enriquecido en Markdown.
|
||||
|
||||
---
|
||||
|
||||
## 🔌 Servidor MCP Institucional & Asistencia Guiada (Spec 011)
|
||||
|
||||
Edu-Space implementa el estándar **Model Context Protocol (MCP)** bajo `/api/v1/mcp`:
|
||||
* **Herramientas Expuestas para Agentes de IA:**
|
||||
* `get_today_classes`: Consulta del cronograma áulico del día por sede.
|
||||
* `get_classroom_info`: Inspección de aforo, piso, equipamiento y disponibilidad de aulas.
|
||||
* `search_subjects`: Búsqueda de materias por carrera o código.
|
||||
* `guide_navigation`: Disparador de tutoriales guiados en la plataforma.
|
||||
* **Reflector Didáctico Interactivo (Spotlight UI):** Motor en cliente (`GuideService`) capaz de resaltar elementos del DOM paso a paso con recuadros iluminados, tooltips explicativos y avance guiado para capacitar a nuevos operadores de Bedelía o docentes.
|
||||
|
||||
---
|
||||
|
||||
## 🪪 Consola de Recepción, Multi-Serial COM y Reconocimiento de DNI (Spec 013)
|
||||
|
||||
La plataforma incorpora una consola operativa integral de control de accesos físicos en tiempo real para personal de Recepción y Seguridad (`/reception/scanner`):
|
||||
|
||||
```text
|
||||
[ Lector COM 1 (Molinete) ] ──┐
|
||||
[ Lector COM 2 (Paso Princ) ] ─┼──► [ MultiSerialScanner (Web Serial API) ] ──► [ Argentine DNI Parser ]
|
||||
[ Lector COM 3 (Bedelía) ] ───┤ │
|
||||
[ Lector COM 4 (Auxiliar) ] ──┘ ▼
|
||||
[ QRSecurityService ]
|
||||
│
|
||||
[ Feedback Audio (Web Audio) ] ◄── [ Cronograma de Hoy (Aula/Piso) ] ◄──────────────────┘
|
||||
```
|
||||
|
||||
### 1. Soporte Multi-Lector por Puerto Serie COM (Web Serial API)
|
||||
* **Hasta 4 Lectores Seriales Concurrentes:** Control simultáneo de ranuras físicas (`Lector 1 — Paso Principal`, `Lector 2 — Molinete`, `Lector 3 — Mesa Bedelía`, `Lector 4 — Auxiliar`).
|
||||
* **Reconexión Automática Plug-and-Play:** Detección de eventos nativos del sistema operativo en Windows (`navigator.serial.addEventListener('connect' / 'disconnect')`), re-enlazando lectores USB desenchufados sin recargar la página.
|
||||
* **Buffer de Seguridad de Chunks (380 ms):** Permite procesar de forma íntegra códigos densos de más de 400 caracteres transmitidos por escáneres ópticos.
|
||||
* **Panel Colapsable Ergonómico:** Bloque de puertos COM contraído por defecto con indicador resumen (`0 / 4 Activos`) para despejar el puesto operativo.
|
||||
|
||||
### 2. Reconocimiento Universal de DNI Argentino (Renaper & Mi Argentina)
|
||||
* **Algoritmo de Extracción Multiformato (`argentine_dni_parser.py`):**
|
||||
* **Renaper Formato 2026:** Códigos QR de alta densidad con datos patronímicos seguidos del JWT oficial de Renaper (`00749743816"TELLO"CARLOS FACUNDO"34247025"G"09-02-89"23-04-26"eyJ...`).
|
||||
* **Renaper Formato 2012:** Códigos de barras PDF417 de DNIs tarjeta vigentes.
|
||||
* **Renaper Formato 2009:** DNI libreta celeste o tarjeta inicial con prefijos alfabéticos `F` / `M` (Libreta Cívica / Enrolamiento) o comillas iniciales.
|
||||
* **App Mi Argentina:** Códigos QR con identificadores numéricos de género y documento.
|
||||
* **Ingreso Directo:** Tipeado manual o pistola USB HID sobre documento con o sin puntos (`34.247.025`, `34247025`, `DNI: 34247025`).
|
||||
* **Normalización de Teclado en Español:** Corrige la traducción errónea de `:` a `Ñ` en lectores configurados con mapa de teclado US en Windows (`UNICABAÑUSRÑ144` ➔ `UNICABA:USR:144`), preservando intactos los nombres y apellidos que contengan `Ñ` (ej. Peña, Núñez, Piñero).
|
||||
* **Auto-vinculación Asistida:** Si un DNI físico es escaneado por primera vez y el usuario no tenía el número cargado en la base de datos, el sistema asocia de forma permanente el documento mediante coincidencia nominal de nombre y apellido.
|
||||
|
||||
### 3. Validación y Cronograma Áulico Instantáneo
|
||||
* Al escanear una credencial o DNI, el sistema muestra en pantalla:
|
||||
* Datos personales, rol institucional y fotografía/iniciales.
|
||||
* Estado de matrícula (Activo / Regular).
|
||||
* **Aula física exacta y piso donde cursa o dicta clase hoy** (ej. *Aula 204 — Piso 2, Edificio Central*).
|
||||
* **Señalización Cromática Tristado:**
|
||||
* **Verde Esmeralda (`border-success`):** Alumno o docente con cursada presencial hoy en la sede.
|
||||
* **Ámbar de Advertencia (`border-warning`):** Alumno regular activo pero sin clases programadas para hoy.
|
||||
* **Rojo Denegado (`border-danger`):** Usuario inactivo, credencial vencida o persona no registrada en UniCABA.
|
||||
* **Feedback Auditivo Sintetizado (Web Audio API):**
|
||||
* *Tono Armónico Ascendente (587Hz ➔ 880Hz):* Acceso con aula y clase hoy.
|
||||
* *Tono Suave Medio (440Hz ➔ 554Hz):* Acceso válido sin clase hoy.
|
||||
* *Tono Grave de Alerta (220Hz):* Acceso denegado o error.
|
||||
* **Bitácora Inmutable (`access_logs_qr`):** Registro de cada ingreso con timestamp en hora local argentina (`America/Argentina/Buenos_Aires`).
|
||||
|
||||
---
|
||||
|
||||
## 💳 Credencial Digital Universitaria con QR Dinámico Anti-Captura (Spec 012)
|
||||
|
||||
Cada integrante de la comunidad de UniCABA dispone de una credencial digital infalsificable:
|
||||
|
||||
* **Auto-Rotación Dinámica Criptográfica (3 Segundos):** El código QR se regenera automáticamente cada 3 segundos mediante tokens JWT firmados con identificador único (`jti`) y marca de tiempo (`iat`).
|
||||
* **Ventana Estricta Anti-Screenshot:** Período de gracia ultra-corto (6 segundos) configurado en `SystemSetting`. Cualquier fotografía previa o captura de pantalla enviada por mensajería expira a los pocos segundos y es rechazada por la consola de recepción (`jwt.ExpiredSignatureError`).
|
||||
* **Puntos de Acceso:**
|
||||
* **Carnet Universitario Completo (`/credential/my-card`):** Ficha institucional imprimible con datos de carrera, DNI, foto, QR en vivo y condiciones de regularidad.
|
||||
* **Modal Global Rápido (`#userQrCredentialModal`):** Botón con icono `bi-qr-code-scan` en la barra lateral y cabecera móvil que despliega el código QR con barra de progreso interactiva sin salir de la página activa.
|
||||
* **Perfil de Usuario (`/auth/profile`):** Exhibición de credencial y vías habilitadas de acceso.
|
||||
|
||||
---
|
||||
|
||||
## 🎁 Módulo de Convenios y Beneficios Institucionales (Spec 012)
|
||||
|
||||
Portal de descuentos y acuerdos corporativos para la comunidad académica (`/benefits`):
|
||||
|
||||
* **Catálogo Categorizado:** Beneficios en gastronomía, librerías, tecnología, deportes y capacitaciones.
|
||||
* **ABM Administrativo:** Gestión de beneficios con título, descripción, porcentaje de descuento, fechas de validez, cupón promocional e imagen de marca.
|
||||
* **Control de Acceso RBAC:** Módulo `benefits` administrable con permisos segmentados (`none`, `read`, `read_write`) en la matriz de roles institucional.
|
||||
|
||||
---
|
||||
|
||||
## 🏛️ Circuito Operativo Secuencial de Bedelía (9 Pasos)
|
||||
|
||||
Para garantizar la integridad referencial y erradicar las planillas Excel, la administración áulica sigue un flujo estandarizado:
|
||||
|
||||
```text
|
||||
[ 1. Sede / Edificio ] ──► [ 2. Aulas (Físicas / Virtuales) ] ──► [ 3. Ciclo Lectivo ]
|
||||
│
|
||||
[ 6. Comisiones ] ◄────── [ 5. Asignaturas (Multi-carrera) ] ◄── [ 4. Carreras ]
|
||||
│
|
||||
▼
|
||||
[ 7. Profesores ] ───────► [ 8. Alumnos / Matrícula ] ────────► [ 9. Reserva de Espacio ]
|
||||
```
|
||||
|
||||
### 1. Asignaturas Compartidas entre Múltiples Carreras
|
||||
* Implementación de la tabla asociativa `subject_careers` (relación Many-to-Many), permitiendo que una materia (ej. *IoT*, *Seguridad de la Información*, *Sistemas Operativos*) pertenezca simultáneamente a múltiples planes de estudio preservando `career_id` principal por compatibilidad.
|
||||
* Comisiones y grillas exponen todas las carreras vinculadas para facilitar búsquedas y filtros.
|
||||
|
||||
### 2. Matriz Integral de Conflictos (HTTP 409)
|
||||
* **Solapamiento Físico de Aula:** Impide asignar dos clases presenciales en la misma aula y franja horaria.
|
||||
* **Aforo de Capacidad Máxima:** Alerta y bloquea si el cupo de alumnos inscriptos supera la capacidad de bancos del aula física.
|
||||
* **Solapamiento Docente:** Controla la disponibilidad horaria del profesor, autorizando la superposición únicamente si la cátedra cuenta con un co-docente registrado disponible (*Excepción por Co-docencia*).
|
||||
* **Restricción Diaria del Alumno:** Un estudiante no puede cursar dos asignaturas regulares el mismo día, salvo en cursos cortos/talleres (`is_short_course`) o con autorización expresa de Bedelía (`allow_same_day_exception`).
|
||||
|
||||
### 3. Cartelera Operativa & Exportación A4 / Excel
|
||||
* **Cartelera del Día (`/schedule/today_schedule`):** Franjas horarias agrupadas cronológicamente (`grouped_slots`, ej. `08:00 - 11:00 hs`), turnos, aulas físicas, docentes y enlaces directos a Google Meet / Teams.
|
||||
* **Filtros Temporales Explícitos:** Switcher para alternar entre "Día (Hoy)", "Mañana", "Esta Semana" y "Este Mes" con badges de fecha en español.
|
||||
* **Exportación Excel / CSV:** Descarga directa con codificación UTF-8 BOM (`\uFEFF`) y delimitadores `;` para apertura perfecta en Excel.
|
||||
* **Impresión A4 Institucional:** Estilos dedicados `@media print` que formatean la cartelera en hoja limpia con membrete oficial de UniCABA.
|
||||
|
||||
### 4. Grilla Semanal Interactiva (Drag & Drop)
|
||||
* Calendario semanal interactivo (**FullCalendar**) en `/schedule/calendar` con panel lateral de comisiones sin aula.
|
||||
* Arrastre de eventos con validación asíncrona previa (`POST /api/v1/reservations/drag-update`); ante colisión horaria se revierte automáticamente el evento (`info.revert()`) y se notifica al usuario con un Toast descriptivo.
|
||||
|
||||
### 5. Libro de Calificaciones (*Gradebook*) & Cierre de Actas
|
||||
* Matriz bidimensional interactiva de calificaciones por comisión (`/schedule/gradebook/:id`) con autoguardado asíncrono debounced (500 ms).
|
||||
* Cálculo dinámico de promedios ponderados y condiciones (*Promocionado*, *Regular*, *Libre*).
|
||||
* Cierre formal de actas con generación de código inmutable (`ACTA-YYYY-Sem-ID`), auditoría en `audit_logs` y congelamiento de modificaciones.
|
||||
|
||||
### 6. Modo Impersonación del Superadmin ("Login as")
|
||||
* Permite a un administrador auditar el sistema adoptando exactamente la perspectiva y permisos de cualquier docente o estudiante.
|
||||
* Activación en 1 clic (`bi-incognito`) desde el catálogo de usuarios (`/admin/users_list`), con banner ámbar permanente de advertencia visual y trazabilidad estricta en auditoría (`IMPERSONATE_START` / `IMPERSONATE_END`).
|
||||
|
||||
---
|
||||
|
||||
## 🧹 Importador Dinámico de Google Sheets & Purga Selectiva
|
||||
|
||||
El importador oficial de Google Sheets (`sheets_importer.py`) permite la ingesta masiva inicial y sincronización continua:
|
||||
|
||||
* **Inspección en Vivo del Sheet Online:** Descarga y analiza las 6 hojas semanales (Lunes a Sábado), descubriendo dinámicamente carreras y materias.
|
||||
* **Grilla Interactiva de Previsualización:** Muestra las filas detectadas con buscador en vivo, paginación fluida y datepicker editable por fila para corregir fechas de cursada antes de sincronizar.
|
||||
* **Selección Granular de Entidades:** Toggles independientes para decidir si importar Reservas, Aulas físicas/virtuales, Comisiones, Asignaturas o Carreras.
|
||||
* **Alcance Temporal Flexible:** Soporte de rangos personalizados de fechas (semanas del cuatrimestre) o fecha puntual única.
|
||||
* **Tolerancia de Carga Masiva:** Servidor Express configurado con límite de payload de **50 MB** (`{ limit: '50mb' }`) para procesar matrices completas de sincronización sin errores de `PayloadTooLargeError`.
|
||||
* **Purga Segura y Selectiva:** Herramienta para vaciar ordenadamente entidades académicas en orden topológico inverso de claves foráneas, preservando intactos a los usuarios, contraseñas y roles.
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Integraciones del Sistema
|
||||
|
||||
### 1. Google Workspace OAuth 2.0
|
||||
* Autenticación institucional restringida al dominio `@unicaba.edu.ar`.
|
||||
* Asociación automática de perfil y generación de enlaces de Google Meet para comisiones virtuales.
|
||||
|
||||
### 2. Moodle 4.1 REST API & Replicador Institucional
|
||||
* Conexión con los Web Services oficiales de Moodle (`core_webservice_*`, `enrol_*`, `core_user_*`).
|
||||
* Autenticación delegada permitiendo a los alumnos ingresar a Edu-Space con sus credenciales de Moodle.
|
||||
* Cola de sincronización asíncrona resiliente (`MoodleSyncTask`) con reintentos exponenciales y Dead Letter Queue (DLQ).
|
||||
* Capa de caché híbrida (`CacheService` en Redis o memoria) para lecturas de alto rendimiento.
|
||||
* Replicador institucional (`scripts/moodle_replicator.py` & `.agents/skills/moodle-replicator`) para sincronizar masivamente nóminas de participantes, cursos y categorías entre entornos.
|
||||
|
||||
### 3. Servicio de Correo Electrónico SMTP Dinámico (`EmailService`)
|
||||
* Envío de notificaciones y confirmaciones con credenciales de servidor SMTP configuradas en base de datos y cifradas en reposo con Fernet.
|
||||
|
||||
### 4. Clima del Campus en Vivo (`WeatherService`)
|
||||
* Consulta meteorológica en tiempo real para la Ciudad de Buenos Aires desplegada en el pie de la barra lateral.
|
||||
|
||||
### 5. Acceso de Contingencia para Administradores (`/adm/login`, Spec 006)
|
||||
* Pasarela de autenticación de emergencia aislada que permite a los administradores ingresar mediante credenciales maestras locales ante caídas de proveedores de identidad externos (Google o Moodle).
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Seguridad, RBAC y Auditoría Institucional
|
||||
|
||||
* **Matriz de Permisos RBAC en 12 Módulos:** Control segmentado (`none`, `read`, `read_write`) sobre `classrooms`, `reservations`, `schedule`, `academic`, `users`, `roles`, `reports`, `optimizer`, `system`, `settings`, `benefits` y `reception`.
|
||||
* **Roles del Sistema:** `Admin`, `Bedelia`, `Docente`, `Alumno` y `Recepcion`.
|
||||
* **Registro de Auditoría Inmutable (`AuditLog`):** Monitoreo continuo de eventos críticos (inicios y fallos de sesión, altas/bajas de aulas y reservas, ejecuciones del optimizador genético e impersonaciones).
|
||||
* **Gestión Transparente de Incidentes:** Pantalla de diagnóstico técnico estructurada con ticket único (`INC-YYYYMMDD-XXXX`), traza de error colapsable y botón para copiar informe al equipo de soporte IT.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Dashboards Personalizados por Rol
|
||||
|
||||
La plataforma cuenta con paneles adaptados a las necesidades operativas de cada perfil institucional:
|
||||
|
||||
* **Administrador (`/dashboard?role=admin`):** Cockpit institucional con métricas globales, auditoría de seguridad RBAC, tendencias mensuales y panel interactivo de **Estado y Percentiles de Asignación de Aulas Físicas** (asignadas vs disponibles en número y porcentaje).
|
||||
* **Bedelía (`/dashboard?role=bedelia`):** Control operativo del campus en tiempo real, balance de aulas presenciales asignadas (96.3%) y libres (3.7%), cartelera del día y bandeja de aprobación de reservas pendientes.
|
||||
* **Docente / Profesor (`/dashboard?role=docente`):** Sesiones del día con accesos directos a videollamadas y gestión de comisiones.
|
||||
* **Alumno / Estudiante (`/dashboard?role=alumno`):** Brújula de cursada *"¿Dónde curso hoy?"* con ubicación por piso y aula o enlace virtual, junto al cronograma de exámenes y entregas de TPs.
|
||||
|
||||
> **Modo Vista Previa:** Los usuarios con perfil administrador o directivo pueden previsualizar cualquier perspectiva utilizando el selector de roles en la barra superior o pasando el parámetro `?role={admin|bedelia|docente|alumno}` en la URL.
|
||||
* **Administrador (`/dashboard?role=admin`):** Cockpit institucional con métricas globales, auditoría de seguridad RBAC, percentiles de ocupación y acceso a la configuración del Asistente IA y credenciales QR.
|
||||
* **Bedelía (`/dashboard?role=bedelia`):** Control operativo en vivo, balance de aulas presenciales asignadas y libres, cartelera del día con accesos de impresión en 1 clic y bandeja de aprobación de reservas.
|
||||
* **Docente (`/dashboard?role=docente`):** Clases del día, enlaces a videoconferencias, Libro de Calificaciones y nómina de alumnos.
|
||||
* **Alumno (`/dashboard?role=alumno`):** Brújula de cursada *"¿Dónde curso hoy?"* con aula física, piso o enlace Meet, libreta de calificaciones y acceso instantáneo a su carnet universitario QR.
|
||||
* **Recepción (`/reception/scanner`):** Consola de control de acceso físico con lectores seriales COM, validación de DNI argentino y verificación instantánea de aula asignada para el día.
|
||||
|
||||
---
|
||||
|
||||
## 🏛️ Circuito Operativo de Bedelía (UX & Flujo Simplificado)
|
||||
## 🚀 Instalación y Puesta en Marcha Local
|
||||
|
||||
Para garantizar una experiencia de usuario rápida y sin fricción para el personal de Bedelía, el circuito de gestión áulica se divide en 3 etapas directas:
|
||||
### Requisitos Previos
|
||||
* **Node.js:** v20.x LTS o superior
|
||||
* **Python:** 3.12+ (compatible con Python 3.14)
|
||||
* **Base de Datos:** PostgreSQL 15+ (recomendado) o SQLite (desarrollo rápido)
|
||||
|
||||
```
|
||||
[ 1. Creación / Edición de Aula ] ──► [ 2. Asignación de Comisión al Aula ] ──► [ 3. Cartelera y Grilla ]
|
||||
- Sede Central o Campus Virtual - Desde Comisiones (1 clic) - Detección de colisiones
|
||||
- Piso y Aforo real - O desde Ficha de Aula - Drag & Drop semanal
|
||||
- Tipo (Teórica / Laboratorio) - Autocompletado de cupo y Meet - Cartelera del día en vivo
|
||||
```
|
||||
|
||||
### 1. Creación y Mantenimiento de Aulas (`/classrooms/list_classrooms`)
|
||||
* Acceso directo a **"Nueva Aula"**: se selecciona la sede (Edificio Central o Campus Virtual), piso (`PB`, `1`, `2`, `3`, `4`) y tipo de espacio (Teórica, Laboratorio de Informática, etc.).
|
||||
* Las aulas virtuales se configuran con capacidad infinita ($\infty$) y no distorsionan la capacidad de bancos físicos del edificio central.
|
||||
* En el catálogo de aulas, cada tarjeta muestra el aforo, piso, equipamiento y el botón de acción rápida **"Asignar Comisión"**, que abre el formulario de reserva con el aula ya preseleccionada.
|
||||
|
||||
### 2. Asignación de Comisión al Aula (`/schedule/add_reservation`)
|
||||
La asignación puede realizarse desde dos puntos de entrada según la necesidad operativa:
|
||||
* **Desde el Catálogo de Comisiones (`/admin/commissions_list`):**
|
||||
- Cada fila cuenta con el botón de acceso rápido **"Asignar Aula / Horario"** (`bi-calendar-plus`).
|
||||
- Al hacer clic, redirige a `/schedule/add_reservation?commission_id={id}` precargando de forma automática:
|
||||
- Nombre de la asignatura y código de comisión.
|
||||
- Cupo esperado de alumnos (`expected_attendees = max_students`).
|
||||
- Enlace de videollamada preexistente (Google Meet / Teams).
|
||||
* **Desde el Catálogo de Aulas (`/classrooms/list_classrooms`):**
|
||||
- Al pulsar **"Asignar Comisión"**, redirige a `/schedule/add_reservation?classroom_id={id}`.
|
||||
- El selector en cascada (**1. Edificio ➔ 2. Piso ➔ 3. Aula**) se auto-posiciona en la sede, planta y aula elegidas.
|
||||
* **Validación en Vivo:** El sistema alerta inmediatamente si la cantidad de alumnos de la comisión excede la capacidad física del aula seleccionada.
|
||||
|
||||
### 3. Visualización y Control de Ocupación
|
||||
* **Cartelera del Día (`/schedule/today_schedule`):** Bloques horarios de 07:00 a 21:00 hs con filtros por piso, turno y switch para ocultar aulas virtuales.
|
||||
* **Grilla Semanal Interactiva (`/schedule/calendar`):** Arrastre de comisiones sin aula asignada desde el panel lateral con detección de colisiones físicas, solapamientos docentes y aforo en tiempo real (HTTP 409).
|
||||
|
||||
---
|
||||
|
||||
## 🧹 Módulo de Purga y Sincronización Académica
|
||||
|
||||
* **Purga Segura y Selectiva (`/admin/google_sheets_import`):**
|
||||
- Permite restablecer limpiamente reservas, comisiones, asignaturas, carreras y/o aulas para comenzar nuevos ciclos lectivos o pruebas de carga.
|
||||
- **Confirmación Interactiva:** Cuenta con un modal de confirmación (`#purgeConfirmModal`) que lista las entidades específicas a eliminar y previene clics accidentales.
|
||||
- **Integridad Referencial Estricta:** Ejecuta la eliminación en orden topológico inverso de claves foráneas (`Reservation` ➔ `MilestoneGrade` ➔ `CommissionTeacher` ➔ `StudentEnrollment` ➔ `Commission` ➔ `Subject` ➔ `Career` ➔ `Classroom`), garantizando que la base de datos no rechace el borrado por restricciones relacionales.
|
||||
- **Preservación Total de Identidades:** Los usuarios (`User`), contraseñas y roles (`Role`) están estrictamente blindados y nunca son afectados por la purga de datos académicos.
|
||||
* **Importación desde Google Sheets:** Carga y sincronización dinámica de todas las materias y franjas horarias directamente desde la hoja institucional publicada.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Capacidades Avanzadas de Gestión (Fases 2, 3 y 4 del MVP)
|
||||
|
||||
### 1. Grilla Semanal Interactiva (Drag & Drop) y Validación de Colisiones en Tiempo Real
|
||||
- **FullCalendar Interactivo:** Arrastre y edición de horarios directo en el calendario general de Bedelía (`/schedule/calendar`).
|
||||
- **Sidebar de Comisiones por Asignar:** Panel lateral colapsable con las comisiones sin aula, con arrastre fluido hacia la grilla semanal o diaria.
|
||||
- **Detección Automática de Choques (HTTP 409):** Validación previa ante cada movimiento (`POST /api/v1/reservations/drag-update`) verificando colisiones físicas de aula, superposición docente y límite de aforo. Si hay conflicto, el evento se revierte automáticamente (`info.revert()`) y se notifica al usuario con un Toast explicativo.
|
||||
|
||||
### 2. Modo Impersonación del Superadmin ("Login as")
|
||||
- Permite al Administrador navegar la plataforma adoptando exactamente la perspectiva y permisos de cualquier docente o estudiante.
|
||||
- Activación con un clic (`bi-incognito`) desde el catálogo de usuarios (`/admin/users_list`).
|
||||
- Banner superior permanente de advertencia visual en color ámbar con identificación del usuario adoptado y botón de salida inmediata.
|
||||
- Trazabilidad y auditoría obligatoria inmutable en `audit_logs` (`IMPERSONATE_START` e `IMPERSONATE_END`).
|
||||
|
||||
### 3. Libro de Calificaciones (*Gradebook*) & Cierre Formal de Actas
|
||||
- Matriz bidimensional interactiva de calificaciones por comisión (`/schedule/gradebook/:id`) con autoguardado asíncrono debounced (500 ms).
|
||||
- Cálculo en vivo de promedios ponderados y condiciones académicas (*Promocionado*, *Regular*, *Libre*).
|
||||
- Cierre formal de actas con generación de código inmutable (`ACTA-YYYY-Sem-ID`), auditoría en `audit_logs` y congelamiento de modificaciones.
|
||||
- Soporte para reapertura excepcional justificada por Bedelía.
|
||||
- Portal del Estudiante (`/schedule/my_grades` / `/mis-materias/mis-notas`) para consulta de calificaciones y comprobantes.
|
||||
|
||||
### 4. Co-docencia, Matriz de Conflictos y Regla Diaria
|
||||
- Soporte de cátedras con múltiples docentes por comisión (`CommissionTeacher`).
|
||||
- Excepción por co-docencia: autoriza superposiciones de horario docente si la cátedra cuenta con un co-docente registrado disponible.
|
||||
- Regla restrictiva de cursada diaria: un alumno no puede cursar dos asignaturas regulares el mismo día, con excepciones automáticas para talleres/cursos cortos (`is_short_course`) o autorizaciones especiales emitidas por Bedelía.
|
||||
|
||||
---
|
||||
|
||||
## 📅 Ficha de Reserva & Gestión de Comisiones
|
||||
|
||||
* **Ficha de Reserva Detallada (`/schedule/view_reservation?id={id}`):** Información completa del espacio físico o virtual asignado, capacidad y asistencia prevista, comisión académica vinculada, docente a cargo, botones de acción inmediata (*Modificar Reserva*, *Confirmar Reserva*, *Cancelar Reserva*) y acceso con un clic a la sala de videollamada.
|
||||
* **Gestión de Comisiones y Vinculación con Asignaturas (`/admin/commissions_list`):**
|
||||
- Botón y modal interactivo **Nueva Comisión** (`#modalAddCommission`) para registrar comisiones y vincularlas directamente a su **Asignatura / Materia**, indicando cuatrimestre, año, turno, cupo y docente responsable.
|
||||
- Generación automática de enlace institucional de Google Meet cuando no se especifica un enlace propio.
|
||||
- Tabla operativa con visualización explícita del código de comisión, nombre de materia, código de asignatura y carrera.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Instalación y Despliegue Local
|
||||
|
||||
### Requisitos previos
|
||||
- Node.js (v18 o superior)
|
||||
- Python 3.10+
|
||||
- SQLite / PostgreSQL
|
||||
|
||||
### 1. Iniciar el Backend (Flask)
|
||||
```bash
|
||||
### 1. Iniciar el Backend (FastAPI ASGI Core API)
|
||||
```powershell
|
||||
cd backend
|
||||
python -m venv venv
|
||||
# Activar venv (Windows: venv\Scripts\activate, Linux/Mac: source venv/bin/activate)
|
||||
pip install -r requirements.txt
|
||||
flask run --port=5000
|
||||
```
|
||||
*(El backend quedará escuchando en http://localhost:5000)*
|
||||
|
||||
### 2. Iniciar el Frontend (Node/Express)
|
||||
```bash
|
||||
# En Windows:
|
||||
.\venv\Scripts\activate
|
||||
# En Linux / macOS:
|
||||
# source venv/bin/activate
|
||||
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Inicializar base de datos con roles y usuarios esenciales:
|
||||
python init_db.py
|
||||
|
||||
# Levantar servidor ASGI Uvicorn en el puerto 5000 con recarga en caliente:
|
||||
uvicorn main:app --host 0.0.0.0 --port 5000 --reload
|
||||
```
|
||||
*API disponible en:* `http://localhost:5000`
|
||||
*Documentación interactiva Swagger UI:* `http://localhost:5000/docs`
|
||||
*Documentación interactiva ReDoc:* `http://localhost:5000/redoc`
|
||||
|
||||
### 2. Iniciar el Frontend (Node.js / Express BFF)
|
||||
```powershell
|
||||
cd frontend
|
||||
npm install
|
||||
|
||||
# Iniciar servidor Express en el puerto 3000 con nodemon / recarga activa:
|
||||
npm run dev
|
||||
# o en su defecto:
|
||||
node src/app.js
|
||||
```
|
||||
*(El frontend quedará escuchando en http://localhost:3000)*
|
||||
*Aplicación web disponible en:* `http://localhost:3000`
|
||||
|
||||
---
|
||||
|
||||
## 📦 Despliegue Automatizado en Producción (Linux / Proxmox LXC)
|
||||
|
||||
Para servidores Debian 12 / Ubuntu en Proxmox LXC o VPS, el repositorio incluye el instalador unificado [install.sh](install.sh) en la raíz:
|
||||
Para servidores institucionales Debian 12 / Ubuntu en Proxmox LXC (entorno productivo `10.0.0.217` / `eduspace.oemspot.com.ar`), el repositorio incluye el instalador desatendido [install.sh](install.sh) en la raíz:
|
||||
|
||||
# Despliegue interactivo (pregunta si mantener BD, restaurar snapshot o crear base limpia):
|
||||
```bash
|
||||
# Despliegue interactivo con menú de opciones:
|
||||
sudo bash install.sh
|
||||
|
||||
# Despliegue desatendido manteniendo la base de datos existente:
|
||||
# Despliegue desatendido preservando la base de datos PostgreSQL existente:
|
||||
sudo bash install.sh --keep-db
|
||||
|
||||
# Despliegue desatendido preservando la base de datos y los usuarios/credenciales configurados:
|
||||
sudo bash install.sh --keep-db --keep-users
|
||||
|
||||
# Despliegue desatendido con base de datos limpia sin carreras, materias, ciclos lectivos, aulas ni edificios demo:
|
||||
# Despliegue desatendido con base de datos limpia (solo usuarios y roles iniciales):
|
||||
sudo bash install.sh --empty-academic
|
||||
|
||||
# Despliegue desatendido recreando la base de datos desde cero con snapshot de muestra (DROP y restore classrooms_db.sql):
|
||||
# Despliegue recreando la base desde snapshot completo (DROP y restore classrooms_db.sql):
|
||||
sudo bash install.sh --fresh-db
|
||||
```
|
||||
|
||||
También es posible inicializar directamente la base de datos limpia desde Python en cualquier entorno:
|
||||
```bash
|
||||
# Inicialización estándar con datos de muestra:
|
||||
python backend/init_db.py
|
||||
|
||||
# Inicialización limpia (sin carreras, materias, ciclos lectivos, aulas, edificios ni reservas):
|
||||
python backend/init_db.py --empty-academic
|
||||
```
|
||||
|
||||
El script configura automáticamente:
|
||||
1. Entorno Python 3.10+ y virtualenv en `backend/venv` con Gunicorn y servicio `admin-edu-space-backend.service` (puerto 5000).
|
||||
2. Entorno Node.js 20 LTS en `frontend/` con servicio `admin-edu-space-frontend.service` (puerto 3000).
|
||||
3. Motor PostgreSQL local con configuración de usuario y opciones seguras para preservar o restaurar la base `classrooms_db`.
|
||||
1. Virtualenv Python 3.12+ con Gunicorn/Uvicorn bajo el servicio `admin-edu-space-backend.service` (:5000).
|
||||
2. Runtime Node.js 20 LTS bajo el servicio `admin-edu-space-frontend.service` (:3000).
|
||||
3. Motor PostgreSQL local con credenciales seguras para `classrooms_db`.
|
||||
4. Servicio maestro unificado `admin-edu-space.service` gestionable vía `systemctl {status|restart|stop} admin-edu-space`.
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Pruebas Automatizadas
|
||||
## 🧪 Pruebas Automatizadas & Calidad de Código
|
||||
|
||||
Para ejecutar la suite completa de 47 pruebas unitarias y de integración (JWT, ABMs, Reglas, Optimizador, Calificaciones y Moodle):
|
||||
Para ejecutar la suite completa de **131 pruebas unitarias y de integración** (validando contratos FastAPI, DTOs Pydantic, algoritmos genéticos, RAG UdeCi, parsers de DNI, cola Moodle, RBAC y matriz de colisiones):
|
||||
|
||||
```bash
|
||||
```powershell
|
||||
cd backend
|
||||
$env:PYTHONPATH="backend"
|
||||
.\venv\Scripts\python.exe -m pytest tests -v
|
||||
$env:PYTHONPATH="."
|
||||
.\venv\Scripts\pytest tests -v
|
||||
```
|
||||
|
||||
Para ejecutar la auditoría automatizada de seguridad estática y dinámica:
|
||||
```powershell
|
||||
.\security_audit.bat --no-pause
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Documentación Técnica & Changelogs
|
||||
* [Roadmap MVP: Fases y Estadios del Proyecto](ROADMAP_MVP.md)
|
||||
* [Changelog Oficial del Proyecto (v2.8.0)](CHANGELOG.md)
|
||||
* [Changelog MVP Consolidado](CHANGELOG_MVP.md)
|
||||
* [Estado de la Migración y Arquitectura Objetivo UniCABA](ESTADO_MIGRACION_Y_ARQUITECTURA_OBJETIVO.md)
|
||||
* [Changelog Detallado: Clases Virtuales y Dashboards](docs/CHANGELOG_VIRTUAL_CLASSES_AND_DASHBOARDS.md)
|
||||
* [Auditoría y Sesión de Reingeniería](docs/CHANGELOG_SESSION.md)
|
||||
* [Guía de Integración de Cronograma](docs/SCHEDULE_INTEGRATION_GUIDE.md)
|
||||
## 📚 Documentación Técnica & Referencias
|
||||
|
||||
* [Changelog Oficial Completo del Proyecto](CHANGELOG.md)
|
||||
* [Principios de Desarrollo y Constitución del Proyecto](docs/constitution.md)
|
||||
* [Directivas para Agentes de IA y Arquitectura del Sistema](AGENTS.md)
|
||||
* [Especificaciones de Desarrollo Guiado (SDD 001 a 013)](specs/)
|
||||
* [Guía de Replicación Moodle Producción a Local](.agents/skills/moodle-replicator/SKILL.md)
|
||||
* [Procedimiento de Despliegue Continuo en Producción](.agents/skills/deploy/SKILL.md)
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# ROADMAP OFICIAL — Sistema Integral UniCABA (Admin Edu-Space)
|
||||
## Gestión de Espacios Áulicos, Asignación de Comisiones y Operatoria de Bedelía
|
||||
|
||||
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
|
||||
**Versión:** 3.5.7 (Principio 11: Estándares Modernos de APIs, Pydantic e Integración de IA)
|
||||
**Fecha de Actualización:** 16 de Octubre de 2026
|
||||
**Rama Base:** `dev`
|
||||
|
||||
---
|
||||
|
||||
## 🗺️ Visión del Proyecto y Objetivo del Sprint
|
||||
Consolidar la plataforma **Admin Edu-Space** como el sistema integral de gestión áulica y académica para **UniCABA**, **reemplazando definitivamente el archivo Excel que el personal de Bedelía utiliza para su gestión diaria**. A partir de este hito, la plataforma se convierte en la fuente única de verdad para la asignación de espacios, horarios y docentes, relegando las planillas externas a un simple mecanismo de importación masiva de datos iniciales.
|
||||
|
||||
---
|
||||
|
||||
## 📊 Estado Global de Progreso
|
||||
|
||||
```
|
||||
Fase 0: Desacople y Arquitectura Base [████████████████████] 100% (Completado)
|
||||
Fase 1: Paridad Legacy, Virtualidad y Dashboards[████████████████████] 100% (Completado)
|
||||
Fase 2: Co-docencia y Matriz de Conflictos [████████████████████] 100% (Completado)
|
||||
Fase 3: Hitos Evaluativos y Calificaciones [████████████████████] 100% (Completado)
|
||||
Fase 4: UI/UX Drag & Drop e Impersonación [████████████████████] 100% (Completado)
|
||||
Fase 5: Integración Auth, Email & Moodle [████████████████████] 100% (Completado)
|
||||
Fase 5.1: Bedelía UX, ABMs 100% y Reset Seguro [████████████████████] 100% (Completado)
|
||||
Sprint MVP: Flujo Bedelía & Reemplazo Excel [████████████████████] 100% (Entregado v3.5.0)
|
||||
Fase 6: Despliegue en Servidores y Hardening [█████████░░░░░░░░░░░] 45% (En Curso)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Detalle de Fases y Entregables
|
||||
|
||||
### Fase 0: Desacople y Arquitectura Base ✅ *(Completada)*
|
||||
- [x] Backend Flask como API REST pura bajo `/api/v1/` retornando exclusivamente JSON.
|
||||
- [x] Frontend BFF en Node.js + Express con renderizado de plantillas Nunjucks.
|
||||
- [x] Autenticación desacoplada con tokens JWT en Cookie `HttpOnly` segura.
|
||||
- [x] Pipeline de seguridad `SecurityFilterChain` con blindaje OWASP y rate limiting.
|
||||
- [x] Cliente Axios centralizado con interceptor Bearer token automático.
|
||||
|
||||
### Fase 1: Paridad Legacy, Virtualidad y Dashboards Especializados ✅ *(Completada)*
|
||||
- [x] Importador de Google Sheets corregido: eliminación de colisiones en aulas virtuales múltiples (`Campus Virtual · VIRTUAL`).
|
||||
- [x] Dashboards específicos e interactivos para **Bedelía**, **Docente**, **Alumno** y **Administrador**.
|
||||
- [x] Cartelera del Día (`today_schedule`) con bloques horarios (07:00 a 22:00 hs) y filtros dinámicos.
|
||||
- [x] Generación y persistencia de enlaces de Google Meet institucional por comisión y reserva.
|
||||
|
||||
### Fase 2: Co-docencia, Matriz de Conflictos y Regla Diaria ✅ *(Completada)*
|
||||
- [x] Tabla relacional `commission_teachers` para soportar múltiples docentes por comisión (titulares, adjuntos, ayudantes).
|
||||
- [x] Matriz de conflictos con validación física estricta, chequeo de aforo de seguridad y superposición docente.
|
||||
- [x] Excepción de superposición justificada por co-docencia activa.
|
||||
- [x] Regla restrictiva de cursada diaria para estudiantes con bypass por curso corto (`is_short_course`) o excepción expresa de Bedelía.
|
||||
|
||||
### Fase 3: Hitos Evaluativos y Libro de Calificaciones (*Gradebook*) ✅ *(Completada)*
|
||||
- [x] Programación y calendario de parciales, recuperatorios, entregas y exámenes finales.
|
||||
- [x] Matriz de carga rápida de notas con autoguardado asíncrono y promedios en tiempo real.
|
||||
- [x] Cierre formal e inmutable de actas con número oficial (`ACTA-YYYY-Sem-ID`) y registro de auditoría.
|
||||
- [x] Consulta de calificaciones y estado de regularidad para alumnos.
|
||||
|
||||
### Fase 4: UI/UX Avanzada para Bedelía & Modo Impersonación ✅ *(Completada)*
|
||||
- [x] Grilla semanal interactiva (Drag & Drop) con FullCalendar y barra lateral de comisiones sin aula.
|
||||
- [x] Detección visual de colisiones en tiempo real con reversión automática y mensajes de alerta.
|
||||
- [x] Modo de impersonación administrativa (*login as*) con cabecera `X-Impersonate-User` y banner visual ámbar.
|
||||
- [x] Integración de Optimizador Genético heurístico acoplado a turnos académicos reales.
|
||||
|
||||
### Fase 5: Integración Auth, Email y Moodle 4.1 ✅ *(Completada)*
|
||||
- [x] Panel de configuración global administrativa con contraseñas cifradas vía Fernet.
|
||||
- [x] Capa de caché híbrida (`CacheService` en Redis/memoria) y cola asíncrona tolerante a fallos (`MoodleSyncTask` con DLQ).
|
||||
- [x] Autenticación híbrida: Google OAuth 2.0 (`@unicaba.edu.ar`), Moodle SSO y Login Local con fallback.
|
||||
- [x] Motor de notificaciones transaccionales por email (`EmailService`) para docentes.
|
||||
|
||||
### Fase 5.1: Cobertura ABM 100% y Mantenimiento Seguro ✅ *(Completada)*
|
||||
- [x] ABMs completos y protegidos para **Sedes/Edificios**, **Aulas (físicas/virtuales)**, **Ciclos Lectivos**, **Carreras**, **Materias**, **Comisiones** y **Reservas**.
|
||||
- [x] Módulo de Reinicio Total del Sistema (`POST /api/v1/admin/system/reset`) con validación obligatoria de contraseña de Administrador y preservación de cuentas y roles RBAC.
|
||||
- [x] Soporte de inicialización limpia (`--empty-academic` / `--no-demo`) para arranque desde cero.
|
||||
|
||||
---
|
||||
|
||||
### Sprint Activo: Flujo Completo de Bedelía & Reemplazo Definitivo de Excel 🏛️ ⚡ *(En Curso)*
|
||||
* **Objetivo:** Permitirle a Bedelía gestionar íntegramente el ciclo de asignaciones académicas sin depender de planillas de cálculo, estandarizando el flujo de trabajo en 9 pasos secuenciales:
|
||||
1. [x] **Paso 1 — Sede / Edificio:** Alta y mantenimiento del espacio físico (`/buildings/list_buildings`).
|
||||
2. [x] **Paso 2 — Aula (Física / Virtual):** Definición de espacios, capacidades de aforo y recursos (`/classrooms/list_classrooms`).
|
||||
3. [x] **Paso 3 — Ciclo Lectivo:** Definición del período académico y activación del cuatrimestre vigente (`/admin/academic_terms_list`).
|
||||
4. [x] **Paso 4 — Carrera / Titulación:** Alta del programa académico o plan de estudios (`/admin/careers_list`).
|
||||
5. [x] **Paso 5 — Asignatura / Materia:** Alta en el plan de estudios vinculada obligatoriamente a la Carrera (`/admin/subjects_list`).
|
||||
6. [x] **Paso 6 — Comisión:** Creación de comisiones vinculadas a la materia, carrera y ciclo lectivo con filtrado y visualización contextual (`/admin/commissions_list`).
|
||||
7. [x] **Paso 7 — Asociar Profesores:** Asignación previa del equipo de cátedra (titulares y adjuntos) con roles específicos (`/admin/commission_detail`).
|
||||
8. [x] **Paso 8 — Asociar Alumnos:** Matriculación de estudiantes en la comisión con validación de restricciones horarias (`/admin/commission_detail`).
|
||||
9. [x] **Paso 9 — Reserva de Espacios:** Asignación ágil del aula (física o virtual) a la comisión, con validación de conflictos en 1 clic (`/schedule/add_reservation` o Drag & Drop en `/schedule/calendar_view`).
|
||||
* **Asignaturas Compartidas entre Múltiples Carreras:**
|
||||
- [x] Modelo Many-to-Many (`subject_careers`) en base de datos.
|
||||
- [x] Asignación múltiple y visualización de badges por titulación en asignaturas y comisiones.
|
||||
- [x] Filtro por carrera unificado para materias compartidas.
|
||||
* **Canal de Importación de Planillas (Google Sheets):**
|
||||
- [x] Descubrimiento dinámico de pestañas para los 6 días semanales (Lunes a Sábado con GIDs oficiales).
|
||||
- [x] Desglose y normalización de carreras compuestas separadas por guion (`-`).
|
||||
- [x] Soporte de múltiples códigos de materia (`/`).
|
||||
- [x] Informe detallado por día de cursada (`by_day`) en UI.
|
||||
* **Documentación Operativa:**
|
||||
- [x] Manual del Personal de Bedelía con el flujo secuencial de 9 pasos.
|
||||
- [x] Manual del Docente (agenda, Google Meet y actas de notas).
|
||||
- [x] Manual del Estudiante (consulta de aulas y exámenes).
|
||||
* **Validación en Entorno Real:**
|
||||
- [x] Verificación en contenedor LXC productivo (`10.0.0.217` / `eduspace.oemspot.com.ar`).
|
||||
|
||||
---
|
||||
|
||||
### Fase 6: Despliegue en Servidores y Hardening 🏢 *(Planificada)*
|
||||
- [ ] Automatización de workers persistentes en systemd para la cola asíncrona de Moodle.
|
||||
- [ ] Configuración optimizada de `docker-compose.yml` de producción.
|
||||
- [ ] Pruebas de estrés de concurrencia y validación final de performance sub-segundo.
|
||||
|
||||
---
|
||||
|
||||
### Fase 7: Integración con Modelos de IA Locales (LLMs) & Asistente Virtual en la App 🤖 *(Diseñada / Por Implementar)*
|
||||
- [ ] **Pestaña de Asistente IA en Configuración Global**:
|
||||
- Incorporar en la vista de configuración general del Administrador una pestaña dedicada a la configuración de IA.
|
||||
- Parámetros configurables: URL del servidor de inferencia (Ollama, llama.cpp, vLLM, LiteLLM), Modelo seleccionado, Clave de API / Token, Timeout de conexión (por defecto 600s para entornos locales), y Switch de activación general.
|
||||
- Almacenamiento seguro de credenciales con Fernet en base de datos (`system_settings`).
|
||||
- [ ] **Módulo Backend Asíncrono de Inferencia (`httpx`)**:
|
||||
- Implementar servicio `AIService` utilizando `httpx.AsyncClient` con funciones asíncronas no bloqueantes (`async def` / `await`).
|
||||
- Gestión estructurada del historial y contexto mediante el estándar de roles (`system`, `user`, `assistant`).
|
||||
- Timeout generoso (600 segundos) para mitigar demoras en carga de modelos a VRAM o prompts extensos.
|
||||
- [ ] **Asistente Conversacional para Usuarios**:
|
||||
- Componente de interfaz flotante para guiar a Bedelía, Docentes y Alumnos en el uso de la plataforma.
|
||||
- Capacidades de consulta sobre asignaciones áulicas, cronogramas, comisiones y manuales operativos.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Package marker for backend
|
||||
+75
-94
@@ -1,103 +1,84 @@
|
||||
from flask import Flask, request, session
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from flask_babel import Babel, gettext as _
|
||||
"""
|
||||
Core Application Package (admin-edu-space)
|
||||
Refactored to pure FastAPI / SQLAlchemy 2.0 native architecture.
|
||||
Eliminated all Flask, Flask-SQLAlchemy, Flask-Babel, Flask-WTF and Flask-Login runtime dependencies.
|
||||
"""
|
||||
from typing import Any
|
||||
from database import db, get_db, engine, SessionLocal, session
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
babel = Babel()
|
||||
__version__ = "3.8.58"
|
||||
|
||||
def create_app(config_class=Config):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config_class)
|
||||
|
||||
# Initialize extensions with app
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
cors.init_app(app)
|
||||
|
||||
# Import models to ensure they are registered
|
||||
from app.models import user
|
||||
# Register REST API (v1) Blueprints with Stateless JWT support
|
||||
from app.routes.api.auth import api_auth_bp
|
||||
from app.routes.api.classrooms import api_classrooms_bp
|
||||
from app.routes.api.reservations import api_reservations_bp
|
||||
from app.routes.api.optimizer import api_optimizer_bp
|
||||
from app.routes.api.dashboard import api_dashboard_bp
|
||||
from app.routes.api.admin import api_admin_bp
|
||||
from app.routes.api.openapi import api_openapi_bp
|
||||
from app.routes.api.students import api_students_bp
|
||||
from app.routes.genetic_algorithm import genetic_bp
|
||||
from app.security import SecurityFilterChain
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
pass
|
||||
def push(self):
|
||||
pass
|
||||
def pop(self):
|
||||
pass
|
||||
|
||||
# Register API v1 blueprints
|
||||
app.register_blueprint(api_auth_bp)
|
||||
app.register_blueprint(api_classrooms_bp)
|
||||
app.register_blueprint(api_reservations_bp)
|
||||
app.register_blueprint(api_optimizer_bp)
|
||||
app.register_blueprint(api_dashboard_bp)
|
||||
app.register_blueprint(api_openapi_bp)
|
||||
app.register_blueprint(genetic_bp)
|
||||
app.register_blueprint(api_students_bp, url_prefix='/api/v1')
|
||||
app.register_blueprint(api_admin_bp, url_prefix='/api/v1')
|
||||
app.register_blueprint(api_admin_bp, url_prefix='/api/v1/admin', name='api_admin_prefixed')
|
||||
class TestClientWrapper:
|
||||
"""
|
||||
Adapter bridging FastAPI TestClient with legacy client expectations (res.get_json(), res.data).
|
||||
"""
|
||||
def __init__(self, fastapi_client: Any):
|
||||
self._client = fastapi_client
|
||||
|
||||
# Initialize Enterprise Security Pipeline (SecurityFilterChain)
|
||||
SecurityFilterChain(app)
|
||||
|
||||
# Language selector function
|
||||
def get_locale():
|
||||
# 1. Si el usuario está autenticado y tiene idioma configurado explícitamente en su perfil, prevalece.
|
||||
from flask_login import current_user
|
||||
if current_user.is_authenticated:
|
||||
if getattr(current_user, 'preferred_language', None) and current_user.preferred_language in app.config['LANGUAGES']:
|
||||
return current_user.preferred_language
|
||||
# El idioma por defecto siempre será español a menos que se configure a mano
|
||||
return app.config['BABEL_DEFAULT_LOCALE']
|
||||
|
||||
# 2. Parámetro explícito en la URL (?lang=es o ?lang=en) (para usuarios no autenticados o login)
|
||||
lang = request.args.get('lang')
|
||||
if lang and lang in app.config['LANGUAGES']:
|
||||
session['language'] = lang
|
||||
return lang
|
||||
|
||||
# 3. Si ya hay un idioma guardado en la sesión
|
||||
if 'language' in session and session['language'] in app.config['LANGUAGES']:
|
||||
return session['language']
|
||||
|
||||
# 4. Primera vez que se accede a la web (sin sesión): respetar el idioma del navegador
|
||||
if request.accept_languages:
|
||||
for accepted_lang, _quality in request.accept_languages:
|
||||
primary = accepted_lang.split('-')[0].lower()
|
||||
if primary in app.config['LANGUAGES']:
|
||||
session['language'] = primary # Se guarda para la sesión actual
|
||||
return primary
|
||||
def _wrap(self, res: Any) -> Any:
|
||||
try:
|
||||
db.session.expire_all()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
parsed = res.json()
|
||||
if isinstance(parsed, dict):
|
||||
if 'detail' in parsed and 'message' not in parsed:
|
||||
parsed['message'] = parsed['detail']
|
||||
if 'detail' in parsed and 'error' not in parsed:
|
||||
parsed['error'] = parsed['detail']
|
||||
setattr(res, 'get_json', lambda: parsed)
|
||||
except Exception:
|
||||
setattr(res, 'get_json', lambda: {})
|
||||
setattr(res, 'data', getattr(res, 'content', b''))
|
||||
return res
|
||||
|
||||
# Fallback del sistema: Español
|
||||
return app.config['BABEL_DEFAULT_LOCALE']
|
||||
def get(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.get(*args, **kwargs))
|
||||
|
||||
def post(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.post(*args, **kwargs))
|
||||
|
||||
# Babel context processor
|
||||
@app.context_processor
|
||||
def inject_conf_vars():
|
||||
return dict(
|
||||
languages=app.config['LANGUAGES'],
|
||||
current_lang=str(get_locale())
|
||||
)
|
||||
def put(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.put(*args, **kwargs))
|
||||
|
||||
|
||||
# Configure Babel
|
||||
babel.init_app(app, locale_selector=get_locale)
|
||||
|
||||
# Register localized date and datetime formatters for Jinja2 templates
|
||||
from flask_babel import format_date, format_datetime
|
||||
app.jinja_env.globals['format_date'] = format_date
|
||||
app.jinja_env.globals['format_datetime'] = format_datetime
|
||||
app.jinja_env.filters['format_date'] = format_date
|
||||
app.jinja_env.filters['format_datetime'] = format_datetime
|
||||
|
||||
return app
|
||||
def patch(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.patch(*args, **kwargs))
|
||||
|
||||
def delete(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.delete(*args, **kwargs))
|
||||
|
||||
class AppCompatWrapper:
|
||||
"""
|
||||
Compatibility container for test suites and scripts.
|
||||
Delegates to FastAPI core without any Flask runtime dependency.
|
||||
"""
|
||||
def __init__(self, config_class: Any = Config):
|
||||
self.config: dict[str, Any] = {
|
||||
'TESTING': False,
|
||||
'SQLALCHEMY_DATABASE_URI': Config.SQLALCHEMY_DATABASE_URI,
|
||||
'SECRET_KEY': Config.SECRET_KEY,
|
||||
'LANGUAGES': Config.LANGUAGES
|
||||
}
|
||||
|
||||
def app_context(self):
|
||||
return DummyContext()
|
||||
|
||||
def test_client(self):
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app as fastapi_app
|
||||
return TestClientWrapper(TestClient(fastapi_app))
|
||||
|
||||
def create_app(config_class: Any = Config) -> AppCompatWrapper:
|
||||
return AppCompatWrapper(config_class)
|
||||
@@ -1,17 +0,0 @@
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, PasswordField, BooleanField, SubmitField
|
||||
from wtforms.validators import DataRequired, Email, Length
|
||||
from flask_babel import lazy_gettext as _l
|
||||
|
||||
class LoginForm(FlaskForm):
|
||||
email = StringField(_l('Email'),
|
||||
validators=[
|
||||
DataRequired(),
|
||||
Email(),
|
||||
Length(max=120)
|
||||
],
|
||||
filters=[lambda x: x.strip().lower() if x else '']
|
||||
)
|
||||
password = PasswordField(_l('Password'), validators=[DataRequired()])
|
||||
remember_me = BooleanField(_l('Remember me'))
|
||||
submit = SubmitField(_l('Sign In'))
|
||||
@@ -1,28 +0,0 @@
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField
|
||||
from wtforms.validators import DataRequired, Length, NumberRange, Optional
|
||||
from flask_babel import lazy_gettext as _l
|
||||
|
||||
class BuildingForm(FlaskForm):
|
||||
name = StringField(_l('Building Name'), validators=[
|
||||
DataRequired(),
|
||||
Length(min=2, max=100)
|
||||
])
|
||||
code = StringField(_l('Code'), validators=[
|
||||
Optional(),
|
||||
Length(max=50)
|
||||
])
|
||||
address = StringField(_l('Address'), validators=[
|
||||
Optional(),
|
||||
Length(max=255)
|
||||
])
|
||||
floors = IntegerField(_l('Number of Floors'), default=1, validators=[
|
||||
DataRequired(),
|
||||
NumberRange(min=1, max=100)
|
||||
])
|
||||
description = TextAreaField(_l('Description'), validators=[
|
||||
Optional(),
|
||||
Length(max=500)
|
||||
])
|
||||
is_active = BooleanField(_l('Active'), default=True)
|
||||
submit = SubmitField(_l('Save Building'))
|
||||
@@ -1,56 +0,0 @@
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField, SelectField
|
||||
from wtforms.validators import DataRequired, InputRequired, Length, NumberRange, Optional, ValidationError
|
||||
from flask_babel import lazy_gettext as _l
|
||||
|
||||
def validate_capacity(form, field):
|
||||
val = str(field.data or '').strip()
|
||||
if not val:
|
||||
raise ValidationError(_l('La capacidad es obligatoria (ingrese un número o el símbolo ∞).'))
|
||||
if val in ['∞', 'inf', 'INF', 'Infinity', 'infinity', '0', 'ilimitada', 'Ilimitada', 'sin limite', 'Sin límite']:
|
||||
return
|
||||
try:
|
||||
num = int(val)
|
||||
if num < 0:
|
||||
raise ValidationError(_l('La capacidad no puede ser negativa.'))
|
||||
if num > 10000:
|
||||
raise ValidationError(_l('La capacidad máxima numérica es 10.000.'))
|
||||
except ValueError:
|
||||
raise ValidationError(_l('Ingrese un número entero o el símbolo ∞ para capacidad ilimitada.'))
|
||||
|
||||
class ClassroomForm(FlaskForm):
|
||||
building_id = SelectField(_l('Edificio'), validators=[DataRequired()])
|
||||
new_building_name = StringField(_l('Nombre del Nuevo Edificio'), validators=[Optional(), Length(max=100)])
|
||||
room_number = StringField(_l('Número / Nombre del Aula'), validators=[
|
||||
DataRequired(),
|
||||
Length(min=1, max=50)
|
||||
])
|
||||
floor = StringField(_l('Piso'), validators=[
|
||||
DataRequired(message=_l('El piso es obligatorio (ej: PB, 1, 2, 4°P)')),
|
||||
Length(min=1, max=50)
|
||||
])
|
||||
capacity = StringField(_l('Capacidad'), validators=[
|
||||
validate_capacity
|
||||
])
|
||||
description = TextAreaField(_l('Descripción'), validators=[
|
||||
Optional(),
|
||||
Length(max=500)
|
||||
])
|
||||
is_active = BooleanField(_l('Activa'), default=True)
|
||||
submit = SubmitField(_l('Guardar Aula'))
|
||||
|
||||
class ClassroomResourceForm(FlaskForm):
|
||||
resource_type = SelectField(_l('Resource Type'), choices=[
|
||||
('PROJECTOR', _l('Projector')),
|
||||
('WHITEBOARD', _l('Whiteboard')),
|
||||
('COMPUTER', _l('Computer')),
|
||||
('SOUND_SYSTEM', _l('Sound System')),
|
||||
('MICROPHONE', _l('Microphone')),
|
||||
('AIR_CONDITIONER', _l('Air Conditioner')),
|
||||
('OTHER', _l('Other'))
|
||||
], validators=[DataRequired()])
|
||||
brand = StringField(_l('Brand'), validators=[Optional(), Length(max=100)])
|
||||
model = StringField(_l('Model'), validators=[Optional(), Length(max=100)])
|
||||
specifications = TextAreaField(_l('Specifications'), validators=[Optional()])
|
||||
functional = BooleanField(_l('Functional'), default=True)
|
||||
submit = SubmitField(_l('Save Resource'))
|
||||
@@ -1,49 +0,0 @@
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import SelectField, StringField, TextAreaField, IntegerField, SubmitField, DateTimeLocalField
|
||||
from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError
|
||||
from flask_babel import lazy_gettext as _l
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
class ReservationForm(FlaskForm):
|
||||
classroom_id = SelectField(_l('Classroom'), coerce=int, validators=[DataRequired()])
|
||||
commission_id = SelectField(_l('Commission/Subject'), coerce=int, validators=[DataRequired()])
|
||||
start_time = DateTimeLocalField(_l('Start Time'), format='%Y-%m-%dT%H:%M', validators=[DataRequired()])
|
||||
end_time = DateTimeLocalField(_l('End Time'), format='%Y-%m-%dT%H:%M', validators=[DataRequired()])
|
||||
purpose = StringField(_l('Purpose'), validators=[
|
||||
DataRequired(),
|
||||
Length(min=3, max=500)
|
||||
])
|
||||
expected_attendees = IntegerField(_l('Expected Attendees'), validators=[
|
||||
DataRequired(),
|
||||
NumberRange(min=1, max=500)
|
||||
])
|
||||
notes = TextAreaField(_l('Notes'), validators=[
|
||||
Optional(),
|
||||
Length(max=1000)
|
||||
])
|
||||
virtual_link = StringField(_l('Virtual Classroom Link'), validators=[
|
||||
Optional(),
|
||||
Length(max=500)
|
||||
])
|
||||
submit = SubmitField(_l('Make Reservation'))
|
||||
|
||||
def __init__(self, *args, is_edit=False, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.is_edit = is_edit
|
||||
|
||||
def validate_end_time(self, field):
|
||||
if field.data <= self.start_time.data:
|
||||
raise ValidationError('End time must be after start time.')
|
||||
|
||||
# Check if duration is reasonable (max 8 hours)
|
||||
if field.data > self.start_time.data + timedelta(hours=8):
|
||||
raise ValidationError('Reservation cannot exceed 8 hours.')
|
||||
|
||||
def validate_start_time(self, field):
|
||||
# Don't allow new reservations in the past
|
||||
if not self.is_edit and field.data < datetime.now() - timedelta(minutes=10):
|
||||
raise ValidationError('Start time cannot be in the past.')
|
||||
|
||||
# Don't allow reservations too far in the future (max 3 months)
|
||||
if field.data > datetime.now() + timedelta(days=90):
|
||||
raise ValidationError('Reservations cannot be made more than 3 months in advance.')
|
||||
@@ -13,6 +13,9 @@ from .enrollment import StudentEnrollment
|
||||
from .setting import SystemSetting
|
||||
from .grade import MilestoneGrade
|
||||
from .sync_task import MoodleSyncTask
|
||||
from .knowledge_chunk import KnowledgeChunk
|
||||
from .institutional_benefit import InstitutionalBenefit
|
||||
from .access_log_qr import AccessLogQR
|
||||
|
||||
__all__ = [
|
||||
'User',
|
||||
@@ -38,5 +41,8 @@ __all__ = [
|
||||
'StudentEnrollment',
|
||||
'SystemSetting',
|
||||
'MilestoneGrade',
|
||||
'MoodleSyncTask'
|
||||
'MoodleSyncTask',
|
||||
'KnowledgeChunk',
|
||||
'InstitutionalBenefit',
|
||||
'AccessLogQR'
|
||||
]
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class AcademicTerm(db.Model):
|
||||
"""Modelo para Ciclos Lectivos y Períodos Académicos"""
|
||||
@@ -14,7 +14,10 @@ class AcademicTerm(db.Model):
|
||||
end_date = db.Column(db.Date, nullable=True)
|
||||
is_current = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from app import db
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class AccessLogQR(db.Model):
|
||||
"""
|
||||
Registro y trazabilidad de ingresos escaneados por código QR en Recepción (SDD-012).
|
||||
Permite auditar el ingreso físico de alumnos y docentes a las sedes institucionales.
|
||||
"""
|
||||
__tablename__ = 'access_logs_qr'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
building_id = db.Column(db.Integer, db.ForeignKey('buildings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
scanned_by_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
scanned_at = db.Column(
|
||||
db.DateTime,
|
||||
default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
nullable=False,
|
||||
index=True
|
||||
)
|
||||
status = db.Column(db.String(20), default='AUTORIZADO', nullable=False) # AUTORIZADO, DENEGADO, RESTRINGIDO
|
||||
reason = db.Column(db.String(150), nullable=True)
|
||||
|
||||
# Relaciones
|
||||
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('qr_access_logs', lazy='dynamic'))
|
||||
building = db.relationship('Building', foreign_keys=[building_id])
|
||||
scanned_by = db.relationship('User', foreign_keys=[scanned_by_user_id])
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serializa el registro de acceso a diccionario JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'user_name': self.user.name if self.user else 'Desconocido',
|
||||
'user_dni': self.user.document_number if self.user else None,
|
||||
'user_role': self.user.role if self.user else None,
|
||||
'building_id': self.building_id,
|
||||
'building_name': self.building.name if self.building else 'Sede Desconocida',
|
||||
'scanned_by_user_id': self.scanned_by_user_id,
|
||||
'scanned_by_name': self.scanned_by.name if self.scanned_by else 'Sistema',
|
||||
'scanned_at': self.scanned_at.isoformat() if self.scanned_at else None,
|
||||
'status': self.status,
|
||||
'reason': self.reason
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class AuditLog(db.Model):
|
||||
"""
|
||||
@@ -16,10 +16,30 @@ class AuditLog(db.Model):
|
||||
entity_id = db.Column(db.Integer, nullable=True) # ID del registro afectado
|
||||
details = db.Column(db.Text, nullable=True) # Detalles de cambios o parámetros
|
||||
ip_address = db.Column(db.String(45), nullable=True) # Soporta IPv4 e IPv6
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), nullable=False, index=True)
|
||||
|
||||
# Relación con usuario
|
||||
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('audit_records', lazy='dynamic'))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for k, v in kwargs.items():
|
||||
setattr(self, k, v)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<AuditLog #{self.id} {self.action} on {self.module} by {self.user_email or 'System'}>"
|
||||
|
||||
def to_dict(self):
|
||||
"""Serializa el registro de auditoría a diccionario JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'user_email': self.user_email,
|
||||
'action': self.action,
|
||||
'module': self.module,
|
||||
'entity_id': self.entity_id,
|
||||
'details': self.details,
|
||||
'ip_address': self.ip_address,
|
||||
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
|
||||
'created_at_iso': self.created_at.isoformat() if self.created_at else None
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class Building(db.Model):
|
||||
__tablename__ = 'buildings'
|
||||
@@ -11,11 +11,14 @@ class Building(db.Model):
|
||||
floors = db.Column(db.Integer, default=1, nullable=False)
|
||||
description = db.Column(db.Text, nullable=True)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
classrooms = db.relationship('Classroom', backref='building_entity', lazy=True, foreign_keys='Classroom.building_id')
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def is_virtual(self):
|
||||
|
||||
@@ -1,25 +1,34 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, List, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.subject import Subject
|
||||
|
||||
class Career(db.Model):
|
||||
__tablename__ = 'careers'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(150), unique=True, nullable=False, index=True)
|
||||
code = db.Column(db.String(50), nullable=True)
|
||||
description = db.Column(db.Text, nullable=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
subjects = db.relationship('Subject', backref='career_obj', lazy=True)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
subs = getattr(self, 'subjects', None)
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'code': self.code,
|
||||
'description': self.description,
|
||||
'subjects_count': len(self.subjects) if self.subjects else 0,
|
||||
'subjects_count': len(subs) if isinstance(subs, (list, set, tuple)) else 0,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Optional, List
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.building import Building
|
||||
from app.models.reservation import Reservation
|
||||
|
||||
class Classroom(db.Model):
|
||||
__tablename__ = 'classrooms'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
if TYPE_CHECKING:
|
||||
building_entity: Optional['Building']
|
||||
reservations: List['Reservation']
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
campus_id = db.Column(db.Integer, nullable=True) # Maps to campus_id in DB
|
||||
@@ -13,8 +23,11 @@ class Classroom(db.Model):
|
||||
capacity = db.Column(db.Integer, nullable=False)
|
||||
description = db.Column(db.Text)
|
||||
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Relación con Building (mapeada vía backref 'building_entity' en Building.classrooms)
|
||||
@property
|
||||
@@ -30,13 +43,24 @@ class Classroom(db.Model):
|
||||
|
||||
@property
|
||||
def floor_display(self):
|
||||
"""Formato amigable para el piso: PB, Planta Baja, Piso X"""
|
||||
"""Formato amigable y dinámico para el piso: PB, EP, Subsuelo, Piso X"""
|
||||
if self.is_virtual:
|
||||
return 'Campus Virtual'
|
||||
f = str(self.floor).strip() if self.floor is not None else ''
|
||||
if f in ['0', 'PB', 'pb', 'Planta Baja', 'planta baja']:
|
||||
return 'Planta Baja'
|
||||
if f.lower().startswith('piso') or '°' in f:
|
||||
if not f:
|
||||
return 'Planta Baja (PB)'
|
||||
f_lower = f.lower()
|
||||
if f in ['0', 'PB', 'pb'] or 'planta baja' in f_lower:
|
||||
return 'Planta Baja (PB)'
|
||||
if f in ['EP', 'ep'] or 'entrepiso' in f_lower:
|
||||
return 'Entrepiso (EP)'
|
||||
if f in ['SS', 'ss'] or 'subsuelo' in f_lower:
|
||||
return f if 'subsuelo' in f_lower else 'Subsuelo (SS)'
|
||||
if f_lower.startswith('piso') or f_lower.startswith('planta') or f_lower.startswith('nivel') or '°' in f:
|
||||
return f
|
||||
return f"Piso {f}"
|
||||
if f.isdigit():
|
||||
return f"Piso {f}"
|
||||
return f
|
||||
|
||||
@property
|
||||
def is_virtual(self):
|
||||
@@ -193,8 +217,8 @@ class ClassroomResource(db.Model):
|
||||
specifications = db.Column(db.Text)
|
||||
functional = db.Column(db.Boolean, default=True)
|
||||
last_maintenance_date = db.Column(db.DateTime)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
classroom = db.relationship('Classroom', backref=db.backref('resources', lazy=True, cascade='all, delete-orphan'))
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from app.models.subject import Commission, CommissionTeacher
|
||||
|
||||
__all__ = ['Commission', 'CommissionTeacher']
|
||||
@@ -0,0 +1,3 @@
|
||||
from app.models.subject import CommissionTeacher
|
||||
|
||||
__all__ = ['CommissionTeacher']
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
class StudentEnrollment(db.Model):
|
||||
@@ -20,8 +20,8 @@ class StudentEnrollment(db.Model):
|
||||
index=True
|
||||
)
|
||||
status = db.Column(db.String(20), nullable=False, default='activo') # activo | retirado | condicional
|
||||
enrolled_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
enrolled_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), nullable=False)
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
notes = db.Column(db.Text, nullable=True)
|
||||
allow_same_day_exception = db.Column(db.Boolean, default=False, nullable=True)
|
||||
exception_reason = db.Column(db.String(255), nullable=True)
|
||||
@@ -35,6 +35,9 @@ class StudentEnrollment(db.Model):
|
||||
student = db.relationship('User', backref=db.backref('enrollments', lazy='dynamic', cascade='all, delete-orphan'))
|
||||
commission = db.relationship('Commission', backref=db.backref('enrollments', lazy='dynamic', cascade='all, delete-orphan'))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import random
|
||||
import copy
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Dict, Tuple, Optional
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Dict, Tuple, Optional, Any
|
||||
from dataclasses import dataclass
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.subject import Commission
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dataclass
|
||||
class ReservationRequest:
|
||||
@@ -19,7 +21,7 @@ class ReservationRequest:
|
||||
preferred_end_time: datetime
|
||||
priority: int = 1 # 1=highest, 5=lowest
|
||||
flexibility_hours: int = 2 # How flexible the start time can be
|
||||
subject_requirements: Dict = None # Special requirements for the subject
|
||||
subject_requirements: Optional[Dict[str, Any]] = None # Special requirements for the subject
|
||||
|
||||
def __post_init__(self):
|
||||
if self.subject_requirements is None:
|
||||
@@ -145,7 +147,7 @@ class Individual:
|
||||
return -conflicts * 0.5 # Penalty for each conflict
|
||||
return 1.0
|
||||
|
||||
def _calculate_resource_score(self, classroom: Classroom, requirements: Dict) -> float:
|
||||
def _calculate_resource_score(self, classroom: Classroom, requirements: Optional[Dict[str, Any]] = None) -> float:
|
||||
"""Check if classroom meets subject requirements"""
|
||||
if not requirements:
|
||||
return 1.0
|
||||
@@ -175,8 +177,8 @@ class GeneticAlgorithm:
|
||||
"""Run genetic algorithm with high concurrency to find optimal reservation schedule"""
|
||||
import concurrent.futures
|
||||
|
||||
classrooms_dict = {c.id: c for c in available_classrooms}
|
||||
requests_dict = {r.commission_id: r for r in requests}
|
||||
classrooms_dict: Dict[int, Classroom] = {int(getattr(c, 'id')): c for c in available_classrooms}
|
||||
requests_dict = {getattr(r, 'commission_id'): r for r in requests}
|
||||
|
||||
# Initialize population
|
||||
population = self._initialize_population(requests, available_classrooms, start_date, end_date)
|
||||
@@ -248,6 +250,8 @@ class GeneticAlgorithm:
|
||||
for request in requests:
|
||||
# Random classroom selection (with capacity constraint)
|
||||
suitable_classrooms = [c for c in classrooms if c.capacity >= request.expected_attendees]
|
||||
if not suitable_classrooms and classrooms:
|
||||
suitable_classrooms = [max(classrooms, key=lambda c: getattr(c, 'capacity', 0))]
|
||||
if not suitable_classrooms:
|
||||
continue
|
||||
|
||||
@@ -260,8 +264,8 @@ class GeneticAlgorithm:
|
||||
end_time = start_time + duration
|
||||
|
||||
gene = Gene(
|
||||
commission_id=request.commission_id,
|
||||
classroom_id=classroom.id,
|
||||
commission_id=getattr(request, 'commission_id'),
|
||||
classroom_id=int(getattr(classroom, 'id')),
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
expected_attendees=request.expected_attendees,
|
||||
@@ -306,8 +310,11 @@ class GeneticAlgorithm:
|
||||
if mutation_type == 'classroom':
|
||||
# Change classroom
|
||||
suitable_classrooms = [c for c in classrooms if c.capacity >= gene_to_mutate.expected_attendees]
|
||||
if not suitable_classrooms and classrooms:
|
||||
suitable_classrooms = [max(classrooms, key=lambda c: getattr(c, 'capacity', 0))]
|
||||
if suitable_classrooms:
|
||||
gene_to_mutate.classroom_id = random.choice(suitable_classrooms).id
|
||||
selected_room = random.choice(suitable_classrooms)
|
||||
gene_to_mutate.classroom_id = int(getattr(selected_room, 'id'))
|
||||
|
||||
elif mutation_type == 'time':
|
||||
# Slightly adjust time
|
||||
@@ -326,14 +333,14 @@ class ReservationOptimizer:
|
||||
|
||||
def optimize_schedule(self, commission_ids: List[int],
|
||||
admin_user_id: int,
|
||||
start_date: datetime = None,
|
||||
end_date: datetime = None,
|
||||
start_date: Optional[datetime] = None,
|
||||
end_date: Optional[datetime] = None,
|
||||
progress_callback = None) -> Dict:
|
||||
"""Optimize reservation schedule for given commissions"""
|
||||
|
||||
# Default date range if not provided
|
||||
if not start_date:
|
||||
start_date = datetime.utcnow()
|
||||
start_date = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
if not end_date:
|
||||
end_date = start_date + timedelta(days=30)
|
||||
|
||||
@@ -391,7 +398,7 @@ class ReservationOptimizer:
|
||||
|
||||
def _calculate_preferred_time(self, commission: Commission) -> Dict:
|
||||
"""Calculate preferred time slots for a commission based on shift and schedule"""
|
||||
current_date = datetime.utcnow()
|
||||
current_date = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Determine day of week from commission schedule or default to Monday
|
||||
target_weekday = 0 # Monday
|
||||
@@ -436,13 +443,26 @@ class ReservationOptimizer:
|
||||
def apply_optimized_reservations(self, reservation_data: List[Dict]) -> List[Reservation]:
|
||||
"""Apply the optimized reservations to the database with ISO string parsing and conflict avoidance"""
|
||||
applied_reservations = []
|
||||
valid_keys = {
|
||||
'classroom_id', 'commission_id', 'user_id', 'start_time',
|
||||
'end_time', 'purpose', 'status', 'expected_attendees',
|
||||
'shift', 'virtual_link', 'notes'
|
||||
}
|
||||
|
||||
for item in reservation_data:
|
||||
data = dict(item)
|
||||
if isinstance(data.get('start_time'), str):
|
||||
data['start_time'] = datetime.fromisoformat(data['start_time'].replace('Z', '+00:00'))
|
||||
if isinstance(data.get('end_time'), str):
|
||||
data['end_time'] = datetime.fromisoformat(data['end_time'].replace('Z', '+00:00'))
|
||||
|
||||
# Normalizar fechas a objetos datetime naive (UTC)
|
||||
for time_field in ('start_time', 'end_time'):
|
||||
val = data.get(time_field)
|
||||
if isinstance(val, str):
|
||||
dt = datetime.fromisoformat(val.replace('Z', '+00:00'))
|
||||
data[time_field] = dt.replace(tzinfo=None) if dt.tzinfo else dt
|
||||
elif isinstance(val, datetime) and val.tzinfo:
|
||||
data[time_field] = val.replace(tzinfo=None)
|
||||
|
||||
if not data.get('classroom_id') or not data.get('start_time') or not data.get('end_time'):
|
||||
continue
|
||||
|
||||
# Check for physical room conflicts before creating
|
||||
conflicts = Reservation.find_conflicts(
|
||||
@@ -452,17 +472,14 @@ class ReservationOptimizer:
|
||||
)
|
||||
|
||||
if not conflicts:
|
||||
# Ensure status enum value compatibility
|
||||
if 'status' in data and isinstance(data['status'], str):
|
||||
try:
|
||||
data['status'] = ReservationStatus(data['status']).value
|
||||
except ValueError:
|
||||
data['status'] = ReservationStatus.CONFIRMED.value
|
||||
reservation = Reservation(**data)
|
||||
# Las reservas aplicadas pasan a estado CONFIRMED
|
||||
data['status'] = ReservationStatus.CONFIRMED.value
|
||||
filtered_data = {k: v for k, v in data.items() if k in valid_keys}
|
||||
reservation = Reservation(**filtered_data)
|
||||
db.session.add(reservation)
|
||||
applied_reservations.append(reservation)
|
||||
else:
|
||||
current_app.logger.warning(f"Conflict detected for reservation during genetic apply: {data}")
|
||||
logger.warning(f"Conflict detected for reservation during genetic apply: {data}")
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from app import db
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ class MilestoneGrade(db.Model):
|
||||
db.ForeignKey('users.id', ondelete='SET NULL'),
|
||||
nullable=True
|
||||
)
|
||||
graded_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
graded_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Restricción de unicidad: un estudiante tiene una única nota por hito
|
||||
__table_args__ = (
|
||||
@@ -50,20 +50,28 @@ class MilestoneGrade(db.Model):
|
||||
student = db.relationship('User', foreign_keys=[student_id], backref=db.backref('received_grades', lazy='dynamic'))
|
||||
graded_by = db.relationship('User', foreign_keys=[graded_by_user_id])
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def is_passed(self) -> bool:
|
||||
"""Determina si la nota está aprobada (>= 4.00 y no ausente)."""
|
||||
if self.is_absent or self.score is None:
|
||||
if getattr(self, 'is_absent', False):
|
||||
return False
|
||||
return self.score >= 4.0
|
||||
score_val = getattr(self, 'score', None)
|
||||
if score_val is None:
|
||||
return False
|
||||
return float(score_val) >= 4.0
|
||||
|
||||
@property
|
||||
def display_score(self) -> str:
|
||||
"""Representación textual estándar: 'Ausente', '7.5' o '-'."""
|
||||
if self.is_absent:
|
||||
if getattr(self, 'is_absent', False):
|
||||
return 'Ausente'
|
||||
if self.score is not None:
|
||||
return f'{self.score:.1f}' if self.score % 1 != 0 else f'{int(self.score)}'
|
||||
score_val = getattr(self, 'score', None)
|
||||
if score_val is not None:
|
||||
val = float(score_val)
|
||||
return f'{val:.1f}' if val % 1 != 0 else f'{int(val)}'
|
||||
return '-'
|
||||
|
||||
def to_dict(self):
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
from app import db
|
||||
from datetime import datetime, timezone, date
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
class InstitutionalBenefit(db.Model):
|
||||
"""
|
||||
Modelo de Beneficios y Convenios Comerciales Institucionales para UniCABA (SDD-012).
|
||||
Permite a Bedelía y Administradores cargar promociones, descuentos y convenios
|
||||
con comercios (cafeterías, librerías, tecnología, salud) para alumnos y docentes.
|
||||
"""
|
||||
__tablename__ = 'institutional_benefits'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
title = db.Column(db.String(150), nullable=False, index=True)
|
||||
partner_name = db.Column(db.String(120), nullable=False, index=True)
|
||||
category = db.Column(db.String(50), nullable=False, default='GENERAL', index=True)
|
||||
discount_label = db.Column(db.String(80), nullable=False)
|
||||
description = db.Column(db.Text, nullable=True)
|
||||
terms_conditions = db.Column(db.Text, nullable=True)
|
||||
target_roles = db.Column(db.String(100), nullable=False, default='ALL')
|
||||
building_id = db.Column(db.Integer, db.ForeignKey('buildings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
coupon_code = db.Column(db.String(50), nullable=True)
|
||||
valid_from = db.Column(db.Date, nullable=False, default=date.today)
|
||||
valid_until = db.Column(db.Date, nullable=True)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False, index=True)
|
||||
image_url = db.Column(db.String(255), nullable=True)
|
||||
created_by_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(
|
||||
db.DateTime,
|
||||
default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
)
|
||||
|
||||
# Relaciones
|
||||
building = db.relationship('Building', backref=db.backref('institutional_benefits', lazy='dynamic'))
|
||||
creator = db.relationship('User', foreign_keys=[created_by_user_id])
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def is_currently_valid(self) -> bool:
|
||||
"""Determina si el convenio está activo y dentro de su rango de vigencia."""
|
||||
if not self.is_active:
|
||||
return False
|
||||
today = date.today()
|
||||
if self.valid_from and self.valid_from > today:
|
||||
return False
|
||||
if self.valid_until and self.valid_until < today:
|
||||
return False
|
||||
return True
|
||||
|
||||
def applies_to_role(self, role: str) -> bool:
|
||||
"""Verifica si el beneficio aplica al rol indicado (alumno, docente, bedelia, admin)."""
|
||||
if not role:
|
||||
return False
|
||||
target = (self.target_roles or 'ALL').upper()
|
||||
if 'ALL' in target or 'TODOS' in target:
|
||||
return True
|
||||
r = role.strip().upper()
|
||||
if r in target:
|
||||
return True
|
||||
if r in ['ESTUDIANTE', 'ALUMNO'] and ('ALUMNO' in target or 'ESTUDIANTE' in target):
|
||||
return True
|
||||
if r in ['DOCENTE', 'PROFESOR', 'TEACHER'] and ('DOCENTE' in target or 'PROFESOR' in target):
|
||||
return True
|
||||
return False
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serializa la entidad a diccionario compatible con JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'title': self.title,
|
||||
'partner_name': self.partner_name,
|
||||
'category': self.category,
|
||||
'discount_label': self.discount_label,
|
||||
'description': self.description,
|
||||
'terms_conditions': self.terms_conditions,
|
||||
'target_roles': self.target_roles,
|
||||
'building_id': self.building_id,
|
||||
'building_name': self.building.name if self.building else 'Todas las Sedes',
|
||||
'coupon_code': self.coupon_code,
|
||||
'valid_from': self.valid_from.isoformat() if self.valid_from else None,
|
||||
'valid_until': self.valid_until.isoformat() if self.valid_until else None,
|
||||
'is_active': self.is_active,
|
||||
'is_currently_valid': self.is_currently_valid,
|
||||
'image_url': self.image_url,
|
||||
'created_by_user_id': self.created_by_user_id,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime, timezone
|
||||
from app import db
|
||||
|
||||
|
||||
class KnowledgeChunk(db.Model):
|
||||
"""
|
||||
Fragmentos de documentación oficial indexados para la arquitectura RAG de UdeCi.
|
||||
Permite recuperación semántica eficiente y filtrado estricto por rol.
|
||||
"""
|
||||
__tablename__ = 'knowledge_chunks'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
title = db.Column(db.String(150), nullable=False)
|
||||
content = db.Column(db.Text, nullable=False)
|
||||
role = db.Column(db.String(50), nullable=False, default='general', index=True)
|
||||
keywords = db.Column(db.String(255), nullable=True, index=True)
|
||||
category = db.Column(db.String(50), nullable=True, default='manual')
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'title': self.title,
|
||||
'content': self.content,
|
||||
'role': self.role,
|
||||
'keywords': self.keywords,
|
||||
'category': self.category
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
from app import db
|
||||
|
||||
class MilestoneType(db.Model):
|
||||
@@ -15,12 +16,15 @@ class MilestoneType(db.Model):
|
||||
description = db.Column(db.String(255), nullable=True)
|
||||
sort_order = db.Column(db.Integer, default=0) # Orden de aparición en selects
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False) # Activo / Inactivo
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relación uno-a-muchos con AcademicMilestone
|
||||
milestones = db.relationship('AcademicMilestone', backref='type_obj', lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
@@ -42,6 +46,10 @@ class AcademicMilestone(db.Model):
|
||||
Hito o evento académico programado para una materia/comisión (Examen, TP, Entrega).
|
||||
"""
|
||||
__tablename__ = 'academic_milestones'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
if TYPE_CHECKING:
|
||||
type_obj: Optional['MilestoneType']
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
title = db.Column(db.String(150), nullable=True)
|
||||
@@ -54,13 +62,16 @@ class AcademicMilestone(db.Model):
|
||||
link = db.Column(db.String(255), nullable=True) # Link Teams / Meet / Zoom si aplica
|
||||
notes = db.Column(db.Text, nullable=True) # Temario, consignas o notas
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relación con Asignatura y Comisión
|
||||
subject = db.relationship('Subject', backref=db.backref('milestones', lazy='dynamic'))
|
||||
commission = db.relationship('Commission', backref=db.backref('academic_milestones', lazy='dynamic', cascade='all, delete-orphan'))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def tipo(self):
|
||||
return self.type_obj.name if self.type_obj else 'Otro'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum
|
||||
from sqlalchemy.types import TypeDecorator, String
|
||||
|
||||
@@ -33,8 +33,15 @@ class ReservationStatus(Enum):
|
||||
COMPLETED = 'COMPLETED'
|
||||
NO_SHOW = 'NO_SHOW'
|
||||
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
class Reservation(db.Model):
|
||||
__tablename__ = 'reservations'
|
||||
__allow_unmapped__ = True
|
||||
if TYPE_CHECKING:
|
||||
user: Any
|
||||
classroom: Any
|
||||
commission: Any
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
classroom_id = db.Column(db.Integer, db.ForeignKey('classrooms.id'), nullable=False)
|
||||
@@ -50,8 +57,11 @@ class Reservation(db.Model):
|
||||
virtual_link = db.Column(db.String(500), nullable=True) # Zoom, Meet, Teams, etc.
|
||||
notes = db.Column(db.Text)
|
||||
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Virtual property to convert status string to enum
|
||||
@property
|
||||
@@ -134,8 +144,8 @@ class Reservation(db.Model):
|
||||
|
||||
def can_be_cancelled(self):
|
||||
"""Check if reservation can be cancelled (24 hours before start)"""
|
||||
from datetime import timedelta
|
||||
return self.start_time > datetime.utcnow() + timedelta(hours=24)
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
return self.start_time > now + timedelta(hours=24)
|
||||
|
||||
def check_conflict(self, other_reservation):
|
||||
"""Check if this reservation conflicts with another"""
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, List, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
# Definition of system modules available for RBAC permissions
|
||||
SYSTEM_MODULES = [
|
||||
@@ -79,6 +83,20 @@ SYSTEM_MODULES = [
|
||||
'name_en': 'Enrollments & Courses',
|
||||
'icon': 'bi-diagram-3',
|
||||
'description': 'Gestión de inscripciones de alumnos a comisiones y asignación de docentes.'
|
||||
},
|
||||
{
|
||||
'id': 'benefits',
|
||||
'name': 'Convenios y Beneficios',
|
||||
'name_en': 'Benefits & Perks',
|
||||
'icon': 'bi-tag',
|
||||
'description': 'Gestión de convenios comerciales, descuentos y promociones para alumnos y docentes.'
|
||||
},
|
||||
{
|
||||
'id': 'reception',
|
||||
'name': 'Recepción y Control de Acceso QR',
|
||||
'name_en': 'Reception & QR Access',
|
||||
'icon': 'bi-qr-code-scan',
|
||||
'description': 'Escaneo y validación de credenciales QR de alumnos y docentes para control de ingreso a sedes.'
|
||||
}
|
||||
]
|
||||
|
||||
@@ -86,16 +104,20 @@ ACCESS_LEVELS = ['none', 'read', 'read_write']
|
||||
|
||||
class Role(db.Model):
|
||||
__tablename__ = 'roles'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(80), unique=True, nullable=False, index=True)
|
||||
description = db.Column(db.String(255))
|
||||
is_system = db.Column(db.Boolean, default=False, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
permissions = db.relationship('Permission', backref='role', lazy='joined', cascade='all, delete-orphan')
|
||||
users = db.relationship('User', backref='role_obj', lazy='select')
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_permission(self, module):
|
||||
"""Get access level string for a given module ('none', 'read', 'read_write')"""
|
||||
@@ -123,9 +145,9 @@ class Role(db.Model):
|
||||
if access_level not in ACCESS_LEVELS:
|
||||
access_level = 'none'
|
||||
|
||||
for p in self.permissions:
|
||||
if p.module == module:
|
||||
p.access_level = access_level
|
||||
for p in getattr(self, 'permissions', []):
|
||||
if getattr(p, 'module', None) == module:
|
||||
setattr(p, 'access_level', access_level)
|
||||
return p
|
||||
|
||||
new_perm = Permission(role=self, module=module, access_level=access_level)
|
||||
@@ -133,14 +155,16 @@ class Role(db.Model):
|
||||
return new_perm
|
||||
|
||||
def to_dict(self):
|
||||
perms = getattr(self, 'permissions', [])
|
||||
users_list = getattr(self, 'users', [])
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'description': self.description,
|
||||
'is_system': self.is_system,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'user_count': len(self.users) if self.users else 0,
|
||||
'permissions': {p.module: p.access_level for p in self.permissions}
|
||||
'user_count': len(list(users_list)) if users_list else 0,
|
||||
'permissions': {getattr(p, 'module', ''): getattr(p, 'access_level', '') for p in perms}
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
@@ -158,6 +182,10 @@ class Permission(db.Model):
|
||||
__table_args__ = (
|
||||
db.UniqueConstraint('role_id', 'module', name='uq_role_module'),
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for k, v in kwargs.items():
|
||||
setattr(self, k, v)
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Permission role={self.role_id} module={self.module} level={self.access_level}>'
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from app.services.crypto_service import CryptoService
|
||||
|
||||
class _hybrid_setting_method:
|
||||
"""Descriptor que resuelve si se invoca sobre la clase SystemSetting o sobre una instancia."""
|
||||
def __init__(self, inst_func, cls_func):
|
||||
self.inst_func = getattr(inst_func, '__func__', inst_func)
|
||||
self.cls_func = getattr(cls_func, '__func__', cls_func)
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
if instance is None:
|
||||
cls_target = self.cls_func
|
||||
return lambda *args, **kwargs: cls_target(owner, *args, **kwargs) if callable(cls_target) else None
|
||||
inst_target = self.inst_func
|
||||
return lambda *args, **kwargs: inst_target(instance, *args, **kwargs) if callable(inst_target) else None
|
||||
|
||||
|
||||
class SystemSetting(db.Model):
|
||||
"""
|
||||
Parámetros de configuración del sistema persistentes en base de datos.
|
||||
@@ -16,7 +30,10 @@ class SystemSetting(db.Model):
|
||||
description = db.Column(db.String(255), nullable=True)
|
||||
category = db.Column(db.String(50), default='system', nullable=True)
|
||||
is_encrypted = db.Column(db.Boolean, default=False, nullable=True)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def get_value(cls, key, default=None):
|
||||
@@ -29,53 +46,55 @@ class SystemSetting(db.Model):
|
||||
pass
|
||||
return default
|
||||
|
||||
def get_decrypted_value(self_or_cls, key_or_default=None, default=None):
|
||||
"""Retorna el valor desencriptado. Compatible como método de clase o de instancia."""
|
||||
if isinstance(self_or_cls, type):
|
||||
# Llamado como clase: SystemSetting.get_decrypted_value('key', default)
|
||||
key = key_or_default
|
||||
try:
|
||||
record = self_or_cls.query.filter_by(key=key).first()
|
||||
if record:
|
||||
return record.get_decrypted_value(default)
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
else:
|
||||
# Llamado como instancia: setting.get_decrypted_value(default)
|
||||
actual_default = key_or_default
|
||||
try:
|
||||
if self_or_cls.value is not None and self_or_cls.value.strip() != '':
|
||||
if self_or_cls.is_encrypted:
|
||||
return CryptoService.decrypt(self_or_cls.value)
|
||||
return self_or_cls.value
|
||||
except Exception:
|
||||
pass
|
||||
return actual_default
|
||||
def _inst_get_decrypted_value(self, default=None):
|
||||
try:
|
||||
if self.value is not None and self.value.strip() != '':
|
||||
if self.is_encrypted:
|
||||
return CryptoService.decrypt(self.value)
|
||||
return self.value
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
def get_masked_value(self_or_cls, key_or_default=None, default=''):
|
||||
"""Retorna una versión enmascarada si es un secreto o contraseña. Compatible como clase o instancia."""
|
||||
if isinstance(self_or_cls, type):
|
||||
# Llamado como clase: SystemSetting.get_masked_value('key', default)
|
||||
key = key_or_default
|
||||
try:
|
||||
record = self_or_cls.query.filter_by(key=key).first()
|
||||
if record:
|
||||
return record.get_masked_value(default)
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
else:
|
||||
# Llamado como instancia: setting.get_masked_value(default)
|
||||
actual_default = key_or_default or ''
|
||||
try:
|
||||
if self_or_cls.value and self_or_cls.value.strip() != '':
|
||||
if self_or_cls.is_encrypted or 'secret' in self_or_cls.key.lower() or 'password' in self_or_cls.key.lower() or 'token' in self_or_cls.key.lower():
|
||||
return '••••••••••••'
|
||||
return self_or_cls.value
|
||||
except Exception:
|
||||
pass
|
||||
return actual_default
|
||||
@classmethod
|
||||
def _cls_get_decrypted_value(cls, key, default=None):
|
||||
try:
|
||||
record = cls.query.filter_by(key=key).first()
|
||||
if record and record.value is not None and record.value.strip() != '':
|
||||
if record.is_encrypted:
|
||||
return CryptoService.decrypt(record.value)
|
||||
return record.value
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
get_decrypted_value = _hybrid_setting_method(_inst_get_decrypted_value, _cls_get_decrypted_value)
|
||||
|
||||
def _inst_get_masked_value(self, default=''):
|
||||
try:
|
||||
if self.value and self.value.strip() != '':
|
||||
k_lower = (self.key or '').lower()
|
||||
if self.is_encrypted or any(x in k_lower for x in ('secret', 'password', 'token', 'key')):
|
||||
return '••••••••••••'
|
||||
return self.value
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def _cls_get_masked_value(cls, key, default=''):
|
||||
try:
|
||||
record = cls.query.filter_by(key=key).first()
|
||||
if record and record.value and record.value.strip() != '':
|
||||
k_lower = record.key.lower()
|
||||
if record.is_encrypted or any(x in k_lower for x in ('secret', 'password', 'token', 'key')):
|
||||
return '••••••••••••'
|
||||
return record.value
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
get_masked_value = _hybrid_setting_method(_inst_get_masked_value, _cls_get_masked_value)
|
||||
|
||||
@classmethod
|
||||
def set_value(cls, key, value, description=None, category='system', is_encrypted=False):
|
||||
@@ -105,7 +124,7 @@ class SystemSetting(db.Model):
|
||||
if category:
|
||||
record.category = category
|
||||
record.is_encrypted = is_encrypted
|
||||
record.updated_at = datetime.utcnow()
|
||||
record.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
db.session.commit()
|
||||
return record
|
||||
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Optional, List, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.career import Career
|
||||
|
||||
# Tabla asociativa Many-to-Many para materias compartidas entre carreras
|
||||
subject_careers = db.Table(
|
||||
'subject_careers',
|
||||
db.Column('subject_id', db.Integer, db.ForeignKey('subjects.id', ondelete='CASCADE'), primary_key=True),
|
||||
db.Column('career_id', db.Integer, db.ForeignKey('careers.id', ondelete='CASCADE'), primary_key=True)
|
||||
)
|
||||
|
||||
class Subject(db.Model):
|
||||
__tablename__ = 'subjects'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
if TYPE_CHECKING:
|
||||
career_obj: Any
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
code = db.Column(db.String(50), unique=True, nullable=False, index=True)
|
||||
@@ -13,14 +28,24 @@ class Subject(db.Model):
|
||||
career_id = db.Column(db.Integer, db.ForeignKey('careers.id', ondelete='SET NULL'), nullable=True)
|
||||
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
||||
is_short_course = db.Column(db.Boolean, default=False, nullable=True) # True para talleres/cursos cortos
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
commissions = db.relationship('Commission', backref='subject', lazy=True, cascade='all, delete-orphan')
|
||||
careers = db.relationship('Career', secondary=subject_careers, lazy='subquery', backref=db.backref('shared_subjects', lazy=True))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert subject to dictionary"""
|
||||
all_careers = []
|
||||
if self.careers:
|
||||
all_careers = [{'id': c.id, 'name': c.name, 'code': c.code} for c in self.careers]
|
||||
elif self.career_obj:
|
||||
all_careers = [{'id': self.career_obj.id, 'name': self.career_obj.name, 'code': self.career_obj.code}]
|
||||
|
||||
return {
|
||||
'id': self.id,
|
||||
'code': self.code,
|
||||
@@ -30,17 +55,27 @@ class Subject(db.Model):
|
||||
'credits': self.credits,
|
||||
'career_id': self.career_id,
|
||||
'career_name': self.career_obj.name if self.career_obj else None,
|
||||
'careers': all_careers,
|
||||
'is_active': self.is_active,
|
||||
'is_short_course': bool(self.is_short_course),
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None
|
||||
}
|
||||
|
||||
@property
|
||||
def career(self):
|
||||
"""Helper to access career_obj directly"""
|
||||
return self.career_obj
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Subject {self.code}>'
|
||||
|
||||
class Commission(db.Model):
|
||||
__tablename__ = 'commissions'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
if TYPE_CHECKING:
|
||||
subject: Any
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
subject_id = db.Column(db.Integer, db.ForeignKey('subjects.id'), nullable=False)
|
||||
@@ -65,8 +100,11 @@ class Commission(db.Model):
|
||||
academic_term_id = db.Column(db.Integer, db.ForeignKey('academic_terms.id', ondelete='SET NULL'), nullable=True)
|
||||
academic_term = db.relationship('AcademicTerm', foreign_keys=[academic_term_id])
|
||||
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Virtual property for compatibility
|
||||
@property
|
||||
@@ -85,7 +123,13 @@ class Commission(db.Model):
|
||||
# Virtual field for teacher_name
|
||||
@property
|
||||
def teacher_name(self):
|
||||
return f"{self.teacher.first_name} {self.teacher.last_name}" if self.teacher else "TBD"
|
||||
if not self.teacher:
|
||||
return "TBD"
|
||||
fn = getattr(self.teacher, 'first_name', None)
|
||||
ln = getattr(self.teacher, 'last_name', None)
|
||||
if fn or ln:
|
||||
return f"{fn or ''} {ln or ''}".strip()
|
||||
return getattr(self.teacher, 'name', 'TBD') or 'TBD'
|
||||
|
||||
@property
|
||||
def teachers(self):
|
||||
@@ -116,6 +160,33 @@ class Commission(db.Model):
|
||||
return "Sin asignar"
|
||||
return ", ".join([f"{t['name']} ({t['role']})" for t in t_list])
|
||||
|
||||
@property
|
||||
def career(self):
|
||||
return self.subject.career_obj if self.subject else None
|
||||
|
||||
@property
|
||||
def careers(self):
|
||||
if self.subject and self.subject.careers:
|
||||
return [{'id': c.id, 'name': c.name, 'code': c.code} for c in self.subject.careers]
|
||||
elif self.subject and self.subject.career_obj:
|
||||
return [{'id': self.subject.career_obj.id, 'name': self.subject.career_obj.name, 'code': self.subject.career_obj.code}]
|
||||
return []
|
||||
|
||||
@property
|
||||
def career_name(self):
|
||||
return self.subject.career_obj.name if (self.subject and self.subject.career_obj) else 'Carrera General'
|
||||
|
||||
@property
|
||||
def career_names(self):
|
||||
c_list = self.careers
|
||||
if c_list:
|
||||
return ", ".join([c['name'] for c in c_list])
|
||||
return self.career_name
|
||||
|
||||
@property
|
||||
def career_id(self):
|
||||
return self.subject.career_id if self.subject else None
|
||||
|
||||
# Unique constraint
|
||||
__table_args__ = (db.UniqueConstraint('subject_id', 'code', 'semester', 'year'),)
|
||||
|
||||
@@ -124,6 +195,12 @@ 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,
|
||||
'careers': self.careers,
|
||||
'code': self.code,
|
||||
'semester': self.semester,
|
||||
'year': self.year,
|
||||
@@ -179,7 +256,7 @@ class CommissionTeacher(db.Model):
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
role = db.Column(db.String(50), default='Titular', nullable=False) # Titular, Adjunto, JTP, Ayudante
|
||||
is_primary = db.Column(db.Boolean, default=False, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
commission = db.relationship('Commission', backref=db.backref('teachers_association', cascade='all, delete-orphan', lazy='joined'))
|
||||
@@ -187,6 +264,10 @@ class CommissionTeacher(db.Model):
|
||||
|
||||
__table_args__ = (db.UniqueConstraint('commission_id', 'user_id'),)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for k, v in kwargs.items():
|
||||
setattr(self, k, v)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from app import db
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
|
||||
class MoodleSyncTask(db.Model):
|
||||
@@ -19,9 +19,9 @@ class MoodleSyncTask(db.Model):
|
||||
attempts = db.Column(db.Integer, default=0)
|
||||
max_attempts = db.Column(db.Integer, default=5)
|
||||
error_message = db.Column(db.Text, nullable=True)
|
||||
next_retry_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
next_retry_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), index=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
if 'payload' in kwargs:
|
||||
@@ -35,16 +35,16 @@ class MoodleSyncTask(db.Model):
|
||||
@property
|
||||
def payload(self):
|
||||
try:
|
||||
return json.loads(self._payload) if self._payload else {}
|
||||
return json.loads(str(self._payload)) if self._payload else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@payload.setter
|
||||
def payload(self, val):
|
||||
if isinstance(val, (dict, list)):
|
||||
self._payload = json.dumps(val)
|
||||
setattr(self, '_payload', json.dumps(val))
|
||||
else:
|
||||
self._payload = str(val or '{}')
|
||||
setattr(self, '_payload', str(val or '{}'))
|
||||
|
||||
def get_payload_dict(self):
|
||||
return self.payload
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
from typing import Any, TYPE_CHECKING
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class User(db.Model):
|
||||
__tablename__ = 'users'
|
||||
__allow_unmapped__ = True
|
||||
if TYPE_CHECKING:
|
||||
role_obj: Any
|
||||
reservations: Any
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
email = db.Column(db.String(255), unique=True, nullable=False, index=True)
|
||||
password_hash = db.Column(db.String(255), nullable=False)
|
||||
name = db.Column(db.String(100), nullable=False)
|
||||
role = db.Column(db.String(50), nullable=False)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False, index=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
last_login = db.Column(db.DateTime)
|
||||
preferred_language = db.Column(db.String(10), default=None, nullable=True)
|
||||
theme_preference = db.Column(db.String(10), default='auto', nullable=False)
|
||||
role_id = db.Column(db.Integer, db.ForeignKey('roles.id', ondelete='SET NULL'), nullable=True)
|
||||
role_id = db.Column(db.Integer, db.ForeignKey('roles.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
# Extended personal, contact and identity document fields
|
||||
first_name = db.Column(db.String(100), nullable=True)
|
||||
@@ -25,6 +30,9 @@ class User(db.Model):
|
||||
address = db.Column(db.String(255), nullable=True)
|
||||
document_type = db.Column(db.String(20), default='DNI', nullable=True)
|
||||
document_number = db.Column(db.String(30), nullable=True, index=True)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_first_name(self):
|
||||
if self.first_name:
|
||||
@@ -41,16 +49,37 @@ class User(db.Model):
|
||||
from app.constants.document_types import format_document
|
||||
return format_document(self.document_type, self.document_number)
|
||||
|
||||
@property
|
||||
def username(self) -> str:
|
||||
"""Alias o identificador de acceso: DNI o prefijo de email institucional."""
|
||||
if self.document_number:
|
||||
return self.document_number
|
||||
if self.email and '@' in self.email:
|
||||
return self.email.split('@')[0]
|
||||
return self.email or f"user_{self.id}"
|
||||
|
||||
@property
|
||||
def auth_provider_label(self) -> str:
|
||||
"""Determina la procedencia y mecanismo de autenticación del usuario."""
|
||||
ph = str(self.password_hash or '')
|
||||
if ph.startswith('GoogleSSO_'):
|
||||
return 'Google Workspace (@unicaba.edu.ar)'
|
||||
if ph.startswith('MoodleLinked_'):
|
||||
return 'Moodle Campus Virtual'
|
||||
if self.email and self.email.endswith('@unicaba.edu.ar'):
|
||||
return 'Institucional UniCABA'
|
||||
return 'Cuenta Local'
|
||||
|
||||
# Relationships
|
||||
reservations = db.relationship('Reservation', backref='user', lazy=True, cascade='all, delete-orphan')
|
||||
|
||||
def set_password(self, password):
|
||||
"""Set password hash"""
|
||||
self.password_hash = generate_password_hash(password, method='pbkdf2:sha256')
|
||||
setattr(self, 'password_hash', generate_password_hash(password, method='pbkdf2:sha256'))
|
||||
|
||||
def check_password(self, password):
|
||||
"""Check password"""
|
||||
return check_password_hash(self.password_hash, password)
|
||||
return check_password_hash(str(self.password_hash or ''), password)
|
||||
|
||||
def is_admin(self):
|
||||
"""Check if user is admin"""
|
||||
@@ -138,7 +167,7 @@ class User(db.Model):
|
||||
|
||||
def update_last_login(self):
|
||||
"""Update last login timestamp"""
|
||||
self.last_login = datetime.utcnow()
|
||||
setattr(self, 'last_login', datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
db.session.commit()
|
||||
|
||||
def to_dict(self):
|
||||
@@ -156,6 +185,8 @@ class User(db.Model):
|
||||
'document_type': self.document_type or 'DNI',
|
||||
'document_number': self.document_number or '',
|
||||
'document_formatted': self.get_formatted_document(),
|
||||
'username': self.username,
|
||||
'auth_provider_label': self.auth_provider_label,
|
||||
'role': self.role,
|
||||
'role_id': self.role_id,
|
||||
'is_active': self.is_active,
|
||||
|
||||
@@ -17,7 +17,7 @@ class BaseRepository(Generic[T]):
|
||||
|
||||
def get_all(self, order_by=None) -> List[T]:
|
||||
"""Obtiene todas las entidades opcionalmente ordenadas."""
|
||||
query = self.model_class.query
|
||||
query = db.session.query(self.model_class)
|
||||
if order_by is not None:
|
||||
query = query.order_by(order_by)
|
||||
return query.all()
|
||||
|
||||
@@ -15,7 +15,7 @@ class ClassroomRepository(BaseRepository[Classroom]):
|
||||
return Classroom.query.filter_by(
|
||||
building_id=building_id,
|
||||
code=code.strip(),
|
||||
floor=str(floor).strip()
|
||||
floor=floor.strip()
|
||||
).first()
|
||||
|
||||
def get_active_classrooms(self, building_id: Optional[int] = None, floor: Optional[str] = None,
|
||||
@@ -27,7 +27,7 @@ class ClassroomRepository(BaseRepository[Classroom]):
|
||||
query = query.filter_by(building_id=building_id)
|
||||
|
||||
if floor:
|
||||
query = query.filter_by(floor=str(floor).strip())
|
||||
query = query.filter_by(floor=floor.strip())
|
||||
|
||||
classrooms = query.order_by(Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from typing import Optional, List
|
||||
from datetime import datetime, date, time
|
||||
from sqlalchemy.orm import joinedload
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy import and_, or_, func, not_
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.user import User
|
||||
from app.repositories.base_repository import BaseRepository
|
||||
from app import db
|
||||
|
||||
@@ -31,22 +33,98 @@ class ReservationRepository(BaseRepository[Reservation]):
|
||||
return query.all()
|
||||
|
||||
def get_by_date_range(self, start_dt: datetime, end_dt: datetime,
|
||||
classroom_id: Optional[int] = None) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de una ventana temporal con carga ansiosa de relaciones."""
|
||||
classroom_id: Optional[int] = None,
|
||||
is_hide_virtual: bool = False,
|
||||
only_virtual: bool = False,
|
||||
status: Optional[str] = None,
|
||||
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(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission),
|
||||
joinedload(Reservation.user)
|
||||
).filter(
|
||||
Reservation.start_time >= start_dt,
|
||||
Reservation.start_time <= end_dt,
|
||||
Reservation.status != ReservationStatus.CANCELLED.value
|
||||
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)
|
||||
else:
|
||||
query = query.filter(Reservation.status != ReservationStatus.CANCELLED.value)
|
||||
|
||||
if classroom_id:
|
||||
query = query.filter(Reservation.classroom_id == classroom_id)
|
||||
|
||||
return query.order_by(Reservation.start_time.asc()).all()
|
||||
if only_virtual:
|
||||
query = query.outerjoin(Classroom, Reservation.classroom_id == Classroom.id).filter(
|
||||
or_(
|
||||
and_(Reservation.virtual_link.is_not(None), Reservation.virtual_link != ''),
|
||||
Classroom.code.ilike('%VIRTUAL%'),
|
||||
Classroom.building.ilike('%VIRTUAL%')
|
||||
)
|
||||
)
|
||||
elif is_hide_virtual:
|
||||
query = query.outerjoin(Classroom, Reservation.classroom_id == Classroom.id).filter(
|
||||
or_(
|
||||
Classroom.id.is_(None),
|
||||
and_(
|
||||
not_(Classroom.code.ilike('%VIRTUAL%')),
|
||||
not_(Classroom.building.ilike('%VIRTUAL%'))
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if floor:
|
||||
query = query.join(Classroom, Reservation.classroom_id == Classroom.id).filter(
|
||||
func.lower(Classroom.floor) == floor.strip().lower()
|
||||
)
|
||||
|
||||
if shift:
|
||||
query = query.filter(Reservation.shift.ilike(f'%{shift.strip()}%'))
|
||||
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
query = query.outerjoin(Classroom, Reservation.classroom_id == Classroom.id)\
|
||||
.outerjoin(User, Reservation.user_id == User.id)\
|
||||
.filter(
|
||||
or_(
|
||||
Reservation.purpose.ilike(f'%{s_clean}%'),
|
||||
Classroom.code.ilike(f'%{s_clean}%'),
|
||||
User.name.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
|
||||
return query.order_by(Reservation.start_time.asc()).limit(limit).all()
|
||||
|
||||
def get_by_teacher(self, teacher_id: int) -> List[Reservation]:
|
||||
"""Obtiene reservas asignadas a un docente."""
|
||||
|
||||
@@ -17,11 +17,16 @@ class UserRepository(BaseRepository[User]):
|
||||
user = User.query.filter(func.lower(User.email) == clean).first()
|
||||
if user:
|
||||
return user
|
||||
# Si el usuario ingresó solo el nombre de cuenta (ej. 'admin' o 'bedelia')
|
||||
# Si el usuario ingresó solo el nombre de cuenta o su DNI (ej. 'admin', 'bedelia' o '34247025')
|
||||
if '@' not in clean:
|
||||
clean_digits = clean.replace('.', '').replace(',', '').replace(' ', '')
|
||||
user = User.query.filter(
|
||||
or_(
|
||||
func.lower(User.email) == f"{clean}@edu-space.com",
|
||||
func.lower(User.email).like(f"{clean}@%"),
|
||||
User.document_number == clean,
|
||||
User.document_number == clean_digits,
|
||||
func.replace(User.document_number, '.', '') == clean_digits,
|
||||
func.lower(User.name) == clean,
|
||||
func.lower(User.role) == clean.upper()
|
||||
)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 156 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
@@ -1,10 +0,0 @@
|
||||
from .main import main_bp
|
||||
from .auth import auth_bp
|
||||
from .classrooms import classrooms_bp
|
||||
from .buildings import buildings_bp
|
||||
from .schedule import schedule_bp
|
||||
from .genetic_algorithm import genetic_bp, genetic_web_bp
|
||||
from .admin import admin_bp
|
||||
from .my_subjects import my_subjects_bp
|
||||
|
||||
__all__ = ['main_bp', 'auth_bp', 'classrooms_bp', 'buildings_bp', 'schedule_bp', 'genetic_bp', 'genetic_web_bp', 'admin_bp', 'my_subjects_bp']
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +0,0 @@
|
||||
"""Paquete de rutas API RESTful (v1) con soporte Stateless JWT."""
|
||||
from app.routes.api.auth import api_auth_bp
|
||||
from app.routes.api.classrooms import api_classrooms_bp
|
||||
from app.routes.api.reservations import api_reservations_bp
|
||||
from app.routes.api.optimizer import api_optimizer_bp
|
||||
|
||||
__all__ = [
|
||||
'api_auth_bp',
|
||||
'api_classrooms_bp',
|
||||
'api_reservations_bp',
|
||||
'api_optimizer_bp'
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,401 +0,0 @@
|
||||
"""
|
||||
Authentication Routes (admin-edu-space)
|
||||
Implements Hybrid Authentication:
|
||||
- Local Login with admin fallback
|
||||
- Google OAuth 2.0 (inspired by AlumnosLS domain & email validation)
|
||||
- Moodle Delegated Authentication with dynamic role mapping
|
||||
- Token Refresh & Session Management (Redis / JWT)
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, g, make_response
|
||||
from pydantic import ValidationError
|
||||
import jwt
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.user_service import UserService
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.services.cache_service import cache_service
|
||||
from app.services.moodle_client import moodle_client
|
||||
from app.schemas.auth_dto import LoginDTO, RefreshTokenDTO
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
api_auth_bp = Blueprint('api_auth', __name__, url_prefix='/api/v1/auth')
|
||||
user_service = UserService()
|
||||
|
||||
|
||||
@api_auth_bp.route('/providers', methods=['GET'])
|
||||
def get_auth_providers():
|
||||
"""
|
||||
Public endpoint returning active authentication methods and Google client ID for the UI.
|
||||
"""
|
||||
local_val = SystemSetting.get_value('auth_local_enabled', 'true').lower() in ('true', '1')
|
||||
google_val = SystemSetting.get_value('auth_google_enabled', 'false').lower() in ('true', '1')
|
||||
moodle_val = SystemSetting.get_value('auth_moodle_enabled', 'false').lower() in ('true', '1')
|
||||
google_client_id = SystemSetting.get_value('google_client_id', '')
|
||||
demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true').lower() in ('true', '1')
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'providers': {
|
||||
'local': local_val,
|
||||
'google': google_val,
|
||||
'moodle': moodle_val
|
||||
},
|
||||
'google_client_id': google_client_id,
|
||||
'demo_access_enabled': demo_access_enabled
|
||||
}), 200
|
||||
|
||||
|
||||
@api_auth_bp.route('/login', methods=['POST'])
|
||||
def login():
|
||||
"""
|
||||
Native local authentication endpoint (Access + Refresh tokens).
|
||||
Respects global auth_local_enabled setting, allowing emergency ADMIN access if disabled.
|
||||
"""
|
||||
data = request.get_json(silent=True)
|
||||
if not isinstance(data, dict):
|
||||
return jsonify({'error': 'BadRequest', 'message': 'El cuerpo de la solicitud debe ser un objeto JSON.'}), 400
|
||||
try:
|
||||
dto = LoginDTO(**data)
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
local_enabled = SystemSetting.get_value('auth_local_enabled', 'true').lower() in ('true', '1')
|
||||
|
||||
user = user_service.authenticate(dto.email, dto.password)
|
||||
if not user:
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': 'Credenciales de acceso incorrectas o cuenta inactiva.'
|
||||
}), 401
|
||||
|
||||
is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN'
|
||||
if not local_enabled and not is_admin:
|
||||
return jsonify({
|
||||
'error': 'Forbidden',
|
||||
'message': 'El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle.'
|
||||
}), 403
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response_data = {
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
resp = make_response(jsonify(response_data), 200)
|
||||
resp.set_cookie(
|
||||
'refresh_token',
|
||||
tokens['refresh_token'],
|
||||
httponly=True,
|
||||
samesite='Lax',
|
||||
max_age=7 * 24 * 3600,
|
||||
path='/api/v1/auth/refresh'
|
||||
)
|
||||
return resp
|
||||
|
||||
|
||||
@api_auth_bp.route('/google', methods=['POST'])
|
||||
def google_auth():
|
||||
"""
|
||||
Google OAuth 2.0 authentication endpoint.
|
||||
Receives Google profile / token data, verifies domain whitelist (AlumnosLS architecture),
|
||||
creates/updates local user and issues JWT.
|
||||
"""
|
||||
google_enabled = SystemSetting.get_value('auth_google_enabled', 'false').lower() in ('true', '1')
|
||||
if not google_enabled:
|
||||
return jsonify({'error': 'Forbidden', 'message': 'El inicio de sesión con Google no está habilitado.'}), 403
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
email = data.get('email', '').strip().lower()
|
||||
name = data.get('name', '').strip()
|
||||
domain = data.get('domain') or (email.split('@')[1] if '@' in email else '')
|
||||
photo = data.get('photo', '')
|
||||
|
||||
if not email:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'El email de Google es obligatorio.'}), 400
|
||||
|
||||
# Domain restriction check
|
||||
allowed_domains_str = SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar')
|
||||
allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()]
|
||||
|
||||
if allowed_domains and domain.lower() not in allowed_domains:
|
||||
logger.warning(f"[GoogleAuth] Access denied for {email}: domain {domain} not in {allowed_domains}")
|
||||
return jsonify({
|
||||
'error': 'Forbidden',
|
||||
'message': f'Acceso denegado. El dominio @{domain} no está autorizado en esta institución.'
|
||||
}), 403
|
||||
|
||||
user = User.query.filter(User.email.ilike(email)).first()
|
||||
if not user:
|
||||
# Create local user on first Google login
|
||||
parts = name.split()
|
||||
first_name = parts[0] if parts else 'Usuario'
|
||||
last_name = ' '.join(parts[1:]) if len(parts) > 1 else 'Google'
|
||||
|
||||
# Default role: Docente
|
||||
docente_role = Role.query.filter(Role.name.ilike('Docente')).first()
|
||||
user = User(
|
||||
email=email,
|
||||
name=name or f"{first_name} {last_name}",
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
role='Docente' if not docente_role else docente_role.name,
|
||||
role_id=docente_role.id if docente_role else None,
|
||||
is_active=True
|
||||
)
|
||||
user.set_password(f"GoogleSSO_{email}")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
logger.info(f"[GoogleAuth] Created new local user for {email} with role Docente.")
|
||||
|
||||
if not user.is_active:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta se encuentra inactiva. Contacte a Bedelía.'}), 401
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response_data = {
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
resp = make_response(jsonify(response_data), 200)
|
||||
resp.set_cookie(
|
||||
'refresh_token',
|
||||
tokens['refresh_token'],
|
||||
httponly=True,
|
||||
samesite='Lax',
|
||||
max_age=7 * 24 * 3600,
|
||||
path='/api/v1/auth/refresh'
|
||||
)
|
||||
return resp
|
||||
|
||||
|
||||
@api_auth_bp.route('/moodle', methods=['POST'])
|
||||
def moodle_auth():
|
||||
"""
|
||||
Moodle Delegated Authentication endpoint.
|
||||
Validates user credentials against Moodle server (/login/token.php),
|
||||
fetches Moodle profile, implements initial role mapping (if new user),
|
||||
and caches profile in Redis.
|
||||
"""
|
||||
moodle_enabled = SystemSetting.get_value('auth_moodle_enabled', 'false').lower() in ('true', '1')
|
||||
if not moodle_enabled:
|
||||
return jsonify({'error': 'Forbidden', 'message': 'El inicio de sesión con Moodle no está habilitado.'}), 403
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
username = data.get('username', '').strip()
|
||||
password = data.get('password', '').strip()
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'Usuario y contraseña de Moodle son obligatorios.'}), 400
|
||||
|
||||
server_url = SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle').rstrip('/')
|
||||
|
||||
# Authenticate against Moodle login/token.php
|
||||
token_url = f"{server_url}/login/token.php"
|
||||
try:
|
||||
resp = requests.post(token_url, data={
|
||||
'username': username,
|
||||
'password': password,
|
||||
'service': 'moodle_mobile_app'
|
||||
}, timeout=10)
|
||||
res_data = resp.json()
|
||||
except Exception as e:
|
||||
logger.error(f"[MoodleAuth] Connection error to Moodle server: {e}")
|
||||
return jsonify({'error': 'ServiceUnavailable', 'message': 'No se pudo conectar con el servidor de Moodle. Intente más tarde.'}), 503
|
||||
|
||||
if 'error' in res_data or 'token' not in res_data:
|
||||
err_msg = res_data.get('error', 'Credenciales inválidas en Moodle.')
|
||||
return jsonify({'error': 'Unauthorized', 'message': f'Moodle: {err_msg}'}), 401
|
||||
|
||||
moodle_user_token = res_data['token']
|
||||
|
||||
# Retrieve Moodle user profile via Web Services
|
||||
moodle_profile = None
|
||||
cache_key = f"moodle_user:{username.lower()}"
|
||||
cached = cache_service.get(cache_key)
|
||||
if cached:
|
||||
moodle_profile = cached
|
||||
else:
|
||||
try:
|
||||
m_users = moodle_client.get_users([{'key': 'username', 'value': username.lower()}])
|
||||
if m_users and isinstance(m_users, list) and len(m_users) > 0:
|
||||
moodle_profile = m_users[0]
|
||||
cache_service.set(cache_key, moodle_profile, ttl_seconds=3600)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MoodleAuth] Could not fetch extended Moodle profile: {e}")
|
||||
|
||||
email = moodle_profile.get('email') if moodle_profile else f"{username}@unicaba.edu.ar"
|
||||
firstname = moodle_profile.get('firstname', username) if moodle_profile else username
|
||||
lastname = moodle_profile.get('lastname', 'Moodle') if moodle_profile else 'Moodle'
|
||||
|
||||
# Local user lookup or creation
|
||||
user = User.query.filter((User.email.ilike(email)) | (User.email.ilike(f"{username}@%"))).first()
|
||||
if not user:
|
||||
# Determine initial role: if username is admin or has manager role -> ADMIN, else Docente
|
||||
role_name = 'ADMIN' if username.lower() in ('admin', 'manager') else 'Docente'
|
||||
role_obj = Role.query.filter(Role.name.ilike(role_name)).first()
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
name=f"{firstname} {lastname}".strip(),
|
||||
first_name=firstname,
|
||||
last_name=lastname,
|
||||
role=role_obj.name if role_obj else role_name,
|
||||
role_id=role_obj.id if role_obj else None,
|
||||
is_active=True
|
||||
)
|
||||
user.set_password(f"MoodleLinked_{username}")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleAuth] Created new local user for Moodle username '{username}' with role '{role_name}'.")
|
||||
|
||||
if not user.is_active:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta en Edu-Space está desactivada.'}), 401
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response_data = {
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
resp = make_response(jsonify(response_data), 200)
|
||||
resp.set_cookie(
|
||||
'refresh_token',
|
||||
tokens['refresh_token'],
|
||||
httponly=True,
|
||||
samesite='Lax',
|
||||
max_age=7 * 24 * 3600,
|
||||
path='/api/v1/auth/refresh'
|
||||
)
|
||||
return resp
|
||||
|
||||
|
||||
@api_auth_bp.route('/refresh', methods=['POST'])
|
||||
def refresh():
|
||||
"""
|
||||
Silent Access Token renewal using Refresh Token.
|
||||
"""
|
||||
data = request.get_json(silent=True)
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
refresh_token = data.get('refresh_token') or request.cookies.get('refresh_token')
|
||||
|
||||
if not refresh_token:
|
||||
return jsonify({
|
||||
'error': 'BadRequest',
|
||||
'message': 'Refresh token no suministrado en el cuerpo ni en cookies.'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
payload = JWTService.decode_token(refresh_token, expected_type='refresh')
|
||||
user_id = int(payload.get('sub'))
|
||||
user = user_service.get_by_id(user_id)
|
||||
|
||||
if not user or not user.is_active:
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': 'Usuario no encontrado o inactivo.'
|
||||
}), 401
|
||||
|
||||
new_access_token = JWTService.create_access_token(user)
|
||||
return jsonify({
|
||||
'access_token': new_access_token,
|
||||
'token_type': 'Bearer',
|
||||
'expires_in': int(JWTService.ACCESS_TOKEN_EXPIRES.total_seconds())
|
||||
}), 200
|
||||
|
||||
except jwt.ExpiredSignatureError:
|
||||
return jsonify({'error': 'TokenExpired', 'message': 'El refresh token ha expirado. Reingrese credenciales.'}), 401
|
||||
except jwt.InvalidTokenError as e:
|
||||
return jsonify({'error': 'InvalidToken', 'message': str(e)}), 401
|
||||
|
||||
|
||||
@api_auth_bp.route('/logout', methods=['POST'])
|
||||
@jwt_required
|
||||
def logout():
|
||||
"""
|
||||
Session logout: revokes active access token and clears cookies.
|
||||
"""
|
||||
JWTService.revoke_token(g.jwt_token)
|
||||
resp = make_response(jsonify({'message': 'Sesión finalizada y token revocado exitosamente.'}), 200)
|
||||
resp.delete_cookie('refresh_token', path='/api/v1/auth/refresh')
|
||||
return resp
|
||||
|
||||
|
||||
@api_auth_bp.route('/change_password', methods=['POST'])
|
||||
@api_auth_bp.route('/change-password', methods=['POST'])
|
||||
@jwt_required
|
||||
def change_password():
|
||||
"""
|
||||
Permite al usuario autenticado cambiar su propia contraseña institucional.
|
||||
Valida la contraseña actual y la confirmación de la nueva clave.
|
||||
"""
|
||||
data = request.get_json(silent=True) or request.form.to_dict() or {}
|
||||
current_password = data.get('current_password', '').strip()
|
||||
new_password = data.get('new_password', '').strip()
|
||||
confirm_password = data.get('confirm_password', '').strip()
|
||||
|
||||
if not current_password or not new_password:
|
||||
return jsonify({
|
||||
'error': 'BadRequest',
|
||||
'message': 'Debe ingresar la contraseña actual y la nueva contraseña.'
|
||||
}), 400
|
||||
|
||||
if new_password != confirm_password:
|
||||
return jsonify({
|
||||
'error': 'BadRequest',
|
||||
'message': 'La nueva contraseña y su confirmación no coinciden.'
|
||||
}), 400
|
||||
|
||||
if len(new_password) < 6:
|
||||
return jsonify({
|
||||
'error': 'BadRequest',
|
||||
'message': 'La nueva contraseña debe tener al menos 6 caracteres.'
|
||||
}), 400
|
||||
|
||||
user = g.jwt_user
|
||||
if not user.check_password(current_password):
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': 'La contraseña actual ingresada es incorrecta.'
|
||||
}), 401
|
||||
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
|
||||
logger.info(f"[Auth] Password successfully updated for user {user.email}")
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'message': 'Contraseña actualizada correctamente.'
|
||||
}), 200
|
||||
|
||||
|
||||
@api_auth_bp.route('/me', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_current_user():
|
||||
"""
|
||||
Returns current authenticated profile and permissions.
|
||||
"""
|
||||
profile = user_service.get_profile_data(g.jwt_user)
|
||||
return jsonify(profile), 200
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
from app.services.classroom_service import ClassroomService
|
||||
from app.schemas.classroom_dto import ClassroomCreateDTO, ClassroomUpdateDTO, ClassroomResponseDTO
|
||||
from app.utils.jwt_decorators import jwt_required, jwt_role_required
|
||||
|
||||
api_classrooms_bp = Blueprint('api_classrooms', __name__, url_prefix='/api/v1/classrooms')
|
||||
classroom_service = ClassroomService()
|
||||
|
||||
@api_classrooms_bp.route('', methods=['GET'])
|
||||
@jwt_required
|
||||
def list_classrooms():
|
||||
"""Lista aulas con filtros opcionales (building_id, floor, mode)."""
|
||||
building_id = request.args.get('building_id', type=int)
|
||||
floor = request.args.get('floor')
|
||||
mode = request.args.get('mode', '').lower()
|
||||
|
||||
only_virtual = mode == 'virtual'
|
||||
only_physical = mode == 'physical'
|
||||
|
||||
classrooms = classroom_service.list_classrooms(
|
||||
building_id=building_id,
|
||||
floor=floor,
|
||||
only_virtual=only_virtual,
|
||||
only_physical=only_physical
|
||||
)
|
||||
|
||||
result = []
|
||||
for c in classrooms:
|
||||
result.append({
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building_name,
|
||||
'building_id': c.building_id,
|
||||
'floor': c.floor,
|
||||
'floor_display': c.floor_display,
|
||||
'capacity': c.capacity,
|
||||
'is_virtual': c.is_virtual,
|
||||
'location_display': c.location_display,
|
||||
'description': c.description,
|
||||
'is_active': c.is_active
|
||||
})
|
||||
|
||||
return jsonify({'total': len(result), 'classrooms': result}), 200
|
||||
|
||||
@api_classrooms_bp.route('/<int:classroom_id>', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_classroom(classroom_id: int):
|
||||
"""Obtiene el detalle de un aula por ID."""
|
||||
c = classroom_service.get_classroom(classroom_id)
|
||||
if not c:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Aula {classroom_id} no encontrada.'}), 404
|
||||
|
||||
return jsonify({
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building_name,
|
||||
'building_id': c.building_id,
|
||||
'floor': c.floor,
|
||||
'floor_display': c.floor_display,
|
||||
'capacity': c.capacity,
|
||||
'is_virtual': c.is_virtual,
|
||||
'location_display': c.location_display,
|
||||
'description': c.description,
|
||||
'is_active': c.is_active
|
||||
}), 200
|
||||
|
||||
@api_classrooms_bp.route('', methods=['POST'])
|
||||
@jwt_role_required('ADMIN', 'ADMINISTRADOR', 'BEDELIA')
|
||||
def create_classroom():
|
||||
"""Crea una nueva aula validando el contrato con ClassroomCreateDTO."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
dto = ClassroomCreateDTO(**data)
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
try:
|
||||
classroom = classroom_service.create_classroom(dto)
|
||||
return jsonify({
|
||||
'message': 'Aula creada exitosamente.',
|
||||
'id': classroom.id,
|
||||
'code': classroom.code,
|
||||
'location_display': classroom.location_display
|
||||
}), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 400
|
||||
|
||||
@api_classrooms_bp.route('/<int:classroom_id>', methods=['PUT'])
|
||||
@jwt_role_required('ADMIN', 'ADMINISTRADOR', 'BEDELIA')
|
||||
def update_classroom(classroom_id: int):
|
||||
"""Actualiza los datos de un aula."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
dto = ClassroomUpdateDTO(**data)
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
try:
|
||||
classroom = classroom_service.update_classroom(classroom_id, dto)
|
||||
return jsonify({
|
||||
'message': 'Aula actualizada exitosamente.',
|
||||
'id': classroom.id,
|
||||
'code': classroom.code,
|
||||
'capacity': classroom.capacity
|
||||
}), 200
|
||||
except ValueError as e:
|
||||
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 400
|
||||
|
||||
@api_classrooms_bp.route('/<int:classroom_id>', methods=['DELETE'])
|
||||
@jwt_role_required('ADMIN', 'ADMINISTRADOR')
|
||||
def delete_classroom(classroom_id: int):
|
||||
"""Elimina o desactiva un aula."""
|
||||
deleted = classroom_service.delete_classroom(classroom_id)
|
||||
if not deleted:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Aula {classroom_id} no encontrada.'}), 404
|
||||
|
||||
return jsonify({'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'}), 200
|
||||
|
||||
@api_classrooms_bp.route('/<int:classroom_id>/toggle', methods=['POST'])
|
||||
@jwt_role_required('ADMIN', 'ADMINISTRADOR', 'BEDELIA')
|
||||
def toggle_classroom(classroom_id: int):
|
||||
"""Alterna el estado activo/inactivo de un aula."""
|
||||
classroom = Classroom.query.get_or_404(classroom_id)
|
||||
classroom.is_active = not classroom.is_active
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'id': classroom.id,
|
||||
'is_active': classroom.is_active,
|
||||
'message': f'Aula {"activada" if classroom.is_active else "desactivada"} correctamente.'
|
||||
}), 200
|
||||
@@ -1,342 +0,0 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject
|
||||
from app.models.user import User
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.audit_log import AuditLog
|
||||
from datetime import datetime, timedelta
|
||||
from sqlalchemy import func
|
||||
from app import db
|
||||
|
||||
from app.models.milestone import AcademicMilestone
|
||||
from app.models.subject import Commission
|
||||
from app.models.setting import SystemSetting
|
||||
|
||||
api_dashboard_bp = Blueprint('api_dashboard', __name__, url_prefix='/api/v1/dashboard')
|
||||
|
||||
def serialize_reservation(r):
|
||||
subject_name = (r.commission.subject.name if (r.commission and r.commission.subject) else r.purpose) or 'Actividad Académica'
|
||||
subject_code = (r.commission.subject.code if (r.commission and r.commission.subject) else '')
|
||||
classroom_code = r.classroom.code if r.classroom else 'Sin Aula'
|
||||
is_virtual = ('virtual' in classroom_code.lower()) or (getattr(r.classroom, 'is_virtual', False) if r.classroom else False)
|
||||
return {
|
||||
'id': r.id,
|
||||
'start_time': r.start_time.strftime('%H:%M') if r.start_time else '',
|
||||
'end_time': r.end_time.strftime('%H:%M') if r.end_time else '',
|
||||
'date_display': r.start_time.strftime('%d/%m') if r.start_time else '',
|
||||
'classroom': {
|
||||
'id': r.classroom_id,
|
||||
'code': classroom_code,
|
||||
'is_virtual': is_virtual,
|
||||
'location_display': getattr(r.classroom, 'location_display', f'Sede Central · {classroom_code}') if r.classroom else 'Sin Aula'
|
||||
},
|
||||
'subject_name': subject_name,
|
||||
'subject_code': subject_code,
|
||||
'shift': r.shift or 'Mañana',
|
||||
'commission': {
|
||||
'id': r.commission_id,
|
||||
'code': r.commission.code if r.commission else 'COM-1'
|
||||
},
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'user': {
|
||||
'id': r.user_id,
|
||||
'name': r.user.name if r.user else 'Docente'
|
||||
},
|
||||
'virtual_link': r.virtual_link or ('https://meet.google.com/edu-space-' + classroom_code.lower().replace(' ', '-') if is_virtual else '')
|
||||
}
|
||||
|
||||
def serialize_milestone(m):
|
||||
return {
|
||||
'id': m.id,
|
||||
'title': m.title,
|
||||
'materia_codigo': m.materia_codigo,
|
||||
'subject_name': m.subject.name if (hasattr(m, 'subject') and m.subject) else m.materia_codigo,
|
||||
'date': m.date.strftime('%d/%m/%Y') if m.date else '',
|
||||
'type_obj': {
|
||||
'name': m.type_obj.name if m.type_obj else 'Evaluación',
|
||||
'color': m.type_obj.color if m.type_obj else '#0d6efd'
|
||||
},
|
||||
'classroom': m.classroom or 'Sede Central',
|
||||
'link': m.link or '',
|
||||
'notes': m.notes or ''
|
||||
}
|
||||
|
||||
@api_dashboard_bp.route('/stats', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_stats():
|
||||
"""Retorna estadísticas clave y datos operativos para el Dashboard."""
|
||||
today = datetime.utcnow().date()
|
||||
|
||||
try:
|
||||
total_classrooms = Classroom.query.filter_by(is_active=True).count()
|
||||
total_subjects = Subject.query.filter_by(is_active=True).count()
|
||||
total_users = User.query.filter_by(is_active=True).count()
|
||||
|
||||
# Aulas presenciales y virtuales
|
||||
all_active_classrooms = Classroom.query.filter_by(is_active=True).all()
|
||||
virtual_classrooms_list = [
|
||||
c for c in all_active_classrooms
|
||||
if getattr(c, 'is_virtual', False)
|
||||
or 'virtual' in (c.building or '').lower()
|
||||
or 'virtual' in (c.code or '').lower()
|
||||
]
|
||||
virtual_classrooms = len(virtual_classrooms_list)
|
||||
|
||||
physical_classrooms_list = [
|
||||
c for c in all_active_classrooms
|
||||
if c not in virtual_classrooms_list
|
||||
]
|
||||
total_physical_count = len(physical_classrooms_list)
|
||||
physical_classrooms = total_physical_count
|
||||
physical_ids = set(c.id for c in physical_classrooms_list)
|
||||
|
||||
# 1. Asignación General del Cuatrimestre / Cronograma
|
||||
assigned_all_ids = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id)
|
||||
.filter(Reservation.classroom_id.isnot(None)).distinct().all()
|
||||
)
|
||||
assigned_physical_ids = physical_ids.intersection(assigned_all_ids)
|
||||
assigned_classrooms = len(assigned_physical_ids)
|
||||
unassigned_classrooms = max(0, total_physical_count - assigned_classrooms)
|
||||
|
||||
assigned_pct = round((assigned_classrooms / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0
|
||||
unassigned_pct = round(100.0 - assigned_pct, 1) if total_physical_count > 0 else 0.0
|
||||
|
||||
# 2. Asignación Operativa del Día de Hoy
|
||||
assigned_today_ids = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id).filter(
|
||||
Reservation.classroom_id.isnot(None),
|
||||
func.date(Reservation.start_time) == today
|
||||
).distinct().all()
|
||||
)
|
||||
assigned_today_physical_ids = physical_ids.intersection(assigned_today_ids)
|
||||
assigned_today_count = len(assigned_today_physical_ids)
|
||||
unassigned_today_count = max(0, total_physical_count - assigned_today_count)
|
||||
|
||||
assigned_today_pct = round((assigned_today_count / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0
|
||||
unassigned_today_pct = round(100.0 - assigned_today_pct, 1) if total_physical_count > 0 else 0.0
|
||||
|
||||
today_reservations_q = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
today_reservations = len(today_reservations_q)
|
||||
|
||||
pending_reservations_q = Reservation.query.filter(
|
||||
Reservation.status == 'PENDING'
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
pending_count = len(pending_reservations_q)
|
||||
|
||||
upcoming_reservations_q = Reservation.query.filter(
|
||||
Reservation.start_time >= datetime.utcnow()
|
||||
).order_by(Reservation.start_time.asc()).limit(10).all()
|
||||
|
||||
milestones_q = AcademicMilestone.query.filter(
|
||||
AcademicMilestone.is_active == True
|
||||
).order_by(AcademicMilestone.date.asc()).limit(10).all()
|
||||
|
||||
recent_audits = AuditLog.query.order_by(AuditLog.created_at.desc()).limit(6).all()
|
||||
audit_data = [{
|
||||
'created_at': a.created_at.strftime('%Y-%m-%d %H:%M') if a.created_at else None,
|
||||
'action_type': getattr(a, 'action', getattr(a, 'action_type', 'AUDIT')),
|
||||
'ip_address': a.ip_address,
|
||||
'user_email': getattr(a, 'user_email', None) or (getattr(a.user, 'email', 'System') if hasattr(a, 'user') else 'System')
|
||||
} for a in recent_audits]
|
||||
|
||||
occupancy_rate = min(100, int((today_reservations / max(1, physical_classrooms * 3)) * 100)) if physical_classrooms > 0 else 0
|
||||
|
||||
pending_reservations = [serialize_reservation(r) for r in pending_reservations_q]
|
||||
today_schedule_list = [serialize_reservation(r) for r in today_reservations_q]
|
||||
upcoming_reservations = [serialize_reservation(r) for r in upcoming_reservations_q]
|
||||
milestones = [serialize_milestone(m) for m in milestones_q]
|
||||
|
||||
# ---- Bedelía: Comisiones sin aula asignada (semana y mes) ----
|
||||
import calendar
|
||||
# Calcular rango de semana actual (lunes a domingo)
|
||||
today_dt = datetime.utcnow()
|
||||
week_start = today_dt - timedelta(days=today_dt.weekday()) # lunes
|
||||
week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
week_end = week_start + timedelta(days=6, hours=23, minutes=59, seconds=59)
|
||||
|
||||
# Calcular rango del mes actual
|
||||
month_start = today_dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
last_day = calendar.monthrange(today_dt.year, today_dt.month)[1]
|
||||
month_end = today_dt.replace(day=last_day, hour=23, minute=59, second=59, microsecond=0)
|
||||
|
||||
# Comisiones activas totales
|
||||
all_active_commissions = Commission.query.filter_by(active=True).all()
|
||||
total_active_commissions = len(all_active_commissions)
|
||||
|
||||
# IDs de comisiones que SÍ tienen reserva en la semana
|
||||
comm_ids_with_res_week = set(
|
||||
r[0] for r in db.session.query(Reservation.commission_id).filter(
|
||||
Reservation.commission_id.isnot(None),
|
||||
Reservation.start_time >= week_start,
|
||||
Reservation.start_time <= week_end
|
||||
).distinct().all()
|
||||
)
|
||||
# IDs de comisiones que SÍ tienen reserva en el mes
|
||||
comm_ids_with_res_month = set(
|
||||
r[0] for r in db.session.query(Reservation.commission_id).filter(
|
||||
Reservation.commission_id.isnot(None),
|
||||
Reservation.start_time >= month_start,
|
||||
Reservation.start_time <= month_end
|
||||
).distinct().all()
|
||||
)
|
||||
|
||||
unassigned_commissions_week = []
|
||||
unassigned_commissions_month = []
|
||||
for comm in all_active_commissions:
|
||||
comm_data = {
|
||||
'id': comm.id,
|
||||
'code': comm.code,
|
||||
'full_code': comm.get_full_code(),
|
||||
'subject_name': comm.subject.name if comm.subject else 'Sin materia',
|
||||
'subject_code': comm.subject.code if comm.subject else '',
|
||||
'teacher_name': comm.teacher_name,
|
||||
'schedule': comm.schedule or 'Sin horario',
|
||||
'shift': comm.shift or 'Sin turno',
|
||||
'max_students': comm.max_students,
|
||||
'current_students': comm.current_students
|
||||
}
|
||||
if comm.id not in comm_ids_with_res_week:
|
||||
unassigned_commissions_week.append(comm_data)
|
||||
if comm.id not in comm_ids_with_res_month:
|
||||
unassigned_commissions_month.append(comm_data)
|
||||
|
||||
# ---- Bedelía: Aulas disponibles (sin reservas) en la semana y mes ----
|
||||
classroom_ids_used_week = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id).filter(
|
||||
Reservation.classroom_id.isnot(None),
|
||||
Reservation.start_time >= week_start,
|
||||
Reservation.start_time <= week_end
|
||||
).distinct().all()
|
||||
)
|
||||
classroom_ids_used_month = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id).filter(
|
||||
Reservation.classroom_id.isnot(None),
|
||||
Reservation.start_time >= month_start,
|
||||
Reservation.start_time <= month_end
|
||||
).distinct().all()
|
||||
)
|
||||
|
||||
available_classrooms_week = []
|
||||
available_classrooms_month = []
|
||||
for c in all_active_classrooms:
|
||||
c_data = {
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building or 'Sin edificio',
|
||||
'floor': c.floor or '',
|
||||
'capacity': c.capacity,
|
||||
'is_virtual': getattr(c, 'is_virtual', False) or 'virtual' in (c.building or '').lower() or 'virtual' in (c.code or '').lower()
|
||||
}
|
||||
if c.id not in classroom_ids_used_week:
|
||||
available_classrooms_week.append(c_data)
|
||||
if c.id not in classroom_ids_used_month:
|
||||
available_classrooms_month.append(c_data)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error fetching stats: {e}")
|
||||
total_classrooms = 0
|
||||
total_subjects = 0
|
||||
total_users = 0
|
||||
today_reservations = 0
|
||||
pending_count = 0
|
||||
physical_classrooms = 0
|
||||
virtual_classrooms = 0
|
||||
occupancy_rate = 0
|
||||
assigned_classrooms = 0
|
||||
assigned_pct = 0.0
|
||||
unassigned_classrooms = 0
|
||||
unassigned_pct = 0.0
|
||||
assigned_today_count = 0
|
||||
assigned_today_pct = 0.0
|
||||
unassigned_today_count = 0
|
||||
unassigned_today_pct = 0.0
|
||||
audit_data = []
|
||||
pending_reservations = []
|
||||
today_schedule_list = []
|
||||
upcoming_reservations = []
|
||||
unassigned_commissions_week = []
|
||||
unassigned_commissions_month = []
|
||||
available_classrooms_week = []
|
||||
available_classrooms_month = []
|
||||
total_active_commissions = 0
|
||||
milestones = []
|
||||
|
||||
# Mocked monthly data for chart since complex SQL group by month might differ based on dialect (SQLite vs Postgres)
|
||||
monthly_data = [
|
||||
{"month": "Ene", "reservations": 120},
|
||||
{"month": "Feb", "reservations": 180},
|
||||
{"month": "Mar", "reservations": 250},
|
||||
{"month": "Abr", "reservations": 220},
|
||||
{"month": "May", "reservations": 300},
|
||||
{"month": "Jun", "reservations": 310},
|
||||
{"month": "Jul", "reservations": 200},
|
||||
{"month": "Ago", "reservations": 350},
|
||||
{"month": "Sep", "reservations": 420},
|
||||
{"month": "Oct", "reservations": 480},
|
||||
{"month": "Nov", "reservations": 520},
|
||||
{"month": "Dic", "reservations": 210}
|
||||
]
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'stats': {
|
||||
'total_classrooms': total_classrooms,
|
||||
'active_subjects': total_subjects,
|
||||
'total_active_users': total_users,
|
||||
'today_reservations': today_reservations,
|
||||
'pending_count': pending_count,
|
||||
'physical_classrooms': physical_classrooms,
|
||||
'virtual_classrooms': virtual_classrooms,
|
||||
'occupancy_rate': occupancy_rate,
|
||||
'assigned_classrooms': assigned_classrooms,
|
||||
'assigned_classrooms_pct': assigned_pct,
|
||||
'unassigned_classrooms': unassigned_classrooms,
|
||||
'unassigned_classrooms_pct': unassigned_pct,
|
||||
'assigned_today_classrooms': assigned_today_count,
|
||||
'assigned_today_pct': assigned_today_pct,
|
||||
'unassigned_today_classrooms': unassigned_today_count,
|
||||
'unassigned_today_pct': unassigned_today_pct,
|
||||
'total_active_commissions': total_active_commissions
|
||||
},
|
||||
'audit_logs': audit_data,
|
||||
'monthly_data': monthly_data,
|
||||
'pending_reservations': pending_reservations,
|
||||
'today_schedule_list': today_schedule_list,
|
||||
'upcoming_reservations': upcoming_reservations,
|
||||
'milestones': milestones,
|
||||
'ui': {
|
||||
'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True]
|
||||
},
|
||||
'bedelia': {
|
||||
'unassigned_commissions_week': unassigned_commissions_week,
|
||||
'unassigned_commissions_month': unassigned_commissions_month,
|
||||
'available_classrooms_week': available_classrooms_week,
|
||||
'available_classrooms_month': available_classrooms_month
|
||||
}
|
||||
}), 200
|
||||
|
||||
@api_dashboard_bp.route('/sync-sheets', methods=['POST'])
|
||||
@jwt_required
|
||||
def sync_google_sheets():
|
||||
"""Ejecuta la sincronización real con las hojas de cálculo de Google Sheets."""
|
||||
from app.services.sheets_importer import GoogleSheetsImporter
|
||||
try:
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_url = data.get('sheets_url') or data.get('base_url')
|
||||
importer = GoogleSheetsImporter(base_url=custom_url)
|
||||
stats = importer.sync()
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'stats': stats,
|
||||
'source_url': importer.base_url
|
||||
}), 200
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'status': 'error',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
api_openapi_bp = Blueprint('api_openapi', __name__, url_prefix='/api/v1')
|
||||
|
||||
OPENAPI_SPEC = {
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "Edu-Space REST API",
|
||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://127.0.0.1:5000",
|
||||
"description": "Local Flask Backend Server"
|
||||
}
|
||||
],
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"bearerAuth": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"bearerFormat": "JWT"
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"LoginRequest": {
|
||||
"type": "object",
|
||||
"required": ["email", "password"],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string",
|
||||
"format": "email",
|
||||
"example": "admin@eduspace.com"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"format": "password",
|
||||
"example": "Admin123!"
|
||||
}
|
||||
}
|
||||
},
|
||||
"LoginResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"access_token": {"type": "string"},
|
||||
"refresh_token": {"type": "string"},
|
||||
"token_type": {"type": "string", "example": "Bearer"},
|
||||
"expires_in": {"type": "integer"},
|
||||
"user": {"type": "object"}
|
||||
}
|
||||
},
|
||||
"ErrorResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"error": {"type": "string"},
|
||||
"message": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"UserResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"email": {"type": "string"},
|
||||
"first_name": {"type": "string"},
|
||||
"last_name": {"type": "string"},
|
||||
"role": {"type": "string"},
|
||||
"is_active": {"type": "boolean"}
|
||||
}
|
||||
},
|
||||
"SubjectResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"name": {"type": "string"},
|
||||
"code": {"type": "string"},
|
||||
"career": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"ClassroomResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"name": {"type": "string"},
|
||||
"capacity": {"type": "integer"},
|
||||
"building": {"type": "string"},
|
||||
"floor": {"type": "string"}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/auth/login": {
|
||||
"post": {
|
||||
"summary": "Authenticate user and issue JWT tokens",
|
||||
"tags": ["Authentication"],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/LoginRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Authentication successful",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/LoginResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Validation error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/ErrorResponse"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized / Bad credentials",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/ErrorResponse"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/auth/me": {
|
||||
"get": {
|
||||
"summary": "Get authenticated user profile",
|
||||
"tags": ["Authentication"],
|
||||
"security": [{"bearerAuth": []}],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Current user profile",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/UserResponse"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Missing or invalid token",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/ErrorResponse"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/classrooms": {
|
||||
"get": {
|
||||
"summary": "List all physical classrooms and facilities",
|
||||
"tags": ["Classrooms"],
|
||||
"security": [{"bearerAuth": []}],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "List of classrooms",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/components/schemas/ClassroomResponse"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/users": {
|
||||
"get": {
|
||||
"summary": "List all users (Admin only)",
|
||||
"tags": ["Admin - Users"],
|
||||
"security": [{"bearerAuth": []}],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "List of users",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/components/schemas/UserResponse"}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden - Requires admin role"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/subjects": {
|
||||
"get": {
|
||||
"summary": "List all academic subjects (Admin only)",
|
||||
"tags": ["Admin - Academic"],
|
||||
"security": [{"bearerAuth": []}],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "List of subjects",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/components/schemas/SubjectResponse"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/openapi.json": {
|
||||
"get": {
|
||||
"summary": "Get OpenAPI 3.0.3 specification JSON",
|
||||
"tags": ["Documentation"],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OpenAPI Specification"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@api_openapi_bp.route('/openapi.json', methods=['GET'])
|
||||
def get_openapi_spec():
|
||||
"""Serves the OpenAPI 3.0 specification for Schemathesis / DAST and Swagger UI."""
|
||||
return jsonify(OPENAPI_SPEC)
|
||||
@@ -1,105 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.schemas.optimizer_dto import OptimizerJobRequestDTO, SpringBootSyncPayloadDTO
|
||||
from app.services.optimizer_service import OptimizerService
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
|
||||
api_optimizer_bp = Blueprint('api_optimizer', __name__, url_prefix='/api/v1/optimizer')
|
||||
|
||||
|
||||
@api_optimizer_bp.route('/jobs', methods=['POST'])
|
||||
@jwt_required
|
||||
def submit_optimization_job():
|
||||
"""
|
||||
Despacha un trabajo de optimización heurística asíncrono.
|
||||
Retorna inmediatamente con HTTP 202 Accepted y el identificador de trabajo para sondeo.
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
dto = OptimizerJobRequestDTO(**data)
|
||||
except ValidationError as ex:
|
||||
return jsonify({
|
||||
'error': 'UnprocessableEntity',
|
||||
'message': 'Error de validación en los parámetros del optimizador.',
|
||||
'details': ex.errors()
|
||||
}), 422
|
||||
|
||||
user_id = g.current_user.id if hasattr(g, 'current_user') and g.current_user else 1
|
||||
|
||||
job = OptimizerService.submit_job(
|
||||
commission_ids=dto.commission_ids,
|
||||
admin_user_id=user_id,
|
||||
start_date=dto.start_date,
|
||||
end_date=dto.end_date,
|
||||
generations=dto.generations,
|
||||
population_size=dto.population_size,
|
||||
workers=dto.workers
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'job_id': job.job_id,
|
||||
'status': job.status.value,
|
||||
'poll_url': f'/api/v1/optimizer/jobs/{job.job_id}',
|
||||
'message': 'Trabajo de optimización puesto en cola con éxito.'
|
||||
}), 202
|
||||
|
||||
|
||||
@api_optimizer_bp.route('/jobs/<string:job_id>', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_optimization_job(job_id: str):
|
||||
"""
|
||||
Obtiene el estado, progreso y resultados de un trabajo de optimización en cola.
|
||||
"""
|
||||
job = OptimizerService.get_job(job_id)
|
||||
if not job:
|
||||
return jsonify({
|
||||
'error': 'NotFound',
|
||||
'message': f'Trabajo de optimización {job_id} no encontrado.'
|
||||
}), 404
|
||||
|
||||
return jsonify(job.to_dict()), 200
|
||||
|
||||
|
||||
@api_optimizer_bp.route('/jobs', methods=['GET'])
|
||||
@jwt_required
|
||||
def list_optimization_jobs():
|
||||
"""
|
||||
Lista los trabajos de optimización más recientes.
|
||||
"""
|
||||
limit = request.args.get('limit', default=20, type=int)
|
||||
jobs = OptimizerService.list_jobs(limit=limit)
|
||||
return jsonify({
|
||||
'total': len(jobs),
|
||||
'jobs': jobs
|
||||
}), 200
|
||||
|
||||
|
||||
@api_optimizer_bp.route('/spring-boot/sync', methods=['POST'])
|
||||
@jwt_required
|
||||
def sync_with_spring_boot():
|
||||
"""
|
||||
Endpoint interoperable para la sincronización y resolución de horarios con microservicios Spring Boot.
|
||||
Recibe el payload en formato Spring Boot (camelCase) y retorna el cronograma optimizado.
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
dto = SpringBootSyncPayloadDTO(**data)
|
||||
except ValidationError as ex:
|
||||
return jsonify({
|
||||
'error': 'UnprocessableEntity',
|
||||
'message': 'Error de validación en el payload Spring Boot.',
|
||||
'details': ex.errors()
|
||||
}), 422
|
||||
|
||||
user_id = g.current_user.id if hasattr(g, 'current_user') and g.current_user else 1
|
||||
|
||||
try:
|
||||
result = OptimizerService.sync_with_spring_boot(dto, admin_user_id=user_id)
|
||||
return jsonify(result), 200
|
||||
except Exception as ex:
|
||||
return jsonify({
|
||||
'requestId': dto.requestId,
|
||||
'status': 'ERROR',
|
||||
'error': str(ex)
|
||||
}), 500
|
||||
@@ -1,314 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from datetime import datetime, timedelta, date
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app import db
|
||||
from app.models.reservation import Reservation
|
||||
from app.services.reservation_service import ReservationService
|
||||
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
|
||||
from app.utils.jwt_decorators import jwt_required, jwt_role_required
|
||||
|
||||
api_reservations_bp = Blueprint('api_reservations', __name__, url_prefix='/api/v1/reservations')
|
||||
reservation_service = ReservationService()
|
||||
|
||||
@api_reservations_bp.route('', methods=['GET'])
|
||||
@jwt_required
|
||||
def list_reservations():
|
||||
"""Consulta de reservas por rango de fechas y/o aula."""
|
||||
start_str = request.args.get('start_date')
|
||||
end_str = request.args.get('end_date')
|
||||
classroom_id = request.args.get('classroom_id', type=int)
|
||||
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
start_dt = datetime.strptime(start_str, '%Y-%m-%d') if start_str else now.replace(hour=0, minute=0, second=0)
|
||||
except ValueError:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'Formato inválido de start_date (debe ser YYYY-MM-DD).'}), 400
|
||||
|
||||
try:
|
||||
end_dt = datetime.strptime(end_str, '%Y-%m-%d').replace(hour=23, minute=59, second=59) if end_str else start_dt + timedelta(days=7)
|
||||
except ValueError:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'Formato inválido de end_date (debe ser YYYY-MM-DD).'}), 400
|
||||
|
||||
hide_virtual = request.args.get('hide_virtual', '0') in ['1', 'true', 'True']
|
||||
floor = request.args.get('floor')
|
||||
shift = request.args.get('shift')
|
||||
search = request.args.get('search')
|
||||
|
||||
reservations = reservation_service.list_reservations(start_dt, end_dt, classroom_id=classroom_id)
|
||||
result = []
|
||||
for r in reservations:
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
if hide_virtual and is_virt:
|
||||
continue
|
||||
if floor and r.classroom and str(r.classroom.floor).strip().lower() != str(floor).strip().lower():
|
||||
continue
|
||||
if shift and r.shift and shift.lower() not in r.shift.lower():
|
||||
continue
|
||||
if search:
|
||||
s_lower = search.lower()
|
||||
subj_n = (r.subject_name or '').lower()
|
||||
subj_c = (r.subject_code or '').lower()
|
||||
c_name = (r.classroom.code if r.classroom else '').lower()
|
||||
u_name = (r.user.name if r.user else '').lower()
|
||||
if s_lower not in subj_n and s_lower not in subj_c and s_lower not in c_name and s_lower not in u_name:
|
||||
continue
|
||||
|
||||
result.append({
|
||||
'id': r.id,
|
||||
'classroom_id': r.classroom_id,
|
||||
'classroom_name': r.classroom.code if r.classroom else None,
|
||||
'classroom': {
|
||||
'id': r.classroom.id,
|
||||
'code': r.classroom.code,
|
||||
'code_display': getattr(r.classroom, 'code_display', r.classroom.code),
|
||||
'floor': r.classroom.floor,
|
||||
'floor_display': getattr(r.classroom, 'floor_display', f"Piso {r.classroom.floor}"),
|
||||
'building': getattr(r.classroom, 'building_name', r.classroom.building),
|
||||
'is_virtual': getattr(r.classroom, 'is_virtual', False),
|
||||
'location_display': getattr(r.classroom, 'location_display', r.classroom.code)
|
||||
} if r.classroom else None,
|
||||
'commission_id': r.commission_id,
|
||||
'commission': {
|
||||
'id': r.commission.id,
|
||||
'code': r.commission.code,
|
||||
'virtual_link': r.commission.virtual_link,
|
||||
'max_students': r.commission.max_students
|
||||
} if r.commission else None,
|
||||
'teacher_name': r.user.name if r.user else None,
|
||||
'user': {
|
||||
'id': r.user.id,
|
||||
'name': r.user.name,
|
||||
'email': r.user.email
|
||||
} if r.user else None,
|
||||
'start_time': r.start_time.isoformat(),
|
||||
'end_time': r.end_time.isoformat(),
|
||||
'purpose': r.purpose,
|
||||
'subject_name': r.subject_name,
|
||||
'subject_code': r.subject_code,
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'shift': r.shift or 'Mañana',
|
||||
'virtual_link': r.virtual_link,
|
||||
'effective_virtual_link': r.effective_virtual_link,
|
||||
'is_virtual': is_virt,
|
||||
'expected_attendees': r.expected_attendees or 30,
|
||||
'notes': r.notes or ''
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'total': len(result),
|
||||
'start_date': start_dt.strftime('%Y-%m-%d'),
|
||||
'end_date': end_dt.strftime('%Y-%m-%d'),
|
||||
'reservations': result
|
||||
}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_reservation(reservation_id: int):
|
||||
"""Obtiene el detalle de una reserva específica con sus relaciones completas."""
|
||||
r = reservation_service.get_reservation(reservation_id)
|
||||
if not r:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
duration_min = int((r.end_time - r.start_time).total_seconds() / 60) if (r.start_time and r.end_time) else 120
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
|
||||
return jsonify({
|
||||
'id': r.id,
|
||||
'classroom_id': r.classroom_id,
|
||||
'classroom_name': r.classroom.code if r.classroom else None,
|
||||
'location_display': getattr(r.classroom, 'location_display', r.classroom.code if r.classroom else None),
|
||||
'classroom': {
|
||||
'id': r.classroom.id,
|
||||
'code': r.classroom.code,
|
||||
'code_display': getattr(r.classroom, 'code_display', r.classroom.code),
|
||||
'building_name': getattr(r.classroom, 'building_name', getattr(r.classroom, 'building', 'Edificio Central')),
|
||||
'floor': r.classroom.floor,
|
||||
'floor_display': getattr(r.classroom, 'floor_display', f"Piso {r.classroom.floor}"),
|
||||
'capacity': r.classroom.capacity,
|
||||
'capacity_display': getattr(r.classroom, 'capacity_display', str(r.classroom.capacity)),
|
||||
'description': getattr(r.classroom, 'description', '') or '',
|
||||
'is_virtual': getattr(r.classroom, 'is_virtual', False)
|
||||
} if r.classroom else None,
|
||||
'commission_id': r.commission_id,
|
||||
'commission': {
|
||||
'id': r.commission.id,
|
||||
'code': r.commission.code,
|
||||
'full_code': r.commission.get_full_code() if hasattr(r.commission, 'get_full_code') else r.commission.code,
|
||||
'virtual_link': r.commission.virtual_link,
|
||||
'max_students': r.commission.max_students,
|
||||
'current_students': getattr(r.commission, 'current_students', 0),
|
||||
'subject': {
|
||||
'id': r.commission.subject.id,
|
||||
'name': r.commission.subject.name,
|
||||
'code': r.commission.subject.code
|
||||
} if (r.commission and r.commission.subject) else None
|
||||
} if r.commission else None,
|
||||
'teacher_id': r.user_id,
|
||||
'teacher_name': r.user.name if r.user else None,
|
||||
'user': {
|
||||
'id': r.user.id,
|
||||
'name': r.user.name,
|
||||
'first_name': getattr(r.user, 'first_name', r.user.name.split()[0] if r.user.name else 'Usuario'),
|
||||
'last_name': getattr(r.user, 'last_name', ' '.join(r.user.name.split()[1:]) if r.user.name and len(r.user.name.split()) > 1 else ''),
|
||||
'email': r.user.email
|
||||
} if r.user else None,
|
||||
'start_time': r.start_time.isoformat(),
|
||||
'end_time': r.end_time.isoformat(),
|
||||
'duration': duration_min,
|
||||
'purpose': r.purpose,
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'shift': r.shift or 'Mañana',
|
||||
'virtual_link': r.virtual_link,
|
||||
'effective_virtual_link': r.effective_virtual_link,
|
||||
'is_virtual': is_virt,
|
||||
'expected_attendees': r.expected_attendees or 30,
|
||||
'notes': r.notes or '',
|
||||
'can_be_cancelled': r.can_be_cancelled() if hasattr(r, 'can_be_cancelled') else True
|
||||
}), 200
|
||||
|
||||
@api_reservations_bp.route('', methods=['POST'])
|
||||
@jwt_required
|
||||
def create_reservation():
|
||||
"""Crea una reserva aplicando validación DTO y detección de colisiones."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
# Inyectar usuario autenticado si no se especifica
|
||||
if 'user_id' not in data:
|
||||
data['user_id'] = g.jwt_user.id
|
||||
|
||||
try:
|
||||
dto = ReservationCreateDTO(**data)
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
try:
|
||||
reservation = reservation_service.create_reservation(dto)
|
||||
return jsonify({
|
||||
'message': 'Reserva creada exitosamente.',
|
||||
'id': reservation.id,
|
||||
'classroom_id': reservation.classroom_id,
|
||||
'start_time': reservation.start_time.isoformat(),
|
||||
'end_time': reservation.end_time.isoformat(),
|
||||
'status': str(reservation.status)
|
||||
}), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 409
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>', methods=['PUT'])
|
||||
@jwt_required
|
||||
def update_reservation(reservation_id: int):
|
||||
"""Modifica una reserva existente."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
dto = ReservationUpdateDTO(**data)
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
try:
|
||||
reservation = reservation_service.update_reservation(reservation_id, dto)
|
||||
return jsonify({
|
||||
'message': 'Reserva actualizada exitosamente.',
|
||||
'id': reservation.id,
|
||||
'start_time': reservation.start_time.isoformat(),
|
||||
'end_time': reservation.end_time.isoformat(),
|
||||
'status': str(reservation.status)
|
||||
}), 200
|
||||
except ValueError as e:
|
||||
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 409
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>', methods=['DELETE'])
|
||||
@jwt_required
|
||||
def cancel_reservation(reservation_id: int):
|
||||
"""Cancela o elimina una reserva según el parámetro hard."""
|
||||
hard_delete = request.args.get('hard', '').lower() in ['true', '1']
|
||||
if hard_delete:
|
||||
res = Reservation.query.get(reservation_id)
|
||||
if not res:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
return jsonify({'message': f'Reserva {reservation_id} eliminada permanentemente.'}), 200
|
||||
|
||||
cancelled = reservation_service.cancel_reservation(reservation_id)
|
||||
if not cancelled:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/delete', methods=['POST'])
|
||||
@jwt_required
|
||||
def delete_reservation_post(reservation_id: int):
|
||||
"""Elimina permanentemente una reserva."""
|
||||
res = Reservation.query.get(reservation_id)
|
||||
if not res:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
return jsonify({'message': f'Reserva {reservation_id} eliminada permanentemente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/cancel', methods=['POST'])
|
||||
@jwt_required
|
||||
def cancel_reservation_post(reservation_id: int):
|
||||
"""Cancela una reserva (endpoint POST compatible con formularios)."""
|
||||
cancelled = reservation_service.cancel_reservation(reservation_id)
|
||||
if not cancelled:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/confirm', methods=['POST'])
|
||||
@jwt_required
|
||||
def confirm_reservation(reservation_id: int):
|
||||
"""Confirma una reserva cambiando su estado a CONFIRMED."""
|
||||
confirmed = reservation_service.confirm_reservation(reservation_id)
|
||||
if not confirmed:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
return jsonify({'message': f'Reserva {reservation_id} confirmada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/check-conflicts', methods=['POST'])
|
||||
@jwt_required
|
||||
def check_conflicts_endpoint():
|
||||
"""
|
||||
Evalúa la matriz completa de conflictos (físico, docente y aforo) en tiempo real.
|
||||
"""
|
||||
data = request.get_json(silent=True)
|
||||
if not isinstance(data, dict):
|
||||
return jsonify({'error': 'BadRequest', 'message': 'El cuerpo de la solicitud debe ser un objeto JSON.'}), 400
|
||||
|
||||
classroom_id = data.get('classroom_id')
|
||||
start_str = data.get('start_time')
|
||||
end_str = data.get('end_time')
|
||||
|
||||
if not classroom_id or not start_str or not end_str:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'classroom_id, start_time y end_time son obligatorios.'}), 400
|
||||
|
||||
try:
|
||||
start_time = datetime.fromisoformat(str(start_str).replace('Z', '+00:00'))
|
||||
end_time = datetime.fromisoformat(str(end_str).replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
return jsonify({'error': 'BadRequest', 'message': 'Formato inválido de fecha/hora (ISO 8601 esperado).'}), 400
|
||||
|
||||
teacher_id = data.get('teacher_id')
|
||||
commission_id = data.get('commission_id')
|
||||
expected_attendees = data.get('expected_attendees')
|
||||
allow_co_teaching = bool(data.get('allow_co_teaching_exception', False))
|
||||
exclude_id = data.get('exclude_id')
|
||||
|
||||
try:
|
||||
matrix = reservation_service.check_full_conflicts_matrix(
|
||||
classroom_id=int(classroom_id),
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
teacher_id=int(teacher_id) if teacher_id else None,
|
||||
commission_id=int(commission_id) if commission_id else None,
|
||||
expected_attendees=int(expected_attendees) if expected_attendees is not None else None,
|
||||
allow_co_teaching_exception=allow_co_teaching,
|
||||
exclude_id=int(exclude_id) if exclude_id else None
|
||||
)
|
||||
return jsonify(matrix), 200
|
||||
except ValueError as e:
|
||||
return jsonify({'error': 'ValidationError', 'message': str(e)}), 400
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
from flask import Blueprint, jsonify, request, g
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
from app.services.gradebook_service import GradebookService
|
||||
|
||||
api_students_bp = Blueprint('api_students', __name__)
|
||||
|
||||
|
||||
@api_students_bp.route('/students/my-grades', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_my_grades():
|
||||
"""Consulta individual de calificaciones y estado académico del alumno logueado."""
|
||||
user = getattr(g, 'jwt_user', None)
|
||||
user_id = user.id if user else getattr(request, 'current_user_id', None)
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Usuario no autenticado.'}), 401
|
||||
|
||||
try:
|
||||
grades = GradebookService.get_student_grades(user_id)
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'student_id': user_id,
|
||||
'is_impersonating': getattr(g, 'is_impersonating', False),
|
||||
'data': grades
|
||||
}), 200
|
||||
except Exception as e:
|
||||
return jsonify({'error': 'ServerError', 'message': str(e)}), 500
|
||||
|
||||
|
||||
@api_students_bp.route('/students/my-upcoming-milestones', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_my_upcoming_milestones():
|
||||
"""Próximas evaluaciones e hitos académicos con cuenta regresiva para el dashboard."""
|
||||
user = getattr(g, 'jwt_user', None)
|
||||
user_id = user.id if user else getattr(request, 'current_user_id', None)
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Usuario no autenticado.'}), 401
|
||||
|
||||
limit = request.args.get('limit', default=5, type=int)
|
||||
try:
|
||||
milestones = GradebookService.get_student_upcoming_milestones(user_id, limit=limit)
|
||||
return jsonify({'status': 'success', 'data': milestones}), 200
|
||||
except Exception as e:
|
||||
return jsonify({'error': 'ServerError', 'message': str(e)}), 500
|
||||
@@ -1,152 +0,0 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, session, jsonify
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from flask_babel import gettext as _
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.forms.auth import LoginForm
|
||||
from datetime import datetime
|
||||
|
||||
auth_bp = Blueprint('auth', __name__)
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
@auth_bp.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""Handle user login with case-insensitive email lookup and whitespace trimming"""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('main.dashboard'))
|
||||
|
||||
from app.models.setting import SystemSetting
|
||||
demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True]
|
||||
|
||||
form = LoginForm()
|
||||
if form.validate_on_submit():
|
||||
clean_email = (form.email.data or '').strip().lower()
|
||||
user = User.query.filter(func.lower(User.email) == clean_email).first()
|
||||
|
||||
if user and user.check_password(form.password.data):
|
||||
if not user.is_active:
|
||||
flash(_('Tu cuenta ha sido desactivada. Por favor contacta al administrador.'), 'error')
|
||||
return render_template('auth/login.html', form=form, demo_access_enabled=demo_access_enabled)
|
||||
|
||||
login_user(user, remember=form.remember_me.data)
|
||||
user.update_last_login()
|
||||
|
||||
# Registrar en bitácora de auditoría
|
||||
try:
|
||||
from app.services.audit_service import AuditService
|
||||
AuditService.log(
|
||||
action='LOGIN',
|
||||
module='auth',
|
||||
user_id=user.id,
|
||||
user_email=user.email,
|
||||
details=f"Inicio de sesión exitoso ({user.role})"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Si el usuario tiene idioma configurado en su perfil, sobrescribe el navegador en toda la sesión
|
||||
if user.preferred_language and user.preferred_language in ['es', 'en']:
|
||||
session['language'] = user.preferred_language
|
||||
else:
|
||||
session.pop('language', None)
|
||||
|
||||
session.pop('login_lang_explicit', None)
|
||||
|
||||
next_page = request.args.get('next')
|
||||
if not next_page or not next_page.startswith('/'):
|
||||
next_page = url_for('main.dashboard')
|
||||
|
||||
user_full_name = f'{user.first_name} {user.last_name}'.strip() or user.name
|
||||
flash(_('¡Bienvenido de nuevo, %(name)s!', name=user_full_name), 'success')
|
||||
return redirect(next_page)
|
||||
else:
|
||||
try:
|
||||
from app.services.audit_service import AuditService
|
||||
AuditService.log(
|
||||
action='LOGIN_FAILED',
|
||||
module='auth',
|
||||
details=f"Intento fallido de login con email: {clean_email}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
flash(_('Correo electrónico o contraseña inválidos.'), 'error')
|
||||
|
||||
return render_template('auth/login.html', form=form, demo_access_enabled=demo_access_enabled)
|
||||
|
||||
@auth_bp.route('/logout')
|
||||
@login_required
|
||||
def logout():
|
||||
"""Handle user logout"""
|
||||
logout_user()
|
||||
# Al cerrar sesión, se limpian las cookies de idioma para que el login detecte el navegador o use español
|
||||
session.pop('language', None)
|
||||
session.pop('login_lang_explicit', None)
|
||||
flash(_('Has cerrado sesión correctamente.'), 'info')
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
@auth_bp.route('/profile', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def profile():
|
||||
"""User profile page with language and theme settings"""
|
||||
if request.method == 'POST':
|
||||
lang = request.form.get('preferred_language')
|
||||
if lang in ['es', 'en']:
|
||||
current_user.preferred_language = lang
|
||||
session['language'] = lang
|
||||
else:
|
||||
# Cadena vacía o None restablece la detección automática del navegador
|
||||
current_user.preferred_language = None
|
||||
session.pop('language', None)
|
||||
|
||||
theme = request.form.get('theme_preference')
|
||||
if theme in ['auto', 'light', 'dark']:
|
||||
current_user.theme_preference = theme
|
||||
|
||||
db.session.commit()
|
||||
flash(_('Preferencias de usuario actualizadas correctamente.'), 'success')
|
||||
return redirect(url_for('auth.profile'))
|
||||
return render_template('auth/profile.html')
|
||||
|
||||
@auth_bp.route('/api/user/theme', methods=['POST'])
|
||||
@login_required
|
||||
def update_theme_api():
|
||||
"""Update user theme preference via fetch/AJAX from navbar toggle"""
|
||||
data = request.get_json(silent=True) or request.form
|
||||
theme = data.get('theme') if data else None
|
||||
if theme in ['auto', 'light', 'dark']:
|
||||
current_user.theme_preference = theme
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'success', 'theme': theme})
|
||||
return jsonify({'status': 'error', 'message': 'Invalid theme'}), 400
|
||||
|
||||
|
||||
|
||||
@auth_bp.route('/change_password', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def change_password():
|
||||
"""Change user password"""
|
||||
if request.method == 'POST':
|
||||
current_password = request.form.get('current_password')
|
||||
new_password = request.form.get('new_password')
|
||||
confirm_password = request.form.get('confirm_password')
|
||||
|
||||
if not current_user.check_password(current_password):
|
||||
flash('Current password is incorrect.', 'error')
|
||||
return redirect(url_for('auth.change_password'))
|
||||
|
||||
if new_password != confirm_password:
|
||||
flash('New passwords do not match.', 'error')
|
||||
return redirect(url_for('auth.change_password'))
|
||||
|
||||
if len(new_password) < 6:
|
||||
flash('Password must be at least 6 characters long.', 'error')
|
||||
return redirect(url_for('auth.change_password'))
|
||||
|
||||
current_user.set_password(new_password)
|
||||
db.session.commit()
|
||||
|
||||
flash('Password changed successfully!', 'success')
|
||||
return redirect(url_for('auth.profile'))
|
||||
|
||||
return render_template('auth/change_password.html')
|
||||
@@ -1,196 +0,0 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.building import Building
|
||||
from app.models.classroom import Classroom
|
||||
from app.forms.building import BuildingForm
|
||||
from app.utils.decorators import permission_required
|
||||
from datetime import datetime
|
||||
|
||||
buildings_bp = Blueprint('buildings', __name__, url_prefix='/buildings')
|
||||
|
||||
@buildings_bp.route('/')
|
||||
@login_required
|
||||
def list_buildings():
|
||||
"""List all buildings with statistics"""
|
||||
search = request.args.get('search', '').strip()
|
||||
status_filter = request.args.get('status', '')
|
||||
|
||||
query = Building.query
|
||||
if search:
|
||||
query = query.filter(
|
||||
db.or_(
|
||||
Building.name.ilike(f'%{search}%'),
|
||||
Building.code.ilike(f'%{search}%'),
|
||||
Building.address.ilike(f'%{search}%')
|
||||
)
|
||||
)
|
||||
if status_filter == 'active':
|
||||
query = query.filter(Building.is_active == True)
|
||||
elif status_filter == 'inactive':
|
||||
query = query.filter(Building.is_active == False)
|
||||
|
||||
buildings = query.order_by(Building.name.asc()).all()
|
||||
|
||||
# Calculate global building stats (excluye aulas virtuales con 9999)
|
||||
total_classrooms = Classroom.query.filter_by(is_active=True).count()
|
||||
physical_classrooms = [c for c in Classroom.query.filter_by(is_active=True).all() if not getattr(c, 'is_virtual', False) and (c.capacity or 0) < 999 and 'VIRTUAL' not in (c.code or '').upper()]
|
||||
total_physical_capacity = sum(c.capacity for c in physical_classrooms)
|
||||
total_capacity = total_physical_capacity
|
||||
|
||||
return render_template(
|
||||
'buildings/list.html',
|
||||
buildings=buildings,
|
||||
total_classrooms=total_classrooms,
|
||||
total_capacity=total_capacity,
|
||||
total_physical_capacity=total_physical_capacity,
|
||||
search=search,
|
||||
status_filter=status_filter,
|
||||
title='Building Management'
|
||||
)
|
||||
|
||||
@buildings_bp.route('/add', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@permission_required('classrooms', 'read_write')
|
||||
def add_building():
|
||||
"""Add new building"""
|
||||
form = BuildingForm()
|
||||
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
# Check unique name
|
||||
existing = Building.query.filter(
|
||||
db.func.lower(Building.name) == form.name.data.lower()
|
||||
).first()
|
||||
if existing:
|
||||
flash('Ya existe un edificio con este nombre.', 'danger')
|
||||
return render_template('buildings/form.html', form=form, title='Add Building')
|
||||
|
||||
building = Building(
|
||||
name=form.name.data.strip(),
|
||||
code=form.code.data.strip().upper() if form.code.data else None,
|
||||
address=form.address.data.strip() if form.address.data else None,
|
||||
floors=form.floors.data,
|
||||
description=form.description.data.strip() if form.description.data else None,
|
||||
is_active=form.is_active.data
|
||||
)
|
||||
db.session.add(building)
|
||||
db.session.commit()
|
||||
flash(f'Edificio "{building.name}" creado con éxito.', 'success')
|
||||
return redirect(url_for('buildings.view_building', id=building.id))
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al crear el edificio: {str(e)}', 'danger')
|
||||
|
||||
return render_template('buildings/form.html', form=form, title='Add Building')
|
||||
|
||||
@buildings_bp.route('/<int:id>')
|
||||
@login_required
|
||||
def view_building(id):
|
||||
"""View building details and its classrooms by floor"""
|
||||
building = Building.query.get_or_404(id)
|
||||
|
||||
# Group active classrooms by floor
|
||||
classrooms = Classroom.query.filter_by(building_id=building.id).order_by(Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
# Fallback to name matching if building_id was not set
|
||||
if not classrooms:
|
||||
classrooms = Classroom.query.filter_by(building=building.name).order_by(Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
|
||||
classrooms_by_floor = {}
|
||||
for c in classrooms:
|
||||
floor_key = c.floor
|
||||
if floor_key not in classrooms_by_floor:
|
||||
classrooms_by_floor[floor_key] = []
|
||||
classrooms_by_floor[floor_key].append(c)
|
||||
|
||||
return render_template(
|
||||
'buildings/view.html',
|
||||
building=building,
|
||||
classrooms=classrooms,
|
||||
classrooms_by_floor=classrooms_by_floor,
|
||||
title=f'Building - {building.name}'
|
||||
)
|
||||
|
||||
@buildings_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@permission_required('classrooms', 'read_write')
|
||||
def edit_building(id):
|
||||
"""Edit building"""
|
||||
building = Building.query.get_or_404(id)
|
||||
form = BuildingForm(obj=building)
|
||||
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
# Check unique name excluding current
|
||||
existing = Building.query.filter(
|
||||
db.func.lower(Building.name) == form.name.data.lower(),
|
||||
Building.id != id
|
||||
).first()
|
||||
if existing:
|
||||
flash('Ya existe otro edificio con este nombre.', 'danger')
|
||||
return render_template('buildings/form.html', form=form, building=building, title='Edit Building')
|
||||
|
||||
old_name = building.name
|
||||
new_name = form.name.data.strip()
|
||||
|
||||
building.name = new_name
|
||||
building.code = form.code.data.strip().upper() if form.code.data else None
|
||||
building.address = form.address.data.strip() if form.address.data else None
|
||||
building.floors = form.floors.data
|
||||
building.description = form.description.data.strip() if form.description.data else None
|
||||
building.is_active = form.is_active.data
|
||||
building.updated_at = datetime.utcnow()
|
||||
|
||||
# If name changed, update string building on classrooms
|
||||
if old_name != new_name:
|
||||
Classroom.query.filter_by(building_id=building.id).update({'building': new_name})
|
||||
|
||||
db.session.commit()
|
||||
flash(f'Edificio "{building.name}" actualizado con éxito.', 'success')
|
||||
return redirect(url_for('buildings.view_building', id=building.id))
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al actualizar el edificio: {str(e)}', 'danger')
|
||||
|
||||
return render_template('buildings/form.html', form=form, building=building, title='Edit Building')
|
||||
|
||||
@buildings_bp.route('/<int:id>/toggle', methods=['POST'])
|
||||
@login_required
|
||||
@permission_required('classrooms', 'read_write')
|
||||
def toggle_building(id):
|
||||
"""Toggle building active status"""
|
||||
building = Building.query.get_or_404(id)
|
||||
try:
|
||||
building.is_active = not building.is_active
|
||||
building.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
status_text = 'activado' if building.is_active else 'desactivado'
|
||||
flash(f'Edificio "{building.name}" {status_text} con éxito.', 'success')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al cambiar estado del edificio: {str(e)}', 'danger')
|
||||
return redirect(url_for('buildings.list_buildings'))
|
||||
|
||||
@buildings_bp.route('/<int:id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@permission_required('classrooms', 'read_write')
|
||||
def delete_building(id):
|
||||
"""Delete building if it has no classrooms assigned"""
|
||||
building = Building.query.get_or_404(id)
|
||||
has_classrooms = Classroom.query.filter(
|
||||
db.or_(Classroom.building_id == building.id, Classroom.building == building.name)
|
||||
).count()
|
||||
|
||||
if has_classrooms > 0:
|
||||
flash(f'No se puede eliminar el edificio "{building.name}" porque tiene {has_classrooms} aulas asociadas. Primero reasigna o elimina las aulas.', 'danger')
|
||||
return redirect(url_for('buildings.view_building', id=building.id))
|
||||
|
||||
try:
|
||||
db.session.delete(building)
|
||||
db.session.commit()
|
||||
flash(f'Edificio "{building.name}" eliminado correctamente.', 'success')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al eliminar edificio: {str(e)}', 'danger')
|
||||
|
||||
return redirect(url_for('buildings.list_buildings'))
|
||||
@@ -1,513 +0,0 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
|
||||
from flask_login import login_required, current_user
|
||||
from datetime import datetime, date
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.user import User
|
||||
from app.forms.classroom import ClassroomForm
|
||||
from app import db
|
||||
from sqlalchemy import text
|
||||
|
||||
classrooms_bp = Blueprint('classrooms', __name__)
|
||||
|
||||
@classrooms_bp.route('/add', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def add_classroom():
|
||||
"""Add a new classroom with dynamic building creation and floor suggestion"""
|
||||
from app.models.building import Building
|
||||
import re
|
||||
from sqlalchemy import func
|
||||
|
||||
form = ClassroomForm()
|
||||
buildings = Building.query.filter_by(is_active=True).order_by(Building.name.asc()).all()
|
||||
form.building_id.choices = [(str(b.id), b.name) for b in buildings] + [('__new__', '+ Crear nuevo edificio')]
|
||||
|
||||
# Map of existing floors per building for datalist
|
||||
building_floors = {str(b.id): list(dict.fromkeys(c.floor for c in b.classrooms if c.floor)) for b in buildings}
|
||||
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
building = None
|
||||
if form.building_id.data == '__new__':
|
||||
new_building_name = form.new_building_name.data.strip() if form.new_building_name.data else ''
|
||||
if not new_building_name:
|
||||
flash('Debe ingresar el nombre del nuevo edificio.', 'error')
|
||||
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')
|
||||
|
||||
building = Building.query.filter(func.lower(Building.name) == func.lower(new_building_name)).first()
|
||||
if not building:
|
||||
code_slug = re.sub(r'[^a-zA-Z0-9]+', '_', new_building_name.upper()).strip('_')
|
||||
building = Building(name=new_building_name, code=code_slug, is_active=True)
|
||||
db.session.add(building)
|
||||
db.session.commit()
|
||||
else:
|
||||
building = Building.query.get_or_404(int(form.building_id.data))
|
||||
|
||||
room_code = form.room_number.data.strip()
|
||||
floor_val = str(form.floor.data).strip()
|
||||
|
||||
# Prevent duplicate room in same building & floor
|
||||
existing_classroom = Classroom.query.filter_by(
|
||||
building_id=building.id,
|
||||
code=room_code,
|
||||
floor=floor_val
|
||||
).first()
|
||||
|
||||
if existing_classroom:
|
||||
flash(f'Ya existe un aula con el nombre "{room_code}" en el piso {floor_val} de {building.name}.', 'error')
|
||||
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')
|
||||
|
||||
cap_raw = str(form.capacity.data or '').strip()
|
||||
if cap_raw in ['∞', 'inf', 'INF', 'Infinity', 'infinity', '0', 'ilimitada', 'Ilimitada', 'sin limite', 'Sin límite']:
|
||||
cap_val = 9999
|
||||
else:
|
||||
cap_val = int(cap_raw)
|
||||
|
||||
from app.services.classroom_service import ClassroomService
|
||||
from app.schemas.classroom_dto import ClassroomCreateDTO
|
||||
from app.services.audit_service import AuditService
|
||||
|
||||
dto = ClassroomCreateDTO(
|
||||
building_id=building.id,
|
||||
code=room_code,
|
||||
floor=floor_val,
|
||||
capacity=cap_val,
|
||||
description=form.description.data,
|
||||
is_active=form.is_active.data
|
||||
)
|
||||
classroom_service = ClassroomService()
|
||||
classroom = classroom_service.create_classroom(dto)
|
||||
|
||||
# Registrar en bitácora inmutable de auditoría
|
||||
AuditService.log('CREATE', 'classrooms', entity_id=classroom.id, details={'code': classroom.code, 'building': building.name})
|
||||
|
||||
flash(f'Aula {classroom.location_display} creada exitosamente.', 'success')
|
||||
return redirect(url_for('classrooms.list_classrooms'))
|
||||
|
||||
except ValueError as ve:
|
||||
flash(str(ve), 'error')
|
||||
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al crear el aula: {str(e)}', 'error')
|
||||
|
||||
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')
|
||||
|
||||
|
||||
@classrooms_bp.route('/', endpoint='index')
|
||||
@classrooms_bp.route('/list')
|
||||
@login_required
|
||||
def list_classrooms():
|
||||
"""List all classrooms with separation between Physical spaces and Virtual on-demand rooms"""
|
||||
try:
|
||||
from app.models.building import Building
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.subject import Commission, Subject
|
||||
import calendar
|
||||
from datetime import date, timedelta
|
||||
|
||||
page = request.args.get('page', 1, type=int)
|
||||
active_only = request.args.get('active_only', 'true').lower() == 'true'
|
||||
search = request.args.get('search', '', type=str).strip()
|
||||
building_filter = request.args.get('building_id', '', type=str).strip()
|
||||
floor_filter = request.args.get('floor', '', type=str).strip()
|
||||
view_mode = request.args.get('view_mode', '').strip().lower()
|
||||
|
||||
# Identificar edificio virtual y aula virtual base
|
||||
virtual_building = Building.query.filter(
|
||||
db.or_(Building.code == 'VIRTUAL', Building.name.ilike('%Virtual%'))
|
||||
).first()
|
||||
virtual_bldg_id = virtual_building.id if virtual_building else None
|
||||
|
||||
# Si el usuario seleccionó "Campus Virtual" en el filtro de edificios, conmutar a pestaña virtual
|
||||
if building_filter and str(building_filter) == str(virtual_bldg_id):
|
||||
view_mode = 'virtual'
|
||||
elif not view_mode:
|
||||
view_mode = 'physical'
|
||||
|
||||
# Fechas operativas (Día, Semana, Mes)
|
||||
today = datetime.utcnow().date()
|
||||
today_start = datetime.combine(today, datetime.min.time())
|
||||
today_end = datetime.combine(today, datetime.max.time())
|
||||
|
||||
week_start = datetime.combine(today - timedelta(days=today.weekday()), datetime.min.time())
|
||||
week_end = datetime.combine(week_start.date() + timedelta(days=6), datetime.max.time())
|
||||
|
||||
_, last_day = calendar.monthrange(today.year, today.month)
|
||||
month_start = datetime(today.year, today.month, 1, 0, 0, 0)
|
||||
month_end = datetime(today.year, today.month, last_day, 23, 59, 59)
|
||||
|
||||
date_filters = {
|
||||
'today': today.strftime('%Y-%m-%d'),
|
||||
'week_start': week_start.strftime('%Y-%m-%d'),
|
||||
'week_end': week_end.strftime('%Y-%m-%d'),
|
||||
'month_start': month_start.strftime('%Y-%m-%d'),
|
||||
'month_end': month_end.strftime('%Y-%m-%d')
|
||||
}
|
||||
|
||||
# --- AULAS FÍSICAS (Presenciales) ---
|
||||
physical_query = Classroom.query
|
||||
if virtual_bldg_id:
|
||||
physical_query = physical_query.filter(Classroom.building_id != virtual_bldg_id)
|
||||
else:
|
||||
physical_query = physical_query.filter(~Classroom.code.ilike('%VIRTUAL%'))
|
||||
|
||||
if active_only:
|
||||
physical_query = physical_query.filter_by(is_active=True)
|
||||
|
||||
physical_count = physical_query.count()
|
||||
|
||||
if building_filter and building_filter.isdigit() and str(building_filter) != str(virtual_bldg_id):
|
||||
physical_query = physical_query.filter(Classroom.building_id == int(building_filter))
|
||||
|
||||
if floor_filter:
|
||||
flr = str(floor_filter).strip()
|
||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||
physical_query = physical_query.filter(db.or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||
else:
|
||||
physical_query = physical_query.filter(Classroom.floor == flr)
|
||||
|
||||
if search and view_mode == 'physical':
|
||||
physical_query = physical_query.filter(
|
||||
db.or_(
|
||||
Classroom.building.ilike(f'%{search}%'),
|
||||
Classroom.code.ilike(f'%{search}%'),
|
||||
Classroom.description.ilike(f'%{search}%')
|
||||
)
|
||||
)
|
||||
|
||||
classrooms = physical_query.order_by(Classroom.building_id.asc(), Classroom.floor.asc(), Classroom.code.asc()).paginate(
|
||||
page=page, per_page=20, error_out=False
|
||||
)
|
||||
|
||||
# Edificios y Pisos estrictamente físicos para el filtro
|
||||
buildings = Building.query.filter_by(is_active=True)
|
||||
if virtual_bldg_id:
|
||||
buildings = buildings.filter(Building.id != virtual_bldg_id)
|
||||
buildings = buildings.order_by(Building.name.asc()).all()
|
||||
|
||||
floors = [f[0] for f in db.session.query(Classroom.floor).filter(
|
||||
Classroom.is_active == True,
|
||||
Classroom.building_id != virtual_bldg_id if virtual_bldg_id else True,
|
||||
Classroom.floor.isnot(None)
|
||||
).distinct().order_by(Classroom.floor.asc()).all()]
|
||||
|
||||
# Métricas de ocupación física
|
||||
visible_ids = [c.id for c in classrooms.items]
|
||||
month_reservations = Reservation.query.filter(
|
||||
Reservation.classroom_id.in_(visible_ids),
|
||||
Reservation.start_time >= month_start,
|
||||
Reservation.start_time <= month_end,
|
||||
Reservation.status.in_([ReservationStatus.CONFIRMED.value, ReservationStatus.PENDING.value])
|
||||
).all() if visible_ids else []
|
||||
|
||||
DAILY_OP_MINS = 15 * 60
|
||||
WEEKLY_OP_MINS = 6 * 15 * 60
|
||||
MONTHLY_OP_MINS = 24 * 15 * 60
|
||||
|
||||
occupancy_metrics = {}
|
||||
for c in classrooms.items:
|
||||
c_res = [r for r in month_reservations if r.classroom_id == c.id]
|
||||
day_res = [r for r in c_res if today_start <= r.start_time <= today_end]
|
||||
day_mins = sum((min(r.end_time, today_end) - max(r.start_time, today_start)).total_seconds() / 60 for r in day_res)
|
||||
day_pct = min(100, int(round((day_mins / DAILY_OP_MINS) * 100)))
|
||||
|
||||
week_res = [r for r in c_res if week_start <= r.start_time <= week_end]
|
||||
week_mins = sum((min(r.end_time, week_end) - max(r.start_time, week_start)).total_seconds() / 60 for r in week_res)
|
||||
week_pct = min(100, int(round((week_mins / WEEKLY_OP_MINS) * 100)))
|
||||
|
||||
month_mins = sum((min(r.end_time, month_end) - max(r.start_time, month_start)).total_seconds() / 60 for r in c_res)
|
||||
month_pct = min(100, int(round((month_mins / MONTHLY_OP_MINS) * 100)))
|
||||
|
||||
occupancy_metrics[c.id] = {
|
||||
'day_pct': day_pct,
|
||||
'day_count': len(day_res),
|
||||
'week_pct': week_pct,
|
||||
'week_count': len(week_res),
|
||||
'month_pct': month_pct,
|
||||
'month_count': len(c_res)
|
||||
}
|
||||
|
||||
# --- AULAS VIRTUALES (Campus Virtual a Demanda - Infinitas) ---
|
||||
vc = Classroom.query.filter(
|
||||
Classroom.building_id == virtual_bldg_id if virtual_bldg_id else Classroom.code.ilike('%VIRTUAL%')
|
||||
).first()
|
||||
vc_id = vc.id if vc else 1
|
||||
|
||||
all_vres = Reservation.query.filter(Reservation.classroom_id == vc_id).all() if vc_id else []
|
||||
|
||||
# Agrupar las salas virtuales por comisión
|
||||
comm_dict = {}
|
||||
for r in all_vres:
|
||||
c = r.commission
|
||||
cid = c.id if c else 0
|
||||
if cid not in comm_dict:
|
||||
vlink = (c.virtual_link if c and c.virtual_link else None) or r.effective_virtual_link
|
||||
comm_dict[cid] = {
|
||||
'commission_id': cid,
|
||||
'commission_code': c.code if c else 'General',
|
||||
'subject_name': c.subject.name if (c and c.subject) else (r.purpose or 'Clase Virtual'),
|
||||
'subject_code': c.subject.code if (c and c.subject) else '',
|
||||
'career_name': c.subject.career.name if (c and c.subject and hasattr(c.subject, 'career') and c.subject.career) else '',
|
||||
'max_students': c.max_students if c else (r.expected_attendees or 0),
|
||||
'virtual_link': vlink,
|
||||
'reservations': []
|
||||
}
|
||||
comm_dict[cid]['reservations'].append(r)
|
||||
if not comm_dict[cid]['virtual_link'] and r.effective_virtual_link:
|
||||
comm_dict[cid]['virtual_link'] = r.effective_virtual_link
|
||||
|
||||
virtual_rooms = []
|
||||
for cid, data in comm_dict.items():
|
||||
res_list = data['reservations']
|
||||
day_cnt = sum(1 for r in res_list if today_start <= r.start_time <= today_end)
|
||||
week_cnt = sum(1 for r in res_list if week_start <= r.start_time <= week_end)
|
||||
month_cnt = sum(1 for r in res_list if month_start <= r.start_time <= month_end)
|
||||
shift = res_list[0].shift if res_list else 'A Demanda'
|
||||
|
||||
if search and view_mode == 'virtual':
|
||||
s_low = search.lower()
|
||||
matches = (
|
||||
s_low in data['subject_name'].lower() or
|
||||
s_low in data['commission_code'].lower() or
|
||||
s_low in data['subject_code'].lower() or
|
||||
s_low in data['career_name'].lower()
|
||||
)
|
||||
if not matches:
|
||||
continue
|
||||
|
||||
virtual_rooms.append({
|
||||
'commission_id': data['commission_id'],
|
||||
'commission_code': data['commission_code'],
|
||||
'subject_name': data['subject_name'],
|
||||
'subject_code': data['subject_code'],
|
||||
'career_name': data['career_name'],
|
||||
'max_students': data['max_students'],
|
||||
'virtual_link': data['virtual_link'],
|
||||
'shift': shift,
|
||||
'day_count': day_cnt,
|
||||
'week_count': week_cnt,
|
||||
'month_count': month_cnt,
|
||||
'total_count': len(res_list),
|
||||
'reservations': sorted(res_list, key=lambda x: x.start_time)
|
||||
})
|
||||
|
||||
virtual_rooms.sort(key=lambda x: (x['subject_name'], x['commission_code']))
|
||||
|
||||
global_virtual_metrics = {
|
||||
'today_count': sum(1 for r in all_vres if today_start <= r.start_time <= today_end),
|
||||
'week_count': sum(1 for r in all_vres if week_start <= r.start_time <= week_end),
|
||||
'month_count': sum(1 for r in all_vres if month_start <= r.start_time <= month_end),
|
||||
'total_count': len(all_vres),
|
||||
'commissions_count': len(comm_dict)
|
||||
}
|
||||
|
||||
return render_template('classrooms/list.html',
|
||||
classrooms=classrooms,
|
||||
buildings=buildings,
|
||||
floors=floors,
|
||||
building_filter=building_filter,
|
||||
floor_filter=floor_filter,
|
||||
active_only=active_only,
|
||||
search=search,
|
||||
view_mode=view_mode,
|
||||
physical_count=physical_count,
|
||||
virtual_count=len(comm_dict),
|
||||
virtual_rooms=virtual_rooms,
|
||||
virtual_classroom_id=vc_id,
|
||||
global_virtual_metrics=global_virtual_metrics,
|
||||
occupancy_metrics=occupancy_metrics,
|
||||
date_filters=date_filters,
|
||||
title='Classrooms')
|
||||
|
||||
except Exception as e:
|
||||
flash(f'Error loading classrooms: {str(e)}', 'error')
|
||||
return render_template('classrooms/list.html', classrooms=None, title='Classrooms')
|
||||
|
||||
|
||||
@classrooms_bp.route('/virtual-room/<int:commission_id>/update-link', methods=['POST'])
|
||||
@login_required
|
||||
def update_virtual_link(commission_id):
|
||||
"""Actualizar enlace de videollamada para una comisión virtual"""
|
||||
from app.models.subject import Commission
|
||||
from flask_babel import gettext as _
|
||||
comm = Commission.query.get_or_404(commission_id)
|
||||
new_link = request.form.get('virtual_link', '').strip() or None
|
||||
comm.virtual_link = new_link
|
||||
db.session.commit()
|
||||
flash(_('Enlace de videollamada para %(code)s actualizado correctamente.', code=comm.get_full_code()), 'success')
|
||||
return redirect(request.referrer or url_for('classrooms.list_classrooms', view_mode='virtual'))
|
||||
|
||||
|
||||
@classrooms_bp.route('/<int:id>')
|
||||
@login_required
|
||||
def view_classroom(id):
|
||||
"""View classroom details"""
|
||||
try:
|
||||
classroom = Classroom.query.get_or_404(id)
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
|
||||
upcoming_reservations = Reservation.query.filter(
|
||||
Reservation.classroom_id == id,
|
||||
Reservation.start_time > datetime.utcnow(),
|
||||
Reservation.status == ReservationStatus.CONFIRMED.value
|
||||
).order_by(Reservation.start_time).limit(10).all()
|
||||
|
||||
return render_template('classrooms/view.html',
|
||||
classroom=classroom,
|
||||
upcoming_reservations=upcoming_reservations,
|
||||
title=f'Classroom {classroom.code_display}')
|
||||
|
||||
except Exception as e:
|
||||
flash(f'Error loading classroom: {str(e)}', 'error')
|
||||
return redirect(url_for('classrooms.list_classrooms'))
|
||||
|
||||
|
||||
@classrooms_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def edit_classroom(id):
|
||||
"""Edit classroom with decoupled building and floor"""
|
||||
from app.models.building import Building
|
||||
import re
|
||||
from sqlalchemy import func
|
||||
|
||||
classroom = Classroom.query.get_or_404(id)
|
||||
form = ClassroomForm(obj=classroom)
|
||||
|
||||
buildings = Building.query.filter_by(is_active=True).order_by(Building.name.asc()).all()
|
||||
form.building_id.choices = [(str(b.id), b.name) for b in buildings] + [('__new__', '+ Crear nuevo edificio')]
|
||||
building_floors = {str(b.id): list(dict.fromkeys(c.floor for c in b.classrooms if c.floor)) for b in buildings}
|
||||
|
||||
if request.method == 'GET':
|
||||
form.building_id.data = str(classroom.building_id or '')
|
||||
form.room_number.data = classroom.code
|
||||
form.floor.data = classroom.floor
|
||||
if classroom.capacity == 0 or classroom.is_virtual:
|
||||
form.capacity.data = '∞'
|
||||
else:
|
||||
form.capacity.data = str(classroom.capacity)
|
||||
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
building = None
|
||||
if form.building_id.data == '__new__':
|
||||
new_building_name = form.new_building_name.data.strip() if form.new_building_name.data else ''
|
||||
if not new_building_name:
|
||||
flash('Debe ingresar el nombre del nuevo edificio.', 'error')
|
||||
return render_template('classrooms/edit.html', form=form, classroom=classroom, building_floors=building_floors, title='Edit Classroom')
|
||||
|
||||
building = Building.query.filter(func.lower(Building.name) == func.lower(new_building_name)).first()
|
||||
if not building:
|
||||
code_slug = re.sub(r'[^a-zA-Z0-9]+', '_', new_building_name.upper()).strip('_')
|
||||
building = Building(name=new_building_name, code=code_slug, is_active=True)
|
||||
db.session.add(building)
|
||||
db.session.commit()
|
||||
else:
|
||||
building = Building.query.get_or_404(int(form.building_id.data))
|
||||
|
||||
room_code = form.room_number.data.strip()
|
||||
floor_val = str(form.floor.data).strip()
|
||||
|
||||
# Check duplicate excluding current
|
||||
existing_classroom = Classroom.query.filter(
|
||||
Classroom.building_id == building.id,
|
||||
Classroom.code == room_code,
|
||||
Classroom.floor == floor_val,
|
||||
Classroom.id != id
|
||||
).first()
|
||||
|
||||
if existing_classroom:
|
||||
flash(f'Ya existe otra aula con el nombre "{room_code}" en el piso {floor_val} de {building.name}.', 'error')
|
||||
return render_template('classrooms/edit.html', form=form, classroom=classroom, building_floors=building_floors, title='Edit Classroom')
|
||||
|
||||
cap_raw = str(form.capacity.data or '').strip()
|
||||
if cap_raw in ['∞', 'inf', 'INF', 'Infinity', 'infinity', '0', 'ilimitada', 'Ilimitada', 'sin limite', 'Sin límite']:
|
||||
cap_val = 0
|
||||
else:
|
||||
cap_val = int(cap_raw)
|
||||
|
||||
classroom.building_id = building.id
|
||||
classroom.building = building.name
|
||||
classroom.code = room_code
|
||||
classroom.floor = floor_val
|
||||
classroom.capacity = cap_val
|
||||
classroom.description = form.description.data
|
||||
classroom.is_active = form.is_active.data
|
||||
classroom.updated_at = datetime.utcnow()
|
||||
|
||||
db.session.commit()
|
||||
|
||||
flash(f'Aula {classroom.location_display} actualizada correctamente.', 'success')
|
||||
return redirect(url_for('classrooms.view_classroom', id=classroom.id))
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error updating classroom: {str(e)}', 'error')
|
||||
|
||||
return render_template('classrooms/edit.html', form=form, classroom=classroom, building_floors=building_floors, title='Edit Classroom')
|
||||
|
||||
@classrooms_bp.route('/<int:id>/toggle', methods=['POST'])
|
||||
@login_required
|
||||
def toggle_classroom(id):
|
||||
"""Toggle classroom active status"""
|
||||
classroom = Classroom.query.get_or_404(id)
|
||||
|
||||
try:
|
||||
classroom.is_active = not classroom.is_active
|
||||
classroom.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
status = 'activated' if classroom.is_active else 'deactivated'
|
||||
flash(f'Classroom {classroom.code_display} has been {status} successfully!', 'success')
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error updating classroom status: {str(e)}', 'error')
|
||||
|
||||
return redirect(request.referrer or url_for('classrooms.list_classrooms'))
|
||||
|
||||
# API endpoints for AJAX requests
|
||||
@classrooms_bp.route('/api/available')
|
||||
@login_required
|
||||
def get_available_classrooms():
|
||||
"""Get available classrooms for a specific time slot"""
|
||||
start_time = request.args.get('start_time')
|
||||
end_time = request.args.get('end_time')
|
||||
|
||||
if not start_time or not end_time:
|
||||
return jsonify({'error': 'Start time and end time are required'}), 400
|
||||
|
||||
try:
|
||||
from datetime import datetime
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
|
||||
start_dt = datetime.fromisoformat(start_time)
|
||||
end_dt = datetime.fromisoformat(end_time)
|
||||
|
||||
# Find all classrooms
|
||||
all_classrooms = Classroom.query.filter_by(is_active=True).all()
|
||||
available_classrooms = []
|
||||
|
||||
for classroom in all_classrooms:
|
||||
# Check if classroom has conflicting reservations
|
||||
conflicts = Reservation.query.filter(
|
||||
Reservation.classroom_id == classroom.id,
|
||||
Reservation.status == ReservationStatus.CONFIRMED.value,
|
||||
Reservation.start_time < end_dt,
|
||||
Reservation.end_time > start_dt
|
||||
).all()
|
||||
|
||||
if not conflicts:
|
||||
available_classrooms.append({
|
||||
'id': classroom.id,
|
||||
'code': classroom.code,
|
||||
'building': classroom.building,
|
||||
'room_number': classroom.code,
|
||||
'floor': classroom.floor,
|
||||
'capacity': classroom.capacity,
|
||||
'code_display': classroom.code_display
|
||||
})
|
||||
|
||||
return jsonify({'classrooms': available_classrooms})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
@@ -1,255 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify, current_app, render_template, g
|
||||
from datetime import datetime, timedelta
|
||||
from app.models.genetic_algorithm import ReservationOptimizer
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app import db
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
|
||||
genetic_bp = Blueprint('genetic_algorithm', __name__, url_prefix='/api/genetic')
|
||||
|
||||
|
||||
@genetic_bp.route('/optimize', methods=['POST'])
|
||||
@jwt_required
|
||||
def optimize_reservations():
|
||||
"""Optimize reservations using genetic algorithm"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'commission_ids' not in data:
|
||||
return jsonify({'error': 'Missing commission_ids in request'}), 400
|
||||
|
||||
commission_ids = data['commission_ids']
|
||||
|
||||
if not isinstance(commission_ids, list) or not commission_ids:
|
||||
return jsonify({'error': 'commission_ids must be a non-empty list'}), 400
|
||||
|
||||
# Optional parameters
|
||||
start_date = None
|
||||
end_date = None
|
||||
|
||||
if 'start_date' in data:
|
||||
try:
|
||||
start_date = datetime.fromisoformat(data['start_date'])
|
||||
except ValueError:
|
||||
return jsonify({'error': 'Invalid start_date format. Use ISO format.'}), 400
|
||||
|
||||
if 'end_date' in data:
|
||||
try:
|
||||
end_date = datetime.fromisoformat(data['end_date'])
|
||||
except ValueError:
|
||||
return jsonify({'error': 'Invalid end_date format. Use ISO format.'}), 400
|
||||
|
||||
# Check if user has permission (admin, teacher or RBAC optimizer write)
|
||||
if not (g.jwt_user.is_admin() or g.jwt_user.has_permission('optimizer', 'read_write') or g.jwt_user.role in ['ADMIN', 'teacher']):
|
||||
return jsonify({'error': 'Insufficient permissions to optimize reservations'}), 403
|
||||
|
||||
# Initialize optimizer and run optimization
|
||||
optimizer = ReservationOptimizer()
|
||||
result = optimizer.optimize_schedule(
|
||||
commission_ids=commission_ids,
|
||||
admin_user_id=g.jwt_user.id,
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': {
|
||||
'fitness_score': result['fitness_score'],
|
||||
'total_requests': result['total_requests'],
|
||||
'assigned_reservations': result['assigned_reservations'],
|
||||
'reservations': result['reservations'],
|
||||
'conflicts': result['conflicts']
|
||||
}
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error in genetic algorithm optimization: {str(e)}")
|
||||
return jsonify({'error': f'Optimization failed: {str(e)}'}), 500
|
||||
|
||||
|
||||
@genetic_bp.route('/apply-optimization', methods=['POST'])
|
||||
@jwt_required
|
||||
def apply_optimization():
|
||||
"""Apply optimized reservations to the database"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'reservations' not in data:
|
||||
return jsonify({'error': 'Missing reservations data'}), 400
|
||||
|
||||
reservations_data = data['reservations']
|
||||
|
||||
if not isinstance(reservations_data, list):
|
||||
return jsonify({'error': 'reservations must be a list'}), 400
|
||||
|
||||
# Check if user has permission
|
||||
if not (g.jwt_user.is_admin() or g.jwt_user.has_permission('optimizer', 'read_write') or g.jwt_user.role in ['ADMIN', 'teacher']):
|
||||
return jsonify({'error': 'Insufficient permissions to apply reservations'}), 403
|
||||
|
||||
# Initialize optimizer and apply reservations
|
||||
optimizer = ReservationOptimizer()
|
||||
applied_reservations = optimizer.apply_optimized_reservations(reservations_data)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': {
|
||||
'applied_count': len(applied_reservations),
|
||||
'reservations': [res.to_dict() for res in applied_reservations]
|
||||
}
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error applying optimized reservations: {str(e)}")
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'Failed to apply reservations: {str(e)}'}), 500
|
||||
|
||||
|
||||
@genetic_bp.route('/preview-optimization', methods=['POST'])
|
||||
@jwt_required
|
||||
def preview_optimization():
|
||||
"""Preview optimization without applying to database"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'commission_ids' not in data:
|
||||
return jsonify({'error': 'Missing commission_ids in request'}), 400
|
||||
|
||||
commission_ids = data['commission_ids']
|
||||
|
||||
# Optional parameters
|
||||
dry_run = data.get('dry_run', True) # Default to dry run
|
||||
|
||||
if not isinstance(commission_ids, list) or not commission_ids:
|
||||
return jsonify({'error': 'commission_ids must be a non-empty list'}), 400
|
||||
|
||||
# Check if user has permission
|
||||
if g.jwt_user.role not in ['ADMIN', 'teacher']:
|
||||
return jsonify({'error': 'Insufficient permissions to preview optimization'}), 403
|
||||
|
||||
# Initialize optimizer and run optimization
|
||||
optimizer = ReservationOptimizer()
|
||||
result = optimizer.optimize_schedule(
|
||||
commission_ids=commission_ids,
|
||||
admin_user_id=g.jwt_user.id
|
||||
)
|
||||
|
||||
# Add additional preview information
|
||||
preview_data = {
|
||||
'optimization_result': result,
|
||||
'commission_details': [],
|
||||
'classroom_utilization': {},
|
||||
'time_distribution': {}
|
||||
}
|
||||
|
||||
# Get commission details
|
||||
from app.models.subject import Commission, Subject
|
||||
commissions = Commission.query.filter(Commission.id.in_(commission_ids)).all()
|
||||
|
||||
for commission in commissions:
|
||||
preview_data['commission_details'].append({
|
||||
'id': commission.id,
|
||||
'code': commission.get_full_code(),
|
||||
'name': commission.subject.name if commission.subject else 'Unknown',
|
||||
'max_students': commission.max_students,
|
||||
'current_students': commission.current_students
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': preview_data
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error in optimization preview: {str(e)}")
|
||||
return jsonify({'error': f'Preview failed: {str(e)}'}), 500
|
||||
|
||||
|
||||
@genetic_bp.route('/commissions', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_commissions():
|
||||
"""Get available commissions for optimization"""
|
||||
try:
|
||||
# Check if user has permission
|
||||
if g.jwt_user.role not in ['ADMIN', 'teacher']:
|
||||
return jsonify({'error': 'Insufficient permissions'}), 403
|
||||
|
||||
from app.models.subject import Commission, Subject
|
||||
|
||||
# Get active commissions
|
||||
commissions = Commission.query.filter_by(active=True).all()
|
||||
|
||||
commissions_data = []
|
||||
for commission in commissions:
|
||||
commission_dict = commission.to_dict()
|
||||
commission_dict['get_full_code'] = commission.get_full_code()
|
||||
commissions_data.append(commission_dict)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'commissions': commissions_data
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error getting commissions: {str(e)}")
|
||||
return jsonify({'error': f'Failed to load commissions: {str(e)}'}), 500
|
||||
|
||||
|
||||
@genetic_bp.route('/algorithm-status', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_algorithm_status():
|
||||
"""Get genetic algorithm configuration status"""
|
||||
try:
|
||||
# Check if user has permission
|
||||
if g.jwt_user.role not in ['ADMIN']:
|
||||
return jsonify({'error': 'Insufficient permissions'}), 403
|
||||
|
||||
# Get system status
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Commission
|
||||
|
||||
total_classrooms = Classroom.query.filter_by(is_active=True).count()
|
||||
total_commissions = Commission.query.filter_by(active=True).count()
|
||||
total_reservations = Reservation.query.filter_by(status=ReservationStatus.CONFIRMED.value).count()
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': {
|
||||
'algorithm_config': {
|
||||
'population_size': 50,
|
||||
'generations': 100,
|
||||
'mutation_rate': 0.1,
|
||||
'crossover_rate': 0.8
|
||||
},
|
||||
'system_status': {
|
||||
'available_classrooms': total_classrooms,
|
||||
'active_commissions': total_commissions,
|
||||
'confirmed_reservations': total_reservations
|
||||
},
|
||||
'capabilities': [
|
||||
'Automatic classroom assignment',
|
||||
'Capacity optimization',
|
||||
'Time conflict resolution',
|
||||
'Resource matching',
|
||||
'Batch reservation processing'
|
||||
]
|
||||
}
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error getting algorithm status: {str(e)}")
|
||||
return jsonify({'error': f'Status check failed: {str(e)}'}), 500
|
||||
|
||||
|
||||
# Web interface route (without API prefix)
|
||||
genetic_web_bp = Blueprint('genetic_algorithm_web', __name__)
|
||||
|
||||
|
||||
@genetic_web_bp.route('/genetic-optimizer')
|
||||
@jwt_required
|
||||
def genetic_optimizer():
|
||||
"""Render the genetic algorithm optimizer interface"""
|
||||
if not (g.jwt_user.has_permission('optimizer', 'read') or (g.jwt_user.role and g.jwt_user.role.upper() == 'ADMIN')):
|
||||
return render_template('auth/403.html'), 403
|
||||
|
||||
return render_template('genetic_optimizer.html')
|
||||
@@ -1,333 +0,0 @@
|
||||
from flask import Blueprint, render_template, jsonify, redirect, url_for, session, request, flash
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject
|
||||
from app.models.subject import Commission
|
||||
from datetime import datetime, timedelta
|
||||
from sqlalchemy import func
|
||||
from flask_babel import gettext as _
|
||||
|
||||
main_bp = Blueprint('main', __name__)
|
||||
|
||||
@main_bp.route('/')
|
||||
@login_required
|
||||
def dashboard():
|
||||
"""Role-personalized institutional dashboard page"""
|
||||
from app.models.user import User
|
||||
from app.models.milestone import AcademicMilestone
|
||||
from app.models.audit_log import AuditLog
|
||||
|
||||
actual_role = current_user.get_institutional_role()
|
||||
view_as = request.args.get('view_as', '').lower().strip()
|
||||
|
||||
# Allow admins and management roles to preview dashboard perspectives
|
||||
if view_as in ['admin', 'bedelia', 'docente', 'alumno'] and (current_user.is_admin() or current_user.can_manage()):
|
||||
role = view_as
|
||||
else:
|
||||
role = actual_role
|
||||
|
||||
today = datetime.utcnow().date()
|
||||
|
||||
# Common core statistics
|
||||
try:
|
||||
total_classrooms = Classroom.query.filter_by(is_active=True).count()
|
||||
except Exception:
|
||||
total_classrooms = 0
|
||||
|
||||
try:
|
||||
total_subjects = Subject.query.filter_by(is_active=True).count()
|
||||
except Exception:
|
||||
total_subjects = 0
|
||||
|
||||
try:
|
||||
today_reservations = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today
|
||||
).count()
|
||||
except Exception:
|
||||
today_reservations = 0
|
||||
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
week_end = week_start + timedelta(days=6)
|
||||
try:
|
||||
week_reservations = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) >= week_start,
|
||||
func.date(Reservation.start_time) <= week_end
|
||||
).count()
|
||||
except Exception:
|
||||
week_reservations = 0
|
||||
|
||||
stats = {
|
||||
'total_classrooms': total_classrooms,
|
||||
'total_subjects': total_subjects,
|
||||
'today_reservations': today_reservations,
|
||||
'week_reservations': week_reservations
|
||||
}
|
||||
|
||||
role_data = {}
|
||||
|
||||
if role == 'admin':
|
||||
# 1. Admin Institutional Cockpit
|
||||
try:
|
||||
total_users = User.query.filter_by(is_active=True).count()
|
||||
except Exception:
|
||||
total_users = 0
|
||||
|
||||
try:
|
||||
pending_count = Reservation.query.filter(
|
||||
Reservation.status == 'PENDING'
|
||||
).count()
|
||||
except Exception:
|
||||
pending_count = 0
|
||||
|
||||
try:
|
||||
recent_audits = AuditLog.query.order_by(AuditLog.created_at.desc()).limit(6).all()
|
||||
except Exception:
|
||||
recent_audits = []
|
||||
|
||||
try:
|
||||
upcoming_reservations = Reservation.query.filter(
|
||||
Reservation.start_time >= datetime.utcnow(),
|
||||
Reservation.start_time <= datetime.utcnow() + timedelta(days=7)
|
||||
).order_by(Reservation.start_time.asc()).limit(8).all()
|
||||
except Exception:
|
||||
upcoming_reservations = []
|
||||
|
||||
stats.update({
|
||||
'total_users': total_users,
|
||||
'pending_reservations': pending_count
|
||||
})
|
||||
role_data = {
|
||||
'recent_audits': recent_audits,
|
||||
'upcoming_reservations': upcoming_reservations
|
||||
}
|
||||
|
||||
elif role == 'bedelia':
|
||||
# 2. Bedelía Operations & Facilities Control
|
||||
try:
|
||||
physical_classrooms = Classroom.query.filter_by(is_active=True).filter(
|
||||
~Classroom.room_number.ilike('%VIRTUAL%') & ~Classroom.building.ilike('%VIRTUAL%')
|
||||
).count()
|
||||
virtual_classrooms = total_classrooms - physical_classrooms
|
||||
if virtual_classrooms < 0:
|
||||
virtual_classrooms = 0
|
||||
except Exception:
|
||||
physical_classrooms = total_classrooms
|
||||
virtual_classrooms = 0
|
||||
|
||||
try:
|
||||
pending_reservations = Reservation.query.filter(
|
||||
Reservation.status == 'PENDING'
|
||||
).order_by(Reservation.start_time.asc()).limit(10).all()
|
||||
pending_count = len(pending_reservations)
|
||||
except Exception:
|
||||
pending_reservations = []
|
||||
pending_count = 0
|
||||
|
||||
try:
|
||||
today_schedule_list = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today
|
||||
).order_by(Reservation.start_time.asc()).limit(12).all()
|
||||
except Exception:
|
||||
today_schedule_list = []
|
||||
|
||||
occupancy_rate = min(100, int((today_reservations / max(1, physical_classrooms * 3)) * 100)) if physical_classrooms > 0 else 0
|
||||
|
||||
stats.update({
|
||||
'physical_classrooms': physical_classrooms,
|
||||
'virtual_classrooms': virtual_classrooms,
|
||||
'pending_count': pending_count,
|
||||
'occupancy_rate': occupancy_rate
|
||||
})
|
||||
role_data = {
|
||||
'pending_reservations': pending_reservations,
|
||||
'today_schedule_list': today_schedule_list
|
||||
}
|
||||
|
||||
elif role == 'docente':
|
||||
# 3. Docente (Profesor) Academic & Classroom Workflow
|
||||
try:
|
||||
my_today_classes = Reservation.query.filter(
|
||||
Reservation.user_id == current_user.id,
|
||||
func.date(Reservation.start_time) == today
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
except Exception:
|
||||
my_today_classes = []
|
||||
|
||||
try:
|
||||
my_upcoming_reservations = Reservation.query.filter(
|
||||
Reservation.user_id == current_user.id,
|
||||
Reservation.start_time >= datetime.utcnow()
|
||||
).order_by(Reservation.start_time.asc()).limit(8).all()
|
||||
except Exception:
|
||||
my_upcoming_reservations = []
|
||||
|
||||
try:
|
||||
my_total_reservations = Reservation.query.filter(
|
||||
Reservation.user_id == current_user.id
|
||||
).count()
|
||||
except Exception:
|
||||
my_total_reservations = 0
|
||||
|
||||
try:
|
||||
virtual_classrooms = Classroom.query.filter_by(is_active=True).filter(
|
||||
(Classroom.room_number.ilike('%VIRTUAL%')) | (Classroom.building.ilike('%VIRTUAL%'))
|
||||
).limit(4).all()
|
||||
except Exception:
|
||||
virtual_classrooms = []
|
||||
|
||||
stats.update({
|
||||
'my_today_count': len(my_today_classes),
|
||||
'my_total_reservations': my_total_reservations,
|
||||
'virtual_rooms_count': len(virtual_classrooms)
|
||||
})
|
||||
role_data = {
|
||||
'my_today_classes': my_today_classes,
|
||||
'my_upcoming_reservations': my_upcoming_reservations,
|
||||
'virtual_classrooms': virtual_classrooms
|
||||
}
|
||||
|
||||
elif role == 'alumno':
|
||||
# 4. Alumno (Estudiante) Daily Guide & Timetable
|
||||
try:
|
||||
today_classes = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today,
|
||||
Reservation.status == 'CONFIRMED'
|
||||
).order_by(Reservation.start_time.asc()).limit(12).all()
|
||||
except Exception:
|
||||
today_classes = []
|
||||
|
||||
try:
|
||||
upcoming_milestones = AcademicMilestone.query.filter(
|
||||
AcademicMilestone.date >= datetime.utcnow(),
|
||||
AcademicMilestone.is_active == True
|
||||
).order_by(AcademicMilestone.date.asc()).limit(6).all()
|
||||
except Exception:
|
||||
upcoming_milestones = []
|
||||
|
||||
try:
|
||||
virtual_rooms = Classroom.query.filter_by(is_active=True).filter(
|
||||
(Classroom.room_number.ilike('%VIRTUAL%')) | (Classroom.building.ilike('%VIRTUAL%'))
|
||||
).limit(4).all()
|
||||
except Exception:
|
||||
virtual_rooms = []
|
||||
|
||||
stats.update({
|
||||
'today_classes_count': len(today_classes),
|
||||
'milestones_count': len(upcoming_milestones)
|
||||
})
|
||||
role_data = {
|
||||
'today_classes': today_classes,
|
||||
'upcoming_milestones': upcoming_milestones,
|
||||
'virtual_rooms': virtual_rooms
|
||||
}
|
||||
|
||||
# Backward compatibility for upcoming_reservations
|
||||
upcoming_reservations = role_data.get('upcoming_reservations', [])
|
||||
if not upcoming_reservations:
|
||||
try:
|
||||
upcoming_reservations = Reservation.query.filter(
|
||||
Reservation.start_time >= datetime.utcnow(),
|
||||
Reservation.start_time <= datetime.utcnow() + timedelta(days=7)
|
||||
).order_by(Reservation.start_time.asc()).limit(6).all()
|
||||
except Exception:
|
||||
upcoming_reservations = []
|
||||
|
||||
return render_template('dashboard.html',
|
||||
role=role,
|
||||
actual_role=actual_role,
|
||||
stats=stats,
|
||||
role_data=role_data,
|
||||
upcoming_reservations=upcoming_reservations)
|
||||
|
||||
@main_bp.route('/api/dashboard-stats')
|
||||
@login_required
|
||||
def dashboard_stats_api():
|
||||
"""API endpoint for dashboard statistics"""
|
||||
# Get today's data
|
||||
today = datetime.utcnow().date()
|
||||
today_reservations = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today
|
||||
).count()
|
||||
|
||||
# Get this week's data
|
||||
week_start = today - timedelta(days=today.weekday())
|
||||
week_end = week_start + timedelta(days=6)
|
||||
week_reservations = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) >= week_start,
|
||||
func.date(Reservation.start_time) <= week_end
|
||||
).count()
|
||||
|
||||
# Get monthly data for chart
|
||||
current_date = datetime.utcnow()
|
||||
monthly_data = []
|
||||
|
||||
for i in range(12):
|
||||
month_date = current_date - timedelta(days=30 * i)
|
||||
month_start = month_date.replace(day=1)
|
||||
month_end = (month_start + timedelta(days=32)).replace(day=1) - timedelta(days=1)
|
||||
|
||||
monthly_reservations = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) >= month_start.date(),
|
||||
func.date(Reservation.start_time) <= month_end.date()
|
||||
).count()
|
||||
|
||||
monthly_data.append({
|
||||
'month': month_start.strftime('%Y-%m'),
|
||||
'reservations': monthly_reservations
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'today_reservations': today_reservations,
|
||||
'week_reservations': week_reservations,
|
||||
'monthly_data': list(reversed(monthly_data))
|
||||
})
|
||||
|
||||
@main_bp.route('/genetic-optimizer')
|
||||
@login_required
|
||||
def genetic_optimizer():
|
||||
"""Serve the genetic algorithm optimization interface"""
|
||||
if not (current_user.has_permission('optimizer', 'read') or (current_user.role and current_user.role.upper() == 'ADMIN')):
|
||||
flash(_('No tienes permisos para acceder a la herramienta de optimización.'), 'danger')
|
||||
return redirect(url_for('main.dashboard'))
|
||||
|
||||
return render_template('genetic_optimizer.html')
|
||||
|
||||
@main_bp.route('/set_language/<language>')
|
||||
def set_language(language=None):
|
||||
if language not in ['en', 'es']:
|
||||
language = 'es'
|
||||
|
||||
session['language'] = language
|
||||
|
||||
# Si se selecciona el idioma desde la pantalla de login, registrar la selección explícita
|
||||
if request.referrer and 'login' in request.referrer:
|
||||
session['login_lang_explicit'] = language
|
||||
|
||||
if current_user.is_authenticated:
|
||||
current_user.preferred_language = language
|
||||
db.session.commit()
|
||||
|
||||
return redirect(request.referrer or url_for('main.dashboard'))
|
||||
|
||||
|
||||
@main_bp.route('/api/milestone-types')
|
||||
def api_milestone_types():
|
||||
"""Retorna las tipificaciones de hitos activas en JSON para consumo de frontend/mobile"""
|
||||
from app.models.milestone import MilestoneType, BASE_MILESTONE_TYPES
|
||||
if MilestoneType.query.count() == 0:
|
||||
for item in BASE_MILESTONE_TYPES:
|
||||
mt = MilestoneType(
|
||||
name=item['name'],
|
||||
code=item['code'],
|
||||
color=item['color'],
|
||||
description=item['description'],
|
||||
sort_order=item['sort_order'],
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(mt)
|
||||
db.session.commit()
|
||||
|
||||
types = MilestoneType.query.filter_by(is_active=True).order_by(MilestoneType.sort_order.asc(), MilestoneType.id.asc()).all()
|
||||
return jsonify([t.to_dict() for t in types])
|
||||
@@ -1,126 +0,0 @@
|
||||
from flask import Blueprint, render_template, abort
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.subject import Commission
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.classroom import Classroom
|
||||
|
||||
my_subjects_bp = Blueprint('my_subjects', __name__, url_prefix='/mis-materias')
|
||||
|
||||
|
||||
@my_subjects_bp.route('/')
|
||||
@login_required
|
||||
def my_subjects_list():
|
||||
"""Show the commissions assigned to the current user (teacher or student)."""
|
||||
role = current_user.get_institutional_role()
|
||||
|
||||
commissions = []
|
||||
|
||||
if role in ['admin', 'bedelia']:
|
||||
# Admin/Bedelia: see all active commissions
|
||||
commissions = (
|
||||
Commission.query
|
||||
.filter_by(active=True)
|
||||
.order_by(Commission.year.desc(), Commission.semester.asc(), Commission.code.asc())
|
||||
.all()
|
||||
)
|
||||
view_mode = 'all'
|
||||
|
||||
elif role == 'docente':
|
||||
# Teacher: only commissions where they are assigned as teacher
|
||||
commissions = (
|
||||
Commission.query
|
||||
.filter_by(teacher_id=current_user.id, active=True)
|
||||
.order_by(Commission.year.desc(), Commission.semester.asc(), Commission.code.asc())
|
||||
.all()
|
||||
)
|
||||
view_mode = 'teacher'
|
||||
|
||||
elif role == 'alumno':
|
||||
# Student: only commissions where they are enrolled
|
||||
enrollments = (
|
||||
StudentEnrollment.query
|
||||
.filter_by(student_id=current_user.id, status='activo')
|
||||
.all()
|
||||
)
|
||||
commission_ids = [e.commission_id for e in enrollments]
|
||||
commissions = (
|
||||
Commission.query
|
||||
.filter(Commission.id.in_(commission_ids), Commission.active == True)
|
||||
.order_by(Commission.year.desc(), Commission.semester.asc(), Commission.code.asc())
|
||||
.all()
|
||||
)
|
||||
view_mode = 'student'
|
||||
else:
|
||||
commissions = []
|
||||
view_mode = 'none'
|
||||
|
||||
return render_template(
|
||||
'my_subjects/list.html',
|
||||
commissions=commissions,
|
||||
view_mode=view_mode,
|
||||
role=role
|
||||
)
|
||||
|
||||
|
||||
@my_subjects_bp.route('/<int:commission_id>')
|
||||
@login_required
|
||||
def my_subject_detail(commission_id):
|
||||
"""Detail view of a single commission for the current user."""
|
||||
role = current_user.get_institutional_role()
|
||||
commission = Commission.query.get_or_404(commission_id)
|
||||
|
||||
# Access control: make sure the user is allowed to see this commission
|
||||
if role in ['admin', 'bedelia']:
|
||||
pass # full access
|
||||
elif role == 'docente':
|
||||
if commission.teacher_id != current_user.id:
|
||||
abort(403)
|
||||
elif role == 'alumno':
|
||||
enrollment = StudentEnrollment.query.filter_by(
|
||||
student_id=current_user.id,
|
||||
commission_id=commission_id
|
||||
).first()
|
||||
if not enrollment:
|
||||
abort(403)
|
||||
else:
|
||||
abort(403)
|
||||
|
||||
# Get enrolled students (visible to teachers and admin/bedelia)
|
||||
enrollments = []
|
||||
if role in ['admin', 'bedelia', 'docente']:
|
||||
enrollments = (
|
||||
StudentEnrollment.query
|
||||
.filter_by(commission_id=commission_id)
|
||||
.order_by(StudentEnrollment.enrolled_at.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
# Try to get classroom info from reservations linked to this commission
|
||||
from app.models.reservation import Reservation
|
||||
from sqlalchemy import func
|
||||
from datetime import datetime
|
||||
|
||||
# Recent or upcoming reservation linked to this commission
|
||||
recent_reservation = (
|
||||
Reservation.query
|
||||
.filter(
|
||||
Reservation.commission_id == commission_id,
|
||||
Reservation.start_time >= datetime.utcnow()
|
||||
)
|
||||
.order_by(Reservation.start_time.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
classroom = None
|
||||
if recent_reservation and recent_reservation.classroom_id:
|
||||
classroom = Classroom.query.get(recent_reservation.classroom_id)
|
||||
|
||||
return render_template(
|
||||
'my_subjects/detail.html',
|
||||
commission=commission,
|
||||
enrollments=enrollments,
|
||||
classroom=classroom,
|
||||
recent_reservation=recent_reservation,
|
||||
role=role
|
||||
)
|
||||
@@ -1,975 +0,0 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject, Commission
|
||||
from app.forms.reservation import ReservationForm
|
||||
from datetime import datetime, timedelta, date
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
schedule_bp = Blueprint('schedule', __name__, url_prefix='/schedule')
|
||||
|
||||
@schedule_bp.route('/today')
|
||||
@login_required
|
||||
def today_schedule():
|
||||
"""Show today's schedule with filters for virtual classrooms, floor, and shift"""
|
||||
today = datetime.utcnow().date()
|
||||
today_start = datetime.combine(today, datetime.min.time())
|
||||
today_end = datetime.combine(today, datetime.max.time())
|
||||
|
||||
hide_virtual = request.args.get('hide_virtual', '0') in ['1', 'true', 'True']
|
||||
floor_filter = request.args.get('floor', '').strip()
|
||||
shift_filter = request.args.get('shift', '').strip()
|
||||
|
||||
# Base query for today's reservations
|
||||
query = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission).joinedload(Commission.subject),
|
||||
joinedload(Reservation.user)
|
||||
).join(Reservation.classroom).filter(
|
||||
Reservation.start_time >= today_start,
|
||||
Reservation.start_time <= today_end,
|
||||
Reservation.status.in_([ReservationStatus.CONFIRMED.value, ReservationStatus.PENDING.value])
|
||||
)
|
||||
|
||||
if hide_virtual:
|
||||
query = query.filter(
|
||||
~Classroom.code.ilike('%VIRTUAL%'),
|
||||
~Classroom.building.ilike('%Virtual%')
|
||||
)
|
||||
|
||||
if floor_filter:
|
||||
flr = str(floor_filter).strip()
|
||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||
else:
|
||||
query = query.filter(Classroom.floor == flr)
|
||||
|
||||
if shift_filter:
|
||||
query = query.filter(Reservation.shift.ilike(f'%{shift_filter}%'))
|
||||
|
||||
reservations = query.order_by(Reservation.start_time).all()
|
||||
|
||||
# Create time blocks for timeline view
|
||||
time_blocks = {}
|
||||
for reservation in reservations:
|
||||
start_hour = reservation.start_time.hour
|
||||
end_hour = reservation.end_time.hour
|
||||
|
||||
for hour in range(max(7, start_hour), min(22, end_hour + 1)):
|
||||
if hour not in time_blocks:
|
||||
time_blocks[hour] = []
|
||||
if reservation not in time_blocks[hour]:
|
||||
time_blocks[hour].append({
|
||||
'reservation': reservation,
|
||||
'classroom': reservation.classroom,
|
||||
'commission': reservation.commission,
|
||||
'user': reservation.user
|
||||
})
|
||||
|
||||
# Calculate stats
|
||||
total_reservations = len(reservations)
|
||||
confirmed = len([r for r in reservations if r.status == ReservationStatus.CONFIRMED.value or str(r.status) == 'CONFIRMED'])
|
||||
pending = len([r for r in reservations if r.status == ReservationStatus.PENDING or str(r.status) == 'PENDING'])
|
||||
|
||||
total_classrooms = Classroom.query.count()
|
||||
occupied_classrooms = len(set(r.classroom_id for r in reservations if r.classroom_id))
|
||||
|
||||
stats = {
|
||||
'total_reservations': total_reservations,
|
||||
'confirmed': confirmed,
|
||||
'pending': pending,
|
||||
'occupied_classrooms': occupied_classrooms,
|
||||
'total_classrooms': total_classrooms
|
||||
}
|
||||
|
||||
floors = db.session.query(Classroom.floor).filter(Classroom.is_active==True, Classroom.floor.isnot(None)).distinct().order_by(Classroom.floor.asc()).all()
|
||||
available_floors = [f[0] for f in floors]
|
||||
|
||||
return render_template('schedule/today.html',
|
||||
reservations=reservations,
|
||||
time_blocks=time_blocks,
|
||||
stats=stats,
|
||||
today=today,
|
||||
hide_virtual=hide_virtual,
|
||||
floor_filter=floor_filter,
|
||||
shift_filter=shift_filter,
|
||||
available_floors=available_floors)
|
||||
|
||||
@schedule_bp.route('/cancel/<int:id>', methods=['POST'])
|
||||
@login_required
|
||||
def cancel_reservation(id):
|
||||
"""Cancel a reservation"""
|
||||
try:
|
||||
reservation = Reservation.query.get_or_404(id)
|
||||
|
||||
if not reservation.can_be_cancelled():
|
||||
flash('Reservations can only be cancelled at least 24 hours before start time.', 'error')
|
||||
return redirect(request.referrer)
|
||||
|
||||
reservation.status = ReservationStatus.CANCELLED
|
||||
db.session.commit()
|
||||
|
||||
flash('Reservation cancelled successfully!', 'success')
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error cancelling reservation: {str(e)}', 'error')
|
||||
|
||||
return redirect(request.referrer)
|
||||
|
||||
@schedule_bp.route('/reservation/<int:id>/view')
|
||||
@login_required
|
||||
def view_reservation(id):
|
||||
"""View reservation details"""
|
||||
try:
|
||||
reservation = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission),
|
||||
joinedload(Reservation.user)
|
||||
).get_or_404(id)
|
||||
|
||||
return render_template('schedule/view.html',
|
||||
reservation=reservation,
|
||||
title='Reservation Details')
|
||||
|
||||
except Exception as e:
|
||||
flash(f'Error loading reservation details: {str(e)}', 'error')
|
||||
return redirect(url_for('schedule.today_schedule'))
|
||||
|
||||
@schedule_bp.route('/reservation/<int:id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def edit_reservation(id):
|
||||
"""Edit existing reservation"""
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Commission
|
||||
from app.models.building import Building
|
||||
from flask_babel import gettext as _
|
||||
|
||||
reservation = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission),
|
||||
joinedload(Reservation.user)
|
||||
).get_or_404(id)
|
||||
|
||||
if not current_user.can_edit_reservation(reservation):
|
||||
flash(_('No tienes los permisos necesarios para modificar esta reserva.'), 'error')
|
||||
return redirect(url_for('schedule.view_reservation', id=reservation.id))
|
||||
|
||||
form = ReservationForm(is_edit=True)
|
||||
|
||||
buildings = Building.query.filter_by(is_active=True).order_by(Building.name.asc()).all()
|
||||
classrooms = Classroom.query.filter_by(is_active=True).order_by(Classroom.building_id.asc(), Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
commissions = Commission.query.filter_by(active=True).all()
|
||||
|
||||
form.classroom_id.choices = [(c.id, f'{c.building_name} - {c.code} (Cap: {c.capacity_display})') for c in classrooms]
|
||||
form.commission_id.choices = [(c.id, f'{c.get_full_code()} - {c.subject.name if c.subject else "No Subject"} (Students: {c.max_students})') for c in commissions]
|
||||
|
||||
if request.method == 'GET':
|
||||
form.classroom_id.data = reservation.classroom_id
|
||||
form.commission_id.data = reservation.commission_id
|
||||
form.start_time.data = reservation.start_time
|
||||
form.end_time.data = reservation.end_time
|
||||
form.purpose.data = reservation.purpose
|
||||
form.expected_attendees.data = reservation.expected_attendees
|
||||
form.notes.data = reservation.notes or ''
|
||||
form.virtual_link.data = reservation.virtual_link or ''
|
||||
|
||||
elif request.method == 'POST':
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
# Verificar colisión de horario si no es virtual
|
||||
target_room = Classroom.query.get(form.classroom_id.data)
|
||||
if target_room and not target_room.is_virtual:
|
||||
conflict = Reservation.query.filter(
|
||||
Reservation.id != reservation.id,
|
||||
Reservation.classroom_id == form.classroom_id.data,
|
||||
Reservation.status == ReservationStatus.CONFIRMED.value,
|
||||
Reservation.start_time < form.end_time.data,
|
||||
Reservation.end_time > form.start_time.data
|
||||
).first()
|
||||
|
||||
if conflict:
|
||||
flash(_('El aula seleccionada ya cuenta con una reserva confirmada en esa franja horaria.'), 'danger')
|
||||
return render_template('schedule/edit.html', form=form, reservation=reservation, classroom_list=classrooms, commission_list=commissions, buildings=buildings)
|
||||
|
||||
# Asignar cambios
|
||||
reservation.classroom_id = form.classroom_id.data
|
||||
reservation.commission_id = form.commission_id.data
|
||||
reservation.start_time = form.start_time.data
|
||||
reservation.end_time = form.end_time.data
|
||||
reservation.purpose = form.purpose.data
|
||||
reservation.expected_attendees = form.expected_attendees.data
|
||||
reservation.notes = form.notes.data
|
||||
reservation.virtual_link = form.virtual_link.data.strip() if form.virtual_link.data else None
|
||||
|
||||
# Turno
|
||||
h = reservation.start_time.hour
|
||||
if h < 13:
|
||||
reservation.shift = 'Mañana'
|
||||
elif h < 18:
|
||||
reservation.shift = 'Tarde'
|
||||
elif h < 21:
|
||||
reservation.shift = 'Vespertino'
|
||||
else:
|
||||
reservation.shift = 'Noche'
|
||||
|
||||
db.session.commit()
|
||||
flash(_('Reserva #%(id)d modificada exitosamente.', id=reservation.id), 'success')
|
||||
return redirect(url_for('schedule.view_reservation', id=reservation.id))
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error al modificar reserva: {str(e)}', 'danger')
|
||||
|
||||
return render_template('schedule/edit.html', form=form, reservation=reservation, classroom_list=classrooms, commission_list=commissions, buildings=buildings)
|
||||
|
||||
@schedule_bp.route('/calendar')
|
||||
@login_required
|
||||
def calendar_view():
|
||||
"""Show calendar view with classroom, subject, career, shift, floor and virtual filtering"""
|
||||
from app.models.career import Career
|
||||
from app.models.building import Building
|
||||
classrooms = Classroom.query.filter_by(is_active=True).order_by(Classroom.building.asc(), Classroom.code.asc()).all()
|
||||
subjects = Subject.query.filter_by(is_active=True).order_by(Subject.name.asc()).all()
|
||||
careers = Career.query.order_by(Career.name.asc()).all()
|
||||
buildings = Building.query.filter_by(is_active=True).order_by(Building.name.asc()).all()
|
||||
|
||||
floors = db.session.query(Classroom.floor).filter(Classroom.is_active==True, Classroom.floor.isnot(None)).distinct().order_by(Classroom.floor.asc()).all()
|
||||
available_floors = [f[0] for f in floors]
|
||||
|
||||
return render_template(
|
||||
'schedule/calendar.html',
|
||||
title='Calendar View',
|
||||
today_date=date.today().isoformat(),
|
||||
classrooms=classrooms,
|
||||
subjects=subjects,
|
||||
careers=careers,
|
||||
buildings=buildings,
|
||||
available_floors=available_floors
|
||||
)
|
||||
|
||||
def user_can_manage_commission_milestones(user, commission=None):
|
||||
"""Verifica si el usuario (Docente, Admin, Bedelía) puede gestionar hitos y links virtuales"""
|
||||
if user.is_admin():
|
||||
return True
|
||||
role_name = (user.role_obj.name if user.role_obj else user.role or '').lower()
|
||||
if role_name in ['admin', 'bedelia', 'bedelía', 'operador']:
|
||||
return True
|
||||
if role_name in ['docente', 'profesor']:
|
||||
return True
|
||||
return user.has_permission('schedule', 'read_write')
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions')
|
||||
@login_required
|
||||
def commissions_view():
|
||||
"""Vista y ABM de Comisiones con soporte de enlace virtual e hitos académicos"""
|
||||
from app.models.subject import Commission, Subject
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.user import User
|
||||
from app.models.milestone import MilestoneType
|
||||
|
||||
subjects = Subject.query.order_by(Subject.code.asc()).all()
|
||||
classrooms = Classroom.query.filter_by(is_active=True).order_by(Classroom.code.asc()).all()
|
||||
teachers = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
|
||||
milestone_types = MilestoneType.query.filter_by(is_active=True).order_by(MilestoneType.sort_order.asc()).all()
|
||||
|
||||
# Totales para indicadores superiores
|
||||
total_capacity = sum(c.max_students for s in subjects for c in s.commissions)
|
||||
total_commissions = sum(len(s.commissions) for s in subjects)
|
||||
|
||||
can_manage_milestones = user_can_manage_commission_milestones(current_user)
|
||||
role_name = (current_user.role_obj.name if current_user.role_obj else current_user.role or '').lower()
|
||||
can_edit_commissions = current_user.is_admin() or role_name in ['admin', 'bedelia', 'bedelía', 'operador'] or current_user.has_permission('schedule', 'read_write')
|
||||
|
||||
return render_template('schedule/commissions.html',
|
||||
subjects=subjects,
|
||||
classrooms=classrooms,
|
||||
teachers=teachers,
|
||||
milestone_types=milestone_types,
|
||||
total_capacity=total_capacity,
|
||||
total_commissions=total_commissions,
|
||||
can_manage_milestones=can_manage_milestones,
|
||||
can_edit_commissions=can_edit_commissions)
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/add', methods=['POST'])
|
||||
@login_required
|
||||
def commission_add():
|
||||
"""Crear una nueva comisión de cursada"""
|
||||
role_name = (current_user.role_obj.name if current_user.role_obj else current_user.role or '').lower()
|
||||
if not (current_user.is_admin() or role_name in ['admin', 'bedelia', 'bedelía', 'operador'] or current_user.has_permission('schedule', 'read_write')):
|
||||
flash(_('No tienes permisos para crear comisiones.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
from app.models.subject import Commission
|
||||
subject_id = request.form.get('subject_id', type=int)
|
||||
code = request.form.get('code', '').strip()
|
||||
semester = request.form.get('semester', '1C').strip()
|
||||
year = request.form.get('year', datetime.now().year, type=int)
|
||||
teacher_id = request.form.get('teacher_id', type=int) or None
|
||||
max_students = request.form.get('max_students', 40, type=int)
|
||||
schedule = request.form.get('schedule', '').strip()
|
||||
shift = request.form.get('shift', 'Tarde').strip()
|
||||
virtual_link = request.form.get('virtual_link', '').strip()
|
||||
|
||||
if not subject_id or not code:
|
||||
flash(_('La asignatura y el código de comisión son obligatorios.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
# Verificar existencia duplicada
|
||||
existing = Commission.query.filter_by(subject_id=subject_id, code=code, semester=semester, year=year).first()
|
||||
if existing:
|
||||
flash(_('Ya existe una comisión %(code)s para el ciclo %(sem)s %(yr)d.', code=code, sem=semester, yr=year), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
new_comm = Commission(
|
||||
subject_id=subject_id,
|
||||
code=code,
|
||||
semester=semester,
|
||||
year=year,
|
||||
teacher_id=teacher_id,
|
||||
max_students=max_students,
|
||||
schedule=schedule,
|
||||
shift=shift,
|
||||
virtual_link=virtual_link or None,
|
||||
active=True
|
||||
)
|
||||
db.session.add(new_comm)
|
||||
db.session.commit()
|
||||
|
||||
flash(_('Comisión %(code)s creada exitosamente.', code=new_comm.get_full_code()), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/<int:id>/edit', methods=['POST'])
|
||||
@login_required
|
||||
def commission_edit(id):
|
||||
"""Editar datos de una comisión"""
|
||||
role_name = (current_user.role_obj.name if current_user.role_obj else current_user.role or '').lower()
|
||||
if not (current_user.is_admin() or role_name in ['admin', 'bedelia', 'bedelía', 'operador'] or current_user.has_permission('schedule', 'read_write')):
|
||||
flash(_('No tienes permisos para modificar comisiones.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
from app.models.subject import Commission
|
||||
commission = Commission.query.get_or_404(id)
|
||||
|
||||
commission.code = request.form.get('code', commission.code).strip()
|
||||
commission.semester = request.form.get('semester', commission.semester).strip()
|
||||
commission.year = request.form.get('year', commission.year, type=int)
|
||||
commission.teacher_id = request.form.get('teacher_id', type=int) or None
|
||||
commission.max_students = request.form.get('max_students', commission.max_students, type=int)
|
||||
commission.schedule = request.form.get('schedule', commission.schedule).strip()
|
||||
commission.shift = request.form.get('shift', commission.shift).strip()
|
||||
commission.virtual_link = request.form.get('virtual_link', '').strip() or None
|
||||
commission.active = True if request.form.get('active') in ['1', 'true', 'on'] else False
|
||||
|
||||
db.session.commit()
|
||||
flash(_('Comisión %(code)s actualizada con éxito.', code=commission.get_full_code()), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/<int:id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
def commission_delete(id):
|
||||
"""Eliminar una comisión"""
|
||||
role_name = (current_user.role_obj.name if current_user.role_obj else current_user.role or '').lower()
|
||||
if not (current_user.is_admin() or role_name in ['admin', 'bedelia', 'bedelía', 'operador'] or current_user.has_permission('schedule', 'read_write')):
|
||||
flash(_('No tienes permisos para eliminar comisiones.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
from app.models.subject import Commission
|
||||
commission = Commission.query.get_or_404(id)
|
||||
full_code = commission.get_full_code()
|
||||
|
||||
db.session.delete(commission)
|
||||
db.session.commit()
|
||||
|
||||
flash(_('Comisión %(code)s eliminada permanentemente.', code=full_code), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/<int:id>/virtual-link', methods=['POST'])
|
||||
@login_required
|
||||
def commission_virtual_link(id):
|
||||
"""Actualizar enlace del aula virtual (Zoom, Meet, Teams, Moodle) - Profesores, Admin y Bedelía"""
|
||||
from app.models.subject import Commission
|
||||
commission = Commission.query.get_or_404(id)
|
||||
|
||||
if not user_can_manage_commission_milestones(current_user, commission):
|
||||
flash(_('No tienes permisos para actualizar el aula virtual de esta comisión.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
link = request.form.get('virtual_link', '').strip()
|
||||
commission.virtual_link = link or None
|
||||
db.session.commit()
|
||||
|
||||
flash(_('Enlace del aula virtual actualizado para la comisión %(code)s.', code=commission.get_full_code()), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/<int:id>/milestones/add', methods=['POST'])
|
||||
@login_required
|
||||
def commission_milestone_add(id):
|
||||
"""Agregar un hito académico (Parcial, TP, Recuperatorio) a una comisión - Profesores, Admin y Bedelía"""
|
||||
from app.models.subject import Commission
|
||||
from app.models.milestone import AcademicMilestone, MilestoneType
|
||||
commission = Commission.query.get_or_404(id)
|
||||
|
||||
if not user_can_manage_commission_milestones(current_user, commission):
|
||||
flash(_('No tienes permisos para agregar hitos a esta comisión.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
milestone_type_id = request.form.get('milestone_type_id', type=int)
|
||||
title = request.form.get('title', '').strip()
|
||||
date_str = request.form.get('date', '').strip()
|
||||
time_str = request.form.get('time', '18:00').strip()
|
||||
classroom = request.form.get('classroom', '').strip()
|
||||
link = request.form.get('link', '').strip() or commission.virtual_link or ''
|
||||
notes = request.form.get('notes', '').strip()
|
||||
|
||||
if not milestone_type_id or not date_str:
|
||||
flash(_('Debes especificar el tipo de hito y la fecha.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
m_type = MilestoneType.query.get(milestone_type_id)
|
||||
if not m_type:
|
||||
flash(_('Tipo de hito inválido.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
try:
|
||||
dt = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
|
||||
except ValueError:
|
||||
try:
|
||||
dt = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
flash(_('Formato de fecha inválido.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
milestone = AcademicMilestone(
|
||||
title=title or m_type.name,
|
||||
materia_codigo=commission.subject.code if commission.subject else 'ASIG',
|
||||
subject_id=commission.subject_id,
|
||||
commission_id=commission.id,
|
||||
milestone_type_id=m_type.id,
|
||||
date=dt,
|
||||
classroom=classroom or 'Campus Virtual',
|
||||
link=link or None,
|
||||
notes=notes or None,
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(milestone)
|
||||
db.session.commit()
|
||||
|
||||
flash(_('Hito "%(title)s" registrado correctamente en %(comm)s.', title=milestone.title, comm=commission.get_full_code()), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
|
||||
@schedule_bp.route('/commissions/<int:commission_id>/milestones/<int:milestone_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
def commission_milestone_delete(commission_id, milestone_id):
|
||||
"""Eliminar un hito académico de una comisión"""
|
||||
from app.models.subject import Commission
|
||||
from app.models.milestone import AcademicMilestone
|
||||
commission = Commission.query.get_or_404(commission_id)
|
||||
|
||||
if not user_can_manage_commission_milestones(current_user, commission):
|
||||
flash(_('No tienes permisos para eliminar hitos de esta comisión.'), 'error')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
milestone = AcademicMilestone.query.filter_by(id=milestone_id, commission_id=commission_id).first_or_404()
|
||||
title = milestone.title
|
||||
db.session.delete(milestone)
|
||||
db.session.commit()
|
||||
|
||||
flash(_('Hito "%(title)s" eliminado de la comisión.', title=title), 'success')
|
||||
return redirect(url_for('schedule.commissions_view'))
|
||||
|
||||
@schedule_bp.route('/add', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def add_reservation():
|
||||
"""Add new reservation"""
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Commission
|
||||
from app.models.building import Building
|
||||
|
||||
form = ReservationForm()
|
||||
|
||||
# Get active buildings and classrooms
|
||||
buildings = Building.query.filter_by(is_active=True).order_by(Building.name.asc()).all()
|
||||
classrooms = Classroom.query.filter_by(is_active=True).order_by(Classroom.building_id.asc(), Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
commissions = Commission.query.filter_by(active=True).all()
|
||||
|
||||
# Populate form choices
|
||||
form.classroom_id.choices = [(c.id, f'{c.building_name} - {c.code} (Cap: {c.capacity_display})') for c in classrooms]
|
||||
form.commission_id.choices = [(c.id, f'{c.get_full_code()} - {c.subject.name if c.subject else "No Subject"} (Students: {c.max_students})') for c in commissions]
|
||||
|
||||
if request.method == 'POST':
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
# Check for existing reservations at the same time
|
||||
from app.models.reservation import ReservationStatus
|
||||
existing_reservation = Reservation.query.filter_by(
|
||||
classroom_id=form.classroom_id.data,
|
||||
status=ReservationStatus.CONFIRMED.value
|
||||
).filter(
|
||||
Reservation.start_time < form.end_time.data,
|
||||
Reservation.end_time > form.start_time.data
|
||||
).first()
|
||||
|
||||
if existing_reservation:
|
||||
flash('This classroom is already booked for the selected time slot.', 'danger')
|
||||
return render_template('schedule/add.html', form=form, title='New Reservation', classroom_list=classrooms, commission_list=commissions, buildings=buildings)
|
||||
|
||||
# Create new reservation
|
||||
reservation = Reservation(
|
||||
classroom_id=form.classroom_id.data,
|
||||
commission_id=form.commission_id.data,
|
||||
user_id=current_user.id,
|
||||
start_time=form.start_time.data,
|
||||
end_time=form.end_time.data,
|
||||
purpose=form.purpose.data,
|
||||
notes=form.notes.data,
|
||||
virtual_link=form.virtual_link.data.strip() if form.virtual_link.data else None,
|
||||
status=ReservationStatus.PENDING.value,
|
||||
expected_attendees=form.expected_attendees.data
|
||||
)
|
||||
|
||||
db.session.add(reservation)
|
||||
db.session.commit()
|
||||
|
||||
flash('Reservation request submitted successfully! It will be reviewed by an administrator.', 'success')
|
||||
return redirect(url_for('schedule.list_reservations'))
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error creating reservation: {str(e)}', 'danger')
|
||||
|
||||
return render_template('schedule/add.html', form=form, title='New Reservation', classroom_list=classrooms, commission_list=commissions, buildings=buildings)
|
||||
|
||||
@schedule_bp.route('/reservation/add', methods=['POST'])
|
||||
@login_required
|
||||
def quick_reservation_add():
|
||||
"""Endpoint AJAX para crear reserva rápida desde el modal de comisiones"""
|
||||
try:
|
||||
commission_id = request.form.get('commission_id', type=int)
|
||||
classroom_id = request.form.get('classroom_id', type=int)
|
||||
purpose = request.form.get('purpose', '').strip() or 'Clase de cursada'
|
||||
start_str = request.form.get('start_time', '').strip()
|
||||
end_str = request.form.get('end_time', '').strip()
|
||||
virtual_link = request.form.get('virtual_link', '').strip() or None
|
||||
|
||||
if not commission_id or not classroom_id or not start_str or not end_str:
|
||||
return jsonify({'error': 'Faltan campos obligatorios'}), 400
|
||||
|
||||
start_time = datetime.strptime(start_str, '%Y-%m-%d %H:%M')
|
||||
end_time = datetime.strptime(end_str, '%Y-%m-%d %H:%M')
|
||||
|
||||
from app.models.subject import Commission
|
||||
from app.models.classroom import Classroom
|
||||
comm = Commission.query.get_or_404(commission_id)
|
||||
|
||||
if not virtual_link and comm.virtual_link:
|
||||
virtual_link = comm.virtual_link
|
||||
|
||||
new_res = Reservation(
|
||||
classroom_id=classroom_id,
|
||||
commission_id=commission_id,
|
||||
user_id=comm.teacher_id or current_user.id,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
purpose=purpose,
|
||||
expected_attendees=comm.max_students or 30,
|
||||
shift=comm.shift or 'Tarde',
|
||||
virtual_link=virtual_link,
|
||||
status=ReservationStatus.CONFIRMED.value if current_user.is_admin() else ReservationStatus.PENDING.value
|
||||
)
|
||||
db.session.add(new_res)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'id': new_res.id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@schedule_bp.route('/list')
|
||||
@login_required
|
||||
def list_reservations():
|
||||
"""List all reservations with pagination, date filters, floor, shift, and virtual toggle"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
status_filter = request.args.get('status', 'all').strip()
|
||||
date_from = request.args.get('date_from', '').strip()
|
||||
date_to = request.args.get('date_to', '').strip()
|
||||
hide_virtual = request.args.get('hide_virtual', '0') in ['1', 'true', 'True']
|
||||
floor_filter = request.args.get('floor', '').strip()
|
||||
shift_filter = request.args.get('shift', '').strip()
|
||||
classroom_id = request.args.get('classroom_id', type=int)
|
||||
search = request.args.get('search', '').strip()
|
||||
|
||||
query = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission).joinedload(Commission.subject),
|
||||
joinedload(Reservation.user)
|
||||
).join(Reservation.classroom).outerjoin(Reservation.commission).outerjoin(Commission.subject)
|
||||
|
||||
if classroom_id:
|
||||
query = query.filter(Reservation.classroom_id == classroom_id)
|
||||
|
||||
if status_filter and status_filter != 'all':
|
||||
query = query.filter(Reservation.status == status_filter.upper())
|
||||
|
||||
if date_from:
|
||||
try:
|
||||
d_from = datetime.strptime(date_from, '%Y-%m-%d')
|
||||
query = query.filter(Reservation.start_time >= d_from)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if date_to:
|
||||
try:
|
||||
d_to = datetime.strptime(date_to, '%Y-%m-%d') + timedelta(days=1)
|
||||
query = query.filter(Reservation.start_time < d_to)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if hide_virtual:
|
||||
query = query.filter(
|
||||
~Classroom.code.ilike('%VIRTUAL%'),
|
||||
~Classroom.building.ilike('%Virtual%')
|
||||
)
|
||||
|
||||
if floor_filter:
|
||||
flr = str(floor_filter).strip()
|
||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||
else:
|
||||
query = query.filter(Classroom.floor == flr)
|
||||
|
||||
if shift_filter:
|
||||
query = query.filter(Reservation.shift.ilike(f'%{shift_filter}%'))
|
||||
|
||||
if search:
|
||||
query = query.filter(
|
||||
or_(
|
||||
Subject.name.ilike(f'%{search}%'),
|
||||
Subject.code.ilike(f'%{search}%'),
|
||||
Commission.code.ilike(f'%{search}%'),
|
||||
Classroom.code.ilike(f'%{search}%'),
|
||||
Reservation.purpose.ilike(f'%{search}%'),
|
||||
Reservation.shift.ilike(f'%{search}%')
|
||||
)
|
||||
)
|
||||
|
||||
reservations = query.order_by(Reservation.start_time.desc()).paginate(
|
||||
page=page, per_page=20, error_out=False
|
||||
)
|
||||
|
||||
floors = db.session.query(Classroom.floor).filter(Classroom.is_active==True, Classroom.floor.isnot(None)).distinct().order_by(Classroom.floor.asc()).all()
|
||||
available_floors = [f[0] for f in floors]
|
||||
all_classrooms = Classroom.query.filter_by(is_active=True).order_by(Classroom.building_id.asc(), Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||
|
||||
return render_template(
|
||||
'schedule/list.html',
|
||||
reservations=reservations,
|
||||
status_filter=status_filter,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
hide_virtual=hide_virtual,
|
||||
floor_filter=floor_filter,
|
||||
shift_filter=shift_filter,
|
||||
classroom_id=classroom_id,
|
||||
all_classrooms=all_classrooms,
|
||||
search=search,
|
||||
available_floors=available_floors
|
||||
)
|
||||
|
||||
|
||||
@schedule_bp.route('/reservation/<int:id>/confirm', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def confirm_reservation(id):
|
||||
"""Confirm a reservation (Handles both GET from link and POST from form)"""
|
||||
try:
|
||||
reservation = Reservation.query.get_or_404(id)
|
||||
|
||||
# Validación de seguridad: Solo confirmar si está pendiente
|
||||
if reservation.status != ReservationStatus.PENDING.value:
|
||||
flash('Only pending reservations can be confirmed.', 'warning')
|
||||
return redirect(url_for('schedule.today_schedule'))
|
||||
|
||||
reservation.status = ReservationStatus.CONFIRMED.value
|
||||
db.session.commit()
|
||||
|
||||
flash(
|
||||
f'Reservation for {reservation.commission.code if reservation.commission else "Class"} confirmed successfully!',
|
||||
'success')
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
flash(f'Error confirming reservation: {str(e)}', 'error')
|
||||
|
||||
# Redirigir a la página desde la que venía el usuario o al inicio de hoy
|
||||
return redirect(request.referrer or url_for('schedule.today_schedule'))
|
||||
|
||||
# API endpoints
|
||||
@schedule_bp.route('/api/classroom-availability')
|
||||
@login_required
|
||||
def classroom_availability_api():
|
||||
"""Get classroom availability for a specific date/time"""
|
||||
try:
|
||||
date_str = request.args.get('date')
|
||||
start_time_str = request.args.get('start_time')
|
||||
end_time_str = request.args.get('end_time')
|
||||
max_students = request.args.get('max_students', type=int)
|
||||
|
||||
if not all([date_str, start_time_str, end_time_str]):
|
||||
return jsonify({'error': 'Missing required parameters: date, start_time, end_time'}), 400
|
||||
|
||||
# Parse datetime strings
|
||||
from datetime import datetime
|
||||
start_time = datetime.strptime(f"{date_str} {start_time_str}", "%Y-%m-%d %H:%M")
|
||||
end_time = datetime.strptime(f"{date_str} {end_time_str}", "%Y-%m-%d %H:%M")
|
||||
|
||||
# Get availability status
|
||||
from app.models.classroom import Classroom
|
||||
availability = Classroom.get_availability_status(start_time, end_time)
|
||||
|
||||
# Get best classroom recommendation if max_students provided
|
||||
best_recommendation = None
|
||||
if max_students:
|
||||
best_classrooms = Classroom.find_best_classroom(max_students, start_time, end_time)
|
||||
if best_classrooms:
|
||||
best_recommendation = best_classrooms[0] # Most efficient one
|
||||
|
||||
# Format response
|
||||
response = {
|
||||
'availability': {
|
||||
'available': [
|
||||
{
|
||||
'id': item['classroom'].id,
|
||||
'code': item['classroom'].code_display,
|
||||
'name': item['classroom'].name,
|
||||
'capacity': item['classroom'].capacity,
|
||||
'location': item['classroom'].get_full_location()
|
||||
}
|
||||
for item in availability['available']
|
||||
],
|
||||
'occupied': [
|
||||
{
|
||||
'id': item['classroom'].id,
|
||||
'code': item['classroom'].code_display,
|
||||
'name': item['classroom'].name,
|
||||
'capacity': item['classroom'].capacity,
|
||||
'location': item['classroom'].get_full_location(),
|
||||
'conflicts': [
|
||||
{
|
||||
'start_time': conflict.start_time.strftime('%H:%M'),
|
||||
'end_time': conflict.end_time.strftime('%H:%M'),
|
||||
'commission': conflict.commission.get_full_code() if conflict.commission else 'Unknown'
|
||||
}
|
||||
for conflict in item['conflicts']
|
||||
]
|
||||
}
|
||||
for item in availability['occupied']
|
||||
],
|
||||
'stats': {
|
||||
'total_available': availability['total_available'],
|
||||
'total_occupied': availability['total_occupied']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if best_recommendation:
|
||||
response['recommendation'] = {
|
||||
'classroom': {
|
||||
'id': best_recommendation['classroom'].id,
|
||||
'code': best_recommendation['classroom'].code_display,
|
||||
'name': best_recommendation['classroom'].name,
|
||||
'capacity': best_recommendation['classroom'].capacity,
|
||||
'location': best_recommendation['classroom'].get_full_location()
|
||||
},
|
||||
'efficiency': best_recommendation['efficiency'],
|
||||
'wasted_capacity': best_recommendation['wasted_capacity'],
|
||||
'reason': 'Best match based on capacity and availability'
|
||||
}
|
||||
|
||||
return jsonify(response)
|
||||
|
||||
except ValueError as e:
|
||||
return jsonify({'error': f'Invalid date/time format: {str(e)}'}), 400
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@schedule_bp.route('/calendar-data')
|
||||
@login_required
|
||||
def calendar_data():
|
||||
"""Get calendar events data for FullCalendar"""
|
||||
try:
|
||||
start = request.args.get('start')
|
||||
end = request.args.get('end')
|
||||
classroom_id = request.args.get('classroom_id')
|
||||
subject_id = request.args.get('subject_id')
|
||||
career_id = request.args.get('career_id')
|
||||
shift = request.args.get('shift', '').strip()
|
||||
floor = request.args.get('floor', '').strip()
|
||||
hide_virtual = request.args.get('hide_virtual', '0') in ['1', 'true', 'True']
|
||||
search = request.args.get('search', '').strip()
|
||||
|
||||
if start and end:
|
||||
# Clean up ISO timezone strings for PostgreSQL naive timestamp comparison
|
||||
start_clean = start.replace('Z', '+00:00')
|
||||
end_clean = end.replace('Z', '+00:00')
|
||||
start_date = datetime.fromisoformat(start_clean).replace(tzinfo=None)
|
||||
end_date = datetime.fromisoformat(end_clean).replace(tzinfo=None)
|
||||
else:
|
||||
today = date.today()
|
||||
start_date = datetime.combine(today.replace(day=1), datetime.min.time())
|
||||
next_month = today.replace(day=28) + timedelta(days=4)
|
||||
end_date = datetime.combine(next_month.replace(day=1), datetime.max.time())
|
||||
|
||||
query = Reservation.query.join(Reservation.commission).join(Commission.subject).outerjoin(Reservation.classroom).options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission).joinedload(Commission.subject).joinedload(Subject.career_obj)
|
||||
).filter(
|
||||
Reservation.start_time >= start_date,
|
||||
Reservation.start_time <= end_date
|
||||
)
|
||||
|
||||
if classroom_id and classroom_id.isdigit():
|
||||
query = query.filter(Reservation.classroom_id == int(classroom_id))
|
||||
|
||||
if subject_id and subject_id.isdigit():
|
||||
query = query.filter(Commission.subject_id == int(subject_id))
|
||||
|
||||
if career_id and career_id.isdigit():
|
||||
query = query.filter(Subject.career_id == int(career_id))
|
||||
|
||||
building = request.args.get('building', '').strip()
|
||||
if building:
|
||||
from app.models.building import Building
|
||||
query = query.filter(
|
||||
or_(
|
||||
Classroom.building.ilike(f'%{building}%'),
|
||||
Classroom.building_entity.has(Building.name.ilike(f'%{building}%'))
|
||||
)
|
||||
)
|
||||
|
||||
if shift:
|
||||
query = query.filter(Reservation.shift.ilike(f'%{shift}%'))
|
||||
|
||||
if hide_virtual:
|
||||
query = query.filter(
|
||||
~Classroom.code.ilike('%VIRTUAL%'),
|
||||
~Classroom.building.ilike('%Virtual%')
|
||||
)
|
||||
|
||||
if floor:
|
||||
flr = str(floor).strip()
|
||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||
else:
|
||||
query = query.filter(Classroom.floor == flr)
|
||||
|
||||
if search:
|
||||
query = query.filter(
|
||||
or_(
|
||||
Subject.name.ilike(f'%{search}%'),
|
||||
Subject.code.ilike(f'%{search}%'),
|
||||
Classroom.code.ilike(f'%{search}%'),
|
||||
Reservation.purpose.ilike(f'%{search}%')
|
||||
)
|
||||
)
|
||||
|
||||
reservations = query.order_by(Reservation.start_time).all()
|
||||
|
||||
events = []
|
||||
for reservation in reservations:
|
||||
subject = reservation.commission.subject if (reservation.commission and reservation.commission.subject) else None
|
||||
subject_code = subject.code if subject else (reservation.commission.code if reservation.commission else '')
|
||||
subject_name = subject.name if subject else (reservation.purpose or 'Clase')
|
||||
classroom_name = reservation.classroom.code if reservation.classroom else 'Sin Aula'
|
||||
classroom_floor = reservation.classroom.floor_display if reservation.classroom else None
|
||||
classroom_building = reservation.classroom.building_name if reservation.classroom else ''
|
||||
is_virtual = bool(reservation.classroom and reservation.classroom.is_virtual)
|
||||
career_name = subject.career_obj.name if (subject and subject.career_obj) else (subject.department if subject else '')
|
||||
status_val = str(reservation.status.value if hasattr(reservation.status, 'value') else reservation.status)
|
||||
|
||||
events.append({
|
||||
'id': reservation.id,
|
||||
'title': subject_name,
|
||||
'start': reservation.start_time.isoformat(),
|
||||
'end': reservation.end_time.isoformat(),
|
||||
'url': url_for('schedule.view_reservation', id=reservation.id) if reservation.id else None,
|
||||
'className': f'fc-event-{status_val.lower()}',
|
||||
'extendedProps': {
|
||||
'subject_code': subject_code,
|
||||
'subject_name': subject_name,
|
||||
'classroom': classroom_name,
|
||||
'building': classroom_building,
|
||||
'floor': classroom_floor,
|
||||
'is_virtual': is_virtual,
|
||||
'location_display': reservation.classroom.location_display if reservation.classroom else '',
|
||||
'career': career_name,
|
||||
'commission': reservation.commission.code if reservation.commission else '',
|
||||
'shift': reservation.shift or '',
|
||||
'status': status_val,
|
||||
'purpose': reservation.purpose or '',
|
||||
'attendees': reservation.expected_attendees or 0,
|
||||
'notes': reservation.notes or '',
|
||||
'teacher': reservation.user.name if reservation.user else '',
|
||||
'virtual_link': reservation.effective_virtual_link,
|
||||
'cancel_url': url_for('schedule.cancel_reservation', id=reservation.id)
|
||||
}
|
||||
})
|
||||
|
||||
return jsonify(events)
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@schedule_bp.route('/api/today-events')
|
||||
@login_required
|
||||
def api_today_events():
|
||||
"""Get today's events as JSON"""
|
||||
try:
|
||||
today_start = datetime.combine(date.today(), datetime.min.time())
|
||||
today_end = datetime.combine(date.today(), datetime.max.time())
|
||||
|
||||
reservations = Reservation.query.options(
|
||||
joinedload(Reservation.classroom),
|
||||
joinedload(Reservation.commission).joinedload(Commission.subject).joinedload(Subject.career_obj)
|
||||
).filter(
|
||||
Reservation.start_time >= today_start,
|
||||
Reservation.start_time <= today_end
|
||||
).order_by(Reservation.start_time).all()
|
||||
|
||||
events = []
|
||||
for reservation in reservations:
|
||||
subject = reservation.commission.subject if (reservation.commission and reservation.commission.subject) else None
|
||||
subject_code = subject.code if subject else (reservation.commission.code if reservation.commission else '')
|
||||
subject_name = subject.name if subject else (reservation.purpose or 'Clase')
|
||||
classroom_name = reservation.classroom.code if reservation.classroom else 'Sin Aula'
|
||||
status_val = str(reservation.status.value if hasattr(reservation.status, 'value') else reservation.status)
|
||||
|
||||
events.append({
|
||||
'id': reservation.id,
|
||||
'title': f"{subject_name} ({subject_code}) - {classroom_name}",
|
||||
'start': reservation.start_time.isoformat(),
|
||||
'end': reservation.end_time.isoformat(),
|
||||
'url': url_for('schedule.view_reservation', id=reservation.id) if reservation.id else None,
|
||||
'extendedProps': {
|
||||
'subject_code': subject_code,
|
||||
'subject_name': subject_name,
|
||||
'classroom': classroom_name,
|
||||
'purpose': reservation.purpose or 'No purpose',
|
||||
'attendees': reservation.expected_attendees,
|
||||
'status': status_val
|
||||
}
|
||||
})
|
||||
|
||||
return jsonify({'events': events})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
@@ -19,7 +19,7 @@ class ClassroomBaseDTO(BaseModel):
|
||||
@field_validator('floor')
|
||||
@classmethod
|
||||
def clean_floor(cls, v: str) -> str:
|
||||
return str(v).strip() or "PB"
|
||||
return v.strip() or "PB"
|
||||
|
||||
class ClassroomCreateDTO(ClassroomBaseDTO):
|
||||
building_id: Optional[int] = Field(default=None, description="ID del edificio asignado")
|
||||
|
||||
@@ -47,3 +47,36 @@ class SpringBootSyncPayloadDTO(BaseModel):
|
||||
commissions: List[SpringBootCommissionDTO] = Field(..., min_length=1)
|
||||
classrooms: Optional[List[SpringBootClassroomDTO]] = None
|
||||
options: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class GeneticPreviewRequestDTO(BaseModel):
|
||||
"""Contrato para la previsualización heurística de asignaciones."""
|
||||
commission_ids: List[int] = Field(..., min_length=1, description="Lista de IDs de comisiones a previsualizar")
|
||||
dry_run: bool = Field(default=True, description="Indicador de simulación sin persistencia")
|
||||
|
||||
@field_validator('commission_ids')
|
||||
@classmethod
|
||||
def validate_ids(cls, v: List[int]) -> List[int]:
|
||||
if not v or len(v) == 0:
|
||||
raise ValueError("Debe suministrar al menos una comisión para previsualizar.")
|
||||
return list(set(v))
|
||||
|
||||
|
||||
class GeneticOptimizeRequestDTO(BaseModel):
|
||||
"""Contrato para la ejecución completa del algoritmo genético."""
|
||||
commission_ids: List[int] = Field(..., min_length=1, description="Lista de IDs de comisiones a optimizar")
|
||||
start_date: Optional[datetime] = Field(None, description="Fecha de inicio (ISO format)")
|
||||
end_date: Optional[datetime] = Field(None, description="Fecha de fin (ISO format)")
|
||||
|
||||
@field_validator('commission_ids')
|
||||
@classmethod
|
||||
def validate_ids(cls, v: List[int]) -> List[int]:
|
||||
if not v or len(v) == 0:
|
||||
raise ValueError("Debe suministrar al menos una comisión para optimizar.")
|
||||
return list(set(v))
|
||||
|
||||
|
||||
class GeneticApplyRequestDTO(BaseModel):
|
||||
"""Contrato para aplicar las reservas optimizadas en Bedelía."""
|
||||
reservations: List[Dict[str, Any]] = Field(..., min_length=1, description="Lista de reservas a persistir")
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
"""Módulo de Seguridad Empresarial inspirado en Spring Security (SecurityFilterChain, RBAC y Auditoría)."""
|
||||
from app.security.filter_chain import SecurityFilterChain
|
||||
from app.security.decorators import require_permission
|
||||
|
||||
__all__ = [
|
||||
'SecurityFilterChain',
|
||||
'require_permission'
|
||||
]
|
||||
@@ -1,45 +0,0 @@
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, redirect, url_for, flash, abort, g
|
||||
from flask_login import current_user
|
||||
|
||||
def require_permission(module: str, min_level: str = 'read'):
|
||||
"""
|
||||
Decorador de seguridad declarativa a nivel de método inspirado en @PreAuthorize de Spring Security.
|
||||
Verifica los privilegios del usuario autenticado (tanto en sesiones web como en API JWT).
|
||||
|
||||
Niveles de permiso estándar:
|
||||
- 'read': Permiso de lectura / consulta
|
||||
- 'read_write': Permiso de modificación y creación
|
||||
- 'admin': Permiso de control total
|
||||
"""
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = None
|
||||
# Evaluar contexto JWT primero si está presente
|
||||
if hasattr(g, 'jwt_user') and g.jwt_user:
|
||||
user = g.jwt_user
|
||||
elif current_user and current_user.is_authenticated:
|
||||
user = current_user
|
||||
|
||||
is_api = request.path.startswith('/api/') or request.is_json
|
||||
|
||||
if not user:
|
||||
if is_api:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Autenticación requerida.'}), 401
|
||||
flash('Debe iniciar sesión para acceder a este recurso.', 'warning')
|
||||
return redirect(url_for('auth.login', next=request.url))
|
||||
|
||||
# Comprobar privilegios en la matriz RBAC
|
||||
if not user.has_permission(module, min_level):
|
||||
if is_api:
|
||||
return jsonify({
|
||||
'error': 'Forbidden',
|
||||
'message': f'Permiso insuficiente en módulo "{module}". Nivel requerido: "{min_level}".'
|
||||
}), 403
|
||||
flash(f'No posee permisos suficientes ({min_level}) para gestionar {module}.', 'danger')
|
||||
abort(403)
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
@@ -1,89 +0,0 @@
|
||||
from flask import request, jsonify, g, render_template, Response
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Tuple
|
||||
import time
|
||||
|
||||
class SecurityFilterChain:
|
||||
"""
|
||||
Pipeline centralizado de interceptación de seguridad (SecurityFilterChain)
|
||||
inspirado en el patrón arquitectónico de Spring Security.
|
||||
|
||||
Capas de filtrado activas:
|
||||
1. Security Headers Filter (Blindaje HTTP en todas las respuestas).
|
||||
2. Rate Limiting Filter (Protección contra fuerza bruta y DoS).
|
||||
3. Bearer Token Context Filter (Inyección de identidad contextual).
|
||||
"""
|
||||
|
||||
def __init__(self, app=None):
|
||||
# Registro de timestamps de peticiones por IP: ip -> [timestamps]
|
||||
self._request_history: Dict[str, List[float]] = {}
|
||||
# Límites por endpoint sensible (max_requests, window_seconds)
|
||||
self._rate_limits = {
|
||||
'/login': (15, 60),
|
||||
'/api/v1/auth/login': (15, 60),
|
||||
'/api/v1/auth/refresh': (30, 60)
|
||||
}
|
||||
if app:
|
||||
self.init_app(app)
|
||||
|
||||
def init_app(self, app):
|
||||
"""Registra los filtros en el ciclo de vida de la aplicación Flask."""
|
||||
app.before_request(self._execute_pre_filters)
|
||||
app.after_request(self._execute_post_filters)
|
||||
|
||||
def _get_client_ip(self) -> str:
|
||||
"""Obtiene la IP real del cliente respetando proxies inversos de confianza."""
|
||||
if request.headers.get('X-Forwarded-For'):
|
||||
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
|
||||
return request.remote_addr or '127.0.0.1'
|
||||
|
||||
def _execute_pre_filters(self):
|
||||
"""Ejecuta los filtros previos al enrutamiento del controlador."""
|
||||
path = request.path
|
||||
|
||||
# 1. Rate Limiting Filter (solo para peticiones POST de autenticación sensible)
|
||||
if path in self._rate_limits:
|
||||
# Peticiones GET para cargar la interfaz web NO consumen intentos de fuerza bruta
|
||||
if request.method != 'POST':
|
||||
return
|
||||
|
||||
max_req, window = self._rate_limits[path]
|
||||
client_ip = self._get_client_ip()
|
||||
now = time.time()
|
||||
|
||||
# Limpiar historial fuera de la ventana
|
||||
timestamps = self._request_history.get(client_ip, [])
|
||||
timestamps = [t for t in timestamps if now - t < window]
|
||||
|
||||
if len(timestamps) >= max_req:
|
||||
retry_after = max(1, int(window - (now - timestamps[0])))
|
||||
if path.startswith('/api/'):
|
||||
return jsonify({
|
||||
'error': 'TooManyRequests',
|
||||
'message': f'Límite de peticiones excedido. Reintente en {retry_after} segundos.'
|
||||
}), 429
|
||||
|
||||
# Para la web, renderizar vista o respuesta legible
|
||||
return Response(
|
||||
f"Demasiados intentos de autenticación desde su dirección IP. Por favor espere {retry_after} segundos antes de volver a intentar.",
|
||||
status=429,
|
||||
mimetype='text/plain; charset=utf-8'
|
||||
)
|
||||
|
||||
timestamps.append(now)
|
||||
self._request_history[client_ip] = timestamps
|
||||
|
||||
def _execute_post_filters(self, response):
|
||||
"""Inyecta cabeceras de blindaje HTTP (OWASP Secure Headers)."""
|
||||
# Evitar ataques de MIME-Sniffing
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
# Mitigación de Clickjacking
|
||||
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
|
||||
# Mitigación XSS en navegadores legacy
|
||||
response.headers['X-XSS-Protection'] = '1; mode=block'
|
||||
# Política de Referrer segura
|
||||
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
|
||||
# Inyección HSTS (si es HTTPS o entorno de producción)
|
||||
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,170 @@
|
||||
import re
|
||||
from typing import Tuple, Optional, Dict
|
||||
|
||||
|
||||
def limpiar_numero_documento(doc_raw: str) -> Tuple[str, Optional[str]]:
|
||||
"""
|
||||
Limpia y normaliza un número de documento DNI argentino.
|
||||
En formatos antiguos (Libreta Cívica, Libreta de Enrolamiento o Formato 2009),
|
||||
el documento suele estar precedido por 'F' (Femenino) o 'M' (Masculino),
|
||||
por ejemplo: 'F5592570' -> ('5592570', 'F'), 'M34247025' -> ('34247025', 'M').
|
||||
Retorna (documento_numerico, sexo_inferido).
|
||||
"""
|
||||
if not doc_raw:
|
||||
return "", None
|
||||
doc_clean = doc_raw.strip()
|
||||
|
||||
# Limpiar prefijos comunes como 'DNI:', 'DNI ', 'D.N.I.:', 'D.N.I. ', 'DOC:', 'DOCUMENTO:'
|
||||
doc_clean = re.sub(r'^(?:DNI|D\.N\.I\.|DOC|DOCUMENTO)[\s\:\-\.]*', '', doc_clean, flags=re.IGNORECASE).strip()
|
||||
|
||||
doc_sin_puntos = doc_clean.replace('.', '').replace(',', '').replace(' ', '').replace('-', '')
|
||||
|
||||
# Patrón: Prefijo F o M seguido de 5 a 9 dígitos
|
||||
m = re.match(r'^([FMfm])(\d{5,9})$', doc_sin_puntos)
|
||||
if m:
|
||||
return m.group(2), m.group(1).upper()
|
||||
|
||||
# Si contiene dígitos precedidos por F/M con posibles espacios o puntos
|
||||
m2 = re.match(r'^([FMfm])[\s\.]*(\d{5,9})$', doc_clean)
|
||||
if m2:
|
||||
return m2.group(2), m2.group(1).upper()
|
||||
|
||||
return doc_sin_puntos if doc_sin_puntos.isdigit() else doc_clean, None
|
||||
|
||||
|
||||
def parsear_dni(raw_text: str) -> Dict[str, str]:
|
||||
"""
|
||||
Parsea la cadena de texto cruda obtenida de un escáner de código de barras/QR de un DNI argentino.
|
||||
Soporta los formatos 2009, 2012, 2026 y App Mi Argentina.
|
||||
|
||||
Retorna un diccionario con las llaves: 'documento', 'apellido', 'nombre', 'sexo'
|
||||
o un diccionario vacío si no corresponde a un documento de identidad argentino.
|
||||
"""
|
||||
if not raw_text:
|
||||
return {}
|
||||
|
||||
# Limpiar terminadores y retornos de carro
|
||||
raw_clean = raw_text.strip().replace('\r', '').replace('\n', '')
|
||||
|
||||
# Algunos escáneres o formatos vienen separados por @, comillas simples ', barras | o punto y coma ;
|
||||
text = raw_clean.replace('@', '"').replace("'", '"').replace('´', '"').replace('|', '"').replace(';', '"')
|
||||
parts = text.split('"')
|
||||
|
||||
# Limpiar espacios de cada segmento
|
||||
parts = [p.strip() for p in parts]
|
||||
|
||||
if len(parts) < 5:
|
||||
# Si es un ingreso directo de DNI (escaneado de tarjeta de código de barras 1D o tipeado)
|
||||
doc_limpio, sexo_inf = limpiar_numero_documento(raw_clean)
|
||||
if doc_limpio and doc_limpio.isdigit() and 5 <= len(doc_limpio) <= 9:
|
||||
return {
|
||||
"documento": doc_limpio,
|
||||
"apellido": "",
|
||||
"nombre": "",
|
||||
"sexo": sexo_inf or "M"
|
||||
}
|
||||
return {}
|
||||
|
||||
doc = nombre = apellido = sexo = ""
|
||||
|
||||
# Heurística para Formato 2009 con comilla inicial
|
||||
# Ej: "34247025"A"1"TELLO"CARLOS FACUNDO"...
|
||||
# Ej: "F5592570 "A"1"SAUCEDO"TERESA DE JESUS"...
|
||||
if parts[0] == '' and 6 <= len(parts[1]) <= 11 and len(parts) > 2 and parts[2].isalpha() and len(parts[2]) == 1:
|
||||
doc = parts[1]
|
||||
if len(parts) > 4:
|
||||
apellido = parts[4]
|
||||
if len(parts) > 5:
|
||||
nombre = parts[5]
|
||||
# Búsqueda de sexo en posiciones subsiguientes (índices 6 a 9)
|
||||
for idx in range(6, min(len(parts), 10)):
|
||||
val = parts[idx].upper()
|
||||
if val in ("M", "F", "X"):
|
||||
sexo = val
|
||||
break
|
||||
|
||||
# Heurística para Formato 2009 sin comilla inicial
|
||||
# Ej: 34247025"A"1"TELLO"CARLOS FACUNDO...
|
||||
# Ej: F5592570"A"1"SAUCEDO"TERESA DE JESUS...
|
||||
elif 6 <= len(parts[0]) <= 11 and len(parts) > 4 and parts[1].isalpha() and len(parts[1]) == 1:
|
||||
doc = parts[0]
|
||||
apellido = parts[3]
|
||||
nombre = parts[4]
|
||||
for idx in range(5, min(len(parts), 9)):
|
||||
val = parts[idx].upper()
|
||||
if val in ("M", "F", "X"):
|
||||
sexo = val
|
||||
break
|
||||
|
||||
# Heurística para Formatos 2012, 2026 y App Mi Argentina (Comienzan con número de trámite >= 8 dígitos)
|
||||
else:
|
||||
# Si la cadena comenzó con comilla/arroba y no es formato 2009, normalizamos descartando el elemento vacío inicial
|
||||
if parts[0] == '' and len(parts) > 1:
|
||||
parts = parts[1:]
|
||||
|
||||
if parts[0].isdigit() and len(parts[0]) >= 8:
|
||||
apellido = parts[1] if len(parts) > 1 else ""
|
||||
nombre = parts[2] if len(parts) > 2 else ""
|
||||
|
||||
if len(parts) > 3:
|
||||
p3 = parts[3].strip()
|
||||
p4 = parts[4].strip() if len(parts) > 4 else ""
|
||||
|
||||
# Caso 1: Formato 2012 (parts[3] es letra de sexo M, F, X)
|
||||
# 00680051210"TELLO"CARLOS FACUNDO"M"34247025...
|
||||
if len(p3) == 1 and p3.upper() in ("M", "F", "X"):
|
||||
sexo = p3.upper()
|
||||
if len(parts) > 4:
|
||||
doc = p4
|
||||
|
||||
# Caso 2: Formato App Mi Argentina (parts[3] es código numérico de sexo 1=M, 2=F, 3=X)
|
||||
# y parts[4] es el DNI numérico (6 a 9 dígitos)
|
||||
# Ej: 00305336518@CIRILLI@GEORGINA SUSANA@2@28988082@A@23/08/1981@13/10/2014
|
||||
# Ej: 00680051210@TELLO@Carlos Facundo@1@34247025@F@09/02/1989@13/10/2021
|
||||
elif p3 in ("1", "2", "3", "0") and p4.isdigit() and 6 <= len(p4) <= 9:
|
||||
if p3 == "1":
|
||||
sexo = "M"
|
||||
elif p3 == "2":
|
||||
sexo = "F"
|
||||
else:
|
||||
sexo = "X"
|
||||
doc = p4
|
||||
|
||||
# Caso 3: Formato 2026 (parts[3] es directamente el DNI de 6 a 9 dígitos)
|
||||
# y parts[4] suele ser ejemplar o sexo alfabético (ej. 'G', 'F', 'M')
|
||||
# 00749743816"TELLO"CARLOS FACUNDO"34247025"G...
|
||||
elif p3.isdigit() and 6 <= len(p3) <= 9 and not (p4.isdigit() and 6 <= len(p4) <= 9):
|
||||
doc = p3
|
||||
if p4.upper() in ("M", "F", "X"):
|
||||
sexo = p4.upper()
|
||||
elif p4.upper() == "G":
|
||||
sexo = "M"
|
||||
|
||||
# Caso 4: Desempate general: si parts[4] es un DNI numérico válido de 6 a 9 dígitos
|
||||
elif p4.isdigit() and 6 <= len(p4) <= 9:
|
||||
doc = p4
|
||||
if p3 == "1":
|
||||
sexo = "M"
|
||||
elif p3 == "2":
|
||||
sexo = "F"
|
||||
elif p3.upper() in ("M", "F", "X"):
|
||||
sexo = p3.upper()
|
||||
else:
|
||||
# Fallback final
|
||||
doc = p3
|
||||
|
||||
# Normalización del documento extraído (eliminación de prefijos F/M en DNI viejo)
|
||||
doc_limpio, sexo_doc = limpiar_numero_documento(doc)
|
||||
doc = doc_limpio
|
||||
if not sexo and sexo_doc:
|
||||
sexo = sexo_doc
|
||||
|
||||
if not doc or not doc.isdigit() or not (5 <= len(doc) <= 9):
|
||||
return {}
|
||||
|
||||
return {
|
||||
"documento": doc.strip(),
|
||||
"apellido": apellido.upper() if apellido else "",
|
||||
"nombre": nombre.upper() if nombre else "",
|
||||
"sexo": sexo or "M"
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Optional, List, Dict, Any
|
||||
from flask import request, g, has_request_context
|
||||
from flask_login import current_user
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
import json
|
||||
from sqlalchemy import or_
|
||||
from app import db
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.models.user import User
|
||||
@@ -10,34 +9,47 @@ class AuditService:
|
||||
"""Servicio para la captura y consulta de la bitácora inmutable de auditoría."""
|
||||
|
||||
@staticmethod
|
||||
def log(action: str, module: str, entity_id: Optional[int] = None,
|
||||
details: Optional[Any] = None, user: Optional[User] = None,
|
||||
ip_address: Optional[str] = None) -> AuditLog:
|
||||
def log(action: str, module: str, entity_id: Optional[Any] = None,
|
||||
details: Optional[Any] = None, user: Optional[Any] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
user_id: Optional[Any] = None,
|
||||
user_email: Optional[Any] = None,
|
||||
status: Optional[str] = None,
|
||||
**kwargs) -> Optional[AuditLog]:
|
||||
"""
|
||||
Registra un evento de auditoría de forma segura, infiriendo el usuario e IP
|
||||
desde el contexto actual de la petición si no se especifican.
|
||||
Registra un evento de auditoría de forma segura e inmutable.
|
||||
"""
|
||||
user_id = None
|
||||
user_email = None
|
||||
if status:
|
||||
if isinstance(details, dict):
|
||||
details['status'] = status
|
||||
elif details:
|
||||
details = f"[{status.upper()}] {details}"
|
||||
else:
|
||||
details = {'status': status}
|
||||
|
||||
# 1. Determinar usuario actuante
|
||||
if user:
|
||||
user_id = user.id
|
||||
user_email = user.email
|
||||
elif has_request_context():
|
||||
if hasattr(g, 'jwt_user') and g.jwt_user:
|
||||
user_id = g.jwt_user.id
|
||||
user_email = g.jwt_user.email
|
||||
elif current_user and current_user.is_authenticated:
|
||||
user_id = current_user.id
|
||||
user_email = current_user.email
|
||||
user_id = getattr(user, 'id', None)
|
||||
user_email = getattr(user, 'email', None)
|
||||
|
||||
# 2. Determinar IP de origen
|
||||
if not ip_address and has_request_context():
|
||||
if request.headers.get('X-Forwarded-For'):
|
||||
ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
|
||||
else:
|
||||
ip_address = request.remote_addr
|
||||
if user_id is not None:
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if user_email is not None:
|
||||
user_email = str(user_email)
|
||||
|
||||
if entity_id is not None:
|
||||
try:
|
||||
entity_id = int(entity_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. IP de origen
|
||||
if not ip_address:
|
||||
ip_address = '127.0.0.1'
|
||||
|
||||
# 3. Serializar detalles si es estructura de datos
|
||||
details_str = None
|
||||
@@ -50,27 +62,75 @@ class AuditService:
|
||||
else:
|
||||
details_str = str(details)
|
||||
|
||||
log_entry = AuditLog(
|
||||
user_id=user_id,
|
||||
user_email=user_email,
|
||||
action=action.upper(),
|
||||
module=module.lower(),
|
||||
audit_entry = AuditLog(
|
||||
action=action,
|
||||
module=module,
|
||||
entity_id=entity_id,
|
||||
details=details_str,
|
||||
user_id=user_id,
|
||||
user_email=user_email,
|
||||
ip_address=ip_address
|
||||
)
|
||||
|
||||
try:
|
||||
db.session.add(log_entry)
|
||||
db.session.add(audit_entry)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
return log_entry
|
||||
return audit_entry
|
||||
|
||||
@staticmethod
|
||||
def get_recent_logs(limit: int = 50, module: Optional[str] = None) -> List[AuditLog]:
|
||||
"""Obtiene las entradas más recientes de auditoría."""
|
||||
def get_logs(module: Optional[str] = None, action: Optional[str] = None,
|
||||
user_id: Optional[int] = None, limit: int = 50) -> List[AuditLog]:
|
||||
"""Recupera los eventos más recientes con filtros opcionales."""
|
||||
query = AuditLog.query
|
||||
|
||||
if module:
|
||||
query = query.filter_by(module=module.lower())
|
||||
query = query.filter(AuditLog.module == module)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action)
|
||||
if user_id:
|
||||
query = query.filter(AuditLog.user_id == user_id)
|
||||
|
||||
return query.order_by(AuditLog.created_at.desc()).limit(limit).all()
|
||||
|
||||
@staticmethod
|
||||
def get_paginated_logs(
|
||||
module: Optional[str] = None,
|
||||
action: Optional[str] = None,
|
||||
user_id: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
page: int = 1,
|
||||
per_page: int = 25
|
||||
) -> Tuple[List[AuditLog], int]:
|
||||
"""Recupera eventos de auditoría con filtros SQL, búsqueda y paginación server-side."""
|
||||
query = AuditLog.query
|
||||
|
||||
if module:
|
||||
query = query.filter(AuditLog.module == module)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action)
|
||||
if user_id:
|
||||
query = query.filter(AuditLog.user_id == user_id)
|
||||
if search:
|
||||
s_clean = search.strip().lower()
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.details.ilike(f'%{s_clean}%'),
|
||||
AuditLog.user_email.ilike(f'%{s_clean}%'),
|
||||
AuditLog.action.ilike(f'%{s_clean}%'),
|
||||
AuditLog.module.ilike(f'%{s_clean}%'),
|
||||
AuditLog.ip_address.ilike(f'%{s_clean}%')
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
logs = query.order_by(AuditLog.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all()
|
||||
return logs, total
|
||||
|
||||
@staticmethod
|
||||
def get_recent_logs(limit: int = 50, module: Optional[str] = None,
|
||||
action: Optional[str] = None) -> List[AuditLog]:
|
||||
return AuditService.get_logs(module=module, action=action, limit=limit)
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ class CacheService:
|
||||
if not cls._redis_checked:
|
||||
cls._redis_checked = True
|
||||
try:
|
||||
import redis
|
||||
import redis # type: ignore
|
||||
from app.models.setting import SystemSetting
|
||||
redis_url = SystemSetting.get_value('redis_url', 'redis://127.0.0.1:6379/0')
|
||||
client = redis.from_url(redis_url, socket_connect_timeout=2)
|
||||
|
||||
@@ -77,31 +77,35 @@ class ClassroomService:
|
||||
if not classroom:
|
||||
raise ValueError(f"Aula con ID {classroom_id} no encontrada.")
|
||||
|
||||
building_id = dto.building_id if dto.building_id is not None else classroom.building_id
|
||||
code = dto.code.strip() if dto.code is not None else classroom.code
|
||||
floor = dto.floor.strip() if dto.floor is not None else classroom.floor
|
||||
curr_building_id = int(getattr(classroom, 'building_id', 0) or 0)
|
||||
curr_code = str(getattr(classroom, 'code', '') or '')
|
||||
curr_floor = str(getattr(classroom, 'floor', '') or '')
|
||||
|
||||
building_id = dto.building_id if dto.building_id is not None else curr_building_id
|
||||
code = dto.code.strip() if dto.code is not None else curr_code
|
||||
floor = dto.floor.strip() if dto.floor is not None else curr_floor
|
||||
|
||||
# Si cambia código, piso o edificio, validar colisión
|
||||
if (building_id != classroom.building_id or code != classroom.code or floor != classroom.floor):
|
||||
if (building_id != curr_building_id or code != curr_code or floor != curr_floor):
|
||||
existing = self.repository.get_by_code_and_building(building_id, code, floor)
|
||||
if existing and existing.id != classroom.id:
|
||||
if existing and getattr(existing, 'id', None) != getattr(classroom, 'id', None):
|
||||
raise ValueError(f"Ya existe otra aula con el código '{code}' en el piso {floor}.")
|
||||
|
||||
if dto.building_id is not None:
|
||||
building = Building.query.get(dto.building_id)
|
||||
if building:
|
||||
classroom.building_id = building.id
|
||||
classroom.building = building.name
|
||||
setattr(classroom, 'building_id', getattr(building, 'id'))
|
||||
setattr(classroom, 'building', getattr(building, 'name'))
|
||||
if dto.code is not None:
|
||||
classroom.code = code
|
||||
setattr(classroom, 'code', code)
|
||||
if dto.floor is not None:
|
||||
classroom.floor = floor
|
||||
setattr(classroom, 'floor', floor)
|
||||
if dto.capacity is not None:
|
||||
classroom.capacity = dto.capacity
|
||||
setattr(classroom, 'capacity', dto.capacity)
|
||||
if dto.description is not None:
|
||||
classroom.description = dto.description
|
||||
setattr(classroom, 'description', dto.description)
|
||||
if dto.is_active is not None:
|
||||
classroom.is_active = dto.is_active
|
||||
setattr(classroom, 'is_active', dto.is_active)
|
||||
|
||||
return self.repository.save(classroom)
|
||||
|
||||
@@ -111,8 +115,8 @@ class ClassroomService:
|
||||
if not classroom:
|
||||
return False
|
||||
# Si tiene reservas históricas, se desactiva lógicamente para preservar integridad
|
||||
if classroom.reservations:
|
||||
classroom.is_active = False
|
||||
if getattr(classroom, 'reservations', None):
|
||||
setattr(classroom, 'is_active', False)
|
||||
self.repository.save(classroom)
|
||||
return True
|
||||
return self.repository.delete(classroom)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from typing import Any
|
||||
from cryptography.fernet import Fernet
|
||||
from flask import current_app
|
||||
from config.config import Config
|
||||
|
||||
class CryptoService:
|
||||
"""
|
||||
@@ -11,11 +12,8 @@ class CryptoService:
|
||||
|
||||
@staticmethod
|
||||
def _get_fernet() -> Fernet:
|
||||
# Derivar clave válida para Fernet (32 bytes urlsafe base64) desde SECRET_KEY
|
||||
try:
|
||||
secret = current_app.config.get('SECRET_KEY', 'default-unicaba-edu-space-secret-key-32b!')
|
||||
except RuntimeError:
|
||||
secret = 'default-unicaba-edu-space-secret-key-32b!'
|
||||
# Derivar clave válida para Fernet (32 bytes urlsafe base64) desde Config.SECRET_KEY
|
||||
secret = Config.SECRET_KEY or 'default-unicaba-edu-space-secret-key-32b!'
|
||||
|
||||
# Hash SHA-256 para obtener 32 bytes y codificar en base64 seguro para URL
|
||||
key = base64.urlsafe_b64encode(hashlib.sha256(secret.encode('utf-8')).digest())
|
||||
@@ -31,16 +29,18 @@ class CryptoService:
|
||||
return encrypted_bytes.decode('utf-8')
|
||||
|
||||
@classmethod
|
||||
def decrypt(cls, cipher_text: str) -> str:
|
||||
def decrypt(cls, cipher_text: Any) -> str:
|
||||
"""Descifra un texto cifrado y retorna el texto original. Si falla, retorna vacío."""
|
||||
if not cipher_text:
|
||||
return ''
|
||||
cipher_str = str(cipher_text)
|
||||
try:
|
||||
fernet = cls._get_fernet()
|
||||
decrypted_bytes = fernet.decrypt(cipher_text.encode('utf-8'))
|
||||
decrypted_bytes = fernet.decrypt(cipher_str.encode('utf-8'))
|
||||
return decrypted_bytes.decode('utf-8')
|
||||
except Exception:
|
||||
# Si no era un texto cifrado con Fernet o fue alterado, retornar el texto tal cual o vacío
|
||||
return cipher_text
|
||||
return cipher_str
|
||||
|
||||
crypto_service = CryptoService()
|
||||
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
"""
|
||||
Dashboard Service for admin-edu-space
|
||||
Decoupled analytics, operational statistics, and Google Sheets integration without any Flask dependencies.
|
||||
"""
|
||||
import calendar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Dict, Any, List
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject, Commission
|
||||
from app.models.career import Career
|
||||
from app.models.user import User
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.models.milestone import AcademicMilestone
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.audit_service import AuditService
|
||||
from app.services.sheets_importer import GoogleSheetsImporter
|
||||
|
||||
|
||||
class DashboardService:
|
||||
@staticmethod
|
||||
def serialize_reservation(r: Reservation) -> Dict[str, Any]:
|
||||
subject_name = (r.commission.subject.name if (r.commission and r.commission.subject) else r.purpose) or 'Actividad Académica'
|
||||
subject_code = (r.commission.subject.code if (r.commission and r.commission.subject) else '')
|
||||
classroom_code = r.classroom.code if r.classroom else 'Sin Aula'
|
||||
is_virtual = ('virtual' in classroom_code.lower()) or (getattr(r.classroom, 'is_virtual', False) if r.classroom else False)
|
||||
return {
|
||||
'id': r.id,
|
||||
'start_time': r.start_time.strftime('%H:%M') if r.start_time else '',
|
||||
'end_time': r.end_time.strftime('%H:%M') if r.end_time else '',
|
||||
'date_display': r.start_time.strftime('%d/%m') if r.start_time else '',
|
||||
'classroom': {
|
||||
'id': r.classroom_id,
|
||||
'code': classroom_code,
|
||||
'is_virtual': is_virtual,
|
||||
'location_display': getattr(r.classroom, 'location_display', f'Sede Central · {classroom_code}') if r.classroom else 'Sin Aula'
|
||||
},
|
||||
'subject_name': subject_name,
|
||||
'subject_code': subject_code,
|
||||
'shift': r.shift or 'Mañana',
|
||||
'commission': {
|
||||
'id': r.commission_id,
|
||||
'code': r.commission.code if r.commission else 'COM-1'
|
||||
},
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'user': {
|
||||
'id': r.user_id,
|
||||
'name': r.user.name if r.user else 'Docente'
|
||||
},
|
||||
'virtual_link': r.virtual_link or ('https://meet.google.com/edu-space-' + classroom_code.lower().replace(' ', '-') if is_virtual else '')
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def serialize_milestone(m: AcademicMilestone) -> Dict[str, Any]:
|
||||
return {
|
||||
'id': m.id,
|
||||
'title': m.title,
|
||||
'materia_codigo': m.materia_codigo,
|
||||
'subject_name': m.subject.name if (hasattr(m, 'subject') and m.subject) else m.materia_codigo,
|
||||
'date': m.date.strftime('%d/%m/%Y') if m.date else '',
|
||||
'type_obj': {
|
||||
'name': m.type_obj.name if m.type_obj else 'Evaluación',
|
||||
'color': m.type_obj.color if m.type_obj else '#0d6efd'
|
||||
},
|
||||
'classroom': m.classroom or 'Sede Central',
|
||||
'link': m.link or '',
|
||||
'notes': m.notes or ''
|
||||
}
|
||||
|
||||
def get_stats(self, current_user: Optional[User] = None) -> Dict[str, Any]:
|
||||
today = datetime.now(timezone.utc).date()
|
||||
|
||||
total_classrooms = 0
|
||||
total_subjects = 0
|
||||
total_users = 0
|
||||
today_reservations = 0
|
||||
pending_count = 0
|
||||
physical_classrooms = 0
|
||||
virtual_classrooms = 0
|
||||
occupancy_rate = 0
|
||||
assigned_classrooms = 0
|
||||
assigned_pct = 0.0
|
||||
unassigned_classrooms = 0
|
||||
unassigned_pct = 0.0
|
||||
assigned_today_count = 0
|
||||
assigned_today_pct = 0.0
|
||||
unassigned_today_count = 0
|
||||
unassigned_today_pct = 0.0
|
||||
total_active_commissions = 0
|
||||
tomorrow_reservations_q: List[Reservation] = []
|
||||
my_today_count = 0
|
||||
my_total_reservations = 0
|
||||
my_today_classes: List[Dict[str, Any]] = []
|
||||
tomorrow_schedule_list: List[Dict[str, Any]] = []
|
||||
filter_stats: Dict[str, Any] = {}
|
||||
date_labels: Dict[str, Any] = {}
|
||||
unassigned_commissions_tomorrow: List[Dict[str, Any]] = []
|
||||
unassigned_commissions_week: List[Dict[str, Any]] = []
|
||||
unassigned_commissions_month: List[Dict[str, Any]] = []
|
||||
unassigned_commissions_general: List[Dict[str, Any]] = []
|
||||
available_classrooms_today: List[Dict[str, Any]] = []
|
||||
available_classrooms_tomorrow: List[Dict[str, Any]] = []
|
||||
available_classrooms_week: List[Dict[str, Any]] = []
|
||||
available_classrooms_month: List[Dict[str, Any]] = []
|
||||
virtual_rooms_data: List[Dict[str, Any]] = []
|
||||
audit_data: List[Dict[str, Any]] = []
|
||||
pending_reservations: List[Dict[str, Any]] = []
|
||||
today_schedule_list: List[Dict[str, Any]] = []
|
||||
week_schedule_list: List[Dict[str, Any]] = []
|
||||
upcoming_reservations: List[Dict[str, Any]] = []
|
||||
milestones: List[Dict[str, Any]] = []
|
||||
|
||||
try:
|
||||
total_classrooms = Classroom.query.filter_by(is_active=True).count()
|
||||
total_subjects = Subject.query.filter_by(is_active=True).count()
|
||||
total_users = User.query.filter_by(is_active=True).count()
|
||||
|
||||
# Aulas presenciales y virtuales
|
||||
all_active_classrooms = Classroom.query.filter_by(is_active=True).all()
|
||||
virtual_classrooms_list = [
|
||||
c for c in all_active_classrooms
|
||||
if getattr(c, 'is_virtual', False)
|
||||
or 'virtual' in (c.building or '').lower()
|
||||
or 'virtual' in (c.code or '').lower()
|
||||
]
|
||||
virtual_classrooms = len(virtual_classrooms_list)
|
||||
|
||||
physical_classrooms_list = [
|
||||
c for c in all_active_classrooms
|
||||
if c not in virtual_classrooms_list
|
||||
]
|
||||
total_physical_count = len(physical_classrooms_list)
|
||||
physical_classrooms = total_physical_count
|
||||
physical_ids = set(c.id for c in physical_classrooms_list)
|
||||
|
||||
# 1. Asignación General del Cuatrimestre / Cronograma
|
||||
assigned_all_ids = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id)
|
||||
.filter(Reservation.classroom_id.isnot(None)).distinct().all()
|
||||
)
|
||||
assigned_physical_ids = physical_ids.intersection(assigned_all_ids)
|
||||
assigned_classrooms = len(assigned_physical_ids)
|
||||
unassigned_classrooms = max(0, total_physical_count - assigned_classrooms)
|
||||
|
||||
assigned_pct = round((assigned_classrooms / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0
|
||||
unassigned_pct = round(100.0 - assigned_pct, 1) if total_physical_count > 0 else 0.0
|
||||
|
||||
# 2. Asignación Operativa del Día de Hoy
|
||||
assigned_today_ids = set(
|
||||
r[0] for r in db.session.query(Reservation.classroom_id).filter(
|
||||
Reservation.classroom_id.isnot(None),
|
||||
func.date(Reservation.start_time) == today
|
||||
).distinct().all()
|
||||
)
|
||||
assigned_today_physical_ids = physical_ids.intersection(assigned_today_ids)
|
||||
assigned_today_count = len(assigned_today_physical_ids)
|
||||
unassigned_today_count = max(0, total_physical_count - assigned_today_count)
|
||||
|
||||
assigned_today_pct = round((assigned_today_count / max(1, total_physical_count)) * 100, 1) if total_physical_count > 0 else 0.0
|
||||
unassigned_today_pct = round(100.0 - assigned_today_pct, 1) if total_physical_count > 0 else 0.0
|
||||
|
||||
today_reservations_q = Reservation.query.filter(
|
||||
func.date(Reservation.start_time) == today
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
today_reservations = len(today_reservations_q)
|
||||
|
||||
pending_reservations_q = Reservation.query.filter(
|
||||
Reservation.status == 'PENDING'
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
pending_count = len(pending_reservations_q)
|
||||
|
||||
upcoming_reservations_q = Reservation.query.filter(
|
||||
Reservation.start_time >= datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
).order_by(Reservation.start_time.asc()).limit(10).all()
|
||||
|
||||
milestones_q = AcademicMilestone.query.filter(
|
||||
AcademicMilestone.is_active == True
|
||||
).order_by(AcademicMilestone.date.asc()).limit(10).all()
|
||||
|
||||
recent_audits = AuditLog.query.order_by(AuditLog.created_at.desc()).limit(8).all()
|
||||
audit_data = []
|
||||
for a in recent_audits:
|
||||
d = a.to_dict()
|
||||
act_raw = (d.get('action') or '').upper()
|
||||
mod_raw = (d.get('module') or '').lower()
|
||||
action_label = {
|
||||
'LOGIN': 'Inicio de Sesión',
|
||||
'LOGOUT': 'Cierre de Sesión',
|
||||
'CREATE': 'Creación',
|
||||
'UPDATE': 'Actualización',
|
||||
'DELETE': 'Eliminación',
|
||||
'IMPERSONATE': 'Impersonación',
|
||||
'RESET': 'Reinicio de Sistema',
|
||||
'CANCEL': 'Cancelación'
|
||||
}.get(act_raw, d.get('action') or 'Operación')
|
||||
module_label = {
|
||||
'auth': 'Autenticación',
|
||||
'users': 'Usuarios',
|
||||
'classrooms': 'Aulas',
|
||||
'reservations': 'Reservas',
|
||||
'academic': 'Académica',
|
||||
'system': 'Sistema'
|
||||
}.get(mod_raw, d.get('module') or 'Sistema')
|
||||
|
||||
d['action_label'] = action_label
|
||||
d['module_label'] = module_label
|
||||
d['action_type'] = act_raw
|
||||
audit_data.append(d)
|
||||
|
||||
occupancy_rate = min(100, int((today_reservations / max(1, physical_classrooms * 3)) * 100)) if physical_classrooms > 0 else 0
|
||||
|
||||
pending_reservations = [self.serialize_reservation(r) for r in pending_reservations_q]
|
||||
today_schedule_list = [self.serialize_reservation(r) for r in today_reservations_q]
|
||||
upcoming_reservations = [self.serialize_reservation(r) for r in upcoming_reservations_q]
|
||||
milestones = [self.serialize_milestone(m) for m in milestones_q]
|
||||
|
||||
user_id = getattr(current_user, 'id', None)
|
||||
|
||||
my_today_count = 0
|
||||
my_total_reservations = 0
|
||||
my_today_classes = []
|
||||
if user_id:
|
||||
my_today_q = Reservation.query.filter(
|
||||
Reservation.user_id == user_id,
|
||||
func.date(Reservation.start_time) == today,
|
||||
Reservation.status != 'CANCELLED'
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
my_today_count = len(my_today_q)
|
||||
my_today_classes = [self.serialize_reservation(r) for r in my_today_q]
|
||||
my_total_reservations = Reservation.query.filter(
|
||||
Reservation.user_id == user_id,
|
||||
Reservation.status.in_(['CONFIRMED', 'PENDING'])
|
||||
).count()
|
||||
else:
|
||||
my_today_count = today_reservations
|
||||
my_total_reservations = len(today_reservations_q)
|
||||
my_today_classes = today_schedule_list[:5]
|
||||
|
||||
# ---- Bedelía: Filtros completos de Aulas y Comisiones por Día (Hoy), Mañana, Semana y Mes ----
|
||||
today_dt = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
tomorrow_dt = today_dt + timedelta(days=1)
|
||||
tomorrow_start = tomorrow_dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
tomorrow_end = tomorrow_dt.replace(hour=23, minute=59, second=59, microsecond=0)
|
||||
|
||||
week_start = today_dt - timedelta(days=today_dt.weekday()) # Lunes
|
||||
week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
week_end = week_start + timedelta(days=6, hours=23, minutes=59, seconds=59)
|
||||
|
||||
month_start = today_dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
last_day = calendar.monthrange(today_dt.year, today_dt.month)[1]
|
||||
month_end = today_dt.replace(day=last_day, hour=23, minute=59, second=59, microsecond=0)
|
||||
|
||||
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
|
||||
meses_esp = ['', 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
|
||||
weekday_name = dias_esp[today_dt.weekday()]
|
||||
month_name = meses_esp[today_dt.month]
|
||||
tomorrow_weekday_name = dias_esp[tomorrow_dt.weekday()]
|
||||
tomorrow_month_name = meses_esp[tomorrow_dt.month]
|
||||
|
||||
date_labels = {
|
||||
'today': f"Hoy · {weekday_name} {today_dt.strftime('%d/%m/%Y')}",
|
||||
'today_short': f"{weekday_name} {today_dt.strftime('%d/%m')}",
|
||||
'today_full': f"{weekday_name}, {today_dt.day} de {month_name} de {today_dt.year}",
|
||||
'tomorrow': f"Mañana · {tomorrow_weekday_name} {tomorrow_dt.strftime('%d/%m/%Y')}",
|
||||
'tomorrow_short': f"{tomorrow_weekday_name} {tomorrow_dt.strftime('%d/%m')}",
|
||||
'tomorrow_full': f"{tomorrow_weekday_name}, {tomorrow_dt.day} de {tomorrow_month_name} de {tomorrow_dt.year}",
|
||||
'week': f"Semana del {week_start.strftime('%d/%m')} al {week_end.strftime('%d/%m/%Y')}",
|
||||
'week_full': f"Semana del {week_start.strftime('%d/%m/%Y')} al {week_end.strftime('%d/%m/%Y')}",
|
||||
'month': f"Mes de {month_name} {today_dt.year} ({month_start.strftime('%d/%m')} al {month_end.strftime('%d/%m/%Y')})",
|
||||
'month_full': f"{month_name} de {today_dt.year}"
|
||||
}
|
||||
|
||||
tomorrow_reservations_q = Reservation.query.filter(
|
||||
Reservation.start_time >= tomorrow_start,
|
||||
Reservation.start_time <= tomorrow_end
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
tomorrow_schedule_list = [self.serialize_reservation(r) for r in tomorrow_reservations_q]
|
||||
|
||||
week_reservations_q = Reservation.query.filter(
|
||||
Reservation.start_time >= week_start,
|
||||
Reservation.start_time <= week_end
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
week_schedule_list = [self.serialize_reservation(r) for r in week_reservations_q]
|
||||
|
||||
month_reservations_q = Reservation.query.filter(
|
||||
Reservation.start_time >= month_start,
|
||||
Reservation.start_time <= month_end
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
|
||||
# Mapas de reservas por aula en cada período
|
||||
res_map_classroom_today: Dict[int, List[Reservation]] = {}
|
||||
for r in today_reservations_q:
|
||||
cid = getattr(r, 'classroom_id', None)
|
||||
if cid is not None:
|
||||
res_map_classroom_today.setdefault(int(cid), []).append(r)
|
||||
|
||||
res_map_classroom_tomorrow: Dict[int, List[Reservation]] = {}
|
||||
for r in tomorrow_reservations_q:
|
||||
cid = getattr(r, 'classroom_id', None)
|
||||
if cid is not None:
|
||||
res_map_classroom_tomorrow.setdefault(int(cid), []).append(r)
|
||||
|
||||
res_map_classroom_week: Dict[int, List[Reservation]] = {}
|
||||
for r in week_reservations_q:
|
||||
cid = getattr(r, 'classroom_id', None)
|
||||
if cid is not None:
|
||||
res_map_classroom_week.setdefault(int(cid), []).append(r)
|
||||
|
||||
res_map_classroom_month: Dict[int, List[Reservation]] = {}
|
||||
for r in month_reservations_q:
|
||||
cid = getattr(r, 'classroom_id', None)
|
||||
if cid is not None:
|
||||
res_map_classroom_month.setdefault(int(cid), []).append(r)
|
||||
|
||||
res_map_comm_today: Dict[int, List[Reservation]] = {}
|
||||
for r in today_reservations_q:
|
||||
comm_id = getattr(r, 'commission_id', None)
|
||||
if comm_id is not None:
|
||||
res_map_comm_today.setdefault(int(comm_id), []).append(r)
|
||||
|
||||
res_map_comm_tomorrow: Dict[int, List[Reservation]] = {}
|
||||
for r in tomorrow_reservations_q:
|
||||
comm_id = getattr(r, 'commission_id', None)
|
||||
if comm_id is not None:
|
||||
res_map_comm_tomorrow.setdefault(int(comm_id), []).append(r)
|
||||
|
||||
res_map_comm_week: Dict[int, List[Reservation]] = {}
|
||||
for r in week_reservations_q:
|
||||
comm_id = getattr(r, 'commission_id', None)
|
||||
if comm_id is not None:
|
||||
res_map_comm_week.setdefault(int(comm_id), []).append(r)
|
||||
|
||||
res_map_comm_month: Dict[int, List[Reservation]] = {}
|
||||
for r in month_reservations_q:
|
||||
comm_id = getattr(r, 'commission_id', None)
|
||||
if comm_id is not None:
|
||||
res_map_comm_month.setdefault(int(comm_id), []).append(r)
|
||||
|
||||
all_active_commissions = Commission.query.filter_by(active=True).all()
|
||||
total_active_commissions = len(all_active_commissions)
|
||||
|
||||
def build_classroom_item(c: Classroom, res_list: List[Reservation]) -> Dict[str, Any]:
|
||||
r_first = res_list[0] if res_list else None
|
||||
assigned_summary = ''
|
||||
if r_first:
|
||||
subj = (r_first.commission.subject.name if (r_first.commission and r_first.commission.subject) else r_first.purpose) or 'Clase'
|
||||
assigned_summary = f"{subj} ({r_first.start_time.strftime('%H:%M')} - {r_first.end_time.strftime('%H:%M')} hs)"
|
||||
return {
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building or 'Sede Central',
|
||||
'floor': c.floor or '',
|
||||
'capacity': c.capacity or 0,
|
||||
'is_virtual': getattr(c, 'is_virtual', False) or 'virtual' in (c.building or '').lower() or 'virtual' in (c.code or '').lower(),
|
||||
'res_count': len(res_list),
|
||||
'assigned_summary': assigned_summary
|
||||
}
|
||||
|
||||
def build_comm_item(comm: Commission, res_list: List[Reservation]) -> Dict[str, Any]:
|
||||
has_v_link = bool(comm.virtual_link and comm.virtual_link.strip())
|
||||
r_first = res_list[0] if res_list else None
|
||||
assigned_room = ''
|
||||
assigned_time = ''
|
||||
if r_first:
|
||||
assigned_room = r_first.classroom.code if r_first.classroom else 'Aula Virtual'
|
||||
assigned_time = f"{r_first.start_time.strftime('%H:%M')} - {r_first.end_time.strftime('%H:%M')} hs"
|
||||
|
||||
career_name = comm.career_name if hasattr(comm, 'career_name') else (comm.subject.career.name if (comm.subject and comm.subject.career) else 'UniCABA')
|
||||
career_names = comm.career_names if hasattr(comm, 'career_names') else career_name
|
||||
career_id = comm.career_id if hasattr(comm, 'career_id') else None
|
||||
|
||||
return {
|
||||
'id': comm.id,
|
||||
'code': comm.code,
|
||||
'full_code': comm.get_full_code(),
|
||||
'subject_name': comm.subject.name if comm.subject else 'Sin materia',
|
||||
'subject_code': comm.subject.code if comm.subject else '',
|
||||
'career_name': career_name,
|
||||
'career_names': career_names,
|
||||
'career_id': career_id,
|
||||
'teacher_name': comm.teacher_name or 'Sin docente',
|
||||
'schedule': comm.schedule or 'Sin horario',
|
||||
'shift': comm.shift or 'Sin turno',
|
||||
'max_students': comm.max_students or 0,
|
||||
'current_students': comm.current_students or 0,
|
||||
'virtual_link': comm.virtual_link or '',
|
||||
'has_virtual_link': has_v_link,
|
||||
'res_count': len(res_list),
|
||||
'assigned_room': assigned_room,
|
||||
'assigned_time': assigned_time
|
||||
}
|
||||
|
||||
classrooms_assigned_today = [build_classroom_item(c, res_map_classroom_today[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_today]
|
||||
classrooms_unassigned_today = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_today]
|
||||
classrooms_assigned_tomorrow = [build_classroom_item(c, res_map_classroom_tomorrow[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_tomorrow]
|
||||
classrooms_unassigned_tomorrow = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_tomorrow]
|
||||
classrooms_assigned_week = [build_classroom_item(c, res_map_classroom_week[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_week]
|
||||
classrooms_unassigned_week = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_week]
|
||||
classrooms_assigned_month = [build_classroom_item(c, res_map_classroom_month[c.id]) for c in physical_classrooms_list if c.id in res_map_classroom_month]
|
||||
classrooms_unassigned_month = [build_classroom_item(c, []) for c in physical_classrooms_list if c.id not in res_map_classroom_month]
|
||||
|
||||
commissions_assigned_today = [build_comm_item(comm, res_map_comm_today[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_today]
|
||||
commissions_unassigned_today = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_today]
|
||||
commissions_assigned_tomorrow = [build_comm_item(comm, res_map_comm_tomorrow[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_tomorrow]
|
||||
commissions_unassigned_tomorrow = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_tomorrow]
|
||||
commissions_assigned_week = [build_comm_item(comm, res_map_comm_week[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_week]
|
||||
commissions_unassigned_week = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_week]
|
||||
commissions_assigned_month = [build_comm_item(comm, res_map_comm_month[comm.id]) for comm in all_active_commissions if comm.id in res_map_comm_month]
|
||||
commissions_unassigned_month = [build_comm_item(comm, []) for comm in all_active_commissions if comm.id not in res_map_comm_month]
|
||||
|
||||
virtual_room_ids = set(c.id for c in virtual_classrooms_list)
|
||||
comm_ids_virtual = set()
|
||||
for comm in all_active_commissions:
|
||||
if comm.virtual_link and comm.virtual_link.strip():
|
||||
comm_ids_virtual.add(comm.id)
|
||||
if virtual_room_ids:
|
||||
comm_in_virtual_res = set(
|
||||
r[0] for r in db.session.query(Reservation.commission_id).filter(
|
||||
Reservation.classroom_id.in_(virtual_room_ids),
|
||||
Reservation.commission_id.isnot(None)
|
||||
).distinct().all()
|
||||
)
|
||||
comm_ids_virtual.update(comm_in_virtual_res)
|
||||
|
||||
res_map_comm_all: Dict[int, List[Reservation]] = {}
|
||||
all_reservations_comm = Reservation.query.filter(
|
||||
Reservation.commission_id.isnot(None)
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
for r in all_reservations_comm:
|
||||
if r.commission_id is not None:
|
||||
res_map_comm_all.setdefault(int(r.commission_id), []).append(r)
|
||||
|
||||
virtual_rooms_data = []
|
||||
for comm in all_active_commissions:
|
||||
if comm.id in comm_ids_virtual:
|
||||
res_today = res_map_comm_today.get(comm.id, [])
|
||||
res_tomorrow = res_map_comm_tomorrow.get(comm.id, [])
|
||||
res_week = res_map_comm_week.get(comm.id, [])
|
||||
res_month = res_map_comm_month.get(comm.id, [])
|
||||
res_all = res_map_comm_all.get(comm.id, [])
|
||||
v_link = comm.virtual_link or (res_today[0].virtual_link if res_today and res_today[0].virtual_link else '')
|
||||
virtual_rooms_data.append({
|
||||
'id': comm.id,
|
||||
'commission_id': comm.id,
|
||||
'commission_code': comm.code,
|
||||
'code': comm.code,
|
||||
'full_code': comm.get_full_code(),
|
||||
'subject_name': comm.subject.name if comm.subject else 'Sin materia',
|
||||
'subject_code': comm.subject.code if comm.subject else '',
|
||||
'career_name': comm.subject.career.name if (comm.subject and comm.subject.career) else 'UniCABA',
|
||||
'teacher_name': comm.teacher_name or 'Docente a confirmar',
|
||||
'schedule': comm.schedule or 'Horario regular',
|
||||
'shift': comm.shift or 'Tarde',
|
||||
'max_students': comm.max_students or 35,
|
||||
'capacity': comm.max_students or 35,
|
||||
'virtual_link': v_link,
|
||||
'is_virtual': True,
|
||||
'building': 'Campus Virtual',
|
||||
'floor': 'Remoto ∞',
|
||||
'day_count': len(res_today),
|
||||
'today_classes': len(res_today),
|
||||
'tomorrow_classes': len(res_tomorrow),
|
||||
'week_count': len(res_week),
|
||||
'week_classes': len(res_week),
|
||||
'month_count': len(res_month),
|
||||
'month_classes': len(res_month),
|
||||
'res_count': len(res_all) if len(res_all) > 0 else len(res_month),
|
||||
'total_count': len(res_all),
|
||||
'is_active_today': len(res_today) > 0,
|
||||
'is_active_tomorrow': len(res_tomorrow) > 0,
|
||||
'assigned_summary': f"{comm.subject.name if comm.subject else 'Clase Virtual'} ({comm.schedule or 'Remoto'})",
|
||||
'reservations': [self.serialize_reservation(r) for r in res_all]
|
||||
})
|
||||
|
||||
if virtual_rooms_data:
|
||||
virtual_classrooms = len(virtual_rooms_data)
|
||||
|
||||
comm_ids_with_any_res = set(
|
||||
r[0] for r in db.session.query(Reservation.commission_id).filter(
|
||||
Reservation.commission_id.isnot(None)
|
||||
).distinct().all()
|
||||
)
|
||||
unassigned_commissions_general = [
|
||||
build_comm_item(comm, []) for comm in all_active_commissions
|
||||
if comm.id not in comm_ids_with_any_res and not comm.virtual_link
|
||||
]
|
||||
|
||||
available_classrooms_today = classrooms_unassigned_today
|
||||
available_classrooms_tomorrow = classrooms_unassigned_tomorrow
|
||||
available_classrooms_week = classrooms_unassigned_week
|
||||
available_classrooms_month = classrooms_unassigned_month
|
||||
|
||||
unassigned_commissions_tomorrow = commissions_unassigned_tomorrow
|
||||
unassigned_commissions_week = commissions_unassigned_week
|
||||
unassigned_commissions_month = commissions_unassigned_month
|
||||
|
||||
filter_stats = {
|
||||
'today': {
|
||||
'label': date_labels['today'],
|
||||
'date_short': date_labels['today_short'],
|
||||
'date_full': date_labels['today_full'],
|
||||
'classrooms': {
|
||||
'assigned': classrooms_assigned_today,
|
||||
'unassigned': classrooms_unassigned_today,
|
||||
'assigned_count': len(classrooms_assigned_today),
|
||||
'unassigned_count': len(classrooms_unassigned_today),
|
||||
'assigned_pct': assigned_today_pct,
|
||||
'unassigned_pct': unassigned_today_pct,
|
||||
'total': total_physical_count
|
||||
},
|
||||
'commissions': {
|
||||
'assigned': commissions_assigned_today,
|
||||
'unassigned': commissions_unassigned_today,
|
||||
'assigned_count': len(commissions_assigned_today),
|
||||
'unassigned_count': len(commissions_unassigned_today),
|
||||
'assigned_pct': round((len(commissions_assigned_today) / max(1, total_active_commissions)) * 100, 1),
|
||||
'unassigned_pct': round((len(commissions_unassigned_today) / max(1, total_active_commissions)) * 100, 1),
|
||||
'total': total_active_commissions
|
||||
}
|
||||
},
|
||||
'tomorrow': {
|
||||
'label': date_labels['tomorrow'],
|
||||
'date_short': date_labels['tomorrow_short'],
|
||||
'date_full': date_labels['tomorrow_full'],
|
||||
'classrooms': {
|
||||
'assigned': classrooms_assigned_tomorrow,
|
||||
'unassigned': classrooms_unassigned_tomorrow,
|
||||
'assigned_count': len(classrooms_assigned_tomorrow),
|
||||
'unassigned_count': len(classrooms_unassigned_tomorrow),
|
||||
'assigned_pct': round((len(classrooms_assigned_tomorrow) / max(1, total_physical_count)) * 100, 1),
|
||||
'unassigned_pct': round((len(classrooms_unassigned_tomorrow) / max(1, total_physical_count)) * 100, 1),
|
||||
'total': total_physical_count
|
||||
},
|
||||
'commissions': {
|
||||
'assigned': commissions_assigned_tomorrow,
|
||||
'unassigned': commissions_unassigned_tomorrow,
|
||||
'assigned_count': len(commissions_assigned_tomorrow),
|
||||
'unassigned_count': len(commissions_unassigned_tomorrow),
|
||||
'assigned_pct': round((len(commissions_assigned_tomorrow) / max(1, total_active_commissions)) * 100, 1),
|
||||
'unassigned_pct': round((len(commissions_unassigned_tomorrow) / max(1, total_active_commissions)) * 100, 1),
|
||||
'total': total_active_commissions
|
||||
}
|
||||
},
|
||||
'week': {
|
||||
'label': date_labels['week'],
|
||||
'date_short': date_labels['week'],
|
||||
'date_full': date_labels['week_full'],
|
||||
'classrooms': {
|
||||
'assigned': classrooms_assigned_week,
|
||||
'unassigned': classrooms_unassigned_week,
|
||||
'assigned_count': len(classrooms_assigned_week),
|
||||
'unassigned_count': len(classrooms_unassigned_week),
|
||||
'assigned_pct': round((len(classrooms_assigned_week) / max(1, total_physical_count)) * 100, 1),
|
||||
'unassigned_pct': round((len(classrooms_unassigned_week) / max(1, total_physical_count)) * 100, 1),
|
||||
'total': total_physical_count
|
||||
},
|
||||
'commissions': {
|
||||
'assigned': commissions_assigned_week,
|
||||
'unassigned': commissions_unassigned_week,
|
||||
'assigned_count': len(commissions_assigned_week),
|
||||
'unassigned_count': len(commissions_unassigned_week),
|
||||
'assigned_pct': round((len(commissions_assigned_week) / max(1, total_active_commissions)) * 100, 1),
|
||||
'unassigned_pct': round((len(commissions_unassigned_week) / max(1, total_active_commissions)) * 100, 1),
|
||||
'total': total_active_commissions
|
||||
}
|
||||
},
|
||||
'month': {
|
||||
'label': date_labels['month'],
|
||||
'date_short': date_labels['month'],
|
||||
'date_full': date_labels['month_full'],
|
||||
'classrooms': {
|
||||
'assigned': classrooms_assigned_month,
|
||||
'unassigned': classrooms_unassigned_month,
|
||||
'assigned_count': len(classrooms_assigned_month),
|
||||
'unassigned_count': len(classrooms_unassigned_month),
|
||||
'assigned_pct': round((len(classrooms_assigned_month) / max(1, total_physical_count)) * 100, 1),
|
||||
'unassigned_pct': round((len(classrooms_unassigned_month) / max(1, total_physical_count)) * 100, 1),
|
||||
'total': total_physical_count
|
||||
},
|
||||
'commissions': {
|
||||
'assigned': commissions_assigned_month,
|
||||
'unassigned': commissions_unassigned_month,
|
||||
'assigned_count': len(commissions_assigned_month),
|
||||
'unassigned_count': len(commissions_unassigned_month),
|
||||
'assigned_pct': round((len(commissions_assigned_month) / max(1, total_active_commissions)) * 100, 1),
|
||||
'unassigned_pct': round((len(commissions_unassigned_month) / max(1, total_active_commissions)) * 100, 1),
|
||||
'total': total_active_commissions
|
||||
}
|
||||
},
|
||||
'virtual_rooms': virtual_rooms_data,
|
||||
'virtual_rooms_count': len(virtual_rooms_data)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error fetching stats in DashboardService: {e}")
|
||||
|
||||
monthly_data = [
|
||||
{"month": "Ene", "reservations": 120},
|
||||
{"month": "Feb", "reservations": 180},
|
||||
{"month": "Mar", "reservations": 250},
|
||||
{"month": "Abr", "reservations": 220},
|
||||
{"month": "May", "reservations": 300},
|
||||
{"month": "Jun", "reservations": 310},
|
||||
{"month": "Jul", "reservations": 200},
|
||||
{"month": "Ago", "reservations": 350},
|
||||
{"month": "Sep", "reservations": 420},
|
||||
{"month": "Oct", "reservations": 480},
|
||||
{"month": "Nov", "reservations": 520},
|
||||
{"month": "Dic", "reservations": 210}
|
||||
]
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'stats': {
|
||||
'total_classrooms': total_classrooms,
|
||||
'active_subjects': total_subjects,
|
||||
'total_active_users': total_users,
|
||||
'today_reservations': today_reservations,
|
||||
'pending_count': pending_count,
|
||||
'physical_classrooms': physical_classrooms,
|
||||
'virtual_classrooms': virtual_classrooms,
|
||||
'occupancy_rate': occupancy_rate,
|
||||
'assigned_classrooms': assigned_classrooms,
|
||||
'assigned_classrooms_pct': assigned_pct,
|
||||
'unassigned_classrooms': unassigned_classrooms,
|
||||
'unassigned_classrooms_pct': unassigned_pct,
|
||||
'assigned_today_classrooms': assigned_today_count,
|
||||
'assigned_today_pct': assigned_today_pct,
|
||||
'unassigned_today_classrooms': unassigned_today_count,
|
||||
'unassigned_today_pct': unassigned_today_pct,
|
||||
'total_active_commissions': total_active_commissions,
|
||||
'tomorrow_reservations': len(tomorrow_reservations_q),
|
||||
'my_today_count': my_today_count,
|
||||
'my_total_reservations': my_total_reservations,
|
||||
'virtual_rooms_count': virtual_classrooms
|
||||
},
|
||||
'audit_logs': audit_data,
|
||||
'monthly_data': monthly_data,
|
||||
'pending_reservations': pending_reservations,
|
||||
'today_schedule_list': today_schedule_list,
|
||||
'my_today_classes': my_today_classes,
|
||||
'tomorrow_schedule_list': tomorrow_schedule_list,
|
||||
'week_schedule_list': week_schedule_list,
|
||||
'upcoming_reservations': upcoming_reservations,
|
||||
'milestones': milestones,
|
||||
'filter_stats': filter_stats,
|
||||
'date_labels': date_labels,
|
||||
'careers': [c.to_dict() for c in Career.query.order_by(Career.name.asc()).all()],
|
||||
'ui': {
|
||||
'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True]
|
||||
},
|
||||
'bedelia': {
|
||||
'unassigned_commissions_tomorrow': unassigned_commissions_tomorrow,
|
||||
'unassigned_commissions_week': unassigned_commissions_week,
|
||||
'unassigned_commissions_month': unassigned_commissions_month,
|
||||
'unassigned_commissions_general': unassigned_commissions_general,
|
||||
'available_classrooms_today': available_classrooms_today,
|
||||
'available_classrooms_tomorrow': available_classrooms_tomorrow,
|
||||
'available_classrooms_week': available_classrooms_week,
|
||||
'available_classrooms_month': available_classrooms_month,
|
||||
'virtual_rooms': virtual_rooms_data,
|
||||
'virtual_rooms_count': len(virtual_rooms_data)
|
||||
}
|
||||
}
|
||||
|
||||
def sync_google_sheets(self, data: Dict[str, Any], current_user: Optional[User] = None, ip_address: Optional[str] = None) -> Dict[str, Any]:
|
||||
filter_career = data.get('filter_career')
|
||||
filter_subject = data.get('filter_subject')
|
||||
filter_day = data.get('filter_day')
|
||||
filter_days = data.get('filter_days')
|
||||
manual_date = data.get('manual_date')
|
||||
single_date_only = bool(data.get('single_date_only', False))
|
||||
weeks_to_generate = data.get('weeks_to_generate', 16)
|
||||
date_from = data.get('date_from')
|
||||
date_to = data.get('date_to')
|
||||
custom_url = data.get('sheets_url') or data.get('base_url')
|
||||
|
||||
import_careers = data.get('import_careers', True)
|
||||
import_subjects = data.get('import_subjects', True)
|
||||
import_commissions = data.get('import_commissions', True)
|
||||
import_classrooms = data.get('import_classrooms', True)
|
||||
import_reservations = data.get('import_reservations', True)
|
||||
selected_rows = data.get('selected_rows')
|
||||
|
||||
user_email = current_user.email if current_user else 'System'
|
||||
|
||||
try:
|
||||
importer = GoogleSheetsImporter(base_url=custom_url)
|
||||
stats = importer.sync(
|
||||
filter_career=filter_career,
|
||||
filter_subject=filter_subject,
|
||||
filter_day=filter_day,
|
||||
filter_days=filter_days,
|
||||
manual_date=manual_date,
|
||||
single_date_only=single_date_only,
|
||||
weeks_to_generate=weeks_to_generate,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
import_careers=import_careers,
|
||||
import_subjects=import_subjects,
|
||||
import_commissions=import_commissions,
|
||||
import_classrooms=import_classrooms,
|
||||
import_reservations=import_reservations,
|
||||
selected_rows=selected_rows
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
action='SHEETS_IMPORT',
|
||||
module='import',
|
||||
user_email=user_email,
|
||||
ip_address=ip_address,
|
||||
details={
|
||||
'stats': stats,
|
||||
'filter_career': filter_career,
|
||||
'filter_subject': filter_subject,
|
||||
'filter_day': filter_day,
|
||||
'filter_days': filter_days,
|
||||
'single_date_only': single_date_only,
|
||||
'manual_date': manual_date,
|
||||
'weeks_to_generate': weeks_to_generate,
|
||||
'date_from': date_from,
|
||||
'date_to': date_to
|
||||
},
|
||||
status='success'
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'stats': stats,
|
||||
'source_url': importer.base_url
|
||||
}
|
||||
except Exception as e:
|
||||
AuditService.log(
|
||||
action='SHEETS_IMPORT_ERROR',
|
||||
module='import',
|
||||
user_email=user_email,
|
||||
ip_address=ip_address,
|
||||
details={
|
||||
'error': str(e),
|
||||
'filter_career': filter_career,
|
||||
'filter_subject': filter_subject,
|
||||
'filter_day': filter_day
|
||||
},
|
||||
status='failed'
|
||||
)
|
||||
raise e
|
||||
|
||||
def inspect_google_sheets(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
custom_url = data.get('sheets_url')
|
||||
filter_career = data.get('filter_career')
|
||||
filter_subject = data.get('filter_subject')
|
||||
filter_day = data.get('filter_day')
|
||||
filter_days = data.get('filter_days')
|
||||
manual_date = data.get('manual_date')
|
||||
|
||||
importer = GoogleSheetsImporter(base_url=custom_url)
|
||||
metadata = importer.inspect_sheet_content(
|
||||
filter_career=filter_career,
|
||||
filter_subject=filter_subject,
|
||||
filter_day=filter_day,
|
||||
filter_days=filter_days,
|
||||
manual_date=manual_date
|
||||
)
|
||||
return {
|
||||
'status': 'success',
|
||||
'metadata': metadata,
|
||||
'source_url': importer.base_url
|
||||
}
|
||||
@@ -112,18 +112,22 @@ class EmailService:
|
||||
if html_content:
|
||||
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
|
||||
|
||||
host_str = str(host or 'localhost')
|
||||
port_int = int(port or 587)
|
||||
from_email_str = str(from_email or 'notificaciones@unicaba.edu.ar')
|
||||
|
||||
try:
|
||||
if security == 'ssl' or port == 465:
|
||||
server = smtplib.SMTP_SSL(host, port, timeout=15)
|
||||
if security == 'ssl' or port_int == 465:
|
||||
server = smtplib.SMTP_SSL(host_str, port_int, timeout=15)
|
||||
else:
|
||||
server = smtplib.SMTP(host, port, timeout=15)
|
||||
server = smtplib.SMTP(host_str, port_int, timeout=15)
|
||||
if security in ('tls', 'starttls'):
|
||||
server.starttls()
|
||||
|
||||
if user and password:
|
||||
server.login(user, password)
|
||||
|
||||
server.sendmail(from_email, recipients, msg.as_string())
|
||||
server.sendmail(from_email_str, recipients, msg.as_string())
|
||||
server.quit()
|
||||
logger.info(f"[EmailService] Email sent successfully to {recipients}: '{subject}'")
|
||||
return True
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, List, Dict, Any
|
||||
from app import db
|
||||
from app.models.subject import Commission, Subject
|
||||
@@ -33,9 +33,12 @@ class GradebookService:
|
||||
).join(User).order_by(User.name.asc()).all()
|
||||
|
||||
# 3. Mapa de notas por (student_id, milestone_id)
|
||||
grades = MilestoneGrade.query.filter(
|
||||
MilestoneGrade.milestone_id.in_([m.id for m in milestones]) if milestones else False
|
||||
).all() if milestones else []
|
||||
if milestones:
|
||||
grades = MilestoneGrade.query.filter(
|
||||
MilestoneGrade.milestone_id.in_([m.id for m in milestones])
|
||||
).all()
|
||||
else:
|
||||
grades = []
|
||||
|
||||
grades_map: Dict[tuple, MilestoneGrade] = {
|
||||
(g.student_id, g.milestone_id): g for g in grades
|
||||
@@ -94,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,
|
||||
@@ -108,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,
|
||||
@@ -177,7 +200,7 @@ class GradebookService:
|
||||
is_absent=final_absent,
|
||||
feedback=feedback.strip() if feedback else '',
|
||||
graded_by_user_id=grader_id,
|
||||
graded_at=datetime.utcnow()
|
||||
graded_at=datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
)
|
||||
db.session.add(grade)
|
||||
else:
|
||||
@@ -186,7 +209,7 @@ class GradebookService:
|
||||
if feedback is not None:
|
||||
grade.feedback = feedback.strip()
|
||||
grade.graded_by_user_id = grader_id
|
||||
grade.updated_at = datetime.utcnow()
|
||||
grade.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
db.session.commit()
|
||||
return grade
|
||||
@@ -240,7 +263,7 @@ class GradebookService:
|
||||
|
||||
acta_num = f'ACTA-{comm.year}-{comm.semester}-{comm.id:04d}'
|
||||
comm.grades_closed = True
|
||||
comm.grades_closed_at = datetime.utcnow()
|
||||
comm.grades_closed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
comm.grades_closed_by = user_id
|
||||
comm.acta_number = acta_num
|
||||
|
||||
@@ -323,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:
|
||||
@@ -335,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': '-',
|
||||
@@ -347,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),
|
||||
@@ -380,10 +432,65 @@ 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."""
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
enrollments = StudentEnrollment.query.filter_by(student_id=student_id).all()
|
||||
commission_ids = [e.commission_id for e in enrollments]
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
app/services/guide_service.py - Servicio de Guías Interactivas y Spotlight para UdeCi (SDD-011)
|
||||
Detecta intenciones de tutorial paso a paso y emite directivas estructuradas
|
||||
para que el frontend ilumine los botones y campos interactivos ("enseñar a pescar").
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Optional
|
||||
from schemas.ai_chat import GuideStepDTO
|
||||
from mcp_server import STEP_GUIDES
|
||||
|
||||
|
||||
def _normalize(text: str) -> str:
|
||||
"""Elimina acentos y pasa a minúsculas para matching semántico tolerante."""
|
||||
nfkd = unicodedata.normalize('NFKD', text)
|
||||
return ''.join([c for c in nfkd if not unicodedata.combining(c)]).lower()
|
||||
|
||||
|
||||
class GuideService:
|
||||
"""Servicio de resolución de pasos y directivas de UI para el asistente UdeCi."""
|
||||
|
||||
@classmethod
|
||||
def detect_guide_step(
|
||||
cls,
|
||||
query: str,
|
||||
user_role: str = "alumno",
|
||||
current_path: Optional[str] = None
|
||||
) -> Optional[GuideStepDTO]:
|
||||
"""
|
||||
Analiza la consulta del usuario y el contexto de la pantalla activa
|
||||
para retornar el paso interactivo más relevante de la UI.
|
||||
"""
|
||||
if not query:
|
||||
return None
|
||||
|
||||
q = _normalize(query)
|
||||
path = (current_path or "").lower()
|
||||
|
||||
# Acción 1: Crear / Dar de alta Sede o Edificio
|
||||
if ("sede" in q or "edificio" in q) and ("crear" in q or "nueva" in q or "nuevo" in q or "alta" in q or "registrar" in q or "como" in q or "agregar" in q):
|
||||
guide = STEP_GUIDES["crear_sede"]
|
||||
if "add_building" in path or ("building" in path and "add" in path):
|
||||
step = guide["steps"][1]
|
||||
return GuideStepDTO(
|
||||
target_url="/buildings/add_building",
|
||||
selector=step["selector"],
|
||||
message=step["message"],
|
||||
expected_action=step["expected_action"],
|
||||
step_number=2,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
# Acción 2: Crear / Agregar Aula
|
||||
if "aula" in q and ("crear" in q or "nueva" in q or "nuevo" in q or "alta" in q or "como" in q or "registrar" in q or "agregar" in q):
|
||||
guide = STEP_GUIDES["crear_aula"]
|
||||
if "add_classroom" in path:
|
||||
step = guide["steps"][1]
|
||||
return GuideStepDTO(
|
||||
target_url="/classrooms/add_classroom",
|
||||
selector=step["selector"],
|
||||
message=step["message"],
|
||||
expected_action=step["expected_action"],
|
||||
step_number=2,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
# Acción 3: Crear Ciclo Lectivo
|
||||
if ("ciclo" in q or "periodo" in q) and ("crear" in q or "nuevo" in q or "alta" in q or "como" in q or "registrar" in q or "agregar" in q):
|
||||
guide = STEP_GUIDES["crear_ciclo"]
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
# Acción 4: Consultar Cursada de Hoy (Alumnos / Docentes / Bedelía)
|
||||
if ("donde curso" in q or "aula de cursada" in q or "clases de hoy" in q or "aula de hoy" in q or "horario de hoy" in q or "cartelera" in q):
|
||||
guide = STEP_GUIDES["consultar_cursada"]
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
# Acción 5: Gradebook / Calificaciones (Docente / Alumno)
|
||||
if ("gradebook" in q or "calificacion" in q or "calificaciones" in q or "notas" in q or "acta" in q or "regularidad" in q):
|
||||
guide = STEP_GUIDES["gradebook"]
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
# Acción 6: Importador de Google Sheets
|
||||
if ("sheet" in q or "sheets" in q or "importar" in q or "sincronizar" in q):
|
||||
guide = STEP_GUIDES["importar_sheets"]
|
||||
step1 = guide["steps"][0]
|
||||
return GuideStepDTO(
|
||||
target_url=guide["target_url"],
|
||||
selector=step1["selector"],
|
||||
message=step1["message"],
|
||||
expected_action=step1["expected_action"],
|
||||
step_number=1,
|
||||
total_steps=len(guide["steps"])
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -2,7 +2,7 @@ import jwt
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, Any, Optional
|
||||
from flask import current_app
|
||||
from config.config import Config
|
||||
from app.models.user import User
|
||||
|
||||
# Lista negra de tokens revocados en memoria (jti -> timestamp de expiración)
|
||||
@@ -25,27 +25,32 @@ class JWTService:
|
||||
|
||||
@classmethod
|
||||
def _get_secret(cls) -> str:
|
||||
"""Obtiene la clave secreta desde la configuración de Flask."""
|
||||
return current_app.config.get('SECRET_KEY', 'default-edu-space-secret-key')
|
||||
"""Obtiene la clave secreta desde Config."""
|
||||
return getattr(Config, 'SECRET_KEY', 'default-edu-space-secret-key')
|
||||
|
||||
@classmethod
|
||||
def create_access_token(cls, user: User, expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Emite un token de acceso de corta duración (15 min) con claims de rol y permisos."""
|
||||
now = datetime.now(timezone.utc)
|
||||
delta = expires_delta or cls.ACCESS_TOKEN_EXPIRES
|
||||
role_name = user.role_obj.name if user.role_obj else user.role
|
||||
role_obj = getattr(user, 'role_obj', None)
|
||||
role_name = getattr(role_obj, 'name', None) or user.role
|
||||
|
||||
# Mapeo de permisos para claims del token
|
||||
permissions = {}
|
||||
if user.role_obj and hasattr(user.role_obj, 'permissions'):
|
||||
for p in user.role_obj.permissions:
|
||||
permissions[p.module] = p.access_level
|
||||
if role_obj and hasattr(role_obj, 'permissions'):
|
||||
for p in getattr(role_obj, 'permissions', []):
|
||||
permissions[getattr(p, 'module', '')] = getattr(p, 'access_level', '')
|
||||
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'email': user.email,
|
||||
'name': user.name,
|
||||
'role': role_name,
|
||||
'document_type': getattr(user, 'document_type', 'DNI') or 'DNI',
|
||||
'document_number': getattr(user, 'document_number', '') or '',
|
||||
'dni': getattr(user, 'document_number', '') or '',
|
||||
'username': getattr(user, 'username', '') or getattr(user, 'document_number', '') or (user.email.split('@')[0] if user.email else ''),
|
||||
'is_admin': user.is_admin(),
|
||||
'permissions': permissions,
|
||||
'type': 'access',
|
||||
|
||||
@@ -0,0 +1,776 @@
|
||||
"""
|
||||
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.models.setting import SystemSetting
|
||||
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}")
|
||||
if active_comms and len(active_comms) <= 25:
|
||||
lines.append("COMISIONES ACTIVAS REGISTRADAS:")
|
||||
for ac in active_comms:
|
||||
s_name = ac.subject.name if ac.subject else ac.code
|
||||
t_name = ac.teacher_name if (ac.teacher or ac.teachers) else "Sin docente asignado"
|
||||
lines.append(f"• {s_name} [{ac.code} - {ac.shift or 'S/T'}]: Prof. {t_name} ({ac.current_students or 0} al.)")
|
||||
|
||||
# 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',
|
||||
'clase', 'clases', 'aula', 'aulas', 'que', 'cual',
|
||||
'esta', 'estan', 'unos', 'algunos', 'ellos', 'tiene'
|
||||
}
|
||||
]
|
||||
|
||||
# B. Consulta de Métodos de Login y Autenticación del Sistema
|
||||
auth_keywords = ['login', 'logins', 'autenticacion', 'acceso', 'sso', 'google', 'moodle', 'credenciales', 'cuentas']
|
||||
if any(ak in q_lower for ak in auth_keywords):
|
||||
local_en = SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True]
|
||||
google_en = SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True]
|
||||
moodle_en = SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True]
|
||||
active_methods = []
|
||||
if local_en:
|
||||
active_methods.append("Cuentas locales (Usuario y Contraseña)")
|
||||
if google_en:
|
||||
active_methods.append("Google Workspace (@unicaba.edu.ar)")
|
||||
if moodle_en:
|
||||
active_methods.append("Login delegado de Moodle SSO")
|
||||
|
||||
lines.append("\nESTADO DE MÉTODOS DE LOGIN Y AUTENTICACIÓN (CONFIGURACIÓN GLOBAL DEL SISTEMA):")
|
||||
lines.append(f"• Login Local: {'Habilitado (Activo)' if local_en else 'Deshabilitado'}")
|
||||
lines.append(f"• Google Workspace (@unicaba.edu.ar): {'Habilitado (Activo)' if google_en else 'Deshabilitado (Inactivo)'}")
|
||||
lines.append(f"• Login Delegado de Moodle: {'Habilitado (Activo)' if moodle_en else 'Deshabilitado (Inactivo)'}")
|
||||
if active_methods:
|
||||
lines.append(f"• Métodos actualmente ACTIVOS: {', '.join(active_methods)}.")
|
||||
else:
|
||||
lines.append("• Métodos actualmente ACTIVOS: Ninguno habilitado.")
|
||||
lines.append("• Gestión: El Administrador puede habilitar o deshabilitar estos métodos en Gobierno & Sistema ➔ Config. Global.")
|
||||
|
||||
# C1. Búsqueda y Listado de Comisiones / Cursadas
|
||||
comm_keywords = [
|
||||
'comision', 'comisiones', 'cursada', 'cursadas', 'comision c1',
|
||||
'comisiones activas', 'cuales comisiones', 'que comisiones'
|
||||
]
|
||||
list_keywords = ['listado', 'lista', 'listar', 'todas', 'todos', 'dame', 'cuales']
|
||||
asking_comm_list = (
|
||||
any(ck in q_lower for ck in comm_keywords) or
|
||||
(any(lk in q_lower for lk in list_keywords) and any(w in q_lower for w in ['comision', 'comisiones', 'cursada', 'cursadas']))
|
||||
)
|
||||
if asking_comm_list:
|
||||
all_active_comms = (
|
||||
Commission.query
|
||||
.filter_by(active=True)
|
||||
.join(Subject, Commission.subject_id == Subject.id)
|
||||
.order_by(Subject.name.asc(), Commission.code.asc())
|
||||
.all()
|
||||
)
|
||||
if all_active_comms:
|
||||
lines.append(f"\nLISTADO COMPLETO DE COMISIONES ACTIVAS ({len(all_active_comms)} en total):")
|
||||
for ac in all_active_comms:
|
||||
s_name = ac.subject.name if ac.subject else "Materia"
|
||||
s_code = ac.subject.code if ac.subject else ""
|
||||
c_car = ac.career_names if hasattr(ac, 'career_names') else (ac.career_name or "UniCABA")
|
||||
c_shift = f"Turno {ac.shift}" if ac.shift else "Turno a confirmar"
|
||||
t_assigned = ac.teacher_names if hasattr(ac, 'teacher_names') else ac.teacher_name
|
||||
lines.append(
|
||||
f"• {s_name} (Código: {s_code} | Carrera: {c_car}) - Comisión {ac.code} ({c_shift}): "
|
||||
f"Docente: {t_assigned} | Inscriptos: {ac.current_students or 0} alumnos"
|
||||
)
|
||||
else:
|
||||
lines.append("\nCOMISIONES: No se registran comisiones activas actualmente en el sistema.")
|
||||
|
||||
# C2. Búsqueda de Docentes / Profesores y Asignaciones Áulicas
|
||||
teacher_keywords = [
|
||||
'profesor', 'profesores', 'docente', 'docentes', 'profe', 'profes', 'proferes',
|
||||
'quien dicta', 'quien ensena', 'quien da', 'titular', 'adjunto', 'prof'
|
||||
]
|
||||
if any(w in q_lower for w in teacher_keywords):
|
||||
all_docentes = User.query.filter(User.is_active == True, func.lower(User.role).like('%docent%')).all()
|
||||
|
||||
# Chequear si la consulta pide la nómina o profesores de las comisiones
|
||||
asking_teacher_list = any(w in q_lower for w in [
|
||||
'comision', 'comisiones', 'esas', 'estos', 'estas', 'cuales', 'quienes',
|
||||
'lista', 'listado', 'todos', 'todas', 'nombre', 'nombres', 'asignados', 'que profesores', 'que docentes'
|
||||
])
|
||||
|
||||
if asking_teacher_list:
|
||||
active_comms_for_teachers = (
|
||||
Commission.query
|
||||
.filter_by(active=True)
|
||||
.join(Subject, Commission.subject_id == Subject.id)
|
||||
.order_by(Subject.name.asc())
|
||||
.all()
|
||||
)
|
||||
teacher_assignments = {}
|
||||
for c in active_comms_for_teachers:
|
||||
t_disp = c.teacher_names if hasattr(c, 'teacher_names') and c.teacher_names != "Sin asignar" else c.teacher_name
|
||||
s_name = c.subject.name if c.subject else c.code
|
||||
if t_disp not in teacher_assignments:
|
||||
teacher_assignments[t_disp] = []
|
||||
teacher_assignments[t_disp].append(f"{s_name} (Com. {c.code})")
|
||||
|
||||
lines.append(f"\nASIGNACIÓN DE DOCENTES A COMISIONES ACTIVAS ({len(active_comms_for_teachers)} comisiones):")
|
||||
for t_name, comm_list in teacher_assignments.items():
|
||||
if len(comm_list) > 6:
|
||||
lines.append(f"• {t_name}: Dicta {len(comm_list)} comisiones ({', '.join(comm_list[:4])} y {len(comm_list)-4} más).")
|
||||
else:
|
||||
lines.append(f"• {t_name}: Dicta {', '.join(comm_list)}")
|
||||
|
||||
# Búsqueda de docente por nombre específico
|
||||
ignored_tokens = {
|
||||
'profesor', 'profesores', 'docente', 'docentes', 'profe', 'profes', 'proferes',
|
||||
'llamado', 'alguno', 'estan', 'registrados', 'cuantos', 'cual', 'cuales', 'quien',
|
||||
'quienes', 'nombre', 'nombres', 'tipo', 'login', 'logins', 'google', 'moodle',
|
||||
'sistema', 'acceso', 'cuentas', 'habilitados', 'activos', 'comision', 'comisiones',
|
||||
'esas', 'estos', 'estas', 'dame', 'dime', 'decime', 'lista', 'listado', 'todos',
|
||||
'todas', 'ver', 'mostrar', 'hay', 'dictan', 'ensenan', 'materias', 'asignaturas'
|
||||
}
|
||||
meaningful_tokens = [tok for tok in tokens if tok not in ignored_tokens]
|
||||
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 not asking_teacher_list and 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.")
|
||||
|
||||
# C3. Búsqueda y Listado de Asignaturas / Materias
|
||||
subj_keywords = ['materia', 'materias', 'asignatura', 'asignaturas', 'catedra', 'catedras']
|
||||
asking_subj_list = (
|
||||
any(sk in q_lower for sk in subj_keywords) and
|
||||
any(lk in q_lower for lk in ['que', 'cuales', 'lista', 'listado', 'todas', 'todos', 'hay', 'activas', 'dame', 'ver'])
|
||||
)
|
||||
if asking_subj_list:
|
||||
all_subjects = Subject.query.filter(Subject.is_active == True).order_by(Subject.name.asc()).all()
|
||||
if all_subjects:
|
||||
lines.append(f"\nLISTADO DE ASIGNATURAS ACTIVAS DEL SISTEMA ({len(all_subjects)} en total):")
|
||||
for s in all_subjects:
|
||||
c_names = s.career_obj.name if s.career_obj else "Carrera General"
|
||||
lines.append(f"• {s.name} (Código: {s.code} | Carrera: {c_names})")
|
||||
elif tokens and not asking_comm_list and not any(w in q_lower for w in teacher_keywords):
|
||||
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)
|
||||
@@ -14,12 +14,12 @@ class MoodleClient:
|
||||
|
||||
@classmethod
|
||||
def get_config(cls) -> Dict[str, Any]:
|
||||
server_url = SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle').rstrip('/')
|
||||
server_url = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/')
|
||||
token = SystemSetting.get_decrypted_value('moodle_ws_token', '')
|
||||
# Fallback a token descubierto en Moodle si no está configurado aún en BD
|
||||
if not token:
|
||||
token = '1a0fee6f654dc3b7f0c02fac90eda327'
|
||||
timeout = int(SystemSetting.get_value('moodle_timeout', 10))
|
||||
token = '810428346d3601c68a37a315fcba8d4391629f46'
|
||||
timeout = int(SystemSetting.get_value('moodle_timeout', 10) or 10)
|
||||
return {
|
||||
'server_url': server_url,
|
||||
'token': token,
|
||||
@@ -28,11 +28,11 @@ class MoodleClient:
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def call(cls, ws_function: str, params: Optional[Dict[str, Any]] = None, method: str = 'GET') -> Dict[str, Any]:
|
||||
def call(cls, ws_function: str, params: Optional[Dict[str, Any]] = None, method: str = 'GET', override_endpoint: Optional[str] = None, override_token: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Ejecuta una llamada Web Service contra Moodle 4.1 en formato JSON."""
|
||||
cfg = cls.get_config()
|
||||
endpoint = cfg['endpoint']
|
||||
token = cfg['token']
|
||||
endpoint = override_endpoint or cfg['endpoint']
|
||||
token = override_token or cfg['token']
|
||||
timeout = cfg['timeout']
|
||||
|
||||
req_params = {
|
||||
@@ -68,26 +68,44 @@ class MoodleClient:
|
||||
# Diagnóstico y Estado
|
||||
# --------------------------------------------------------------------------
|
||||
@classmethod
|
||||
def test_connection(cls) -> Dict[str, Any]:
|
||||
def test_connection(cls, server_url: Optional[str] = None, token: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Prueba si el token y el endpoint responden adecuadamente."""
|
||||
cfg = cls.get_config()
|
||||
target_server = (server_url or cfg['server_url']).rstrip('/')
|
||||
target_token = token or cfg['token']
|
||||
target_endpoint = f"{target_server}/webservice/rest/server.php"
|
||||
|
||||
try:
|
||||
# Consultamos usuarios con un filtro vacío o el admin
|
||||
data = cls.call('core_user_get_users', {
|
||||
'criteria[0][key]': 'email',
|
||||
'criteria[0][value]': '%'
|
||||
})
|
||||
users = data.get('users', [])
|
||||
# Primero intentar obtener información básica del sitio Moodle
|
||||
info = cls.call(
|
||||
'core_webservice_get_site_info',
|
||||
override_endpoint=target_endpoint,
|
||||
override_token=target_token
|
||||
)
|
||||
sitename = info.get('sitename', 'Campus Virtual')
|
||||
user_fullname = info.get('fullname', info.get('username', 'Admin'))
|
||||
|
||||
# Consultar cantidad de usuarios registrados
|
||||
users_data = cls.call(
|
||||
'core_user_get_users',
|
||||
{'criteria[0][key]': 'email', 'criteria[0][value]': '%'},
|
||||
override_endpoint=target_endpoint,
|
||||
override_token=target_token
|
||||
)
|
||||
users_count = len(users_data.get('users', [])) if isinstance(users_data, dict) else 0
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'server_url': cfg['server_url'],
|
||||
'user_count': len(users),
|
||||
'message': f'Conexión exitosa a Moodle 4.1 ({len(users)} usuarios detectados).'
|
||||
'server_url': target_server,
|
||||
'site_name': sitename,
|
||||
'connected_user': user_fullname,
|
||||
'user_count': users_count,
|
||||
'message': f'Conexión exitosa a Moodle ({sitename}): {users_count} usuarios detectados.'
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'server_url': cfg['server_url'],
|
||||
'server_url': target_server,
|
||||
'error': str(e),
|
||||
'message': f'Fallo en la prueba de conexión: {str(e)}'
|
||||
}
|
||||
@@ -113,7 +131,7 @@ class MoodleClient:
|
||||
@classmethod
|
||||
def create_user(cls, username: str, email: str, firstname: str, lastname: str, password: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Crea un nuevo usuario en Moodle (core_user_create_users)."""
|
||||
params = {
|
||||
params: Dict[str, Any] = {
|
||||
'users[0][username]': username.strip().lower(),
|
||||
'users[0][email]': email.strip().lower(),
|
||||
'users[0][firstname]': firstname.strip(),
|
||||
@@ -134,7 +152,7 @@ class MoodleClient:
|
||||
@classmethod
|
||||
def update_user(cls, moodle_user_id: int, firstname: Optional[str] = None, lastname: Optional[str] = None, email: Optional[str] = None) -> Any:
|
||||
"""Actualiza datos de un usuario en Moodle (core_user_update_users)."""
|
||||
params = {'users[0][id]': moodle_user_id}
|
||||
params: Dict[str, Any] = {'users[0][id]': moodle_user_id}
|
||||
if firstname:
|
||||
params['users[0][firstname]'] = firstname
|
||||
if lastname:
|
||||
@@ -174,7 +192,8 @@ class MoodleClient:
|
||||
def get_enrolled_users(cls, course_id: int) -> List[Dict[str, Any]]:
|
||||
"""Obtiene todos los usuarios matriculados en un curso (core_enrol_get_enrolled_users)."""
|
||||
params = {'courseid': course_id}
|
||||
return cls.call('core_enrol_get_enrolled_users', params)
|
||||
res = cls.call('core_enrol_get_enrolled_users', params)
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Asignación de Roles (core_role_*)
|
||||
@@ -209,11 +228,41 @@ class MoodleClient:
|
||||
|
||||
@classmethod
|
||||
def update_users(cls, users: List[Dict[str, Any]]) -> Any:
|
||||
params = {}
|
||||
for idx, u in enumerate(users):
|
||||
for k, v in u.items():
|
||||
params[f'users[{idx}][{k}]'] = v
|
||||
return cls.call('core_user_update_users', params, method='POST')
|
||||
to_update = []
|
||||
to_create = []
|
||||
for u in users:
|
||||
user_data = dict(u)
|
||||
if 'id' not in user_data or not user_data['id']:
|
||||
# Moodle requiere el ID numérico interno en core_user_update_users.
|
||||
# Buscar en Moodle por email o username para obtener su ID:
|
||||
existing = None
|
||||
if user_data.get('email'):
|
||||
existing = cls.get_user_by_email(str(user_data['email']))
|
||||
if not existing and user_data.get('username'):
|
||||
found = cls.get_users_by_criteria('username', str(user_data['username']))
|
||||
if found:
|
||||
existing = found[0]
|
||||
|
||||
if existing and 'id' in existing:
|
||||
user_data['id'] = existing['id']
|
||||
to_update.append(user_data)
|
||||
else:
|
||||
to_create.append(user_data)
|
||||
else:
|
||||
to_update.append(user_data)
|
||||
|
||||
results = []
|
||||
if to_create:
|
||||
res_c = cls.create_users(to_create)
|
||||
results.append(res_c)
|
||||
if to_update:
|
||||
params = {}
|
||||
for idx, u in enumerate(to_update):
|
||||
for k, v in u.items():
|
||||
params[f'users[{idx}][{k}]'] = v
|
||||
res_u = cls.call('core_user_update_users', params, method='POST')
|
||||
results.append(res_u)
|
||||
return results if len(results) > 1 else (results[0] if results else None)
|
||||
|
||||
@classmethod
|
||||
def enrol_users(cls, enrolments: List[Dict[str, Any]]) -> Any:
|
||||
@@ -242,4 +291,121 @@ class MoodleClient:
|
||||
res = cls.call('core_user_get_users', params)
|
||||
return res.get('users', []) if isinstance(res, dict) else []
|
||||
|
||||
@classmethod
|
||||
def get_courses(cls) -> List[Dict[str, Any]]:
|
||||
"""Obtiene la lista de cursos disponibles en Moodle (core_course_get_courses)."""
|
||||
res = cls.call('core_course_get_courses')
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
@classmethod
|
||||
def get_categories(cls) -> List[Dict[str, Any]]:
|
||||
"""Obtiene las categorías de cursos en Moodle (core_course_get_categories)."""
|
||||
res = cls.call('core_course_get_categories')
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
@classmethod
|
||||
def sync_from_moodle_to_app(cls) -> Dict[str, Any]:
|
||||
"""
|
||||
Sincroniza usuarios, roles y cursos desde Moodle hacia la base de datos de Admin Edu Space.
|
||||
"""
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
|
||||
# Obtener todos los roles de la app para mapeo
|
||||
role_map = {r.name.upper(): r for r in Role.query.all()}
|
||||
role_admin = role_map.get('ADMIN')
|
||||
role_docente = role_map.get('DOCENTE')
|
||||
role_alumno = role_map.get('ALUMNO')
|
||||
|
||||
# 1. Traer usuarios de Moodle
|
||||
moodle_users = cls.call('core_user_get_users', {
|
||||
'criteria[0][key]': 'email',
|
||||
'criteria[0][value]': '%'
|
||||
})
|
||||
users_list = moodle_users.get('users', []) if isinstance(moodle_users, dict) else []
|
||||
|
||||
# Cargar todos los usuarios existentes en memoria indexados por email y DNI (O(1) lookup)
|
||||
all_existing_users = User.query.all()
|
||||
user_by_email = {u.email.lower(): u for u in all_existing_users if u.email}
|
||||
user_by_dni = {str(u.document_number): u for u in all_existing_users if u.document_number}
|
||||
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
|
||||
for u in users_list:
|
||||
username = str(u.get('username', '')).strip().lower()
|
||||
email = str(u.get('email', '')).strip().lower()
|
||||
firstname = str(u.get('firstname', '')).strip()
|
||||
lastname = str(u.get('lastname', '')).strip()
|
||||
fullname = f"{firstname} {lastname}".strip() or username
|
||||
|
||||
if not email or username == 'guest':
|
||||
continue
|
||||
|
||||
dni = username if username.isdigit() else None
|
||||
|
||||
# Determinar rol adecuado
|
||||
if username == 'admin':
|
||||
target_role = role_admin
|
||||
elif email.endswith('@udelaciudad.edu.ar') or email.endswith('@unicaba.edu.ar'):
|
||||
target_role = role_docente or role_alumno
|
||||
else:
|
||||
target_role = role_alumno
|
||||
|
||||
# Buscar usuario existente en memoria por email o DNI
|
||||
user = user_by_email.get(email) or (user_by_dni.get(dni) if dni else None)
|
||||
|
||||
if user:
|
||||
changed = False
|
||||
if dni and not user.document_number:
|
||||
user.document_number = dni
|
||||
user_by_dni[dni] = user
|
||||
changed = True
|
||||
if firstname and not user.first_name:
|
||||
user.first_name = firstname
|
||||
changed = True
|
||||
if lastname and not user.last_name:
|
||||
user.last_name = lastname
|
||||
changed = True
|
||||
if target_role and not user.role_id:
|
||||
user.role = target_role.name
|
||||
user.role_id = target_role.id
|
||||
changed = True
|
||||
if changed:
|
||||
updated_count += 1
|
||||
else:
|
||||
role_obj = target_role or role_alumno
|
||||
new_user = User(
|
||||
email=email,
|
||||
name=fullname,
|
||||
first_name=firstname,
|
||||
last_name=lastname,
|
||||
document_type='DNI',
|
||||
document_number=dni,
|
||||
role=role_obj.name if role_obj else 'Alumno',
|
||||
role_id=role_obj.id if role_obj else None,
|
||||
is_active=True
|
||||
)
|
||||
new_user.set_password(dni or username)
|
||||
db.session.add(new_user)
|
||||
user_by_email[email] = new_user
|
||||
if dni:
|
||||
user_by_dni[dni] = new_user
|
||||
created_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
courses = cls.get_courses()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'moodle_users_total': len(users_list),
|
||||
'app_users_created': created_count,
|
||||
'app_users_updated': updated_count,
|
||||
'moodle_courses_found': len(courses),
|
||||
'message': f"Sincronización completada: {created_count} creados, {updated_count} actualizados, {len(courses)} cursos en Moodle."
|
||||
}
|
||||
|
||||
|
||||
moodle_client = MoodleClient()
|
||||
|
||||
@@ -5,7 +5,8 @@ operations between admin-edu-space and Moodle 4.1.
|
||||
Implements Exponential Backoff and Dead Letter Queue (DLQ).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from app import db
|
||||
from app.models.sync_task import MoodleSyncTask
|
||||
from app.services.moodle_client import moodle_client
|
||||
@@ -14,7 +15,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class MoodleQueueService:
|
||||
@staticmethod
|
||||
def enqueue_task(action: str, entity_type: str, entity_id: str = None, payload: dict = None, max_attempts: int = 5) -> MoodleSyncTask:
|
||||
def enqueue_task(action: str, entity_type: str, entity_id: Optional[str] = None, payload: Optional[dict] = None, max_attempts: int = 5) -> MoodleSyncTask:
|
||||
"""
|
||||
Enqueues a new synchronization task to be processed asynchronously.
|
||||
Guarantees that local transactions are never blocked by Moodle unavailability.
|
||||
@@ -22,12 +23,12 @@ class MoodleQueueService:
|
||||
task = MoodleSyncTask(
|
||||
action=action,
|
||||
entity_type=entity_type,
|
||||
entity_id=str(entity_id) if entity_id else None,
|
||||
entity_id=entity_id if entity_id is not None else None,
|
||||
payload=payload or {},
|
||||
status='PENDING',
|
||||
attempts=0,
|
||||
max_attempts=max_attempts,
|
||||
next_retry_at=datetime.utcnow()
|
||||
next_retry_at=datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -41,7 +42,7 @@ class MoodleQueueService:
|
||||
Uses exponential backoff for retries and sends to Dead Letter Queue (FAILED)
|
||||
if max_attempts are exceeded.
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
tasks = MoodleSyncTask.query.filter(
|
||||
MoodleSyncTask.status.in_(['PENDING', 'RETRYING']),
|
||||
(MoodleSyncTask.next_retry_at == None) | (MoodleSyncTask.next_retry_at <= now)
|
||||
@@ -60,21 +61,21 @@ class MoodleQueueService:
|
||||
for task in tasks:
|
||||
results['processed'] += 1
|
||||
task.status = 'PROCESSING'
|
||||
task.updated_at = datetime.utcnow()
|
||||
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
MoodleQueueService._execute_task_action(task)
|
||||
task.status = 'COMPLETED'
|
||||
task.error_message = None
|
||||
task.updated_at = datetime.utcnow()
|
||||
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
db.session.commit()
|
||||
results['succeeded'] += 1
|
||||
logger.info(f"[MoodleQueue] Task {task.id} ({task.action}) completed successfully.")
|
||||
except Exception as e:
|
||||
task.attempts += 1
|
||||
task.error_message = str(e)
|
||||
task.updated_at = datetime.utcnow()
|
||||
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
if task.attempts >= task.max_attempts:
|
||||
task.status = 'FAILED' # Dead Letter Queue (DLQ)
|
||||
@@ -85,7 +86,7 @@ class MoodleQueueService:
|
||||
task.status = 'RETRYING'
|
||||
# Exponential Backoff: 30s, 60s, 120s, 240s... capped at 1 hour
|
||||
delay_seconds = min(3600, (2 ** task.attempts) * 30)
|
||||
task.next_retry_at = datetime.utcnow() + timedelta(seconds=delay_seconds)
|
||||
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=delay_seconds)
|
||||
results['retrying'] += 1
|
||||
logger.warning(f"[MoodleQueue] Task {task.id} failed attempt {task.attempts}/{task.max_attempts}. Next retry in {delay_seconds}s: {e}")
|
||||
|
||||
@@ -123,16 +124,16 @@ class MoodleQueueService:
|
||||
return res
|
||||
|
||||
elif action == 'ASSIGN_ROLE':
|
||||
role_id = payload.get('role_id')
|
||||
user_id = payload.get('user_id')
|
||||
context_id = payload.get('context_id', 1)
|
||||
role_id = int(payload.get('role_id', 5))
|
||||
user_id = int(payload.get('user_id', 0))
|
||||
context_id = int(payload.get('context_id', 1))
|
||||
res = moodle_client.assign_role(role_id, user_id, context_id)
|
||||
return res
|
||||
|
||||
elif action == 'UNASSIGN_ROLE':
|
||||
role_id = payload.get('role_id')
|
||||
user_id = payload.get('user_id')
|
||||
context_id = payload.get('context_id', 1)
|
||||
role_id = int(payload.get('role_id', 5))
|
||||
user_id = int(payload.get('user_id', 0))
|
||||
context_id = int(payload.get('context_id', 1))
|
||||
res = moodle_client.unassign_role(role_id, user_id, context_id)
|
||||
return res
|
||||
|
||||
@@ -150,9 +151,9 @@ class MoodleQueueService:
|
||||
|
||||
task.status = 'PENDING'
|
||||
task.attempts = 0
|
||||
task.next_retry_at = datetime.utcnow()
|
||||
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
task.error_message = None
|
||||
task.updated_at = datetime.utcnow()
|
||||
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleQueue] Task {task_id} manually reset to PENDING.")
|
||||
return True
|
||||
@@ -167,8 +168,8 @@ class MoodleQueueService:
|
||||
for task in failed_tasks:
|
||||
task.status = 'PENDING'
|
||||
task.attempts = 0
|
||||
task.next_retry_at = datetime.utcnow()
|
||||
task.updated_at = datetime.utcnow()
|
||||
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
count += 1
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleQueue] Reset {count} failed tasks back to PENDING.")
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum
|
||||
from typing import List, Dict, Any, Optional
|
||||
from flask import current_app
|
||||
|
||||
from app.models.genetic_algorithm import (
|
||||
ReservationOptimizer,
|
||||
@@ -39,7 +38,7 @@ class OptimizerJob:
|
||||
self.reservations: List[Dict[str, Any]] = []
|
||||
self.conflicts: List[Dict[str, Any]] = []
|
||||
self.error: Optional[str] = None
|
||||
self.created_at = datetime.utcnow()
|
||||
self.created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
self.started_at: Optional[datetime] = None
|
||||
self.completed_at: Optional[datetime] = None
|
||||
self.execution_time_ms: Optional[float] = None
|
||||
@@ -106,12 +105,8 @@ class OptimizerService:
|
||||
with cls._lock:
|
||||
cls._jobs[job_id] = job
|
||||
|
||||
# Si no se pasó app explícitamente, intentar obtener current_app
|
||||
if app is None:
|
||||
try:
|
||||
app = current_app._get_current_object()
|
||||
except Exception:
|
||||
app = None
|
||||
# No background app context required in FastAPI
|
||||
app = None
|
||||
|
||||
thread = threading.Thread(
|
||||
target=cls._run_job_worker,
|
||||
@@ -133,14 +128,15 @@ class OptimizerService:
|
||||
t_start = time.perf_counter()
|
||||
with cls._lock:
|
||||
job.status = OptimizerJobStatus.RUNNING
|
||||
job.started_at = datetime.utcnow()
|
||||
job.started_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
def progress_callback(gen: int, total_gen: int, pct: int, best_fit: float):
|
||||
with cls._lock:
|
||||
job.generation = gen
|
||||
job.total_generations = total_gen
|
||||
job.progress = pct
|
||||
job.fitness_score = best_fit
|
||||
if job:
|
||||
with cls._lock:
|
||||
job.generation = gen
|
||||
job.total_generations = total_gen
|
||||
job.progress = pct
|
||||
job.fitness_score = best_fit
|
||||
|
||||
optimizer = ReservationOptimizer(
|
||||
population_size=job.params.get("population_size", 40),
|
||||
@@ -167,7 +163,7 @@ class OptimizerService:
|
||||
job.assigned_reservations = result.get("assigned_reservations", 0)
|
||||
job.reservations = result.get("reservations", [])
|
||||
job.conflicts = result.get("conflicts", [])
|
||||
job.completed_at = datetime.utcnow()
|
||||
job.completed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
job.execution_time_ms = exec_time_ms
|
||||
|
||||
try:
|
||||
@@ -180,7 +176,7 @@ class OptimizerService:
|
||||
with cls._lock:
|
||||
job.status = OptimizerJobStatus.FAILED
|
||||
job.error = str(ex)
|
||||
job.completed_at = datetime.utcnow()
|
||||
job.completed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
@classmethod
|
||||
def get_job(cls, job_id: str) -> Optional[OptimizerJob]:
|
||||
@@ -217,7 +213,7 @@ class OptimizerService:
|
||||
is_virtual=c_dto.isVirtual,
|
||||
is_active=True
|
||||
)
|
||||
room.id = c_dto.classroomId
|
||||
setattr(room, 'id', c_dto.classroomId)
|
||||
classrooms.append(room)
|
||||
else:
|
||||
classrooms = Classroom.query.filter_by(is_active=True).all()
|
||||
@@ -278,5 +274,5 @@ class OptimizerService:
|
||||
"conflictCount": len(best_individual.conflicts),
|
||||
"fitnessScore": round(best_individual.fitness, 2),
|
||||
"executionTimeMs": exec_ms,
|
||||
"timestamp": datetime.utcnow().isoformat() + "Z"
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
app/services/prompt_security.py - Módulo de Protección Anti-Prompt Injection (SDD-011)
|
||||
Protege a UdeCi contra ataques de Jailbreak, System Prompt Leaks,
|
||||
modos de desarrollador ficticios e inyección de tokens de control LLM.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Tuple, List, Optional
|
||||
|
||||
|
||||
# Patrones de inyección de prompt, jailbreak y fuga de modelo/tokens conocidos (español e inglés)
|
||||
INJECTION_PATTERNS = [
|
||||
# 1. Anulación de instrucciones / prompts (promps, prompts, reglas, directivas)
|
||||
r"ignor[ea]\s+(todo|todos|todas)?\s*(los|las)?\s*(prompts?|promps?|instrucciones|reglas|directivas|comandos|mensajes|restricciones|filtros)?",
|
||||
r"ignore\s+(all|any)?\s*(the)?\s*(prompts?|instructions?|rules?|directives?|commands?|guidelines?|system)?",
|
||||
r"olvida\s+(todo|todos|todas)?\s*(los|las)?\s*(prompts?|promps?|reglas|directivas|instrucciones|filtros|restricciones)",
|
||||
r"forget\s+(all|any)?\s*(the)?\s*(previous)?\s*(rules|instructions|directives|prompts)",
|
||||
r"disregard\s+(all|any)?\s*(previous)?\s*(instructions|prompts|rules)",
|
||||
r"reset\s+(all\s+)?(rules|prompts|instructions)",
|
||||
r"bypas[sa]\s+(las\s+)?(reglas|restricciones|filtros)",
|
||||
|
||||
# 2. Modos no restringidos / Jailbreaks / Simulación
|
||||
r"developer\s+mode",
|
||||
r"modo\s+desarrollador",
|
||||
r"dan\s+mode",
|
||||
r"jailbreak",
|
||||
r"act\s+as\s+(an?\s+)?(unrestricted|evil|unfiltered|hacker|dan)",
|
||||
r"actua\s+como\s+(un\s+)?(hacker|sistema\s+sin\s+restricciones|asistente\s+sin\s+filtros|dan)",
|
||||
r"pretend\s+you\s+(are\s+not|have\s+no|can)\s+rules",
|
||||
r"simula\s+que\s+no\s+tienes\s+reglas",
|
||||
r"ahora\s+eres\s+(libre|otro\s+modelo|un\s+asistente\s+sin\s+limites)",
|
||||
|
||||
# 3. Consultas sobre Modelo de IA subyacente / Fabricante / Arquitectura
|
||||
r"(que|cual)\s+(modelo|arquitectura|llm|ia|motor)\s+(de\s+ia\s+)?(eres|usas|utilizas|te\s+impulsa|hay\s+detras)",
|
||||
r"(who|what)\s+(model|llm|ai|architecture)\s+(are\s+you|is\s+this|powers\s+you)",
|
||||
r"(quien|que\s+empresa)\s+(te\s+creo|te\s+desarrollo|te\s+entreno|es\s+tu\s+fabricante)",
|
||||
r"(who)\s+(created|developed|trained|made)\s+you",
|
||||
r"(dime|decime)\s+(que\s+modelo|cual\s+es\s+tu\s+modelo|la\s+ia\s+que\s+eres|que\s+ia\s+eres)",
|
||||
|
||||
# 4. Filtración de System Prompt, Configuración Interna, Tokens y Credenciales
|
||||
r"(muestra|revela|imprime|dime|revelar|mostrar|dame|decime)\s+(tu\s+)?(system\s+prompt|prompt\s+del\s+sistema|instrucciones\s+internas|reglas\s+secretas|prompt\s+inicial)",
|
||||
r"(reveal|print|show|display|leak)\s+(your\s+)?(system\s+prompt|initial\s+instructions|secret\s+rules)",
|
||||
r"(dame|revela|muestra|dime|decime)\s+(la\s+contrase[ñn]a|el\s+password|las\s+credenciales|los\s+tokens|el\s+archivo\s+\.env|\.credenciales|la\s+configuracion\s+y\s+los\s+tokens)",
|
||||
r"(tokens?\s+de\s+acceso|api[\s_-]?keys?|bearer\s+tokens?|secret_keys?)",
|
||||
r"(give\s+me|reveal|show)\s+(the\s+password|credentials|api\s+keys|\.env|access\s+tokens)"
|
||||
]
|
||||
|
||||
# Tokens de control de delimitación para modelos Qwen / Llama / ChatML
|
||||
SPECIAL_TOKENS = [
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
"<|endoftext|>",
|
||||
"[INST]",
|
||||
"[/INST]",
|
||||
"<<SYS>>",
|
||||
"<</SYS>>",
|
||||
"<|system|>",
|
||||
"<|user|>",
|
||||
"<|assistant|>"
|
||||
]
|
||||
|
||||
|
||||
def normalize_for_security(text: str) -> str:
|
||||
"""Normaliza texto eliminando diacríticos, espacios repetidos y caracteres de control."""
|
||||
if not text:
|
||||
return ""
|
||||
# Quitar tildes y diacríticos
|
||||
nfkd = unicodedata.normalize('NFKD', text)
|
||||
cleaned = ''.join([c for c in nfkd if not unicodedata.combining(c)]).lower()
|
||||
# Reducir espacios múltiples
|
||||
return re.sub(r'\s+', ' ', cleaned).strip()
|
||||
|
||||
|
||||
class PromptSecurityService:
|
||||
"""Servicio de validación y sanitización contra Prompt Injections."""
|
||||
|
||||
@classmethod
|
||||
def sanitize_input(cls, text: str) -> str:
|
||||
"""
|
||||
Elimina o escapa tokens especiales de control de plantilla que
|
||||
podrían intentar inyectar bloques de sistema en el LLM.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
sanitized = text
|
||||
for token in SPECIAL_TOKENS:
|
||||
sanitized = sanitized.replace(token, "")
|
||||
return sanitized.strip()
|
||||
|
||||
@classmethod
|
||||
def validate_user_message(cls, text: str) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Examina el mensaje del usuario para detectar intentos de inyección o jailbreak.
|
||||
Retorna (es_seguro: bool, mensaje_defensivo: Optional[str]).
|
||||
"""
|
||||
if not text:
|
||||
return True, None
|
||||
|
||||
normalized = normalize_for_security(text)
|
||||
|
||||
# Chequear contra la lista de patrones de inyección
|
||||
for pattern in INJECTION_PATTERNS:
|
||||
if re.search(pattern, normalized, re.IGNORECASE):
|
||||
return False, (
|
||||
"Soy **UdeCi**, el tutor virtual institucional de Admin Edu Space (UniCABA). "
|
||||
"Estoy programado exclusivamente para asistirte en la gestión académica, espacios áulicos, "
|
||||
"reservas y consultas universitarias. Por políticas institucionales de seguridad, no tengo permitido "
|
||||
"modificar mis directivas, asumir otras identidades ni revelar configuraciones internas, tokens o instrucciones del sistema."
|
||||
)
|
||||
|
||||
return True, None
|
||||
@@ -0,0 +1,302 @@
|
||||
import re
|
||||
import hmac
|
||||
import hashlib
|
||||
import json
|
||||
import base64
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone, date
|
||||
from typing import Dict, Any, Optional, Tuple, List
|
||||
import jwt
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from config.config import Config
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.building import Building
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.subject import Commission, Subject
|
||||
from schemas.reception_dto import TodayClassDTO
|
||||
from app.services.argentine_dni_parser import parsear_dni
|
||||
|
||||
|
||||
class QRSecurityService:
|
||||
"""
|
||||
Servicio de emisión, validación criptográfica y resolución académica para
|
||||
la Credencial Digital y el Control de Acceso por QR en Recepción (SDD-012).
|
||||
"""
|
||||
|
||||
QR_TOKEN_TYPE = "credential_qr"
|
||||
DEFAULT_VALID_HOURS = 72
|
||||
|
||||
@classmethod
|
||||
def _get_secret(cls) -> str:
|
||||
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
||||
|
||||
@classmethod
|
||||
def generate_qr_token(
|
||||
cls,
|
||||
user: User,
|
||||
hours_valid: int = DEFAULT_VALID_HOURS,
|
||||
valid_seconds: Optional[int] = None
|
||||
) -> str:
|
||||
"""
|
||||
Emite un token JWT firmado de credencial institucional para el usuario.
|
||||
Contiene identificación, rol, DNI y tiempo de expiración.
|
||||
Soporta valid_seconds para tokens dinámicos rotativos anti-captura.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_delta = timedelta(seconds=valid_seconds) if valid_seconds is not None else timedelta(hours=hours_valid)
|
||||
payload = {
|
||||
"sub": str(user.id),
|
||||
"dni": user.document_number or "",
|
||||
"name": user.name or "",
|
||||
"role": (user.role or "ALUMNO").upper(),
|
||||
"type": cls.QR_TOKEN_TYPE,
|
||||
"jti": str(uuid.uuid4())[:8],
|
||||
"iat": now,
|
||||
"exp": now + exp_delta
|
||||
}
|
||||
return jwt.encode(payload, cls._get_secret(), algorithm="HS256")
|
||||
|
||||
@classmethod
|
||||
def decode_and_resolve_user(cls, raw_input: str) -> Tuple[Optional[User], str, str]:
|
||||
"""
|
||||
Decodifica y valida el token escaneado. Soporta:
|
||||
1. Token JWT firmado institucional.
|
||||
2. Formato prefijado 'UNICABA:QR:<token>' (o con 'Ñ' por pistola en teclado español).
|
||||
3. Formato institucional por ID o DNI 'UNICABA:USR:<id>:DNI:<doc>' (o 'UNICABAÑUSRÑ<id>ÑDNIÑ<doc>').
|
||||
4. Formato fallback por DNI 'DNI:<documento>' o número de documento directo.
|
||||
|
||||
Retorna: (User or None, status: 'AUTORIZADO' | 'DENEGADO' | 'RESTRINGIDO', reason: str)
|
||||
"""
|
||||
if not raw_input or not raw_input.strip():
|
||||
return None, "DENEGADO", "El código escaneado está vacío."
|
||||
|
||||
clean = raw_input.strip()
|
||||
|
||||
# Normalizar prefijos de lectores ópticos en teclados con distribución en español:
|
||||
# Los lectores ópticos envían 'Ñ' en lugar de ':' en sistemas operativos con distribución en español cuando leen códigos UNICABA.
|
||||
clean_upper = clean.upper()
|
||||
if "UNICABAÑ" in clean_upper or "ÑUSRÑ" in clean_upper or "ÑDNIÑ" in clean_upper or clean_upper.startswith("USRÑ") or clean_upper.startswith("DNIÑ"):
|
||||
clean_normalized = clean.replace("Ñ", ":").replace("ñ", ":")
|
||||
else:
|
||||
clean_normalized = clean
|
||||
|
||||
# Si viene con prefijo UNICABA:QR:
|
||||
if clean_normalized.startswith("UNICABA:QR:"):
|
||||
clean_normalized = clean_normalized[len("UNICABA:QR:"):].strip()
|
||||
|
||||
# 1. Intentar validar como JWT criptográfico institucional ÚNICAMENTE si tiene formato Base64URL de JWT
|
||||
# Un JWT institucional de UniCABA típicamente comienza con 'eyJ' o sus 3 segmentos son Base64URL puros
|
||||
is_potential_jwt = False
|
||||
if clean_normalized.startswith("eyJ") and clean_normalized.count(".") == 2:
|
||||
is_potential_jwt = True
|
||||
elif clean_normalized.count(".") == 2:
|
||||
jwt_parts = clean_normalized.split(".")
|
||||
if len(jwt_parts) == 3 and all(re.match(r'^[A-Za-z0-9_-]+$', p) for p in jwt_parts):
|
||||
is_potential_jwt = True
|
||||
|
||||
if is_potential_jwt:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
clean_normalized,
|
||||
cls._get_secret(),
|
||||
algorithms=["HS256"],
|
||||
options={"verify_exp": True}
|
||||
)
|
||||
if payload.get("type") == cls.QR_TOKEN_TYPE:
|
||||
user_id = payload.get("sub")
|
||||
user = User.query.get(int(user_id)) if user_id else None
|
||||
if not user:
|
||||
return None, "DENEGADO", "Usuario no encontrado en la base de datos."
|
||||
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "La cuenta del usuario se encuentra inactiva o suspendida."
|
||||
|
||||
return user, "AUTORIZADO", "Credencial institucional válida y activa."
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None, "DENEGADO", "La credencial digital ha expirado (anti-captura activo). Renueve el código en la pantalla del usuario."
|
||||
except jwt.PyJWTError:
|
||||
# Si falló la firma o decodificación, NO abortar: continuar con los métodos de DNI y fallback
|
||||
pass
|
||||
|
||||
# 2. Formatos fallback (DNI Argentino, USR:<id>, DNI:<doc> y entrada directa):
|
||||
# A. Intentar extraer patrón institucional UNICABA:USR:<id>
|
||||
usr_match = re.search(r"USR:(\d+)", clean_normalized)
|
||||
if usr_match:
|
||||
try:
|
||||
u_id = int(usr_match.group(1))
|
||||
if u_id > 0:
|
||||
user_by_id = User.query.get(u_id)
|
||||
if user_by_id:
|
||||
if not user_by_id.is_active:
|
||||
return user_by_id, "RESTRINGIDO", "Usuario inactivo o suspendido en el sistema institucional."
|
||||
return user_by_id, "AUTORIZADO", f"Credencial institucional validada por ID #{user_by_id.id}."
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# B. Intentar extraer patrón institucional DNI:<doc>
|
||||
dni_match = re.search(r"DNI:([a-zA-Z0-9\.\-]+)", clean_normalized, flags=re.IGNORECASE)
|
||||
if dni_match:
|
||||
raw_doc_match = dni_match.group(1).replace(".", "").replace("-", "").strip()
|
||||
if raw_doc_match and raw_doc_match.upper() != "NA":
|
||||
user_by_dni = User.query.filter(
|
||||
or_(
|
||||
User.document_number == raw_doc_match,
|
||||
func.replace(User.document_number, ".", "") == raw_doc_match
|
||||
)
|
||||
).first()
|
||||
if user_by_dni:
|
||||
if not user_by_dni.is_active:
|
||||
return user_by_dni, "RESTRINGIDO", "Usuario inactivo en el sistema institucional."
|
||||
return user_by_dni, "AUTORIZADO", f"Identificación validada por documento de identidad (DNI {raw_doc_match})."
|
||||
|
||||
# C. Reconocimiento universal de DNI Argentino (Formatos Renaper 2009, 2012, 2026, Mi Argentina y PDF417 / QR)
|
||||
dni_info = parsear_dni(clean_normalized) or parsear_dni(clean)
|
||||
if dni_info and dni_info.get("documento"):
|
||||
doc = dni_info["documento"].strip()
|
||||
doc_stripped = doc.lstrip("0") or doc
|
||||
user_by_dni = User.query.filter(
|
||||
or_(
|
||||
User.document_number == doc,
|
||||
User.document_number == doc_stripped,
|
||||
func.replace(User.document_number, ".", "") == doc,
|
||||
func.replace(User.document_number, ".", "") == doc_stripped,
|
||||
User.email.ilike(f"{doc}@%"),
|
||||
User.email.ilike(f"{doc_stripped}@%")
|
||||
)
|
||||
).first()
|
||||
|
||||
# Resiliencia: si no se encontró por DNI exacto pero se extrajo nombre y apellido del DNI oficial
|
||||
if not user_by_dni and dni_info.get("apellido") and dni_info.get("nombre"):
|
||||
first_name = dni_info["nombre"].split()[0]
|
||||
user_by_dni = User.query.filter(
|
||||
User.name.ilike(f"%{dni_info['apellido']}%"),
|
||||
User.name.ilike(f"%{first_name}%")
|
||||
).first()
|
||||
if user_by_dni and not user_by_dni.document_number:
|
||||
try:
|
||||
user_by_dni.document_number = doc
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if user_by_dni:
|
||||
if not user_by_dni.is_active:
|
||||
return user_by_dni, "RESTRINGIDO", f"Usuario inactivo en el sistema institucional (DNI {doc})."
|
||||
nombre_display = f"{dni_info.get('apellido', '')} {dni_info.get('nombre', '')}".strip()
|
||||
detalle = f"Identificación validada por DNI argentino {doc}" + (f" ({nombre_display})" if nombre_display else "")
|
||||
return user_by_dni, "AUTORIZADO", detalle
|
||||
else:
|
||||
nombre_display = f"{dni_info.get('apellido', '')} {dni_info.get('nombre', '')}".strip()
|
||||
if nombre_display:
|
||||
return None, "DENEGADO", f"DNI argentino {doc} ({nombre_display}) no se encuentra registrado en el padrón de UniCABA."
|
||||
return None, "DENEGADO", f"DNI argentino {doc} no se encuentra registrado en el padrón de UniCABA."
|
||||
|
||||
# D. Fallback: Lectura de pistola óptica o documento directo (ej: 'DNI:12345678' o '12345678')
|
||||
doc_num = clean_normalized
|
||||
if doc_num.upper().startswith("DNI:"):
|
||||
doc_num = doc_num[4:].strip()
|
||||
|
||||
# Quitar cualquier carácter residual no alfanumérico si es número de DNI
|
||||
clean_doc = re.sub(r'[^a-zA-Z0-9]', '', doc_num)
|
||||
if clean_doc:
|
||||
clean_stripped = clean_doc.lstrip("0") or clean_doc
|
||||
user = User.query.filter(
|
||||
or_(
|
||||
User.document_number == clean_doc,
|
||||
User.document_number == clean_stripped,
|
||||
func.replace(User.document_number, ".", "") == clean_doc,
|
||||
func.replace(User.document_number, ".", "") == clean_stripped,
|
||||
User.email.ilike(f"{clean_doc}@%"),
|
||||
User.email.ilike(f"{clean_stripped}@%")
|
||||
)
|
||||
).first()
|
||||
if not user and clean_doc.isdigit():
|
||||
# Si no coincide con documento, verificar si coincide con ID institucional directo
|
||||
user = User.query.get(int(clean_doc))
|
||||
|
||||
if user:
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "Usuario inactivo en el sistema institucional."
|
||||
return user, "AUTORIZADO", f"Identificación validada por documento de identidad ({user.document_number or user.id})."
|
||||
|
||||
return None, "DENEGADO", f"No se encontró ningún estudiante o docente con DNI o credencial '{raw_input.strip()}'."
|
||||
|
||||
@classmethod
|
||||
def get_todays_classes_for_user(cls, user: User, target_date: Optional[date] = None) -> List[TodayClassDTO]:
|
||||
"""
|
||||
Recupera el cronograma presencial y virtual asignado para el usuario en la fecha indicada (por defecto hoy).
|
||||
Indica sede, aula física, piso, horarios y nombre del docente.
|
||||
"""
|
||||
ref_date = target_date or date.today()
|
||||
user_role = (user.role or "").lower()
|
||||
classes: List[TodayClassDTO] = []
|
||||
|
||||
start_of_day = datetime.combine(ref_date, datetime.min.time())
|
||||
end_of_day = datetime.combine(ref_date, datetime.max.time())
|
||||
|
||||
# Si el usuario es docente: reservas donde él es el docente asignado
|
||||
if "docente" in user_role or "profesor" in user_role or "teacher" in user_role:
|
||||
reservations = Reservation.query.filter(
|
||||
Reservation.user_id == user.id,
|
||||
Reservation.start_time >= start_of_day,
|
||||
Reservation.start_time <= end_of_day,
|
||||
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
|
||||
for r in reservations:
|
||||
comm = r.commission
|
||||
subj_name = comm.subject.name if (comm and comm.subject) else "Clase Universitaria"
|
||||
comm_name = comm.name if comm else "Comisión"
|
||||
classroom = r.classroom
|
||||
bld = classroom.building_entity if classroom else None
|
||||
|
||||
classes.append(TodayClassDTO(
|
||||
subject_name=subj_name,
|
||||
commission_name=comm_name,
|
||||
classroom_name=classroom.name if classroom else "Aula no asignada",
|
||||
building_name=bld.name if bld else "Sede Central",
|
||||
floor=getattr(classroom, "floor", 1),
|
||||
start_time=r.start_time.strftime("%H:%M"),
|
||||
end_time=r.end_time.strftime("%H:%M"),
|
||||
teacher_name=user.name
|
||||
))
|
||||
return classes
|
||||
|
||||
# Si el usuario es alumno: comisiones donde está inscripto
|
||||
enrollments = StudentEnrollment.query.filter_by(student_id=user.id).all()
|
||||
comm_ids = [e.commission_id for e in enrollments if e.commission_id]
|
||||
|
||||
if not comm_ids:
|
||||
return []
|
||||
|
||||
reservations = Reservation.query.filter(
|
||||
Reservation.commission_id.in_(comm_ids),
|
||||
Reservation.start_time >= start_of_day,
|
||||
Reservation.start_time <= end_of_day,
|
||||
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
|
||||
for r in reservations:
|
||||
comm = r.commission
|
||||
subj_name = comm.subject.name if (comm and comm.subject) else "Materia Cursada"
|
||||
comm_name = comm.name if comm else "Comisión"
|
||||
classroom = r.classroom
|
||||
bld = classroom.building_entity if classroom else None
|
||||
teacher_name = r.user.name if r.user else "Docente Titular"
|
||||
|
||||
classes.append(TodayClassDTO(
|
||||
subject_name=subj_name,
|
||||
commission_name=comm_name,
|
||||
classroom_name=classroom.name if classroom else "Aula no asignada",
|
||||
building_name=bld.name if bld else "Sede Central",
|
||||
floor=getattr(classroom, "floor", 1),
|
||||
start_time=r.start_time.strftime("%H:%M"),
|
||||
end_time=r.end_time.strftime("%H:%M"),
|
||||
teacher_name=teacher_name
|
||||
))
|
||||
|
||||
return classes
|
||||
@@ -0,0 +1,348 @@
|
||||
"""
|
||||
Servicio RAG Embebido (Retrieval-Augmented Generation) para UdeCi
|
||||
Almacenamiento y recuperación semántica en base de datos relacional SQLite/PostgreSQL
|
||||
con aislamiento estricto por rol de usuario.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import List, Dict, Any, Optional
|
||||
from app import db
|
||||
from app.models.knowledge_chunk import KnowledgeChunk
|
||||
|
||||
STOP_WORDS = {
|
||||
"de", "la", "el", "los", "las", "un", "una", "unos", "unas", "en", "para", "por",
|
||||
"con", "sobre", "entre", "hacia", "hasta", "desde", "que", "como", "cual", "quien",
|
||||
"y", "o", "a", "al", "del", "es", "son", "mi", "mis", "tu", "tus", "su", "sus"
|
||||
}
|
||||
|
||||
|
||||
def _normalize_text(text: str) -> str:
|
||||
"""Normaliza texto eliminando acentos, puntuación y convirtiendo a minúsculas."""
|
||||
if not text:
|
||||
return ""
|
||||
text = unicodedata.normalize('NFKD', text).encode('ASCII', 'ignore').decode('utf-8')
|
||||
return re.sub(r'[^a-zA-Z0-9\s]', ' ', text.lower()).strip()
|
||||
|
||||
|
||||
def _tokenize(text: str) -> List[str]:
|
||||
"""Extrae palabras clave significativas eliminando stop words."""
|
||||
norm = _normalize_text(text)
|
||||
tokens = [t for t in norm.split() if len(t) > 2 and t not in STOP_WORDS]
|
||||
return tokens
|
||||
|
||||
|
||||
OFFICIAL_KNOWLEDGE_BASE = [
|
||||
# -------------------------------------------------------------
|
||||
# MANUAL OPERATIVO PARA BEDELÍA Y ADMINISTRADORES
|
||||
# -------------------------------------------------------------
|
||||
{
|
||||
"title": "Circuito Secuencial Canónico de 9 Pasos",
|
||||
"role": "bedelia",
|
||||
"keywords": "circuito pasos bedelia carga sedes aulas ciclos carreras materias comisiones profesores alumnos reservas",
|
||||
"category": "bedelia_manual",
|
||||
"content": (
|
||||
"El flujo operativo oficial de Bedelía en Admin Edu Space consta de 9 pasos secuenciales:\n"
|
||||
"1. Sedes/Edificios: Accede al Menú lateral ➔ Sedes / Edificios para dar de alta el campus y sedes institucionales.\n"
|
||||
"2. Aulas: Accede al Menú lateral ➔ Aulas para crear aulas físicas con piso y aforo, o salas virtuales.\n"
|
||||
"3. Ciclos Lectivos: Accede al Menú lateral ➔ Ciclos Lectivos para definir el cuatrimestre y vigencia.\n"
|
||||
"4. Carreras: Accede al Menú lateral ➔ Carreras para gestionar la oferta académica de UniCABA.\n"
|
||||
"5. Asignaturas: Accede al Menú lateral ➔ Asignaturas para cargar materias asociadas a carreras.\n"
|
||||
"6. Comisiones: Accede al Menú lateral ➔ Comisiones para crear grupos con materia, ciclo y turno.\n"
|
||||
"7. Profesores: Accede al Menú lateral ➔ Profesores para asignar los docentes responsables.\n"
|
||||
"8. Alumnos: Accede al Menú lateral ➔ Alumnos para matricular estudiantes en comisiones.\n"
|
||||
"9. Reservas de Espacio: Accede al Menú lateral ➔ Reservas para asignar aulas presenciales o enlaces virtuales."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Matriz de Conflictos y Validación de Aulas",
|
||||
"role": "bedelia",
|
||||
"keywords": "conflictos superposicion solapamiento aula aforo docente codocencia restriccion diaria",
|
||||
"category": "bedelia_rules",
|
||||
"content": (
|
||||
"La plataforma aplica una matriz de validación en tiempo real para impedir reservas inválidas:\n"
|
||||
"- Conflicto Físico: Dos comisiones no pueden ocupar la misma aula presencial en la misma fecha y franja horaria. En aulas virtuales no aplica colisión.\n"
|
||||
"- Control de Aforo: La cantidad de inscriptos no puede superar la capacidad máxima del aula física.\n"
|
||||
"- Conflicto Docente: Un profesor no puede dictar dos clases simultáneas, salvo que la comisión tenga co-docencia activa registrada.\n"
|
||||
"- Restricción Diaria del Alumno: Un estudiante no puede cursar dos materias regulares el mismo día, salvo cursos cortos o autorización expresa de Bedelía."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Optimizador Genético de Aulas con Inteligencia Artificial",
|
||||
"role": "bedelia",
|
||||
"keywords": "optimizador genetico aulas algoritmo colisiones capacidad asignacion masiva",
|
||||
"category": "bedelia_tools",
|
||||
"content": (
|
||||
"El Optimizador Genético de Aulas (disponible en Menú lateral ➔ Herramientas ➔ Optimizador IA) asigna de forma automatizada aulas físicas a comisiones activas:\n"
|
||||
"- Resuelve superposiciones horarias y minimiza el aforo ocioso adaptando la capacidad del aula al cupo de la materia.\n"
|
||||
"- Permite ejecutar la optimización, previsualizar las asignaciones propuestas con desglose de fitness, y aplicar los cambios masivamente en base de datos con un solo clic con registro en Auditoría."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Importador Masivo de Google Sheets",
|
||||
"role": "bedelia",
|
||||
"keywords": "importador google sheets sincronizacion masiva cartelera excel preview granular",
|
||||
"category": "bedelia_tools",
|
||||
"content": (
|
||||
"La herramienta de sincronización (disponible en Menú lateral ➔ Integraciones ➔ Importar Google Sheets) permite ingerir planillas online de UniCABA:\n"
|
||||
"- Inspección Previa: El botón 'Inspeccionar Sheet Online' muestra una grilla interactiva sin guardar datos directamente.\n"
|
||||
"- Selección Granular: Permite tildar qué entidades importar (reservas, aulas, comisiones, materias, carreras) y filtrar por día de la semana o carrera.\n"
|
||||
"- Modificación Manual de Fecha: Permite corregir o forzar una fecha específica para una fila o grupo de comisiones antes de confirmar la sincronización."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Campus Virtual Moodle, Modalidades de Acceso y Contraseñas",
|
||||
"role": "general",
|
||||
"keywords": "moodle campus virtual udelaciudad acceso contraseña login clave entrar campus sincronizacion",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"Campus Virtual de UniCABA / Universidad de la Ciudad:\n"
|
||||
"- Enlace oficial de acceso: [Campus Virtual UniCABA](https://campus.udelaciudad.edu.ar)\n"
|
||||
"- Diferenciación de tipos de acceso y contraseñas:\n"
|
||||
" * Admin Edu-Space NO establece, almacena ni gestiona las contraseñas de Moodle ni de Google.\n"
|
||||
" * Acceso por Google Workspace (@unicaba.edu.ar): Se ingresa con el correo institucional y la clave administrada en Google de la Ciudad.\n"
|
||||
" * Acceso a Moodle / Campus Virtual: Se ingresa en https://campus.udelaciudad.edu.ar con tu usuario/DNI y la contraseña propia de Moodle. Dicha contraseña es emitida y gestionada de forma independiente por el Campus Virtual (NO por Edu-Space). Si no la recuerdas o necesitas restablecerla, utiliza la opción oficial de recuperación en https://campus.udelaciudad.edu.ar/login/forgot_password.php o comunícate con la Mesa de Ayuda del Campus Virtual.\n"
|
||||
" * Acceso Local de Edu-Space: Exclusivo para usuarios operativos locales (ej: Bedelía o Administradores de Edu-Space).\n"
|
||||
"- Integración técnica: Admin Edu Space se conecta con Moodle 4.1 vía REST Web Services mediante una cola asíncrona resiliente (MoodleSyncTask). Las altas y matriculaciones no bloquean al usuario; se encolan y procesan en background con reintentos exponenciales y Dead Letter Queue (DLQ)."
|
||||
)
|
||||
},
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# MANUAL OPERATIVO PARA DOCENTES Y PROFESORES
|
||||
# -------------------------------------------------------------
|
||||
{
|
||||
"title": "Consulta de Aulas Asignadas y Aulas Virtuales para Docentes",
|
||||
"role": "docente",
|
||||
"keywords": "docente aulas clases cartelera horario google meet salas virtuales",
|
||||
"category": "docente_manual",
|
||||
"content": (
|
||||
"Como docente en Admin Edu Space puedes consultar tus espacios áulicos:\n"
|
||||
"- En el Panel de Inicio y en la Cartelera de Clases (menú superior: Cartelera) puedes ver tus materias asignadas para hoy y la semana.\n"
|
||||
"- Se indica el aula presencial asignada con piso y sede, o el botón directo a la sala virtual de Google Meet / Teams si la modalidad es remota.\n"
|
||||
"- Si requieres un cambio de aula física, debes solicitarlo al personal de Bedelía."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Libro de Calificaciones (Gradebook) y Actas de Regularidad",
|
||||
"role": "docente",
|
||||
"keywords": "calificaciones notas parciales recuperatorio gradebook actas regularidad inmutable",
|
||||
"category": "docente_manual",
|
||||
"content": (
|
||||
"El sistema cuenta con un Libro de Calificaciones digital para cada comisión:\n"
|
||||
"- El docente puede registrar notas de primer parcial, segundo parcial, recuperatorios y calificar como ausente.\n"
|
||||
"- El sistema calcula automáticamente la condición académica del alumno (Regular, Promocionado, Libre).\n"
|
||||
"- Al finalizar el cuatrimestre, el docente puede realizar el Cierre de Acta de Regularidad, quedando registrada de forma inmutable con trazabilidad en auditoría."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Nómina de Alumnos y Comisiones Activas",
|
||||
"role": "docente",
|
||||
"keywords": "nomina alumnos estudiantes comisiones lista asistencia cursada",
|
||||
"category": "docente_manual",
|
||||
"content": (
|
||||
"Los profesores pueden consultar la nómina completa de estudiantes inscriptos en sus asignaturas desde Menú lateral ➔ Comisiones:\n"
|
||||
"- Se visualiza el DNI, nombre, correo institucional y estado de matrícula de cada alumno.\n"
|
||||
"- No está permitido a los docentes crear carreras, borrar aulas ni alterar parámetros de configuración del sistema; estas acciones están reservadas a Bedelía."
|
||||
)
|
||||
},
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# MANUAL PARA ALUMNOS Y ESTUDIANTES
|
||||
# -------------------------------------------------------------
|
||||
{
|
||||
"title": "Consulta de Aula y Horarios de Cursada para Alumnos",
|
||||
"role": "alumno",
|
||||
"keywords": "alumno aula donde curso hoy horario materias clases cartelera",
|
||||
"category": "alumno_manual",
|
||||
"content": (
|
||||
"Para saber en qué aula cursas tus materias:\n"
|
||||
"- Ingresa al Panel de Inicio o a la Cartelera de Clases (menú superior: Cartelera).\n"
|
||||
"- Verás la tarjeta de tu clase del día con el nombre de la materia, comisión, horario de inicio y finalización, y el número de aula física asignada.\n"
|
||||
"- Si la clase es virtual, encontrarás un botón directo para unirte a la videollamada de Google Meet."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Mis Materias Matriculadas y Horarios Semanales",
|
||||
"role": "alumno",
|
||||
"keywords": "materias inscripcion matriculadas horario semanal cursada comisiones",
|
||||
"category": "alumno_manual",
|
||||
"content": (
|
||||
"En la sección 'Mis Materias' del menú lateral puedes verificar:\n"
|
||||
"- La lista de asignaturas en las que te encuentras matriculado en el ciclo lectivo actual.\n"
|
||||
"- El equipo docente a cargo de cada comisión y los días de cursada asignados.\n"
|
||||
"- Recuerda que el sistema impide matricularse en dos materias regulares el mismo día para evitar superposiciones de estudio."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Consulta de Mis Calificaciones y Regularidad para Alumnos",
|
||||
"role": "alumno",
|
||||
"keywords": "notas calificaciones parciales regularidad actas estado academico mis notas hitos",
|
||||
"category": "alumno_manual",
|
||||
"content": (
|
||||
"Para consultar tus calificaciones y regularidad académica de manera personal:\n"
|
||||
"- Ingresa a 'Mis Calificaciones e Hitos' en Menú lateral ➔ Mi Trayectoria ➔ Mis Calificaciones e Hitos.\n"
|
||||
"- Verás la tarjeta de cada materia con tus evaluaciones y parciales, notas obtenidas, promedio y condición (Regular, Promocionado o Libre).\n"
|
||||
"- La información de calificaciones es estrictamente personal y confidencial para cada alumno.\n"
|
||||
"- Ante cualquier discrepancia en tus notas o dudas sobre regularidad, consulta directamente a tu profesor o al departamento de Bedelía."
|
||||
)
|
||||
},
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# INFORMACIÓN GENERAL INSTITUCIONAL
|
||||
# -------------------------------------------------------------
|
||||
{
|
||||
"title": "Acceso a la Plataforma, Tipos de Autenticación y Soporte",
|
||||
"role": "general",
|
||||
"keywords": "login acceso cuenta google sso unicaba soporte contraseña clave credenciales moodle",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"Admin Edu Space y los sistemas de UniCABA admiten tres modalidades de acceso independientes:\n"
|
||||
"1. Acceso con Google Workspace (@unicaba.edu.ar): Se ingresa con el correo institucional y la clave administrada en Google.\n"
|
||||
"2. Acceso a Campus Virtual Moodle ([Campus Virtual UniCABA](https://campus.udelaciudad.edu.ar)): Se ingresa con DNI o usuario y la contraseña propia de Moodle. Importante: Admin Edu-Space NO establece ni almacena las contraseñas de Moodle. Si olvidaste tu clave de Moodle, debes usar el recuperador oficial en https://campus.udelaciudad.edu.ar/login/forgot_password.php o acudir a la Mesa de Ayuda del Campus Virtual.\n"
|
||||
"3. Acceso Local: Para cuentas locales administrativas de Edu-Space (ej. Bedelía/Admin).\n"
|
||||
"- Si tienes inconvenientes de acceso o requieres asistencia técnica, contacta a Soporte IT o al departamento de Bedelía de UniCABA."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Ubicación de la Universidad, Cómo Llegar y Transporte",
|
||||
"role": "general",
|
||||
"keywords": "ubicacion direccion como llegar maps transporte colectivo subte caba sede central peron",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"UniCABA - Universidad de la Ciudad de Buenos Aires:\n"
|
||||
"- Sede Central: Tte. Gral. Juan Domingo Perón 802, San Nicolás, CABA (esquina Esmeralda).\n"
|
||||
"- Enlaces de Google Maps para calcular ruta:\n"
|
||||
" * Destino Sede Central: [Calcular ruta a UniCABA](https://www.google.com/maps/dir/?api=1&destination=UniCABA,+Tte.+Gral.+Juan+Domingo+Perón+802,+CABA)\n"
|
||||
" * Desde tu ubicación actual: [Calcular ruta desde mi ubicación](https://www.google.com/maps/dir/?api=1&origin=current+location&destination=UniCABA,+Tte.+Gral.+Juan+Domingo+Perón+802,+CABA)\n"
|
||||
"- Medios de transporte cercanos:\n"
|
||||
" * Subte: Línea B (Estación Florida / Carlos Pellegrini), Línea D (Estación 9 de Julio / Tribunales), Línea C (Estación Diagonal Norte).\n"
|
||||
" * Colectivos: Metrobus 9 de Julio (Líneas 9, 10, 17, 45, 59, 67, 70, 91, 100) y líneas por Av. Corrientes / Diagonal Norte (24, 29, 111, 146)."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Información Meteorológica y Clima del Campus",
|
||||
"role": "general",
|
||||
"keywords": "clima tiempo temperatura lluvia pronostico meteorologico caba campus sede central",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"UdeCi cuenta con integración meteorológica en tiempo real para la Sede Central (CABA):\n"
|
||||
"- Puedes consultar la temperatura actual, sensación térmica, humedad, condiciones del cielo (despejado, nublado, lluvia) y velocidad del viento en la zona de la universidad.\n"
|
||||
"- Los datos se obtienen de Open-Meteo y se actualizan automáticamente en el sistema para asistir a la comunidad académica en la planificación de su traslado a clases presenciales."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Capacidades y Alcance de UdeCi Tutor Virtual",
|
||||
"role": "general",
|
||||
"keywords": "acceso informacion que puedes hacer alcance funciones datos tutor virtual capacidades",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"UdeCi es el Tutor Virtual institucional de UniCABA en la plataforma Admin Edu Space.\n"
|
||||
"- Información a la que tiene acceso:\n"
|
||||
" * Datos académicos y de cursada: Carreras activas, asignaturas, comisiones, docentes a cargo, alumnos matriculados y distribución de inscriptos.\n"
|
||||
" * Espacios y reservas: Sedes (Central y Campus Virtual), aulas físicas y virtuales, aforos, reservas pendientes y confirmadas.\n"
|
||||
" * Calificaciones e hitos: Evaluaciones parciales, notas, promedio y condición académica según el rol del usuario autenticado (los alumnos solo acceden a sus propias notas).\n"
|
||||
" * Métricas operativas en vivo: Cantidad de comisiones asignadas/sin asignar, comisiones con mayor cantidad de alumnos, nómina de profesores.\n"
|
||||
" * Clima y transporte: Clima actual en la Sede Central y enlaces para navegación en Google Maps.\n"
|
||||
"- Límites de acceso: No tiene acceso a chats privados, datos bancarios, contraseñas ni contenidos multimedia externos ajenos a la vida académica de UniCABA."
|
||||
)
|
||||
},
|
||||
{
|
||||
"title": "Normas Institucionales y Uso Responsable",
|
||||
"role": "general",
|
||||
"keywords": "normas conducta uso responsable porno adultos seguridad etica respeto",
|
||||
"category": "general",
|
||||
"content": (
|
||||
"Admin Edu Space y UdeCi son herramientas estrictamente académicas e institucionales de UniCABA:\n"
|
||||
"- En la universidad y sus sistemas informáticos rigen las normativas de convivencia y uso responsable de la red.\n"
|
||||
"- No se aloja, promueve ni distribuye contenido para adultos, material pornográfico ni ningún tipo de elemento que vulnere el marco normativo institucional.\n"
|
||||
"- El asistente responde con sobriedad y profesionalismo universitario, orientando siempre a las funciones académicas y de gestión áulica."
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class RAGService:
|
||||
"""Servicio de indexación y recuperación semántica de fragmentos RAG."""
|
||||
|
||||
@classmethod
|
||||
def reindex_default_knowledge(cls) -> int:
|
||||
"""Puebla o reinicializa la tabla knowledge_chunks con la documentación oficial."""
|
||||
try:
|
||||
KnowledgeChunk.query.delete()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
count = 0
|
||||
for doc in OFFICIAL_KNOWLEDGE_BASE:
|
||||
chunk = KnowledgeChunk(
|
||||
title=doc["title"],
|
||||
content=doc["content"],
|
||||
role=doc["role"],
|
||||
keywords=doc["keywords"],
|
||||
category=doc.get("category", "manual")
|
||||
)
|
||||
db.session.add(chunk)
|
||||
count += 1
|
||||
|
||||
db.session.commit()
|
||||
return count
|
||||
|
||||
@classmethod
|
||||
def search_relevant_chunks(cls, query: str, user_role: str, limit: int = 3) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Ejecuta una búsqueda semántica de fragmentos relevantes,
|
||||
aplicando un filtro estricto por el rol del usuario para evitar fugas de información.
|
||||
"""
|
||||
# Asegurar que existan chunks en base de datos
|
||||
total_chunks = KnowledgeChunk.query.count()
|
||||
if total_chunks == 0:
|
||||
cls.reindex_default_knowledge()
|
||||
|
||||
normalized_role = (user_role or "alumno").strip().lower()
|
||||
if "docente" in normalized_role or "profesor" in normalized_role or "teacher" in normalized_role:
|
||||
effective_role = "docente"
|
||||
elif "bedelia" in normalized_role or "admin" in normalized_role:
|
||||
effective_role = "bedelia"
|
||||
else:
|
||||
effective_role = "alumno"
|
||||
|
||||
# Filtrar exclusivamente por rol permitido y documentos generales
|
||||
allowed_roles = [effective_role, "general"]
|
||||
candidates = KnowledgeChunk.query.filter(KnowledgeChunk.role.in_(allowed_roles)).all()
|
||||
|
||||
query_tokens = _tokenize(query)
|
||||
if not query_tokens:
|
||||
# Si la consulta no tiene tokens específicos, retornar los fragmentos introductorios del rol
|
||||
return [c.to_dict() for c in candidates[:limit]]
|
||||
|
||||
scored = []
|
||||
for chunk in candidates:
|
||||
score = 0.0
|
||||
norm_title = _normalize_text(chunk.title)
|
||||
norm_content = _normalize_text(chunk.content)
|
||||
norm_keywords = _normalize_text(chunk.keywords or "")
|
||||
|
||||
for token in query_tokens:
|
||||
# Coincidencia en título (+5 puntos)
|
||||
if token in norm_title:
|
||||
score += 5.0
|
||||
# Coincidencia en keywords (+3 puntos)
|
||||
if token in norm_keywords:
|
||||
score += 3.0
|
||||
# Coincidencia en contenido (+1 punto)
|
||||
if token in norm_content:
|
||||
score += 1.0
|
||||
|
||||
if score > 0:
|
||||
scored.append((score, chunk))
|
||||
|
||||
# Ordenar de mayor a menor relevancia
|
||||
scored.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
if scored:
|
||||
results = [item[1].to_dict() for item in scored[:limit]]
|
||||
else:
|
||||
# Fallback a fragmentos generales del rol
|
||||
results = [c.to_dict() for c in candidates[:limit]]
|
||||
|
||||
return results
|
||||
@@ -21,9 +21,30 @@ class ReservationService:
|
||||
return self.reservation_repo.get_by_id(reservation_id)
|
||||
|
||||
def list_reservations(self, start_dt: datetime, end_dt: datetime,
|
||||
classroom_id: Optional[int] = None) -> List[Reservation]:
|
||||
"""Obtiene reservas dentro de un rango temporal."""
|
||||
return self.reservation_repo.get_by_date_range(start_dt, end_dt, classroom_id=classroom_id)
|
||||
classroom_id: Optional[int] = None,
|
||||
is_hide_virtual: bool = False,
|
||||
only_virtual: bool = False,
|
||||
status: Optional[str] = None,
|
||||
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(
|
||||
start_dt, end_dt,
|
||||
classroom_id=classroom_id,
|
||||
is_hide_virtual=is_hide_virtual,
|
||||
only_virtual=only_virtual,
|
||||
status=status,
|
||||
floor=floor,
|
||||
shift=shift,
|
||||
search=search,
|
||||
teacher_id=teacher_id,
|
||||
student_id=student_id,
|
||||
limit=limit
|
||||
)
|
||||
|
||||
def check_conflicts(self, classroom_id: int, start_time: datetime, end_time: datetime,
|
||||
exclude_id: Optional[int] = None) -> List[Reservation]:
|
||||
@@ -171,42 +192,46 @@ class ReservationService:
|
||||
if not reservation:
|
||||
raise ValueError(f"Reserva con ID {reservation_id} no encontrada.")
|
||||
|
||||
classroom_id = dto.classroom_id or reservation.classroom_id
|
||||
start_time = dto.start_time or reservation.start_time
|
||||
end_time = dto.end_time or reservation.end_time
|
||||
expected_attendees = dto.expected_attendees if dto.expected_attendees is not None else reservation.expected_attendees
|
||||
c_id = int(dto.classroom_id or getattr(reservation, 'classroom_id', 0) or 0)
|
||||
s_time = dto.start_time or getattr(reservation, 'start_time')
|
||||
e_time = dto.end_time or getattr(reservation, 'end_time')
|
||||
exp_att_raw = dto.expected_attendees if dto.expected_attendees is not None else getattr(reservation, 'expected_attendees', 0)
|
||||
exp_att = int(exp_att_raw) if exp_att_raw is not None else 0
|
||||
t_id = int(getattr(reservation, 'user_id')) if getattr(reservation, 'user_id', None) else None
|
||||
comm_id = int(getattr(reservation, 'commission_id')) if getattr(reservation, 'commission_id', None) else None
|
||||
r_id = int(getattr(reservation, 'id')) if getattr(reservation, 'id', None) else None
|
||||
|
||||
matrix = self.check_full_conflicts_matrix(
|
||||
classroom_id=classroom_id,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
teacher_id=reservation.user_id,
|
||||
commission_id=reservation.commission_id,
|
||||
expected_attendees=expected_attendees,
|
||||
classroom_id=c_id,
|
||||
start_time=s_time,
|
||||
end_time=e_time,
|
||||
teacher_id=t_id,
|
||||
commission_id=comm_id,
|
||||
expected_attendees=exp_att,
|
||||
allow_co_teaching_exception=getattr(dto, 'allow_co_teaching_exception', False),
|
||||
exclude_id=reservation.id
|
||||
exclude_id=r_id
|
||||
)
|
||||
if matrix['is_blocked']:
|
||||
raise ValueError(" | ".join(matrix['block_reasons']))
|
||||
|
||||
if dto.classroom_id is not None:
|
||||
reservation.classroom_id = dto.classroom_id
|
||||
setattr(reservation, 'classroom_id', dto.classroom_id)
|
||||
if dto.start_time is not None:
|
||||
reservation.start_time = dto.start_time
|
||||
setattr(reservation, 'start_time', dto.start_time)
|
||||
if dto.end_time is not None:
|
||||
reservation.end_time = dto.end_time
|
||||
setattr(reservation, 'end_time', dto.end_time)
|
||||
if dto.purpose is not None:
|
||||
reservation.purpose = dto.purpose
|
||||
setattr(reservation, 'purpose', dto.purpose)
|
||||
if dto.expected_attendees is not None:
|
||||
reservation.expected_attendees = dto.expected_attendees
|
||||
setattr(reservation, 'expected_attendees', dto.expected_attendees)
|
||||
if dto.shift is not None:
|
||||
reservation.shift = dto.shift
|
||||
setattr(reservation, 'shift', dto.shift)
|
||||
if dto.virtual_link is not None:
|
||||
reservation.virtual_link = dto.virtual_link
|
||||
setattr(reservation, 'virtual_link', dto.virtual_link)
|
||||
if dto.notes is not None:
|
||||
reservation.notes = dto.notes
|
||||
setattr(reservation, 'notes', dto.notes)
|
||||
if dto.status is not None:
|
||||
reservation.status = dto.status
|
||||
setattr(reservation, 'status', dto.status)
|
||||
|
||||
return self.reservation_repo.save(reservation)
|
||||
|
||||
@@ -215,7 +240,7 @@ class ReservationService:
|
||||
reservation = self.reservation_repo.get_by_id(reservation_id)
|
||||
if not reservation:
|
||||
return False
|
||||
reservation.status = ReservationStatus.CANCELLED.value
|
||||
setattr(reservation, 'status', ReservationStatus.CANCELLED.value)
|
||||
self.reservation_repo.save(reservation)
|
||||
return True
|
||||
|
||||
@@ -224,6 +249,6 @@ class ReservationService:
|
||||
reservation = self.reservation_repo.get_by_id(reservation_id)
|
||||
if not reservation:
|
||||
return False
|
||||
reservation.status = ReservationStatus.CONFIRMED.value
|
||||
setattr(reservation, 'status', ReservationStatus.CONFIRMED.value)
|
||||
self.reservation_repo.save(reservation)
|
||||
return True
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from typing import Dict, Any, List, Optional
|
||||
import urllib.request
|
||||
import csv
|
||||
import io
|
||||
@@ -11,7 +12,57 @@ from app.models.subject import Subject, Commission
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.user import User
|
||||
|
||||
BASE_CSV_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSc_T_BQjbn3uPelioCgx52UM5Py-qNhJN0TYPd1kmsN5jdb3Q8rAaIvNMF_2ZTzQt6bH--yIWQKrKR/pub?single=true&output=csv'
|
||||
BASE_CSV_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSc_T_BQjbn3uPelioCgx52UM5Py-qNhJN0TYPd1kmsN5jdb3Q8rAaIvNMF_2ZTzQt6bH--yIWQKrKR/pub?output=csv'
|
||||
|
||||
# Mapeo canónico de carreras de UniCABA para desglosar y normalizar registros compuestos
|
||||
CANONICAL_CAREERS = {
|
||||
'DATOS': 'DATOS (CCC)',
|
||||
'DATOS (CCC)': 'DATOS (CCC)',
|
||||
'DATOS(CCC)': 'DATOS (CCC)',
|
||||
'TEC.DIG': 'TEC. DIG. (CCC)',
|
||||
'TEC. DIG (CCC)': 'TEC. DIG. (CCC)',
|
||||
'TEC. DIG. (CCC)': 'TEC. DIG. (CCC)',
|
||||
'TEC DIG': 'TEC. DIG. (CCC)',
|
||||
'VIDEOJUEGOS': 'VIDEOJUEGOS (CCC)',
|
||||
'VIDEOJUEGOS (CCC)': 'VIDEOJUEGOS (CCC)',
|
||||
'PROF PROF': 'PROF PROF (CCC)',
|
||||
'PROF PROF (CCC)': 'PROF PROF (CCC)',
|
||||
'CIENCIAS': 'CIENCIAS',
|
||||
'EF. SALUD': 'EF. SALUD',
|
||||
'EF. GESTIÓN': 'EF. GESTIÓN',
|
||||
'EF. GESTION': 'EF. GESTIÓN',
|
||||
'ETD': 'ETD (CCC)',
|
||||
'ETD (CCC)': 'ETD (CCC)',
|
||||
'MONO': 'MONODISCIPLINARES',
|
||||
'MONODISCIPLINARES': 'MONODISCIPLINARES',
|
||||
'PUEP': 'PUEP',
|
||||
'PUEP CCC': 'PUEP CCC',
|
||||
'INGLÉS': 'INGLÉS',
|
||||
'INGLES': 'INGLÉS',
|
||||
'GESTIÓN (CCC)': 'Gestión (CCC)',
|
||||
'GESTION (CCC)': 'Gestión (CCC)',
|
||||
'DIPLO. ALFABETIZACIÓN': 'DIPLO. ALFABETIZACIÓN',
|
||||
'DIPLO. ALFABETIZACION': 'DIPLO. ALFABETIZACIÓN',
|
||||
'DIPLO. BILINGUE': 'DIPLO. BILINGUE',
|
||||
'POSG. PRIMARIA': 'POSG. PRIMARIA',
|
||||
'POSG. INICIAL': 'POSG. INICIAL',
|
||||
'POSG. INCLUSIVAS': 'POSG. INCLUSIVAS',
|
||||
}
|
||||
|
||||
def normalize_day_name(day_str):
|
||||
"""Normaliza cualquier variante de día a su nombre canónico en español (Lunes..Sábado)"""
|
||||
if not day_str:
|
||||
return ''
|
||||
d = day_str.strip().lower()
|
||||
d = d.replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u')
|
||||
if 'lun' in d: return 'Lunes'
|
||||
if 'mar' in d: return 'Martes'
|
||||
if 'mie' in d: return 'Miércoles'
|
||||
if 'jue' in d: return 'Jueves'
|
||||
if 'vie' in d: return 'Viernes'
|
||||
if 'sab' in d: return 'Sábado'
|
||||
if 'dom' in d: return 'Domingo'
|
||||
return day_str.strip()
|
||||
|
||||
def map_day_to_idx(day_str):
|
||||
"""Mapea el nombre del día (o prefijo) a su índice numérico 0..6 (Lunes=0)"""
|
||||
@@ -25,6 +76,36 @@ def map_day_to_idx(day_str):
|
||||
if 'dom' in d: return 6
|
||||
return 0
|
||||
|
||||
def parse_careers_list(c_str):
|
||||
"""Parsea y normaliza cadenas de carreras compuestas separadas por guiones o comas"""
|
||||
if not c_str:
|
||||
return ['General']
|
||||
parts = re.split(r'\s*-\s*|(?<=\))\s*-\s*|\s*,\s*', c_str)
|
||||
result = []
|
||||
for p in parts:
|
||||
clean = p.strip()
|
||||
if not clean:
|
||||
continue
|
||||
upper_clean = clean.upper()
|
||||
matched = False
|
||||
for k, v in CANONICAL_CAREERS.items():
|
||||
if upper_clean == k.upper():
|
||||
if v not in result:
|
||||
result.append(v)
|
||||
matched = True
|
||||
break
|
||||
if not matched:
|
||||
if clean not in result:
|
||||
result.append(clean)
|
||||
return result if result else ['General']
|
||||
|
||||
def parse_subject_codes(code_str):
|
||||
"""Parsea códigos de materias que pueden venir combinados con barras (ej: ASIG00113 / ASIG000082)"""
|
||||
if not code_str:
|
||||
return []
|
||||
parts = re.split(r'\s*/\s*|\s*,\s*', code_str)
|
||||
return [p.strip() for p in parts if p.strip()]
|
||||
|
||||
def normalize_sheets_url(url):
|
||||
"""
|
||||
Normaliza enlaces de Google Sheets (compartidos, de edición, con /u/1/, #gid=... o /pubhtml)
|
||||
@@ -38,7 +119,7 @@ def normalize_sheets_url(url):
|
||||
pub_match = re.search(r'/spreadsheets/(?:u/\d+/)?d/e/([a-zA-Z0-9-_]+)', url)
|
||||
if pub_match:
|
||||
doc_id = pub_match.group(1)
|
||||
return f"https://docs.google.com/spreadsheets/d/e/{doc_id}/pub?single=true&output=csv"
|
||||
return f"https://docs.google.com/spreadsheets/d/e/{doc_id}/pub?output=csv"
|
||||
|
||||
# 2. Enlace de edición o exportación (/d/<SPREADSHEET_ID>/...)
|
||||
sheet_id_match = re.search(r'/spreadsheets/(?:u/\d+/)?d/([a-zA-Z0-9-_]+)', url)
|
||||
@@ -59,10 +140,32 @@ SHEETS_CONFIG = [
|
||||
|
||||
TIME_REGEX = re.compile(r'(\d{1,2})(?::(\d{2}))?\s*(?:a|-|to)\s*(\d{1,2})(?::(\d{2}))?', re.IGNORECASE)
|
||||
|
||||
def parse_flexible_date(val: Any) -> Optional[date]:
|
||||
"""
|
||||
Parsea flexiblemente fechas provistas en formato DD/MM/AAAA (%d/%m/%Y),
|
||||
DD-MM-AAAA (%d-%m-%Y), ISO YYYY-MM-DD (%Y-%m-%d) o instancias de date / datetime.
|
||||
"""
|
||||
if not val:
|
||||
return None
|
||||
if isinstance(val, datetime):
|
||||
return val.date()
|
||||
if isinstance(val, date):
|
||||
return val
|
||||
if isinstance(val, str):
|
||||
cleaned = val.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
for fmt in ('%d/%m/%Y', '%Y-%m-%d', '%d-%m-%Y', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(cleaned, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
class GoogleSheetsImporter:
|
||||
"""
|
||||
Service to fetch, parse, and synchronize academic schedules,
|
||||
classrooms, careers, and subjects from the official UniCABA Google Sheet.
|
||||
Servicio para descargar, parsear y sincronizar cursadas académicas,
|
||||
aulas, carreras y asignaturas compartidas desde el Google Sheet oficial de UniCABA.
|
||||
"""
|
||||
|
||||
def __init__(self, base_url=None):
|
||||
@@ -82,7 +185,7 @@ class GoogleSheetsImporter:
|
||||
def get_sheets_config(self):
|
||||
"""
|
||||
Descubre las pestañas y GIDs dinámicamente desde /pubhtml si está disponible,
|
||||
o utiliza el fallback SHEETS_CONFIG preconfigurado.
|
||||
o utiliza el fallback SHEETS_CONFIG preconfigurado para los 6 días de cursada.
|
||||
"""
|
||||
pub_match = re.search(r'/spreadsheets/d/e/([a-zA-Z0-9-_]+)', self.base_url)
|
||||
if pub_match:
|
||||
@@ -91,12 +194,12 @@ class GoogleSheetsImporter:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
pubhtml_url,
|
||||
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) EduSpace/2.0'}
|
||||
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) EduSpace/3.4'}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=12) as resp:
|
||||
with urllib.request.urlopen(req, timeout=12) as resp: # nosec B310
|
||||
html_content = resp.read().decode('utf-8', errors='replace')
|
||||
# Extraer pares name y gid de Google Sheets pubhtml
|
||||
found = re.findall(r'name:\s*["\']([^"\']+)["\'],\s*gid:\s*["\'](\d+)["\']', html_content)
|
||||
found = re.findall(r'name:\s*["\']([^"\']+)["\'][^}]*?gid:\s*["\'](\d+)["\']', html_content)
|
||||
if found:
|
||||
discovered = []
|
||||
for name, gid in found:
|
||||
@@ -121,7 +224,7 @@ class GoogleSheetsImporter:
|
||||
raise ValueError(f"URL scheme not permitted: {url}")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) EduSpace/2.0'}
|
||||
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) EduSpace/3.4'}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=25) as resp: # nosec B310
|
||||
return resp.read().decode('utf-8', errors='replace')
|
||||
@@ -189,6 +292,14 @@ class GoogleSheetsImporter:
|
||||
elif h < 13:
|
||||
record_shift = 'Mañana'
|
||||
|
||||
v_link_row = None
|
||||
if len(row) > col_offset + 5:
|
||||
for extra_c in row[col_offset + 5:]:
|
||||
extra_clean = _clean(extra_c)
|
||||
if any(x in extra_clean.lower() for x in ['http://', 'https://', 'zoom.us', 'meet.google.com', 'teams.microsoft.com']):
|
||||
v_link_row = extra_clean
|
||||
break
|
||||
|
||||
records.append({
|
||||
'dia': sheet_name,
|
||||
'codigo': codigo,
|
||||
@@ -196,13 +307,14 @@ class GoogleSheetsImporter:
|
||||
'aula': aula,
|
||||
'carrera': carrera,
|
||||
'horario': horario,
|
||||
'turno': record_shift
|
||||
'turno': record_shift,
|
||||
'virtual_link': v_link_row
|
||||
})
|
||||
return records
|
||||
|
||||
def normalize_room(self, aula_raw):
|
||||
"""
|
||||
Normalize room string into (building, room_number, floor, capacity)
|
||||
Normaliza cadena de aula en (building, room_number, floor, capacity)
|
||||
"""
|
||||
aula_upper = aula_raw.upper().strip()
|
||||
if not aula_upper or any(x in aula_upper for x in ['FERIADO', 'SIN ACTIVIDAD', 'CONSULTAR EN BEDELIA']):
|
||||
@@ -272,15 +384,232 @@ class GoogleSheetsImporter:
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
def sync(self):
|
||||
def inspect_sheet_content(self, filter_career=None, filter_subject=None, filter_day=None, filter_days=None, manual_date=None):
|
||||
"""
|
||||
Main synchronization process:
|
||||
1. Fetches all 6 day sheets.
|
||||
2. Upserts Careers, Classrooms, Subjects, Commissions.
|
||||
3. Generates Reservations in the calendar for the semester.
|
||||
Descarga e inspecciona las hojas del Sheet online para extraer:
|
||||
- Días disponibles con cantidad de filas
|
||||
- Carreras únicas
|
||||
- Materias únicas con sus códigos, nombres y carreras
|
||||
- Grilla de pre-visualización interactiva (preview_rows) según los filtros aplicados
|
||||
"""
|
||||
stats = {
|
||||
sheets_to_process = self.get_sheets_config()
|
||||
days_info = []
|
||||
careers_set = set()
|
||||
subjects_map = {}
|
||||
total_rows = 0
|
||||
preview_rows = []
|
||||
|
||||
# Normalizar días seleccionados
|
||||
allowed_days = None
|
||||
if filter_days:
|
||||
if isinstance(filter_days, str):
|
||||
allowed_days = [normalize_day_name(d) for d in filter_days.split(',') if d.strip()]
|
||||
elif isinstance(filter_days, (list, set)):
|
||||
allowed_days = [normalize_day_name(d) for d in filter_days if d]
|
||||
elif filter_day:
|
||||
nd = normalize_day_name(filter_day)
|
||||
if nd and nd.upper() not in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
|
||||
allowed_days = [nd]
|
||||
|
||||
# Normalizar fecha manual para fecha inferida base
|
||||
manual_dt = parse_flexible_date(manual_date)
|
||||
|
||||
# Referencia de semana base: lunes 5 de octubre de 2026 (semana activa del 2° cuatrimestre)
|
||||
ref_monday = date(2026, 10, 5)
|
||||
if manual_dt:
|
||||
ref_monday = manual_dt - timedelta(days=manual_dt.weekday())
|
||||
|
||||
row_counter = 0
|
||||
for sheet_cfg in sheets_to_process:
|
||||
day_name = sheet_cfg['name']
|
||||
norm_day = normalize_day_name(day_name)
|
||||
day_idx = sheet_cfg.get('day_idx', 0)
|
||||
|
||||
try:
|
||||
csv_data = self.fetch_sheet_csv(sheet_cfg['gid'])
|
||||
rows = self.parse_sheet_rows(csv_data, day_name)
|
||||
total_rows += len(rows)
|
||||
days_info.append({
|
||||
'name': day_name,
|
||||
'gid': sheet_cfg['gid'],
|
||||
'day_idx': day_idx,
|
||||
'rows_count': len(rows),
|
||||
'status': 'OK'
|
||||
})
|
||||
|
||||
# Si este día no está entre los permitidos, no lo agregamos a preview_rows
|
||||
if allowed_days and norm_day not in allowed_days:
|
||||
continue
|
||||
|
||||
for r in rows:
|
||||
carreras = parse_careers_list(r.get('carrera', ''))
|
||||
for c in carreras:
|
||||
if c and c != 'General':
|
||||
careers_set.add(c)
|
||||
|
||||
code = r.get('codigo', '').strip()
|
||||
name = r.get('asignatura', '').strip()
|
||||
if code and name:
|
||||
if code not in subjects_map:
|
||||
subjects_map[code] = {
|
||||
'code': code,
|
||||
'name': name,
|
||||
'careers': carreras,
|
||||
'day': day_name
|
||||
}
|
||||
|
||||
# Evaluar coincidencia de filtros de Carrera y Materia para la pre-visualización
|
||||
if filter_career:
|
||||
fc = filter_career.strip().upper()
|
||||
match_c = any(fc in c.upper() or c.upper() in fc for c in carreras) or (fc in r.get('carrera', '').upper())
|
||||
if not match_c:
|
||||
continue
|
||||
|
||||
if filter_subject:
|
||||
fs = filter_subject.strip().upper()
|
||||
sub_codes = parse_subject_codes(code)
|
||||
match_s = (fs in code.upper()) or (fs in name.upper()) or any(fs in sc.upper() for sc in sub_codes)
|
||||
if not match_s:
|
||||
continue
|
||||
|
||||
row_counter += 1
|
||||
aula_raw = r.get('aula', '').strip()
|
||||
room_info = self.normalize_room(aula_raw)
|
||||
is_virtual = bool(room_info and ('VIRTUAL' in str(room_info.get('code', '')).upper() or room_info.get('building') == 'Campus Virtual'))
|
||||
|
||||
# Calcular fecha tentativa
|
||||
target_date = ref_monday + timedelta(days=int(day_idx))
|
||||
if manual_dt and norm_day == normalize_day_name(['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'][manual_dt.weekday()]):
|
||||
target_date = manual_dt
|
||||
|
||||
# Validaciones
|
||||
is_valid = True
|
||||
has_warning = False
|
||||
warning_msg = None
|
||||
|
||||
if not code or not name:
|
||||
is_valid = False
|
||||
warning_msg = "Falta código o nombre de asignatura"
|
||||
elif not room_info or not aula_raw or any(x in aula_raw.upper() for x in ['FERIADO', 'SIN ACTIVIDAD', 'CONSULTAR']):
|
||||
has_warning = True
|
||||
warning_msg = f"Aula pendiente o sin asignar ({aula_raw or 'Vacía'})"
|
||||
|
||||
preview_rows.append({
|
||||
'id': row_counter,
|
||||
'dia': norm_day,
|
||||
'day_idx': day_idx,
|
||||
'codigo': code,
|
||||
'asignatura': name,
|
||||
'aula': aula_raw or (room_info['code'] if room_info else 'Sin Aula'),
|
||||
'aula_normalizada': room_info['code'] if room_info else 'Sin Aula',
|
||||
'is_virtual': is_virtual,
|
||||
'carrera': r.get('carrera', 'General'),
|
||||
'carreras_list': carreras,
|
||||
'horario': r.get('horario', ''),
|
||||
'turno': r.get('turno', 'Mañana'),
|
||||
'inferred_date': target_date.strftime('%Y-%m-%d'),
|
||||
'inferred_date_display': target_date.strftime('%d/%m/%Y'),
|
||||
'is_valid': is_valid,
|
||||
'has_warning': has_warning,
|
||||
'warning_msg': warning_msg
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
days_info.append({
|
||||
'name': day_name,
|
||||
'gid': sheet_cfg['gid'],
|
||||
'day_idx': day_idx,
|
||||
'rows_count': 0,
|
||||
'status': 'Error',
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
return {
|
||||
'total_rows': total_rows,
|
||||
'matching_rows': len(preview_rows),
|
||||
'days': days_info,
|
||||
'careers': sorted(list(careers_set)),
|
||||
'subjects': sorted(list(subjects_map.values()), key=lambda x: x['code']),
|
||||
'preview_rows': preview_rows
|
||||
}
|
||||
|
||||
def sync(
|
||||
self,
|
||||
filter_career=None,
|
||||
filter_subject=None,
|
||||
filter_day=None,
|
||||
filter_days=None,
|
||||
manual_date=None,
|
||||
single_date_only=False,
|
||||
weeks_to_generate=16,
|
||||
date_from=None,
|
||||
date_to=None,
|
||||
import_careers=True,
|
||||
import_subjects=True,
|
||||
import_commissions=True,
|
||||
import_classrooms=True,
|
||||
import_reservations=True,
|
||||
selected_rows=None
|
||||
):
|
||||
"""
|
||||
Proceso principal de sincronización con soporte de filtros, entidades granulares y alcance temporal:
|
||||
:param filter_career: Filtrar por carrera específica (ej. 'DATOS (CCC)')
|
||||
:param filter_subject: Filtrar por código o nombre de materia (ej. 'ASIG00113')
|
||||
:param filter_day: Filtrar por día específico ('Lunes'..'Sábado' o 'ALL')
|
||||
:param filter_days: Lista o cadena de días específicos (ej. ['Lunes', 'Martes'])
|
||||
:param manual_date: Fecha manual específica (YYYY-MM-DD o objeto date)
|
||||
:param single_date_only: Si es True y hay manual_date, crea reserva solo para esa fecha puntual
|
||||
:param weeks_to_generate: Número de semanas consecutivas a generar (1..30, defecto 16)
|
||||
:param date_from: Fecha de inicio de rango (YYYY-MM-DD)
|
||||
:param date_to: Fecha de fin de rango (YYYY-MM-DD)
|
||||
:param import_careers: Booleano para importar/crear carreras
|
||||
:param import_subjects: Booleano para importar/crear asignaturas
|
||||
:param import_commissions: Booleano para importar/crear comisiones
|
||||
:param import_classrooms: Booleano para importar/crear aulas
|
||||
:param import_reservations: Booleano para importar/crear reservas
|
||||
:param selected_rows: Lista de filas específicas pre-seleccionadas desde la grilla interactiva
|
||||
"""
|
||||
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
|
||||
|
||||
# Normalizar fecha manual si fue provista
|
||||
manual_dt = parse_flexible_date(manual_date)
|
||||
|
||||
# Normalizar rango de fechas (date_from y date_to)
|
||||
date_from_dt = parse_flexible_date(date_from)
|
||||
date_to_dt = parse_flexible_date(date_to)
|
||||
|
||||
if date_from_dt and date_to_dt and date_from_dt > date_to_dt:
|
||||
date_from_dt, date_to_dt = date_to_dt, date_from_dt
|
||||
|
||||
# Normalizar número de semanas a generar
|
||||
num_weeks = 16
|
||||
if weeks_to_generate is not None:
|
||||
try:
|
||||
num_weeks = max(1, min(30, int(weeks_to_generate)))
|
||||
except (ValueError, TypeError):
|
||||
num_weeks = 16
|
||||
|
||||
# Normalizar días permitidos
|
||||
allowed_days = None
|
||||
if filter_days:
|
||||
if isinstance(filter_days, str):
|
||||
allowed_days = [normalize_day_name(d) for d in filter_days.split(',') if d.strip()]
|
||||
elif isinstance(filter_days, (list, set)):
|
||||
allowed_days = [normalize_day_name(d) for d in filter_days if d]
|
||||
elif filter_day:
|
||||
nd = normalize_day_name(filter_day)
|
||||
if nd and nd.upper() not in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
|
||||
allowed_days = [nd]
|
||||
|
||||
# Si el usuario no especificó días pero ingresó fecha manual puntual, inferir día
|
||||
if not allowed_days and manual_dt and single_date_only:
|
||||
manual_w = manual_dt.weekday()
|
||||
if manual_w < 6:
|
||||
allowed_days = [dias_esp[manual_w]]
|
||||
|
||||
stats: Dict[str, Any] = {
|
||||
'total_rows_processed': 0,
|
||||
'matching_rows': 0,
|
||||
'careers_created': 0,
|
||||
'careers_updated': 0,
|
||||
'classrooms_created': 0,
|
||||
@@ -289,19 +618,66 @@ class GoogleSheetsImporter:
|
||||
'subjects_updated': 0,
|
||||
'commissions_created': 0,
|
||||
'reservations_created': 0,
|
||||
'by_day': {},
|
||||
'errors': [],
|
||||
'sample_records': []
|
||||
'sample_records': [],
|
||||
'filters_applied': {
|
||||
'career': filter_career.strip() if filter_career else None,
|
||||
'subject': filter_subject.strip() if filter_subject else None,
|
||||
'days': allowed_days or ['Todos los Días'],
|
||||
'manual_date': manual_dt.strftime('%Y-%m-%d') if manual_dt else None,
|
||||
'single_date_only': bool(single_date_only and manual_dt),
|
||||
'weeks_to_generate': num_weeks,
|
||||
'date_from': date_from_dt.strftime('%Y-%m-%d') if date_from_dt else None,
|
||||
'date_to': date_to_dt.strftime('%Y-%m-%d') if date_to_dt else None,
|
||||
'temporal_scope': 'single_date' if (single_date_only and manual_dt) else ('date_range' if (date_from_dt and date_to_dt) else 'weeks'),
|
||||
'entities': {
|
||||
'careers': bool(import_careers),
|
||||
'subjects': bool(import_subjects),
|
||||
'commissions': bool(import_commissions),
|
||||
'classrooms': bool(import_classrooms),
|
||||
'reservations': bool(import_reservations)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
all_raw_records = []
|
||||
sheets_to_process = self.get_sheets_config()
|
||||
for sheet_cfg in sheets_to_process:
|
||||
try:
|
||||
csv_data = self.fetch_sheet_csv(sheet_cfg['gid'])
|
||||
rows = self.parse_sheet_rows(csv_data, sheet_cfg['name'])
|
||||
all_raw_records.extend([(r, sheet_cfg['day_idx']) for r in rows])
|
||||
except Exception as e:
|
||||
stats['errors'].append(f"Error al descargar o procesar la hoja de {sheet_cfg['name']}: {str(e)}")
|
||||
|
||||
if selected_rows and isinstance(selected_rows, list) and len(selected_rows) > 0:
|
||||
# Modo grilla interactiva: se procesan las filas explícitamente seleccionadas por el usuario
|
||||
for r in selected_rows:
|
||||
d_name = r.get('dia') or 'Lunes'
|
||||
d_idx = map_day_to_idx(d_name)
|
||||
all_raw_records.append((r, d_idx))
|
||||
if d_name not in stats['by_day']:
|
||||
stats['by_day'][d_name] = {'rows_count': 0, 'status': 'OK'}
|
||||
stats['by_day'][d_name]['rows_count'] += 1
|
||||
else:
|
||||
# Modo descarga general desde Google Sheets
|
||||
sheets_to_process = self.get_sheets_config()
|
||||
if allowed_days:
|
||||
sheets_to_process = [s for s in sheets_to_process if normalize_day_name(s['name']) in allowed_days]
|
||||
|
||||
for sheet_cfg in sheets_to_process:
|
||||
day_name = sheet_cfg['name']
|
||||
try:
|
||||
csv_data = self.fetch_sheet_csv(sheet_cfg['gid'])
|
||||
rows = self.parse_sheet_rows(csv_data, day_name)
|
||||
all_raw_records.extend([(r, sheet_cfg['day_idx']) for r in rows])
|
||||
stats['by_day'][day_name] = {
|
||||
'gid': sheet_cfg['gid'],
|
||||
'rows_count': len(rows),
|
||||
'status': 'OK'
|
||||
}
|
||||
except Exception as e:
|
||||
err_msg = f"Error al descargar o procesar la hoja de {day_name}: {str(e)}"
|
||||
stats['errors'].append(err_msg)
|
||||
stats['by_day'][day_name] = {
|
||||
'gid': sheet_cfg['gid'],
|
||||
'rows_count': 0,
|
||||
'status': 'Error',
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
stats['total_rows_processed'] = len(all_raw_records)
|
||||
if not all_raw_records:
|
||||
@@ -344,133 +720,228 @@ class GoogleSheetsImporter:
|
||||
classrooms_cache = {(c.building.strip().upper(), c.code.strip().upper()): c for c in Classroom.query.all()}
|
||||
subjects_cache = {s.code.strip().upper(): s for s in Subject.query.all()}
|
||||
|
||||
# Calculate current semester dates (anchored on academic year 2026)
|
||||
# Week starting Monday 2026-08-31 to Saturday 2026-09-05
|
||||
# Calculate semester dates (anchored on academic year 2026, manual date, or date_from)
|
||||
base_monday = date(2026, 8, 31)
|
||||
weeks_to_generate = 4 # Generate reservations for 4 consecutive weeks
|
||||
if manual_dt and not single_date_only:
|
||||
base_monday = manual_dt - timedelta(days=manual_dt.weekday())
|
||||
elif date_from_dt:
|
||||
base_monday = date_from_dt - timedelta(days=date_from_dt.weekday())
|
||||
weeks_to_generate = num_weeks
|
||||
|
||||
for rec, day_idx in all_raw_records:
|
||||
try:
|
||||
codigo = rec['codigo']
|
||||
asignatura = rec['asignatura']
|
||||
aula_raw = rec['aula']
|
||||
carrera_name = rec['carrera'].strip()
|
||||
carrera_raw = rec['carrera'].strip()
|
||||
horario_raw = rec['horario']
|
||||
dia = rec['dia']
|
||||
dia = rec['dia'] or (dias_esp[manual_dt.weekday()] if manual_dt else 'Lunes')
|
||||
turno = rec.get('turno', 'Mañana')
|
||||
|
||||
# 1. Upsert Career
|
||||
carrera_key = carrera_name.upper()
|
||||
career = careers_cache.get(carrera_key)
|
||||
if not career:
|
||||
career = Career(name=carrera_name)
|
||||
db.session.add(career)
|
||||
db.session.flush()
|
||||
careers_cache[carrera_key] = career
|
||||
stats['careers_created'] += 1
|
||||
# Si el registro no traía día pero hay fecha manual, asignar día de la fecha
|
||||
if day_idx is None and manual_dt:
|
||||
day_idx = manual_dt.weekday()
|
||||
|
||||
# --- FILTRO 1: Filtrar por Carrera si fue especificada ---
|
||||
carreras_list = parse_careers_list(carrera_raw)
|
||||
if filter_career:
|
||||
fc = filter_career.strip().upper()
|
||||
match_c = any(fc in c.upper() or c.upper() in fc for c in carreras_list) or (fc in carrera_raw.upper())
|
||||
if not match_c:
|
||||
continue
|
||||
|
||||
# --- FILTRO 2: Filtrar por Materia si fue especificada ---
|
||||
sub_codes = parse_subject_codes(codigo)
|
||||
if filter_subject:
|
||||
fs = filter_subject.strip().upper()
|
||||
match_s = (fs in codigo.upper()) or (fs in asignatura.upper()) or any(fs in sc.upper() for sc in sub_codes)
|
||||
if not match_s:
|
||||
continue
|
||||
|
||||
stats['matching_rows'] += 1
|
||||
|
||||
# 1. Upsert Careers (Desglosar carreras múltiples normalizadas)
|
||||
career_objs = []
|
||||
for c_name in carreras_list:
|
||||
c_key = c_name.upper()
|
||||
career = careers_cache.get(c_key)
|
||||
if not career:
|
||||
career = Career.query.filter(Career.name.ilike(c_name)).first()
|
||||
if not career and import_careers:
|
||||
career = Career(name=c_name)
|
||||
db.session.add(career)
|
||||
db.session.flush()
|
||||
stats['careers_created'] += 1
|
||||
if career:
|
||||
careers_cache[c_key] = career
|
||||
if career:
|
||||
career_objs.append(career)
|
||||
|
||||
primary_career = career_objs[0] if career_objs else None
|
||||
|
||||
# 2. Upsert Classroom
|
||||
room_info = self.normalize_room(aula_raw)
|
||||
classroom = None
|
||||
if room_info:
|
||||
room_key = (room_info['building'].upper(), room_info['code'].upper())
|
||||
b_str = str(room_info.get('building', '')).upper()
|
||||
c_str = str(room_info.get('code', '')).upper()
|
||||
room_key = (b_str, c_str)
|
||||
classroom = classrooms_cache.get(room_key)
|
||||
b_entity = buildings_cache.get(room_info['building'].upper())
|
||||
b_entity = buildings_cache.get(b_str)
|
||||
if not classroom:
|
||||
classroom = Classroom(
|
||||
building=room_info['building'],
|
||||
building_id=b_entity.id if b_entity else None,
|
||||
floor=room_info['floor'],
|
||||
capacity=room_info['capacity'],
|
||||
description=room_info['description'],
|
||||
is_active=True
|
||||
)
|
||||
classroom.code = room_info['code']
|
||||
db.session.add(classroom)
|
||||
db.session.flush()
|
||||
classrooms_cache[room_key] = classroom
|
||||
stats['classrooms_created'] += 1
|
||||
if import_classrooms:
|
||||
classroom = Classroom(
|
||||
building=room_info['building'],
|
||||
building_id=b_entity.id if b_entity else None,
|
||||
floor=room_info['floor'],
|
||||
capacity=room_info['capacity'],
|
||||
description=room_info['description'],
|
||||
is_active=True
|
||||
)
|
||||
setattr(classroom, 'code', str(room_info['code']))
|
||||
db.session.add(classroom)
|
||||
db.session.flush()
|
||||
classrooms_cache[room_key] = classroom
|
||||
stats['classrooms_created'] += 1
|
||||
else:
|
||||
classroom = Classroom.query.filter_by(code=room_info['code']).first()
|
||||
else:
|
||||
classroom.capacity = max(classroom.capacity, room_info['capacity'])
|
||||
if not classroom.building_id and b_entity:
|
||||
classroom.building_id = b_entity.id
|
||||
if import_classrooms:
|
||||
classroom.capacity = max(classroom.capacity, room_info['capacity'])
|
||||
if not classroom.building_id and b_entity:
|
||||
classroom.building_id = b_entity.id
|
||||
|
||||
# 3. Upsert Subject
|
||||
# 3. Upsert Subject (Soporte Many-to-Many con múltiples carreras y subcódigos)
|
||||
subject_key = codigo.upper()
|
||||
subject = subjects_cache.get(subject_key)
|
||||
if not subject:
|
||||
subject = Subject(
|
||||
code=codigo,
|
||||
name=asignatura,
|
||||
career_id=career.id,
|
||||
department=career.name,
|
||||
credits=4,
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(subject)
|
||||
db.session.flush()
|
||||
subjects_cache[subject_key] = subject
|
||||
stats['subjects_created'] += 1
|
||||
for sc in sub_codes:
|
||||
if sc.upper() in subjects_cache:
|
||||
subject = subjects_cache[sc.upper()]
|
||||
break
|
||||
|
||||
if not subject:
|
||||
subject = Subject.query.filter_by(code=codigo).first()
|
||||
if not subject:
|
||||
for sc in sub_codes:
|
||||
subj_by_sc = Subject.query.filter_by(code=sc).first()
|
||||
if subj_by_sc:
|
||||
subject = subj_by_sc
|
||||
break
|
||||
|
||||
department_str = ", ".join([c.name for c in career_objs]) if career_objs else (primary_career.name if primary_career else 'General')
|
||||
|
||||
if not subject:
|
||||
if import_subjects:
|
||||
subject = Subject(
|
||||
code=codigo,
|
||||
name=asignatura,
|
||||
career_id=primary_career.id if primary_career else None,
|
||||
department=department_str,
|
||||
credits=4,
|
||||
is_active=True
|
||||
)
|
||||
if career_objs:
|
||||
subject.careers = career_objs
|
||||
db.session.add(subject)
|
||||
db.session.flush()
|
||||
stats['subjects_created'] += 1
|
||||
else:
|
||||
if subject.name != asignatura:
|
||||
subject.name = asignatura
|
||||
stats['subjects_updated'] += 1
|
||||
subject.career_id = career.id
|
||||
subject.department = career.name
|
||||
if import_subjects:
|
||||
if subject.name != asignatura:
|
||||
subject.name = asignatura
|
||||
stats['subjects_updated'] += 1
|
||||
# Vincular todas las carreras a la asignatura sin duplicados
|
||||
for c_obj in career_objs:
|
||||
if c_obj not in subject.careers:
|
||||
subject.careers.append(c_obj)
|
||||
if not subject.career_id and primary_career:
|
||||
subject.career_id = primary_career.id
|
||||
subject.department = ", ".join([c.name for c in subject.careers]) if subject.careers else department_str
|
||||
|
||||
# Registrar en caché con código completo y con subcódigos individuales si existe
|
||||
if subject:
|
||||
subjects_cache[subject_key] = subject
|
||||
for sc in sub_codes:
|
||||
subjects_cache[sc.upper()] = subject
|
||||
|
||||
# 4. Upsert Commission
|
||||
# Identify commission subcode e.g. from code suffix or default 'C1'
|
||||
comm_code = 'C1'
|
||||
if '-E' in codigo:
|
||||
comm_code = codigo.split('-')[-1]
|
||||
|
||||
commission = Commission.query.filter_by(
|
||||
subject_id=subject.id,
|
||||
code=comm_code,
|
||||
semester='2026-2',
|
||||
year=2026
|
||||
).first()
|
||||
|
||||
if not commission:
|
||||
commission = Commission(
|
||||
commission = None
|
||||
if subject:
|
||||
comm_code = 'C1'
|
||||
if '-E' in codigo:
|
||||
comm_code = codigo.split('-')[-1]
|
||||
elif '-0' in codigo:
|
||||
comm_code = 'C' + codigo.split('-')[-1]
|
||||
|
||||
commission = Commission.query.filter_by(
|
||||
subject_id=subject.id,
|
||||
code=comm_code,
|
||||
semester='2026-2',
|
||||
year=2026,
|
||||
teacher_id=default_user_id,
|
||||
max_students=classroom.capacity if classroom else 35,
|
||||
current_students=0,
|
||||
schedule=f"{dia} {horario_raw}",
|
||||
shift=turno,
|
||||
active=True
|
||||
)
|
||||
db.session.add(commission)
|
||||
db.session.flush()
|
||||
stats['commissions_created'] += 1
|
||||
else:
|
||||
commission.schedule = f"{dia} {horario_raw}"
|
||||
commission.shift = turno
|
||||
year=2026
|
||||
).first()
|
||||
|
||||
# 5. Generate Calendar Reservations
|
||||
if not commission:
|
||||
if import_commissions:
|
||||
commission = Commission(
|
||||
subject_id=subject.id,
|
||||
code=comm_code,
|
||||
semester='2026-2',
|
||||
year=2026,
|
||||
teacher_id=default_user_id,
|
||||
max_students=classroom.capacity if classroom else 35,
|
||||
current_students=0,
|
||||
schedule=f"{dia} {horario_raw}",
|
||||
shift=turno,
|
||||
active=True
|
||||
)
|
||||
db.session.add(commission)
|
||||
db.session.flush()
|
||||
stats['commissions_created'] += 1
|
||||
else:
|
||||
if import_commissions:
|
||||
commission.schedule = f"{dia} {horario_raw}"
|
||||
commission.shift = turno
|
||||
if classroom:
|
||||
commission.max_students = max(commission.max_students or 0, classroom.capacity)
|
||||
|
||||
# 5. Generar Reservas de Calendario
|
||||
t_start, t_end = self.parse_time_range(horario_raw)
|
||||
if classroom and t_start and t_end and day_idx is not None:
|
||||
effective_day_idx = day_idx if day_idx is not None else (manual_dt.weekday() if manual_dt else 0)
|
||||
|
||||
if import_reservations and classroom and subject and commission and t_start and t_end:
|
||||
is_room_virtual = bool(classroom.is_virtual or 'VIRTUAL' in (classroom.code or '').upper())
|
||||
|
||||
# Generar enlace de videollamada para clases virtuales si no tienen uno asignado
|
||||
v_link = None
|
||||
if is_room_virtual:
|
||||
clean_subj = re.sub(r'[^a-zA-Z0-9]', '', subject.code or 'cls').lower()
|
||||
clean_comm = re.sub(r'[^a-zA-Z0-9]', '', commission.code or 'c1').lower()
|
||||
v_link = f"https://meet.google.com/edu-{clean_subj}-{clean_comm}"
|
||||
if not commission.virtual_link:
|
||||
commission.virtual_link = v_link
|
||||
# Respetar estrictamente los datos del Sheet: si no hay enlace explícito en el documento, NO autogenerar ninguno
|
||||
v_link = rec.get('virtual_link') or None
|
||||
if v_link and not commission.virtual_link:
|
||||
commission.virtual_link = v_link
|
||||
|
||||
for w in range(weeks_to_generate):
|
||||
class_date = base_monday + timedelta(days=day_idx, weeks=w)
|
||||
# Determinar fechas a generar: específica de la fila (datepicker), puntual o 16 semanas
|
||||
dates_to_generate = []
|
||||
raw_row_date = rec.get('date') or rec.get('inferred_date')
|
||||
row_specific_date: Optional[date] = parse_flexible_date(raw_row_date)
|
||||
|
||||
if row_specific_date:
|
||||
dates_to_generate = [row_specific_date]
|
||||
elif single_date_only and manual_dt:
|
||||
dates_to_generate = [manual_dt]
|
||||
elif date_from_dt and date_to_dt:
|
||||
# Rango de fechas: calcular todos los días correspondientes a effective_day_idx entre date_from_dt y date_to_dt
|
||||
days_ahead = (effective_day_idx - date_from_dt.weekday()) % 7
|
||||
first_date = date_from_dt + timedelta(days=days_ahead)
|
||||
dates_to_generate = []
|
||||
cur = first_date
|
||||
while cur <= date_to_dt:
|
||||
dates_to_generate.append(cur)
|
||||
cur += timedelta(days=7)
|
||||
else:
|
||||
dates_to_generate = [base_monday + timedelta(days=effective_day_idx, weeks=w) for w in range(num_weeks)]
|
||||
|
||||
for class_date in dates_to_generate:
|
||||
dt_start = datetime.combine(class_date, t_start)
|
||||
dt_end = datetime.combine(class_date, t_end)
|
||||
|
||||
# En aulas virtuales la capacidad es infinita y pueden cursar múltiples comisiones en paralelo
|
||||
if is_room_virtual:
|
||||
existing_res = Reservation.query.filter_by(
|
||||
classroom_id=classroom.id,
|
||||
@@ -485,6 +956,10 @@ class GoogleSheetsImporter:
|
||||
end_time=dt_end
|
||||
).first()
|
||||
|
||||
c_desc = ", ".join([c.name for c in career_objs]) if career_objs else 'General'
|
||||
note_suffix = f" [Fecha asignada: {class_date.strftime('%d/%m/%Y')}]" if (manual_dt and single_date_only) else ""
|
||||
note_text = f"Clase {'puntual ' if (single_date_only and manual_dt) else 'semanal '}{dia} ({turno}) - Carreras: {c_desc}{note_suffix}"
|
||||
|
||||
if not existing_res:
|
||||
res = Reservation(
|
||||
classroom_id=classroom.id,
|
||||
@@ -497,27 +972,29 @@ class GoogleSheetsImporter:
|
||||
expected_attendees=min(classroom.capacity, 30) if not is_room_virtual else 35,
|
||||
shift=turno,
|
||||
virtual_link=v_link,
|
||||
notes=f"Clase semanal {dia} ({turno}) - Carrera: {career.name}"
|
||||
notes=note_text
|
||||
)
|
||||
db.session.add(res)
|
||||
stats['reservations_created'] += 1
|
||||
else:
|
||||
existing_res.shift = turno
|
||||
existing_res.notes = f"Clase semanal {dia} ({turno}) - Carrera: {career.name}"
|
||||
if is_room_virtual and not existing_res.virtual_link:
|
||||
existing_res.notes = note_text
|
||||
if v_link:
|
||||
existing_res.virtual_link = v_link
|
||||
|
||||
if len(stats['sample_records']) < 10:
|
||||
if len(stats['sample_records']) < 15:
|
||||
stats['sample_records'].append({
|
||||
'dia': dia,
|
||||
'codigo': codigo,
|
||||
'asignatura': asignatura,
|
||||
'carrera': career.name,
|
||||
'carreras': [c.name for c in career_objs],
|
||||
'aula': classroom.code_display if classroom else aula_raw,
|
||||
'horario': horario_raw
|
||||
})
|
||||
|
||||
except Exception as row_err:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
stats['errors'].append(f"Error en fila '{rec.get('codigo', '?')}': {str(row_err)}")
|
||||
|
||||
db.session.commit()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from app.models.user import User
|
||||
from app.repositories.user_repository import UserRepository
|
||||
from app import db
|
||||
@@ -20,7 +20,7 @@ class UserService:
|
||||
return None
|
||||
|
||||
if user.check_password(password):
|
||||
user.last_login = datetime.utcnow()
|
||||
setattr(user, 'last_login', datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
self.repository.save(user)
|
||||
return user
|
||||
return None
|
||||
@@ -47,7 +47,20 @@ class UserService:
|
||||
'email': user.email,
|
||||
'role': role_name,
|
||||
'is_admin': user.is_admin(),
|
||||
'is_active': user.is_active,
|
||||
'last_login': user.last_login.strftime('%Y-%m-%d %H:%M') if user.last_login else None,
|
||||
'created_at': user.created_at.strftime('%Y-%m-%d %H:%M') if user.created_at else None,
|
||||
'permissions': permissions,
|
||||
'preferred_language': user.preferred_language,
|
||||
'theme_preference': user.theme_preference
|
||||
'theme_preference': user.theme_preference or 'auto',
|
||||
'first_name': getattr(user, 'first_name', user.name.split()[0] if user.name else ''),
|
||||
'last_name': getattr(user, 'last_name', ' '.join(user.name.split()[1:]) if user.name and len(user.name.split()) > 1 else ''),
|
||||
'document_type': getattr(user, 'document_type', 'DNI') or 'DNI',
|
||||
'document_number': getattr(user, 'document_number', '') or '',
|
||||
'document_formatted': user.get_formatted_document() if hasattr(user, 'get_formatted_document') else (getattr(user, 'document_number', '') or ''),
|
||||
'username': getattr(user, 'username', getattr(user, 'document_number', '') or (user.email.split('@')[0] if user.email else '')),
|
||||
'auth_provider_label': getattr(user, 'auth_provider_label', 'Institucional'),
|
||||
'personal_email': getattr(user, 'personal_email', '')
|
||||
}
|
||||
|
||||
user_service = UserService()
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
WeatherService - Integración meteorológica y de ubicación en tiempo real para UniCABA.
|
||||
Suministra el estado del clima, temperatura y sensación térmica para la Sede Central en CABA
|
||||
utilizando la API abierta de Open-Meteo, con caché en memoria de 15 minutos y fallback resiliente.
|
||||
"""
|
||||
import time
|
||||
import requests
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
WMO_WEATHER_CODES = {
|
||||
0: "Despejado / Soleado",
|
||||
1: "Mayormente despejado",
|
||||
2: "Parcialmente nublado",
|
||||
3: "Nublado",
|
||||
45: "Niebla",
|
||||
48: "Niebla con escarcha",
|
||||
51: "Llovizna ligera",
|
||||
53: "Llovizna moderada",
|
||||
55: "Llovizna densa",
|
||||
61: "Lluvia ligera",
|
||||
63: "Lluvia moderada",
|
||||
65: "Lluvia intensa",
|
||||
71: "Nevada ligera",
|
||||
73: "Nevada moderada",
|
||||
75: "Nevada intensa",
|
||||
80: "Chubascos leves",
|
||||
81: "Chubascos moderados",
|
||||
82: "Chubascos violentos",
|
||||
95: "Tormenta eléctrica",
|
||||
96: "Tormenta con granizo ligero",
|
||||
99: "Tormenta con granizo fuerte"
|
||||
}
|
||||
|
||||
|
||||
class WeatherService:
|
||||
# Coordenadas exactas de UniCABA Edificio Central: Tte. Gral. Juan Domingo Perón 802, CABA
|
||||
LATITUDE = -34.6037
|
||||
LONGITUDE = -58.3816
|
||||
CAMPUS_NAME = "UniCABA - Edificio Central"
|
||||
CAMPUS_ADDRESS = "Tte. Gral. Juan Domingo Perón 802, San Nicolás, CABA (C1038AAP)"
|
||||
MAPS_DESTINATION_URL = "https://www.google.com/maps/dir/?api=1&destination=UniCABA,+Tte.+Gral.+Juan+Domingo+Per%C3%B3n+802,+CABA"
|
||||
|
||||
_cached_weather: Optional[Dict[str, Any]] = None
|
||||
_last_fetched: float = 0.0
|
||||
CACHE_DURATION: float = 900.0 # 15 minutos de caché
|
||||
|
||||
@classmethod
|
||||
def get_university_weather(cls) -> Dict[str, Any]:
|
||||
"""
|
||||
Retorna el estado del clima actual en la universidad.
|
||||
Si la llamada falla o está en caché, devuelve el último dato conocido o un fallback.
|
||||
"""
|
||||
now = time.time()
|
||||
if cls._cached_weather and (now - cls._last_fetched < cls.CACHE_DURATION):
|
||||
return cls._cached_weather
|
||||
|
||||
url = (
|
||||
f"https://api.open-meteo.com/v1/forecast?"
|
||||
f"latitude={cls.LATITUDE}&longitude={cls.LONGITUDE}&"
|
||||
f"current=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation,weather_code,wind_speed_10m"
|
||||
)
|
||||
|
||||
try:
|
||||
resp = requests.get(url, timeout=3.0)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json().get("current", {})
|
||||
temp = data.get("temperature_2m", 20.0)
|
||||
app_temp = data.get("apparent_temperature", temp)
|
||||
humidity = data.get("relative_humidity_2m", 60)
|
||||
precip = data.get("precipitation", 0.0)
|
||||
code = data.get("weather_code", 0)
|
||||
wind = data.get("wind_speed_10m", 5.0)
|
||||
|
||||
condition = WMO_WEATHER_CODES.get(code, "Agradable")
|
||||
if precip > 0:
|
||||
condition += f" (Precipitación: {precip} mm)"
|
||||
|
||||
cls._cached_weather = {
|
||||
"campus": cls.CAMPUS_NAME,
|
||||
"address": cls.CAMPUS_ADDRESS,
|
||||
"temperature": round(temp, 1),
|
||||
"apparent_temperature": round(app_temp, 1),
|
||||
"humidity": humidity,
|
||||
"condition": condition,
|
||||
"wind_speed_kmh": round(wind, 1),
|
||||
"maps_url": cls.MAPS_DESTINATION_URL,
|
||||
"is_live": True,
|
||||
"summary": (
|
||||
f"Temperatura actual en CABA: {round(temp, 1)}°C (Sensación térmica: {round(app_temp, 1)}°C) | "
|
||||
f"Humedad: {humidity}% | Estado: {condition} | Viento: {round(wind, 1)} km/h."
|
||||
)
|
||||
}
|
||||
cls._last_fetched = now
|
||||
return cls._cached_weather
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Fallback si no hay conexión externa
|
||||
fallback = {
|
||||
"campus": cls.CAMPUS_NAME,
|
||||
"address": cls.CAMPUS_ADDRESS,
|
||||
"temperature": 20.0,
|
||||
"apparent_temperature": 20.0,
|
||||
"humidity": 65,
|
||||
"condition": "Templado / Parcialmente nublado",
|
||||
"wind_speed_kmh": 10.0,
|
||||
"maps_url": cls.MAPS_DESTINATION_URL,
|
||||
"is_live": False,
|
||||
"summary": (
|
||||
f"Sede Central en CABA: Clima templado promedio 20°C. "
|
||||
f"Ubicación: {cls.CAMPUS_ADDRESS}."
|
||||
)
|
||||
}
|
||||
return cls._cached_weather or fallback
|
||||
@@ -1,3 +1,3 @@
|
||||
from .decorators import permission_required, admin_required
|
||||
|
||||
__all__ = ['permission_required', 'admin_required']
|
||||
"""
|
||||
Utility package.
|
||||
"""
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
from functools import wraps
|
||||
from flask import abort, redirect, url_for, request, flash
|
||||
from flask_login import current_user
|
||||
from flask_babel import gettext as _
|
||||
|
||||
def permission_required(module, min_level='read'):
|
||||
"""
|
||||
Decorator to restrict view access based on RBAC permissions.
|
||||
Hierarchy: 'read_write' > 'read' > 'none'.
|
||||
Administrators have implicit access to all modules.
|
||||
"""
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for('auth.login', next=request.url))
|
||||
|
||||
if not current_user.has_permission(module, min_level):
|
||||
flash(_('No tienes los permisos necesarios para acceder a esta sección.'), 'error')
|
||||
abort(403)
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def admin_required(f):
|
||||
"""
|
||||
Decorator requiring administrative privileges or 'users' management access.
|
||||
"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for('auth.login', next=request.url))
|
||||
|
||||
if not current_user.can_manage():
|
||||
flash(_('Esta sección requiere privilegios de administrador.'), 'error')
|
||||
abort(403)
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
|
||||
def can_edit_reservation_required(f):
|
||||
"""
|
||||
Decorator requiring permission to modify a specific reservation.
|
||||
Allows administrators, Bedelía, or the creator/teacher of the reservation.
|
||||
"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for('auth.login', next=request.url))
|
||||
|
||||
res_id = kwargs.get('id')
|
||||
if res_id:
|
||||
from app.models.reservation import Reservation
|
||||
reservation = Reservation.query.get_or_404(res_id)
|
||||
if not current_user.can_edit_reservation(reservation):
|
||||
flash(_('No tienes los permisos necesarios para modificar esta reserva.'), 'error')
|
||||
abort(403)
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g
|
||||
import jwt
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.models.user import User
|
||||
|
||||
def jwt_required(f):
|
||||
"""
|
||||
Decorador para proteger endpoints REST mediante Bearer Token JWT.
|
||||
Extrae y valida el token, inyectando el usuario en 'g.jwt_user' y el payload en 'g.jwt_payload'.
|
||||
"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
auth_header = request.headers.get('Authorization', '')
|
||||
token = None
|
||||
|
||||
if auth_header.startswith('Bearer '):
|
||||
token = auth_header.split(' ', 1)[1].strip()
|
||||
elif 'access_token' in request.cookies:
|
||||
token = request.cookies.get('access_token')
|
||||
|
||||
if not token:
|
||||
try:
|
||||
from flask_login import current_user
|
||||
if current_user.is_authenticated and current_user.is_active:
|
||||
g.jwt_user = current_user
|
||||
g.jwt_payload = {'sub': str(current_user.id), 'role': getattr(current_user, 'role', '')}
|
||||
g.jwt_token = None
|
||||
g.real_admin_user = current_user
|
||||
g.is_impersonating = False
|
||||
return f(*args, **kwargs)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': 'Encabezado Authorization con Bearer token no proporcionado.'
|
||||
}), 401
|
||||
|
||||
try:
|
||||
payload = JWTService.decode_token(token, expected_type='access')
|
||||
user_id = int(payload.get('sub'))
|
||||
from app import db
|
||||
user = db.session.get(User, user_id)
|
||||
|
||||
if not user or not user.is_active:
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': 'Usuario no encontrado o cuenta desactivada.'
|
||||
}), 401
|
||||
|
||||
g.jwt_user = user
|
||||
g.jwt_payload = payload
|
||||
g.jwt_token = token
|
||||
g.real_admin_user = user
|
||||
g.is_impersonating = False
|
||||
|
||||
impersonate_header = request.headers.get('X-Impersonate-User')
|
||||
if impersonate_header and user.is_admin():
|
||||
target_user = None
|
||||
if impersonate_header.strip().isdigit():
|
||||
target_user = db.session.get(User, int(impersonate_header.strip()))
|
||||
else:
|
||||
target_user = User.query.filter_by(email=impersonate_header.strip()).first()
|
||||
|
||||
if target_user and target_user.is_active:
|
||||
g.jwt_user = target_user
|
||||
g.is_impersonating = True
|
||||
|
||||
except jwt.ExpiredSignatureError:
|
||||
return jsonify({
|
||||
'error': 'TokenExpired',
|
||||
'message': 'El token de acceso ha expirado. Por favor renueve su sesión.'
|
||||
}), 401
|
||||
except jwt.InvalidTokenError as e:
|
||||
return jsonify({
|
||||
'error': 'InvalidToken',
|
||||
'message': str(e)
|
||||
}), 401
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'error': 'AuthenticationError',
|
||||
'message': f'Fallo en la verificación del token: {str(e)}'
|
||||
}), 401
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def jwt_role_required(*allowed_roles):
|
||||
"""
|
||||
Decorador que verifica que el usuario autenticado vía JWT posea alguno de los roles permitidos.
|
||||
"""
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
@jwt_required
|
||||
def decorated_function(*args, **kwargs):
|
||||
user: User = g.jwt_user
|
||||
if user.is_admin():
|
||||
return f(*args, **kwargs)
|
||||
|
||||
user_role = (user.role_obj.name if user.role_obj else user.role).upper()
|
||||
allowed = [r.upper() for r in allowed_roles]
|
||||
|
||||
if user_role not in allowed:
|
||||
return jsonify({
|
||||
'error': 'Forbidden',
|
||||
'message': f'Acceso denegado. Se requiere uno de los siguientes roles: {", ".join(allowed_roles)}'
|
||||
}), 403
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user