feat(avisos): bloque 1 bis, hoja avisos de la plantilla, avisos históricos y alertas de aviso reportadas o anteriores a la operación de la plataforma
This commit is contained in:
1 parent
58e8cee702
commit
20ce2eebb2
20 files changed
+1132
-27
No files matched your search
@@ -0,0 +1,272 @@
|
||||
"""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-000000123",
|
||||
"fecha_presentacion": date(2025, 11, 14),
|
||||
"referencia_aviso": "A2025100000001",
|
||||
"id_credito": cr_a.id_credito,
|
||||
},
|
||||
{ # informe sin operaciones
|
||||
"periodo": "202601",
|
||||
"folio_acuse": "2026-000000001",
|
||||
"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-000000123"
|
||||
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].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-000000123" 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-000000123",
|
||||
"fecha_presentacion": date(2025, 11, 14),
|
||||
"referencia_aviso": "A2025100000001",
|
||||
"id_credito": cr["A"].id_credito,
|
||||
},
|
||||
{
|
||||
"periodo": "202510",
|
||||
"folio_acuse": "2025-000000123",
|
||||
"fecha_presentacion": date(2025, 11, 14),
|
||||
"referencia_aviso": "A2025100000001",
|
||||
"id_credito": cr["A"].id_credito,
|
||||
},
|
||||
{
|
||||
"periodo": "202613",
|
||||
"folio_acuse": "2026-000000009",
|
||||
"fecha_presentacion": date(2027, 1, 15),
|
||||
"referencia_aviso": "",
|
||||
"id_credito": "",
|
||||
},
|
||||
{
|
||||
"periodo": "202603",
|
||||
"folio_acuse": "2026-000000005",
|
||||
"fecha_presentacion": date(2026, 4, 15),
|
||||
"referencia_aviso": "",
|
||||
"id_credito": cr["B"].id_credito,
|
||||
},
|
||||
{
|
||||
"periodo": "202606",
|
||||
"folio_acuse": "2026-000000007",
|
||||
"fecha_presentacion": date(2026, 6, 30),
|
||||
"referencia_aviso": "",
|
||||
"id_credito": "",
|
||||
},
|
||||
{
|
||||
"periodo": "202604",
|
||||
"folio_acuse": "2026-000000006",
|
||||
"fecha_presentacion": date(2026, 5, 15),
|
||||
"referencia_aviso": "REF-1",
|
||||
"id_credito": cr["A"].id_credito,
|
||||
},
|
||||
{
|
||||
"periodo": "202607",
|
||||
"folio_acuse": "2026-000000008",
|
||||
"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
|
||||
@@ -294,3 +294,48 @@ def test_los_archivos_de_prueba_se_comportan_como_dice_la_guia(salida, entorno)
|
||||
assert "02_errores" in (
|
||||
Path(__file__).resolve().parents[1] / "docs" / "prueba_carga.md"
|
||||
).read_text("utf-8") # noqa: E501
|
||||
|
||||
|
||||
def test_la_hoja_avisos_cubre_la_historia_y_deja_abierto_solo_el_periodo_del_corte(
|
||||
salida, entorno
|
||||
) -> None:
|
||||
"""La empresa de la demo ya presentó sus avisos: la hoja `avisos` lista cada crédito igual o
|
||||
mayor al umbral dispuesto antes del mes del corte (más dos informes sin operaciones); al cargar,
|
||||
esas A-01 nacen cerradas, las no listadas anteriores al corte quedan históricas y en la bandeja
|
||||
solo quedan las del mes del corte."""
|
||||
import csv
|
||||
|
||||
from app.models import Aviso
|
||||
from app.models.alertas import ESTADO_HISTORICA
|
||||
|
||||
carpeta, _ = salida
|
||||
with (carpeta / "carga_inicial_2026-08-31_avisos.csv").open(encoding="utf-8-sig") as f:
|
||||
filas = list(csv.DictReader(f))
|
||||
assert filas and all(f["periodo"] < "202608" for f in filas)
|
||||
assert sum(1 for f in filas if not f["id_credito"]) == 2
|
||||
assert len({(f["periodo"], f["folio_acuse"]) for f in filas}) == len(
|
||||
{f["periodo"] for f in filas}
|
||||
)
|
||||
fabrica, tenant_id = entorno
|
||||
with sesion_de(fabrica, tenant_id) as sesion:
|
||||
cargar(sesion, carpeta / "carga_inicial_2026-08-31.xlsx")
|
||||
assert sesion.scalar(sa.select(sa.func.count(Aviso.id))) == len(
|
||||
{f["periodo"] for f in filas}
|
||||
)
|
||||
a01 = sesion.scalars(
|
||||
sa.select(Alerta)
|
||||
.join(ReglaAlerta, Alerta.regla_id == ReglaAlerta.id)
|
||||
.where(ReglaAlerta.clave == "A-01", Alerta.tenant_id == tenant_id)
|
||||
).all()
|
||||
por_estado: dict[str, int] = {}
|
||||
for a in a01:
|
||||
por_estado[a.estado] = por_estado.get(a.estado, 0) + 1
|
||||
periodo = str(a.evidencia["fecha_evento"])[:7].replace("-", "")
|
||||
if a.estado == "nueva":
|
||||
assert periodo == "202608", (a.id, periodo)
|
||||
else:
|
||||
assert periodo < "202608"
|
||||
assert por_estado.get("cerrada", 0) == len([f for f in filas if f["id_credito"]])
|
||||
# En la cartera chica de las pruebas puede no haber crédito ≥ umbral en el mes del corte
|
||||
# (ni A-01 sin reportar): lo que importa es que nada anterior al corte quede abierto.
|
||||
assert set(por_estado) <= {"nueva", "cerrada", ESTADO_HISTORICA}
|
||||
@@ -14,7 +14,7 @@ RAIZ = Path(__file__).resolve().parents[1]
|
||||
TABLAS_0001 = {"tenant", "usuario", "audit_trail"}
|
||||
TABLAS_0006 = {"identificacion"} # Fase 4: el head ya la incluye
|
||||
TABLAS_0012 = {"usuario_plataforma", "bitacora_plataforma", "invitacion"} # Pieza L
|
||||
TABLAS_0014 = {"equivalencia"} # Pieza N
|
||||
TABLAS_0014 = {"equivalencia", "aviso", "aviso_operacion"} # Pieza N
|
||||
TABLAS_0002 = {
|
||||
"cliente",
|
||||
"documento",
|
||||
|
||||
@@ -73,6 +73,8 @@ def test_upgrade_crea_identificacion_y_las_columnas_y_downgrade_las_quita(tmp_pa
|
||||
"usuario_plataforma",
|
||||
"bitacora_plataforma",
|
||||
"equivalencia",
|
||||
"aviso",
|
||||
"aviso_operacion",
|
||||
"invitacion",
|
||||
}
|
||||
tablas_base = set(sa.inspect(conn).get_table_names()) - {"alembic_version"}
|
||||
|
||||
@@ -64,6 +64,8 @@ def test_upgrade_anade_columnas_y_el_downgrade_las_quita(tmp_path) -> None:
|
||||
"usuario_plataforma",
|
||||
"bitacora_plataforma",
|
||||
"equivalencia",
|
||||
"aviso",
|
||||
"aviso_operacion",
|
||||
"invitacion",
|
||||
}
|
||||
tablas_base = set(sa.inspect(conn).get_table_names()) - {"alembic_version"}
|
||||
|
||||
@@ -62,12 +62,12 @@ def test_excel_y_csv_tienen_las_mismas_columnas_en_el_mismo_orden() -> None:
|
||||
esperado = {r.clave: list(r.encabezados) for r in GIRO.registros}
|
||||
assert _encabezados_xlsx(pl.plantilla_xlsx(GIRO)) == esperado
|
||||
assert _encabezados_zip(pl.plantilla_csv_zip(GIRO)) == esperado
|
||||
assert list(esperado) == ["clientes", "creditos", "pagos"]
|
||||
assert list(esperado) == ["clientes", "creditos", "pagos", "avisos"]
|
||||
|
||||
|
||||
def test_la_hoja_de_instrucciones_documenta_cada_columna() -> None:
|
||||
libro = _libro(pl.plantilla_xlsx(GIRO))
|
||||
assert libro.sheetnames == ["Instrucciones", "clientes", "creditos", "pagos"]
|
||||
assert libro.sheetnames == ["Instrucciones", "clientes", "creditos", "pagos", "avisos"]
|
||||
filas = [tuple(f) for f in libro["Instrucciones"].iter_rows(values_only=True)]
|
||||
texto = " ".join(str(v) for f in filas for v in f if v)
|
||||
for parte in ("AAAA-MM-DD", "sin separadores", "datos ficticios", "requerida por el sistema",
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.services import alertas as servicio_alertas
|
||||
from app.services import casos as servicio_casos
|
||||
from app.services import riesgo as servicio_riesgo
|
||||
from app.services import screening as servicio_screening
|
||||
from app.services.alertas import ESTADOS_ABIERTOS
|
||||
from seed import plantar_casos
|
||||
from seed.identidades_sinteticas import sembrar as sembrar_identidades
|
||||
from seed.usuarios_demo import sembrar
|
||||
@@ -83,7 +84,7 @@ def fabrica(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> sessionmaker[Ses
|
||||
cargar(fabrica)
|
||||
with _con_actor(fabrica) as sesion:
|
||||
abierta = sesion.scalar(
|
||||
sa.select(Alerta.id).where(Alerta.estado != "cerrada").order_by(Alerta.id)
|
||||
sa.select(Alerta.id).where(Alerta.estado.in_(ESTADOS_ABIERTOS)).order_by(Alerta.id)
|
||||
)
|
||||
servicio_casos.abrir_caso(sesion, [abierta], responsable="analista", usuario="pytest")
|
||||
sesion.commit()
|
||||
@@ -106,7 +107,9 @@ def _rutas(fabrica: sessionmaker[Session]) -> list[str]:
|
||||
alerta_id = uno(sa.select(Alerta.id).order_by(Alerta.id))
|
||||
# La primera alerta abierta ya está en el caso de la fixture: escalar otra.
|
||||
sin_caso_id = uno(
|
||||
sa.select(Alerta.id).where(Alerta.estado != "cerrada").order_by(Alerta.id.desc())
|
||||
sa.select(Alerta.id)
|
||||
.where(Alerta.estado.in_(ESTADOS_ABIERTOS))
|
||||
.order_by(Alerta.id.desc())
|
||||
)
|
||||
coincidencia_id = uno(sa.select(Coincidencia.id).order_by(Coincidencia.id))
|
||||
auditoria_id = uno(sa.select(AuditTrail.id).order_by(AuditTrail.id))
|
||||
|
||||
Reference in new issue
Block a user