diff --git a/app/routers/alertas.py b/app/routers/alertas.py
index fe4158f..b7a1565 100644
--- a/app/routers/alertas.py
+++ b/app/routers/alertas.py
@@ -28,7 +28,10 @@ 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,
@@ -44,7 +47,7 @@ ROLES_MUTAN = (Rol.ANALISTA, Rol.OFICIAL)
POR_DICTAMINAR = ("nueva", "en_revision")
SIN_PENDIENTES = "Sin alertas pendientes"
FAMILIAS = ("A", "B", "C", "D", "E")
-NIVELES = ("critica", "preventiva", "informativa")
+NIVELES = NIVELES_ALERTA
ESTADOS = ("nueva", "en_revision", "escalada", "cerrada", ESTADO_HISTORICA)
ETIQUETAS_EVIDENCIA = {
"monto": "Monto del crédito",
@@ -135,6 +138,19 @@ def _evidencia_legible(evidencia: dict | None) -> list[tuple[str, str]]:
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,
@@ -153,10 +169,14 @@ def bandeja(
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)
- else: # las anteriores a la operación de la plataforma solo si se piden (Pieza N)
+ # 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:
@@ -171,8 +191,13 @@ def bandeja(
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(Alerta.vence_el.is_(None), Alerta.vence_el, Alerta.id)
+ base.order_by(vencida, cerrada, Alerta.vence_el.is_(None), Alerta.vence_el, Alerta.id)
).all()
total = len(filas_db)
@@ -215,7 +240,10 @@ def bandeja(
"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},
+ # 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,
}
@@ -236,7 +264,7 @@ def bandeja(
"filtros": filtros,
"conteos": conteos,
"familias": FAMILIAS,
- "niveles": NIVELES,
+ "niveles": _niveles_en_uso(db, tenant.id, todas),
"estados": ESTADOS,
"responsables": responsables,
"pagina": pagina,
@@ -277,7 +305,9 @@ def _detalle(
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)
+ puede_cerrar = puede_mutar and (
+ alerta.nivel not in CIERRA_SOLO_OFICIAL or usuario.rol == Rol.OFICIAL
+ )
analistas = sorted(
{
u
diff --git a/app/schemas/alertas.py b/app/schemas/alertas.py
index 341e60a..294c7c0 100644
--- a/app/schemas/alertas.py
+++ b/app/schemas/alertas.py
@@ -60,8 +60,9 @@ class FiltrosAlertas(BaseModel):
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
+ nivel: Literal["critica", "aviso_umbral", "preventiva", "informativa"] | None = None
+ # Sin estado la bandeja muestra las abiertas; "todas" quita el filtro (salvo las históricas).
+ estado: EstadoAlerta | Literal["abiertas", "todas"] | None = None
responsable: str | None = Field(default=None, max_length=64)
vencidas: bool = False
cliente_id: int | None = Field(default=None, ge=1)
diff --git a/app/services/alertas.py b/app/services/alertas.py
index d5158cf..38d6218 100644
--- a/app/services/alertas.py
+++ b/app/services/alertas.py
@@ -96,6 +96,12 @@ RUTA_CATALOGOS = RAIZ / "seed" / "catalogos"
RUTA_REGLAS = RAIZ / "seed" / "reglas_alerta_v2.json"
ROL_OFICIAL = "oficial"
NIVEL_CRITICA = "critica"
+# La obligación de aviso por umbral (A-01, A-02): no es una señal de riesgo, así que no pide
+# reevaluación extraordinaria; cerrarla sigue siendo del oficial. Qué regla la usa lo dice su
+# `nivel` versionado (pendiente del especialista `nivel_aviso_umbral`), nunca este código.
+NIVEL_AVISO_UMBRAL = "aviso_umbral"
+NIVELES_ALERTA = (NIVEL_CRITICA, NIVEL_AVISO_UMBRAL, "preventiva", "informativa")
+CIERRA_SOLO_OFICIAL = frozenset({NIVEL_CRITICA, NIVEL_AVISO_UMBRAL})
CAMPOS_VERSIONABLES = (
"nombre",
"criterio_texto",
@@ -726,8 +732,9 @@ def cambiar_estado(
raise TransicionInvalidaError(f"{alerta.estado} → {estado} no está permitida")
if estado == "cerrada" and not (motivo and motivo.strip()):
raise TransicionInvalidaError("cerrar una alerta exige motivo")
- if estado == "cerrada" and alerta.nivel == NIVEL_CRITICA and rol and rol != ROL_OFICIAL:
- raise RolInsuficienteError("cerrar una alerta crítica exige rol oficial")
+ solo_oficial = alerta.nivel in CIERRA_SOLO_OFICIAL
+ if estado == "cerrada" and solo_oficial and rol and rol != ROL_OFICIAL:
+ raise RolInsuficienteError(f"cerrar una alerta {alerta.nivel} exige rol oficial")
antes = {"estado": alerta.estado, "responsable": alerta.responsable}
alerta.estado = estado
alerta.responsable = responsable or alerta.responsable or autor
diff --git a/app/static/app.css b/app/static/app.css
index 1ed3e07..5e1db7c 100644
--- a/app/static/app.css
+++ b/app/static/app.css
@@ -386,6 +386,7 @@ a.resumen__cifra:hover, button.resumen__cifra:hover { background: var(--color-su
.celda-doble small { display: block; font-family: var(--fuente); font-variant-numeric: tabular-nums; font-size: 11.5px; color: var(--color-texto-suave); }
.celda-regla { max-width: 340px; }
.punto[data-nivel-alerta="critica"] { background: var(--tono-peligro); }
+.punto[data-nivel-alerta="aviso_umbral"] { background: var(--tono-acento); }
.punto[data-nivel-alerta="preventiva"] { background: var(--tono-aviso-punto); }
.punto[data-nivel-alerta="informativa"] { background: var(--color-verde); }
.celda-num { font-family: var(--fuente); font-variant-numeric: tabular-nums; font-size: 13.5px; white-space: nowrap; font-variant-numeric: tabular-nums; }
diff --git a/app/templates/_componentes/badges.html b/app/templates/_componentes/badges.html
index 08cf15e..c258364 100644
--- a/app/templates/_componentes/badges.html
+++ b/app/templates/_componentes/badges.html
@@ -5,7 +5,7 @@
badge(texto, tono) tono: neutro | info | exito | aviso | peligro | acento
badge_nivel(nivel) nivel de riesgo: bajo | medio | alto (o 1 | 2 | 3)
badge_estado_alerta(estado) nueva | en_revision | escalada | cerrada | historica
- badge_nivel_alerta(nivel) informativa | preventiva | critica
+ badge_nivel_alerta(nivel) informativa | preventiva | critica | aviso_umbral
-#}
{%- macro badge(texto, tono="neutro") -%}
@@ -37,6 +37,7 @@
"informativa": ("Informativa", "info"),
"preventiva": ("Preventiva", "aviso"),
"critica": ("Crítica", "peligro"),
+ "aviso_umbral": ("Aviso por umbral", "acento"),
} -%}
{%- set etiqueta, tono = niveles.get(clave, (nivel, "neutro")) -%}
{{ etiqueta }}
diff --git a/app/templates/alertas/bandeja.html b/app/templates/alertas/bandeja.html
index 0473ee0..e97e5a1 100644
--- a/app/templates/alertas/bandeja.html
+++ b/app/templates/alertas/bandeja.html
@@ -45,7 +45,7 @@
Alertas y casos
-
{{ conteos.abiertas }} abiertas de {{ conteos.total }} · {{ conteos.vencidas }} vencidas · ordenadas por vencimiento
+
{{ conteos.abiertas }} abiertas de {{ conteos.total }} · {{ conteos.vencidas }} vencidas · primero las vencidas, luego por vencimiento