feat(api): migracion completa de Flask API a FastAPI ASGI con arquitectura en 4 capas v3.6.0
This commit is contained in:
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
__version__ = "3.5.7"
|
||||
__version__ = "3.6.0"
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
|
||||
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
|
||||
"info": {
|
||||
"title": "Edu-Space REST API",
|
||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||
"version": "3.5.7"
|
||||
"version": "3.6.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
||||
@@ -25,8 +25,15 @@ class JWTService:
|
||||
|
||||
@classmethod
|
||||
def _get_secret(cls) -> str:
|
||||
"""Obtiene la clave secreta desde la configuración de Flask."""
|
||||
return current_app.config.get('SECRET_KEY', 'default-edu-space-secret-key')
|
||||
"""Obtiene la clave secreta desde 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
|
||||
return getattr(Config, 'SECRET_KEY', 'default-edu-space-secret-key')
|
||||
|
||||
@classmethod
|
||||
def create_access_token(cls, user: User, expires_delta: Optional[timedelta] = None) -> str:
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
ASGI entrypoint for Admin Edu-Space (FastAPI).
|
||||
Utilized by systemd / uvicorn / gunicorn -k uvicorn.workers.UvicornWorker in production.
|
||||
"""
|
||||
from main import app
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("asgi:app", host="0.0.0.0", port=5000)
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
Database & Persistence Management for FastAPI (Capa 4)
|
||||
Integrates SQLAlchemy Engine, SessionLocal and get_db dependency.
|
||||
"""
|
||||
from typing import Generator
|
||||
from sqlalchemy.orm import Session
|
||||
from app import create_app, db as flask_db
|
||||
|
||||
# Initialize shared application context
|
||||
flask_app = create_app()
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""
|
||||
FastAPI dependency yielding the SQLAlchemy session within Flask app context
|
||||
to guarantee all models, ORM queries and services work seamlessly.
|
||||
"""
|
||||
with flask_app.app_context():
|
||||
yield flask_db.session
|
||||
|
||||
def get_flask_app():
|
||||
return flask_app
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
FastAPI Security & Authentication Dependencies
|
||||
Handles JWT extraction from HttpOnly cookies and Bearer headers,
|
||||
and implements declarative RBAC validation with app context.
|
||||
"""
|
||||
from typing import Optional, List, Callable
|
||||
from fastapi import Request, HTTPException, Depends, status
|
||||
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]:
|
||||
"""Extrae el token JWT desde cookies HttpOnly o cabecera Authorization Bearer."""
|
||||
token = request.cookies.get('access_token')
|
||||
if token:
|
||||
return token
|
||||
|
||||
auth_header = request.headers.get('Authorization')
|
||||
if auth_header and auth_header.startswith('Bearer '):
|
||||
return auth_header.split(' ', 1)[1].strip()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_current_user(request: Request) -> User:
|
||||
"""
|
||||
Dependencia FastAPI que resuelve y autentica al usuario actual.
|
||||
Lanza HTTP 401 si no hay token, si es inválido o si el usuario no existe.
|
||||
"""
|
||||
token = get_token_from_request(request)
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="No se proporcionó token de autenticación."
|
||||
)
|
||||
|
||||
try:
|
||||
payload = JWTService.decode_token(token, expected_type='access')
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="El token de acceso ha expirado."
|
||||
)
|
||||
except jwt.PyJWTError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"Token inválido: {str(e)}"
|
||||
)
|
||||
|
||||
user_id = payload.get('sub')
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token no contiene identificador de usuario válido."
|
||||
)
|
||||
|
||||
with flask_app.app_context():
|
||||
from sqlalchemy.orm import joinedload
|
||||
try:
|
||||
user = User.query.options(joinedload(User.role_obj)).get(int(user_id))
|
||||
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."
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_optional_current_user(request: Request) -> Optional[User]:
|
||||
"""Dependencia opcional: retorna el usuario autenticado o None si es anónimo."""
|
||||
token = get_token_from_request(request)
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
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))
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
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.).
|
||||
"""
|
||||
normalized_allowed = [r.lower() 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']
|
||||
|
||||
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
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
Admin Edu-Space - FastAPI Core Application (Principio 11)
|
||||
High-performance ASGI server with modular routers, Pydantic schemas,
|
||||
OpenAPI /docs documentation and zero-regression WSGI bridge.
|
||||
"""
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from a2wsgi import WSGIMiddleware
|
||||
|
||||
from app import __version__
|
||||
from database import get_flask_app
|
||||
|
||||
# Import modular FastAPI routers
|
||||
from routers.version import version_router
|
||||
from routers.auth import auth_router
|
||||
from routers.classrooms import classrooms_router
|
||||
from routers.reservations import reservations_router
|
||||
from routers.students import students_router
|
||||
from routers.dashboard import dashboard_router
|
||||
from routers.optimizer import optimizer_router, genetic_router
|
||||
|
||||
# Initialize FastAPI Application
|
||||
app = FastAPI(
|
||||
title="Admin Edu-Space REST API",
|
||||
description="Plataforma de gestión de espacios áulicos, sincronización académica y optimización inteligente.",
|
||||
version=__version__,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json"
|
||||
)
|
||||
|
||||
# CORS Middleware configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Register high-performance FastAPI Routers
|
||||
app.include_router(version_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(classrooms_router)
|
||||
app.include_router(reservations_router)
|
||||
app.include_router(students_router)
|
||||
app.include_router(dashboard_router)
|
||||
app.include_router(optimizer_router)
|
||||
app.include_router(genetic_router)
|
||||
|
||||
# Mount zero-regression WSGI bridge for remaining legacy routes and admin modules
|
||||
flask_app = get_flask_app()
|
||||
app.mount("/", WSGIMiddleware(flask_app))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=5000, reload=True)
|
||||
@@ -20,3 +20,7 @@ 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
|
||||
httpx>=0.27.0
|
||||
a2wsgi>=1.10.0
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Routers package initialization
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
FastAPI Authentication Router (/api/v1/auth)
|
||||
Implements Hybrid Authentication:
|
||||
- Local Authentication with Admin fallback
|
||||
- Google OAuth 2.0 institutional login
|
||||
- Moodle Delegated Authentication
|
||||
- Impersonation mode for Administrators
|
||||
- Dual Token JWT management with HttpOnly cookies
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.models.user import User
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.user_service import UserService
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.services.moodle_client import moodle_client
|
||||
from app.services.audit_service import AuditService
|
||||
from dependencies import get_current_user, require_roles, get_token_from_request
|
||||
from database import get_flask_app
|
||||
from schemas.auth import (
|
||||
LoginRequest,
|
||||
GoogleAuthRequest,
|
||||
MoodleAuthRequest,
|
||||
ImpersonateRequest,
|
||||
RefreshTokenRequest
|
||||
)
|
||||
|
||||
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')
|
||||
|
||||
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."
|
||||
)
|
||||
|
||||
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.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.")
|
||||
|
||||
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}."
|
||||
)
|
||||
|
||||
user = user_service.get_or_create_google_user(
|
||||
email=email,
|
||||
name=payload.name or email.split('@')[0],
|
||||
photo=payload.photo
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@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.")
|
||||
|
||||
user = user_service.authenticate_moodle(payload.username, payload.password)
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Credenciales de Moodle inválidas o usuario no sincronizado.")
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@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():
|
||||
profile = user_service.get_profile_data(user)
|
||||
return {
|
||||
'status': 'success',
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/logout")
|
||||
def logout(request: Request, response: Response):
|
||||
"""Cierra la sesión y revoca los tokens activos."""
|
||||
token = get_token_from_request(request)
|
||||
if token:
|
||||
try:
|
||||
JWTService.revoke_token(token)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
response.delete_cookie(key="access_token", path="/")
|
||||
response.delete_cookie(key="refresh_token", path="/api/v1/auth/refresh")
|
||||
return {'status': 'success', 'message': 'Sesión cerrada exitosamente.'}
|
||||
|
||||
|
||||
@auth_router.post("/refresh")
|
||||
def refresh_token(request: Request, response: Response, payload: Optional[RefreshTokenRequest] = None):
|
||||
"""Renueva el token de acceso a partir de un refresh token válido."""
|
||||
token = (payload and payload.refresh_token) or request.cookies.get('refresh_token')
|
||||
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')
|
||||
user = User.query.get(int(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)}")
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
FastAPI Classrooms Router (/api/v1/classrooms)
|
||||
Provides endpoints for listing, retrieving, creating, updating and toggling classrooms.
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
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
|
||||
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("")
|
||||
def list_classrooms(
|
||||
building_id: Optional[int] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
mode: Optional[str] = Query(None),
|
||||
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'
|
||||
|
||||
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 {
|
||||
'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)
|
||||
def create_classroom(
|
||||
dto: ClassroomCreateDTO,
|
||||
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))
|
||||
|
||||
|
||||
@classrooms_router.put("/{classroom_id}")
|
||||
def update_classroom(
|
||||
classroom_id: int,
|
||||
dto: ClassroomUpdateDTO,
|
||||
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.")
|
||||
|
||||
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}")
|
||||
def delete_classroom(
|
||||
classroom_id: int,
|
||||
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.")
|
||||
|
||||
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")
|
||||
def toggle_classroom(
|
||||
classroom_id: int,
|
||||
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.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.'
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
FastAPI Dashboard Router (/api/v1/dashboard)
|
||||
Provides operational metrics, today/tomorrow/week schedule, and Google Sheets sync inspection.
|
||||
"""
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, 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 dependencies import get_current_user
|
||||
from database import get_flask_app
|
||||
|
||||
dashboard_router = APIRouter(prefix="/api/v1/dashboard", tags=["Dashboard"])
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@dashboard_router.post("/sync-sheets")
|
||||
def sync_google_sheets(
|
||||
payload: Dict[str, Any],
|
||||
request: Request,
|
||||
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
|
||||
|
||||
|
||||
@dashboard_router.get("/sheets-inspect")
|
||||
@dashboard_router.post("/sheets-inspect")
|
||||
def inspect_google_sheets(
|
||||
request: Request,
|
||||
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
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
FastAPI Optimizer & Genetic Algorithm Router (/api/v1/optimizer and /api/genetic)
|
||||
Provides asynchronous optimization jobs and genetic heuristic room assignment.
|
||||
"""
|
||||
from typing import Optional, Dict, Any
|
||||
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
|
||||
|
||||
optimizer_router = APIRouter(prefix="/api/v1/optimizer", tags=["Optimizer"])
|
||||
genetic_router = APIRouter(prefix="/api/genetic", tags=["Genetic Heuristics"])
|
||||
|
||||
|
||||
@optimizer_router.post("/jobs", status_code=status.HTTP_202_ACCEPTED)
|
||||
def submit_optimization_job(
|
||||
dto: OptimizerJobRequestDTO,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Despacha un trabajo de optimización heurística asíncrono."""
|
||||
job = OptimizerService.submit_job(
|
||||
commission_ids=dto.commission_ids,
|
||||
admin_user_id=current_user.id,
|
||||
start_date=dto.start_date,
|
||||
end_date=dto.end_date,
|
||||
generations=dto.generations,
|
||||
population_size=dto.population_size,
|
||||
workers=dto.workers
|
||||
)
|
||||
|
||||
return {
|
||||
'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.'
|
||||
}
|
||||
|
||||
|
||||
@optimizer_router.get("/jobs/{job_id}")
|
||||
def get_optimization_job(
|
||||
job_id: str,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Obtiene el estado, progreso y resultados de un trabajo de optimización en cola."""
|
||||
job = OptimizerService.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Trabajo de optimización {job_id} no encontrado.")
|
||||
|
||||
return job.to_dict()
|
||||
|
||||
|
||||
@optimizer_router.get("/jobs")
|
||||
def list_optimization_jobs(
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista los trabajos de optimización más recientes."""
|
||||
jobs = OptimizerService.list_jobs(limit=limit)
|
||||
return {'total': len(jobs), 'jobs': jobs}
|
||||
|
||||
|
||||
@optimizer_router.post("/spring-boot/sync")
|
||||
def sync_with_spring_boot(
|
||||
dto: SpringBootSyncPayloadDTO,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Endpoint interoperable para la sincronización con microservicios Spring Boot."""
|
||||
try:
|
||||
result = OptimizerService.sync_with_spring_boot(dto, admin_user_id=current_user.id)
|
||||
return result
|
||||
except Exception as ex:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail={'requestId': dto.requestId, 'status': 'ERROR', 'error': str(ex)}
|
||||
)
|
||||
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,379 @@
|
||||
"""
|
||||
FastAPI Reservations Router (/api/v1/reservations)
|
||||
Handles creation, listing, updating, cancelling, confirmation and full conflict matrix validation.
|
||||
"""
|
||||
from typing import Optional, Any, Dict
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
|
||||
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 dependencies import get_current_user
|
||||
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("")
|
||||
def list_reservations(
|
||||
start_date: Optional[str] = Query(None),
|
||||
end_date: Optional[str] = Query(None),
|
||||
classroom_id: Optional[int] = Query(None),
|
||||
hide_virtual: Optional[str] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Consulta de reservas por rango de fechas y/o aula."""
|
||||
with flask_app.app_context():
|
||||
now = datetime.utcnow()
|
||||
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).")
|
||||
|
||||
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() != str(floor).strip().lower():
|
||||
continue
|
||||
if shift and r.shift and shift.lower() not in r.shift.lower():
|
||||
continue
|
||||
if search:
|
||||
s_lower = search.lower()
|
||||
subj_n = (r.subject_name or '').lower()
|
||||
subj_c = (r.subject_code or '').lower()
|
||||
c_name = (r.classroom.code if r.classroom else '').lower()
|
||||
u_name = (r.user.name if r.user else '').lower()
|
||||
if s_lower not in subj_n and s_lower not in subj_c and s_lower not in c_name and s_lower not in u_name:
|
||||
continue
|
||||
|
||||
result.append({
|
||||
'id': r.id,
|
||||
'classroom_id': r.classroom_id,
|
||||
'classroom_name': r.classroom.code if r.classroom else None,
|
||||
'classroom': {
|
||||
'id': r.classroom.id,
|
||||
'code': r.classroom.code,
|
||||
'code_display': getattr(r.classroom, 'code_display', r.classroom.code),
|
||||
'floor': r.classroom.floor,
|
||||
'floor_display': getattr(r.classroom, 'floor_display', f"Piso {r.classroom.floor}"),
|
||||
'building': getattr(r.classroom, 'building_name', r.classroom.building),
|
||||
'is_virtual': getattr(r.classroom, 'is_virtual', False),
|
||||
'location_display': getattr(r.classroom, 'location_display', r.classroom.code)
|
||||
} if r.classroom else None,
|
||||
'commission_id': r.commission_id,
|
||||
'commission': {
|
||||
'id': r.commission.id,
|
||||
'code': r.commission.code,
|
||||
'virtual_link': r.commission.virtual_link,
|
||||
'max_students': r.commission.max_students
|
||||
} if r.commission else None,
|
||||
'teacher_name': r.user.name if r.user else None,
|
||||
'user': {
|
||||
'id': r.user.id,
|
||||
'name': r.user.name,
|
||||
'email': r.user.email
|
||||
} if r.user else None,
|
||||
'start_time': r.start_time.isoformat(),
|
||||
'end_time': r.end_time.isoformat(),
|
||||
'purpose': r.purpose,
|
||||
'subject_name': r.subject_name,
|
||||
'subject_code': r.subject_code,
|
||||
'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
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
|
||||
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': 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
|
||||
}
|
||||
|
||||
|
||||
@reservations_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
def create_reservation(
|
||||
payload: Dict[str, Any],
|
||||
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
|
||||
|
||||
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))
|
||||
|
||||
|
||||
@reservations_router.put("/{reservation_id}")
|
||||
def update_reservation(
|
||||
reservation_id: int,
|
||||
dto: ReservationUpdateDTO,
|
||||
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))
|
||||
|
||||
|
||||
@reservations_router.delete("/{reservation_id}")
|
||||
def cancel_reservation(
|
||||
reservation_id: int,
|
||||
hard: Optional[str] = Query(None),
|
||||
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():
|
||||
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.")
|
||||
|
||||
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.")
|
||||
|
||||
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')
|
||||
|
||||
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).")
|
||||
|
||||
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))
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
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 app.services.gradebook_service import GradebookService
|
||||
from dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
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)):
|
||||
"""Consulta individual de calificaciones y estado académico del alumno logueado."""
|
||||
try:
|
||||
grades = GradebookService.get_student_grades(current_user.id)
|
||||
return {
|
||||
'status': 'success',
|
||||
'student_id': current_user.id,
|
||||
'is_impersonating': False,
|
||||
'data': grades
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@students_router.get("/my-upcoming-milestones")
|
||||
def get_my_upcoming_milestones(
|
||||
limit: int = Query(5, ge=1, le=50),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Próximas evaluaciones e hitos académicos con cuenta regresiva para el dashboard."""
|
||||
try:
|
||||
milestones = GradebookService.get_student_upcoming_milestones(current_user.id, limit=limit)
|
||||
return {'status': 'success', 'data': milestones}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
@@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter
|
||||
from app import __version__
|
||||
|
||||
version_router = APIRouter(prefix="/api/v1", tags=["Version"])
|
||||
|
||||
@version_router.get("/version")
|
||||
def get_version():
|
||||
return {
|
||||
"status": "success",
|
||||
"version": __version__,
|
||||
"engine": "FastAPI ASGI",
|
||||
"api_prefix": "/api/v1"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# Schemas package initialization
|
||||
@@ -0,0 +1,36 @@
|
||||
from typing import Optional, Dict, Any
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr = Field(..., description="Correo electrónico institucional o de acceso")
|
||||
password: str = Field(..., min_length=1, description="Contraseña de usuario")
|
||||
|
||||
|
||||
class RefreshTokenRequest(BaseModel):
|
||||
refresh_token: Optional[str] = Field(None, description="Token de refresco JWT")
|
||||
|
||||
|
||||
class GoogleAuthRequest(BaseModel):
|
||||
email: EmailStr = Field(..., description="Correo electrónico de Google institucional")
|
||||
name: Optional[str] = Field(None, description="Nombre completo")
|
||||
domain: Optional[str] = Field(None, description="Dominio de correo")
|
||||
photo: Optional[str] = Field(None, description="URL de foto de perfil")
|
||||
|
||||
|
||||
class MoodleAuthRequest(BaseModel):
|
||||
username: str = Field(..., min_length=1, description="DNI o nombre de usuario de Moodle")
|
||||
password: str = Field(..., min_length=1, description="Contraseña de Moodle")
|
||||
|
||||
|
||||
class ImpersonateRequest(BaseModel):
|
||||
user_id: int = Field(..., gt=0, description="ID del usuario objetivo a impersonar")
|
||||
|
||||
|
||||
class UserProfileResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
name: str
|
||||
role: str
|
||||
is_admin: bool
|
||||
role_obj: Optional[Dict[str, Any]] = None
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.5.7",
|
||||
version="3.6.0",
|
||||
description="Administrative interface for Edu-Space Classroom Management System",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
Test suite validating FastAPI ASGI Core & Routers.
|
||||
"""
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
from app.models.user import User
|
||||
from app.models.classroom import Classroom
|
||||
from app.services.jwt_service import JWTService
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
|
||||
def test_fastapi_version_endpoint():
|
||||
client = TestClient(app)
|
||||
response = client.get('/api/v1/version')
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data['status'] == 'success'
|
||||
assert 'version' in data
|
||||
assert data['engine'] == 'FastAPI ASGI'
|
||||
|
||||
|
||||
def test_fastapi_docs_endpoint():
|
||||
client = TestClient(app)
|
||||
response = client.get('/docs')
|
||||
assert response.status_code == 200
|
||||
assert 'swagger-ui' in response.text.lower() or 'html' in response.text.lower()
|
||||
|
||||
|
||||
def test_fastapi_auth_providers(init_database):
|
||||
client = TestClient(app)
|
||||
response = client.get('/api/v1/auth/providers')
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data['status'] == 'success'
|
||||
assert 'providers' in data
|
||||
assert 'local' in data['providers']
|
||||
|
||||
|
||||
def test_fastapi_auth_login_invalid(init_database):
|
||||
client = TestClient(app)
|
||||
response = client.post('/api/v1/auth/login', json={'email': 'inexistente@unicaba.edu.ar', 'password': 'wrong'})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_fastapi_full_flow_auth_and_classrooms(init_database):
|
||||
client = TestClient(app)
|
||||
|
||||
# 1. Crear usuario Admin de prueba
|
||||
u = User(
|
||||
email="admin.fastapi@unicaba.edu.ar",
|
||||
name="Admin FastAPI",
|
||||
password_hash=generate_password_hash("Secret123!"),
|
||||
role="ADMIN",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(u)
|
||||
init_database.session.commit()
|
||||
|
||||
# 2. Login
|
||||
login_res = client.post('/api/v1/auth/login', json={
|
||||
'email': 'admin.fastapi@unicaba.edu.ar',
|
||||
'password': 'Secret123!'
|
||||
})
|
||||
assert login_res.status_code == 200
|
||||
login_data = login_res.json()
|
||||
token = login_data['access_token']
|
||||
assert token is not None
|
||||
|
||||
# 3. GET /me con Bearer token
|
||||
me_res = client.get('/api/v1/auth/me', headers={'Authorization': f'Bearer {token}'})
|
||||
assert me_res.status_code == 200
|
||||
assert me_res.json()['user']['email'] == 'admin.fastapi@unicaba.edu.ar'
|
||||
|
||||
# 4. GET /classrooms
|
||||
classrooms_res = client.get('/api/v1/classrooms', headers={'Authorization': f'Bearer {token}'})
|
||||
assert classrooms_res.status_code == 200
|
||||
assert 'classrooms' in classrooms_res.json()
|
||||
+10
-4
@@ -1,7 +1,13 @@
|
||||
from app import create_app
|
||||
"""
|
||||
WSGI / ASGI compatibility bridge for Gunicorn and systemd.
|
||||
Exports FastAPI application adapted via a2wsgi.ASGIMiddleware for zero-downtime compatibility.
|
||||
"""
|
||||
from main import app as fastapi_app
|
||||
from a2wsgi import ASGIMiddleware
|
||||
|
||||
app = create_app()
|
||||
# Adapt ASGI FastAPI app into WSGI callable for Gunicorn
|
||||
app = ASGIMiddleware(fastapi_app)
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Server entrypoint with auto-reload (RBAC 8 modules, ∞ Infinite Capacity & Clean Class Hours active)
|
||||
app.run(debug=True, host='0.0.0.0', port=5000)
|
||||
import uvicorn
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=5000, reload=True)
|
||||
Reference in New Issue
Block a user