111 lines
4.2 KiB
Python
111 lines
4.2 KiB
Python
"""El fixture de la carga incremental de la Pieza G (`operaciones_incremental.xlsx`, formato del
|
|
esquema de origen) convertido a la plantilla de carga del giro crédito (Pieza K).
|
|
|
|
Mismos datos: veinte pagos de septiembre de 2026 de créditos del fixture, el crédito nuevo (con
|
|
su enganche) para un cliente que se identifica por su `id_externo` (la cartera importada no trae
|
|
RFC) y, si se pide, la fila con el instrumento fuera de catálogo (`CHEQUE`). El titular `CUENTA`
|
|
del esquema, que la plantilla pública no tiene, se carga como `CLIENTE` (solo `TERCERO` dispara
|
|
B-06). Se genera en memoria; ningún dato real.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
from datetime import date, datetime
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from openpyxl import Workbook, load_workbook
|
|
|
|
from app.importers.esquema_origen import COLUMNAS_CARTERA, COLUMNAS_TRANSACCIONES, normalizar
|
|
from app.importers.plantillas import CREDITOS, PAGOS, texto_de
|
|
|
|
INCREMENTAL = Path(__file__).parent / "operaciones_incremental.xlsx"
|
|
ENCABEZADO_SINTETICO = "id cliente sintético"
|
|
|
|
|
|
def _tabla(hoja, fila_encabezados: int, columnas: dict[str, str]) -> list[dict[str, Any]]:
|
|
filas = list(hoja.iter_rows(values_only=True))
|
|
encabezados = [normalizar(e) for e in filas[fila_encabezados - 1]]
|
|
salida = []
|
|
for valores in filas[fila_encabezados:]:
|
|
if not valores or all(v is None for v in valores):
|
|
continue
|
|
salida.append(
|
|
{
|
|
columnas.get(e, e): v
|
|
for e, v in zip(encabezados, valores, strict=False)
|
|
if e and (e in columnas or e == normalizar(ENCABEZADO_SINTETICO))
|
|
}
|
|
)
|
|
return salida
|
|
|
|
|
|
def _fecha(valor: Any) -> str:
|
|
if isinstance(valor, datetime):
|
|
return valor.date().isoformat()
|
|
if isinstance(valor, date):
|
|
return valor.isoformat()
|
|
return texto_de(valor)
|
|
|
|
|
|
def filas_de_plantilla(*, con_fila_invalida: bool = False) -> dict[str, list[dict[str, Any]]]:
|
|
wb = load_workbook(INCREMENTAL, read_only=True, data_only=True)
|
|
transacciones = _tabla(wb["Transacciones"], 3, COLUMNAS_TRANSACCIONES)
|
|
cartera = _tabla(wb["Cartera"], 1, COLUMNAS_CARTERA)
|
|
wb.close()
|
|
creditos = [
|
|
{
|
|
"id_credito": texto_de(c["id_credito"]),
|
|
"rfc_cliente": c[normalizar(ENCABEZADO_SINTETICO)],
|
|
"producto": c.get("producto"),
|
|
"fecha_disposicion": _fecha(c.get("fecha_disposicion")),
|
|
"monto": c.get("monto"),
|
|
"plazo_meses": c.get("plazo_originacion"),
|
|
"mensualidad": c.get("pago_periodico_original"),
|
|
"estado": str(c.get("status")).upper(),
|
|
"pagos_vencidos": c.get("pagos_vencidos") or 0,
|
|
"enganche": c.get("enganche"),
|
|
"periodicidad": c.get("periodicidad"),
|
|
}
|
|
for c in cartera
|
|
]
|
|
pagos = []
|
|
for t in transacciones:
|
|
if t.get("metodo") == "CHEQUE" and not con_fila_invalida:
|
|
continue
|
|
titular = t.get("titular_origen")
|
|
pagos.append(
|
|
{
|
|
"id_credito": texto_de(t["id_credito"]),
|
|
"fecha_pago": _fecha(t["fecha_pago"]),
|
|
"monto": t["total"],
|
|
"instrumento": t.get("metodo"),
|
|
"tipo": t.get("tipo"),
|
|
"pagador": "CLIENTE" if titular in (None, "CUENTA") else titular,
|
|
"referencia": t.get("pago_id"),
|
|
}
|
|
)
|
|
return {"creditos": creditos, "pagos": pagos}
|
|
|
|
|
|
def xlsx(filas: dict[str, list[dict[str, Any]]]) -> bytes:
|
|
wb = Workbook()
|
|
wb.remove(wb.active)
|
|
for registro in (CREDITOS, PAGOS):
|
|
hoja = wb.create_sheet(registro.clave)
|
|
hoja.append(list(registro.encabezados))
|
|
for fila in filas.get(registro.clave, []):
|
|
hoja.append([fila.get(c) for c in registro.encabezados])
|
|
salida = io.BytesIO()
|
|
wb.save(salida)
|
|
return salida.getvalue()
|
|
|
|
|
|
@lru_cache(maxsize=2)
|
|
def bytes_plantilla(con_fila_invalida: bool = False) -> bytes:
|
|
"""El archivo de la plantilla (cacheado: openpyxl graba la hora al guardar y dos llamadas en
|
|
segundos distintos darían SHA-256 distintos)."""
|
|
return xlsx(filas_de_plantilla(con_fila_invalida=con_fila_invalida))
|