"""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) # Estas pruebas son de pantallas: la reevaluación por alerta crítica (Pieza C) se desactiva # para que el nivel vigente lo controle cada test. monkeypatch.setattr( "app.services.riesgo.solicitar_reevaluacion", lambda session, cliente_id, evento: None ) 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 # Secciones del expediente (Fase 4, PR 1); el beneficiario controlador solo en morales (PR 3) assert "Identificación" in html and "Documentos" in html and "Declaración" in html assert "No proporcionados por CHM" in html # importado sin identificación assert "PR 3" not in html and "Beneficiario controlador de" not 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"]