Orden fijo de los pendientes, umbral y UMA desde la configuración, aviso de UMA desde el 1 de febrero, periodo y fecha límite del aviso en cambios de mes y de año, informe sin operaciones, información incompleta, cada número contra su lista, permisos y el estado vacío. Brief v2.5, nota de la Pieza M en CLAUDE.md y O6 a O9 en el backlog.
444 lines
18 KiB
Python
444 lines
18 KiB
Python
"""Inicio del oficial de cumplimiento y perfil regulatorio (Pieza M)."""
|
|
|
|
# ruff: noqa: F811 (las fixtures vienen de tests/test_textos)
|
|
from __future__ import annotations
|
|
|
|
import html
|
|
import re
|
|
from collections.abc import Iterator
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from types import SimpleNamespace
|
|
|
|
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.main import crear_app
|
|
from app.models import Alerta, AuditTrail, Base, LoteCarga, ReglaAlerta, Tenant
|
|
from app.models.usuario import Rol
|
|
from app.services import alertas as servicio_alertas
|
|
from app.services import inicio as servicio_inicio
|
|
from app.services import operaciones as servicio_carga
|
|
from app.services import tenant as servicio_tenant
|
|
from seed.usuarios_demo import sembrar
|
|
from tests.test_expediente import CONTRASENAS, entrar
|
|
from tests.test_textos import cliente, fabrica # noqa: F401
|
|
|
|
LEY = (
|
|
"Ley Federal para la Prevención e Identificación de Operaciones con Recursos de Procedencia "
|
|
"Ilícita"
|
|
)
|
|
|
|
|
|
def pagina(c: TestClient, ruta: str) -> str:
|
|
respuesta = c.get(ruta)
|
|
assert respuesta.status_code == 200, ruta
|
|
return html.unescape(respuesta.text)
|
|
|
|
|
|
def cambiar_uma(fabrica: sessionmaker[Session], uma: str, anio: int) -> None:
|
|
with fabrica() as sesion:
|
|
audit.fijar_actor(sesion, "oficial", 1)
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
servicio_tenant.actualizar_uma(
|
|
sesion, tenant, Decimal(uma), anio, usuario="oficial", motivo="UMA publicada"
|
|
)
|
|
sesion.commit()
|
|
|
|
|
|
# --- Bloque 1 · encabezado y perfil regulatorio --------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize("rol", list(Rol))
|
|
def test_el_perfil_regulatorio_lo_ven_todos_y_tiene_todo_el_marco(
|
|
cliente: TestClient, rol: Rol
|
|
) -> None:
|
|
entrar(cliente, rol)
|
|
texto = pagina(cliente, "/perfil-regulatorio")
|
|
for esperado in (
|
|
LEY,
|
|
"Servicio de Administración Tributaria",
|
|
"Unidad de Inteligencia Financiera",
|
|
"Acuerdo 115/2026",
|
|
"en vigor desde el 30/11/2026",
|
|
"Artículo 17, fracción IV",
|
|
"Otorgamiento de créditos por quien no es entidad financiera",
|
|
"Identificación de todos los clientes",
|
|
"Aviso desde $188,282.55 (1,605 UMA de $117.31)",
|
|
"regla A-01 v2",
|
|
"$117.31 (2026)",
|
|
"actualizada en la plataforma el ",
|
|
):
|
|
assert esperado in texto, esperado
|
|
assert "LFPIORPI" not in texto
|
|
|
|
|
|
def test_inicio_lleva_al_perfil_desde_el_encabezado(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.OFICIAL)
|
|
texto = pagina(cliente, "/inicio")
|
|
encabezado = texto.split("data-encabezado-regulatorio>")[1].split("</a>")[0]
|
|
assert encabezado == (
|
|
"Artículo 17, fracción IV · Aviso desde $188,282.55 (1,605 UMA de $117.31) · "
|
|
"Identificación de todos los clientes"
|
|
)
|
|
assert 'href="/perfil-regulatorio" data-encabezado-regulatorio' in texto
|
|
for fuera in ("Sujeto obligado", "LFPIORPI", "Fecha de corte", "Ventana"):
|
|
assert fuera not in texto, fuera
|
|
|
|
|
|
def test_el_umbral_y_la_uma_salen_de_la_configuracion(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
"""Cambiar la UMA (o el factor de la regla) cambia el encabezado y el perfil."""
|
|
cambiar_uma(fabrica, "120.00", 2027)
|
|
entrar(cliente, Rol.OFICIAL)
|
|
esperado = "Aviso desde $192,600.00 (1,605 UMA de $120.00)"
|
|
assert esperado in pagina(cliente, "/inicio")
|
|
perfil = pagina(cliente, "/perfil-regulatorio")
|
|
assert esperado in perfil and "$120.00 (2027)" in perfil
|
|
with fabrica() as sesion:
|
|
fila = sesion.scalar(
|
|
sa.select(AuditTrail)
|
|
.where(AuditTrail.entidad == "tenant", AuditTrail.accion == "actualizar_uma")
|
|
.order_by(AuditTrail.id.desc())
|
|
)
|
|
assert fila.antes["uma_vigente"] == "117.31" and fila.despues["uma_anio"] == 2027
|
|
regla = sesion.scalar(
|
|
sa.select(ReglaAlerta).where(
|
|
ReglaAlerta.clave == "A-01", ReglaAlerta.valid_to.is_(None)
|
|
)
|
|
)
|
|
regla.parametros = {**regla.parametros, "factor_uma": 1000}
|
|
sesion.commit()
|
|
assert "Aviso desde $120,000.00 (1,000 UMA de $120.00)" in pagina(cliente, "/inicio")
|
|
|
|
|
|
def test_actualizar_uma_sin_cambio_no_deja_fila(fabrica: sessionmaker[Session]) -> None:
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
assert not servicio_tenant.actualizar_uma(
|
|
sesion, tenant, tenant.uma_vigente, tenant.uma_anio, usuario="x", motivo="x"
|
|
)
|
|
with pytest.raises(ValueError):
|
|
servicio_tenant.actualizar_uma(
|
|
sesion, tenant, Decimal(0), 2026, usuario="x", motivo="x"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("hoy", "uma_anio", "desactualizada"),
|
|
[
|
|
(date(2027, 1, 31), 2026, False), # enero: la UMA nueva todavía no rige
|
|
(date(2027, 2, 1), 2026, True),
|
|
(date(2027, 2, 1), 2027, False),
|
|
(date(2027, 12, 31), 2026, True),
|
|
(date(2027, 3, 1), None, True),
|
|
],
|
|
)
|
|
def test_uma_desactualizada_desde_el_1_de_febrero(
|
|
hoy: date, uma_anio: int | None, desactualizada: bool
|
|
) -> None:
|
|
tenant = SimpleNamespace(uma_anio=uma_anio)
|
|
assert servicio_tenant.uma_desactualizada(tenant, hoy) is desactualizada
|
|
|
|
|
|
def test_el_aviso_de_uma_lo_ve_el_oficial(
|
|
cliente: TestClient, fabrica: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
aviso = "El umbral está calculado con la UMA anterior (2026)"
|
|
monkeypatch.setattr("app.fechas.hoy", lambda: date(2027, 2, 1))
|
|
entrar(cliente, Rol.OFICIAL)
|
|
assert aviso in pagina(cliente, "/inicio") and aviso in pagina(cliente, "/perfil-regulatorio")
|
|
entrar(cliente, Rol.ANALISTA)
|
|
assert aviso not in pagina(cliente, "/inicio")
|
|
cambiar_uma(fabrica, "121.00", 2027)
|
|
entrar(cliente, Rol.OFICIAL)
|
|
assert "UMA anterior" not in pagina(cliente, "/inicio")
|
|
|
|
|
|
def test_la_ventana_esta_en_el_detalle_de_la_alerta_a02(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
with fabrica() as sesion:
|
|
alerta = sesion.scalar(
|
|
sa.select(Alerta)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.where(ReglaAlerta.clave == "A-02")
|
|
.limit(1)
|
|
)
|
|
assert alerta is not None
|
|
entrar(cliente, Rol.OFICIAL)
|
|
assert "6 meses: (28/02/2026, 31/08/2026]" in pagina(cliente, f"/alertas/{alerta.id}")
|
|
|
|
|
|
# --- Bloque 2 · estado del mes -------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("hoy", "inicio", "fin", "limite"),
|
|
[
|
|
(date(2026, 11, 4), date(2026, 10, 1), date(2026, 10, 31), date(2026, 11, 17)),
|
|
(date(2026, 11, 30), date(2026, 10, 1), date(2026, 10, 31), date(2026, 11, 17)),
|
|
(date(2026, 12, 1), date(2026, 11, 1), date(2026, 11, 30), date(2026, 12, 17)),
|
|
(date(2027, 1, 1), date(2026, 12, 1), date(2026, 12, 31), date(2027, 1, 17)),
|
|
(date(2027, 3, 1), date(2027, 2, 1), date(2027, 2, 28), date(2027, 3, 17)),
|
|
(date(2028, 3, 10), date(2028, 2, 1), date(2028, 2, 29), date(2028, 3, 17)),
|
|
],
|
|
)
|
|
def test_periodo_y_fecha_limite_del_aviso(hoy: date, inicio: date, fin: date, limite: date) -> None:
|
|
assert servicio_inicio.periodo_del_aviso(hoy) == (inicio, fin, limite)
|
|
|
|
|
|
def _en(monkeypatch: pytest.MonkeyPatch, hoy: date) -> None:
|
|
monkeypatch.setattr("app.fechas.hoy", lambda: hoy)
|
|
|
|
|
|
def _total_bandeja(c: TestClient, ruta: str) -> int:
|
|
texto = pagina(c, ruta)
|
|
return int(re.search(r"(\d[\d,]*) alertas · página", texto).group(1).replace(",", ""))
|
|
|
|
|
|
def test_el_aviso_del_periodo_cuenta_lo_que_lista_la_bandeja(
|
|
cliente: TestClient, fabrica: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
with fabrica() as sesion: # el mes con más alertas de aviso del fixture
|
|
limite = sesion.scalar(
|
|
sa.select(Alerta.vence_el)
|
|
.where(Alerta.plazo_aviso == "aviso", Alerta.vence_el.is_not(None))
|
|
.group_by(Alerta.vence_el)
|
|
.order_by(sa.func.count(Alerta.id).desc())
|
|
.limit(1)
|
|
)
|
|
esperadas = sesion.scalar(
|
|
sa.select(sa.func.count(Alerta.id)).where(
|
|
Alerta.plazo_aviso == "aviso", Alerta.vence_el == limite
|
|
)
|
|
)
|
|
hoy = limite.replace(day=4)
|
|
_en(monkeypatch, hoy)
|
|
entrar(cliente, Rol.OFICIAL)
|
|
texto = pagina(cliente, "/inicio")
|
|
fila = texto.split('data-renglon="aviso"')[1].split("</li>")[0]
|
|
enlace = f"/alertas?plazo=aviso&vence_el={limite.isoformat()}"
|
|
assert f'href="{enlace}"' in fila
|
|
assert f"{esperadas:,} operaci" in fila and f"fecha límite {limite:%d/%m/%Y}" in fila
|
|
assert "faltan 13 días" in fila
|
|
assert _total_bandeja(cliente, enlace) == esperadas
|
|
|
|
|
|
def test_sin_operaciones_objeto_de_aviso_corresponde_informe(
|
|
cliente: TestClient, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
_en(monkeypatch, date(2031, 6, 20))
|
|
entrar(cliente, Rol.OFICIAL)
|
|
fila = pagina(cliente, "/inicio").split('data-renglon="aviso"')[1].split("</li>")[0]
|
|
assert "Aviso de mayo de 2031" in fila
|
|
assert "Sin operaciones objeto de aviso: corresponde informe sin operaciones" in fila
|
|
assert "fecha límite 17/06/2031" in fila and "venció hace 3 días" in fila
|
|
|
|
|
|
def test_la_informacion_que_no_cubre_el_periodo_avisa(
|
|
cliente: TestClient, fabrica: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
with fabrica() as sesion:
|
|
al = servicio_inicio.informacion_al(sesion, sesion.scalar(sa.select(Tenant)))
|
|
assert al is not None
|
|
entrar(cliente, Rol.OFICIAL)
|
|
# Mucho después del último movimiento: la información no llega al fin del periodo (mayo).
|
|
_en(monkeypatch, date(2031, 6, 20))
|
|
texto = pagina(cliente, "/inicio")
|
|
assert f"Información al {al:%d/%m/%Y}" in texto
|
|
assert f"El aviso de mayo no puede prepararse: la información llega al {al:%d/%m/%Y}" in texto
|
|
# Dentro del periodo cubierto, no hay advertencia.
|
|
_en(monkeypatch, date(al.year, al.month, 1))
|
|
assert "no puede prepararse" not in pagina(cliente, "/inicio")
|
|
|
|
|
|
def test_la_ultima_carga_con_rechazos_lleva_a_su_reporte(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
lote = LoteCarga(
|
|
tenant_id=tenant.id,
|
|
created_by="oficial",
|
|
tipo=servicio_carga.TIPO_LOTE,
|
|
archivo_hash="1" * 64,
|
|
usuario="oficial",
|
|
estado=servicio_carga.TERMINADO,
|
|
filas={"aceptadas": 12, "rechazadas": 3},
|
|
)
|
|
sesion.add(lote)
|
|
sesion.commit()
|
|
lote_id = lote.id
|
|
entrar(cliente, Rol.OFICIAL)
|
|
fila = pagina(cliente, "/inicio").split('data-renglon="informacion"')[1].split("</li>")[0]
|
|
assert "por oficial" in fila and "12 filas aceptadas" in fila and "3 rechazadas" in fila
|
|
assert f'href="/carga/lotes/{lote_id}/rechazos"' in fila
|
|
|
|
|
|
# --- Bloque 3 · pendientes -----------------------------------------------------------------------
|
|
|
|
|
|
def _cifras(texto: str) -> dict[str, tuple[int, str]]:
|
|
"""`data-cifra` → (número, enlace) de cada número de Inicio."""
|
|
return {
|
|
clave: (int(numero.replace(",", "")), html.unescape(enlace))
|
|
for enlace, clave, numero in re.findall(
|
|
r'<a href="([^"]+)" data-cifra="([a-z_0-9]+)">([\d,]+)', texto
|
|
)
|
|
}
|
|
|
|
|
|
def _total_de_la_lista(c: TestClient, ruta: str) -> int:
|
|
texto = pagina(c, ruta)
|
|
for patron in (
|
|
r"(\d[\d,]*) alertas · página", # /alertas
|
|
r"(\d[\d,]*) en total · página", # /screening
|
|
r'data-total-lista="(\d+)"', # /riesgo
|
|
r"(\d[\d,]*) clientes? con expediente incompleto", # /expediente
|
|
r"(\d[\d,]*) filas?\b", # /auditoria
|
|
):
|
|
if m := re.search(patron, texto):
|
|
return int(m.group(1).replace(",", ""))
|
|
raise AssertionError(f"la lista {ruta} no dice cuántos son")
|
|
|
|
|
|
def test_los_pendientes_van_en_orden_fijo(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.OFICIAL)
|
|
texto = pagina(cliente, "/inicio")
|
|
orden = re.findall(r'data-pendiente-orden="([a-z_0-9]+)"', texto)
|
|
assert tuple(orden) == servicio_inicio.ORDEN_PENDIENTES
|
|
titulos = re.findall(r'<h2 class="tarjeta__titulo">([^<]+)</h2>', texto)
|
|
assert titulos[:3] == ["Estado del mes", "Pendientes", "Evidencia"]
|
|
|
|
|
|
def test_las_alertas_de_24_horas_van_primero_y_luego_por_vencimiento(
|
|
fabrica: sessionmaker[Session],
|
|
) -> None:
|
|
hoy = date(2026, 11, 4)
|
|
with fabrica() as sesion:
|
|
p = servicio_inicio.pendientes(sesion, sesion.scalar(sa.select(Tenant)), hoy)
|
|
assert p.alertas
|
|
de_24h = [a.plazo_aviso == "24h" for a in p.alertas]
|
|
assert de_24h == sorted(de_24h, reverse=True) # todas las de 24 h antes que las demás
|
|
for grupo in (True, False):
|
|
vencen = [a.vence_el for a in p.alertas if (a.plazo_aviso == "24h") is grupo]
|
|
assert [v for v in vencen if v] == sorted(v for v in vencen if v)
|
|
for a in p.alertas:
|
|
assert a.vencida == (a.vence_el is not None and a.vence_el < hoy)
|
|
assert a.antiguedad_dias >= 0
|
|
|
|
|
|
def test_cada_numero_de_inicio_coincide_con_la_lista_a_la_que_lleva(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
with fabrica() as sesion: # una decisión y un cierre del mes, para que la evidencia no sea 0
|
|
audit.fijar_actor(sesion, "oficial", 1)
|
|
alerta = sesion.scalar(sa.select(Alerta).where(Alerta.estado == "nueva").limit(1))
|
|
servicio_alertas.cambiar_estado(
|
|
sesion, alerta.id, "cerrada", usuario="oficial", motivo="Sin inusualidad", rol="oficial"
|
|
)
|
|
sesion.commit()
|
|
entrar(cliente, Rol.OFICIAL)
|
|
cifras = _cifras(pagina(cliente, "/inicio"))
|
|
esperadas = {
|
|
"coincidencias", "alertas_24h", "alertas_otras", "sin_clasificacion",
|
|
"expediente_incompleto", "alertas_dictaminadas", "clientes_clasificados",
|
|
} # fmt: skip
|
|
assert esperadas <= set(cifras), esperadas - set(cifras)
|
|
for clave, (numero, enlace) in cifras.items():
|
|
if clave in ("aceptadas", "aviso"):
|
|
continue # el lote y el aviso tienen sus propias pruebas
|
|
assert _total_de_la_lista(cliente, enlace) == numero, (clave, enlace)
|
|
|
|
|
|
def test_sin_pendientes_dice_cuando_fue_el_ultimo_calculo(
|
|
cliente: TestClient, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
real = servicio_inicio.pendientes
|
|
|
|
def sin_nada(sesion, tenant, hoy=None):
|
|
calculo = real(sesion, tenant, hoy).ultimo_calculo
|
|
renglones = [
|
|
servicio_inicio.Pendiente(c, c, 0, "/") for c in servicio_inicio.ORDEN_PENDIENTES
|
|
]
|
|
return servicio_inicio.Pendientes(renglones, [], calculo)
|
|
|
|
monkeypatch.setattr(servicio_inicio, "pendientes", sin_nada)
|
|
entrar(cliente, Rol.OFICIAL)
|
|
texto = pagina(cliente, "/inicio")
|
|
assert "data-sin-pendientes>Sin pendientes · último cálculo " in texto
|
|
assert "data-pendiente-orden" not in texto
|
|
|
|
|
|
# --- Bloque 4 · evidencia y permisos -------------------------------------------------------------
|
|
|
|
|
|
def test_la_evidencia_del_anio(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.OFICIAL)
|
|
anio = pagina(cliente, "/inicio").split('data-evidencia="anio"')[1].split("</ul>")[0]
|
|
assert re.search(r"v2 · vigente desde el \d\d/\d\d/\d{4}", anio)
|
|
for clave in ("capacitacion", "conservacion"):
|
|
fila = anio.split(f'data-indicador="{clave}"')[1].split("</li>")[0]
|
|
assert "Sin registro" in fila, clave
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("rol", "ve_bitacora"), [(Rol.OFICIAL, True), (Rol.AUDITOR, True), (Rol.ANALISTA, False)]
|
|
)
|
|
def test_solo_quien_ve_el_audit_trail_ve_los_dictamenes(
|
|
cliente: TestClient, rol: Rol, ve_bitacora: bool
|
|
) -> None:
|
|
entrar(cliente, rol)
|
|
texto = pagina(cliente, "/inicio")
|
|
assert ('data-evidencia="mes"' in texto) is ve_bitacora
|
|
assert ("/auditoria?" in texto) is ve_bitacora
|
|
assert 'data-evidencia="anio"' in texto and 'data-pendiente-orden="coincidencias"' in texto
|
|
assert (cliente.get("/auditoria").status_code == 200) is ve_bitacora
|
|
|
|
|
|
# --- Empresa recién dada de alta -----------------------------------------------------------------
|
|
|
|
|
|
@pytest.fixture
|
|
def vacia(monkeypatch: pytest.MonkeyPatch, tmp_path) -> Iterator[TestClient]:
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
fabrica_vacia = crear_session_factory(engine)
|
|
monkeypatch.setattr("app.db.SessionLocal", fabrica_vacia)
|
|
monkeypatch.setattr(get_settings(), "data_dir", tmp_path)
|
|
with fabrica_vacia() as sesion:
|
|
sembrar(sesion, CONTRASENAS)
|
|
sesion.commit()
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
yield c
|
|
|
|
|
|
def test_el_estado_vacio_de_una_empresa_recien_dada_de_alta(
|
|
vacia: TestClient, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
_en(monkeypatch, date(2026, 12, 3))
|
|
entrar(vacia, Rol.OFICIAL)
|
|
texto = pagina(vacia, "/inicio")
|
|
for esperado in (
|
|
"Artículo 17, fracción IV · Sin regla de umbral de aviso vigente",
|
|
"Aviso de noviembre de 2026",
|
|
"Sin operaciones objeto de aviso: corresponde informe sin operaciones",
|
|
"fecha límite 17/12/2026",
|
|
"Información al —",
|
|
"Sin cargas por el módulo de carga de información",
|
|
"El aviso de noviembre no puede prepararse: no hay información cargada",
|
|
"Sin pendientes",
|
|
"Sin metodología vigente",
|
|
):
|
|
assert esperado in texto, esperado
|
|
assert "último cálculo" not in texto
|
|
assert all(n == 0 for n, _ in _cifras(texto).values())
|
|
assert "Sin regla de umbral de aviso vigente" in pagina(vacia, "/perfil-regulatorio")
|