feat(fastapi): migrar arquitectura completa a fastapi 100% nativo y retirar wsgimiddleware v3.7.0
This commit is contained in:
@@ -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.'
|
||||
}
|
||||
Reference in New Issue
Block a user