fix(cobranza): {fecha} = vencimiento del renglón + no generar Conekta sin link
{fecha} ahora es la fecha de vencimiento del renglón (sin sumar días ni usar
hoy):
- renta: día de pago (el de la tabla) + mes/año en curso.
- vr/extra/otro: su fecha_vencimiento.
Si no hay fecha, la línea se omite aunque el bloque esté activo. Aplica en el
cobro individual (frontend) y en el lote (backend, _fecha_vencimiento_str).
Etiqueta del checkbox: "Incluir fecha de vencimiento".
Conekta: _generar_cobro_para_renglon acepta con_link; el lote no genera link
cuando la plantilla tiene incluir_link desactivado (antes lo generaba y lo
descartaba). El abono pendiente (tipo personal) se sigue creando.
Tests: vencimiento vr/renta, omisión de línea vacía, inclusión con fecha.
28 tests OK.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5a4b325f8b
commit
4979d3ea1c
3 files changed
+105
-19
No files matched your search
+52
-14
@@ -6,10 +6,11 @@ ve y muta SU versión de la cobranza. Reutiliza `validar_token_admin` para
|
||||
compartir el mismo storage (`admin_token:{token}`) que los recordatorios.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
@@ -64,9 +65,34 @@ def _aplicar_vars(tpl: str, variables: dict) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _fecha_vencimiento_str(r: dict) -> str:
|
||||
"""Fecha de vencimiento del renglón, dd/mm/aaaa.
|
||||
|
||||
- renta: día de pago (el de la tabla) + mes/año en curso.
|
||||
- vr/extra/otro: su `fecha_vencimiento` (ISO).
|
||||
Devuelve "" si no se puede determinar.
|
||||
"""
|
||||
tipo = (r.get("tipo") or "renta")
|
||||
if tipo == "renta" and r.get("dia_pago"):
|
||||
ahora = datetime.now(cobranza_acumulada.MEXICO)
|
||||
ult = calendar.monthrange(ahora.year, ahora.month)[1]
|
||||
try:
|
||||
dia = int(r["dia_pago"])
|
||||
except (TypeError, ValueError):
|
||||
dia = 1
|
||||
dia = min(max(dia, 1), ult)
|
||||
return f"{dia:02d}/{ahora.month:02d}/{ahora.year}"
|
||||
fv = (r.get("fecha_vencimiento") or "").strip()
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2}$", fv):
|
||||
y, m, d = fv.split("-")
|
||||
return f"{d}/{m}/{y}"
|
||||
return ""
|
||||
|
||||
|
||||
def _armar_mensaje_plantilla(
|
||||
plantilla: dict, cuentas: list[dict], *,
|
||||
cliente: str, vehiculo: str, concepto: str, monto: float, link: str,
|
||||
fecha: 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
|
||||
@@ -75,14 +101,13 @@ def _armar_mensaje_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"),
|
||||
"fecha": fecha or "",
|
||||
}
|
||||
T = {
|
||||
"cliente": pl.get("texto_cliente", "Cliente: {cliente}"),
|
||||
@@ -105,7 +130,7 @@ def _armar_mensaje_plantilla(
|
||||
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"):
|
||||
if pl.get("incluir_fecha_limite") and variables["fecha"]:
|
||||
out += _aplicar_vars(T["fecha"], variables) + "\n"
|
||||
out += "\n"
|
||||
for c in cuentas_inc:
|
||||
@@ -520,12 +545,16 @@ def _monto_para_cobro(r: dict, tipo: str, monto_in: float | None) -> float:
|
||||
async def _generar_cobro_para_renglon(
|
||||
numero: str, renglon: dict, tipo: str,
|
||||
monto_in: float | None, concepto: str | None,
|
||||
con_link: bool = True,
|
||||
) -> dict:
|
||||
"""Crea el link Conekta y devuelve el resumen del cobro.
|
||||
"""Resuelve el cobro y (si `con_link`) crea el link Conekta.
|
||||
|
||||
Para tipo='personal' además crea un abono PENDIENTE en el renglón y
|
||||
enlaza la referencia con `id_abono`, de modo que el webhook Conekta
|
||||
pueda marcarlo como pagado individualmente.
|
||||
|
||||
Si `con_link` es False (p. ej. la plantilla tiene el link desactivado),
|
||||
NO se llama a Conekta y se devuelve link vacío.
|
||||
"""
|
||||
monto = round(_monto_para_cobro(renglon, tipo, monto_in), 2)
|
||||
if monto <= 0:
|
||||
@@ -550,16 +579,21 @@ async def _generar_cobro_para_renglon(
|
||||
ref = f"{numero}:{renglon['id']}:abono:{id_abono}"
|
||||
else:
|
||||
ref = f"{numero}:{renglon['id']}:{tipo}"
|
||||
desc = f"{concepto_final} ({renglon.get('vehiculo','')})"
|
||||
res = await pagos.crear_link_cobro(
|
||||
monto=monto,
|
||||
descripcion=desc,
|
||||
cliente_nombre=renglon.get("cliente", "Cliente"),
|
||||
referencia=ref,
|
||||
)
|
||||
link = ""
|
||||
id_cobro = ""
|
||||
if con_link:
|
||||
desc = f"{concepto_final} ({renglon.get('vehiculo','')})"
|
||||
res = await pagos.crear_link_cobro(
|
||||
monto=monto,
|
||||
descripcion=desc,
|
||||
cliente_nombre=renglon.get("cliente", "Cliente"),
|
||||
referencia=ref,
|
||||
)
|
||||
link = res.get("link")
|
||||
id_cobro = res.get("id")
|
||||
return {
|
||||
"link": res.get("link"),
|
||||
"id_cobro": res.get("id"),
|
||||
"link": link,
|
||||
"id_cobro": id_cobro,
|
||||
"monto": monto,
|
||||
"concepto": concepto_final,
|
||||
"id_abono": id_abono, # vacío si no es personal
|
||||
@@ -636,6 +670,7 @@ async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
plantilla = cfg.get("plantilla") or {}
|
||||
cuentas = cfg.get("cuentas") or []
|
||||
incluir_link = plantilla.get("incluir_link") is not False
|
||||
enviados = 0
|
||||
omitidos_sin_tel: list[str] = []
|
||||
errores: list[str] = []
|
||||
@@ -654,8 +689,10 @@ async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
# trae uno propio.
|
||||
concepto_fila = (fila.concepto or "").strip() or body.concepto or ""
|
||||
try:
|
||||
# Si la plantilla tiene el link apagado, no se genera Conekta.
|
||||
cobro = await _generar_cobro_para_renglon(
|
||||
numero, r, fila.tipo, fila.monto, concepto_fila,
|
||||
con_link=incluir_link,
|
||||
)
|
||||
except HTTPException as e:
|
||||
logger.warning("Lote: error en %s: %s", fila.id, e.detail)
|
||||
@@ -672,6 +709,7 @@ async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
concepto=concepto_fila,
|
||||
monto=cobro["monto"],
|
||||
link=cobro["link"],
|
||||
fecha=_fecha_vencimiento_str(r),
|
||||
)
|
||||
ok = await whatsapp.enviar_texto(_wa_address(tel_efectivo), texto, _instance())
|
||||
if ok:
|
||||
|
||||
@@ -6,7 +6,7 @@ import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
from src.api.cobranza_api import _armar_mensaje_plantilla
|
||||
from src.api.cobranza_api import _armar_mensaje_plantilla, _fecha_vencimiento_str
|
||||
|
||||
|
||||
PLANTILLA = {
|
||||
@@ -57,3 +57,36 @@ def test_lote_sin_link_ni_cuentas_avisa():
|
||||
)
|
||||
assert "No hay cuentas activadas ni link configurado" in out
|
||||
assert "http" not in out
|
||||
|
||||
|
||||
def test_fecha_vencimiento_vr_usa_fecha_del_renglon():
|
||||
r = {"tipo": "vr", "fecha_vencimiento": "2026-06-30"}
|
||||
assert _fecha_vencimiento_str(r) == "30/06/2026"
|
||||
|
||||
|
||||
def test_fecha_vencimiento_renta_usa_dia_pago_mes_actual():
|
||||
# renta: día de pago + mes/año en curso (sin sumar días).
|
||||
from datetime import datetime
|
||||
from src.services.cobranza_acumulada import MEXICO
|
||||
ahora = datetime.now(MEXICO)
|
||||
r = {"tipo": "renta", "dia_pago": 5}
|
||||
esperado = f"05/{ahora.month:02d}/{ahora.year}"
|
||||
assert _fecha_vencimiento_str(r) == esperado
|
||||
|
||||
|
||||
def test_fecha_vacia_omite_la_linea():
|
||||
pl = dict(PLANTILLA, incluir_fecha_limite=True)
|
||||
out = _armar_mensaje_plantilla(
|
||||
pl, [], cliente="ACME", vehiculo="HILUX", concepto="X",
|
||||
monto=100, link="http://x", fecha="", # sin fecha => sin línea
|
||||
)
|
||||
assert "Fecha límite" not in out
|
||||
|
||||
|
||||
def test_fecha_se_incluye_cuando_se_pasa():
|
||||
pl = dict(PLANTILLA, incluir_fecha_limite=True)
|
||||
out = _armar_mensaje_plantilla(
|
||||
pl, [], cliente="ACME", vehiculo="HILUX", concepto="X",
|
||||
monto=100, link="http://x", fecha="30/06/2026",
|
||||
)
|
||||
assert "Fecha límite: 30/06/2026" in out
|
||||
+19
-4
@@ -423,7 +423,7 @@
|
||||
<input type="text" class="form-input bloque-txt" id="pl-monto-txt" oninput="renderVistaPreviaMsg()" placeholder="Monto: {monto}">
|
||||
</div>
|
||||
<div class="bloque-row">
|
||||
<label class="check-row"><input type="checkbox" id="pl-fecha" onchange="bloqueChanged()"> Incluir fecha límite (hoy + 5 días)</label>
|
||||
<label class="check-row"><input type="checkbox" id="pl-fecha" onchange="bloqueChanged()"> Incluir fecha de vencimiento</label>
|
||||
<input type="text" class="form-input bloque-txt" id="pl-fecha-txt" oninput="renderVistaPreviaMsg()" placeholder="Fecha límite: {fecha}">
|
||||
</div>
|
||||
<div class="bloque-row">
|
||||
@@ -1762,6 +1762,22 @@ async function guardarPlantilla(){
|
||||
// ── Mensaje SPEI ──────────────────────────────────────────────
|
||||
const _MESES_CORTO = ["ENE","FEB","MAR","ABR","MAY","JUN","JUL","AGO","SEP","OCT","NOV","DIC"];
|
||||
|
||||
// Fecha de vencimiento del renglón (dd/mm/aaaa):
|
||||
// - renta: día de pago (el de la tabla) + mes/año en curso.
|
||||
// - vr/extra/otro: su fecha_vencimiento (ISO).
|
||||
function fechaVencimiento(r){
|
||||
if(r && r.tipo === "renta" && r.dia_pago){
|
||||
const d = new Date();
|
||||
const ult = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
|
||||
const dia = Math.min(Math.max(parseInt(r.dia_pago, 10) || 1, 1), ult);
|
||||
return new Date(d.getFullYear(), d.getMonth(), dia)
|
||||
.toLocaleDateString("es-MX", {day:"2-digit", month:"2-digit", year:"numeric"});
|
||||
}
|
||||
const fv = (r && r.fecha_vencimiento) || "";
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(fv);
|
||||
return m ? `${m[3]}/${m[2]}/${m[1]}` : "";
|
||||
}
|
||||
|
||||
function autoConcepto(r){
|
||||
const tipo = (r && r.tipo) ? r.tipo.toUpperCase() : "COBRO";
|
||||
let tipoStr;
|
||||
@@ -1793,14 +1809,13 @@ function armarMensajeCobro(r, monto, concepto, link){
|
||||
const pl = cfg.plantilla || {};
|
||||
const cuentas = (cfg.cuentas || []).filter(c => c.incluir_en_mensaje);
|
||||
const d = new Date();
|
||||
const fLim = new Date(); fLim.setDate(fLim.getDate() + 5);
|
||||
const vars = {
|
||||
cliente: r.cliente || "",
|
||||
vehiculo: r.vehiculo || "",
|
||||
monto: fmt(monto),
|
||||
concepto: concepto || "",
|
||||
mes: _MESES_CORTO[d.getMonth()] + " " + d.getFullYear(),
|
||||
fecha: fLim.toLocaleDateString("es-MX",{day:"2-digit",month:"2-digit",year:"numeric"}),
|
||||
fecha: fechaVencimiento(r),
|
||||
};
|
||||
// Texto editable por bloque (cae al default si la plantilla no lo trae).
|
||||
const T = {
|
||||
@@ -1819,7 +1834,7 @@ function armarMensajeCobro(r, monto, concepto, link){
|
||||
if(pl.incluir_cliente !== false && r.cliente) out += _aplicarVariables(T.cliente, vars) + "\n";
|
||||
if(pl.incluir_vehiculo !== false && r.vehiculo) out += _aplicarVariables(T.vehiculo, vars) + "\n";
|
||||
if(pl.incluir_monto !== false) out += _aplicarVariables(T.monto, vars) + "\n";
|
||||
if(pl.incluir_fecha_limite) out += _aplicarVariables(T.fecha, vars) + "\n";
|
||||
if(pl.incluir_fecha_limite && vars.fecha) out += _aplicarVariables(T.fecha, vars) + "\n";
|
||||
out += "\n";
|
||||
if(cuentas.length){
|
||||
cuentas.forEach(c => {
|
||||
|
||||
Reference in new issue
Block a user