Files
wk-bot/src/api/admin_ui.py
T

659 lines
22 KiB
Python

"""
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>"""