feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi
This commit is contained in:
+761
-794
File diff suppressed because it is too large
Load Diff
+756
-764
File diff suppressed because it is too large
Load Diff
+222
-229
@@ -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)}")
|
||||
|
||||
+183
-190
@@ -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.'
|
||||
}
|
||||
|
||||
+109
-116
@@ -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.'
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
|
||||
@@ -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'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+317
-322
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user