feat(cobranza): abono/saldar con fecha + bitácora de movimientos (Fase 2)
Ledger `cobranza_mov:{numero}` independiente de los renglones: cada
abono, saldado y mes saldado queda registrado (fecha capturada, monto,
nota) y SOBREVIVE al borrado del renglón. Guarda hasta 500; la config
`movimientos_visibles` (editable en pestaña Mensaje) limita solo la
vista. Panel: modal de abono (monto+fecha+nota) y de saldar (fecha) en
la vista Cuentas, botón Movs con historial por subcuenta.
API: GET /api/movimientos, POST /api/config/movimientos, campo `fecha`
en /api/abono y /api/marcar-pagado. Todo aditivo; 129 tests en verde.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
da2795c74c
commit
d178a99d2a
4 files changed
+490
-14
No files matched your search
+63
-3
@@ -10,7 +10,7 @@ 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
|
||||
@@ -175,6 +175,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):
|
||||
@@ -186,6 +187,24 @@ 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 _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):
|
||||
@@ -331,7 +350,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}
|
||||
@@ -361,8 +383,9 @@ 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)
|
||||
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")
|
||||
@@ -396,6 +419,29 @@ 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),
|
||||
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).
|
||||
"""
|
||||
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,
|
||||
limite=limite or visibles,
|
||||
)
|
||||
return {"movimientos": movs, "visibles": visibles}
|
||||
|
||||
|
||||
@router.put("/api/renglon")
|
||||
async def editar(body: RenglonEditBody, token: str = Query(...)):
|
||||
numero = await _numero_token(token)
|
||||
@@ -782,6 +828,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,99 @@ 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 = "",
|
||||
) -> 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"}.
|
||||
"""
|
||||
try:
|
||||
mov = {
|
||||
"id": uuid.uuid4().hex[:8],
|
||||
"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 "",
|
||||
}
|
||||
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,
|
||||
) -> 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.
|
||||
"""
|
||||
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
|
||||
out.append(m)
|
||||
if limite and len(out) >= limite:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
# ── Cálculos del moratorio ──────────────────────────────────────
|
||||
|
||||
def _hoy_mx() -> date:
|
||||
@@ -721,27 +814,37 @@ 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,
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -771,6 +874,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 +888,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}",
|
||||
)
|
||||
return True
|
||||
r["periodos"] = restantes
|
||||
r["monto"] = round(sum(float(p.get("mensualidad") or 0.0) for p in restantes), 2)
|
||||
@@ -787,31 +900,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 +1000,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(
|
||||
@@ -1443,9 +1575,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)),
|
||||
}
|
||||
|
||||
|
||||
@@ -1516,6 +1653,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,148 @@
|
||||
"""
|
||||
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"
|
||||
|
||||
|
||||
@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"
|
||||
|
||||
|
||||
@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"
|
||||
|
||||
|
||||
@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_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
|
||||
+125
-4
@@ -233,6 +233,17 @@
|
||||
.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; }
|
||||
.mov-item:last-child { border-bottom: none; }
|
||||
.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); }
|
||||
@@ -486,6 +497,16 @@
|
||||
|
||||
<button class="btn-save" onclick="guardarPlantilla()">Guardar plantilla</button>
|
||||
|
||||
<div class="section-label" style="margin-top:24px"><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" style="margin-top:24px"><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"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg> Vista previa</div>
|
||||
<div class="preview-msg" id="preview-msg"></div>
|
||||
</div>
|
||||
@@ -824,8 +845,12 @@ function renderCuentas(){
|
||||
</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("");
|
||||
@@ -1415,11 +1440,95 @@ 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" class="form-input" id="inp-ab-monto" placeholder="0.00" inputmode="decimal"></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; }
|
||||
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;
|
||||
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></p>
|
||||
<div id="movs-lista" style="font-size:13px;color:var(--text-tertiary)">Cargando…</div>`;
|
||||
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"));
|
||||
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 Mensaje).</div>` +
|
||||
movs.map(m => `
|
||||
<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-desc">${m.nota || ""}</span>
|
||||
<span class="mov-monto">${fmt(m.monto)}</span>
|
||||
</div>`).join("");
|
||||
} catch(e){
|
||||
const cont = document.getElementById("movs-lista");
|
||||
if(cont) cont.textContent = "No se pudieron cargar los movimientos.";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Periodos de renta ────────────────────────────────────────
|
||||
@@ -1823,6 +1932,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(){
|
||||
|
||||
Reference in new issue
Block a user