feat(cobranza): el cobro en lote hereda la plantilla del mensaje
Antes el lote usaba un mensaje hardcodeado (_mensaje_cobro) que ignoraba la
plantilla: sin saludo/despedida, sin cuentas SPEI y sin los textos editables.
Se agrega _armar_mensaje_plantilla (espejo en Python de armarMensajeCobro):
arma el mensaje con saludo, bloques editables por concepto, cuentas SPEI
incluidas, link y despedida, aplicando variables ({cliente},{vehiculo},
{monto},{fecha},{concepto},{mes}). El link se inserta por renglón (se genera
en el backend durante el lote). cobrar_lote carga la config una vez y usa este
armador. _mensaje_cobro queda solo para el endpoint legacy /enviar-cliente.
tests/test_lote_mensaje.py: hereda plantilla (saludo/textos/cuentas/link/
despedida) y aviso cuando no hay cuentas ni link. 24 tests OK.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
dc9af65ae4
commit
5a4b325f8b
2 files changed
+142
-1
No files matched your search
+83
-1
@@ -8,6 +8,8 @@ compartir el mismo storage (`admin_token:{token}`) que los recordatorios.
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
@@ -49,6 +51,81 @@ def _instance() -> str:
|
||||
return os.getenv("EVOLUTION_INSTANCE", "wk-bot")
|
||||
|
||||
|
||||
_MESES_CORTO = ["ENE", "FEB", "MAR", "ABR", "MAY", "JUN",
|
||||
"JUL", "AGO", "SEP", "OCT", "NOV", "DIC"]
|
||||
|
||||
|
||||
def _aplicar_vars(tpl: str, variables: dict) -> str:
|
||||
"""Reemplaza {clave} por su valor (equivale a _aplicarVariables del front)."""
|
||||
return re.sub(
|
||||
r"\{(\w+)\}",
|
||||
lambda m: str(variables.get(m.group(1), "")),
|
||||
tpl or "",
|
||||
)
|
||||
|
||||
|
||||
def _armar_mensaje_plantilla(
|
||||
plantilla: dict, cuentas: list[dict], *,
|
||||
cliente: str, vehiculo: str, concepto: str, monto: float, link: str,
|
||||
) -> str:
|
||||
"""Arma el mensaje de cobro con la MISMA plantilla del panel (saludo,
|
||||
bloques editables, cuentas SPEI, link y despedida). Espejo en Python de
|
||||
`armarMensajeCobro` del frontend, para que el lote herede la plantilla.
|
||||
"""
|
||||
pl = plantilla or {}
|
||||
cuentas_inc = [c for c in (cuentas or []) if c.get("incluir_en_mensaje")]
|
||||
ahora = datetime.now(cobranza_acumulada.MEXICO)
|
||||
flim = ahora + timedelta(days=5)
|
||||
variables = {
|
||||
"cliente": cliente or "",
|
||||
"vehiculo": vehiculo or "",
|
||||
"monto": f"${monto:,.2f}",
|
||||
"concepto": concepto or "",
|
||||
"mes": f"{_MESES_CORTO[ahora.month - 1]} {ahora.year}",
|
||||
"fecha": flim.strftime("%d/%m/%Y"),
|
||||
}
|
||||
T = {
|
||||
"cliente": pl.get("texto_cliente", "Cliente: {cliente}"),
|
||||
"vehiculo": pl.get("texto_vehiculo", "Vehículo: {vehiculo}"),
|
||||
"monto": pl.get("texto_monto", "Monto: {monto}"),
|
||||
"fecha": pl.get("texto_fecha", "Fecha límite: {fecha}"),
|
||||
"link": pl.get("texto_link",
|
||||
"Puede pagar con tarjeta, SPEI o efectivo en Oxxo desde este link:"),
|
||||
}
|
||||
incluir_link = (pl.get("incluir_link") is not False) and bool(link)
|
||||
|
||||
out = ""
|
||||
if pl.get("saludo"):
|
||||
out += _aplicar_vars(pl["saludo"], variables) + "\n\n"
|
||||
out += "Le compartimos los datos para realizar su pago:\n\n"
|
||||
out += f"Concepto: {concepto}\n"
|
||||
if pl.get("incluir_cliente") is not False and cliente:
|
||||
out += _aplicar_vars(T["cliente"], variables) + "\n"
|
||||
if pl.get("incluir_vehiculo") is not False and vehiculo:
|
||||
out += _aplicar_vars(T["vehiculo"], variables) + "\n"
|
||||
if pl.get("incluir_monto") is not False:
|
||||
out += _aplicar_vars(T["monto"], variables) + "\n"
|
||||
if pl.get("incluir_fecha_limite"):
|
||||
out += _aplicar_vars(T["fecha"], variables) + "\n"
|
||||
out += "\n"
|
||||
for c in cuentas_inc:
|
||||
out += f"🏦 {c.get('banco', '')}\n"
|
||||
if c.get("beneficiario"):
|
||||
out += f"Beneficiario: {c['beneficiario']}\n"
|
||||
if c.get("cuenta"):
|
||||
out += f"Cuenta: {c['cuenta']}\n"
|
||||
if c.get("clabe"):
|
||||
out += f"CLABE: {c['clabe']}\n"
|
||||
out += "\n"
|
||||
if incluir_link:
|
||||
out += _aplicar_vars(T["link"], variables) + f"\n{link}\n\n"
|
||||
if not cuentas_inc and not incluir_link:
|
||||
out += "⚠️ No hay cuentas activadas ni link configurado.\n\n"
|
||||
if pl.get("despedida"):
|
||||
out += _aplicar_vars(pl["despedida"], variables)
|
||||
return out.strip()
|
||||
|
||||
|
||||
def _mensaje_cobro(cliente: str, vehiculo: str, concepto: str,
|
||||
monto: float, link: str) -> str:
|
||||
return (
|
||||
@@ -555,6 +632,10 @@ async def reenviar_contacto(body: ReenviarContactoBody, token: str = Query(...))
|
||||
async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
renglones = {r.get("id"): r for r in await cobranza_acumulada.listar(numero)}
|
||||
# Plantilla + cuentas: el lote hereda la MISMA configuración del panel.
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
plantilla = cfg.get("plantilla") or {}
|
||||
cuentas = cfg.get("cuentas") or []
|
||||
enviados = 0
|
||||
omitidos_sin_tel: list[str] = []
|
||||
errores: list[str] = []
|
||||
@@ -584,7 +665,8 @@ async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
logger.exception("Lote: excepción generando cobro para %s", fila.id)
|
||||
errores.append(r.get("cliente", fila.id))
|
||||
continue
|
||||
texto = _mensaje_cobro(
|
||||
texto = _armar_mensaje_plantilla(
|
||||
plantilla, cuentas,
|
||||
cliente=r.get("cliente", ""),
|
||||
vehiculo=r.get("vehiculo", ""),
|
||||
concepto=concepto_fila,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
El mensaje del cobro en lote debe heredar la plantilla del panel
|
||||
(saludo, textos editables por bloque, cuentas SPEI, link y despedida).
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
from src.api.cobranza_api import _armar_mensaje_plantilla
|
||||
|
||||
|
||||
PLANTILLA = {
|
||||
"saludo": "Hola {cliente}, le saludamos.",
|
||||
"despedida": "Gracias, {cliente}.",
|
||||
"incluir_cliente": True,
|
||||
"incluir_vehiculo": True,
|
||||
"incluir_monto": True,
|
||||
"incluir_fecha_limite": False, # se omite a propósito
|
||||
"incluir_link": True,
|
||||
"texto_cliente": "Cliente: {cliente}",
|
||||
"texto_vehiculo": "Unidad: {vehiculo}", # texto editado
|
||||
"texto_monto": "Total a pagar: {monto}", # texto editado
|
||||
"texto_fecha": "Fecha límite: {fecha}",
|
||||
"texto_link": "Pague aquí:", # texto editado
|
||||
}
|
||||
|
||||
CUENTAS = [
|
||||
{"id": "1", "banco": "BBVA", "beneficiario": "WK", "cuenta": "123",
|
||||
"clabe": "012345678901234567", "incluir_en_mensaje": True},
|
||||
{"id": "2", "banco": "OCULTA", "incluir_en_mensaje": False}, # no debe salir
|
||||
]
|
||||
|
||||
|
||||
def test_lote_hereda_plantilla():
|
||||
out = _armar_mensaje_plantilla(
|
||||
PLANTILLA, CUENTAS,
|
||||
cliente="ACME", vehiculo="HILUX", concepto="WK-RENTA-ACME",
|
||||
monto=1234.5, link="http://pago/x",
|
||||
)
|
||||
assert "Hola ACME, le saludamos." in out # saludo con variable
|
||||
assert "Concepto: WK-RENTA-ACME" in out
|
||||
assert "Cliente: ACME" in out
|
||||
assert "Unidad: HILUX" in out # texto editado de vehículo
|
||||
assert "Total a pagar: $1,234.50" in out # texto editado + formato
|
||||
assert "Fecha límite" not in out # bloque desactivado
|
||||
assert "🏦 BBVA" in out and "CLABE: 012345678901234567" in out
|
||||
assert "OCULTA" not in out # cuenta no incluida
|
||||
assert "Pague aquí:" in out and "http://pago/x" in out
|
||||
assert out.rstrip().endswith("Gracias, ACME.") # despedida con variable
|
||||
|
||||
|
||||
def test_lote_sin_link_ni_cuentas_avisa():
|
||||
pl = dict(PLANTILLA, incluir_link=False)
|
||||
out = _armar_mensaje_plantilla(
|
||||
pl, [], # sin cuentas
|
||||
cliente="ACME", vehiculo="HILUX", concepto="X", monto=100, link="",
|
||||
)
|
||||
assert "No hay cuentas activadas ni link configurado" in out
|
||||
assert "http" not in out
|
||||
Reference in new issue
Block a user