diff --git a/src/api/cobranza_api.py b/src/api/cobranza_api.py index b0af042..398a40d 100644 --- a/src/api/cobranza_api.py +++ b/src/api/cobranza_api.py @@ -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, diff --git a/tests/test_lote_mensaje.py b/tests/test_lote_mensaje.py new file mode 100644 index 0000000..49edff3 --- /dev/null +++ b/tests/test_lote_mensaje.py @@ -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