services/reconstruccion.py responde qué sabía el sistema del cliente al final de una fecha (hora de Ciudad de México): modelo y reglas vigentes, expediente, coincidencias con su decisión, evaluaciones con su detalle guardado, alertas y casos con su estado a esa fecha y el agregado vigente. Tablas versionadas con vigente_a; estados que cambian en sitio, desde audit_trail. Solo lee.
419 lines
15 KiB
Python
419 lines
15 KiB
Python
"""Reconstrucción de un cliente a una fecha (Fase 5 del brief, Pieza F PR 1).
|
|
|
|
Las fechas intermedias se toman como instantes (`datetime` en UTC) entre dos operaciones: así no
|
|
hay que falsear fechas en la base para probar "antes y después" del mismo día.
|
|
"""
|
|
|
|
from collections.abc import Iterator
|
|
from datetime import UTC, date, datetime
|
|
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.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,
|
|
Coincidencia,
|
|
Documento,
|
|
ModeloRiesgo,
|
|
ahora_utc,
|
|
)
|
|
from app.models.usuario import Rol
|
|
from app.schemas.riesgo import CambiosModelo
|
|
from app.services.agregados import tenant_de_sesion
|
|
from app.services.alertas import cambiar_estado, levantar_manual, versionar_regla
|
|
from app.services.casos import abrir_caso
|
|
from app.services.modelos import crear_version, modelo_vigente
|
|
from app.services.reconstruccion import (
|
|
ClienteNoEncontradoError,
|
|
corte,
|
|
hoy_local,
|
|
reconstruir_cliente,
|
|
vigente_a,
|
|
)
|
|
from app.services.riesgo import evaluar_cliente, solicitar_reevaluacion
|
|
from seed.usuarios_demo import sembrar
|
|
from tests.fixtures.oraculo import FIXTURE
|
|
|
|
|
|
def ahora() -> datetime:
|
|
return datetime.now(UTC)
|
|
|
|
|
|
@pytest.fixture
|
|
def sesion() -> Iterator[Session]:
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
with crear_session_factory(engine)() as s:
|
|
importar_esquema(s, FIXTURE, "pytest", sal="sal")
|
|
audit.fijar_actor(s, "oficial", tenant_de_sesion(s).id)
|
|
yield s
|
|
|
|
|
|
@pytest.fixture
|
|
def cliente_id(sesion: Session) -> int:
|
|
return sesion.scalar(sa.select(Cliente.id).order_by(Cliente.id).limit(1))
|
|
|
|
|
|
def _conteos(sesion: Session) -> dict[str, int]:
|
|
return {
|
|
tabla.name: sesion.scalar(sa.select(sa.func.count()).select_from(tabla))
|
|
for tabla in Base.metadata.sorted_tables
|
|
}
|
|
|
|
|
|
# --- Corte --------------------------------------------------------------------------------
|
|
|
|
|
|
def test_una_fecha_es_el_final_de_ese_dia_en_ciudad_de_mexico() -> None:
|
|
assert corte(date(2026, 10, 7)) == datetime(2026, 10, 8, 6, 0)
|
|
assert corte(datetime(2026, 10, 7, 15, 30, tzinfo=UTC)) == datetime(2026, 10, 7, 15, 30)
|
|
|
|
|
|
# --- Modelo de riesgo ----------------------------------------------------------------------
|
|
|
|
|
|
def test_antes_de_un_cambio_de_modelo_muestra_la_version_antigua_y_su_evaluacion(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
v2 = modelo_vigente(sesion, tenant_de_sesion(sesion))
|
|
primera = evaluar_cliente(sesion, cliente_id, "inicial")
|
|
sesion.flush()
|
|
entre = ahora()
|
|
|
|
v3 = crear_version(
|
|
sesion,
|
|
v2.id,
|
|
CambiosModelo(ponderaciones={"T1": Decimal("0.25"), "T3": Decimal("0.05")}),
|
|
"oficial",
|
|
"Más peso al instrumento",
|
|
)
|
|
# vigente_desde es una fecha: se igualan para que decida el momento de creación.
|
|
for modelo in (v2, v3):
|
|
modelo.vigente_desde = date(2026, 1, 1)
|
|
segunda = solicitar_reevaluacion(sesion, cliente_id, "Cambio de metodología")
|
|
sesion.flush()
|
|
despues = ahora()
|
|
|
|
antes_del_cambio = reconstruir_cliente(sesion, cliente_id, entre)
|
|
assert antes_del_cambio.modelo["version"] == "v2"
|
|
assert antes_del_cambio.evaluacion_vigente["id"] == primera.id
|
|
assert antes_del_cambio.evaluacion_vigente["modelo"] == "v2"
|
|
assert [e["id"] for e in antes_del_cambio.evaluaciones.filas] == [primera.id]
|
|
|
|
tras_el_cambio = reconstruir_cliente(sesion, cliente_id, despues)
|
|
assert tras_el_cambio.modelo["version"] == "v3"
|
|
assert tras_el_cambio.evaluacion_vigente["id"] == segunda.id
|
|
assert tras_el_cambio.evaluacion_vigente["evento"] == "Cambio de metodología"
|
|
assert len(tras_el_cambio.evaluaciones.filas) == 2
|
|
|
|
# El detalle es el guardado, no un recálculo con el modelo nuevo.
|
|
assert antes_del_cambio.evaluacion_vigente["detalle"] == primera.detalle
|
|
t1 = {i["clave"]: i["ponderacion"] for i in antes_del_cambio.modelo["indicadores"]}["T1"]
|
|
assert t1 == Decimal("0.15")
|
|
|
|
|
|
def test_sin_modelo_ni_evaluacion_lo_dice(sesion: Session, cliente_id: int) -> None:
|
|
r = reconstruir_cliente(sesion, cliente_id, ahora())
|
|
assert r.evaluacion_vigente is None
|
|
assert r.evaluaciones.nota == "No había evaluaciones de riesgo a esta fecha."
|
|
assert r.resumen == {"modelo": "v2", "reglas_vigentes": 21, "nivel": None}
|
|
|
|
|
|
# --- Reglas --------------------------------------------------------------------------------
|
|
|
|
|
|
def test_una_regla_versionada_muestra_la_version_vigente_a_cada_fecha(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
antes = ahora()
|
|
nueva = versionar_regla(
|
|
sesion,
|
|
"B-02",
|
|
{"parametros": {"capacidad_pago_max": 0.5}},
|
|
"Calibración con CHM",
|
|
"oficial",
|
|
)
|
|
sesion.flush()
|
|
despues = ahora()
|
|
|
|
def b02(instante: datetime) -> dict:
|
|
reglas = reconstruir_cliente(sesion, cliente_id, instante).reglas.filas
|
|
assert len([r for r in reglas if r["clave"] == "B-02"]) == 1
|
|
return next(r for r in reglas if r["clave"] == "B-02")
|
|
|
|
assert b02(antes)["version"] == "v2"
|
|
assert b02(antes)["parametros"]["capacidad_pago_max"] == 0.40
|
|
assert b02(despues)["version"] == nueva.version
|
|
assert b02(despues)["parametros"]["capacidad_pago_max"] == 0.5
|
|
|
|
|
|
# --- Expediente ----------------------------------------------------------------------------
|
|
|
|
|
|
def test_un_documento_actualizado_muestra_la_version_de_cada_fecha(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
tenant_id = tenant_de_sesion(sesion).id
|
|
v1 = Documento(
|
|
tenant_id=tenant_id, created_by="analista", cliente_id=cliente_id,
|
|
tipo="identificacion", vigencia=date(2026, 9, 30), ruta="docs/ine_v1.pdf", version=1,
|
|
) # fmt: skip
|
|
sesion.add(v1)
|
|
sesion.flush()
|
|
entre = ahora()
|
|
|
|
v1.valid_to = ahora_utc()
|
|
sesion.add(
|
|
Documento(
|
|
tenant_id=tenant_id,
|
|
created_by="analista",
|
|
cliente_id=cliente_id,
|
|
tipo="identificacion",
|
|
vigencia=date(2031, 9, 30),
|
|
ruta="docs/ine_v2.pdf",
|
|
version=2,
|
|
) # fmt: skip
|
|
)
|
|
sesion.flush()
|
|
despues = ahora()
|
|
|
|
(antes,) = reconstruir_cliente(sesion, cliente_id, entre).documentos.filas
|
|
assert (antes["version"], antes["archivo"]) == (1, "ine_v1.pdf")
|
|
(hoy,) = reconstruir_cliente(sesion, cliente_id, despues).documentos.filas
|
|
assert (hoy["version"], hoy["estado_a_la_fecha"]) == (2, "vigente")
|
|
|
|
|
|
def test_la_vigencia_del_documento_se_juzga_a_la_fecha(sesion: Session, cliente_id: int) -> None:
|
|
sesion.add(
|
|
Documento(
|
|
tenant_id=tenant_de_sesion(sesion).id,
|
|
created_by="analista",
|
|
cliente_id=cliente_id,
|
|
tipo="comprobante_domicilio",
|
|
vigencia=date(2026, 9, 30),
|
|
version=1,
|
|
valid_from=datetime(2026, 1, 1, tzinfo=UTC),
|
|
) # fmt: skip
|
|
)
|
|
sesion.flush()
|
|
alta = sesion.get(Cliente, cliente_id)
|
|
alta.created_at = datetime(2025, 12, 1, tzinfo=UTC)
|
|
|
|
assert (
|
|
reconstruir_cliente(sesion, cliente_id, date(2026, 6, 1)).documentos.filas[0][
|
|
"estado_a_la_fecha"
|
|
]
|
|
== "vigente"
|
|
)
|
|
assert (
|
|
reconstruir_cliente(sesion, cliente_id, date(2026, 10, 1)).documentos.filas[0][
|
|
"estado_a_la_fecha"
|
|
]
|
|
== "vencido"
|
|
)
|
|
|
|
|
|
def test_la_decision_de_una_coincidencia_sale_del_audit_trail(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
coincidencia = Coincidencia(
|
|
tenant_id=tenant_de_sesion(sesion).id, created_by="analista", persona_id=cliente_id,
|
|
texto_lista="OFAC SDN", score=Decimal("91.5"), decision="pendiente", fuente="OFAC",
|
|
) # fmt: skip
|
|
sesion.add(coincidencia)
|
|
sesion.flush()
|
|
entre = ahora()
|
|
|
|
coincidencia.decision = "confirmada"
|
|
coincidencia.decidido_por = "oficial"
|
|
audit.registrar(
|
|
sesion, "coincidencia", coincidencia.id, "decidir",
|
|
antes={"decision": "pendiente", "decidido_por": None},
|
|
despues={"decision": "confirmada", "decidido_por": "oficial"},
|
|
motivo="Mismo nombre y fecha de nacimiento",
|
|
) # fmt: skip
|
|
sesion.flush()
|
|
despues = ahora()
|
|
|
|
def decision(instante: datetime) -> tuple:
|
|
filas = reconstruir_cliente(sesion, cliente_id, instante).coincidencias.filas
|
|
fila = next(f for f in filas if f["id"] == coincidencia.id)
|
|
return fila["decision"], fila["decidido_por"]
|
|
|
|
assert decision(entre) == ("pendiente", None)
|
|
assert decision(despues) == ("confirmada", "oficial")
|
|
|
|
|
|
# --- Alertas y casos -----------------------------------------------------------------------
|
|
|
|
|
|
def test_una_alerta_cerrada_aparece_nueva_en_una_fecha_intermedia(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
alerta = levantar_manual(sesion, "B-05", cliente_id, "Intentó pagar en efectivo", "analista")
|
|
sesion.flush()
|
|
nueva = ahora()
|
|
cambiar_estado(sesion, alerta.id, "en_revision", usuario="analista")
|
|
sesion.flush()
|
|
en_revision = ahora()
|
|
cambiar_estado(
|
|
sesion, alerta.id, "cerrada", motivo="Sin indicios", usuario="oficial", rol="oficial"
|
|
)
|
|
sesion.flush()
|
|
cerrada = ahora()
|
|
|
|
def estado(instante: datetime) -> str:
|
|
filas = reconstruir_cliente(sesion, cliente_id, instante).alertas.filas
|
|
return next(f for f in filas if f["id"] == alerta.id)["estado"]
|
|
|
|
assert estado(nueva) == "nueva"
|
|
assert estado(en_revision) == "en_revision"
|
|
assert estado(cerrada) == "cerrada"
|
|
assert sesion.get(Alerta, alerta.id).estado == "cerrada" # en sitio, como decidió D
|
|
|
|
|
|
def test_un_caso_y_su_linea_de_tiempo_hasta_la_fecha(sesion: Session, cliente_id: int) -> None:
|
|
alerta = levantar_manual(sesion, "B-07", cliente_id, "Presión para agilizar", "analista")
|
|
sesion.flush()
|
|
antes_del_caso = ahora()
|
|
caso = abrir_caso(sesion, [alerta.id], "oficial", "oficial", "Revisar con el área comercial")
|
|
sesion.flush()
|
|
despues = ahora()
|
|
|
|
assert reconstruir_cliente(sesion, cliente_id, antes_del_caso).casos.filas == []
|
|
(fila,) = reconstruir_cliente(sesion, cliente_id, despues).casos.filas
|
|
assert fila["id"] == caso.id and fila["estado"] == "abierto"
|
|
assert fila["linea_de_tiempo"]
|
|
alerta_en_caso = next(
|
|
f
|
|
for f in reconstruir_cliente(sesion, cliente_id, despues).alertas.filas
|
|
if f["id"] == alerta.id
|
|
)
|
|
assert alerta_en_caso["estado"] == "escalada"
|
|
|
|
|
|
# --- Cliente -------------------------------------------------------------------------------
|
|
|
|
|
|
def test_antes_del_alta_el_cliente_no_existia(sesion: Session, cliente_id: int) -> None:
|
|
r = reconstruir_cliente(sesion, cliente_id, date(2020, 1, 1))
|
|
|
|
assert r.existia is False
|
|
assert r.mensaje.startswith("El cliente no existía el 2020-01-01")
|
|
assert r.evaluaciones.filas == [] and r.alertas.filas == []
|
|
assert r.como_dict()["existia"] is False
|
|
|
|
|
|
def test_un_cliente_de_otro_tenant_o_inexistente_falla(sesion: Session) -> None:
|
|
with pytest.raises(ClienteNoEncontradoError):
|
|
reconstruir_cliente(sesion, 999_999, date(2026, 10, 7))
|
|
|
|
|
|
def test_vigente_a_usa_valid_from_y_valid_to() -> None:
|
|
consulta = vigente_a(sa.select(Documento), Documento, datetime(2026, 10, 8, 6))
|
|
texto = str(consulta.compile(compile_kwargs={"literal_binds": True}))
|
|
assert "documento.valid_from <" in texto and "documento.valid_to >=" in texto
|
|
|
|
|
|
# --- Solo lectura --------------------------------------------------------------------------
|
|
|
|
|
|
def test_reconstruir_no_escribe_nada(sesion: Session, cliente_id: int) -> None:
|
|
evaluar_cliente(sesion, cliente_id, "inicial")
|
|
levantar_manual(sesion, "B-05", cliente_id, "x", "analista")
|
|
sesion.commit()
|
|
antes = _conteos(sesion)
|
|
|
|
reconstruir_cliente(sesion, cliente_id, ahora())
|
|
reconstruir_cliente(sesion, cliente_id, date(2026, 1, 1))
|
|
sesion.flush()
|
|
|
|
assert _conteos(sesion) == antes
|
|
assert not sesion.new and not sesion.dirty
|
|
|
|
|
|
# --- Pantalla ------------------------------------------------------------------------------
|
|
|
|
|
|
@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)
|
|
with fabrica() as s:
|
|
importar_esquema(s, FIXTURE, "pytest", sal="sal")
|
|
sembrar(s, {Rol.ANALISTA: "a-1", Rol.OFICIAL: "o-2", Rol.AUDITOR: "u-3"})
|
|
s.commit()
|
|
return fabrica
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("rol", "clave"), [(Rol.ANALISTA, "a-1"), (Rol.OFICIAL, "o-2"), (Rol.AUDITOR, "u-3")]
|
|
)
|
|
def test_la_pantalla_es_de_los_tres_roles_y_solo_deja_el_acceso(
|
|
fabrica: sessionmaker[Session], rol: Rol, clave: str
|
|
) -> None:
|
|
with fabrica() as s:
|
|
cliente_id = s.scalar(sa.select(Cliente.id).limit(1))
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
c.post("/login", data={"usuario": rol.value, "contrasena": clave})
|
|
with fabrica() as s:
|
|
antes = _conteos(s)
|
|
respuesta = c.get(f"/evidencia/{cliente_id}?fecha={hoy_local().isoformat()}")
|
|
with fabrica() as s:
|
|
despues = _conteos(s)
|
|
acceso = s.scalar(
|
|
sa.select(AuditTrail).where(AuditTrail.accion == f"GET /evidencia/{cliente_id}")
|
|
)
|
|
|
|
assert respuesta.status_code == 200
|
|
assert "A esta fecha:" in respuesta.text and "21 reglas vigentes" in respuesta.text
|
|
assert {k: despues[k] - antes[k] for k in antes if despues[k] != antes[k]} == {"audit_trail": 1}
|
|
assert (
|
|
acceso.usuario == rol.value
|
|
and acceso.despues["consulta"] == f"fecha={hoy_local().isoformat()}"
|
|
)
|
|
|
|
|
|
def test_la_pantalla_valida_la_fecha_y_el_cliente(fabrica: sessionmaker[Session]) -> None:
|
|
with fabrica() as s:
|
|
cliente = s.scalar(sa.select(Cliente).limit(1))
|
|
ids = (cliente.id, cliente.id_externo)
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
c.post("/login", data={"usuario": "auditor", "contrasena": "u-3"})
|
|
assert c.get(f"/evidencia/{ids[0]}?fecha=7-10-2026").status_code == 400
|
|
assert c.get("/evidencia/999999").status_code == 404
|
|
assert "no existía" in c.get(f"/evidencia/{ids[0]}?fecha=2020-01-01").text
|
|
busqueda = c.get(f"/evidencia?cliente={ids[1]}&fecha=2026-10-01")
|
|
assert busqueda.headers["location"] == f"/evidencia/{ids[0]}?fecha=2026-10-01"
|
|
assert "No hay ningún cliente" in c.get("/evidencia?cliente=zzz").text
|
|
assert f'href="/evidencia/{ids[0]}"' in c.get(f"/riesgo/{ids[0]}").text
|
|
inicio = c.get("/inicio").text
|
|
assert 'href="/evidencia"' in inicio[inicio.index('<nav class="nav"') :]
|
|
|
|
|
|
def test_modelo_de_otro_dia_no_cuenta_aunque_se_haya_creado_antes(
|
|
sesion: Session, cliente_id: int
|
|
) -> None:
|
|
"""vigente_desde también manda: una versión que entra en vigor mañana no es la de hoy."""
|
|
v2 = modelo_vigente(sesion, tenant_de_sesion(sesion))
|
|
v2.vigente_desde = date(2026, 1, 1)
|
|
futura = crear_version(sesion, v2.id, CambiosModelo(), "oficial", "Entra en vigor después")
|
|
futura.vigente_desde = date(2099, 1, 1)
|
|
sesion.flush()
|
|
|
|
assert reconstruir_cliente(sesion, cliente_id, ahora()).modelo["version"] == "v2"
|
|
assert sesion.scalar(sa.select(sa.func.count()).select_from(ModeloRiesgo)) == 2
|