test(screening): normalización, lectores, versiones, umbral, alias, decisiones, roles y pantallas
This commit is contained in:
1 parent
20ae22266a
commit
39c4fdf609
2 files changed
+620
-2
No files matched your search
@@ -0,0 +1,617 @@
|
||||
"""Screening (Fase 4, PR 2): normalización, lectores de listas, versiones, umbral por lista,
|
||||
coincidencia por alias, no duplicación, decisiones (reevaluación y preponderancia con el servicio
|
||||
real de la Pieza C), `declarada_por_CHM`, roles y pantallas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from collections.abc import Iterator
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app import audit
|
||||
from app.config import get_settings
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.engine.screening import Entrada, Indice, normalizar, tokens
|
||||
from app.importers import lists as importador
|
||||
from app.importers.chm_schema import importar_esquema
|
||||
from app.main import crear_app
|
||||
from app.models import (
|
||||
AuditTrail,
|
||||
Base,
|
||||
Cliente,
|
||||
Coincidencia,
|
||||
EvaluacionRiesgo,
|
||||
Lista,
|
||||
LoteCarga,
|
||||
)
|
||||
from app.models.usuario import Rol
|
||||
from app.services import alertas as servicio_alertas
|
||||
from app.services import expediente as servicio_expediente
|
||||
from app.services import riesgo as servicio_riesgo
|
||||
from app.services import screening as servicio
|
||||
from app.services.alertas import tenant_de_sesion
|
||||
from seed.identidades_sinteticas import sembrar as sembrar_identidades
|
||||
from seed.usuarios_demo import sembrar
|
||||
from tests.test_expediente import CONTRASENAS, FISICA, FIXTURE, dar_de_alta, entrar
|
||||
|
||||
DIR_LISTAS = Path(__file__).parent / "fixtures" / "listas"
|
||||
JUSTIFICACION = (
|
||||
"Coinciden nombre completo, alias y fecha de nacimiento verificada en el expediente."
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fabrica(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> sessionmaker[Session]:
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
fabrica = crear_session_factory(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
||||
monkeypatch.setattr(get_settings(), "data_dir", tmp_path)
|
||||
servicio.vaciar_cache()
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
sesion.commit()
|
||||
importar_esquema(sesion, FIXTURE, "pytest", sal="sal-screening")
|
||||
servicio_alertas.ejecutar_reglas(sesion, usuario="pytest")
|
||||
sembrar_identidades(sesion)
|
||||
for nombre in importador.LISTAS:
|
||||
archivo = next(DIR_LISTAS.glob(importador.LISTAS[nombre].patron_archivo))
|
||||
importador.importar_lista(sesion, nombre, archivo, usuario="pytest")
|
||||
sesion.commit()
|
||||
return fabrica
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cliente(fabrica: sessionmaker[Session]) -> Iterator[TestClient]:
|
||||
with TestClient(crear_app(), follow_redirects=False) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def sesion_con_actor(fabrica: sessionmaker[Session]) -> Session:
|
||||
sesion = fabrica()
|
||||
audit.fijar_actor(sesion, "pytest", 1)
|
||||
return sesion
|
||||
|
||||
|
||||
def alta(
|
||||
cliente: TestClient, nombre: str, apellido_paterno: str, apellido_materno: str = ""
|
||||
) -> int:
|
||||
entrar(cliente)
|
||||
return dar_de_alta(
|
||||
cliente,
|
||||
{
|
||||
**FISICA,
|
||||
"nombre": nombre,
|
||||
"apellido_paterno": apellido_paterno,
|
||||
"apellido_materno": apellido_materno,
|
||||
"curp": "",
|
||||
"rfc": "",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# --- Motor (puro) ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("texto", "esperado"),
|
||||
[
|
||||
("José Pérez-López", "JOSE PEREZ LOPEZ"),
|
||||
("Ficticia, S.A. de C.V.", "FICTICIA"),
|
||||
("Grupo Ejemplo S.A.P.I. de C.V.", "GRUPO EJEMPLO"),
|
||||
("Comercial del Norte, S. de R.L. de C.V.", "COMERCIAL DEL NORTE"),
|
||||
("Asesores & Hijos, S.C.", "ASESORES Y HIJOS"),
|
||||
("ANGLO-CARIBBEAN CO., LTD.", "ANGLO CARIBBEAN"),
|
||||
(" Ñandú ÜBER ", "NANDU UBER"),
|
||||
("", ""),
|
||||
(None, ""),
|
||||
],
|
||||
)
|
||||
def test_normalizacion(texto: str | None, esperado: str) -> None:
|
||||
assert normalizar(texto) == esperado
|
||||
|
||||
|
||||
def test_tokens_informativos_ignoran_conectivos_y_cortos() -> None:
|
||||
assert tokens("JOSE DE LA CRUZ Y GARCIA") == {"JOSE", "CRUZ", "GARCIA"}
|
||||
|
||||
|
||||
def test_indice_prefiltra_por_token_y_busca_por_nombre_y_alias() -> None:
|
||||
entradas = [
|
||||
Entrada("1", "ABBAS, Abu", alias=("ZAYDAN, Muhammad",), tipo_persona="fisica"),
|
||||
Entrada("2", "PEREZ LOPEZ, Ana Maria", tipo_persona="fisica"),
|
||||
Entrada("3", "FICTICIA, S.A. DE C.V.", tipo_persona="moral"),
|
||||
]
|
||||
indice = Indice(entradas)
|
||||
assert len(indice) == 3
|
||||
assert indice.candidatas(normalizar("Muhammad Zaydan")) == {0}
|
||||
assert indice.candidatas(normalizar("Nadie Conocido")) == set()
|
||||
por_alias = indice.buscar("Muhammad Zaydan", 85)
|
||||
assert [c.entrada.identificador for c in por_alias] == ["1"]
|
||||
assert por_alias[0].es_alias and por_alias[0].texto == "ZAYDAN, Muhammad"
|
||||
assert por_alias[0].score == 100
|
||||
moral = indice.buscar("Ficticia SA de CV", 85)
|
||||
assert moral and moral[0].entrada.identificador == "3" and not moral[0].es_alias
|
||||
assert indice.buscar("Ana Maria Perez Lopez", 85)[0].score == 100
|
||||
assert indice.buscar("Ana Perez", 85) == []
|
||||
assert indice.buscar("Ana Perez", 60)[0].entrada.identificador == "2"
|
||||
|
||||
|
||||
# --- Lectores e importación -----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_lectores_normalizan_cada_formato() -> None:
|
||||
ofac = importador.leer_ofac(DIR_LISTAS / "ofac_sdn_2026-01-01.csv")
|
||||
por_id = {e.identificador: e for e in ofac}
|
||||
assert set(por_id) == {"1001", "1002", "1003", "1004", "1005"}
|
||||
assert por_id["1001"].alias == ("ZAYDAN, Muhammad", "ABU ABBAS")
|
||||
assert por_id["1001"].fecha_nacimiento == date(1948, 12, 10)
|
||||
assert por_id["1001"].tipo_persona == "fisica" and por_id["1001"].datos["programa"] == "SDGT"
|
||||
assert por_id["1002"].tipo_persona == "moral" and por_id["1002"].alias == (
|
||||
"NATIONAL CARIBBEAN COMPANY",
|
||||
)
|
||||
assert por_id["1003"].tipo_persona is None # buque
|
||||
assert por_id["1004"].fecha_nacimiento == date(1990, 5, 4)
|
||||
|
||||
onu = importador.leer_onu(DIR_LISTAS / "onu_consolidada_2026-01-01.xml")
|
||||
assert [e.identificador for e in onu] == ["9001", "9002", "9101"]
|
||||
assert onu[0].nombre == "ERIC BADEGE" and onu[0].alias == ("Colonel Eric Badege",)
|
||||
assert onu[0].fecha_nacimiento == date(1971, 1, 1)
|
||||
assert onu[0].pais == "Democratic Republic of the Congo"
|
||||
assert onu[1].nombre == "JUAN CARLOS RAMIREZ SOTO" and onu[1].fecha_nacimiento == date(
|
||||
1980, 2, 2
|
||||
)
|
||||
assert onu[2].tipo_persona == "moral" and onu[2].pais == "Panama" and onu[2].alias == ("EFI",)
|
||||
|
||||
sat = importador.leer_69b(DIR_LISTAS / "sat_69b_2026-01-01.csv")
|
||||
assert [e.identificador for e in sat] == ["FIC010101AB1", "GOMA800101AB3"] # solo Definitivo
|
||||
assert sat[0].tipo_persona == "moral" and sat[1].tipo_persona == "fisica"
|
||||
assert sat[1].nombre == "GÓMEZ MARTÍNEZ ANTONIO" # latin-1 bien decodificado
|
||||
assert sat[0].datos["publicacion_dof"] == "15/08/2018"
|
||||
|
||||
pep = importador.leer_pep(DIR_LISTAS / "pep_ejemplo_2026-01-01.csv")
|
||||
assert [e.identificador for e in pep] == ["PEP-MX-0001", "PEP-EX-0001"]
|
||||
assert pep[0].alias == ("R. Villasenor",) and pep[0].datos["cargo"] == "Gobernador"
|
||||
assert pep[1].pais == "Brasil" and pep[1].datos["tipo_pep"] == "extranjera"
|
||||
|
||||
|
||||
def test_importar_crea_lista_y_lote_y_es_idempotente_por_hash(
|
||||
fabrica: sessionmaker[Session],
|
||||
) -> None:
|
||||
with fabrica() as sesion:
|
||||
listas = sesion.scalars(sa.select(Lista).order_by(Lista.nombre)).all()
|
||||
assert [(li.nombre, li.entradas, li.fecha_version) for li in listas] == [
|
||||
("ofac_sdn", 5, date(2026, 1, 1)),
|
||||
("onu", 3, date(2026, 1, 1)),
|
||||
("pep", 2, date(2026, 1, 1)),
|
||||
("sat_69b", 2, date(2026, 1, 1)),
|
||||
]
|
||||
assert {li.nombre: li.umbral for li in listas} == {
|
||||
"ofac_sdn": Decimal("85.00"),
|
||||
"onu": Decimal("80.00"),
|
||||
"pep": Decimal("80.00"),
|
||||
"sat_69b": Decimal("85.00"),
|
||||
}
|
||||
assert all(len(li.archivo_hash) == 64 for li in listas)
|
||||
assert all(li.ruta.startswith("tests/fixtures/listas/") for li in listas)
|
||||
lotes = sesion.scalars(sa.select(LoteCarga).where(LoteCarga.tipo == "lista")).all()
|
||||
assert {lote.archivo_hash for lote in lotes} == {li.archivo_hash for li in listas}
|
||||
assert (
|
||||
sesion.scalar(
|
||||
sa.select(sa.func.count(AuditTrail.id)).where(
|
||||
AuditTrail.entidad == "lista", AuditTrail.accion == "cargar_version"
|
||||
)
|
||||
)
|
||||
== 4
|
||||
)
|
||||
# El mismo archivo otra vez: sin fila nueva.
|
||||
assert (
|
||||
importador.importar_lista(
|
||||
sesion, "ofac_sdn", DIR_LISTAS / "ofac_sdn_2026-01-01.csv", usuario="pytest"
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert sesion.scalar(sa.select(sa.func.count(Lista.id))) == 4
|
||||
with pytest.raises(importador.ListaDesconocidaError):
|
||||
importador.definicion("interpol")
|
||||
|
||||
|
||||
def test_una_version_nueva_no_toca_la_anterior(
|
||||
fabrica: sessionmaker[Session], tmp_path: Path
|
||||
) -> None:
|
||||
nueva = tmp_path / "ofac_sdn_2026-02-01.csv"
|
||||
shutil.copy(DIR_LISTAS / "ofac_sdn_2026-01-01.csv", nueva)
|
||||
nueva.write_text(
|
||||
nueva.read_text(encoding="latin-1")
|
||||
+ '1006,"NUEVO, Registro","individual","SDGT",-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- \n',
|
||||
encoding="latin-1",
|
||||
)
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
tenant = tenant_de_sesion(sesion)
|
||||
anterior = servicio.listas_vigentes(sesion, tenant)["ofac_sdn"]
|
||||
servicio.actualizar_umbral(
|
||||
sesion,
|
||||
anterior.id,
|
||||
90,
|
||||
"Umbral de la versión anterior, para comprobar que no se hereda ni se pierde.",
|
||||
)
|
||||
v2 = importador.importar_lista(sesion, "ofac_sdn", nueva, usuario="pytest")
|
||||
sesion.commit()
|
||||
assert v2 is not None and v2.id != anterior.id
|
||||
assert v2.fecha_version == date(2026, 2, 1) and v2.entradas == 6
|
||||
assert v2.ruta == str(nueva.resolve()) # fuera del repo: absoluta
|
||||
assert v2.umbral == Decimal("85.00") # por omisión de la lista, no de la versión anterior
|
||||
sesion.refresh(anterior)
|
||||
assert anterior.entradas == 5 and anterior.umbral == Decimal("90.00")
|
||||
assert anterior.fecha_version == date(2026, 1, 1)
|
||||
vigentes = servicio.listas_vigentes(sesion, tenant)
|
||||
assert vigentes["ofac_sdn"].id == v2.id
|
||||
versiones = [li.id for li in servicio.versiones(sesion, tenant) if li.nombre == "ofac_sdn"]
|
||||
assert versiones == [v2.id, anterior.id]
|
||||
|
||||
|
||||
# --- Servicio ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_coincidencia_por_alias_y_sin_duplicados(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
cliente_id = alta(cliente, "Muhammad", "Zaydan")
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
resumen = servicio.screening_cliente(sesion, cliente_id)
|
||||
sesion.commit()
|
||||
assert (
|
||||
resumen.consultados == 1
|
||||
and resumen.creadas == 1
|
||||
and dict(resumen.por_lista) == {"ofac_sdn": 1}
|
||||
)
|
||||
fila = sesion.scalar(sa.select(Coincidencia).where(Coincidencia.persona_id == cliente_id))
|
||||
assert fila.decision == "pendiente" and fila.fuente == "screening"
|
||||
assert fila.entrada_id == "1001" and fila.alias == "ZAYDAN, Muhammad"
|
||||
assert fila.texto_lista == "ZAYDAN, Muhammad" and fila.score == Decimal("100.00")
|
||||
assert fila.detalle["nombre_en_lista"] == "ABBAS, Abu"
|
||||
assert (
|
||||
fila.detalle["programa"] == "SDGT" and fila.detalle["fecha_nacimiento"] == "1948-12-10"
|
||||
)
|
||||
assert fila.detalle["coincidio_por_alias"] is True
|
||||
lista = sesion.get(Lista, fila.lista_id)
|
||||
assert lista.nombre == "ofac_sdn" and lista.fecha_version == date(2026, 1, 1)
|
||||
# Segunda consulta: misma persona, lista y entrada → no duplica.
|
||||
otra = servicio.screening_cliente(sesion, cliente_id)
|
||||
sesion.commit()
|
||||
assert otra.creadas == 0 and otra.existentes == 1
|
||||
assert (
|
||||
sesion.scalar(
|
||||
sa.select(sa.func.count(Coincidencia.id)).where(
|
||||
Coincidencia.persona_id == cliente_id
|
||||
)
|
||||
)
|
||||
== 1
|
||||
)
|
||||
# La cartera completa tampoco duplica y no revienta con los importados.
|
||||
cartera = servicio.screening_cartera(sesion)
|
||||
assert cartera.creadas == 0 and cartera.existentes >= 1 and cartera.consultados >= 31
|
||||
|
||||
|
||||
def test_umbral_por_lista(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
|
||||
cliente_id = alta(cliente, "Ana", "Perez") # vs "PEREZ LOPEZ, Ana Maria": score ~ 67
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
assert servicio.screening_cliente(sesion, cliente_id).creadas == 0
|
||||
tenant = tenant_de_sesion(sesion)
|
||||
ofac = servicio.listas_vigentes(sesion, tenant)["ofac_sdn"]
|
||||
servicio.actualizar_umbral(
|
||||
sesion, ofac.id, 60, "Prueba: bajar el umbral de OFAC para captar nombres parciales."
|
||||
)
|
||||
assert servicio.screening_cliente(sesion, cliente_id).creadas == 1
|
||||
fila = sesion.scalar(sa.select(Coincidencia).where(Coincidencia.persona_id == cliente_id))
|
||||
assert fila.entrada_id == "1004" and 60 <= fila.score < 85
|
||||
# Otras listas siguen en 85: el PEP "Rodrigo Villaseñor Ibarra" no aparece para "Ana Perez".
|
||||
assert (
|
||||
sesion.scalar(
|
||||
sa.select(sa.func.count(Coincidencia.id)).where(
|
||||
Coincidencia.persona_id == cliente_id
|
||||
)
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
def test_consulta_beneficiarios_y_terceros_declarados(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
cliente_id = alta(cliente, "Persona", "Limpia")
|
||||
tercero_id = alta(cliente, "Juan Carlos", "Ramirez", "Soto") # entrada ONU 9002
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
tercero = sesion.get(Cliente, tercero_id)
|
||||
from app.schemas.expediente import DeclaracionEntrada
|
||||
|
||||
servicio_expediente.registrar_declaracion(
|
||||
sesion,
|
||||
sesion.get(Cliente, cliente_id),
|
||||
DeclaracionEntrada(por_cuenta_propia=False, tercero_id_externo=tercero.id_externo),
|
||||
)
|
||||
sesion.commit()
|
||||
nombres = servicio.nombres_a_consultar(sesion, sesion.get(Cliente, cliente_id))
|
||||
assert [(n.persona_id, n.rol) for n in nombres] == [
|
||||
(cliente_id, "cliente"),
|
||||
(tercero_id, "tercero_declarado"),
|
||||
]
|
||||
resumen = servicio.screening_cliente(sesion, cliente_id)
|
||||
sesion.commit()
|
||||
assert resumen.consultados == 2 and dict(resumen.por_lista) == {"onu": 1}
|
||||
fila = sesion.scalar(sa.select(Coincidencia).where(Coincidencia.persona_id == tercero_id))
|
||||
assert fila.detalle["consultado_desde_cliente_id"] == cliente_id
|
||||
assert fila.detalle["rol_consultado"] == "tercero_declarado"
|
||||
assert (
|
||||
fila.detalle["programa"] == "Al-Qaida"
|
||||
and fila.detalle["fecha_nacimiento"] == "1980-02-02"
|
||||
)
|
||||
# La ficha del cliente muestra la coincidencia del tercero.
|
||||
pares = servicio.coincidencias_de_cliente(sesion, sesion.get(Cliente, cliente_id))
|
||||
assert [c.persona_id for c, _ in pares] == [tercero_id]
|
||||
entrar(cliente)
|
||||
html = cliente.get(f"/clientes/{cliente_id}").text
|
||||
assert (
|
||||
"Listas y coincidencias" in html and "RAMIREZ SOTO" in html and "tercero declarado" in html
|
||||
)
|
||||
|
||||
|
||||
def _cliente_bajo_con_nombre_en_lista(fabrica: sessionmaker[Session], tmp_path: Path) -> int:
|
||||
"""Un importado con nivel bajo cuyo nombre sintético se planta en una versión nueva de OFAC."""
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
servicio_riesgo.evaluar_cartera(sesion, "inicial")
|
||||
sesion.commit()
|
||||
bajo = sesion.execute(
|
||||
sa.select(EvaluacionRiesgo.cliente_id)
|
||||
.where(EvaluacionRiesgo.nivel == "bajo", EvaluacionRiesgo.motivo == "inicial")
|
||||
.order_by(EvaluacionRiesgo.id)
|
||||
.limit(1)
|
||||
).scalar_one()
|
||||
nombre = servicio_expediente.identificacion_vigente(sesion, bajo).nombre_busqueda
|
||||
archivo = tmp_path / "ofac_sdn_2026-03-01.csv"
|
||||
archivo.write_text(
|
||||
f'7001,"{nombre.upper()}","individual","SDGT"' + ",-0- " * 8 + "\n",
|
||||
encoding="latin-1",
|
||||
)
|
||||
importador.importar_lista(sesion, "ofac_sdn", archivo, usuario="pytest")
|
||||
sesion.commit()
|
||||
return bajo
|
||||
|
||||
|
||||
def test_confirmar_reevalua_y_la_preponderancia_fuerza_alto(
|
||||
fabrica: sessionmaker[Session], tmp_path: Path
|
||||
) -> None:
|
||||
cliente_id = _cliente_bajo_con_nombre_en_lista(fabrica, tmp_path)
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
assert servicio.screening_cliente(sesion, cliente_id).creadas == 1
|
||||
sesion.commit()
|
||||
fila = sesion.scalar(
|
||||
sa.select(Coincidencia).where(
|
||||
Coincidencia.persona_id == cliente_id, Coincidencia.fuente == "screening"
|
||||
)
|
||||
)
|
||||
assert servicio_riesgo.nivel_vigente(sesion, cliente_id) == "bajo"
|
||||
evaluaciones_antes = sesion.scalar(
|
||||
sa.select(sa.func.count(EvaluacionRiesgo.id)).where(
|
||||
EvaluacionRiesgo.cliente_id == cliente_id
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(servicio.ScreeningError):
|
||||
servicio.decidir(sesion, fila.id, "confirmada", "muy corta", "pytest")
|
||||
with pytest.raises(servicio.ScreeningError):
|
||||
servicio.decidir(sesion, fila.id, "otra", JUSTIFICACION, "pytest")
|
||||
|
||||
servicio.decidir(sesion, fila.id, "confirmada", JUSTIFICACION, "pytest")
|
||||
sesion.commit()
|
||||
assert fila.decision == "confirmada" and fila.decidido_por == "pytest"
|
||||
evaluaciones = sesion.scalars(
|
||||
sa.select(EvaluacionRiesgo)
|
||||
.where(EvaluacionRiesgo.cliente_id == cliente_id)
|
||||
.order_by(EvaluacionRiesgo.id)
|
||||
).all()
|
||||
assert len(evaluaciones) > evaluaciones_antes
|
||||
extraordinaria = evaluaciones[evaluaciones_antes]
|
||||
assert extraordinaria.motivo == "extraordinaria"
|
||||
assert extraordinaria.detalle["evento"] == "coincidencia_confirmada:ofac_sdn"
|
||||
assert extraordinaria.nivel == "alto"
|
||||
assert "LISTA_CONFIRMADA" in extraordinaria.detalle["preponderancia"]
|
||||
assert servicio_riesgo.nivel_vigente(sesion, cliente_id) == "alto"
|
||||
acciones = sesion.scalars(
|
||||
sa.select(AuditTrail.accion).where(
|
||||
AuditTrail.entidad == "coincidencia", AuditTrail.entidad_id == fila.id
|
||||
)
|
||||
).all()
|
||||
assert acciones == ["registrar", "decidir:confirmada"]
|
||||
auditoria = sesion.scalar(
|
||||
sa.select(AuditTrail).where(
|
||||
AuditTrail.entidad == "coincidencia",
|
||||
AuditTrail.entidad_id == fila.id,
|
||||
AuditTrail.accion == "decidir:confirmada",
|
||||
)
|
||||
)
|
||||
assert (
|
||||
auditoria.antes["decision"] == "pendiente"
|
||||
and auditoria.despues["decision"] == "confirmada"
|
||||
)
|
||||
assert auditoria.motivo == JUSTIFICACION
|
||||
|
||||
|
||||
def test_descartar_conserva_la_fila(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
|
||||
cliente_id = alta(cliente, "Muhammad", "Zaydan")
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
servicio.screening_cliente(sesion, cliente_id)
|
||||
fila = sesion.scalar(sa.select(Coincidencia).where(Coincidencia.persona_id == cliente_id))
|
||||
servicio.decidir(
|
||||
sesion,
|
||||
fila.id,
|
||||
"descartada",
|
||||
"Fecha de nacimiento y país no coinciden: homónimo.",
|
||||
"pytest",
|
||||
)
|
||||
sesion.commit()
|
||||
assert sesion.get(Coincidencia, fila.id).decision == "descartada"
|
||||
assert (
|
||||
servicio.screening_cliente(sesion, cliente_id).creadas == 0
|
||||
) # tampoco se vuelve a crear
|
||||
assert servicio.pendientes(sesion, tenant_de_sesion(sesion)) == 0
|
||||
assert (
|
||||
servicio_riesgo.ultima_evaluacion(sesion, cliente_id).motivo == "inicial"
|
||||
) # sin reevaluación
|
||||
|
||||
|
||||
def test_declarada_por_chm_no_se_puede_descartar(fabrica: sessionmaker[Session]) -> None:
|
||||
with sesion_con_actor(fabrica) as sesion:
|
||||
chm = sesion.scalar(
|
||||
sa.select(Coincidencia).where(Coincidencia.fuente == "declarada_por_CHM")
|
||||
)
|
||||
assert chm is not None and chm.decision == "confirmada"
|
||||
with pytest.raises(servicio.ScreeningError, match="declarada por CHM"):
|
||||
servicio.decidir(sesion, chm.id, "descartada", JUSTIFICACION, "pytest")
|
||||
assert sesion.get(Coincidencia, chm.id).decision == "confirmada"
|
||||
|
||||
|
||||
# --- Pantallas y roles ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_bandeja_detalle_y_contador(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
|
||||
cliente_id = alta(cliente, "Muhammad", "Zaydan")
|
||||
volver = cliente.post(f"/clientes/{cliente_id}/screening")
|
||||
assert volver.status_code == 303 and "aviso=screening-1-1" in volver.headers["location"]
|
||||
bandeja = cliente.get("/screening")
|
||||
assert bandeja.status_code == 200
|
||||
assert "ZAYDAN, Muhammad" in bandeja.text and "Muhammad Zaydan" in bandeja.text
|
||||
assert 'class="nav__contador"' in bandeja.text and ">1</span>" in bandeja.text
|
||||
filtrada = cliente.get("/screening?lista=onu&decision=pendiente")
|
||||
assert "ZAYDAN" not in filtrada.text
|
||||
por_score = cliente.get("/screening?decision=todas&score_min=99&q=Zaydan")
|
||||
assert "ZAYDAN, Muhammad" in por_score.text
|
||||
assert "ZAYDAN" not in cliente.get("/screening?decision=todas&score_max=50").text
|
||||
with fabrica() as sesion:
|
||||
coincidencia_id = sesion.scalar(
|
||||
sa.select(Coincidencia.id).where(Coincidencia.persona_id == cliente_id)
|
||||
)
|
||||
detalle = cliente.get(f"/screening/{coincidencia_id}")
|
||||
assert detalle.status_code == 200
|
||||
for fragmento in (
|
||||
"MUHAMMAD ZAYDAN",
|
||||
"Coincidió por alias",
|
||||
"ABBAS, Abu",
|
||||
"SDGT",
|
||||
"1948-12-10",
|
||||
"01/01/2026",
|
||||
"100.00",
|
||||
):
|
||||
assert fragmento in detalle.text, fragmento
|
||||
assert cliente.get("/screening/999999").status_code == 404
|
||||
listas = cliente.get("/screening/listas")
|
||||
assert (
|
||||
listas.status_code == 200
|
||||
and "OFAC SDN" in listas.text
|
||||
and "lista de ejemplo" in listas.text
|
||||
)
|
||||
assert "Solo el oficial edita el umbral" in listas.text
|
||||
|
||||
|
||||
def test_decidir_desde_pantalla_y_400_sin_justificacion(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
cliente_id = alta(cliente, "Muhammad", "Zaydan")
|
||||
cliente.post(f"/clientes/{cliente_id}/screening")
|
||||
with fabrica() as sesion:
|
||||
coincidencia_id = sesion.scalar(
|
||||
sa.select(Coincidencia.id).where(Coincidencia.persona_id == cliente_id)
|
||||
)
|
||||
sin = cliente.post(
|
||||
f"/screening/{coincidencia_id}/decidir",
|
||||
data={"decision": "confirmada", "justificacion": "corta"},
|
||||
)
|
||||
assert sin.status_code == 400 and "al menos 20 caracteres" in sin.text
|
||||
ok = cliente.post(
|
||||
f"/screening/{coincidencia_id}/decidir",
|
||||
data={"decision": "confirmada", "justificacion": JUSTIFICACION},
|
||||
)
|
||||
assert ok.status_code == 303 and ok.headers["location"].endswith("aviso=confirmada")
|
||||
detalle = cliente.get(f"/screening/{coincidencia_id}").text
|
||||
assert (
|
||||
"Historial de decisiones" in detalle
|
||||
and "pendiente → <strong>confirmada</strong>" in detalle
|
||||
)
|
||||
with fabrica() as sesion:
|
||||
assert servicio_riesgo.nivel_vigente(sesion, cliente_id) == "alto"
|
||||
chm = sesion.scalar(
|
||||
sa.select(Coincidencia.id).where(Coincidencia.fuente == "declarada_por_CHM")
|
||||
)
|
||||
assert (
|
||||
cliente.post(
|
||||
f"/screening/{chm}/decidir",
|
||||
data={"decision": "descartada", "justificacion": JUSTIFICACION},
|
||||
).status_code
|
||||
== 400
|
||||
)
|
||||
assert "no se puede descartar" in cliente.get(f"/screening/{chm}").text
|
||||
|
||||
|
||||
def test_umbral_solo_oficial_y_queda_en_audit_trail(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
with fabrica() as sesion:
|
||||
lista_id = sesion.scalar(sa.select(Lista.id).where(Lista.nombre == "sat_69b"))
|
||||
datos = {
|
||||
"umbral": "92.5",
|
||||
"justificacion": "Razones sociales largas: subir el umbral para evitar falsos positivos.",
|
||||
}
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert cliente.post(f"/screening/listas/{lista_id}/umbral", data=datos).status_code == 403
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
assert cliente.post(f"/screening/listas/{lista_id}/umbral", data=datos).status_code == 403
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
assert "Guardar umbral" in cliente.get("/screening/listas").text
|
||||
fuera = cliente.post(f"/screening/listas/{lista_id}/umbral", data={**datos, "umbral": "20"})
|
||||
assert fuera.status_code == 303 and "error=" in fuera.headers["location"]
|
||||
ok = cliente.post(f"/screening/listas/{lista_id}/umbral", data=datos)
|
||||
assert ok.status_code == 303 and f"aviso=umbral-{lista_id}" in ok.headers["location"]
|
||||
with fabrica() as sesion:
|
||||
assert sesion.get(Lista, lista_id).umbral == Decimal("92.50")
|
||||
fila = sesion.scalar(
|
||||
sa.select(AuditTrail).where(
|
||||
AuditTrail.entidad == "lista",
|
||||
AuditTrail.entidad_id == lista_id,
|
||||
AuditTrail.accion == "cambiar_umbral",
|
||||
)
|
||||
)
|
||||
assert (
|
||||
fila.usuario == "oficial"
|
||||
and fila.antes == {"umbral": "85.00"}
|
||||
and fila.despues == {"umbral": "92.50"}
|
||||
)
|
||||
assert fila.motivo == datos["justificacion"]
|
||||
assert cliente.post("/screening/listas/999999/umbral", data=datos).status_code == 404
|
||||
|
||||
|
||||
def test_el_auditor_solo_lee(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
|
||||
cliente_id = alta(cliente, "Muhammad", "Zaydan")
|
||||
cliente.post(f"/clientes/{cliente_id}/screening")
|
||||
with fabrica() as sesion:
|
||||
coincidencia_id = sesion.scalar(
|
||||
sa.select(Coincidencia.id).where(Coincidencia.persona_id == cliente_id)
|
||||
)
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
assert cliente.get("/screening").status_code == 200
|
||||
detalle = cliente.get(f"/screening/{coincidencia_id}")
|
||||
assert detalle.status_code == 200 and "solo consulta" in detalle.text
|
||||
assert (
|
||||
cliente.post(
|
||||
f"/screening/{coincidencia_id}/decidir",
|
||||
data={"decision": "confirmada", "justificacion": JUSTIFICACION},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert cliente.post(f"/clientes/{cliente_id}/screening").status_code == 403
|
||||
assert cliente.get("/screening/listas").status_code == 200
|
||||
Reference in new issue
Block a user