Merge remote-tracking branch 'upstream/main'
This commit is contained in:
commit
a54761cce0
10 files changed
+1774
-38
No files matched your search
+271
-11
@@ -10,14 +10,21 @@ import calendar
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.responses import HTMLResponse, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.services import cobranza_acumulada, pagos, recordatorios, sheets, whatsapp
|
||||
from src.services import (
|
||||
cobranza_acumulada,
|
||||
estado_cuenta,
|
||||
pagos,
|
||||
recordatorios,
|
||||
sheets,
|
||||
whatsapp,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -122,8 +129,10 @@ def _armar_mensaje_plantilla(
|
||||
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"
|
||||
intro = pl.get("texto_intro", "Le compartimos los datos para realizar su pago:")
|
||||
concepto_txt = pl.get("texto_concepto", "Concepto: {concepto}")
|
||||
out += _aplicar_vars(intro, variables) + "\n\n"
|
||||
out += _aplicar_vars(concepto_txt, variables) + "\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:
|
||||
@@ -133,6 +142,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"):
|
||||
@@ -142,10 +163,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()
|
||||
@@ -173,6 +240,7 @@ class IdBody(BaseModel):
|
||||
class MarcarPagadoBody(BaseModel):
|
||||
id: str
|
||||
nota: str | None = None
|
||||
fecha: str | None = None # ISO YYYY-MM-DD del pago (default hoy)
|
||||
|
||||
|
||||
class PeriodoSaldarBody(BaseModel):
|
||||
@@ -184,6 +252,30 @@ class AbonoBody(BaseModel):
|
||||
id: str
|
||||
monto: float
|
||||
concepto: str | None = ""
|
||||
fecha: str | None = None # ISO YYYY-MM-DD del pago (default hoy)
|
||||
|
||||
|
||||
class MovimientosVisiblesBody(BaseModel):
|
||||
movimientos_visibles: int
|
||||
|
||||
|
||||
def _abono_excede_saldo(monto: float, saldo: float) -> bool:
|
||||
"""El abono no puede superar el saldo vigente de la subcuenta.
|
||||
Tolerancia de 1 centavo por redondeos de display."""
|
||||
return float(monto) > float(saldo) + 0.01
|
||||
|
||||
|
||||
def _validar_fecha_opcional(fecha: str | None) -> str | None:
|
||||
"""Devuelve la fecha ISO limpia, None si no vino, o lanza 400 si es inválida."""
|
||||
fecha = (fecha or "").strip()
|
||||
if not fecha:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(fecha).isoformat()
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="Fecha inválida (usa YYYY-MM-DD)",
|
||||
)
|
||||
|
||||
|
||||
class RenglonEditBody(BaseModel):
|
||||
@@ -256,11 +348,14 @@ class PlantillaBody(BaseModel):
|
||||
incluir_fecha_limite: bool | None = None
|
||||
incluir_link: bool | None = None
|
||||
# Texto editable de cada bloque del cuerpo.
|
||||
texto_intro: str | None = None
|
||||
texto_concepto: str | None = None
|
||||
texto_cliente: str | None = None
|
||||
texto_vehiculo: str | None = None
|
||||
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):
|
||||
@@ -308,6 +403,10 @@ class CobrarLoteBody(BaseModel):
|
||||
filas: list[LoteFila]
|
||||
|
||||
|
||||
class CobroConsolidadoBody(BaseModel):
|
||||
ids: list[str] # renglones seleccionados (todos del mismo cliente)
|
||||
|
||||
|
||||
# ── Endpoints ───────────────────────────────────────────────────
|
||||
|
||||
@router.get("/api/validate")
|
||||
@@ -327,7 +426,10 @@ async def listar(token: str = Query(...)):
|
||||
@router.post("/api/marcar-pagado")
|
||||
async def marcar_pagado(body: MarcarPagadoBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
ok = await cobranza_acumulada.marcar_pagado(numero, body.id, body.nota or "")
|
||||
fecha = _validar_fecha_opcional(body.fecha)
|
||||
ok = await cobranza_acumulada.marcar_pagado(
|
||||
numero, body.id, body.nota or "", fecha=fecha,
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||
return {"ok": True}
|
||||
@@ -357,8 +459,16 @@ async def abono(body: AbonoBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
if body.monto <= 0:
|
||||
raise HTTPException(status_code=400, detail="Monto debe ser > 0")
|
||||
fecha = _validar_fecha_opcional(body.fecha)
|
||||
r = await _buscar_renglon(numero, body.id) # 404 si no existe
|
||||
saldo = float(r.get("saldo") or 0.0)
|
||||
if _abono_excede_saldo(body.monto, saldo):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"El abono (${body.monto:,.2f}) excede el saldo actual (${saldo:,.2f})",
|
||||
)
|
||||
ok = await cobranza_acumulada.registrar_abono(
|
||||
numero, body.id, body.monto, body.concepto or "",
|
||||
numero, body.id, body.monto, body.concepto or "", fecha=fecha,
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||
@@ -392,6 +502,89 @@ async def abono_cancelar(body: AbonoIdBody, token: str = Query(...)):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/api/movimientos")
|
||||
async def movimientos(
|
||||
token: str = Query(...),
|
||||
cliente: str | None = Query(default=None),
|
||||
vehiculo: str | None = Query(default=None),
|
||||
tipo: str | None = Query(default=None),
|
||||
renglon_id: str | None = Query(default=None),
|
||||
limite: int | None = Query(default=None, ge=1, le=cobranza_acumulada.MOV_MAX),
|
||||
):
|
||||
"""Bitácora de movimientos (abonos/saldados), más recientes primero.
|
||||
|
||||
Sin `limite` explícito aplica `movimientos_visibles` de la config global.
|
||||
Filtros opcionales por subcuenta (cliente/vehiculo/tipo) y por renglón
|
||||
exacto (`renglon_id`, distingue dos subcuentas con la misma identidad).
|
||||
"""
|
||||
numero = await _numero_token(token)
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
visibles = cfg.get("movimientos_visibles") or cobranza_acumulada.MOV_DEFAULT_VISIBLES
|
||||
movs = await cobranza_acumulada.obtener_movimientos(
|
||||
numero, cliente=cliente, vehiculo=vehiculo, tipo=tipo,
|
||||
renglon_id=renglon_id, limite=limite or visibles,
|
||||
)
|
||||
return {"movimientos": movs, "visibles": visibles}
|
||||
|
||||
|
||||
@router.get("/api/estado-cuenta.pdf")
|
||||
async def estado_cuenta_pdf(
|
||||
token: str = Query(...),
|
||||
cliente: str = Query(...),
|
||||
limite: int | None = Query(default=None, ge=1, le=cobranza_acumulada.MOV_MAX),
|
||||
vehiculo: str | None = Query(default=None),
|
||||
tipo: str | None = Query(default=None),
|
||||
ids: str | None = Query(default=None),
|
||||
):
|
||||
"""Estado de cuenta PDF de un cliente: saldos vigentes por subcuenta +
|
||||
últimos X movimientos de la bitácora (X = config `movimientos_visibles`
|
||||
o el `limite` pedido).
|
||||
|
||||
`ids` (CSV de ids de renglón) acota el reporte a subcuentas EXACTAS:
|
||||
una (botón Exportar del modal Movs) o varias (botón 'Imprimir
|
||||
movimientos' de la selección en la vista Cuentas)."""
|
||||
numero = await _numero_token(token)
|
||||
objetivo = cobranza_acumulada._norm(cliente)
|
||||
veh_obj = cobranza_acumulada._norm(vehiculo) if vehiculo else None
|
||||
ids_sel = [s for s in (ids or "").split(",") if s.strip()] or None
|
||||
renglones = [
|
||||
r for r in await cobranza_acumulada.listar(numero)
|
||||
if cobranza_acumulada._norm(r.get("cliente") or "") == objetivo
|
||||
and (veh_obj is None
|
||||
or cobranza_acumulada._norm(r.get("vehiculo") or "") == veh_obj)
|
||||
and (tipo is None or (r.get("tipo") or "renta") == tipo)
|
||||
and (ids_sel is None or r.get("id") in ids_sel)
|
||||
]
|
||||
cfg = await cobranza_acumulada.obtener_config_global()
|
||||
visibles = (
|
||||
limite or cfg.get("movimientos_visibles")
|
||||
or cobranza_acumulada.MOV_DEFAULT_VISIBLES
|
||||
)
|
||||
movs = await cobranza_acumulada.obtener_movimientos(
|
||||
numero, cliente=cliente, vehiculo=vehiculo, tipo=tipo,
|
||||
renglon_ids=ids_sel, limite=visibles,
|
||||
)
|
||||
if not renglones and not movs:
|
||||
raise HTTPException(status_code=404, detail="Sin datos de ese cliente")
|
||||
nombre = renglones[0].get("cliente") if renglones else (
|
||||
movs[0].get("cliente") or cliente
|
||||
)
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente=nombre, renglones=renglones, movimientos=movs,
|
||||
visibles=visibles,
|
||||
)
|
||||
base = cliente if not vehiculo else f"{cliente}-{vehiculo}"
|
||||
slug = re.sub(r"[^A-Za-z0-9]+", "-", base).strip("-").lower() or "cliente"
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition":
|
||||
f'inline; filename="estado-cuenta-{slug}.pdf"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.put("/api/renglon")
|
||||
async def editar(body: RenglonEditBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
@@ -743,6 +936,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")
|
||||
@@ -778,6 +1024,20 @@ async def config_plantilla_guardar(body: PlantillaBody, token: str = Query(...))
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/config/movimientos")
|
||||
async def config_movimientos_guardar(
|
||||
body: MovimientosVisiblesBody, token: str = Query(...),
|
||||
):
|
||||
"""Cuántos movimientos de la bitácora se muestran (el storage guarda todos)."""
|
||||
await _numero_token(token)
|
||||
if body.movimientos_visibles < 1:
|
||||
raise HTTPException(status_code=400, detail="Debe ser al menos 1")
|
||||
n = await cobranza_acumulada.guardar_movimientos_visibles(
|
||||
body.movimientos_visibles,
|
||||
)
|
||||
return {"movimientos_visibles": n}
|
||||
|
||||
|
||||
# ── Envío genérico (mensaje pre-armado por el frontend) ─────────
|
||||
|
||||
@router.post("/api/enviar-mensaje-cliente")
|
||||
|
||||
@@ -122,6 +122,133 @@ async def _push_historial(numero: str, descripcion: str) -> None:
|
||||
logger.exception("Error empujando historial de %s", numero)
|
||||
|
||||
|
||||
# ── Bitácora de movimientos (ledger) ────────────────────────────
|
||||
# Independiente de los renglones: los renglones se BORRAN al saldarse,
|
||||
# pero la bitácora sobrevive (estado de cuenta / historial por subcuenta).
|
||||
# Storage: lista Redis `cobranza_mov:{numero}`, más reciente primero
|
||||
# (LPUSH), tope MOV_MAX. La config `movimientos_visibles` solo limita
|
||||
# cuántos se MUESTRAN, no cuántos se guardan.
|
||||
|
||||
MOV_MAX = 500
|
||||
MOV_DEFAULT_VISIBLES = 10
|
||||
|
||||
|
||||
def _key_mov(numero: str) -> str:
|
||||
return f"cobranza_mov:{numero}"
|
||||
|
||||
|
||||
def _fecha_o_hoy(fecha: str | None) -> str:
|
||||
"""Fecha ISO validada; inválida o vacía → hoy (MX)."""
|
||||
try:
|
||||
return date.fromisoformat((fecha or "").strip()).isoformat()
|
||||
except (TypeError, ValueError):
|
||||
return _hoy_mx().isoformat()
|
||||
|
||||
|
||||
async def registrar_movimiento(
|
||||
numero: str,
|
||||
r: dict,
|
||||
movimiento: str,
|
||||
monto: float,
|
||||
fecha: str | None = None,
|
||||
nota: str = "",
|
||||
saldo_despues: float | None = None,
|
||||
) -> None:
|
||||
"""Anota un movimiento en la bitácora de la subcuenta del renglón `r`.
|
||||
|
||||
Best-effort: la bitácora nunca tumba la operación principal.
|
||||
`movimiento` ∈ {"abono", "saldado", "saldo_periodo"}.
|
||||
|
||||
Incluye un SNAPSHOT de la subcuenta al momento del movimiento
|
||||
(capital, abonado acumulado, fecha_alta): el renglón puede borrarse
|
||||
después (al saldarse) y el estado de cuenta necesita ese contexto.
|
||||
"""
|
||||
try:
|
||||
mov = {
|
||||
"id": uuid.uuid4().hex[:8],
|
||||
# Renglón exacto al que pertenece: distingue dos subcuentas con
|
||||
# la misma identidad (ej. dos VR del mismo vehículo con
|
||||
# vencimientos distintos).
|
||||
"renglon_id": r.get("id") or "",
|
||||
"fecha": _fecha_o_hoy(fecha),
|
||||
"fecha_registro": datetime.now(MEXICO).isoformat(),
|
||||
"cliente": r.get("cliente") or "",
|
||||
"vehiculo": r.get("vehiculo") or "",
|
||||
"tipo": r.get("tipo") or "renta",
|
||||
"etiqueta": r.get("etiqueta") or "",
|
||||
"movimiento": movimiento,
|
||||
"monto": round(float(monto or 0.0), 2),
|
||||
"nota": nota or "",
|
||||
# Snapshot de la subcuenta al momento del movimiento.
|
||||
"capital": round(_capital(r), 2),
|
||||
"abonado": _abonado(r),
|
||||
"fecha_alta": r.get("fecha_alta") or "",
|
||||
# Saldo que queda DESPUÉS del movimiento. Los callers que
|
||||
# borran el renglón (saldar) pasan 0.0 explícito; el default
|
||||
# lo calcula del renglón ya mutado.
|
||||
"saldo_despues": round(float(
|
||||
saldo_despues if saldo_despues is not None
|
||||
else _saldo(r, _hoy_mx())
|
||||
), 2),
|
||||
}
|
||||
cli = get_client()
|
||||
await cli.lpush(_key_mov(numero), json.dumps(mov, ensure_ascii=False))
|
||||
await cli.ltrim(_key_mov(numero), 0, MOV_MAX - 1)
|
||||
except Exception:
|
||||
logger.exception("Error registrando movimiento de %s", numero)
|
||||
|
||||
|
||||
async def obtener_movimientos(
|
||||
numero: str,
|
||||
cliente: str | None = None,
|
||||
vehiculo: str | None = None,
|
||||
tipo: str | None = None,
|
||||
limite: int | None = None,
|
||||
renglon_id: str | None = None,
|
||||
renglon_ids: list[str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""Movimientos más recientes primero, con filtros opcionales.
|
||||
|
||||
El match de cliente/vehículo usa `_norm` (mismo criterio que el
|
||||
identificador de renglón), así el historial sigue encontrándose
|
||||
aunque el renglón se haya borrado y regenerado.
|
||||
|
||||
`renglon_id` (uno) o `renglon_ids` (varios, ej. la selección del
|
||||
panel) acotan a renglones EXACTOS: necesario cuando coexisten dos
|
||||
subcuentas con la misma identidad (dos VR del mismo vehículo).
|
||||
Movimientos sin el campo (previos) quedan fuera de ese filtro.
|
||||
"""
|
||||
ids_exactos: set[str] = set()
|
||||
if renglon_id:
|
||||
ids_exactos.add(renglon_id)
|
||||
if renglon_ids:
|
||||
ids_exactos.update(renglon_ids)
|
||||
try:
|
||||
cli = get_client()
|
||||
raw = await cli.lrange(_key_mov(numero), 0, MOV_MAX - 1)
|
||||
except Exception:
|
||||
logger.exception("Error leyendo movimientos de %s", numero)
|
||||
return []
|
||||
out: list[dict] = []
|
||||
for item in raw:
|
||||
try:
|
||||
m = json.loads(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if cliente is not None and _norm(m.get("cliente") or "") != _norm(cliente):
|
||||
continue
|
||||
if vehiculo is not None and _norm(m.get("vehiculo") or "") != _norm(vehiculo):
|
||||
continue
|
||||
if tipo is not None and (m.get("tipo") or "renta") != tipo:
|
||||
continue
|
||||
if ids_exactos and m.get("renglon_id") not in ids_exactos:
|
||||
continue
|
||||
out.append(m)
|
||||
if limite and len(out) >= limite:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
# ── Cálculos del moratorio ──────────────────────────────────────
|
||||
|
||||
def _hoy_mx() -> date:
|
||||
@@ -721,27 +848,38 @@ def telefono_efectivo(renglon: dict, directorio: dict[str, str]) -> str:
|
||||
return directorio.get(cliente_norm, "")
|
||||
|
||||
|
||||
async def marcar_pagado(numero: str, id: str, nota: str = "Saldado manualmente") -> bool:
|
||||
async def marcar_pagado(
|
||||
numero: str, id: str, nota: str = "Saldado manualmente",
|
||||
fecha: str | None = None,
|
||||
) -> bool:
|
||||
"""Saldar = BORRAR el renglón completo. Libera el identificador único para
|
||||
que 'cargar cobranza de hoy' pueda volver a traer ese concepto en el
|
||||
siguiente periodo. DESHACER recrea el renglón completo desde el snapshot.
|
||||
|
||||
Para RENTA (modelo de periodos) esto equivale a "saldar TODOS los periodos":
|
||||
el renglón desaparece. Para saldar UN periodo específico usa `saldar_periodo`.
|
||||
|
||||
`fecha` (ISO, opcional) es la fecha del pago que queda en la bitácora;
|
||||
default hoy. El monto saldado registrado es el saldo vigente.
|
||||
"""
|
||||
actuales = await _load(numero)
|
||||
hoy_iso = _hoy_mx().isoformat()
|
||||
hoy = _hoy_mx()
|
||||
for r in actuales:
|
||||
if r.get("id") == id:
|
||||
await _push_historial(numero, f"saldar {r.get('cliente','')}")
|
||||
saldado = _saldo(r, hoy)
|
||||
logger.info(
|
||||
"saldado/borrado: %s | %s | %s | $%.2f | %s",
|
||||
r.get("cliente",""), r.get("vehiculo",""),
|
||||
r.get("tipo","renta"), float(r.get("monto") or 0.0),
|
||||
hoy_iso,
|
||||
hoy.isoformat(),
|
||||
)
|
||||
nuevos = [x for x in actuales if x.get("id") != id]
|
||||
await _save(numero, nuevos)
|
||||
await registrar_movimiento(
|
||||
numero, r, "saldado", saldado, fecha=fecha, nota=nota,
|
||||
saldo_despues=0.0,
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -771,6 +909,12 @@ async def saldar_periodo(numero: str, id_renglon: str, periodo: str) -> bool:
|
||||
if len(restantes) == len(periodos):
|
||||
return False # el periodo no existía
|
||||
await _push_historial(numero, f"saldar periodo {periodo} {r.get('cliente','')}")
|
||||
hoy = _hoy_mx()
|
||||
tasa = float(r.get("tasa_mensual") or DEFAULT_TASA_MENSUAL)
|
||||
saldado_periodo = round(sum(
|
||||
float(p.get("mensualidad") or 0.0) + _mora_periodo(p, tasa, hoy)
|
||||
for p in periodos if p.get("periodo") == periodo
|
||||
), 2)
|
||||
if not restantes:
|
||||
# Sin periodos → se borra el renglón (como saldar todo).
|
||||
nuevos = [x for x in actuales if x.get("id") != id_renglon]
|
||||
@@ -779,6 +923,10 @@ async def saldar_periodo(numero: str, id_renglon: str, periodo: str) -> bool:
|
||||
r.get("cliente", ""), r.get("vehiculo", ""), periodo,
|
||||
)
|
||||
await _save(numero, nuevos)
|
||||
await registrar_movimiento(
|
||||
numero, r, "saldo_periodo", saldado_periodo,
|
||||
nota=f"mes {periodo}", saldo_despues=0.0,
|
||||
)
|
||||
return True
|
||||
r["periodos"] = restantes
|
||||
r["monto"] = round(sum(float(p.get("mensualidad") or 0.0) for p in restantes), 2)
|
||||
@@ -787,31 +935,46 @@ async def saldar_periodo(numero: str, id_renglon: str, periodo: str) -> bool:
|
||||
r.get("cliente", ""), r.get("vehiculo", ""), periodo, len(restantes),
|
||||
)
|
||||
await _save(numero, actuales)
|
||||
await registrar_movimiento(
|
||||
numero, r, "saldo_periodo", saldado_periodo, nota=f"mes {periodo}",
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def registrar_abono(numero: str, id: str, monto: float, concepto: str) -> bool:
|
||||
"""Compat: crea un abono ya PAGADO (resta del saldo inmediatamente).
|
||||
async def registrar_abono(
|
||||
numero: str, id: str, monto: float, concepto: str,
|
||||
fecha: str | None = None,
|
||||
) -> bool:
|
||||
"""Crea un abono ya PAGADO (resta del saldo inmediatamente).
|
||||
|
||||
Lo usa el endpoint /api/abono y el webhook Conekta cuando recibe un pago
|
||||
con referencia legacy `{numero}:{id}:personal` (sin id_abono).
|
||||
|
||||
`fecha` (ISO, opcional) es la fecha del pago capturada por el usuario;
|
||||
default hoy. Queda en el abono y en la bitácora. El saldo se calcula
|
||||
a HOY (resta simple: la mora sigue corriendo sobre lo pendiente).
|
||||
"""
|
||||
if monto <= 0:
|
||||
return False
|
||||
actuales = await _load(numero)
|
||||
hoy = _hoy_mx()
|
||||
fecha_pago = _fecha_o_hoy(fecha)
|
||||
for r in actuales:
|
||||
if r.get("id") == id:
|
||||
await _push_historial(numero, f"abono {r.get('cliente','')}")
|
||||
r.setdefault("abonos", []).append({
|
||||
"id": uuid.uuid4().hex[:8],
|
||||
"fecha": hoy.isoformat(),
|
||||
"fecha_pago": hoy.isoformat(),
|
||||
"fecha": fecha_pago,
|
||||
"fecha_pago": fecha_pago,
|
||||
"monto": round(float(monto), 2),
|
||||
"concepto": concepto or "",
|
||||
"estado": "pagado",
|
||||
})
|
||||
await registrar_movimiento(
|
||||
numero, r, "abono", monto, fecha=fecha_pago,
|
||||
nota=concepto or "",
|
||||
)
|
||||
if _saldo(r, hoy) <= 0.5:
|
||||
# Saldar = borrar. DESHACER restaura desde el snapshot.
|
||||
logger.info(
|
||||
@@ -872,6 +1035,10 @@ async def saldar_abono(numero: str, id_renglon: str, id_abono: str) -> bool:
|
||||
await _push_historial(numero, f"saldar abono {r.get('cliente','')}")
|
||||
a["estado"] = "pagado"
|
||||
a["fecha_pago"] = hoy.isoformat()
|
||||
await registrar_movimiento(
|
||||
numero, r, "abono", float(a.get("monto") or 0.0),
|
||||
fecha=hoy.isoformat(), nota=a.get("concepto") or "",
|
||||
)
|
||||
if _saldo(r, hoy) <= 0.5:
|
||||
# Cierre por abono = borrar. DESHACER lo revive.
|
||||
logger.info(
|
||||
@@ -1147,8 +1314,28 @@ async def deshacer(numero: str) -> dict | None:
|
||||
|
||||
# ── Detección/limpieza de duplicados (red de seguridad) ─────────
|
||||
|
||||
def _clave_duplicado(r: dict) -> str:
|
||||
"""Clave para detectar duplicados REALES (no cobros legítimamente distintos).
|
||||
|
||||
- renta: identidad = cliente|vehiculo|renta (una renta por vehículo; los meses
|
||||
se acumulan como periodos DENTRO del renglón).
|
||||
- vr/extra/otro: dos cobros del mismo vehículo con DISTINTO vencimiento o monto
|
||||
son distintos (p.ej. dos VR del mismo activo que vencen en fechas distintas),
|
||||
así que la clave incluye fecha_vencimiento + monto (+ etiqueta para 'otro').
|
||||
Solo coincidencias EXACTAS cuentan como duplicado.
|
||||
"""
|
||||
tipo = r.get("tipo") or "renta"
|
||||
base = identificador(r.get("cliente", ""), r.get("vehiculo", ""), tipo)
|
||||
if tipo == "renta":
|
||||
return base
|
||||
fv = (r.get("fecha_vencimiento") or "").strip()
|
||||
monto = round(float(r.get("monto") or 0.0), 2)
|
||||
etiqueta = (r.get("etiqueta") or "").strip().lower() if tipo == "otro" else ""
|
||||
return f"{base}|{fv}|{monto}|{etiqueta}"
|
||||
|
||||
|
||||
async def detectar_duplicados(numero: str) -> list[dict]:
|
||||
"""Devuelve los grupos cuyo identificador único se repite.
|
||||
"""Devuelve los grupos cuya clave de duplicado se repite.
|
||||
|
||||
Cada grupo es {"ident", "renglones": [...] con los datos decorados}.
|
||||
"""
|
||||
@@ -1156,11 +1343,7 @@ async def detectar_duplicados(numero: str) -> list[dict]:
|
||||
hoy = _hoy_mx()
|
||||
grupos: dict[str, list[dict]] = {}
|
||||
for r in actuales:
|
||||
ident = identificador(
|
||||
r.get("cliente", ""), r.get("vehiculo", ""),
|
||||
r.get("tipo") or "renta",
|
||||
)
|
||||
grupos.setdefault(ident, []).append(_decorar(r, hoy))
|
||||
grupos.setdefault(_clave_duplicado(r), []).append(_decorar(r, hoy))
|
||||
return [
|
||||
{"ident": k, "renglones": v}
|
||||
for k, v in grupos.items()
|
||||
@@ -1176,11 +1359,7 @@ async def eliminar_duplicados(numero: str) -> dict:
|
||||
actuales = await _load(numero)
|
||||
grupos: dict[str, list[dict]] = {}
|
||||
for r in actuales:
|
||||
ident = identificador(
|
||||
r.get("cliente", ""), r.get("vehiculo", ""),
|
||||
r.get("tipo") or "renta",
|
||||
)
|
||||
grupos.setdefault(ident, []).append(r)
|
||||
grupos.setdefault(_clave_duplicado(r), []).append(r)
|
||||
|
||||
a_borrar_ids: set[str] = set()
|
||||
for ident, lista in grupos.items():
|
||||
@@ -1417,11 +1596,15 @@ DEFAULT_PLANTILLA: dict = {
|
||||
"incluir_link": True,
|
||||
# Texto editable de cada bloque del cuerpo (soporta variables {cliente},
|
||||
# {vehiculo}, {monto}, {fecha}, {concepto}, {mes}).
|
||||
"texto_intro": "Le compartimos los datos para realizar su pago:",
|
||||
"texto_concepto": "Concepto: {concepto}",
|
||||
"texto_cliente": "Cliente: {cliente}",
|
||||
"texto_vehiculo": "Vehículo: {vehiculo}",
|
||||
"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}",
|
||||
}
|
||||
|
||||
|
||||
@@ -1429,9 +1612,14 @@ def _normalizar_config(cfg: dict | None) -> dict:
|
||||
cfg = dict(cfg or {})
|
||||
plantilla = dict(DEFAULT_PLANTILLA)
|
||||
plantilla.update(cfg.get("plantilla") or {})
|
||||
try:
|
||||
visibles = int(cfg.get("movimientos_visibles") or MOV_DEFAULT_VISIBLES)
|
||||
except (TypeError, ValueError):
|
||||
visibles = MOV_DEFAULT_VISIBLES
|
||||
return {
|
||||
"cuentas": list(cfg.get("cuentas") or []),
|
||||
"plantilla": plantilla,
|
||||
"movimientos_visibles": max(1, min(MOV_MAX, visibles)),
|
||||
}
|
||||
|
||||
|
||||
@@ -1502,6 +1690,16 @@ async def eliminar_cuenta_global(id: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
async def guardar_movimientos_visibles(n: int) -> int:
|
||||
"""Fija cuántos movimientos de la bitácora se MUESTRAN (1..MOV_MAX).
|
||||
El almacenamiento siempre conserva hasta MOV_MAX; esto es solo display."""
|
||||
n = max(1, min(MOV_MAX, int(n)))
|
||||
cfg = await obtener_config_global()
|
||||
cfg["movimientos_visibles"] = n
|
||||
await _save_config_global(cfg)
|
||||
return n
|
||||
|
||||
|
||||
async def guardar_plantilla_global(plantilla: dict) -> dict:
|
||||
"""Aplica un parche sobre la plantilla actual (campos None se ignoran)."""
|
||||
cfg = await obtener_config_global()
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
"""
|
||||
Estado de cuenta en PDF (ReportLab) para un cliente de cobranza.
|
||||
|
||||
Dos secciones:
|
||||
1. SALDOS VIGENTES — las subcuentas activas del cliente (renglones ya
|
||||
decorados por `cobranza_acumulada.listar`): capital, mora, abonado
|
||||
y saldo, con total.
|
||||
2. MOVIMIENTOS — los últimos X de la bitácora (`cobranza_mov`), más
|
||||
recientes primero. X es `movimientos_visibles` de la config global
|
||||
(el mismo de la pestaña Mensaje), o el `limite` pedido.
|
||||
|
||||
No consulta nada: recibe datos ya cargados y devuelve bytes del PDF.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.platypus import (
|
||||
Paragraph,
|
||||
SimpleDocTemplate,
|
||||
Spacer,
|
||||
Table,
|
||||
TableStyle,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MEXICO = ZoneInfo("America/Mexico_City")
|
||||
|
||||
# Membrete W+k: la MISMA hoja membretada de la plantilla de cotización
|
||||
# (Plantilla_WK2.docm → word/media/image1.jpeg, página carta completa con
|
||||
# logo, dirección y marca de agua). Se extrae en runtime para heredar
|
||||
# automáticamente cualquier cambio de branding en la plantilla.
|
||||
TEMPLATE_PATH = Path(__file__).resolve().parents[2] / "Plantilla_WK2.docm"
|
||||
|
||||
_membrete_cache: ImageReader | None = None
|
||||
_membrete_probado = False
|
||||
|
||||
|
||||
def _membrete() -> ImageReader | None:
|
||||
global _membrete_cache, _membrete_probado
|
||||
if not _membrete_probado:
|
||||
_membrete_probado = True
|
||||
try:
|
||||
with zipfile.ZipFile(TEMPLATE_PATH) as z:
|
||||
_membrete_cache = ImageReader(
|
||||
BytesIO(z.read("word/media/image1.jpeg")),
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Sin membrete WK (%s): estado de cuenta sin fondo",
|
||||
TEMPLATE_PATH,
|
||||
)
|
||||
_membrete_cache = None
|
||||
return _membrete_cache
|
||||
|
||||
|
||||
# Navy del logotipo W+k consulting (encabezados de tabla y títulos).
|
||||
_ACCENT = colors.HexColor("#3a3467")
|
||||
_GRIS = colors.HexColor("#586173")
|
||||
_LINEA = colors.HexColor("#d4dae4")
|
||||
_FILA_ALT = colors.HexColor("#f4f6fa")
|
||||
|
||||
_TIPO_LABEL = {"renta": "Renta mensual", "extra": "Extraordinaria",
|
||||
"vr": "Valor residual"}
|
||||
|
||||
_MOV_LABEL = {"abono": "Abono", "saldado": "Saldado",
|
||||
"saldo_periodo": "Mes saldado"}
|
||||
|
||||
|
||||
def _money(x: float) -> str:
|
||||
return f"${float(x or 0.0):,.2f}"
|
||||
|
||||
|
||||
def _fecha_es(iso: str) -> str:
|
||||
"""'2026-08-04' → '04/08/2026' (best-effort)."""
|
||||
s = (iso or "")[:10]
|
||||
partes = s.split("-")
|
||||
if len(partes) == 3:
|
||||
return f"{partes[2]}/{partes[1]}/{partes[0]}"
|
||||
return s
|
||||
|
||||
|
||||
def _tipo_label(r: dict) -> str:
|
||||
tipo = r.get("tipo") or "renta"
|
||||
if tipo == "otro":
|
||||
return r.get("etiqueta") or "Otro"
|
||||
return _TIPO_LABEL.get(tipo, tipo)
|
||||
|
||||
|
||||
def _vencimiento_renglon(r: dict) -> str:
|
||||
"""Fecha de la obligación de una subcuenta.
|
||||
|
||||
- vr/extra/otro: su fecha_vencimiento.
|
||||
- renta con periodos: el vencimiento MÁS ANTIGUO pendiente.
|
||||
- renta sin periodos: 'día N' (día de pago mensual).
|
||||
"""
|
||||
tipo = r.get("tipo") or "renta"
|
||||
if tipo != "renta":
|
||||
return _fecha_es(r.get("fecha_vencimiento") or "") or "—"
|
||||
fechas = sorted(
|
||||
f for f in ((p.get("fecha_vencimiento") or "")
|
||||
for p in (r.get("periodos") or []))
|
||||
if f
|
||||
)
|
||||
if fechas:
|
||||
return _fecha_es(fechas[0])
|
||||
if r.get("dia_pago"):
|
||||
return f"día {r['dia_pago']}"
|
||||
return "—"
|
||||
|
||||
|
||||
def _norm_sub(s: str) -> str:
|
||||
"""Normalización ligera para casar movimiento ↔ renglón (espejo del
|
||||
`_norm` de cobranza_acumulada: upper, sin puntos, espacios colapsados)."""
|
||||
s = (s or "").upper().replace(".", "")
|
||||
return " ".join(s.split())
|
||||
|
||||
|
||||
def _completar_snapshot(movimientos: list[dict], renglones: list[dict]) -> list[dict]:
|
||||
"""Movimientos viejos (sin snapshot capital/abonado/fecha_alta) toman el
|
||||
contexto del renglón ACTIVO que coincida en vehículo+tipo+etiqueta. Si la
|
||||
subcuenta ya no existe, los campos quedan vacíos ('—' al render)."""
|
||||
idx = {
|
||||
(_norm_sub(r.get("vehiculo") or ""), r.get("tipo") or "renta",
|
||||
_norm_sub(r.get("etiqueta") or "")): r
|
||||
for r in renglones
|
||||
}
|
||||
out = []
|
||||
for m in movimientos:
|
||||
m = dict(m)
|
||||
if m.get("capital") is None or m.get("fecha_alta") in (None, ""):
|
||||
r = idx.get((
|
||||
_norm_sub(m.get("vehiculo") or ""),
|
||||
m.get("tipo") or "renta",
|
||||
_norm_sub(m.get("etiqueta") or ""),
|
||||
))
|
||||
if r:
|
||||
if m.get("capital") is None:
|
||||
m["capital"] = r.get("capital")
|
||||
if m.get("abonado") is None:
|
||||
m["abonado"] = r.get("abonado")
|
||||
if not m.get("fecha_alta"):
|
||||
m["fecha_alta"] = r.get("fecha_alta") or ""
|
||||
out.append(m)
|
||||
return out
|
||||
|
||||
|
||||
def _estilo(nombre: str, **kw) -> ParagraphStyle:
|
||||
base = {"fontName": "Helvetica", "fontSize": 9.5, "leading": 12,
|
||||
"textColor": colors.HexColor("#131922")}
|
||||
base.update(kw)
|
||||
return ParagraphStyle(nombre, **base)
|
||||
|
||||
|
||||
def generar_pdf(
|
||||
cliente: str,
|
||||
renglones: list[dict],
|
||||
movimientos: list[dict],
|
||||
visibles: int,
|
||||
) -> bytes:
|
||||
"""Genera el PDF del estado de cuenta. `renglones` ya vienen decorados
|
||||
(saldo/capital/moratorio/abonado) y filtrados por cliente; `movimientos`
|
||||
ya vienen filtrados y limitados (más recientes primero)."""
|
||||
buf = BytesIO()
|
||||
membrete = _membrete()
|
||||
# Con membrete: contenido debajo del logo y arriba del bloque de
|
||||
# dirección (esquinas del membrete). Sin membrete: márgenes normales.
|
||||
doc = SimpleDocTemplate(
|
||||
buf, pagesize=letter,
|
||||
leftMargin=18 * mm, rightMargin=18 * mm,
|
||||
topMargin=34 * mm if membrete else 16 * mm,
|
||||
bottomMargin=48 * mm if membrete else 16 * mm,
|
||||
title=f"Estado de cuenta — {cliente}",
|
||||
)
|
||||
|
||||
def _fondo(canvas, _doc):
|
||||
if not membrete:
|
||||
return
|
||||
canvas.saveState()
|
||||
canvas.drawImage(
|
||||
membrete, 0, 0, width=letter[0], height=letter[1],
|
||||
)
|
||||
canvas.restoreState()
|
||||
st_titulo = _estilo("titulo", fontName="Helvetica-Bold", fontSize=15,
|
||||
leading=18, textColor=_ACCENT)
|
||||
st_sub = _estilo("sub", fontSize=9.5, textColor=_GRIS)
|
||||
st_seccion = _estilo("seccion", fontName="Helvetica-Bold", fontSize=10.5,
|
||||
leading=13, spaceBefore=6)
|
||||
st_celda = _estilo("celda")
|
||||
st_celda_b = _estilo("celda_b", fontName="Helvetica-Bold")
|
||||
|
||||
ahora = datetime.now(MEXICO)
|
||||
# Con membrete el logo ya da la marca: solo el título del documento.
|
||||
if membrete:
|
||||
encabezado = [Paragraph("ESTADO DE CUENTA", st_titulo)]
|
||||
else:
|
||||
encabezado = [
|
||||
Paragraph("WK FINANCING SOLUTIONS", st_titulo),
|
||||
Paragraph("ESTADO DE CUENTA", st_seccion),
|
||||
]
|
||||
story = encabezado + [
|
||||
Spacer(1, 3 * mm),
|
||||
Paragraph(f"Cliente: <b>{cliente}</b>", st_celda),
|
||||
Paragraph(
|
||||
f"Fecha de corte: {ahora.strftime('%d/%m/%Y %H:%M')} "
|
||||
"(hora del centro de México)", st_sub,
|
||||
),
|
||||
Spacer(1, 6 * mm),
|
||||
]
|
||||
|
||||
# ── 1. Saldos vigentes ──────────────────────────────────────
|
||||
story.append(Paragraph("SALDOS VIGENTES", st_seccion))
|
||||
story.append(Spacer(1, 2 * mm))
|
||||
if renglones:
|
||||
head = ["Subcuenta", "Concepto", "Vencimiento", "Capital", "Mora",
|
||||
"Abonado", "Saldo"]
|
||||
filas = [head]
|
||||
total = 0.0
|
||||
for r in renglones:
|
||||
saldo = float(r.get("saldo") or 0.0)
|
||||
total += saldo
|
||||
filas.append([
|
||||
Paragraph(str(r.get("vehiculo") or ""), st_celda),
|
||||
Paragraph(_tipo_label(r), st_celda),
|
||||
_vencimiento_renglon(r),
|
||||
_money(r.get("capital")),
|
||||
_money(r.get("moratorio")),
|
||||
_money(r.get("abonado")),
|
||||
_money(saldo),
|
||||
])
|
||||
filas.append(["", "", "", "", "", Paragraph("TOTAL", st_celda_b),
|
||||
_money(total)])
|
||||
t = Table(filas,
|
||||
colWidths=[36 * mm, 26 * mm, 22 * mm, None, None, None, None],
|
||||
repeatRows=1)
|
||||
t.setStyle(TableStyle([
|
||||
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 8),
|
||||
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
|
||||
("BACKGROUND", (0, 0), (-1, 0), _ACCENT),
|
||||
("ALIGN", (3, 0), (-1, -1), "RIGHT"),
|
||||
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -2), [colors.white, _FILA_ALT]),
|
||||
("LINEBELOW", (0, 0), (-1, -2), 0.4, _LINEA),
|
||||
("FONTNAME", (0, -1), (-1, -1), "Helvetica-Bold"),
|
||||
("LINEABOVE", (0, -1), (-1, -1), 0.9, _ACCENT),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
]))
|
||||
story.append(t)
|
||||
else:
|
||||
story.append(Paragraph(
|
||||
"Sin saldos vigentes: el cliente no tiene subcuentas activas.",
|
||||
st_sub,
|
||||
))
|
||||
story.append(Spacer(1, 7 * mm))
|
||||
|
||||
# ── 2. Movimientos ──────────────────────────────────────────
|
||||
story.append(Paragraph(
|
||||
f"MOVIMIENTOS (últimos {visibles})", st_seccion,
|
||||
))
|
||||
story.append(Spacer(1, 2 * mm))
|
||||
if movimientos:
|
||||
movimientos = _completar_snapshot(movimientos, renglones)
|
||||
st_nota = _estilo("nota", fontSize=7.5, textColor=_GRIS, leading=9)
|
||||
filas = [["Fecha", "Subcuenta", "Movimiento",
|
||||
"Saldo previo", "Monto", "Saldo después"]]
|
||||
for m in movimientos:
|
||||
sub = f"{m.get('vehiculo') or ''} · {_tipo_label(m)}"
|
||||
origen = _fecha_es(m.get("fecha_alta") or "")
|
||||
if origen:
|
||||
sub += f" ({origen})"
|
||||
celda_sub = [Paragraph(sub, st_celda)]
|
||||
if m.get("nota"):
|
||||
celda_sub.append(Paragraph(str(m["nota"]), st_nota))
|
||||
cap = m.get("capital")
|
||||
despues = m.get("saldo_despues")
|
||||
if despues is None and cap is not None and m.get("abonado") is not None:
|
||||
# Movimientos previos a este campo: aproximación desde el
|
||||
# snapshot (capital − abonado acumulado; sin la mora de
|
||||
# aquel momento).
|
||||
despues = round(float(cap) - float(m["abonado"]), 2)
|
||||
monto = float(m.get("monto") or 0.0)
|
||||
# Saldo ANTES del movimiento (con moratorios): el saldo después
|
||||
# más lo pagado en este movimiento. La fila cuadra:
|
||||
# previo − monto = después.
|
||||
antes = round(despues + monto, 2) if despues is not None else None
|
||||
filas.append([
|
||||
_fecha_es(m.get("fecha") or ""),
|
||||
celda_sub,
|
||||
_MOV_LABEL.get(m.get("movimiento") or "", m.get("movimiento") or ""),
|
||||
_money(antes) if antes is not None else "—",
|
||||
_money(monto),
|
||||
_money(despues) if despues is not None else "—",
|
||||
])
|
||||
t = Table(filas,
|
||||
colWidths=[19 * mm, 58 * mm, 22 * mm, None, None, None],
|
||||
repeatRows=1)
|
||||
t.setStyle(TableStyle([
|
||||
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 8),
|
||||
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
|
||||
("BACKGROUND", (0, 0), (-1, 0), _ACCENT),
|
||||
("ALIGN", (3, 0), (-1, -1), "RIGHT"),
|
||||
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, _FILA_ALT]),
|
||||
("LINEBELOW", (0, 0), (-1, -1), 0.4, _LINEA),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
]))
|
||||
story.append(t)
|
||||
else:
|
||||
story.append(Paragraph(
|
||||
"Sin movimientos registrados en la bitácora.", st_sub,
|
||||
))
|
||||
|
||||
story.append(Spacer(1, 8 * mm))
|
||||
story.append(Paragraph(
|
||||
"La mora se calcula al día de corte; el saldo puede variar después "
|
||||
"de esta fecha. Documento informativo, no comprobante fiscal.",
|
||||
_estilo("pie", fontSize=7.5, textColor=_GRIS),
|
||||
))
|
||||
|
||||
doc.build(story, onFirstPage=_fondo, onLaterPages=_fondo)
|
||||
return buf.getvalue()
|
||||
@@ -136,6 +136,11 @@ def _get_client() -> gspread.Client | None:
|
||||
return None
|
||||
creds_dict = json.loads(creds_json)
|
||||
_gc = gspread.service_account_from_dict(creds_dict)
|
||||
# Timeout duro (conexión, lectura) a TODA llamada HTTP a Google.
|
||||
# gspread usa requests SIN timeout por default: si la red al API de
|
||||
# Google se cuelga, la llamada síncrona bloquea el event loop y el
|
||||
# bot COMPLETO deja de contestar (cotizador incluido).
|
||||
_gc.set_timeout((10, 20))
|
||||
return _gc
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
Detección de duplicados: dos cobros VR del mismo vehículo con DISTINTO
|
||||
vencimiento/monto NO son duplicados (bug reportado: EXCAVADORA 01/08 vs 10/08).
|
||||
Solo coincidencias exactas (cliente|vehiculo|tipo|vencimiento|monto) cuentan.
|
||||
"""
|
||||
import fakeredis.aioredis
|
||||
import pytest
|
||||
|
||||
from src.services import cobranza_acumulada as ca
|
||||
|
||||
NUM = "2228733600"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_redis(monkeypatch):
|
||||
fake = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
monkeypatch.setattr(ca, "get_client", lambda: fake)
|
||||
yield
|
||||
|
||||
|
||||
def _vr(id, venc, monto, cliente="GRUPO MEENT", veh="EXCAVADORA"):
|
||||
return {"id": id, "tipo": "vr", "cliente": cliente, "vehiculo": veh,
|
||||
"monto": monto, "tasa_mensual": 2.0, "abonos": [],
|
||||
"fecha_vencimiento": venc, "fecha_alta": "2026-08-01"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dos_vr_mismo_vehiculo_distinto_vencimiento_no_es_dup():
|
||||
# El caso reportado: dos EXCAVADORA-VR, fechas y montos distintos.
|
||||
await ca._save(NUM, [
|
||||
_vr("a", "2026-08-01", 214514.16),
|
||||
_vr("b", "2026-08-10", 171572.70),
|
||||
])
|
||||
dups = await ca.detectar_duplicados(NUM)
|
||||
assert dups == [] # NO hay duplicados
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vr_identico_si_es_dup():
|
||||
# Mismo cliente/vehiculo/tipo/vencimiento/monto → duplicado real.
|
||||
await ca._save(NUM, [
|
||||
_vr("a", "2026-08-01", 214514.16),
|
||||
_vr("b", "2026-08-01", 214514.16),
|
||||
])
|
||||
dups = await ca.detectar_duplicados(NUM)
|
||||
assert len(dups) == 1 and len(dups[0]["renglones"]) == 2
|
||||
# eliminar_duplicados conserva uno y borra el otro.
|
||||
res = await ca.eliminar_duplicados(NUM)
|
||||
assert res["eliminados"] == 1
|
||||
assert len(await ca._load(NUM)) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vr_mismo_vencimiento_distinto_monto_no_es_dup():
|
||||
# Mismo vencimiento pero montos distintos → distintos (no se borran).
|
||||
await ca._save(NUM, [
|
||||
_vr("a", "2026-08-01", 100000.0),
|
||||
_vr("b", "2026-08-01", 58737.50),
|
||||
])
|
||||
assert await ca.detectar_duplicados(NUM) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_renta_misma_identidad_sigue_siendo_dup():
|
||||
# Renta: la identidad NO cambia (cliente|vehiculo|renta). Dos rentas del
|
||||
# mismo vehículo siguen contando como duplicado (una renta por vehículo).
|
||||
def _renta(id):
|
||||
return {"id": id, "tipo": "renta", "cliente": "X", "vehiculo": "HILUX",
|
||||
"periodos": [{"periodo": "2026-08", "mensualidad": 10000.0,
|
||||
"fecha_vencimiento": "2026-08-04"}],
|
||||
"tasa_mensual": 2.0, "abonos": [], "fecha_alta": "2026-08-01"}
|
||||
await ca._save(NUM, [_renta("a"), _renta("b")])
|
||||
dups = await ca.detectar_duplicados(NUM)
|
||||
assert len(dups) == 1 and len(dups[0]["renglones"]) == 2
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
Estado de cuenta PDF: saldos vigentes por subcuenta + últimos X
|
||||
movimientos de la bitácora. Validamos el contenido extrayendo el texto
|
||||
con pdfplumber.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
import pdfplumber
|
||||
|
||||
from src.services import estado_cuenta
|
||||
|
||||
RENGLONES = [
|
||||
{"tipo": "renta", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"capital": 20000.0, "moratorio": 312.40, "abonado": 6000.0,
|
||||
"saldo": 14312.40, "fecha_alta": "2026-06-01",
|
||||
"periodos": [
|
||||
{"periodo": "2026-07", "mensualidad": 10000.0,
|
||||
"fecha_vencimiento": "2026-07-05"},
|
||||
{"periodo": "2026-08", "mensualidad": 10000.0,
|
||||
"fecha_vencimiento": "2026-08-05"},
|
||||
]},
|
||||
{"tipo": "vr", "cliente": "GRUPO MEENT", "vehiculo": "EXCAVADORA",
|
||||
"capital": 171572.70, "moratorio": 201.76, "abonado": 0.0,
|
||||
"saldo": 171774.46, "fecha_vencimiento": "2026-08-10",
|
||||
"fecha_alta": "2026-08-01"},
|
||||
]
|
||||
|
||||
MOVIMIENTOS = [
|
||||
{"fecha": "2026-08-01", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"tipo": "renta", "movimiento": "abono", "monto": 6000.0,
|
||||
"nota": "transferencia BBVA", "capital": 20000.0, "abonado": 6000.0,
|
||||
"fecha_alta": "2026-06-01", "saldo_despues": 14312.40},
|
||||
# Sin saldo_despues (movimiento previo al campo): se aproxima con
|
||||
# capital − abonado del snapshot.
|
||||
{"fecha": "2026-07-15", "cliente": "GRUPO MEENT", "vehiculo": "HILUX",
|
||||
"tipo": "renta", "movimiento": "saldo_periodo", "monto": 10000.0,
|
||||
"nota": "mes 2026-06", "capital": 30000.0, "abonado": 12500.0,
|
||||
"fecha_alta": "2026-06-01"},
|
||||
]
|
||||
|
||||
|
||||
def _texto(pdf_bytes: bytes) -> str:
|
||||
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
|
||||
return "\n".join(p.extract_text() or "" for p in pdf.pages)
|
||||
|
||||
|
||||
def test_pdf_contiene_saldos_y_movimientos():
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="GRUPO MEENT", renglones=RENGLONES,
|
||||
movimientos=MOVIMIENTOS, visibles=10,
|
||||
)
|
||||
assert pdf.startswith(b"%PDF")
|
||||
txt = _texto(pdf)
|
||||
assert "ESTADO DE CUENTA" in txt
|
||||
assert "GRUPO MEENT" in txt
|
||||
# Saldos vigentes: subcuentas, montos y total.
|
||||
assert "HILUX" in txt and "EXCAVADORA" in txt
|
||||
assert "Renta mensual" in txt and "Valor residual" in txt
|
||||
assert "$14,312.40" in txt and "$171,774.46" in txt
|
||||
assert "$186,086.86" in txt # TOTAL = suma de saldos
|
||||
# Vencimiento de cada obligación: renta = periodo más antiguo pendiente;
|
||||
# vr = su fecha_vencimiento.
|
||||
assert "Vencimiento" in txt
|
||||
assert "05/07/2026" in txt and "10/08/2026" in txt
|
||||
# Movimientos: fecha, etiqueta, nota y snapshot de la subcuenta
|
||||
# (originación, capital, abonado).
|
||||
assert "MOVIMIENTOS" in txt and "01/08/2026" in txt
|
||||
assert "Abono" in txt and "Mes saldado" in txt
|
||||
assert "transferencia BBVA" in txt
|
||||
assert "$6,000.00" in txt
|
||||
assert "(01/06/2026)" in txt # originación en la subcuenta
|
||||
assert "Originación" not in txt # ya no es columna aparte
|
||||
assert "$20,000.00" in txt # capital de la subcuenta
|
||||
# Saldo previo (con mora) y saldo después: la fila cuadra
|
||||
# previo − monto = después. Primero: 20,312.40 − 6,000 = 14,312.40.
|
||||
# Viejo sin campo: aproximado (30,000 − 12,500 = 17,500 después;
|
||||
# previo = 17,500 + 10,000 = 27,500).
|
||||
assert "Saldo previo" in txt and "Saldo después" in txt
|
||||
assert "Capital" in txt # sigue en SALDOS VIGENTES
|
||||
assert "$20,312.40" in txt and "$14,312.40" in txt
|
||||
assert "$27,500.00" in txt and "$17,500.00" in txt
|
||||
|
||||
|
||||
def test_pdf_sin_renglones_ni_movs_avisa():
|
||||
# Cliente saldado por completo: sin subcuentas activas ni bitácora aún.
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=[], movimientos=[], visibles=10,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
assert "Sin saldos vigentes" in txt
|
||||
assert "Sin movimientos registrados" in txt
|
||||
|
||||
|
||||
def test_pdf_solo_movimientos_de_cliente_saldado():
|
||||
# El renglón se borró al saldarse, pero la bitácora sobrevive: el
|
||||
# estado de cuenta sigue mostrando el historial. Sin snapshot ni
|
||||
# renglón activo, las columnas de contexto salen como '—'.
|
||||
movs = [{"fecha": "2026-08-01", "cliente": "ACME", "vehiculo": "GT3",
|
||||
"tipo": "vr", "movimiento": "saldado", "monto": 500000.0,
|
||||
"nota": "pago total"}]
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=[], movimientos=movs, visibles=5,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
assert "Sin saldos vigentes" in txt
|
||||
assert "Saldado" in txt and "$500,000.00" in txt
|
||||
assert "(últimos 5)" in txt
|
||||
assert "—" in txt
|
||||
|
||||
|
||||
def test_pdf_con_membrete_y_sin_plantilla(monkeypatch, tmp_path):
|
||||
# Con la plantilla presente (repo) el PDF lleva el membrete W+k y el
|
||||
# título es solo 'ESTADO DE CUENTA' (el logo ya da la marca).
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=RENGLONES, movimientos=[], visibles=10,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
assert "ESTADO DE CUENTA" in txt
|
||||
assert "WK FINANCING SOLUTIONS" not in txt # lo pone el logo, no texto
|
||||
assert len(pdf) > 100_000 # trae el jpeg del membrete
|
||||
|
||||
# Sin plantilla (deploy sin el .docm): NO truena — cae al encabezado
|
||||
# de texto de siempre.
|
||||
monkeypatch.setattr(estado_cuenta, "TEMPLATE_PATH",
|
||||
tmp_path / "no-existe.docm")
|
||||
monkeypatch.setattr(estado_cuenta, "_membrete_cache", None)
|
||||
monkeypatch.setattr(estado_cuenta, "_membrete_probado", False)
|
||||
pdf2 = estado_cuenta.generar_pdf(
|
||||
cliente="ACME", renglones=RENGLONES, movimientos=[], visibles=10,
|
||||
)
|
||||
txt2 = _texto(pdf2)
|
||||
assert "WK FINANCING SOLUTIONS" in txt2 # encabezado de texto
|
||||
# monkeypatch restaura TEMPLATE_PATH y el cache al salir del test.
|
||||
|
||||
|
||||
def test_pdf_movimiento_viejo_toma_contexto_del_renglon_activo():
|
||||
# Movimientos registrados ANTES del snapshot (sin capital/abonado/
|
||||
# fecha_alta) heredan el contexto del renglón activo que coincide.
|
||||
movs = [{"fecha": "2026-08-03", "cliente": "GRUPO MEENT",
|
||||
"vehiculo": "EXCAVADORA", "tipo": "vr",
|
||||
"movimiento": "abono", "monto": 25.0, "nota": ""}]
|
||||
pdf = estado_cuenta.generar_pdf(
|
||||
cliente="GRUPO MEENT", renglones=RENGLONES, movimientos=movs,
|
||||
visibles=10,
|
||||
)
|
||||
txt = _texto(pdf)
|
||||
# Toma capital y fecha_alta del renglón EXCAVADORA·vr activo.
|
||||
assert "$171,572.70" in txt
|
||||
assert "01/08/2026" in txt
|
||||
@@ -49,6 +49,33 @@ def test_lote_hereda_plantilla():
|
||||
assert out.rstrip().endswith("Gracias, ACME.") # despedida con variable
|
||||
|
||||
|
||||
def test_intro_y_concepto_por_default():
|
||||
# Sin texto_intro/texto_concepto en la plantilla → textos por defecto.
|
||||
out = _armar_mensaje_plantilla(
|
||||
PLANTILLA, CUENTAS,
|
||||
cliente="ACME", vehiculo="HILUX", concepto="WK-RENTA-ACME",
|
||||
monto=100, link="http://x",
|
||||
)
|
||||
assert "Le compartimos los datos para realizar su pago:" in out
|
||||
assert "Concepto: WK-RENTA-ACME" in out
|
||||
|
||||
|
||||
def test_intro_y_concepto_configurables():
|
||||
# texto_intro y texto_concepto personalizados (con variables) se aplican.
|
||||
pl = dict(PLANTILLA,
|
||||
texto_intro="Estimado {cliente}, sus datos de pago:",
|
||||
texto_concepto="Referencia de pago: {concepto}")
|
||||
out = _armar_mensaje_plantilla(
|
||||
pl, CUENTAS,
|
||||
cliente="ACME", vehiculo="HILUX", concepto="WK-RENTA-ACME",
|
||||
monto=100, link="http://x",
|
||||
)
|
||||
assert "Estimado ACME, sus datos de pago:" in out
|
||||
assert "Referencia de pago: WK-RENTA-ACME" in out
|
||||
assert "Le compartimos los datos para realizar su pago:" not in out
|
||||
assert "Concepto: WK-RENTA-ACME" not in out
|
||||
|
||||
|
||||
def test_lote_sin_link_ni_cuentas_avisa():
|
||||
pl = dict(PLANTILLA, incluir_link=False)
|
||||
out = _armar_mensaje_plantilla(
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""
|
||||
Bitácora de movimientos (ledger) de cobranza: los abonos/saldados quedan
|
||||
registrados en `cobranza_mov:{numero}` con la fecha capturada, sobreviven
|
||||
al borrado del renglón, y `movimientos_visibles` (config) limita solo
|
||||
cuántos se muestran.
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
||||
|
||||
import fakeredis.aioredis
|
||||
import pytest
|
||||
|
||||
from src.services import cobranza_acumulada as ca
|
||||
|
||||
NUM = "2228733600"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_redis(monkeypatch):
|
||||
fake = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
monkeypatch.setattr(ca, "get_client", lambda: fake)
|
||||
yield
|
||||
|
||||
|
||||
def _vr(id="v1", monto=1000.0, cliente="GRUPO MEENT", veh="EXCAVADORA",
|
||||
venc="2099-12-31"):
|
||||
return {"id": id, "tipo": "vr", "cliente": cliente, "vehiculo": veh,
|
||||
"monto": monto, "tasa_mensual": 2.0, "abonos": [],
|
||||
"fecha_vencimiento": venc, "fecha_alta": "2026-08-01"}
|
||||
|
||||
|
||||
def _renta(id="r1", cliente="ACME", veh="HILUX"):
|
||||
return {"id": id, "tipo": "renta", "cliente": cliente, "vehiculo": veh,
|
||||
"tasa_mensual": 2.0, "abonos": [], "fecha_alta": "2026-07-01",
|
||||
"periodos": [
|
||||
{"periodo": "2026-07", "mensualidad": 10000.0,
|
||||
"fecha_vencimiento": "2099-07-01"},
|
||||
{"periodo": "2026-08", "mensualidad": 10000.0,
|
||||
"fecha_vencimiento": "2099-08-01"},
|
||||
]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abono_con_fecha_queda_en_abono_y_bitacora():
|
||||
await ca._save(NUM, [_vr()])
|
||||
ok = await ca.registrar_abono(NUM, "v1", 400.0, "transferencia",
|
||||
fecha="2026-07-15")
|
||||
assert ok
|
||||
r = (await ca._load(NUM))[0]
|
||||
assert r["abonos"][0]["fecha"] == "2026-07-15"
|
||||
movs = await ca.obtener_movimientos(NUM)
|
||||
assert len(movs) == 1
|
||||
m = movs[0]
|
||||
assert m["movimiento"] == "abono"
|
||||
assert m["monto"] == 400.0
|
||||
assert m["fecha"] == "2026-07-15"
|
||||
assert m["nota"] == "transferencia"
|
||||
assert m["cliente"] == "GRUPO MEENT" and m["tipo"] == "vr"
|
||||
# Snapshot de la subcuenta al momento del movimiento (para el estado
|
||||
# de cuenta, aunque el renglón se borre después).
|
||||
assert m["capital"] == 1000.0
|
||||
assert m["abonado"] == 400.0 # incluye este abono
|
||||
assert m["fecha_alta"] == "2026-08-01"
|
||||
assert m["saldo_despues"] == 600.0 # 1000 − 400 (sin mora: vence futuro)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fecha_invalida_cae_a_hoy():
|
||||
await ca._save(NUM, [_vr()])
|
||||
await ca.registrar_abono(NUM, "v1", 100.0, "", fecha="15/07/2026")
|
||||
r = (await ca._load(NUM))[0]
|
||||
hoy = ca._hoy_mx().isoformat()
|
||||
assert r["abonos"][0]["fecha"] == hoy
|
||||
movs = await ca.obtener_movimientos(NUM)
|
||||
assert movs[0]["fecha"] == hoy
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_saldar_registra_movimiento_y_sobrevive_al_borrado():
|
||||
# marcar_pagado BORRA el renglón, pero la bitácora conserva el saldado
|
||||
# con el monto liquidado (aquí sin mora: vence en el futuro).
|
||||
await ca._save(NUM, [_vr(monto=2500.0)])
|
||||
ok = await ca.marcar_pagado(NUM, "v1", "pago total", fecha="2026-08-01")
|
||||
assert ok
|
||||
assert await ca._load(NUM) == [] # renglón borrado
|
||||
movs = await ca.obtener_movimientos(NUM, cliente="GRUPO MEENT",
|
||||
vehiculo="EXCAVADORA", tipo="vr")
|
||||
assert len(movs) == 1
|
||||
assert movs[0]["movimiento"] == "saldado"
|
||||
assert movs[0]["monto"] == 2500.0
|
||||
assert movs[0]["fecha"] == "2026-08-01"
|
||||
assert movs[0]["nota"] == "pago total"
|
||||
assert movs[0]["saldo_despues"] == 0.0 # saldado = ya no debe nada
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abono_que_liquida_borra_renglon_pero_conserva_movimiento():
|
||||
await ca._save(NUM, [_vr(monto=500.0)])
|
||||
await ca.registrar_abono(NUM, "v1", 500.0, "liquidación")
|
||||
assert await ca._load(NUM) == [] # cierre automático por saldo 0
|
||||
movs = await ca.obtener_movimientos(NUM)
|
||||
assert len(movs) == 1 and movs[0]["movimiento"] == "abono"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_saldar_periodo_registra_mes():
|
||||
await ca._save(NUM, [_renta()])
|
||||
ok = await ca.saldar_periodo(NUM, "r1", "2026-07")
|
||||
assert ok
|
||||
r = (await ca._load(NUM))[0]
|
||||
assert len(r["periodos"]) == 1 # queda solo 2026-08
|
||||
movs = await ca.obtener_movimientos(NUM)
|
||||
assert len(movs) == 1
|
||||
assert movs[0]["movimiento"] == "saldo_periodo"
|
||||
assert movs[0]["monto"] == 10000.0 # sin mora (vence en el futuro)
|
||||
assert movs[0]["nota"] == "mes 2026-07"
|
||||
assert movs[0]["saldo_despues"] == 10000.0 # queda el mes 2026-08
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_filtro_por_subcuenta_y_limite():
|
||||
await ca._save(NUM, [_vr(), _renta()])
|
||||
await ca.registrar_abono(NUM, "v1", 10.0, "vr-1")
|
||||
await ca.registrar_abono(NUM, "r1", 20.0, "renta-1")
|
||||
await ca.registrar_abono(NUM, "r1", 30.0, "renta-2")
|
||||
# Filtro por subcuenta: solo los de la renta de ACME/HILUX.
|
||||
movs = await ca.obtener_movimientos(NUM, cliente="acme", vehiculo="HILUX",
|
||||
tipo="renta")
|
||||
assert [m["nota"] for m in movs] == ["renta-2", "renta-1"] # recientes 1o
|
||||
# Límite: solo el más reciente.
|
||||
movs = await ca.obtener_movimientos(NUM, limite=1)
|
||||
assert len(movs) == 1 and movs[0]["nota"] == "renta-2"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_saldar_abono_pendiente_registra_movimiento():
|
||||
await ca._save(NUM, [_vr(monto=1000.0)])
|
||||
ab = await ca.crear_abono_pendiente(NUM, "v1", 250.0, "apartado")
|
||||
assert (await ca.obtener_movimientos(NUM)) == [] # pendiente NO registra
|
||||
await ca.saldar_abono(NUM, "v1", ab["id"])
|
||||
movs = await ca.obtener_movimientos(NUM)
|
||||
assert len(movs) == 1
|
||||
assert movs[0]["movimiento"] == "abono" and movs[0]["monto"] == 250.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_filtro_por_renglon_exacto_separa_subcuentas_gemelas():
|
||||
# Dos VR del MISMO vehículo/cliente (identidad igual, vencimientos
|
||||
# distintos): el filtro renglon_id separa los movimientos de cada una
|
||||
# (bug reportado: el modal de la EXCAVADORA de 171k mostraba el
|
||||
# saldado de la de 214k).
|
||||
await ca._save(NUM, [
|
||||
_vr("v214", monto=214943.47, venc="2026-08-01"),
|
||||
_vr("v171", monto=171572.70, venc="2026-08-10"),
|
||||
])
|
||||
await ca.marcar_pagado(NUM, "v214", "pago total")
|
||||
await ca.registrar_abono(NUM, "v171", 50000.0, "parcial")
|
||||
# Por identidad (vehiculo+tipo) salen AMBOS…
|
||||
todos = await ca.obtener_movimientos(NUM, vehiculo="EXCAVADORA", tipo="vr")
|
||||
assert len(todos) == 2
|
||||
# …por renglón exacto, solo el suyo.
|
||||
solo_171 = await ca.obtener_movimientos(NUM, renglon_id="v171")
|
||||
assert len(solo_171) == 1
|
||||
assert solo_171[0]["movimiento"] == "abono"
|
||||
assert solo_171[0]["monto"] == 50000.0
|
||||
solo_214 = await ca.obtener_movimientos(NUM, renglon_id="v214")
|
||||
assert len(solo_214) == 1 and solo_214[0]["movimiento"] == "saldado"
|
||||
# Varios renglones a la vez (selección del panel → Imprimir movimientos).
|
||||
ambos = await ca.obtener_movimientos(NUM, renglon_ids=["v171", "v214"])
|
||||
assert len(ambos) == 2
|
||||
assert await ca.obtener_movimientos(NUM, renglon_ids=["v171"]) == solo_171
|
||||
|
||||
|
||||
def test_tope_abono_al_saldo():
|
||||
# El abono se topa al saldo vigente (tolerancia de 1 centavo por
|
||||
# redondeos de display). Igual al saldo = liquidar, permitido.
|
||||
from src.api.cobranza_api import _abono_excede_saldo
|
||||
assert not _abono_excede_saldo(500.0, 500.0) # exacto → ok
|
||||
assert not _abono_excede_saldo(500.01, 500.0) # centavo → ok
|
||||
assert not _abono_excede_saldo(499.99, 500.0)
|
||||
assert _abono_excede_saldo(500.02, 500.0) # excede → rechazado
|
||||
assert _abono_excede_saldo(1000.0, 500.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_movimientos_visibles():
|
||||
cfg = await ca.obtener_config_global()
|
||||
assert cfg["movimientos_visibles"] == ca.MOV_DEFAULT_VISIBLES
|
||||
assert await ca.guardar_movimientos_visibles(25) == 25
|
||||
cfg = await ca.obtener_config_global()
|
||||
assert cfg["movimientos_visibles"] == 25
|
||||
# Clamps: piso 1, techo MOV_MAX.
|
||||
assert await ca.guardar_movimientos_visibles(0) == 1
|
||||
assert await ca.guardar_movimientos_visibles(99999) == ca.MOV_MAX
|
||||
+428
-9
@@ -60,7 +60,7 @@
|
||||
.header p { font-size: 12.5px; color: var(--text-secondary); margin-top: 3px; }
|
||||
|
||||
.tabs { display: flex; gap: 4px; background: var(--surface-2); border: 1px solid var(--line); border-radius: 12px; padding: 4px; margin-bottom: 1.4rem; animation: fadeUp 0.62s ease both; }
|
||||
.tab { flex: 1; padding: 9px 8px; border: none; background: transparent; border-radius: 9px; font-size: 13px; font-weight: 600; font-family: 'DM Sans', sans-serif; color: var(--text-secondary); cursor: pointer; transition: all 0.18s ease; }
|
||||
.tab { flex: 1; padding: 9px 4px; border: none; background: transparent; border-radius: 9px; font-size: 12.5px; font-weight: 600; font-family: 'DM Sans', sans-serif; color: var(--text-secondary); cursor: pointer; transition: all 0.18s ease; white-space: nowrap; }
|
||||
.tab:hover { color: var(--text-primary); }
|
||||
.tab.active { background: var(--surface); box-shadow: 0 1px 2px rgba(18,24,38,.08), 0 0 0 1px var(--line); color: var(--accent); }
|
||||
|
||||
@@ -209,6 +209,49 @@
|
||||
.btn-danger-soft { background: var(--surface); color: var(--danger); border-color: var(--line); }
|
||||
.btn-danger-soft:hover { background: var(--danger-soft); border-color: transparent; }
|
||||
|
||||
/* Vista Cuentas: acordeón por cliente con subcuentas seleccionables */
|
||||
.cta-block { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-card); box-shadow: var(--nm-out); margin-bottom: 12px; animation: fadeUp 0.5s ease both; overflow: hidden; }
|
||||
.cta-head { display: flex; align-items: center; gap: 10px; padding: 0.95rem 1.1rem; cursor: pointer; user-select: none; }
|
||||
.cta-head:hover { background: var(--surface-2); }
|
||||
.cta-chev { flex: 0 0 auto; width: 22px; height: 22px; border-radius: 7px; background: var(--accent-soft); color: var(--accent); font-size: 12px; display: inline-flex; align-items: center; justify-content: center; }
|
||||
.cta-name { flex: 1; min-width: 0; font-size: 14.5px; font-weight: 700; letter-spacing: -0.2px; line-height: 1.25; }
|
||||
.cta-sub { font-size: 11px; font-weight: 500; color: var(--text-secondary); margin-top: 2px; }
|
||||
.cta-selbadge { color: var(--accent); font-weight: 700; }
|
||||
.cta-tot { flex: 0 0 auto; text-align: right; font-family: 'Space Grotesk', sans-serif; font-size: 17px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.3px; }
|
||||
.cta-mora { font-family: 'DM Sans', sans-serif; font-size: 10px; font-weight: 600; color: var(--warning); margin-top: 1px; }
|
||||
.cta-body { border-top: 1px solid var(--line); padding: 0.85rem 1rem 1rem; background: var(--surface-2); }
|
||||
.cta-tools { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; gap: 8px; }
|
||||
.cta-edocta { background: transparent; border: none; color: var(--accent); font-family: 'DM Sans', sans-serif; font-size: 11.5px; font-weight: 700; letter-spacing: 0.3px; cursor: pointer; padding: 4px 6px; white-space: nowrap; }
|
||||
.cta-edocta:hover { text-decoration: underline; }
|
||||
.cta-seltodo { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--text-secondary); cursor: pointer; }
|
||||
.cta-seltodo input { width: 17px; height: 17px; accent-color: var(--accent); cursor: pointer; }
|
||||
.sub-card { background: var(--surface); border: 1px solid var(--line); border-radius: 13px; box-shadow: var(--nm-subtle); margin-bottom: 10px; overflow: hidden; transition: border-color 0.15s ease, box-shadow 0.15s ease; }
|
||||
.sub-card.sel { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 6px 14px -6px var(--accent-glow); }
|
||||
.sub-row { display: flex; align-items: center; gap: 10px; padding: 0.75rem 0.85rem; cursor: pointer; }
|
||||
.sub-check { flex: 0 0 auto; width: 20px; height: 20px; border-radius: 7px; border: 2px solid var(--line-strong); background: var(--surface); color: #fff; font-size: 12px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; transition: all 0.15s ease; }
|
||||
.sub-check.on { background: var(--accent); border-color: var(--accent); }
|
||||
.sub-main { flex: 1; min-width: 0; }
|
||||
.sub-title { font-size: 13px; font-weight: 700; display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }
|
||||
.sub-meta { font-size: 11px; color: var(--text-secondary); margin-top: 3px; }
|
||||
.sub-saldo { flex: 0 0 auto; font-family: 'Space Grotesk', sans-serif; font-size: 14.5px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.sub-actions { display: flex; gap: 7px; padding: 0 0.85rem 0.8rem; }
|
||||
.sub-actions .btn { padding: 8px 10px; font-size: 11.5px; border-radius: 10px; }
|
||||
.btn-abono { background: var(--renta); color: #fff; box-shadow: 0 6px 16px -5px rgba(37,99,201,0.4); }
|
||||
.btn-abono:hover { filter: brightness(0.94); }
|
||||
.btn-abono:active { transform: scale(0.97); }
|
||||
.mov-item { display: flex; align-items: center; gap: 10px; padding: 9px 2px; border-bottom: 1px solid var(--line); font-size: 12.5px; flex-wrap: wrap; }
|
||||
.mov-item:last-child { border-bottom: none; }
|
||||
.mov-det { flex-basis: 100%; font-size: 11px; color: var(--text-secondary); margin-top: 1px; padding-left: 84px; }
|
||||
.mov-fecha { flex: 0 0 auto; color: var(--text-tertiary); font-variant-numeric: tabular-nums; font-size: 11.5px; width: 74px; }
|
||||
.mov-tipo { flex: 0 0 auto; font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 999px; text-transform: uppercase; letter-spacing: 0.3px; }
|
||||
.mov-tipo.abono { background: var(--renta-soft); color: var(--renta); }
|
||||
.mov-tipo.saldado, .mov-tipo.saldo_periodo { background: var(--success-soft); color: var(--success); }
|
||||
.mov-desc { flex: 1; min-width: 0; color: var(--text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mov-monto { flex: 0 0 auto; font-family: 'Space Grotesk', sans-serif; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.cta-foot { display: flex; justify-content: space-between; align-items: center; padding: 0.7rem 0.2rem 0; font-size: 12.5px; font-weight: 600; color: var(--text-secondary); }
|
||||
.cta-foot .val { font-family: 'Space Grotesk', sans-serif; font-size: 16px; font-weight: 600; color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.cta-foot.empty { justify-content: center; font-weight: 500; font-size: 11.5px; color: var(--text-tertiary); }
|
||||
|
||||
/* Modo edición inline */
|
||||
.edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 1rem; }
|
||||
.edit-field label { font-size: 10px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.4px; display: block; margin-bottom: 5px; font-weight: 700; }
|
||||
@@ -362,6 +405,7 @@
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" data-view="tarjetas" onclick="setView('tarjetas')">Tarjetas</button>
|
||||
<button class="tab" data-view="cuentas" onclick="setView('cuentas')">Cuentas</button>
|
||||
<button class="tab" data-view="tabla" onclick="setView('tabla')">Tabla</button>
|
||||
<button class="tab" data-view="directorio" onclick="setView('directorio')">Directorio</button>
|
||||
<button class="tab" data-view="mensaje" onclick="setView('mensaje')">Mensaje</button>
|
||||
@@ -395,6 +439,21 @@
|
||||
<div id="lista"></div>
|
||||
</div>
|
||||
|
||||
<div class="view" id="view-cuentas">
|
||||
<div class="section-label"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> Bitácora de movimientos</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Movimientos visibles en el historial</label>
|
||||
<div style="display:flex;gap:10px;align-items:center">
|
||||
<input type="number" class="form-input" id="mov-visibles" min="1" max="500" style="max-width:110px">
|
||||
<button class="btn-save" style="margin:0;width:auto;padding-left:18px;padding-right:18px" onclick="guardarMovVisibles()">Guardar</button>
|
||||
</div>
|
||||
<div class="form-hint">Cuántos movimientos se muestran por subcuenta (abonos, saldados). El registro completo se conserva siempre.</div>
|
||||
</div>
|
||||
|
||||
<div class="section-label" id="cta-count" style="margin-top:20px">cuentas por cliente</div>
|
||||
<div id="cta-lista"></div>
|
||||
</div>
|
||||
|
||||
<div class="view" id="view-tabla">
|
||||
<div class="section-label">Vista tabla — desliza horizontal →</div>
|
||||
<button class="btn-wide" style="margin-bottom:12px" onclick="abrirCrearRenglon()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg> Agregar cobro personalizado</button>
|
||||
@@ -412,6 +471,19 @@
|
||||
<textarea class="form-input" id="pl-saludo" rows="2" oninput="renderVistaPreviaMsg()"></textarea>
|
||||
<div class="form-hint">Variables: <code>{cliente}</code> <code>{vehiculo}</code> <code>{monto}</code> <code>{concepto}</code> <code>{mes}</code></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Introducción (antes de los datos)</label>
|
||||
<textarea class="form-input" id="pl-intro" rows="2" oninput="renderVistaPreviaMsg()"></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<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>
|
||||
@@ -688,7 +760,7 @@ async function refrescarDuplicados(){
|
||||
} catch(e){ /* sin banner */ }
|
||||
}
|
||||
|
||||
function render(){ renderTarjetas(); renderTabla(); renderStats(); }
|
||||
function render(){ renderTarjetas(); renderCuentas(); renderTabla(); renderStats(); }
|
||||
function renderStats(){
|
||||
let total=0, mora=0;
|
||||
// Desglose del total (saldo pendiente) por tipo de cobro.
|
||||
@@ -708,6 +780,214 @@ function renderStats(){
|
||||
document.getElementById("stat-otro").textContent = fmtK(porTipo.otro);
|
||||
}
|
||||
|
||||
// ── Vista CUENTAS: agrupado por cliente con subcuentas ─────────
|
||||
let ctaClientes = []; // [{nombre, rs, total, mora}] del último render
|
||||
let ctaSel = new Set(); // ids de subcuentas (renglones) seleccionadas
|
||||
let ctaAbiertas = new Set(); // nombres de cliente con acordeón abierto
|
||||
|
||||
function ctaResumenSub(r){
|
||||
const partes = [];
|
||||
const periodos = Array.isArray(r.periodos) ? r.periodos : [];
|
||||
if(r.tipo === "renta" && periodos.length >= 2){
|
||||
partes.push(periodos.length + " meses pendientes");
|
||||
}
|
||||
if((r.tipo === "vr" || r.tipo === "extra") && r.fecha_vencimiento){
|
||||
partes.push("vence " + fmtFechaEs(r.fecha_vencimiento));
|
||||
} else if(r.tipo === "renta" && r.dia_pago){
|
||||
partes.push("paga día " + r.dia_pago);
|
||||
}
|
||||
if(Number(r.moratorio) > 0) partes.push("mora " + fmt(r.moratorio));
|
||||
if(Number(r.dias_retraso) > 0) partes.push(r.dias_retraso + "d de atraso");
|
||||
return partes.join(" · ");
|
||||
}
|
||||
|
||||
function renderCuentas(){
|
||||
const cont = document.getElementById("cta-lista");
|
||||
if(!cont) return;
|
||||
// Poda la selección de renglones que ya no existen (saldados/eliminados).
|
||||
const vivos = new Set(renglones.map(r => r.id));
|
||||
[...ctaSel].forEach(id => { if(!vivos.has(id)) ctaSel.delete(id); });
|
||||
|
||||
const grupos = new Map();
|
||||
renglones.forEach(r => {
|
||||
const k = (r.cliente || "").trim() || "(Sin cliente)";
|
||||
if(!grupos.has(k)) grupos.set(k, []);
|
||||
grupos.get(k).push(r);
|
||||
});
|
||||
ctaClientes = [...grupos.entries()]
|
||||
.map(([nombre, rs]) => ({ nombre, rs,
|
||||
total: rs.reduce((s,r)=>s+(Number(r.saldo)||0),0),
|
||||
mora: rs.reduce((s,r)=>s+(Number(r.moratorio)||0),0) }))
|
||||
.sort((a,b) => b.total - a.total);
|
||||
|
||||
const nCli = ctaClientes.length;
|
||||
document.getElementById("cta-count").textContent =
|
||||
nCli + (nCli === 1 ? " cliente" : " clientes") + " · " +
|
||||
renglones.length + (renglones.length === 1 ? " subcuenta" : " subcuentas");
|
||||
|
||||
if(!nCli){
|
||||
cont.innerHTML = `<div style="text-align:center;color:var(--text-tertiary);padding:28px;font-size:13px">Sin cobranza activa. Usa "Cargar cobranza de hoy" en Tarjetas.</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
cont.innerHTML = ctaClientes.map((c,i) => {
|
||||
const abierta = ctaAbiertas.has(c.nombre);
|
||||
const sel = c.rs.filter(r => ctaSel.has(r.id));
|
||||
const totalSel = sel.reduce((s,r)=>s+(Number(r.saldo)||0),0);
|
||||
const selBadge = sel.length
|
||||
? ` <span class="cta-selbadge">· ${sel.length} sel · ${fmt(totalSel)}</span>` : "";
|
||||
const moraLinea = c.mora > 0 ? `<div class="cta-mora">mora ${fmt(c.mora)}</div>` : "";
|
||||
let body = "";
|
||||
if(abierta){
|
||||
const subcards = c.rs.map(r => {
|
||||
if(editingId === r.id) return `<div class="card" style="margin:10px 0">${renderEditInline(r)}</div>`;
|
||||
const marcada = ctaSel.has(r.id);
|
||||
return `
|
||||
<div class="sub-card${marcada ? " sel" : ""}">
|
||||
<div class="sub-row" onclick="ctaSelSub('${r.id}')">
|
||||
<span class="sub-check${marcada ? " on" : ""}">${marcada ? "✓" : ""}</span>
|
||||
<div class="sub-main">
|
||||
<div class="sub-title">${r.vehiculo} <span class="pill-tipo ${r.tipo}" style="margin:0">${tipoLabel(r)}</span></div>
|
||||
<div class="sub-meta">${ctaResumenSub(r)}</div>
|
||||
</div>
|
||||
<div class="sub-saldo">${fmt(r.saldo)}</div>
|
||||
</div>
|
||||
<div class="sub-actions">
|
||||
<button class="btn btn-cobro" onclick="abrirCobro('${r.id}')">Generar cobro</button>
|
||||
<button class="btn btn-abono" onclick="abrirAbonoDirecto('${r.id}')">💵 Abono</button>
|
||||
</div>
|
||||
<div class="sub-actions" style="padding-top:0">
|
||||
<button class="btn btn-pagado" onclick="marcarPagado('${r.id}')">✓ Saldar</button>
|
||||
<button class="btn btn-edit" onclick="entrarEdicion('${r.id}')">Editar</button>
|
||||
<button class="btn btn-edit" onclick="abrirMovs('${r.id}')">🕐 Movs</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}).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>
|
||||
<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>
|
||||
<button class="btn-wide" style="margin-top:10px" onclick="ctaImprimirMovs(${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="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg> Imprimir movimientos (${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">
|
||||
<div class="cta-tools">
|
||||
<label class="cta-seltodo">
|
||||
<input type="checkbox" ${todas ? "checked" : ""} onchange="ctaSelTodo(${i})"> Seleccionar todo
|
||||
</label>
|
||||
</div>
|
||||
${subcards}
|
||||
${foot}
|
||||
</div>`;
|
||||
}
|
||||
return `
|
||||
<div class="cta-block" style="animation-delay:${i*0.04}s">
|
||||
<div class="cta-head" onclick="ctaToggle(${i})">
|
||||
<span class="cta-chev">${abierta ? "▾" : "▸"}</span>
|
||||
<div class="cta-name">${escapeAttr(c.nombre)}
|
||||
<div class="cta-sub">${c.rs.length} subcuenta${c.rs.length===1?"":"s"}${selBadge}</div>
|
||||
</div>
|
||||
<div class="cta-tot">${fmt(c.total)}${moraLinea}</div>
|
||||
</div>
|
||||
${body}
|
||||
</div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function ctaToggle(i){
|
||||
const c = ctaClientes[i]; if(!c) return;
|
||||
if(ctaAbiertas.has(c.nombre)) ctaAbiertas.delete(c.nombre); else ctaAbiertas.add(c.nombre);
|
||||
renderCuentas();
|
||||
}
|
||||
function ctaSelSub(id){
|
||||
if(ctaSel.has(id)) ctaSel.delete(id); else ctaSel.add(id);
|
||||
renderCuentas();
|
||||
}
|
||||
function ctaSelTodo(i){
|
||||
const c = ctaClientes[i]; if(!c) return;
|
||||
const todas = c.rs.every(r => ctaSel.has(r.id));
|
||||
c.rs.forEach(r => { if(todas) ctaSel.delete(r.id); else ctaSel.add(r.id); });
|
||||
renderCuentas();
|
||||
}
|
||||
|
||||
// Imprimir movimientos: estado de cuenta PDF de las subcuentas
|
||||
// SELECCIONADAS del cliente (saldos + movimientos solo de esas).
|
||||
function ctaImprimirMovs(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; }
|
||||
window.open(API + "/estado-cuenta.pdf?token=" + encodeURIComponent(TOKEN) +
|
||||
"&cliente=" + encodeURIComponent(c.nombre) +
|
||||
"&ids=" + encodeURIComponent(ids.join(",")), "_blank");
|
||||
}
|
||||
|
||||
// Estado de cuenta PDF acotado a UNA subcuenta (desde el modal Movs).
|
||||
function exportarMovsPdf(id){
|
||||
const r = renglones.find(x => x.id === id); if(!r) return;
|
||||
window.open(API + "/estado-cuenta.pdf?token=" + encodeURIComponent(TOKEN) +
|
||||
"&cliente=" + encodeURIComponent(r.cliente || "") +
|
||||
"&vehiculo=" + encodeURIComponent(r.vehiculo || "") +
|
||||
"&tipo=" + encodeURIComponent(r.tipo || "renta") +
|
||||
"&ids=" + encodeURIComponent(r.id), "_blank");
|
||||
}
|
||||
|
||||
// ── 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 = "";
|
||||
@@ -828,8 +1108,12 @@ function renderCardNormal(r){
|
||||
<div class="card-total"><span class="lbl">Saldo pendiente</span><span class="val">${fmt(saldo)}</span></div>
|
||||
<div class="card-actions">
|
||||
<button class="btn btn-cobro" onclick="abrirCobro('${r.id}')"><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"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg> Generar cobro</button>
|
||||
<button class="btn btn-abono" onclick="abrirAbonoDirecto('${r.id}')">💵 Abono</button>
|
||||
</div>
|
||||
<div class="card-actions" style="margin-top:9px">
|
||||
<button class="btn btn-pagado" onclick="marcarPagado('${r.id}')">✓ Saldar</button>
|
||||
<button class="btn btn-edit" onclick="entrarEdicion('${r.id}')">Editar</button>
|
||||
<button class="btn btn-edit" onclick="abrirMovs('${r.id}')">🕐 Movs</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -876,11 +1160,13 @@ function entrarEdicion(id){
|
||||
editingId = id;
|
||||
editDraft = {}; // se reconstruye en renderEditInline
|
||||
renderTarjetas();
|
||||
renderCuentas();
|
||||
}
|
||||
function cancelarEdicion(){
|
||||
editingId = null;
|
||||
editDraft = {};
|
||||
renderTarjetas();
|
||||
renderCuentas();
|
||||
}
|
||||
async function guardarEdicion(){
|
||||
if(!editDraft.id) return;
|
||||
@@ -1249,11 +1535,121 @@ async function reenviarMensajeCobroContacto(){
|
||||
}
|
||||
|
||||
// ── Marcar pagado ────────────────────────────────────────────
|
||||
async function marcarPagado(id){
|
||||
// Fecha local (MX) en ISO — new Date().toISOString() sería UTC y de noche
|
||||
// daría el día siguiente.
|
||||
function hoyLocalISO(){
|
||||
const d = new Date();
|
||||
return d.getFullYear() + "-" + String(d.getMonth()+1).padStart(2,"0") + "-" + String(d.getDate()).padStart(2,"0");
|
||||
}
|
||||
|
||||
function marcarPagado(id){
|
||||
const r = renglones.find(x => x.id === id);
|
||||
if(!r) return;
|
||||
document.getElementById("modal-inner").classList.remove("lote");
|
||||
document.getElementById("modal-inner").innerHTML = `
|
||||
<div class="modal-header"><span class="modal-title">Saldar subcuenta</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:1.2rem">${r.cliente}<br>${r.vehiculo} · <span class="pill-tipo ${r.tipo}" style="margin:0">${tipoLabel(r)}</span><br>Saldo a liquidar: <strong style="color:var(--text-primary)">${fmt(r.saldo)}</strong></p>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Fecha del pago</label>
|
||||
<input type="date" class="form-input" id="inp-saldar-fecha" value="${hoyLocalISO()}">
|
||||
<div class="form-hint">Queda registrada en la bitácora de movimientos.</div>
|
||||
</div>
|
||||
<button class="btn-save" onclick="saldarConfirmar('${id}')">✓ Saldar completo</button>`;
|
||||
document.getElementById("modal").classList.add("open");
|
||||
}
|
||||
async function saldarConfirmar(id){
|
||||
const fecha = document.getElementById("inp-saldar-fecha").value || "";
|
||||
try {
|
||||
await api("/marcar-pagado", {method:"POST", body: JSON.stringify({id})});
|
||||
toast("Saldado"); await cargarRenglones();
|
||||
} catch(e){ toast("No se pudo saldar"); }
|
||||
await api("/marcar-pagado", {method:"POST", body: JSON.stringify({id, fecha})});
|
||||
toast("Saldado"); cerrar(); await cargarRenglones();
|
||||
} catch(e){ toast("No se pudo saldar: " + e.message); }
|
||||
}
|
||||
|
||||
// ── Abono directo (monto + fecha) desde la vista Cuentas ──────
|
||||
function abrirAbonoDirecto(id){
|
||||
const r = renglones.find(x => x.id === id);
|
||||
if(!r) return;
|
||||
document.getElementById("modal-inner").classList.remove("lote");
|
||||
document.getElementById("modal-inner").innerHTML = `
|
||||
<div class="modal-header"><span class="modal-title">Registrar abono</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:1.2rem">${r.cliente}<br>${r.vehiculo} · <span class="pill-tipo ${r.tipo}" style="margin:0">${tipoLabel(r)}</span><br>Saldo actual: <strong style="color:var(--text-primary)">${fmt(r.saldo)}</strong></p>
|
||||
<div class="form-group"><label class="form-label">Monto del abono</label><input type="number" step="0.01" min="0.01" max="${(Number(r.saldo)||0).toFixed(2)}" class="form-input" id="inp-ab-monto" placeholder="0.00" inputmode="decimal"><div class="form-hint">Máximo el saldo actual: ${fmt(r.saldo)}.</div></div>
|
||||
<div class="form-group"><label class="form-label">Fecha del pago</label><input type="date" class="form-input" id="inp-ab-fecha" value="${hoyLocalISO()}"></div>
|
||||
<div class="form-group"><label class="form-label">Nota (opcional)</label><input type="text" class="form-input" id="inp-ab-nota" placeholder="ej. transferencia BBVA"></div>
|
||||
<button class="btn-save" onclick="abonoDirectoConfirmar('${id}')">Registrar abono</button>`;
|
||||
document.getElementById("modal").classList.add("open");
|
||||
setTimeout(() => document.getElementById("inp-ab-monto").focus(), 80);
|
||||
}
|
||||
async function abonoDirectoConfirmar(id){
|
||||
const monto = parseFloat(document.getElementById("inp-ab-monto").value);
|
||||
const fecha = document.getElementById("inp-ab-fecha").value || "";
|
||||
const nota = document.getElementById("inp-ab-nota").value.trim();
|
||||
if(!monto || monto <= 0){ toast("Ingresa un monto válido"); return; }
|
||||
const r = renglones.find(x => x.id === id);
|
||||
const saldo = r ? (Number(r.saldo)||0) : 0;
|
||||
if(monto > saldo + 0.01){
|
||||
toast("El abono no puede exceder el saldo: " + fmt(saldo));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api("/abono", {method:"POST", body: JSON.stringify({id, monto, fecha, concepto: nota})});
|
||||
toast("Abono registrado"); cerrar(); await cargarRenglones();
|
||||
} catch(e){ toast("No se pudo registrar: " + e.message); }
|
||||
}
|
||||
|
||||
// ── Bitácora de movimientos de una subcuenta ──────────────────
|
||||
const MOV_LABEL = { abono: "Abono", saldado: "Saldado", saldo_periodo: "Mes saldado" };
|
||||
async function abrirMovs(id){
|
||||
const r = renglones.find(x => x.id === id);
|
||||
if(!r) return;
|
||||
const metaSub = [];
|
||||
if(r.fecha_alta) metaSub.push("Originación: " + fmtFechaEs(r.fecha_alta));
|
||||
metaSub.push("Saldo actual: " + fmt(r.saldo));
|
||||
document.getElementById("modal-inner").classList.remove("lote");
|
||||
document.getElementById("modal-inner").innerHTML = `
|
||||
<div class="modal-header"><span class="modal-title">Movimientos</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:1rem">${r.cliente}<br>${r.vehiculo} · <span class="pill-tipo ${r.tipo}" style="margin:0">${tipoLabel(r)}</span><br><span style="font-size:11.5px">${metaSub.join(" · ")}</span></p>
|
||||
<div id="movs-lista" style="font-size:13px;color:var(--text-tertiary)">Cargando…</div>
|
||||
<button class="btn-wide" style="margin-top:14px" onclick="exportarMovsPdf('${r.id}')"><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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg> Exportar estado de cuenta (PDF)</button>`;
|
||||
document.getElementById("modal").classList.add("open");
|
||||
try {
|
||||
const res = await api("/movimientos?cliente=" + encodeURIComponent(r.cliente||"") +
|
||||
"&vehiculo=" + encodeURIComponent(r.vehiculo||"") + "&tipo=" + encodeURIComponent(r.tipo||"renta") +
|
||||
"&renglon_id=" + encodeURIComponent(r.id));
|
||||
const movs = res.movimientos || [];
|
||||
const cont = document.getElementById("movs-lista");
|
||||
if(!cont) return;
|
||||
if(!movs.length){
|
||||
cont.innerHTML = `<div style="text-align:center;padding:18px">Sin movimientos registrados aún.</div>`;
|
||||
return;
|
||||
}
|
||||
cont.innerHTML = `<div class="form-hint" style="margin-bottom:6px">Últimos ${res.visibles} movimientos (configurable en la pestaña Cuentas).</div>` +
|
||||
movs.map(m => {
|
||||
// Mismo desglose que el estado de cuenta: saldo previo (con
|
||||
// moratorios) y saldo después del movimiento. Aproximado con
|
||||
// capital − abonado si el movimiento es previo al snapshot.
|
||||
const cap = (m.capital != null) ? Number(m.capital) : null;
|
||||
let despues = (m.saldo_despues != null) ? Number(m.saldo_despues) : null;
|
||||
if(despues == null && cap != null && m.abonado != null){
|
||||
despues = cap - Number(m.abonado);
|
||||
}
|
||||
const det = [];
|
||||
if(m.fecha_alta) det.push("Originación " + fmtFechaEs(m.fecha_alta));
|
||||
if(despues != null) det.push("Saldo previo " + fmt(despues + (Number(m.monto)||0)));
|
||||
if(despues != null) det.push("Saldo después " + fmt(despues));
|
||||
if(m.nota) det.push(m.nota);
|
||||
return `
|
||||
<div class="mov-item">
|
||||
<span class="mov-fecha">${fmtFechaEs(m.fecha)}</span>
|
||||
<span class="mov-tipo ${m.movimiento}">${MOV_LABEL[m.movimiento] || m.movimiento}</span>
|
||||
<span class="mov-monto" style="margin-left:auto">${fmt(m.monto)}</span>
|
||||
${det.length ? `<div class="mov-det">${det.join(" · ")}</div>` : ""}
|
||||
</div>`;
|
||||
}).join("");
|
||||
} catch(e){
|
||||
const cont = document.getElementById("movs-lista");
|
||||
if(cont) cont.textContent = "No se pudieron cargar los movimientos.";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Periodos de renta ────────────────────────────────────────
|
||||
@@ -1627,7 +2023,7 @@ function cerrar(){
|
||||
document.getElementById("modal").classList.remove("open");
|
||||
document.getElementById("modal-inner").classList.remove("lote");
|
||||
}
|
||||
const VISTAS_VALIDAS = ["tarjetas", "tabla", "directorio", "mensaje"];
|
||||
const VISTAS_VALIDAS = ["tarjetas", "cuentas", "tabla", "directorio", "mensaje"];
|
||||
const VIEW_KEY = "cobranza_view";
|
||||
|
||||
function setView(v){
|
||||
@@ -1657,6 +2053,18 @@ async function cargarConfigGlobal(){
|
||||
renderCuentasLista();
|
||||
rellenarPlantillaInputs();
|
||||
renderVistaPreviaMsg();
|
||||
const mv = document.getElementById("mov-visibles");
|
||||
if(mv) mv.value = configGlobal.movimientos_visibles || 10;
|
||||
}
|
||||
|
||||
async function guardarMovVisibles(){
|
||||
const n = parseInt(document.getElementById("mov-visibles").value, 10);
|
||||
if(!n || n < 1){ toast("Debe ser al menos 1"); return; }
|
||||
try {
|
||||
const res = await api("/config/movimientos", {method:"POST", body: JSON.stringify({movimientos_visibles: n})});
|
||||
if(configGlobal) configGlobal.movimientos_visibles = res.movimientos_visibles;
|
||||
toast("Guardado: se muestran " + res.movimientos_visibles + " movimientos");
|
||||
} catch(e){ toast("No se pudo guardar"); }
|
||||
}
|
||||
|
||||
function renderCuentasLista(){
|
||||
@@ -1773,6 +2181,9 @@ function bloqueChanged(){ sincBloquesUI(); renderVistaPreviaMsg(); }
|
||||
function rellenarPlantillaInputs(){
|
||||
const p = (configGlobal && configGlobal.plantilla) ? configGlobal.plantilla : {};
|
||||
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;
|
||||
@@ -1790,6 +2201,9 @@ function rellenarPlantillaInputs(){
|
||||
async function guardarPlantilla(){
|
||||
const body = {
|
||||
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,
|
||||
@@ -1874,10 +2288,13 @@ function armarMensajeCobro(r, monto, concepto, link){
|
||||
};
|
||||
const incluirLink = (pl.incluir_link !== false) && !!link;
|
||||
|
||||
const introTxt = pl.texto_intro != null ? pl.texto_intro : "Le compartimos los datos para realizar su pago:";
|
||||
const conceptoTxt = pl.texto_concepto != null ? pl.texto_concepto : "Concepto: {concepto}";
|
||||
|
||||
let out = "";
|
||||
if(pl.saludo) out += _aplicarVariables(pl.saludo, vars) + "\n\n";
|
||||
out += "Le compartimos los datos para realizar su pago:\n\n";
|
||||
out += `Concepto: ${concepto}\n`;
|
||||
out += _aplicarVariables(introTxt, vars) + "\n\n";
|
||||
out += _aplicarVariables(conceptoTxt, vars) + "\n";
|
||||
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";
|
||||
@@ -1915,6 +2332,8 @@ function renderVistaPreviaMsg(){
|
||||
cuentas: (configGlobal && configGlobal.cuentas) ? configGlobal.cuentas : [],
|
||||
plantilla: {
|
||||
saludo: document.getElementById("pl-saludo").value,
|
||||
texto_intro: document.getElementById("pl-intro").value,
|
||||
texto_concepto: document.getElementById("pl-concepto").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