feat(ui): bandeja y detalle de alertas
- /alertas: filtros por familia, nivel, estado, responsable, vencidas y cliente; conteos; orden por vence_el; paginación de 50 - /alertas/<id>: regla y versión, cliente, crédito y transacciones involucradas, evidencia legible, historial desde audit_trail - acciones: asignar responsable, en revisión, escalar (solo estado; el caso llega en el PR 3), cerrar con justificación - permisos: analista y oficial mutan; cerrar crítica exige oficial; auditor 403 en toda mutación - savepoints en las acciones para no perder la auditoría de accesos; enlaces desde la ficha del cliente
This commit is contained in:
1 parent
8d3bb61d72
commit
00784dbb4c
7 files changed
+904
-7
No files matched your search
+339
-2
@@ -1,4 +1,341 @@
|
||||
"""Router `alertas`: Bandeja de alertas por familia y nivel, alertas manuales.
|
||||
"""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).
|
||||
|
||||
Se implementa en Fase 3.
|
||||
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.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,
|
||||
}
|
||||
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
|
||||
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,
|
||||
"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)
|
||||
)
|
||||
)
|
||||
@@ -137,11 +137,12 @@ def alerta_manual(
|
||||
_cliente(db, tenant.id, cliente_id)
|
||||
try:
|
||||
entrada = AlertaManualEntrada(regla_clave=regla_clave, descripcion=descripcion)
|
||||
alerta = levantar_manual(
|
||||
db, entrada.regla_clave, cliente_id, entrada.descripcion, usuario.usuario
|
||||
)
|
||||
# Savepoint: un fallo deshace solo lo de la acción sin expirar el usuario de la sesión.
|
||||
with db.begin_nested():
|
||||
alerta = levantar_manual(
|
||||
db, entrada.regla_clave, cliente_id, entrada.descripcion, usuario.usuario
|
||||
)
|
||||
except (ValidationError, ReglaNoEncontradaError, ReglaNoManualError) as exc:
|
||||
db.rollback()
|
||||
if isinstance(exc, ValidationError):
|
||||
mensaje = (
|
||||
"Elige una regla manual (B-05, B-07 o E-03) y describe el hecho "
|
||||
|
||||
@@ -51,3 +51,35 @@ class FiltrosCartera(BaseModel):
|
||||
return None
|
||||
v = str(v).strip()
|
||||
return v or None
|
||||
|
||||
|
||||
class FiltrosAlertas(BaseModel):
|
||||
"""Filtros de la bandeja `/alertas`; todo opcional y tolerante a valores vacíos."""
|
||||
|
||||
model_config = ConfigDict(str_strip_whitespace=True)
|
||||
|
||||
familia: Literal["A", "B", "C", "D", "E"] | None = None
|
||||
nivel: Literal["critica", "preventiva", "informativa"] | None = None
|
||||
estado: EstadoAlerta | None = None
|
||||
responsable: str | None = Field(default=None, max_length=64)
|
||||
vencidas: bool = False
|
||||
cliente_id: int | None = Field(default=None, ge=1)
|
||||
pagina: int = Field(default=1, ge=1)
|
||||
por_pagina: int = Field(default=POR_PAGINA, ge=1, le=200)
|
||||
|
||||
@field_validator("familia", "nivel", "estado", "responsable", mode="before")
|
||||
@classmethod
|
||||
def _vacio_es_nulo(cls, v):
|
||||
if v is None:
|
||||
return None
|
||||
v = str(v).strip()
|
||||
if not v:
|
||||
return None
|
||||
return v.upper() if len(v) == 1 else v.lower()
|
||||
|
||||
@field_validator("vencidas", mode="before")
|
||||
@classmethod
|
||||
def _marca(cls, v):
|
||||
if v is None or v is False:
|
||||
return False
|
||||
return str(v).strip().lower() in ("1", "true", "si", "sí", "on")
|
||||
@@ -0,0 +1,77 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_componentes/tarjeta.html" import tarjeta %}
|
||||
{% from "_componentes/badges.html" import badge, badge_estado_alerta, badge_nivel_alerta %}
|
||||
{% from "_componentes/tabla.html" import tabla %}
|
||||
|
||||
{% block titulo %}Alertas{% endblock %}
|
||||
|
||||
{% block contenido %}
|
||||
<header class="pagina__encabezado">
|
||||
<h1 class="pagina__titulo">Alertas</h1>
|
||||
<p class="pagina__bajada">{{ conteos.abiertas }} abiertas de {{ conteos.total }} · {{ conteos.vencidas }} vencidas · ordenadas por vencimiento</p>
|
||||
</header>
|
||||
|
||||
<section class="resumen" aria-label="Resumen de alertas">
|
||||
<a class="resumen__cifra" href="/alertas"><strong>{{ conteos.total }}</strong><span>Alertas</span></a>
|
||||
<a class="resumen__cifra" href="/alertas?estado=nueva"><strong>{{ conteos.por_estado.nueva }}</strong><span>Nuevas</span></a>
|
||||
<a class="resumen__cifra" href="/alertas?estado=en_revision"><strong>{{ conteos.por_estado.en_revision }}</strong><span>En revisión</span></a>
|
||||
<a class="resumen__cifra" href="/alertas?estado=escalada"><strong>{{ conteos.por_estado.escalada }}</strong><span>Escaladas</span></a>
|
||||
<a class="resumen__cifra" href="/alertas?vencidas=1"><strong>{{ conteos.vencidas }}</strong><span>Vencidas</span></a>
|
||||
{% for n in niveles %}<a class="resumen__cifra" href="/alertas?nivel={{ n }}"><strong>{{ conteos.por_nivel[n] }}</strong><span>{{ n | capitalize }}s</span></a>{% endfor %}
|
||||
</section>
|
||||
|
||||
{% call tarjeta("Filtros") %}
|
||||
<form class="formulario formulario--linea" method="get" action="/alertas">
|
||||
<label class="campo"><span class="campo__etiqueta">Familia</span>
|
||||
<select class="campo__entrada" name="familia"><option value="">Todas</option>
|
||||
{% for f in familias %}<option value="{{ f }}" {% if filtros.familia == f %}selected{% endif %}>{{ f }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label class="campo"><span class="campo__etiqueta">Nivel</span>
|
||||
<select class="campo__entrada" name="nivel"><option value="">Todos</option>
|
||||
{% for n in niveles %}<option value="{{ n }}" {% if filtros.nivel == n %}selected{% endif %}>{{ n | capitalize }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label class="campo"><span class="campo__etiqueta">Estado</span>
|
||||
<select class="campo__entrada" name="estado"><option value="">Todos</option>
|
||||
{% for e in estados %}<option value="{{ e }}" {% if filtros.estado == e %}selected{% endif %}>{{ e | replace("_", " ") | capitalize }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label class="campo"><span class="campo__etiqueta">Responsable</span>
|
||||
<select class="campo__entrada" name="responsable"><option value="">Todos</option>
|
||||
{% for r in responsables %}<option value="{{ r }}" {% if filtros.responsable == r %}selected{% endif %}>{{ r }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<label class="campo campo--marca"><input type="checkbox" name="vencidas" value="1" {% if filtros.vencidas %}checked{% endif %}> <span class="campo__etiqueta">Solo vencidas</span></label>
|
||||
{% if filtros.cliente_id %}<input type="hidden" name="cliente_id" value="{{ filtros.cliente_id }}">{% endif %}
|
||||
<button class="boton boton--primario" type="submit">Filtrar</button>
|
||||
<a class="boton boton--discreto" href="/alertas">Limpiar</a>
|
||||
</form>
|
||||
{% if filtros.cliente_id %}<p>{{ badge("Cliente " ~ filtros.cliente_id, "info") }} <a href="/clientes/{{ filtros.cliente_id }}">ver ficha</a> · <a href="/alertas">todas las alertas</a></p>{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Bandeja", subtitulo=conteos.filtradas ~ " alertas · página " ~ pagina ~ " de " ~ paginas) %}
|
||||
{% set columnas = [
|
||||
{"clave": "id", "titulo": "#"},
|
||||
{"clave": "clave", "titulo": "Regla"},
|
||||
{"clave": "cliente", "titulo": "Cliente"},
|
||||
{"clave": "nivel", "titulo": "Nivel"},
|
||||
{"clave": "estado", "titulo": "Estado"},
|
||||
{"clave": "vence_el", "titulo": "Vence"},
|
||||
{"clave": "responsable", "titulo": "Responsable"},
|
||||
] %}
|
||||
{% call(fila, col) tabla(columnas, filas, vacio="Ninguna alerta cumple los filtros.") %}
|
||||
{% if col.clave == "id" %}<a href="/alertas/{{ fila.id }}">{{ fila.id }}</a>
|
||||
{% elif col.clave == "clave" %}<a href="/alertas/{{ fila.id }}"><strong>{{ fila.clave }}</strong></a> <small>{{ fila.nombre }} · {{ fila.version }}</small>
|
||||
{% elif col.clave == "cliente" %}<a href="/clientes/{{ fila.cliente_id }}"><code>{{ fila.cliente }}</code></a>
|
||||
{% elif col.clave == "nivel" %}{{ badge_nivel_alerta(fila.nivel) }}
|
||||
{% elif col.clave == "estado" %}{{ badge_estado_alerta(fila.estado) }}
|
||||
{% elif col.clave == "vence_el" %}{% if fila.vence_el %}{{ fila.vence_el.strftime("%d/%m/%Y") }} {% if fila.vencida %}{{ badge("Vencida", "peligro") }}{% endif %}{% else %}—{% endif %}
|
||||
{% else %}{{ fila.responsable or "—" }}{% endif %}
|
||||
{% endcall %}
|
||||
{% if paginas > 1 %}
|
||||
<nav class="paginacion" aria-label="Paginación">
|
||||
{% set base = "/alertas?" ~ ("familia=" ~ filtros.familia ~ "&" if filtros.familia else "") ~ ("nivel=" ~ filtros.nivel ~ "&" if filtros.nivel else "") ~ ("estado=" ~ filtros.estado ~ "&" if filtros.estado else "") ~ ("responsable=" ~ filtros.responsable ~ "&" if filtros.responsable else "") ~ ("vencidas=1&" if filtros.vencidas else "") ~ ("cliente_id=" ~ filtros.cliente_id ~ "&" if filtros.cliente_id else "") %}
|
||||
{% if pagina > 1 %}<a class="boton boton--discreto" href="{{ base }}pagina={{ pagina - 1 }}">← Anterior</a>{% endif %}
|
||||
<span>Página {{ pagina }} de {{ paginas }}</span>
|
||||
{% if pagina < paginas %}<a class="boton boton--discreto" href="{{ base }}pagina={{ pagina + 1 }}">Siguiente →</a>{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% endcall %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,88 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_componentes/tarjeta.html" import tarjeta %}
|
||||
{% from "_componentes/badges.html" import badge, badge_estado_alerta, badge_nivel_alerta %}
|
||||
{% from "_componentes/tabla.html" import tabla %}
|
||||
{% from "_componentes/aviso.html" import aviso as aviso_en_linea %}
|
||||
|
||||
{% block titulo %}Alerta {{ alerta.id }} · {{ regla.clave }}{% endblock %}
|
||||
|
||||
{% block contenido %}
|
||||
<header class="pagina__encabezado">
|
||||
<p class="pagina__bajada"><a href="/alertas">← Alertas</a></p>
|
||||
<h1 class="pagina__titulo">Alerta #{{ alerta.id }} · {{ regla.clave }} {{ regla.nombre }}</h1>
|
||||
<p class="pagina__bajada">{{ badge_nivel_alerta(alerta.nivel) }} {{ badge_estado_alerta(alerta.estado) }} · regla {{ regla.version }} vigente desde {{ regla.vigente_desde.strftime("%d/%m/%Y") }} · plazo: {{ alerta.plazo_aviso or "análisis interno" }}{% if alerta.vence_el %} · vence el {{ alerta.vence_el.strftime("%d/%m/%Y") }}{% endif %}</p>
|
||||
</header>
|
||||
|
||||
{% if aviso %}<div data-toast="{{ {'responsable': 'Responsable asignado.', 'en_revision': 'Alerta en revisión.', 'escalada': 'Alerta escalada.', 'cerrada': 'Alerta cerrada.'}.get(aviso, 'Actualizado.') }}" data-tono="exito" hidden></div>{% endif %}
|
||||
{% if error %}{{ aviso_en_linea(error, tono="peligro") }}{% endif %}
|
||||
|
||||
{% call tarjeta("Regla", subtitulo=regla.criterio_texto) %}
|
||||
<dl class="datos">
|
||||
<div class="datos__par"><dt>Clave</dt><dd>{{ regla.clave }} · familia {{ regla.familia }}</dd></div>
|
||||
<div class="datos__par"><dt>Versión que la produjo</dt><dd>{{ regla.version }} (regla_id {{ regla.id }}){% if regla.valid_to %} {{ badge("sustituida", "aviso") }}{% endif %}</dd></div>
|
||||
<div class="datos__par"><dt>Tipo de evaluación</dt><dd>{{ regla.tipo_evaluacion }}</dd></div>
|
||||
<div class="datos__par"><dt>Parámetros</dt><dd>{% for k, v in (alerta.evidencia.parametros or {}).items() if not k.startswith("_") %}<code>{{ k }}={{ v }}</code> {% else %}—{% endfor %}</dd></div>
|
||||
</dl>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Cliente, crédito y transacciones") %}
|
||||
<dl class="datos">
|
||||
<div class="datos__par"><dt>Cliente</dt><dd><a href="/clientes/{{ cliente.id }}"><code>{{ cliente.id_externo }}</code></a> · <a href="/alertas?cliente_id={{ cliente.id }}">sus alertas</a></dd></div>
|
||||
<div class="datos__par"><dt>Crédito</dt><dd>{% if credito %}<code>{{ credito.id_externo }}</code> · ${{ "{:,.2f}".format(credito.monto) }} · {{ credito.status }}{% else %}—{% endif %}</dd></div>
|
||||
</dl>
|
||||
{% if transacciones %}
|
||||
{% set columnas = [{"clave": "fecha_pago", "titulo": "Fecha"}, {"clave": "tipo", "titulo": "Tipo"}, {"clave": "metodo", "titulo": "Método"}, {"clave": "titular_origen", "titulo": "Titular origen"}, {"clave": "total", "titulo": "Total", "alinear": "der"}] %}
|
||||
{% call(fila, col) tabla(columnas, transacciones) %}
|
||||
{% if col.clave == "fecha_pago" %}{{ fila.fecha_pago.strftime("%d/%m/%Y") }}{% if fila.id == alerta.evidencia.transaccion_id %} {{ badge("dispara", "peligro") }}{% endif %}
|
||||
{% elif col.clave == "total" %}${{ "{:,.2f}".format(fila.total) }}
|
||||
{% else %}{{ fila[col.clave] or "—" }}{% endif %}
|
||||
{% endcall %}
|
||||
{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Evidencia", subtitulo="Los valores que dispararon la regla y el umbral aplicado") %}
|
||||
<dl class="datos">
|
||||
{% for etiqueta, valor in evidencia %}<div class="datos__par"><dt>{{ etiqueta }}</dt><dd>{{ valor }}</dd></div>{% endfor %}
|
||||
</dl>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Gestión", subtitulo="Responsable: " ~ (alerta.responsable or "sin asignar")) %}
|
||||
{% if puede_mutar %}
|
||||
<div class="acciones">
|
||||
<form class="formulario formulario--linea" method="post" action="/alertas/{{ alerta.id }}/responsable">
|
||||
<label class="campo"><span class="campo__etiqueta">Asignar responsable</span>
|
||||
<select class="campo__entrada" name="responsable">{% for u in usuarios %}<option value="{{ u }}" {% if u == (alerta.responsable or usuario.usuario) %}selected{% endif %}>{{ u }}</option>{% endfor %}</select></label>
|
||||
<button class="boton" type="submit">Asignar</button>
|
||||
</form>
|
||||
{% if transicion_disponible.en_revision %}
|
||||
<form method="post" action="/alertas/{{ alerta.id }}/estado"><input type="hidden" name="estado" value="en_revision"><button class="boton" type="submit">Pasar a revisión</button></form>
|
||||
{% endif %}
|
||||
{% if transicion_disponible.escalada %}
|
||||
<form method="post" action="/alertas/{{ alerta.id }}/estado" data-confirmar="¿Escalar la alerta? El caso se abre en el siguiente paso."><input type="hidden" name="estado" value="escalada"><button class="boton" type="submit">Escalar</button></form>
|
||||
{% endif %}
|
||||
{% if puede_cerrar %}
|
||||
<form class="formulario" method="post" action="/alertas/{{ alerta.id }}/estado" data-confirmar="¿Cerrar la alerta con esta justificación?">
|
||||
<input type="hidden" name="estado" value="cerrada">
|
||||
<label class="campo"><span class="campo__etiqueta">Justificación del cierre</span><textarea class="campo__entrada" name="motivo" rows="2" required minlength="5"></textarea></label>
|
||||
<button class="boton boton--primario" type="submit">Cerrar alerta</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p>{{ badge("Cerrar requiere rol oficial", "aviso") }} Esta alerta es crítica.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% elif alerta.estado == "cerrada" %}
|
||||
<p>{{ badge("Cerrada", "neutro") }} Sin acciones disponibles.</p>
|
||||
{% else %}
|
||||
<p>{{ badge("Solo lectura", "neutro") }} Tu rol ({{ usuario.rol }}) solo consulta.</p>
|
||||
{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Historial", subtitulo="Reconstruido desde el audit trail") %}
|
||||
{% set columnas = [{"clave": "fecha", "titulo": "Fecha"}, {"clave": "accion", "titulo": "Acción"}, {"clave": "usuario", "titulo": "Usuario"}, {"clave": "cambio", "titulo": "Cambio"}, {"clave": "motivo", "titulo": "Motivo"}] %}
|
||||
{% call(fila, col) tabla(columnas, historial, vacio="Sin eventos.") %}
|
||||
{% if col.clave == "fecha" %}{{ fila.fecha.strftime("%d/%m/%Y %H:%M") }}
|
||||
{% elif col.clave == "cambio" %}{% if fila.antes %}{{ fila.antes.estado or fila.antes.responsable or "" }} → {% endif %}{{ (fila.despues or {}).get("estado") or (fila.despues or {}).get("responsable") or (fila.despues or {}).get("regla") or "" }}
|
||||
{% else %}{{ fila[col.clave] or "—" }}{% endif %}
|
||||
{% endcall %}
|
||||
{% endcall %}
|
||||
{% endblock %}
|
||||
@@ -60,10 +60,11 @@
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Alertas", subtitulo=alertas | length ~ " en total") %}
|
||||
<p><a class="boton boton--discreto" href="/alertas?cliente_id={{ cliente.id }}">Ver en la bandeja de alertas</a></p>
|
||||
{% set columnas = [{"clave": "regla", "titulo": "Regla"}, {"clave": "nivel", "titulo": "Nivel"}, {"clave": "estado", "titulo": "Estado"}, {"clave": "vence_el", "titulo": "Vence"}, {"clave": "credito", "titulo": "Crédito"}, {"clave": "responsable", "titulo": "Responsable"}] %}
|
||||
{% call(fila, col) tabla(columnas, alertas, vacio="Sin alertas.") %}
|
||||
{% set alerta, regla = fila[0], fila[1] %}
|
||||
{% if col.clave == "regla" %}<strong>{{ regla.clave }}</strong> <small>{{ regla.nombre }} · {{ regla.version }}</small>
|
||||
{% if col.clave == "regla" %}<a href="/alertas/{{ alerta.id }}"><strong>{{ regla.clave }}</strong></a> <small>{{ regla.nombre }} · {{ regla.version }}</small>
|
||||
{% elif col.clave == "nivel" %}{{ badge_nivel_alerta(alerta.nivel) }}
|
||||
{% elif col.clave == "estado" %}{{ badge_estado_alerta(alerta.estado) }}
|
||||
{% elif col.clave == "vence_el" %}{{ alerta.vence_el.strftime("%d/%m/%Y") if alerta.vence_el else "—" }}
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Bandeja `/alertas`, detalle, acciones por rol y versionado de reglas (Fase 3, PR 2)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.importers.chm_schema import importar_esquema
|
||||
from app.main import crear_app
|
||||
from app.models import Alerta, AuditTrail, Base, ReglaAlerta
|
||||
from app.models.usuario import Rol
|
||||
from app.services import alertas as servicio
|
||||
from seed.usuarios_demo import sembrar
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "esquema_mini.xlsx"
|
||||
CONTRASENAS = {
|
||||
Rol.ANALISTA: "clave-analista-1",
|
||||
Rol.OFICIAL: "clave-oficial-2",
|
||||
Rol.AUDITOR: "clave-auditor-3",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fabrica(monkeypatch: pytest.MonkeyPatch) -> sessionmaker[Session]:
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
fabrica = crear_session_factory(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
sesion.commit()
|
||||
importar_esquema(sesion, FIXTURE, "pytest", sal="sal-alertas")
|
||||
servicio.ejecutar_reglas(sesion, usuario="pytest")
|
||||
sesion.commit()
|
||||
return fabrica
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cliente(fabrica) -> Iterator[TestClient]:
|
||||
with TestClient(crear_app(), follow_redirects=False) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def entrar(cliente: TestClient, rol: Rol) -> None:
|
||||
r = cliente.post("/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]})
|
||||
assert r.status_code == 303
|
||||
|
||||
|
||||
def id_alerta(fabrica, clave: str) -> int:
|
||||
with fabrica() as sesion:
|
||||
return sesion.execute(
|
||||
sa.select(Alerta.id)
|
||||
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
||||
.where(ReglaAlerta.clave == clave)
|
||||
.order_by(Alerta.id)
|
||||
).first()[0]
|
||||
|
||||
|
||||
def estado_de(fabrica, alerta_id: int) -> tuple[str, str | None]:
|
||||
with fabrica() as sesion:
|
||||
a = sesion.get(Alerta, alerta_id)
|
||||
return a.estado, a.responsable
|
||||
|
||||
|
||||
def filas(html: str) -> int:
|
||||
return html.count('<a href="/alertas/')
|
||||
|
||||
|
||||
# --- Bandeja --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sin_sesion_redirige(cliente: TestClient) -> None:
|
||||
assert cliente.get("/alertas").headers["location"] == "/login"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rol", list(Rol))
|
||||
def test_los_tres_roles_ven_la_bandeja_ordenada_por_vencimiento(cliente, rol: Rol) -> None:
|
||||
entrar(cliente, rol)
|
||||
r = cliente.get("/alertas")
|
||||
assert r.status_code == 200
|
||||
assert "124 abiertas de 124" in r.text
|
||||
assert "Página 1 de 3" in r.text
|
||||
assert 'href="/alertas"' in cliente.get("/inicio").text # paso habilitado en la barra lateral
|
||||
|
||||
|
||||
def test_filtros_por_familia_nivel_estado_responsable_y_vencidas(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert "124 alertas" in cliente.get("/alertas").text
|
||||
assert (
|
||||
"55 alertas" in cliente.get("/alertas?familia=B").text
|
||||
) # B-01 3 + B-04 1 + B-06 50 + B-08 1
|
||||
with fabrica() as sesion:
|
||||
criticas = sesion.scalar(
|
||||
sa.select(sa.func.count(Alerta.id)).where(
|
||||
Alerta.nivel == "critica", Alerta.estado == "nueva"
|
||||
)
|
||||
)
|
||||
assert criticas == 74 # A-01 12 + B-01 3 + B-04 1 + B-06 50 + B-08 1 + D-03 2 + D-04 1 + E-01 4
|
||||
assert f"{criticas} alertas" in cliente.get("/alertas?nivel=critica&estado=nueva").text
|
||||
assert "0 alertas" in cliente.get("/alertas?estado=cerrada").text
|
||||
assert "0 alertas" in cliente.get("/alertas?responsable=oficial").text
|
||||
|
||||
a01 = id_alerta(fabrica, "A-01")
|
||||
with fabrica() as sesion:
|
||||
servicio.asignar_responsable(sesion, a01, "oficial", usuario="pytest")
|
||||
servicio.cambiar_estado(sesion, a01, "cerrada", motivo="prueba", usuario="pytest")
|
||||
sesion.commit()
|
||||
assert "1 alertas" in cliente.get("/alertas?estado=cerrada").text
|
||||
assert "1 alertas" in cliente.get("/alertas?responsable=oficial").text
|
||||
# vencidas: abiertas con vence_el anterior a hoy. Las de crédito y transacción vencen desde la
|
||||
# fecha del evento (A-01, B-06, B-08, D-04); C-03 no tiene plazo (vence_el nulo) y las de
|
||||
# cliente, sin fecha de evento, vencen a partir de hoy: ninguna de esas cuenta.
|
||||
with fabrica() as sesion:
|
||||
vencidas = sesion.scalar(
|
||||
sa.select(sa.func.count(Alerta.id)).where(
|
||||
Alerta.vence_el < date.today(), Alerta.estado != "cerrada"
|
||||
)
|
||||
)
|
||||
assert vencidas == 63 # A-01 12 + B-06 50 + B-08 1 + D-04 1 = 64, menos la A-01 cerrada
|
||||
assert f"{vencidas} alertas" in cliente.get("/alertas?vencidas=1").text
|
||||
assert "123 abiertas" in cliente.get("/alertas").text
|
||||
|
||||
|
||||
def test_filtro_por_cliente_enlaza_con_la_ficha(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
with fabrica() as sesion:
|
||||
cliente_id = sesion.scalar(sa.select(Alerta.cliente_id).order_by(Alerta.id))
|
||||
esperadas = sesion.scalar(
|
||||
sa.select(sa.func.count(Alerta.id)).where(Alerta.cliente_id == cliente_id)
|
||||
)
|
||||
r = cliente.get(f"/alertas?cliente_id={cliente_id}")
|
||||
assert f"{esperadas} alertas" in r.text and f'href="/clientes/{cliente_id}"' in r.text
|
||||
assert f"/alertas?cliente_id={cliente_id}" in cliente.get(f"/clientes/{cliente_id}").text
|
||||
|
||||
|
||||
def test_filtro_invalido_da_422(cliente) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert cliente.get("/alertas?familia=Z").status_code == 422
|
||||
assert cliente.get("/alertas?nivel=enorme").status_code == 422
|
||||
assert cliente.get("/alertas?pagina=0").status_code == 422
|
||||
|
||||
|
||||
# --- Detalle --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_detalle_muestra_regla_version_evidencia_y_transacciones(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
c03 = id_alerta(fabrica, "C-03")
|
||||
r = cliente.get(f"/alertas/{c03}")
|
||||
assert r.status_code == 200
|
||||
html = r.text
|
||||
assert "C-03" in html and "v2" in html and "Evidencia" in html
|
||||
assert "Meses desde el pago anterior" in html or "Cambios de método en la ventana" in html
|
||||
assert "dispara" in html # la transacción que dispara, marcada
|
||||
assert "Historial" in html and "crear" in html
|
||||
assert "Solo lectura" in html and 'action="/alertas/' not in html
|
||||
assert cliente.get("/alertas/999999").status_code == 404
|
||||
|
||||
|
||||
# --- Acciones y permisos --------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_auditor_recibe_403_en_toda_mutacion(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
a = id_alerta(fabrica, "B-01")
|
||||
assert (
|
||||
cliente.post(f"/alertas/{a}/responsable", data={"responsable": "auditor"}).status_code
|
||||
== 403
|
||||
)
|
||||
for estado in ("en_revision", "escalada", "cerrada"):
|
||||
r = cliente.post(f"/alertas/{a}/estado", data={"estado": estado, "motivo": "x"})
|
||||
assert r.status_code == 403
|
||||
assert estado_de(fabrica, a) == ("nueva", None)
|
||||
|
||||
|
||||
def test_analista_asigna_revisa_y_escala_y_queda_en_audit_trail(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
a = id_alerta(fabrica, "C-03")
|
||||
assert (
|
||||
cliente.post(f"/alertas/{a}/responsable", data={"responsable": "analista"}).status_code
|
||||
== 303
|
||||
)
|
||||
assert estado_de(fabrica, a) == ("nueva", "analista")
|
||||
assert cliente.post(f"/alertas/{a}/estado", data={"estado": "en_revision"}).status_code == 303
|
||||
assert estado_de(fabrica, a)[0] == "en_revision"
|
||||
assert cliente.post(f"/alertas/{a}/estado", data={"estado": "escalada"}).status_code == 303
|
||||
assert estado_de(fabrica, a)[0] == "escalada"
|
||||
with fabrica() as sesion:
|
||||
acciones = sesion.scalars(
|
||||
sa.select(AuditTrail.accion)
|
||||
.where(AuditTrail.entidad == "alerta", AuditTrail.entidad_id == a)
|
||||
.order_by(AuditTrail.id)
|
||||
).all()
|
||||
assert acciones == ["crear", "asignar", "estado:en_revision", "estado:escalada"]
|
||||
html = cliente.get(f"/alertas/{a}").text
|
||||
assert "en_revision" in html and "escalada" in html and "analista" in html
|
||||
|
||||
|
||||
def test_transiciones_invalidas_dan_400(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
a = id_alerta(fabrica, "C-03") # preventiva
|
||||
assert (
|
||||
cliente.post(f"/alertas/{a}/estado", data={"estado": "cerrada", "motivo": "ok"}).status_code
|
||||
== 303
|
||||
)
|
||||
assert cliente.post(f"/alertas/{a}/estado", data={"estado": "en_revision"}).status_code == 400
|
||||
assert (
|
||||
cliente.post(f"/alertas/{a}/responsable", data={"responsable": "oficial"}).status_code
|
||||
== 400
|
||||
)
|
||||
assert cliente.post(f"/alertas/{a}/estado", data={"estado": "inventado"}).status_code == 400
|
||||
assert estado_de(fabrica, a)[0] == "cerrada"
|
||||
|
||||
|
||||
def test_cerrar_sin_justificacion_da_400(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
a = id_alerta(fabrica, "D-05")
|
||||
r = cliente.post(f"/alertas/{a}/estado", data={"estado": "cerrada", "motivo": " "})
|
||||
assert r.status_code == 400 and "justificación" in r.text
|
||||
assert estado_de(fabrica, a)[0] == "nueva"
|
||||
|
||||
|
||||
def test_cerrar_critica_requiere_oficial(cliente, fabrica) -> None:
|
||||
a = id_alerta(fabrica, "A-01") # critica
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert "Cerrar requiere rol oficial" in cliente.get(f"/alertas/{a}").text
|
||||
r = cliente.post(f"/alertas/{a}/estado", data={"estado": "cerrada", "motivo": "falso positivo"})
|
||||
assert r.status_code == 403
|
||||
assert estado_de(fabrica, a)[0] == "nueva"
|
||||
cliente.post("/logout")
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
r = cliente.post(f"/alertas/{a}/estado", data={"estado": "cerrada", "motivo": "falso positivo"})
|
||||
assert r.status_code == 303
|
||||
assert estado_de(fabrica, a) == ("cerrada", "oficial")
|
||||
|
||||
|
||||
# --- Versionado de reglas (genérico; el brief lo pide para B-02) ----------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clave", ["B-06", "B-02", "A-01"])
|
||||
def test_versionar_regla_no_altera_las_alertas_previas(fabrica, clave: str) -> None:
|
||||
with fabrica() as sesion:
|
||||
vieja = sesion.scalar(
|
||||
sa.select(ReglaAlerta).where(ReglaAlerta.clave == clave, ReglaAlerta.valid_to.is_(None))
|
||||
)
|
||||
previas = {
|
||||
a.id: a.regla_id
|
||||
for a in sesion.scalars(sa.select(Alerta).where(Alerta.regla_id == vieja.id))
|
||||
}
|
||||
nueva = servicio.versionar_regla(
|
||||
sesion,
|
||||
clave,
|
||||
{"parametros": {**(vieja.parametros or {}), "factor_prueba": 9}},
|
||||
"Cambio de parámetro para la prueba",
|
||||
"oficial",
|
||||
)
|
||||
sesion.commit()
|
||||
|
||||
assert nueva.id != vieja.id and nueva.version == "v2.1" and vieja.version == "v2"
|
||||
assert vieja.valid_to is not None and nueva.valid_to is None
|
||||
assert nueva.parametros["factor_prueba"] == 9
|
||||
assert nueva.parametros["_sustituye_a"] == "v2"
|
||||
assert nueva.parametros["_justificacion"] == "Cambio de parámetro para la prueba"
|
||||
assert nueva.aprobado_por == "oficial" and nueva.vigente_desde == date.today()
|
||||
vigentes = {
|
||||
r.clave: r for r in servicio.reglas_vigentes(sesion, servicio.tenant_de_sesion(sesion))
|
||||
}
|
||||
assert vigentes[clave].id == nueva.id
|
||||
# las alertas creadas con la versión anterior conservan su regla_id
|
||||
for alerta_id, regla_id in previas.items():
|
||||
assert sesion.get(Alerta, alerta_id).regla_id == regla_id == vieja.id
|
||||
auditoria = sesion.scalar(
|
||||
sa.select(AuditTrail).where(
|
||||
AuditTrail.entidad == "regla_alerta", AuditTrail.entidad_id == nueva.id
|
||||
)
|
||||
)
|
||||
assert (
|
||||
auditoria.accion == "versionar"
|
||||
and auditoria.motivo == "Cambio de parámetro para la prueba"
|
||||
)
|
||||
# versionar otra vez da v2.2; sin justificación falla; campos desconocidos fallan
|
||||
assert servicio.versionar_regla(sesion, clave, {}, "otra", "oficial").version == "v2.2"
|
||||
with pytest.raises(ValueError):
|
||||
servicio.versionar_regla(sesion, clave, {}, " ", "oficial")
|
||||
with pytest.raises(ValueError):
|
||||
servicio.versionar_regla(sesion, clave, {"clave": "X"}, "x", "oficial")
|
||||
|
||||
|
||||
def test_version_nueva_no_duplica_hallazgos_abiertos_y_aplica_el_parametro_nuevo(fabrica) -> None:
|
||||
with fabrica() as sesion:
|
||||
abiertas_antes = sesion.scalar(sa.select(sa.func.count(Alerta.id)))
|
||||
nueva = servicio.versionar_regla(
|
||||
sesion,
|
||||
"B-06",
|
||||
{"parametros": {"titulares_que_disparan": ["TERCERO", "CUENTA"]}},
|
||||
"CHM confirma que CUENTA también dispara",
|
||||
"oficial",
|
||||
)
|
||||
resumen = servicio.ejecutar_reglas(sesion, claves=["B-06"], usuario="pytest")
|
||||
sesion.commit()
|
||||
assert resumen.por_regla["B-06"].version == "v2.1"
|
||||
assert resumen.por_regla["B-06"].existentes == 50 # las TERCERO abiertas no se duplican
|
||||
assert resumen.por_regla["B-06"].creadas == 215 # las CUENTA, con la versión nueva
|
||||
assert sesion.scalar(sa.select(sa.func.count(Alerta.id))) == abiertas_antes + 215
|
||||
assert (
|
||||
sesion.scalar(sa.select(sa.func.count(Alerta.id)).where(Alerta.regla_id == nueva.id))
|
||||
== 215
|
||||
)
|
||||
|
||||
|
||||
def test_sincronizar_desde_json_versiona_solo_lo_que_cambio(fabrica, tmp_path) -> None:
|
||||
with fabrica() as sesion:
|
||||
# el JSON actual ya está cargado: nada cambia
|
||||
assert (
|
||||
servicio.sincronizar_reglas_desde_json(sesion, usuario="oficial")["versionadas"] == []
|
||||
)
|
||||
datos = json.loads(servicio.RUTA_REGLAS.read_text(encoding="utf-8"))
|
||||
for r in datos["reglas"]:
|
||||
if r["clave"] == "B-02":
|
||||
r["parametros"]["capacidad_pago_max"] = 0.5
|
||||
ruta = tmp_path / "reglas.json"
|
||||
ruta.write_text(json.dumps(datos, ensure_ascii=False), encoding="utf-8")
|
||||
resultado = servicio.sincronizar_reglas_desde_json(sesion, ruta, usuario="oficial")
|
||||
sesion.commit()
|
||||
assert resultado["versionadas"] == ["B-02"] and resultado["nuevas"] == []
|
||||
versiones = sesion.scalars(
|
||||
sa.select(ReglaAlerta.version)
|
||||
.where(ReglaAlerta.clave == "B-02")
|
||||
.order_by(ReglaAlerta.id)
|
||||
).all()
|
||||
assert versiones == ["v2", "v2.1"]
|
||||
vigente = sesion.scalar(
|
||||
sa.select(ReglaAlerta).where(
|
||||
ReglaAlerta.clave == "B-02", ReglaAlerta.valid_to.is_(None)
|
||||
)
|
||||
)
|
||||
assert vigente.parametros["capacidad_pago_max"] == 0.5
|
||||
assert (
|
||||
servicio.sincronizar_reglas_desde_json(sesion, ruta, usuario="oficial")["versionadas"]
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
def test_vencimiento_vencida_se_marca_en_bandeja(cliente, fabrica) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
a = id_alerta(fabrica, "A-01") # vence el 17 del mes siguiente a la disposición (2023…)
|
||||
with fabrica() as sesion:
|
||||
alerta = sesion.get(Alerta, a)
|
||||
assert alerta.vence_el is not None and alerta.vence_el < date.today() - timedelta(days=1)
|
||||
assert "Vencida" in cliente.get(f"/alertas?cliente_id={alerta.cliente_id}&familia=A").text
|
||||
b01 = id_alerta(fabrica, "B-01") # sin fecha de evento: vence mañana (24h), no está vencida
|
||||
with fabrica() as sesion:
|
||||
assert sesion.get(Alerta, b01).vence_el == date.today() + timedelta(days=1)
|
||||
Reference in new issue
Block a user