241 lines
13 KiB
HTML
241 lines
13 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
|
<title>Leads Comparador de Luz - IntegraRepara</title>
|
|
<script src="https://cdn.tailwindcss.com"></script>
|
|
<script src="https://unpkg.com/lucide@latest"></script>
|
|
<style>
|
|
:root { --primary: #2563eb; --app-bg: #f4f7f9; }
|
|
body { background: var(--app-bg); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
|
|
@keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
|
|
.fade-in { animation: fadeIn .25s ease-out; }
|
|
.badge { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; padding: 3px 9px; border-radius: 999px; display: inline-flex; align-items: center; gap: 4px; }
|
|
.tab-btn { flex: 1; text-align: center; padding: 10px 4px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .04em; border-radius: 9999px; color: #64748b; transition: all .15s; }
|
|
.tab-btn.active { background: #0f172a; color: #fff; }
|
|
.detalle { max-height: 0; overflow: hidden; transition: max-height .25s ease; }
|
|
.detalle.open { max-height: 1200px; }
|
|
</style>
|
|
</head>
|
|
<body class="min-h-screen flex flex-col">
|
|
|
|
<header class="bg-white border-b border-slate-100 px-5 py-4 flex items-center gap-3 sticky top-0 z-10">
|
|
<a href="comparador-luz.html" class="shrink-0 w-9 h-9 rounded-full bg-slate-100 flex items-center justify-center active:scale-95 transition-transform">
|
|
<i data-lucide="arrow-left" class="w-4 h-4 text-slate-700"></i>
|
|
</a>
|
|
<h1 class="font-black text-slate-800 text-lg">Leads Comparador de Luz</h1>
|
|
</header>
|
|
|
|
<main class="flex-1 overflow-y-auto p-5 fade-in">
|
|
<div class="space-y-5">
|
|
|
|
<div class="bg-white rounded-[2rem] p-2 shadow-sm border border-slate-100 flex gap-1">
|
|
<button class="tab-btn active" data-estado="todos" onclick="cambiarFiltro('todos')">Todos</button>
|
|
<button class="tab-btn" data-estado="nuevo" onclick="cambiarFiltro('nuevo')">Nuevos</button>
|
|
<button class="tab-btn" data-estado="revisado" onclick="cambiarFiltro('revisado')">Revisados</button>
|
|
<button class="tab-btn" data-estado="contactado" onclick="cambiarFiltro('contactado')">Contactados</button>
|
|
<button class="tab-btn" data-estado="descartado" onclick="cambiarFiltro('descartado')">Descartados</button>
|
|
</div>
|
|
|
|
<div id="resumen" class="grid grid-cols-3 gap-3"></div>
|
|
|
|
<div id="listaLeads" class="space-y-4"></div>
|
|
|
|
</div>
|
|
</main>
|
|
|
|
<div id="toast" class="hidden fixed bottom-6 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-xs font-bold px-5 py-3 rounded-full shadow-lg z-50"></div>
|
|
|
|
<script>
|
|
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
|
? 'http://localhost:3000'
|
|
: 'https://integrarepara-api.integrarepara.es';
|
|
const token = localStorage.getItem('token');
|
|
|
|
function authHeaders(json = false) {
|
|
const h = { Authorization: `Bearer ${token}` };
|
|
if (json) h['Content-Type'] = 'application/json';
|
|
return h;
|
|
}
|
|
|
|
function showToast(msg, isError = false) {
|
|
const t = document.getElementById('toast');
|
|
t.textContent = msg;
|
|
t.classList.remove('hidden', 'bg-slate-900', 'bg-rose-600');
|
|
t.classList.add(isError ? 'bg-rose-600' : 'bg-slate-900');
|
|
setTimeout(() => t.classList.add('hidden'), 2500);
|
|
}
|
|
|
|
function escapeHtml(str) {
|
|
if (str === null || str === undefined) return '';
|
|
return String(str).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
}
|
|
|
|
function fmtEuro(n) {
|
|
if (n === null || n === undefined || n === '') return '—';
|
|
return Number(n).toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
|
|
}
|
|
|
|
function fmtFecha(iso) {
|
|
if (!iso) return '—';
|
|
const d = new Date(iso);
|
|
return d.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric' }) + ' ' + d.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
|
|
const ESTADO_INFO = {
|
|
nuevo: { label: 'Nuevo', cls: 'bg-blue-50 text-blue-600' },
|
|
revisado: { label: 'Revisado', cls: 'bg-amber-50 text-amber-600' },
|
|
contactado: { label: 'Contactado', cls: 'bg-emerald-50 text-emerald-600' },
|
|
descartado: { label: 'Descartado', cls: 'bg-slate-100 text-slate-500' }
|
|
};
|
|
|
|
let TODOS_LEADS = [];
|
|
let filtroActual = 'todos';
|
|
|
|
async function cargarLeads() {
|
|
document.getElementById('listaLeads').innerHTML = '<p class="text-center text-xs font-bold text-slate-400 py-10">Cargando...</p>';
|
|
try {
|
|
const res = await fetch(`${API_URL}/energy-leads`, { headers: authHeaders() });
|
|
const data = await res.json();
|
|
TODOS_LEADS = data.leads || data || [];
|
|
renderResumen();
|
|
renderLista();
|
|
} catch (e) {
|
|
document.getElementById('listaLeads').innerHTML = '<p class="text-center text-xs font-bold text-rose-500 py-10">No se pudieron cargar los leads.</p>';
|
|
}
|
|
}
|
|
|
|
function renderResumen() {
|
|
const total = TODOS_LEADS.length;
|
|
const nuevos = TODOS_LEADS.filter(l => l.estado === 'nuevo').length;
|
|
const revisar = TODOS_LEADS.filter(l => l.revisar_manualmente).length;
|
|
const cont = document.getElementById('resumen');
|
|
const tile = (num, label, cls) => `
|
|
<div class="bg-white rounded-2xl p-4 shadow-sm border border-slate-100 text-center">
|
|
<p class="text-2xl font-black ${cls}">${num}</p>
|
|
<p class="text-[9px] font-bold text-slate-400 uppercase tracking-wide mt-1">${label}</p>
|
|
</div>`;
|
|
cont.innerHTML = tile(total, 'Total leads', 'text-slate-800') + tile(nuevos, 'Nuevos', 'text-blue-600') + tile(revisar, 'A revisar', 'text-amber-600');
|
|
}
|
|
|
|
function cambiarFiltro(estado) {
|
|
filtroActual = estado;
|
|
document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b.dataset.estado === estado));
|
|
renderLista();
|
|
}
|
|
|
|
function renderLista() {
|
|
const cont = document.getElementById('listaLeads');
|
|
let leads = TODOS_LEADS;
|
|
if (filtroActual !== 'todos') leads = leads.filter(l => l.estado === filtroActual);
|
|
leads = [...leads].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
|
|
|
if (leads.length === 0) {
|
|
cont.innerHTML = '<p class="text-center text-xs font-bold text-slate-400 py-10">Sin leads en esta categoría.</p>';
|
|
return;
|
|
}
|
|
|
|
cont.innerHTML = leads.map(l => renderCard(l)).join('');
|
|
lucide.createIcons();
|
|
}
|
|
|
|
function renderCard(l) {
|
|
const ei = ESTADO_INFO[l.estado] || ESTADO_INFO.nuevo;
|
|
const mejor = (l.comparativa_json || [])[0] || null;
|
|
const fj = l.factura_json || {};
|
|
|
|
const comparativaRows = (l.comparativa_json || []).slice(0, 6).map((c, i) => `
|
|
<div class="flex items-center justify-between py-1.5 ${i === 0 ? 'font-bold text-emerald-700' : 'text-slate-600'}">
|
|
<span class="text-xs">${i === 0 ? '🏆 ' : ''}${escapeHtml(c.nombre)}</span>
|
|
<span class="text-xs">${fmtEuro(c.total)} <span class="text-[10px] text-slate-400">(${c.ahorroFactura >= 0 ? '+' : ''}${c.ahorroFactura}€)</span></span>
|
|
</div>`).join('') || '<p class="text-xs text-slate-400">Sin tarifas comparadas.</p>';
|
|
|
|
const facturaRows = [
|
|
['Comercializadora', fj.comercializadora], ['Tarifa acceso', fj.tarifa_acceso],
|
|
['Días facturados', fj.dias_facturados], ['Potencia P1 / P2 (kW)', `${fj.potencia_p1_kw ?? '—'} / ${fj.potencia_p2_kw ?? '—'}`],
|
|
['Consumo punta/llano/valle (kWh)', `${fj.kwh_punta ?? '—'} / ${fj.kwh_llano ?? '—'} / ${fj.kwh_valle ?? '—'}`],
|
|
['Precio energía punta/llano/valle (€/kWh)', `${fj.precio_energia_punta ?? '—'} / ${fj.precio_energia_llano ?? '—'} / ${fj.precio_energia_valle ?? '—'}`],
|
|
['Descuento', `${fj.descuento_pct ?? 0}% (${fj.descuento_aplica_a || '—'})`],
|
|
['Permanencia', `${fj.permanencia || '—'}${fj.permanencia_fecha_fin ? ' hasta ' + fj.permanencia_fecha_fin : ''}`]
|
|
].map(([k, v]) => `<div class="flex justify-between gap-3 py-1 border-b border-slate-50 last:border-0"><span class="text-[11px] text-slate-400">${k}</span><span class="text-[11px] font-semibold text-slate-700 text-right">${escapeHtml(v)}</span></div>`).join('');
|
|
|
|
return `
|
|
<div class="bg-white rounded-[2rem] p-5 shadow-sm border border-slate-100">
|
|
<div class="flex items-start justify-between gap-2">
|
|
<div>
|
|
<p class="font-black text-slate-800 text-sm">${escapeHtml(l.email)}</p>
|
|
<p class="text-xs text-slate-400 font-medium mt-0.5">${escapeHtml(l.telefono)}${l.codigo_postal ? ' · CP ' + escapeHtml(l.codigo_postal) : ''}</p>
|
|
<p class="text-[10px] text-slate-300 font-semibold mt-1">${fmtFecha(l.created_at)}</p>
|
|
</div>
|
|
<span class="badge ${ei.cls} shrink-0">${ei.label}</span>
|
|
</div>
|
|
|
|
${l.revisar_manualmente ? `
|
|
<div class="mt-3 bg-amber-50 border border-amber-100 rounded-xl px-3 py-2 flex items-center gap-2">
|
|
<i data-lucide="alert-triangle" class="w-3.5 h-3.5 text-amber-500 shrink-0"></i>
|
|
<p class="text-[11px] font-bold text-amber-700">Revisar manualmente — factura real ${fmtEuro(l.total_real)} vs recálculo ${fmtEuro(l.total_recalculado)} (dif. ${l.diferencia ?? '—'}€)</p>
|
|
</div>` : `
|
|
<div class="mt-3 bg-emerald-50 border border-emerald-100 rounded-xl px-3 py-2 flex items-center gap-2">
|
|
<i data-lucide="check-circle-2" class="w-3.5 h-3.5 text-emerald-500 shrink-0"></i>
|
|
<p class="text-[11px] font-bold text-emerald-700">${mejor ? `Mejor tarifa: ${escapeHtml(mejor.nombre)} — ahorro ${mejor.ahorroFactura}€/factura, ${mejor.ahorroAnual}€/año` : 'Sin tarifas activas para comparar.'}</p>
|
|
</div>`}
|
|
|
|
<button onclick="toggleDetalle(${l.id})" class="mt-3 text-[11px] font-bold text-blue-600 flex items-center gap-1">
|
|
<span id="detToggleLabel-${l.id}">Ver detalle de la factura y comparativa</span>
|
|
<i data-lucide="chevron-down" class="w-3.5 h-3.5" id="detToggleIcon-${l.id}"></i>
|
|
</button>
|
|
|
|
<div class="detalle" id="detalle-${l.id}">
|
|
<div class="mt-3 bg-slate-50 rounded-xl p-3">
|
|
<p class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Datos extraídos de la factura</p>
|
|
${facturaRows}
|
|
</div>
|
|
<div class="mt-3 bg-slate-50 rounded-xl p-3">
|
|
<p class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Comparativa de tarifas</p>
|
|
${comparativaRows}
|
|
</div>
|
|
</div>
|
|
|
|
<div class="mt-4 flex gap-2 flex-wrap">
|
|
${l.estado !== 'revisado' ? `<button onclick="cambiarEstado(${l.id}, 'revisado')" class="flex-1 min-w-[90px] bg-amber-50 text-amber-700 text-[11px] font-bold py-2 rounded-xl active:scale-95 transition-transform">Marcar revisado</button>` : ''}
|
|
${l.estado !== 'contactado' ? `<button onclick="cambiarEstado(${l.id}, 'contactado')" class="flex-1 min-w-[90px] bg-emerald-50 text-emerald-700 text-[11px] font-bold py-2 rounded-xl active:scale-95 transition-transform">Marcar contactado</button>` : ''}
|
|
${l.estado !== 'descartado' ? `<button onclick="cambiarEstado(${l.id}, 'descartado')" class="flex-1 min-w-[90px] bg-slate-100 text-slate-500 text-[11px] font-bold py-2 rounded-xl active:scale-95 transition-transform">Descartar</button>` : ''}
|
|
<a href="https://wa.me/34${escapeHtml((l.telefono || '').replace(/\D/g, ''))}" target="_blank" rel="noopener" class="flex-1 min-w-[90px] bg-blue-600 text-white text-[11px] font-bold py-2 rounded-xl text-center active:scale-95 transition-transform flex items-center justify-center gap-1">
|
|
<i data-lucide="message-circle" class="w-3.5 h-3.5"></i> WhatsApp
|
|
</a>
|
|
</div>
|
|
</div>`;
|
|
}
|
|
|
|
function toggleDetalle(id) {
|
|
const el = document.getElementById(`detalle-${id}`);
|
|
const icon = document.getElementById(`detToggleIcon-${id}`);
|
|
const label = document.getElementById(`detToggleLabel-${id}`);
|
|
const open = el.classList.toggle('open');
|
|
icon.style.transform = open ? 'rotate(180deg)' : 'rotate(0deg)';
|
|
label.textContent = open ? 'Ocultar detalle' : 'Ver detalle de la factura y comparativa';
|
|
}
|
|
|
|
async function cambiarEstado(id, estado) {
|
|
try {
|
|
const res = await fetch(`${API_URL}/energy-leads/${id}`, { method: 'PATCH', headers: authHeaders(true), body: JSON.stringify({ estado }) });
|
|
if (!res.ok) throw new Error();
|
|
const lead = TODOS_LEADS.find(l => l.id === id);
|
|
if (lead) lead.estado = estado;
|
|
showToast('Estado actualizado');
|
|
renderResumen();
|
|
renderLista();
|
|
} catch (e) {
|
|
showToast('No se pudo actualizar el estado', true);
|
|
}
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
lucide.createIcons();
|
|
cargarLeads();
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|