Snapshot inicial wk-bot en produccion: cobranza acumulada completa, Conekta, SPEI, directorio

This commit is contained in:
Collina Admin committed 2026-06-19 23:25:56 +00:00
commit 729a45e4fa
61 files changed
+13111

No files matched your search

View File
Whitespace-only changes.
+118
View File
@@ -0,0 +1,118 @@
"""
API REST de administración de recordatorios.
Cualquier usuario autorizado (con token válido) puede ver y gestionar
TODOS los recordatorios, no solo los suyos. La identidad del token solo
se usa como default al crear (si no se especifica `numero` en el body).
"""
import logging
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from src.services import recordatorios
from src.services.scheduler import sincronizar_jobs
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/admin")
NOMBRES_CONOCIDOS = {
"2222127552": "Paulino",
"2225072517": "Vianney",
"2225548174": "Gustavo",
}
def _nombre(numero: str) -> str:
"""Devuelve el nombre conocido o los últimos 10 dígitos."""
return NOMBRES_CONOCIDOS.get(numero, (numero or "")[-10:])
async def _verificar_token(token: str) -> str:
"""Devuelve el número asociado al token o lanza 401."""
numero = await recordatorios.validar_token_admin(token)
if not numero:
raise HTTPException(status_code=401, detail="Link expirado o inválido")
return numero
class RecordatorioIn(BaseModel):
tipo: str
hora: str
dias: list[int]
activo: bool = True
# Opcional: para quién es el recordatorio. Si no se manda, se usa el
# número del token (legacy behavior).
numero: str | None = None
@router.get("/ping")
async def ping(token: str = Query(..., description="Token de admin")):
numero = await _verificar_token(token)
return {"numero": numero, "nombre": _nombre(numero), "valid": True}
@router.get("/recordatorios")
async def listar(token: str = Query(...)):
"""Devuelve TODOS los recordatorios (no solo los del usuario del token)."""
await _verificar_token(token)
items = await recordatorios.get_recordatorios()
# Enriquecemos con el nombre del owner para el UI.
for r in items:
r["nombre"] = _nombre(r.get("numero", ""))
return items
@router.post("/recordatorios")
async def crear(body: RecordatorioIn, token: str = Query(...)):
"""Crea un recordatorio para `body.numero` (o el del token por default)."""
numero_token = await _verificar_token(token)
data = body.model_dump()
numero_destino = (data.get("numero") or "").strip() or numero_token
data["numero"] = numero_destino
data["nombre"] = _nombre(numero_destino)
nuevo = await recordatorios.crear_recordatorio(data)
await sincronizar_jobs()
return nuevo
@router.put("/recordatorios/{id}")
async def actualizar(id: str, body: RecordatorioIn, token: str = Query(...)):
"""Actualiza cualquier recordatorio (sin chequear ownership)."""
await _verificar_token(token)
data = body.model_dump()
# Permite mover un recordatorio a otro número si se incluye en el body.
if data.get("numero"):
data["nombre"] = _nombre(data["numero"])
else:
data.pop("numero", None)
actualizado = await recordatorios.actualizar_recordatorio(id, data)
if not actualizado:
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
await sincronizar_jobs()
return actualizado
@router.delete("/recordatorios/{id}")
async def eliminar(id: str, token: str = Query(...)):
"""Elimina cualquier recordatorio (sin chequear ownership)."""
await _verificar_token(token)
ok = await recordatorios.eliminar_recordatorio(id)
if not ok:
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
await sincronizar_jobs()
return {"ok": True}
@router.patch("/recordatorios/{id}/toggle")
async def toggle(id: str, token: str = Query(...)):
"""Activa/desactiva cualquier recordatorio (sin chequear ownership)."""
await _verificar_token(token)
actualizado = await recordatorios.toggle_activo(id)
if not actualizado:
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
await sincronizar_jobs()
return actualizado
+658
View File
@@ -0,0 +1,658 @@
"""
Página HTML de administración de recordatorios (estética neumórfica).
Una sola SPA inline (sin dependencias externas excepto Google Fonts).
Se sirve desde GET /admin/ui?token=XXX. El JS hace fetch a
/admin/recordatorios?token=XXX para CRUD.
"""
from fastapi import APIRouter, Query
from fastapi.responses import HTMLResponse
from src.services import recordatorios
router = APIRouter()
@router.get("/admin/ui", response_class=HTMLResponse)
async def ui(token: str = Query(...)):
numero = await recordatorios.validar_token_admin(token)
if not numero:
return HTMLResponse(_HTML_EXPIRED, status_code=401)
return HTMLResponse(_HTML_PAGE.replace("__TOKEN__", token))
# ── Página de token expirado ───────────────────────────────────────
_HTML_EXPIRED = """<!DOCTYPE html>
<html lang="es"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Link expirado · Recordatorios WK</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
--bg:#e8eaf0; --surface:#eef0f5;
--shadow-light:rgba(255,255,255,0.85);
--shadow-dark:rgba(180,185,200,0.6);
--text-primary:#2d3148; --text-secondary:#7b82a0; --text-tertiary:#a8aec4;
--accent:#4f8ef7; --accent-glow:rgba(79,142,247,0.25);
--nm-out:6px 6px 14px var(--shadow-dark), -6px -6px 14px var(--shadow-light);
--nm-subtle:3px 3px 8px var(--shadow-dark), -3px -3px 8px var(--shadow-light);
}
*{box-sizing:border-box;-webkit-font-smoothing:antialiased;}
body{
font-family:'DM Sans',-apple-system,system-ui,sans-serif;
background:var(--bg); margin:0; padding:0;
min-height:100vh; display:flex; align-items:center; justify-content:center;
color:var(--text-primary); padding:24px;
}
.card{
background:var(--surface); border-radius:28px;
box-shadow:var(--nm-out); padding:40px 32px;
max-width:380px; width:100%; text-align:center;
}
.icon-wrap{
width:80px; height:80px; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-out);
display:flex; align-items:center; justify-content:center;
margin:0 auto 24px; font-size:36px;
}
h1{ font-size:22px; font-weight:600; margin:0 0 12px; color:var(--text-primary); }
p{ color:var(--text-secondary); font-size:15px; line-height:1.55; margin:0; }
strong{ color:var(--accent); font-weight:600; }
</style>
</head><body>
<div class="card">
<div class="icon-wrap">🔒</div>
<h1>Link expirado</h1>
<p>Este link de configuración ya no es válido. Envía la palabra <strong>recordatorio</strong> al bot de WhatsApp para obtener uno nuevo.</p>
</div>
</body></html>"""
# ── SPA principal ──────────────────────────────────────────────────
_HTML_PAGE = """<!DOCTYPE html>
<html lang="es"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Recordatorios WK · Cotizador Collina</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
--bg:#e8eaf0; --surface:#eef0f5;
--shadow-light:rgba(255,255,255,0.85);
--shadow-dark:rgba(180,185,200,0.6);
--text-primary:#2d3148; --text-secondary:#7b82a0; --text-tertiary:#a8aec4;
--accent:#4f8ef7; --accent-glow:rgba(79,142,247,0.25);
--accent-soft:rgba(79,142,247,0.08);
--success:#34c98a; --danger:#f06070;
--nm-out:6px 6px 14px var(--shadow-dark), -6px -6px 14px var(--shadow-light);
--nm-in:inset 4px 4px 10px var(--shadow-dark), inset -4px -4px 10px var(--shadow-light);
--nm-subtle:3px 3px 8px var(--shadow-dark), -3px -3px 8px var(--shadow-light);
}
*{ box-sizing:border-box; -webkit-font-smoothing:antialiased; }
html,body{ background:var(--bg); }
body{
font-family:'DM Sans',-apple-system,system-ui,sans-serif;
margin:0; padding:24px 16px 96px;
color:var(--text-primary); min-height:100vh;
}
.container{ max-width:480px; margin:0 auto; }
/* ── Header ── */
.header{ text-align:center; margin-bottom:28px; }
.header .icon-wrap{
width:72px; height:72px; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-out);
display:flex; align-items:center; justify-content:center;
margin:0 auto 16px; font-size:32px;
}
.header h1{
font-size:22px; font-weight:700; margin:0 0 4px;
color:var(--text-primary); letter-spacing:-0.3px;
}
.header .subtitle{
font-size:14px; color:var(--text-secondary); margin:0; font-weight:500;
}
/* ── Lista de recordatorios ── */
#list{ display:flex; flex-direction:column; gap:14px; }
.rec-card{
background:var(--surface); border-radius:22px;
box-shadow:var(--nm-out); padding:18px;
opacity:0; transform:translateY(12px);
animation:fadeUp .45s cubic-bezier(.34,1.56,.64,1) forwards;
}
@keyframes fadeUp{ to{ opacity:1; transform:translateY(0); } }
.rec-top{ display:flex; align-items:center; gap:14px; }
.avatar{
width:48px; height:48px; flex-shrink:0; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-subtle);
display:flex; align-items:center; justify-content:center;
font-size:22px;
}
.rec-info{ flex:1; min-width:0; }
.rec-name{
font-size:15px; font-weight:600; color:var(--text-primary);
margin:0 0 4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
}
.rec-meta{
display:flex; align-items:center; gap:8px; flex-wrap:wrap;
font-size:12.5px; color:var(--text-secondary); font-weight:500;
}
.pill{
background:var(--accent-soft); color:var(--accent);
padding:3px 10px; border-radius:12px;
font-size:11.5px; font-weight:600; text-transform:capitalize;
letter-spacing:0.2px;
}
.dot{ color:var(--text-tertiary); }
/* ── Toggle neumórfico ── */
.toggle{
width:46px; height:26px; border-radius:14px;
background:var(--surface); box-shadow:var(--nm-in);
position:relative; cursor:pointer; flex-shrink:0;
transition:background .35s cubic-bezier(.34,1.56,.64,1);
}
.toggle::after{
content:''; position:absolute; top:3px; left:3px;
width:20px; height:20px; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-subtle);
transition:transform .35s cubic-bezier(.34,1.56,.64,1), background .25s;
}
.toggle.on{ background:var(--accent); box-shadow:var(--nm-in), 0 0 0 1px var(--accent-glow); }
.toggle.on::after{ transform:translateX(20px); background:#fff; }
/* ── Acciones de la card ── */
.rec-actions{
display:flex; justify-content:flex-end; gap:10px;
margin-top:14px; padding-top:12px;
border-top:1px solid rgba(168,174,196,0.18);
}
.icon-btn{
width:38px; height:38px; border-radius:12px;
background:var(--surface); box-shadow:var(--nm-subtle);
border:none; cursor:pointer; font-size:15px;
color:var(--text-secondary);
display:flex; align-items:center; justify-content:center;
transition:all .15s ease;
}
.icon-btn:hover{ color:var(--accent); }
.icon-btn:active{ box-shadow:var(--nm-in); transform:scale(.96); }
.icon-btn.danger:hover{ color:var(--danger); }
/* ── Empty state ── */
.empty{
text-align:center; padding:48px 24px;
background:var(--surface); border-radius:22px;
box-shadow:var(--nm-out); color:var(--text-secondary);
font-size:14.5px; line-height:1.6;
}
.empty .icon-wrap{
width:64px; height:64px; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-in);
display:flex; align-items:center; justify-content:center;
margin:0 auto 16px; font-size:28px; opacity:0.7;
}
/* ── Botón "Nuevo recordatorio" ── */
.add-btn{
display:flex; align-items:center; justify-content:center; gap:12px;
width:100%; padding:16px; margin-top:24px;
background:var(--surface); color:var(--text-primary);
border:none; border-radius:18px; cursor:pointer;
box-shadow:var(--nm-out);
font:600 15px/1 'DM Sans',sans-serif;
transition:all .15s ease;
}
.add-btn:active{ box-shadow:var(--nm-in); }
.add-circle{
width:36px; height:36px; border-radius:50%;
background:var(--accent); color:#fff;
display:flex; align-items:center; justify-content:center;
font-size:22px; font-weight:300; line-height:1;
box-shadow:0 4px 12px var(--accent-glow);
}
/* ── Modal ── */
.modal-backdrop{
position:fixed; inset:0; background:rgba(45,49,72,0.28);
backdrop-filter:blur(8px); -webkit-backdrop-filter:blur(8px);
display:none; align-items:flex-end; justify-content:center;
z-index:100; padding:0;
}
.modal-backdrop.show{ display:flex; animation:fade .25s ease; }
@keyframes fade{ from{ opacity:0; } to{ opacity:1; } }
.modal{
background:var(--surface); border-radius:28px 28px 0 0;
width:100%; max-width:480px; max-height:92vh; overflow-y:auto;
padding:24px 22px 28px;
box-shadow:0 -8px 32px rgba(45,49,72,0.18);
transform:translateY(100%);
animation:slideUp .42s cubic-bezier(.34,1.56,.64,1) forwards;
}
@keyframes slideUp{ to{ transform:translateY(0); } }
.modal-handle{
width:48px; height:5px; border-radius:3px;
background:var(--text-tertiary); opacity:0.4;
margin:0 auto 18px;
}
.modal h2{
font-size:18px; font-weight:600; margin:0 0 20px;
text-align:center; color:var(--text-primary);
}
.field{ margin-bottom:18px; }
.field label{
display:block; font-size:12.5px; font-weight:600;
color:var(--text-secondary); margin-bottom:8px;
text-transform:uppercase; letter-spacing:0.5px;
}
.input{
width:100%; padding:14px 16px;
background:var(--surface); color:var(--text-primary);
border:none; border-radius:14px; box-shadow:var(--nm-in);
font:500 15px/1 'DM Sans',sans-serif; outline:none;
appearance:none; -webkit-appearance:none;
}
select.input{
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1l5 5 5-5' stroke='%237b82a0' stroke-width='1.8' fill='none' stroke-linecap='round'/></svg>");
background-repeat:no-repeat; background-position:right 18px center;
padding-right:42px;
}
input[type=time].input{ font-variant-numeric:tabular-nums; }
.days{ display:grid; grid-template-columns:repeat(7,1fr); gap:8px; }
.day{
background:var(--surface); box-shadow:var(--nm-subtle);
border:none; border-radius:12px; cursor:pointer;
padding:12px 0; text-align:center;
font:600 14px/1 'DM Sans',sans-serif;
color:var(--text-secondary);
transition:all .18s ease;
}
.day:active{ transform:scale(.94); }
.day.active{
background:var(--accent); color:#fff;
box-shadow:var(--nm-subtle), 0 0 0 1px var(--accent-glow);
}
.modal-actions{
display:flex; gap:12px; margin-top:26px;
}
.btn{
flex:1; padding:14px; border:none; border-radius:14px;
cursor:pointer; font:600 15px/1 'DM Sans',sans-serif;
transition:all .15s ease;
}
.btn-secondary{
background:var(--surface); color:var(--text-secondary);
box-shadow:var(--nm-subtle);
}
.btn-secondary:active{ box-shadow:var(--nm-in); }
.btn-primary{
background:var(--accent); color:#fff;
box-shadow:0 6px 18px var(--accent-glow);
}
.btn-primary:active{ transform:scale(.98); box-shadow:0 3px 10px var(--accent-glow); }
/* ── Pantalla de token expirado (oculta por default) ── */
.expired-screen{
position:fixed; inset:0; z-index:300;
background:var(--bg);
display:flex; align-items:center; justify-content:center;
padding:24px;
}
.expired-card{
background:var(--surface); border-radius:28px;
box-shadow:var(--nm-out); padding:40px 32px;
max-width:380px; width:100%; text-align:center;
}
.expired-icon{
width:80px; height:80px; border-radius:50%;
background:var(--surface); box-shadow:var(--nm-out);
display:flex; align-items:center; justify-content:center;
margin:0 auto 24px; font-size:36px;
}
.expired-card h1{
font-size:22px; font-weight:600; margin:0 0 12px;
color:var(--text-primary);
}
.expired-card p{
color:var(--text-secondary); font-size:15px; line-height:1.55; margin:0;
}
.expired-card strong{ color:var(--accent); font-weight:600; }
/* ── Toast ── */
.toast{
position:fixed; left:50%; bottom:32px;
transform:translate(-50%,120%);
background:#2d3148; color:#fff;
padding:12px 22px; border-radius:20px;
font:500 14px/1 'DM Sans',sans-serif;
box-shadow:0 8px 24px rgba(45,49,72,0.32);
z-index:200; opacity:0; pointer-events:none;
}
.toast.show{
animation:toastIn .45s cubic-bezier(.34,1.56,.64,1) forwards;
}
@keyframes toastIn{
0%{ transform:translate(-50%,120%); opacity:0; }
60%{ transform:translate(-50%,-8%); opacity:1; }
100%{ transform:translate(-50%,0); opacity:1; }
}
</style>
</head><body>
<div class="container">
<div class="header">
<div class="icon-wrap">🔔</div>
<h1>Recordatorios WK</h1>
<p class="subtitle" id="userName">Cargando…</p>
</div>
<div id="list"></div>
<button class="add-btn" onclick="openModal()">
<span class="add-circle">+</span>
<span>Nuevo recordatorio</span>
</button>
</div>
<div class="modal-backdrop" id="modal" onclick="if(event.target===this)closeModal()">
<div class="modal">
<div class="modal-handle"></div>
<h2 id="modalTitle">Nuevo recordatorio</h2>
<div class="field">
<label>Para quién</label>
<select id="numero" class="input" onchange="onNumeroChange()">
<option value="2222127552">Paulino</option>
<option value="2225072517">Vianney</option>
<option value="2225548174">Gustavo</option>
<option value="__other__">Otro número…</option>
</select>
</div>
<div class="field" id="otherNumeroField" style="display:none">
<label>Número (10 dígitos, +521 se agrega automáticamente)</label>
<input type="tel" id="numeroOtro" class="input"
inputmode="numeric" pattern="[0-9]*" maxlength="10"
placeholder="2221234567"
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
</div>
<div class="field">
<label>Tipo de reporte</label>
<select id="tipo" class="input">
<option value="diario">Diario (cobros del día)</option>
<option value="semanal">Semanal (lun-vie)</option>
<option value="mensual">Mensual (VR + extraordinarias)</option>
</select>
</div>
<div class="field">
<label>Hora (zona México)</label>
<input type="time" id="hora" class="input" value="08:00">
</div>
<div class="field">
<label>Días de la semana</label>
<div class="days" id="days">
<button type="button" class="day" data-d="0">L</button>
<button type="button" class="day" data-d="1">M</button>
<button type="button" class="day" data-d="2">X</button>
<button type="button" class="day" data-d="3">J</button>
<button type="button" class="day" data-d="4">V</button>
<button type="button" class="day" data-d="5">S</button>
<button type="button" class="day" data-d="6">D</button>
</div>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
<button class="btn btn-primary" onclick="guardar()">Guardar</button>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<section id="expired" class="expired-screen" style="display:none">
<div class="expired-card">
<div class="expired-icon">🔒</div>
<h1>Link expirado</h1>
<p>Envía <strong>recordatorio</strong> al bot de WhatsApp para obtener uno nuevo.</p>
</div>
</section>
<script>
const TOKEN = "__TOKEN__";
const API = "/admin/recordatorios";
const NOMBRES = {
"2222127552": "Paulino",
"2225072517": "Vianney",
"2225548174": "Gustavo",
};
const EMOJIS = {
"2222127552": "👨‍💼",
"2225072517": "👩‍💼",
"2225548174": "👨‍💻",
};
const DAY_NAMES = ["L","M","X","J","V","S","D"];
const TIPO_LABEL = { diario:"Diario", semanal:"Semanal", mensual:"Mensual" };
let recordatorios = [];
let editingId = null;
let currentNumero = null;
function nombreDe(numero){
if(!numero) return "";
if(NOMBRES[numero]) return NOMBRES[numero];
// Formato +52 1 222 123 4567 para números desconocidos.
const s = String(numero);
if(s.length === 10){
return "+52 1 " + s.slice(0,3) + " " + s.slice(3,6) + " " + s.slice(6);
}
return s;
}
function emojiDe(numero){ return EMOJIS[numero] || "👤"; }
function esConocido(numero){ return !!NOMBRES[numero]; }
function onNumeroChange(){
const sel = document.getElementById("numero");
const wrap = document.getElementById("otherNumeroField");
const input = document.getElementById("numeroOtro");
if(sel.value === "__other__"){
wrap.style.display = "block";
setTimeout(() => input.focus(), 50);
} else {
wrap.style.display = "none";
input.value = "";
}
}
function toast(msg){
const t = document.getElementById("toast");
t.textContent = msg;
t.classList.remove("show");
void t.offsetWidth;
t.classList.add("show");
setTimeout(() => t.classList.remove("show"), 2600);
}
function showExpired(){
// Oculta TODO lo demás y muestra solo la pantalla de expirado.
document.querySelectorAll(".container, .modal-backdrop, .toast")
.forEach(el => { el.style.display = "none"; });
const exp = document.getElementById("expired");
if(exp) exp.style.display = "flex";
}
async function loadPing(){
try{
const res = await fetch("/admin/ping?token=" + TOKEN);
if(!res.ok){ showExpired(); return false; }
const data = await res.json();
currentNumero = data.numero;
document.getElementById("userName").textContent =
"Sesión de " + data.nombre + " · gestionas los recordatorios de todos";
return true;
} catch(e){
showExpired();
return false;
}
}
async function load(){
const ok = await loadPing();
if(!ok) return;
const res = await fetch(API + "?token=" + TOKEN);
if(!res.ok) return;
recordatorios = await res.json();
render();
}
function render(){
const list = document.getElementById("list");
if(!recordatorios.length){
list.innerHTML = `
<div class="empty">
<div class="icon-wrap">📭</div>
<div>No tienes recordatorios todavía.<br>Crea uno con el botón de abajo.</div>
</div>`;
return;
}
list.innerHTML = recordatorios.map((r, i) => {
const ownerNumero = r.numero || "";
const ownerName = r.nombre || nombreDe(ownerNumero);
const emoji = emojiDe(ownerNumero);
const tipo = TIPO_LABEL[r.tipo] || r.tipo;
const dias = (r.dias || []).map(d => DAY_NAMES[d]).join(" ");
return `
<div class="rec-card" style="animation-delay:${i*50}ms;">
<div class="rec-top">
<div class="avatar">${emoji}</div>
<div class="rec-info">
<div class="rec-name">${ownerName}</div>
<div class="rec-meta">
<span>${r.hora}</span>
<span class="dot">·</span>
<span class="pill">${tipo}</span>
<span class="dot">·</span>
<span>${dias}</span>
</div>
</div>
<div class="toggle ${r.activo ? 'on' : ''}" onclick="toggle('${r.id}')"></div>
</div>
<div class="rec-actions">
<button class="icon-btn" onclick="edit('${r.id}')" title="Editar">✏️</button>
<button class="icon-btn danger" onclick="del('${r.id}')" title="Eliminar">🗑</button>
</div>
</div>`;
}).join("");
}
function openModal(r){
editingId = r ? r.id : null;
document.getElementById("modalTitle").textContent =
r ? "Editar recordatorio" : "Nuevo recordatorio";
const ownerNumero = r ? (r.numero || currentNumero) : currentNumero;
const numeroSelect = document.getElementById("numero");
const numeroOtro = document.getElementById("numeroOtro");
if(numeroSelect){
if(ownerNumero && esConocido(ownerNumero)){
numeroSelect.value = ownerNumero;
numeroOtro.value = "";
} else if(ownerNumero){
numeroSelect.value = "__other__";
numeroOtro.value = String(ownerNumero);
} else {
numeroSelect.value = currentNumero && esConocido(currentNumero)
? currentNumero : numeroSelect.options[0].value;
numeroOtro.value = "";
}
}
onNumeroChange();
document.getElementById("tipo").value = r ? r.tipo : "diario";
document.getElementById("hora").value = r ? r.hora : "08:00";
const dias = r ? r.dias : [0,1,2,3,4];
document.querySelectorAll(".day").forEach(d => {
const v = parseInt(d.dataset.d);
d.classList.toggle("active", dias.includes(v));
});
document.getElementById("modal").classList.add("show");
}
function closeModal(){
document.getElementById("modal").classList.remove("show");
editingId = null;
}
document.querySelectorAll(".day").forEach(d => {
d.addEventListener("click", () => d.classList.toggle("active"));
});
function edit(id){
const r = recordatorios.find(x => x.id === id);
if(r) openModal(r);
}
async function toggle(id){
const res = await fetch(API + "/" + id + "/toggle?token=" + TOKEN, { method:"PATCH" });
if(res.ok){ await load(); toast("Actualizado"); }
}
async function del(id){
if(!confirm("¿Eliminar este recordatorio?")) return;
const res = await fetch(API + "/" + id + "?token=" + TOKEN, { method:"DELETE" });
if(res.ok){ await load(); toast("Eliminado"); }
}
async function guardar(){
const tipo = document.getElementById("tipo").value;
const hora = document.getElementById("hora").value;
const sel = document.getElementById("numero").value;
let numero = sel;
if(sel === "__other__"){
numero = (document.getElementById("numeroOtro").value || "").trim();
if(!/^\\d{10}$/.test(numero)){
alert("El número debe tener exactamente 10 dígitos (sin +521).");
return;
}
}
const dias = Array.from(document.querySelectorAll(".day.active"))
.map(d => parseInt(d.dataset.d));
if(!dias.length){ alert("Selecciona al menos un día"); return; }
if(!hora){ alert("Indica la hora"); return; }
if(!numero){ alert("Selecciona para quién"); return; }
const body = { tipo, hora, dias, activo:true, numero };
const url = editingId ? API + "/" + editingId + "?token=" + TOKEN
: API + "?token=" + TOKEN;
const method = editingId ? "PUT" : "POST";
const res = await fetch(url, {
method,
headers:{ "Content-Type":"application/json" },
body: JSON.stringify(body),
});
if(res.ok){
closeModal();
await load();
toast("Guardado");
} else {
const err = await res.json().catch(() => ({}));
alert("Error: " + (err.detail || res.statusText));
}
}
load();
</script>
</body></html>"""
+670
View File
@@ -0,0 +1,670 @@
"""
API REST + UI del panel de cobranza acumulada.
Cada token está scoped al número del usuario que lo generó: el panel solo
ve y muta SU versión de la cobranza. Reutiliza `validar_token_admin` para
compartir el mismo storage (`admin_token:{token}`) que los recordatorios.
"""
import logging
import os
from pathlib import Path
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from src.services import cobranza_acumulada, pagos, recordatorios, whatsapp
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/admin/cobranza")
# ── Contactos para el "reenviar a contacto" del panel ───────────
# Mismas tres personas conocidas del bot. Cualquiera con un token puede
# reenviar un link a estos contactos.
CONTACTOS = {
"Paulino": "2222127552",
"Vianney": "2225072517",
"Gustavo": "2225548174",
}
# ── Helpers ─────────────────────────────────────────────────────
async def _numero_token(token: str) -> str:
n = await recordatorios.validar_token_admin(token)
if not n:
raise HTTPException(status_code=401, detail="Link expirado o inválido")
return n
def _wa_address(numero_10: str) -> str:
"""Convierte 10 dígitos en la dirección WhatsApp que espera EvolutionAPI."""
return f"521{numero_10}@s.whatsapp.net"
def _instance() -> str:
return os.getenv("EVOLUTION_INSTANCE", "wk-bot")
def _mensaje_cobro(cliente: str, vehiculo: str, concepto: str,
monto: float, link: str) -> str:
return (
f"Hola, le saludamos de WK Financing. Le compartimos su pago pendiente:\n\n"
f"Cliente: {cliente}\n"
f"Vehículo: {vehiculo}\n"
f"Concepto: {concepto}\n"
f"Monto a pagar: ${monto:,.2f}\n\n"
f"Puede pagar con tarjeta, transferencia SPEI o efectivo en Oxxo desde este link:\n{link}\n\n"
f"Gracias por su preferencia."
)
# ── Pydantic ────────────────────────────────────────────────────
class IdBody(BaseModel):
id: str
class MarcarPagadoBody(BaseModel):
id: str
nota: str | None = None
class AbonoBody(BaseModel):
id: str
monto: float
concepto: str | None = ""
class RenglonEditBody(BaseModel):
id: str
cliente: str | None = None
vehiculo: str | None = None
# Modelo nuevo: un solo `monto` por renglón (su concepto).
monto: float | None = None
tasa_mensual: float | None = None
telefono: str | None = None
fecha_alta: str | None = None
class TelefonoBody(BaseModel):
id: str
telefono: str
# Nombre opcional asociado al override (heredado de un contacto del
# dropdown o capturado en el input "Nombre (opcional)" del modal).
# Compatible con clientes viejos que no manden el campo.
nombre: str | None = None
class DirectorioBody(BaseModel):
nombre_norm: str
telefono: str # 10 dígitos o "" para borrar
class ContactoManualCreateBody(BaseModel):
nombre: str
telefono: str # 10 dígitos exactos
class ContactoManualEditBody(BaseModel):
id: str
nombre: str | None = None
telefono: str | None = None
class AbonoIdBody(BaseModel):
id_renglon: str
id_abono: str
class RenglonManualBody(BaseModel):
cliente: str
vehiculo: str
tipo: str # renta | vr | extra
monto: float
tasa_mensual: float | None = 0.0
dia_pago: int | None = None # solo para renta
fecha_vencimiento: str | None = "" # solo para vr/extra (ISO YYYY-MM-DD)
class CuentaSPEIBody(BaseModel):
id: str | None = None
beneficiario: str
banco: str
cuenta: str | None = ""
clabe: str | None = ""
incluir_en_mensaje: bool = True
class PlantillaBody(BaseModel):
saludo: str | None = None
despedida: str | None = None
incluir_vehiculo: bool | None = None
incluir_monto: bool | None = None
incluir_cliente: bool | None = None
incluir_fecha_limite: bool | None = None
incluir_link: bool | None = None
class EnviarMensajeBody(BaseModel):
id: str
texto: str
class ReenviarMensajeBody(BaseModel):
id: str
contacto: str
texto: str
class GenerarCobroBody(BaseModel):
id: str
tipo: str # "saldo" | "sinmora" | "personal"
monto: float | None = None
concepto: str | None = None
class EnviarClienteBody(BaseModel):
id: str
link: str
monto: float
concepto: str
class ReenviarContactoBody(BaseModel):
id: str
contacto: str # nombre del contacto (Paulino/Vianney/Gustavo)
link: str
monto: float
concepto: str
class LoteFila(BaseModel):
id: str
tipo: str # "saldo" | "sinmora" | "personal"
monto: float | None = None
class CobrarLoteBody(BaseModel):
concepto: str
filas: list[LoteFila]
# ── Endpoints ───────────────────────────────────────────────────
@router.get("/api/validate")
async def validate(token: str = Query(...)):
numero = await _numero_token(token)
from src.api.admin import NOMBRES_CONOCIDOS # noqa
nombre = NOMBRES_CONOCIDOS.get(numero, numero[-10:])
return {"numero": numero, "nombre": nombre, "valid": True}
@router.get("/api/renglones")
async def listar(token: str = Query(...)):
numero = await _numero_token(token)
return await cobranza_acumulada.listar(numero)
@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 "")
if not ok:
raise HTTPException(status_code=404, detail="Renglón no encontrado")
return {"ok": True}
@router.post("/api/abono")
async def abono(body: AbonoBody, token: str = Query(...)):
"""COMPAT: crea un abono ya pagado (resta del saldo de inmediato).
El flujo nuevo de "abono pendiente" se inicia desde `/api/generar-cobro`
con tipo='personal' y se confirma con `/api/abono/saldar`.
"""
numero = await _numero_token(token)
if body.monto <= 0:
raise HTTPException(status_code=400, detail="Monto debe ser > 0")
ok = await cobranza_acumulada.registrar_abono(
numero, body.id, body.monto, body.concepto or "",
)
if not ok:
raise HTTPException(status_code=404, detail="Renglón no encontrado")
return {"ok": True}
@router.post("/api/abono/saldar")
async def abono_saldar(body: AbonoIdBody, token: str = Query(...)):
"""Marca un abono pendiente como pagado y baja el saldo del renglón."""
numero = await _numero_token(token)
ok = await cobranza_acumulada.saldar_abono(
numero, body.id_renglon, body.id_abono,
)
if not ok:
raise HTTPException(status_code=404, detail="Renglón o abono no encontrado")
return {"ok": True}
@router.post("/api/abono/cancelar")
async def abono_cancelar(body: AbonoIdBody, token: str = Query(...)):
"""Elimina un abono pendiente (creado por error). No toca los pagados."""
numero = await _numero_token(token)
ok = await cobranza_acumulada.cancelar_abono(
numero, body.id_renglon, body.id_abono,
)
if not ok:
raise HTTPException(
status_code=404,
detail="Renglón o abono pendiente no encontrado",
)
return {"ok": True}
@router.put("/api/renglon")
async def editar(body: RenglonEditBody, token: str = Query(...)):
numero = await _numero_token(token)
campos = {k: v for k, v in body.model_dump().items() if k != "id" and v is not None}
ok = await cobranza_acumulada.editar_renglon(numero, body.id, campos)
if not ok:
raise HTTPException(status_code=404, detail="Renglón no encontrado")
return {"ok": True}
@router.delete("/api/renglon")
async def eliminar(body: IdBody, token: str = Query(...)):
"""Borra cualquier renglón (sheet o manual)."""
numero = await _numero_token(token)
ok = await cobranza_acumulada.eliminar_renglon(numero, body.id)
if not ok:
raise HTTPException(status_code=404, detail="Renglón no encontrado")
return {"ok": True}
@router.post("/api/renglon-manual")
async def renglon_manual_crear(body: RenglonManualBody, token: str = Query(...)):
"""Crea un renglón con origen='manual'. Sobrevive a reiniciar/acumular."""
numero = await _numero_token(token)
nuevo, err = await cobranza_acumulada.crear_renglon_manual(
numero,
cliente=body.cliente,
vehiculo=body.vehiculo,
tipo=body.tipo,
monto=body.monto,
tasa_mensual=body.tasa_mensual or 0.0,
dia_pago=body.dia_pago,
fecha_vencimiento=body.fecha_vencimiento or "",
)
if err:
status = 409 if err.lower().startswith("ya existe") else 400
raise HTTPException(status_code=status, detail=err)
return nuevo
@router.post("/api/telefono")
async def telefono(body: TelefonoBody, token: str = Query(...)):
numero = await _numero_token(token)
ok = await cobranza_acumulada.guardar_telefono(
numero, body.id, body.telefono, body.nombre or "",
)
if not ok:
raise HTTPException(status_code=400, detail="Teléfono inválido o renglón no encontrado")
return {"ok": True}
@router.post("/api/cargar-dia")
async def cargar_dia(token: str = Query(...)):
numero = await _numero_token(token)
return await cobranza_acumulada.acumular_dia(numero)
@router.post("/api/deshacer")
async def deshacer(token: str = Query(...)):
numero = await _numero_token(token)
res = await cobranza_acumulada.deshacer(numero)
if not res:
raise HTTPException(status_code=404, detail="Nada que deshacer")
return res
@router.get("/api/directorio")
async def directorio_listar(token: str = Query(...)):
"""Devuelve TODOS los clientes del Sheet con su teléfono del directorio
(vacío si aún no se registró). Para la pestaña Directorio del panel.
"""
numero = await _numero_token(token)
return {"clientes": await cobranza_acumulada.listar_directorio(numero)}
@router.post("/api/directorio")
async def directorio_guardar(body: DirectorioBody, token: str = Query(...)):
"""Guarda/actualiza/borra el teléfono de un cliente en el directorio."""
numero = await _numero_token(token)
ok = await cobranza_acumulada.guardar_telefono_directorio(
numero, body.nombre_norm, body.telefono,
)
if not ok:
raise HTTPException(
status_code=400,
detail="nombre_norm vacío o teléfono inválido (debe ser 10 dígitos o cadena vacía)",
)
return {"ok": True}
# ── Contactos manuales (no vienen del Sheet) ────────────────────
@router.post("/api/contacto-manual")
async def contacto_manual_crear(
body: ContactoManualCreateBody, token: str = Query(...),
):
numero = await _numero_token(token)
nuevo = await cobranza_acumulada.agregar_contacto_manual(
numero, body.nombre, body.telefono,
)
if nuevo is None:
raise HTTPException(
status_code=400,
detail="Nombre vacío (>100) o teléfono inválido (10 dígitos exactos)",
)
return nuevo
@router.put("/api/contacto-manual")
async def contacto_manual_editar(
body: ContactoManualEditBody, token: str = Query(...),
):
numero = await _numero_token(token)
ok = await cobranza_acumulada.editar_contacto_manual(
numero, body.id, nombre=body.nombre, telefono=body.telefono,
)
if not ok:
raise HTTPException(
status_code=400,
detail="Contacto no encontrado o datos inválidos",
)
return {"ok": True}
@router.delete("/api/contacto-manual")
async def contacto_manual_eliminar(body: IdBody, token: str = Query(...)):
numero = await _numero_token(token)
ok = await cobranza_acumulada.eliminar_contacto_manual(numero, body.id)
if not ok:
raise HTTPException(status_code=404, detail="Contacto no encontrado")
return {"ok": True}
@router.get("/api/duplicados")
async def listar_duplicados(token: str = Query(...)):
"""Devuelve los grupos de renglones que comparten identificador único."""
numero = await _numero_token(token)
return await cobranza_acumulada.detectar_duplicados(numero)
@router.post("/api/eliminar-duplicados")
async def borrar_duplicados(token: str = Query(...)):
"""Conserva el más antiguo de cada grupo y borra el resto. Deshacible."""
numero = await _numero_token(token)
return await cobranza_acumulada.eliminar_duplicados(numero)
# ── Generación de cobro Conekta y envíos ────────────────────────
def _monto_para_cobro(r: dict, tipo: str, monto_in: float | None) -> float:
"""Resuelve el monto según el tipo de cobro elegido en el panel."""
if tipo == "saldo":
return float(r.get("saldo") or 0.0)
if tipo == "sinmora":
return float(r.get("capital") or 0.0) - float(r.get("abonado") or 0.0)
if tipo == "personal":
return float(monto_in or 0.0)
raise HTTPException(status_code=400, detail=f"Tipo de cobro inválido: {tipo}")
async def _generar_cobro_para_renglon(
numero: str, renglon: dict, tipo: str,
monto_in: float | None, concepto: str | None,
) -> dict:
"""Crea el link Conekta y devuelve el resumen del cobro.
Para tipo='personal' además crea un abono PENDIENTE en el renglón y
enlaza la referencia con `id_abono`, de modo que el webhook Conekta
pueda marcarlo como pagado individualmente.
"""
monto = round(_monto_para_cobro(renglon, tipo, monto_in), 2)
if monto <= 0:
raise HTTPException(status_code=400, detail="Monto inválido")
concepto_final = (
concepto or f"Pago WK Financing - {renglon.get('cliente','')}"
)
id_abono = ""
if tipo == "personal":
nuevo = await cobranza_acumulada.crear_abono_pendiente(
numero, renglon["id"], monto, concepto_final,
)
if not nuevo:
raise HTTPException(status_code=400, detail="No se pudo registrar el abono pendiente")
id_abono = nuevo["id"]
# Referencia que el webhook Conekta interpreta.
# - 3 partes : {numero}:{id_renglon}:{tipo} (saldo|sinmora|personal-legacy)
# - 4 partes : {numero}:{id_renglon}:abono:{id_abono} (abono específico)
if tipo == "personal" and id_abono:
ref = f"{numero}:{renglon['id']}:abono:{id_abono}"
else:
ref = f"{numero}:{renglon['id']}:{tipo}"
desc = f"{concepto_final} ({renglon.get('vehiculo','')})"
res = await pagos.crear_link_cobro(
monto=monto,
descripcion=desc,
cliente_nombre=renglon.get("cliente", "Cliente"),
referencia=ref,
)
return {
"link": res.get("link"),
"id_cobro": res.get("id"),
"monto": monto,
"concepto": concepto_final,
"id_abono": id_abono, # vacío si no es personal
}
async def _buscar_renglon(numero: str, id: str) -> dict:
renglones = await cobranza_acumulada.listar(numero)
for r in renglones:
if r.get("id") == id:
return r
raise HTTPException(status_code=404, detail="Renglón no encontrado")
@router.post("/api/generar-cobro")
async def generar_cobro(body: GenerarCobroBody, token: str = Query(...)):
numero = await _numero_token(token)
r = await _buscar_renglon(numero, body.id)
try:
return await _generar_cobro_para_renglon(
numero, r, body.tipo, body.monto, body.concepto,
)
except HTTPException:
raise
except Exception:
logger.exception("Error generando cobro Conekta")
raise HTTPException(status_code=502, detail="Conekta no respondió")
@router.post("/api/enviar-cliente")
async def enviar_cliente(body: EnviarClienteBody, token: str = Query(...)):
numero = await _numero_token(token)
r = await _buscar_renglon(numero, body.id)
# `_buscar_renglon` ya devuelve renglón decorado con telefono_efectivo
# (override > directorio > "").
tel = r.get("telefono_efectivo") or r.get("telefono") or ""
if not tel:
raise HTTPException(status_code=400, detail="El renglón no tiene teléfono")
texto = _mensaje_cobro(
cliente=r.get("cliente", ""),
vehiculo=r.get("vehiculo", ""),
concepto=body.concepto,
monto=body.monto,
link=body.link,
)
ok = await whatsapp.enviar_texto(_wa_address(tel), texto, _instance())
return {"enviado": bool(ok)}
@router.post("/api/reenviar-contacto")
async def reenviar_contacto(body: ReenviarContactoBody, token: str = Query(...)):
numero = await _numero_token(token)
r = await _buscar_renglon(numero, body.id)
destino = CONTACTOS.get(body.contacto)
if not destino:
raise HTTPException(status_code=400, detail=f"Contacto desconocido: {body.contacto}")
texto = (
f"📋 Link de cobro para reenviar al cliente\n\n"
f"Cliente: {r.get('cliente','')}\n"
f"Vehículo: {r.get('vehiculo','')}\n"
f"Concepto: {body.concepto}\n"
f"Monto: ${body.monto:,.2f}\n\n"
f"{body.link}"
)
ok = await whatsapp.enviar_texto(_wa_address(destino), texto, _instance())
return {"enviado": bool(ok), "contacto": body.contacto}
@router.post("/api/cobrar-lote")
async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
numero = await _numero_token(token)
renglones = {r.get("id"): r for r in await cobranza_acumulada.listar(numero)}
enviados = 0
omitidos_sin_tel: list[str] = []
errores: list[str] = []
for fila in body.filas:
r = renglones.get(fila.id)
if not r:
errores.append(fila.id)
continue
# `listar()` ya decoró con telefono_efectivo (override > directorio).
tel_efectivo = r.get("telefono_efectivo") or ""
if not tel_efectivo:
omitidos_sin_tel.append(r.get("cliente", fila.id))
continue
try:
cobro = await _generar_cobro_para_renglon(
numero, r, fila.tipo, fila.monto, body.concepto,
)
except HTTPException as e:
logger.warning("Lote: error en %s: %s", fila.id, e.detail)
errores.append(r.get("cliente", fila.id))
continue
except Exception:
logger.exception("Lote: excepción generando cobro para %s", fila.id)
errores.append(r.get("cliente", fila.id))
continue
texto = _mensaje_cobro(
cliente=r.get("cliente", ""),
vehiculo=r.get("vehiculo", ""),
concepto=body.concepto,
monto=cobro["monto"],
link=cobro["link"],
)
ok = await whatsapp.enviar_texto(_wa_address(tel_efectivo), texto, _instance())
if ok:
enviados += 1
else:
errores.append(r.get("cliente", fila.id))
return {
"enviados": enviados,
"omitidos_sin_telefono": omitidos_sin_tel,
"errores": errores,
}
# ── Config GLOBAL (cuentas SPEI + plantilla del mensaje) ────────
@router.get("/api/config")
async def config_obtener(token: str = Query(...)):
"""Devuelve la config global (cuentas + plantilla). Mismo para todos."""
await _numero_token(token)
return await cobranza_acumulada.obtener_config_global()
@router.post("/api/config/cuenta")
async def config_cuenta_upsert(body: CuentaSPEIBody, token: str = Query(...)):
await _numero_token(token)
nuevo, err = await cobranza_acumulada.upsert_cuenta_global(body.model_dump())
if err:
raise HTTPException(status_code=400, detail=err)
return nuevo
@router.delete("/api/config/cuenta")
async def config_cuenta_eliminar(body: IdBody, token: str = Query(...)):
await _numero_token(token)
ok = await cobranza_acumulada.eliminar_cuenta_global(body.id)
if not ok:
raise HTTPException(status_code=404, detail="Cuenta no encontrada")
return {"ok": True}
@router.post("/api/config/plantilla")
async def config_plantilla_guardar(body: PlantillaBody, token: str = Query(...)):
await _numero_token(token)
return await cobranza_acumulada.guardar_plantilla_global(
body.model_dump(exclude_none=True),
)
# ── Envío genérico (mensaje pre-armado por el frontend) ─────────
@router.post("/api/enviar-mensaje-cliente")
async def enviar_mensaje_cliente(body: EnviarMensajeBody, token: str = Query(...)):
"""Envía un texto YA armado al cliente del renglón (override > directorio)."""
numero = await _numero_token(token)
r = await _buscar_renglon(numero, body.id)
tel = r.get("telefono_efectivo") or r.get("telefono") or ""
if not tel:
raise HTTPException(status_code=400, detail="El renglón no tiene teléfono")
if not (body.texto or "").strip():
raise HTTPException(status_code=400, detail="Texto vacío")
ok = await whatsapp.enviar_texto(_wa_address(tel), body.texto, _instance())
return {"enviado": bool(ok)}
@router.post("/api/reenviar-mensaje-contacto")
async def reenviar_mensaje_contacto(body: ReenviarMensajeBody, token: str = Query(...)):
"""Envía un texto YA armado al contacto seleccionado (Paulino/Vianney/Gustavo)."""
await _numero_token(token)
destino = CONTACTOS.get(body.contacto)
if not destino:
raise HTTPException(status_code=400, detail=f"Contacto desconocido: {body.contacto}")
if not (body.texto or "").strip():
raise HTTPException(status_code=400, detail="Texto vacío")
ok = await whatsapp.enviar_texto(_wa_address(destino), body.texto, _instance())
return {"enviado": bool(ok), "contacto": body.contacto}
# ── UI (HTML) ───────────────────────────────────────────────────
_HTML_PATH = Path(__file__).resolve().parents[2] / "web" / "cobranza.html"
@router.get("/ui", response_class=HTMLResponse)
async def ui(token: str = Query(...)):
"""Sirve el panel reemplazando __TOKEN__ por el token validado.
NO valida el token aquí: el HTML llama a /api/validate al cargar y
muestra la pantalla de "Acceso expirado" si está roto. Esto permite
cargar el panel aunque el token expire entre TTLs.
"""
if not _HTML_PATH.exists():
return HTMLResponse(
"<h1>Panel de cobranza no instalado</h1>",
status_code=500,
)
html = _HTML_PATH.read_text(encoding="utf-8")
return HTMLResponse(html.replace("__TOKEN__", token))
+3196
View File
File diff suppressed because it is too large. Load diff
+123
View File
@@ -0,0 +1,123 @@
"""
Webhook entrante de Conekta. NO requiere autorización: el endpoint lo
consume el dashboard de Conekta directamente.
La referencia (`metadata.referencia`) puede venir en dos formatos:
"{numero_wa_10}:{id_renglon}:{tipo}" (3 partes)
tipo ∈ {"saldo", "sinmora", "personal"}
"{numero_wa_10}:{id_renglon}:abono:{id_abono}" (4 partes)
tipo = "abono" → marca ESE abono pendiente como pagado
Cuando llega `charge.paid` o `order.paid`:
- "saldo" o "sinmora" → marca el renglón como pagado.
- "personal" → COMPAT: registra el monto como abono ya pagado.
- "abono" + id_abono → marca ESE abono específico como pagado
(el saldo del renglón baja por ese monto;
si el saldo llega a <=0.5, cierre automático).
"""
import logging
from fastapi import APIRouter, Request
logger = logging.getLogger(__name__)
router = APIRouter()
def _parse_ref(ref: str) -> tuple[str, str, str, str] | None:
"""Devuelve (numero, id_renglon, tipo, id_abono) o None.
`id_abono` es "" cuando no aplica (3 partes).
"""
if not ref or ":" not in ref:
return None
partes = ref.split(":")
if len(partes) < 3:
return None
numero = partes[0].strip()
id_renglon = partes[1].strip()
tipo = partes[2].strip().lower()
if not numero or not id_renglon:
return None
if tipo == "abono":
if len(partes) < 4 or not partes[3].strip():
return None
return numero, id_renglon, "abono", partes[3].strip()
if tipo in {"saldo", "sinmora", "personal"}:
return numero, id_renglon, tipo, ""
return None
@router.post("/webhook/conekta")
async def webhook_conekta(request: Request):
try:
payload = await request.json()
except Exception:
logger.warning("Webhook Conekta sin JSON parseable")
return {"ok": False}
evento = payload.get("type", "")
if evento not in ("charge.paid", "order.paid"):
# Otros eventos (chargeback, refund, etc.) los ignoramos por ahora.
return {"ok": True}
data_obj = (payload.get("data") or {}).get("object") or {}
metadata = data_obj.get("metadata") or {}
# Conekta puede anidar metadata adentro del order si el charge es hijo.
if not metadata:
order = data_obj.get("order") or {}
metadata = order.get("metadata") or {}
ref = metadata.get("referencia", "") or ""
monto_cent = data_obj.get("amount") or 0
monto = monto_cent / 100.0
logger.info(
"Pago confirmado Conekta: evento=%s ref=%s monto=$%.2f",
evento, ref, monto,
)
parsed = _parse_ref(ref)
if not parsed:
logger.warning("Referencia Conekta sin formato esperable: %r", ref)
return {"ok": True}
numero, id_renglon, tipo, id_abono = parsed
# Imports tardíos para evitar ciclos.
from src.services import cobranza_acumulada
try:
if tipo == "abono":
ok = await cobranza_acumulada.saldar_abono(
numero, id_renglon, id_abono,
)
logger.info(
"Abono pendiente saldado vía Conekta: %s renglón=%s abono=%s monto=$%.2f ok=%s",
numero, id_renglon, id_abono, monto, ok,
)
elif tipo == "personal":
# COMPAT con cobros generados antes del flujo nuevo (sin id_abono).
await cobranza_acumulada.registrar_abono(
numero, id_renglon, monto,
concepto="Pago Conekta",
)
logger.info(
"Abono registrado (legacy): %s renglón=%s monto=$%.2f",
numero, id_renglon, monto,
)
else:
await cobranza_acumulada.marcar_pagado(
numero, id_renglon,
nota=f"Pagado vía Conekta (${monto:,.2f})",
)
logger.info(
"Renglón saldado: %s renglón=%s monto=$%.2f tipo=%s",
numero, id_renglon, monto, tipo,
)
except Exception:
logger.exception(
"Error aplicando pago Conekta a %s renglón=%s",
numero, id_renglon,
)
return {"ok": True}