feat(cobranza): cobro consolidado por cliente desde la vista Cuentas (Fase 3)
Al seleccionar subcuentas de un cliente aparece 'Cobro consolidado': POST /api/cobro-consolidado arma UN mensaje con el desglose por subcuenta (• vehículo · concepto: $monto, rentas con N meses) + línea de total configurable (texto_total en la plantilla, editable en la pestaña Mensaje) + cuentas SPEI + despedida. Valida que la selección sea de un solo cliente. El panel lo previsualiza editable y lo envía al cliente o lo reenvía a un contacto (endpoints existentes). Sin link Conekta: el consolidado se dirige a SPEI. 133 tests en verde. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
d178a99d2a
commit
8c35461761
4 files changed
+259
-5
No files matched your search
+120
-4
@@ -135,6 +135,18 @@ def _armar_mensaje_plantilla(
|
||||
if pl.get("incluir_fecha_limite") and variables["fecha"]:
|
||||
out += _aplicar_vars(T["fecha"], variables) + "\n"
|
||||
out += "\n"
|
||||
out += _bloque_cuentas(cuentas_inc)
|
||||
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 _bloque_cuentas(cuentas_inc: list[dict]) -> str:
|
||||
out = ""
|
||||
for c in cuentas_inc:
|
||||
out += f"🏦 {c.get('banco', '')}\n"
|
||||
if c.get("beneficiario"):
|
||||
@@ -144,10 +156,56 @@ def _armar_mensaje_plantilla(
|
||||
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"
|
||||
return out
|
||||
|
||||
|
||||
_TIPO_LABEL = {"renta": "Renta mensual", "extra": "Extraordinaria",
|
||||
"vr": "Valor residual"}
|
||||
|
||||
|
||||
def _tipo_label(r: dict) -> str:
|
||||
"""Etiqueta legible del tipo de renglón (espejo de tipoLabel del panel)."""
|
||||
tipo = r.get("tipo") or "renta"
|
||||
if tipo == "otro":
|
||||
return r.get("etiqueta") or "Otro"
|
||||
return _TIPO_LABEL.get(tipo, tipo)
|
||||
|
||||
|
||||
def _armar_mensaje_consolidado(
|
||||
plantilla: dict, cuentas: list[dict], *,
|
||||
cliente: str, lineas: list[dict], total: float,
|
||||
) -> str:
|
||||
"""Mensaje de cobro CONSOLIDADO de un cliente: desglose por subcuenta
|
||||
(una línea por concepto seleccionado) + total, con la misma plantilla
|
||||
del panel (saludo, intro, cuentas SPEI, despedida).
|
||||
|
||||
Sin link Conekta: el pago consolidado se dirige a SPEI.
|
||||
`lineas` = [{"texto": "HILUX · Renta mensual (2 meses)", "monto": 14312.40}].
|
||||
"""
|
||||
pl = plantilla or {}
|
||||
cuentas_inc = [c for c in (cuentas or []) if c.get("incluir_en_mensaje")]
|
||||
ahora = datetime.now(cobranza_acumulada.MEXICO)
|
||||
variables = {
|
||||
"cliente": cliente or "",
|
||||
"vehiculo": "",
|
||||
"monto": f"${total:,.2f}",
|
||||
"concepto": "",
|
||||
"mes": f"{_MESES_CORTO[ahora.month - 1]} {ahora.year}",
|
||||
"fecha": "",
|
||||
}
|
||||
out = ""
|
||||
if pl.get("saludo"):
|
||||
out += _aplicar_vars(pl["saludo"], variables) + "\n\n"
|
||||
intro = pl.get("texto_intro", "Le compartimos los datos para realizar su pago:")
|
||||
out += _aplicar_vars(intro, variables) + "\n\n"
|
||||
for ln in lineas:
|
||||
out += f"• {ln['texto']}: ${float(ln['monto']):,.2f}\n"
|
||||
out += "\n"
|
||||
texto_total = pl.get("texto_total", "Total a pagar: {monto}")
|
||||
out += _aplicar_vars(texto_total, variables) + "\n\n"
|
||||
out += _bloque_cuentas(cuentas_inc)
|
||||
if not cuentas_inc:
|
||||
out += "⚠️ No hay cuentas SPEI activadas.\n\n"
|
||||
if pl.get("despedida"):
|
||||
out += _aplicar_vars(pl["despedida"], variables)
|
||||
return out.strip()
|
||||
@@ -284,6 +342,7 @@ class PlantillaBody(BaseModel):
|
||||
texto_monto: str | None = None
|
||||
texto_fecha: str | None = None
|
||||
texto_link: str | None = None
|
||||
texto_total: str | None = None # línea del total en el cobro consolidado
|
||||
|
||||
|
||||
class EnviarMensajeBody(BaseModel):
|
||||
@@ -331,6 +390,10 @@ class CobrarLoteBody(BaseModel):
|
||||
filas: list[LoteFila]
|
||||
|
||||
|
||||
class CobroConsolidadoBody(BaseModel):
|
||||
ids: list[str] # renglones seleccionados (todos del mismo cliente)
|
||||
|
||||
|
||||
# ── Endpoints ───────────────────────────────────────────────────
|
||||
|
||||
@router.get("/api/validate")
|
||||
@@ -793,6 +856,59 @@ async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/cobro-consolidado")
|
||||
async def cobro_consolidado(body: CobroConsolidadoBody, token: str = Query(...)):
|
||||
"""Arma UN mensaje con el desglose de las subcuentas seleccionadas de un
|
||||
cliente + total. No envía nada: el frontend lo previsualiza y decide
|
||||
(enviar-mensaje-cliente / reenviar-mensaje-contacto). Sin link Conekta."""
|
||||
numero = await _numero_token(token)
|
||||
if not body.ids:
|
||||
raise HTTPException(status_code=400, detail="Selecciona al menos una subcuenta")
|
||||
renglones = {r.get("id"): r for r in await cobranza_acumulada.listar(numero)}
|
||||
sel = []
|
||||
for id in body.ids:
|
||||
r = renglones.get(id)
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail=f"Renglón no encontrado: {id}")
|
||||
sel.append(r)
|
||||
clientes = {cobranza_acumulada._norm(r.get("cliente") or "") for r in sel}
|
||||
if len(clientes) > 1:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="El cobro consolidado es por cliente: selecciona subcuentas de un solo cliente",
|
||||
)
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
lineas: list[dict] = []
|
||||
total = 0.0
|
||||
for r in sel:
|
||||
saldo = float(r.get("saldo") or 0.0)
|
||||
total += saldo
|
||||
extra = ""
|
||||
periodos = r.get("periodos") or []
|
||||
if (r.get("tipo") or "renta") == "renta" and len(periodos) >= 2:
|
||||
extra = f" ({len(periodos)} meses)"
|
||||
lineas.append({
|
||||
"texto": f"{r.get('vehiculo', '')} · {_tipo_label(r)}{extra}",
|
||||
"monto": saldo,
|
||||
})
|
||||
texto = _armar_mensaje_consolidado(
|
||||
cfg.get("plantilla") or {}, cfg.get("cuentas") or [],
|
||||
cliente=sel[0].get("cliente", ""), lineas=lineas, total=total,
|
||||
)
|
||||
# Renglón de referencia para resolver el teléfono al enviar: el primero
|
||||
# que ya tenga número; si ninguno tiene, el primero (el panel pedirá tel).
|
||||
id_ref = next(
|
||||
(r.get("id") for r in sel if r.get("telefono_efectivo")),
|
||||
sel[0].get("id"),
|
||||
)
|
||||
return {
|
||||
"texto": texto,
|
||||
"total": round(total, 2),
|
||||
"cliente": sel[0].get("cliente", ""),
|
||||
"id_ref": id_ref,
|
||||
}
|
||||
|
||||
|
||||
# ── Config GLOBAL (cuentas SPEI + plantilla del mensaje) ────────
|
||||
|
||||
@router.get("/api/config")
|
||||
|
||||
@@ -1568,6 +1568,8 @@ DEFAULT_PLANTILLA: dict = {
|
||||
"texto_monto": "Monto: {monto}",
|
||||
"texto_fecha": "Fecha límite: {fecha}",
|
||||
"texto_link": "Puede pagar con tarjeta, SPEI o efectivo en Oxxo desde este link:",
|
||||
# Línea del total en el cobro CONSOLIDADO (desglose por subcuentas).
|
||||
"texto_total": "Total a pagar: {monto}",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Cobro consolidado: UN mensaje por cliente con el desglose de las
|
||||
subcuentas seleccionadas + total, heredando la plantilla del panel
|
||||
(saludo/intro/cuentas SPEI/despedida). Sin link Conekta.
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
from src.api.cobranza_api import _armar_mensaje_consolidado, _tipo_label
|
||||
|
||||
|
||||
PLANTILLA = {
|
||||
"saludo": "Hola {cliente}, le saludamos.",
|
||||
"despedida": "Gracias, {cliente}.",
|
||||
"texto_intro": "Le compartimos los datos para realizar su pago:",
|
||||
}
|
||||
|
||||
CUENTAS = [
|
||||
{"id": "1", "banco": "BBVA", "beneficiario": "WK", "cuenta": "123",
|
||||
"clabe": "012345678901234567", "incluir_en_mensaje": True},
|
||||
{"id": "2", "banco": "OCULTA", "incluir_en_mensaje": False},
|
||||
]
|
||||
|
||||
LINEAS = [
|
||||
{"texto": "HILUX · Renta mensual (2 meses)", "monto": 14312.40},
|
||||
{"texto": "EXCAVADORA · Valor residual", "monto": 171774.46},
|
||||
]
|
||||
|
||||
|
||||
def test_consolidado_desglose_y_total():
|
||||
out = _armar_mensaje_consolidado(
|
||||
PLANTILLA, CUENTAS, cliente="GRUPO MEENT",
|
||||
lineas=LINEAS, total=186086.86,
|
||||
)
|
||||
assert "Hola GRUPO MEENT, le saludamos." in out
|
||||
assert "• HILUX · Renta mensual (2 meses): $14,312.40" in out
|
||||
assert "• EXCAVADORA · Valor residual: $171,774.46" in out
|
||||
assert "Total a pagar: $186,086.86" in out
|
||||
assert "🏦 BBVA" in out and "CLABE: 012345678901234567" in out
|
||||
assert "OCULTA" not in out # cuenta desactivada
|
||||
assert out.rstrip().endswith("Gracias, GRUPO MEENT.")
|
||||
# El desglose va ANTES del total y el total antes de las cuentas.
|
||||
assert out.index("• HILUX") < out.index("Total a pagar")
|
||||
assert out.index("Total a pagar") < out.index("🏦 BBVA")
|
||||
|
||||
|
||||
def test_consolidado_texto_total_configurable():
|
||||
pl = dict(PLANTILLA, texto_total="Suma de sus cobros: {monto}")
|
||||
out = _armar_mensaje_consolidado(
|
||||
pl, CUENTAS, cliente="ACME", lineas=LINEAS[:1], total=14312.40,
|
||||
)
|
||||
assert "Suma de sus cobros: $14,312.40" in out
|
||||
assert "Total a pagar" not in out
|
||||
|
||||
|
||||
def test_consolidado_sin_cuentas_avisa():
|
||||
out = _armar_mensaje_consolidado(
|
||||
PLANTILLA, [], cliente="ACME", lineas=LINEAS[:1], total=100.0,
|
||||
)
|
||||
assert "No hay cuentas SPEI activadas" in out
|
||||
assert "http" not in out # nunca lleva link
|
||||
|
||||
|
||||
def test_tipo_label():
|
||||
assert _tipo_label({"tipo": "renta"}) == "Renta mensual"
|
||||
assert _tipo_label({"tipo": "vr"}) == "Valor residual"
|
||||
assert _tipo_label({"tipo": "extra"}) == "Extraordinaria"
|
||||
assert _tipo_label({"tipo": "otro", "etiqueta": "Multa"}) == "Multa"
|
||||
assert _tipo_label({"tipo": "otro"}) == "Otro"
|
||||
assert _tipo_label({}) == "Renta mensual" # default renta
|
||||
+66
-1
@@ -465,6 +465,11 @@
|
||||
<label class="form-label">Concepto</label>
|
||||
<input type="text" class="form-input" id="pl-concepto" oninput="renderVistaPreviaMsg()" placeholder="Concepto: {concepto}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Total (cobro consolidado)</label>
|
||||
<input type="text" class="form-input" id="pl-total" placeholder="Total a pagar: {monto}">
|
||||
<div class="form-hint">Línea del total cuando cobras varias subcuentas juntas desde la vista Cuentas.</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Despedida</label>
|
||||
<textarea class="form-input" id="pl-despedida" rows="3" oninput="renderVistaPreviaMsg()"></textarea>
|
||||
@@ -856,7 +861,8 @@ function renderCuentas(){
|
||||
}).join("");
|
||||
const todas = sel.length === c.rs.length;
|
||||
const foot = sel.length
|
||||
? `<div class="cta-foot"><span>${sel.length} seleccionada${sel.length===1?"":"s"}</span><span class="val">${fmt(totalSel)}</span></div>`
|
||||
? `<div class="cta-foot"><span>${sel.length} seleccionada${sel.length===1?"":"s"}</span><span class="val">${fmt(totalSel)}</span></div>
|
||||
<button class="btn-wide lote" style="margin-top:10px" onclick="ctaCobroConsolidado(${i})"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg> Cobro consolidado (${sel.length})</button>`
|
||||
: `<div class="cta-foot empty">Toca una subcuenta para seleccionarla y ver el total a cobrar.</div>`;
|
||||
body = `
|
||||
<div class="cta-body">
|
||||
@@ -897,6 +903,63 @@ function ctaSelTodo(i){
|
||||
renderCuentas();
|
||||
}
|
||||
|
||||
// ── Cobro consolidado: un mensaje con el desglose de la selección ──
|
||||
let consolidadoState = null; // {texto, total, cliente, id_ref} del backend
|
||||
|
||||
async function ctaCobroConsolidado(i){
|
||||
const c = ctaClientes[i]; if(!c) return;
|
||||
const ids = c.rs.filter(r => ctaSel.has(r.id)).map(r => r.id);
|
||||
if(!ids.length){ toast("Selecciona al menos una subcuenta"); return; }
|
||||
try {
|
||||
const res = await api("/cobro-consolidado", {method:"POST", body: JSON.stringify({ids})});
|
||||
mostrarPreviewConsolidado(res);
|
||||
} catch(e){ toast("No se pudo generar: " + e.message); }
|
||||
}
|
||||
|
||||
function mostrarPreviewConsolidado(res){
|
||||
consolidadoState = res;
|
||||
const opciones = CONTACTOS.map(c => `<option>${c}</option>`).join("");
|
||||
document.getElementById("modal-inner").classList.remove("lote");
|
||||
document.getElementById("modal-inner").innerHTML = `
|
||||
<div class="modal-header"><span class="modal-title">Cobro consolidado</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||||
<div style="font-size:13px;color:var(--text-secondary);margin-bottom:0.8rem">${res.cliente}<br>Total: <strong style="color:var(--text-primary)">${fmt(res.total)}</strong></div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Mensaje (editable antes de enviar)</label>
|
||||
<textarea class="form-input" id="consolidado-texto" rows="14" style="font-family:'DM Sans',sans-serif;font-size:12.5px;line-height:1.5">${escapeAttr(res.texto)}</textarea>
|
||||
</div>
|
||||
<div class="entrega-label">¿Cómo lo entregas?</div>
|
||||
<button class="btn-cliente" onclick="enviarConsolidadoCliente()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg> Enviar al cliente</button>
|
||||
<div class="reenvio-divider">o reenviar a un contacto</div>
|
||||
<div class="reenvio-row">
|
||||
<select id="sel-contacto-consolidado">${opciones}</select>
|
||||
<button class="btn-reenviar" onclick="reenviarConsolidadoContacto()"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button>
|
||||
</div>`;
|
||||
document.getElementById("modal").classList.add("open");
|
||||
}
|
||||
|
||||
async function enviarConsolidadoCliente(){
|
||||
const texto = document.getElementById("consolidado-texto").value;
|
||||
const r = renglones.find(x => x.id === consolidadoState.id_ref);
|
||||
if(!r || !(r.telefono_efectivo || r.telefono)){
|
||||
toast("El cliente no tiene teléfono. Agrégalo primero");
|
||||
if(r) editarTel(r.id);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api("/enviar-mensaje-cliente", {method:"POST", body: JSON.stringify({id: consolidadoState.id_ref, texto})});
|
||||
toast("Cobro consolidado enviado"); cerrar();
|
||||
} catch(e){ toast("No se pudo enviar: " + e.message); }
|
||||
}
|
||||
|
||||
async function reenviarConsolidadoContacto(){
|
||||
const c = document.getElementById("sel-contacto-consolidado").value;
|
||||
const texto = document.getElementById("consolidado-texto").value;
|
||||
try {
|
||||
await api("/reenviar-mensaje-contacto", {method:"POST", body: JSON.stringify({id: consolidadoState.id_ref, contacto: c, texto})});
|
||||
toast("Reenviado a " + c); cerrar();
|
||||
} catch(e){ toast("No se pudo reenviar: " + e.message); }
|
||||
}
|
||||
|
||||
function renderTarjetas(){
|
||||
const lista = document.getElementById("lista");
|
||||
lista.innerHTML = "";
|
||||
@@ -2062,6 +2125,7 @@ function rellenarPlantillaInputs(){
|
||||
document.getElementById("pl-saludo").value = p.saludo || "";
|
||||
document.getElementById("pl-intro").value = p.texto_intro != null ? p.texto_intro : "Le compartimos los datos para realizar su pago:";
|
||||
document.getElementById("pl-concepto").value = p.texto_concepto != null ? p.texto_concepto : "Concepto: {concepto}";
|
||||
document.getElementById("pl-total").value = p.texto_total != null ? p.texto_total : "Total a pagar: {monto}";
|
||||
document.getElementById("pl-despedida").value = p.despedida || "";
|
||||
document.getElementById("pl-cliente").checked = p.incluir_cliente !== false;
|
||||
document.getElementById("pl-vehiculo").checked = p.incluir_vehiculo !== false;
|
||||
@@ -2081,6 +2145,7 @@ async function guardarPlantilla(){
|
||||
saludo: document.getElementById("pl-saludo").value,
|
||||
texto_intro: document.getElementById("pl-intro").value,
|
||||
texto_concepto: document.getElementById("pl-concepto").value,
|
||||
texto_total: document.getElementById("pl-total").value,
|
||||
despedida: document.getElementById("pl-despedida").value,
|
||||
incluir_cliente: document.getElementById("pl-cliente").checked,
|
||||
incluir_vehiculo: document.getElementById("pl-vehiculo").checked,
|
||||
|
||||
Reference in new issue
Block a user