- Estado por omisión: abiertas (nueva, en revisión, escalada); Todas, cerradas e históricas con el filtro. Orden: vencidas primero, luego por vencimiento. - Los recuadros Críticas, Preventivas e Informativas cuentan solo abiertas. - Nivel aviso_umbral («Aviso por umbral»): no pide reevaluación extraordinaria y lo cierra el oficial. A-01 y A-02 siguen críticas en el seed hasta que lo valide el especialista (pendiente nivel_aviso_umbral); adoptarlo es versionar las reglas. - test_cierre_periodo: HOY no antes del día real (la bitácora usa el reloj real).
446 lines
17 KiB
Python
446 lines
17 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 urllib.parse import urlencode
|
|
|
|
from fastapi import APIRouter, Depends, Form, HTTPException, Query, Request, status
|
|
from pydantic import ValidationError
|
|
from sqlalchemy import case, func, or_, select
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
|
|
from app import fechas
|
|
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.alertas import ESTADO_HISTORICA
|
|
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 (
|
|
CIERRA_SOLO_OFICIAL,
|
|
ESTADOS_ABIERTOS,
|
|
NIVEL_AVISO_UMBRAL,
|
|
NIVELES_ALERTA,
|
|
RolInsuficienteError,
|
|
TransicionInvalidaError,
|
|
asignar_responsable,
|
|
cambiar_estado,
|
|
historial_estados,
|
|
tenant_de_sesion,
|
|
)
|
|
from app.services.expediente import nombres_para_mostrar
|
|
|
|
router = APIRouter(tags=["alertas"])
|
|
ROLES_MUTAN = (Rol.ANALISTA, Rol.OFICIAL)
|
|
# Por dictaminar: nueva o en revisión. Una escalada ya tiene caso y se resuelve en él.
|
|
POR_DICTAMINAR = ("nueva", "en_revision")
|
|
SIN_PENDIENTES = "Sin alertas pendientes"
|
|
FAMILIAS = ("A", "B", "C", "D", "E")
|
|
NIVELES = NIVELES_ALERTA
|
|
ESTADOS = ("nueva", "en_revision", "escalada", "cerrada", ESTADO_HISTORICA)
|
|
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",
|
|
"ventana": "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",
|
|
"plazo_desde": "Plazo contado desde",
|
|
"plazo_desde_motivo": "Por qué",
|
|
}
|
|
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),
|
|
abiertas: str | None = Query(default=None),
|
|
plazo: str | None = Query(default=None, max_length=12),
|
|
vence_el: str | None = Query(default=None, max_length=10),
|
|
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,
|
|
abiertas=abiertas,
|
|
plazo=plazo,
|
|
vence_el=vence_el,
|
|
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
|
|
|
|
|
|
def _niveles_en_uso(db: Session, tenant_id: int, todas: list) -> tuple[str, ...]:
|
|
"""Los niveles de la bandeja. «Aviso por umbral» aparece cuando una regla vigente lo usa o
|
|
alguna alerta lo tiene (su adopción depende del especialista: `nivel_aviso_umbral`)."""
|
|
en_uso = any(niv == NIVEL_AVISO_UMBRAL for _, niv, _ in todas) or db.scalar(
|
|
select(func.count(ReglaAlerta.id)).where(
|
|
ReglaAlerta.tenant_id == tenant_id,
|
|
ReglaAlerta.valid_to.is_(None),
|
|
ReglaAlerta.nivel == NIVEL_AVISO_UMBRAL,
|
|
)
|
|
)
|
|
return tuple(n for n in NIVELES if n != NIVEL_AVISO_UMBRAL or en_uso)
|
|
|
|
|
|
@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 = fechas.hoy() # la fecha de México, la misma con la que Inicio cuenta las vencidas
|
|
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)
|
|
# Por omisión, las abiertas; las cerradas y las históricas se ven cambiando el filtro.
|
|
estado = filtros.estado or "abiertas"
|
|
if estado == "abiertas":
|
|
base = base.where(Alerta.estado.in_(ESTADOS_ABIERTOS))
|
|
elif estado == "todas": # las anteriores a la operación de la plataforma solo si se piden
|
|
base = base.where(Alerta.estado != ESTADO_HISTORICA)
|
|
else:
|
|
base = base.where(Alerta.estado == 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))
|
|
if filtros.abiertas:
|
|
base = base.where(Alerta.estado.in_(ESTADOS_ABIERTOS))
|
|
if filtros.plazo == "otros":
|
|
base = base.where(or_(Alerta.plazo_aviso.is_(None), Alerta.plazo_aviso != "24h"))
|
|
elif filtros.plazo:
|
|
base = base.where(Alerta.plazo_aviso == filtros.plazo)
|
|
if filtros.vence_el:
|
|
base = base.where(Alerta.vence_el == filtros.vence_el)
|
|
# Las vencidas primero, luego las abiertas por vencimiento (las sin fecha al final de ellas) y,
|
|
# si el filtro las incluye, las cerradas.
|
|
abierta = Alerta.estado.in_(ESTADOS_ABIERTOS)
|
|
vencida = case((abierta & (Alerta.vence_el < hoy), 0), else_=1)
|
|
cerrada = case((abierta, 0), else_=1)
|
|
filas_db = db.execute(
|
|
base.order_by(vencida, cerrada, 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
|
|
pagina_db = filas_db[inicio : inicio + filtros.por_pagina]
|
|
# El nombre o el RFC del cliente, no su identificador interno (ALTA-000999).
|
|
nombres = nombres_para_mostrar(db, tenant, list({a.cliente_id for a, _, _ in pagina_db}))
|
|
filas = [
|
|
{
|
|
"id": a.id,
|
|
"clave": r.clave,
|
|
"familia": r.familia,
|
|
"nombre": r.nombre,
|
|
"version": r.version,
|
|
"nivel": a.nivel,
|
|
"estado": a.estado,
|
|
"por_dictaminar": a.estado in POR_DICTAMINAR, # botón «Dictaminar»
|
|
"responsable": a.responsable,
|
|
"vence_el": a.vence_el if a.estado in ESTADOS_ABIERTOS else None, # cerrada: no vence
|
|
"vencida": a.vence_el is not None and a.vence_el < hoy and a.estado in ESTADOS_ABIERTOS,
|
|
"cliente_id": a.cliente_id,
|
|
"cliente": nombres.get(a.cliente_id) or id_externo,
|
|
"id_externo": 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 pagina_db
|
|
]
|
|
|
|
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
|
|
),
|
|
# Como Abiertas, Nuevas y Vencidas: solo las abiertas, no las cerradas ni las históricas.
|
|
"por_nivel": {
|
|
n: sum(1 for e, niv, _ in todas if niv == n and e in ESTADOS_ABIERTOS) 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_en_uso(db, tenant.id, todas),
|
|
"estados": ESTADOS,
|
|
"responsables": responsables,
|
|
"pagina": pagina,
|
|
"paginas": paginas,
|
|
"hoy": hoy,
|
|
"aviso": request.query_params.get("aviso"),
|
|
},
|
|
)
|
|
|
|
|
|
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 not in CIERRA_SOLO_OFICIAL 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,
|
|
# El nombre o el RFC del cliente, no su identificador interno (ALTA-000999).
|
|
"nombre_cliente": nombres_para_mostrar(db, tenant_de_sesion(db), [cliente.id]).get(
|
|
cliente.id
|
|
)
|
|
or cliente.id_externo,
|
|
"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,
|
|
# Ya dictaminada (cerrada o escalada): «Siguiente pendiente».
|
|
"ofrece_siguiente": usuario.rol in ROLES_MUTAN and alerta.estado not in POR_DICTAMINAR,
|
|
"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,
|
|
)
|
|
|
|
|
|
def siguiente_pendiente(
|
|
db: Session, tenant_id: int, hoy: date, excepto: int | None = None
|
|
) -> int | None:
|
|
"""La próxima alerta por dictaminar: primero las vencidas, luego por fecha de vencimiento
|
|
(las que no vencen al final)."""
|
|
consulta = select(Alerta.id).where(
|
|
Alerta.tenant_id == tenant_id, Alerta.estado.in_(POR_DICTAMINAR)
|
|
)
|
|
if excepto is not None:
|
|
consulta = consulta.where(Alerta.id != excepto)
|
|
vencida = case((Alerta.vence_el < hoy, 0), else_=1)
|
|
sin_fecha = case((Alerta.vence_el.is_(None), 1), else_=0)
|
|
return db.scalar(consulta.order_by(vencida, sin_fecha, Alerta.vence_el, Alerta.id).limit(1))
|
|
|
|
|
|
@router.get("/alertas/siguiente", include_in_schema=False)
|
|
def siguiente(
|
|
db: Annotated[Session, Depends(get_db)],
|
|
desde: Annotated[int | None, Query()] = None,
|
|
) -> Response:
|
|
"""La siguiente alerta por dictaminar o, si no queda ninguna, la bandeja con el aviso."""
|
|
tenant = tenant_de_sesion(db)
|
|
proxima = siguiente_pendiente(db, tenant.id, fechas.hoy(), excepto=desde)
|
|
if proxima is None:
|
|
return RedirectResponse(f"/alertas?{urlencode({'aviso': SIN_PENDIENTES})}", status_code=303)
|
|
return RedirectResponse(f"/alertas/{proxima}", status_code=303)
|
|
|
|
|
|
@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)
|
|
)
|
|
)
|