Cada fila de GET /alertas suma descripcion (criterio de la regla), generada (created_at) y
credito_id, que ya estaban cargados: ninguna consulta nueva. Las acciones (asignar, revisar,
cerrar) siguen en /alertas/{id} y sus redirecciones no cambian (decisión D4, opción a).
349 lines
13 KiB
Python
349 lines
13 KiB
Python
"""Router `alertas`: bandeja de alertas por familia, nivel, estado, responsable y vencidas, y
|
|
detalle con acciones (asignar responsable, en revisión, escalar, cerrar). Fase 3 (Pieza D).
|
|
|
|
Permisos: `analista` y `oficial` cambian estado y asignan; cerrar una alerta `critica` exige
|
|
`oficial`; `auditor` solo lee (403 en toda mutación). Escalar solo cambia el estado; el caso se
|
|
crea en el PR 3. El historial de estados se reconstruye desde `audit_trail`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, Form, HTTPException, Query, Request, status
|
|
from pydantic import ValidationError
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
|
|
from app.auth import requiere_rol
|
|
from app.db import get_db
|
|
from app.models import Alerta, Cliente, Credito, ReglaAlerta, Transaccion, Usuario
|
|
from app.models.usuario import Rol
|
|
from app.routers import render
|
|
from app.schemas.alertas import CambioEstadoEntrada, FiltrosAlertas
|
|
from app.services import casos as servicio_casos
|
|
from app.services.alertas import (
|
|
ESTADOS_ABIERTOS,
|
|
RolInsuficienteError,
|
|
TransicionInvalidaError,
|
|
asignar_responsable,
|
|
cambiar_estado,
|
|
historial_estados,
|
|
tenant_de_sesion,
|
|
)
|
|
|
|
router = APIRouter(tags=["alertas"])
|
|
ROLES_MUTAN = (Rol.ANALISTA, Rol.OFICIAL)
|
|
FAMILIAS = ("A", "B", "C", "D", "E")
|
|
NIVELES = ("critica", "preventiva", "informativa")
|
|
ESTADOS = ("nueva", "en_revision", "escalada", "cerrada")
|
|
ETIQUETAS_EVIDENCIA = {
|
|
"monto": "Monto del crédito",
|
|
"umbral": "Umbral aplicado",
|
|
"uma": "UMA vigente",
|
|
"factor_uma": "Factor UMA",
|
|
"credito": "Crédito",
|
|
"total": "Importe de la transacción",
|
|
"ingresos_mensuales_netos": "Ingresos mensuales netos",
|
|
"factor_ingresos": "Factor sobre ingresos",
|
|
"factor_ingreso_anual": "Factor sobre ingreso anual",
|
|
"meses_anualizacion": "Meses de anualización",
|
|
"titular_origen": "Titular de la cuenta origen",
|
|
"titulares_que_disparan": "Titulares que disparan",
|
|
"fecha_pago": "Fecha de pago",
|
|
"fecha_pago_anterior": "Pago anterior",
|
|
"motivo": "Motivo",
|
|
"cambios_en_ventana": "Cambios de método en la ventana",
|
|
"cambios_metodo": "Cambios requeridos",
|
|
"pagos_consecutivos": "Pagos consecutivos",
|
|
"meses_desde_pago_anterior": "Meses desde el pago anterior",
|
|
"hueco_meses": "Hueco requerido (meses)",
|
|
"metodos": "Métodos de los últimos pagos",
|
|
"pep": "Condición PEP",
|
|
"condicion": "Condición",
|
|
"coincidencia": "Coincidencia en listas",
|
|
"campo": "Campo",
|
|
"valor": "Valor",
|
|
"catalogos": "Catálogos",
|
|
"comprobante_ingresos": "Comprobante de ingresos",
|
|
"inconsistencia_documentos": "Inconsistencia documental",
|
|
"descripcion": "Descripción",
|
|
"levantada_por": "Levantada por",
|
|
"manual": "Alerta manual",
|
|
"tipo": "Tipo de transacción",
|
|
"tipos_transaccion": "Tipos de transacción considerados",
|
|
"fecha_evento": "Fecha del evento",
|
|
}
|
|
OCULTAS_EVIDENCIA = {"regla", "version", "parametros", "transaccion_id"}
|
|
|
|
|
|
def _filtros(
|
|
familia: str | None = Query(default=None),
|
|
nivel: str | None = Query(default=None),
|
|
estado: str | None = Query(default=None),
|
|
responsable: str | None = Query(default=None),
|
|
vencidas: str | None = Query(default=None),
|
|
cliente_id: int | None = Query(default=None),
|
|
pagina: int = Query(default=1, ge=1),
|
|
) -> FiltrosAlertas:
|
|
try:
|
|
return FiltrosAlertas(
|
|
familia=familia,
|
|
nivel=nivel,
|
|
estado=estado,
|
|
responsable=responsable,
|
|
vencidas=vencidas,
|
|
cliente_id=cliente_id,
|
|
pagina=pagina,
|
|
)
|
|
except ValidationError as exc:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, exc.errors()) from None
|
|
|
|
|
|
def _evidencia_legible(evidencia: dict | None) -> list[tuple[str, str]]:
|
|
filas = []
|
|
for clave, valor in (evidencia or {}).items():
|
|
if clave in OCULTAS_EVIDENCIA or clave.startswith("_"):
|
|
continue
|
|
if isinstance(valor, bool):
|
|
texto = "Sí" if valor else "No"
|
|
elif isinstance(valor, list):
|
|
texto = ", ".join(str(v) for v in valor) or "—"
|
|
elif isinstance(valor, dict):
|
|
texto = ", ".join(f"{k}: {v}" for k, v in valor.items())
|
|
else:
|
|
texto = str(valor)
|
|
filas.append((ETIQUETAS_EVIDENCIA.get(clave, clave.replace("_", " ").capitalize()), texto))
|
|
return filas
|
|
|
|
|
|
@router.get("/alertas", include_in_schema=False)
|
|
def bandeja(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
filtros: Annotated[FiltrosAlertas, Depends(_filtros)],
|
|
) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
hoy = date.today()
|
|
base = (
|
|
select(Alerta, ReglaAlerta, Cliente.id_externo)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.join(Cliente, Cliente.id == Alerta.cliente_id)
|
|
.where(Alerta.tenant_id == tenant.id)
|
|
)
|
|
if filtros.familia:
|
|
base = base.where(ReglaAlerta.familia == filtros.familia)
|
|
if filtros.nivel:
|
|
base = base.where(Alerta.nivel == filtros.nivel)
|
|
if filtros.estado:
|
|
base = base.where(Alerta.estado == filtros.estado)
|
|
if filtros.responsable:
|
|
base = base.where(Alerta.responsable == filtros.responsable)
|
|
if filtros.cliente_id:
|
|
base = base.where(Alerta.cliente_id == filtros.cliente_id)
|
|
if filtros.vencidas:
|
|
base = base.where(Alerta.vence_el < hoy, Alerta.estado.in_(ESTADOS_ABIERTOS))
|
|
filas_db = db.execute(
|
|
base.order_by(Alerta.vence_el.is_(None), Alerta.vence_el, Alerta.id)
|
|
).all()
|
|
|
|
total = len(filas_db)
|
|
paginas = max(1, -(-total // filtros.por_pagina))
|
|
pagina = min(filtros.pagina, paginas)
|
|
inicio = (pagina - 1) * filtros.por_pagina
|
|
filas = [
|
|
{
|
|
"id": a.id,
|
|
"clave": r.clave,
|
|
"familia": r.familia,
|
|
"nombre": r.nombre,
|
|
"version": r.version,
|
|
"nivel": a.nivel,
|
|
"estado": a.estado,
|
|
"responsable": a.responsable,
|
|
"vence_el": a.vence_el,
|
|
"vencida": a.vence_el is not None and a.vence_el < hoy and a.estado in ESTADOS_ABIERTOS,
|
|
"cliente_id": a.cliente_id,
|
|
"cliente": id_externo,
|
|
# Para el cajón de la bandeja (resumen; las acciones viven en /alertas/{id}).
|
|
"descripcion": r.criterio_texto,
|
|
"generada": a.created_at,
|
|
"credito_id": a.credito_id,
|
|
}
|
|
for a, r, id_externo in filas_db[inicio : inicio + filtros.por_pagina]
|
|
]
|
|
|
|
todas = db.execute(
|
|
select(Alerta.estado, Alerta.nivel, Alerta.vence_el).where(Alerta.tenant_id == tenant.id)
|
|
).all()
|
|
conteos = {
|
|
"total": len(todas),
|
|
"abiertas": sum(1 for e, _, _ in todas if e in ESTADOS_ABIERTOS),
|
|
"vencidas": sum(
|
|
1 for e, _, v in todas if e in ESTADOS_ABIERTOS and v is not None and v < hoy
|
|
),
|
|
"por_nivel": {n: sum(1 for _, niv, _ in todas if niv == n) for n in NIVELES},
|
|
"por_estado": {e: sum(1 for est, _, _ in todas if est == e) for e in ESTADOS},
|
|
"filtradas": total,
|
|
}
|
|
responsables = sorted(
|
|
{
|
|
r
|
|
for (r,) in db.execute(
|
|
select(Alerta.responsable).where(Alerta.tenant_id == tenant.id).distinct()
|
|
)
|
|
if r
|
|
}
|
|
)
|
|
return render(
|
|
request,
|
|
"alertas/bandeja.html",
|
|
{
|
|
"filas": filas,
|
|
"filtros": filtros,
|
|
"conteos": conteos,
|
|
"familias": FAMILIAS,
|
|
"niveles": NIVELES,
|
|
"estados": ESTADOS,
|
|
"responsables": responsables,
|
|
"pagina": pagina,
|
|
"paginas": paginas,
|
|
"hoy": hoy,
|
|
},
|
|
)
|
|
|
|
|
|
def _alerta(db: Session, alerta_id: int) -> tuple[Alerta, ReglaAlerta]:
|
|
tenant = tenant_de_sesion(db)
|
|
fila = db.execute(
|
|
select(Alerta, ReglaAlerta)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.where(Alerta.id == alerta_id, Alerta.tenant_id == tenant.id)
|
|
).first()
|
|
if fila is None:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Alerta no encontrada.")
|
|
return fila[0], fila[1]
|
|
|
|
|
|
def _detalle(
|
|
request: Request, db: Session, alerta_id: int, *, status_code: int = 200, **extra
|
|
) -> HTMLResponse:
|
|
alerta, regla = _alerta(db, alerta_id)
|
|
cliente = db.get(Cliente, alerta.cliente_id)
|
|
credito = db.get(Credito, alerta.credito_id) if alerta.credito_id else None
|
|
transacciones = (
|
|
db.scalars(
|
|
select(Transaccion)
|
|
.where(Transaccion.id.in_(alerta.transaccion_ids))
|
|
.order_by(Transaccion.fecha_pago, Transaccion.id)
|
|
).all()
|
|
if alerta.transaccion_ids
|
|
else []
|
|
)
|
|
usuario = request.state.usuario
|
|
caso_abierto = servicio_casos.caso_abierto_de_alerta(db, alerta.id)
|
|
puede_mutar = usuario.rol in ROLES_MUTAN and alerta.estado != "cerrada"
|
|
puede_cerrar = puede_mutar and (alerta.nivel != "critica" or usuario.rol == Rol.OFICIAL)
|
|
analistas = sorted(
|
|
{
|
|
u
|
|
for (u,) in db.execute(
|
|
select(Usuario.usuario).where(Usuario.tenant_id == alerta.tenant_id)
|
|
)
|
|
}
|
|
)
|
|
return render(
|
|
request,
|
|
"alertas/detalle.html",
|
|
{
|
|
"alerta": alerta,
|
|
"regla": regla,
|
|
"cliente": cliente,
|
|
"credito": credito,
|
|
"transacciones": transacciones,
|
|
"evidencia": _evidencia_legible(alerta.evidencia),
|
|
"historial": historial_estados(db, alerta.id),
|
|
"puede_mutar": puede_mutar,
|
|
"puede_cerrar": puede_cerrar,
|
|
"caso_abierto": caso_abierto,
|
|
"usuarios": analistas,
|
|
"transicion_disponible": {
|
|
"en_revision": alerta.estado in ("nueva", "escalada"),
|
|
"escalada": alerta.estado in ("nueva", "en_revision"),
|
|
"cerrada": alerta.estado != "cerrada",
|
|
},
|
|
**extra,
|
|
},
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
@router.get("/alertas/{alerta_id}", include_in_schema=False)
|
|
def detalle(
|
|
request: Request, alerta_id: int, db: Annotated[Session, Depends(get_db)]
|
|
) -> HTMLResponse:
|
|
return _detalle(request, db, alerta_id, aviso=request.query_params.get("aviso"))
|
|
|
|
|
|
@router.post("/alertas/{alerta_id}/responsable", include_in_schema=False)
|
|
def responsable(
|
|
request: Request,
|
|
alerta_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_MUTAN))],
|
|
responsable: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
_alerta(db, alerta_id)
|
|
try:
|
|
# Savepoint: un fallo deshace solo lo de la acción sin expirar el usuario de la sesión.
|
|
with db.begin_nested():
|
|
asignar_responsable(db, alerta_id, responsable, usuario=usuario.usuario)
|
|
except (ValueError, TransicionInvalidaError) as exc:
|
|
return _detalle(request, db, alerta_id, error=f"No se pudo asignar: {exc}", status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/alertas/{alerta_id}?aviso=responsable", status_code=303)
|
|
|
|
|
|
@router.post("/alertas/{alerta_id}/estado", include_in_schema=False)
|
|
def estado(
|
|
request: Request,
|
|
alerta_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:
|
|
_alerta(db, alerta_id)
|
|
try:
|
|
entrada = CambioEstadoEntrada(estado=estado, motivo=motivo or None)
|
|
with db.begin_nested():
|
|
cambiar_estado(
|
|
db,
|
|
alerta_id,
|
|
entrada.estado,
|
|
motivo=entrada.motivo,
|
|
usuario=usuario.usuario,
|
|
rol=usuario.rol.value,
|
|
)
|
|
except RolInsuficienteError as exc:
|
|
raise HTTPException(status.HTTP_403_FORBIDDEN, str(exc)) from None
|
|
except (ValidationError, TransicionInvalidaError) as exc:
|
|
mensaje = (
|
|
"Indica un estado válido; cerrar exige una justificación."
|
|
if isinstance(exc, ValidationError)
|
|
else f"No se pudo cambiar el estado: {exc}"
|
|
)
|
|
return _detalle(request, db, alerta_id, error=mensaje, status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(f"/alertas/{alerta_id}?aviso={entrada.estado}", status_code=303)
|
|
|
|
|
|
def alertas_abiertas(db: Session, tenant_id: int) -> int:
|
|
return db.scalar(
|
|
select(func.count(Alerta.id)).where(
|
|
Alerta.tenant_id == tenant_id, Alerta.estado.in_(ESTADOS_ABIERTOS)
|
|
)
|
|
)
|