"""Lector mínimo del oráculo de alertas del fixture `esquema_mini.xlsx` (Pieza D). Provisional: se borra cuando llegue `tests/fixtures/oraculo.py` de la Pieza C, cuya estructura (`Oraculo`, `OraculoCliente`, `OraculoCredito`, `OraculoTransaccion`, `ids_en_base`) se imita aquí en lo que las alertas necesitan. Columnas-oráculo: Clientes AP–BB (alertas por cliente), Cartera AI–AK (por crédito) y Transacciones AA–AC (por transacción). Valores: "ALERTA" o vacío. """ from __future__ import annotations 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 / "fixtures" / "esquema_mini.xlsx" FILA_ENCABEZADOS = 3 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 nivel: str 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 pago_id: str alertas: frozenset[str] @dataclass(frozen=True) class Oraculo: uma: Decimal 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 _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(str(parametros["UMA"])), fecha_fin=_fecha(parametros["FECHA FIN"]) ) for n, fila in _datos(wb["Clientes"]): id_ = str(_celda(fila, "A")).strip() oraculo.clientes[id_] = OraculoCliente( id_fixture=id_, fila=n, 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(str(_celda(fila, "O"))), pago_id=str(_celda(fila, "P")).strip(), 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()