feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi
This commit is contained in:
+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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user