10 Commits

6 changed files with 782 additions and 9 deletions

View File

@@ -122,7 +122,7 @@
<input type="hidden" id="detId"> <input type="hidden" id="detId">
<input type="hidden" id="detPhoneRaw"> <input type="hidden" id="detPhoneRaw">
<div id="phoneSelectorRow" class="hidden flex items-center gap-2 mb-3 overflow-x-auto no-scrollbar"></div> <div id="phoneSelectorRow" class="hidden flex items-center gap-2 mb-3 overflow-x-auto no-scrollbar"></div>
<div class="grid grid-cols-2 gap-3 mb-6"> <div class="grid grid-cols-3 gap-3 mb-6">
<button onclick="callClient()" class="bg-blue-50 border border-blue-100 text-blue-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm"> <button onclick="callClient()" class="bg-blue-50 border border-blue-100 text-blue-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm">
<i data-lucide="phone" class="w-5 h-5"></i> <i data-lucide="phone" class="w-5 h-5"></i>
<span class="text-[10px] uppercase tracking-widest">Llamar</span> <span class="text-[10px] uppercase tracking-widest">Llamar</span>
@@ -131,6 +131,10 @@
<i data-lucide="message-circle" class="w-5 h-5"></i> <i data-lucide="message-circle" class="w-5 h-5"></i>
<span class="text-[10px] uppercase tracking-widest">WhatsApp</span> <span class="text-[10px] uppercase tracking-widest">WhatsApp</span>
</button> </button>
<button onclick="sendInstagramPromo()" class="bg-pink-50 border border-pink-100 text-pink-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm">
<i data-lucide="instagram" class="w-5 h-5"></i>
<span class="text-[10px] uppercase tracking-widest">Instagram</span>
</button>
</div> </div>
<hr class="border-slate-100 mb-6"> <hr class="border-slate-100 mb-6">
<div class="bg-white border border-slate-200 rounded-[1.5rem] p-5 shadow-sm space-y-5"> <div class="bg-white border border-slate-200 rounded-[1.5rem] p-5 shadow-sm space-y-5">
@@ -496,12 +500,11 @@
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ duration: duration, date: date, time: time }) body: JSON.stringify({ duration: duration, date: date, time: time })
}); });
const data = await res.json().catch(() => ({})); if (res.ok) {
if (res.ok && data.ok !== false) {
showToast("Cita Aceptada"); showToast("Cita Aceptada");
closeModal('approveModal', 'approveModalContent'); closeModal('approveModal', 'approveModalContent');
refreshData(); refreshData();
} else { alert(data.error || "Error al confirmar."); } } else { alert("Error al confirmar."); }
} catch (e) { alert("Error de conexión"); } } catch (e) { alert("Error de conexión"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); } finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
} }
@@ -960,6 +963,22 @@ function renderServices(servicesToRender = localServices) {
if (phone) window.open(`https://wa.me/34${phone}`, '_blank'); if (phone) window.open(`https://wa.me/34${phone}`, '_blank');
else alert("No hay un teléfono válido guardado."); else alert("No hay un teléfono válido guardado.");
} }
async function sendInstagramPromo() {
const id = document.getElementById('detId').value;
if (!id) return;
try {
const res = await fetch(`${API_URL}/services/${id}/send-instagram`, {
method: 'POST',
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) alert("¡Mensaje de Instagram enviado! 📸");
else alert(data.error || "No se pudo enviar el mensaje de Instagram.");
} catch (e) {
alert("Error de conexión al enviar el mensaje de Instagram.");
}
}
// 📞 Cuando el servicio trae más de un teléfono (típico de HomeServe), pintamos un // 📞 Cuando el servicio trae más de un teléfono (típico de HomeServe), pintamos un
// selector de chips para que el operario elija cuál usar antes de Llamar/WhatsApp. // selector de chips para que el operario elija cuál usar antes de Llamar/WhatsApp.
// Con un solo teléfono no mostramos nada (para no añadir ruido visual de más). // Con un solo teléfono no mostramos nada (para no añadir ruido visual de más).

View File

@@ -180,6 +180,9 @@
<button onclick="openWhatsApp()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center"> <button onclick="openWhatsApp()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="message-circle" class="w-4 h-4 text-emerald-500"></i> WhatsApp <i data-lucide="message-circle" class="w-4 h-4 text-emerald-500"></i> WhatsApp
</button> </button>
<button onclick="sendInstagramPromo()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="instagram" class="w-4 h-4 text-pink-500"></i> Instagram
</button>
<button onclick="abrirFichaCliente()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center"> <button onclick="abrirFichaCliente()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="user-round" class="w-4 h-4 text-primary-dynamic"></i> Ficha del Cliente <i data-lucide="user-round" class="w-4 h-4 text-primary-dynamic"></i> Ficha del Cliente
</button> </button>
@@ -1507,6 +1510,22 @@
} else { alert("Sin teléfono"); } } else { alert("Sin teléfono"); }
} }
async function sendInstagramPromo() {
const id = document.getElementById('detId').value;
if (!id) return;
try {
const res = await fetch(`${API_URL}/services/${id}/send-instagram`, {
method: 'POST',
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) alert("¡Mensaje de Instagram enviado! 📸");
else alert(data.error || "No se pudo enviar el mensaje de Instagram.");
} catch (e) {
alert("Error de conexión al enviar el mensaje de Instagram.");
}
}
// 🧑‍🔧 Abre la ficha del cliente (historial de servicios + notas del equipo) con los // 🧑‍🔧 Abre la ficha del cliente (historial de servicios + notas del equipo) con los
// datos que ya tenemos cargados en el modal, para no tener que volver a pedirlos. // datos que ya tenemos cargados en el modal, para no tener que volver a pedirlos.
function abrirFichaCliente() { function abrirFichaCliente() {

406
comparador-luz.html Normal file
View File

@@ -0,0 +1,406 @@
<!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, viewport-fit=cover">
<title>Comparador de Luz - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<script src="js/layout.js"></script>
<style>
:root { --primary: #2563eb; --app-bg: #f4f7f9; }
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
.fade-in { animation: fadeIn 0.4s ease-out forwards; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
/* Estilo Toggle Pro */
.toggle-dot { transition: all 0.3s ease-in-out; }
input:checked ~ .toggle-bg { background-color: #10b981; }
input:checked ~ .toggle-dot { transform: translateX(1.5rem); }
</style>
</head>
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative text-left">
<header class="bg-white px-5 pt-safe mt-6 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-200">
<div class="flex items-center gap-3 justify-between">
<div class="flex items-center gap-3">
<a href="configuracion.html" class="w-10 h-10 shrink-0 bg-slate-50 rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:scale-95 transition-transform">
<i data-lucide="arrow-left" class="w-5 h-5"></i>
</a>
<h1 class="text-xl font-black tracking-tight text-slate-900">Comparador de Luz</h1>
</div>
<a href="leads-luz.html" class="flex items-center gap-1.5 bg-slate-900 text-white text-[11px] font-bold px-3 py-2 rounded-full active:scale-95 transition-transform">
<i data-lucide="users" class="w-3.5 h-3.5"></i> Leads
</a>
</div>
</header>
<main class="flex-1 overflow-y-auto p-5 fade-in">
<div class="space-y-6">
<!-- AJUSTES + WHATSAPP -->
<div class="bg-white rounded-[2.5rem] p-6 shadow-sm border border-slate-100">
<div class="flex items-center gap-3 mb-6">
<div class="bg-emerald-100 p-2 rounded-xl text-emerald-600"><i data-lucide="message-circle" class="w-5 h-5"></i></div>
<h3 class="font-black text-slate-800 uppercase text-xs tracking-widest">Aviso por WhatsApp</h3>
</div>
<div class="space-y-4">
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">WhatsApp para avisos de nuevos leads</label>
<input type="tel" id="adminWhatsapp" placeholder="+34600000000" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800 placeholder:text-slate-300 placeholder:font-medium focus:outline-none focus:border-blue-300">
<p class="text-[9px] font-medium text-slate-400 mt-1.5 ml-1 uppercase">Recibirás un WhatsApp cada vez que un cliente suba su factura en marsalva.es</p>
</div>
</div>
</div>
<!-- AJUSTES DE CALCULO -->
<div class="bg-white rounded-[2.5rem] p-6 shadow-sm border border-slate-100">
<div class="flex items-center gap-3 mb-6">
<div class="bg-blue-100 p-2 rounded-xl text-blue-600"><i data-lucide="sliders-horizontal" class="w-5 h-5"></i></div>
<h3 class="font-black text-slate-800 uppercase text-xs tracking-widest">Ajustes del Cálculo</h3>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">IEE %</label>
<input type="number" step="0.0001" id="ieePct" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800 focus:outline-none focus:border-blue-300">
</div>
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">IVA %</label>
<input type="number" step="0.01" id="ivaPct" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800 focus:outline-none focus:border-blue-300">
</div>
</div>
<div class="mt-3">
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Modelo de IA (opcional)</label>
<input type="text" id="openaiModel" placeholder="gpt-4o-mini" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800 placeholder:text-slate-300 placeholder:font-medium focus:outline-none focus:border-blue-300">
</div>
<div class="flex items-center justify-between p-4 mt-4 bg-slate-50 rounded-2xl border border-slate-100">
<div class="flex-1 pr-4">
<p class="font-black text-sm text-slate-800 leading-tight">Comparar con el mercado (CNMC)</p>
<p class="text-[10px] font-medium text-slate-400 mt-1 uppercase">Añade ofertas oficiales como dato informativo</p>
</div>
<label class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" id="toggleCNMC" class="sr-only">
<div class="toggle-bg block bg-slate-300 w-12 h-6 rounded-full transition-colors"></div>
<div class="toggle-dot absolute left-1 top-1 bg-white w-4 h-4 rounded-full shadow transition-transform"></div>
</div>
</label>
</div>
<button onclick="guardarSettings()" class="w-full mt-5 bg-slate-900 text-white font-black py-4 rounded-2xl text-xs uppercase tracking-widest active:scale-[0.98] transition-transform flex items-center justify-center gap-2">
<i data-lucide="save" class="w-4 h-4"></i> Guardar ajustes
</button>
</div>
<!-- TARIFAS -->
<div class="bg-white rounded-[2.5rem] p-6 shadow-sm border border-slate-100">
<div class="flex items-center justify-between mb-6">
<div class="flex items-center gap-3">
<div class="bg-amber-100 p-2 rounded-xl text-amber-600"><i data-lucide="zap" class="w-5 h-5"></i></div>
<h3 class="font-black text-slate-800 uppercase text-xs tracking-widest">Tarifas</h3>
</div>
<button onclick="abrirModal()" class="w-9 h-9 flex items-center justify-center bg-slate-900 text-white rounded-full active:scale-95 transition-transform">
<i data-lucide="plus" class="w-5 h-5"></i>
</button>
</div>
<div class="flex items-center gap-1 bg-slate-100 p-1 rounded-2xl mb-4">
<button id="tab-propia" onclick="cambiarTab('propia')" class="flex-1 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest bg-white shadow-sm text-slate-900">Propias</button>
<button id="tab-repsol" onclick="cambiarTab('repsol')" class="flex-1 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-400">Repsol</button>
<button id="tab-mercado" onclick="cambiarTab('mercado')" class="flex-1 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-400">Mercado</button>
</div>
<div id="listaTarifas" class="space-y-2">
<p class="text-center text-slate-400 text-xs font-bold uppercase py-8">Cargando...</p>
</div>
</div>
</div>
</main>
<!-- MODAL TARIFA -->
<div id="modalTarifa" class="hidden fixed inset-0 bg-black/40 z-50 flex items-end justify-center">
<div class="bg-white w-full max-w-lg rounded-t-[2.5rem] p-6 max-h-[90vh] overflow-y-auto">
<div class="flex items-center justify-between mb-5">
<h3 id="modalTitulo" class="font-black text-lg text-slate-900">Nueva tarifa</h3>
<button onclick="cerrarModal()" class="w-9 h-9 flex items-center justify-center bg-slate-50 rounded-full border border-slate-200 text-slate-500"><i data-lucide="x" class="w-5 h-5"></i></button>
</div>
<div class="space-y-3">
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Tipo</label>
<select id="f_tipo" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800">
<option value="propia">Propia</option>
<option value="repsol">Repsol</option>
<option value="mercado">Mercado</option>
</select>
</div>
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Nombre *</label>
<input type="text" id="f_nombre" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800">
</div>
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Comercializadora</label>
<input type="text" id="f_comercializadora" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800">
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Precio Potencia P1 (€/kW·día)</label>
<input type="number" step="0.000001" id="f_p1" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800">
</div>
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Precio Potencia P2 (€/kW·día)</label>
<input type="number" step="0.000001" id="f_p2" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-slate-800">
</div>
</div>
<div class="grid grid-cols-3 gap-2">
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">€/kWh Punta</label>
<input type="number" step="0.000001" id="f_punta" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">€/kWh Llano</label>
<input type="number" step="0.000001" id="f_llano" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">€/kWh Valle</label>
<input type="number" step="0.000001" id="f_valle" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
</div>
<div class="grid grid-cols-3 gap-2">
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">Descuento %</label>
<input type="number" step="0.01" id="f_descuento" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">Bono Social €/día</label>
<input type="number" step="0.000001" id="f_bonosocial" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
<div>
<label class="text-[9px] font-bold text-slate-400 uppercase ml-1">Alq. contador €/día</label>
<input type="number" step="0.000001" id="f_alquiler" class="w-full mt-1 p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs font-bold text-slate-800">
</div>
</div>
<div>
<label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Notas</label>
<textarea id="f_notas" rows="2" class="w-full mt-1 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-medium text-slate-800"></textarea>
</div>
<div class="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-slate-100">
<p class="font-black text-sm text-slate-800">Tarifa activa</p>
<label class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" id="f_activa" class="sr-only">
<div class="toggle-bg block bg-slate-300 w-12 h-6 rounded-full transition-colors"></div>
<div class="toggle-dot absolute left-1 top-1 bg-white w-4 h-4 rounded-full shadow transition-transform"></div>
</div>
</label>
</div>
<button onclick="guardarTarifa()" class="w-full mt-2 bg-blue-600 text-white font-black py-4 rounded-2xl text-xs uppercase tracking-widest active:scale-[0.98] transition-transform">
Guardar tarifa
</button>
</div>
</div>
</div>
<div id="toast" class="fixed top-5 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-xs font-bold px-4 py-2.5 rounded-full shadow-lg z-50 transition-opacity" style="opacity:0;"></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');
let tarifas = [];
let currentTab = 'propia';
let editingId = null;
function authHeaders(json = true) {
const h = { "Authorization": `Bearer ${token}` };
if (json) h["Content-Type"] = "application/json";
return h;
}
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
toast.textContent = msg;
toast.className = `fixed top-5 left-1/2 -translate-x-1/2 ${isError ? 'bg-rose-600' : 'bg-slate-900'} text-white text-xs font-bold px-4 py-2.5 rounded-full shadow-lg z-50 transition-opacity`;
toast.style.opacity = '1';
setTimeout(() => { toast.style.opacity = '0'; }, 2500);
}
async function cargarSettings() {
try {
const res = await fetch(`${API_URL}/energy-settings`, { headers: authHeaders(false) });
const data = await res.json();
const s = (data.ok && data.settings) ? data.settings : {};
document.getElementById('ieePct').value = s.iee_pct ?? 5.1126963;
document.getElementById('ivaPct').value = s.iva_pct ?? 21;
document.getElementById('openaiModel').value = s.openai_model || '';
document.getElementById('adminWhatsapp').value = s.admin_whatsapp || '';
document.getElementById('toggleCNMC').checked = s.cnmc_enabled !== false;
} catch (e) {
showToast('No se pudieron cargar los ajustes', true);
}
}
async function guardarSettings() {
const body = {
ieePct: parseFloat(document.getElementById('ieePct').value) || 5.1126963,
ivaPct: parseFloat(document.getElementById('ivaPct').value) || 21,
openaiModel: document.getElementById('openaiModel').value.trim() || null,
cnmcEnabled: document.getElementById('toggleCNMC').checked,
adminWhatsapp: document.getElementById('adminWhatsapp').value.trim() || null,
};
try {
const res = await fetch(`${API_URL}/energy-settings`, { method: 'PUT', headers: authHeaders(), body: JSON.stringify(body) });
const data = await res.json();
if (data.ok) showToast('Ajustes guardados'); else showToast('Error al guardar', true);
} catch (e) {
showToast('Error de conexión', true);
}
}
async function cargarTarifas() {
try {
const res = await fetch(`${API_URL}/energy-tariffs`, { headers: authHeaders(false) });
const data = await res.json();
tarifas = data.ok ? data.tarifas : [];
} catch (e) {
tarifas = [];
}
renderTarifas();
}
function renderTarifas() {
const list = tarifas.filter(t => t.tipo === currentTab);
const cont = document.getElementById('listaTarifas');
if (!list.length) {
cont.innerHTML = `<p class="text-center text-slate-400 text-xs font-bold uppercase py-8">Sin tarifas en esta categoría</p>`;
return;
}
cont.innerHTML = list.map(t => `
<div class="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-slate-100">
<div class="flex-1 pr-3">
<p class="font-black text-sm text-slate-800">${escapeHtml(t.nombre)} ${t.activa === false ? '<span class="text-[9px] font-bold text-rose-500 uppercase ml-1">(inactiva)</span>' : ''}</p>
<p class="text-[10px] font-medium text-slate-400 mt-0.5 uppercase">${escapeHtml(t.comercializadora || '')} · Desc. ${Number(t.descuento_pct)}%</p>
</div>
<div class="flex items-center gap-2 shrink-0">
<button onclick="abrirModal(${t.id})" class="w-8 h-8 flex items-center justify-center bg-white rounded-full border border-slate-200 text-slate-500 active:scale-95"><i data-lucide="pencil" class="w-4 h-4"></i></button>
<button onclick="borrarTarifa(${t.id})" class="w-8 h-8 flex items-center justify-center bg-white rounded-full border border-slate-200 text-rose-500 active:scale-95"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
</div>
</div>
`).join('');
lucide.createIcons();
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
function cambiarTab(tipo) {
currentTab = tipo;
['propia', 'repsol', 'mercado'].forEach(t => {
const btn = document.getElementById('tab-' + t);
if (t === tipo) btn.className = 'flex-1 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest bg-white shadow-sm text-slate-900';
else btn.className = 'flex-1 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-400';
});
renderTarifas();
}
function abrirModal(id = null) {
editingId = id;
const t = id ? tarifas.find(x => x.id === id) : null;
document.getElementById('modalTitulo').textContent = id ? 'Editar tarifa' : 'Nueva tarifa';
document.getElementById('f_tipo').value = t ? t.tipo : currentTab;
document.getElementById('f_nombre').value = t ? t.nombre : '';
document.getElementById('f_comercializadora').value = t ? (t.comercializadora || '') : '';
document.getElementById('f_p1').value = t ? t.precio_potencia_p1 : 0;
document.getElementById('f_p2').value = t ? t.precio_potencia_p2 : 0;
document.getElementById('f_punta').value = t ? t.precio_energia_punta : 0;
document.getElementById('f_llano').value = t ? t.precio_energia_llano : 0;
document.getElementById('f_valle').value = t ? t.precio_energia_valle : 0;
document.getElementById('f_descuento').value = t ? t.descuento_pct : 0;
document.getElementById('f_bonosocial').value = t ? t.bono_social_dia : 0;
document.getElementById('f_alquiler').value = t ? t.alquiler_contador_dia : 0;
document.getElementById('f_notas').value = t ? (t.notas || '') : '';
document.getElementById('f_activa').checked = t ? t.activa !== false : true;
document.getElementById('modalTarifa').classList.remove('hidden');
lucide.createIcons();
}
function cerrarModal() {
document.getElementById('modalTarifa').classList.add('hidden');
}
async function guardarTarifa() {
const body = {
tipo: document.getElementById('f_tipo').value,
nombre: document.getElementById('f_nombre').value.trim(),
comercializadora: document.getElementById('f_comercializadora').value.trim() || null,
precioPotenciaP1: parseFloat(document.getElementById('f_p1').value) || 0,
precioPotenciaP2: parseFloat(document.getElementById('f_p2').value) || 0,
precioEnergiaPunta: parseFloat(document.getElementById('f_punta').value) || 0,
precioEnergiaLlano: parseFloat(document.getElementById('f_llano').value) || 0,
precioEnergiaValle: parseFloat(document.getElementById('f_valle').value) || 0,
descuentoPct: parseFloat(document.getElementById('f_descuento').value) || 0,
bonoSocialDia: parseFloat(document.getElementById('f_bonosocial').value) || 0,
alquilerContadorDia: parseFloat(document.getElementById('f_alquiler').value) || 0,
notas: document.getElementById('f_notas').value.trim() || null,
activa: document.getElementById('f_activa').checked,
};
if (!body.nombre) { showToast('El nombre es obligatorio', true); return; }
try {
const url = editingId ? `${API_URL}/energy-tariffs/${editingId}` : `${API_URL}/energy-tariffs`;
const method = editingId ? 'PUT' : 'POST';
const res = await fetch(url, { method, headers: authHeaders(), body: JSON.stringify(body) });
const data = await res.json();
if (data.ok) {
showToast('Tarifa guardada');
cerrarModal();
cargarTarifas();
} else {
showToast('Error al guardar', true);
}
} catch (e) {
showToast('Error de conexión', true);
}
}
async function borrarTarifa(id) {
if (!confirm('¿Eliminar esta tarifa?')) return;
try {
const res = await fetch(`${API_URL}/energy-tariffs/${id}`, { method: 'DELETE', headers: authHeaders(false) });
const data = await res.json();
if (data.ok) {
showToast('Tarifa eliminada');
cargarTarifas();
} else {
showToast('Error al eliminar', true);
}
} catch (e) {
showToast('Error de conexión', true);
}
}
document.addEventListener('DOMContentLoaded', () => {
lucide.createIcons();
if (!token) {
showToast('Sesión no válida', true);
return;
}
cargarSettings();
cargarTarifas();
});
</script>
</body>
</html>

View File

@@ -6,7 +6,7 @@
<title>Configuración - IntegraRepara</title> <title>Configuración - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script> <script src="https://unpkg.com/lucide@latest"></script>
<script src="js/layout.js"></script> <script src="js/layout.js"></script>
<style> <style>
:root { --primary: #2563eb; --app-bg: #f4f7f9; } :root { --primary: #2563eb; --app-bg: #f4f7f9; }
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; } body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
@@ -59,20 +59,86 @@
<div class="flex items-center gap-2 text-[9px] font-bold text-slate-400 uppercase"><i data-lucide="check" class="w-3 h-3 text-emerald-500"></i> Finalización de servicios</div> <div class="flex items-center gap-2 text-[9px] font-bold text-slate-400 uppercase"><i data-lucide="check" class="w-3 h-3 text-emerald-500"></i> Finalización de servicios</div>
</div> </div>
</div> </div>
<div class="bg-white rounded-[2.5rem] p-6 shadow-sm border border-slate-100">
<div class="flex items-center gap-3 mb-4">
<div class="bg-pink-100 p-2 rounded-xl text-pink-600"><i data-lucide="instagram" class="w-5 h-5"></i></div>
<h3 class="font-black text-slate-800 uppercase text-xs tracking-widest">Mensaje de Instagram</h3>
</div>
<p class="text-[10px] font-medium text-slate-400 uppercase mb-3">Se envía por WhatsApp al pulsar "Enviar Instagram" en un servicio</p>
<textarea id="instaMsg" rows="5" class="w-full bg-slate-50 border border-slate-200 p-4 rounded-xl text-sm font-medium text-slate-700 shadow-inner outline-none focus:ring-2 focus:ring-pink-500 transition-all"></textarea>
<div class="flex items-center gap-2 mt-3">
<button onclick="saveInstagramMessage()" class="flex-1 bg-pink-500 text-white font-black py-3 rounded-xl uppercase text-[10px] tracking-widest active:scale-95 transition-transform">Guardar</button>
<button onclick="restoreDefaultInstagramMessage()" class="bg-slate-100 text-slate-500 font-black py-3 px-4 rounded-xl uppercase text-[10px] tracking-widest active:scale-95 transition-transform">Restaurar</button>
</div>
</div>
<a href="comparador-luz.html" class="block bg-white rounded-[2.5rem] p-6 shadow-sm border border-slate-100 active:scale-[0.98] transition-transform">
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="bg-amber-100 p-2 rounded-xl text-amber-600"><i data-lucide="zap" class="w-5 h-5"></i></div>
<div>
<h3 class="font-black text-slate-800 uppercase text-xs tracking-widest">Comparador de Luz</h3>
<p class="text-[10px] font-medium text-slate-400 mt-1 uppercase">Tarifas, Repsol y aviso por WhatsApp</p>
</div>
</div>
<i data-lucide="chevron-right" class="w-5 h-5 text-slate-300"></i>
</div>
</a>
</div> </div>
</main> </main>
<script> <script>
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? 'http://localhost:3000'
: 'https://integrarepara-api.integrarepara.es';
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
lucide.createIcons(); lucide.createIcons();
const isAuto = localStorage.getItem("auto_homeserve") === "true"; const isAuto = localStorage.getItem("auto_homeserve") === "true";
document.getElementById('toggleHS').checked = isAuto; document.getElementById('toggleHS').checked = isAuto;
loadInstagramMessage();
}); });
function saveConfig() { function saveConfig() {
const isChecked = document.getElementById('toggleHS').checked; const isChecked = document.getElementById('toggleHS').checked;
localStorage.setItem("auto_homeserve", isChecked); localStorage.setItem("auto_homeserve", isChecked);
} }
async function loadInstagramMessage() {
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
document.getElementById('instaMsg').value = data.instagram_promo_message || data.default_instagram_promo_message || '';
}
} catch (e) { /* si falla, se deja vacío y el usuario puede escribir el suyo */ }
}
async function saveInstagramMessage() {
const mensaje = document.getElementById('instaMsg').value;
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ instagram_promo_message: mensaje })
});
const data = await res.json();
if (data.ok) alert("¡Mensaje guardado!"); else alert("No se pudo guardar.");
} catch (e) { alert("Error de conexión al guardar."); }
}
async function restoreDefaultInstagramMessage() {
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) document.getElementById('instaMsg').value = data.default_instagram_promo_message || '';
} catch (e) { alert("Error de conexión."); }
}
</script> </script>
</body> </body>
</html> </html>

BIN
img/repsol-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

263
leads-luz.html Normal file
View File

@@ -0,0 +1,263 @@
<!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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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>
${l.pdf_enviado ? `<p class="text-[10px] text-blue-500 font-semibold mt-0.5">PDF enviado el ${fmtFecha(l.pdf_enviado_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>` : ''}
${l.pdf_enviado ? `<button id="btnPdf-${l.id}" onclick="enviarPdf(${l.id})" class="flex-1 min-w-[120px] bg-slate-100 text-slate-500 text-[11px] font-bold py-2 rounded-xl active:scale-95 transition-transform flex items-center justify-center gap-1"><i data-lucide="file-check-2" class="w-3.5 h-3.5"></i> Reenviar PDF</button>` : `<button id="btnPdf-${l.id}" onclick="enviarPdf(${l.id})" class="flex-1 min-w-[120px] bg-blue-600 text-white text-[11px] font-bold py-2 rounded-xl active:scale-95 transition-transform flex items-center justify-center gap-1"><i data-lucide="file-text" class="w-3.5 h-3.5"></i> Enviar PDF</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);
}
}
async function enviarPdf(id) {
const btn = document.getElementById(`btnPdf-${id}`);
const original = btn ? btn.innerHTML : null;
if (btn) {
btn.disabled = true;
btn.innerHTML = '<span class="text-[11px]">Enviando...</span>';
}
try {
const res = await fetch(`${API_URL}/energy-leads/${id}/send-pdf`, { method: 'POST', headers: authHeaders() });
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.ok) throw new Error(data.detail || 'Error');
const lead = TODOS_LEADS.find(l => l.id === id);
if (lead) { lead.pdf_enviado = true; lead.pdf_enviado_at = new Date().toISOString(); }
showToast('PDF enviado por WhatsApp');
renderLista();
} catch (e) {
showToast(e.message || 'No se pudo enviar el PDF', true);
if (btn && original) { btn.disabled = false; btn.innerHTML = original; }
}
}
document.addEventListener('DOMContentLoaded', () => {
lucide.createIcons();
cargarLeads();
});
</script>
</body>
</html>