feat(engine): agregados de ventana con paridad contra el Excel

engine/aggregates.py calcula las columnas J–T de la hoja Clientes con la semántica deducida de las fórmulas del Excel de CHM. tests/fixtures/oraculo.py es el único lector de las columnas calculadas del fixture (agregados, indicadores, puntaje, nivel y alertas por cliente, crédito y transacción).
This commit is contained in:
Jorem Juárez committed 2026-10-06 19:13:18 -06:00
1 parent 65fecc4a49
commit 0a2edb482e
2 files changed
+349 -2

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
"""Oráculo del test de paridad: lo que calculó el Excel de CHM para el fixture `esquema_mini.xlsx`.
Único punto de lectura de las columnas calculadas del fixture (Piezas C y D):
- Clientes: J–T (agregados de `agregado_cliente`), AC–AL (impacto por indicador), AM (puntaje),
AN (nivel) y AP–BB (alertas por cliente).
- Cartera: AI–AK (alertas por crédito: A-01, A-02, B-08).
- Transacciones: AA–AC (alertas por transacción: B-06, C-03, D-04).
Los identificadores son los del fixture. Al importar, el cliente recibe un `id_externo` nuevo
(hash con la sal de la importación): `ids_en_base(sal)` da la traducción. El crédito conserva su
`id_externo`.
"""
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from functools import lru_cache
from pathlib import Path
from typing import Any
from openpyxl import load_workbook
from openpyxl.utils import column_index_from_string
FIXTURE = Path(__file__).parent / "esquema_mini.xlsx"
FILA_ENCABEZADOS = 3
# Columna del Excel → campo de `agregado_cliente`.
COLUMNAS_AGREGADOS = {
"J": "num_creditos_total",
"K": "suma_acumulada",
"L": "monto_promedio",
"M": "suma_cuotas",
"N": "capacidad_pago",
"O": "pct_transferencia",
"P": "pct_pagos_atipicos",
"Q": "acumulado_ventana",
"R": "num_creditos_ventana",
"S": "acumulado_creditos_ventana",
"T": "pagos_ultimo_mes",
}
ENTEROS = {"num_creditos_total", "num_creditos_ventana"}
COLUMNAS_INDICADORES = {
"AC": "P1",
"AD": "C1",
"AE": "C2",
"AF": "C3",
"AG": "C4",
"AH": "C5",
"AI": "G1",
"AJ": "T1",
"AK": "T2",
"AL": "T3",
}
COLUMNAS_ALERTAS_CLIENTE = {
"AP": "B-01",
"AQ": "B-02",
"AR": "B-03",
"AS": "B-04",
"AT": "B-06",
"AU": "C-01",
"AV": "C-02",
"AW": "D-01",
"AX": "D-02",
"AY": "D-03",
"AZ": "D-05",
"BA": "E-01",
"BB": "E-02",
}
COLUMNAS_ALERTAS_CREDITO = {"AI": "A-01", "AJ": "A-02", "AK": "B-08"}
COLUMNAS_ALERTAS_TRANSACCION = {"AA": "B-06", "AB": "C-03", "AC": "D-04"}
@dataclass(frozen=True)
class OraculoCliente:
id_fixture: str
fila: int
agregados: dict[str, Decimal | int]
impactos: dict[str, int] # clave de indicador → impacto (10, 50, 100)
puntaje: Decimal
nivel: str # bajo | medio | alto
alertas: frozenset[str]
@dataclass(frozen=True)
class OraculoCredito:
id_credito: str
id_cliente_fixture: str
fila: int
alertas: frozenset[str]
@dataclass(frozen=True)
class OraculoTransaccion:
id_credito: str
id_cliente_fixture: str
fila: int
fecha_pago: date
total: Decimal
alertas: frozenset[str]
@dataclass(frozen=True)
class Oraculo:
uma: Decimal
fecha_inicio: date
fecha_fin: date
clientes: dict[str, OraculoCliente] = field(default_factory=dict)
creditos: dict[str, OraculoCredito] = field(default_factory=dict)
transacciones: list[OraculoTransaccion] = field(default_factory=list)
def _celda(fila: tuple, columna: str) -> Any:
i = column_index_from_string(columna) - 1
return fila[i] if i < len(fila) else None
def _fecha(valor: Any) -> date:
return valor.date() if isinstance(valor, datetime) else valor
def _decimal(valor: Any) -> Decimal:
return Decimal(str(valor if valor not in (None, "") else 0))
def _alertas(fila: tuple, columnas: dict[str, str]) -> frozenset[str]:
return frozenset(
regla
for columna, regla in columnas.items()
if str(_celda(fila, columna) or "").strip().upper() == "ALERTA"
)
def _datos(ws) -> list[tuple[int, tuple]]:
return [
(n, fila)
for n, fila in enumerate(ws.iter_rows(values_only=True), start=1)
if n > FILA_ENCABEZADOS and fila and fila[0] not in (None, "")
]
@lru_cache
def leer_oraculo(ruta: Path = FIXTURE) -> Oraculo:
wb = load_workbook(ruta, read_only=True, data_only=True)
try:
parametros = {
str(f[1]).strip(): f[2]
for f in wb["Parámetros"].iter_rows(values_only=True)
if f and len(f) > 2 and f[1]
}
oraculo = Oraculo(
uma=_decimal(parametros["UMA"]),
fecha_inicio=_fecha(parametros["FECHA INICIO"]),
fecha_fin=_fecha(parametros["FECHA FIN"]),
)
for n, fila in _datos(wb["Clientes"]):
id_ = str(_celda(fila, "A")).strip()
agregados: dict[str, Decimal | int] = {}
for columna, campo in COLUMNAS_AGREGADOS.items():
valor = _decimal(_celda(fila, columna))
agregados[campo] = int(valor) if campo in ENTEROS else valor
oraculo.clientes[id_] = OraculoCliente(
id_fixture=id_,
fila=n,
agregados=agregados,
impactos={
clave: int(_celda(fila, columna))
for columna, clave in COLUMNAS_INDICADORES.items()
},
puntaje=_decimal(_celda(fila, "AM")),
nivel=str(_celda(fila, "AN")).strip().lower(),
alertas=_alertas(fila, COLUMNAS_ALERTAS_CLIENTE),
)
for n, fila in _datos(wb["Cartera"]):
id_credito = str(_celda(fila, "A")).strip()
oraculo.creditos[id_credito] = OraculoCredito(
id_credito=id_credito,
id_cliente_fixture=str(_celda(fila, "B")).strip(),
fila=n,
alertas=_alertas(fila, COLUMNAS_ALERTAS_CREDITO),
)
for n, fila in _datos(wb["Transacciones"]):
oraculo.transacciones.append(
OraculoTransaccion(
id_credito=str(_celda(fila, "A")).strip(),
id_cliente_fixture=str(_celda(fila, "B")).strip(),
fila=n,
fecha_pago=_fecha(_celda(fila, "C")),
total=_decimal(_celda(fila, "O")),
alertas=_alertas(fila, COLUMNAS_ALERTAS_TRANSACCION),
)
)
return oraculo
finally:
wb.close()
def ids_en_base(sal: str, ruta: Path = FIXTURE) -> dict[str, str]:
"""id del cliente en el fixture → `cliente.id_externo` tras importar con esa sal."""
from app.importers.anonymize import Anonimizador
anon = Anonimizador(sal)
try:
return {id_: anon.id_sintetico(id_) for id_ in leer_oraculo(ruta).clientes}
finally:
anon.descartar()