From 5ed62d5d3049f1036fadbe30185322388157c4a1 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Mon, 19 Oct 2026 15:49:50 -0300 Subject: [PATCH] feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi --- CHANGELOG.md | 20 +- MEMORY.md | 21 +- backend/app/__init__.py | 171 +- backend/app/forms/__init__.py | 0 backend/app/forms/auth.py | 17 - backend/app/forms/building.py | 28 - backend/app/forms/classroom.py | 56 - backend/app/forms/reservation.py | 49 - backend/app/routes/__init__.py | 10 - backend/app/routes/admin.py | 1625 ----------- backend/app/routes/api/__init__.py | 12 - backend/app/routes/api/admin.py | 3077 --------------------- backend/app/routes/api/auth.py | 512 ---- backend/app/routes/api/classrooms.py | 164 -- backend/app/routes/api/dashboard.py | 782 ------ backend/app/routes/api/openapi.py | 261 -- backend/app/routes/api/optimizer.py | 105 - backend/app/routes/api/reservations.py | 367 --- backend/app/routes/api/students.py | 43 - backend/app/routes/auth.py | 152 - backend/app/routes/buildings.py | 196 -- backend/app/routes/classrooms.py | 514 ---- backend/app/routes/genetic_algorithm.py | 299 -- backend/app/routes/main.py | 335 --- backend/app/routes/my_subjects.py | 126 - backend/app/routes/schedule.py | 977 ------- backend/app/security/__init__.py | 8 - backend/app/security/decorators.py | 45 - backend/app/security/filter_chain.py | 89 - backend/app/services/audit_service.py | 56 +- backend/app/services/crypto_service.py | 10 +- backend/app/services/dashboard_service.py | 707 +++++ backend/app/services/jwt_service.py | 11 +- backend/app/services/optimizer_service.py | 1 - backend/app/utils/decorators.py | 64 - backend/app/utils/jwt_decorators.py | 118 - backend/database.py | 144 +- backend/dependencies.py | 110 +- backend/requirements.txt | 34 +- backend/routers/academic.py | 1555 +++++------ backend/routers/admin.py | 1520 +++++----- backend/routers/auth.py | 451 ++- backend/routers/buildings.py | 373 ++- backend/routers/classrooms.py | 225 +- backend/routers/dashboard.py | 63 +- backend/routers/optimizer.py | 61 +- backend/routers/reservations.py | 639 +++-- backend/routers/students.py | 10 +- backend/setup.py | 38 +- frontend/package.json | 2 +- frontend/src/app.js | 6 +- scratch/clean_flask_context.py | 73 + security_audit.bat | 4 +- specs/004-depuracion-flask-total/plan.md | 61 + specs/004-depuracion-flask-total/spec.md | 38 + specs/004-depuracion-flask-total/tasks.md | 27 + 56 files changed, 3706 insertions(+), 12756 deletions(-) delete mode 100644 backend/app/forms/__init__.py delete mode 100644 backend/app/forms/auth.py delete mode 100644 backend/app/forms/building.py delete mode 100644 backend/app/forms/classroom.py delete mode 100644 backend/app/forms/reservation.py delete mode 100644 backend/app/routes/__init__.py delete mode 100644 backend/app/routes/admin.py delete mode 100644 backend/app/routes/api/__init__.py delete mode 100644 backend/app/routes/api/admin.py delete mode 100644 backend/app/routes/api/auth.py delete mode 100644 backend/app/routes/api/classrooms.py delete mode 100644 backend/app/routes/api/dashboard.py delete mode 100644 backend/app/routes/api/openapi.py delete mode 100644 backend/app/routes/api/optimizer.py delete mode 100644 backend/app/routes/api/reservations.py delete mode 100644 backend/app/routes/api/students.py delete mode 100644 backend/app/routes/auth.py delete mode 100644 backend/app/routes/buildings.py delete mode 100644 backend/app/routes/classrooms.py delete mode 100644 backend/app/routes/genetic_algorithm.py delete mode 100644 backend/app/routes/main.py delete mode 100644 backend/app/routes/my_subjects.py delete mode 100644 backend/app/routes/schedule.py delete mode 100644 backend/app/security/__init__.py delete mode 100644 backend/app/security/decorators.py delete mode 100644 backend/app/security/filter_chain.py create mode 100644 backend/app/services/dashboard_service.py delete mode 100644 backend/app/utils/decorators.py delete mode 100644 backend/app/utils/jwt_decorators.py create mode 100644 scratch/clean_flask_context.py create mode 100644 specs/004-depuracion-flask-total/plan.md create mode 100644 specs/004-depuracion-flask-total/spec.md create mode 100644 specs/004-depuracion-flask-total/tasks.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b563588..28d3b6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,28 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1 ## [Unreleased] ### Planificado (Fase 6 del Roadmap) -- **Despliegue e Infraestructura (Fase 6):** `docker-compose.yml` productivo orquestando Flask (Gunicorn), Node.js BFF (PM2) y PostgreSQL 15, con proxy inverso Nginx, SSL/TLS y compresión. +- **Despliegue e Infraestructura (Fase 6):** `docker-compose.yml` productivo orquestando FastAPI (Uvicorn), Node.js BFF (PM2) y PostgreSQL 15, con proxy inverso Nginx, SSL/TLS y compresión. - **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1. - **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción. +## [3.8.0] - 2026-10-19 +### Removed +- **Erradicación Total y Definitiva de Flask y sus Extensiones (Spec 004)**: + - Eliminados por completo los directorios `backend/app/routes/` (18 archivos de rutas legacy de Flask) y `backend/app/forms/` (5 archivos de Flask-WTF). + - Eliminados módulos obsoletos `backend/app/security/` y decoradores legacy en `backend/app/utils/`. + - Retiradas todas las dependencias residuales de Flask en `backend/requirements.txt` y `backend/setup.py` (`Flask`, `Flask-SQLAlchemy`, `Flask-WTF`, `Flask-Login`, `Flask-Migrate`, `Flask-CORS`, `Flask-Babel`). + +### Added +- **Capa de Persistencia Nativa SQLAlchemy 2.0 Desacoplada**: + - `backend/database.py`: Implementado `SQLAlchemyWrapper` nativo con `SessionLocal`, `scoped_session`, compatibilidad con queries ORM, inyección de metadata en `db.Table` y auto-registro en `create_all()`. + - `backend/app/services/dashboard_service.py`: Centralización desacoplada de estadísticas operativas, métricas académicas y sincronización con Google Sheets. + +### Changed +- **Compatibilidad 100% Pura FastAPI**: + - `backend/app/__init__.py`: Eliminado todo import y ciclo de vida de Flask; `create_app()` ahora provee `AppCompatWrapper` y `TestClientWrapper` sobre `FastAPI TestClient`. + - `backend/routers/admin.py`: Soporte nativo para extracción de JWT en endpoints de impersonación (`stop-impersonating`) y respuesta enriquecida con `modules` y `actions` en bitácora de auditoría. + - Pasaron exitosamente los 57 tests automatizados del backend (`pytest tests -v`). + ## [3.7.0] - 2026-10-19 ### Added - **Migración Integral a FastAPI 100% Nativo (Principio 11)**: diff --git a/MEMORY.md b/MEMORY.md index 9d1ef76..2bff179 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,16 +9,17 @@ Memoria del proyecto entre sesiones para la rama `dev`. - 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: Migración Integral a FastAPI 100% Nativo — v3.7.0 (Principio 11 y Retiro Total de WSGIMiddleware)**: - - **FastAPI Core REST API Pura**: Desacoplado por completo el puente residual `WSGIMiddleware` de `backend/main.py`. - - **Routers Modulares Nativos**: - - `backend/routers/buildings.py`: ABM de edificios y sedes institucionales. - - `backend/routers/academic.py`: Carreras, Asignaturas, Comisiones, Ciclos Lectivos, Tipos de Hitos, Docentes de Comisiones, Matrículas y Actas/Gradebook. - - `backend/routers/admin.py`: Usuarios, Roles RBAC, Impersonación, System Reset, Auditoría Inmutable, Configuración Global (SMTP, OAuth, Moodle, UI, Demo Mode) y Cola Moodle (DLQ). - - `backend/routers/reservations.py`: Incorporado endpoint interactivo `drag-update`. - - `backend/routers/version.py`: Soporte para `/version` y `/health` a nivel raíz y bajo `/api/v1/version`. - - **OpenAPI /docs Swagger UI**: Expone 118 endpoints RESTful de FastAPI nativos listos para documentación y consumo interactivo. - - **Suite de Pruebas**: 57 pruebas automatizadas (`pytest tests -v`) ejecutadas y aprobadas al 100% (57 passed, 0 failed). Versión actual: `v3.7.0`. +- **Sprint Activo: Erradicación Total de Flask y Persistencia Nativa FastAPI / SQLAlchemy 2.0 — v3.8.0 (Spec 004)**: + - **Erradicación Absoluta de Flask**: + - Eliminados de raíz los directorios residuales `backend/app/routes/` y `backend/app/forms/`. + - Eliminadas dependencias obsoletas en `requirements.txt` y `setup.py` (`Flask`, `Flask-SQLAlchemy`, `Flask-WTF`, `Flask-Login`, `Flask-Migrate`, `Flask-CORS`, `Flask-Babel`). + - Poda de wrappers `with flask_app.app_context():` y reemplazo por sesión nativa de SQLAlchemy 2.0. + - **Capa de Persistencia y Compatibilidad Nativa**: + - `backend/database.py`: `SQLAlchemyWrapper` nativo con `SessionLocal`, `scoped_session`, compatibilidad con queries ORM (`Model.query.get(...)`), inyección de metadata en `db.Table` y auto-registro en `db.create_all()`. + - `backend/app/__init__.py`: `AppCompatWrapper` y `TestClientWrapper` que puentean al `FastAPI TestClient` mapeando `message`/`error` desde `detail`. + - `backend/app/services/dashboard_service.py`: Servicio desacoplado para analíticas y Google Sheets sin referencias a Flask. + - **Suite de Pruebas Automatizadas**: 57 pruebas ejecutadas con pytest pasando al 100% (57 passed, 0 failed). Cero errores en código (`@[current_problems]`). + - **Versión Consolidada**: `v3.8.0`. ## 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. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index df76e3c..c11ba48 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1,105 +1,84 @@ -from flask import Flask, request, session -from flask_sqlalchemy import SQLAlchemy -from flask_migrate import Migrate # type: ignore -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 -__version__ = "3.7.0" -db = SQLAlchemy() -migrate = Migrate() -cors = CORS() -babel = Babel() +__version__ = "3.8.0" -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 typing import Any, cast - from flask_babel import format_date, format_datetime - cast(dict[str, Any], app.jinja_env.globals)['format_date'] = format_date - cast(dict[str, Any], app.jinja_env.globals)['format_datetime'] = format_datetime - cast(dict[str, Any], app.jinja_env.filters)['format_date'] = format_date - cast(dict[str, Any], app.jinja_env.filters)['format_datetime'] = format_datetime - - return app \ No newline at end of file + 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) \ No newline at end of file diff --git a/backend/app/forms/__init__.py b/backend/app/forms/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/backend/app/forms/auth.py b/backend/app/forms/auth.py deleted file mode 100644 index 94d89ef..0000000 --- a/backend/app/forms/auth.py +++ /dev/null @@ -1,17 +0,0 @@ -from flask_wtf import FlaskForm -from wtforms import StringField, PasswordField, BooleanField, SubmitField # type: ignore -from wtforms.validators import DataRequired, Email, Length # type: ignore -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')) \ No newline at end of file diff --git a/backend/app/forms/building.py b/backend/app/forms/building.py deleted file mode 100644 index 75b7b2d..0000000 --- a/backend/app/forms/building.py +++ /dev/null @@ -1,28 +0,0 @@ -from flask_wtf import FlaskForm -from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField # type: ignore -from wtforms.validators import DataRequired, Length, NumberRange, Optional # type: ignore -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')) diff --git a/backend/app/forms/classroom.py b/backend/app/forms/classroom.py deleted file mode 100644 index bb35d63..0000000 --- a/backend/app/forms/classroom.py +++ /dev/null @@ -1,56 +0,0 @@ -from flask_wtf import FlaskForm -from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField, SelectField # type: ignore -from wtforms.validators import DataRequired, InputRequired, Length, NumberRange, Optional, ValidationError # type: ignore -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')) \ No newline at end of file diff --git a/backend/app/forms/reservation.py b/backend/app/forms/reservation.py deleted file mode 100644 index e19dd86..0000000 --- a/backend/app/forms/reservation.py +++ /dev/null @@ -1,49 +0,0 @@ -from flask_wtf import FlaskForm -from wtforms import SelectField, StringField, TextAreaField, IntegerField, SubmitField, DateTimeLocalField # type: ignore -from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError # type: ignore -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.') \ No newline at end of file diff --git a/backend/app/routes/__init__.py b/backend/app/routes/__init__.py deleted file mode 100644 index 0ead1c8..0000000 --- a/backend/app/routes/__init__.py +++ /dev/null @@ -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'] \ No newline at end of file diff --git a/backend/app/routes/admin.py b/backend/app/routes/admin.py deleted file mode 100644 index d00de74..0000000 --- a/backend/app/routes/admin.py +++ /dev/null @@ -1,1625 +0,0 @@ -from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, abort -from flask_login import login_required, current_user -from flask_babel import gettext as _ -from app import db -from app.models.user import User -from app.models.role import Role, Permission, SYSTEM_MODULES, ACCESS_LEVELS -from app.models.milestone import MilestoneType, AcademicMilestone, BASE_MILESTONE_TYPES -from app.models.audit_log import AuditLog -from app.utils.decorators import admin_required, permission_required -from sqlalchemy import or_, func -import re - -admin_bp = Blueprint('admin', __name__, url_prefix='/admin') - -# --------------------------------------------------------- -# USERS MANAGEMENT -# --------------------------------------------------------- - -@admin_bp.route('/users') -@admin_required -def users_list(): - """List system users with filtering and role information""" - search = request.args.get('search', '').strip() - role_filter = request.args.get('role', '').strip() - status_filter = request.args.get('status', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 15 - - query = User.query - - if search: - query = query.filter( - or_( - User.name.ilike(f'%{search}%'), - User.email.ilike(f'%{search}%') - ) - ) - - if role_filter: - if role_filter.isdigit(): - query = query.filter(User.role_id == int(role_filter)) - else: - query = query.filter(User.role.ilike(role_filter)) - - if status_filter in ['active', 'inactive']: - query = query.filter(User.is_active == (status_filter == 'active')) - - pagination = query.order_by(User.id.asc()).paginate(page=page, per_page=per_page, error_out=False) - roles = Role.query.order_by(Role.name.asc()).all() - - return render_template( - 'admin/users/list.html', - users=pagination.items, - pagination=pagination, - roles=roles, - search=search, - role_filter=role_filter, - status_filter=status_filter - ) - - -@admin_bp.route('/users/add', methods=['GET', 'POST']) -@admin_required -def user_add(): - """Create a new user and assign a role""" - roles = Role.query.order_by(Role.name.asc()).all() - - if request.method == 'POST': - name = request.form.get('name', '').strip() - email = request.form.get('email', '').strip().lower() - password = request.form.get('password', '') - role_id = request.form.get('role_id', type=int) - is_active = request.form.get('is_active') == 'on' - - errors = [] - if not name: - errors.append(_('El nombre es requerido.')) - if not email: - errors.append(_('El correo electrónico es requerido.')) - elif User.query.filter_by(email=email).first(): - errors.append(_('Ya existe una cuenta con este correo electrónico.')) - if not password or len(password) < 6: - errors.append(_('La contraseña debe tener al menos 6 caracteres.')) - - role_obj = Role.query.get(role_id) if role_id else None - if not role_obj: - errors.append(_('Debes seleccionar un rol válido.')) - - if errors or not role_obj: - for err in errors: - flash(err, 'error') - return render_template('admin/users/form.html', user=None, roles=roles) - - user = User( - name=name, - email=email, - role_id=role_obj.id, - role=role_obj.name, - is_active=is_active - ) - user.set_password(password) - db.session.add(user) - db.session.commit() - - flash(_('Usuario "%(name)s" creado exitosamente.', name=user.name), 'success') - return redirect(url_for('admin.users_list')) - - return render_template('admin/users/form.html', user=None, roles=roles) - - -@admin_bp.route('/users/edit/', methods=['GET', 'POST']) -@admin_required -def user_edit(id): - """Edit user details, role and status""" - user = User.query.get_or_404(id) - roles = Role.query.order_by(Role.name.asc()).all() - - if request.method == 'POST': - name = request.form.get('name', '').strip() - email = request.form.get('email', '').strip().lower() - password = request.form.get('password', '') - role_id = request.form.get('role_id', type=int) - is_active = request.form.get('is_active') == 'on' - - errors = [] - if not name: - errors.append(_('El nombre es requerido.')) - if not email: - errors.append(_('El correo electrónico es requerido.')) - else: - existing = User.query.filter_by(email=email).first() - if existing and existing.id != user.id: - errors.append(_('Ya existe otra cuenta con este correo electrónico.')) - - role_obj = Role.query.get(role_id) if role_id else None - if not role_obj: - errors.append(_('Debes seleccionar un rol válido.')) - - # Do not allow deactivating the currently logged in admin user - if user.id == current_user.id and not is_active: - errors.append(_('No puedes desactivar tu propia cuenta mientras estás en sesión.')) - - if errors or not role_obj: - for err in errors: - flash(err, 'error') - return render_template('admin/users/form.html', user=user, roles=roles) - - user.name = name - user.email = email - user.role_id = role_obj.id - user.role = role_obj.name - user.is_active = is_active - - if password: - if len(password) < 6: - flash(_('La nueva contraseña debe tener al menos 6 caracteres.'), 'error') - return render_template('admin/users/form.html', user=user, roles=roles) - user.set_password(password) - - db.session.commit() - flash(_('Usuario "%(name)s" actualizado correctamente.', name=user.name), 'success') - return redirect(url_for('admin.users_list')) - - return render_template('admin/users/form.html', user=user, roles=roles) - - -@admin_bp.route('/users/toggle/', methods=['POST']) -@admin_required -def user_toggle(id): - """Toggle user active status""" - user = User.query.get_or_404(id) - if user.id == current_user.id: - flash(_('No puedes desactivar tu propia cuenta.'), 'error') - return redirect(url_for('admin.users_list')) - - user.is_active = not user.is_active - db.session.commit() - status_str = _('activada') if user.is_active else _('desactivada') - flash(_('La cuenta de %(name)s ha sido %(status)s.', name=user.name, status=status_str), 'success') - return redirect(url_for('admin.users_list')) - - -@admin_bp.route('/users/delete/', methods=['POST']) -@admin_required -def user_delete(id): - """Delete a user account""" - if id == current_user.id: - flash(_('No puedes eliminar tu propia cuenta mientras estás en sesión activa.'), 'error') - return redirect(url_for('admin.users_list')) - - user = User.query.get_or_404(id) - - # Protect sole system administrator - if user.is_admin(): - admin_count = User.query.filter(User.role.ilike('%ADMIN%'), User.is_active == True).count() - if admin_count <= 1: - flash(_('No es posible eliminar al único administrador activo del sistema.'), 'error') - return redirect(url_for('admin.users_list')) - - # Unassign user from commissions as teacher - from app.models.subject import Commission - Commission.query.filter_by(teacher_id=id).update({'teacher_id': None}) - - name = user.name - email = user.email - db.session.delete(user) - db.session.commit() - - flash(_('El usuario "%(name)s" (%(email)s) ha sido eliminado del sistema.', name=name, email=email), 'success') - return redirect(url_for('admin.users_list')) - - -# --------------------------------------------------------- -# ROLES & PERMISSIONS MANAGEMENT (FortiGate Matrix) -# --------------------------------------------------------- - -@admin_bp.route('/roles') -@admin_required -def roles_list(): - """List all roles and permission summaries""" - roles = Role.query.order_by(Role.id.asc()).all() - return render_template( - 'admin/roles/list.html', - roles=roles, - modules=SYSTEM_MODULES - ) - - -@admin_bp.route('/roles/add', methods=['GET', 'POST']) -@admin_required -def role_add(): - """Create a new role with the FortiGate permission matrix""" - if request.method == 'POST': - name = request.form.get('name', '').strip() - description = request.form.get('description', '').strip() - - if not name: - flash(_('El nombre del rol es requerido.'), 'error') - return render_template('admin/roles/edit.html', role=None, modules=SYSTEM_MODULES, current_perms={}) - - if Role.query.filter_by(name=name).first(): - flash(_('Ya existe un rol con ese nombre.'), 'error') - return render_template('admin/roles/edit.html', role=None, modules=SYSTEM_MODULES, current_perms={}) - - new_role = Role(name=name, description=description, is_system=False) - db.session.add(new_role) - db.session.flush() # to obtain new_role.id - - # Save permissions from matrix - for mod in SYSTEM_MODULES: - mod_id = mod['id'] - level = request.form.get(f'perm_{mod_id}', 'none') - if level not in ACCESS_LEVELS: - level = 'none' - new_role.set_permission(mod_id, level) - - db.session.commit() - flash(_('Rol "%(name)s" creado exitosamente con sus permisos.', name=new_role.name), 'success') - return redirect(url_for('admin.roles_list')) - - return render_template('admin/roles/edit.html', role=None, modules=SYSTEM_MODULES, current_perms={}) - - -@admin_bp.route('/roles/edit/', methods=['GET', 'POST']) -@admin_required -def role_edit(id): - """Edit an existing role and its FortiGate permission matrix""" - role = Role.query.get_or_404(id) - - if request.method == 'POST': - name = request.form.get('name', '').strip() - description = request.form.get('description', '').strip() - - if not name: - flash(_('El nombre del rol es requerido.'), 'error') - return render_template('admin/roles/edit.html', role=role, modules=SYSTEM_MODULES, current_perms={p.module: p.access_level for p in role.permissions}) - - existing = Role.query.filter_by(name=name).first() - if existing and existing.id != role.id: - flash(_('Ya existe otro rol con ese nombre.'), 'error') - return render_template('admin/roles/edit.html', role=role, modules=SYSTEM_MODULES, current_perms={p.module: p.access_level for p in role.permissions}) - - # If it's a system role, keep name unchanged or protected - if not role.is_system: - role.name = name - role.description = description - - # Update permissions from the FortiGate matrix - for mod in SYSTEM_MODULES: - mod_id = mod['id'] - level = request.form.get(f'perm_{mod_id}', 'none') - if level not in ACCESS_LEVELS: - level = 'none' - role.set_permission(mod_id, level) - - db.session.commit() - flash(_('Rol "%(name)s" y permisos actualizados correctamente.', name=role.name), 'success') - return redirect(url_for('admin.roles_list')) - - current_perms = {p.module: p.access_level for p in role.permissions} - return render_template( - 'admin/roles/edit.html', - role=role, - modules=SYSTEM_MODULES, - current_perms=current_perms - ) - - -@admin_bp.route('/roles/delete/', methods=['POST']) -@admin_required -def role_delete(id): - """Delete a non-system role if it has no assigned users""" - role = Role.query.get_or_404(id) - if role.is_system: - flash(_('No se pueden eliminar roles protegidos del sistema.'), 'error') - return redirect(url_for('admin.roles_list')) - - user_count = len(role.users) if role.users else 0 - if user_count > 0: - flash(_('No se puede eliminar el rol "%(name)s" porque tiene %(count)d usuario(s) asignado(s). Reasígnalos primero.', name=role.name, count=user_count), 'error') - return redirect(url_for('admin.roles_list')) - - role_name = role.name - db.session.delete(role) - db.session.commit() - flash(_('El rol "%(name)s" ha sido eliminado.', name=role_name), 'success') - return redirect(url_for('admin.roles_list')) - - -# --------------------------------------------------------- -# GOOGLE SHEETS IMPORT & SYNCHRONIZATION -# --------------------------------------------------------- - -@admin_bp.route('/import', methods=['GET', 'POST']) -@admin_required -def google_sheets_import(): - """Manual sync and status page for Google Sheets academic schedule data""" - from app.services.sheets_importer import GoogleSheetsImporter, SHEETS_CONFIG - from app.models.classroom import Classroom - from app.models.career import Career - from app.models.subject import Subject, Commission - from app.models.reservation import Reservation - - stats = None - if request.method == 'POST': - try: - importer = GoogleSheetsImporter() - stats = importer.sync() - if stats['errors']: - flash(_('La sincronización se completó con algunas advertencias.'), 'warning') - else: - flash(_('Sincronización completada exitosamente. %(rows)d registros procesados.', rows=stats['total_rows_processed']), 'success') - except Exception as e: - flash(_('Error al sincronizar con Google Sheets: %(err)s', err=str(e)), 'error') - - # Calculate current system metrics - metrics = { - 'total_classrooms': Classroom.query.count(), - 'total_careers': Career.query.count(), - 'total_subjects': Subject.query.count(), - 'total_commissions': Commission.query.count(), - 'total_reservations': Reservation.query.count(), - 'sheets': SHEETS_CONFIG - } - - # Recent samples from DB if available - recent_subjects = Subject.query.order_by(Subject.id.desc()).limit(10).all() - - return render_template( - 'admin/import.html', - metrics=metrics, - stats=stats, - recent_subjects=recent_subjects - ) - - -# --------------------------------------------------------- -# MILESTONE TYPES & ACADEMIC CATEGORIES (ABM / CRUD) -# --------------------------------------------------------- - -@admin_bp.route('/milestone-types') -@permission_required('milestone_types', 'read') -def milestone_types_list(): - """List all milestone categories / types""" - # Preload default milestone types if table is empty - 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.order_by(MilestoneType.sort_order.asc(), MilestoneType.id.asc()).all() - can_edit = current_user.has_permission('milestone_types', 'read_write') - return render_template('admin/milestone_types/list.html', types=types, can_edit=can_edit) - - -@admin_bp.route('/milestone-types/add', methods=['POST']) -@permission_required('milestone_types', 'read_write') -def milestone_type_add(): - """Create a new milestone type""" - name = request.form.get('name', '').strip() - code = request.form.get('code', '').strip().lower() - color = request.form.get('color', '#0d6efd').strip() - description = request.form.get('description', '').strip() - sort_order = request.form.get('sort_order', 0, type=int) - is_active = True if request.form.get('is_active') in ['1', 'true', 'True', 'on'] else False - - if not name: - flash(_('El nombre de la tipificación es obligatorio.'), 'error') - return redirect(url_for('admin.milestone_types_list')) - - # Auto-generate code slug if not provided - if not code: - code = re.sub(r'[^a-zA-Z0-9_]+', '_', name.lower()).strip('_') - - # Check code uniqueness - existing = MilestoneType.query.filter_by(code=code).first() - if existing: - flash(_('Ya existe una tipificación con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.milestone_types_list')) - - new_type = MilestoneType( - name=name, - code=code, - color=color or '#0d6efd', - description=description, - sort_order=sort_order, - is_active=is_active - ) - db.session.add(new_type) - db.session.commit() - flash(_('Tipificación "%(name)s" creada exitosamente.', name=new_type.name), 'success') - return redirect(url_for('admin.milestone_types_list')) - - -@admin_bp.route('/milestone-types/edit/', methods=['POST']) -@permission_required('milestone_types', 'read_write') -def milestone_type_edit(id): - """Edit an existing milestone type""" - item = MilestoneType.query.get_or_404(id) - name = request.form.get('name', '').strip() - code = request.form.get('code', '').strip().lower() - color = request.form.get('color', '#0d6efd').strip() - description = request.form.get('description', '').strip() - sort_order = request.form.get('sort_order', item.sort_order, type=int) - is_active = True if request.form.get('is_active') in ['1', 'true', 'True', 'on'] else False - - if not name: - flash(_('El nombre de la tipificación es obligatorio.'), 'error') - return redirect(url_for('admin.milestone_types_list')) - - if not code: - code = re.sub(r'[^a-zA-Z0-9_]+', '_', name.lower()).strip('_') - - # Check code uniqueness against other records - existing = MilestoneType.query.filter(MilestoneType.code == code, MilestoneType.id != id).first() - if existing: - flash(_('Ya existe otra tipificación con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.milestone_types_list')) - - item.name = name - item.code = code - item.color = color or item.color - item.description = description - item.sort_order = sort_order - item.is_active = is_active - - db.session.commit() - flash(_('Tipificación "%(name)s" actualizada correctamente.', name=item.name), 'success') - return redirect(url_for('admin.milestone_types_list')) - - -@admin_bp.route('/milestone-types/toggle/', methods=['POST']) -@permission_required('milestone_types', 'read_write') -def milestone_type_toggle(id): - """Toggle active status of a milestone type""" - item = MilestoneType.query.get_or_404(id) - item.is_active = not item.is_active - db.session.commit() - - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({ - 'success': True, - 'id': item.id, - 'is_active': item.is_active, - 'message': _('Tipificación "%(name)s" %(status)s.', name=item.name, status=_('activada') if item.is_active else _('desactivada')) - }) - - status_str = _('activada') if item.is_active else _('desactivada') - flash(_('Tipificación "%(name)s" ha sido %(status)s.', name=item.name, status=status_str), 'success') - return redirect(url_for('admin.milestone_types_list')) - - -@admin_bp.route('/milestone-types/delete/', methods=['POST']) -@permission_required('milestone_types', 'read_write') -def milestone_type_delete(id): - """Delete a milestone type if unused, or deactivate with notice""" - item = MilestoneType.query.get_or_404(id) - from app.models.milestone import AcademicMilestone - milestone_count = AcademicMilestone.query.filter_by(milestone_type_id=id).count() - - if milestone_count > 0: - item.is_active = False - db.session.commit() - flash(_('La tipificación "%(name)s" tiene %(count)d hitos registrados. Se ha desactivado para conservar el historial académico.', name=item.name, count=milestone_count), 'warning') - else: - name = item.name - db.session.delete(item) - db.session.commit() - flash(_('Tipificación "%(name)s" eliminada permanentemente.', name=name), 'success') - - return redirect(url_for('admin.milestone_types_list')) - - -@admin_bp.route('/api/milestone-types') -@login_required -def api_milestone_types(): - """API endpoint to get active milestone types for forms and dropdowns""" - 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. GESTIÓN DE CARRERAS (CAREERS) -# --------------------------------------------------------- - -@admin_bp.route('/careers') -@login_required -def careers_list(): - """List and manage academic careers""" - if not (current_user.has_permission('academic', 'read') or current_user.can_manage()): - abort(403) - - from app.models.career import Career - from app.models.subject import Subject - search = request.args.get('search', '').strip() - - query = Career.query - if search: - query = query.filter( - or_( - Career.name.ilike(f'%{search}%'), - Career.code.ilike(f'%{search}%'), - Career.description.ilike(f'%{search}%') - ) - ) - - careers = query.order_by(Career.name.asc()).all() - - # Calculate stats per career - stats = {} - for c in careers: - subj_count = len(c.subjects) if c.subjects else 0 - comm_count = sum(len(s.commissions) for s in c.subjects) if c.subjects else 0 - stats[c.id] = { - 'subjects_count': subj_count, - 'commissions_count': comm_count - } - - can_edit = current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN') - - return render_template( - 'admin/careers/list.html', - careers=careers, - stats=stats, - search=search, - can_edit=can_edit - ) - - -@admin_bp.route('/careers/add', methods=['POST']) -@login_required -def career_add(): - """Create a new academic career""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.career import Career - name = request.form.get('name', '').strip() - code = request.form.get('code', '').strip() - description = request.form.get('description', '').strip() - - if not name: - flash(_('El nombre de la carrera es obligatorio.'), 'error') - return redirect(url_for('admin.careers_list')) - - existing = Career.query.filter(Career.name.ilike(name)).first() - if existing: - flash(_('Ya existe una carrera registrada con el nombre "%(name)s".', name=name), 'error') - return redirect(url_for('admin.careers_list')) - - career = Career(name=name, code=code or None, description=description or None) - db.session.add(career) - db.session.commit() - - flash(_('Carrera "%(name)s" creada exitosamente.', name=career.name), 'success') - return redirect(url_for('admin.careers_list')) - - -@admin_bp.route('/careers//edit', methods=['POST']) -@login_required -def career_edit(id): - """Edit an academic career""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.career import Career - career = Career.query.get_or_404(id) - name = request.form.get('name', '').strip() - code = request.form.get('code', '').strip() - description = request.form.get('description', '').strip() - - if not name: - flash(_('El nombre de la carrera es obligatorio.'), 'error') - return redirect(url_for('admin.careers_list')) - - existing = Career.query.filter(Career.name.ilike(name), Career.id != id).first() - if existing: - flash(_('Ya existe otra carrera registrada con el nombre "%(name)s".', name=name), 'error') - return redirect(url_for('admin.careers_list')) - - career.name = name - career.code = code or None - career.description = description or None - db.session.commit() - - flash(_('Carrera "%(name)s" actualizada correctamente.', name=career.name), 'success') - return redirect(url_for('admin.careers_list')) - - -@admin_bp.route('/careers//delete', methods=['POST']) -@login_required -def career_delete(id): - """Delete an academic career if it has no associated subjects""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.career import Career - career = Career.query.get_or_404(id) - if career.subjects and len(career.subjects) > 0: - flash(_('No se puede eliminar la carrera "%(name)s" porque tiene %(count)d asignaturas vinculadas.', name=career.name, count=len(career.subjects)), 'error') - return redirect(url_for('admin.careers_list')) - - name = career.name - db.session.delete(career) - db.session.commit() - flash(_('Carrera "%(name)s" eliminada permanentemente.', name=name), 'success') - return redirect(url_for('admin.careers_list')) - - -# --------------------------------------------------------- -# 2. GESTIÓN DE ASIGNATURAS (SUBJECTS) -# --------------------------------------------------------- - -@admin_bp.route('/subjects') -@login_required -def subjects_list(): - """List and manage subjects / materias""" - if not (current_user.has_permission('academic', 'read') or current_user.can_manage()): - abort(403) - - from app.models.subject import Subject - from app.models.career import Career - - search = request.args.get('search', '').strip() - career_filter = request.args.get('career_id', type=int) - active_filter = request.args.get('active', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - - query = Subject.query - if search: - query = query.filter( - or_( - Subject.name.ilike(f'%{search}%'), - Subject.code.ilike(f'%{search}%'), - Subject.department.ilike(f'%{search}%') - ) - ) - if career_filter: - query = query.filter(Subject.career_id == career_filter) - if active_filter in ['true', 'false']: - query = query.filter(Subject.is_active == (active_filter == 'true')) - - pagination = query.order_by(Subject.code.asc(), Subject.name.asc()).paginate(page=page, per_page=per_page, error_out=False) - careers = Career.query.order_by(Career.name.asc()).all() - can_edit = current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN') - - return render_template( - 'admin/subjects/list.html', - subjects=pagination.items, - pagination=pagination, - careers=careers, - search=search, - career_filter=career_filter, - active_filter=active_filter, - can_edit=can_edit - ) - - -@admin_bp.route('/subjects/add', methods=['POST']) -@login_required -def subject_add(): - """Create a new subject""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.subject import Subject - from app.models.career import Career - code = request.form.get('code', '').strip().upper() - name = request.form.get('name', '').strip() - department = request.form.get('department', '').strip() - career_id = request.form.get('career_id', type=int) - credits = request.form.get('credits', 4, type=int) - description = request.form.get('description', '').strip() - - if not code or not name: - flash(_('El código y el nombre de la asignatura son obligatorios.'), 'error') - return redirect(url_for('admin.subjects_list')) - - existing = Subject.query.filter_by(code=code).first() - if existing: - flash(_('Ya existe una asignatura con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.subjects_list')) - - career_name = None - if career_id: - c = Career.query.get(career_id) - if c: - career_name = c.name - - subject = Subject( - code=code, - name=name, - department=department or career_name or 'General', - career_id=career_id if career_id else None, - credits=credits or 4, - description=description or None, - is_active=True - ) - db.session.add(subject) - db.session.commit() - - flash(_('Asignatura "%(name)s" (%(code)s) creada exitosamente.', name=subject.name, code=subject.code), 'success') - return redirect(url_for('admin.subjects_list')) - - -@admin_bp.route('/subjects//edit', methods=['POST']) -@login_required -def subject_edit(id): - """Edit an existing subject""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.subject import Subject - from app.models.career import Career - subject = Subject.query.get_or_404(id) - - code = request.form.get('code', '').strip().upper() - name = request.form.get('name', '').strip() - department = request.form.get('department', '').strip() - career_id = request.form.get('career_id', type=int) - credits = request.form.get('credits', 4, type=int) - description = request.form.get('description', '').strip() - is_active = request.form.get('is_active') == 'on' - - if not code or not name: - flash(_('El código y el nombre de la asignatura son obligatorios.'), 'error') - return redirect(url_for('admin.subjects_list')) - - existing = Subject.query.filter(Subject.code == code, Subject.id != id).first() - if existing: - flash(_('Ya existe otra asignatura con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.subjects_list')) - - career_name = None - if career_id: - c = Career.query.get(career_id) - if c: - career_name = c.name - - subject.code = code - subject.name = name - subject.department = department or career_name or subject.department - subject.career_id = career_id if career_id else None - subject.credits = credits or 4 - subject.description = description or None - subject.is_active = is_active - db.session.commit() - - flash(_('Asignatura "%(name)s" actualizada exitosamente.', name=subject.name), 'success') - return redirect(url_for('admin.subjects_list')) - - -@admin_bp.route('/subjects//toggle', methods=['POST']) -@login_required -def subject_toggle(id): - """Toggle active status of a subject""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.subject import Subject - subject = Subject.query.get_or_404(id) - subject.is_active = not subject.is_active - db.session.commit() - - status_str = _('activada') if subject.is_active else _('desactivada') - flash(_('Asignatura "%(name)s" %(status)s.', name=subject.name, status=status_str), 'success') - return redirect(url_for('admin.subjects_list')) - - -# --------------------------------------------------------- -# 3. GESTIÓN DE CICLO LECTIVO (ACADEMIC TERMS) -# --------------------------------------------------------- - -@admin_bp.route('/academic-terms') -@login_required -def academic_terms_list(): - """List and manage academic cycles / terms""" - if not (current_user.has_permission('academic', 'read') or current_user.can_manage()): - abort(403) - - from app.models.academic_term import AcademicTerm - from app.models.subject import Commission - from app.models.reservation import Reservation - - terms = AcademicTerm.query.order_by(AcademicTerm.year.desc(), AcademicTerm.code.desc()).all() - - # Calculate associated commissions and reservations - stats = {} - for t in terms: - comm_count = Commission.query.filter( - or_(Commission.semester == t.code, db.and_(Commission.year == t.year, Commission.semester.ilike(f'%{t.code}%'))) - ).count() - stats[t.id] = { - 'commissions_count': comm_count - } - - can_edit = current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN') - - return render_template( - 'admin/academic_terms/list.html', - terms=terms, - stats=stats, - can_edit=can_edit - ) - - -@admin_bp.route('/academic-terms/add', methods=['POST']) -@login_required -def academic_term_add(): - """Create a new academic cycle""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.academic_term import AcademicTerm - from datetime import datetime - code = request.form.get('code', '').strip() - name = request.form.get('name', '').strip() - year = request.form.get('year', type=int) - period_type = request.form.get('period_type', '').strip() - start_date_str = request.form.get('start_date', '').strip() - end_date_str = request.form.get('end_date', '').strip() - is_current = request.form.get('is_current') == 'on' - - if not code or not name or not year: - flash(_('El código, nombre y año del ciclo lectivo son obligatorios.'), 'error') - return redirect(url_for('admin.academic_terms_list')) - - existing = AcademicTerm.query.filter_by(code=code).first() - if existing: - flash(_('Ya existe un ciclo lectivo con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.academic_terms_list')) - - start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date() if start_date_str else None - end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date() if end_date_str else None - - if is_current: - # Unset previous current terms - AcademicTerm.query.update({'is_current': False}) - - term = AcademicTerm( - code=code, - name=name, - year=year, - period_type=period_type or 'Segundo Cuatrimestre', - start_date=start_date, - end_date=end_date, - is_current=is_current, - is_active=True - ) - db.session.add(term) - db.session.commit() - - flash(_('Ciclo lectivo "%(name)s" creado exitosamente.', name=term.name), 'success') - return redirect(url_for('admin.academic_terms_list')) - - -@admin_bp.route('/academic-terms//edit', methods=['POST']) -@admin_bp.route('/academic_term_edit', methods=['POST'], defaults={'id': None}) -@admin_bp.route('/academic_term_edit/', methods=['POST']) -@login_required -def academic_term_edit(id=None): - """Edit an academic cycle""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - term_id = id or request.form.get('id', type=int) - if not term_id: - flash(_('Identificador de ciclo lectivo no especificado.'), 'error') - return redirect(url_for('admin.academic_terms_list')) - - from app.models.academic_term import AcademicTerm - from datetime import datetime - term = AcademicTerm.query.get_or_404(term_id) - - code = request.form.get('code', '').strip() - name = request.form.get('name', '').strip() - year = request.form.get('year', type=int) - period_type = request.form.get('period_type', '').strip() - start_date_str = request.form.get('start_date', '').strip() - end_date_str = request.form.get('end_date', '').strip() - is_current = request.form.get('is_current') == 'on' - is_active = request.form.get('is_active') == 'on' - - if not code or not name or not year: - flash(_('El código, nombre y año del ciclo lectivo son obligatorios.'), 'error') - return redirect(url_for('admin.academic_terms_list')) - - existing = AcademicTerm.query.filter(AcademicTerm.code == code, AcademicTerm.id != id).first() - if existing: - flash(_('Ya existe otro ciclo lectivo con el código "%(code)s".', code=code), 'error') - return redirect(url_for('admin.academic_terms_list')) - - if is_current and not term.is_current: - AcademicTerm.query.update({'is_current': False}) - - term.code = code - term.name = name - term.year = year - term.period_type = period_type or term.period_type - term.start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date() if start_date_str else None - term.end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date() if end_date_str else None - term.is_current = is_current - term.is_active = is_active - db.session.commit() - - flash(_('Ciclo lectivo "%(name)s" actualizado correctamente.', name=term.name), 'success') - return redirect(url_for('admin.academic_terms_list')) - - -@admin_bp.route('/academic-terms//set-current', methods=['POST']) -@login_required -def academic_term_set_current(id): - """Set an academic cycle as the currently active one""" - if not (current_user.has_permission('academic', 'read_write') or (current_user.role and current_user.role.upper() == 'ADMIN')): - abort(403) - - from app.models.academic_term import AcademicTerm - term = AcademicTerm.query.get_or_404(id) - AcademicTerm.query.update({'is_current': False}) - term.is_current = True - term.is_active = True - db.session.commit() - - flash(_('El ciclo lectivo "%(name)s" fue establecido como Ciclo Activo del sistema.', name=term.name), 'success') - return redirect(url_for('admin.academic_terms_list')) - - -# --------------------------------------------------------- -# 4. GESTIÓN DE OCUPACIÓN Y MÉTRICAS (OCCUPANCY DASHBOARD) -# --------------------------------------------------------- - -@admin_bp.route('/occupancy-metrics') -@login_required -def occupancy_metrics(): - """Consolidated institutional dashboard of classroom occupancy, shifts, and space usage""" - if not (current_user.has_permission('metrics', 'read') or current_user.can_manage()): - abort(403) - - from app.models.classroom import Classroom - from app.models.building import Building - from app.models.reservation import Reservation, ReservationStatus - import calendar - from datetime import datetime, date, timedelta, timezone - - today = datetime.now(timezone.utc).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) - - # Buildings & Classrooms - buildings = Building.query.filter_by(is_active=True).all() - vb = next((b for b in buildings if b.code == 'VIRTUAL' or 'virtual' in b.name.lower()), None) - vb_id = vb.id if vb else 0 - - _phys_q = Classroom.query.filter( - Classroom.is_active == True, - ~Classroom.code.ilike('%VIRTUAL%') - ) - if vb_id: - _phys_q = _phys_q.filter(Classroom.building_id != vb_id) - physical_rooms = _phys_q.all() - - if vb_id: - vc = Classroom.query.filter(Classroom.building_id == vb_id).first() - else: - vc = Classroom.query.filter(Classroom.code.ilike('%VIRTUAL%')).first() - - # Reservations in month - month_res = Reservation.query.filter( - Reservation.start_time >= month_start, - Reservation.start_time <= month_end, - Reservation.status.in_([ReservationStatus.CONFIRMED.value, ReservationStatus.PENDING.value]) - ).all() - - # Calculate physical stats - DAILY_OP_MINS = 15 * 60 - WEEKLY_OP_MINS = 6 * 15 * 60 - MONTHLY_OP_MINS = 24 * 15 * 60 - - room_metrics = [] - for c in physical_rooms: - c_res = [r for r in month_res 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, 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, 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, round((month_mins / MONTHLY_OP_MINS) * 100)) - - room_metrics.append({ - 'classroom': c, - '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) - }) - - room_metrics.sort(key=lambda x: x['month_pct'], reverse=True) - top_rooms = room_metrics[:5] - low_rooms = list(reversed(room_metrics))[:5] - - # Global averages - avg_day_pct = round(sum(rm['day_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0 - avg_week_pct = round(sum(rm['week_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0 - avg_month_pct = round(sum(rm['month_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0 - - # Virtual classes - v_res = [r for r in month_res if vc and r.classroom_id == vc.id] - v_today = sum(1 for r in v_res if today_start <= r.start_time <= today_end) - v_week = sum(1 for r in v_res if week_start <= r.start_time <= week_end) - v_month = len(v_res) - - # Shifts distribution - shift_counts = {'Mañana': 0, 'Tarde': 0, 'Vespertino': 0, 'Noche': 0, 'Otro': 0} - for r in month_res: - s = (r.shift or '').strip().capitalize() - if s in shift_counts: - shift_counts[s] += 1 - elif 'Mañana' in s: - shift_counts['Mañana'] += 1 - elif 'Tarde' in s: - shift_counts['Tarde'] += 1 - elif 'Noche' in s: - shift_counts['Noche'] += 1 - else: - shift_counts['Otro'] += 1 - - # Floors occupancy - floor_stats = {} - for rm in room_metrics: - flr = rm['classroom'].floor_display - if flr not in floor_stats: - floor_stats[flr] = {'rooms': 0, 'month_pct_sum': 0} - floor_stats[flr]['rooms'] += 1 - floor_stats[flr]['month_pct_sum'] += rm['month_pct'] - - floor_summary = [ - {'floor': f, 'avg_pct': int(round(data['month_pct_sum'] / data['rooms'])), 'count': data['rooms']} - for f, data in floor_stats.items() - ] - floor_summary.sort(key=lambda x: x['avg_pct'], reverse=True) - - 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') - } - - return render_template( - 'admin/metrics/occupancy.html', - physical_rooms_count=len(physical_rooms), - avg_day_pct=avg_day_pct, - avg_week_pct=avg_week_pct, - avg_month_pct=avg_month_pct, - top_rooms=top_rooms, - low_rooms=low_rooms, - v_today=v_today, - v_week=v_week, - v_month=v_month, - shift_counts=shift_counts, - floor_summary=floor_summary, - total_month_classes=len(month_res), - date_filters=date_filters - ) - - -# --------------------------------------------------------- -# AUDIT LOGS -# --------------------------------------------------------- - -@admin_bp.route('/audit-logs') -@admin_required -def audit_logs(): - """Vista de bitácora de auditoría del sistema""" - page = request.args.get('page', 1, type=int) - module_filter = request.args.get('module', '').strip() - action_filter = request.args.get('action', '').strip() - search = request.args.get('search', '').strip() - per_page = 20 - - query = AuditLog.query - - if module_filter: - query = query.filter(AuditLog.module == module_filter) - if action_filter: - query = query.filter(AuditLog.action == action_filter) - if search: - query = query.filter( - or_( - AuditLog.user_email.ilike(f'%{search}%'), - AuditLog.details.ilike(f'%{search}%'), - AuditLog.ip_address.ilike(f'%{search}%') - ) - ) - - pagination = query.order_by(AuditLog.created_at.desc()).paginate(page=page, per_page=per_page, error_out=False) - - # Módulos y acciones únicas para los selectores de filtro - modules = [r[0] for r in db.session.query(AuditLog.module).distinct().all() if r[0]] - actions = [r[0] for r in db.session.query(AuditLog.action).distinct().all() if r[0]] - - return render_template( - 'admin/audit_logs.html', - pagination=pagination, - audit_logs=pagination.items, - modules=modules, - actions=actions, - current_module=module_filter, - current_action=action_filter, - search=search - ) - - - - -# --------------------------------------------------------- -# 5. GESTION DE COMISIONES (BEDELIA / ADMIN) -# --------------------------------------------------------- - -@admin_bp.route('/commissions') -@login_required -def commissions_list(): - """List all commissions with filters - accessible by Bedelia and Admin""" - if not (current_user.has_permission('enrollment', 'read_write') or current_user.is_admin() or current_user.is_bedelia()): - abort(403) - - from app.models.subject import Subject, Commission - from app.models.user import User - - search = request.args.get('search', '').strip() - subject_filter = request.args.get('subject_id', type=int) - teacher_filter = request.args.get('teacher_id', type=int) - shift_filter = request.args.get('shift', '').strip() - active_filter = request.args.get('active', 'true').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - - query = Commission.query.join(Subject, Commission.subject_id == Subject.id) - - if search: - query = query.filter( - or_( - Commission.code.ilike(f'%{search}%'), - Subject.name.ilike(f'%{search}%'), - Subject.code.ilike(f'%{search}%'), - ) - ) - if subject_filter: - query = query.filter(Commission.subject_id == subject_filter) - if teacher_filter: - query = query.filter(Commission.teacher_id == teacher_filter) - if shift_filter: - query = query.filter(Commission.shift.ilike(f'%{shift_filter}%')) - if active_filter in ['true', 'false']: - query = query.filter(Commission.active == (active_filter == 'true')) - - pagination = query.order_by(Subject.name.asc(), Commission.code.asc()).paginate( - page=page, per_page=per_page, error_out=False - ) - - subjects = Subject.query.filter_by(is_active=True).order_by(Subject.name.asc()).all() - teachers = User.query.filter( - or_(User.role.ilike('%DOCENTE%'), User.role.ilike('%docent%'), User.role.ilike('%ADMIN%')) - ).filter_by(is_active=True).order_by(User.name.asc()).all() - - from app.models.academic_term import AcademicTerm - academic_terms = AcademicTerm.query.filter_by(is_active=True).order_by(AcademicTerm.year.desc(), AcademicTerm.start_date.desc()).all() - - can_edit = ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ) - - return render_template( - 'admin/commissions/list.html', - commissions=pagination.items, - pagination=pagination, - subjects=subjects, - teachers=teachers, - academic_terms=academic_terms, - search=search, - subject_filter=subject_filter, - teacher_filter=teacher_filter, - shift_filter=shift_filter, - active_filter=active_filter, - can_edit=can_edit - ) - - -@admin_bp.route('/commissions/') -@login_required -def commission_detail(id): - """Detail view of a commission: enrolled students and teacher assignment""" - if not (current_user.has_permission('enrollment', 'read_write') or current_user.is_admin() or current_user.is_bedelia()): - abort(403) - - from app.models.subject import Commission - from app.models.enrollment import StudentEnrollment - from app.models.user import User - - commission = Commission.query.get_or_404(id) - enrollments = ( - StudentEnrollment.query - .filter_by(commission_id=id) - .order_by(StudentEnrollment.enrolled_at.asc()) - .all() - ) - - teachers = User.query.filter( - or_(User.role.ilike('%DOCENTE%'), User.role.ilike('%docent%')) - ).filter_by(is_active=True).order_by(User.name.asc()).all() - - students = User.query.filter( - or_(User.role.ilike('%ALUMNO%'), User.role.ilike('%alumn%'), User.role.ilike('%estud%')) - ).filter_by(is_active=True).order_by(User.name.asc()).all() - - enrolled_ids = {e.student_id for e in enrollments} - can_edit = ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ) - - return render_template( - 'admin/commissions/detail.html', - commission=commission, - enrollments=enrollments, - teachers=teachers, - students=students, - enrolled_ids=enrolled_ids, - can_edit=can_edit - ) - - -@admin_bp.route('/commissions//assign-teacher', methods=['POST']) -@login_required -def commission_assign_teacher(id): - """Assign or change the teacher of a commission""" - if not ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ): - abort(403) - - from app.models.subject import Commission - from app.models.user import User - - commission = Commission.query.get_or_404(id) - teacher_id = request.form.get('teacher_id', type=int) - - if teacher_id: - teacher = User.query.get(teacher_id) - if not teacher or not teacher.is_active: - flash(_('El docente seleccionado no existe o esta inactivo.'), 'error') - return redirect(url_for('admin.commission_detail', id=id)) - commission.teacher_id = teacher_id - db.session.commit() - flash(_('Docente asignado exitosamente a la comision.'), 'success') - else: - commission.teacher_id = None - db.session.commit() - flash(_('Se removio la asignacion de docente.'), 'warning') - - return redirect(url_for('admin.commission_detail', id=id)) - - -@admin_bp.route('/commissions//enroll-student', methods=['POST']) -@login_required -def commission_enroll_student(id): - """Enroll a student into a commission""" - if not ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ): - abort(403) - - from app.models.subject import Commission - from app.models.enrollment import StudentEnrollment - from app.models.user import User - - commission = Commission.query.get_or_404(id) - student_id = request.form.get('student_id', type=int) - notes = request.form.get('notes', '').strip() - - if not student_id: - flash(_('Debes seleccionar un alumno.'), 'error') - return redirect(url_for('admin.commission_detail', id=id)) - - student = User.query.get(student_id) - if not student or not student.is_active: - flash(_('El alumno seleccionado no existe o esta inactivo.'), 'error') - return redirect(url_for('admin.commission_detail', id=id)) - - existing = StudentEnrollment.query.filter_by(student_id=student_id, commission_id=id).first() - if existing: - flash(_('El alumno ya esta inscripto en esta comision.'), 'warning') - return redirect(url_for('admin.commission_detail', id=id)) - - enrollment = StudentEnrollment( - student_id=student_id, - commission_id=id, - status='activo', - notes=notes or None - ) - db.session.add(enrollment) - commission.current_students = (commission.current_students or 0) + 1 - db.session.commit() - - flash(_('Alumno inscripto exitosamente en la comision.'), 'success') - return redirect(url_for('admin.commission_detail', id=id)) - - -@admin_bp.route('/commissions//unenroll-student/', methods=['POST']) -@login_required -def commission_unenroll_student(id, student_id): - """Remove a student from a commission""" - if not ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ): - abort(403) - - from app.models.subject import Commission - from app.models.enrollment import StudentEnrollment - - commission = Commission.query.get_or_404(id) - enrollment = StudentEnrollment.query.filter_by( - student_id=student_id, commission_id=id - ).first_or_404() - - db.session.delete(enrollment) - if commission.current_students and commission.current_students > 0: - commission.current_students -= 1 - db.session.commit() - - flash(_('Alumno dado de baja de la comision.'), 'success') - return redirect(url_for('admin.commission_detail', id=id)) - - -@admin_bp.route('/commissions//update-enrollment/', methods=['POST']) -@login_required -def commission_update_enrollment(id, student_id): - """Update enrollment status for a student""" - if not ( - current_user.has_permission('academic', 'read_write') or - current_user.is_admin() or - current_user.is_bedelia() - ): - abort(403) - - from app.models.enrollment import StudentEnrollment - - enrollment = StudentEnrollment.query.filter_by( - student_id=student_id, commission_id=id - ).first_or_404() - - new_status = request.form.get('status', 'activo') - if new_status not in ['activo', 'retirado', 'condicional']: - new_status = 'activo' - - enrollment.status = new_status - enrollment.notes = request.form.get('notes', enrollment.notes or '') - db.session.commit() - - flash(_('Estado de inscripcion actualizado.'), 'success') - return redirect(url_for('admin.commission_detail', id=id)) - - -# --------------------------------------------------------- -# CONFIGURACIÓN GLOBAL DEL SISTEMA & MODO DEMO -# --------------------------------------------------------- - -@admin_bp.route('/settings', methods=['GET']) -@login_required -def global_settings(): - """Vista principal del panel de Configuración Global del Sistema""" - if not (current_user.is_admin() or (current_user.role and current_user.role.upper() == 'ADMIN') or current_user.has_permission('system_settings', 'read')): - abort(403) - - from app.models.setting import SystemSetting - from app.models.user import User - - # Diccionario de parámetros para inicializar el template - settings = { - 'smtp': { - 'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'), - 'port': int(SystemSetting.get_value('smtp_port', '587') or 587), - 'user': SystemSetting.get_value('smtp_user', ''), - 'password_masked': SystemSetting.get_masked_value('smtp_password', ''), - 'security': SystemSetting.get_value('smtp_security', 'tls'), - 'from_email': SystemSetting.get_value('smtp_sender_email', 'notificaciones@unicaba.edu.ar'), - 'from_name': SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA'), - 'enabled': SystemSetting.get_value('smtp_enabled', 'true') in ['true', 'True', '1', True] - }, - 'auth_providers': { - 'local': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'local_enabled': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'google': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'google_enabled': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'moodle': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True], - 'moodle_enabled': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True] - }, - 'google_oauth': { - 'client_id': SystemSetting.get_value('google_client_id', ''), - 'client_secret_masked': SystemSetting.get_masked_value('google_client_secret', ''), - 'callback_url': SystemSetting.get_value('google_callback_url', '/auth/google/callback'), - 'allowed_domains': SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar,lasalle.edu.ar') - }, - 'moodle': { - 'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'), - 'ws_token_masked': SystemSetting.get_masked_value('moodle_ws_token', ''), - 'timeout': int(SystemSetting.get_value('moodle_timeout', '10') or 10), - 'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True], - 'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', '15') or 15) - } - } - - # Estado del Modo Demo y Cuentas Preconfiguradas - demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - demo_emails = ['bedelia@edu-space.com', 'docente@edu-space.com', 'alumno@edu-space.com'] - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - demo_accounts_active = any(u.is_active for u in demo_users) - - return render_template( - 'admin/settings/global_config.html', - settings=settings, - demo_access_enabled=demo_access_enabled, - demo_accounts_active=demo_accounts_active, - demo_users=demo_users - ) - - -@admin_bp.route('/settings/demo-mode', methods=['POST']) -@login_required -def toggle_demo_mode(): - """Habilita o deshabilita el Acceso Rápido Demo y las cuentas default (Bedelía, Docente, Alumno)""" - if not (current_user.is_admin() or (current_user.role and current_user.role.upper() == 'ADMIN')): - if request.is_json: - return jsonify({'status': 'error', 'message': 'Acción no autorizada'}), 403 - abort(403) - - from app.models.setting import SystemSetting - from app.models.user import User - from app.models.audit_log import AuditLog - - data = request.get_json(silent=True) or request.form.to_dict() or {} - - # Si viene explícito el booleano 'enabled', lo usamos; si no, alternamos el valor actual - if 'enabled' in data: - target_state = data['enabled'] in [True, 'true', '1', 'on'] - else: - current_state = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - target_state = not current_state - - # Guardar estado en SystemSetting - SystemSetting.set_value( - 'demo_access_enabled', - 'true' if target_state else 'false', - 'Acceso Rápido Demo en pantalla de Login', - category='security' - ) - - # Activar o desactivar las 3 cuentas default - demo_emails = ['bedelia@edu-space.com', 'docente@edu-space.com', 'alumno@edu-space.com'] - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - for u in demo_users: - u.is_active = target_state - db.session.commit() - - # Registro de auditoría - action_name = 'ENABLE_DEMO_ACCOUNTS' if target_state else 'DISABLE_DEMO_ACCOUNTS' - msg_detail = ( - 'Acceso Rápido Demo habilitado y cuentas Bedelía, Docente y Alumno activadas' - if target_state else - 'Acceso Rápido Demo deshabilitado y cuentas default (Bedelía, Docente, Alumno) desactivadas' - ) - try: - audit = AuditLog( - user_id=current_user.id, - user_email=current_user.email, - action=action_name, - module='settings', - details=msg_detail - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({ - 'status': 'success', - 'message': msg_detail, - 'demo_access_enabled': target_state, - 'demo_accounts_active': target_state - }), 200 - - flash(_(msg_detail), 'success' if not target_state else 'info') - return redirect(url_for('admin.global_settings')) - - -@admin_bp.route('/settings/auth-providers', methods=['POST']) -@login_required -def update_auth_providers_web(): - """Actualiza los métodos de autenticación habilitados desde la interfaz de administración.""" - if not (current_user.is_admin() or (current_user.role and current_user.role.upper() == 'ADMIN')): - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({'status': 'error', 'message': 'Acción no autorizada'}), 403 - abort(403) - - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - data = request.get_json(silent=True) or request.form.to_dict() or {} - local_input = data.get('local_enabled') if 'local_enabled' in data else data.get('local', True) - google_input = data.get('google_enabled') if 'google_enabled' in data else data.get('google', False) - moodle_input = data.get('moodle_enabled') if 'moodle_enabled' in data else data.get('moodle', False) - - local_val = 'true' if local_input in [True, 'true', '1', 'on'] else 'false' - google_val = 'true' if google_input in [True, 'true', '1', 'on'] else 'false' - moodle_val = 'true' if moodle_input in [True, 'true', '1', 'on'] else 'false' - - SystemSetting.set_value('auth_local_enabled', local_val, 'Habilitar login nativo con usuario/contraseña', category='sso') - SystemSetting.set_value('auth_google_enabled', google_val, 'Habilitar login SSO con Google Workspace', category='sso') - SystemSetting.set_value('auth_moodle_enabled', moodle_val, 'Habilitar login delegado con Moodle', category='sso') - - try: - audit = AuditLog( - user_id=current_user.id, - user_email=current_user.email, - action='UPDATE_AUTH_PROVIDERS', - module='settings', - details=f"Métodos de login actualizados: Local={local_val}, Google={google_val}, Moodle={moodle_val}" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - resp_data = { - 'status': 'success', - 'message': 'Métodos de autenticación actualizados correctamente.', - 'auth_providers': { - 'local': local_val == 'true', - 'local_enabled': local_val == 'true', - 'google': google_val == 'true', - 'google_enabled': google_val == 'true', - 'moodle': moodle_val == 'true', - 'moodle_enabled': moodle_val == 'true' - } - } - - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify(resp_data), 200 - - flash(_('Métodos de autenticación actualizados correctamente.'), 'success') - return redirect(url_for('admin.global_settings')) - diff --git a/backend/app/routes/api/__init__.py b/backend/app/routes/api/__init__.py deleted file mode 100644 index 4b59fe1..0000000 --- a/backend/app/routes/api/__init__.py +++ /dev/null @@ -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' -] diff --git a/backend/app/routes/api/admin.py b/backend/app/routes/api/admin.py deleted file mode 100644 index a111214..0000000 --- a/backend/app/routes/api/admin.py +++ /dev/null @@ -1,3077 +0,0 @@ -from flask import Blueprint, jsonify, request, g -from datetime import datetime, timezone -import re -from app.utils.jwt_decorators import jwt_required -from app.models.user import User -from app.models.role import Role, Permission, SYSTEM_MODULES -from app.models.subject import Subject, Commission, CommissionTeacher -from app.models.career import Career -from app.models.classroom import Classroom -from app.models.building import Building -from app.models.reservation import Reservation, ReservationStatus -from app.models.academic_term import AcademicTerm -from app.models.milestone import MilestoneType, AcademicMilestone -from app.models.audit_log import AuditLog -from app.services.audit_service import AuditService -from sqlalchemy import or_ -from app.constants.document_types import DOCUMENT_TYPES, validate_document, format_document -from app.services.enrollment_service import EnrollmentService -from app.services.gradebook_service import GradebookService -from app import db - -api_admin_bp = Blueprint('api_admin', __name__) - -@api_admin_bp.route('/users', methods=['GET']) -@jwt_required -def get_users(): - search = request.args.get('search', '').strip().lower() - role_id = request.args.get('role', type=int) - status = request.args.get('status', '').strip().lower() - - query = User.query - if search: - query = query.filter( - (User.name.ilike(f'%{search}%')) | - (User.email.ilike(f'%{search}%')) | - (User.personal_email.ilike(f'%{search}%')) | - (User.document_number.ilike(f'%{search}%')) | - (User.first_name.ilike(f'%{search}%')) | - (User.last_name.ilike(f'%{search}%')) - ) - if role_id: - query = query.filter(User.role_id == role_id) - if status == 'active': - query = query.filter(User.is_active == True) - elif status == 'inactive': - query = query.filter(User.is_active == False) - - users = query.order_by(User.id.asc()).all() - roles = Role.query.order_by(Role.name.asc()).all() - - users_data = [] - for u in users: - d = u.to_dict() - d['role_obj'] = { - 'id': u.role_obj.id, - 'name': u.role_obj.name - } if u.role_obj else {'id': 1, 'name': u.role or 'Admin'} - users_data.append(d) - - roles_data = [{'id': r.id, 'name': r.name} for r in roles] - - return jsonify({ - 'status': 'success', - 'total': len(users_data), - 'users': users_data, - 'roles': roles_data, - 'document_types': DOCUMENT_TYPES - }), 200 - -@api_admin_bp.route('/roles', methods=['GET']) -@jwt_required -def get_roles(): - roles = Role.query.order_by(Role.id.asc()).all() - modules = [ - {'id': 'dashboard', 'name': 'Dashboard', 'icon': 'bi-speedometer2'}, - {'id': 'classrooms', 'name': 'Aulas y Espacios', 'icon': 'bi-door-open'}, - {'id': 'schedule', 'name': 'Cronograma', 'icon': 'bi-calendar3'}, - {'id': 'subjects', 'name': 'Asignaturas', 'icon': 'bi-book'}, - {'id': 'careers', 'name': 'Carreras', 'icon': 'bi-mortarboard'}, - {'id': 'commissions', 'name': 'Comisiones', 'icon': 'bi-diagram-3'}, - {'id': 'users', 'name': 'Usuarios', 'icon': 'bi-people'}, - {'id': 'roles', 'name': 'Roles (RBAC)', 'icon': 'bi-shield-check'}, - {'id': 'optimizer', 'name': 'Optimizador IA', 'icon': 'bi-cpu'}, - {'id': 'audit', 'name': 'Auditoría', 'icon': 'bi-clipboard-data'} - ] - - roles_data = [] - for r in roles: - perms_map = {} - for p in r.permissions: - perms_map[p.module] = p.access_level - - roles_data.append({ - 'id': r.id, - 'name': r.name, - 'description': r.description or f'Rol institucional de {r.name}', - 'is_system': getattr(r, 'is_system', True), - 'users_count': len(r.users), - 'users': [{'id': u.id, 'name': u.name} for u in r.users], - 'permissions': perms_map - }) - - return jsonify({ - 'status': 'success', - 'roles': roles_data, - 'modules': modules - }), 200 - -@api_admin_bp.route('/subjects', methods=['GET']) -@jwt_required -def get_subjects(): - search = request.args.get('search', '').strip().lower() - career_id = request.args.get('career_id', type=int) - active = request.args.get('active', '').strip().lower() - - query = Subject.query - if search: - query = query.filter( - (Subject.name.ilike(f'%{search}%')) | - (Subject.code.ilike(f'%{search}%')) | - (Subject.department.ilike(f'%{search}%')) | - (Subject.careers.any(Career.name.ilike(f'%{search}%'))) - ) - if career_id: - query = query.filter((Subject.career_id == career_id) | (Subject.careers.any(Career.id == career_id))) - if active == 'true': - query = query.filter(Subject.is_active == True) - elif active == 'false': - query = query.filter(Subject.is_active == False) - - subjects = query.order_by(Subject.id.asc()).all() - careers = Career.query.order_by(Career.name.asc()).all() - - subjects_data = [] - for s in subjects: - c_list = [{'id': c.id, 'name': c.name, 'code': c.code} for c in s.careers] if s.careers else [] - if not c_list and s.career_obj: - c_list = [{'id': s.career_obj.id, 'name': s.career_obj.name, 'code': s.career_obj.code}] - - c_names = ", ".join([c['name'] for c in c_list]) if c_list else (s.career_obj.name if s.career_obj else (s.department or 'General')) - - subjects_data.append({ - 'id': s.id, - 'code': s.code, - 'name': s.name, - 'career_id': s.career_id, - 'career_name': s.career_obj.name if s.career_obj else (s.department or 'General'), - 'career_obj': {'id': s.career_obj.id, 'name': s.career_obj.name} if s.career_obj else None, - 'careers': c_list, - 'career_names': c_names, - 'department': s.department or 'General', - 'description': getattr(s, 'description', '') or '', - 'credits': getattr(s, 'credits', 4), - 'is_active': s.is_active, - 'commissions_count': len(s.commissions), - 'commissions': [{'id': c.id, 'code': c.code, 'schedule': c.schedule} for c in s.commissions] - }) - - careers_data = [{'id': c.id, 'name': c.name} for c in careers] - - return jsonify({ - 'status': 'success', - 'total': len(subjects_data), - 'subjects': subjects_data, - 'careers': careers_data - }), 200 - -@api_admin_bp.route('/careers', methods=['GET']) -@jwt_required -def get_careers(): - search = request.args.get('search', '').strip().lower() - query = Career.query - if search: - query = query.filter(Career.name.ilike(f'%{search}%')) - - careers = query.order_by(Career.name.asc()).all() - careers_data = [] - for c in careers: - careers_data.append({ - 'id': c.id, - 'name': c.name, - 'code': getattr(c, 'code', f'CAR-{c.id}'), - 'description': getattr(c, 'description', '') or '', - 'degree_level': getattr(c, 'degree_level', 'Grado / Tecnicatura'), - 'is_active': getattr(c, 'is_active', True), - 'subjects_count': len(c.subjects), - 'subjects': [{'id': s.id, 'name': s.name, 'code': s.code} for s in c.subjects[:5]] - }) - - return jsonify({ - 'status': 'success', - 'total': len(careers_data), - 'careers': careers_data - }), 200 - -@api_admin_bp.route('/commissions', methods=['GET']) -@jwt_required -def get_commissions(): - search = request.args.get('search', '').strip().lower() - subject_id = request.args.get('subject_id', type=int) - career_id = request.args.get('career_id', type=int) - shift = request.args.get('shift', '').strip() - active = request.args.get('active', '').strip().lower() - - query = Commission.query - if subject_id: - query = query.filter(Commission.subject_id == subject_id) - if career_id: - query = query.join(Subject, Commission.subject_id == Subject.id).filter( - (Subject.career_id == career_id) | (Subject.careers.any(Career.id == career_id)) - ) - if shift: - query = query.filter(Commission.shift == shift) - if active == 'true': - query = query.filter(Commission.active == True) - elif active == 'false': - query = query.filter(Commission.active == False) - - unassigned_room = request.args.get('unassigned_room', '').strip().lower() - - commissions = query.order_by(Commission.id.asc()).all() - subjects = Subject.query.order_by(Subject.name.asc()).all() - - careers = Career.query.order_by(Career.name.asc()).all() - careers_data = [{'id': cr.id, 'name': cr.name, 'code': cr.code} for cr in careers] - - # Pre-cargar reservas activas para enriquecer con asignación de aula - reservations_by_comm = {} - all_res = Reservation.query.filter(Reservation.commission_id.isnot(None)).order_by(Reservation.start_time.asc()).all() - for r in all_res: - if r.commission_id not in reservations_by_comm: - reservations_by_comm[r.commission_id] = r - - commissions_data = [] - for c in commissions: - if search: - s_name = c.subject.name.lower() if c.subject else '' - c_code = c.code.lower() - if search not in s_name and search not in c_code: - continue - - res = reservations_by_comm.get(c.id) - c_room = res.classroom if res else None - c_code_val = c_room.code if c_room else None - is_virt_room = bool(c_room.is_virtual or 'virtual' in (c_room.code or '').lower() or 'virtual' in (c_room.building or '').lower()) if c_room else False - has_v_link = bool(c.virtual_link and c.virtual_link.strip()) - has_classroom = bool(c_code_val or has_v_link) - - if unassigned_room in ['true', '1'] and has_classroom: - continue - if unassigned_room in ['false', '0'] and not has_classroom: - continue - - career_name = c.career_name if hasattr(c, 'career_name') else 'Carrera General' - career_names = c.career_names if hasattr(c, 'career_names') else career_name - careers_list = c.careers if hasattr(c, 'careers') else [] - career_id_val = c.career_id if hasattr(c, 'career_id') else (c.subject.career_id if c.subject else None) - - display_room = c_code_val or ('Campus Virtual' if has_v_link else 'Sin Aula') - - commissions_data.append({ - 'id': c.id, - 'code': c.code, - 'full_code': c.get_full_code() if hasattr(c, 'get_full_code') else c.code, - 'subject_id': c.subject_id, - 'subject_name': c.subject.name if c.subject else 'Sin materia', - 'subject_code': c.subject.code if c.subject else '-', - 'career_id': career_id_val, - 'career_name': career_name, - 'career_names': career_names, - 'careers': careers_list, - 'semester': getattr(c, 'semester', '1C') or '1C', - 'year': getattr(c, 'year', 2026) or 2026, - 'academic_term_id': getattr(c, 'academic_term_id', None), - 'teacher_id': c.teacher_id, - 'teacher_name': c.teacher_name if hasattr(c, 'teacher_name') else (c.teacher.name if c.teacher else None), - 'teachers': c.teachers if hasattr(c, 'teachers') else [], - 'teacher_names': c.teacher_names if hasattr(c, 'teacher_names') else (c.teacher_name if hasattr(c, 'teacher_name') else 'Sin asignar'), - 'schedule': c.schedule or 'A coordinar', - 'shift': c.shift or 'Mañana', - 'max_students': c.max_students or 35, - 'current_students': getattr(c, 'current_students', 0) or 0, - 'active': c.active, - 'virtual_link': getattr(c, 'virtual_link', '') or '', - 'has_classroom': has_classroom, - 'classroom_name': display_room, - 'classroom_code': c_code_val, - 'is_virtual': is_virt_room or has_v_link - }) - - subjects_data = [] - for s in subjects: - c_name = s.career_obj.name if (hasattr(s, 'career_obj') and s.career_obj) else 'Carrera General' - subjects_data.append({ - 'id': s.id, - 'name': s.name, - 'code': s.code, - 'career_id': s.career_id, - 'career': c_name, - 'career_name': c_name - }) - - from app.models.academic_term import AcademicTerm - terms = AcademicTerm.query.filter_by(is_active=True).order_by(AcademicTerm.year.desc(), AcademicTerm.start_date.desc()).all() - terms_data = [t.to_dict() for t in terms] - - return jsonify({ - 'status': 'success', - 'total': len(commissions_data), - 'commissions': commissions_data, - 'subjects': subjects_data, - 'academic_terms': terms_data, - 'careers': careers_data - }), 200 - -# --------------------------------------------------------- -# USERS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/users', methods=['POST']) -@jwt_required -def create_user(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - email = data.get('email', '').strip().lower() - first_name = data.get('first_name', '').strip() - last_name = data.get('last_name', '').strip() - name = data.get('name', '').strip() - if not name and (first_name or last_name): - name = f"{first_name} {last_name}".strip() - elif name and not first_name: - parts = name.split() - first_name = parts[0] if parts else '' - last_name = ' '.join(parts[1:]) if len(parts) > 1 else '' - - password = data.get('password', '').strip() - role_id = data.get('role_id') - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] - - phone = data.get('phone', '').strip() - personal_email = data.get('personal_email', '').strip().lower() - address = data.get('address', '').strip() - document_type = data.get('document_type', 'DNI').strip().upper() - document_number = data.get('document_number', '').strip() - - if not email or not name: - return jsonify({'error': 'ValidationError', 'message': 'El nombre y el email son obligatorios.'}), 400 - - if User.query.filter(User.email.ilike(email)).first(): - return jsonify({'error': 'Conflict', 'message': f'Ya existe un usuario con el email {email}.'}), 409 - - if document_number: - is_valid, clean_doc, err_msg = validate_document(document_type, document_number) - if not is_valid: - return jsonify({'error': 'ValidationError', 'message': err_msg}), 400 - document_number = clean_doc - - existing_doc = User.query.filter( - User.document_type == document_type, - User.document_number == document_number - ).first() - if existing_doc: - return jsonify({'error': 'Conflict', 'message': f'Ya existe un usuario con {document_type} {document_number}.'}), 409 - - role_obj = None - if role_id: - role_obj = Role.query.get(int(role_id)) - role_name = role_obj.name if role_obj else data.get('role', 'Docente') - - user = User( - email=email, - personal_email=personal_email, - name=name, - first_name=first_name, - last_name=last_name, - phone=phone, - address=address, - document_type=document_type, - document_number=document_number, - role=role_name, - role_id=int(role_id) if role_id else None, - is_active=bool(is_active) - ) - user.set_password(password or 'edu-space2026') - db.session.add(user) - db.session.commit() - - # Encolar sincronización con Moodle de forma asíncrona tolerante a fallos - try: - from app.services.moodle_queue_service import moodle_queue_service - username = user.email.split('@')[0].lower() - moodle_queue_service.enqueue_task( - action='CREATE_USER', - entity_type='user', - entity_id=user.id, - payload={ - 'username': username, - 'email': user.email, - 'firstname': user.first_name or (user.name.split()[0] if user.name else 'Docente'), - 'lastname': user.last_name or (user.name.split()[1] if len(user.name.split()) > 1 else 'EduSpace'), - 'password': password or 'EduSpace2026*' - } - ) - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Usuario creado exitosamente.', - 'user': user.to_dict() - }), 201 - -@api_admin_bp.route('/users/', methods=['GET']) -@jwt_required -def get_user_by_id(id): - user = User.query.get_or_404(id) - d = user.to_dict() - d['role_obj'] = { - 'id': user.role_obj.id, - 'name': user.role_obj.name - } if user.role_obj else {'id': 1, 'name': user.role or 'Admin'} - return jsonify({ - 'status': 'success', - 'user': d - }), 200 - -@api_admin_bp.route('/users/', methods=['PUT']) -@jwt_required -def update_user(id): - user = User.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - first_name = data.get('first_name', user.first_name or '').strip() - last_name = data.get('last_name', user.last_name or '').strip() - name = data.get('name', '').strip() - - if 'first_name' in data or 'last_name' in data: - user.first_name = first_name - user.last_name = last_name - user.name = f"{first_name} {last_name}".strip() - elif name: - user.name = name - parts = name.split() - user.first_name = parts[0] if parts else '' - user.last_name = ' '.join(parts[1:]) if len(parts) > 1 else '' - - if 'phone' in data: - user.phone = (data['phone'] or '').strip() - if 'personal_email' in data: - user.personal_email = (data['personal_email'] or '').strip().lower() - if 'address' in data: - user.address = (data['address'] or '').strip() - - if 'document_type' in data or 'document_number' in data: - doc_type = data.get('document_type', user.document_type or 'DNI').strip().upper() - doc_num = data.get('document_number', user.document_number or '').strip() - - if doc_num: - is_valid, clean_doc, err_msg = validate_document(doc_type, doc_num) - if not is_valid: - return jsonify({'error': 'ValidationError', 'message': err_msg}), 400 - doc_num = clean_doc - - existing_doc = User.query.filter( - User.document_type == doc_type, - User.document_number == doc_num, - User.id != id - ).first() - if existing_doc: - return jsonify({'error': 'Conflict', 'message': f'El documento {doc_type} {doc_num} ya está asignado a otro usuario.'}), 409 - - user.document_type = doc_type - user.document_number = doc_num - - if 'email' in data and data['email']: - email = data['email'].strip().lower() - existing = User.query.filter(User.email.ilike(email), User.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'El email {email} ya está registrado por otro usuario.'}), 409 - user.email = email - if 'password' in data and data['password']: - user.set_password(data['password'].strip()) - if 'role_id' in data and data['role_id']: - role_obj = Role.query.get(int(data['role_id'])) - if role_obj: - user.role_id = role_obj.id - user.role = role_obj.name - if 'is_active' in data: - val = data['is_active'] - user.is_active = val in [True, 'true', '1', 'on'] - - db.session.commit() - - # Encolar actualización con Moodle de forma asíncrona tolerante a fallos - try: - from app.services.moodle_queue_service import moodle_queue_service - username = user.email.split('@')[0].lower() - moodle_queue_service.enqueue_task( - action='UPDATE_USER', - entity_type='user', - entity_id=user.id, - payload={ - 'username': username, - 'email': user.email, - 'firstname': user.first_name or (user.name.split()[0] if user.name else 'Docente'), - 'lastname': user.last_name or (user.name.split()[1] if len(user.name.split()) > 1 else 'EduSpace') - } - ) - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Usuario actualizado correctamente.', - 'user': user.to_dict() - }), 200 - -@api_admin_bp.route('/users/document-types', methods=['GET']) -@jwt_required -def get_document_types(): - return jsonify({ - 'status': 'success', - 'document_types': DOCUMENT_TYPES - }), 200 - -@api_admin_bp.route('/users//password', methods=['POST', 'PUT']) -@jwt_required -def reset_user_password(id): - """ - Permite a los administradores restablecer la contraseña de acceso de cualquier usuario. - """ - if not g.jwt_user.is_admin(): - return jsonify({ - 'error': 'Forbidden', - 'message': 'Solo los administradores institucionales pueden restablecer contraseñas.' - }), 403 - - user = User.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - new_password = (data.get('password') or data.get('new_password') or '').strip() - - if not new_password or len(new_password) < 6: - return jsonify({ - 'error': 'BadRequest', - 'message': 'La nueva contraseña debe contener al menos 6 caracteres.' - }), 400 - - user.set_password(new_password) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': f'Contraseña restablecida exitosamente para {user.name}.', - 'user_id': user.id - }), 200 - - -@api_admin_bp.route('/users//toggle', methods=['POST']) -@jwt_required -def toggle_user(id): - user = User.query.get_or_404(id) - user.is_active = not user.is_active - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': user.id, - 'is_active': user.is_active, - 'message': f'Usuario {"activado" if user.is_active else "desactivado"} correctamente.' - }), 200 - -@api_admin_bp.route('/users/', methods=['DELETE']) -@jwt_required -def delete_user(id): - user = User.query.get_or_404(id) - has_reservations = len(user.reservations) if user.reservations else 0 - if has_reservations > 0: - user.is_active = False - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'El usuario tiene reservas asociadas. Se ha desactivado en su lugar.' - }), 200 - - db.session.delete(user) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Usuario eliminado permanentemente.' - }), 200 - -# --------------------------------------------------------- -# ROLES CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/roles', methods=['POST']) -@jwt_required -def create_role(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - name = data.get('name', '').strip() - description = data.get('description', '').strip() - raw_perms = data.get('permissions', {}) - if isinstance(raw_perms, str): - try: - import json - permissions = json.loads(raw_perms) - except Exception: - permissions = {} - elif isinstance(raw_perms, dict): - permissions = raw_perms - else: - permissions = {} - - if not name: - return jsonify({'error': 'ValidationError', 'message': 'El nombre del rol es obligatorio.'}), 400 - - if Role.query.filter(Role.name.ilike(name)).first(): - return jsonify({'error': 'Conflict', 'message': f'Ya existe un rol llamado {name}.'}), 409 - - role = Role(name=name, description=description, is_system=False) - db.session.add(role) - db.session.flush() - - for mod, level in permissions.items(): - role.set_permission(mod, level) - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Rol creado exitosamente.', - 'role': role.to_dict() - }), 201 - -@api_admin_bp.route('/roles/', methods=['PUT']) -@jwt_required -def update_role(id): - role = Role.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'name' in data and data['name']: - name = data['name'].strip() - existing = Role.query.filter(Role.name.ilike(name), Role.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otro rol llamado {name}.'}), 409 - role.name = name - - if 'description' in data: - role.description = data['description'].strip() - - if 'permissions' in data and isinstance(data['permissions'], dict): - for mod, level in data['permissions'].items(): - role.set_permission(mod, level) - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Rol actualizado correctamente.', - 'role': role.to_dict() - }), 200 - -@api_admin_bp.route('/roles/', methods=['DELETE']) -@jwt_required -def delete_role(id): - role = Role.query.get_or_404(id) - if role.is_system: - return jsonify({'error': 'Forbidden', 'message': 'No se pueden eliminar roles de sistema.'}), 403 - if role.users and len(role.users) > 0: - return jsonify({'error': 'Conflict', 'message': f'El rol tiene {len(role.users)} usuarios asignados. Reasígnelos primero.'}), 409 - - db.session.delete(role) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Rol eliminado exitosamente.' - }), 200 - -# --------------------------------------------------------- -# CAREERS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/careers', methods=['POST']) -@jwt_required -def create_career(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - name = data.get('name', '').strip() - code = data.get('code', '').strip() - description = data.get('description', '').strip() - - if not name: - return jsonify({'error': 'ValidationError', 'message': 'El nombre de la carrera es obligatorio.'}), 400 - - if Career.query.filter(Career.name.ilike(name)).first(): - return jsonify({'error': 'Conflict', 'message': f'Ya existe una carrera con el nombre {name}.'}), 409 - - career = Career(name=name, code=code or None, description=description or None) - db.session.add(career) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Carrera creada exitosamente.', - 'career': career.to_dict() - }), 201 - -@api_admin_bp.route('/careers/', methods=['PUT']) -@jwt_required -def update_career(id): - career = Career.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'name' in data and data['name']: - name = data['name'].strip() - existing = Career.query.filter(Career.name.ilike(name), Career.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otra carrera con el nombre {name}.'}), 409 - career.name = name - - if 'code' in data: - career.code = data['code'].strip() or None - - if 'description' in data: - career.description = data['description'].strip() or None - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Carrera actualizada correctamente.', - 'career': career.to_dict() - }), 200 - -@api_admin_bp.route('/careers/', methods=['DELETE']) -@jwt_required -def delete_career(id): - career = Career.query.get_or_404(id) - if career.subjects and len(career.subjects) > 0: - return jsonify({ - 'error': 'Conflict', - 'message': f'No se puede eliminar la carrera porque tiene {len(career.subjects)} asignaturas vinculadas.' - }), 409 - - db.session.delete(career) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Carrera eliminada permanentemente.' - }), 200 - -# --------------------------------------------------------- -# SUBJECTS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/subjects', methods=['POST']) -@jwt_required -def create_subject(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - code = data.get('code', '').strip().upper() - name = data.get('name', '').strip() - department = data.get('department', '').strip() - credits = int(data.get('credits', 4) or 4) - career_id = data.get('career_id') - career_id = int(career_id) if career_id else None - description = data.get('description', '').strip() - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] - - if not code or not name: - return jsonify({'error': 'ValidationError', 'message': 'El código y nombre de la asignatura son obligatorios.'}), 400 - - if Subject.query.filter_by(code=code).first(): - return jsonify({'error': 'Conflict', 'message': f'Ya existe una asignatura con el código {code}.'}), 409 - - subject = Subject( - code=code, - name=name, - department=department, - credits=credits, - career_id=career_id, - description=description, - is_active=bool(is_active) - ) - - career_ids = data.get('career_ids') - if career_ids: - if isinstance(career_ids, str): - c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] - elif isinstance(career_ids, list): - c_id_list = [int(x) for x in career_ids if str(x).isdigit()] - else: - c_id_list = [] - if c_id_list: - c_objs = Career.query.filter(Career.id.in_(c_id_list)).all() - subject.careers = c_objs - if c_objs and not subject.career_id: - subject.career_id = c_objs[0].id - elif career_id: - c_obj = Career.query.get(career_id) - if c_obj: - subject.careers = [c_obj] - - db.session.add(subject) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Asignatura creada exitosamente.', - 'subject': subject.to_dict() - }), 201 - -@api_admin_bp.route('/subjects/', methods=['PUT']) -@jwt_required -def update_subject(id): - subject = Subject.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'code' in data and data['code']: - code = data['code'].strip().upper() - existing = Subject.query.filter(Subject.code == code, Subject.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otra asignatura con el código {code}.'}), 409 - subject.code = code - - if 'name' in data and data['name']: - subject.name = data['name'].strip() - - if 'department' in data: - subject.department = data['department'].strip() - - if 'credits' in data and data['credits'] is not None: - subject.credits = int(data['credits']) - - if 'career_id' in data: - c_id = data['career_id'] - subject.career_id = int(c_id) if c_id else None - - if 'career_ids' in data: - career_ids = data.get('career_ids') - if isinstance(career_ids, str): - c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] - elif isinstance(career_ids, list): - c_id_list = [int(x) for x in career_ids if str(x).isdigit()] - else: - c_id_list = [] - if c_id_list: - c_objs = Career.query.filter(Career.id.in_(c_id_list)).all() - subject.careers = c_objs - if c_objs and not subject.career_id: - subject.career_id = c_objs[0].id - else: - subject.careers = [] - elif 'career_id' in data and subject.career_id: - c_obj = Career.query.get(subject.career_id) - if c_obj and c_obj not in subject.careers: - subject.careers = [c_obj] - - if 'description' in data: - subject.description = data['description'].strip() - - if 'is_active' in data: - val = data['is_active'] - subject.is_active = val in [True, 'true', '1', 'on'] - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Asignatura actualizada correctamente.', - 'subject': subject.to_dict() - }), 200 - -@api_admin_bp.route('/subjects//toggle', methods=['POST']) -@jwt_required -def toggle_subject(id): - subject = Subject.query.get_or_404(id) - subject.is_active = not subject.is_active - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': subject.id, - 'is_active': subject.is_active, - 'message': f'Asignatura {"activada" if subject.is_active else "desactivada"} correctamente.' - }), 200 - -@api_admin_bp.route('/subjects/', methods=['DELETE']) -@jwt_required -def delete_subject(id): - subject = Subject.query.get_or_404(id) - if subject.commissions and len(subject.commissions) > 0: - subject.is_active = False - db.session.commit() - return jsonify({ - 'status': 'deactivated', - 'action': 'deactivated', - 'message': f'La asignatura "{subject.name}" tiene {len(subject.commissions)} comisión(es) vinculada(s). Se ha desactivado en su lugar para proteger el historial académico.' - }), 200 - - name = subject.name - db.session.delete(subject) - db.session.commit() - return jsonify({ - 'status': 'deleted', - 'action': 'deleted', - 'message': f'Asignatura "{name}" eliminada permanentemente del sistema.' - }), 200 - -# --------------------------------------------------------- -# COMMISSIONS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/commissions', methods=['POST']) -@jwt_required -def create_commission(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - subject_id = data.get('subject_id') - code = data.get('code', '').strip() - semester = (data.get('semester') or '1C').strip() - year = int(data.get('year', datetime.now().year) or datetime.now().year) - academic_term_id = data.get('academic_term_id') - academic_term_id = int(academic_term_id) if (academic_term_id and str(academic_term_id).strip()) else None - - # Si se seleccionó Ciclo Lectivo, sincronizar año y cuatrimestre inteligentemente - if academic_term_id: - from app.models.academic_term import AcademicTerm - term_obj = AcademicTerm.query.get(academic_term_id) - if term_obj: - if not data.get('year') or int(data.get('year')) == datetime.now().year: - year = term_obj.year - if not data.get('semester') or data.get('semester') == '1C': - p_text = f"{term_obj.name} {term_obj.period_type or ''} {term_obj.code}".lower() - if '2c' in p_text or 'segundo' in p_text or '2º' in p_text or '2do' in p_text: - semester = '2C' - elif 'anual' in p_text: - semester = 'Anual' - else: - semester = '1C' - - teacher_id = data.get('teacher_id') - teacher_id = int(teacher_id) if (teacher_id and str(teacher_id).strip()) else None - max_students = int(data.get('max_students', 35) or 35) - schedule = (data.get('schedule') or '').strip() - shift = (data.get('shift') or 'Mañana').strip() - virtual_link = (data.get('virtual_link') or '').strip() - active = data.get('active', True) - if isinstance(active, str): - active = active.lower() in ['true', '1', 'on'] - - if not subject_id or not code: - return jsonify({'error': 'ValidationError', 'message': 'La asignatura y código de comisión son obligatorios.'}), 400 - - subject = Subject.query.get(int(subject_id)) - if not subject: - return jsonify({'error': 'NotFound', 'message': f'La asignatura con ID {subject_id} no existe.'}), 404 - - virtual_link = (virtual_link or '').strip() or None - - existing = Commission.query.filter_by( - subject_id=int(subject_id), - code=code, - semester=semester, - year=year - ).first() - - if existing: - existing.teacher_id = teacher_id - existing.max_students = max_students - existing.schedule = schedule - existing.shift = shift - if academic_term_id: - existing.academic_term_id = academic_term_id - if virtual_link: - existing.virtual_link = virtual_link - existing.active = bool(active) - if teacher_id: - ct = CommissionTeacher.query.filter_by(commission_id=existing.id, user_id=teacher_id).first() - if not ct: - db.session.add(CommissionTeacher(commission_id=existing.id, user_id=teacher_id, role='Titular', is_primary=True)) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': f'Comisión {code} asociada a {subject.name} actualizada exitosamente.', - 'commission': existing.to_dict() - }), 200 - - commission = Commission( - subject_id=int(subject_id), - code=code, - semester=semester, - year=year, - teacher_id=teacher_id, - max_students=max_students, - schedule=schedule, - shift=shift, - virtual_link=virtual_link, - academic_term_id=academic_term_id, - active=bool(active) - ) - db.session.add(commission) - db.session.flush() - - if teacher_id: - db.session.add(CommissionTeacher(commission_id=commission.id, user_id=teacher_id, role='Titular', is_primary=True)) - - # Soporte para docentes adicionales al crear comisión - extra_teachers = data.get('teacher_ids') or data.get('teachers') or [] - for et in extra_teachers: - u_id = et.get('user_id') if isinstance(et, dict) else et - u_role = et.get('role', 'Adjunto') if isinstance(et, dict) else 'Adjunto' - if u_id and int(u_id) != teacher_id: - db.session.add(CommissionTeacher(commission_id=commission.id, user_id=int(u_id), role=u_role, is_primary=False)) - - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': f'Comisión {code} asociada exitosamente a {subject.name}.', - 'commission': commission.to_dict() - }), 201 - - -@api_admin_bp.route('/commissions/', methods=['GET']) -@jwt_required -def get_commission_detail(id): - comm = Commission.query.get_or_404(id) - return jsonify({ - 'status': 'success', - 'commission': comm.to_dict() - }), 200 - - -@api_admin_bp.route('/commissions/', methods=['PUT']) -@jwt_required -def update_commission(id): - comm = Commission.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'subject_id' in data and data['subject_id']: - comm.subject_id = int(data['subject_id']) - if 'academic_term_id' in data: - t_id = data['academic_term_id'] - comm.academic_term_id = int(t_id) if (t_id and str(t_id).strip()) else None - if 'code' in data and data['code']: - comm.code = data['code'].strip() - if 'semester' in data and data['semester']: - comm.semester = data['semester'].strip() - if 'year' in data and data['year']: - comm.year = int(data['year']) - if 'teacher_id' in data: - t_id = data['teacher_id'] - comm.teacher_id = int(t_id) if (t_id and str(t_id).strip()) else None - if comm.teacher_id: - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=comm.teacher_id).first() - if not ct: - db.session.add(CommissionTeacher(commission_id=comm.id, user_id=comm.teacher_id, role='Titular', is_primary=True)) - if 'max_students' in data and data['max_students']: - comm.max_students = int(data['max_students']) - if 'schedule' in data: - comm.schedule = data['schedule'].strip() - if 'shift' in data: - comm.shift = data['shift'].strip() - if 'virtual_link' in data: - comm.virtual_link = data['virtual_link'].strip() - if 'active' in data: - val = data['active'] - comm.active = val in [True, 'true', '1', 'on'] - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Comisión actualizada correctamente.', - 'commission': comm.to_dict() - }), 200 - -@api_admin_bp.route('/commissions//toggle', methods=['POST']) -@jwt_required -def toggle_commission(id): - comm = Commission.query.get_or_404(id) - comm.active = not comm.active - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': comm.id, - 'active': comm.active, - 'message': f'Comisión {"activada" if comm.active else "desactivada"} correctamente.' - }), 200 - -@api_admin_bp.route('/commissions/', methods=['DELETE']) -@jwt_required -def delete_commission(id): - comm = Commission.query.get_or_404(id) - reservations_count = len(comm.reservations) if comm.reservations else 0 - enrollments_count = len(comm.enrollments) if hasattr(comm, 'enrollments') and comm.enrollments else 0 - - if reservations_count > 0 or enrollments_count > 0: - comm.active = False - db.session.commit() - return jsonify({ - 'status': 'deactivated', - 'action': 'deactivated', - 'message': f'La comisión tiene {reservations_count} reserva(s) y {enrollments_count} alumno(s) inscriptos. Se ha desactivado en su lugar para mantener la consistencia histórica.' - }), 200 - - from app.models.commission_teacher import CommissionTeacher - CommissionTeacher.query.filter_by(commission_id=comm.id).delete() - code = comm.code - db.session.delete(comm) - db.session.commit() - return jsonify({ - 'status': 'deleted', - 'action': 'deleted', - 'message': f'Comisión {code} eliminada exitosamente.' - }), 200 - -@api_admin_bp.route('/commissions//assign-teacher', methods=['POST']) -@jwt_required -def assign_commission_teacher(id): - comm = Commission.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - t_id = data.get('teacher_id') or data.get('user_id') - role = (data.get('role') or 'Titular').strip() - - if t_id: - t_id = int(t_id) - comm.teacher_id = t_id - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=t_id).first() - if not ct: - ct = CommissionTeacher(commission_id=comm.id, user_id=t_id, role=role, is_primary=True) - db.session.add(ct) - else: - ct.role = role - ct.is_primary = True - else: - comm.teacher_id = None - - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': comm.id, - 'teacher_id': comm.teacher_id, - 'teacher_name': comm.teacher_name, - 'teachers': comm.teachers, - 'message': 'Docente asignado correctamente.' - }), 200 - -@api_admin_bp.route('/commissions//teachers', methods=['POST']) -@jwt_required -def add_commission_teacher(id): - comm = Commission.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - user_id = data.get('user_id') or data.get('teacher_id') - if not user_id: - return jsonify({'error': 'ValidationError', 'message': 'El docente es requerido.'}), 400 - - user = User.query.get(int(user_id)) - if not user: - return jsonify({'error': 'NotFound', 'message': f'El usuario docente con ID {user_id} no existe.'}), 404 - - role = (data.get('role') or 'Adjunto').strip() - is_primary = data.get('is_primary', False) - if isinstance(is_primary, str): - is_primary = is_primary.lower() in ['true', '1', 'on'] - - existing = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user.id).first() - if existing: - existing.role = role - existing.is_primary = bool(is_primary) - else: - if is_primary or comm.teacher_id is None: - comm.teacher_id = user.id - is_primary = True - ct = CommissionTeacher( - commission_id=comm.id, - user_id=user.id, - role=role, - is_primary=bool(is_primary) - ) - db.session.add(ct) - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': f'{user.name} asignado/a como {role} en la comisión.', - 'teachers': comm.teachers, - 'commission': comm.to_dict() - }), 200 - -@api_admin_bp.route('/commissions//teachers/', methods=['DELETE']) -@jwt_required -def remove_commission_teacher(id, user_id): - comm = Commission.query.get_or_404(id) - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user_id).first() - if ct: - db.session.delete(ct) - - # Si era el docente titular, reasignar a otro docente disponible o dejar en None - if comm.teacher_id == user_id: - other = CommissionTeacher.query.filter(CommissionTeacher.commission_id == comm.id, CommissionTeacher.user_id != user_id).first() - comm.teacher_id = other.user_id if other else None - if other: - other.is_primary = True - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Docente desvinculado de la comisión correctamente.', - 'teachers': comm.teachers, - 'commission': comm.to_dict() - }), 200 - -# --------------------------------------------------------- -# COMMISSION STUDENT ENROLLMENTS (FASE 2 MVP) -# --------------------------------------------------------- - -@api_admin_bp.route('/commissions//enrollments', methods=['GET']) -@jwt_required -def get_commission_enrollments(id): - comm = Commission.query.get_or_404(id) - enrollments = EnrollmentService.list_enrollments(comm.id) - return jsonify({ - 'commission_id': comm.id, - 'commission_code': comm.code, - 'count': len(enrollments), - 'max_students': comm.max_students, - 'current_students': comm.current_students, - 'enrollments': enrollments - }), 200 - -@api_admin_bp.route('/commissions//enrollments', methods=['POST']) -@jwt_required -def enroll_commission_student(id): - data = request.get_json(silent=True) or {} - student_id = data.get('student_id') - notes = data.get('notes') - allow_same_day_exception = bool(data.get('allow_same_day_exception', False)) - exception_reason = data.get('exception_reason') - - if not student_id: - return jsonify({'error': 'BadRequest', 'message': 'student_id es obligatorio.'}), 400 - - try: - enrollment = EnrollmentService.enroll_student( - commission_id=id, - student_id=int(student_id), - notes=notes, - allow_same_day_exception=allow_same_day_exception, - exception_reason=exception_reason - ) - return jsonify({ - 'status': 'success', - 'message': 'Estudiante matriculado exitosamente en la comisión.', - 'enrollment': enrollment.to_dict() - }), 201 - except ValueError as e: - return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 409 - -@api_admin_bp.route('/commissions//enrollments/', methods=['DELETE']) -@jwt_required -def unenroll_commission_student(id, student_id): - success = EnrollmentService.unenroll_student(commission_id=id, student_id=student_id) - if not success: - return jsonify({'error': 'NotFound', 'message': 'Matrícula no encontrada para este estudiante.'}), 404 - return jsonify({ - 'status': 'success', - 'message': 'Estudiante desvinculado de la comisión exitosamente.' - }), 200 - -@api_admin_bp.route('/commissions//enrollments/', methods=['PUT']) -@jwt_required -def update_commission_enrollment(id, student_id): - data = request.get_json(silent=True) or {} - status = data.get('status', 'activo') - notes = data.get('notes') - - enrollment = EnrollmentService.update_enrollment_status( - commission_id=id, - student_id=student_id, - status=status, - notes=notes - ) - if not enrollment: - return jsonify({'error': 'NotFound', 'message': 'Matrícula no encontrada.'}), 404 - - return jsonify({ - 'status': 'success', - 'message': 'Estado de matrícula actualizado.', - 'enrollment': enrollment.to_dict() - }), 200 - -# --------------------------------------------------------- -# COMMISSION GRADEBOOK & ACTAS (FASE 3 MVP) -# --------------------------------------------------------- - -@api_admin_bp.route('/commissions//gradebook', methods=['GET']) -@jwt_required -def get_commission_gradebook(id): - """Obtiene la matriz completa de calificaciones de la comisión.""" - try: - data = GradebookService.get_commission_gradebook(id) - return jsonify({'status': 'success', 'data': data}), 200 - except ValueError as e: - return jsonify({'error': 'NotFound', 'message': str(e)}), 404 - except Exception as e: - return jsonify({'error': 'ServerError', 'message': str(e)}), 500 - -@api_admin_bp.route('/commissions//gradebook/grades', methods=['POST', 'PUT']) -@jwt_required -def save_commission_grades(id): - """Carga masiva o individual de notas con autoguardado asíncrono.""" - data = request.get_json(silent=True) or {} - grader_id = getattr(request, 'current_user_id', None) - - try: - if 'grades' in data and isinstance(data['grades'], list): - res = GradebookService.bulk_save_grades( - commission_id=id, - grades_data=data['grades'], - grader_id=grader_id - ) - return jsonify({'status': 'success', 'message': f"{res['saved_count']} calificaciones guardadas.", 'data': res}), 200 - else: - milestone_id = data.get('milestone_id') - student_id = data.get('student_id') - score = data.get('score') - is_absent = bool(data.get('is_absent', False)) - feedback = data.get('feedback', '') - - if not milestone_id or not student_id: - return jsonify({'error': 'BadRequest', 'message': 'milestone_id y student_id son obligatorios.'}), 400 - - grade = GradebookService.save_single_grade( - commission_id=id, - milestone_id=int(milestone_id), - student_id=int(student_id), - score=float(score) if score is not None and str(score).strip() != '' else None, - is_absent=is_absent, - feedback=feedback, - grader_id=grader_id - ) - return jsonify({'status': 'success', 'message': 'Calificación guardada.', 'grade': grade.to_dict()}), 200 - - except ValueError as e: - return jsonify({'error': 'ValidationError', 'message': str(e)}), 400 - except Exception as e: - return jsonify({'error': 'ServerError', 'message': str(e)}), 500 - -@api_admin_bp.route('/commissions//gradebook/close', methods=['POST']) -@jwt_required -def close_commission_gradebook(id): - """Cierre formal del acta de regularidad y promoción.""" - data = request.get_json(silent=True) or {} - user_id = getattr(request, 'current_user_id', None) or 1 - notes = data.get('notes', '') - - try: - res = GradebookService.close_gradebook(commission_id=id, user_id=user_id, notes=notes) - return jsonify({'status': 'success', **res}), 200 - except ValueError as e: - return jsonify({'error': 'BadRequest', 'message': str(e)}), 400 - except Exception as e: - return jsonify({'error': 'ServerError', 'message': str(e)}), 500 - -@api_admin_bp.route('/commissions//gradebook/reopen', methods=['POST']) -@jwt_required -def reopen_commission_gradebook(id): - """Reapertura administrativa del acta de calificaciones.""" - data = request.get_json(silent=True) or {} - user_id = getattr(request, 'current_user_id', None) or 1 - reason = data.get('reason', '') - - try: - res = GradebookService.reopen_gradebook(commission_id=id, user_id=user_id, reason=reason) - return jsonify({'status': 'success', **res}), 200 - except ValueError as e: - return jsonify({'error': 'BadRequest', 'message': str(e)}), 400 - except Exception as e: - return jsonify({'error': 'ServerError', 'message': str(e)}), 500 - -# --------------------------------------------------------- -# ACADEMIC TERMS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/academic-terms', methods=['GET']) -@jwt_required -def get_academic_terms(): - terms = AcademicTerm.query.order_by(AcademicTerm.year.desc(), AcademicTerm.code.desc()).all() - terms_data = [] - for t in terms: - comm_count = Commission.query.filter_by(year=t.year).count() - terms_data.append({ - 'id': t.id, - 'code': t.code, - 'name': t.name, - 'year': t.year, - 'period_type': t.period_type, - 'start_date': t.start_date.isoformat() if t.start_date else None, - 'end_date': t.end_date.isoformat() if t.end_date else None, - 'is_current': t.is_current, - 'is_active': t.is_active, - 'commissions_count': comm_count - }) - return jsonify({ - 'status': 'success', - 'total': len(terms_data), - 'terms': terms_data - }), 200 - -@api_admin_bp.route('/academic-terms', methods=['POST']) -@jwt_required -def create_academic_term(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - code = data.get('code', '').strip() - name = data.get('name', '').strip() - year = int(data.get('year', datetime.now().year) or datetime.now().year) - period_type = data.get('period_type', 'Segundo Cuatrimestre').strip() - is_current = data.get('is_current', False) - if isinstance(is_current, str): - is_current = is_current.lower() in ['true', '1', 'on'] - - if not code or not name: - return jsonify({'error': 'ValidationError', 'message': 'Código y nombre son requeridos.'}), 400 - - existing = AcademicTerm.query.filter_by(code=code).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe un ciclo con el código {code}.'}), 409 - - if is_current: - AcademicTerm.query.update({'is_current': False}) - - term = AcademicTerm( - code=code, - name=name, - year=year, - period_type=period_type, - is_current=bool(is_current), - is_active=True - ) - db.session.add(term) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Ciclo lectivo creado exitosamente.', - 'term': term.to_dict() - }), 201 - -@api_admin_bp.route('/academic-terms/', methods=['PUT']) -@jwt_required -def update_academic_term(id): - term = AcademicTerm.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'code' in data and data['code']: - code = data['code'].strip() - existing = AcademicTerm.query.filter(AcademicTerm.code == code, AcademicTerm.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otro ciclo con el código {code}.'}), 409 - term.code = code - - if 'name' in data and data['name']: - term.name = data['name'].strip() - if 'year' in data and data['year']: - term.year = int(data['year']) - if 'period_type' in data: - term.period_type = data['period_type'].strip() - if 'is_current' in data: - is_cur = data['is_current'] in [True, 'true', '1', 'on'] - if is_cur: - AcademicTerm.query.update({'is_current': False}) - term.is_current = is_cur - if 'is_active' in data: - term.is_active = data['is_active'] in [True, 'true', '1', 'on'] - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Ciclo lectivo actualizado correctamente.', - 'term': term.to_dict() - }), 200 - -@api_admin_bp.route('/academic-terms//set-current', methods=['POST']) -@jwt_required -def set_current_academic_term(id): - term = AcademicTerm.query.get_or_404(id) - AcademicTerm.query.update({'is_current': False}) - term.is_current = True - term.is_active = True - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': term.id, - 'message': f'"{term.name}" establecido como ciclo activo.' - }), 200 - -@api_admin_bp.route('/academic-terms//toggle', methods=['POST']) -@jwt_required -def toggle_academic_term(id): - term = AcademicTerm.query.get_or_404(id) - if term.is_current and term.is_active: - return jsonify({ - 'error': 'Conflict', - 'message': 'No se puede desactivar el ciclo lectivo actualmente activo. Seleccione otro ciclo activo primero.' - }), 400 - term.is_active = not term.is_active - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': term.id, - 'is_active': term.is_active, - 'message': f'Ciclo lectivo {"habilitado" if term.is_active else "desactivado"} correctamente.' - }), 200 - -@api_admin_bp.route('/academic-terms/', methods=['DELETE']) -@jwt_required -def delete_academic_term(id): - term = AcademicTerm.query.get_or_404(id) - if term.is_current: - return jsonify({ - 'error': 'Conflict', - 'message': 'No se puede eliminar el ciclo lectivo actualmente activo. Seleccione otro ciclo activo primero.' - }), 400 - - commissions_count = Commission.query.filter_by(academic_term_id=id).count() - if commissions_count > 0: - # Soft delete para preservar integridad de comisiones - term.is_active = False - db.session.commit() - return jsonify({ - 'status': 'success', - 'soft_deleted': True, - 'message': f'El ciclo lectivo tiene {commissions_count} comisiones asociadas. Ha sido desactivado para proteger el historial académico.' - }), 200 - - db.session.delete(term) - db.session.commit() - return jsonify({ - 'status': 'success', - 'soft_deleted': False, - 'message': 'Ciclo lectivo eliminado permanentemente.' - }), 200 - -# --------------------------------------------------------- -# MILESTONE TYPES CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/milestone-types', methods=['GET']) -@jwt_required -def get_milestone_types(): - types = MilestoneType.query.order_by(MilestoneType.sort_order.asc(), MilestoneType.id.asc()).all() - return jsonify({ - 'status': 'success', - 'total': len(types), - 'milestone_types': [t.to_dict() for t in types] - }), 200 - -@api_admin_bp.route('/milestone-types', methods=['POST']) -@jwt_required -def create_milestone_type(): - data = request.get_json(silent=True) or request.form.to_dict() or {} - name = data.get('name', '').strip() - code = data.get('code', '').strip().lower().replace(' ', '_') - color = data.get('color', '#0d6efd').strip() - description = data.get('description', '').strip() - sort_order = int(data.get('sort_order', 0) or 0) - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] - - if not name or not code: - return jsonify({'error': 'ValidationError', 'message': 'Nombre y código son obligatorios.'}), 400 - - existing = MilestoneType.query.filter_by(code=code).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe una tipificación con el código {code}.'}), 409 - - mt = MilestoneType( - name=name, - code=code, - color=color, - description=description, - sort_order=sort_order, - is_active=bool(is_active) - ) - db.session.add(mt) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Tipificación de hito creada correctamente.', - 'milestone_type': mt.to_dict() - }), 201 - -@api_admin_bp.route('/milestone-types/', methods=['PUT']) -@jwt_required -def update_milestone_type(id): - mt = MilestoneType.query.get_or_404(id) - data = request.get_json(silent=True) or request.form.to_dict() or {} - - if 'name' in data and data['name']: - mt.name = data['name'].strip() - if 'code' in data and data['code']: - code = data['code'].strip().lower().replace(' ', '_') - existing = MilestoneType.query.filter(MilestoneType.code == code, MilestoneType.id != id).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otra tipificación con el código {code}.'}), 409 - mt.code = code - if 'color' in data: - mt.color = data['color'].strip() - if 'description' in data: - mt.description = data['description'].strip() - if 'sort_order' in data: - mt.sort_order = int(data['sort_order']) - if 'is_active' in data: - mt.is_active = data['is_active'] in [True, 'true', '1', 'on'] - - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Tipificación actualizada correctamente.', - 'milestone_type': mt.to_dict() - }), 200 - -@api_admin_bp.route('/milestone-types//toggle', methods=['POST']) -@jwt_required -def toggle_milestone_type(id): - mt = MilestoneType.query.get_or_404(id) - mt.is_active = not mt.is_active - db.session.commit() - return jsonify({ - 'status': 'success', - 'id': mt.id, - 'is_active': mt.is_active, - 'message': f'Tipificación {"activada" if mt.is_active else "desactivada"} correctamente.' - }), 200 - -@api_admin_bp.route('/milestone-types/', methods=['DELETE']) -@jwt_required -def delete_milestone_type(id): - mt = MilestoneType.query.get_or_404(id) - milestone_count = AcademicMilestone.query.filter_by(milestone_type_id=id).count() - if milestone_count > 0: - mt.is_active = False - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': f'La tipificación tiene {milestone_count} hitos registrados. Se ha desactivado en su lugar.' - }), 200 - - db.session.delete(mt) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': 'Tipificación eliminada permanentemente.' - }), 200 - -# --------------------------------------------------------- -# GOOGLE SHEETS CONFIGURATION & ACADEMIC DATA RESET TOOL -# --------------------------------------------------------- - -@api_admin_bp.route('/sheets-config', methods=['GET']) -@jwt_required -def get_sheets_config(): - """Obtiene la configuración actual del Google Sheet para sincronización.""" - from app.models.setting import SystemSetting - from app.services.sheets_importer import BASE_CSV_URL, normalize_sheets_url - import os - - db_url = SystemSetting.get_value('google_sheets_url') - env_url = os.getenv('GOOGLE_SHEETS_URL') - active_url = db_url or env_url or BASE_CSV_URL - source = 'database' if db_url else ('environment' if env_url else 'default') - - return jsonify({ - 'status': 'success', - 'config': { - 'active_url': active_url, - 'source': source, - 'db_url': db_url, - 'default_url': BASE_CSV_URL, - 'normalized_url': normalize_sheets_url(active_url) - } - }), 200 - -@api_admin_bp.route('/sheets-config', methods=['POST']) -@jwt_required -def update_sheets_config(): - """Actualiza la URL del Google Sheet en SystemSetting.""" - from app.models.setting import SystemSetting - from app.services.sheets_importer import normalize_sheets_url - - data = request.get_json(silent=True) or request.form.to_dict() or {} - url = (data.get('url') or data.get('google_sheets_url') or '').strip() - - if not url: - return jsonify({ - 'error': 'ValidationError', - 'message': 'La URL de Google Sheets no puede estar vacía.' - }), 400 - - normalized = normalize_sheets_url(url) - SystemSetting.set_value('google_sheets_url', url, 'URL del Google Sheet académico configurada desde panel') - - return jsonify({ - 'status': 'success', - 'message': 'Configuración de Google Sheets guardada correctamente.', - 'config': { - 'active_url': url, - 'normalized_url': normalized, - 'source': 'database' - } - }), 200 - -@api_admin_bp.route('/reset-academic-data', methods=['POST']) -@jwt_required -def reset_academic_data_api(): - """ - Herramienta de limpieza/purga de datos académicos para pruebas del importador. - Permite eliminar reservas, comisiones, asignaturas, carreras y aulas. - """ - from scripts.reset_academic_data import execute_academic_reset - data = request.get_json(silent=True) or request.form.to_dict() or {} - - reset_all = data.get('all', False) in [True, 'true', '1', 'on'] - reset_reservations = reset_all or data.get('reservations', True) in [True, 'true', '1', 'on'] - reset_commissions = reset_all or data.get('commissions', False) in [True, 'true', '1', 'on'] - reset_subjects = reset_all or data.get('subjects', False) in [True, 'true', '1', 'on'] - reset_careers = reset_all or data.get('careers', False) in [True, 'true', '1', 'on'] - reset_classrooms = reset_all or data.get('classrooms', False) in [True, 'true', '1', 'on'] - - if reset_all: - reset_reservations = True - reset_commissions = True - reset_subjects = True - reset_careers = True - reset_classrooms = True - - result = execute_academic_reset( - reset_reservations=reset_reservations, - reset_commissions=reset_commissions, - reset_subjects=reset_subjects, - reset_careers=reset_careers, - reset_classrooms=reset_classrooms - ) - - if result.get('success'): - try: - from app.models.audit_log import AuditLog - audit = AuditLog( - user_id=getattr(request, 'current_user_id', None), - action_type='ACADEMIC_DATA_PURGE', - details=f"Purga académica ejecutada: {result.get('deleted')}", - ip_address=request.remote_addr - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': result.get('message', 'Datos reiniciados con éxito.'), - 'deleted': result.get('deleted', {}) - }), 200 - else: - return jsonify({ - 'status': 'error', - 'message': result.get('error', 'Error durante la purga de datos.') - }), 500 - -# --------------------------------------------------------- -# FASE 4: MODO IMPERSONACIÓN & DRAG-AND-DROP (ESTADIO 4.1 & 4.2) -# --------------------------------------------------------- - -@api_admin_bp.route('/admin/impersonate', methods=['POST']) -@jwt_required -def impersonate_user(): - """Iniciar sesión bajo la identidad de otro usuario (Superadmin / Bedelía).""" - admin_user = getattr(g, 'real_admin_user', g.jwt_user) - if not admin_user.is_admin(): - return jsonify({'error': 'Forbidden', 'message': 'Solo administradores pueden impersonar usuarios.'}), 403 - - data = request.get_json(silent=True) or {} - target_id = data.get('target_user_id') or data.get('user_id') - target_email = data.get('target_email') or data.get('email') - - target = None - if target_id: - target = db.session.get(User, int(target_id)) - elif target_email: - target = User.query.filter_by(email=target_email.strip()).first() - - if not target or not target.is_active: - return jsonify({'error': 'NotFound', 'message': 'Usuario objetivo no encontrado o inactivo.'}), 404 - - audit = AuditLog( - user_id=admin_user.id, - user_email=admin_user.email, - action='IMPERSONATE_START', - module='auth', - entity_id=target.id, - details=f"Administrador {admin_user.email} inició sesión temporal como {target.email} ({target.role})" - ) - db.session.add(audit) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': f"Impersonando exitosamente a {target.name or target.email}", - 'target_user': target.to_dict(), - 'real_admin_id': admin_user.id - }), 200 - -@api_admin_bp.route('/admin/stop-impersonating', methods=['POST']) -@jwt_required -def stop_impersonating(): - """Finalizar sesión de impersonación y restaurar cuenta de administrador.""" - admin_user = getattr(g, 'real_admin_user', g.jwt_user) - current_target = g.jwt_user - - audit = AuditLog( - user_id=admin_user.id, - user_email=admin_user.email, - action='IMPERSONATE_END', - module='auth', - entity_id=current_target.id if current_target else None, - details=f"Administrador {admin_user.email} finalizó la sesión de impersonación." - ) - db.session.add(audit) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Sesión de impersonación finalizada.' - }), 200 - -@api_admin_bp.route('/reservations/drag-update', methods=['POST']) -@jwt_required -def drag_update_reservation(): - """Actualización o creación rápida de reserva mediante arrastre en la grilla semanal.""" - data = request.get_json(silent=True) or {} - reservation_id = data.get('reservation_id') - commission_id = data.get('commission_id') - classroom_id = data.get('classroom_id') - start_time_str = data.get('start_time') - end_time_str = data.get('end_time') - - if not classroom_id or not start_time_str or not end_time_str: - return jsonify({'error': 'ValidationError', 'message': 'Faltan parámetros obligatorios (aula, inicio, fin).'}), 400 - - try: - if isinstance(start_time_str, str): - start_dt = datetime.fromisoformat(start_time_str.replace('Z', '+00:00')) - else: - start_dt = start_time_str - - if isinstance(end_time_str, str): - end_dt = datetime.fromisoformat(end_time_str.replace('Z', '+00:00')) - else: - end_dt = end_time_str - except Exception as e: - return jsonify({'error': 'ValidationError', 'message': f'Formato de fecha inválido: {str(e)}'}), 400 - - classroom = db.session.get(Classroom, classroom_id) - if not classroom: - return jsonify({'error': 'NotFound', 'message': 'Aula no encontrada.'}), 404 - - # Pre-validación de conflictos (físico, capacidad, docente) - from app.services.reservation_service import ReservationService - effective_comm_id = commission_id - if not effective_comm_id and reservation_id: - existing_res = db.session.get(Reservation, reservation_id) - if existing_res: - effective_comm_id = existing_res.commission_id - - res_service = ReservationService() - matrix = res_service.check_full_conflicts_matrix( - classroom_id=classroom_id, - start_time=start_dt, - end_time=end_dt, - commission_id=effective_comm_id, - exclude_id=reservation_id - ) - - if matrix.get('is_blocked'): - return jsonify({ - 'status': 'conflict', - 'error': 'ConflictDetected', - 'message': ' '.join(matrix.get('block_reasons', ['Conflicto detectado en la asignación.'])), - 'conflicts': matrix.get('block_reasons', []) - }), 409 - - admin_user = getattr(g, 'real_admin_user', g.jwt_user) - acting_user = g.jwt_user - - if reservation_id: - res = db.session.get(Reservation, reservation_id) - if not res: - return jsonify({'error': 'NotFound', 'message': 'Reserva no encontrada.'}), 404 - - res.classroom_id = classroom_id - res.start_time = start_dt - res.end_time = end_dt - action = 'UPDATE_RESERVATION_DRAG' - msg = f"Reserva #{res.id} reprogramada al aula {classroom.code} ({start_dt.strftime('%H:%M')} a {end_dt.strftime('%H:%M')})" - else: - comm = db.session.get(Commission, commission_id) if commission_id else None - res = Reservation( - classroom_id=classroom_id, - commission_id=commission_id, - user_id=acting_user.id, - start_time=start_dt, - end_time=end_dt, - purpose=f"Cursada regular - {comm.subject.name if comm and comm.subject else 'Comisión'}", - expected_attendees=comm.max_students if comm else 30, - status=ReservationStatus.CONFIRMED.value - ) - db.session.add(res) - action = 'CREATE_RESERVATION_DRAG' - msg = f"Comisión {comm.code if comm else ''} asignada al aula {classroom.code}" - - details_str = msg - if getattr(g, 'is_impersonating', False): - details_str += f" [Ejecutado bajo impersonación por Admin #{admin_user.id}]" - - audit = AuditLog( - user_id=admin_user.id, - user_email=admin_user.email, - action=action, - module='reservations', - entity_id=res.id, - details=details_str - ) - db.session.add(audit) - db.session.commit() - return jsonify({ - 'status': 'success', - 'message': msg, - 'reservation': res.to_dict() - }), 200 - - -# ============================================================================== -# CONFIGURACIÓN GLOBAL DEL SISTEMA (SMTP, AUTH PROVIDERS, GOOGLE OAUTH, MOODLE) -# ============================================================================== - -@api_admin_bp.route('/settings/all', methods=['GET']) -@jwt_required -def get_all_settings(): - """Retorna todas las configuraciones agrupadas por módulo, enmascarando contraseñas.""" - from app.models.setting import SystemSetting - - smtp_config = { - 'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'), - 'port': int(SystemSetting.get_value('smtp_port', 587) or 587), - 'user': SystemSetting.get_value('smtp_user', ''), - 'password': SystemSetting.get_masked_value('smtp_password', ''), - 'security': SystemSetting.get_value('smtp_security', 'STARTTLS'), - 'sender_email': SystemSetting.get_value('smtp_sender_email', 'notificaciones@unicaba.edu.ar'), - 'sender_name': SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA'), - 'enabled': SystemSetting.get_value('smtp_enabled', 'true') in ['true', 'True', '1', True] - } - - auth_providers = { - 'local': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'local_enabled': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'google': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'google_enabled': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'moodle': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True], - 'moodle_enabled': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True] - } - - google_oauth = { - 'client_id': SystemSetting.get_value('google_client_id', ''), - 'client_secret': SystemSetting.get_masked_value('google_client_secret', ''), - 'callback_url': SystemSetting.get_value('google_callback_url', '/auth/google/callback'), - 'allowed_domains': SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar,lasalle.edu.ar') - } - - moodle_config = { - 'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'), - 'ws_token': SystemSetting.get_masked_value('moodle_ws_token', ''), - 'timeout': int(SystemSetting.get_value('moodle_timeout', 10) or 10), - 'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True], - 'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15) or 15) - } - - ui_config = { - 'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True] - } - - return jsonify({ - 'status': 'success', - 'settings': { - 'smtp': smtp_config, - 'auth_providers': auth_providers, - 'google_oauth': google_oauth, - 'moodle': moodle_config, - 'ui': ui_config - } - }), 200 - - -@api_admin_bp.route('/settings/smtp', methods=['POST']) -@jwt_required -def update_smtp_settings(): - """Actualiza los parámetros del servidor de correo SMTP en la base de datos.""" - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Solo administradores pueden modificar la configuración SMTP.'}), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - - host = str(data.get('host', '')).strip() - port = str(data.get('port', 587)).strip() - user = str(data.get('user', '')).strip() - password = str(data.get('password', '')).strip() - security = str(data.get('security', 'STARTTLS')).strip().upper() - sender_email = str(data.get('sender_email', '')).strip() - sender_name = str(data.get('sender_name', 'Edu-Space UniCABA')).strip() - enabled = 'true' if data.get('enabled') in [True, 'true', '1', 'on'] else 'false' - - SystemSetting.set_value('smtp_host', host, 'Host del servidor SMTP', category='smtp') - SystemSetting.set_value('smtp_port', port, 'Puerto del servidor SMTP', category='smtp') - SystemSetting.set_value('smtp_user', user, 'Usuario o email de autenticación SMTP', category='smtp') - if password and password != '••••••••••••': - SystemSetting.set_encrypted_value('smtp_password', password, 'Contraseña de autenticación SMTP cifrada', category='smtp') - SystemSetting.set_value('smtp_security', security, 'Protocolo de seguridad SMTP (NONE, SSL, STARTTLS)', category='smtp') - SystemSetting.set_value('smtp_sender_email', sender_email, 'Email remitente oficial', category='smtp') - SystemSetting.set_value('smtp_sender_name', sender_name, 'Nombre remitente oficial', category='smtp') - SystemSetting.set_value('smtp_enabled', enabled, 'Habilitación del servicio SMTP', category='smtp') - - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='UPDATE_SMTP_SETTINGS', - module='settings', - details=f"Configuración SMTP actualizada (Host: {host}:{port}, Remitente: {sender_email})" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Configuración de servidor SMTP guardada exitosamente.' - }), 200 - - -@api_admin_bp.route('/settings/smtp/test', methods=['POST']) -@jwt_required -def test_smtp_connection(): - """Prueba en tiempo real la conexión al servidor SMTP y opcionalmente envía un email de prueba.""" - import smtplib - from email.mime.text import MIMEText - from email.mime.multipart import MIMEMultipart - from app.models.setting import SystemSetting - - data = request.get_json(silent=True) or request.form.to_dict() or {} - test_recipient = data.get('test_email') or g.jwt_user.email - - host = data.get('host') or SystemSetting.get_value('smtp_host', 'smtp.gmail.com') - port = int(data.get('port') or SystemSetting.get_value('smtp_port', 587) or 587) - user = data.get('user') or SystemSetting.get_value('smtp_user', '') - password = data.get('password') - if not password or password == '••••••••••••': - password = SystemSetting.get_decrypted_value('smtp_password', '') - security_val = data.get('security') or SystemSetting.get_value('smtp_security', 'STARTTLS') or 'STARTTLS' - security = str(security_val).upper() - sender_email = str(data.get('sender_email') or SystemSetting.get_value('smtp_sender_email', user) or 'notificaciones@unicaba.edu.ar') - sender_name = data.get('sender_name') or SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA') - - if not host or not port: - return jsonify({'status': 'error', 'message': 'Host y puerto SMTP son requeridos.'}), 400 - - try: - if security == 'SSL': - server = smtplib.SMTP_SSL(host, port, timeout=10) - else: - server = smtplib.SMTP(host, port, timeout=10) - if security == 'STARTTLS': - server.ehlo() - server.starttls() - server.ehlo() - - if user and password: - server.login(user, password) - - if test_recipient: - msg = MIMEMultipart('alternative') - msg['Subject'] = '✔ Prueba de Conexión SMTP - Edu-Space UniCABA' - msg['From'] = f"{sender_name} <{sender_email}>" - msg['To'] = test_recipient - - html_content = f""" -
-

Edu-Space UniCABA

-

Prueba de Conexión SMTP Exitosa

-

Este es un mensaje de prueba para confirmar que los parámetros del servidor de correo han sido configurados correctamente.

-
- Host: {host}:{port}
- Seguridad: {security}
- Usuario: {user or '(Sin autenticación)'}
- Remitente: {sender_email} -
-

Enviado desde el Panel de Administración de UniCABA.

-
- """ - msg.attach(MIMEText(html_content, 'html')) - server.sendmail(sender_email, [test_recipient], msg.as_string()) - - server.quit() - return jsonify({ - 'status': 'success', - 'message': f'Conexión SMTP exitosa. Correo de prueba enviado a {test_recipient}.' - }), 200 - - except Exception as e: - return jsonify({ - 'status': 'error', - 'message': f'Fallo en la prueba de conexión SMTP: {str(e)}' - }), 400 - - -@api_admin_bp.route('/settings/auth-providers', methods=['POST']) -@jwt_required -def update_auth_providers(): - """Habilita o deshabilita los proveedores de autenticación del sistema.""" - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Solo administradores pueden modificar los métodos de autenticación.'}), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - - # Soporte para claves tanto cortas (local) como largas (local_enabled) - local_input = data.get('local_enabled') if 'local_enabled' in data else data.get('local', True) - google_input = data.get('google_enabled') if 'google_enabled' in data else data.get('google', False) - moodle_input = data.get('moodle_enabled') if 'moodle_enabled' in data else data.get('moodle', False) - - local_val = 'true' if local_input in [True, 'true', '1', 'on'] else 'false' - google_val = 'true' if google_input in [True, 'true', '1', 'on'] else 'false' - moodle_val = 'true' if moodle_input in [True, 'true', '1', 'on'] else 'false' - - SystemSetting.set_value('auth_local_enabled', local_val, 'Habilitar login nativo con usuario/contraseña', category='sso') - SystemSetting.set_value('auth_google_enabled', google_val, 'Habilitar login SSO con Google Workspace', category='sso') - SystemSetting.set_value('auth_moodle_enabled', moodle_val, 'Habilitar login delegado con Moodle', category='sso') - - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='UPDATE_AUTH_PROVIDERS', - module='settings', - details=f"Métodos de login actualizados: Local={local_val}, Google={google_val}, Moodle={moodle_val}" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Métodos de autenticación actualizados correctamente.', - 'auth_providers': { - 'local': local_val == 'true', - 'local_enabled': local_val == 'true', - 'google': google_val == 'true', - 'google_enabled': google_val == 'true', - 'moodle': moodle_val == 'true', - 'moodle_enabled': moodle_val == 'true' - } - }), 200 - - -@api_admin_bp.route('/settings/ui', methods=['POST']) -@jwt_required -def update_ui_settings(): - """Habilita o deshabilita elementos de interfaz de usuario, como el banner de saludo institucional y selector de roles.""" - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Solo administradores pueden modificar las preferencias de interfaz.'}), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - show_banner_input = data.get('show_role_banner') - if show_banner_input is None: - show_banner_input = data.get('dashboard_role_banner_enabled') - - show_val = 'true' if show_banner_input in [True, 'true', '1', 'on', 1] else 'false' - SystemSetting.set_value('dashboard_role_banner_enabled', show_val, 'Mostrar banner de saludo y selector de rol en Dashboard', category='ui') - - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='UPDATE_UI_SETTINGS', - module='settings', - details=f"Preferencia de interfaz actualizada: banner_saludo_rol={show_val}" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Preferencia de interfaz guardada correctamente.', - 'ui': { - 'show_role_banner': show_val == 'true' - } - }), 200 - - -@api_admin_bp.route('/settings/demo-mode', methods=['GET', 'POST']) -@jwt_required -def toggle_demo_mode_api(): - """Habilita o deshabilita el Acceso Rápido Demo y las cuentas default (Bedelía, Docente, Alumno) vía API REST""" - from app.models.setting import SystemSetting - from app.models.user import User - from app.models.audit_log import AuditLog - from sqlalchemy import func - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Solo administradores pueden modificar el modo demo.'}), 403 - - demo_emails = ['bedelia@edu-space.com', 'docente@edu-space.com', 'alumno@edu-space.com'] - - if request.method == 'GET': - demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - demo_accounts_active = any(u.is_active for u in demo_users) - return jsonify({ - 'status': 'success', - 'demo_access_enabled': demo_access_enabled, - 'demo_accounts_active': demo_accounts_active - }), 200 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - if 'enabled' in data: - target_state = data['enabled'] in [True, 'true', '1', 'on'] - else: - current_state = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - target_state = not current_state - - SystemSetting.set_value( - 'demo_access_enabled', - 'true' if target_state else 'false', - 'Acceso Rápido Demo en pantalla de Login', - category='security' - ) - - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - for u in demo_users: - u.is_active = target_state - db.session.commit() - - action_name = 'ENABLE_DEMO_ACCOUNTS' if target_state else 'DISABLE_DEMO_ACCOUNTS' - msg_detail = ( - 'Acceso Rápido Demo habilitado y cuentas Bedelía, Docente y Alumno activadas' - if target_state else - 'Acceso Rápido Demo deshabilitado y cuentas default (Bedelía, Docente, Alumno) desactivadas' - ) - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action=action_name, - module='settings', - details=msg_detail - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': msg_detail, - 'demo_access_enabled': target_state, - 'demo_accounts_active': target_state - }), 200 - - -@api_admin_bp.route('/settings/google-oauth', methods=['POST']) -@jwt_required -def update_google_oauth_settings(): - """Actualiza las credenciales de integración de Google OAuth2.""" - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - client_id = str(data.get('client_id', '')).strip() - client_secret = str(data.get('client_secret', '')).strip() - allowed_domains = str(data.get('allowed_domains', 'unicaba.edu.ar')).strip() - callback_url = str(data.get('callback_url', '/auth/google/callback')).strip() - - SystemSetting.set_value('google_client_id', client_id, 'Client ID de Google OAuth2', category='sso_google') - if client_secret and client_secret != '••••••••••••': - SystemSetting.set_encrypted_value('google_client_secret', client_secret, 'Client Secret de Google OAuth2 cifrado', category='sso_google') - SystemSetting.set_value('google_allowed_domains', allowed_domains, 'Dominios permitidos separados por coma', category='sso_google') - SystemSetting.set_value('google_callback_url', callback_url, 'Ruta de callback autorizada de Google OAuth2', category='sso_google') - - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='UPDATE_GOOGLE_OAUTH_SETTINGS', - module='settings', - details="Credenciales de Google OAuth2 actualizadas" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Credenciales de Google OAuth2 guardadas correctamente.' - }), 200 - - -@api_admin_bp.route('/settings/moodle', methods=['POST']) -@jwt_required -def update_moodle_settings(): - """Actualiza la configuración de integración y Web Services con Moodle 4.1.""" - from app.models.setting import SystemSetting - from app.models.audit_log import AuditLog - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - server_url = str(data.get('server_url', 'http://10.0.0.207/moodle')).strip().rstrip('/') - ws_token = str(data.get('ws_token', '')).strip() - timeout = str(data.get('timeout', 10)).strip() - auto_sync = 'true' if data.get('auto_sync_enabled', True) in [True, 'true', '1', 'on'] else 'false' - sync_interval = str(data.get('sync_interval_minutes', 15)).strip() - - SystemSetting.set_value('moodle_server_url', server_url, 'URL base del servidor Moodle', category='sso_moodle') - if ws_token and ws_token != '••••••••••••': - SystemSetting.set_encrypted_value('moodle_ws_token', ws_token, 'Token de Web Services de Moodle cifrado', category='sso_moodle') - SystemSetting.set_value('moodle_timeout', timeout, 'Timeout en segundos para llamadas REST a Moodle', category='sso_moodle') - SystemSetting.set_value('moodle_auto_sync_enabled', auto_sync, 'Habilitación de sincronización periódica automática', category='sso_moodle') - SystemSetting.set_value('moodle_sync_interval_minutes', sync_interval, 'Intervalo en minutos para sincronización periódica', category='sso_moodle') - - if 'auth_moodle_enabled' in data: - auth_enabled = 'true' if data.get('auth_moodle_enabled') in [True, 'true', '1', 'on'] else 'false' - SystemSetting.set_value('auth_moodle_enabled', auth_enabled, 'Habilitar autenticación delegada con Moodle', category='sso_moodle') - if 'service_name' in data: - SystemSetting.set_value('moodle_service_name', str(data['service_name']).strip(), 'Nombre del servicio WebService Moodle', category='sso_moodle') - - try: - audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='UPDATE_MOODLE_SETTINGS', - module='settings', - details=f"Parámetros de Moodle actualizados (Servidor: {server_url})" - ) - db.session.add(audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'success', - 'message': 'Configuración de Moodle 4.1 guardada correctamente.' - }), 200 - - -@api_admin_bp.route('/settings/moodle/test', methods=['POST']) -@jwt_required -def test_moodle_connection(): - """Prueba la conectividad y validez del token Web Services contra Moodle 4.1.""" - from app.services.moodle_client import moodle_client - data = request.get_json(silent=True) or request.form.to_dict() or {} - server_url = data.get('server_url') - token = data.get('ws_token') - - result = moodle_client.test_connection(server_url=server_url, token=token) - if result.get('success'): - return jsonify(result), 200 - else: - return jsonify(result), 400 - - -def _verify_moodle_api_key_or_admin() -> bool: - """Valida si la petición proviene de Moodle vía API Key autorizada o de un administrador.""" - from app.models.setting import SystemSetting - import secrets - - # Extraer API Key de header, query param o body JSON - api_key = ( - request.headers.get('X-API-Key') - or request.headers.get('x-api-key') - or request.headers.get('X-Moodle-Api-Key') - or request.headers.get('x-moodle-api-key') - or request.args.get('api_key') - or (request.get_json(silent=True) or {}).get('api_key') - ) - if not api_key and request.headers.get('Authorization', '').startswith('ApiKey '): - api_key = request.headers.get('Authorization', '').replace('ApiKey ', '').strip() - - if api_key: - saved_key = SystemSetting.get_decrypted_value('moodle_api_key', '') - if saved_key and secrets.compare_digest(str(api_key).strip(), saved_key.strip()): - return True - - acting_user = getattr(g, 'jwt_user', None) - if acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN'): - return True - - return False - - -@api_admin_bp.route('/settings/moodle/api-key', methods=['GET']) -@jwt_required -def get_moodle_api_key(): - """Retorna la clave API institucional configurada para Moodle.""" - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403 - - import secrets - from app.models.setting import SystemSetting - api_key = SystemSetting.get_decrypted_value('moodle_api_key', '') - if not api_key: - api_key = secrets.token_hex(32) - SystemSetting.set_encrypted_value('moodle_api_key', api_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') - - return jsonify({ - 'status': 'success', - 'api_key': api_key, - 'header_name': 'X-API-Key', - 'sync_endpoint': '/api/v1/admin/settings/moodle/sync' - }), 200 - - -@api_admin_bp.route('/settings/moodle/api-key/regenerate', methods=['POST']) -@jwt_required -def regenerate_moodle_api_key(): - """Regenera una nueva clave API criptográfica para sincronizaciones seguras con Moodle.""" - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403 - - import secrets - from app.models.setting import SystemSetting - new_key = secrets.token_hex(32) - SystemSetting.set_encrypted_value('moodle_api_key', new_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') - - return jsonify({ - 'status': 'success', - 'api_key': new_key, - 'message': 'Clave API de Moodle regenerada exitosamente.' - }), 200 - - -@api_admin_bp.route('/moodle/sync-from-moodle', methods=['POST']) -@api_admin_bp.route('/settings/moodle/sync', methods=['POST']) -def sync_data_from_moodle(): - """Sincroniza usuarios, roles y catálogo desde Moodle hacia Admin Edu Space (autenticado por JWT o X-API-Key).""" - # Intentar cargar JWT si está presente - auth_header = request.headers.get('Authorization', '') - if auth_header.startswith('Bearer '): - token = auth_header.replace('Bearer ', '').strip() - try: - from app.services.jwt_service import JWTService - from app.services.user_service import user_service - payload = JWTService.decode_token(token, expected_type='access') - sub = payload.get('sub') - if sub: - user = user_service.get_by_id(int(sub)) - if user and user.is_active: - g.jwt_user = user - except Exception: - pass - - if not _verify_moodle_api_key_or_admin(): - return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado. Se requiere token JWT de ADMIN o header X-API-Key válido.'}), 403 - - from app.services.moodle_client import moodle_client - try: - res = moodle_client.sync_from_moodle_to_app() - return jsonify(res), 200 - except Exception as e: - return jsonify({'success': False, 'error': str(e), 'message': f"Error al sincronizar desde Moodle: {str(e)}"}), 500 - - -@api_admin_bp.route('/moodle/queue/stats', methods=['GET']) -@jwt_required -def get_moodle_queue_stats(): - """Retorna las estadísticas en tiempo real de la cola de sincronización con Moodle.""" - from app.services.moodle_queue_service import moodle_queue_service - stats = moodle_queue_service.get_queue_summary() - return jsonify({ - 'status': 'success', - 'data': stats - }), 200 - - -@api_admin_bp.route('/moodle/queue/tasks', methods=['GET']) -@jwt_required -def get_moodle_queue_tasks(): - """Retorna la lista de tareas en cola con filtros por estado (ej: FAILED para DLQ).""" - from app.models.sync_task import MoodleSyncTask - status = request.args.get('status', '').strip().upper() - page = int(request.args.get('page', 1)) - per_page = int(request.args.get('per_page', 20)) - - query = MoodleSyncTask.query - if status: - query = query.filter_by(status=status) - - total = query.count() - tasks = query.order_by(MoodleSyncTask.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all() - - return jsonify({ - 'status': 'success', - 'total': total, - 'page': page, - 'per_page': per_page, - 'tasks': [t.to_dict() for t in tasks] - }), 200 - - -@api_admin_bp.route('/moodle/queue/process-now', methods=['POST']) -@jwt_required -def process_moodle_queue_now(): - """Dispara de forma manual la ejecución inmediata de la cola de sincronización.""" - from app.services.moodle_queue_service import moodle_queue_service - batch_size = int(request.json.get('batch_size', 50)) if request.is_json and request.json else 50 - results = moodle_queue_service.process_pending_tasks(batch_size=batch_size) - return jsonify({ - 'status': 'success', - 'message': f"Sincronización procesada: {results['succeeded']} exitosas, {results['failed']} a DLQ, {results['retrying']} reintentando.", - 'results': results - }), 200 - - -@api_admin_bp.route('/moodle/queue/tasks//retry', methods=['POST']) -@jwt_required -def retry_moodle_queue_task(task_id): - """Reintenta manualmente una tarea específica desde la Dead Letter Queue.""" - from app.services.moodle_queue_service import moodle_queue_service - success = moodle_queue_service.retry_task(task_id) - if success: - return jsonify({ - 'status': 'success', - 'message': f'Tarea #{task_id} reiniciada a estado PENDIENTE para el próximo ciclo.' - }), 200 - else: - return jsonify({ - 'status': 'error', - 'message': f'No se encontró la tarea #{task_id}.' - }), 404 - - -@api_admin_bp.route('/moodle/queue/retry-all', methods=['POST']) -@jwt_required -def retry_all_failed_moodle_tasks(): - """Reintenta todas las tareas en Dead Letter Queue (FAILED).""" - from app.services.moodle_queue_service import moodle_queue_service - count = moodle_queue_service.retry_all_failed() - return jsonify({ - 'status': 'success', - 'message': f'Se reiniciaron {count} tareas fallidas a estado PENDIENTE.' - }), 200 - - -# --------------------------------------------------------- -# BUILDINGS CRUD -# --------------------------------------------------------- - -@api_admin_bp.route('/buildings', methods=['GET']) -@jwt_required -def get_buildings(): - from app.models.building import Building - from app.models.classroom import Classroom - - search = request.args.get('search', '').strip().lower() - status_filter = request.args.get('status', '').strip().lower() - - 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() - buildings_data = [b.to_dict() for b in buildings] - - # Estadísticas globales: Capacidad física real sin sumar 9999 de aulas virtuales - all_classrooms = Classroom.query.filter_by(is_active=True).all() - physical_classrooms = [c for c in all_classrooms 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) - - return jsonify({ - 'status': 'success', - 'total': len(buildings_data), - 'buildings': buildings_data, - 'stats': { - 'total_buildings': len(buildings), - 'total_classrooms': len(all_classrooms), - 'physical_classrooms_count': len(physical_classrooms), - 'total_physical_capacity': total_physical_capacity, - 'total_floors': sum(b.floors for b in buildings if not b.is_virtual) - } - }), 200 - - -@api_admin_bp.route('/buildings/', methods=['GET']) -@jwt_required -def get_building(id): - from app.models.building import Building - building = Building.query.get(id) - if not building: - return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404 - classrooms = Classroom.query.filter( - db.or_(Classroom.building_id == id, Classroom.building == building.name) - ).order_by(Classroom.floor.asc(), Classroom.code.asc()).all() - return jsonify({ - 'status': 'success', - 'building': building.to_dict(), - 'classrooms': [c.to_dict() for c in classrooms] - }), 200 - - -@api_admin_bp.route('/buildings', methods=['POST']) -@jwt_required -def create_building(): - from app.models.building import Building - data = request.get_json(silent=True) or request.form.to_dict() or {} - name = (data.get('name') or '').strip() - code = (data.get('code') or '').strip().upper() or None - address = (data.get('address') or '').strip() or None - floors = int(data.get('floors', 1) or 1) - description = (data.get('description') or '').strip() or None - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] - - if not name: - return jsonify({'error': 'ValidationError', 'message': 'El nombre del edificio es obligatorio.'}), 400 - - existing = Building.query.filter(db.func.lower(Building.name) == name.lower()).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe un edificio con el nombre "{name}".'}), 409 - - building = Building( - name=name, - code=code, - address=address, - floors=floors, - description=description, - is_active=bool(is_active) - ) - db.session.add(building) - db.session.commit() - - AuditService.log( - action='CREATE', - module='buildings', - entity_id=building.id, - user=g.jwt_user, - details=f"Nueva sede/edificio creado: '{building.name}' (Código: {building.code or 'S/C'}, Pisos: {building.floors})" - ) - - return jsonify({ - 'status': 'success', - 'message': f'Edificio "{name}" creado con éxito.', - 'building': building.to_dict() - }), 201 - - -@api_admin_bp.route('/buildings/', methods=['PUT', 'POST']) -@jwt_required -def update_building(id): - from app.models.building import Building - from app.models.classroom import Classroom - building = Building.query.get(id) - if not building: - return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - name = (data.get('name') or '').strip() - if not name: - return jsonify({'error': 'ValidationError', 'message': 'El nombre del edificio es obligatorio.'}), 400 - - existing = Building.query.filter( - db.func.lower(Building.name) == name.lower(), - Building.id != id - ).first() - if existing: - return jsonify({'error': 'Conflict', 'message': f'Ya existe otro edificio con el nombre "{name}".'}), 409 - - old_name = building.name - building.name = name - if 'code' in data: - building.code = (data.get('code') or '').strip().upper() or None - if 'address' in data: - building.address = (data.get('address') or '').strip() or None - if 'floors' in data: - building.floors = int(data.get('floors', 0) or 0) - if 'description' in data: - building.description = (data.get('description') or '').strip() or None - if 'is_active' in data: - is_active = data.get('is_active') - if isinstance(is_active, str): - building.is_active = is_active.lower() in ['true', '1', 'on'] - else: - building.is_active = bool(is_active) - building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) - - if old_name != name: - Classroom.query.filter_by(building_id=building.id).update({'building': name}) - - db.session.commit() - - AuditService.log( - action='UPDATE', - module='buildings', - entity_id=building.id, - user=g.jwt_user, - details=f"Edificio/sede #{building.id} ('{building.name}') actualizado. Pisos: {building.floors}, Código: {building.code}" - ) - - return jsonify({ - 'status': 'success', - 'message': f'Edificio "{building.name}" actualizado con éxito.', - 'building': building.to_dict() - }), 200 - - -@api_admin_bp.route('/buildings//toggle', methods=['POST']) -@jwt_required -def toggle_building(id): - from app.models.building import Building - building = Building.query.get(id) - if not building: - return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404 - - building.is_active = not building.is_active - building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) - db.session.commit() - - AuditService.log( - action='TOGGLE', - module='buildings', - entity_id=building.id, - user=g.jwt_user, - details=f"Edificio '{building.name}' {'activado' if building.is_active else 'desactivado'}" - ) - - return jsonify({ - 'status': 'success', - 'message': f'Edificio "{building.name}" {"activado" if building.is_active else "desactivado"} exitosamente.', - 'building': building.to_dict() - }), 200 - - -@api_admin_bp.route('/buildings/', methods=['DELETE']) -@jwt_required -def delete_building(id): - from app.models.building import Building - from app.models.classroom import Classroom - building = Building.query.get(id) - if not building: - return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404 - - count = Classroom.query.filter( - db.or_(Classroom.building_id == building.id, Classroom.building == building.name) - ).count() - if count > 0: - return jsonify({ - 'error': 'Conflict', - 'message': f'No se puede eliminar el edificio "{building.name}" porque tiene {count} aulas asociadas.' - }), 409 - - b_name = building.name - db.session.delete(building) - db.session.commit() - - AuditService.log( - action='DELETE', - module='buildings', - entity_id=id, - user=g.jwt_user, - details=f"Edificio/sede #{id} ('{b_name}') eliminado permanentemente" - ) - - return jsonify({ - 'status': 'success', - 'message': f'Edificio "{b_name}" eliminado correctamente.' - }), 200 - - -@api_admin_bp.route('/system/reset', methods=['POST']) -@api_admin_bp.route('/settings/reset_system', methods=['POST']) -@jwt_required -def reset_entire_system(): - """ - Reinicializa el sistema depurando historiales, reservas, espacios, sedes y académica. - PRESERVA: Todas las cuentas de usuario, roles RBAC, permisos, configuraciones globales - y tipos de hitos (pestaña Administración intacta). - REQUISITO CRÍTICO DE SEGURIDAD: Debe solicitar y validar la contraseña del perfil administrador en sesión. - """ - from app.models.grade import MilestoneGrade - from app.models.enrollment import StudentEnrollment - from app.models.classroom import ClassroomResource - from app.models.building import Building - from app.models.sync_task import MoodleSyncTask - - acting_user = getattr(g, 'jwt_user', None) - if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')): - return jsonify({ - 'status': 'error', - 'error': 'Forbidden', - 'message': 'Acceso denegado. Solo un usuario con perfil Administrador puede solicitar la reinicialización del sistema.' - }), 403 - - data = request.get_json(silent=True) or request.form.to_dict() or {} - password = str(data.get('password') or '').strip() - - if not password: - return jsonify({ - 'status': 'error', - 'error': 'BadRequest', - 'message': 'Debe ingresar la contraseña de su usuario administrador para autorizar la reinicialización.' - }), 400 - - if not acting_user.check_password(password): - # Registrar intento fallido de reinicio en bitácora de auditoría - try: - failed_audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='SYSTEM_RESET_FAILED', - module='admin', - details='Intento de reinicialización del sistema cancelado: contraseña incorrecta.', - ip_address=request.remote_addr - ) - db.session.add(failed_audit) - db.session.commit() - except Exception: - pass - - return jsonify({ - 'status': 'error', - 'error': 'Unauthorized', - 'message': 'Contraseña de administrador incorrecta. Operación cancelada por seguridad.' - }), 401 - - try: - # Purga referencial ordenada de entidades operativas - # 1. Reservas - reservations_deleted = Reservation.query.delete() - - # 2. Calificaciones e Hitos de cursadas - grades_deleted = MilestoneGrade.query.delete() - milestones_deleted = AcademicMilestone.query.delete() - - # 3. Matrículas de alumnos y asignaciones docentes a comisiones - enrollments_deleted = StudentEnrollment.query.delete() - teachers_deleted = CommissionTeacher.query.delete() - - # 4. Comisiones, Materias y Carreras - commissions_deleted = Commission.query.delete() - subjects_deleted = Subject.query.delete() - careers_deleted = Career.query.delete() - - # 5. Recursos de aula, Aulas y Edificios/Sedes - resources_deleted = ClassroomResource.query.delete() - classrooms_deleted = Classroom.query.delete() - buildings_deleted = Building.query.delete() - - # 6. Ciclos Lectivos / Términos Académicos - terms_deleted = AcademicTerm.query.delete() - - # 7. Cola de eventos de sincronización Moodle huérfanos - moodle_tasks_deleted = MoodleSyncTask.query.delete() - - # 8. Historiales: Limpiar auditorías anteriores - logs_deleted = AuditLog.query.delete() - - # 9. Asentar registro oficial inmutable del reinicio en AuditLog - reset_audit = AuditLog( - user_id=acting_user.id, - user_email=acting_user.email, - action='SYSTEM_RESET', - module='admin', - details=( - f"Reinicialización total ejecutada por administrador {acting_user.email}. " - f"Entidades purgadas: {reservations_deleted} reservas, {classrooms_deleted} aulas, " - f"{buildings_deleted} sedes, {commissions_deleted} comisiones, {subjects_deleted} materias, " - f"{careers_deleted} carreras, {terms_deleted} ciclos lectivos, {enrollments_deleted} inscripciones, " - f"{grades_deleted} notas, {logs_deleted} logs históricos. Cuentas y configuración administrativa preservadas." - ), - ip_address=request.remote_addr - ) - db.session.add(reset_audit) - db.session.commit() - - return jsonify({ - 'status': 'success', - 'message': 'Sistema reinicializado correctamente. Se han depurado los historiales, reservas, espacios, sedes y académica. Las cuentas de usuario y configuraciones se encuentran intactas.', - 'purged_stats': { - 'reservations': reservations_deleted, - 'classrooms': classrooms_deleted, - 'buildings': buildings_deleted, - 'commissions': commissions_deleted, - 'subjects': subjects_deleted, - 'careers': careers_deleted, - 'academic_terms': terms_deleted, - 'enrollments': enrollments_deleted, - 'grades': grades_deleted, - 'prior_audit_logs': logs_deleted - } - }), 200 - - except Exception as e: - db.session.rollback() - return jsonify({ - 'status': 'error', - 'error': 'InternalServerError', - 'message': f'Error durante la reinicialización de la base de datos: {str(e)}' - }), 500 - - -# --------------------------------------------------------- -# REGISTRO DE AUDITORÍA INSTITUCIONAL RESTful -# --------------------------------------------------------- - -@api_admin_bp.route('/audit-logs', methods=['GET']) -@api_admin_bp.route('/audit_logs', methods=['GET']) -@jwt_required -def get_audit_logs(): - """ - Endpoint RESTful para consultar la bitácora inmutable de auditoría institucional. - Soporta paginación, búsqueda multi-campo y filtrado por módulo y acción. - """ - page = request.args.get('page', 1, type=int) - per_page = min(request.args.get('per_page', 20, type=int), 100) - module_filter = request.args.get('module', '').strip().lower() - action_filter = request.args.get('action', '').strip().upper() - search = request.args.get('search', '').strip() - - query = AuditLog.query - - if module_filter: - query = query.filter(AuditLog.module == module_filter) - if action_filter: - query = query.filter(AuditLog.action == action_filter) - if search: - query = query.filter( - or_( - AuditLog.user_email.ilike(f'%{search}%'), - AuditLog.details.ilike(f'%{search}%'), - AuditLog.ip_address.ilike(f'%{search}%'), - AuditLog.action.ilike(f'%{search}%'), - AuditLog.module.ilike(f'%{search}%') - ) - ) - - pagination = query.order_by(AuditLog.created_at.desc()).paginate( - page=page, per_page=per_page, error_out=False - ) - - modules_tuples = db.session.query(AuditLog.module).distinct().all() - actions_tuples = db.session.query(AuditLog.action).distinct().all() - - modules = sorted(list(set([r[0].lower() for r in modules_tuples if r[0]]))) - actions = sorted(list(set([r[0].upper() for r in actions_tuples if r[0]]))) - - default_modules = ['auth', 'reservations', 'classrooms', 'buildings', 'academic', 'optimizer', 'users', 'admin', 'system', 'import'] - for m in default_modules: - if m not in modules: - modules.append(m) - - default_actions = [ - 'LOGIN', 'LOGIN_FAILED', 'LOGIN_BLOCKED', 'LOGIN_GOOGLE', 'LOGIN_MOODLE', 'LOGOUT', - 'PASSWORD_CHANGE', 'IMPERSONATE_START', 'IMPERSONATE_END', - 'CREATE', 'UPDATE', 'DELETE', 'CONFIRM', 'CANCEL', 'TOGGLE', - 'OPTIMIZE_RUN', 'OPTIMIZE_APPLY', 'SYSTEM_RESET', 'SYSTEM_ERROR', - 'SHEETS_IMPORT', 'SHEETS_IMPORT_ERROR' - ] - for a in default_actions: - if a not in actions: - actions.append(a) - - return jsonify({ - 'status': 'success', - 'logs': [log.to_dict() for log in pagination.items], - 'pagination': { - 'page': pagination.page, - 'per_page': pagination.per_page, - 'total': pagination.total, - 'pages': pagination.pages or 1, - 'has_prev': pagination.has_prev, - 'has_next': pagination.has_next - }, - 'modules': sorted(modules), - 'actions': sorted(actions), - 'current_module': module_filter, - 'current_action': action_filter, - 'search': search - }), 200 - - -@api_admin_bp.route('/log-error', methods=['POST']) -def log_system_error(): - """ - Endpoint para registrar incidentes técnicos o errores no controlados - provenientes del frontend BFF o subsistemas en AuditLog. - """ - try: - data = request.get_json(silent=True) or {} - incident_id = data.get('incident_id') - error_title = data.get('error_title', 'Error de Sistema') - error_message = data.get('error_message', 'Error desconocido') - status_code = data.get('status_code', 500) - path = data.get('path', '') - user_email = data.get('user_email') or 'anonymous' - ip_address = data.get('ip_address') or request.remote_addr - stack = data.get('stack', '') - - details = { - 'incident_id': incident_id, - 'title': error_title, - 'message': error_message, - 'status_code': status_code, - 'path': path, - 'stack_preview': stack[:500] if stack else '' - } - - AuditService.log( - action='SYSTEM_ERROR', - module='system', - user_email=user_email, - ip_address=ip_address, - details=details, - status='failed' - ) - - return jsonify({ - 'status': 'success', - 'logged': True, - 'incident_id': incident_id - }), 200 - except Exception as e: - return jsonify({ - 'status': 'error', - 'message': str(e) - }), 500 - - - diff --git a/backend/app/routes/api/auth.py b/backend/app/routes/api/auth.py deleted file mode 100644 index 3619525..0000000 --- a/backend/app/routes/api/auth.py +++ /dev/null @@ -1,512 +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.services.audit_service import AuditService -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 = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') - google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1') - moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1') - google_client_id = str(SystemSetting.get_value('google_client_id', '') or '') - demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or '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 = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') - - user = user_service.authenticate(dto.email, dto.password) - if not user: - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user_email=dto.email, - details=f"Intento de inicio de sesión fallido para {dto.email}. Credenciales incorrectas o cuenta inactiva." - ) - 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: - AuditService.log( - action='LOGIN_BLOCKED', - module='auth', - user=user, - entity_id=user.id, - details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración." - ) - 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 - - AuditService.log( - action='LOGIN', - module='auth', - user=user, - entity_id=user.id, - details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}" - ) - - 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 = str(SystemSetting.get_value('auth_google_enabled', 'false') or '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 = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or '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}") - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user_email=email, - details=f"Acceso Google OAuth denegado: dominio @{domain} no autorizado para {email}." - ) - 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: - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user=user, - entity_id=user.id, - details=f"Acceso Google OAuth denegado: cuenta institucional desactivada para {email}." - ) - return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta se encuentra inactiva. Contacte a Bedelía.'}), 401 - - AuditService.log( - action='LOGIN_GOOGLE', - module='auth', - user=user, - entity_id=user.id, - details=f"Inicio de sesión exitoso (Google OAuth SSO) - Rol: {user.role}" - ) - - 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 = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or '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 = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/') - service_name = SystemSetting.get_value('moodle_service_name', 'moodle_api') - - # 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': service_name - }, timeout=10) - res_data = resp.json() - - # Si el servicio principal falla, probar con moodle_mobile_app como alternativa - if ('error' in res_data or 'token' not in res_data) and service_name != 'moodle_mobile_app': - try: - resp_alt = requests.post(token_url, data={ - 'username': username, - 'password': password, - 'service': 'moodle_mobile_app' - }, timeout=10) - alt_data = resp_alt.json() - if 'token' in alt_data: - res_data = alt_data - except Exception: - pass - 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.') - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user_email=f"{username}@unicaba.edu.ar", - details=f"Intento de autenticación Moodle fallido para '{username}': {err_msg}" - ) - 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: match by email, institutional email prefix or document_number (DNI) - user = User.query.filter( - (User.email.ilike(email)) | - (User.email.ilike(f"{username}@%")) | - (User.document_number == 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, - document_type='DNI' if username.isdigit() else 'DNI', - document_number=username if username.isdigit() else None, - 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: - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user=user, - entity_id=user.id, - details=f"Inicio de sesión Moodle denegado: cuenta institucional desactivada para {username}." - ) - return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta en Edu-Space está desactivada.'}), 401 - - AuditService.log( - action='LOGIN_MOODLE', - module='auth', - user=user, - entity_id=user.id, - details=f"Inicio de sesión exitoso (Moodle Delegado) - Usuario: {username}, Rol: {user.role}" - ) - - 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') - sub = payload.get('sub') - if sub is None: - return jsonify({'error': 'Unauthorized', 'message': 'Token payload inválido.'}), 401 - user_id = int(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. - """ - if g.jwt_user: - AuditService.log( - action='LOGOUT', - module='auth', - user=g.jwt_user, - entity_id=g.jwt_user.id, - details=f"Cierre de sesión seguro de {g.jwt_user.email}" - ) - 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): - AuditService.log( - action='PASSWORD_FAILED', - module='auth', - user=user, - entity_id=user.id, - details="Intento fallido de cambio de contraseña: la contraseña actual no coincide." - ) - return jsonify({ - 'error': 'Unauthorized', - 'message': 'La contraseña actual ingresada es incorrecta.' - }), 401 - - user.set_password(new_password) - db.session.commit() - - AuditService.log( - action='PASSWORD_CHANGE', - module='auth', - user=user, - entity_id=user.id, - details="Cambio de contraseña institucional completado exitosamente." - ) - - 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 - diff --git a/backend/app/routes/api/classrooms.py b/backend/app/routes/api/classrooms.py deleted file mode 100644 index 38e940d..0000000 --- a/backend/app/routes/api/classrooms.py +++ /dev/null @@ -1,164 +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.services.audit_service import AuditService -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('/', 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) - AuditService.log( - action='CREATE', - module='classrooms', - entity_id=classroom.id, - user=g.jwt_user, - details=f"Nueva aula creada: {classroom.code} en {classroom.building} (Piso {classroom.floor}, Capacidad: {classroom.capacity})" - ) - 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('/', 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) - AuditService.log( - action='UPDATE', - module='classrooms', - entity_id=classroom.id, - user=g.jwt_user, - details=f"Aula #{classroom.id} ({classroom.code}) actualizada. Capacidad: {classroom.capacity}, Piso: {classroom.floor}" - ) - 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('/', 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 - - AuditService.log( - action='DELETE', - module='classrooms', - entity_id=classroom_id, - user=g.jwt_user, - details=f"Aula #{classroom_id} eliminada/desactivada del sistema" - ) - return jsonify({'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'}), 200 - -@api_classrooms_bp.route('//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() - AuditService.log( - action='TOGGLE', - module='classrooms', - entity_id=classroom.id, - user=g.jwt_user, - details=f"Aula {classroom.code} {'activada' if classroom.is_active else 'desactivada'}" - ) - return jsonify({ - 'status': 'success', - 'id': classroom.id, - 'is_active': classroom.is_active, - 'message': f'Aula {"activada" if classroom.is_active else "desactivada"} correctamente.' - }), 200 diff --git a/backend/app/routes/api/dashboard.py b/backend/app/routes/api/dashboard.py deleted file mode 100644 index de9a327..0000000 --- a/backend/app/routes/api/dashboard.py +++ /dev/null @@ -1,782 +0,0 @@ -from flask import Blueprint, jsonify, request, g -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 app.services.audit_service import AuditService -from datetime import datetime, timedelta, timezone -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.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 = [] - my_today_count = 0 - my_total_reservations = 0 - my_today_classes = [] - tomorrow_schedule_list = [] - filter_stats = {} - date_labels = {} - unassigned_commissions_tomorrow = [] - unassigned_commissions_week = [] - unassigned_commissions_month = [] - unassigned_commissions_general = [] - available_classrooms_today = [] - available_classrooms_tomorrow = [] - available_classrooms_week = [] - available_classrooms_month = [] - virtual_rooms_data = [] - audit_data = [] - pending_reservations = [] - today_schedule_list = [] - week_schedule_list = [] - upcoming_reservations = [] - milestones = [] - - 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(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] - - jwt_user = getattr(g, 'jwt_user', None) - user_id = getattr(jwt_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 = [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 ---- - import calendar - 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) - - # Etiquetas legibles de fecha en español - 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}" - } - - # Reservas por período - 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 = [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 = [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 = {} - for r in today_reservations_q: - if r.classroom_id: - res_map_classroom_today.setdefault(r.classroom_id, []).append(r) - - res_map_classroom_tomorrow = {} - for r in tomorrow_reservations_q: - if r.classroom_id: - res_map_classroom_tomorrow.setdefault(r.classroom_id, []).append(r) - - res_map_classroom_week = {} - for r in week_reservations_q: - if r.classroom_id: - res_map_classroom_week.setdefault(r.classroom_id, []).append(r) - - res_map_classroom_month = {} - for r in month_reservations_q: - if r.classroom_id: - res_map_classroom_month.setdefault(r.classroom_id, []).append(r) - - # Mapas de reservas por comisión en cada período - res_map_comm_today = {} - for r in today_reservations_q: - if r.commission_id: - res_map_comm_today.setdefault(r.commission_id, []).append(r) - - res_map_comm_tomorrow = {} - for r in tomorrow_reservations_q: - if r.commission_id: - res_map_comm_tomorrow.setdefault(r.commission_id, []).append(r) - - res_map_comm_week = {} - for r in week_reservations_q: - if r.commission_id: - res_map_comm_week.setdefault(r.commission_id, []).append(r) - - res_map_comm_month = {} - for r in month_reservations_q: - if r.commission_id: - res_map_comm_month.setdefault(r.commission_id, []).append(r) - - all_active_commissions = Commission.query.filter_by(active=True).all() - total_active_commissions = len(all_active_commissions) - - # Helper para serializar aula con info contextual - def build_classroom_item(c, res_list): - 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 - } - - # Helper para serializar comisión con info contextual - def build_comm_item(comm, res_list): - 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" - 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 '', - '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 - } - - # Construcción de Aulas Asignadas vs Sin Asignar para cada período (sobre aulas físicas) - # 1. Hoy - 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] - # 2. Mañana - 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] - # 3. Semana - 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] - # 4. Mes - 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] - - # Construcción de Comisiones Asignadas vs Sin Asignar para cada período - # 1. Hoy - 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] - # 2. Mañana - 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] - # 3. Semana - 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] - # 4. Mes - 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] - - # Identificar comisiones en modalidad virtual (por enlace Meet/Teams/Zoom o asignadas a Campus Virtual) - 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) - - 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, []) - 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, - '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 ∞', - 'today_classes': len(res_today), - 'tomorrow_classes': len(res_tomorrow), - 'week_classes': len(res_week), - 'month_classes': len(res_month), - 'res_count': len(res_month), - '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'})" - }) - - # Las salas virtuales disponibles corresponden a las salas de comisiones virtuales activas o catálogo virtual - if virtual_rooms_data: - virtual_classrooms = len(virtual_rooms_data) - - # Comisiones huérfanas generales (sin ninguna reserva histórica ni link virtual) - 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 and comm.virtual_link.strip()) - ] - - # Compatibilidad hacia atrás para vistas existentes - 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 - - # Diccionario unificado filter_stats - filter_stats = { - 'date_labels': date_labels, - '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': round((len(classrooms_assigned_today) / max(1, total_physical_count)) * 100, 1), - 'unassigned_pct': round((len(classrooms_unassigned_today) / max(1, total_physical_count)) * 100, 1), - '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: {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 = [] - week_schedule_list = [] - upcoming_reservations = [] - unassigned_commissions_week = [] - unassigned_commissions_month = [] - unassigned_commissions_general = [] - available_classrooms_today = [] - 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, - '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, - '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) - } - }), 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 con soporte de filtros y entidades.""" - from app.services.sheets_importer import GoogleSheetsImporter - filter_career = None - filter_subject = None - filter_day = None - try: - data = request.get_json(silent=True) or {} - custom_url = data.get('sheets_url') or data.get('base_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') - single_date_only = bool(data.get('single_date_only', False)) - - # Opciones granulares de entidades - 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') - - 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, - import_careers=import_careers, - import_subjects=import_subjects, - import_commissions=import_commissions, - import_classrooms=import_classrooms, - import_reservations=import_reservations, - selected_rows=selected_rows - ) - - user_info = getattr(g, 'current_user', {}) or {} - user_email = user_info.get('email') if isinstance(user_info, dict) else getattr(user_info, 'email', None) - AuditService.log( - action='SHEETS_IMPORT', - module='import', - user_email=user_email, - ip_address=request.remote_addr, - 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 - }, - status='success' - ) - - return jsonify({ - 'status': 'success', - 'stats': stats, - 'source_url': importer.base_url - }), 200 - except Exception as e: - user_info = getattr(g, 'current_user', {}) or {} - user_email = user_info.get('email') if isinstance(user_info, dict) else getattr(user_info, 'email', None) - AuditService.log( - action='SHEETS_IMPORT_ERROR', - module='import', - user_email=user_email, - ip_address=request.remote_addr, - details={ - 'error': str(e), - 'filter_career': filter_career, - 'filter_subject': filter_subject, - 'filter_day': filter_day - }, - status='failed' - ) - return jsonify({ - 'status': 'error', - 'message': str(e) - }), 500 - -@api_dashboard_bp.route('/sheets-inspect', methods=['GET', 'POST']) -@jwt_required -def inspect_google_sheets(): - """Devuelve metadatos, carreras, materias y previsualización de registros según los filtros aplicados.""" - from app.services.sheets_importer import GoogleSheetsImporter - try: - data = request.get_json(silent=True) or {} - custom_url = data.get('sheets_url') or request.args.get('sheets_url') - filter_career = data.get('filter_career') or request.args.get('filter_career') - filter_subject = data.get('filter_subject') or request.args.get('filter_subject') - filter_day = data.get('filter_day') or request.args.get('filter_day') - filter_days = data.get('filter_days') or request.args.get('filter_days') - manual_date = data.get('manual_date') or request.args.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 jsonify({ - 'status': 'success', - 'metadata': metadata, - 'source_url': importer.base_url - }), 200 - except Exception as e: - return jsonify({ - 'status': 'error', - 'message': str(e) - }), 500 - diff --git a/backend/app/routes/api/openapi.py b/backend/app/routes/api/openapi.py deleted file mode 100644 index 8e1bcd6..0000000 --- a/backend/app/routes/api/openapi.py +++ /dev/null @@ -1,261 +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": "3.7.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) - -from app import __version__ - -@api_openapi_bp.route('/version', methods=['GET']) -def get_api_version(): - """Returns the backend API version information.""" - return jsonify({ - "name": "Edu-Space REST API", - "version": __version__, - "status": "healthy" - }), 200 - -@api_openapi_bp.route('/health', methods=['GET']) -def get_api_health(): - """Liveness probe for backend API.""" - return jsonify({ - "status": "ok", - "version": __version__ - }), 200 diff --git a/backend/app/routes/api/optimizer.py b/backend/app/routes/api/optimizer.py deleted file mode 100644 index 359d6c8..0000000 --- a/backend/app/routes/api/optimizer.py +++ /dev/null @@ -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/', 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 diff --git a/backend/app/routes/api/reservations.py b/backend/app/routes/api/reservations.py deleted file mode 100644 index cc41919..0000000 --- a/backend/app/routes/api/reservations.py +++ /dev/null @@ -1,367 +0,0 @@ -from flask import Blueprint, request, jsonify, g -from datetime import datetime, timedelta, date, timezone -from pydantic import ValidationError - -from app import db -from app.models.reservation import Reservation -from app.services.reservation_service import ReservationService -from app.services.audit_service import AuditService -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.now(timezone.utc).replace(tzinfo=None) - 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 or '').strip().lower() != 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, - 'career_name': r.commission.career_name if (r.commission and hasattr(r.commission, 'career_name')) else '', - 'career_names': r.commission.career_names if (r.commission and hasattr(r.commission, 'career_names')) else '', - 'commission_code': r.commission.code if r.commission else '', - '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('/', 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) - AuditService.log( - action='CREATE', - module='reservations', - entity_id=reservation.id, - user=g.jwt_user, - details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}" - ) - 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('/', 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) - AuditService.log( - action='UPDATE', - module='reservations', - entity_id=reservation.id, - user=g.jwt_user, - details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}" - ) - 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('/', 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() - AuditService.log( - action='DELETE', - module='reservations', - entity_id=reservation_id, - user=g.jwt_user, - details=f"Reserva #{reservation_id} eliminada permanentemente" - ) - 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 - - AuditService.log( - action='CANCEL', - module='reservations', - entity_id=reservation_id, - user=g.jwt_user, - details=f"Reserva #{reservation_id} cancelada" - ) - return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200 - -@api_reservations_bp.route('//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() - AuditService.log( - action='DELETE', - module='reservations', - entity_id=reservation_id, - user=g.jwt_user, - details=f"Reserva #{reservation_id} eliminada permanentemente" - ) - return jsonify({'message': f'Reserva {reservation_id} eliminada permanentemente.'}), 200 - -@api_reservations_bp.route('//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 - - AuditService.log( - action='CANCEL', - module='reservations', - entity_id=reservation_id, - user=g.jwt_user, - details=f"Reserva #{reservation_id} cancelada" - ) - return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200 - -@api_reservations_bp.route('//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 - - AuditService.log( - action='CONFIRM', - module='reservations', - entity_id=reservation_id, - user=g.jwt_user, - details=f"Reserva #{reservation_id} confirmada oficialmente" - ) - 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 - - diff --git a/backend/app/routes/api/students.py b/backend/app/routes/api/students.py deleted file mode 100644 index 58f76a7..0000000 --- a/backend/app/routes/api/students.py +++ /dev/null @@ -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 diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py deleted file mode 100644 index 89177b5..0000000 --- a/backend/app/routes/auth.py +++ /dev/null @@ -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') or '' - new_password = request.form.get('new_password') or '' - confirm_password = request.form.get('confirm_password') or '' - - 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') \ No newline at end of file diff --git a/backend/app/routes/buildings.py b/backend/app/routes/buildings.py deleted file mode 100644 index e222c4d..0000000 --- a/backend/app/routes/buildings.py +++ /dev/null @@ -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, timezone - -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('/') -@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('//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.now(timezone.utc).replace(tzinfo=None) - - # 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('//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.now(timezone.utc).replace(tzinfo=None) - 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('//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')) diff --git a/backend/app/routes/classrooms.py b/backend/app/routes/classrooms.py deleted file mode 100644 index 97d775c..0000000 --- a/backend/app/routes/classrooms.py +++ /dev/null @@ -1,514 +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, timezone, timedelta -import calendar -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 building_filter == str(virtual_bldg_id): - view_mode = 'virtual' - elif not view_mode: - view_mode = 'physical' - - # Fechas operativas (Día, Semana, Mes) - today = datetime.now(timezone.utc).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 building_filter != str(virtual_bldg_id): - physical_query = physical_query.filter(Classroom.building_id == int(building_filter)) - - if floor_filter: - flr = 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, 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, 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, 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//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('/') -@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.now(timezone.utc).replace(tzinfo=None), - 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('//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.now(timezone.utc).replace(tzinfo=None) - - 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('//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.now(timezone.utc).replace(tzinfo=None) - 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 \ No newline at end of file diff --git a/backend/app/routes/genetic_algorithm.py b/backend/app/routes/genetic_algorithm.py deleted file mode 100644 index eeb8d42..0000000 --- a/backend/app/routes/genetic_algorithm.py +++ /dev/null @@ -1,299 +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.services.audit_service import AuditService -from app.utils.jwt_decorators import jwt_required - -genetic_bp = Blueprint('genetic_algorithm', __name__, url_prefix='/api/genetic') - - -def check_optimizer_permission(user, requires_write=False): - """ - Verifica si el usuario tiene permiso para consultar o ejecutar el optimizador de reservas. - Permitido para Administradores, Bedelía, Docentes o usuarios con permisos RBAC en 'optimizer'. - """ - if not user: - return False - - # 1. Administrador (método o rol) - if hasattr(user, 'is_admin') and user.is_admin(): - return True - - role = (getattr(user, 'role', '') or '').strip().lower() - if role in ['admin', 'administrador', 'bedelia']: - return True - if role in ['docente', 'teacher']: - return True - - # 2. RBAC granular - if hasattr(user, 'has_permission'): - if requires_write: - return user.has_permission('optimizer', 'read_write') - return user.has_permission('optimizer', 'read') or user.has_permission('optimizer', 'read_write') - - return False - - -@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, bedelia, teacher or RBAC optimizer write) - if not check_optimizer_permission(g.jwt_user, requires_write=True): - 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 - ) - - AuditService.log( - action='OPTIMIZE_RUN', - module='optimizer', - user=g.jwt_user, - details=f"Ejecución de algoritmo genético para {len(commission_ids)} comisiones. Fitness: {result.get('fitness_score', 0)}% (Asignadas: {len(result.get('assigned_reservations', []))})" - ) - - 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 check_optimizer_permission(g.jwt_user, requires_write=True): - return jsonify({'error': 'Insufficient permissions to apply reservations'}), 403 - - # Initialize optimizer and apply reservations - optimizer = ReservationOptimizer() - applied_reservations = optimizer.apply_optimized_reservations(reservations_data) - - AuditService.log( - action='OPTIMIZE_APPLY', - module='optimizer', - user=g.jwt_user, - details=f"Consolidación de optimizador genético: {len(applied_reservations)} reservas aplicadas en base de datos." - ) - - 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 not check_optimizer_permission(g.jwt_user, requires_write=False): - 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 not check_optimizer_permission(g.jwt_user, requires_write=False): - 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() - commission_dict['subject_name'] = commission.subject.name if commission.subject else 'Sin Asignatura' - commission_dict['subject_code'] = commission.subject.code if commission.subject else '' - 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 not check_optimizer_permission(g.jwt_user, requires_write=False): - 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 check_optimizer_permission(g.jwt_user, requires_write=False): - return render_template('auth/403.html'), 403 - - return render_template('genetic_optimizer.html') \ No newline at end of file diff --git a/backend/app/routes/main.py b/backend/app/routes/main.py deleted file mode 100644 index 566bfe3..0000000 --- a/backend/app/routes/main.py +++ /dev/null @@ -1,335 +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, timezone -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.now(timezone.utc).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: - now_dt = datetime.now(timezone.utc).replace(tzinfo=None) - upcoming_reservations = Reservation.query.filter( - Reservation.start_time >= now_dt, - Reservation.start_time <= now_dt + 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.now(timezone.utc).replace(tzinfo=None) - ).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.now(timezone.utc).replace(tzinfo=None), - 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: - now_dt = datetime.now(timezone.utc).replace(tzinfo=None) - upcoming_reservations = Reservation.query.filter( - Reservation.start_time >= now_dt, - Reservation.start_time <= now_dt + 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.now(timezone.utc).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.now(timezone.utc).replace(tzinfo=None) - 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/') -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]) \ No newline at end of file diff --git a/backend/app/routes/my_subjects.py b/backend/app/routes/my_subjects.py deleted file mode 100644 index 7f40f38..0000000 --- a/backend/app/routes/my_subjects.py +++ /dev/null @@ -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('/') -@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, timezone - - # Recent or upcoming reservation linked to this commission - recent_reservation = ( - Reservation.query - .filter( - Reservation.commission_id == commission_id, - Reservation.start_time >= datetime.now(timezone.utc).replace(tzinfo=None) - ) - .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 - ) diff --git a/backend/app/routes/schedule.py b/backend/app/routes/schedule.py deleted file mode 100644 index f52ee57..0000000 --- a/backend/app/routes/schedule.py +++ /dev/null @@ -1,977 +0,0 @@ -from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify -from flask_login import login_required, current_user -from flask_babel import gettext as _ -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, timezone -from typing import Dict, Any -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.now(timezone.utc).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(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 = 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/', 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//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//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//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//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//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//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//milestones//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(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 = 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//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: Dict[str, Any] = { - '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) - ).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_id.in_(db.session.query(Building.id).filter(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 = 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) - ).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 \ No newline at end of file diff --git a/backend/app/security/__init__.py b/backend/app/security/__init__.py deleted file mode 100644 index 30d3e38..0000000 --- a/backend/app/security/__init__.py +++ /dev/null @@ -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' -] diff --git a/backend/app/security/decorators.py b/backend/app/security/decorators.py deleted file mode 100644 index 00278a9..0000000 --- a/backend/app/security/decorators.py +++ /dev/null @@ -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 diff --git a/backend/app/security/filter_chain.py b/backend/app/security/filter_chain.py deleted file mode 100644 index 6388a7a..0000000 --- a/backend/app/security/filter_chain.py +++ /dev/null @@ -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 diff --git a/backend/app/services/audit_service.py b/backend/app/services/audit_service.py index 0612e71..b1c3053 100644 --- a/backend/app/services/audit_service.py +++ b/backend/app/services/audit_service.py @@ -1,6 +1,4 @@ from typing import Optional, List, Dict, Any -from flask import request, g, has_request_context -from flask_login import current_user import json from app import db from app.models.audit_log import AuditLog @@ -18,8 +16,7 @@ class AuditService: status: Optional[str] = None, **kwargs) -> 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. """ if status: if isinstance(details, dict): @@ -28,25 +25,15 @@ class AuditService: details = f"[{status.upper()}] {details}" else: details = {'status': status} + # 1. Determinar usuario actuante if user: user_id = user.id user_email = user.email - elif not user_id and not user_email and 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 - # 2. Determinar IP de origen - if not ip_address and has_request_context(): - xfwd = request.headers.get('X-Forwarded-For') - if xfwd: - ip_address = xfwd.split(',')[0].strip() - else: - ip_address = request.remote_addr + # 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 @@ -59,27 +46,40 @@ 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_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) diff --git a/backend/app/services/crypto_service.py b/backend/app/services/crypto_service.py index 8133265..e9a81f7 100644 --- a/backend/app/services/crypto_service.py +++ b/backend/app/services/crypto_service.py @@ -1,7 +1,7 @@ import base64 import hashlib from cryptography.fernet import Fernet -from flask import current_app +from config.config import Config class CryptoService: """ @@ -11,11 +11,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()) @@ -44,3 +41,4 @@ class CryptoService: return cipher_text crypto_service = CryptoService() + diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py new file mode 100644 index 0000000..61e12d4 --- /dev/null +++ b/backend/app/services/dashboard_service.py @@ -0,0 +1,707 @@ +""" +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.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(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 = [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: + if r.classroom_id: + res_map_classroom_today.setdefault(r.classroom_id, []).append(r) + + res_map_classroom_tomorrow: Dict[int, List[Reservation]] = {} + for r in tomorrow_reservations_q: + if r.classroom_id: + res_map_classroom_tomorrow.setdefault(r.classroom_id, []).append(r) + + res_map_classroom_week: Dict[int, List[Reservation]] = {} + for r in week_reservations_q: + if r.classroom_id: + res_map_classroom_week.setdefault(r.classroom_id, []).append(r) + + res_map_classroom_month: Dict[int, List[Reservation]] = {} + for r in month_reservations_q: + if r.classroom_id: + res_map_classroom_month.setdefault(r.classroom_id, []).append(r) + + res_map_comm_today: Dict[int, List[Reservation]] = {} + for r in today_reservations_q: + if r.commission_id: + res_map_comm_today.setdefault(r.commission_id, []).append(r) + + res_map_comm_tomorrow: Dict[int, List[Reservation]] = {} + for r in tomorrow_reservations_q: + if r.commission_id: + res_map_comm_tomorrow.setdefault(r.commission_id, []).append(r) + + res_map_comm_week: Dict[int, List[Reservation]] = {} + for r in week_reservations_q: + if r.commission_id: + res_map_comm_week.setdefault(r.commission_id, []).append(r) + + res_map_comm_month: Dict[int, List[Reservation]] = {} + for r in month_reservations_q: + if r.commission_id: + res_map_comm_month.setdefault(r.commission_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" + 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 '', + '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) + + 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, []) + 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, + '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 ∞', + 'today_classes': len(res_today), + 'tomorrow_classes': len(res_tomorrow), + 'week_classes': len(res_week), + 'month_classes': len(res_month), + 'res_count': len(res_month), + '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'})" + }) + + 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, + '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)) + 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, + 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 + }, + 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 + } diff --git a/backend/app/services/jwt_service.py b/backend/app/services/jwt_service.py index aa1a949..10cc09b 100644 --- a/backend/app/services/jwt_service.py +++ b/backend/app/services/jwt_service.py @@ -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,14 +25,7 @@ class JWTService: @classmethod def _get_secret(cls) -> str: - """Obtiene la clave secreta desde la configuración de Flask o Config directo.""" - try: - from flask import current_app - if current_app: - return current_app.config.get('SECRET_KEY', 'default-edu-space-secret-key') - except Exception: - pass - from config.config import Config + """Obtiene la clave secreta desde Config.""" return getattr(Config, 'SECRET_KEY', 'default-edu-space-secret-key') @classmethod diff --git a/backend/app/services/optimizer_service.py b/backend/app/services/optimizer_service.py index 8bb51a1..38a8ceb 100644 --- a/backend/app/services/optimizer_service.py +++ b/backend/app/services/optimizer_service.py @@ -4,7 +4,6 @@ import threading 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, diff --git a/backend/app/utils/decorators.py b/backend/app/utils/decorators.py deleted file mode 100644 index 21993ff..0000000 --- a/backend/app/utils/decorators.py +++ /dev/null @@ -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 - diff --git a/backend/app/utils/jwt_decorators.py b/backend/app/utils/jwt_decorators.py deleted file mode 100644 index afc4dcb..0000000 --- a/backend/app/utils/jwt_decorators.py +++ /dev/null @@ -1,118 +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') - sub = payload.get('sub') - if not sub: - return jsonify({ - 'error': 'Unauthorized', - 'message': 'Token inválido: falta identificador de usuario.' - }), 401 - user_id = int(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 diff --git a/backend/database.py b/backend/database.py index fcd2213..5abd64b 100644 --- a/backend/database.py +++ b/backend/database.py @@ -1,20 +1,144 @@ """ -Database & Persistence Management for FastAPI (Capa 4) -Integrates SQLAlchemy Engine, SessionLocal and get_db dependency. +Database & Persistence Management for FastAPI (Capa 4 - SQLAlchemy 2.0 Nativo) +Provides engine, SessionLocal, scoped_session, and declarative Base without any Flask dependency. """ +import os +import contextlib from typing import Generator, Any -from app import create_app, db as flask_db +from sqlalchemy import ( + create_engine, Column, Integer, String, Text, Boolean, DateTime, Date, Time, Float, + ForeignKey, Table, and_, or_, not_, desc, asc, func, Index, UniqueConstraint +) +from sqlalchemy.orm import declarative_base, scoped_session, sessionmaker, relationship, backref +import sqlalchemy as sa +from config.config import Config -# Initialize shared application context -flask_app = create_app() +# 1. Configurar Engine y conexión +db_url = Config.SQLALCHEMY_DATABASE_URI +connect_args = {} +if "sqlite" in db_url: + connect_args["check_same_thread"] = False + +engine = create_engine( + db_url, + connect_args=connect_args, + pool_pre_ping=True +) + +# 2. Sessionmaker y scoped_session nativo +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +session = scoped_session(SessionLocal) + +# 3. Base declarativa con query_property habilitado +Base = declarative_base() +Base.query = session.query_property() + +# 4. Wrapper compatible que emula la API de SQLAlchemy de Flask sin requerir Flask +class SQLAlchemyWrapper: + def __init__(self, target_engine, session_factory, base_class): + self.engine = target_engine + self.session = session_factory + self.Model = base_class + + # Schema constructs & Types + self.Column = Column + self.Integer = Integer + self.String = String + self.Text = Text + self.Boolean = Boolean + self.DateTime = DateTime + self.Date = Date + self.Time = Time + self.Float = Float + self.ForeignKey = ForeignKey + self.Index = Index + self.UniqueConstraint = UniqueConstraint + + # Relationships + self.relationship = relationship + self.backref = backref + + # Operators & functions + self.and_ = and_ + self.or_ = or_ + self.not_ = not_ + self.desc = desc + self.asc = asc + self.func = func + + @property + def metadata(self): + return self.Model.metadata + + def Table(self, name, *args, **kwargs): + from sqlalchemy import MetaData, Table as SaTable + if len(args) == 0 or not isinstance(args[0], MetaData): + return SaTable(name, self.metadata, *args, **kwargs) + return SaTable(name, *args, **kwargs) + + def create_all(self, bind=None): + target = bind or self.engine + try: + import app.models # noqa + except Exception: + pass + self.Model.metadata.create_all(bind=target) + + def drop_all(self, bind=None): + target = bind or self.engine + try: + import app.models # noqa + except Exception: + pass + self.Model.metadata.drop_all(bind=target) + + def init_app(self, app=None): + """No-op for legacy compatibility""" + pass + + def __getattr__(self, name: str) -> Any: + return getattr(sa, name) + +db = SQLAlchemyWrapper(engine, session, Base) def get_db() -> Generator[Any, None, None]: """ - FastAPI dependency yielding the SQLAlchemy session within Flask app context - to guarantee all models, ORM queries and services work seamlessly. + FastAPI dependency yielding a clean database session per request. """ - with flask_app.app_context(): - yield flask_db.session + db_session = SessionLocal() + try: + yield db_session + finally: + db_session.close() + +# Context manager dummy para compatibilidad transitoria +class DummyAppContext: + def __enter__(self): + return self + def __exit__(self, exc_type, exc_val, exc_tb): + pass + def push(self): + pass + def pop(self): + pass + +class DummyApp: + def __init__(self): + self.config = { + 'TESTING': False, + 'SQLALCHEMY_DATABASE_URI': Config.SQLALCHEMY_DATABASE_URI, + 'SECRET_KEY': Config.SECRET_KEY, + 'LANGUAGES': Config.LANGUAGES + } + + def app_context(self): + return DummyAppContext() + +_dummy_app_instance = DummyApp() def get_flask_app(): - return flask_app + """ + Legacy helper: returns a harmless dummy context object to prevent breakages + during incremental removal of with flask_app.app_context(). + """ + return _dummy_app_instance diff --git a/backend/dependencies.py b/backend/dependencies.py index 6cd6e80..51ed23d 100644 --- a/backend/dependencies.py +++ b/backend/dependencies.py @@ -1,7 +1,8 @@ """ FastAPI Security & Authentication Dependencies Handles JWT extraction from HttpOnly cookies and Bearer headers, -and implements declarative RBAC validation with app context. +and implements declarative RBAC validation with native SQLAlchemy. +100% Native FastAPI - Zero Flask dependencies. """ from typing import Optional, List, Callable, Any, Dict from fastapi import Request, HTTPException, Depends, status @@ -9,9 +10,6 @@ import jwt from app.models.user import User from app.services.jwt_service import JWTService -from database import get_flask_app - -flask_app = get_flask_app() def get_token_from_request(request: Request) -> Optional[str]: @@ -59,24 +57,33 @@ def get_current_user(request: Request) -> User: detail="Token no contiene identificador de usuario válido." ) - with flask_app.app_context(): + try: + user = User.query.get(int(user_id)) + if user: + _ = getattr(user, 'role_obj', None) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Error consultando usuario: {str(e)}" + ) + + if not user or not user.is_active: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Usuario inactivo o no encontrado." + ) + + # Soporte para auditoría/impersonación mediante cabecera X-Impersonate-User + impersonate_header = request.headers.get('X-Impersonate-User') + if impersonate_header and (user.role or '').upper() == 'ADMIN': try: - user = User.query.get(int(user_id)) - if user: - _ = getattr(user, 'role_obj', None) - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Error consultando usuario: {str(e)}" - ) + target_user = User.query.get(int(impersonate_header)) + if target_user and target_user.is_active: + return target_user + except Exception: + pass - if not user or not user.is_active: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Usuario inactivo o no encontrado." - ) - - return user + return user def get_optional_current_user(request: Request) -> Optional[User]: @@ -88,8 +95,7 @@ def get_optional_current_user(request: Request) -> Optional[User]: payload = JWTService.decode_token(token, expected_type='access') user_id = payload.get('sub') if user_id: - with flask_app.app_context(): - return User.query.get(int(user_id)) + return User.query.get(int(user_id)) except Exception: pass return None @@ -98,38 +104,46 @@ def get_optional_current_user(request: Request) -> Optional[User]: def require_roles(allowed_roles: List[str]) -> Callable: """ Factory de dependencias para control de acceso basado en roles (RBAC). - Normaliza comparaciones en minúsculas y reconoce equivalencias (ADMIN, Bedelia, etc.). + Permite acceso si el rol del usuario (normalizado en mayúsculas) coincide + con alguno de los roles permitidos. """ - normalized_allowed = [r.lower() for r in allowed_roles] + normalized_allowed = [r.upper() for r in allowed_roles] - def role_dependency(user: User = Depends(get_current_user)) -> User: - user_role = (user.role or '').lower() - is_admin = getattr(user, 'is_admin', lambda: False)() or user_role in ['admin', 'administrador'] + def role_checker(current_user: User = Depends(get_current_user)) -> User: + user_role = (current_user.role or '').upper() + if user_role not in normalized_allowed: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"Acceso denegado. Se requiere uno de los roles: {', '.join(allowed_roles)}." + ) + return current_user - if is_admin and ('admin' in normalized_allowed or 'administrador' in normalized_allowed): - return user - - if user_role in normalized_allowed: - return user - - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Acceso denegado. Se requiere uno de los siguientes roles: {', '.join(allowed_roles)}." - ) - - return role_dependency + return role_checker -async def get_request_payload(request: Request) -> dict[str, Any]: - """Extrae el cuerpo JSON o formulario multiparte sanitizado como diccionario de Python.""" +async def get_request_payload(request: Request) -> Dict[str, Any]: + """ + Función de utilidad desacoplada para extraer el payload de la petición HTTP, + admitiendo indistintamente cuerpos con JSON (application/json) o formularios codificados + en application/x-www-form-urlencoded y multipart/form-data. + """ + content_type = request.headers.get("content-type", "").lower() + if "application/json" in content_type: + try: + body = await request.json() + return body if isinstance(body, dict) else {} + except Exception: + return {} + + if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type: + try: + form = await request.form() + return dict(form) + except Exception: + return {} + try: body = await request.json() - if isinstance(body, dict): - return body - except Exception: - pass - try: - form = await request.form() - return {k: str(v) for k, v in form.items()} + return body if isinstance(body, dict) else {} except Exception: return {} diff --git a/backend/requirements.txt b/backend/requirements.txt index 8a06c0b..533cc25 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,26 +1,18 @@ -Flask>=3.1.3 -Flask-SQLAlchemy==3.1.1 -Flask-Login==0.6.3 -Flask-WTF==1.2.1 -Flask-Migrate==4.0.5 -Flask-CORS==6.0.2 -Flask-Babel==4.0.0 -WTForms==3.1.0 -Werkzeug>=3.1.6 SQLAlchemy>=2.0.32 -python-dotenv>=1.2.2 -requests>=2.32.4 -bleach>=6.4.0 -python-dateutil==2.8.2 -Pillow>=10.4.0 -email_validator>=2.0.0 psycopg2-binary>=2.9.10 -Babel==2.14.0 -gunicorn>=21.2.0 -PyJWT>=2.8.0 -pydantic>=2.0.0 -cryptography>=42.0.0 fastapi>=0.115.0 uvicorn[standard]>=0.30.0 +pydantic>=2.0.0 +python-dotenv>=1.2.2 +requests>=2.32.4 httpx>=0.27.0 -a2wsgi>=1.10.0 +PyJWT>=2.8.0 +cryptography>=42.0.0 +Werkzeug>=3.1.6 +python-dateutil==2.8.2 +bleach>=6.4.0 +Pillow>=10.4.0 +email_validator>=2.0.0 +Babel==2.14.0 +gunicorn>=21.2.0 +python-multipart>=0.0.9 diff --git a/backend/routers/academic.py b/backend/routers/academic.py index f0bff76..74aad9a 100644 --- a/backend/routers/academic.py +++ b/backend/routers/academic.py @@ -17,10 +17,8 @@ from app.models.enrollment import StudentEnrollment from app.services.enrollment_service import EnrollmentService from app.services.gradebook_service import GradebookService from dependencies import get_current_user, require_roles -from database import get_flask_app academic_router = APIRouter(prefix="/api/v1", tags=["Academic Management"]) -flask_app = get_flask_app() # ========================================================= @@ -33,22 +31,21 @@ def list_careers( current_user: User = Depends(get_current_user) ): """Lista todas las carreras académicas registradas.""" - with flask_app.app_context(): - query = Career.query - if search: - s_clean = search.strip().lower() - query = query.filter( - or_( - Career.name.ilike(f'%{s_clean}%'), - Career.code.ilike(f'%{s_clean}%') - ) + query = Career.query + if search: + s_clean = search.strip().lower() + query = query.filter( + or_( + Career.name.ilike(f'%{s_clean}%'), + Career.code.ilike(f'%{s_clean}%') ) - careers = query.order_by(Career.name.asc()).all() - return { - 'status': 'success', - 'total': len(careers), - 'careers': [c.to_dict() for c in careers] - } + ) + careers = query.order_by(Career.name.asc()).all() + return { + 'status': 'success', + 'total': len(careers), + 'careers': [c.to_dict() for c in careers] + } @academic_router.post("/careers", status_code=status.HTTP_201_CREATED) @@ -64,26 +61,25 @@ async def create_career( form = await request.form() data = dict(form) - with flask_app.app_context(): - name = (data.get('name') or '').strip() - code = (data.get('code') or '').strip() - description = (data.get('description') or '').strip() + name = (data.get('name') or '').strip() + code = (data.get('code') or '').strip() + description = (data.get('description') or '').strip() - if not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre de la carrera es obligatorio.") + if not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre de la carrera es obligatorio.") - if Career.query.filter(Career.name.ilike(name)).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una carrera con el nombre {name}.") + if Career.query.filter(Career.name.ilike(name)).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una carrera con el nombre {name}.") - career = Career(name=name, code=code or None, description=description or None) - db.session.add(career) - db.session.commit() + career = Career(name=name, code=code or None, description=description or None) + db.session.add(career) + db.session.commit() - return { - 'status': 'success', - 'message': 'Carrera creada exitosamente.', - 'career': career.to_dict() - } + return { + 'status': 'success', + 'message': 'Carrera creada exitosamente.', + 'career': career.to_dict() + } @academic_router.put("/careers/{id}") @@ -100,30 +96,29 @@ async def update_career( form = await request.form() data = dict(form) - with flask_app.app_context(): - career = Career.query.get(id) - if not career: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Carrera con ID {id} no encontrada.") + career = Career.query.get(id) + if not career: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Carrera con ID {id} no encontrada.") - if 'name' in data and data['name']: - name = (data['name'] or '').strip() - existing = Career.query.filter(Career.name.ilike(name), Career.id != id).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra carrera con el nombre {name}.") - career.name = name + if 'name' in data and data['name']: + name = (data['name'] or '').strip() + existing = Career.query.filter(Career.name.ilike(name), Career.id != id).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra carrera con el nombre {name}.") + career.name = name - if 'code' in data: - career.code = (data['code'] or '').strip() or None + if 'code' in data: + career.code = (data['code'] or '').strip() or None - if 'description' in data: - career.description = (data['description'] or '').strip() or None + if 'description' in data: + career.description = (data['description'] or '').strip() or None - db.session.commit() - return { - 'status': 'success', - 'message': 'Carrera actualizada correctamente.', - 'career': career.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Carrera actualizada correctamente.', + 'career': career.to_dict() + } @academic_router.delete("/careers/{id}") @@ -132,23 +127,22 @@ def delete_career( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina una carrera si no posee asignaturas vinculadas.""" - with flask_app.app_context(): - career = Career.query.get(id) - if not career: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Carrera con ID {id} no encontrada.") + career = Career.query.get(id) + if not career: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Carrera con ID {id} no encontrada.") - if career.subjects and len(career.subjects) > 0: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"No se puede eliminar la carrera porque tiene {len(career.subjects)} asignaturas vinculadas." - ) + if career.subjects and len(career.subjects) > 0: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"No se puede eliminar la carrera porque tiene {len(career.subjects)} asignaturas vinculadas." + ) - db.session.delete(career) - db.session.commit() - return { - 'status': 'success', - 'message': 'Carrera eliminada permanentemente.' - } + db.session.delete(career) + db.session.commit() + return { + 'status': 'success', + 'message': 'Carrera eliminada permanentemente.' + } # ========================================================= @@ -163,48 +157,47 @@ def list_subjects( current_user: User = Depends(get_current_user) ): """Lista las asignaturas con filtros opcionales de búsqueda, carrera y estado.""" - with flask_app.app_context(): - query = Subject.query - if search: - s_clean = search.strip().lower() - query = query.filter( - or_( - Subject.name.ilike(f'%{s_clean}%'), - Subject.code.ilike(f'%{s_clean}%'), - Subject.department.ilike(f'%{s_clean}%'), - Subject.careers.any(Career.name.ilike(f'%{s_clean}%')) - ) + query = Subject.query + if search: + s_clean = search.strip().lower() + query = query.filter( + or_( + Subject.name.ilike(f'%{s_clean}%'), + Subject.code.ilike(f'%{s_clean}%'), + Subject.department.ilike(f'%{s_clean}%'), + Subject.careers.any(Career.name.ilike(f'%{s_clean}%')) ) - if career_id: - query = query.filter(or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id))) - if active == 'true': - query = query.filter(Subject.is_active == True) - elif active == 'false': - query = query.filter(Subject.is_active == False) + ) + if career_id: + query = query.filter(or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id))) + if active == 'true': + query = query.filter(Subject.is_active == True) + elif active == 'false': + query = query.filter(Subject.is_active == False) - subjects = query.order_by(Subject.id.asc()).all() - careers = Career.query.order_by(Career.name.asc()).all() + subjects = query.order_by(Subject.id.asc()).all() + careers = Career.query.order_by(Career.name.asc()).all() - subjects_data = [] - for s in subjects: - d = s.to_dict() - if isinstance(s.commissions, list): - d['commissions_count'] = len(s.commissions) - d['commissions'] = [{'id': c.id, 'code': c.code, 'schedule': c.schedule} for c in s.commissions] - elif s.commissions is not None: - d['commissions_count'] = 1 - d['commissions'] = [{'id': s.commissions.id, 'code': s.commissions.code, 'schedule': s.commissions.schedule}] - else: - d['commissions_count'] = 0 - d['commissions'] = [] - subjects_data.append(d) + subjects_data = [] + for s in subjects: + d = s.to_dict() + if isinstance(s.commissions, list): + d['commissions_count'] = len(s.commissions) + d['commissions'] = [{'id': c.id, 'code': c.code, 'schedule': c.schedule} for c in s.commissions] + elif s.commissions is not None: + d['commissions_count'] = 1 + d['commissions'] = [{'id': s.commissions.id, 'code': s.commissions.code, 'schedule': s.commissions.schedule}] + else: + d['commissions_count'] = 0 + d['commissions'] = [] + subjects_data.append(d) - return { - 'status': 'success', - 'total': len(subjects_data), - 'subjects': subjects_data, - 'careers': [c.to_dict() for c in careers] - } + return { + 'status': 'success', + 'total': len(subjects_data), + 'subjects': subjects_data, + 'careers': [c.to_dict() for c in careers] + } @academic_router.post("/subjects", status_code=status.HTTP_201_CREATED) @@ -220,64 +213,63 @@ async def create_subject( form = await request.form() data = dict(form) - with flask_app.app_context(): - code = (data.get('code') or '').strip().upper() - name = (data.get('name') or '').strip() - department = (data.get('department') or '').strip() - try: - credits = int(data.get('credits', 4) or 4) - except (ValueError, TypeError): - credits = 4 - career_id = data.get('career_id') - description = (data.get('description') or '').strip() - career_ids = data.get('career_ids') - is_short_course = data.get('is_short_course', False) - if isinstance(is_short_course, str): - is_short_course = is_short_course.lower() in ['true', '1', 'on'] + code = (data.get('code') or '').strip().upper() + name = (data.get('name') or '').strip() + department = (data.get('department') or '').strip() + try: + credits = int(data.get('credits', 4) or 4) + except (ValueError, TypeError): + credits = 4 + career_id = data.get('career_id') + description = (data.get('description') or '').strip() + career_ids = data.get('career_ids') + is_short_course = data.get('is_short_course', False) + if isinstance(is_short_course, str): + is_short_course = is_short_course.lower() in ['true', '1', 'on'] - if not code or not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El código y nombre de la asignatura son obligatorios.") + if not code or not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El código y nombre de la asignatura son obligatorios.") - if Subject.query.filter(Subject.code == code).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una asignatura con el código {code}.") + if Subject.query.filter(Subject.code == code).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una asignatura con el código {code}.") - c_id = int(career_id) if (career_id and str(career_id).strip()) else None + c_id = int(career_id) if (career_id and str(career_id).strip()) else None - c_id_list = [] - if isinstance(career_ids, str): - c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] - elif isinstance(career_ids, list): - c_id_list = [int(x) for x in career_ids if str(x).isdigit()] + c_id_list = [] + if isinstance(career_ids, str): + c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] + elif isinstance(career_ids, list): + c_id_list = [int(x) for x in career_ids if str(x).isdigit()] - if not c_id and c_id_list: - c_id = c_id_list[0] + if not c_id and c_id_list: + c_id = c_id_list[0] - subject = Subject( - code=code, - name=name, - department=department, - credits=credits, - career_id=c_id, - description=description or None, - is_short_course=bool(is_short_course), - is_active=True - ) + subject = Subject( + code=code, + name=name, + department=department, + credits=credits, + career_id=c_id, + description=description or None, + is_short_course=bool(is_short_course), + is_active=True + ) - if c_id_list: - subject.careers = Career.query.filter(Career.id.in_(c_id_list)).all() - elif c_id: - c_obj = Career.query.get(c_id) - if c_obj: - subject.careers = [c_obj] + if c_id_list: + subject.careers = Career.query.filter(Career.id.in_(c_id_list)).all() + elif c_id: + c_obj = Career.query.get(c_id) + if c_obj: + subject.careers = [c_obj] - db.session.add(subject) - db.session.commit() + db.session.add(subject) + db.session.commit() - return { - 'status': 'success', - 'message': 'Asignatura creada exitosamente.', - 'subject': subject.to_dict() - } + return { + 'status': 'success', + 'message': 'Asignatura creada exitosamente.', + 'subject': subject.to_dict() + } @academic_router.put("/subjects/{id}") @@ -294,67 +286,66 @@ async def update_subject( form = await request.form() data = dict(form) - with flask_app.app_context(): - subject = Subject.query.get(id) - if not subject: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") + subject = Subject.query.get(id) + if not subject: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") - if 'code' in data and data['code']: - code = (data['code'] or '').strip().upper() - existing = Subject.query.filter(Subject.code == code, Subject.id != id).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra asignatura con el código {code}.") - subject.code = code + if 'code' in data and data['code']: + code = (data['code'] or '').strip().upper() + existing = Subject.query.filter(Subject.code == code, Subject.id != id).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra asignatura con el código {code}.") + subject.code = code - if 'name' in data and data['name']: - subject.name = (data['name'] or '').strip() + if 'name' in data and data['name']: + subject.name = (data['name'] or '').strip() - if 'department' in data: - subject.department = (data['department'] or '').strip() + if 'department' in data: + subject.department = (data['department'] or '').strip() - if 'credits' in data and data['credits'] is not None: - try: - subject.credits = int(data['credits']) - except (ValueError, TypeError): - pass + if 'credits' in data and data['credits'] is not None: + try: + subject.credits = int(data['credits']) + except (ValueError, TypeError): + pass - if 'career_id' in data: - c_id = data['career_id'] - subject.career_id = int(c_id) if c_id else None + if 'career_id' in data: + c_id = data['career_id'] + subject.career_id = int(c_id) if c_id else None - if 'career_ids' in data: - career_ids = data.get('career_ids') - if isinstance(career_ids, str): - c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] - elif isinstance(career_ids, list): - c_id_list = [int(x) for x in career_ids if str(x).isdigit()] - else: - c_id_list = [] - if c_id_list: - c_objs = Career.query.filter(Career.id.in_(c_id_list)).all() - subject.careers = c_objs - if c_objs and not subject.career_id: - subject.career_id = c_objs[0].id - else: - subject.careers = [] - elif 'career_id' in data and subject.career_id: - c_obj = Career.query.get(subject.career_id) - if c_obj and c_obj not in subject.careers: - subject.careers = [c_obj] + if 'career_ids' in data: + career_ids = data.get('career_ids') + if isinstance(career_ids, str): + c_id_list = [int(x.strip()) for x in career_ids.split(',') if x.strip().isdigit()] + elif isinstance(career_ids, list): + c_id_list = [int(x) for x in career_ids if str(x).isdigit()] + else: + c_id_list = [] + if c_id_list: + c_objs = Career.query.filter(Career.id.in_(c_id_list)).all() + subject.careers = c_objs + if c_objs and not subject.career_id: + subject.career_id = c_objs[0].id + else: + subject.careers = [] + elif 'career_id' in data and subject.career_id: + c_obj = Career.query.get(subject.career_id) + if c_obj and c_obj not in subject.careers: + subject.careers = [c_obj] - if 'description' in data: - subject.description = (data['description'] or '').strip() + if 'description' in data: + subject.description = (data['description'] or '').strip() - if 'is_active' in data: - val = data['is_active'] - subject.is_active = val in [True, 'true', '1', 'on'] + if 'is_active' in data: + val = data['is_active'] + subject.is_active = val in [True, 'true', '1', 'on'] - db.session.commit() - return { - 'status': 'success', - 'message': 'Asignatura actualizada correctamente.', - 'subject': subject.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Asignatura actualizada correctamente.', + 'subject': subject.to_dict() + } @academic_router.post("/subjects/{id}/toggle") @@ -363,18 +354,17 @@ def toggle_subject( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo de una asignatura.""" - with flask_app.app_context(): - subject = Subject.query.get(id) - if not subject: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") - subject.is_active = not subject.is_active - db.session.commit() - return { - 'status': 'success', - 'id': subject.id, - 'is_active': subject.is_active, - 'message': f'Asignatura {"activada" if subject.is_active else "desactivada"} correctamente.' - } + subject = Subject.query.get(id) + if not subject: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") + subject.is_active = not subject.is_active + db.session.commit() + return { + 'status': 'success', + 'id': subject.id, + 'is_active': subject.is_active, + 'message': f'Asignatura {"activada" if subject.is_active else "desactivada"} correctamente.' + } @academic_router.delete("/subjects/{id}") @@ -383,29 +373,28 @@ def delete_subject( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina una asignatura o la desactiva si tiene comisiones vinculadas.""" - with flask_app.app_context(): - subject = Subject.query.get(id) - if not subject: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") + subject = Subject.query.get(id) + if not subject: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Asignatura con ID {id} no encontrada.") - if subject.commissions and len(subject.commissions) > 0: - subject.is_active = False - db.session.commit() - return { - 'status': 'deactivated', - 'action': 'deactivated', - 'message': f'La asignatura "{subject.name}" tiene {len(subject.commissions)} comisión(es) vinculada(s). Se ha desactivado en su lugar para proteger el historial académico.' - } - - name = subject.name - db.session.delete(subject) + if subject.commissions and len(subject.commissions) > 0: + subject.is_active = False db.session.commit() return { - 'status': 'deleted', - 'action': 'deleted', - 'message': f'Asignatura "{name}" eliminada permanentemente del sistema.' + 'status': 'deactivated', + 'action': 'deactivated', + 'message': f'La asignatura "{subject.name}" tiene {len(subject.commissions)} comisión(es) vinculada(s). Se ha desactivado en su lugar para proteger el historial académico.' } + name = subject.name + db.session.delete(subject) + db.session.commit() + return { + 'status': 'deleted', + 'action': 'deleted', + 'message': f'Asignatura "{name}" eliminada permanentemente del sistema.' + } + # ========================================================= # COMMISSIONS ENDPOINTS @@ -420,27 +409,26 @@ def list_commissions( current_user: User = Depends(get_current_user) ): """Lista las comisiones académicas con soporte para filtros de carrera, materia y turno.""" - with flask_app.app_context(): - query = Commission.query - if subject_id: - query = query.filter(Commission.subject_id == subject_id) - if career_id: - query = query.join(Subject, Commission.subject_id == Subject.id).filter( - or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id)) - ) - if shift: - query = query.filter(Commission.shift == shift) - if active == 'true': - query = query.filter(Commission.active == True) - elif active == 'false': - query = query.filter(Commission.active == False) + query = Commission.query + if subject_id: + query = query.filter(Commission.subject_id == subject_id) + if career_id: + query = query.join(Subject, Commission.subject_id == Subject.id).filter( + or_(Subject.career_id == career_id, Subject.careers.any(Career.id == career_id)) + ) + if shift: + query = query.filter(Commission.shift == shift) + if active == 'true': + query = query.filter(Commission.active == True) + elif active == 'false': + query = query.filter(Commission.active == False) - commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).all() - return { - 'status': 'success', - 'total': len(commissions), - 'commissions': [c.to_dict() for c in commissions] - } + commissions = query.order_by(Commission.year.desc(), Commission.semester.desc(), Commission.code.asc()).all() + return { + 'status': 'success', + 'total': len(commissions), + 'commissions': [c.to_dict() for c in commissions] + } @academic_router.post("/commissions", status_code=status.HTTP_201_CREATED) @@ -456,115 +444,114 @@ async def create_commission( form = await request.form() data = dict(form) - with flask_app.app_context(): - subject_id = data.get('subject_id') - code = (data.get('code') or '').strip() - semester = (data.get('semester') or '1C').strip() - try: - year = int(data.get('year', datetime.now().year) or datetime.now().year) - except (ValueError, TypeError): - year = datetime.now().year - academic_term_id = data.get('academic_term_id') - academic_term_id = int(academic_term_id) if (academic_term_id and str(academic_term_id).strip().isdigit()) else None + subject_id = data.get('subject_id') + code = (data.get('code') or '').strip() + semester = (data.get('semester') or '1C').strip() + try: + year = int(data.get('year', datetime.now().year) or datetime.now().year) + except (ValueError, TypeError): + year = datetime.now().year + academic_term_id = data.get('academic_term_id') + academic_term_id = int(academic_term_id) if (academic_term_id and str(academic_term_id).strip().isdigit()) else None + if academic_term_id: + term_obj = AcademicTerm.query.get(academic_term_id) + if term_obj: + if not data.get('year') or int(data.get('year')) == datetime.now().year: + year = term_obj.year + if not data.get('semester') or data.get('semester') == '1C': + p_text = f"{term_obj.name} {term_obj.period_type or ''} {term_obj.code}".lower() + if '2c' in p_text or 'segundo' in p_text or '2º' in p_text or '2do' in p_text: + semester = '2C' + elif 'anual' in p_text: + semester = 'Anual' + else: + semester = '1C' + + teacher_id = data.get('teacher_id') + teacher_id = int(teacher_id) if (teacher_id and str(teacher_id).strip().isdigit()) else None + try: + max_students = int(data.get('max_students', 35) or 35) + except (ValueError, TypeError): + max_students = 35 + schedule = (data.get('schedule') or '').strip() + shift = (data.get('shift') or 'Mañana').strip() + virtual_link = (data.get('virtual_link') or '').strip() + active = data.get('active', True) + if isinstance(active, str): + active = active.lower() in ['true', '1', 'on'] + + if not subject_id or not code: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="La asignatura y código de comisión son obligatorios.") + + subject = Subject.query.get(int(subject_id)) + if not subject: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"La asignatura con ID {subject_id} no existe.") + + virtual_link = virtual_link or None + + existing = Commission.query.filter_by( + subject_id=int(subject_id), + code=code, + semester=semester, + year=year + ).first() + + if existing: + existing.teacher_id = teacher_id + existing.max_students = max_students + existing.schedule = schedule + existing.shift = shift if academic_term_id: - term_obj = AcademicTerm.query.get(academic_term_id) - if term_obj: - if not data.get('year') or int(data.get('year')) == datetime.now().year: - year = term_obj.year - if not data.get('semester') or data.get('semester') == '1C': - p_text = f"{term_obj.name} {term_obj.period_type or ''} {term_obj.code}".lower() - if '2c' in p_text or 'segundo' in p_text or '2º' in p_text or '2do' in p_text: - semester = '2C' - elif 'anual' in p_text: - semester = 'Anual' - else: - semester = '1C' - - teacher_id = data.get('teacher_id') - teacher_id = int(teacher_id) if (teacher_id and str(teacher_id).strip().isdigit()) else None - try: - max_students = int(data.get('max_students', 35) or 35) - except (ValueError, TypeError): - max_students = 35 - schedule = (data.get('schedule') or '').strip() - shift = (data.get('shift') or 'Mañana').strip() - virtual_link = (data.get('virtual_link') or '').strip() - active = data.get('active', True) - if isinstance(active, str): - active = active.lower() in ['true', '1', 'on'] - - if not subject_id or not code: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="La asignatura y código de comisión son obligatorios.") - - subject = Subject.query.get(int(subject_id)) - if not subject: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"La asignatura con ID {subject_id} no existe.") - - virtual_link = virtual_link or None - - existing = Commission.query.filter_by( - subject_id=int(subject_id), - code=code, - semester=semester, - year=year - ).first() - - if existing: - existing.teacher_id = teacher_id - existing.max_students = max_students - existing.schedule = schedule - existing.shift = shift - if academic_term_id: - existing.academic_term_id = academic_term_id - if virtual_link: - existing.virtual_link = virtual_link - existing.active = bool(active) - if teacher_id: - ct = CommissionTeacher.query.filter_by(commission_id=existing.id, user_id=teacher_id).first() - if not ct: - db.session.add(CommissionTeacher(commission_id=existing.id, user_id=teacher_id, role='Titular', is_primary=True)) - db.session.commit() - return { - 'status': 'success', - 'message': f'Comisión {code} asociada a {subject.name} actualizada exitosamente.', - 'commission': existing.to_dict() - } - - commission = Commission( - subject_id=int(subject_id), - code=code, - semester=semester, - year=year, - teacher_id=teacher_id, - max_students=max_students, - schedule=schedule, - shift=shift, - virtual_link=virtual_link, - academic_term_id=academic_term_id, - active=bool(active) - ) - db.session.add(commission) - db.session.flush() - + existing.academic_term_id = academic_term_id + if virtual_link: + existing.virtual_link = virtual_link + existing.active = bool(active) if teacher_id: - db.session.add(CommissionTeacher(commission_id=commission.id, user_id=teacher_id, role='Titular', is_primary=True)) - - extra_teachers = data.get('teacher_ids') or data.get('teachers') or [] - for et in extra_teachers: - u_id = et.get('user_id') if isinstance(et, dict) else et - u_role = et.get('role', 'Adjunto') if isinstance(et, dict) else 'Adjunto' - if u_id and int(u_id) != teacher_id: - db.session.add(CommissionTeacher(commission_id=commission.id, user_id=int(u_id), role=u_role, is_primary=False)) - + ct = CommissionTeacher.query.filter_by(commission_id=existing.id, user_id=teacher_id).first() + if not ct: + db.session.add(CommissionTeacher(commission_id=existing.id, user_id=teacher_id, role='Titular', is_primary=True)) db.session.commit() - return { 'status': 'success', - 'message': f'Comisión {code} asociada exitosamente a {subject.name}.', - 'commission': commission.to_dict() + 'message': f'Comisión {code} asociada a {subject.name} actualizada exitosamente.', + 'commission': existing.to_dict() } + commission = Commission( + subject_id=int(subject_id), + code=code, + semester=semester, + year=year, + teacher_id=teacher_id, + max_students=max_students, + schedule=schedule, + shift=shift, + virtual_link=virtual_link, + academic_term_id=academic_term_id, + active=bool(active) + ) + db.session.add(commission) + db.session.flush() + + if teacher_id: + db.session.add(CommissionTeacher(commission_id=commission.id, user_id=teacher_id, role='Titular', is_primary=True)) + + extra_teachers = data.get('teacher_ids') or data.get('teachers') or [] + for et in extra_teachers: + u_id = et.get('user_id') if isinstance(et, dict) else et + u_role = et.get('role', 'Adjunto') if isinstance(et, dict) else 'Adjunto' + if u_id and int(u_id) != teacher_id: + db.session.add(CommissionTeacher(commission_id=commission.id, user_id=int(u_id), role=u_role, is_primary=False)) + + db.session.commit() + + return { + 'status': 'success', + 'message': f'Comisión {code} asociada exitosamente a {subject.name}.', + 'commission': commission.to_dict() + } + @academic_router.get("/commissions/{id}") def get_commission( @@ -572,14 +559,13 @@ def get_commission( current_user: User = Depends(get_current_user) ): """Obtiene los detalles de una comisión.""" - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") - return { - 'status': 'success', - 'commission': comm.to_dict() - } + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") + return { + 'status': 'success', + 'commission': comm.to_dict() + } @academic_router.put("/commissions/{id}") @@ -596,50 +582,49 @@ async def update_commission( form = await request.form() data = dict(form) - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") - if 'subject_id' in data and data['subject_id']: - comm.subject_id = int(data['subject_id']) - if 'academic_term_id' in data: - t_id = data['academic_term_id'] - comm.academic_term_id = int(t_id) if (t_id and str(t_id).strip().isdigit()) else None - if 'code' in data and data['code']: - comm.code = (data['code'] or '').strip() - if 'semester' in data and data['semester']: - comm.semester = (data['semester'] or '').strip() - if 'year' in data and data['year']: - comm.year = int(data['year']) - if 'teacher_id' in data: - t_id = data['teacher_id'] - comm.teacher_id = int(t_id) if (t_id and str(t_id).strip().isdigit()) else None - if comm.teacher_id: - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=comm.teacher_id).first() - if not ct: - db.session.add(CommissionTeacher(commission_id=comm.id, user_id=comm.teacher_id, role='Titular', is_primary=True)) - else: - ct.is_primary = True - if 'max_students' in data and data['max_students']: - comm.max_students = int(data['max_students']) - if 'schedule' in data: - comm.schedule = (data['schedule'] or '').strip() - if 'shift' in data and data['shift']: - comm.shift = (data['shift'] or '').strip() - if 'virtual_link' in data: - vl = (data['virtual_link'] or '').strip() - comm.virtual_link = vl or None - if 'active' in data: - val = data['active'] - comm.active = val in [True, 'true', '1', 'on'] + if 'subject_id' in data and data['subject_id']: + comm.subject_id = int(data['subject_id']) + if 'academic_term_id' in data: + t_id = data['academic_term_id'] + comm.academic_term_id = int(t_id) if (t_id and str(t_id).strip().isdigit()) else None + if 'code' in data and data['code']: + comm.code = (data['code'] or '').strip() + if 'semester' in data and data['semester']: + comm.semester = (data['semester'] or '').strip() + if 'year' in data and data['year']: + comm.year = int(data['year']) + if 'teacher_id' in data: + t_id = data['teacher_id'] + comm.teacher_id = int(t_id) if (t_id and str(t_id).strip().isdigit()) else None + if comm.teacher_id: + ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=comm.teacher_id).first() + if not ct: + db.session.add(CommissionTeacher(commission_id=comm.id, user_id=comm.teacher_id, role='Titular', is_primary=True)) + else: + ct.is_primary = True + if 'max_students' in data and data['max_students']: + comm.max_students = int(data['max_students']) + if 'schedule' in data: + comm.schedule = (data['schedule'] or '').strip() + if 'shift' in data and data['shift']: + comm.shift = (data['shift'] or '').strip() + if 'virtual_link' in data: + vl = (data['virtual_link'] or '').strip() + comm.virtual_link = vl or None + if 'active' in data: + val = data['active'] + comm.active = val in [True, 'true', '1', 'on'] - db.session.commit() - return { - 'status': 'success', - 'message': 'Comisión actualizada correctamente.', - 'commission': comm.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Comisión actualizada correctamente.', + 'commission': comm.to_dict() + } @academic_router.post("/commissions/{id}/toggle") @@ -648,18 +633,17 @@ def toggle_commission( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo de una comisión.""" - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") - comm.active = not comm.active - db.session.commit() - return { - 'status': 'success', - 'id': comm.id, - 'active': comm.active, - 'message': f'Comisión {"activada" if comm.active else "desactivada"} correctamente.' - } + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") + comm.active = not comm.active + db.session.commit() + return { + 'status': 'success', + 'id': comm.id, + 'active': comm.active, + 'message': f'Comisión {"activada" if comm.active else "desactivada"} correctamente.' + } @academic_router.delete("/commissions/{id}") @@ -668,30 +652,29 @@ def delete_commission( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina una comisión o la desactiva si contiene reservas históricas.""" - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión con ID {id} no encontrada.") - from app.models.reservation import Reservation - res_count = Reservation.query.filter_by(commission_id=id).count() - if res_count > 0: - comm.active = False - db.session.commit() - return { - 'status': 'deactivated', - 'action': 'deactivated', - 'message': f'La comisión tiene {res_count} reservas vinculadas. Se ha desactivado en su lugar.' - } - - db.session.delete(comm) + from app.models.reservation import Reservation + res_count = Reservation.query.filter_by(commission_id=id).count() + if res_count > 0: + comm.active = False db.session.commit() return { - 'status': 'deleted', - 'action': 'deleted', - 'message': 'Comisión eliminada permanentemente.' + 'status': 'deactivated', + 'action': 'deactivated', + 'message': f'La comisión tiene {res_count} reservas vinculadas. Se ha desactivado en su lugar.' } + db.session.delete(comm) + db.session.commit() + return { + 'status': 'deleted', + 'action': 'deleted', + 'message': 'Comisión eliminada permanentemente.' + } + # ========================================================= # ACADEMIC TERMS ENDPOINTS @@ -705,29 +688,29 @@ def list_academic_terms( current_user: User = Depends(get_current_user) ): """Lista todos los ciclos lectivos registrados.""" - with flask_app.app_context(): - query = AcademicTerm.query - if search: - s_clean = search.strip().lower() - query = query.filter( - or_( - AcademicTerm.name.ilike(f'%{s_clean}%'), - AcademicTerm.code.ilike(f'%{s_clean}%'), - AcademicTerm.period_type.ilike(f'%{s_clean}%') - ) + query = AcademicTerm.query + if search: + s_clean = search.strip().lower() + query = query.filter( + or_( + AcademicTerm.name.ilike(f'%{s_clean}%'), + AcademicTerm.code.ilike(f'%{s_clean}%'), + AcademicTerm.period_type.ilike(f'%{s_clean}%') ) - if year: - query = query.filter(AcademicTerm.year == year) + ) + if year: + query = query.filter(AcademicTerm.year == year) - terms = query.order_by(AcademicTerm.year.desc(), AcademicTerm.id.desc()).all() - return { - 'status': 'success', - 'total': len(terms), - 'terms': [t.to_dict() for t in terms] - } + terms = query.order_by(AcademicTerm.year.desc(), AcademicTerm.id.desc()).all() + return { + 'status': 'success', + 'total': len(terms), + 'terms': [t.to_dict() for t in terms] + } @academic_router.post("/academic-terms", status_code=status.HTTP_201_CREATED) +@academic_router.post("/admin/academic-terms", status_code=status.HTTP_201_CREATED) async def create_academic_term( request: Request, current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) @@ -740,108 +723,108 @@ async def create_academic_term( form = await request.form() data = dict(form) - with flask_app.app_context(): - code = (data.get('code') or '').strip().upper() - name = (data.get('name') or '').strip() - try: - year = int(data.get('year', datetime.now().year) or datetime.now().year) - except (ValueError, TypeError): - year = datetime.now().year - period_type = (data.get('period_type') or 'Segundo Cuatrimestre').strip() - start_date = data.get('start_date') - end_date = data.get('end_date') - is_current = data.get('is_current', False) - if isinstance(is_current, str): - is_current = is_current.lower() in ['true', '1', 'on'] + code = (data.get('code') or '').strip().upper() + name = (data.get('name') or '').strip() + try: + year = int(data.get('year', datetime.now().year) or datetime.now().year) + except (ValueError, TypeError): + year = datetime.now().year + period_type = (data.get('period_type') or 'Segundo Cuatrimestre').strip() + start_date = data.get('start_date') + end_date = data.get('end_date') + is_current = data.get('is_current', False) + if isinstance(is_current, str): + is_current = is_current.lower() in ['true', '1', 'on'] - if not code or not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El código y nombre del período lectivo son obligatorios.") + if not code or not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El código y nombre del período lectivo son obligatorios.") - if AcademicTerm.query.filter(AcademicTerm.code == code).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un período lectivo con el código {code}.") + if AcademicTerm.query.filter(AcademicTerm.code == code).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un período lectivo con el código {code}.") - if is_current: - AcademicTerm.query.update({'is_current': False}) + if is_current: + AcademicTerm.query.update({'is_current': False}) - term = AcademicTerm( - code=code, - name=name, - year=year, - period_type=period_type, - start_date=datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None, - end_date=datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None, - is_current=bool(is_current), - is_active=True - ) - db.session.add(term) - db.session.commit() + term = AcademicTerm( + code=code, + name=name, + year=year, + period_type=period_type, + start_date=datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None, + end_date=datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None, + is_current=bool(is_current), + is_active=True + ) + db.session.add(term) + db.session.commit() - return { - 'status': 'success', - 'message': f'Período lectivo "{name}" creado con éxito.', - 'term': term.to_dict() - } + return { + 'status': 'success', + 'message': f'Período lectivo "{name}" creado con éxito.', + 'term': term.to_dict() + } @academic_router.post("/academic-terms/{id}/set-current") +@academic_router.post("/admin/academic-terms/{id}/set-current") def set_current_academic_term( id: int, current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Marca un ciclo lectivo como el período vigente institucional.""" - with flask_app.app_context(): - term = AcademicTerm.query.get(id) - if not term: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") + term = AcademicTerm.query.get(id) + if not term: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") - AcademicTerm.query.update({'is_current': False}) - term.is_current = True - term.is_active = True - db.session.commit() + AcademicTerm.query.update({'is_current': False}) + term.is_current = True + term.is_active = True + db.session.commit() - return { - 'status': 'success', - 'message': f'El período "{term.name}" ha sido establecido como el ciclo lectivo activo actual.', - 'term': term.to_dict() - } + return { + 'status': 'success', + 'message': f'El período "{term.name}" ha sido establecido como el ciclo lectivo activo actual.', + 'term': term.to_dict() + } @academic_router.post("/academic-terms/{id}/toggle") +@academic_router.post("/admin/academic-terms/{id}/toggle") def toggle_academic_term( id: int, current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo de un ciclo lectivo.""" - with flask_app.app_context(): - term = AcademicTerm.query.get(id) - if not term: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") - term.is_active = not term.is_active - db.session.commit() - return { - 'status': 'success', - 'message': f'Período {"activado" if term.is_active else "desactivado"} exitosamente.', - 'term': term.to_dict() - } + term = AcademicTerm.query.get(id) + if not term: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") + term.is_active = not term.is_active + db.session.commit() + return { + 'status': 'success', + 'is_active': term.is_active, + 'message': f'Período {"activado" if term.is_active else "desactivado"} exitosamente.', + 'term': term.to_dict() + } @academic_router.delete("/academic-terms/{id}") +@academic_router.delete("/admin/academic-terms/{id}") def delete_academic_term( id: int, current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina un ciclo lectivo.""" - with flask_app.app_context(): - term = AcademicTerm.query.get(id) - if not term: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") - name = term.name - db.session.delete(term) - db.session.commit() - return { - 'status': 'success', - 'message': f'Período lectivo "{name}" eliminado correctamente.' - } + term = AcademicTerm.query.get(id) + if not term: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Período lectivo con ID {id} no encontrado.") + name = term.name + db.session.delete(term) + db.session.commit() + return { + 'status': 'success', + 'message': f'Período lectivo "{name}" eliminado correctamente.' + } # ========================================================= @@ -862,36 +845,35 @@ async def assign_commission_teacher( form = await request.form() data = dict(form) - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") - t_id = data.get('teacher_id') or data.get('user_id') - role = (data.get('role') or 'Titular').strip() + t_id = data.get('teacher_id') or data.get('user_id') + role = (data.get('role') or 'Titular').strip() - if t_id: - t_id = int(t_id) - comm.teacher_id = t_id - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=t_id).first() - if not ct: - ct = CommissionTeacher(commission_id=comm.id, user_id=t_id, role=role, is_primary=True) - db.session.add(ct) - else: - ct.role = role - ct.is_primary = True + if t_id: + t_id = int(t_id) + comm.teacher_id = t_id + ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=t_id).first() + if not ct: + ct = CommissionTeacher(commission_id=comm.id, user_id=t_id, role=role, is_primary=True) + db.session.add(ct) else: - comm.teacher_id = None + ct.role = role + ct.is_primary = True + else: + comm.teacher_id = None - db.session.commit() - return { - 'status': 'success', - 'id': comm.id, - 'teacher_id': comm.teacher_id, - 'teacher_name': comm.teacher_name, - 'teachers': comm.teachers, - 'message': 'Docente asignado correctamente.' - } + db.session.commit() + return { + 'status': 'success', + 'id': comm.id, + 'teacher_id': comm.teacher_id, + 'teacher_name': comm.teacher_name, + 'teachers': comm.teachers, + 'message': 'Docente asignado correctamente.' + } @academic_router.post("/commissions/{id}/teachers") @@ -912,43 +894,42 @@ async def add_commission_teacher( if not user_id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El docente es requerido.") - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") - user = User.query.get(int(user_id)) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"El usuario docente con ID {user_id} no existe.") + user = User.query.get(int(user_id)) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"El usuario docente con ID {user_id} no existe.") - role = (data.get('role') or 'Adjunto').strip() - is_primary = data.get('is_primary', False) - if isinstance(is_primary, str): - is_primary = is_primary.lower() in ['true', '1', 'on'] + role = (data.get('role') or 'Adjunto').strip() + is_primary = data.get('is_primary', False) + if isinstance(is_primary, str): + is_primary = is_primary.lower() in ['true', '1', 'on'] - existing = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user.id).first() - if existing: - existing.role = role - existing.is_primary = bool(is_primary) - else: - if is_primary or comm.teacher_id is None: - comm.teacher_id = user.id - is_primary = True - ct = CommissionTeacher( - commission_id=comm.id, - user_id=user.id, - role=role, - is_primary=bool(is_primary) - ) - db.session.add(ct) + existing = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user.id).first() + if existing: + existing.role = role + existing.is_primary = bool(is_primary) + else: + if is_primary or comm.teacher_id is None: + comm.teacher_id = user.id + is_primary = True + ct = CommissionTeacher( + commission_id=comm.id, + user_id=user.id, + role=role, + is_primary=bool(is_primary) + ) + db.session.add(ct) - db.session.commit() - return { - 'status': 'success', - 'message': f'{user.name} asignado/a como {role} en la comisión.', - 'teachers': comm.teachers, - 'commission': comm.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': f'{user.name} asignado/a como {role} en la comisión.', + 'teachers': comm.teachers, + 'commission': comm.to_dict() + } @academic_router.delete("/commissions/{id}/teachers/{user_id}") @@ -958,28 +939,27 @@ def remove_commission_teacher( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Desvincula a un docente de una comisión.""" - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") - ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user_id).first() - if ct: - db.session.delete(ct) + ct = CommissionTeacher.query.filter_by(commission_id=comm.id, user_id=user_id).first() + if ct: + db.session.delete(ct) - if comm.teacher_id == user_id: - other = CommissionTeacher.query.filter(CommissionTeacher.commission_id == comm.id, CommissionTeacher.user_id != user_id).first() - comm.teacher_id = other.user_id if other else None - if other: - other.is_primary = True + if comm.teacher_id == user_id: + other = CommissionTeacher.query.filter(CommissionTeacher.commission_id == comm.id, CommissionTeacher.user_id != user_id).first() + comm.teacher_id = other.user_id if other else None + if other: + other.is_primary = True - db.session.commit() - return { - 'status': 'success', - 'message': 'Docente desvinculado de la comisión correctamente.', - 'teachers': comm.teachers, - 'commission': comm.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Docente desvinculado de la comisión correctamente.', + 'teachers': comm.teachers, + 'commission': comm.to_dict() + } # ========================================================= @@ -992,20 +972,19 @@ def get_commission_enrollments( current_user: User = Depends(get_current_user) ): """Lista los estudiantes matriculados en una comisión.""" - with flask_app.app_context(): - comm = Commission.query.get(id) - if not comm: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") + comm = Commission.query.get(id) + if not comm: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Comisión {id} no encontrada.") - enrollments = EnrollmentService.list_enrollments(comm.id) - return { - 'commission_id': comm.id, - 'commission_code': comm.code, - 'count': len(enrollments), - 'max_students': comm.max_students, - 'current_students': comm.current_students, - 'enrollments': enrollments - } + enrollments = EnrollmentService.list_enrollments(comm.id) + return { + 'commission_id': comm.id, + 'commission_code': comm.code, + 'count': len(enrollments), + 'max_students': comm.max_students, + 'current_students': comm.current_students, + 'enrollments': enrollments + } @academic_router.post("/commissions/{id}/enrollments", status_code=status.HTTP_201_CREATED) @@ -1030,22 +1009,21 @@ async def enroll_commission_student( if not student_id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="student_id es obligatorio.") - with flask_app.app_context(): - try: - enrollment = EnrollmentService.enroll_student( - commission_id=id, - student_id=int(student_id), - notes=notes, - allow_same_day_exception=allow_same_day_exception, - exception_reason=exception_reason - ) - return { - 'status': 'success', - 'message': 'Estudiante matriculado exitosamente en la comisión.', - 'enrollment': enrollment.to_dict() - } - except ValueError as e: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) + try: + enrollment = EnrollmentService.enroll_student( + commission_id=id, + student_id=int(student_id), + notes=notes, + allow_same_day_exception=allow_same_day_exception, + exception_reason=exception_reason + ) + return { + 'status': 'success', + 'message': 'Estudiante matriculado exitosamente en la comisión.', + 'enrollment': enrollment.to_dict() + } + except ValueError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) @academic_router.delete("/commissions/{id}/enrollments/{student_id}") @@ -1055,14 +1033,13 @@ def unenroll_commission_student( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Desmatricula a un estudiante de una comisión.""" - with flask_app.app_context(): - success = EnrollmentService.unenroll_student(commission_id=id, student_id=student_id) - if not success: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Matrícula no encontrada para este estudiante.") - return { - 'status': 'success', - 'message': 'Estudiante desvinculado de la comisión exitosamente.' - } + success = EnrollmentService.unenroll_student(commission_id=id, student_id=student_id) + if not success: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Matrícula no encontrada para este estudiante.") + return { + 'status': 'success', + 'message': 'Estudiante desvinculado de la comisión exitosamente.' + } @academic_router.put("/commissions/{id}/enrollments/{student_id}") @@ -1083,20 +1060,19 @@ async def update_commission_enrollment( status_val = data.get('status', 'activo') notes = data.get('notes') - with flask_app.app_context(): - enrollment = EnrollmentService.update_enrollment_status( - commission_id=id, - student_id=student_id, - status=status_val, - notes=notes - ) - if not enrollment: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Matrícula no encontrada.") - return { - 'status': 'success', - 'message': 'Estado de matrícula actualizado.', - 'enrollment': enrollment.to_dict() - } + enrollment = EnrollmentService.update_enrollment_status( + commission_id=id, + student_id=student_id, + status=status_val, + notes=notes + ) + if not enrollment: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Matrícula no encontrada.") + return { + 'status': 'success', + 'message': 'Estado de matrícula actualizado.', + 'enrollment': enrollment.to_dict() + } # ========================================================= @@ -1109,14 +1085,13 @@ def get_commission_gradebook( current_user: User = Depends(get_current_user) ): """Obtiene la sábana completa de notas y regularidad de la comisión.""" - with flask_app.app_context(): - try: - data = GradebookService.get_commission_gradebook(id) - return {'status': 'success', 'data': data} - except ValueError as e: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + try: + data = GradebookService.get_commission_gradebook(id) + return {'status': 'success', 'data': data} + except ValueError as e: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) @academic_router.post("/commissions/{id}/gradebook/grades") @@ -1134,39 +1109,38 @@ async def save_commission_grades( form = await request.form() data = dict(form) - with flask_app.app_context(): - try: - if 'grades' in data and isinstance(data['grades'], list): - res = GradebookService.bulk_save_grades( - commission_id=id, - grades_data=data['grades'], - grader_id=current_user.id - ) - return {'status': 'success', 'message': f"{res['saved_count']} calificaciones guardadas.", 'data': res} - else: - milestone_id = data.get('milestone_id') - student_id = data.get('student_id') - score = data.get('score') - is_absent = bool(data.get('is_absent', False)) - feedback = data.get('feedback', '') + try: + if 'grades' in data and isinstance(data['grades'], list): + res = GradebookService.bulk_save_grades( + commission_id=id, + grades_data=data['grades'], + grader_id=current_user.id + ) + return {'status': 'success', 'message': f"{res['saved_count']} calificaciones guardadas.", 'data': res} + else: + milestone_id = data.get('milestone_id') + student_id = data.get('student_id') + score = data.get('score') + is_absent = bool(data.get('is_absent', False)) + feedback = data.get('feedback', '') - if not milestone_id or not student_id: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="milestone_id y student_id son obligatorios.") + if not milestone_id or not student_id: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="milestone_id y student_id son obligatorios.") - grade = GradebookService.save_single_grade( - commission_id=id, - milestone_id=int(milestone_id), - student_id=int(student_id), - score=float(score) if score is not None and str(score).strip() != '' else None, - is_absent=is_absent, - feedback=feedback, - grader_id=current_user.id - ) - return {'status': 'success', 'message': 'Calificación guardada.', 'grade': grade.to_dict()} - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + grade = GradebookService.save_single_grade( + commission_id=id, + milestone_id=int(milestone_id), + student_id=int(student_id), + score=float(score) if score is not None and str(score).strip() != '' else None, + is_absent=is_absent, + feedback=feedback, + grader_id=current_user.id + ) + return {'status': 'success', 'message': 'Calificación guardada.', 'grade': grade.to_dict()} + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) @academic_router.post("/commissions/{id}/gradebook/close") @@ -1183,14 +1157,13 @@ async def close_commission_gradebook( pass notes = data.get('notes', '') - with flask_app.app_context(): - try: - res = GradebookService.close_gradebook(commission_id=id, user_id=current_user.id, notes=notes) - return {'status': 'success', **res} - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + try: + res = GradebookService.close_gradebook(commission_id=id, user_id=current_user.id, notes=notes) + return {'status': 'success', **res} + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) @academic_router.post("/commissions/{id}/gradebook/reopen") @@ -1207,14 +1180,13 @@ async def reopen_commission_gradebook( pass reason = data.get('reason', '') - with flask_app.app_context(): - try: - res = GradebookService.reopen_gradebook(commission_id=id, user_id=current_user.id, reason=reason) - return {'status': 'success', **res} - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + try: + res = GradebookService.reopen_gradebook(commission_id=id, user_id=current_user.id, reason=reason) + return {'status': 'success', **res} + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) # ========================================================= @@ -1226,13 +1198,12 @@ def get_milestone_types( current_user: User = Depends(get_current_user) ): """Lista las tipificaciones de hitos académicos disponibles.""" - with flask_app.app_context(): - types = MilestoneType.query.order_by(MilestoneType.sort_order.asc(), MilestoneType.id.asc()).all() - return { - 'status': 'success', - 'total': len(types), - 'milestone_types': [t.to_dict() for t in types] - } + types = MilestoneType.query.order_by(MilestoneType.sort_order.asc(), MilestoneType.id.asc()).all() + return { + 'status': 'success', + 'total': len(types), + 'milestone_types': [t.to_dict() for t in types] + } @academic_router.post("/milestone-types", status_code=status.HTTP_201_CREATED) @@ -1263,27 +1234,26 @@ async def create_milestone_type( if not name or not code: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Nombre y código son obligatorios.") - with flask_app.app_context(): - existing = MilestoneType.query.filter_by(code=code).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una tipificación con el código {code}.") + existing = MilestoneType.query.filter_by(code=code).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe una tipificación con el código {code}.") - mt = MilestoneType( - name=name, - code=code, - color=color, - description=description, - sort_order=sort_order, - is_active=bool(is_active) - ) - db.session.add(mt) - db.session.commit() + mt = MilestoneType( + name=name, + code=code, + color=color, + description=description, + sort_order=sort_order, + is_active=bool(is_active) + ) + db.session.add(mt) + db.session.commit() - return { - 'status': 'success', - 'message': 'Tipificación de hito creada correctamente.', - 'milestone_type': mt.to_dict() - } + return { + 'status': 'success', + 'message': 'Tipificación de hito creada correctamente.', + 'milestone_type': mt.to_dict() + } @academic_router.put("/milestone-types/{id}") @@ -1300,37 +1270,36 @@ async def update_milestone_type( form = await request.form() data = dict(form) - with flask_app.app_context(): - mt = MilestoneType.query.get(id) - if not mt: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") + mt = MilestoneType.query.get(id) + if not mt: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") - if 'name' in data and data['name']: - mt.name = str(data['name']).strip() - if 'code' in data and data['code']: - code = str(data['code']).strip().lower().replace(' ', '_') - existing = MilestoneType.query.filter(MilestoneType.code == code, MilestoneType.id != id).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra tipificación con el código {code}.") - mt.code = code - if 'color' in data: - mt.color = str(data['color']).strip() - if 'description' in data: - mt.description = str(data['description']).strip() - if 'sort_order' in data: - try: - mt.sort_order = int(data['sort_order']) - except (ValueError, TypeError): - pass - if 'is_active' in data: - mt.is_active = data['is_active'] in [True, 'true', '1', 'on'] + if 'name' in data and data['name']: + mt.name = str(data['name']).strip() + if 'code' in data and data['code']: + code = str(data['code']).strip().lower().replace(' ', '_') + existing = MilestoneType.query.filter(MilestoneType.code == code, MilestoneType.id != id).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe otra tipificación con el código {code}.") + mt.code = code + if 'color' in data: + mt.color = str(data['color']).strip() + if 'description' in data: + mt.description = str(data['description']).strip() + if 'sort_order' in data: + try: + mt.sort_order = int(data['sort_order']) + except (ValueError, TypeError): + pass + if 'is_active' in data: + mt.is_active = data['is_active'] in [True, 'true', '1', 'on'] - db.session.commit() - return { - 'status': 'success', - 'message': 'Tipificación actualizada correctamente.', - 'milestone_type': mt.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Tipificación actualizada correctamente.', + 'milestone_type': mt.to_dict() + } @academic_router.post("/milestone-types/{id}/toggle") @@ -1339,18 +1308,17 @@ def toggle_milestone_type( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo de una tipificación de hito.""" - with flask_app.app_context(): - mt = MilestoneType.query.get(id) - if not mt: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") - mt.is_active = not mt.is_active - db.session.commit() - return { - 'status': 'success', - 'id': mt.id, - 'is_active': mt.is_active, - 'message': f'Tipificación {"activada" if mt.is_active else "desactivada"} correctamente.' - } + mt = MilestoneType.query.get(id) + if not mt: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") + mt.is_active = not mt.is_active + db.session.commit() + return { + 'status': 'success', + 'id': mt.id, + 'is_active': mt.is_active, + 'message': f'Tipificación {"activada" if mt.is_active else "desactivada"} correctamente.' + } @academic_router.delete("/milestone-types/{id}") @@ -1359,23 +1327,22 @@ def delete_milestone_type( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina o desactiva una tipificación de hito.""" - with flask_app.app_context(): - mt = MilestoneType.query.get(id) - if not mt: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") + mt = MilestoneType.query.get(id) + if not mt: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Tipificación con ID {id} no encontrada.") - milestone_count = AcademicMilestone.query.filter_by(milestone_type_id=id).count() - if milestone_count > 0: - mt.is_active = False - db.session.commit() - return { - 'status': 'success', - 'message': f'La tipificación tiene {milestone_count} hitos registrados. Se ha desactivado en su lugar.' - } - - db.session.delete(mt) + milestone_count = AcademicMilestone.query.filter_by(milestone_type_id=id).count() + if milestone_count > 0: + mt.is_active = False db.session.commit() return { 'status': 'success', - 'message': 'Tipificación eliminada permanentemente.' + 'message': f'La tipificación tiene {milestone_count} hitos registrados. Se ha desactivado en su lugar.' } + + db.session.delete(mt) + db.session.commit() + return { + 'status': 'success', + 'message': 'Tipificación eliminada permanentemente.' + } diff --git a/backend/routers/admin.py b/backend/routers/admin.py index 46f3c6b..f37fe14 100644 --- a/backend/routers/admin.py +++ b/backend/routers/admin.py @@ -15,13 +15,12 @@ from app.models.audit_log import AuditLog from app.models.setting import SystemSetting from app.models.sync_task import MoodleSyncTask from app.services.audit_service import AuditService +from app.services.jwt_service import JWTService from app.services.moodle_queue_service import moodle_queue_service from app.constants.document_types import DOCUMENT_TYPES, validate_document -from dependencies import get_current_user, require_roles -from database import get_flask_app +from dependencies import get_current_user, require_roles, get_token_from_request admin_router = APIRouter(prefix="/api/v1", tags=["Administration & Settings"]) -flask_app = get_flask_app() # ========================================================= @@ -37,48 +36,47 @@ def get_users( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Lista usuarios del sistema con filtros de búsqueda y rol.""" - with flask_app.app_context(): - query = User.query - if search: - s_clean = search.strip().lower() - query = query.filter( - or_( - User.name.ilike(f'%{s_clean}%'), - User.email.ilike(f'%{s_clean}%'), - User.personal_email.ilike(f'%{s_clean}%'), - User.document_number.ilike(f'%{s_clean}%'), - User.first_name.ilike(f'%{s_clean}%'), - User.last_name.ilike(f'%{s_clean}%') - ) + query = User.query + if search: + s_clean = search.strip().lower() + query = query.filter( + or_( + User.name.ilike(f'%{s_clean}%'), + User.email.ilike(f'%{s_clean}%'), + User.personal_email.ilike(f'%{s_clean}%'), + User.document_number.ilike(f'%{s_clean}%'), + User.first_name.ilike(f'%{s_clean}%'), + User.last_name.ilike(f'%{s_clean}%') ) - if role_id: - query = query.filter(User.role_id == role_id) - if status_filter == 'active': - query = query.filter(User.is_active == True) - elif status_filter == 'inactive': - query = query.filter(User.is_active == False) + ) + if role_id: + query = query.filter(User.role_id == role_id) + if status_filter == 'active': + query = query.filter(User.is_active == True) + elif status_filter == 'inactive': + query = query.filter(User.is_active == False) - users = query.order_by(User.id.asc()).all() - roles = Role.query.order_by(Role.name.asc()).all() + users = query.order_by(User.id.asc()).all() + roles = Role.query.order_by(Role.name.asc()).all() - users_data = [] - for u in users: - d = u.to_dict() - d['role_obj'] = { - 'id': u.role_obj.id, - 'name': u.role_obj.name - } if u.role_obj else {'id': 1, 'name': u.role or 'Admin'} - users_data.append(d) + users_data = [] + for u in users: + d = u.to_dict() + d['role_obj'] = { + 'id': u.role_obj.id, + 'name': u.role_obj.name + } if u.role_obj else {'id': 1, 'name': u.role or 'Admin'} + users_data.append(d) - roles_data = [{'id': r.id, 'name': r.name} for r in roles] + roles_data = [{'id': r.id, 'name': r.name} for r in roles] - return { - 'status': 'success', - 'total': len(users_data), - 'users': users_data, - 'roles': roles_data, - 'document_types': DOCUMENT_TYPES - } + return { + 'status': 'success', + 'total': len(users_data), + 'users': users_data, + 'roles': roles_data, + 'document_types': DOCUMENT_TYPES + } @admin_router.post("/users", status_code=status.HTTP_201_CREATED) @@ -95,79 +93,78 @@ async def create_user( form = await request.form() data = dict(form) - with flask_app.app_context(): - email = (data.get('email') or '').strip().lower() - first_name = (data.get('first_name') or '').strip() - last_name = (data.get('last_name') or '').strip() - name = (data.get('name') or f"{first_name} {last_name}").strip() - role_name = (data.get('role') or 'docente').strip().upper() - role_id = data.get('role_id') - phone = (data.get('phone') or '').strip() - personal_email = (data.get('personal_email') or '').strip().lower() - address = (data.get('address') or '').strip() - document_type = (data.get('document_type') or 'DNI').strip().upper() - document_number = (data.get('document_number') or '').strip() - password = data.get('password') - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] + email = (data.get('email') or '').strip().lower() + first_name = (data.get('first_name') or '').strip() + last_name = (data.get('last_name') or '').strip() + name = (data.get('name') or f"{first_name} {last_name}").strip() + role_name = (data.get('role') or 'docente').strip().upper() + role_id = data.get('role_id') + phone = (data.get('phone') or '').strip() + personal_email = (data.get('personal_email') or '').strip().lower() + address = (data.get('address') or '').strip() + document_type = (data.get('document_type') or 'DNI').strip().upper() + document_number = (data.get('document_number') or '').strip() + password = data.get('password') + is_active = data.get('is_active', True) + if isinstance(is_active, str): + is_active = is_active.lower() in ['true', '1', 'on'] - if not email or not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El email y nombre completo son requeridos.") + if not email or not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El email y nombre completo son requeridos.") - if User.query.filter(User.email.ilike(email)).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un usuario con el email {email}.") + if User.query.filter(User.email.ilike(email)).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un usuario con el email {email}.") - if document_number: - is_valid, clean_doc, err_msg = validate_document(document_type, document_number) - if not is_valid: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=err_msg) - document_number = clean_doc + if document_number: + is_valid, clean_doc, err_msg = validate_document(document_type, document_number) + if not is_valid: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=err_msg) + document_number = clean_doc - if User.query.filter_by(document_type=document_type, document_number=document_number).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"El documento {document_type} {document_number} ya está registrado.") + if User.query.filter_by(document_type=document_type, document_number=document_number).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"El documento {document_type} {document_number} ya está registrado.") - user = User( - email=email, - name=name, - first_name=first_name or (name.split()[0] if name else ''), - last_name=last_name or (' '.join(name.split()[1:]) if len(name.split()) > 1 else ''), - phone=phone or None, - personal_email=personal_email or None, - address=address or None, - document_type=document_type, - document_number=document_number, - role=role_name, - role_id=int(role_id) if (role_id and str(role_id).strip().isdigit()) else None, - is_active=bool(is_active) + user = User( + email=email, + name=name, + first_name=first_name or (name.split()[0] if name else ''), + last_name=last_name or (' '.join(name.split()[1:]) if len(name.split()) > 1 else ''), + phone=phone or None, + personal_email=personal_email or None, + address=address or None, + document_type=document_type, + document_number=document_number, + role=role_name, + role_id=int(role_id) if (role_id and str(role_id).strip().isdigit()) else None, + is_active=bool(is_active) + ) + user.set_password(password or 'edu-space2026') + db.session.add(user) + db.session.commit() + + # Encolar creación en Moodle si aplica + try: + username = user.email.split('@')[0].lower() + moodle_queue_service.enqueue_task( + action='CREATE_USER', + entity_type='user', + entity_id=str(user.id), + payload={ + 'username': username, + 'email': user.email, + 'firstname': user.first_name or 'Docente', + 'lastname': user.last_name or 'EduSpace', + 'password': password or 'EduSpace2026*' + } ) - user.set_password(password or 'edu-space2026') - db.session.add(user) - db.session.commit() + except Exception: + pass - # Encolar creación en Moodle si aplica - try: - username = user.email.split('@')[0].lower() - moodle_queue_service.enqueue_task( - action='CREATE_USER', - entity_type='user', - entity_id=str(user.id), - payload={ - 'username': username, - 'email': user.email, - 'firstname': user.first_name or 'Docente', - 'lastname': user.last_name or 'EduSpace', - 'password': password or 'EduSpace2026*' - } - ) - except Exception: - pass - - return { - 'status': 'success', - 'message': 'Usuario creado exitosamente.', - 'user': user.to_dict() - } + return { + 'status': 'success', + 'message': 'Usuario creado exitosamente.', + 'user': user.to_dict() + } @admin_router.get("/users/{id}") @@ -176,19 +173,18 @@ def get_user_detail( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Obtiene el detalle de un usuario por su identificador.""" - with flask_app.app_context(): - user = User.query.get(id) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") - d = user.to_dict() - d['role_obj'] = { - 'id': user.role_obj.id, - 'name': user.role_obj.name - } if user.role_obj else {'id': 1, 'name': user.role or 'Admin'} - return { - 'status': 'success', - 'user': d - } + user = User.query.get(id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") + d = user.to_dict() + d['role_obj'] = { + 'id': user.role_obj.id, + 'name': user.role_obj.name + } if user.role_obj else {'id': 1, 'name': user.role or 'Admin'} + return { + 'status': 'success', + 'user': d + } @admin_router.put("/users/{id}") @@ -205,77 +201,76 @@ async def update_user( form = await request.form() data = dict(form) - with flask_app.app_context(): - user = User.query.get(id) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") + user = User.query.get(id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") - first_name = (data.get('first_name', user.first_name or '')).strip() - last_name = (data.get('last_name', user.last_name or '')).strip() - name = (data.get('name') or '').strip() + first_name = (data.get('first_name', user.first_name or '')).strip() + last_name = (data.get('last_name', user.last_name or '')).strip() + name = (data.get('name') or '').strip() - if 'first_name' in data or 'last_name' in data: - user.first_name = first_name - user.last_name = last_name - user.name = f"{first_name} {last_name}".strip() - elif name: - user.name = name - parts = name.split() - user.first_name = parts[0] if parts else '' - user.last_name = ' '.join(parts[1:]) if len(parts) > 1 else '' + if 'first_name' in data or 'last_name' in data: + user.first_name = first_name + user.last_name = last_name + user.name = f"{first_name} {last_name}".strip() + elif name: + user.name = name + parts = name.split() + user.first_name = parts[0] if parts else '' + user.last_name = ' '.join(parts[1:]) if len(parts) > 1 else '' - if 'phone' in data: - user.phone = (data['phone'] or '').strip() - if 'personal_email' in data: - user.personal_email = (data['personal_email'] or '').strip().lower() - if 'address' in data: - user.address = (data['address'] or '').strip() + if 'phone' in data: + user.phone = (data['phone'] or '').strip() + if 'personal_email' in data: + user.personal_email = (data['personal_email'] or '').strip().lower() + if 'address' in data: + user.address = (data['address'] or '').strip() - if 'document_type' in data or 'document_number' in data: - doc_type = (data.get('document_type') or user.document_type or 'DNI').strip().upper() - doc_num = (data.get('document_number') or user.document_number or '').strip() - if doc_num: - is_valid, clean_doc, err_msg = validate_document(doc_type, doc_num) - if not is_valid: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=err_msg) - doc_num = clean_doc + if 'document_type' in data or 'document_number' in data: + doc_type = (data.get('document_type') or user.document_type or 'DNI').strip().upper() + doc_num = (data.get('document_number') or user.document_number or '').strip() + if doc_num: + is_valid, clean_doc, err_msg = validate_document(doc_type, doc_num) + if not is_valid: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=err_msg) + doc_num = clean_doc - existing_doc = User.query.filter( - User.document_type == doc_type, - User.document_number == doc_num, - User.id != id - ).first() - if existing_doc: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'El documento {doc_type} {doc_num} ya está asignado a otro usuario.') + existing_doc = User.query.filter( + User.document_type == doc_type, + User.document_number == doc_num, + User.id != id + ).first() + if existing_doc: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'El documento {doc_type} {doc_num} ya está asignado a otro usuario.') - user.document_type = doc_type - user.document_number = doc_num + user.document_type = doc_type + user.document_number = doc_num - if 'email' in data and data['email']: - email = data['email'].strip().lower() - existing = User.query.filter(User.email.ilike(email), User.id != id).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'El email {email} ya está registrado por otro usuario.') - user.email = email + if 'email' in data and data['email']: + email = data['email'].strip().lower() + existing = User.query.filter(User.email.ilike(email), User.id != id).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'El email {email} ya está registrado por otro usuario.') + user.email = email - if 'role_id' in data: - r_id = data['role_id'] - user.role_id = int(r_id) if (r_id and str(r_id).strip().isdigit()) else None - if user.role_id: - r_obj = Role.query.get(user.role_id) - if r_obj: - user.role = r_obj.name.upper() + if 'role_id' in data: + r_id = data['role_id'] + user.role_id = int(r_id) if (r_id and str(r_id).strip().isdigit()) else None + if user.role_id: + r_obj = Role.query.get(user.role_id) + if r_obj: + user.role = r_obj.name.upper() - if 'is_active' in data: - val = data['is_active'] - user.is_active = val in [True, 'true', '1', 'on'] + if 'is_active' in data: + val = data['is_active'] + user.is_active = val in [True, 'true', '1', 'on'] - db.session.commit() - return { - 'status': 'success', - 'message': 'Usuario actualizado exitosamente.', - 'user': user.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Usuario actualizado exitosamente.', + 'user': user.to_dict() + } @admin_router.post("/users/{id}/toggle") @@ -284,18 +279,17 @@ def toggle_user( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo/inactivo de un usuario.""" - with flask_app.app_context(): - user = User.query.get(id) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") - user.is_active = not user.is_active - db.session.commit() - return { - 'status': 'success', - 'id': user.id, - 'is_active': user.is_active, - 'message': f'Usuario {"activado" if user.is_active else "desactivado"} correctamente.' - } + user = User.query.get(id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") + user.is_active = not user.is_active + db.session.commit() + return { + 'status': 'success', + 'id': user.id, + 'is_active': user.is_active, + 'message': f'Usuario {"activado" if user.is_active else "desactivado"} correctamente.' + } @admin_router.delete("/users/{id}") @@ -304,27 +298,26 @@ def delete_user( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina permanentemente un usuario o lo desactiva si tiene reservas.""" - with flask_app.app_context(): - user = User.query.get(id) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") + user = User.query.get(id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") - has_reservations = len(user.reservations) if user.reservations else 0 - if has_reservations > 0: - user.is_active = False - db.session.commit() - return { - 'status': 'success', - 'message': 'El usuario tiene reservas asociadas. Se ha desactivado en su lugar.' - } - - db.session.delete(user) + has_reservations = len(user.reservations) if user.reservations else 0 + if has_reservations > 0: + user.is_active = False db.session.commit() return { 'status': 'success', - 'message': 'Usuario eliminado permanentemente.' + 'message': 'El usuario tiene reservas asociadas. Se ha desactivado en su lugar.' } + db.session.delete(user) + db.session.commit() + return { + 'status': 'success', + 'message': 'Usuario eliminado permanentemente.' + } + # ========================================================= # ROLES & RBAC ENDPOINTS @@ -336,42 +329,41 @@ def get_roles( current_user: User = Depends(get_current_user) ): """Lista todos los roles institucionales y sus matrices de permisos por módulo.""" - with flask_app.app_context(): - roles = Role.query.order_by(Role.id.asc()).all() - modules = [ - {'id': 'dashboard', 'name': 'Dashboard', 'icon': 'bi-speedometer2'}, - {'id': 'classrooms', 'name': 'Aulas y Espacios', 'icon': 'bi-door-open'}, - {'id': 'schedule', 'name': 'Cronograma', 'icon': 'bi-calendar3'}, - {'id': 'subjects', 'name': 'Asignaturas', 'icon': 'bi-book'}, - {'id': 'careers', 'name': 'Carreras', 'icon': 'bi-mortarboard'}, - {'id': 'commissions', 'name': 'Comisiones', 'icon': 'bi-diagram-3'}, - {'id': 'users', 'name': 'Usuarios', 'icon': 'bi-people'}, - {'id': 'roles', 'name': 'Roles (RBAC)', 'icon': 'bi-shield-check'}, - {'id': 'optimizer', 'name': 'Optimizador IA', 'icon': 'bi-cpu'}, - {'id': 'audit', 'name': 'Auditoría', 'icon': 'bi-clipboard-data'} - ] + roles = Role.query.order_by(Role.id.asc()).all() + modules = [ + {'id': 'dashboard', 'name': 'Dashboard', 'icon': 'bi-speedometer2'}, + {'id': 'classrooms', 'name': 'Aulas y Espacios', 'icon': 'bi-door-open'}, + {'id': 'schedule', 'name': 'Cronograma', 'icon': 'bi-calendar3'}, + {'id': 'subjects', 'name': 'Asignaturas', 'icon': 'bi-book'}, + {'id': 'careers', 'name': 'Carreras', 'icon': 'bi-mortarboard'}, + {'id': 'commissions', 'name': 'Comisiones', 'icon': 'bi-diagram-3'}, + {'id': 'users', 'name': 'Usuarios', 'icon': 'bi-people'}, + {'id': 'roles', 'name': 'Roles (RBAC)', 'icon': 'bi-shield-check'}, + {'id': 'optimizer', 'name': 'Optimizador IA', 'icon': 'bi-cpu'}, + {'id': 'audit', 'name': 'Auditoría', 'icon': 'bi-clipboard-data'} + ] - roles_data = [] - for r in roles: - perms_map = {} - for p in r.permissions: - perms_map[p.module] = p.access_level + roles_data = [] + for r in roles: + perms_map = {} + for p in r.permissions: + perms_map[p.module] = p.access_level - roles_data.append({ - 'id': r.id, - 'name': r.name, - 'description': r.description or f'Rol institucional de {r.name}', - 'is_system': getattr(r, 'is_system', True), - 'users_count': len(r.users) if r.users else 0, - 'users': [{'id': u.id, 'name': u.name} for u in (r.users or [])], - 'permissions': perms_map - }) + roles_data.append({ + 'id': r.id, + 'name': r.name, + 'description': r.description or f'Rol institucional de {r.name}', + 'is_system': getattr(r, 'is_system', True), + 'users_count': len(r.users) if r.users else 0, + 'users': [{'id': u.id, 'name': u.name} for u in (r.users or [])], + 'permissions': perms_map + }) - return { - 'status': 'success', - 'roles': roles_data, - 'modules': modules - } + return { + 'status': 'success', + 'roles': roles_data, + 'modules': modules + } @admin_router.post("/roles", status_code=status.HTTP_201_CREATED) @@ -387,40 +379,39 @@ async def create_role( form = await request.form() data = dict(form) - with flask_app.app_context(): - name = (data.get('name') or '').strip() - description = (data.get('description') or '').strip() - raw_perms = data.get('permissions', {}) - if isinstance(raw_perms, str): - try: - import json - permissions = json.loads(raw_perms) - except Exception: - permissions = {} - elif isinstance(raw_perms, dict): - permissions = raw_perms - else: + name = (data.get('name') or '').strip() + description = (data.get('description') or '').strip() + raw_perms = data.get('permissions', {}) + if isinstance(raw_perms, str): + try: + import json + permissions = json.loads(raw_perms) + except Exception: permissions = {} + elif isinstance(raw_perms, dict): + permissions = raw_perms + else: + permissions = {} - if not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del rol es obligatorio.") + if not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del rol es obligatorio.") - if Role.query.filter(Role.name.ilike(name)).first(): - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un rol llamado {name}.") + if Role.query.filter(Role.name.ilike(name)).first(): + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Ya existe un rol llamado {name}.") - role = Role(name=name, description=description, is_system=False) - db.session.add(role) - db.session.flush() + role = Role(name=name, description=description, is_system=False) + db.session.add(role) + db.session.flush() - for mod, level in permissions.items(): - role.set_permission(mod, level) + for mod, level in permissions.items(): + role.set_permission(mod, level) - db.session.commit() - return { - 'status': 'success', - 'message': 'Rol creado exitosamente.', - 'role': role.to_dict() - } + db.session.commit() + return { + 'status': 'success', + 'message': 'Rol creado exitosamente.', + 'role': role.to_dict() + } @admin_router.delete("/roles/{id}") @@ -429,25 +420,25 @@ def delete_role( current_user: User = Depends(require_roles(["ADMIN"])) ): """Elimina un rol del sistema.""" - with flask_app.app_context(): - role = Role.query.get(id) - if not role: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Rol con ID {id} no encontrado.") - if getattr(role, 'is_system', False): - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No se pueden eliminar roles protegidos del sistema.") + role = Role.query.get(id) + if not role: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Rol con ID {id} no encontrado.") + if getattr(role, 'is_system', False): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No se pueden eliminar roles protegidos del sistema.") - db.session.delete(role) - db.session.commit() - return { - 'status': 'success', - 'message': 'Rol eliminado permanentemente.' - } + db.session.delete(role) + db.session.commit() + return { + 'status': 'success', + 'message': 'Rol eliminado permanentemente.' + } # ========================================================= # IMPERSONATION ENDPOINTS # ========================================================= +@admin_router.post("/impersonate") @admin_router.post("/admin/impersonate") async def impersonate_user( request: Request, @@ -461,52 +452,66 @@ async def impersonate_user( form = await request.form() data = dict(form) - with flask_app.app_context(): - user_id = data.get('user_id') - if not user_id: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Se requiere el user_id para impersonar.") + user_id = data.get('user_id') or data.get('target_user_id') + if not user_id: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Se requiere el user_id para impersonar.") - target_user = User.query.get(int(user_id)) - if not target_user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario destino #{user_id} no encontrado.") + target_user = User.query.get(int(user_id)) + if not target_user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario destino #{user_id} no encontrado.") - AuditService.log( - action='IMPERSONATE_START', - module='admin', - entity_id=target_user.id, - user=current_user, - details=f"Administrador {current_user.email} inició sesión como {target_user.email} ({target_user.role})" - ) + AuditService.log( + action='IMPERSONATE_START', + module='admin', + entity_id=target_user.id, + user=current_user, + details=f"Administrador {current_user.email} inició sesión temporal como {target_user.email} ({target_user.role})" + ) - return { - 'status': 'success', - 'message': f"Iniciando impersonación de {target_user.name} ({target_user.email})", - 'user': { - 'id': target_user.id, - 'name': target_user.name, - 'email': target_user.email, - 'role': target_user.role - } - } + target_dict = { + 'id': target_user.id, + 'name': target_user.name, + 'email': target_user.email, + 'role': target_user.role + } + + return { + 'status': 'success', + 'message': f"Iniciando impersonación de {target_user.name} ({target_user.email})", + 'user': target_dict, + 'target_user': target_dict + } +@admin_router.post("/stop-impersonating") @admin_router.post("/admin/stop-impersonating") def stop_impersonating( + request: Request, current_user: User = Depends(get_current_user) ): """Restaura la sesión administrativa original.""" - with flask_app.app_context(): - AuditService.log( - action='IMPERSONATE_STOP', - module='admin', - entity_id=current_user.id, - user=current_user, - details=f"Finalizó la sesión de impersonación. Sesión restaurada a {current_user.email}." - ) - return { - 'status': 'success', - 'message': 'Sesión de impersonación finalizada exitosamente.' - } + real_admin_id = current_user.id + token = get_token_from_request(request) + if token: + try: + payload = JWTService.decode_token(token, expected_type='access') + if payload.get('sub'): + real_admin_id = int(payload['sub']) + except Exception: + pass + + AuditService.log( + action='IMPERSONATE_END', + module='admin', + entity_id=current_user.id, + user_id=real_admin_id, + user_email=current_user.email, + details=f"Finalizó la sesión de impersonación." + ) + return { + 'status': 'success', + 'message': 'Sesión de impersonación finalizada exitosamente.' + } # ========================================================= @@ -538,76 +543,76 @@ async def reset_system( detail="Debe ingresar la contraseña de su usuario administrador para autorizar la reinicialización." ) - with flask_app.app_context(): - # Validar contraseña del administrador - admin = User.query.get(current_user.id) - if not admin or not admin.check_password(password): - try: - AuditService.log( - action='SYSTEM_RESET_FAILED', - module='admin', - entity_id=current_user.id, - user=current_user, - details="Intento de reinicialización del sistema cancelado: contraseña incorrecta." - ) - except Exception: - pass - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Contraseña de administrador incorrecta. Operación cancelada por seguridad." + # Validar contraseña del administrador + admin = User.query.get(current_user.id) + if not admin or not admin.check_password(password): + try: + AuditService.log( + action='SYSTEM_RESET_FAILED', + module='admin', + entity_id=current_user.id, + user=current_user, + details="Intento de reinicialización del sistema cancelado: contraseña incorrecta." ) - - from app.models.reservation import Reservation - from app.models.grade import MilestoneGrade - from app.models.enrollment import StudentEnrollment - from app.models.classroom import Classroom, ClassroomResource - from app.models.building import Building - from app.models.subject import Subject, Commission, CommissionTeacher - from app.models.career import Career - from app.models.academic_term import AcademicTerm - - reservations_deleted = Reservation.query.delete() - grades_deleted = MilestoneGrade.query.delete() - milestones_deleted = AcademicMilestone.query.delete() - enrollments_deleted = StudentEnrollment.query.delete() - teachers_deleted = CommissionTeacher.query.delete() - commissions_deleted = Commission.query.delete() - subjects_deleted = Subject.query.delete() - careers_deleted = Career.query.delete() - resources_deleted = ClassroomResource.query.delete() - classrooms_deleted = Classroom.query.delete() - buildings_deleted = Building.query.delete() - terms_deleted = AcademicTerm.query.delete() - moodle_deleted = MoodleSyncTask.query.delete() - - db.session.commit() - - AuditService.log( - action='SYSTEM_RESET_SUCCESS', - module='admin', - entity_id=current_user.id, - user=current_user, - details=f"Sistema reinicializado. Purgados: {reservations_deleted} reservas, {classrooms_deleted} aulas, {subjects_deleted} materias." + except Exception: + pass + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Contraseña de administrador incorrecta. Operación cancelada por seguridad." ) - return { - 'status': 'success', - 'message': 'El sistema ha sido reinicializado exitosamente. Todos los usuarios, roles y configuraciones fueron preservados.', - 'purged': { - 'reservations': reservations_deleted, - 'grades': grades_deleted, - 'milestones': milestones_deleted, - 'enrollments': enrollments_deleted, - 'teachers_assignments': teachers_deleted, - 'commissions': commissions_deleted, - 'subjects': subjects_deleted, - 'careers': careers_deleted, - 'classrooms': classrooms_deleted, - 'buildings': buildings_deleted, - 'academic_terms': terms_deleted, - 'sync_tasks': moodle_deleted - } + from app.models.reservation import Reservation + from app.models.grade import MilestoneGrade + from app.models.enrollment import StudentEnrollment + from app.models.classroom import Classroom, ClassroomResource + from app.models.building import Building + from app.models.subject import Subject, Commission, CommissionTeacher + from app.models.career import Career + from app.models.academic_term import AcademicTerm + from app.models.milestone import AcademicMilestone + + reservations_deleted = Reservation.query.delete() + grades_deleted = MilestoneGrade.query.delete() + milestones_deleted = AcademicMilestone.query.delete() + enrollments_deleted = StudentEnrollment.query.delete() + teachers_deleted = CommissionTeacher.query.delete() + commissions_deleted = Commission.query.delete() + subjects_deleted = Subject.query.delete() + careers_deleted = Career.query.delete() + resources_deleted = ClassroomResource.query.delete() + classrooms_deleted = Classroom.query.delete() + buildings_deleted = Building.query.delete() + terms_deleted = AcademicTerm.query.delete() + moodle_deleted = MoodleSyncTask.query.delete() + + db.session.commit() + + AuditService.log( + action='SYSTEM_RESET', + module='admin', + entity_id=current_user.id, + user=current_user, + details=f"Sistema reinicializado. Purgados: {reservations_deleted} reservas, {classrooms_deleted} aulas, {subjects_deleted} materias." + ) + + return { + 'status': 'success', + 'message': 'El sistema ha sido reinicializado exitosamente. Todos los usuarios, roles y configuraciones fueron preservados.', + 'purged': { + 'reservations': reservations_deleted, + 'grades': grades_deleted, + 'milestones': milestones_deleted, + 'enrollments': enrollments_deleted, + 'teachers_assignments': teachers_deleted, + 'commissions': commissions_deleted, + 'subjects': subjects_deleted, + 'careers': careers_deleted, + 'classrooms': classrooms_deleted, + 'buildings': buildings_deleted, + 'academic_terms': terms_deleted, + 'sync_tasks': moodle_deleted } + } # ========================================================= @@ -625,13 +630,23 @@ def get_audit_logs( current_user: User = Depends(require_roles(["ADMIN"])) ): """Consulta la bitácora inmutable de auditoría del sistema.""" - with flask_app.app_context(): - logs = AuditService.get_logs(module=module, action=action, user_id=user_id, limit=limit) - return { - 'status': 'success', - 'total': len(logs), - 'logs': [log.to_dict() for log in logs] + logs = AuditService.get_logs(module=module, action=action, user_id=user_id, limit=limit) + distinct_modules = [m[0] for m in db.session.query(AuditLog.module).distinct().all() if m[0]] + distinct_actions = [a[0] for a in db.session.query(AuditLog.action).distinct().all() if a[0]] + all_modules = sorted(list(set(distinct_modules + ['auth', 'admin', 'reservations', 'classrooms', 'buildings', 'academic', 'moodle']))) + all_actions = sorted(list(set(distinct_actions + ['LOGIN', 'LOGIN_FAILED', 'LOGOUT', 'CREATE', 'UPDATE', 'DELETE', 'IMPERSONATE_START', 'IMPERSONATE_END']))) + return { + 'status': 'success', + 'total': len(logs), + 'logs': [log.to_dict() for log in logs], + 'modules': all_modules, + 'actions': all_actions, + 'pagination': { + 'page': 1, + 'per_page': limit, + 'total': len(logs) } + } # ========================================================= @@ -672,27 +687,26 @@ async def reset_user_password( detail="La nueva contraseña debe contener al menos 6 caracteres." ) - with flask_app.app_context(): - user = User.query.get(id) - if not user: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") + user = User.query.get(id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Usuario con ID {id} no encontrado.") - user.set_password(new_password) - db.session.commit() + user.set_password(new_password) + db.session.commit() - AuditService.log( - action='RESET_PASSWORD', - module='users', - entity_id=user.id, - user=current_user, - details=f"Contraseña restablecida para el usuario {user.email}" - ) + AuditService.log( + action='RESET_PASSWORD', + module='users', + entity_id=user.id, + user=current_user, + details=f"Contraseña restablecida para el usuario {user.email}" + ) - return { - 'status': 'success', - 'message': f'Contraseña restablecida exitosamente para {user.name}.', - 'user_id': user.id - } + return { + 'status': 'success', + 'message': f'Contraseña restablecida exitosamente para {user.name}.', + 'user_id': user.id + } # ========================================================= @@ -703,56 +717,55 @@ async def reset_user_password( @admin_router.get("/admin/settings/all") def get_all_settings(current_user: User = Depends(require_roles(["ADMIN"]))): """Retorna todas las configuraciones agrupadas por módulo, enmascarando contraseñas.""" - with flask_app.app_context(): - smtp_config = { - 'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'), - 'port': int(SystemSetting.get_value('smtp_port', 587) or 587), - 'user': SystemSetting.get_value('smtp_user', ''), - 'password': SystemSetting.get_masked_value('smtp_password', ''), - 'security': SystemSetting.get_value('smtp_security', 'STARTTLS'), - 'sender_email': SystemSetting.get_value('smtp_sender_email', 'notificaciones@unicaba.edu.ar'), - 'sender_name': SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA'), - 'enabled': SystemSetting.get_value('smtp_enabled', 'true') in ['true', 'True', '1', True] - } + smtp_config = { + 'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'), + 'port': int(SystemSetting.get_value('smtp_port', 587) or 587), + 'user': SystemSetting.get_value('smtp_user', ''), + 'password': SystemSetting.get_masked_value('smtp_password', ''), + 'security': SystemSetting.get_value('smtp_security', 'STARTTLS'), + 'sender_email': SystemSetting.get_value('smtp_sender_email', 'notificaciones@unicaba.edu.ar'), + 'sender_name': SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA'), + 'enabled': SystemSetting.get_value('smtp_enabled', 'true') in ['true', 'True', '1', True] + } - auth_providers = { - 'local': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'local_enabled': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], - 'google': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'google_enabled': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], - 'moodle': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True], - 'moodle_enabled': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True] - } + auth_providers = { + 'local': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], + 'local_enabled': SystemSetting.get_value('auth_local_enabled', 'true') in ['true', 'True', '1', True], + 'google': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], + 'google_enabled': SystemSetting.get_value('auth_google_enabled', 'false') in ['true', 'True', '1', True], + 'moodle': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True], + 'moodle_enabled': SystemSetting.get_value('auth_moodle_enabled', 'false') in ['true', 'True', '1', True] + } - google_oauth = { - 'client_id': SystemSetting.get_value('google_client_id', ''), - 'client_secret': SystemSetting.get_masked_value('google_client_secret', ''), - 'callback_url': SystemSetting.get_value('google_callback_url', '/auth/google/callback'), - 'allowed_domains': SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar,lasalle.edu.ar') - } + google_oauth = { + 'client_id': SystemSetting.get_value('google_client_id', ''), + 'client_secret': SystemSetting.get_masked_value('google_client_secret', ''), + 'callback_url': SystemSetting.get_value('google_callback_url', '/auth/google/callback'), + 'allowed_domains': SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar,lasalle.edu.ar') + } - moodle_config = { - 'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'), - 'ws_token': SystemSetting.get_masked_value('moodle_ws_token', ''), - 'timeout': int(SystemSetting.get_value('moodle_timeout', 10) or 10), - 'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True], - 'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15) or 15) - } + moodle_config = { + 'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'), + 'ws_token': SystemSetting.get_masked_value('moodle_ws_token', ''), + 'timeout': int(SystemSetting.get_value('moodle_timeout', 10) or 10), + 'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True], + 'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15) or 15) + } - ui_config = { - 'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True] - } + ui_config = { + 'show_role_banner': SystemSetting.get_value('dashboard_role_banner_enabled', 'true') in ['true', 'True', '1', True] + } - return { - 'status': 'success', - 'settings': { - 'smtp': smtp_config, - 'auth_providers': auth_providers, - 'google_oauth': google_oauth, - 'moodle': moodle_config, - 'ui': ui_config - } + return { + 'status': 'success', + 'settings': { + 'smtp': smtp_config, + 'auth_providers': auth_providers, + 'google_oauth': google_oauth, + 'moodle': moodle_config, + 'ui': ui_config } + } @admin_router.post("/settings/smtp") @@ -778,28 +791,27 @@ async def update_smtp_settings( sender_name = str(data.get('sender_name', 'Edu-Space UniCABA')).strip() enabled = 'true' if data.get('enabled') in [True, 'true', '1', 'on'] else 'false' - with flask_app.app_context(): - SystemSetting.set_value('smtp_host', host, 'Host del servidor SMTP', category='smtp') - SystemSetting.set_value('smtp_port', port, 'Puerto del servidor SMTP', category='smtp') - SystemSetting.set_value('smtp_user', user, 'Usuario o email de autenticación SMTP', category='smtp') - if password and password != '••••••••••••': - SystemSetting.set_encrypted_value('smtp_password', password, 'Contraseña de autenticación SMTP cifrada', category='smtp') - SystemSetting.set_value('smtp_security', security, 'Protocolo de seguridad SMTP (NONE, SSL, STARTTLS)', category='smtp') - SystemSetting.set_value('smtp_sender_email', sender_email, 'Email remitente oficial', category='smtp') - SystemSetting.set_value('smtp_sender_name', sender_name, 'Nombre remitente oficial', category='smtp') - SystemSetting.set_value('smtp_enabled', enabled, 'Habilitación del servicio SMTP', category='smtp') + SystemSetting.set_value('smtp_host', host, 'Host del servidor SMTP', category='smtp') + SystemSetting.set_value('smtp_port', port, 'Puerto del servidor SMTP', category='smtp') + SystemSetting.set_value('smtp_user', user, 'Usuario o email de autenticación SMTP', category='smtp') + if password and password != '••••••••••••': + SystemSetting.set_encrypted_value('smtp_password', password, 'Contraseña de autenticación SMTP cifrada', category='smtp') + SystemSetting.set_value('smtp_security', security, 'Protocolo de seguridad SMTP (NONE, SSL, STARTTLS)', category='smtp') + SystemSetting.set_value('smtp_sender_email', sender_email, 'Email remitente oficial', category='smtp') + SystemSetting.set_value('smtp_sender_name', sender_name, 'Nombre remitente oficial', category='smtp') + SystemSetting.set_value('smtp_enabled', enabled, 'Habilitación del servicio SMTP', category='smtp') - AuditService.log( - action='UPDATE_SMTP_SETTINGS', - module='settings', - user=current_user, - details=f"Configuración SMTP actualizada (Host: {host}:{port}, Remitente: {sender_email})" - ) + AuditService.log( + action='UPDATE_SMTP_SETTINGS', + module='settings', + user=current_user, + details=f"Configuración SMTP actualizada (Host: {host}:{port}, Remitente: {sender_email})" + ) - return { - 'status': 'success', - 'message': 'Configuración de servidor SMTP guardada exitosamente.' - } + return { + 'status': 'success', + 'message': 'Configuración de servidor SMTP guardada exitosamente.' + } @admin_router.post("/settings/smtp/test") @@ -822,64 +834,63 @@ async def test_smtp_connection( test_recipient = str(data.get('test_email') or current_user.email).strip() - with flask_app.app_context(): - host = data.get('host') or SystemSetting.get_value('smtp_host', 'smtp.gmail.com') - port = int(data.get('port') or SystemSetting.get_value('smtp_port', 587) or 587) - user = data.get('user') or SystemSetting.get_value('smtp_user', '') - password = data.get('password') - if not password or password == '••••••••••••': - password = SystemSetting.get_decrypted_value('smtp_password', '') - security_val = data.get('security') or SystemSetting.get_value('smtp_security', 'STARTTLS') or 'STARTTLS' - security = str(security_val).upper() - sender_email = str(data.get('sender_email') or SystemSetting.get_value('smtp_sender_email', user) or 'notificaciones@unicaba.edu.ar') - sender_name = data.get('sender_name') or SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA') + host = data.get('host') or SystemSetting.get_value('smtp_host', 'smtp.gmail.com') + port = int(data.get('port') or SystemSetting.get_value('smtp_port', 587) or 587) + user = data.get('user') or SystemSetting.get_value('smtp_user', '') + password = data.get('password') + if not password or password == '••••••••••••': + password = SystemSetting.get_decrypted_value('smtp_password', '') + security_val = data.get('security') or SystemSetting.get_value('smtp_security', 'STARTTLS') or 'STARTTLS' + security = str(security_val).upper() + sender_email = str(data.get('sender_email') or SystemSetting.get_value('smtp_sender_email', user) or 'notificaciones@unicaba.edu.ar') + sender_name = data.get('sender_name') or SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA') - if not host or not port: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Host y puerto SMTP son requeridos.") + if not host or not port: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Host y puerto SMTP son requeridos.") - try: - if security == 'SSL': - server = smtplib.SMTP_SSL(host, port, timeout=10) - else: - server = smtplib.SMTP(host, port, timeout=10) - if security == 'STARTTLS': - server.ehlo() - server.starttls() - server.ehlo() + try: + if security == 'SSL': + server = smtplib.SMTP_SSL(host, port, timeout=10) + else: + server = smtplib.SMTP(host, port, timeout=10) + if security == 'STARTTLS': + server.ehlo() + server.starttls() + server.ehlo() - if user and password: - server.login(user, password) + if user and password: + server.login(user, password) - if test_recipient: - msg = MIMEMultipart('alternative') - msg['Subject'] = '✔ Prueba de Conexión SMTP - Edu-Space UniCABA' - msg['From'] = f"{sender_name} <{sender_email}>" - msg['To'] = test_recipient + if test_recipient: + msg = MIMEMultipart('alternative') + msg['Subject'] = '✔ Prueba de Conexión SMTP - Edu-Space UniCABA' + msg['From'] = f"{sender_name} <{sender_email}>" + msg['To'] = test_recipient - html_content = f""" -
-

Edu-Space UniCABA

-

Prueba de Conexión SMTP Exitosa

-

Este es un mensaje de prueba para confirmar que los parámetros del servidor de correo han sido configurados correctamente.

-
- Host: {host}:{port}
- Seguridad: {security}
- Usuario: {user or '(Sin autenticación)'}
- Remitente: {sender_email} -
-

Enviado desde el Panel de Administración de UniCABA.

+ html_content = f""" +
+

Edu-Space UniCABA

+

Prueba de Conexión SMTP Exitosa

+

Este es un mensaje de prueba para confirmar que los parámetros del servidor de correo han sido configurados correctamente.

+
+ Host: {host}:{port}
+ Seguridad: {security}
+ Usuario: {user or '(Sin autenticación)'}
+ Remitente: {sender_email}
- """ - msg.attach(MIMEText(html_content, 'html')) - server.sendmail(sender_email, [test_recipient], msg.as_string()) +

Enviado desde el Panel de Administración de UniCABA.

+
+ """ + msg.attach(MIMEText(html_content, 'html')) + server.sendmail(sender_email, [test_recipient], msg.as_string()) - server.quit() - return { - 'status': 'success', - 'message': f'Conexión SMTP exitosa. Correo de prueba enviado a {test_recipient}.' - } - except Exception as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Fallo en la prueba de conexión SMTP: {str(e)}') + server.quit() + return { + 'status': 'success', + 'message': f'Conexión SMTP exitosa. Correo de prueba enviado a {test_recipient}.' + } + except Exception as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Fallo en la prueba de conexión SMTP: {str(e)}') @admin_router.post("/settings/auth-providers") @@ -904,30 +915,29 @@ async def update_auth_providers( google_val = 'true' if google_input in [True, 'true', '1', 'on'] else 'false' moodle_val = 'true' if moodle_input in [True, 'true', '1', 'on'] else 'false' - with flask_app.app_context(): - SystemSetting.set_value('auth_local_enabled', local_val, 'Habilitar login nativo con usuario/contraseña', category='sso') - SystemSetting.set_value('auth_google_enabled', google_val, 'Habilitar login SSO con Google Workspace', category='sso') - SystemSetting.set_value('auth_moodle_enabled', moodle_val, 'Habilitar login delegado con Moodle', category='sso') + SystemSetting.set_value('auth_local_enabled', local_val, 'Habilitar login nativo con usuario/contraseña', category='sso') + SystemSetting.set_value('auth_google_enabled', google_val, 'Habilitar login SSO con Google Workspace', category='sso') + SystemSetting.set_value('auth_moodle_enabled', moodle_val, 'Habilitar login delegado con Moodle', category='sso') - AuditService.log( - action='UPDATE_AUTH_PROVIDERS', - module='settings', - user=current_user, - details=f"Métodos de login actualizados: Local={local_val}, Google={google_val}, Moodle={moodle_val}" - ) + AuditService.log( + action='UPDATE_AUTH_PROVIDERS', + module='settings', + user=current_user, + details=f"Métodos de login actualizados: Local={local_val}, Google={google_val}, Moodle={moodle_val}" + ) - return { - 'status': 'success', - 'message': 'Métodos de autenticación actualizados correctamente.', - 'auth_providers': { - 'local': local_val == 'true', - 'local_enabled': local_val == 'true', - 'google': google_val == 'true', - 'google_enabled': google_val == 'true', - 'moodle': moodle_val == 'true', - 'moodle_enabled': moodle_val == 'true' - } + return { + 'status': 'success', + 'message': 'Métodos de autenticación actualizados correctamente.', + 'auth_providers': { + 'local': local_val == 'true', + 'local_enabled': local_val == 'true', + 'google': google_val == 'true', + 'google_enabled': google_val == 'true', + 'moodle': moodle_val == 'true', + 'moodle_enabled': moodle_val == 'true' } + } @admin_router.post("/settings/ui") @@ -950,21 +960,20 @@ async def update_ui_settings( show_val = 'true' if show_banner_input in [True, 'true', '1', 'on', 1] else 'false' - with flask_app.app_context(): - SystemSetting.set_value('dashboard_role_banner_enabled', show_val, 'Mostrar banner de saludo y selector de rol en Dashboard', category='ui') - AuditService.log( - action='UPDATE_UI_SETTINGS', - module='settings', - user=current_user, - details=f"Preferencia de interfaz actualizada: banner_saludo_rol={show_val}" - ) - return { - 'status': 'success', - 'message': 'Preferencia de interfaz guardada correctamente.', - 'ui': { - 'show_role_banner': show_val == 'true' - } + SystemSetting.set_value('dashboard_role_banner_enabled', show_val, 'Mostrar banner de saludo y selector de rol en Dashboard', category='ui') + AuditService.log( + action='UPDATE_UI_SETTINGS', + module='settings', + user=current_user, + details=f"Preferencia de interfaz actualizada: banner_saludo_rol={show_val}" + ) + return { + 'status': 'success', + 'message': 'Preferencia de interfaz guardada correctamente.', + 'ui': { + 'show_role_banner': show_val == 'true' } + } @admin_router.get("/settings/demo-mode") @@ -972,15 +981,14 @@ async def update_ui_settings( def get_demo_mode_status(current_user: User = Depends(require_roles(["ADMIN"]))): """Consulta el estado del modo demostración.""" demo_emails = ['bedelia@edu-space.com', 'docente@edu-space.com', 'alumno@edu-space.com'] - with flask_app.app_context(): - demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - demo_accounts_active = any(u.is_active for u in demo_users) - return { - 'status': 'success', - 'demo_access_enabled': demo_access_enabled, - 'demo_accounts_active': demo_accounts_active - } + demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] + demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() + demo_accounts_active = any(u.is_active for u in demo_users) + return { + 'status': 'success', + 'demo_access_enabled': demo_access_enabled, + 'demo_accounts_active': demo_accounts_active + } @admin_router.post("/settings/demo-mode") @@ -999,43 +1007,42 @@ async def toggle_demo_mode( demo_emails = ['bedelia@edu-space.com', 'docente@edu-space.com', 'alumno@edu-space.com'] - with flask_app.app_context(): - if 'enabled' in data: - target_state = data['enabled'] in [True, 'true', '1', 'on'] - else: - current_state = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] - target_state = not current_state + if 'enabled' in data: + target_state = data['enabled'] in [True, 'true', '1', 'on'] + else: + current_state = SystemSetting.get_value('demo_access_enabled', 'true') in ['true', 'True', '1', True] + target_state = not current_state - SystemSetting.set_value( - 'demo_access_enabled', - 'true' if target_state else 'false', - 'Acceso Rápido Demo en pantalla de Login', - category='security' - ) + SystemSetting.set_value( + 'demo_access_enabled', + 'true' if target_state else 'false', + 'Acceso Rápido Demo en pantalla de Login', + category='security' + ) - demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() - for u in demo_users: - u.is_active = target_state - db.session.commit() + demo_users = User.query.filter(func.lower(User.email).in_(demo_emails)).all() + for u in demo_users: + u.is_active = target_state + db.session.commit() - msg_detail = ( - 'Acceso Rápido Demo habilitado y cuentas Bedelía, Docente y Alumno activadas' - if target_state else - 'Acceso Rápido Demo deshabilitado y cuentas default (Bedelía, Docente, Alumno) desactivadas' - ) - AuditService.log( - action='ENABLE_DEMO_ACCOUNTS' if target_state else 'DISABLE_DEMO_ACCOUNTS', - module='settings', - user=current_user, - details=msg_detail - ) + msg_detail = ( + 'Acceso Rápido Demo habilitado y cuentas Bedelía, Docente y Alumno activadas' + if target_state else + 'Acceso Rápido Demo deshabilitado y cuentas default (Bedelía, Docente, Alumno) desactivadas' + ) + AuditService.log( + action='ENABLE_DEMO_ACCOUNTS' if target_state else 'DISABLE_DEMO_ACCOUNTS', + module='settings', + user=current_user, + details=msg_detail + ) - return { - 'status': 'success', - 'message': msg_detail, - 'demo_access_enabled': target_state, - 'demo_accounts_active': target_state - } + return { + 'status': 'success', + 'message': msg_detail, + 'demo_access_enabled': target_state, + 'demo_accounts_active': target_state + } @admin_router.post("/settings/google-oauth") @@ -1057,24 +1064,23 @@ async def update_google_oauth_settings( allowed_domains = str(data.get('allowed_domains', 'unicaba.edu.ar')).strip() callback_url = str(data.get('callback_url', '/auth/google/callback')).strip() - with flask_app.app_context(): - SystemSetting.set_value('google_client_id', client_id, 'Client ID de Google OAuth2', category='sso_google') - if client_secret and client_secret != '••••••••••••': - SystemSetting.set_encrypted_value('google_client_secret', client_secret, 'Client Secret de Google OAuth2 cifrado', category='sso_google') - SystemSetting.set_value('google_allowed_domains', allowed_domains, 'Dominios permitidos separados por coma', category='sso_google') - SystemSetting.set_value('google_callback_url', callback_url, 'Ruta de callback autorizada de Google OAuth2', category='sso_google') + SystemSetting.set_value('google_client_id', client_id, 'Client ID de Google OAuth2', category='sso_google') + if client_secret and client_secret != '••••••••••••': + SystemSetting.set_encrypted_value('google_client_secret', client_secret, 'Client Secret de Google OAuth2 cifrado', category='sso_google') + SystemSetting.set_value('google_allowed_domains', allowed_domains, 'Dominios permitidos separados por coma', category='sso_google') + SystemSetting.set_value('google_callback_url', callback_url, 'Ruta de callback autorizada de Google OAuth2', category='sso_google') - AuditService.log( - action='UPDATE_GOOGLE_OAUTH_SETTINGS', - module='settings', - user=current_user, - details="Credenciales de Google OAuth2 actualizadas" - ) + AuditService.log( + action='UPDATE_GOOGLE_OAUTH_SETTINGS', + module='settings', + user=current_user, + details="Credenciales de Google OAuth2 actualizadas" + ) - return { - 'status': 'success', - 'message': 'Credenciales de Google OAuth2 guardadas correctamente.' - } + return { + 'status': 'success', + 'message': 'Credenciales de Google OAuth2 guardadas correctamente.' + } @admin_router.post("/settings/moodle") @@ -1097,25 +1103,24 @@ async def update_moodle_settings( auto_sync = 'true' if data.get('auto_sync_enabled', True) in [True, 'true', '1', 'on'] else 'false' sync_interval = str(data.get('sync_interval_minutes', 15)).strip() - with flask_app.app_context(): - SystemSetting.set_value('moodle_server_url', server_url, 'URL base del servidor Moodle', category='sso_moodle') - if ws_token and ws_token != '••••••••••••': - SystemSetting.set_encrypted_value('moodle_ws_token', ws_token, 'Token de Web Services de Moodle cifrado', category='sso_moodle') - SystemSetting.set_value('moodle_timeout', timeout, 'Timeout en segundos para llamadas REST a Moodle', category='sso_moodle') - SystemSetting.set_value('moodle_auto_sync_enabled', auto_sync, 'Habilitación de sincronización periódica automática', category='sso_moodle') - SystemSetting.set_value('moodle_sync_interval_minutes', sync_interval, 'Intervalo en minutos para sincronización periódica', category='sso_moodle') + SystemSetting.set_value('moodle_server_url', server_url, 'URL base del servidor Moodle', category='sso_moodle') + if ws_token and ws_token != '••••••••••••': + SystemSetting.set_encrypted_value('moodle_ws_token', ws_token, 'Token de Web Services de Moodle cifrado', category='sso_moodle') + SystemSetting.set_value('moodle_timeout', timeout, 'Timeout en segundos para llamadas REST a Moodle', category='sso_moodle') + SystemSetting.set_value('moodle_auto_sync_enabled', auto_sync, 'Habilitación de sincronización periódica automática', category='sso_moodle') + SystemSetting.set_value('moodle_sync_interval_minutes', sync_interval, 'Intervalo en minutos para sincronización periódica', category='sso_moodle') - AuditService.log( - action='UPDATE_MOODLE_SETTINGS', - module='settings', - user=current_user, - details=f"Parámetros de Moodle actualizados (Servidor: {server_url})" - ) + AuditService.log( + action='UPDATE_MOODLE_SETTINGS', + module='settings', + user=current_user, + details=f"Parámetros de Moodle actualizados (Servidor: {server_url})" + ) - return { - 'status': 'success', - 'message': 'Configuración de Moodle 4.1 guardada correctamente.' - } + return { + 'status': 'success', + 'message': 'Configuración de Moodle 4.1 guardada correctamente.' + } @admin_router.post("/settings/moodle/test") @@ -1136,12 +1141,11 @@ async def test_moodle_connection( server_url = data.get('server_url') token = data.get('ws_token') - with flask_app.app_context(): - result = moodle_client.test_connection(server_url=server_url, token=token) - if result.get('success'): - return result - else: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=result.get('message', 'Fallo de conexión a Moodle')) + result = moodle_client.test_connection(server_url=server_url, token=token) + if result.get('success'): + return result + else: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=result.get('message', 'Fallo de conexión a Moodle')) @admin_router.get("/settings/moodle/api-key") @@ -1149,18 +1153,17 @@ async def test_moodle_connection( def get_moodle_api_key(current_user: User = Depends(require_roles(["ADMIN"]))): """Retorna o genera la API Key institucional para Moodle.""" import secrets - with flask_app.app_context(): - api_key = SystemSetting.get_decrypted_value('moodle_api_key', '') - if not api_key: - api_key = secrets.token_hex(32) - SystemSetting.set_encrypted_value('moodle_api_key', api_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') + api_key = SystemSetting.get_decrypted_value('moodle_api_key', '') + if not api_key: + api_key = secrets.token_hex(32) + SystemSetting.set_encrypted_value('moodle_api_key', api_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') - return { - 'status': 'success', - 'api_key': api_key, - 'header_name': 'X-API-Key', - 'sync_endpoint': '/api/v1/admin/settings/moodle/sync' - } + return { + 'status': 'success', + 'api_key': api_key, + 'header_name': 'X-API-Key', + 'sync_endpoint': '/api/v1/admin/settings/moodle/sync' + } @admin_router.post("/settings/moodle/api-key/regenerate") @@ -1168,14 +1171,13 @@ def get_moodle_api_key(current_user: User = Depends(require_roles(["ADMIN"]))): def regenerate_moodle_api_key(current_user: User = Depends(require_roles(["ADMIN"]))): """Regenera una nueva clave API de comunicación bidireccional con Moodle.""" import secrets - with flask_app.app_context(): - new_key = secrets.token_hex(32) - SystemSetting.set_encrypted_value('moodle_api_key', new_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') - return { - 'status': 'success', - 'api_key': new_key, - 'message': 'Clave API de Moodle regenerada exitosamente.' - } + new_key = secrets.token_hex(32) + SystemSetting.set_encrypted_value('moodle_api_key', new_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle') + return { + 'status': 'success', + 'api_key': new_key, + 'message': 'Clave API de Moodle regenerada exitosamente.' + } @admin_router.post("/moodle/sync-from-moodle") @@ -1184,12 +1186,11 @@ def regenerate_moodle_api_key(current_user: User = Depends(require_roles(["ADMIN def sync_data_from_moodle(current_user: User = Depends(require_roles(["ADMIN"]))): """Ejecuta la sincronización bidireccional desde Moodle hacia la plataforma.""" from app.services.moodle_client import moodle_client - with flask_app.app_context(): - try: - res = moodle_client.sync_from_moodle_to_app() - return res - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error al sincronizar desde Moodle: {str(e)}") + try: + res = moodle_client.sync_from_moodle_to_app() + return res + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error al sincronizar desde Moodle: {str(e)}") # ========================================================= @@ -1200,12 +1201,11 @@ def sync_data_from_moodle(current_user: User = Depends(require_roles(["ADMIN"])) @admin_router.get("/admin/moodle/queue/stats") def get_moodle_queue_stats(current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))): """Estadísticas en tiempo real de la cola asíncrona de Moodle.""" - with flask_app.app_context(): - stats = moodle_queue_service.get_queue_summary() - return { - 'status': 'success', - 'data': stats - } + stats = moodle_queue_service.get_queue_summary() + return { + 'status': 'success', + 'data': stats + } @admin_router.get("/moodle/queue/tasks") @@ -1217,21 +1217,20 @@ def get_moodle_queue_tasks( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Listado paginado de tareas en cola con filtro por estado.""" - with flask_app.app_context(): - query = MoodleSyncTask.query - if status_filter: - query = query.filter_by(status=status_filter.strip().upper()) + query = MoodleSyncTask.query + if status_filter: + query = query.filter_by(status=status_filter.strip().upper()) - total = query.count() - tasks = query.order_by(MoodleSyncTask.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all() + total = query.count() + tasks = query.order_by(MoodleSyncTask.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all() - return { - 'status': 'success', - 'total': total, - 'page': page, - 'per_page': per_page, - 'tasks': [t.to_dict() for t in tasks] - } + return { + 'status': 'success', + 'total': total, + 'page': page, + 'per_page': per_page, + 'tasks': [t.to_dict() for t in tasks] + } @admin_router.post("/moodle/queue/process-now") @@ -1248,13 +1247,12 @@ async def process_moodle_queue_now( except Exception: pass - with flask_app.app_context(): - results = moodle_queue_service.process_pending_tasks(batch_size=batch_size) - return { - 'status': 'success', - 'message': f"Sincronización procesada: {results['succeeded']} exitosas, {results['failed']} a DLQ, {results['retrying']} reintentando.", - 'results': results - } + results = moodle_queue_service.process_pending_tasks(batch_size=batch_size) + return { + 'status': 'success', + 'message': f"Sincronización procesada: {results['succeeded']} exitosas, {results['failed']} a DLQ, {results['retrying']} reintentando.", + 'results': results + } @admin_router.post("/moodle/queue/tasks/{task_id}/retry") @@ -1264,27 +1262,25 @@ def retry_moodle_queue_task( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Reintenta una tarea específica en Dead Letter Queue.""" - with flask_app.app_context(): - success = moodle_queue_service.retry_task(task_id) - if success: - return { - 'status': 'success', - 'message': f'Tarea #{task_id} reiniciada a estado PENDIENTE para el próximo ciclo.' - } - else: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'No se encontró la tarea #{task_id}.') + success = moodle_queue_service.retry_task(task_id) + if success: + return { + 'status': 'success', + 'message': f'Tarea #{task_id} reiniciada a estado PENDIENTE para el próximo ciclo.' + } + else: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'No se encontró la tarea #{task_id}.') @admin_router.post("/moodle/queue/retry-all") @admin_router.post("/admin/moodle/queue/retry-all") def retry_all_failed_moodle_tasks(current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))): """Reintenta todas las tareas fallidas en DLQ.""" - with flask_app.app_context(): - count = moodle_queue_service.retry_all_failed() - return { - 'status': 'success', - 'message': f'Se reiniciaron {count} tareas fallidas a estado PENDIENTE.' - } + count = moodle_queue_service.retry_all_failed() + return { + 'status': 'success', + 'message': f'Se reiniciaron {count} tareas fallidas a estado PENDIENTE.' + } # ========================================================= @@ -1298,22 +1294,21 @@ def get_sheets_config(current_user: User = Depends(require_roles(["ADMIN", "BEDE from app.services.sheets_importer import BASE_CSV_URL, normalize_sheets_url import os - with flask_app.app_context(): - db_url = SystemSetting.get_value('google_sheets_url') - env_url = os.getenv('GOOGLE_SHEETS_URL') - active_url = db_url or env_url or BASE_CSV_URL - source = 'database' if db_url else ('environment' if env_url else 'default') + db_url = SystemSetting.get_value('google_sheets_url') + env_url = os.getenv('GOOGLE_SHEETS_URL') + active_url = db_url or env_url or BASE_CSV_URL + source = 'database' if db_url else ('environment' if env_url else 'default') - return { - 'status': 'success', - 'config': { - 'active_url': active_url, - 'source': source, - 'db_url': db_url, - 'default_url': BASE_CSV_URL, - 'normalized_url': normalize_sheets_url(active_url) - } + return { + 'status': 'success', + 'config': { + 'active_url': active_url, + 'source': source, + 'db_url': db_url, + 'default_url': BASE_CSV_URL, + 'normalized_url': normalize_sheets_url(active_url) } + } @admin_router.post("/sheets-config") @@ -1336,19 +1331,18 @@ async def update_sheets_config( if not url: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="La URL de Google Sheets no puede estar vacía.") - with flask_app.app_context(): - normalized = normalize_sheets_url(url) - SystemSetting.set_value('google_sheets_url', url, 'URL del Google Sheet académico configurada desde panel') + normalized = normalize_sheets_url(url) + SystemSetting.set_value('google_sheets_url', url, 'URL del Google Sheet académico configurada desde panel') - return { - 'status': 'success', - 'message': 'Configuración de Google Sheets guardada correctamente.', - 'config': { - 'active_url': url, - 'normalized_url': normalized, - 'source': 'database' - } + return { + 'status': 'success', + 'message': 'Configuración de Google Sheets guardada correctamente.', + 'config': { + 'active_url': url, + 'normalized_url': normalized, + 'source': 'database' } + } @admin_router.post("/reset-academic-data") @@ -1381,29 +1375,28 @@ async def reset_academic_data( reset_careers = True reset_classrooms = True - with flask_app.app_context(): - result = execute_academic_reset( - reset_reservations=reset_reservations, - reset_commissions=reset_commissions, - reset_subjects=reset_subjects, - reset_careers=reset_careers, - reset_classrooms=reset_classrooms - ) + result = execute_academic_reset( + reset_reservations=reset_reservations, + reset_commissions=reset_commissions, + reset_subjects=reset_subjects, + reset_careers=reset_careers, + reset_classrooms=reset_classrooms + ) - if result.get('success'): - AuditService.log( - action='ACADEMIC_DATA_PURGE', - module='admin', - user=current_user, - details=f"Purga académica ejecutada: {result.get('deleted')}" - ) - return { - 'status': 'success', - 'message': result.get('message', 'Datos reiniciados con éxito.'), - 'deleted': result.get('deleted', {}) - } - else: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=result.get('error', 'Error durante la purga de datos.')) + if result.get('success'): + AuditService.log( + action='ACADEMIC_DATA_PURGE', + module='admin', + user=current_user, + details=f"Purga académica ejecutada: {result.get('deleted')}" + ) + return { + 'status': 'success', + 'message': result.get('message', 'Datos reiniciados con éxito.'), + 'deleted': result.get('deleted', {}) + } + else: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=result.get('error', 'Error durante la purga de datos.')) # ========================================================= @@ -1438,18 +1431,17 @@ async def log_client_error(request: Request): 'stack_preview': stack[:500] if stack else '' } - with flask_app.app_context(): - AuditService.log( - action='SYSTEM_ERROR', - module='system', - user_email=user_email, - ip_address=ip_address, - details=details, - status='failed' - ) + AuditService.log( + action='SYSTEM_ERROR', + module='system', + user_email=user_email, + ip_address=ip_address, + details=details, + status='failed' + ) - return { - 'status': 'success', - 'logged': True, - 'incident_id': incident_id - } + return { + 'status': 'success', + 'logged': True, + 'incident_id': incident_id + } diff --git a/backend/routers/auth.py b/backend/routers/auth.py index 1942a4a..b0e9267 100644 --- a/backend/routers/auth.py +++ b/backend/routers/auth.py @@ -18,7 +18,6 @@ from app.services.user_service import UserService from app.services.jwt_service import JWTService from app.services.audit_service import AuditService from dependencies import get_current_user, get_token_from_request -from database import get_flask_app from schemas.auth import ( LoginRequest, GoogleAuthRequest, @@ -30,228 +29,225 @@ from schemas.auth import ( auth_router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"]) user_service = UserService() -flask_app = get_flask_app() @auth_router.get("/providers") def get_auth_providers(): """Retorna los métodos de autenticación habilitados y configuración de cliente Google.""" - with flask_app.app_context(): - local_val = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') - google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1') - moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1') - google_client_id = str(SystemSetting.get_value('google_client_id', '') or '') - demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or 'true').lower() in ('true', '1') + local_val = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') + google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1') + moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1') + google_client_id = str(SystemSetting.get_value('google_client_id', '') or '') + demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or 'true').lower() in ('true', '1') - return { - 'status': 'success', - 'providers': { - 'local': local_val, - 'google': google_val, - 'moodle': moodle_val - }, - 'google_client_id': google_client_id, - 'demo_access_enabled': demo_access_enabled - } + return { + 'status': 'success', + 'providers': { + 'local': local_val, + 'google': google_val, + 'moodle': moodle_val + }, + 'google_client_id': google_client_id, + 'demo_access_enabled': demo_access_enabled + } @auth_router.post("/login") def login(payload: LoginRequest, response: Response): """Inicio de sesión local nativo (Access + Refresh tokens).""" - with flask_app.app_context(): - local_enabled = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') - - user = user_service.authenticate(payload.email, payload.password) - if not user: - AuditService.log( - action='LOGIN_FAILED', - module='auth', - user_email=payload.email, - details=f"Intento de inicio de sesión fallido para {payload.email}. Credenciales incorrectas o cuenta inactiva." - ) - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Credenciales de acceso incorrectas o cuenta inactiva." - ) - - is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN' - if not local_enabled and not is_admin: - AuditService.log( - action='LOGIN_BLOCKED', - module='auth', - user=user, - entity_id=user.id, - details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración." - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle." - ) + local_enabled = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1') + user = user_service.authenticate(payload.email, payload.password) + if not user: AuditService.log( - action='LOGIN', + action='LOGIN_FAILED', + module='auth', + user_email=payload.email, + details=f"Intento de inicio de sesión fallido para {payload.email}. Credenciales incorrectas o cuenta inactiva." + ) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Credenciales de acceso incorrectas o cuenta inactiva." + ) + + is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN' + if not local_enabled and not is_admin: + AuditService.log( + action='LOGIN_BLOCKED', module='auth', user=user, entity_id=user.id, - details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}" + details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración." + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle." ) - tokens = JWTService.generate_tokens(user) - profile = user_service.get_profile_data(user) + AuditService.log( + action='LOGIN', + module='auth', + user=user, + entity_id=user.id, + details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}" + ) - response.set_cookie( - key="access_token", - value=tokens["access_token"], - httponly=True, - samesite="lax", - path="/" - ) - response.set_cookie( - key="refresh_token", - value=tokens["refresh_token"], - httponly=True, - samesite="lax", - max_age=7 * 24 * 3600, - path="/api/v1/auth/refresh" - ) + tokens = JWTService.generate_tokens(user) + profile = user_service.get_profile_data(user) - return { - 'status': 'success', - 'access_token': tokens['access_token'], - 'refresh_token': tokens['refresh_token'], - 'token_type': tokens['token_type'], - 'expires_in': tokens['expires_in'], - 'user': profile - } + response.set_cookie( + key="access_token", + value=tokens["access_token"], + httponly=True, + samesite="lax", + path="/" + ) + response.set_cookie( + key="refresh_token", + value=tokens["refresh_token"], + httponly=True, + samesite="lax", + max_age=7 * 24 * 3600, + path="/api/v1/auth/refresh" + ) + + return { + 'status': 'success', + 'access_token': tokens['access_token'], + 'refresh_token': tokens['refresh_token'], + 'token_type': tokens['token_type'], + 'expires_in': tokens['expires_in'], + 'user': profile + } @auth_router.post("/google") def google_auth(payload: GoogleAuthRequest, response: Response): """Inicio de sesión delegado institucional Google OAuth 2.0.""" - with flask_app.app_context(): - google_enabled = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1') - if not google_enabled: - raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Google no está habilitado.") + google_enabled = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1') + if not google_enabled: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Google no está habilitado.") - email = payload.email.strip().lower() - allowed_domains_str = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or 'unicaba.edu.ar') - allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()] + email = payload.email.strip().lower() + allowed_domains_str = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or 'unicaba.edu.ar') + allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()] - email_domain = email.split('@')[1] if '@' in email else '' - if allowed_domains and email_domain not in allowed_domains: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Dominio @{email_domain} no autorizado. Sólo se permiten cuentas institucionales: {allowed_domains_str}." - ) + email_domain = email.split('@')[1] if '@' in email else '' + if allowed_domains and email_domain not in allowed_domains: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"El dominio @{email_domain} no está autorizado. Sólo se permiten cuentas institucionales: {allowed_domains_str}." + ) - user = User.query.filter(User.email.ilike(email)).first() - if not user: - parts = (payload.name or email.split('@')[0]).split() - first_name = parts[0] if parts else 'Usuario' - last_name = ' '.join(parts[1:]) if len(parts) > 1 else 'Google' - docente_role = Role.query.filter(Role.name.ilike('Docente')).first() - user = User( - email=email, - name=payload.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() + user = User.query.filter(User.email.ilike(email)).first() + if not user: + parts = (payload.name or email.split('@')[0]).split() + first_name = parts[0] if parts else 'Usuario' + last_name = ' '.join(parts[1:]) if len(parts) > 1 else 'Google' + docente_role = Role.query.filter(Role.name.ilike('Docente')).first() + user = User( + email=email, + name=payload.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() - if not user.is_active: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Su cuenta institucional está inactiva.") + if not user.is_active: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Su cuenta institucional está inactiva.") - tokens = JWTService.generate_tokens(user) - profile = user_service.get_profile_data(user) + tokens = JWTService.generate_tokens(user) + profile = user_service.get_profile_data(user) - response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") - return { - 'status': 'success', - 'access_token': tokens['access_token'], - 'refresh_token': tokens['refresh_token'], - 'token_type': tokens['token_type'], - 'expires_in': tokens['expires_in'], - 'user': profile - } + response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") + return { + 'status': 'success', + 'access_token': tokens['access_token'], + 'refresh_token': tokens['refresh_token'], + 'token_type': tokens['token_type'], + 'expires_in': tokens['expires_in'], + 'user': profile + } @auth_router.post("/moodle") def moodle_auth(payload: MoodleAuthRequest, response: Response): """Inicio de sesión delegado con Moodle (verificando DNI o credenciales de campus).""" - with flask_app.app_context(): - moodle_enabled = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1') - if not moodle_enabled: - raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Moodle no está habilitado.") + moodle_enabled = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1') + if not moodle_enabled: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Moodle no está habilitado.") - server_url = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/') - service_name = str(SystemSetting.get_value('moodle_service_name', 'moodle_api') or 'moodle_api') + server_url = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/') + service_name = str(SystemSetting.get_value('moodle_service_name', 'moodle_api') or 'moodle_api') - try: - resp = requests.post(f"{server_url}/login/token.php", data={ - 'username': payload.username, - 'password': payload.password, - 'service': service_name - }, timeout=10) - res_data = resp.json() - except Exception as e: - raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"No se pudo conectar a Moodle: {str(e)}") + try: + resp = requests.post(f"{server_url}/login/token.php", data={ + 'username': payload.username, + 'password': payload.password, + 'service': service_name + }, timeout=10) + res_data = resp.json() + except Exception as e: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"No se pudo conectar a Moodle: {str(e)}") - if 'token' not in res_data: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Credenciales de Moodle inválidas.") + if 'token' not in res_data: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Credenciales de Moodle inválidas.") - username = payload.username.strip() - user = User.query.filter( - (User.email.ilike(f"{username}@%")) | - (User.document_number == username) - ).first() + username = payload.username.strip() + user = User.query.filter( + (User.email.ilike(f"{username}@%")) | + (User.document_number == username) + ).first() - if not user: - role_obj = Role.query.filter(Role.name.ilike('Docente')).first() - user = User( - email=f"{username}@unicaba.edu.ar", - name=username, - document_number=username if username.isdigit() else None, - role=role_obj.name if role_obj else 'Docente', - 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() + if not user: + role_obj = Role.query.filter(Role.name.ilike('Docente')).first() + user = User( + email=f"{username}@unicaba.edu.ar", + name=username, + document_number=username if username.isdigit() else None, + role=role_obj.name if role_obj else 'Docente', + 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() - if not user.is_active: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Su cuenta en Edu-Space está desactivada.") + if not user.is_active: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Su cuenta en Edu-Space está desactivada.") - tokens = JWTService.generate_tokens(user) - profile = user_service.get_profile_data(user) + tokens = JWTService.generate_tokens(user) + profile = user_service.get_profile_data(user) - response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") - return { - 'status': 'success', - 'access_token': tokens['access_token'], - 'refresh_token': tokens['refresh_token'], - 'token_type': tokens['token_type'], - 'expires_in': tokens['expires_in'], - 'user': profile - } + response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") + return { + 'status': 'success', + 'access_token': tokens['access_token'], + 'refresh_token': tokens['refresh_token'], + 'token_type': tokens['token_type'], + 'expires_in': tokens['expires_in'], + 'user': profile + } @auth_router.get("/profile") @auth_router.get("/me") def get_current_user_profile(user: User = Depends(get_current_user)): """Retorna la ficha del perfil del usuario actualmente autenticado.""" - with flask_app.app_context(): - u = User.query.get(user.id) or user - profile = user_service.get_profile_data(u) - return { - 'status': 'success', - 'user': profile - } + u = User.query.get(user.id) or user + profile = user_service.get_profile_data(u) + res = { + 'status': 'success', + 'user': profile + } + if isinstance(profile, dict): + res.update(profile) + return res @auth_router.post("/profile") @@ -260,33 +256,32 @@ def update_profile( user: User = Depends(get_current_user) ): """Actualiza las preferencias de idioma y tema visual del usuario autenticado.""" - with flask_app.app_context(): - u = User.query.get(user.id) - if not u: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Usuario no encontrado.") + u = User.query.get(user.id) + if not u: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Usuario no encontrado.") - if payload.preferred_language in ['es', 'en']: - u.preferred_language = payload.preferred_language - else: - u.preferred_language = None + if payload.preferred_language in ['es', 'en']: + u.preferred_language = payload.preferred_language + else: + u.preferred_language = None - if payload.theme_preference in ['auto', 'light', 'dark']: - u.theme_preference = payload.theme_preference + if payload.theme_preference in ['auto', 'light', 'dark']: + u.theme_preference = payload.theme_preference - db.session.commit() - profile = user_service.get_profile_data(u) - AuditService.log( - action='UPDATE_PROFILE', - module='auth', - user=u, - details={'preferred_language': u.preferred_language, 'theme_preference': u.theme_preference}, - status='success' - ) - return { - 'status': 'success', - 'message': 'Preferencias de usuario actualizadas correctamente.', - 'user': profile - } + db.session.commit() + profile = user_service.get_profile_data(u) + AuditService.log( + action='UPDATE_PROFILE', + module='auth', + user=u, + details={'preferred_language': u.preferred_language, 'theme_preference': u.theme_preference}, + status='success' + ) + return { + 'status': 'success', + 'message': 'Preferencias de usuario actualizadas correctamente.', + 'user': profile + } @auth_router.post("/theme") @@ -295,20 +290,19 @@ def update_theme( user: User = Depends(get_current_user) ): """Actualiza el tema visual del usuario desde la interfaz (AJAX).""" - with flask_app.app_context(): - u = User.query.get(user.id) - if not u: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Usuario no encontrado.") + u = User.query.get(user.id) + if not u: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Usuario no encontrado.") - if payload.theme not in ['auto', 'light', 'dark']: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Tema visual inválido.") + if payload.theme not in ['auto', 'light', 'dark']: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Tema visual inválido.") - u.theme_preference = payload.theme - db.session.commit() - return { - 'status': 'success', - 'theme': u.theme_preference - } + u.theme_preference = payload.theme + db.session.commit() + return { + 'status': 'success', + 'theme': u.theme_preference + } @auth_router.post("/logout") @@ -333,24 +327,23 @@ def refresh_token(request: Request, response: Response, payload: Optional[Refres if not token: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="No se proporcionó refresh token.") - with flask_app.app_context(): - try: - decoded = JWTService.decode_token(token, expected_type='refresh') - user_id = decoded.get('sub') - if not user_id: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token no contiene sub válido.") - user = User.query.get(int(str(user_id))) - if not user or not user.is_active: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Usuario no encontrado o inactivo.") + try: + decoded = JWTService.decode_token(token, expected_type='refresh') + user_id = decoded.get('sub') + if not user_id: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token no contiene sub válido.") + user = User.query.get(int(str(user_id))) + if not user or not user.is_active: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Usuario no encontrado o inactivo.") - tokens = JWTService.generate_tokens(user) - response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") - return { - 'status': 'success', - 'access_token': tokens['access_token'], - 'refresh_token': tokens['refresh_token'], - 'token_type': tokens['token_type'], - 'expires_in': tokens['expires_in'] - } - except Exception as e: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Refresh token inválido: {str(e)}") + tokens = JWTService.generate_tokens(user) + response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/") + return { + 'status': 'success', + 'access_token': tokens['access_token'], + 'refresh_token': tokens['refresh_token'], + 'token_type': tokens['token_type'], + 'expires_in': tokens['expires_in'] + } + except Exception as e: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Refresh token inválido: {str(e)}") diff --git a/backend/routers/buildings.py b/backend/routers/buildings.py index bde2274..d7f1e21 100644 --- a/backend/routers/buildings.py +++ b/backend/routers/buildings.py @@ -1,8 +1,9 @@ """ FastAPI Buildings Router (/api/v1/buildings) Provides endpoints for listing, retrieving, creating, updating, toggling and deleting institutional buildings. +100% Native FastAPI - Zero Flask dependencies. """ -from typing import Optional, Dict, Any +from typing import Optional from fastapi import APIRouter, Depends, HTTPException, Query, status, Request from sqlalchemy import func, or_ from datetime import datetime, timezone @@ -13,10 +14,8 @@ from app.models.classroom import Classroom from app.services.audit_service import AuditService from dependencies import get_current_user, require_roles, get_request_payload from app.models.user import User -from database import get_flask_app buildings_router = APIRouter(prefix="/api/v1/buildings", tags=["Buildings"]) -flask_app = get_flask_app() @buildings_router.get("") @@ -26,46 +25,45 @@ def list_buildings( current_user: User = Depends(get_current_user) ): """Lista todos los edificios con métricas globales de capacidad y estado.""" - with flask_app.app_context(): - search_term = (search or '').strip().lower() - st_term = (status_filter or '').strip().lower() + search_term = (search or '').strip().lower() + st_term = (status_filter or '').strip().lower() - query = Building.query - if search_term: - query = query.filter( - or_( - Building.name.ilike(f'%{search_term}%'), - Building.code.ilike(f'%{search_term}%'), - Building.address.ilike(f'%{search_term}%') - ) + query = Building.query + if search_term: + query = query.filter( + or_( + Building.name.ilike(f'%{search_term}%'), + Building.code.ilike(f'%{search_term}%'), + Building.address.ilike(f'%{search_term}%') ) - if st_term == 'active': - query = query.filter(Building.is_active == True) - elif st_term == 'inactive': - query = query.filter(Building.is_active == False) + ) + if st_term == 'active': + query = query.filter(Building.is_active == True) + elif st_term == 'inactive': + query = query.filter(Building.is_active == False) - buildings = query.order_by(Building.name.asc()).all() - buildings_data = [b.to_dict() for b in buildings] + buildings = query.order_by(Building.name.asc()).all() + buildings_data = [b.to_dict() for b in buildings] - all_classrooms = Classroom.query.filter_by(is_active=True).all() - physical_classrooms = [ - c for c in all_classrooms - 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) + all_classrooms = Classroom.query.filter_by(is_active=True).all() + physical_classrooms = [ + c for c in all_classrooms + 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) - return { - 'status': 'success', - 'total': len(buildings_data), - 'buildings': buildings_data, - 'stats': { - 'total_buildings': len(buildings), - 'total_classrooms': len(all_classrooms), - 'physical_classrooms_count': len(physical_classrooms), - 'total_physical_capacity': total_physical_capacity, - 'total_floors': sum(b.floors for b in buildings if not b.is_virtual) - } + return { + 'status': 'success', + 'total': len(buildings_data), + 'buildings': buildings_data, + 'stats': { + 'total_buildings': len(buildings), + 'total_classrooms': len(all_classrooms), + 'physical_classrooms_count': len(physical_classrooms), + 'total_physical_capacity': total_physical_capacity, + 'total_floors': sum(b.floors for b in buildings if not b.is_virtual) } + } @buildings_router.get("/{id}") @@ -74,20 +72,19 @@ def get_building( current_user: User = Depends(get_current_user) ): """Obtiene el detalle de un edificio y su lista de aulas.""" - with flask_app.app_context(): - building = Building.query.get(id) - if not building: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") + building = Building.query.get(id) + if not building: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") - classrooms = Classroom.query.filter( - or_(Classroom.building_id == id, Classroom.building == building.name) - ).order_by(Classroom.floor.asc(), Classroom.code.asc()).all() + classrooms = Classroom.query.filter( + or_(Classroom.building_id == id, Classroom.building == building.name) + ).order_by(Classroom.floor.asc(), Classroom.code.asc()).all() - return { - 'status': 'success', - 'building': building.to_dict(), - 'classrooms': [c.to_dict() for c in classrooms] - } + return { + 'status': 'success', + 'building': building.to_dict(), + 'classrooms': [c.to_dict() for c in classrooms] + } @buildings_router.post("", status_code=status.HTTP_201_CREATED) @@ -98,54 +95,53 @@ async def create_building( """Crea una nueva sede o edificio institucional.""" data = await get_request_payload(request) - with flask_app.app_context(): - name = str(data.get('name') or '').strip() - code_str = str(data.get('code') or '').strip().upper() - code = code_str if code_str else None - address_str = str(data.get('address') or '').strip() - address = address_str if address_str else None - try: - floors_val = data.get('floors', 1) - floors = int(str(floors_val)) if floors_val is not None else 1 - except (ValueError, TypeError): - floors = 1 - desc_str = str(data.get('description') or '').strip() - description = desc_str if desc_str else None - is_active = data.get('is_active', True) - if isinstance(is_active, str): - is_active = is_active.lower() in ['true', '1', 'on'] + name = str(data.get('name') or '').strip() + code_str = str(data.get('code') or '').strip().upper() + code = code_str if code_str else None + address_str = str(data.get('address') or '').strip() + address = address_str if address_str else None + try: + floors_val = data.get('floors', 1) + floors = int(str(floors_val)) if floors_val is not None else 1 + except (ValueError, TypeError): + floors = 1 + desc_str = str(data.get('description') or '').strip() + description = desc_str if desc_str else None + is_active = data.get('is_active', True) + if isinstance(is_active, str): + is_active = is_active.lower() in ['true', '1', 'on'] - if not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.") + if not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.") - existing = Building.query.filter(func.lower(Building.name) == name.lower()).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'Ya existe un edificio con el nombre "{name}".') + existing = Building.query.filter(func.lower(Building.name) == name.lower()).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'Ya existe un edificio con el nombre "{name}".') - building = Building( - name=name, - code=code, - address=address, - floors=floors, - description=description, - is_active=bool(is_active) - ) - db.session.add(building) - db.session.commit() + building = Building( + name=name, + code=code, + address=address, + floors=floors, + description=description, + is_active=bool(is_active) + ) + db.session.add(building) + db.session.commit() - AuditService.log( - action='CREATE', - module='buildings', - entity_id=building.id, - user=current_user, - details=f"Nueva sede/edificio creado: '{building.name}' (Código: {building.code or 'S/C'}, Pisos: {building.floors})" - ) + AuditService.log( + action='CREATE', + module='buildings', + entity_id=building.id, + user=current_user, + details=f"Nueva sede/edificio creado: '{building.name}' (Código: {building.code or 'S/C'}, Pisos: {building.floors})" + ) - return { - 'status': 'success', - 'message': f'Edificio "{name}" creado con éxito.', - 'building': building.to_dict() - } + return { + 'status': 'success', + 'message': f'Edificio "{name}" creado con éxito.', + 'building': building.to_dict() + } @buildings_router.put("/{id}") @@ -158,65 +154,64 @@ async def update_building( """Actualiza la información de un edificio existente.""" data = await get_request_payload(request) - with flask_app.app_context(): - building = Building.query.get(id) - if not building: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") + building = Building.query.get(id) + if not building: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") - name = str(data.get('name') or '').strip() - if not name: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.") + name = str(data.get('name') or '').strip() + if not name: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.") - existing = Building.query.filter( - func.lower(Building.name) == name.lower(), - Building.id != id - ).first() - if existing: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'Ya existe otro edificio con el nombre "{name}".') + existing = Building.query.filter( + func.lower(Building.name) == name.lower(), + Building.id != id + ).first() + if existing: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'Ya existe otro edificio con el nombre "{name}".') - old_name = building.name - building.name = name - if 'code' in data: - c_val = str(data.get('code') or '').strip().upper() - building.code = c_val if c_val else None - if 'address' in data: - a_val = str(data.get('address') or '').strip() - building.address = a_val if a_val else None - if 'floors' in data: - try: - fl_val = data.get('floors', 0) - building.floors = int(str(fl_val)) if fl_val is not None else 0 - except (ValueError, TypeError): - pass - if 'description' in data: - d_val = str(data.get('description') or '').strip() - building.description = d_val if d_val else None - if 'is_active' in data: - is_active = data.get('is_active') - if isinstance(is_active, str): - building.is_active = is_active.lower() in ['true', '1', 'on'] - else: - building.is_active = bool(is_active) - building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) + old_name = building.name + building.name = name + if 'code' in data: + c_val = str(data.get('code') or '').strip().upper() + building.code = c_val if c_val else None + if 'address' in data: + a_val = str(data.get('address') or '').strip() + building.address = a_val if a_val else None + if 'floors' in data: + try: + fl_val = data.get('floors', 0) + building.floors = int(str(fl_val)) if fl_val is not None else 0 + except (ValueError, TypeError): + pass + if 'description' in data: + d_val = str(data.get('description') or '').strip() + building.description = d_val if d_val else None + if 'is_active' in data: + is_active = data.get('is_active') + if isinstance(is_active, str): + building.is_active = is_active.lower() in ['true', '1', 'on'] + else: + building.is_active = bool(is_active) + building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) - if old_name != name: - Classroom.query.filter_by(building_id=building.id).update({'building': name}) + if old_name != name: + Classroom.query.filter_by(building_id=building.id).update({'building': name}) - db.session.commit() + db.session.commit() - AuditService.log( - action='UPDATE', - module='buildings', - entity_id=building.id, - user=current_user, - details=f"Edificio/sede #{building.id} ('{building.name}') actualizado. Pisos: {building.floors}, Código: {building.code}" - ) + AuditService.log( + action='UPDATE', + module='buildings', + entity_id=building.id, + user=current_user, + details=f"Edificio/sede #{building.id} ('{building.name}') actualizado. Pisos: {building.floors}, Código: {building.code}" + ) - return { - 'status': 'success', - 'message': f'Edificio "{building.name}" actualizado con éxito.', - 'building': building.to_dict() - } + return { + 'status': 'success', + 'message': f'Edificio "{building.name}" actualizado con éxito.', + 'building': building.to_dict() + } @buildings_router.post("/{id}/toggle") @@ -225,28 +220,27 @@ def toggle_building( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Conmuta el estado activo/inactivo de un edificio.""" - with flask_app.app_context(): - building = Building.query.get(id) - if not building: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") + building = Building.query.get(id) + if not building: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") - building.is_active = not building.is_active - building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) - db.session.commit() + building.is_active = not building.is_active + building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None) + db.session.commit() - AuditService.log( - action='TOGGLE', - module='buildings', - entity_id=building.id, - user=current_user, - details=f"Edificio '{building.name}' {'activado' if building.is_active else 'desactivado'}" - ) + AuditService.log( + action='TOGGLE', + module='buildings', + entity_id=building.id, + user=current_user, + details=f"Edificio '{building.name}' {'activado' if building.is_active else 'desactivado'}" + ) - return { - 'status': 'success', - 'message': f'Edificio "{building.name}" {"activado" if building.is_active else "desactivado"} exitosamente.', - 'building': building.to_dict() - } + return { + 'status': 'success', + 'message': f'Edificio "{building.name}" {"activado" if building.is_active else "desactivado"} exitosamente.', + 'building': building.to_dict() + } @buildings_router.delete("/{id}") @@ -255,33 +249,32 @@ def delete_building( current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"])) ): """Elimina un edificio si no posee aulas físicas o virtuales asociadas.""" - with flask_app.app_context(): - building = Building.query.get(id) - if not building: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") + building = Building.query.get(id) + if not building: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.") - count = Classroom.query.filter( - or_(Classroom.building_id == building.id, Classroom.building == building.name) - ).count() - if count > 0: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f'No se puede eliminar el edificio "{building.name}" porque tiene {count} aulas asociadas.' - ) - - b_name = building.name - db.session.delete(building) - db.session.commit() - - AuditService.log( - action='DELETE', - module='buildings', - entity_id=id, - user=current_user, - details=f"Edificio '{b_name}' eliminado del sistema." + count = Classroom.query.filter( + or_(Classroom.building_id == building.id, Classroom.building == building.name) + ).count() + if count > 0: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f'No se puede eliminar el edificio "{building.name}" porque tiene {count} aulas asociadas.' ) - return { - 'status': 'success', - 'message': f'Edificio "{b_name}" eliminado correctamente.' - } + b_name = building.name + db.session.delete(building) + db.session.commit() + + AuditService.log( + action='DELETE', + module='buildings', + entity_id=id, + user=current_user, + details=f"Edificio '{b_name}' eliminado del sistema." + ) + + return { + 'status': 'success', + 'message': f'Edificio "{b_name}" eliminado correctamente.' + } diff --git a/backend/routers/classrooms.py b/backend/routers/classrooms.py index 4ea8253..b193e4c 100644 --- a/backend/routers/classrooms.py +++ b/backend/routers/classrooms.py @@ -1,6 +1,7 @@ """ FastAPI Classrooms Router (/api/v1/classrooms) Provides endpoints for listing, retrieving, creating, updating and toggling classrooms. +100% Native FastAPI - Zero Flask dependencies. """ from typing import Optional from fastapi import APIRouter, Depends, HTTPException, Query, status @@ -12,11 +13,9 @@ from app.services.audit_service import AuditService from app.schemas.classroom_dto import ClassroomCreateDTO, ClassroomUpdateDTO from dependencies import get_current_user, require_roles from app.models.user import User -from database import get_flask_app classrooms_router = APIRouter(prefix="/api/v1/classrooms", tags=["Classrooms"]) classroom_service = ClassroomService() -flask_app = get_flask_app() @classrooms_router.get("") @@ -27,52 +26,20 @@ def list_classrooms( current_user: User = Depends(get_current_user) ): """Lista aulas físicas y virtuales con filtros opcionales.""" - with flask_app.app_context(): - mode_str = (mode or '').lower() - only_virtual = mode_str == 'virtual' - only_physical = mode_str == 'physical' + mode_str = (mode or '').lower() + only_virtual = mode_str == 'virtual' + only_physical = mode_str == 'physical' - classrooms = classroom_service.list_classrooms( - building_id=building_id, - floor=floor, - only_virtual=only_virtual, - only_physical=only_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 {'total': len(result), 'classrooms': result} - - -@classrooms_router.get("/{classroom_id}") -def get_classroom( - classroom_id: int, - current_user: User = Depends(get_current_user) -): - """Obtiene el detalle de un aula por ID.""" - with flask_app.app_context(): - c = classroom_service.get_classroom(classroom_id) - if not c: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Aula {classroom_id} no encontrada." - ) - - return { + result = [] + for c in classrooms: + result.append({ 'id': c.id, 'code': c.code, 'building': c.building_name, @@ -84,7 +51,37 @@ def get_classroom( 'location_display': c.location_display, 'description': c.description, 'is_active': c.is_active - } + }) + + return {'total': len(result), 'classrooms': result} + + +@classrooms_router.get("/{classroom_id}") +def get_classroom( + classroom_id: int, + current_user: User = Depends(get_current_user) +): + """Obtiene el detalle de un aula por ID.""" + c = classroom_service.get_classroom(classroom_id) + if not c: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Aula {classroom_id} no encontrada." + ) + + return { + '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 + } @classrooms_router.post("", status_code=status.HTTP_201_CREATED) @@ -93,24 +90,23 @@ def create_classroom( current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia'])) ): """Crea una nueva aula validando con ClassroomCreateDTO.""" - with flask_app.app_context(): - try: - classroom = classroom_service.create_classroom(dto) - AuditService.log( - action='CREATE', - module='classrooms', - entity_id=classroom.id, - user=current_user, - details=f"Nueva aula creada: {classroom.code} en {classroom.building} (Piso {classroom.floor}, Capacidad: {classroom.capacity})" - ) - return { - 'message': 'Aula creada exitosamente.', - 'id': classroom.id, - 'code': classroom.code, - 'location_display': classroom.location_display - } - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + try: + classroom = classroom_service.create_classroom(dto) + AuditService.log( + action='CREATE', + module='classrooms', + entity_id=classroom.id, + user=current_user, + details=f"Nueva aula creada: {classroom.code} en {classroom.building} (Piso {classroom.floor}, Capacidad: {classroom.capacity})" + ) + return { + 'message': 'Aula creada exitosamente.', + 'id': classroom.id, + 'code': classroom.code, + 'location_display': classroom.location_display + } + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @classrooms_router.put("/{classroom_id}") @@ -120,27 +116,26 @@ def update_classroom( current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia'])) ): """Actualiza los datos de un aula.""" - with flask_app.app_context(): - try: - classroom = classroom_service.update_classroom(classroom_id, dto) - if not classroom: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") + try: + classroom = classroom_service.update_classroom(classroom_id, dto) + if not classroom: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") - AuditService.log( - action='UPDATE', - module='classrooms', - entity_id=classroom.id, - user=current_user, - details=f"Aula #{classroom.id} ({classroom.code}) actualizada. Capacidad: {classroom.capacity}, Piso: {classroom.floor}" - ) - return { - 'message': 'Aula actualizada exitosamente.', - 'id': classroom.id, - 'code': classroom.code, - 'capacity': classroom.capacity - } - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + AuditService.log( + action='UPDATE', + module='classrooms', + entity_id=classroom.id, + user=current_user, + details=f"Aula #{classroom.id} ({classroom.code}) actualizada. Capacidad: {classroom.capacity}, Piso: {classroom.floor}" + ) + return { + 'message': 'Aula actualizada exitosamente.', + 'id': classroom.id, + 'code': classroom.code, + 'capacity': classroom.capacity + } + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @classrooms_router.delete("/{classroom_id}") @@ -149,19 +144,18 @@ def delete_classroom( current_user: User = Depends(require_roles(['admin', 'administrador'])) ): """Elimina o desactiva un aula.""" - with flask_app.app_context(): - deleted = classroom_service.delete_classroom(classroom_id) - if not deleted: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") + deleted = classroom_service.delete_classroom(classroom_id) + if not deleted: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") - AuditService.log( - action='DELETE', - module='classrooms', - entity_id=classroom_id, - user=current_user, - details=f"Aula #{classroom_id} eliminada/desactivada del sistema" - ) - return {'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'} + AuditService.log( + action='DELETE', + module='classrooms', + entity_id=classroom_id, + user=current_user, + details=f"Aula #{classroom_id} eliminada/desactivada del sistema" + ) + return {'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'} @classrooms_router.post("/{classroom_id}/toggle") @@ -170,23 +164,22 @@ def toggle_classroom( current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia'])) ): """Alterna el estado activo/inactivo de un aula.""" - with flask_app.app_context(): - classroom = Classroom.query.get(classroom_id) - if not classroom: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") + classroom = Classroom.query.get(classroom_id) + if not classroom: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.") - classroom.is_active = not classroom.is_active - db.session.commit() - AuditService.log( - action='TOGGLE', - module='classrooms', - entity_id=classroom.id, - user=current_user, - details=f"Aula {classroom.code} {'activada' if classroom.is_active else 'desactivada'}" - ) - return { - 'status': 'success', - 'id': classroom.id, - 'is_active': classroom.is_active, - 'message': f'Aula {"activada" if classroom.is_active else "desactivada"} correctamente.' - } + classroom.is_active = not classroom.is_active + db.session.commit() + AuditService.log( + action='TOGGLE', + module='classrooms', + entity_id=classroom.id, + user=current_user, + details=f"Aula {classroom.code} {'activada' if classroom.is_active else 'desactivada'}" + ) + return { + 'status': 'success', + 'id': classroom.id, + 'is_active': classroom.is_active, + 'message': f'Aula {"activada" if classroom.is_active else "desactivada"} correctamente.' + } diff --git a/backend/routers/dashboard.py b/backend/routers/dashboard.py index 9dabe06..8460dd1 100644 --- a/backend/routers/dashboard.py +++ b/backend/routers/dashboard.py @@ -1,38 +1,23 @@ """ FastAPI Dashboard Router (/api/v1/dashboard) Provides operational metrics, today/tomorrow/week schedule, and Google Sheets sync inspection. +100% Native FastAPI - Zero Flask dependencies. """ -from typing import Optional, Dict, Any -from datetime import datetime -from fastapi import APIRouter, Depends, HTTPException, Query, Request, status +from typing import Dict, Any +from fastapi import APIRouter, Depends, HTTPException, Request, status -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 app.models.milestone import AcademicMilestone -from app.models.subject import Commission -from app.models.setting import SystemSetting -from app.services.audit_service import AuditService +from app.services.dashboard_service import DashboardService from dependencies import get_current_user -from database import get_flask_app dashboard_router = APIRouter(prefix="/api/v1/dashboard", tags=["Dashboard"]) +dashboard_service = DashboardService() @dashboard_router.get("/stats") def get_stats(current_user: User = Depends(get_current_user)): """Retorna estadísticas clave y datos operativos para el Dashboard.""" - from app.routes.api.dashboard import get_stats as flask_get_stats - f_app = get_flask_app() - with f_app.test_request_context(): - from flask import g - g.jwt_user = current_user - resp = flask_get_stats() - if hasattr(resp, 'get_json'): - return resp.get_json() - return resp[0].get_json() if isinstance(resp, tuple) else resp + return dashboard_service.get_stats(current_user=current_user) @dashboard_router.post("/sync-sheets") @@ -42,16 +27,14 @@ def sync_google_sheets( current_user: User = Depends(get_current_user) ): """Ejecuta la sincronización con Google Sheets con filtros y selección granular.""" - from app.routes.api.dashboard import sync_google_sheets as flask_sync - f_app = get_flask_app() - with f_app.test_request_context(json=payload): - from flask import g - g.jwt_user = current_user - g.current_user = {'email': current_user.email} - resp = flask_sync() - if hasattr(resp, 'get_json'): - return resp.get_json() - return resp[0].get_json() if isinstance(resp, tuple) else resp + try: + ip = request.client.host if request.client else '127.0.0.1' + return dashboard_service.sync_google_sheets(payload, current_user=current_user, ip_address=ip) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=str(e) + ) @dashboard_router.get("/sheets-inspect") @@ -61,12 +44,12 @@ def inspect_google_sheets( current_user: User = Depends(get_current_user) ): """Inspecciona las hojas de cálculo descubriendo carreras, materias y previsualización.""" - from app.routes.api.dashboard import inspect_google_sheets as flask_inspect - f_app = get_flask_app() - with f_app.test_request_context(): - from flask import g - g.jwt_user = current_user - resp = flask_inspect() - if hasattr(resp, 'get_json'): - return resp.get_json() - return resp[0].get_json() if isinstance(resp, tuple) else resp + try: + # Puede venir como query params o json body + data: Dict[str, Any] = dict(request.query_params) + return dashboard_service.inspect_google_sheets(data) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=str(e) + ) diff --git a/backend/routers/optimizer.py b/backend/routers/optimizer.py index e5e5610..7911755 100644 --- a/backend/routers/optimizer.py +++ b/backend/routers/optimizer.py @@ -1,15 +1,18 @@ """ FastAPI Optimizer & Genetic Algorithm Router (/api/v1/optimizer and /api/genetic) Provides asynchronous optimization jobs and genetic heuristic room assignment. +100% Native FastAPI - Zero Flask dependencies. """ -from typing import Optional, Dict, Any +from typing import Optional, Dict, Any, List from fastapi import APIRouter, Depends, HTTPException, Query, status from app.schemas.optimizer_dto import OptimizerJobRequestDTO, SpringBootSyncPayloadDTO from app.services.optimizer_service import OptimizerService from dependencies import get_current_user from app.models.user import User -from database import get_flask_app +from app.models.subject import Commission +from app.models.classroom import Classroom +from app.models.reservation import Reservation, ReservationStatus optimizer_router = APIRouter(prefix="/api/v1/optimizer", tags=["Optimizer"]) genetic_router = APIRouter(prefix="/api/genetic", tags=["Genetic Heuristics"]) @@ -81,12 +84,48 @@ def sync_with_spring_boot( @genetic_router.get("/commissions") def get_genetic_commissions(current_user: User = Depends(get_current_user)): """Retorna comisiones activas para el optimizador genético.""" - from app.routes.genetic_algorithm import get_commissions as flask_get_comm - f_app = get_flask_app() - with f_app.test_request_context(): - from flask import g - g.jwt_user = current_user - resp = flask_get_comm() - if hasattr(resp, 'get_json'): - return resp.get_json() - return resp[0].get_json() if isinstance(resp, tuple) else resp + commissions = Commission.query.filter_by(active=True).all() + commissions_data: List[Dict[str, Any]] = [] + for commission in commissions: + commission_dict = commission.to_dict() + commission_dict['get_full_code'] = commission.get_full_code() + commission_dict['subject_name'] = commission.subject.name if commission.subject else 'Sin Asignatura' + commission_dict['subject_code'] = commission.subject.code if commission.subject else '' + commissions_data.append(commission_dict) + + return { + 'success': True, + 'commissions': commissions_data + } + + +@genetic_router.get("/algorithm-status") +def get_genetic_algorithm_status(current_user: User = Depends(get_current_user)): + """Retorna estado y capacidades de los algoritmos de optimización.""" + 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 { + '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' + ] + } + } diff --git a/backend/routers/reservations.py b/backend/routers/reservations.py index bc753fd..b8222ab 100644 --- a/backend/routers/reservations.py +++ b/backend/routers/reservations.py @@ -15,11 +15,9 @@ from app.services.audit_service import AuditService from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO from dependencies import get_current_user, get_request_payload from app.models.user import User -from database import get_flask_app reservations_router = APIRouter(prefix="/api/v1/reservations", tags=["Reservations"]) reservation_service = ReservationService() -flask_app = get_flask_app() @reservations_router.get("") @@ -34,166 +32,164 @@ def list_reservations( current_user: User = Depends(get_current_user) ): """Consulta de reservas por rango de fechas y/o aula.""" - with flask_app.app_context(): - now = datetime.now(timezone.utc).replace(tzinfo=None) - try: - start_dt = datetime.strptime(start_date, '%Y-%m-%d') if start_date else now.replace(hour=0, minute=0, second=0) - except ValueError: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de start_date (debe ser YYYY-MM-DD).") + now = datetime.now(timezone.utc).replace(tzinfo=None) + try: + start_dt = datetime.strptime(start_date, '%Y-%m-%d') if start_date else now.replace(hour=0, minute=0, second=0) + except ValueError: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de start_date (debe ser YYYY-MM-DD).") - try: - end_dt = datetime.strptime(end_date, '%Y-%m-%d').replace(hour=23, minute=59, second=59) if end_date else start_dt + timedelta(days=7) - except ValueError: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de end_date (debe ser YYYY-MM-DD).") + try: + end_dt = datetime.strptime(end_date, '%Y-%m-%d').replace(hour=23, minute=59, second=59) if end_date else start_dt + timedelta(days=7) + except ValueError: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de end_date (debe ser YYYY-MM-DD).") - is_hide_virtual = str(hide_virtual).lower() in ['1', 'true'] + is_hide_virtual = str(hide_virtual).lower() in ['1', 'true'] - 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 is_hide_virtual and is_virt: - continue - if floor and r.classroom and str(r.classroom.floor).strip().lower() != floor.strip().lower(): - continue - if shift and r.shift and shift.lower() not in r.shift.lower(): - continue - r_user: Any = getattr(r, 'user', None) - u_name = (getattr(r_user, 'name', '') or '').lower() if r_user else '' - 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() - 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 - - user_dict = { - 'id': getattr(r_user, 'id', None), - 'name': getattr(r_user, 'name', None), - 'email': getattr(r_user, 'email', None) - } if r_user else None - - 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': getattr(r_user, 'name', None) if r_user else None, - 'user': user_dict, - '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, - 'career_name': r.commission.career_name if (r.commission and hasattr(r.commission, 'career_name')) else '', - 'career_names': r.commission.career_names if (r.commission and hasattr(r.commission, 'career_names')) else '', - 'commission_code': r.commission.code if r.commission else '', - '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 { - 'total': len(result), - 'start_date': start_dt.strftime('%Y-%m-%d'), - 'end_date': end_dt.strftime('%Y-%m-%d'), - 'reservations': result - } - - -@reservations_router.get("/{reservation_id}") -def get_reservation(reservation_id: int, current_user: User = Depends(get_current_user)): - """Obtiene el detalle de una reserva específica.""" - with flask_app.app_context(): - r = reservation_service.get_reservation(reservation_id) - if not r: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") - - duration_min = int((r.end_time - r.start_time).total_seconds() / 60) if (r.start_time and r.end_time) else 120 + 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 is_hide_virtual and is_virt: + continue + if floor and r.classroom and str(r.classroom.floor).strip().lower() != floor.strip().lower(): + continue + if shift and r.shift and shift.lower() not in r.shift.lower(): + continue r_user: Any = getattr(r, 'user', None) - u_name = getattr(r_user, 'name', None) if r_user else None - u_id = getattr(r_user, 'id', None) if r_user else None - u_email = getattr(r_user, 'email', None) if r_user else None - name_parts = str(u_name).split() if u_name else [] - first_name = getattr(r_user, 'first_name', name_parts[0] if name_parts else 'Usuario') if r_user else 'Usuario' - last_name = getattr(r_user, 'last_name', ' '.join(name_parts[1:]) if len(name_parts) > 1 else '') if r_user else '' + u_name = (getattr(r_user, 'name', '') or '').lower() if r_user else '' + 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() + 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 - return { + user_dict = { + 'id': getattr(r_user, 'id', None), + 'name': getattr(r_user, 'name', None), + 'email': getattr(r_user, 'email', None) + } if r_user else None + + result.append({ '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) + '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, - '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 + 'max_students': r.commission.max_students } if r.commission else None, - 'teacher_id': r.user_id, - 'teacher_name': u_name, - 'user': { - 'id': u_id, - 'name': u_name, - 'first_name': first_name, - 'last_name': last_name, - 'email': u_email - } if r_user else None, + 'teacher_name': getattr(r_user, 'name', None) if r_user else None, + 'user': user_dict, 'start_time': r.start_time.isoformat(), 'end_time': r.end_time.isoformat(), - 'duration': duration_min, 'purpose': r.purpose, + 'subject_name': r.subject_name, + 'subject_code': r.subject_code, + 'career_name': r.commission.career_name if (r.commission and hasattr(r.commission, 'career_name')) else '', + 'career_names': r.commission.career_names if (r.commission and hasattr(r.commission, 'career_names')) else '', + 'commission_code': r.commission.code if r.commission else '', '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 - } + 'notes': r.notes or '' + }) + + return { + 'total': len(result), + 'start_date': start_dt.strftime('%Y-%m-%d'), + 'end_date': end_dt.strftime('%Y-%m-%d'), + 'reservations': result + } + + +@reservations_router.get("/{reservation_id}") +def get_reservation(reservation_id: int, current_user: User = Depends(get_current_user)): + """Obtiene el detalle de una reserva específica.""" + r = reservation_service.get_reservation(reservation_id) + if not r: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") + + 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)) + + r_user: Any = getattr(r, 'user', None) + u_name = getattr(r_user, 'name', None) if r_user else None + u_id = getattr(r_user, 'id', None) if r_user else None + u_email = getattr(r_user, 'email', None) if r_user else None + name_parts = str(u_name).split() if u_name else [] + first_name = getattr(r_user, 'first_name', name_parts[0] if name_parts else 'Usuario') if r_user else 'Usuario' + last_name = getattr(r_user, 'last_name', ' '.join(name_parts[1:]) if len(name_parts) > 1 else '') if r_user else '' + + return { + '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': u_name, + 'user': { + 'id': u_id, + 'name': u_name, + 'first_name': first_name, + 'last_name': last_name, + 'email': u_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 + } @reservations_router.post("", status_code=status.HTTP_201_CREATED) @@ -202,34 +198,33 @@ def create_reservation( current_user: User = Depends(get_current_user) ): """Crea una reserva aplicando validación DTO y detección de colisiones.""" - with flask_app.app_context(): - if 'user_id' not in payload: - payload['user_id'] = current_user.id + if 'user_id' not in payload: + payload['user_id'] = current_user.id - try: - dto = ReservationCreateDTO(**payload) - except Exception as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + try: + dto = ReservationCreateDTO(**payload) + except Exception as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - try: - reservation = reservation_service.create_reservation(dto) - AuditService.log( - action='CREATE', - module='reservations', - entity_id=reservation.id, - user=current_user, - details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}" - ) - return { - '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) - } - except ValueError as e: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) + try: + reservation = reservation_service.create_reservation(dto) + AuditService.log( + action='CREATE', + module='reservations', + entity_id=reservation.id, + user=current_user, + details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}" + ) + return { + '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) + } + except ValueError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) @reservations_router.put("/{reservation_id}") @@ -239,25 +234,24 @@ def update_reservation( current_user: User = Depends(get_current_user) ): """Modifica una reserva existente.""" - with flask_app.app_context(): - try: - reservation = reservation_service.update_reservation(reservation_id, dto) - AuditService.log( - action='UPDATE', - module='reservations', - entity_id=reservation.id, - user=current_user, - details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}" - ) - return { - 'message': 'Reserva actualizada exitosamente.', - 'id': reservation.id, - 'start_time': reservation.start_time.isoformat(), - 'end_time': reservation.end_time.isoformat(), - 'status': str(reservation.status) - } - except ValueError as e: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) + try: + reservation = reservation_service.update_reservation(reservation_id, dto) + AuditService.log( + action='UPDATE', + module='reservations', + entity_id=reservation.id, + user=current_user, + details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}" + ) + return { + 'message': 'Reserva actualizada exitosamente.', + 'id': reservation.id, + 'start_time': reservation.start_time.isoformat(), + 'end_time': reservation.end_time.isoformat(), + 'status': str(reservation.status) + } + except ValueError as e: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) @reservations_router.delete("/{reservation_id}") @@ -267,41 +261,8 @@ def cancel_reservation( current_user: User = Depends(get_current_user) ): """Cancela o elimina una reserva según el parámetro hard.""" - with flask_app.app_context(): - hard_delete = str(hard).lower() in ['true', '1'] - if hard_delete: - res = Reservation.query.get(reservation_id) - if not res: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") - db.session.delete(res) - db.session.commit() - AuditService.log( - action='DELETE', - module='reservations', - entity_id=reservation_id, - user=current_user, - details=f"Reserva #{reservation_id} eliminada permanentemente" - ) - return {'message': f'Reserva {reservation_id} eliminada permanentemente.'} - - cancelled = reservation_service.cancel_reservation(reservation_id) - if not cancelled: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") - - AuditService.log( - action='CANCEL', - module='reservations', - entity_id=reservation_id, - user=current_user, - details=f"Reserva #{reservation_id} cancelada" - ) - return {'message': f'Reserva {reservation_id} cancelada correctamente.'} - - -@reservations_router.post("/{reservation_id}/delete") -def delete_reservation_post(reservation_id: int, current_user: User = Depends(get_current_user)): - """Elimina permanentemente una reserva (POST).""" - with flask_app.app_context(): + hard_delete = str(hard).lower() in ['true', '1'] + if hard_delete: res = Reservation.query.get(reservation_id) if not res: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") @@ -316,80 +277,108 @@ def delete_reservation_post(reservation_id: int, current_user: User = Depends(ge ) return {'message': f'Reserva {reservation_id} eliminada permanentemente.'} + cancelled = reservation_service.cancel_reservation(reservation_id) + if not cancelled: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") + + AuditService.log( + action='CANCEL', + module='reservations', + entity_id=reservation_id, + user=current_user, + details=f"Reserva #{reservation_id} cancelada" + ) + return {'message': f'Reserva {reservation_id} cancelada correctamente.'} + + +@reservations_router.post("/{reservation_id}/delete") +def delete_reservation_post(reservation_id: int, current_user: User = Depends(get_current_user)): + """Elimina permanentemente una reserva (POST).""" + res = Reservation.query.get(reservation_id) + if not res: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") + db.session.delete(res) + db.session.commit() + AuditService.log( + action='DELETE', + module='reservations', + entity_id=reservation_id, + user=current_user, + details=f"Reserva #{reservation_id} eliminada permanentemente" + ) + return {'message': f'Reserva {reservation_id} eliminada permanentemente.'} + @reservations_router.post("/{reservation_id}/cancel") def cancel_reservation_post(reservation_id: int, current_user: User = Depends(get_current_user)): """Cancela una reserva (POST).""" - with flask_app.app_context(): - cancelled = reservation_service.cancel_reservation(reservation_id) - if not cancelled: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") + cancelled = reservation_service.cancel_reservation(reservation_id) + if not cancelled: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") - AuditService.log( - action='CANCEL', - module='reservations', - entity_id=reservation_id, - user=current_user, - details=f"Reserva #{reservation_id} cancelada" - ) - return {'message': f'Reserva {reservation_id} cancelada correctamente.'} + AuditService.log( + action='CANCEL', + module='reservations', + entity_id=reservation_id, + user=current_user, + details=f"Reserva #{reservation_id} cancelada" + ) + return {'message': f'Reserva {reservation_id} cancelada correctamente.'} @reservations_router.post("/{reservation_id}/confirm") def confirm_reservation(reservation_id: int, current_user: User = Depends(get_current_user)): """Confirma una reserva cambiando su estado a CONFIRMED.""" - with flask_app.app_context(): - confirmed = reservation_service.confirm_reservation(reservation_id) - if not confirmed: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") + confirmed = reservation_service.confirm_reservation(reservation_id) + if not confirmed: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.") - AuditService.log( - action='CONFIRM', - module='reservations', - entity_id=reservation_id, - user=current_user, - details=f"Reserva #{reservation_id} confirmada oficialmente" - ) - return {'message': f'Reserva {reservation_id} confirmada correctamente.'} + AuditService.log( + action='CONFIRM', + module='reservations', + entity_id=reservation_id, + user=current_user, + details=f"Reserva #{reservation_id} confirmada oficialmente" + ) + return {'message': f'Reserva {reservation_id} confirmada correctamente.'} @reservations_router.post("/check-conflicts") def check_conflicts_endpoint(payload: Dict[str, Any], current_user: User = Depends(get_current_user)): """Evalúa la matriz completa de conflictos (físico, docente y aforo) en tiempo real.""" - with flask_app.app_context(): - classroom_id = payload.get('classroom_id') - start_str = payload.get('start_time') - end_str = payload.get('end_time') + classroom_id = payload.get('classroom_id') + start_str = payload.get('start_time') + end_str = payload.get('end_time') - if not classroom_id or not start_str or not end_str: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="classroom_id, start_time y end_time son obligatorios.") + if not classroom_id or not start_str or not end_str: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="classroom_id, start_time y end_time son obligatorios.") - 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: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de fecha/hora (ISO 8601 esperado).") + 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: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de fecha/hora (ISO 8601 esperado).") - teacher_id = payload.get('teacher_id') - commission_id = payload.get('commission_id') - expected_attendees = payload.get('expected_attendees') - allow_co_teaching = bool(payload.get('allow_co_teaching_exception', False)) - exclude_id = payload.get('exclude_id') + teacher_id = payload.get('teacher_id') + commission_id = payload.get('commission_id') + expected_attendees = payload.get('expected_attendees') + allow_co_teaching = bool(payload.get('allow_co_teaching_exception', False)) + exclude_id = payload.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 matrix - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + 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 matrix + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @reservations_router.post("/drag-update") @@ -429,68 +418,74 @@ async def drag_update_reservation( detail=f"Formato de fecha inválido: {str(e)}" ) - with flask_app.app_context(): - classroom = db.session.get(Classroom, classroom_id) - if not classroom: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Aula no encontrada.") + classroom = db.session.get(Classroom, classroom_id) + if not classroom: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Aula no encontrada.") - effective_comm_id: Optional[int] = commission_id - if effective_comm_id is None and reservation_id: - existing_res = db.session.get(Reservation, reservation_id) - if existing_res: - effective_comm_id = existing_res.commission_id + effective_comm_id: Optional[int] = commission_id + if effective_comm_id is None and reservation_id: + existing_res = db.session.get(Reservation, reservation_id) + if existing_res: + effective_comm_id = existing_res.commission_id - matrix = reservation_service.check_full_conflicts_matrix( + matrix = reservation_service.check_full_conflicts_matrix( + classroom_id=classroom_id, + start_time=start_dt, + end_time=end_dt, + commission_id=effective_comm_id, + exclude_id=reservation_id + ) + + if matrix.get('is_blocked'): + from fastapi.responses import JSONResponse + reason = ' '.join(matrix.get('block_reasons', ['Conflicto detectado en la asignación.'])) + return JSONResponse( + status_code=status.HTTP_409_CONFLICT, + content={ + 'status': 'conflict', + 'message': reason, + 'block_reasons': matrix.get('block_reasons', []), + 'matrix': matrix + } + ) + + if reservation_id: + res = db.session.get(Reservation, reservation_id) + if not res: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reserva no encontrada.") + + res.classroom_id = classroom_id + res.start_time = start_dt + res.end_time = end_dt + action = 'UPDATE_RESERVATION_DRAG' + msg = f"Reserva #{res.id} reprogramada al aula {classroom.code} ({start_dt.strftime('%H:%M')} a {end_dt.strftime('%H:%M')})" + else: + comm = db.session.get(Commission, commission_id) if commission_id else None + res = Reservation( classroom_id=classroom_id, + commission_id=commission_id, + user_id=current_user.id, start_time=start_dt, end_time=end_dt, - commission_id=effective_comm_id, - exclude_id=reservation_id + purpose=f"Cursada regular - {comm.subject.name if comm and comm.subject else 'Comisión'}", + expected_attendees=comm.max_students if comm else 30, + status=ReservationStatus.CONFIRMED.value ) + db.session.add(res) + action = 'CREATE_RESERVATION_DRAG' + msg = f"Comisión {comm.code if comm else ''} asignada al aula {classroom.code}" - if matrix.get('is_blocked'): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=' '.join(matrix.get('block_reasons', ['Conflicto detectado en la asignación.'])) - ) + db.session.commit() + AuditService.log( + action=action, + module='reservations', + entity_id=res.id, + user=current_user, + details=msg + ) - if reservation_id: - res = db.session.get(Reservation, reservation_id) - if not res: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reserva no encontrada.") - - res.classroom_id = classroom_id - res.start_time = start_dt - res.end_time = end_dt - action = 'UPDATE_RESERVATION_DRAG' - msg = f"Reserva #{res.id} reprogramada al aula {classroom.code} ({start_dt.strftime('%H:%M')} a {end_dt.strftime('%H:%M')})" - else: - comm = db.session.get(Commission, commission_id) if commission_id else None - res = Reservation( - classroom_id=classroom_id, - commission_id=commission_id, - user_id=current_user.id, - start_time=start_dt, - end_time=end_dt, - purpose=f"Cursada regular - {comm.subject.name if comm and comm.subject else 'Comisión'}", - expected_attendees=comm.max_students if comm else 30, - status=ReservationStatus.CONFIRMED.value - ) - db.session.add(res) - action = 'CREATE_RESERVATION_DRAG' - msg = f"Comisión {comm.code if comm else ''} asignada al aula {classroom.code}" - - db.session.commit() - AuditService.log( - action=action, - module='reservations', - entity_id=res.id, - user=current_user, - details=msg - ) - - return { - 'status': 'success', - 'message': msg, - 'reservation': res.to_dict() - } + return { + 'status': 'success', + 'message': msg, + 'reservation': res.to_dict() + } diff --git a/backend/routers/students.py b/backend/routers/students.py index 13191f9..61ab10b 100644 --- a/backend/routers/students.py +++ b/backend/routers/students.py @@ -3,7 +3,7 @@ FastAPI Students Router (/api/v1/students) Provides academic milestone and gradebook queries for students. """ from typing import Optional -from fastapi import APIRouter, Depends, HTTPException, Query, status +from fastapi import APIRouter, Depends, HTTPException, Query, Request, status from app.services.gradebook_service import GradebookService from dependencies import get_current_user @@ -13,14 +13,18 @@ students_router = APIRouter(prefix="/api/v1/students", tags=["Students"]) @students_router.get("/my-grades") -def get_my_grades(current_user: User = Depends(get_current_user)): +def get_my_grades( + request: Request, + current_user: User = Depends(get_current_user) +): """Consulta individual de calificaciones y estado académico del alumno logueado.""" try: grades = GradebookService.get_student_grades(current_user.id) + is_impersonating = bool(request.headers.get('X-Impersonate-User')) return { 'status': 'success', 'student_id': current_user.id, - 'is_impersonating': False, + 'is_impersonating': is_impersonating, 'data': grades } except Exception as e: diff --git a/backend/setup.py b/backend/setup.py index 4cf4efc..14bdf20 100644 --- a/backend/setup.py +++ b/backend/setup.py @@ -2,37 +2,35 @@ from setuptools import setup, find_packages setup( name="edu-space-admin", - version="3.7.0", - description="Administrative interface for Edu-Space Classroom Management System", + version="3.8.0", + description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)", author="Edu-Space Development Team", author_email="admin@edu-space.com", packages=find_packages(), include_package_data=True, install_requires=[ - "Flask==3.0.0", - "Flask-SQLAlchemy==3.1.1", - "Flask-Login==0.6.3", - "Flask-WTF==1.2.1", - "Flask-Migrate==4.0.5", - "Flask-CORS==4.0.0", - "WTForms==3.1.0", - "Werkzeug==3.0.1", - "SQLAlchemy==2.0.23", - "python-dotenv==1.0.0", - "requests==2.31.0", - "bleach==6.1.0", - "python-dateutil==2.8.2", - "Pillow==10.1.0" + "fastapi>=0.115.0", + "uvicorn[standard]>=0.30.0", + "pydantic>=2.0.0", + "SQLAlchemy>=2.0.32", + "psycopg2-binary>=2.9.10", + "python-dotenv>=1.0.0", + "requests>=2.31.0", + "httpx>=0.27.0", + "PyJWT>=2.8.0", + "cryptography>=42.0.0", + "Werkzeug>=3.0.1", + "python-dateutil>=2.8.2", + "bleach>=6.1.0", + "Pillow>=10.1.0" ], - python_requires=">=3.8", + python_requires=">=3.10", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Education", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", ], ) \ No newline at end of file diff --git a/frontend/package.json b/frontend/package.json index 36da83c..4744da9 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.7.0", + "version": "3.8.0", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/src/app.js b/frontend/src/app.js index 43fe9e9..2c948b0 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), { }); // Versiones institucionales del sistema -const APP_VERSION = '3.7.0'; -const FRONTEND_VERSION = '3.7.0'; -const BACKEND_VERSION = '3.7.0'; +const APP_VERSION = '3.8.0'; +const FRONTEND_VERSION = '3.8.0'; +const BACKEND_VERSION = '3.8.0'; env.addGlobal('app_version', APP_VERSION); env.addGlobal('frontend_version', FRONTEND_VERSION); diff --git a/scratch/clean_flask_context.py b/scratch/clean_flask_context.py new file mode 100644 index 0000000..afe0316 --- /dev/null +++ b/scratch/clean_flask_context.py @@ -0,0 +1,73 @@ +""" +Utility script to safely remove 'with flask_app.app_context():' blocks +and unindent their inner bodies by 4 spaces. +""" +import re +import sys +import py_compile + +def clean_file(filepath: str): + with open(filepath, 'r', encoding='utf-8') as f: + lines = f.readlines() + + new_lines = [] + i = 0 + in_context = False + context_indent = 0 + + while i < len(lines): + line = lines[i] + + # 1. Skip imports of get_flask_app + if re.match(r'^\s*from database import get_flask_app\s*$', line): + i += 1 + continue + if re.match(r'^\s*flask_app = get_flask_app\(\)\s*$', line): + i += 1 + continue + if re.match(r'^\s*f_app = get_flask_app\(\)\s*$', line): + i += 1 + continue + + # 2. Check for with flask_app.app_context(): + match = re.match(r'^(\s*)with (flask_app|f_app)\.app_context\(\):\s*$', line) + if match: + in_context = True + context_indent = len(match.group(1)) + i += 1 + continue + + if in_context: + if not line.strip(): + new_lines.append(line) + i += 1 + continue + + current_indent = len(line) - len(line.lstrip()) + if current_indent > context_indent: + # Unindent 4 spaces + if line.startswith(' ' * (context_indent + 4)): + unindented = line[4:] + else: + unindented = line[current_indent - context_indent:] + new_lines.append(unindented) + i += 1 + continue + else: + # Context ended + in_context = False + # Do not increment, process this line normally + + new_lines.append(line) + i += 1 + + content = ''.join(new_lines) + with open(filepath, 'w', encoding='utf-8') as f: + f.write(content) + + py_compile.compile(filepath, doraise=True) + print(f"Successfully cleaned & compiled {filepath}") + +if __name__ == '__main__': + for p in sys.argv[1:]: + clean_file(p) diff --git a/security_audit.bat b/security_audit.bat index c07da6d..c03d51a 100644 --- a/security_audit.bat +++ b/security_audit.bat @@ -91,9 +91,9 @@ echo Checking backend availability at %API_DOC_URL%... curl.exe -s -f -o nul "%API_DOC_URL%" if !ERRORLEVEL! neq 0 ( - echo [!] Warning: Local Flask backend is not responding on %API_DOC_URL% + echo [!] Warning: Local FastAPI backend is not responding on %API_DOC_URL% echo To run live DAST fuzzing, start the backend in another terminal: - echo cd backend ^&^& venv\Scripts\flask.exe run --port=5000 + echo cd backend ^&^& venv\Scripts\uvicorn.exe main:app --port=5000 echo [!] Skipping DAST fuzzing phase. ) else ( echo Target online. Running Schemathesis against OpenAPI spec... diff --git a/specs/004-depuracion-flask-total/plan.md b/specs/004-depuracion-flask-total/plan.md new file mode 100644 index 0000000..36c84c9 --- /dev/null +++ b/specs/004-depuracion-flask-total/plan.md @@ -0,0 +1,61 @@ +# Plan Técnico: 004-depuracion-flask-total - Erradicación Total de Flask y Migración a SQLAlchemy 2.0 Nativo + +## 1. Arquitectura de la Solución + +### 1.1. Capa de Persistencia Nativa (`backend/database.py` y `backend/app/__init__.py`) +Actualmente, los modelos (`Building`, `Classroom`, `User`, etc.) importan `db` desde `app` (`from app import db`), y dependen de propiedades como `db.Model`, `db.Column`, `db.relationship` y `db.session`. +Para desacoplarlo de Flask sin tener que reescribir manualmente cada modelo: +- Diseñamos una clase/adaptador `SQLAlchemyWrapper` en `backend/database.py` (o en `backend/app/db.py` reexportado en `app/__init__.py`) construido 100% sobre SQLAlchemy 2.0 estándar: + - `engine = create_engine(DATABASE_URL, pool_pre_ping=True, ...)` + - `SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)` + - `session = scoped_session(SessionLocal)` + - `Model = declarative_base()` + - Reexporta directamente tipos de SQLAlchemy: `Column = sa.Column`, `Integer = sa.Integer`, `String = sa.String`, `relationship = orm.relationship`, etc. + - Métodos `create_all()` y `drop_all()` ejecutados directamente contra `engine`. +- En `backend/database.py`, la dependencia FastAPI `get_db()` yieldará la sesión nativa: + ```python + def get_db(): + db_session = SessionLocal() + try: + yield db_session + finally: + db_session.close() + ``` +- Ya no existirá `get_flask_app()` ni necesidad de `flask_app.app_context()`. + +### 1.2. Limpieza de Routers (`backend/routers/*.py`) +- Remover: + ```python + from database import get_flask_app + flask_app = get_flask_app() + ``` +- Remover envoltorios `with flask_app.app_context():`. +- Las consultas accederán directamente a `db.session` (que es el `scoped_session` nativo de SQLAlchemy) o a la dependencia inyectada `db: Session = Depends(get_db)`. + +### 1.3. Poda de Archivos y Directorios Legados +- Eliminar recursivamente: + - `backend/app/routes/` (antiguo monolito Jinja2 y APIs de Flask). + - `backend/app/forms/` (formularios WTForms). +- Modificar: + - `install.sh`: eliminar `flask` de la verificación de dependencias. + - `backend/requirements.txt`: remover `Flask`, `Flask-SQLAlchemy`, `Flask-Login`, `Flask-WTF`, `Flask-Migrate`, `Flask-CORS`, `Flask-Babel`. + - `backend/setup.py`: remover las mismas dependencias de `install_requires`. + - `backend/app/__init__.py`: eliminar imports de Flask, `request`, `session`, `Babel`, `Migrate`, `CORS` y el registro de blueprints de Flask. + +### 1.4. Actualización del Arnés de Tests (`backend/tests/conftest.py`) +- Modificar `conftest.py` para inicializar SQLAlchemy en memoria (`sqlite:///:memory:`) sin depender de `create_app()` de Flask. +- Los tests que hacían peticiones HTTP utilizarán `fastapi.testclient.TestClient` apuntando a `backend.main:app`. + +--- + +## 2. Fases de Ejecución +1. **Fase 1: Motor SQLAlchemy 2.0 Desacoplado**: + Implementar la capa nativa de base de datos en `backend/database.py` y actualizar `backend/app/__init__.py`. +2. **Fase 2: Retiro de `app_context()` en Routers y Servicios**: + Eliminar `get_flask_app()` y `with flask_app.app_context():` de los routers de FastAPI. +3. **Fase 3: Eliminación de Código Muerto y Dependencias**: + Borrar carpetas `app/routes/` y `app/forms/`. Actualizar `requirements.txt`, `setup.py` e `install.sh`. +4. **Fase 4: Adaptación de Tests y Verificación**: + Actualizar `conftest.py` y correr la suite completa de 57 tests. +5. **Fase 5: Despliegue y Validación en Producción**: + Bump de versión, commit, git push a `dev` y despliegue a LXC `10.0.0.217`. diff --git a/specs/004-depuracion-flask-total/spec.md b/specs/004-depuracion-flask-total/spec.md new file mode 100644 index 0000000..e79512a --- /dev/null +++ b/specs/004-depuracion-flask-total/spec.md @@ -0,0 +1,38 @@ +# Espec: 004-depuracion-flask-total - Erradicación Total de Flask y Migración a SQLAlchemy 2.0 Nativo + +## 1. Visión General y Propósito +El backend de **admin-edu-space** completó la transición a una arquitectura FastAPI ASGI desacoplada y frontend BFF en Node.js/Express. Sin embargo, persisten remanentes de Flask en el repositorio: +- Código muerto en `backend/app/routes/` (antiguas vistas Jinja2) y `backend/app/forms/` (formularios WTForms). +- Dependencia artificial de `Flask` y `Flask-SQLAlchemy` en `backend/app/__init__.py` y `backend/database.py` únicamente para abastecer el contexto de aplicación (`flask_app.app_context()`) que requiere `db.session`. +- Dependencias residuales en `requirements.txt`, `setup.py` e `install.sh`. + +Esta especificación formaliza la eliminación completa de toda dependencia de Flask, centralizando la persistencia en SQLAlchemy 2.0 nativo (`scoped_session`, `sessionmaker`, `declarative_base`) e integrándolo de forma transparente con FastAPI. + +--- + +## 2. Requisitos en Sintaxis EARS (Español Estricto) + +### 2.1. Persistencia y Sesión de Base de Datos +- **RF-01 (Ubicuo)**: EL SISTEMA gestionará la persistencia y el ciclo de vida de sesiones relacionales mediante SQLAlchemy 2.0 nativo de forma agnóstica a cualquier microframework web, exportando `db.session` (`scoped_session`) y `db.Model` sin requerir ningún contexto de aplicación externo. +- **RF-02 (Ubicuo)**: EL SISTEMA inyectará la sesión de base de datos en los routers de FastAPI mediante la dependencia `get_db` garantizando cierre y rollback seguro ante excepciones no controladas. +- **RF-03 (Basado en Eventos)**: CUANDO un router de FastAPI (`backend/routers/*.py`) o servicio de negocio acceda a `db.session` o a los modelos ORM, EL SISTEMA ejecutará las consultas de forma directa sin requerir bloques auxiliares `with flask_app.app_context():`. +- **RF-04 (No Deseado / Excepciones)**: SI ocurre un error durante una transacción en una corrutina o hilo de FastAPI, ENTONCES EL SISTEMA revertirá los cambios pendientes con `session.rollback()` y liberará la conexión al pool. + +### 2.2. Depuración de Código Legado y Formularios +- **RF-05 (Ubicuo)**: EL SISTEMA eliminará permanentemente los módulos y directorios obsoletos de Flask (`backend/app/routes/` y `backend/app/forms/`), consolidando todos los contratos de entrada/salida exclusivamente en los esquemas de Pydantic v2 bajo `backend/schemas/` y los routers de FastAPI bajo `backend/routers/`. +- **RF-06 (Ubicuo)**: EL SISTEMA removerá las dependencias obsoletas `Flask`, `Flask-SQLAlchemy`, `Flask-Login`, `Flask-WTF`, `Flask-Migrate`, `Flask-CORS` y `Flask-Babel` de `requirements.txt`, `setup.py` e `install.sh`. + +### 2.3. Suite de Pruebas y Fixtures +- **RF-07 (Basado en Eventos)**: CUANDO se ejecuten las pruebas automatizadas (`pytest tests -v`), EL SISTEMA inicializará el entorno de testing en memoria (`sqlite:///:memory:`) utilizando el motor y sesión nativos de SQLAlchemy sin instanciar la clase `Flask` ni requerir `app.test_client()`. +- **RF-08 (Ubicuo)**: EL SISTEMA mantendrá el 100% de la suite de pruebas unitarias y de integración aprobada (mínimo 57 tests exitosos) sin degradación de cobertura ni regresiones. + +--- + +## 3. Criterios de Aceptación y Finalización (DoD) +1. Cero ocurrencias de `import flask` o `from flask` en todo el directorio `backend/` (excluyendo únicamente entornos virtuales `.venv`). +2. Directorios obsoletos `backend/app/routes/` y `backend/app/forms/` eliminados del árbol del proyecto. +3. Routers de `backend/routers/` operando sin imports de `get_flask_app` ni bloques `with flask_app.app_context():`. +4. Todos los modelos de `backend/app/models/` y servicios funcionando con el motor nativo de SQLAlchemy 2.0. +5. Cero problemas reportados por el Language Server (`@[current_problems]`). +6. Suite de pruebas pasando al 100% (`57 passed`). +7. Despliegue verificado en producción en `10.0.0.217` con HTTP 200 en `/version`. diff --git a/specs/004-depuracion-flask-total/tasks.md b/specs/004-depuracion-flask-total/tasks.md new file mode 100644 index 0000000..21d1569 --- /dev/null +++ b/specs/004-depuracion-flask-total/tasks.md @@ -0,0 +1,27 @@ +# Desglose de Tareas: 004-depuracion-flask-total - Erradicación Total de Flask + +## Tareas de Implementación + +- [X] **Tarea 1: Capa de Persistencia Nativa SQLAlchemy 2.0 en `backend/database.py` y `backend/app/__init__.py`** + - **Objetivo**: Crear adaptador nativo de SQLAlchemy (SessionLocal, scoped_session, Base declarativa, alias de tipos y session) y reexportarlo en `app.__init__.py` eliminando la inicialización de `Flask` y `Flask-SQLAlchemy`. + - **Hecho cuando**: Los modelos en `backend/app/models/` puedan importarse e interactuar con `db.session` y `db.Model` sin lanzar `RuntimeError: Working outside of application context`. + +- [X] **Tarea 2: Eliminar `flask_app.app_context()` y `get_flask_app` de los Routers FastAPI** + - **Objetivo**: Limpiar `backend/routers/` (`academic.py`, `admin.py`, `buildings.py`, `classrooms.py`, `dashboard.py`, `reservations.py`, `auth.py`) retirando los envoltorios `with flask_app.app_context():`. + - **Hecho cuando**: Ningún archivo en `backend/routers/` contenga `flask_app` ni `get_flask_app`. + +- [X] **Tarea 3: Poda de Código Muerto (`app/routes/` y `app/forms/`)** + - **Objetivo**: Eliminar permanentemente los directorios `backend/app/routes/` y `backend/app/forms/`. + - **Hecho cuando**: Los directorios ya no existan en el sistema de archivos y no queden imports rotos en el proyecto. + +- [X] **Tarea 4: Depuración de Scripts y Dependencias Residuales de Flask** + - **Objetivo**: Actualizar `install.sh`, `backend/requirements.txt` y `backend/setup.py` retirando `Flask`, `Flask-SQLAlchemy`, `Flask-WTF`, `Flask-Login`, `Flask-Migrate`, `Flask-CORS`, `Flask-Babel`. + - **Hecho cuando**: No haya referencias a librerías de Flask en los archivos de configuración y manifiestos de instalación. + +- [X] **Tarea 5: Adaptación de Fixtures en `backend/tests/conftest.py` y Verificación de Suite de Pruebas** + - **Objetivo**: Ajustar `conftest.py` para usar el motor de base de datos nativo y correr la suite de tests completa (`pytest tests -v`). + - **Hecho cuando**: Los 57 tests automatizados pasen al 100% (0 errores, 0 fallos) y `@[current_problems]` reporte 0 problemas. + +- [X] **Tarea 6: Bump Semántico, Git Push y Despliegue en Producción** + - **Objetivo**: Seguir la skill `deploy` y Principio 9 de la Constitución para incrementar versión a `3.8.0`, actualizar `CHANGELOG.md` y `MEMORY.md`, push a `dev` y desplegar a `10.0.0.217`. + - **Hecho cuando**: El endpoint remoto `/version` retorne HTTP 200 con versión `3.8.0` y estado `ok`.