488 lines
21 KiB
Python
488 lines
21 KiB
Python
"""
|
|
FastAPI Reservations Router (/api/v1/reservations)
|
|
Handles creation, listing, updating, cancelling, confirmation and full conflict matrix validation.
|
|
"""
|
|
from typing import Optional, Any, Dict
|
|
from datetime import datetime, timedelta, timezone
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
|
|
|
from app import db
|
|
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
|
|
from dependencies import get_current_user, get_request_payload
|
|
from app.models.user import User
|
|
|
|
reservations_router = APIRouter(prefix="/api/v1/reservations", tags=["Reservations"])
|
|
reservation_service = ReservationService()
|
|
|
|
|
|
@reservations_router.get("")
|
|
def list_reservations(
|
|
start_date: Optional[str] = Query(None),
|
|
end_date: Optional[str] = Query(None),
|
|
classroom_id: Optional[str] = Query(None),
|
|
hide_virtual: Optional[str] = Query(None),
|
|
floor: Optional[str] = Query(None),
|
|
shift: Optional[str] = Query(None),
|
|
search: Optional[str] = Query(None),
|
|
limit: int = Query(1000, le=5000),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""Consulta de reservas por rango de fechas y/o aula con filtros en SQL."""
|
|
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).")
|
|
|
|
is_hide_virtual = str(hide_virtual).lower() in ['1', 'true']
|
|
parsed_classroom_id = int(classroom_id.strip()) if classroom_id and classroom_id.strip().isdigit() else None
|
|
|
|
reservations = reservation_service.list_reservations(
|
|
start_dt, end_dt,
|
|
classroom_id=parsed_classroom_id,
|
|
is_hide_virtual=is_hide_virtual,
|
|
floor=floor,
|
|
shift=shift,
|
|
search=search,
|
|
limit=limit
|
|
)
|
|
result = []
|
|
for r in reservations:
|
|
r_user: Any = getattr(r, 'user', None)
|
|
|
|
is_virt = bool(r.is_virtual or (r.classroom and getattr(r.classroom, 'is_virtual', False)))
|
|
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."""
|
|
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)
|
|
def create_reservation(
|
|
payload: Dict[str, Any],
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""Crea una reserva aplicando validación DTO y detección de colisiones."""
|
|
if 'user_id' not in payload:
|
|
payload['user_id'] = current_user.id
|
|
|
|
try:
|
|
dto = ReservationCreateDTO(**payload)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
|
|
|
try:
|
|
reservation = reservation_service.create_reservation(dto)
|
|
AuditService.log(
|
|
action='CREATE',
|
|
module='reservations',
|
|
entity_id=reservation.id,
|
|
user=current_user,
|
|
details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}"
|
|
)
|
|
return {
|
|
'message': 'Reserva creada exitosamente.',
|
|
'id': reservation.id,
|
|
'classroom_id': reservation.classroom_id,
|
|
'start_time': reservation.start_time.isoformat(),
|
|
'end_time': reservation.end_time.isoformat(),
|
|
'status': str(reservation.status)
|
|
}
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
|
|
|
|
|
@reservations_router.put("/{reservation_id}")
|
|
def update_reservation(
|
|
reservation_id: int,
|
|
dto: ReservationUpdateDTO,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""Modifica una reserva existente."""
|
|
try:
|
|
reservation = reservation_service.update_reservation(reservation_id, dto)
|
|
AuditService.log(
|
|
action='UPDATE',
|
|
module='reservations',
|
|
entity_id=reservation.id,
|
|
user=current_user,
|
|
details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}"
|
|
)
|
|
return {
|
|
'message': 'Reserva actualizada exitosamente.',
|
|
'id': reservation.id,
|
|
'start_time': reservation.start_time.isoformat(),
|
|
'end_time': reservation.end_time.isoformat(),
|
|
'status': str(reservation.status)
|
|
}
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
|
|
|
|
|
@reservations_router.delete("/{reservation_id}")
|
|
def cancel_reservation(
|
|
reservation_id: int,
|
|
hard: Optional[str] = Query(None),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""Cancela o elimina una reserva según el parámetro hard."""
|
|
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)."""
|
|
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)."""
|
|
cancelled = reservation_service.cancel_reservation(reservation_id)
|
|
if not cancelled:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
|
|
|
AuditService.log(
|
|
action='CANCEL',
|
|
module='reservations',
|
|
entity_id=reservation_id,
|
|
user=current_user,
|
|
details=f"Reserva #{reservation_id} cancelada"
|
|
)
|
|
return {'message': f'Reserva {reservation_id} cancelada correctamente.'}
|
|
|
|
|
|
@reservations_router.post("/{reservation_id}/confirm")
|
|
def confirm_reservation(reservation_id: int, current_user: User = Depends(get_current_user)):
|
|
"""Confirma una reserva cambiando su estado a CONFIRMED."""
|
|
confirmed = reservation_service.confirm_reservation(reservation_id)
|
|
if not confirmed:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
|
|
|
AuditService.log(
|
|
action='CONFIRM',
|
|
module='reservations',
|
|
entity_id=reservation_id,
|
|
user=current_user,
|
|
details=f"Reserva #{reservation_id} confirmada oficialmente"
|
|
)
|
|
return {'message': f'Reserva {reservation_id} confirmada correctamente.'}
|
|
|
|
|
|
@reservations_router.post("/check-conflicts")
|
|
def check_conflicts_endpoint(payload: Dict[str, Any], current_user: User = Depends(get_current_user)):
|
|
"""Evalúa la matriz completa de conflictos (físico, docente y aforo) en tiempo real."""
|
|
classroom_id = payload.get('classroom_id')
|
|
start_str = payload.get('start_time')
|
|
end_str = payload.get('end_time')
|
|
|
|
if not classroom_id or not start_str or not end_str:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="classroom_id, start_time y end_time son obligatorios.")
|
|
|
|
try:
|
|
start_time = datetime.fromisoformat(str(start_str).replace('Z', '+00:00'))
|
|
end_time = datetime.fromisoformat(str(end_str).replace('Z', '+00:00'))
|
|
except ValueError:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de fecha/hora (ISO 8601 esperado).")
|
|
|
|
teacher_id = payload.get('teacher_id')
|
|
commission_id = payload.get('commission_id')
|
|
expected_attendees = payload.get('expected_attendees')
|
|
allow_co_teaching = bool(payload.get('allow_co_teaching_exception', False))
|
|
exclude_id = payload.get('exclude_id')
|
|
|
|
try:
|
|
matrix = reservation_service.check_full_conflicts_matrix(
|
|
classroom_id=int(classroom_id),
|
|
start_time=start_time,
|
|
end_time=end_time,
|
|
teacher_id=int(teacher_id) if teacher_id else None,
|
|
commission_id=int(commission_id) if commission_id else None,
|
|
expected_attendees=int(expected_attendees) if expected_attendees is not None else None,
|
|
allow_co_teaching_exception=allow_co_teaching,
|
|
exclude_id=int(exclude_id) if exclude_id else None
|
|
)
|
|
return matrix
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
|
|
|
|
|
@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 = await get_request_payload(request)
|
|
|
|
res_id_raw = data.get('reservation_id')
|
|
reservation_id = int(str(res_id_raw)) if res_id_raw is not None and str(res_id_raw).isdigit() else None
|
|
comm_id_raw = data.get('commission_id')
|
|
commission_id = int(str(comm_id_raw)) if comm_id_raw is not None and str(comm_id_raw).isdigit() else None
|
|
cls_id_raw = data.get('classroom_id')
|
|
if cls_id_raw is None or not str(cls_id_raw).isdigit():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="classroom_id es obligatorio y debe ser numérico."
|
|
)
|
|
classroom_id = int(str(cls_id_raw))
|
|
start_time_str = str(data.get('start_time') or '').strip()
|
|
end_time_str = str(data.get('end_time') or '').strip()
|
|
|
|
if not start_time_str or not end_time_str:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Faltan parámetros obligatorios (inicio, fin)."
|
|
)
|
|
|
|
try:
|
|
start_dt: datetime = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
|
|
end_dt: datetime = datetime.fromisoformat(end_time_str.replace('Z', '+00:00'))
|
|
except Exception as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Formato de fecha inválido: {str(e)}"
|
|
)
|
|
|
|
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
|
|
|
|
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,
|
|
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()
|
|
}
|