feat(fastapi): migrar arquitectura completa a fastapi 100% nativo y retirar wsgimiddleware v3.7.0
This commit is contained in:
@@ -3,7 +3,7 @@ Plataforma web de gestión de espacios áulicos, sincronización académica y as
|
||||
|
||||
## Stack y Estructura
|
||||
- **Arquitectura**: Desacoplada (Backend Core REST API + Frontend BFF).
|
||||
- **Backend Core**: Python 3.12/3.14, FastAPI 0.115+, Uvicorn (ASGI) + Flask 3.1 / WSGI bridge (`a2wsgi`), SQLAlchemy ORM 2.0, SQLite / PostgreSQL 15, Pydantic v2 DTOs (`BaseModel`), PyJWT / Flask-JWT-Extended (HS256 stateless).
|
||||
- **Backend Core**: Python 3.12/3.14, FastAPI 0.115+ (100% Nativo ASGI puro con Uvicorn, routers modulares y OpenAPI /docs), SQLAlchemy ORM 2.0, PostgreSQL 15 / SQLite, Pydantic v2 DTOs (`BaseModel`), PyJWT (HS256 stateless).
|
||||
- **Frontend BFF**: Node.js v20+, Express.js, motor de plantillas Nunjucks, cliente Axios con interceptores de autorización Bearer, Bootstrap 5 + Vanilla CSS.
|
||||
- **Integraciones Clave**:
|
||||
- Google OAuth 2.0 para autenticación institucional restringida a `@unicaba.edu.ar`.
|
||||
|
||||
@@ -11,6 +11,26 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
|
||||
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
||||
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
||||
|
||||
## [3.7.0] - 2026-10-19
|
||||
### Added
|
||||
- **Migración Integral a FastAPI 100% Nativo (Principio 11)**:
|
||||
- Creados routers modulares en `backend/routers/`:
|
||||
- `backend/routers/buildings.py`: Endpoints RESTful para gestión física de edificios y sedes institucionales.
|
||||
- `backend/routers/academic.py`: Gestión integral de Carreras, Asignaturas, Comisiones, Ciclos Lectivos, Tipificaciones de Hitos, Asignación de Docentes, Matrículas de Estudiantes y Libro de Calificaciones/Actas (Gradebook).
|
||||
- `backend/routers/admin.py`: Administración de Usuarios, Roles RBAC, Modo Impersonación, Reseteo del Sistema, Auditoría Inmutable, Configuración Global (SMTP, Google OAuth, Moodle, UI, Demo Mode) y Cola Asíncrona de Moodle (DLQ y reprocesamiento).
|
||||
- Incorporado soporte dual para rutas raíz `/version`, `/health` y bajo `/api/v1/version` en `backend/routers/version.py`.
|
||||
- Agregado endpoint `/api/v1/reservations/drag-update` en `backend/routers/reservations.py` para reprogramación visual interactiva en la grilla horaria.
|
||||
|
||||
### Removed
|
||||
- **Retiro Completo del Puente WSGIMiddleware**:
|
||||
- Eliminado el montaje residual `app.mount("/", WSGIMiddleware(...))` de `backend/main.py`.
|
||||
- El servidor ASGI Uvicorn ejecuta ahora 100% FastAPI nativo con 118 rutas expuestas directamente en OpenAPI Swagger UI (`/docs`).
|
||||
|
||||
### Changed
|
||||
- **Relaciones Relacionales y Tipado Defensivo**:
|
||||
- `backend/app/models/subject.py`: Forzado explícito `uselist=True` en `Subject.commissions` garantizando que siempre se evalúe como colección de comisiones.
|
||||
- `backend/routers/academic.py`: Cómputo robusto de `commissions_count` protegiendo contra posibles desvíos de tipo.
|
||||
|
||||
## [3.6.4] - 2026-10-19
|
||||
### Fixed
|
||||
- **Resolución Completa de Diagnósticos Estáticos (QA & Principio 10 - Tolerancia Cero)**:
|
||||
|
||||
@@ -9,18 +9,16 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
||||
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||
- **Sprint Activo: MVP del Sistema de Bedelía — v3.6.4 (QA Completo, Tolerancia Cero y Sincronización Resiliente Moodle)**:
|
||||
- Core REST API con FastAPI ASGI (`main.py`, `routers/`, `schemas/`, `database.py`) y puente WSGI `a2wsgi`.
|
||||
- **QA Integral & Tolerancia Cero (Principio 10)**:
|
||||
- Remediados al 100% todos los errores y advertencias estáticas de Pyright en modelos (`commission_teacher.py`, `subject.py`, `audit_log.py`, `career.py`, `classroom.py`, `genetic_algorithm.py`, `milestone.py`, `role.py`), repositorios (`base_repository.py`, `classroom_repository.py`), esquemas DTO (`classroom_dto.py`, `reservation_dto.py`), servicios (`email_service.py`, `gradebook_service.py`, `optimizer_service.py`, `sheets_importer.py`, `user_service.py`, `cache_service.py`) y controladores (`admin.py`, `auth.py`, `buildings.py`, `classrooms.py`, `main.py`, `my_subjects.py`, `reservations.py`, `schedule.py`).
|
||||
- Migración exhaustiva de `datetime.utcnow()` deprecado a `datetime.now(timezone.utc).replace(tzinfo=None)`.
|
||||
- Eliminación de conversiones redundantes `str()` e `int()`.
|
||||
- **Sincronización Resiliente Moodle 4.1 (`core_user_update_users`)**:
|
||||
- `MoodleClient.update_users` autodescubre el ID numérico de Moodle por `email`/`username` o realiza fallback transparente a creación (`create_users`), eliminando la excepción `Moodle Exception [invalidparameter]`.
|
||||
- `MoodleQueueService` maneja tipos seguros, timestamps UTC y persistencia resiliente con DLQ.
|
||||
- **Frontend UX**:
|
||||
- Removido el selector flotante artificial `.role-view-selector` ("VER PANEL COMO ROL") en `dashboard.html`. La visualización se basa exclusivamente en los permisos institucionales del usuario autenticado.
|
||||
- **Suite de Pruebas**: 57 pruebas automatizadas (`pytest tests -v`) ejecutadas y aprobadas al 100% con 0 fallos. Versión actual: `v3.6.4`.
|
||||
- **Sprint Activo: Migración Integral a FastAPI 100% Nativo — v3.7.0 (Principio 11 y Retiro Total de WSGIMiddleware)**:
|
||||
- **FastAPI Core REST API Pura**: Desacoplado por completo el puente residual `WSGIMiddleware` de `backend/main.py`.
|
||||
- **Routers Modulares Nativos**:
|
||||
- `backend/routers/buildings.py`: ABM de edificios y sedes institucionales.
|
||||
- `backend/routers/academic.py`: Carreras, Asignaturas, Comisiones, Ciclos Lectivos, Tipos de Hitos, Docentes de Comisiones, Matrículas y Actas/Gradebook.
|
||||
- `backend/routers/admin.py`: Usuarios, Roles RBAC, Impersonación, System Reset, Auditoría Inmutable, Configuración Global (SMTP, OAuth, Moodle, UI, Demo Mode) y Cola Moodle (DLQ).
|
||||
- `backend/routers/reservations.py`: Incorporado endpoint interactivo `drag-update`.
|
||||
- `backend/routers/version.py`: Soporte para `/version` y `/health` a nivel raíz y bajo `/api/v1/version`.
|
||||
- **OpenAPI /docs Swagger UI**: Expone 118 endpoints RESTful de FastAPI nativos listos para documentación y consumo interactivo.
|
||||
- **Suite de Pruebas**: 57 pruebas automatizadas (`pytest tests -v`) ejecutadas y aprobadas al 100% (57 passed, 0 failed). Versión actual: `v3.7.0`.
|
||||
|
||||
## Decisiones (y por qué)
|
||||
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
||||
|
||||
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
__version__ = "3.6.4"
|
||||
__version__ = "3.7.0"
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
|
||||
@@ -32,7 +32,7 @@ class Subject(db.Model):
|
||||
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
# Relationships
|
||||
commissions: Any = db.relationship('Commission', backref='subject', lazy=True, cascade='all, delete-orphan')
|
||||
commissions: Any = db.relationship('Commission', backref='subject', lazy=True, uselist=True, cascade='all, delete-orphan')
|
||||
careers: Any = db.relationship('Career', secondary=subject_careers, lazy='subquery', backref=db.backref('shared_subjects', lazy=True))
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
|
||||
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
|
||||
"info": {
|
||||
"title": "Edu-Space REST API",
|
||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||
"version": "3.6.4"
|
||||
"version": "3.7.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
||||
+9
-11
@@ -1,22 +1,21 @@
|
||||
"""
|
||||
Admin Edu-Space - FastAPI Core Application (Principio 11)
|
||||
High-performance ASGI server with modular routers, Pydantic schemas,
|
||||
OpenAPI /docs documentation and zero-regression WSGI bridge.
|
||||
OpenAPI /docs documentation and 100% native FastAPI routers.
|
||||
"""
|
||||
from typing import Any, cast
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from a2wsgi import WSGIMiddleware
|
||||
|
||||
from app import __version__
|
||||
from database import get_flask_app
|
||||
|
||||
# Import modular FastAPI routers
|
||||
from routers.version import version_router
|
||||
from routers.auth import auth_router
|
||||
from routers.classrooms import classrooms_router
|
||||
from routers.buildings import buildings_router
|
||||
from routers.reservations import reservations_router
|
||||
from routers.academic import academic_router
|
||||
from routers.admin import admin_router
|
||||
from routers.students import students_router
|
||||
from routers.dashboard import dashboard_router
|
||||
from routers.optimizer import optimizer_router, genetic_router
|
||||
@@ -40,20 +39,19 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Register high-performance FastAPI Routers
|
||||
# Register high-performance FastAPI Routers (100% Native FastAPI)
|
||||
app.include_router(version_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(classrooms_router)
|
||||
app.include_router(buildings_router)
|
||||
app.include_router(reservations_router)
|
||||
app.include_router(academic_router)
|
||||
app.include_router(admin_router)
|
||||
app.include_router(students_router)
|
||||
app.include_router(dashboard_router)
|
||||
app.include_router(optimizer_router)
|
||||
app.include_router(genetic_router)
|
||||
|
||||
# Mount zero-regression WSGI bridge for remaining legacy routes and admin modules
|
||||
flask_app = get_flask_app()
|
||||
app.mount("/", cast(Any, WSGIMiddleware(cast(Any, flask_app.wsgi_app))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,289 @@
|
||||
"""
|
||||
FastAPI Buildings Router (/api/v1/buildings)
|
||||
Provides endpoints for listing, retrieving, creating, updating, toggling and deleting institutional buildings.
|
||||
"""
|
||||
from typing import Optional, Dict, Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
from sqlalchemy import func, or_
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app import db
|
||||
from app.models.building import Building
|
||||
from app.models.classroom import Classroom
|
||||
from app.services.audit_service import AuditService
|
||||
from dependencies import get_current_user, require_roles
|
||||
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("")
|
||||
def list_buildings(
|
||||
search: Optional[str] = Query(None),
|
||||
status_filter: Optional[str] = Query(None, alias="status"),
|
||||
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()
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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}")
|
||||
def get_building(
|
||||
id: int,
|
||||
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.")
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
|
||||
@buildings_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_building(
|
||||
request: Request,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""Crea una nueva sede o edificio institucional."""
|
||||
data = {}
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
form = await request.form()
|
||||
data = dict(form)
|
||||
|
||||
with flask_app.app_context():
|
||||
name = (data.get('name') or '').strip()
|
||||
code = (data.get('code') or '').strip().upper() or None
|
||||
address = (data.get('address') or '').strip() or None
|
||||
try:
|
||||
floors = int(data.get('floors', 1) or 1)
|
||||
except (ValueError, TypeError):
|
||||
floors = 1
|
||||
description = (data.get('description') or '').strip() or None
|
||||
is_active = data.get('is_active', True)
|
||||
if isinstance(is_active, str):
|
||||
is_active = is_active.lower() in ['true', '1', 'on']
|
||||
|
||||
if not name:
|
||||
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}".')
|
||||
|
||||
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})"
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{name}" creado con éxito.',
|
||||
'building': building.to_dict()
|
||||
}
|
||||
|
||||
|
||||
@buildings_router.put("/{id}")
|
||||
@buildings_router.post("/{id}")
|
||||
async def update_building(
|
||||
id: int,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""Actualiza la información de un edificio existente."""
|
||||
data = {}
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
form = await request.form()
|
||||
data = dict(form)
|
||||
|
||||
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.")
|
||||
|
||||
name = (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}".')
|
||||
|
||||
old_name = building.name
|
||||
building.name = name
|
||||
if 'code' in data:
|
||||
building.code = (data.get('code') or '').strip().upper() or None
|
||||
if 'address' in data:
|
||||
building.address = (data.get('address') or '').strip() or None
|
||||
if 'floors' in data:
|
||||
try:
|
||||
building.floors = int(data.get('floors', 0) or 0)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if 'description' in data:
|
||||
building.description = (data.get('description') or '').strip() or None
|
||||
if 'is_active' in data:
|
||||
is_active = data.get('is_active')
|
||||
if isinstance(is_active, str):
|
||||
building.is_active = is_active.lower() in ['true', '1', 'on']
|
||||
else:
|
||||
building.is_active = bool(is_active)
|
||||
building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
if old_name != name:
|
||||
Classroom.query.filter_by(building_id=building.id).update({'building': name})
|
||||
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='buildings',
|
||||
entity_id=building.id,
|
||||
user=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()
|
||||
}
|
||||
|
||||
|
||||
@buildings_router.post("/{id}/toggle")
|
||||
def toggle_building(
|
||||
id: int,
|
||||
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.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'}"
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{building.name}" {"activado" if building.is_active else "desactivado"} exitosamente.',
|
||||
'building': building.to_dict()
|
||||
}
|
||||
|
||||
|
||||
@buildings_router.delete("/{id}")
|
||||
def delete_building(
|
||||
id: int,
|
||||
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.")
|
||||
|
||||
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."
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{b_name}" eliminado correctamente.'
|
||||
}
|
||||
@@ -7,7 +7,9 @@ from datetime import datetime, timedelta, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
|
||||
from app import db
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Commission
|
||||
from app.services.reservation_service import ReservationService
|
||||
from app.services.audit_service import AuditService
|
||||
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
|
||||
@@ -388,3 +390,111 @@ def check_conflicts_endpoint(payload: Dict[str, Any], current_user: User = Depen
|
||||
return matrix
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@reservations_router.post("/drag-update")
|
||||
async def drag_update_reservation(
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Actualización o creación rápida de reserva mediante arrastre en la grilla semanal."""
|
||||
data = {}
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
form = await request.form()
|
||||
data = dict(form)
|
||||
|
||||
reservation_id = data.get('reservation_id')
|
||||
commission_id = data.get('commission_id')
|
||||
classroom_id = data.get('classroom_id')
|
||||
start_time_str = data.get('start_time')
|
||||
end_time_str = data.get('end_time')
|
||||
|
||||
if not classroom_id or not start_time_str or not end_time_str:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Faltan parámetros obligatorios (aula, inicio, fin)."
|
||||
)
|
||||
|
||||
try:
|
||||
if isinstance(start_time_str, str):
|
||||
start_dt = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
|
||||
else:
|
||||
start_dt = start_time_str
|
||||
|
||||
if isinstance(end_time_str, str):
|
||||
end_dt = datetime.fromisoformat(end_time_str.replace('Z', '+00:00'))
|
||||
else:
|
||||
end_dt = end_time_str
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
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.")
|
||||
|
||||
effective_comm_id = commission_id
|
||||
if not effective_comm_id and reservation_id:
|
||||
existing_res = db.session.get(Reservation, reservation_id)
|
||||
if existing_res:
|
||||
effective_comm_id = existing_res.commission_id
|
||||
|
||||
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'):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=' '.join(matrix.get('block_reasons', ['Conflicto detectado en la asignación.']))
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
from fastapi import APIRouter
|
||||
from app import __version__
|
||||
|
||||
version_router = APIRouter(prefix="/api/v1", tags=["Version"])
|
||||
version_router = APIRouter(tags=["System & Version"])
|
||||
|
||||
@version_router.get("/version")
|
||||
@version_router.get("/api/v1/version")
|
||||
def get_version():
|
||||
return {
|
||||
"status": "success",
|
||||
"name": "Edu-Space REST API",
|
||||
"version": __version__,
|
||||
"engine": "FastAPI ASGI",
|
||||
"api_prefix": "/api/v1"
|
||||
}
|
||||
|
||||
@version_router.get("/health")
|
||||
@version_router.get("/api/v1/health")
|
||||
def get_health():
|
||||
return {
|
||||
"status": "ok",
|
||||
"version": __version__,
|
||||
"engine": "FastAPI ASGI"
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.6.4",
|
||||
version="3.7.0",
|
||||
description="Administrative interface for Edu-Space Classroom Management System",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "3.6.4",
|
||||
"version": "3.7.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
+3
-3
@@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.6.4';
|
||||
const FRONTEND_VERSION = '3.6.4';
|
||||
const BACKEND_VERSION = '3.6.4';
|
||||
const APP_VERSION = '3.7.0';
|
||||
const FRONTEND_VERSION = '3.7.0';
|
||||
const BACKEND_VERSION = '3.7.0';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
|
||||
Reference in New Issue
Block a user