feat(cotizador): etiqueta de la toma con el modelo tomado a cuenta

El renglón de la toma en el PDF ahora dice 'TOMA A CUENTA RENTA ANTICIPADA
<MODELO>' (antes solo 'TOMA A CUENTA'). El modelo es el vehículo de la toma,
inyectado vía nuevo placeholder $TOMANOMBRE$ en la plantilla; Word lo envuelve
a dos renglones si es largo. Sin toma → $TOMANOMBRE$='' y la fila se auto-oculta.

pdf_generator hilA toma_vehiculo (build_replacements/_build_docx/generar_pdf*);
_generar_clonacion pasa clonacion['toma_vehiculo']. NO toca calculator.py.
Verificado con PDF real (con/sin toma, nombre corto y largo). 80 tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jorem JuárezandClaude Opus 4.8 committed 2026-07-07 14:16:07 -06:00
1 parent a8630a3272
commit 441f102b47
4 files changed
+32 -9

No files matched your search

Binary file not shown.
+4 -1
View File
@@ -3034,7 +3034,10 @@ async def _generar_clonacion(msg: WebhookMessage, clonacion: dict) -> bool:
_borrar_docx_pendiente(docx_anterior)
await session.limpiar_docx_pendiente(numero)
pdf_bytes, docx_path = generar_pdf_y_docx(params, result, toma_valor=toma_valor)
pdf_bytes, docx_path = generar_pdf_y_docx(
params, result, toma_valor=toma_valor,
toma_vehiculo=clonacion.get("toma_vehiculo") or "",
)
filename = f"Cotizacion_{marca}_{tipo}_{anio or ''}_{plazo}m.pdf"
await whatsapp.enviar_pdf(numero, pdf_bytes, filename, msg.instance)
logger.info("PDF clonado enviado: %s a %s", filename, numero)
+12 -7
View File
@@ -58,7 +58,8 @@ def _open_docm_as_docx(docm_path: str, dest_path: str):
def _build_replacements(params: CotizacionParams, result: CotizacionResult,
toma_valor: float = 0.0) -> dict[str, str]:
toma_valor: float = 0.0,
toma_vehiculo: str = "") -> dict[str, str]:
fecha_hoy = date.today().strftime("%d/%m/%Y")
nombre_cliente = params.nombre_cliente or "A QUIEN CORRESPONDA"
atencion = params.atencion or "A QUIEN CORRESPONDA"
@@ -133,17 +134,20 @@ def _build_replacements(params: CotizacionParams, result: CotizacionResult,
# Si no hay toma, queda "" y el ocultado automático de líneas pareadas
# (más abajo en _build_docx) elimina la línea $TOMA$ y su etiqueta.
"$TOMA$": ("- " + _fmt_money(toma_valor)) if toma_valor and toma_valor > 0 else "",
# Nombre del vehículo tomado a cuenta, en la etiqueta del renglón
# ("TOMA A CUENTA RENTA ANTICIPADA <MODELO>"). Vacío si no hay toma.
"$TOMANOMBRE$": (toma_vehiculo or "").upper() if toma_valor and toma_valor > 0 else "",
}
def _build_docx(params: CotizacionParams, result: CotizacionResult, tmpdir: str,
toma_valor: float = 0.0) -> str:
toma_valor: float = 0.0, toma_vehiculo: str = "") -> str:
"""Construye el .docx final dentro de tmpdir y devuelve su ruta."""
docx_path = os.path.join(tmpdir, "cotizacion.docx")
_open_docm_as_docx(str(TEMPLATE_PATH), docx_path)
doc = Document(docx_path)
replacements = _build_replacements(params, result, toma_valor)
replacements = _build_replacements(params, result, toma_valor, toma_vehiculo)
# Replace placeholders in paragraphs and tables
for paragraph in doc.paragraphs:
@@ -220,17 +224,18 @@ def _slug(texto: str) -> str:
def generar_pdf(params: CotizacionParams, result: CotizacionResult,
toma_valor: float = 0.0) -> bytes:
toma_valor: float = 0.0, toma_vehiculo: str = "") -> bytes:
tmpdir = tempfile.mkdtemp()
try:
docx_path = _build_docx(params, result, tmpdir, toma_valor)
docx_path = _build_docx(params, result, tmpdir, toma_valor, toma_vehiculo)
return _docx_to_pdf_bytes(docx_path, tmpdir)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def generar_pdf_y_docx(params: CotizacionParams, result: CotizacionResult,
toma_valor: float = 0.0) -> tuple[bytes, str]:
toma_valor: float = 0.0,
toma_vehiculo: str = "") -> tuple[bytes, str]:
"""Genera el PDF y deja una copia persistente del .docx en /tmp.
El archivo queda en un subdirectorio único (`/tmp/wk_docx_XXXX/`) para
@@ -240,7 +245,7 @@ def generar_pdf_y_docx(params: CotizacionParams, result: CotizacionResult,
"""
tmpdir = tempfile.mkdtemp()
try:
docx_tmp = _build_docx(params, result, tmpdir, toma_valor)
docx_tmp = _build_docx(params, result, tmpdir, toma_valor, toma_vehiculo)
pdf_bytes = _docx_to_pdf_bytes(docx_tmp, tmpdir)
marca = _slug(params.marca)
+16 -1
View File
@@ -55,6 +55,19 @@ def test_plantilla_tiene_placeholder_toma():
with zipfile.ZipFile(pg.TEMPLATE_PATH) as z:
xml = z.read("word/document.xml").decode("utf-8", "ignore")
assert "$TOMA$" in xml
assert "$TOMANOMBRE$" in xml # etiqueta con el modelo tomado a cuenta
def test_toma_nombre_placeholder_con_vehiculo():
reps = pg._build_replacements(_params(), _result(95000.0),
toma_valor=30000.0, toma_vehiculo="Teramont")
assert reps["$TOMANOMBRE$"] == "TERAMONT" # en mayúsculas
def test_toma_nombre_placeholder_sin_toma_vacio():
reps = pg._build_replacements(_params(), _result(125000.0),
toma_valor=0.0, toma_vehiculo="Teramont")
assert reps["$TOMANOMBRE$"] == "" # sin toma → vacío (la fila se oculta)
def _texto_tablas_docx(path):
@@ -153,9 +166,10 @@ def _mock_generacion(cap):
async def _detectar(a, b):
return ("TOYOTA", "HILUX")
def _gen(params, result, toma_valor=0.0):
def _gen(params, result, toma_valor=0.0, toma_vehiculo=""):
cap["result"] = result
cap["toma_valor"] = toma_valor
cap["toma_vehiculo"] = toma_vehiculo
return (b"pdf", "/tmp/x.docx")
def _tasa(**kw):
@@ -245,6 +259,7 @@ def test_toma_igual_a_ra_aceptada():
ok, cap = _correr_completar(toma_valor=100000.0)
assert cap["result"].total_pago_inicial == 25000.0
assert cap["toma_valor"] == 100000.0
assert cap["toma_vehiculo"] == "Teramont" # el modelo llega al generador
assert cap["result"].total_pago_inicial > 0 # la fila TOTAL nunca queda en 0