274 lines
11 KiB
Python
274 lines
11 KiB
Python
"""Hoja `avisos` de la plantilla y alertas de aviso históricas (Pieza N, bloque 1 bis).
|
|
|
|
Una empresa que migra ya presentó avisos: lo que la hoja lista queda marcado como reportado
|
|
(alerta cerrada con el folio), lo anterior al periodo en curso que nadie reportó queda como
|
|
«anterior a la operación de la plataforma» (fuera de la bandeja) y el periodo en curso sigue
|
|
abierto. También: validaciones de la hoja y cascada contra créditos."""
|
|
|
|
from __future__ import annotations
|
|
|
|
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 import audit
|
|
from app.config import get_settings
|
|
from app.db import crear_engine, crear_session_factory
|
|
from app.importers.esquema_origen import (
|
|
RUTA_MODELO_V2,
|
|
RUTA_REGLAS_V2,
|
|
cargar_modelo,
|
|
cargar_reglas,
|
|
)
|
|
from app.importers.lists import importar_todas
|
|
from app.main import crear_app
|
|
from app.models import (
|
|
Alerta,
|
|
AuditTrail,
|
|
Aviso,
|
|
AvisoOperacion,
|
|
Base,
|
|
Credito,
|
|
ReglaAlerta,
|
|
Tenant,
|
|
)
|
|
from app.models.alertas import ESTADO_HISTORICA
|
|
from app.models.avisos import TIPO_NORMAL, TIPO_SIN_OPERACIONES
|
|
from app.models.usuario import Rol
|
|
from app.services import avisos as servicio_avisos
|
|
from app.services import operaciones as carga
|
|
from scripts import generar_carga_prueba as gen
|
|
from seed.usuarios_demo import sembrar
|
|
from tests.test_plataforma import CONTRASENAS, entrar_empresa
|
|
|
|
CORTE = date(2026, 8, 31)
|
|
USUARIO = "oficial"
|
|
|
|
|
|
@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)
|
|
monkeypatch.setattr(get_settings(), "data_dir", tmp_path / "data")
|
|
with fabrica() as sesion:
|
|
sembrar(sesion, CONTRASENAS)
|
|
tenant = sesion.scalar(sa.select(Tenant).where(Tenant.clave == "demo"))
|
|
cargar_modelo(sesion, tenant, RUTA_MODELO_V2, "pytest", CORTE)
|
|
cargar_reglas(sesion, tenant, RUTA_REGLAS_V2, "pytest", CORTE)
|
|
audit.fijar_actor(sesion, "pytest", tenant.id)
|
|
importar_todas(sesion, usuario="pytest")
|
|
sesion.commit()
|
|
return fabrica
|
|
|
|
|
|
@pytest.fixture
|
|
def cliente(fabrica) -> Iterator[TestClient]:
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
yield c
|
|
|
|
|
|
def _cartera() -> tuple[gen.Cartera, dict[str, gen.Credito]]:
|
|
"""Tres clientes con un crédito de $300,000 cada uno: A dispuesto hace diez meses, B hace
|
|
cinco y C en el mes del corte."""
|
|
g = gen.Generador(gen.Parametros(7, CORTE, 3, 3, 36, (70, 25, 5)))
|
|
clientes, creditos = [], {}
|
|
for clave, disposicion in (
|
|
("A", date(2025, 10, 10)),
|
|
("B", date(2026, 3, 5)),
|
|
("C", date(2026, 8, 12)),
|
|
):
|
|
c = g.nuevo_cliente("bajo", moral=False, hoy=CORTE)
|
|
cr = g.nuevo_credito(c, monto=Decimal(300000), plazo=36, disposicion=disposicion)
|
|
g.pagar(c, cr)
|
|
clientes.append(c)
|
|
creditos[clave] = cr
|
|
return gen.Cartera(clientes, list(creditos.values()), [], CORTE), creditos
|
|
|
|
|
|
def _archivo(tmp_path: Path, hojas: dict, nombre: str = "carga.xlsx") -> Path:
|
|
ruta = tmp_path / nombre
|
|
ruta.write_bytes(gen.xlsx_de(hojas))
|
|
return ruta
|
|
|
|
|
|
def _cargar(sesion: Session, tenant_id: int, ruta: Path, *, procesar: bool = True):
|
|
audit.fijar_actor(sesion, USUARIO, tenant_id)
|
|
lote, repetido = carga.preparar_carga(sesion, ruta, ruta.name, USUARIO)
|
|
assert not repetido
|
|
if procesar:
|
|
assert lote.estado == carga.PREPARADO, list(carga.rechazos(sesion, lote))[:5]
|
|
carga.confirmar_carga(sesion, lote.id, USUARIO)
|
|
sesion.commit()
|
|
lote = sesion.get(type(lote), lote.id)
|
|
carga.procesar_lote(sesion, lote, USUARIO)
|
|
sesion.commit()
|
|
return lote
|
|
|
|
|
|
def _alerta_a01(sesion: Session, id_credito: str) -> Alerta:
|
|
return sesion.scalar(
|
|
sa.select(Alerta)
|
|
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
|
.join(Credito, Credito.id == Alerta.credito_id)
|
|
.where(ReglaAlerta.clave == "A-01", Credito.id_externo == id_credito)
|
|
)
|
|
|
|
|
|
HOJA_AVISOS = lambda cr_a: [ # noqa: E731
|
|
{
|
|
"periodo": "202510",
|
|
"folio_acuse": "2025-123",
|
|
"fecha_presentacion": date(2025, 11, 14),
|
|
"referencia_aviso": "A2025100000001",
|
|
"id_credito": cr_a.id_credito,
|
|
},
|
|
{ # informe sin operaciones
|
|
"periodo": "202601",
|
|
"folio_acuse": "2026-1",
|
|
"fecha_presentacion": date(2026, 2, 16),
|
|
"referencia_aviso": "",
|
|
"id_credito": "",
|
|
},
|
|
]
|
|
|
|
|
|
def test_reportada_historica_y_abierta_segun_la_hoja_y_el_periodo_en_curso(
|
|
fabrica, tmp_path: Path, cliente: TestClient
|
|
) -> None:
|
|
cartera, cr = _cartera()
|
|
hojas = {**gen._filas(cartera), "avisos": HOJA_AVISOS(cr["A"])}
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant).where(Tenant.clave == "demo"))
|
|
lote = _cargar(sesion, tenant.id, _archivo(tmp_path, hojas))
|
|
assert lote.filas["avisos_historicos"] == 2 and lote.filas["creditos_reportados"] == 1
|
|
# Históricas: la A-01 de B y su A-02 (B está en la ventana de seis meses del corte).
|
|
assert lote.filas["alertas_de_aviso"] == {"reportadas": 1, "historicas": 2}
|
|
avisos = {a.periodo: a for a in sesion.scalars(sa.select(Aviso))}
|
|
assert avisos["202510"].tipo == TIPO_NORMAL and avisos["202510"].estado == "acusado"
|
|
assert avisos["202510"].folio_acuse == "2025-123"
|
|
assert avisos["202510"].fecha_limite == date(2025, 11, 17)
|
|
assert avisos["202601"].tipo == TIPO_SIN_OPERACIONES
|
|
operaciones = sesion.scalars(sa.select(AvisoOperacion)).all()
|
|
assert len(operaciones) == 1 and operaciones[0].referencia_aviso == "A2025100000001"
|
|
assert operaciones[0].folio_acuse == "2025-123" # el folio va por <aviso>
|
|
assert operaciones[0].monto == Decimal(300000)
|
|
# A: reportada (cerrada con el folio); B: histórica; C: abierta (periodo en curso).
|
|
a, b, c = (_alerta_a01(sesion, cr[k].id_credito) for k in "ABC")
|
|
assert a.estado == "cerrada" and b.estado == ESTADO_HISTORICA and c.estado == "nueva"
|
|
motivos = {
|
|
f.entidad_id: f.motivo
|
|
for f in sesion.scalars(sa.select(AuditTrail).where(AuditTrail.accion.like("estado:%")))
|
|
}
|
|
assert "acuse 2025-123" in motivos[a.id] and "202510" in motivos[a.id]
|
|
assert servicio_avisos.TEXTO_HISTORICA in motivos[b.id] and "202603" in motivos[b.id]
|
|
assert c.id not in motivos
|
|
reportados = servicio_avisos.creditos_reportados(sesion, tenant)
|
|
assert set(reportados) == {a.credito_id}
|
|
# Volver a cargar la hoja (con un pago nuevo para que el lote tenga algo que cargar) no
|
|
# duplica avisos ni revive alertas (misma firma).
|
|
pago_nuevo = gen.Pago(
|
|
cr["C"].id_credito, date(2026, 8, 20), Decimal(1000), "TRANSFERENCIA", "PAGO"
|
|
)
|
|
hojas2 = {**hojas, "pagos": [pago_nuevo.fila()]}
|
|
lote2 = _cargar(sesion, tenant.id, _archivo(tmp_path, hojas2, "otra.xlsx"))
|
|
assert lote2.filas["por_registro"]["avisos"][carga.EXISTENTE] == 2
|
|
assert sesion.scalar(sa.select(sa.func.count(Aviso.id))) == 2
|
|
assert _alerta_a01(sesion, cr["A"].id_credito).estado == "cerrada"
|
|
b_id, c_id = b.id, c.id
|
|
# Bandeja: la histórica no aparece por omisión; con el filtro sí, con su etiqueta larga.
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
html = cliente.get("/alertas").text
|
|
assert f"/alertas/{c_id}" in html and f"/alertas/{b_id}" not in html
|
|
html = cliente.get(f"/alertas?estado={ESTADO_HISTORICA}").text
|
|
assert f"/alertas/{b_id}" in html and f"/alertas/{c_id}" not in html
|
|
assert "Anterior a la operación de la plataforma" in html
|
|
assert f'data-estado="{ESTADO_HISTORICA}"' in html
|
|
|
|
|
|
def test_la_hoja_avisos_valida_y_cae_en_cascada(fabrica, tmp_path: Path) -> None:
|
|
cartera, cr = _cartera()
|
|
hojas = gen._filas(cartera)
|
|
hojas["creditos"][1]["monto"] = -5 # el crédito B se rechaza: cascada sobre su aviso
|
|
hojas["avisos"] = [
|
|
{
|
|
"periodo": "202510",
|
|
"folio_acuse": "2025-123",
|
|
"fecha_presentacion": date(2025, 11, 14),
|
|
"referencia_aviso": "A2025100000001",
|
|
"id_credito": cr["A"].id_credito,
|
|
},
|
|
{
|
|
"periodo": "202510",
|
|
"folio_acuse": "2025-123",
|
|
"fecha_presentacion": date(2025, 11, 14),
|
|
"referencia_aviso": "A2025100000001",
|
|
"id_credito": cr["A"].id_credito,
|
|
},
|
|
{
|
|
"periodo": "202613",
|
|
"folio_acuse": "2026-9",
|
|
"fecha_presentacion": date(2027, 1, 15),
|
|
"referencia_aviso": "",
|
|
"id_credito": "",
|
|
},
|
|
{
|
|
"periodo": "202603",
|
|
"folio_acuse": "2026-5",
|
|
"fecha_presentacion": date(2026, 4, 15),
|
|
"referencia_aviso": "",
|
|
"id_credito": cr["B"].id_credito,
|
|
},
|
|
{
|
|
"periodo": "202606",
|
|
"folio_acuse": "2026-7",
|
|
"fecha_presentacion": date(2026, 6, 30),
|
|
"referencia_aviso": "",
|
|
"id_credito": "",
|
|
},
|
|
{
|
|
"periodo": "202604",
|
|
"folio_acuse": "2026-6",
|
|
"fecha_presentacion": date(2026, 5, 15),
|
|
"referencia_aviso": "REF-1",
|
|
"id_credito": cr["A"].id_credito,
|
|
},
|
|
{
|
|
"periodo": "202607",
|
|
"folio_acuse": "2026-8",
|
|
"fecha_presentacion": date(2026, 8, 14),
|
|
"referencia_aviso": "",
|
|
"id_credito": "CR-NOPE",
|
|
},
|
|
{
|
|
"periodo": "202605",
|
|
"folio_acuse": "ab",
|
|
"fecha_presentacion": date(2026, 6, 15),
|
|
"referencia_aviso": "",
|
|
"id_credito": "",
|
|
},
|
|
]
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant).where(Tenant.clave == "demo"))
|
|
lote = _cargar(sesion, tenant.id, _archivo(tmp_path, hojas), procesar=False)
|
|
conteo = lote.filas["por_registro"]["avisos"]
|
|
assert conteo[carga.ACEPTADA] == 1 and conteo[carga.RECHAZADA] == 7
|
|
assert conteo["en_cascada"] == 1
|
|
textos = " | ".join(
|
|
motivo
|
|
for registro, _fila, _col, _val, motivo in carga.rechazos(sesion, lote)
|
|
if registro == "avisos"
|
|
)
|
|
assert "aviso repetido en el archivo" in textos
|
|
assert "el periodo debe ser AAAAMM" in textos
|
|
assert "depende de la fila" in textos and "de créditos, rechazada" in textos
|
|
assert "crédito inexistente" in textos and "solo letras" in textos
|
|
assert "de 6 a 20 letras" in textos and "posterior al mes reportado" in textos
|