Inicio decía «1,030 clientes con documentos pendientes» en una cartera recién cargada: la plantilla de carga no trae documentos, y ese número mezclaba no haber cargado ninguno con tener uno vencido. Ahora son dos renglones, cada uno con su lista en /expediente: - «Clientes sin documentos cargados» (?documentos=sin_cargar); - «Clientes con documentos vencidos o por completar» (?documentos=por_actualizar): ya tienen documentos, pero alguno obligatorio falta, venció o quedó desactualizado. La regla de completitud no cambia y nada se da por presente: los dos números suman el de antes (?documentos=1 sigue listando a todos).
564 lines
24 KiB
Python
564 lines
24 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, timedelta
|
|
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, fechas
|
|
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, Documento, 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)),
|
|
# el 17 de enero de 2027 es domingo: la fecha límite legal es el lunes 18
|
|
(date(2027, 1, 1), date(2026, 12, 1), date(2026, 12, 31), date(2027, 1, 18)),
|
|
(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_las_operaciones_del_periodo_del_hecho(
|
|
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)
|
|
)
|
|
en_bandeja = sesion.scalar(
|
|
sa.select(sa.func.count(Alerta.id)).where(
|
|
Alerta.plazo_aviso == "aviso", Alerta.vence_el == limite
|
|
)
|
|
)
|
|
# Operaciones objeto de aviso: créditos distintos (A-01 y A-02 pueden coincidir), sin E-01.
|
|
esperadas = sesion.scalar(
|
|
sa.select(sa.func.count(sa.func.distinct(Alerta.credito_id)))
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.where(
|
|
Alerta.plazo_aviso == "aviso",
|
|
Alerta.vence_el == limite,
|
|
Alerta.credito_id.is_not(None),
|
|
ReglaAlerta.clave != "E-01",
|
|
)
|
|
)
|
|
assert 0 < esperadas <= en_bandeja
|
|
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]
|
|
# Pieza N: el número lleva a la preparación del aviso del periodo, que cuenta por el periodo
|
|
# del hecho (no por el vencimiento: una carga cuenta el plazo desde el corte).
|
|
periodo = f"{limite.replace(day=1) - timedelta(days=1):%Y%m}"
|
|
assert f'href="/avisos/{periodo}"' in fila
|
|
assert f"{esperadas:,} operaci" in fila and f"fecha límite {limite:%d/%m/%Y}" in fila
|
|
assert f"faltan {(limite - hoy).days} días" in fila
|
|
enlace = f"/alertas?plazo=aviso&vence_el={limite.isoformat()}"
|
|
assert _total_bandeja(cliente, enlace) == en_bandeja # la bandeja sigue filtrando por plazo
|
|
|
|
|
|
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
|
|
assert "facilidad del sexto dígito" not in fila # la demo no tiene RFC
|
|
|
|
|
|
def test_la_fecha_limite_salta_el_dia_inhabil_y_muestra_la_facilidad_del_sexto_digito(
|
|
cliente: TestClient, fabrica: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
# 17 de enero de 2027 es domingo: la fecha legal es el lunes 18. Con RFC cuyo sexto dígito es
|
|
# 2 (un día hábil más), la facilidad da el martes 19.
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
tenant.rfc = "FAD200102AB1"
|
|
sesion.commit()
|
|
_en(monkeypatch, date(2027, 1, 20))
|
|
entrar(cliente, Rol.OFICIAL)
|
|
fila = pagina(cliente, "/inicio").split('data-renglon="aviso"')[1].split("</li>")[0]
|
|
assert "fecha límite 18/01/2027" in fila
|
|
assert "con la facilidad del sexto dígito del RFC: 19/01/2027" in fila
|
|
assert "venció hace 2 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"Corte del periodo: {al:%d/%m/%Y}" in texto
|
|
assert (
|
|
f"El aviso de mayo no puede prepararse: el corte del periodo es el {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 datos del expediente incompletos|sin documentos cargados"
|
|
r"|con documentos (?:pendientes|vencidos o por completar))",
|
|
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 = fechas.hoy() # las alertas se crean hoy: una fecha fija haría negativa la antigüedad
|
|
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"
|
|
)
|
|
# Un cliente con un documento cargado y los demás por completar, para que los dos
|
|
# renglones de documentos tengan número.
|
|
sesion.add(
|
|
Documento(
|
|
tenant_id=1, created_by="pytest", cliente_id=alerta.cliente_id,
|
|
tipo="comprobante_domicilio", version=1, fecha_emision=date(2026, 8, 1),
|
|
ruta="documentos/x.pdf", sha256="0" * 64, nombre_original="x.pdf",
|
|
)
|
|
) # fmt: skip
|
|
sesion.commit()
|
|
entrar(cliente, Rol.OFICIAL)
|
|
cifras = _cifras(pagina(cliente, "/inicio"))
|
|
esperadas = {
|
|
"coincidencias", "alertas_24h", "alertas_otras", "sin_clasificacion",
|
|
"expediente_incompleto", "sin_documentos", "documentos_por_actualizar",
|
|
"alertas_dictaminadas",
|
|
"alertas_cerradas_por_carga", "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",
|
|
"Corte del periodo: —",
|
|
"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")
|
|
|
|
|
|
def test_la_evidencia_del_mes_no_cuenta_lo_de_una_cartera_que_ya_se_vacio(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
"""El audit trail nunca se borra: después de vaciar la empresa conserva los cierres y las
|
|
decisiones de la cartera anterior. Inicio habla de la cartera vigente: cuenta lo posterior al
|
|
último vaciado, y la lista a la que lleva cada número aplica el mismo filtro."""
|
|
from datetime import timedelta
|
|
|
|
from app.models import AuditTrail, ahora_utc
|
|
from app.services.avisos import MOTIVO_REPORTADA
|
|
|
|
def fila(accion: str, entidad: str, motivo: str, minutos: int) -> None:
|
|
with fabrica() as sesion:
|
|
sesion.add(
|
|
AuditTrail(
|
|
tenant_id=1, created_by="oficial", usuario="oficial", entidad=entidad,
|
|
entidad_id=1, accion=accion,
|
|
motivo=motivo, fecha=ahora_utc() - timedelta(minutes=minutos),
|
|
)
|
|
) # fmt: skip
|
|
sesion.commit()
|
|
|
|
reportada = f"{MOTIVO_REPORTADA} 202609, acuse 2026-9 (lote 1)"
|
|
for _ in range(3): # tres cierres de la carga de la cartera anterior
|
|
fila("estado:cerrada", "alerta", reportada, 30)
|
|
fila("vaciar_empresa", "tenant", "Vaciado de empresa de prueba", 20)
|
|
for _ in range(2): # dos de la cartera vigente
|
|
fila("estado:cerrada", "alerta", reportada, 10)
|
|
entrar(cliente, Rol.OFICIAL)
|
|
numero, enlace = _cifras(pagina(cliente, "/inicio"))["alertas_cerradas_por_carga"]
|
|
assert numero == 2 and "cartera_vigente=1" in enlace
|
|
assert _total_de_la_lista(cliente, enlace) == 2
|
|
assert "posterior al último vaciado" in pagina(cliente, enlace)
|
|
# Sin el filtro, la bitácora completa sigue ahí: nada se borró.
|
|
assert _total_de_la_lista(cliente, enlace.replace("cartera_vigente=1", "")) == 5
|
|
|
|
|
|
def test_inicio_distingue_el_corte_del_periodo_de_la_ultima_operacion_cargada(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
"""Una carga del mes en curso trae operaciones posteriores al corte: Inicio dice las dos
|
|
fechas, y que esas operaciones cuentan en los acumulados al cerrar el periodo."""
|
|
from app.models import Credito, Transaccion
|
|
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
corte = tenant.fecha_corte
|
|
ultima = servicio_inicio.ultima_operacion(sesion, tenant)
|
|
assert ultima is not None and ultima <= corte
|
|
entrar(cliente, Rol.OFICIAL)
|
|
texto = pagina(cliente, "/inicio")
|
|
assert f"Corte del periodo: {corte:%d/%m/%Y}" in texto
|
|
assert f"Última operación cargada: {ultima:%d/%m/%Y}" in texto
|
|
assert "posterior al corte" not in texto
|
|
with fabrica() as sesion: # un pago después del corte, como el de una carga del mes en curso
|
|
credito = sesion.scalar(sa.select(Credito).limit(1))
|
|
despues = corte + timedelta(days=12)
|
|
sesion.add(
|
|
Transaccion(
|
|
tenant_id=credito.tenant_id, created_by="pytest", credito_id=credito.id,
|
|
fecha_pago=despues, total=Decimal("1000"), tipo="PAGO", metodo="TRANSFERENCIA",
|
|
)
|
|
) # fmt: skip
|
|
sesion.commit()
|
|
texto = pagina(cliente, "/inicio")
|
|
assert f"Corte del periodo: {corte:%d/%m/%Y}" in texto
|
|
assert (
|
|
f"Última operación cargada: {despues:%d/%m/%Y} (posterior al corte: cuenta en los "
|
|
"acumulados al cerrar el periodo)" in texto
|
|
)
|