From 841b364e7db23076c6433b1be444d7cbedfd0140 Mon Sep 17 00:00:00 2001 From: Fernando Davila Date: Tue, 6 Oct 2026 16:47:32 -0600 Subject: [PATCH] test(rules): paridad de alertas contra el fixture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - test_rules.py: bordes por regla (A-01 en el umbral, C-03 2 vs 3 cambios y hueco de 2 vs 3 meses y 89 vs 90 días, B-06 con CUENTA, D-04 solo pagos), ejecutar(), vencimiento(), firma() - test_paridad_alertas.py: las 12 reglas contra las columnas-oráculo del fixture sin diferencias, totales de la fila 2, idempotencia, versión en cada alerta - test_cartera.py y test_clientes.py: roles, filtros, 403, alerta manual con regla y versión, < 1 s con 1,023 clientes - tests/_oraculo_alertas.py: lector provisional hasta que llegue tests/fixtures/oraculo.py de la Pieza C --- tests/_oraculo_alertas.py | 158 +++++++++++++++++ tests/test_cartera.py | 170 +++++++++++++++++++ tests/test_clientes.py | 209 +++++++++++++++++++++++ tests/test_paridad_alertas.py | 151 +++++++++++++++++ tests/test_rules.py | 311 ++++++++++++++++++++++++++++++++++ 5 files changed, 999 insertions(+) create mode 100644 tests/_oraculo_alertas.py create mode 100644 tests/test_cartera.py create mode 100644 tests/test_clientes.py create mode 100644 tests/test_paridad_alertas.py create mode 100644 tests/test_rules.py diff --git a/tests/_oraculo_alertas.py b/tests/_oraculo_alertas.py new file mode 100644 index 0000000..2646103 --- /dev/null +++ b/tests/_oraculo_alertas.py @@ -0,0 +1,158 @@ +"""Lector mínimo del oráculo de alertas del fixture `esquema_mini.xlsx` (Pieza D). + +Provisional: se borra cuando llegue `tests/fixtures/oraculo.py` de la Pieza C, cuya estructura +(`Oraculo`, `OraculoCliente`, `OraculoCredito`, `OraculoTransaccion`, `ids_en_base`) se imita aquí +en lo que las alertas necesitan. + +Columnas-oráculo: Clientes AP–BB (alertas por cliente), Cartera AI–AK (por crédito) y +Transacciones AA–AC (por transacción). Valores: "ALERTA" o vacío. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import Decimal +from functools import lru_cache +from pathlib import Path +from typing import Any + +from openpyxl import load_workbook +from openpyxl.utils import column_index_from_string + +FIXTURE = Path(__file__).parent / "fixtures" / "esquema_mini.xlsx" +FILA_ENCABEZADOS = 3 +COLUMNAS_ALERTAS_CLIENTE = { + "AP": "B-01", + "AQ": "B-02", + "AR": "B-03", + "AS": "B-04", + "AT": "B-06", + "AU": "C-01", + "AV": "C-02", + "AW": "D-01", + "AX": "D-02", + "AY": "D-03", + "AZ": "D-05", + "BA": "E-01", + "BB": "E-02", +} +COLUMNAS_ALERTAS_CREDITO = {"AI": "A-01", "AJ": "A-02", "AK": "B-08"} +COLUMNAS_ALERTAS_TRANSACCION = {"AA": "B-06", "AB": "C-03", "AC": "D-04"} + + +@dataclass(frozen=True) +class OraculoCliente: + id_fixture: str + fila: int + nivel: str + alertas: frozenset[str] + + +@dataclass(frozen=True) +class OraculoCredito: + id_credito: str + id_cliente_fixture: str + fila: int + alertas: frozenset[str] + + +@dataclass(frozen=True) +class OraculoTransaccion: + id_credito: str + id_cliente_fixture: str + fila: int + fecha_pago: date + total: Decimal + pago_id: str + alertas: frozenset[str] + + +@dataclass(frozen=True) +class Oraculo: + uma: Decimal + fecha_fin: date + clientes: dict[str, OraculoCliente] = field(default_factory=dict) + creditos: dict[str, OraculoCredito] = field(default_factory=dict) + transacciones: list[OraculoTransaccion] = field(default_factory=list) + + +def _celda(fila: tuple, columna: str) -> Any: + i = column_index_from_string(columna) - 1 + return fila[i] if i < len(fila) else None + + +def _fecha(valor: Any) -> date: + return valor.date() if isinstance(valor, datetime) else valor + + +def _alertas(fila: tuple, columnas: dict[str, str]) -> frozenset[str]: + return frozenset( + regla + for columna, regla in columnas.items() + if str(_celda(fila, columna) or "").strip().upper() == "ALERTA" + ) + + +def _datos(ws) -> list[tuple[int, tuple]]: + return [ + (n, fila) + for n, fila in enumerate(ws.iter_rows(values_only=True), start=1) + if n > FILA_ENCABEZADOS and fila and fila[0] not in (None, "") + ] + + +@lru_cache +def leer_oraculo(ruta: Path = FIXTURE) -> Oraculo: + wb = load_workbook(ruta, read_only=True, data_only=True) + try: + parametros = { + str(f[1]).strip(): f[2] + for f in wb["Parámetros"].iter_rows(values_only=True) + if f and len(f) > 2 and f[1] + } + oraculo = Oraculo( + uma=Decimal(str(parametros["UMA"])), fecha_fin=_fecha(parametros["FECHA FIN"]) + ) + for n, fila in _datos(wb["Clientes"]): + id_ = str(_celda(fila, "A")).strip() + oraculo.clientes[id_] = OraculoCliente( + id_fixture=id_, + fila=n, + nivel=str(_celda(fila, "AN")).strip().lower(), + alertas=_alertas(fila, COLUMNAS_ALERTAS_CLIENTE), + ) + for n, fila in _datos(wb["Cartera"]): + id_credito = str(_celda(fila, "A")).strip() + oraculo.creditos[id_credito] = OraculoCredito( + id_credito=id_credito, + id_cliente_fixture=str(_celda(fila, "B")).strip(), + fila=n, + alertas=_alertas(fila, COLUMNAS_ALERTAS_CREDITO), + ) + for n, fila in _datos(wb["Transacciones"]): + oraculo.transacciones.append( + OraculoTransaccion( + id_credito=str(_celda(fila, "A")).strip(), + id_cliente_fixture=str(_celda(fila, "B")).strip(), + fila=n, + fecha_pago=_fecha(_celda(fila, "C")), + total=Decimal(str(_celda(fila, "O"))), + pago_id=str(_celda(fila, "P")).strip(), + alertas=_alertas(fila, COLUMNAS_ALERTAS_TRANSACCION), + ) + ) + return oraculo + finally: + wb.close() + + +def ids_en_base(sal: str, ruta: Path = FIXTURE) -> dict[str, str]: + """id del cliente en el fixture → `cliente.id_externo` tras importar con esa sal.""" + from app.importers.anonymize import Anonimizador + + anon = Anonimizador(sal) + try: + return {id_: anon.id_sintetico(id_) for id_ in leer_oraculo(ruta).clientes} + finally: + anon.descartar() diff --git a/tests/test_cartera.py b/tests/test_cartera.py new file mode 100644 index 0000000..e74ffbc --- /dev/null +++ b/tests/test_cartera.py @@ -0,0 +1,170 @@ +"""Pantalla `/cartera`: filtros, conteos, paginación, roles y tiempo de respuesta.""" + +from __future__ import annotations + +import time +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.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 Base, Cliente, EvaluacionRiesgo, ModeloRiesgo, Tenant +from app.models.usuario import Rol +from app.services.alertas import ejecutar_reglas +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]: + """Base en memoria con usuarios demo, el fixture importado y las reglas ejecutadas.""" + 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-cartera") + ejecutar_reglas(sesion, 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 entrar(cliente: TestClient, rol: Rol) -> None: + assert ( + cliente.post( + "/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]} + ).status_code + == 303 + ) + + +def evaluar(fabrica: sessionmaker[Session], cliente_id: int, nivel: str) -> None: + """Simula una evaluación de la Pieza C: una fila en `evaluacion_riesgo` (A escribe, B lee).""" + with fabrica() as sesion: + tenant = sesion.scalar(sa.select(Tenant)) + modelo = sesion.scalar(sa.select(ModeloRiesgo)) + sesion.add( + EvaluacionRiesgo( + tenant_id=tenant.id, + created_by="pytest", + cliente_id=cliente_id, + modelo_id=modelo.id, + score_inherente=Decimal("30"), + score_residual=Decimal("30"), + nivel=nivel, + detalle=[], + motivo="inicial", + ) + ) + sesion.commit() + + +def test_sin_sesion_redirige_al_login(cliente: TestClient) -> None: + respuesta = cliente.get("/cartera") + assert respuesta.status_code == 303 and respuesta.headers["location"] == "/login" + + +@pytest.mark.parametrize("rol", list(Rol)) +def test_los_tres_roles_ven_la_cartera(cliente: TestClient, rol: Rol) -> None: + entrar(cliente, rol) + respuesta = cliente.get("/cartera") + assert respuesta.status_code == 200 + assert "30 clientes" in respuesta.text + assert respuesta.text.count('href="/clientes/') == 30 + assert "Sin evaluar" in respuesta.text + + +def test_filtro_por_nivel_usa_la_ultima_evaluacion(cliente: TestClient, fabrica) -> None: + with fabrica() as sesion: + ids = sesion.scalars(sa.select(Cliente.id).order_by(Cliente.id)).all() + evaluar(fabrica, ids[0], "bajo") + evaluar(fabrica, ids[0], "alto") # la última manda + evaluar(fabrica, ids[1], "medio") + entrar(cliente, Rol.ANALISTA) + + alto = cliente.get("/cartera?nivel=alto") + assert alto.status_code == 200 + assert alto.text.count('href="/clientes/') == 1 and f'href="/clientes/{ids[0]}"' in alto.text + assert cliente.get("/cartera?nivel=bajo").text.count('href="/clientes/') == 0 + assert cliente.get("/cartera?nivel=sin_evaluar").text.count('href="/clientes/') == 28 + assert "1 coincidencias" in alto.text + + +def test_busqueda_por_id_externo_y_filtro_vacio(cliente: TestClient, fabrica) -> None: + with fabrica() as sesion: + primero = sesion.scalar(sa.select(Cliente).order_by(Cliente.id)) + entrar(cliente, Rol.OFICIAL) + respuesta = cliente.get(f"/cartera?q={primero.id_externo[:8]}&nivel=&estado_relacion=") + assert respuesta.status_code == 200 + assert primero.id_externo in respuesta.text + assert respuesta.text.count('href="/clientes/') >= 1 + assert cliente.get("/cartera?q=no-existe-zzz").text.count('href="/clientes/') == 0 + assert "Ningún cliente cumple los filtros" in cliente.get("/cartera?q=no-existe-zzz").text + + +def test_conteo_de_alertas_abiertas(cliente: TestClient, fabrica) -> None: + entrar(cliente, Rol.AUDITOR) + respuesta = cliente.get("/cartera") + assert "124 alertas abiertas" in respuesta.text + + +def test_pagina_fuera_de_rango_y_parametros_invalidos(cliente: TestClient) -> None: + entrar(cliente, Rol.ANALISTA) + assert cliente.get("/cartera?pagina=99").status_code == 200 + assert cliente.get("/cartera?pagina=0").status_code == 422 + assert cliente.get("/cartera?nivel=altisimo").status_code == 422 + + +def test_responde_en_menos_de_un_segundo_con_1023_clientes(cliente: TestClient, fabrica) -> None: + with fabrica() as sesion: + tenant = sesion.scalar(sa.select(Tenant)) + existentes = sesion.scalar(sa.select(sa.func.count(Cliente.id))) + sesion.execute( + sa.insert(Cliente), + [ + { + "tenant_id": tenant.id, + "created_by": "pytest", + "id_externo": f"sintetico{i:06d}", + "tipo_persona": "fisica", + "fecha_nacimiento": date(1980, 1, 1), + "estado": "Jalisco", + "pais": "México", + "estado_relacion": "activa", + } + for i in range(1023 - existentes) + ], + ) + sesion.commit() + entrar(cliente, Rol.ANALISTA) + inicio = time.perf_counter() + respuesta = cliente.get("/cartera") + duracion = time.perf_counter() - inicio + assert respuesta.status_code == 200 + assert "1023 clientes" in respuesta.text + assert respuesta.text.count('href="/clientes/') == 50 # paginada + assert duracion < 1.0, f"{duracion:.2f}s" + assert "Página 1 de 21" in respuesta.text + assert cliente.get("/cartera?estado_relacion=activa").text.count('href="/clientes/') == 50 diff --git a/tests/test_clientes.py b/tests/test_clientes.py new file mode 100644 index 0000000..65d0216 --- /dev/null +++ b/tests/test_clientes.py @@ -0,0 +1,209 @@ +"""Ficha mínima `/clientes/` y alta de alertas manuales (B-05, B-07, E-03).""" + +from __future__ import annotations + +from collections.abc import Iterator +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, Cliente, Pep, ReglaAlerta +from app.models.usuario import Rol +from app.services import alertas as servicio_alertas +from app.services import riesgo as servicio_riesgo +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", +} +DESCRIPCION = "El cliente intentó un enganche en efectivo y desistió al pedir el origen." + + +@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-clientes") + servicio_alertas.ejecutar_reglas(sesion, 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 + + +@pytest.fixture +def cliente_pep(fabrica: sessionmaker[Session]) -> Cliente: + with fabrica() as sesion: + pep = sesion.scalar(sa.select(Pep).where(Pep.tipo == "nacional")) + return sesion.get(Cliente, pep.persona_id) + + +def entrar(cliente: TestClient, rol: Rol) -> None: + assert ( + cliente.post( + "/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]} + ).status_code + == 303 + ) + + +@pytest.mark.parametrize("rol", list(Rol)) +def test_la_ficha_se_ve_con_los_tres_roles( + cliente: TestClient, cliente_pep: Cliente, rol: Rol +) -> None: + entrar(cliente, rol) + respuesta = cliente.get(f"/clientes/{cliente_pep.id}") + assert respuesta.status_code == 200 + html = respuesta.text + assert cliente_pep.id_externo in html + assert "PEP nacional" in html and "D-02" in html # bandera y alerta producida por ella + assert f'href="/riesgo/{cliente_pep.id}"' in html and "Sin evaluar" in html + assert "Expediente completo" in html and "fase 4" in html + assert "Titular origen" in html # transacciones recientes por crédito + if rol is Rol.AUDITOR: + assert "Tu rol (auditor) solo consulta" in html + else: + assert 'action="/clientes/' in html and "B-05" in html and "E-03" in html + + +def test_cliente_inexistente_da_404(cliente: TestClient) -> None: + entrar(cliente, Rol.ANALISTA) + assert cliente.get("/clientes/999999").status_code == 404 + + +def test_usa_nivel_vigente_de_la_pieza_c_cuando_existe( + cliente: TestClient, cliente_pep: Cliente, monkeypatch: pytest.MonkeyPatch +) -> None: + llamadas = [] + + def nivel_vigente(session, cliente_id): + llamadas.append(cliente_id) + return "alto" + + monkeypatch.setattr(servicio_riesgo, "nivel_vigente", nivel_vigente, raising=False) + entrar(cliente, Rol.OFICIAL) + html = cliente.get(f"/clientes/{cliente_pep.id}").text + assert llamadas == [cliente_pep.id] + assert 'data-nivel="alto"' in html and "Sin evaluar" not in html + + +@pytest.mark.parametrize("rol", [Rol.ANALISTA, Rol.OFICIAL]) +def test_alerta_manual_crea_fila_con_regla_y_version( + cliente: TestClient, fabrica, cliente_pep: Cliente, rol: Rol +) -> None: + entrar(cliente, rol) + respuesta = cliente.post( + f"/clientes/{cliente_pep.id}/alertas-manuales", + data={"regla_clave": "B-05", "descripcion": DESCRIPCION}, + ) + assert respuesta.status_code == 303 + assert respuesta.headers["location"].startswith(f"/clientes/{cliente_pep.id}?aviso=alerta-") + + with fabrica() as sesion: + regla = sesion.scalar(sa.select(ReglaAlerta).where(ReglaAlerta.clave == "B-05")) + alerta = sesion.scalar( + sa.select(Alerta).where( + Alerta.cliente_id == cliente_pep.id, Alerta.regla_id == regla.id + ) + ) + assert alerta is not None + assert alerta.evidencia["manual"] is True and alerta.evidencia["version"] == "v2" + assert alerta.evidencia["descripcion"] == DESCRIPCION + assert alerta.estado == "nueva" and alerta.responsable == rol.value + assert alerta.nivel == regla.nivel == "critica" + assert alerta.vence_el is not None # 24h + auditoria = sesion.scalar( + sa.select(AuditTrail).where( + AuditTrail.entidad == "alerta", + AuditTrail.entidad_id == alerta.id, + AuditTrail.accion == "crear_manual", + ) + ) + assert auditoria is not None and auditoria.usuario == rol.value + html = cliente.get(respuesta.headers["location"]).text + assert "Alerta manual registrada" in html and "B-05" in html + + +def test_auditor_no_puede_levantar_alerta_manual(cliente: TestClient, fabrica, cliente_pep) -> None: + entrar(cliente, Rol.AUDITOR) + respuesta = cliente.post( + f"/clientes/{cliente_pep.id}/alertas-manuales", + data={"regla_clave": "B-05", "descripcion": DESCRIPCION}, + ) + assert respuesta.status_code == 403 + with fabrica() as sesion: + assert ( + sesion.scalar( + sa.select(sa.func.count(Alerta.id)).where( + Alerta.evidencia["manual"].as_boolean().is_(True) + ) + ) + == 0 + ) + + +def test_sin_sesion_no_se_puede_levantar(cliente: TestClient, cliente_pep) -> None: + respuesta = cliente.post( + f"/clientes/{cliente_pep.id}/alertas-manuales", + data={"regla_clave": "B-05", "descripcion": DESCRIPCION}, + ) + assert respuesta.status_code == 303 and respuesta.headers["location"] == "/login" + + +@pytest.mark.parametrize( + ("regla", "descripcion"), + [("A-01", DESCRIPCION), ("B-05", "corto"), ("Z-99", DESCRIPCION)], +) +def test_regla_no_manual_o_descripcion_corta_no_crea_nada( + cliente: TestClient, fabrica, cliente_pep, regla: str, descripcion: str +) -> None: + entrar(cliente, Rol.ANALISTA) + with fabrica() as sesion: + antes = sesion.scalar(sa.select(sa.func.count(Alerta.id))) + respuesta = cliente.post( + f"/clientes/{cliente_pep.id}/alertas-manuales", + data={"regla_clave": regla, "descripcion": descripcion}, + ) + assert respuesta.status_code == 400 + assert "No se puede levantar" in respuesta.text or "Elige una regla manual" in respuesta.text + with fabrica() as sesion: + assert sesion.scalar(sa.select(sa.func.count(Alerta.id))) == antes + + +def test_cambiar_estado_audita_y_exige_motivo_al_cerrar(fabrica) -> None: + with fabrica() as sesion: + alerta = sesion.scalar(sa.select(Alerta).order_by(Alerta.id)) + servicio_alertas.cambiar_estado(sesion, alerta.id, "en_revision", usuario="oficial") + with pytest.raises(servicio_alertas.TransicionInvalidaError): + servicio_alertas.cambiar_estado(sesion, alerta.id, "cerrada", usuario="oficial") + servicio_alertas.cambiar_estado( + sesion, alerta.id, "cerrada", motivo="Falso positivo documentado", usuario="oficial" + ) + with pytest.raises(servicio_alertas.TransicionInvalidaError): + servicio_alertas.cambiar_estado(sesion, alerta.id, "nueva", usuario="oficial") + sesion.commit() + assert alerta.estado == "cerrada" and alerta.responsable == "oficial" + acciones = sesion.scalars( + sa.select(AuditTrail.accion) + .where(AuditTrail.entidad == "alerta", AuditTrail.entidad_id == alerta.id) + .order_by(AuditTrail.id) + ).all() + assert acciones == ["crear", "estado:en_revision", "estado:cerrada"] diff --git a/tests/test_paridad_alertas.py b/tests/test_paridad_alertas.py new file mode 100644 index 0000000..82239ce --- /dev/null +++ b/tests/test_paridad_alertas.py @@ -0,0 +1,151 @@ +"""Paridad de alertas: las 12 reglas sin dependencias contra las columnas-oráculo del fixture. + +Para los 30 clientes del fixture se compara, regla por regla, el conjunto de alertas que produce +el motor con lo que calculó el Excel de CHM. Cualquier diferencia es un fallo salvo las listadas en +`DIFERENCIAS_ESPERADAS`, con motivo. También: idempotencia y versión de regla en cada alerta. +""" + +from __future__ import annotations + +from collections import defaultdict +from pathlib import Path + +import pytest +import sqlalchemy as sa + +from app.db import crear_engine, crear_session_factory +from app.importers.chm_schema import importar_esquema +from app.models import Alerta, Base, Cliente, Credito, ReglaAlerta, Transaccion +from app.services.alertas import ejecutar_reglas +from tests._oraculo_alertas import ids_en_base, leer_oraculo + +FIXTURE = Path(__file__).parent / "fixtures" / "esquema_mini.xlsx" +SAL = "sal-paridad" + +REGLAS_CLIENTE = ("B-01", "B-04", "D-02", "D-03", "D-05", "E-01", "E-02") +REGLAS_CREDITO = ("A-01", "B-08") +REGLAS_TRANSACCION = ("B-06", "C-03", "D-04") +REGLAS_PR1 = REGLAS_CLIENTE + REGLAS_CREDITO + REGLAS_TRANSACCION + +# Regla → {identificador del oráculo: motivo}. Vacío: el motor reproduce el Excel exactamente. +# Nota: la columna AT de Clientes ("B-06" por cliente) marca a quien pagó el ENGANCHE con TERCERO; +# el motor evalúa B-06 por transacción (columna AA de Transacciones, 929 hits en el esquema), +# que es la que se compara aquí. AT no es un oráculo de esta regla. +DIFERENCIAS_ESPERADAS: dict[str, dict[str, str]] = {} + + +@pytest.fixture(scope="module") +def sesion_con_alertas(): + engine = crear_engine("sqlite://") + Base.metadata.create_all(engine) + fabrica = crear_session_factory(engine) + with fabrica() as sesion: + importar_esquema(sesion, FIXTURE, "pytest", sal=SAL) + resumen = ejecutar_reglas(sesion, usuario="pytest") + sesion.commit() + yield sesion, resumen + + +def _alertas_por_regla(sesion) -> dict[str, list[Alerta]]: + filas = sesion.execute( + sa.select(Alerta, ReglaAlerta.clave).join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id) + ) + por_regla: dict[str, list[Alerta]] = defaultdict(list) + for alerta, clave in filas: + por_regla[clave].append(alerta) + return por_regla + + +def _esperado_vs_obtenido(sesion, regla: str) -> tuple[set[str], set[str]]: + oraculo = leer_oraculo() + traduccion = ids_en_base(SAL) # id fixture → id_externo en base + clientes = {c.id: c.id_externo for c in sesion.scalars(sa.select(Cliente))} + creditos = {c.id: c.id_externo for c in sesion.scalars(sa.select(Credito))} + transacciones = { + t.id: f"{creditos[t.credito_id]}#{t.pago_id}" + for t in sesion.scalars(sa.select(Transaccion)) + } + obtenidas = _alertas_por_regla(sesion).get(regla, []) + + if regla in REGLAS_CLIENTE: + esperado = { + traduccion[c.id_fixture] for c in oraculo.clientes.values() if regla in c.alertas + } + obtenido = {clientes[a.cliente_id] for a in obtenidas} + elif regla in REGLAS_CREDITO: + esperado = {c.id_credito for c in oraculo.creditos.values() if regla in c.alertas} + obtenido = {creditos[a.credito_id] for a in obtenidas} + else: + esperado = { + f"{t.id_credito}#{t.pago_id}" for t in oraculo.transacciones if regla in t.alertas + } + obtenido = {transacciones[a.evidencia["transaccion_id"]] for a in obtenidas} + return esperado, obtenido + + +@pytest.mark.parametrize("regla", REGLAS_PR1) +def test_paridad_por_regla(sesion_con_alertas, regla: str) -> None: + sesion, _ = sesion_con_alertas + esperado, obtenido = _esperado_vs_obtenido(sesion, regla) + toleradas = set(DIFERENCIAS_ESPERADAS.get(regla, {})) + faltan = esperado - obtenido - toleradas + sobran = obtenido - esperado - toleradas + assert not faltan and not sobran, f"{regla}: faltan {sorted(faltan)}; sobran {sorted(sobran)}" + # una diferencia tolerada que ya no ocurre debe salir de la lista + assert toleradas <= (esperado ^ obtenido), f"{regla}: diferencias esperadas obsoletas" + + +def test_los_totales_coinciden_con_la_fila_2_del_fixture(sesion_con_alertas) -> None: + sesion, resumen = sesion_con_alertas + por_regla = _alertas_por_regla(sesion) + oraculo = leer_oraculo() + totales = { + **{r: sum(1 for c in oraculo.clientes.values() if r in c.alertas) for r in REGLAS_CLIENTE}, + **{r: sum(1 for c in oraculo.creditos.values() if r in c.alertas) for r in REGLAS_CREDITO}, + **{r: sum(1 for t in oraculo.transacciones if r in t.alertas) for r in REGLAS_TRANSACCION}, + } + assert {r: len(por_regla.get(r, [])) for r in REGLAS_PR1} == totales + assert {r: resumen.por_regla[r].creadas for r in REGLAS_PR1} == totales + + +def test_ejecutar_dos_veces_es_idempotente(sesion_con_alertas) -> None: + sesion, primera = sesion_con_alertas + antes = sesion.scalar(sa.select(sa.func.count(Alerta.id))) + segunda = ejecutar_reglas(sesion, usuario="pytest") + sesion.commit() + assert segunda.creadas == 0 + assert segunda.existentes == primera.creadas + assert sesion.scalar(sa.select(sa.func.count(Alerta.id))) == antes + + +def test_reglas_manuales_y_pendientes_quedan_omitidas(sesion_con_alertas) -> None: + _, resumen = sesion_con_alertas + assert {c.clave for c in resumen.por_regla.values() if c.omitida == "manual"} == { + "B-05", + "B-07", + "E-03", + } + assert {c.clave for c in resumen.por_regla.values() if c.omitida == "pendiente_agregados"} == { + "A-02", + "B-02", + "B-03", + "C-01", + "C-02", + "D-01", + } + + +def test_cada_alerta_guarda_regla_version_nivel_y_evidencia(sesion_con_alertas) -> None: + sesion, _ = sesion_con_alertas + for alerta, regla in sesion.execute( + sa.select(Alerta, ReglaAlerta).join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id) + ): + assert alerta.evidencia["regla"] == regla.clave + assert alerta.evidencia["version"] == regla.version == "v2" + assert alerta.nivel == regla.nivel and alerta.plazo_aviso == regla.plazo_aviso + assert alerta.estado == "nueva" + if regla.clave == "A-01": + assert set(alerta.evidencia) >= {"monto", "umbral", "uma", "factor_uma"} + assert alerta.vence_el is not None and alerta.vence_el.day == 17 + if regla.clave in REGLAS_TRANSACCION: + assert alerta.transaccion_ids and alerta.credito_id is not None diff --git a/tests/test_rules.py b/tests/test_rules.py new file mode 100644 index 0000000..466117c --- /dev/null +++ b/tests/test_rules.py @@ -0,0 +1,311 @@ +"""Motor de reglas puro: bordes por regla sobre contextos construidos a mano (sin base de datos).""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.engine import rules +from app.engine.rules import ( + AlertaCandidata, + ClienteCtx, + Contexto, + CreditoCtx, + ReglaVigente, + TransaccionCtx, +) +from app.engine.rules_catalog import MANUALES, PENDIENTES_AGREGADOS, REGISTRO + +UMA = Decimal("117.31") +CORTE = date(2026, 8, 31) + + +def contexto(clientes=(), creditos=(), transacciones=(), catalogos=None) -> Contexto: + return Contexto( + uma=UMA, + ventana_meses=6, + fecha_corte=CORTE, + clientes={c.id: c for c in clientes}, + creditos={c.id: c for c in creditos}, + transacciones=list(transacciones), + catalogos=catalogos or {}, + ) + + +def cliente(id_=1, **kw) -> ClienteCtx: + base = {"id_externo": f"c{id_}", "pais": "México", "ingresos_mensuales_netos": Decimal("20000")} + return ClienteCtx(id=id_, **(base | kw)) + + +def credito(id_=10, cliente_id=1, monto="100000", **kw) -> CreditoCtx: + base = {"id_externo": f"k{id_}", "fecha_disposicion": date(2026, 3, 10)} + return CreditoCtx(id=id_, cliente_id=cliente_id, monto=Decimal(monto), **(base | kw)) + + +def pago(id_, fecha, metodo="TRANSFERENCIA", tipo="PAGO", total="5000", **kw) -> TransaccionCtx: + base = {"credito_id": 10, "cliente_id": 1, "titular_origen": "CLIENTE"} + return TransaccionCtx( + id=id_, fecha_pago=fecha, total=Decimal(total), tipo=tipo, metodo=metodo, **(base | kw) + ) + + +def correr(clave: str, ctx: Contexto, **parametros) -> list[AlertaCandidata]: + return list(REGISTRO[clave](ctx, parametros)) + + +# --- Catálogo ------------------------------------------------------------------------------- + + +def test_catalogo_cubre_las_12_reglas_sin_dependencias_y_separa_el_resto() -> None: + assert set(REGISTRO) == { + "A-01", "B-01", "B-04", "B-06", "B-08", "C-03", + "D-02", "D-03", "D-04", "D-05", "E-01", "E-02", + } # fmt: skip + assert PENDIENTES_AGREGADOS == {"A-02", "B-02", "B-03", "C-01", "C-02", "D-01"} + assert MANUALES == {"B-05", "B-07", "E-03"} + assert not (set(REGISTRO) & PENDIENTES_AGREGADOS) and not (set(REGISTRO) & MANUALES) + + +# --- A-01 ----------------------------------------------------------------------------------- + + +def test_a01_exactamente_en_el_umbral_dispara_y_un_centavo_menos_no() -> None: + umbral = UMA * 1605 # 188,282.55 + ctx = contexto( + [cliente()], + [credito(10, monto=str(umbral)), credito(11, monto=str(umbral - Decimal("0.01")))], + ) + alertas = correr("A-01", ctx, factor_uma=1605) + assert [a.credito_id for a in alertas] == [10] + assert alertas[0].evidencia["umbral"] == umbral and alertas[0].evidencia["uma"] == UMA + assert alertas[0].fecha_evento == date(2026, 3, 10) + + +def test_a01_el_factor_es_parametro() -> None: + ctx = contexto([cliente()], [credito(10, monto="120000")]) + assert correr("A-01", ctx, factor_uma=1605) == [] + assert len(correr("A-01", ctx, factor_uma=1000)) == 1 + + +# --- B-01 / B-04 ---------------------------------------------------------------------------- + + +def test_b01_y_b04_banderas_del_cliente() -> None: + ctx = contexto( + [ + cliente(1, comprobante_ingresos=False, inconsistencia_documentos=True), + cliente(2, comprobante_ingresos=True, inconsistencia_documentos=False), + cliente(3, comprobante_ingresos=None, inconsistencia_documentos=None), + ] + ) + assert [a.cliente_id for a in correr("B-01", ctx)] == [1] + assert [a.cliente_id for a in correr("B-04", ctx)] == [1] + + +# --- B-06 ----------------------------------------------------------------------------------- + + +def test_b06_tercero_dispara_y_cuenta_no() -> None: + ctx = contexto( + [cliente()], + [credito()], + [ + pago(1, date(2026, 1, 5), titular_origen="TERCERO"), + pago(2, date(2026, 2, 5), titular_origen="CUENTA"), + pago(3, date(2026, 3, 5), titular_origen="CLIENTE"), + ], + ) + alertas = correr("B-06", ctx, titulares_que_disparan=["TERCERO"]) + assert [a.transaccion_ids for a in alertas] == [(1,)] + assert alertas[0].evidencia["titular_origen"] == "TERCERO" + # si CHM decide que CUENTA también dispara, es un cambio de parámetro + assert len(correr("B-06", ctx, titulares_que_disparan=["TERCERO", "CUENTA"])) == 2 + + +# --- B-08 ----------------------------------------------------------------------------------- + + +def test_b08_monto_mayor_que_factor_por_ingreso_anual() -> None: + umbral = Decimal("1.5") * Decimal("20000") * 12 # 360,000 + ctx = contexto( + [cliente()], [credito(10, monto=str(umbral)), credito(11, monto=str(umbral + 1))] + ) + alertas = correr("B-08", ctx, factor_ingreso_anual=1.5, meses_anualizacion=12) + assert [a.credito_id for a in alertas] == [11] + assert alertas[0].evidencia["umbral"] == umbral + + +def test_b08_sin_ingresos_no_dispara() -> None: + ctx = contexto([cliente(ingresos_mensuales_netos=None)], [credito(10, monto="9999999")]) + assert correr("B-08", ctx) == [] + + +# --- C-03 ----------------------------------------------------------------------------------- + + +def _pagos_con_metodos(metodos: list[str], inicio=date(2026, 1, 15)) -> list[TransaccionCtx]: + pagos = [pago(0, date(2025, 12, 15), metodo=metodos[0], tipo="ENGANCHE")] + for i, metodo in enumerate(metodos[1:], start=1): + mes = (inicio.month - 1 + i - 1) % 12 + 1 + anio = inicio.year + (inicio.month - 1 + i - 1) // 12 + pagos.append(pago(i, date(anio, mes, 15), metodo=metodo)) + return pagos + + +def test_c03_tres_cambios_en_tres_pagos_dispara_y_dos_no() -> None: + # enganche T; pagos: E (cambio), T (cambio), E (cambio) → 3 cambios en 3 pagos + tres = contexto([cliente()], [credito()], _pagos_con_metodos(["T", "E", "T", "E"])) + alertas = correr("C-03", tres, cambios_metodo=3, pagos_consecutivos=3, hueco_meses=3) + assert len(alertas) == 1 + assert alertas[0].evidencia["motivo"] == "cambios_metodo" + assert alertas[0].evidencia["transaccion_id"] == 3 + assert alertas[0].transaccion_ids == (1, 2, 3) + + # enganche T; pagos: E (cambio), E, T (cambio) → 2 cambios en 3 pagos + dos = contexto([cliente()], [credito()], _pagos_con_metodos(["T", "E", "E", "T"])) + assert correr("C-03", dos, cambios_metodo=3, pagos_consecutivos=3, hueco_meses=3) == [] + + +def test_c03_hueco_de_tres_meses_calendario_dispara_y_dos_no() -> None: + sin_hueco = contexto( + [cliente()], [credito()], [pago(1, date(2026, 1, 15)), pago(2, date(2026, 3, 15))] + ) + assert correr("C-03", sin_hueco, hueco_meses=3) == [] + con_hueco = contexto( + [cliente()], [credito()], [pago(1, date(2026, 1, 15)), pago(2, date(2026, 4, 15))] + ) + alertas = correr("C-03", con_hueco, hueco_meses=3) + assert len(alertas) == 1 and alertas[0].evidencia["motivo"] == "hueco" + assert alertas[0].evidencia["meses_desde_pago_anterior"] == 3 + assert alertas[0].transaccion_ids == (1, 2) + + +def test_c03_hueco_89_vs_90_dias_en_el_borde_del_mes() -> None: + # 1 ene → 31 mar: 89 días y 2 meses calendario → no; 1 ene → 1 abr: 90 días y 3 meses → sí + ochenta_y_nueve = contexto( + [cliente()], [credito()], [pago(1, date(2026, 1, 1)), pago(2, date(2026, 3, 31))] + ) + noventa = contexto( + [cliente()], [credito()], [pago(1, date(2026, 1, 1)), pago(2, date(2026, 4, 1))] + ) + assert correr("C-03", ochenta_y_nueve, hueco_meses=3) == [] + assert len(correr("C-03", noventa, hueco_meses=3)) == 1 + + +def test_c03_no_mezcla_creditos() -> None: + ctx = contexto( + [cliente()], + [credito(10), credito(11)], + [ + pago(1, date(2026, 1, 15), credito_id=10, metodo="T"), + pago(2, date(2026, 2, 15), credito_id=11, metodo="E"), + pago(3, date(2026, 3, 15), credito_id=10, metodo="E"), + pago(4, date(2026, 4, 15), credito_id=11, metodo="T"), + ], + ) + assert correr("C-03", ctx, cambios_metodo=3, pagos_consecutivos=3, hueco_meses=3) == [] + + +# --- Familia D ------------------------------------------------------------------------------ + + +def test_d02_d03_d05_segun_tipo_de_pep_vigente() -> None: + ctx = contexto( + [ + cliente(1, pep_tipos=frozenset({"nacional"})), + cliente(2, pep_tipos=frozenset({"extranjera"})), + cliente(3, pep_tipos=frozenset({"asimilado"})), + cliente(4), + ] + ) + assert [a.cliente_id for a in correr("D-02", ctx)] == [1] + assert [a.cliente_id for a in correr("D-03", ctx)] == [2] + assert [a.cliente_id for a in correr("D-05", ctx)] == [3] + + +def test_d04_solo_pagos_de_pep_por_encima_de_los_ingresos() -> None: + ctx = contexto( + [cliente(1, pep_tipos=frozenset({"nacional"})), cliente(2)], + [credito(10, cliente_id=1), credito(11, cliente_id=2)], + [ + pago(1, date(2026, 5, 1), total="20000.01"), # PEP, PAGO, > ingresos → sí + pago(2, date(2026, 5, 2), total="20000"), # igual a ingresos → no + pago(3, date(2026, 5, 3), total="50000", tipo="ENGANCHE"), # enganche → no + pago(4, date(2026, 5, 4), total="50000", credito_id=11, cliente_id=2), # no PEP + ], + ) + alertas = correr("D-04", ctx, factor_ingresos=1.0, tipos_pep=["nacional", "extranjera"]) + assert [a.transaccion_ids for a in alertas] == [(1,)] + assert alertas[0].evidencia["pep"] == ["nacional"] + assert len(correr("D-04", ctx, tipos_transaccion=["PAGO", "ENGANCHE"])) == 2 + + +# --- Familia E ------------------------------------------------------------------------------ + + +def test_e01_solo_coincidencia_confirmada() -> None: + ctx = contexto([cliente(1, coincidencia_confirmada=True), cliente(2)]) + assert [a.cliente_id for a in correr("E-01", ctx)] == [1] + + +def test_e02_pais_en_gafi_o_paraiso_fiscal() -> None: + catalogos = {"paises_gafi": frozenset({"Siria"}), "paraisos_fiscales": frozenset({"Panamá"})} + ctx = contexto( + [cliente(1, pais="Siria"), cliente(2, pais="panamá"), cliente(3, pais="México"), + cliente(4, pais="México", nacionalidad="Yemen")], + catalogos=catalogos, + ) # fmt: skip + alertas = correr("E-02", ctx, catalogos=["gafi", "paraisos_fiscales"]) + assert [a.cliente_id for a in alertas] == [1, 2] + assert alertas[1].evidencia["catalogos"] == ["paraisos_fiscales"] + ctx.catalogos["paises_gafi"] = frozenset({"Siria", "Yemen"}) + assert [a.cliente_id for a in correr("E-02", ctx, catalogos=["gafi"])] == [1, 4] + + +# --- ejecutar(), vencimiento(), firma() ---------------------------------------------------- + + +def _regla(clave: str, tipo: str, **params) -> ReglaVigente: + return ReglaVigente( + id=hash(clave) % 1000, clave=clave, version="v2", nombre=clave, tipo_evaluacion=tipo, + nivel="critica", plazo_aviso="24h", parametros=params, + ) # fmt: skip + + +def test_ejecutar_despacha_por_clave_y_omite_manuales_y_pendientes() -> None: + ctx = contexto([cliente(1, comprobante_ingresos=False)]) + reglas_ = [_regla("B-01", "cliente"), _regla("B-05", "manual"), _regla("B-02", "cliente"), + _regla("Z-99", "cliente")] # fmt: skip + resultados = {r.regla.clave: r for r in rules.ejecutar(reglas_, ctx)} + assert len(resultados["B-01"].candidatas) == 1 and resultados["B-01"].omitida is None + assert resultados["B-05"].omitida == "manual" + assert resultados["B-02"].omitida == "pendiente_agregados" + assert resultados["Z-99"].omitida == "sin_implementacion" + assert [r.regla.clave for r in rules.ejecutar(reglas_, ctx, claves=["b-01"])] == ["B-01"] + + +@pytest.mark.parametrize( + ("plazo", "desde", "esperado"), + [ + ("24h", date(2026, 8, 31), date(2026, 9, 1)), + ("aviso", date(2026, 8, 31), date(2026, 9, 17)), + ("aviso", date(2026, 12, 5), date(2027, 1, 17)), + ("inmediato", date(2026, 8, 31), date(2026, 8, 31)), + (None, date(2026, 8, 31), None), + ], +) +def test_vencimiento_segun_plazo_de_aviso(plazo, desde, esperado) -> None: + assert rules.vencimiento(plazo, desde) == esperado + + +def test_vencimiento_rechaza_plazos_desconocidos() -> None: + with pytest.raises(ValueError): + rules.vencimiento("72h", date(2026, 1, 1)) + + +def test_firma_identifica_la_alerta_sin_importar_el_orden_de_transacciones() -> None: + assert rules.firma(1, 2, 3, [9, 7]) == rules.firma(1, 2, 3, [7, 9]) + assert rules.firma(1, 2, 3, [9]) != rules.firma(1, 2, 3, [7]) + assert rules.firma(1, 2, None, []) != rules.firma(1, 2, 3, [])