Files
web/servicios.html
2026-02-17 21:32:39 +00:00

631 lines
41 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panel de Servicios - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.no-scrollbar::-webkit-scrollbar { display: none; }
.card-hover:hover { transform: translateY(-2px); transition: all 0.2s; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05); }
/* ANIMACIÓN DE TEMBLOR (SHAKE) PARA TARJETAS BLOQUEADAS */
.shake { animation: shake 0.4s cubic-bezier(.36,.07,.19,.97) both; }
@keyframes shake {
10%, 90% { transform: translate3d(-2px, 0, 0); }
20%, 80% { transform: translate3d(4px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-6px, 0, 0); }
40%, 60% { transform: translate3d(6px, 0, 0); }
}
</style>
</head>
<body class="bg-slate-50 text-slate-800 font-sans antialiased text-left">
<div class="flex h-screen overflow-hidden">
<div id="sidebar-container" class="h-full shrink-0"></div>
<div class="flex-1 flex flex-col overflow-hidden relative">
<div id="header-container"></div>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-slate-50 p-6 no-scrollbar text-left relative">
<div class="fade-in max-w-full mx-auto space-y-6">
<div class="flex justify-between items-center bg-white p-6 rounded-[2rem] shadow-sm border border-slate-100">
<div>
<h2 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-3">
<span class="bg-blue-600 p-2.5 rounded-xl text-white shadow-lg shadow-blue-200"><i data-lucide="kanban"></i></span>
PANEL OPERATIVO
</h2>
<p class="text-sm text-slate-500 mt-1 font-medium">Tablero Kanban de gestión de expedientes.</p>
</div>
<button onclick="openCreateModal()" class="bg-slate-900 hover:bg-blue-600 text-white px-6 py-3.5 rounded-2xl shadow-xl flex items-center gap-3 font-black text-xs uppercase tracking-widest transition-all active:scale-95">
<i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio
</button>
</div>
<div class="flex flex-wrap gap-4 items-center bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 mb-6">
<div class="relative flex-1 min-w-[250px]">
<i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
<input type="text" id="searchFilter" oninput="renderLists()" placeholder="Buscar por cliente, REF, población, teléfono..." class="w-full pl-11 pr-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold focus:ring-2 focus:ring-blue-500 outline-none transition-all">
</div>
<div class="relative w-full md:w-64">
<select id="opFilter" onchange="renderLists()" class="w-full bg-slate-50 border border-slate-200 text-xs font-black px-4 py-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 uppercase tracking-widest text-slate-600 appearance-none pr-10 cursor-pointer">
<option value="ALL">TODOS LOS OPERARIOS</option>
</select>
<i data-lucide="chevron-down" class="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
<div class="space-y-4 bg-slate-100/50 p-4 rounded-[2rem] border border-slate-200/60">
<div class="flex items-center gap-2 px-2 pb-2 border-b border-slate-200">
<div class="w-2.5 h-2.5 rounded-full bg-rose-500 shadow-[0_0_10px_rgba(244,63,94,0.5)]"></div>
<h3 class="font-black text-slate-600 uppercase text-[10px] tracking-widest">Sin Asignar / En Pausa</h3>
</div>
<div id="unassigned-list" class="space-y-3"></div>
</div>
<div class="space-y-4 bg-slate-100/50 p-4 rounded-[2rem] border border-slate-200/60">
<div class="flex items-center gap-2 px-2 pb-2 border-b border-slate-200">
<div class="w-2.5 h-2.5 rounded-full bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)]"></div>
<h3 class="font-black text-slate-600 uppercase text-[10px] tracking-widest">Asignados (Falta Fecha)</h3>
</div>
<div id="pending-list" class="space-y-3"></div>
</div>
<div class="space-y-4 bg-slate-100/50 p-4 rounded-[2rem] border border-slate-200/60">
<div class="flex items-center gap-2 px-2 pb-2 border-b border-slate-200">
<div class="w-2.5 h-2.5 rounded-full bg-emerald-500 shadow-[0_0_10px_rgba(16,185,129,0.5)]"></div>
<h3 class="font-black text-slate-600 uppercase text-[10px] tracking-widest">Citados / En Curso</h3>
</div>
<div id="assigned-list" class="space-y-3"></div>
</div>
</div>
</div>
</main>
</div>
</div>
<div id="createModal" class="fixed inset-0 bg-slate-900/80 hidden z-[100] flex items-center justify-center backdrop-blur-sm p-4 text-left">
<div class="bg-white rounded-[2.5rem] shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col fade-in">
<div class="p-8 border-b flex justify-between items-center bg-slate-50">
<h3 class="font-black text-slate-800 uppercase tracking-tighter text-xl">Alta de Expediente Manual</h3>
<button onclick="closeCreateModal()" class="text-slate-400 hover:text-red-500 transition-colors"><i data-lucide="x"></i></button>
</div>
<form onsubmit="saveNewService(event)" class="p-8 overflow-y-auto no-scrollbar grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-4">
<div class="bg-blue-50/50 p-6 rounded-3xl border border-blue-100 space-y-4">
<h4 class="font-black text-blue-400 uppercase text-[10px] tracking-widest">Información del Cliente</h4>
<input type="tel" id="nPhone" placeholder="Teléfono" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
<input type="text" id="nName" placeholder="Nombre completo" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
<input type="text" id="nAddr" placeholder="Dirección completa" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
</div>
<textarea id="nDesc" placeholder="Descripción de la avería..." rows="4" class="w-full bg-slate-50 border-none px-4 py-3 rounded-3xl text-sm font-medium outline-none"></textarea>
</div>
<div class="space-y-6">
<select id="nGuild" class="w-full bg-slate-100 p-4 rounded-2xl font-bold outline-none" onchange="loadOps(this.value, 'nWorker')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-6 rounded-[2rem] text-white space-y-4">
<button type="submit" name="action" value="auto" class="w-full bg-blue-600 hover:bg-blue-500 p-4 rounded-2xl flex items-center justify-between text-left transition-all">
<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[10px] text-blue-200">WhatsApp Automático</p></div>
<i data-lucide="zap" class="w-6 h-6"></i>
</button>
<div class="bg-slate-800 p-4 rounded-2xl space-y-3">
<p class="font-black uppercase text-[10px] text-slate-500 text-center">Asignar a Mano:</p>
<select id="nWorker" class="w-full bg-slate-700 border-none text-white px-3 py-2 rounded-xl text-sm outline-none">
<option value="">-- Primero elija gremio --</option>
</select>
<button type="submit" name="action" value="manual" class="w-full bg-white text-slate-900 font-black py-3 rounded-xl text-xs uppercase hover:bg-emerald-400 transition-colors">Confirmar Directo</button>
</div>
</div>
</div>
</form>
</div>
</div>
<div id="detailModal" class="fixed inset-0 bg-slate-900/90 hidden z-[120] flex items-center justify-center backdrop-blur-sm p-4 text-left">
<div class="bg-white rounded-[2rem] shadow-2xl w-full max-w-4xl overflow-hidden flex flex-col fade-in relative">
<button onclick="closeDetailModal()" class="absolute top-6 right-6 text-slate-400 hover:text-red-500 bg-white shadow-sm border border-slate-200 p-2.5 rounded-full transition-all hover:bg-red-50 hover:border-red-100 z-10"><i data-lucide="x" class="w-5 h-5"></i></button>
<div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50 pr-24">
<div class="flex items-center gap-3">
<div class="bg-blue-100 p-2.5 rounded-xl text-blue-600 shadow-inner"><i data-lucide="folder-open" class="w-5 h-5"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Expediente Oficial</p>
<h3 class="font-black text-slate-800 text-xl leading-none tracking-tight">#<span id="detRef"></span></h3>
</div>
</div>
<div class="flex flex-col items-end text-right">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Compañía Aseguradora</p>
<span id="detCompany" class="bg-white border border-slate-200 px-3 py-1 rounded-lg text-xs font-black text-slate-700 mt-1 uppercase shadow-sm truncate max-w-[250px]"></span>
</div>
</div>
<div class="p-6 grid grid-cols-1 md:grid-cols-5 gap-6 bg-white overflow-y-auto max-h-[80vh] no-scrollbar">
<input type="hidden" id="detId">
<input type="hidden" id="detCp">
<div class="md:col-span-3 space-y-4">
<div class="bg-slate-50 p-5 rounded-[1.5rem] border border-slate-100 space-y-4">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Asegurado / Cliente</p>
<p id="detName" class="font-black text-slate-800 text-lg uppercase mt-0.5 leading-tight"></p>
<a href="#" id="detPhoneLink" class="text-sm text-blue-600 font-black flex items-center gap-1.5 mt-1.5 hover:underline w-max">
<i data-lucide="phone" class="w-3.5 h-3.5"></i> <span id="detPhone"></span>
</a>
</div>
<hr class="border-slate-200">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Ubicación y Dirección</p>
<p class="text-sm font-bold text-slate-600 mt-1 flex items-start gap-1.5 leading-snug">
<i data-lucide="map-pin" class="w-4 h-4 mt-0.5 text-slate-400 shrink-0"></i>
<span id="detAddrText" class="uppercase"></span>
</p>
</div>
</div>
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2 ml-2">Descripción de la Avería</p>
<div class="bg-amber-50/60 border border-amber-100 p-5 rounded-[1.5rem] text-sm font-medium text-slate-700 min-h-[120px] max-h-48 overflow-y-auto no-scrollbar shadow-inner leading-relaxed" id="detDesc"></div>
</div>
</div>
<div class="md:col-span-2 flex flex-col gap-4">
<div id="panelAsignado" class="bg-blue-50/40 p-6 rounded-[1.5rem] border border-blue-100 flex flex-col justify-between shadow-sm h-full hidden">
<div class="space-y-6">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Operario Asignado</p>
<div class="flex items-center gap-3 bg-white p-3 rounded-2xl border border-slate-100 shadow-sm">
<div class="bg-emerald-100 w-10 h-10 rounded-full flex items-center justify-center text-emerald-600 shrink-0"><i data-lucide="hard-hat" class="w-5 h-5"></i></div>
<p id="detWorker" class="font-black text-slate-700 text-xs uppercase leading-tight"></p>
</div>
</div>
<div class="space-y-3">
<p class="text-[10px] font-black text-blue-600 uppercase tracking-widest flex items-center gap-1.5 border-b border-blue-100 pb-2"><i data-lucide="calendar-clock" class="w-4 h-4"></i> Agendar Cita</p>
<div class="grid grid-cols-2 gap-2">
<input type="date" id="dateInput" class="w-full bg-white border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
<input type="time" id="timeInput" class="w-full bg-white border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
</div>
</div>
<div class="space-y-2 pt-2">
<p class="text-[10px] font-black text-slate-800 uppercase ml-1 flex items-center gap-1.5"><i data-lucide="arrow-right-left" class="w-4 h-4 text-blue-500"></i> Cambio de Estado</p>
<div class="relative">
<select id="detStatusMap" class="w-full bg-slate-800 text-white border-none p-4 rounded-xl text-xs font-bold shadow-lg outline-none cursor-pointer appearance-none pr-10">
<option value="sin_asignar">🔴 SIN ASIGNAR / EN PAUSA</option>
<option value="citado">📅 CITADO (Visita programada)</option>
<option value="de_camino">🚗 DE CAMINO AL DOMICILIO</option>
<option value="trabajando">🛠️ TRABAJANDO EN EL LUGAR</option>
<option value="incidencia">⚠️ CON INCIDENCIA / PAUSADO</option>
<option value="terminado">✅ TRABAJO TERMINADO</option>
</select>
<i data-lucide="chevron-down" class="w-4 h-4 text-slate-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
</div>
<button id="btnSaveAppt" onclick="saveAppointment()" class="w-full mt-8 bg-blue-600 text-white font-black py-4 rounded-2xl text-xs uppercase tracking-widest shadow-[0_8px_20px_-6px_rgba(37,99,235,0.5)] hover:bg-blue-700 hover:shadow-blue-600/30 transition-all active:scale-95 flex items-center justify-center gap-2 border border-blue-500">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios
</button>
</div>
<div id="panelSinAsignar" class="bg-rose-50/40 p-6 rounded-[1.5rem] border border-rose-100 flex flex-col shadow-sm h-full hidden">
<div class="flex items-center gap-2 mb-6">
<div class="w-2.5 h-2.5 rounded-full bg-rose-500 animate-pulse"></div>
<p class="text-[10px] font-black text-rose-600 uppercase tracking-widest">Pendiente de Asignar</p>
</div>
<div class="space-y-5 flex-1">
<select id="reGremio" class="w-full bg-white border border-rose-200 p-4 rounded-2xl text-xs font-bold text-slate-700 outline-none" onchange="loadOps(this.value, 'reOperario')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-5 rounded-2xl text-white space-y-4">
<button onclick="sendToAutomate()" id="btnAuto" class="w-full bg-blue-600 hover:bg-blue-500 p-3 rounded-xl flex items-center justify-between text-left transition-all active:scale-95">
<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[9px] text-blue-200">Rueda automática (WA)</p></div>
<i data-lucide="zap" class="w-5 h-5"></i>
</button>
<div class="bg-slate-800 p-4 rounded-xl space-y-3">
<p class="font-black uppercase text-[9px] text-slate-400 text-center">O Asignar a Mano:</p>
<select id="reOperario" class="w-full bg-slate-700 border-none text-white px-3 py-2.5 rounded-lg text-xs font-bold outline-none">
<option value="">-- Elija gremio primero --</option>
</select>
<button onclick="assignManualFromPanel()" class="w-full bg-white text-slate-900 font-black py-2.5 rounded-lg text-[10px] uppercase hover:bg-emerald-400 transition-colors">Confirmar Directo</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="toastAppt" class="fixed bottom-8 right-8 bg-emerald-600 text-white px-6 py-4 rounded-2xl shadow-2xl hidden z-[200] font-bold text-sm flex items-center gap-3 transition-colors duration-300">
<span id="toastIconContainer"><i data-lucide="check-circle" class="w-5 h-5"></i></span>
<span id="toastMsg">Guardado correctamente</span>
</div>
<script src="js/layout.js"></script>
<script>
let localData = [];
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
refreshPanel();
loadGuilds();
setInterval(refreshPanel, 20000);
});
async function refreshPanel() {
try {
const res = await fetch(`${API_URL}/services/active`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
localData = data.services;
updateOperatorFilter();
renderLists();
}
} catch (e) { console.error(e); }
}
function updateOperatorFilter() {
const opSelect = document.getElementById('opFilter');
const currentValue = opSelect.value;
const uniqueOps = [...new Set(localData.map(s => s.assigned_name).filter(Boolean))].sort();
let html = '<option value="ALL">TODOS LOS OPERARIOS</option>';
uniqueOps.forEach(op => { html += `<option value="${op}">${op}</option>`; });
opSelect.innerHTML = html;
if (html.includes(`value="${currentValue}"`)) opSelect.value = currentValue;
}
function renderLists() {
const searchTerm = document.getElementById('searchFilter').value.toLowerCase();
const selectedOp = document.getElementById('opFilter').value;
const filteredData = localData.filter(s => {
const raw = s.raw_data;
const name = (raw["Nombre Cliente"] || raw["CLIENTE"] || "").toLowerCase();
const addr = (raw["Dirección"] || raw["DOMICILIO"] || "").toLowerCase();
const pop = (raw["Población"] || raw["POBLACION-PROVINCIA"] || "").toLowerCase();
const phone = (raw["Teléfono"] || raw["TELEFONO"] || "").toLowerCase();
const ref = (s.service_ref || "").toLowerCase();
const assigned = s.assigned_name || "";
const matchesSearch = searchTerm === "" || name.includes(searchTerm) || ref.includes(searchTerm) || addr.includes(searchTerm) || pop.includes(searchTerm) || phone.includes(searchTerm);
const matchesOp = selectedOp === "ALL" || assigned === selectedOp;
return matchesSearch && matchesOp;
});
const unassigned = filteredData.filter(s => !s.assigned_name || s.raw_data.status_operativo === 'sin_asignar');
const pending = filteredData.filter(s => s.assigned_name && (!s.raw_data.scheduled_date || s.raw_data.scheduled_date === "") && s.raw_data.status_operativo !== 'sin_asignar');
const assigned = filteredData.filter(s => s.raw_data.scheduled_date && s.raw_data.scheduled_date !== "" && s.raw_data.status_operativo !== 'sin_asignar');
document.getElementById('unassigned-list').innerHTML = unassigned.length > 0
? unassigned.map(s => {
let color = 'rose';
let label = s.assigned_name ? 'Pausado' : 'Sin Asignar';
// COLORES INTELIGENTES PARA LA BOLSA DE TRABAJO
if (!s.assigned_name) {
if (s.automation_status === 'in_progress') { color = 'amber'; label = 'Buscando (WA)'; }
if (s.automation_status === 'failed') { color = 'orange'; label = 'En Bolsa'; }
}
return cardTemplate(s, color, label);
}).join('')
: '<p class="text-center py-10 text-slate-300 text-xs font-bold uppercase border-2 border-dashed border-slate-200/50 rounded-[1.5rem]">Vacío</p>';
document.getElementById('pending-list').innerHTML = pending.length > 0
? pending.map(s => cardTemplate(s, 'blue', 'Falta Fecha')).join('')
: '<p class="text-center py-10 text-slate-300 text-xs font-bold uppercase border-2 border-dashed border-slate-200/50 rounded-[1.5rem]">Vacío</p>';
document.getElementById('assigned-list').innerHTML = assigned.length > 0
? assigned.map(s => {
let color = 'emerald';
let label = 'Citado';
if(s.raw_data.status_operativo === 'de_camino') { color = 'blue'; label = 'De Camino'; }
if(s.raw_data.status_operativo === 'trabajando') { color = 'amber'; label = 'Trabajando'; }
if(s.raw_data.status_operativo === 'incidencia') { color = 'red'; label = 'Incidencia'; }
if(s.raw_data.status_operativo === 'terminado') { color = 'purple'; label = 'Terminado'; }
return cardTemplate(s, color, label);
}).join('')
: '<p class="text-center py-10 text-slate-300 text-xs font-bold uppercase border-2 border-dashed border-slate-200/50 rounded-[1.5rem]">Vacío</p>';
lucide.createIcons();
}
function cardTemplate(s, color, label) {
const raw = s.raw_data || {};
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
const addr = raw["Dirección"] || raw["DOMICILIO"] || "---";
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
const fullAddr = `${addr} ${pop}`.trim();
const phone = raw["Teléfono"] || raw["TELEFONO"] || raw["TELEFONOS"] || "";
// Extraer solo números para el enlace de llamada
const cleanPhone = phone.toString().replace(/\D/g, '');
const cita = raw.scheduled_date ? `${raw.scheduled_date} | ${raw.scheduled_time}` : 'Pendiente Cita';
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || (s.provider === 'MANUAL' ? 'PARTICULAR' : 'ASEGURADORA');
let iconEstado = 'calendar';
if(raw.status_operativo === 'de_camino') iconEstado = 'car';
if(raw.status_operativo === 'trabajando') iconEstado = 'wrench';
if(raw.status_operativo === 'incidencia') iconEstado = 'alert-triangle';
if(raw.status_operativo === 'terminado') iconEstado = 'check-circle';
// DICCIONARIO DE COLORES BLINDADO PARA TAILWIND JIT
const colorClasses = {
'rose': 'bg-rose-100 text-rose-600',
'blue': 'bg-blue-100 text-blue-600',
'emerald': 'bg-emerald-100 text-emerald-600',
'amber': 'bg-amber-100 text-amber-600',
'orange': 'bg-orange-100 text-orange-600',
'red': 'bg-red-100 text-red-600',
'purple': 'bg-purple-100 text-purple-600'
};
const badgeClass = colorClasses[color] || 'bg-slate-100 text-slate-600';
// LÓGICA DE BLOQUEO (No se puede abrir si está buscando o en bolsa, a menos que ya tenga operario y sea pausa)
const isBlocked = !s.assigned_name && (s.automation_status === 'in_progress' || s.automation_status === 'failed');
const clickAction = isBlocked ? `shakeCard(this, '${s.automation_status}'); event.stopPropagation();` : `openDetail(${s.id})`;
const cursorStyle = isBlocked ? 'cursor-not-allowed' : 'cursor-pointer';
// Renderizado de la Tarjeta Mejorada
return `
<div class="bg-white p-4 rounded-3xl border border-slate-200 shadow-sm card-hover text-left flex flex-col gap-3 relative ${cursorStyle}" onclick="${clickAction}">
<div class="flex items-center justify-between w-full">
<span class="text-[9px] font-black ${badgeClass} px-2.5 py-1 rounded-lg uppercase tracking-wider shadow-sm flex items-center gap-1.5">
${isBlocked ? '<span class="w-1.5 h-1.5 bg-current rounded-full pulse-slow opacity-70"></span>' : ''}
${label}
</span>
<span class="text-[9px] text-slate-400 font-bold uppercase bg-slate-50 border border-slate-100 px-2 py-1 rounded-lg">#${s.service_ref}</span>
</div>
<div>
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-0.5">${companyName}</p>
<h4 class="font-black text-slate-800 uppercase text-sm leading-tight line-clamp-1" title="${name}">${name}</h4>
</div>
<div class="space-y-1.5 bg-slate-50/50 p-2.5 rounded-xl border border-slate-100">
<p class="text-[10px] text-slate-600 font-medium uppercase line-clamp-1 flex items-center gap-1.5" title="${fullAddr}">
<i data-lucide="map-pin" class="w-3 h-3 text-slate-400 shrink-0"></i> ${fullAddr}
</p>
${phone ? `
<div class="flex items-center justify-between">
<p class="text-[10px] font-black text-slate-700 flex items-center gap-1.5">
<i data-lucide="phone" class="w-3 h-3 text-slate-400"></i> ${phone}
</p>
${cleanPhone ? `<a href="tel:${cleanPhone}" onclick="event.stopPropagation();" class="bg-emerald-50 text-emerald-600 p-1.5 rounded-lg hover:bg-emerald-500 hover:text-white transition-colors shadow-sm" title="Llamar al cliente"><i data-lucide="phone-call" class="w-3.5 h-3.5"></i></a>` : ''}
</div>
` : '<p class="text-[10px] italic text-slate-400">Sin teléfono</p>'}
</div>
<div class="flex items-center justify-between mt-1 pt-3 border-t border-slate-100">
<div class="flex items-center gap-1.5 min-w-0">
<div class="bg-slate-100 p-1 rounded-md text-slate-500 shrink-0"><i data-lucide="hard-hat" class="w-3 h-3"></i></div>
<span class="text-[9px] font-black text-slate-600 uppercase truncate" title="${s.assigned_name || 'Sin asignar'}">${s.assigned_name || 'Sin asignar'}</span>
</div>
${raw.scheduled_date && !isBlocked ? `
<div class="flex items-center gap-1.5 text-blue-600 shrink-0 ml-2">
<i data-lucide="${iconEstado}" class="w-3 h-3"></i>
<span class="text-[9px] font-black uppercase">${cita}</span>
</div>` : ''}
</div>
</div>`;
}
// FUNCIÓN QUE HACE TEMBLAR LA TARJETA
function shakeCard(element, status) {
element.classList.add('shake');
setTimeout(() => element.classList.remove('shake'), 400);
if (status === 'in_progress') {
showToast("⏳ El robot está asignando este servicio por WhatsApp...", "warning");
} else {
showToast("📍 Este servicio está en la bolsa esperando a que un operario lo coja.", "warning");
}
}
function showToast(msg, type = 'success') {
const toast = document.getElementById('toastAppt');
const iconContainer = document.getElementById('toastIconContainer');
document.getElementById('toastMsg').innerText = msg;
if (type === 'warning') {
toast.classList.replace('bg-emerald-600', 'bg-amber-500');
iconContainer.innerHTML = '<i data-lucide="alert-circle" class="w-5 h-5"></i>';
} else {
toast.classList.replace('bg-amber-500', 'bg-emerald-600');
iconContainer.innerHTML = '<i data-lucide="check-circle" class="w-5 h-5"></i>';
}
lucide.createIcons();
toast.classList.remove('hidden');
setTimeout(() => { toast.classList.add('hidden'); }, 3500);
}
function openDetail(id) {
const s = localData.find(x => x.id === id);
if (!s) return;
const raw = s.raw_data;
document.getElementById('detId').value = s.id;
document.getElementById('detRef').innerText = s.service_ref;
document.getElementById('detCp').value = raw["Código Postal"] || "00000";
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "Particular";
document.getElementById('detCompany').innerText = companyName;
document.getElementById('detName').innerText = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
const phone = raw["Teléfono"] || raw["TELEFONO"] || "Sin Teléfono";
document.getElementById('detPhone').innerText = phone;
document.getElementById('detPhoneLink').href = phone.replace(/\D/g,'') ? `tel:${phone.replace(/\D/g,'')}` : "#";
document.getElementById('detAddrText').innerText = `${raw["Dirección"] || "Dirección no especificada"} ${raw["Población"] || ""}`;
document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.").replace(/\n/g, '<br>');
if (s.assigned_name && raw.status_operativo !== 'sin_asignar') {
document.getElementById('panelAsignado').classList.remove('hidden');
document.getElementById('panelSinAsignar').classList.add('hidden');
document.getElementById('detWorker').innerText = s.assigned_name;
document.getElementById('dateInput').value = raw.scheduled_date || "";
document.getElementById('timeInput').value = raw.scheduled_time || "";
document.getElementById('detStatusMap').value = raw.status_operativo || 'citado';
} else {
document.getElementById('panelAsignado').classList.add('hidden');
document.getElementById('panelSinAsignar').classList.remove('hidden');
if(raw.guild_id) {
document.getElementById('reGremio').value = raw.guild_id;
loadOps(raw.guild_id, 'reOperario');
} else {
document.getElementById('reGremio').value = "";
document.getElementById('reOperario').innerHTML = '<option value="">-- Elija gremio primero --</option>';
}
}
document.getElementById('detailModal').classList.remove('hidden');
lucide.createIcons();
}
async function saveAppointment() {
const id = document.getElementById('detId').value;
const date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
const statusMap = document.getElementById('detStatusMap').value;
if (statusMap !== 'sin_asignar' && !date && statusMap !== 'incidencia' && statusMap !== 'terminado') {
if(!confirm("No has asignado Fecha. ¿Deseas continuar?")) return;
}
const btn = document.getElementById('btnSaveAppt');
const originalContent = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...`;
btn.disabled = true;
try {
if(statusMap === 'sin_asignar') {
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_operativo: statusMap, assigned_to: null, assigned_to_name: null })
});
} else {
await fetch(`${API_URL}/services/set-appointment/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ date, time, status_operativo: statusMap })
});
}
closeDetailModal(); showToast("Estado actualizado"); refreshPanel();
} catch (e) { alert("Error"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; }
}
async function sendToAutomate() {
const id = document.getElementById('detId').value;
const guild_id = document.getElementById('reGremio').value;
const cp = document.getElementById('detCp').value;
if(!guild_id) return alert("Selecciona un gremio primero.");
const btn = document.getElementById('btnAuto');
btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin mx-auto"></i>';
// Leemos si el usuario tiene activado el retraso (es true por defecto)
const savedSetting = localStorage.getItem('wa_delay_enabled');
const useDelay = savedSetting === null ? true : savedSetting === 'true';
try {
const res = await fetch(`${API_URL}/providers/automate/${id}`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
// Añadimos useDelay al payload que va al servidor
body: JSON.stringify({ guild_id, cp, useDelay })
});
const data = await res.json();
if(data.ok) { closeDetailModal(); showToast("Enviado a la rueda de WhatsApp"); refreshPanel(); }
else { alert(data.error || "No hay operarios en esa zona para ese gremio"); btn.innerHTML = '<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[9px] text-blue-200">Rueda automática (WA)</p></div><i data-lucide="zap" class="w-5 h-5"></i>'; lucide.createIcons(); }
} catch (e) { alert("Error"); }
}
async function assignManualFromPanel() {
const id = document.getElementById('detId').value;
const guild_id = document.getElementById('reGremio').value;
const assigned_to = document.getElementById('reOperario').value;
if(!guild_id || !assigned_to) return alert("Selecciona gremio y operario.");
try {
const select = document.getElementById('reOperario');
const name = select.options[select.selectedIndex].text;
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({
automation_status: 'completed',
assigned_to: assigned_to,
assigned_name: name,
guild_id: guild_id,
status_operativo: 'asignado_operario'
})
});
closeDetailModal(); showToast("Asignado correctamente"); refreshPanel();
} catch (e) { alert("Error"); }
}
async function saveNewService(e) {
e.preventDefault();
const action = e.submitter.value;
const data = {
phone: document.getElementById('nPhone').value, name: document.getElementById('nName').value,
address: document.getElementById('nAddr').value, description: document.getElementById('nDesc').value,
guild_id: document.getElementById('nGuild').value, assigned_to: document.getElementById('nWorker').value || null
};
try {
const res = await fetch(`${API_URL}/services/manual-high`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ ...data, mode: action })
});
if (res.ok) { closeCreateModal(); refreshPanel(); }
} catch(e) { alert("Error al guardar"); }
}
function closeDetailModal() { document.getElementById('detailModal').classList.add('hidden'); }
function openCreateModal() { document.getElementById('createModal').classList.remove('hidden'); }
function closeCreateModal() { document.getElementById('createModal').classList.add('hidden'); }
async function loadGuilds() {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
const opts = '<option value="">Seleccionar Gremio...</option>' + data.guilds.map(g => `<option value="${g.id}">${g.name}</option>`).join('');
document.getElementById('nGuild').innerHTML = opts;
document.getElementById('reGremio').innerHTML = opts;
}
}
async function loadOps(gid, targetSelectId) {
const sel = document.getElementById(targetSelectId);
if(!gid) { sel.innerHTML = '<option value="">-- Primero elija gremio --</option>'; return; }
const res = await fetch(`${API_URL}/operators?guild_id=${gid}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) sel.innerHTML = '<option value="">Seleccionar operario...</option>' + data.operators.map(o => `<option value="${o.id}">${o.full_name}</option>`).join('');
}
</script>
</body>
</html>