281 lines
9.6 KiB
Python
281 lines
9.6 KiB
Python
"""
|
|
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
|
|
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, get_request_payload
|
|
from app.models.user import User
|
|
|
|
buildings_router = APIRouter(prefix="/api/v1/buildings", tags=["Buildings"])
|
|
|
|
|
|
@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."""
|
|
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."""
|
|
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 = await get_request_payload(request)
|
|
|
|
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.")
|
|
|
|
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 = await get_request_payload(request)
|
|
|
|
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.")
|
|
|
|
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)
|
|
|
|
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."""
|
|
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."""
|
|
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.'
|
|
}
|