- /casos con filtros por estado, responsable y cliente; /casos/nuevo?alerta_id= preselecciona la alerta y ofrece las demás abiertas del cliente; /casos/<id> con alertas vinculadas, línea de tiempo cronológica, nota o adjunto, cambio de estado, cierre y descarga auditada - Escalar en /alertas/<id> abre el formulario de caso; si la alerta ya está en un caso abierto, enlaza a él - ficha del cliente con sus casos; permisos: analista y oficial mutan, cerrar solo oficial, auditor lee y descarga
360 lines
13 KiB
Python
360 lines
13 KiB
Python
"""Router `casos`: lista, apertura desde alertas, detalle con línea de tiempo, eventos con adjunto,
|
|
cambio de estado, cierre con decisión y fundamento, y descarga auditada de adjuntos (Fase 3).
|
|
|
|
Permisos: `analista` abre casos, agrega eventos y avanza el estado hasta `escalado`; cerrar
|
|
exige `oficial`; `auditor` solo lee y descarga adjuntos (403 en toda mutación).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Annotated
|
|
|
|
from fastapi import (
|
|
APIRouter,
|
|
Depends,
|
|
File,
|
|
Form,
|
|
HTTPException,
|
|
Query,
|
|
Request,
|
|
UploadFile,
|
|
status,
|
|
)
|
|
from pydantic import ValidationError
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import FileResponse, HTMLResponse, RedirectResponse, Response
|
|
|
|
from app.auth import requiere_rol
|
|
from app.db import get_db
|
|
from app.models import Alerta, Caso, Cliente, EventoCaso, ReglaAlerta, Usuario
|
|
from app.models.usuario import Rol
|
|
from app.routers import render
|
|
from app.schemas.alertas import CasoNuevoEntrada, CierreCasoEntrada, EventoEntrada, FiltrosCasos
|
|
from app.services import casos as servicio
|
|
from app.services.alertas import ESTADOS_ABIERTOS, tenant_de_sesion
|
|
|
|
router = APIRouter(tags=["casos"])
|
|
ROLES_MUTAN = (Rol.ANALISTA, Rol.OFICIAL)
|
|
ETIQUETAS_DECISION = {
|
|
"sin_inusualidad": "Sin inusualidad",
|
|
"reportar_aviso": "Reportar aviso",
|
|
"medidas_reforzadas": "Medidas reforzadas",
|
|
}
|
|
|
|
|
|
def _filtros(
|
|
estado: str | None = Query(default=None),
|
|
responsable: str | None = Query(default=None),
|
|
cliente_id: int | None = Query(default=None),
|
|
pagina: int = Query(default=1, ge=1),
|
|
) -> FiltrosCasos:
|
|
try:
|
|
return FiltrosCasos(
|
|
estado=estado, responsable=responsable, cliente_id=cliente_id, pagina=pagina
|
|
)
|
|
except ValidationError as exc:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, exc.errors()) from None
|
|
|
|
|
|
def _resumen(db: Session, caso: Caso) -> dict:
|
|
alertas = servicio.alertas_del_caso(db, caso)
|
|
cliente = db.get(Cliente, alertas[0].cliente_id) if alertas else None
|
|
claves = db.scalars(
|
|
select(ReglaAlerta.clave)
|
|
.join(Alerta, Alerta.regla_id == ReglaAlerta.id)
|
|
.where(Alerta.id.in_(caso.alerta_ids or [0]))
|
|
.order_by(Alerta.id)
|
|
).all()
|
|
return {
|
|
"id": caso.id,
|
|
"estado": caso.estado,
|
|
"responsable": caso.responsable,
|
|
"decision": caso.decision,
|
|
"created_at": caso.created_at,
|
|
"cliente_id": cliente.id if cliente else None,
|
|
"cliente": cliente.id_externo if cliente else "—",
|
|
"alertas": len(alertas),
|
|
"claves": sorted(set(claves)),
|
|
}
|
|
|
|
|
|
@router.get("/casos", include_in_schema=False)
|
|
def lista(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
filtros: Annotated[FiltrosCasos, Depends(_filtros)],
|
|
) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
casos = db.scalars(
|
|
select(Caso).where(Caso.tenant_id == tenant.id).order_by(Caso.id.desc())
|
|
).all()
|
|
resumenes = [_resumen(db, c) for c in casos]
|
|
if filtros.estado:
|
|
resumenes = [r for r in resumenes if r["estado"] == filtros.estado]
|
|
if filtros.responsable:
|
|
resumenes = [r for r in resumenes if r["responsable"] == filtros.responsable]
|
|
if filtros.cliente_id:
|
|
resumenes = [r for r in resumenes if r["cliente_id"] == filtros.cliente_id]
|
|
conteos = {
|
|
"total": len(casos),
|
|
"por_estado": {e: sum(1 for c in casos if c.estado == e) for e in servicio.ESTADOS},
|
|
"filtrados": len(resumenes),
|
|
}
|
|
paginas = max(1, -(-len(resumenes) // filtros.por_pagina))
|
|
pagina = min(filtros.pagina, paginas)
|
|
inicio = (pagina - 1) * filtros.por_pagina
|
|
return render(
|
|
request,
|
|
"casos/lista.html",
|
|
{
|
|
"filas": resumenes[inicio : inicio + filtros.por_pagina],
|
|
"filtros": filtros,
|
|
"conteos": conteos,
|
|
"estados": servicio.ESTADOS,
|
|
"responsables": sorted({c.responsable for c in casos if c.responsable}),
|
|
"pagina": pagina,
|
|
"paginas": paginas,
|
|
},
|
|
)
|
|
|
|
|
|
def _alertas_abiertas_del_cliente(db: Session, cliente_id: int) -> list[tuple[Alerta, ReglaAlerta]]:
|
|
filas = db.execute(
|
|
select(Alerta, ReglaAlerta)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.where(Alerta.cliente_id == cliente_id, Alerta.estado.in_(ESTADOS_ABIERTOS))
|
|
.order_by(Alerta.id)
|
|
).all()
|
|
return [(a, r) for a, r in filas if servicio.caso_abierto_de_alerta(db, a.id) is None]
|
|
|
|
|
|
@router.get("/casos/nuevo", include_in_schema=False)
|
|
def nuevo(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
alerta_id: int = Query(...),
|
|
) -> Response:
|
|
tenant = tenant_de_sesion(db)
|
|
alerta = db.get(Alerta, alerta_id)
|
|
if alerta is None or alerta.tenant_id != tenant.id:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Alerta no encontrada.")
|
|
existente = servicio.caso_abierto_de_alerta(db, alerta.id)
|
|
if existente is not None:
|
|
return RedirectResponse(f"/casos/{existente.id}", status_code=303)
|
|
return _formulario_nuevo(request, db, alerta, usuario)
|
|
|
|
|
|
def _formulario_nuevo(request, db, alerta, usuario, *, error=None, status_code=200) -> HTMLResponse:
|
|
cliente = db.get(Cliente, alerta.cliente_id)
|
|
return render(
|
|
request,
|
|
"casos/nuevo.html",
|
|
{
|
|
"alerta": alerta,
|
|
"cliente": cliente,
|
|
"candidatas": _alertas_abiertas_del_cliente(db, alerta.cliente_id),
|
|
"usuarios": sorted({u for (u,) in db.execute(select(Usuario.usuario))}),
|
|
"responsable_sugerido": alerta.responsable or usuario.usuario,
|
|
"error": error,
|
|
},
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
@router.post("/casos", include_in_schema=False)
|
|
def abrir(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
alerta_ids: Annotated[list[int] | None, Form()] = None,
|
|
responsable: Annotated[str, Form()] = "",
|
|
descripcion: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
alerta_ids = alerta_ids or []
|
|
try:
|
|
entrada = CasoNuevoEntrada(
|
|
alerta_ids=alerta_ids, responsable=responsable, descripcion=descripcion
|
|
)
|
|
with db.begin_nested():
|
|
caso = servicio.abrir_caso(
|
|
db, entrada.alerta_ids, entrada.responsable, usuario.usuario, entrada.descripcion
|
|
)
|
|
except (ValidationError, servicio.CasoError, LookupError) as exc:
|
|
primera = db.get(Alerta, alerta_ids[0]) if alerta_ids else None
|
|
if primera is None or primera.tenant_id != tenant_de_sesion(db).id:
|
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Elige al menos una alerta.") from None
|
|
mensaje = "Revisa el formulario." if isinstance(exc, ValidationError) else str(exc)
|
|
return _formulario_nuevo(request, db, primera, usuario, error=mensaje, status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/casos/{caso.id}?aviso=abierto", status_code=303)
|
|
|
|
|
|
def _caso(db: Session, caso_id: int) -> Caso:
|
|
caso = db.get(Caso, caso_id)
|
|
if caso is None or caso.tenant_id != tenant_de_sesion(db).id:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Caso no encontrado.")
|
|
return caso
|
|
|
|
|
|
def _detalle(
|
|
request: Request, db: Session, caso_id: int, *, status_code: int = 200, **extra
|
|
) -> HTMLResponse:
|
|
caso = _caso(db, caso_id)
|
|
alertas = db.execute(
|
|
select(Alerta, ReglaAlerta)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.where(Alerta.id.in_(caso.alerta_ids or [0]))
|
|
.order_by(Alerta.id)
|
|
).all()
|
|
cliente = servicio.cliente_del_caso(db, caso)
|
|
usuario = request.state.usuario
|
|
abierto = caso.estado != "cerrado"
|
|
siguiente = (
|
|
servicio.ESTADOS[servicio.ESTADOS.index(caso.estado) + 1]
|
|
if abierto and caso.estado != "escalado"
|
|
else None
|
|
)
|
|
return render(
|
|
request,
|
|
"casos/detalle.html",
|
|
{
|
|
"caso": caso,
|
|
"cliente": cliente,
|
|
"alertas": alertas,
|
|
"eventos": servicio.eventos(db, caso.id),
|
|
"puede_mutar": usuario.rol in ROLES_MUTAN and abierto,
|
|
"puede_cerrar": usuario.rol == Rol.OFICIAL and abierto,
|
|
"siguiente_estado": siguiente,
|
|
"decisiones": ETIQUETAS_DECISION,
|
|
"usuarios": sorted({u for (u,) in db.execute(select(Usuario.usuario))}),
|
|
**extra,
|
|
},
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
@router.get("/casos/{caso_id}", include_in_schema=False)
|
|
def detalle(
|
|
request: Request, caso_id: int, db: Annotated[Session, Depends(get_db)]
|
|
) -> HTMLResponse:
|
|
return _detalle(request, db, caso_id, aviso=request.query_params.get("aviso"))
|
|
|
|
|
|
@router.post("/casos/{caso_id}/eventos", include_in_schema=False)
|
|
async def evento(
|
|
request: Request,
|
|
caso_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
tipo: Annotated[str, Form()] = "nota",
|
|
descripcion: Annotated[str, Form()] = "",
|
|
archivo: Annotated[UploadFile | None, File()] = None,
|
|
) -> Response:
|
|
_caso(db, caso_id)
|
|
adjunto = None
|
|
if archivo is not None and archivo.filename:
|
|
contenido = await archivo.read(servicio.TAMANO_MAXIMO + 1)
|
|
adjunto = servicio.Adjunto(nombre=archivo.filename, contenido=contenido)
|
|
try:
|
|
entrada = EventoEntrada(tipo=tipo, descripcion=descripcion)
|
|
with db.begin_nested():
|
|
servicio.agregar_evento(
|
|
db, caso_id, entrada.tipo, entrada.descripcion, usuario.usuario, adjunto
|
|
)
|
|
except (ValidationError, servicio.CasoError) as exc:
|
|
mensaje = "Escribe una descripción." if isinstance(exc, ValidationError) else str(exc)
|
|
return _detalle(request, db, caso_id, error=mensaje, status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/casos/{caso_id}?aviso=evento", status_code=303)
|
|
|
|
|
|
@router.post("/casos/{caso_id}/estado", include_in_schema=False)
|
|
def estado(
|
|
request: Request,
|
|
caso_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
estado: Annotated[str, Form()] = "",
|
|
motivo: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
_caso(db, caso_id)
|
|
try:
|
|
with db.begin_nested():
|
|
servicio.cambiar_estado(
|
|
db, caso_id, estado, usuario.usuario, motivo or None, rol=usuario.rol.value
|
|
)
|
|
except servicio.CasoError as exc:
|
|
return _detalle(request, db, caso_id, error=str(exc), status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/casos/{caso_id}?aviso={estado}", status_code=303)
|
|
|
|
|
|
@router.post("/casos/{caso_id}/responsable", include_in_schema=False)
|
|
def responsable(
|
|
request: Request,
|
|
caso_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
responsable: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
_caso(db, caso_id)
|
|
try:
|
|
with db.begin_nested():
|
|
servicio.asignar_responsable(db, caso_id, responsable, usuario.usuario)
|
|
except servicio.CasoError as exc:
|
|
return _detalle(request, db, caso_id, error=str(exc), status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/casos/{caso_id}?aviso=responsable", status_code=303)
|
|
|
|
|
|
@router.post("/casos/{caso_id}/cerrar", include_in_schema=False)
|
|
def cerrar(
|
|
request: Request,
|
|
caso_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(Rol.OFICIAL))],
|
|
decision: Annotated[str, Form()] = "",
|
|
fundamento: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
_caso(db, caso_id)
|
|
try:
|
|
entrada = CierreCasoEntrada(decision=decision, fundamento=fundamento)
|
|
with db.begin_nested():
|
|
servicio.cerrar(
|
|
db,
|
|
caso_id,
|
|
entrada.decision,
|
|
entrada.fundamento,
|
|
usuario.usuario,
|
|
rol=usuario.rol.value,
|
|
)
|
|
except servicio.RolInsuficienteError as exc:
|
|
raise HTTPException(status.HTTP_403_FORBIDDEN, str(exc)) from None
|
|
except (ValidationError, servicio.CasoError) as exc:
|
|
mensaje = (
|
|
"Elige una decisión y escribe un fundamento de al menos 20 caracteres."
|
|
if isinstance(exc, ValidationError)
|
|
else str(exc)
|
|
)
|
|
return _detalle(request, db, caso_id, error=mensaje, status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/casos/{caso_id}?aviso=cerrado", status_code=303)
|
|
|
|
|
|
@router.get("/casos/{caso_id}/adjuntos/{evento_id}", include_in_schema=False)
|
|
def descargar(
|
|
request: Request, caso_id: int, evento_id: int, db: Annotated[Session, Depends(get_db)]
|
|
) -> Response:
|
|
caso = _caso(db, caso_id)
|
|
evento = db.get(EventoCaso, evento_id)
|
|
if evento is None or evento.caso_id != caso.id or not evento.adjunto:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Adjunto no encontrado.")
|
|
ruta = servicio.ruta_adjunto(evento.adjunto)
|
|
if not ruta.is_file():
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "El archivo ya no está en el volumen.")
|
|
servicio.registrar_descarga(db, evento.id, request.state.usuario.usuario)
|
|
db.commit()
|
|
return FileResponse(ruta, filename=ruta.name)
|