feat(cobranza): VR agrupado por flotilla + plazo visible en el anualizado

Los VR del reporte se agrupan como las rentas: (cliente, vehículo
normalizado, fecha) → una línea por flotilla con montos sumados y 'N
unidades' (caso SLUTEN: 60 líneas de $10,000 → 2 líneas de $300,000;
variantes '"WK" FRISON'/'"WK"FRISON' unifican, "WK" ≠ "ARRENDADORA"
no se fusionan; claves internas agrupan). La siembra del panel hereda
el agrupado (mismo shape, monto_a_cobrar sumado).

El monto anualizado ahora imprime '(anual · plazo Xm)': un plazo mal
capturado en el Sheet (caso CLEAN PRO: 30 en col N con contrato a 48)
salta a la vista. La línea usa monto_a_cobrar, igual que el total.
144 tests en verde.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jorem JuárezandClaude Opus 4.8 committed 2026-08-18 16:36:54 -06:00
1 parent 5713204513
commit 27aa57a777
3 files changed
+149 -24

No files matched your search

+15 -9
View File
@@ -1521,17 +1521,19 @@ def _fmt_fecha(f) -> str:
def _fmt_vr_anual(v: dict) -> str:
"""Devuelve el monto de VR ANUAL formateado.
"""Devuelve el monto de VR a cobrar formateado.
Si el contrato trae `plazo_meses`, divide el VR total entre los años.
Si no hay plazo, muestra el total con sufijo ' (total)'.
Usa `_vr_monto_a_cobrar` (mismo número que suma el total, así línea y
total siempre cuadran). Si el contrato trae `plazo_meses`, el monto ya
viene anualizado y se muestra el plazo usado — así un plazo mal
capturado en el Sheet (ej. 30 en vez de 48 meses) salta a la vista.
Sin plazo, muestra el total con sufijo ' (total)'.
"""
total = float(v.get("monto") or 0.0)
m = _vr_monto_a_cobrar(v)
plazo = int(v.get("plazo_meses") or 0)
if plazo >= 12:
anios = plazo / 12
return _fmt_money(round(total / anios, 2))
return f"{_fmt_money(total)} (total)"
return f"{_fmt_money(m)} (anual · plazo {plazo}m)"
return f"{_fmt_money(m)} (total)"
def _vr_monto_a_cobrar(v: dict) -> float:
@@ -1724,8 +1726,10 @@ def _formatear_reporte(reporte: dict, link: str | None = None) -> str:
for v in vr:
m_v = _vr_monto_a_cobrar(v)
total_vr += m_v
u = v.get("unidades", 1) or 1
suf_u = f" ({u} unidades)" if u > 1 else ""
partes.append(
f"- {v.get('cliente','')} — {v.get('vehiculo','')} — {_fmt_vr_anual(v)}"
f"- {v.get('cliente','')} — {v.get('vehiculo','')}{suf_u} — {_fmt_vr_anual(v)}"
)
f_vr = v.get("fecha_vr")
if f_vr:
@@ -2015,8 +2019,10 @@ def _formatear_reporte_mensual(reporte: dict) -> str:
partes.append("")
for v in vr:
total_vr += _vr_monto_a_cobrar(v)
u = v.get("unidades", 1) or 1
suf_u = f" ({u} unidades)" if u > 1 else ""
partes.append(
f"- {v.get('cliente','')} — {v.get('vehiculo','')} — "
f"- {v.get('cliente','')} — {v.get('vehiculo','')}{suf_u} — "
f"{_fmt_vr_anual(v)}"
)
fecha_vr = v.get("fecha") or _fmt_fecha(v.get("fecha_vr"))
+31 -15
View File
@@ -910,7 +910,12 @@ def generar_reporte_cobros(
)
# ── Sección 2: valor residual vencido este mes ──
vr_items: list[dict] = []
# Agrupado por FLOTILLA (cliente, vehículo normalizado, fecha), igual
# que las rentas: N unidades → UNA línea con montos sumados y campo
# `unidades`. La clave unifica variantes de comillas ('"WK" FRISON' y
# '"WK"FRISON' son la misma flotilla) pero NO fusiona prefijos
# distintos ("WK" ≠ "ARRENDADORA": arrendadores diferentes).
grupos_vr: dict[tuple, dict] = {}
for row in filas:
fechas = _parse_fechas(_celda(row, _IDX_FECHAS_VR))
fecha_match = next(
@@ -937,20 +942,31 @@ def generar_reporte_cobros(
monto_a_cobrar = round(monto / (plazo_m / 12.0), 2)
else:
monto_a_cobrar = monto
vr_items.append({
"cliente": cliente,
"vehiculo": _celda(row, _IDX_VEHICULO),
"monto": monto,
"monto_a_cobrar": monto_a_cobrar,
"plazo_meses": plazo_m,
"fecha": fecha_match.strftime("%d/%m/%Y"),
"fecha_vr": fecha_match,
"nota_q": _limpiar_nota(_celda(row, _IDX_NOTAS)),
"nota_u": _limpiar_nota(_celda(row, _IDX_NOTAS_EXTRA)),
"tasa_mensual": _parse_tasa_moratoria_mensual(
_celda(row, _idx_tasa_moratoria())
),
})
vehiculo_raw = _celda(row, _IDX_VEHICULO)
vehiculo = _normalizar_vehiculo(vehiculo_raw) or vehiculo_raw
clave_veh = re.sub(r"\s+", " ", vehiculo.replace('"', " ")).strip().lower()
key = (cliente.strip().lower(), clave_veh, fecha_match)
g = grupos_vr.get(key)
if g is None:
g = grupos_vr[key] = {
"cliente": cliente,
"vehiculo": vehiculo,
"monto": 0.0,
"monto_a_cobrar": 0.0,
"unidades": 0,
"plazo_meses": plazo_m,
"fecha": fecha_match.strftime("%d/%m/%Y"),
"fecha_vr": fecha_match,
"nota_q": _limpiar_nota(_celda(row, _IDX_NOTAS)),
"nota_u": _limpiar_nota(_celda(row, _IDX_NOTAS_EXTRA)),
"tasa_mensual": _parse_tasa_moratoria_mensual(
_celda(row, _idx_tasa_moratoria())
),
}
g["monto"] = round(g["monto"] + monto, 2)
g["monto_a_cobrar"] = round(g["monto_a_cobrar"] + monto_a_cobrar, 2)
g["unidades"] += 1
vr_items: list[dict] = list(grupos_vr.values())
# ── Sección 3: rentas extraordinarias este mes ──
extras: list[dict] = []
+103
View File
@@ -0,0 +1,103 @@
"""
VR agrupado por FLOTILLA en el reporte de cobranza (caso SLUTEN):
30 unidades '"WK" FRISON' + 30 '"ARRENDADORA" FRISON' del mismo cliente y
fecha deben salir como DOS líneas (una por flotilla) con montos sumados,
no 60 líneas de $10,000. Prefijos distintos NO se fusionan; variantes de
comillas pegadas ('"WK"FRISON') sí.
"""
import os
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
from datetime import date
from unittest.mock import MagicMock, patch
from src.services import sheets
HEADER = [f"c{i}" for i in range(23)]
def _fila_vr(cliente, vehiculo, fecha_ddmmaaaa, total="10000", plazo=""):
f = [""] * 23
f[1] = cliente
f[2] = vehiculo
f[11] = total # _IDX_VR_TOTAL
f[13] = plazo # _IDX_PLAZO (col N)
f[16] = "DEP GARANTÍA $12,367.78" # nota Q
f[18] = f"({fecha_ddmmaaaa})" # _IDX_FECHAS_VR
return f
def _mock_gc(rows):
ws = MagicMock()
ws.get_all_values.return_value = rows
sh = MagicMock()
sh.worksheet.return_value = ws
gc = MagicMock()
gc.open_by_key.return_value = sh
return gc
def _reporte(rows, hoy=date(2026, 9, 2)):
with patch.object(sheets, "_IDX_TASA_MORATORIA_CACHE", None), \
patch.object(sheets, "_gc", None), \
patch.object(sheets, "_get_client") as m:
m.return_value = _mock_gc([HEADER] + rows)
return sheets.generar_reporte_cobros(hoy=hoy)
def test_flotillas_wk_y_arrendadora_agrupan_separadas():
rows = (
[_fila_vr("SLUTEN", '"WK" FRISON T6 FLEX', "02/09/2026")] * 15
+ [_fila_vr("SLUTEN", '"WK"FRISON T6 FLEX', "02/09/2026")] * 15
+ [_fila_vr("SLUTEN", '"ARRENDADORA" FRISON T6 FLEX', "02/09/2026")] * 30
)
vr = _reporte(rows)["vr"]
assert len(vr) == 2 # una línea por flotilla
por_veh = {v["vehiculo"]: v for v in vr}
wk = por_veh['"WK" FRISON T6 FLEX'] # comillas pegadas se unifican
arr = por_veh['"ARRENDADORA" FRISON T6 FLEX']
assert wk["unidades"] == 30 and arr["unidades"] == 30
assert wk["monto"] == 300000.0 and arr["monto"] == 300000.0
assert wk["monto_a_cobrar"] == 300000.0 # sin plazo → total
assert wk["nota_q"].startswith("DEP GARANTÍA")
def test_claves_internas_agrupan_misma_flotilla():
# MEENT: misma flotilla con clave interna distinta por unidad.
rows = [
_fila_vr("MEENT", "FRISON T6 FLEX (Clave interna: 8013)",
"04/09/2026", total="28750"),
_fila_vr("MEENT", "FRISON T6 FLEX (Clave interna: 8011)",
"04/09/2026", total="28750"),
]
vr = _reporte(rows)["vr"]
assert len(vr) == 1
assert vr[0]["unidades"] == 2 and vr[0]["monto"] == 57500.0
def test_no_agrupa_entre_clientes_ni_fechas():
rows = [
_fila_vr("CLIENTE-A", "FRISON T6 FLEX", "02/09/2026"),
_fila_vr("CLIENTE-B", "FRISON T6 FLEX", "02/09/2026"),
_fila_vr("CLIENTE-A", "FRISON T6 FLEX", "15/09/2026"),
]
vr = _reporte(rows)["vr"]
assert len(vr) == 3
assert all(v["unidades"] == 1 for v in vr)
def test_vr_anualizado_muestra_plazo_usado():
# Caso CLEAN PRO: VR total 299,940 con plazo 48 → 74,985 anual. Si el
# Sheet trae 30, el reporte muestra 119,976 PERO con '(plazo 30m)'
# visible para cachar el error de captura a simple vista.
from src.api.webhook import _fmt_vr_anual
v48 = _reporte([_fila_vr("CLEAN PRO", "320i AUTOMÁTICO", "30/09/2026",
total="299940", plazo="48")])["vr"][0]
assert v48["monto_a_cobrar"] == 74985.0
assert _fmt_vr_anual(v48) == "$74,985.00 (anual · plazo 48m)"
v30 = _reporte([_fila_vr("CLEAN PRO", "320i AUTOMÁTICO", "30/09/2026",
total="299940", plazo="30")])["vr"][0]
assert v30["monto_a_cobrar"] == 119976.0
assert "plazo 30m" in _fmt_vr_anual(v30)