759 lines
48 KiB
HTML
759 lines
48 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); } }
|
|
|
|
/* Ocultar barra de scroll pero mantener funcionalidad */
|
|
.no-scrollbar::-webkit-scrollbar { display: none; }
|
|
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
|
|
|
|
/* Scroll horizontal bonito para el Kanban */
|
|
.kanban-board {
|
|
display: flex;
|
|
overflow-x: auto;
|
|
scroll-snap-type: x mandatory;
|
|
gap: 1.5rem;
|
|
padding-bottom: 1rem;
|
|
}
|
|
.kanban-board::-webkit-scrollbar { height: 8px; }
|
|
.kanban-board::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
|
|
.kanban-board::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
|
|
.kanban-board::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
|
|
|
|
.kanban-column {
|
|
min-width: 320px;
|
|
max-width: 320px;
|
|
scroll-snap-align: start;
|
|
}
|
|
|
|
.card-hover { transition: all 0.2s ease; cursor: pointer; }
|
|
.card-hover:hover { transform: translateY(-3px); box-shadow: 0 12px 25px -5px rgba(0, 0, 0, 0.1); border-color: #93c5fd; }
|
|
|
|
.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); }
|
|
}
|
|
.pulse-slow { animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
|
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
|
|
</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-hidden flex flex-col bg-slate-50 p-6 relative">
|
|
|
|
<div class="flex justify-between items-center bg-white p-6 rounded-[2rem] shadow-sm border border-slate-100 shrink-0 mb-6">
|
|
<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 activos.</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 shrink-0">
|
|
<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="renderBoard()" placeholder="Buscar por cliente, REF, población, teléfono, compañía..." 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="flex gap-3 w-full md:w-auto">
|
|
<div class="relative min-w-[200px]">
|
|
<select id="opFilter" onchange="renderBoard()" 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 class="relative min-w-[200px]">
|
|
<select id="statusFilter" onchange="renderBoard()" 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 ESTADOS</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>
|
|
|
|
<div id="kanbanBoard" class="kanban-board flex-1">
|
|
</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>
|
|
|
|
<div class="flex items-center gap-4 mt-1.5">
|
|
<a href="#" id="detPhoneLink" class="text-sm text-blue-600 font-black flex items-center gap-1.5 hover:underline w-max">
|
|
<i data-lucide="phone" class="w-3.5 h-3.5"></i> <span id="detPhone"></span>
|
|
</a>
|
|
<button onclick="copyClientPortalLink()" id="btnPortalLink" class="text-[10px] font-black bg-blue-50 border border-blue-100 hover:bg-blue-600 hover:text-white text-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1.5 transition-all shadow-sm active:scale-95">
|
|
<i data-lucide="link" class="w-3 h-3"></i> Copiar Portal Cliente
|
|
</button>
|
|
</div>
|
|
</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">
|
|
</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 = [];
|
|
let systemStatuses = []; // Guardará todos los estados de la DB
|
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
if (!localStorage.getItem("token")) window.location.href = "index.html";
|
|
loadInitialData();
|
|
setInterval(refreshPanelOnly, 20000);
|
|
});
|
|
|
|
async function loadInitialData() {
|
|
await loadStatuses();
|
|
await loadGuilds();
|
|
await refreshPanelOnly();
|
|
}
|
|
|
|
// NUEVO: Cargar los estados reales desde la DB
|
|
async function loadStatuses() {
|
|
try {
|
|
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
|
const data = await res.json();
|
|
if (data.ok) {
|
|
systemStatuses = data.statuses;
|
|
|
|
// Rellenar filtro superior
|
|
const filterSelect = document.getElementById('statusFilter');
|
|
filterSelect.innerHTML = '<option value="ALL">TODOS LOS ESTADOS</option>';
|
|
systemStatuses.forEach(st => {
|
|
// Omitimos los finales (Terminado/Anulado) por defecto en el panel operativo para no saturarlo,
|
|
// pero los dejamos en el filtro para que se puedan buscar
|
|
filterSelect.innerHTML += `<option value="${st.id}">${st.name}</option>`;
|
|
});
|
|
|
|
// Rellenar selector del modal de detalles
|
|
const modalSelect = document.getElementById('detStatusMap');
|
|
modalSelect.innerHTML = '';
|
|
systemStatuses.forEach(st => {
|
|
modalSelect.innerHTML += `<option value="${st.id}">👉 ${st.name}</option>`;
|
|
});
|
|
}
|
|
} catch (e) { console.error("Error cargando estados:", e); }
|
|
}
|
|
|
|
async function refreshPanelOnly() {
|
|
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();
|
|
renderBoard();
|
|
}
|
|
} 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;
|
|
}
|
|
|
|
// ==========================================
|
|
// 🚀 NUEVO RENDERIZADOR DE KANBAN DINÁMICO
|
|
// ==========================================
|
|
function renderBoard() {
|
|
if(systemStatuses.length === 0) return; // Si no hay estados cargados, no hace nada
|
|
|
|
const searchTerm = document.getElementById('searchFilter').value.toLowerCase();
|
|
const selectedOp = document.getElementById('opFilter').value;
|
|
const selectedStatus = document.getElementById('statusFilter').value;
|
|
|
|
// Filtro Global
|
|
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 comp = (raw["Compañía"] || raw["COMPAÑIA"] || raw["Procedencia"] || "").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 || "";
|
|
|
|
// Mapeo inverso: El backend antiguo de "scraped" guarda textos como 'citado'.
|
|
// Ahora debemos casarlos con los IDs reales de systemStatuses.
|
|
// Para no romper la DB existente, buscamos por ID o por coincidencia de nombre.
|
|
let currentStatusId = "ALL";
|
|
const dbStatusText = s.raw_data.status_operativo;
|
|
|
|
if (!s.assigned_name || dbStatusText === 'sin_asignar') {
|
|
currentStatusId = systemStatuses.find(st => st.name.toLowerCase().includes('pendiente'))?.id || "ALL";
|
|
} else if (dbStatusText === 'asignado_operario') {
|
|
currentStatusId = systemStatuses.find(st => st.name.toLowerCase() === 'asignado')?.id || "ALL";
|
|
} else if (dbStatusText === 'citado' || (!dbStatusText && s.raw_data.scheduled_date)) {
|
|
currentStatusId = systemStatuses.find(st => st.name.toLowerCase().includes('citado'))?.id || "ALL";
|
|
} else {
|
|
// Si el status_operativo de la DB ya es un ID numérico (del nuevo selector)
|
|
const foundStatus = systemStatuses.find(st => String(st.id) === String(dbStatusText));
|
|
if (foundStatus) currentStatusId = foundStatus.id;
|
|
}
|
|
|
|
// Guardamos el ID calculado en el objeto para poder agruparlo luego fácilmente
|
|
s._calculated_status_id = String(currentStatusId);
|
|
|
|
const matchesSearch = searchTerm === "" || name.includes(searchTerm) || ref.includes(searchTerm) || addr.includes(searchTerm) || pop.includes(searchTerm) || phone.includes(searchTerm) || comp.includes(searchTerm);
|
|
const matchesOp = selectedOp === "ALL" || assigned === selectedOp;
|
|
const matchesStatus = selectedStatus === "ALL" || String(currentStatusId) === String(selectedStatus);
|
|
|
|
return matchesSearch && matchesOp && matchesStatus;
|
|
});
|
|
|
|
const board = document.getElementById('kanbanBoard');
|
|
board.innerHTML = ""; // Limpiamos el tablero
|
|
|
|
// Mapeo de colores de Tailwind para los estados dinámicos
|
|
const colorMap = {
|
|
'gray': { bg: 'bg-slate-100/50', border: 'border-slate-200/60', dot: 'bg-slate-500', shadow: 'shadow-slate-500/50' },
|
|
'blue': { bg: 'bg-blue-50/50', border: 'border-blue-200/60', dot: 'bg-blue-500', shadow: 'shadow-blue-500/50' },
|
|
'emerald': { bg: 'bg-emerald-50/50', border: 'border-emerald-200/60', dot: 'bg-emerald-500', shadow: 'shadow-emerald-500/50' },
|
|
'rose': { bg: 'bg-rose-50/50', border: 'border-rose-200/60', dot: 'bg-rose-500', shadow: 'shadow-rose-500/50' },
|
|
'amber': { bg: 'bg-amber-50/50', border: 'border-amber-200/60', dot: 'bg-amber-500', shadow: 'shadow-amber-500/50' },
|
|
'indigo': { bg: 'bg-indigo-50/50', border: 'border-indigo-200/60', dot: 'bg-indigo-500', shadow: 'shadow-indigo-500/50' },
|
|
'purple': { bg: 'bg-purple-50/50', border: 'border-purple-200/60', dot: 'bg-purple-500', shadow: 'shadow-purple-500/50' },
|
|
'red': { bg: 'bg-red-50/50', border: 'border-red-200/60', dot: 'bg-red-500', shadow: 'shadow-red-500/50' }
|
|
};
|
|
|
|
// Creamos una columna para cada estado (Ocultamos los finales a menos que se filtren explícitamente)
|
|
systemStatuses.forEach(st => {
|
|
if (st.is_final && selectedStatus !== String(st.id) && searchTerm === "") return; // No pintar Finalizados en vista general salvo que se busque
|
|
|
|
const servicesInThisStatus = filteredData.filter(s => s._calculated_status_id === String(st.id));
|
|
const colors = colorMap[st.color] || colorMap['gray'];
|
|
|
|
const column = document.createElement('div');
|
|
column.className = `kanban-column space-y-4 p-4 rounded-[2rem] border ${colors.bg} ${colors.border}`;
|
|
|
|
let cardsHtml = servicesInThisStatus.length > 0
|
|
? servicesInThisStatus.map(s => cardTemplate(s, st.color, st.name)).join('')
|
|
: '<p class="text-center py-10 text-slate-400 text-xs font-bold uppercase border-2 border-dashed border-slate-200/50 rounded-[1.5rem] bg-white/30">Vacío</p>';
|
|
|
|
column.innerHTML = `
|
|
<div class="flex items-center justify-between px-2 pb-2 border-b ${colors.border}">
|
|
<div class="flex items-center gap-2">
|
|
<div class="w-2.5 h-2.5 rounded-full ${colors.dot} shadow-[0_0_10px_currentColor]"></div>
|
|
<h3 class="font-black text-slate-700 uppercase text-[10px] tracking-widest">${st.name}</h3>
|
|
</div>
|
|
<span class="text-[10px] font-black text-slate-400 bg-white px-2 py-0.5 rounded-lg shadow-sm">${servicesInThisStatus.length}</span>
|
|
</div>
|
|
<div class="space-y-3 overflow-y-auto max-h-[calc(100vh-280px)] no-scrollbar pb-10">
|
|
${cardsHtml}
|
|
</div>
|
|
`;
|
|
board.appendChild(column);
|
|
});
|
|
|
|
lucide.createIcons();
|
|
}
|
|
|
|
// ==========================================
|
|
// RESTO DE FUNCIONES INTACTAS
|
|
// ==========================================
|
|
|
|
function cardTemplate(s, colorName, 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 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 = 'tag';
|
|
if(raw.scheduled_date) iconEstado = 'calendar';
|
|
if(label.toLowerCase().includes('camino')) iconEstado = 'car';
|
|
if(label.toLowerCase().includes('reparaci') || label.toLowerCase().includes('trabaja')) iconEstado = 'wrench';
|
|
if(label.toLowerCase().includes('incidencia')) iconEstado = 'alert-triangle';
|
|
if(label.toLowerCase().includes('terminad') || label.toLowerCase().includes('finaliz')) iconEstado = 'check-circle';
|
|
|
|
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',
|
|
'indigo': 'bg-indigo-100 text-indigo-600',
|
|
'gray': 'bg-slate-200 text-slate-600'
|
|
};
|
|
const badgeClass = colorClasses[colorName] || colorClasses['gray'];
|
|
|
|
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';
|
|
|
|
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 truncate max-w-[60%]">
|
|
${isBlocked ? '<span class="w-1.5 h-1.5 bg-current rounded-full pulse-slow opacity-70 shrink-0"></span>' : ''}
|
|
<span class="truncate">${label}</span>
|
|
</span>
|
|
<span class="text-[9px] text-slate-400 font-bold uppercase bg-slate-50 border border-slate-100 px-2 py-1 rounded-lg shrink-0">#${s.service_ref}</span>
|
|
</div>
|
|
<div>
|
|
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-0.5 truncate">${companyName}</p>
|
|
<h4 class="font-black text-slate-800 uppercase text-sm leading-tight line-clamp-1" title="${name}">${name}</h4>
|
|
</div>
|
|
<div class="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>
|
|
</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>`;
|
|
}
|
|
|
|
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 rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
|
|
const singlePhone = matchPhone ? matchPhone[0] : "";
|
|
|
|
if (singlePhone) {
|
|
document.getElementById('detPhone').innerText = singlePhone;
|
|
document.getElementById('detPhoneLink').href = `tel:+34${singlePhone}`;
|
|
document.getElementById('detPhoneLink').classList.remove('text-slate-400', 'pointer-events-none');
|
|
document.getElementById('detPhoneLink').classList.add('text-blue-600');
|
|
} else {
|
|
document.getElementById('detPhone').innerText = "Sin Teléfono";
|
|
document.getElementById('detPhoneLink').href = "#";
|
|
document.getElementById('detPhoneLink').classList.remove('text-blue-600');
|
|
document.getElementById('detPhoneLink').classList.add('text-slate-400', 'pointer-events-none');
|
|
}
|
|
|
|
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 && s._calculated_status_id !== '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 || "";
|
|
|
|
// Mapeo del estado calculado al selector
|
|
document.getElementById('detStatusMap').value = s._calculated_status_id;
|
|
} 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;
|
|
|
|
// Busca el estado seleccionado en el array real de la base de datos
|
|
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
|
|
|
|
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa')) {
|
|
if(!confirm("No has asignado Fecha para este estado. ¿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 {
|
|
// Guarda directamente el ID del estado en status_operativo
|
|
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"); refreshPanelOnly();
|
|
} 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>';
|
|
|
|
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")}` },
|
|
body: JSON.stringify({ guild_id, cp, useDelay })
|
|
});
|
|
const data = await res.json();
|
|
if(data.ok) { closeDetailModal(); showToast("Enviado a la rueda de WhatsApp"); refreshPanelOnly(); }
|
|
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"); refreshPanelOnly();
|
|
} 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(); refreshPanelOnly(); }
|
|
} 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('');
|
|
}
|
|
|
|
async function copyClientPortalLink() {
|
|
const phone = document.getElementById('detPhone').innerText;
|
|
const name = document.getElementById('detName').innerText;
|
|
const addr = document.getElementById('detAddrText').innerText;
|
|
|
|
if (!phone || phone === "Sin Teléfono") {
|
|
showToast("No hay un teléfono válido para este cliente.", "warning");
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('btnPortalLink');
|
|
const originalHtml = btn.innerHTML;
|
|
|
|
btn.innerHTML = '<i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> Generando...';
|
|
lucide.createIcons();
|
|
|
|
try {
|
|
const res = await fetch(`${API_URL}/clients/ensure`, {
|
|
method: 'POST',
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Authorization": `Bearer ${localStorage.getItem("token")}`
|
|
},
|
|
body: JSON.stringify({ phone: phone, name: name, address: addr })
|
|
});
|
|
const data = await res.json();
|
|
|
|
if (data.ok && data.client && data.client.portal_token) {
|
|
const portalLink = `https://portal.integrarepara.es/?token=${data.client.portal_token}`;
|
|
await navigator.clipboard.writeText(portalLink);
|
|
|
|
btn.innerHTML = '<i data-lucide="check-circle" class="w-3 h-3"></i> ¡Copiado!';
|
|
btn.classList.replace('text-blue-600', 'text-emerald-600');
|
|
btn.classList.replace('bg-blue-50', 'bg-emerald-50');
|
|
btn.classList.replace('border-blue-100', 'border-emerald-200');
|
|
showToast("Enlace copiado. ¡Listo para pegar en WhatsApp!");
|
|
|
|
setTimeout(() => {
|
|
btn.innerHTML = originalHtml;
|
|
btn.className = "text-[10px] font-black bg-blue-50 border border-blue-100 hover:bg-blue-600 hover:text-white text-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1.5 transition-all shadow-sm active:scale-95";
|
|
lucide.createIcons();
|
|
}, 3000);
|
|
} else {
|
|
showToast("No se pudo generar el token. Revisa la consola.", "warning");
|
|
btn.innerHTML = originalHtml;
|
|
lucide.createIcons();
|
|
}
|
|
} catch (error) {
|
|
console.error("Error obteniendo token:", error);
|
|
showToast("Error al conectar con el servidor", "warning");
|
|
btn.innerHTML = originalHtml;
|
|
lucide.createIcons();
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |