feat(cobranza): estado de cuenta PDF por cliente (Fase 4)
Botón '📄 Estado de cuenta' en cada cliente de la vista Cuentas abre GET /api/estado-cuenta.pdf?cliente=... — PDF ReportLab con dos secciones: SALDOS VIGENTES (subcuentas activas: capital, mora, abonado, saldo, total) y MOVIMIENTOS (últimos X de la bitácora, X = movimientos_visibles de la config o ?limite=N). Funciona también para clientes ya saldados (sin renglones, solo historial). Generador en src/services/estado_cuenta.py, tests validan el contenido extrayendo texto con pdfplumber. 136 tests en verde. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
8c35461761
commit
1649e2f732
4 files changed
+351
-6
No files matched your search
+52
-2
@@ -14,10 +14,17 @@ from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.responses import HTMLResponse, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.services import cobranza_acumulada, pagos, recordatorios, sheets, whatsapp
|
||||
from src.services import (
|
||||
cobranza_acumulada,
|
||||
estado_cuenta,
|
||||
pagos,
|
||||
recordatorios,
|
||||
sheets,
|
||||
whatsapp,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -505,6 +512,49 @@ async def movimientos(
|
||||
return {"movimientos": movs, "visibles": visibles}
|
||||
|
||||
|
||||
@router.get("/api/estado-cuenta.pdf")
|
||||
async def estado_cuenta_pdf(
|
||||
token: str = Query(...),
|
||||
cliente: str = Query(...),
|
||||
limite: int | None = Query(default=None, ge=1, le=cobranza_acumulada.MOV_MAX),
|
||||
):
|
||||
"""Estado de cuenta PDF de un cliente: saldos vigentes por subcuenta +
|
||||
últimos X movimientos de la bitácora (X = config `movimientos_visibles`
|
||||
o el `limite` pedido)."""
|
||||
numero = await _numero_token(token)
|
||||
objetivo = cobranza_acumulada._norm(cliente)
|
||||
renglones = [
|
||||
r for r in await cobranza_acumulada.listar(numero)
|
||||
if cobranza_acumulada._norm(r.get("cliente") or "") == objetivo
|
||||
]
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
visibles = (
|
||||
limite or cfg.get("movimientos_visibles")
|
||||
or cobranza_acumulada.MOV_DEFAULT_VISIBLES
|
||||
)
|
||||
movs = await cobranza_acumulada.obtener_movimientos(
|
||||
numero, cliente=cliente, limite=visibles,
|
||||
)
|
||||
if not renglones and not movs:
|
||||
raise HTTPException(status_code=404, detail="Sin datos de ese cliente")
|
||||
nombre = renglones[0].get("cliente") if renglones else (
|
||||
movs[0].get("cliente") or cliente
|
||||
)
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente=nombre, renglones=renglones, movimientos=movs,
|
||||
visibles=visibles,
|
||||
)
|
||||
slug = re.sub(r"[^A-Za-z0-9]+", "-", cliente).strip("-").lower() or "cliente"
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition":
|
||||
f'inline; filename="estado-cuenta-{slug}.pdf"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.put("/api/renglon")
|
||||
async def editar(body: RenglonEditBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
Estado de cuenta en PDF (ReportLab) para un cliente de cobranza.
|
||||
|
||||
Dos secciones:
|
||||
1. SALDOS VIGENTES — las subcuentas activas del cliente (renglones ya
|
||||
decorados por `cobranza_acumulada.listar`): capital, mora, abonado
|
||||
y saldo, con total.
|
||||
2. MOVIMIENTOS — los últimos X de la bitácora (`cobranza_mov`), más
|
||||
recientes primero. X es `movimientos_visibles` de la config global
|
||||
(el mismo de la pestaña Mensaje), o el `limite` pedido.
|
||||
|
||||
No consulta nada: recibe datos ya cargados y devuelve bytes del PDF.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.platypus import (
|
||||
Paragraph,
|
||||
SimpleDocTemplate,
|
||||
Spacer,
|
||||
Table,
|
||||
TableStyle,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MEXICO = ZoneInfo("America/Mexico_City")
|
||||
|
||||
_ACCENT = colors.HexColor("#0e7c66") # verde WK del panel
|
||||
_GRIS = colors.HexColor("#586173")
|
||||
_LINEA = colors.HexColor("#d4dae4")
|
||||
_FILA_ALT = colors.HexColor("#f4f6fa")
|
||||
|
||||
_TIPO_LABEL = {"renta": "Renta mensual", "extra": "Extraordinaria",
|
||||
"vr": "Valor residual"}
|
||||
|
||||
_MOV_LABEL = {"abono": "Abono", "saldado": "Saldado",
|
||||
"saldo_periodo": "Mes saldado"}
|
||||
|
||||
|
||||
def _money(x: float) -> str:
|
||||
return f"${float(x or 0.0):,.2f}"
|
||||
|
||||
|
||||
def _fecha_es(iso: str) -> str:
|
||||
"""'2026-08-04' → '04/08/2026' (best-effort)."""
|
||||
s = (iso or "")[:10]
|
||||
partes = s.split("-")
|
||||
if len(partes) == 3:
|
||||
return f"{partes[2]}/{partes[1]}/{partes[0]}"
|
||||
return s
|
||||
|
||||
|
||||
def _tipo_label(r: dict) -> str:
|
||||
tipo = r.get("tipo") or "renta"
|
||||
if tipo == "otro":
|
||||
return r.get("etiqueta") or "Otro"
|
||||
return _TIPO_LABEL.get(tipo, tipo)
|
||||
|
||||
|
||||
def _estilo(nombre: str, **kw) -> ParagraphStyle:
|
||||
base = {"fontName": "Helvetica", "fontSize": 9.5, "leading": 12,
|
||||
"textColor": colors.HexColor("#131922")}
|
||||
base.update(kw)
|
||||
return ParagraphStyle(nombre, **base)
|
||||
|
||||
|
||||
def generar_pdf(
|
||||
cliente: str,
|
||||
renglones: list[dict],
|
||||
movimientos: list[dict],
|
||||
visibles: int,
|
||||
) -> bytes:
|
||||
"""Genera el PDF del estado de cuenta. `renglones` ya vienen decorados
|
||||
(saldo/capital/moratorio/abonado) y filtrados por cliente; `movimientos`
|
||||
ya vienen filtrados y limitados (más recientes primero)."""
|
||||
buf = BytesIO()
|
||||
doc = SimpleDocTemplate(
|
||||
buf, pagesize=letter,
|
||||
leftMargin=18 * mm, rightMargin=18 * mm,
|
||||
topMargin=16 * mm, bottomMargin=16 * mm,
|
||||
title=f"Estado de cuenta — {cliente}",
|
||||
)
|
||||
st_titulo = _estilo("titulo", fontName="Helvetica-Bold", fontSize=15,
|
||||
leading=18, textColor=_ACCENT)
|
||||
st_sub = _estilo("sub", fontSize=9.5, textColor=_GRIS)
|
||||
st_seccion = _estilo("seccion", fontName="Helvetica-Bold", fontSize=10.5,
|
||||
leading=13, spaceBefore=6)
|
||||
st_celda = _estilo("celda")
|
||||
st_celda_b = _estilo("celda_b", fontName="Helvetica-Bold")
|
||||
|
||||
ahora = datetime.now(MEXICO)
|
||||
story = [
|
||||
Paragraph("WK FINANCING SOLUTIONS", st_titulo),
|
||||
Paragraph("ESTADO DE CUENTA", st_seccion),
|
||||
Spacer(1, 3 * mm),
|
||||
Paragraph(f"Cliente: <b>{cliente}</b>", st_celda),
|
||||
Paragraph(
|
||||
f"Fecha de corte: {ahora.strftime('%d/%m/%Y %H:%M')} "
|
||||
"(hora del centro de México)", st_sub,
|
||||
),
|
||||
Spacer(1, 6 * mm),
|
||||
]
|
||||
|
||||
# ── 1. Saldos vigentes ──────────────────────────────────────
|
||||
story.append(Paragraph("SALDOS VIGENTES", st_seccion))
|
||||
story.append(Spacer(1, 2 * mm))
|
||||
if renglones:
|
||||
head = ["Subcuenta", "Concepto", "Capital", "Mora", "Abonado", "Saldo"]
|
||||
filas = [head]
|
||||
total = 0.0
|
||||
for r in renglones:
|
||||
saldo = float(r.get("saldo") or 0.0)
|
||||
total += saldo
|
||||
filas.append([
|
||||
Paragraph(str(r.get("vehiculo") or ""), st_celda),
|
||||
Paragraph(_tipo_label(r), st_celda),
|
||||
_money(r.get("capital")),
|
||||
_money(r.get("moratorio")),
|
||||
_money(r.get("abonado")),
|
||||
_money(saldo),
|
||||
])
|
||||
filas.append(["", "", "", "", Paragraph("TOTAL", st_celda_b),
|
||||
_money(total)])
|
||||
t = Table(filas, colWidths=[42 * mm, 34 * mm, None, None, None, None],
|
||||
repeatRows=1)
|
||||
t.setStyle(TableStyle([
|
||||
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 8.5),
|
||||
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
|
||||
("BACKGROUND", (0, 0), (-1, 0), _ACCENT),
|
||||
("ALIGN", (2, 0), (-1, -1), "RIGHT"),
|
||||
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -2), [colors.white, _FILA_ALT]),
|
||||
("LINEBELOW", (0, 0), (-1, -2), 0.4, _LINEA),
|
||||
("FONTNAME", (0, -1), (-1, -1), "Helvetica-Bold"),
|
||||
("LINEABOVE", (0, -1), (-1, -1), 0.9, _ACCENT),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
]))
|
||||
story.append(t)
|
||||
else:
|
||||
story.append(Paragraph(
|
||||
"Sin saldos vigentes: el cliente no tiene subcuentas activas.",
|
||||
st_sub,
|
||||
))
|
||||
story.append(Spacer(1, 7 * mm))
|
||||
|
||||
# ── 2. Movimientos ──────────────────────────────────────────
|
||||
story.append(Paragraph(
|
||||
f"MOVIMIENTOS (últimos {visibles})", st_seccion,
|
||||
))
|
||||
story.append(Spacer(1, 2 * mm))
|
||||
if movimientos:
|
||||
filas = [["Fecha", "Subcuenta", "Movimiento", "Nota", "Monto"]]
|
||||
for m in movimientos:
|
||||
sub = f"{m.get('vehiculo') or ''} · {_tipo_label(m)}"
|
||||
filas.append([
|
||||
_fecha_es(m.get("fecha") or ""),
|
||||
Paragraph(sub, st_celda),
|
||||
_MOV_LABEL.get(m.get("movimiento") or "", m.get("movimiento") or ""),
|
||||
Paragraph(str(m.get("nota") or ""), st_celda),
|
||||
_money(m.get("monto")),
|
||||
])
|
||||
t = Table(filas, colWidths=[20 * mm, 52 * mm, 24 * mm, None, 24 * mm],
|
||||
repeatRows=1)
|
||||
t.setStyle(TableStyle([
|
||||
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 8.5),
|
||||
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
|
||||
("BACKGROUND", (0, 0), (-1, 0), _ACCENT),
|
||||
("ALIGN", (-1, 0), (-1, -1), "RIGHT"),
|
||||
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, _FILA_ALT]),
|
||||
("LINEBELOW", (0, 0), (-1, -1), 0.4, _LINEA),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
]))
|
||||
story.append(t)
|
||||
else:
|
||||
story.append(Paragraph(
|
||||
"Sin movimientos registrados en la bitácora.", st_sub,
|
||||
))
|
||||
|
||||
story.append(Spacer(1, 8 * mm))
|
||||
story.append(Paragraph(
|
||||
"La mora se calcula al día de corte; el saldo puede variar después "
|
||||
"de esta fecha. Documento informativo, no comprobante fiscal.",
|
||||
_estilo("pie", fontSize=7.5, textColor=_GRIS),
|
||||
))
|
||||
|
||||
doc.build(story)
|
||||
return buf.getvalue()
|
||||
Reference in new issue
Block a user