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()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
Estado de cuenta PDF: saldos vigentes por subcuenta + últimos X
|
||||
movimientos de la bitácora. Validamos el contenido extrayendo el texto
|
||||
con pdfplumber.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
import pdfplumber
|
||||
|
||||
from src.services import estado_cuenta
|
||||
|
||||
RENGLONES = [
|
||||
{"tipo": "renta", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"capital": 20000.0, "moratorio": 312.40, "abonado": 6000.0,
|
||||
"saldo": 14312.40},
|
||||
{"tipo": "vr", "cliente": "GRUPO MEENT", "vehiculo": "EXCAVADORA",
|
||||
"capital": 171572.70, "moratorio": 201.76, "abonado": 0.0,
|
||||
"saldo": 171774.46},
|
||||
]
|
||||
|
||||
MOVIMIENTOS = [
|
||||
{"fecha": "2026-08-01", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"tipo": "renta", "movimiento": "abono", "monto": 6000.0,
|
||||
"nota": "transferencia BBVA"},
|
||||
{"fecha": "2026-07-15", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"tipo": "renta", "movimiento": "saldo_periodo", "monto": 10000.0,
|
||||
"nota": "mes 2026-06"},
|
||||
]
|
||||
|
||||
|
||||
def _texto(pdf_bytes: bytes) -> str:
|
||||
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
|
||||
return "\n".join(p.extract_text() or "" for p in pdf.pages)
|
||||
|
||||
|
||||
def test_pdf_contiene_saldos_y_movimientos():
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="GRUPO MEENT", renglones=RENGLONES,
|
||||
movimientos=MOVIMIENTOS, visibles=10,
|
||||
)
|
||||
assert pdf.startswith(b"%PDF")
|
||||
txt = _texto(pdf)
|
||||
assert "ESTADO DE CUENTA" in txt
|
||||
assert "GRUPO MEENT" in txt
|
||||
# Saldos vigentes: subcuentas, montos y total.
|
||||
assert "HILUX" in txt and "EXCAVADORA" in txt
|
||||
assert "Renta mensual" in txt and "Valor residual" in txt
|
||||
assert "$14,312.40" in txt and "$171,774.46" in txt
|
||||
assert "$186,086.86" in txt # TOTAL = suma de saldos
|
||||
# Movimientos: fecha, etiqueta y nota.
|
||||
assert "MOVIMIENTOS" in txt and "01/08/2026" in txt
|
||||
assert "Abono" in txt and "Mes saldado" in txt
|
||||
assert "transferencia BBVA" in txt
|
||||
assert "$6,000.00" in txt
|
||||
|
||||
|
||||
def test_pdf_sin_renglones_ni_movs_avisa():
|
||||
# Cliente saldado por completo: sin subcuentas activas ni bitácora aún.
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=[], movimientos=[], visibles=10,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
assert "Sin saldos vigentes" in txt
|
||||
assert "Sin movimientos registrados" in txt
|
||||
|
||||
|
||||
def test_pdf_solo_movimientos_de_cliente_saldado():
|
||||
# El renglón se borró al saldarse, pero la bitácora sobrevive: el
|
||||
# estado de cuenta sigue mostrando el historial.
|
||||
movs = [{"fecha": "2026-08-01", "cliente": "ACME", "vehiculo": "GT3",
|
||||
"tipo": "vr", "movimiento": "saldado", "monto": 500000.0,
|
||||
"nota": "pago total"}]
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=[], movimientos=movs, visibles=5,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
assert "Sin saldos vigentes" in txt
|
||||
assert "Saldado" in txt and "$500,000.00" in txt
|
||||
assert "(últimos 5)" in txt
|
||||
+17
-4
@@ -220,7 +220,10 @@
|
||||
.cta-tot { flex: 0 0 auto; text-align: right; font-family: 'Space Grotesk', sans-serif; font-size: 17px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.3px; }
|
||||
.cta-mora { font-family: 'DM Sans', sans-serif; font-size: 10px; font-weight: 600; color: var(--warning); margin-top: 1px; }
|
||||
.cta-body { border-top: 1px solid var(--line); padding: 0.85rem 1rem 1rem; background: var(--surface-2); }
|
||||
.cta-seltodo { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--text-secondary); cursor: pointer; margin-bottom: 10px; }
|
||||
.cta-tools { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; gap: 8px; }
|
||||
.cta-edocta { background: transparent; border: none; color: var(--accent); font-family: 'DM Sans', sans-serif; font-size: 11.5px; font-weight: 700; letter-spacing: 0.3px; cursor: pointer; padding: 4px 6px; white-space: nowrap; }
|
||||
.cta-edocta:hover { text-decoration: underline; }
|
||||
.cta-seltodo { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--text-secondary); cursor: pointer; }
|
||||
.cta-seltodo input { width: 17px; height: 17px; accent-color: var(--accent); cursor: pointer; }
|
||||
.sub-card { background: var(--surface); border: 1px solid var(--line); border-radius: 13px; box-shadow: var(--nm-subtle); margin-bottom: 10px; overflow: hidden; transition: border-color 0.15s ease, box-shadow 0.15s ease; }
|
||||
.sub-card.sel { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 6px 14px -6px var(--accent-glow); }
|
||||
@@ -866,9 +869,12 @@ function renderCuentas(){
|
||||
: `<div class="cta-foot empty">Toca una subcuenta para seleccionarla y ver el total a cobrar.</div>`;
|
||||
body = `
|
||||
<div class="cta-body">
|
||||
<label class="cta-seltodo">
|
||||
<input type="checkbox" ${todas ? "checked" : ""} onchange="ctaSelTodo(${i})"> Seleccionar todo
|
||||
</label>
|
||||
<div class="cta-tools">
|
||||
<label class="cta-seltodo">
|
||||
<input type="checkbox" ${todas ? "checked" : ""} onchange="ctaSelTodo(${i})"> Seleccionar todo
|
||||
</label>
|
||||
<button class="cta-edocta" onclick="descargarEdoCuenta(${i})">📄 Estado de cuenta</button>
|
||||
</div>
|
||||
${subcards}
|
||||
${foot}
|
||||
</div>`;
|
||||
@@ -903,6 +909,13 @@ function ctaSelTodo(i){
|
||||
renderCuentas();
|
||||
}
|
||||
|
||||
// Abre el estado de cuenta PDF del cliente en una pestaña nueva.
|
||||
function descargarEdoCuenta(i){
|
||||
const c = ctaClientes[i]; if(!c) return;
|
||||
window.open(API + "/estado-cuenta.pdf?token=" + encodeURIComponent(TOKEN) +
|
||||
"&cliente=" + encodeURIComponent(c.nombre), "_blank");
|
||||
}
|
||||
|
||||
// ── Cobro consolidado: un mensaje con el desglose de la selección ──
|
||||
let consolidadoState = null; // {texto, total, cliente, id_ref} del backend
|
||||
|
||||
|
||||
Reference in new issue
Block a user