Files
web/servicios2.html
2026-03-22 11:27:52 +00:00

1233 lines
78 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 Kanban Operativo - 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; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
/* Animaciones para tarjetas y alertas */
.pulse-slow { animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
/* Estilos del Tablero Kanban */
.kanban-col { min-width: 320px; max-width: 400px; display: flex; flex-direction: column; max-height: calc(100vh - 220px); }
.kanban-cards { flex: 1; overflow-y: auto; padding-bottom: 2rem; }
.kanban-card { transition: all 0.2s ease; cursor: pointer; border-left: 4px solid transparent; }
.kanban-card:hover { transform: translateY(-3px); box-shadow: 0 12px 20px -5px rgba(0, 0, 0, 0.08); }
/* Colores de borde izquierdo según la columna */
.border-col-1 { border-left-color: #ef4444; } /* Rojo: Sin Asignar */
.border-col-2 { border-left-color: #f59e0b; } /* Ambar: Sin Cita */
.border-col-3 { border-left-color: #3b82f6; } /* Azul: Pendiente Inicio */
.border-col-4 { border-left-color: #10b981; } /* Verde: Trabajando */
/* Estilos base para formularios y modales */
.input-modern { @apply w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl text-sm font-semibold text-slate-700 outline-none transition-all focus:border-blue-500 focus:bg-white focus:ring-2 focus:ring-blue-100; }
.label-modern { @apply block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1.5 ml-1; }
.input-editable { border-bottom: 2px solid #3b82f6 !important; background: #eff6ff !important; border-radius: 0.5rem !important; padding: 4px 8px !important; pointer-events: auto !important; }
.input-readonly { border: none !important; background: transparent !important; pointer-events: none; outline: none; }
/* Estilos para el chat */
.msg-me { background-color: #dcfce7; border-bottom-right-radius: 4px; border: 1px solid #bbf7d0; align-self: flex-end; }
.msg-other { background-color: #f1f5f9; border-bottom-left-radius: 4px; border: 1px solid #e2e8f0; align-self: flex-start; }
.msg-internal { background-color: #fffbeb; border-radius: 8px; border: 1px solid #fde68a; align-self: center; width: 90%; }
</style>
</head>
<body class="bg-slate-50 text-slate-800 font-sans antialiased text-left overflow-hidden">
<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-auto overflow-y-hidden bg-slate-50 p-6 no-scrollbar relative flex flex-col">
<div class="flex flex-col bg-white p-6 rounded-[2rem] shadow-sm border border-slate-200 gap-4 shrink-0 mb-6 min-w-max fade-in">
<div class="flex justify-between items-center w-full">
<div>
<h2 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-3">
<span class="bg-slate-900 p-2.5 rounded-xl text-white shadow-lg"><i data-lucide="kanban"></i></span>
TABLERO OPERATIVO
</h2>
<p class="text-sm text-slate-500 mt-1 font-medium">Control visual del flujo de trabajo de la flota.</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 shrink-0">
<i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio
</button>
</div>
<div class="flex flex-wrap gap-4 items-center mt-2">
<div class="relative flex-1 min-w-[250px] max-w-md">
<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="renderKanban()" 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-48">
<select id="opFilter" onchange="renderKanban()" 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">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 w-full md:w-56">
<input type="week" id="weekFilter" onchange="renderKanban()" 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 text-slate-600 cursor-pointer" title="Filtrar por semana">
</div>
<button onclick="document.getElementById('weekFilter').value = ''; renderKanban();" class="text-xs font-bold text-slate-400 hover:text-red-500 px-2 py-3">Limpiar Sem.</button>
<button onclick="refreshData()" class="bg-white border border-slate-200 text-slate-600 hover:text-blue-600 px-4 py-3 rounded-xl shadow-sm transition-all active:scale-95 shrink-0 flex items-center gap-2 ml-auto">
<i data-lucide="refresh-cw" class="w-4 h-4"></i> <span class="hidden md:inline text-xs font-black uppercase tracking-widest">Recargar</span>
</button>
</div>
<div class="flex flex-wrap gap-2 items-center pt-2" id="statusPills">
<span class="text-[10px] font-black text-slate-400 uppercase"><i data-lucide="loader-2" class="w-3 h-3 animate-spin inline"></i> Cargando estados...</span>
</div>
</div>
<div class="flex gap-6 overflow-x-auto no-scrollbar flex-1 pb-6 w-full fade-in min-w-max">
<div class="kanban-col bg-slate-100/70 rounded-[2rem] p-4 border border-slate-200/60 shadow-inner">
<div class="flex justify-between items-center mb-4 px-2">
<h3 class="font-black text-slate-700 uppercase tracking-widest text-xs flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-red-500"></span> Sin Asignar
</h3>
<span id="count-unassigned" class="bg-white border border-slate-200 text-slate-600 text-[10px] font-black px-2.5 py-1 rounded-lg shadow-sm">0</span>
</div>
<div id="col-unassigned" class="kanban-cards space-y-3 no-scrollbar"></div>
</div>
<div class="kanban-col bg-slate-100/70 rounded-[2rem] p-4 border border-slate-200/60 shadow-inner">
<div class="flex justify-between items-center mb-4 px-2">
<h3 class="font-black text-slate-700 uppercase tracking-widest text-xs flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-amber-500 animate-pulse"></span> Sin Cita
</h3>
<span id="count-unscheduled" class="bg-white border border-slate-200 text-slate-600 text-[10px] font-black px-2.5 py-1 rounded-lg shadow-sm">0</span>
</div>
<div id="col-unscheduled" class="kanban-cards space-y-3 no-scrollbar"></div>
</div>
<div class="kanban-col bg-slate-100/70 rounded-[2rem] p-4 border border-slate-200/60 shadow-inner">
<div class="flex justify-between items-center mb-4 px-2">
<h3 class="font-black text-slate-700 uppercase tracking-widest text-xs flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-blue-500"></span> Pte. Inicio
</h3>
<span id="count-pending-start" class="bg-white border border-slate-200 text-slate-600 text-[10px] font-black px-2.5 py-1 rounded-lg shadow-sm">0</span>
</div>
<div id="col-pending-start" class="kanban-cards space-y-3 no-scrollbar"></div>
</div>
<div class="kanban-col bg-slate-100/70 rounded-[2rem] p-4 border border-slate-200/60 shadow-inner">
<div class="flex justify-between items-center mb-4 px-2">
<h3 class="font-black text-slate-700 uppercase tracking-widest text-xs flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-emerald-500"></span> Trabajando
</h3>
<span id="count-working" class="bg-white border border-slate-200 text-slate-600 text-[10px] font-black px-2.5 py-1 rounded-lg shadow-sm">0</span>
</div>
<div id="col-working" class="kanban-cards space-y-3 no-scrollbar"></div>
</div>
</div>
</main>
</div>
</div>
<div id="createModal" class="fixed inset-0 bg-slate-900/60 hidden z-[100] flex items-center justify-center backdrop-blur-sm p-4 text-left">
<div class="bg-white rounded-[2rem] shadow-2xl w-full max-w-5xl max-h-[95vh] overflow-hidden flex flex-col fade-in">
<div class="p-6 border-b border-slate-100 flex justify-between items-center bg-white shrink-0">
<div class="flex items-center gap-3">
<div class="bg-blue-100 p-2.5 rounded-xl text-blue-600"><i data-lucide="file-plus" class="w-5 h-5"></i></div>
<div>
<h3 class="font-black text-slate-800 text-lg uppercase tracking-tight">Alta de Expediente Manual</h3>
<p class="text-xs text-slate-500 font-medium">Registra un nuevo servicio directamente en el sistema</p>
</div>
</div>
<button onclick="closeCreateModal()" class="text-slate-400 hover:text-red-500 bg-slate-50 p-2 rounded-full transition-colors"><i data-lucide="x" class="w-5 h-5"></i></button>
</div>
<form onsubmit="saveNewService(event)" class="flex-1 overflow-y-auto no-scrollbar p-6 bg-slate-50/50">
<div class="grid grid-cols-1 md:grid-cols-12 gap-8">
<div class="md:col-span-7 space-y-6">
<div class="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
<h4 class="font-black text-slate-800 uppercase text-xs flex items-center gap-2 border-b border-slate-100 pb-3 mb-4">
<i data-lucide="user" class="w-4 h-4 text-blue-500"></i> Datos del Cliente
</h4>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="label-modern">Teléfono</label>
<input type="tel" id="nPhone" oninput="searchClientByPhone(this.value)" placeholder="Ej: 600123456" class="input-modern" required>
</div>
<div>
<label class="label-modern">Nombre Completo</label>
<input type="text" id="nName" placeholder="Nombre del asegurado" class="input-modern" required>
</div>
</div>
<div>
<label class="label-modern">Dirección Completa</label>
<input type="text" id="nAddr" placeholder="Calle, número, piso, población..." class="input-modern" required>
<div id="addrSuggestions" class="hidden mt-2 p-2 bg-amber-50 border border-amber-200 rounded-lg text-[10px] font-bold text-amber-700">⚠️ Cliente con otras direcciones registradas.</div>
</div>
<div class="pt-2">
<label class="flex items-center gap-3 cursor-pointer mb-2">
<input type="checkbox" id="isCompanyCheck" onchange="toggleCompanyFields(this.checked)" class="w-5 h-5 rounded text-blue-600">
<span class="text-xs font-black text-slate-700 uppercase">¿Es de Compañía de Seguros?</span>
</label>
<div id="companyFields" class="hidden space-y-4 p-4 bg-blue-50/30 rounded-xl border border-blue-100">
<select id="nCompanySelect" class="input-modern bg-white"><option value="">Seleccionar compañía...</option></select>
<input type="text" id="nExpRef" onblur="checkDuplicateRef(this.value)" placeholder="Nº Expediente" class="input-modern bg-white uppercase">
<p id="refAlert" class="hidden text-[10px] text-red-600 font-bold mt-1 uppercase">⚠️ Referencia ya existente</p>
</div>
</div>
</div>
<div class="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
<h4 class="font-black text-slate-800 uppercase text-xs flex items-center gap-2 border-b border-slate-100 pb-3 mb-4">
<i data-lucide="align-left" class="w-4 h-4 text-amber-500"></i> Detalles de la Avería
</h4>
<label class="label-modern">Descripción</label>
<textarea id="nDesc" placeholder="Describe el problema a reparar..." rows="6" class="input-modern resize-none"></textarea>
</div>
</div>
<div class="md:col-span-5 space-y-6">
<div class="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
<h4 class="font-black text-slate-800 uppercase text-xs flex items-center gap-2 border-b border-slate-100 pb-3 mb-4">
<i data-lucide="hammer" class="w-4 h-4 text-purple-500"></i> Asignación y Tiempo
</h4>
<div>
<label class="label-modern">Gremio Recomendado</label>
<div class="relative">
<select id="nGuild" class="input-modern appearance-none cursor-pointer pr-10" onchange="loadOps(this.value, 'nWorker')">
<option value="">Seleccionar gremio...</option>
</select>
<i data-lucide="chevron-down" class="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div class="grid grid-cols-1 gap-4">
<div>
<label class="label-modern">Operario</label>
<div class="relative">
<select id="nWorker" class="input-modern appearance-none cursor-pointer pr-8">
<option value="">(Sin asignar)</option>
</select>
<i data-lucide="chevron-down" class="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div>
<label class="label-modern">Duración Estimada</label>
<div class="relative">
<select id="nDuration" class="input-modern font-black text-blue-600 uppercase appearance-none cursor-pointer pr-8">
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="45">45 min</option>
<option value="60" selected>1 hora</option>
<option value="90">1.5 horas</option>
<option value="120">2 horas</option>
<option value="180">3 horas</option>
<option value="240">4 horas (Max)</option>
</select>
<i data-lucide="clock" class="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
</div>
</div>
<div class="space-y-3">
<button type="submit" name="action" value="manual" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-black py-4 rounded-xl text-sm uppercase tracking-widest shadow-[0_8px_20px_-6px_rgba(5,150,105,0.5)] transition-all active:scale-95 flex items-center justify-center gap-2">
<i data-lucide="check-circle" class="w-5 h-5"></i> Crear y Guardar
</button>
<div class="relative flex items-center justify-center py-2">
<span class="border-t border-slate-200 w-full absolute"></span>
<span class="bg-slate-50 px-3 text-[9px] font-black text-slate-400 uppercase tracking-widest relative z-10">Opciones Automáticas</span>
</div>
<button type="submit" name="action" value="auto" class="w-full bg-slate-800 hover:bg-slate-700 text-white font-black py-3 rounded-xl text-xs uppercase tracking-widest shadow-md transition-all active:scale-95 flex items-center justify-between px-5 border border-slate-600">
<div class="text-left">
<span class="block">Mandar a la Cola</span>
<span class="block text-[9px] text-slate-400 font-medium normal-case mt-0.5">Busca operario vía WhatsApp</span>
</div>
<i data-lucide="zap" class="w-5 h-5 text-amber-400"></i>
</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-6xl 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-20"><i data-lucide="x" class="w-5 h-5"></i></button>
<div class="p-6 border-b border-slate-100 bg-slate-50/50 pr-24 flex justify-between items-center">
<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 leading-none mb-1">Expediente Oficial</p>
<h3 class="font-black text-slate-800 text-xl tracking-tight leading-none">#<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] inline-flex items-center gap-1.5"></span>
</div>
</div>
<div class="flex flex-col md:flex-row h-[75vh] bg-white overflow-hidden">
<input type="hidden" id="detId">
<input type="hidden" id="detCp">
<div class="w-full md:w-7/12 p-5 overflow-y-auto no-scrollbar flex flex-col gap-4">
<div class="bg-slate-50 p-4 pb-6 rounded-[1rem] border border-slate-100 shrink-0 max-h-[380px] overflow-y-auto no-scrollbar shadow-inner">
<div class="flex justify-between items-start mb-3">
<div class="flex-1">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Asegurado / Cliente</p>
<input type="text" id="editName" class="input-readonly w-full font-black text-slate-800 text-lg uppercase leading-none" readonly>
</div>
<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 shrink-0 mt-1">
<i data-lucide="link" class="w-3 h-3"></i> Copiar Portal
</button>
</div>
<div class="flex items-center gap-4 mb-4">
<div class="flex items-center gap-1.5">
<i data-lucide="phone" class="w-3.5 h-3.5 text-blue-600"></i>
<input type="tel" id="editPhone" class="input-readonly text-sm text-blue-600 font-black w-32" readonly>
<a id="btnCallPhone" href="#" class="p-1.5 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 hidden" title="Llamar"><i data-lucide="phone-call" class="w-3.5 h-3.5"></i></a>
</div>
<div class="flex items-center gap-1.5 flex-1">
<i data-lucide="map-pin" class="w-3.5 h-3.5 text-slate-400 shrink-0"></i>
<textarea id="editAddr" rows="1" class="input-readonly w-full text-[11px] font-bold text-slate-600 resize-none uppercase" readonly></textarea>
</div>
</div>
<hr class="border-slate-200 mb-4">
<div class="pb-2">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="sparkles" class="w-3 h-3 text-amber-500"></i> Avería (Limpiada por IA)</p>
<textarea id="editDesc" rows="6" class="w-full bg-white border border-slate-200 p-4 rounded-xl text-sm font-medium text-slate-800 leading-relaxed outline-none overflow-y-auto" readonly></textarea>
</div>
</div>
<div id="panelAsignado" class="bg-blue-50/40 p-4 rounded-[1rem] border border-blue-100 flex flex-col shadow-sm shrink-0 hidden">
<div class="grid grid-cols-2 gap-4 items-center">
<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-2 bg-white p-2 rounded-xl border border-slate-100 shadow-sm">
<div class="bg-emerald-100 w-8 h-8 rounded-full flex items-center justify-center text-emerald-600 shrink-0"><i data-lucide="hard-hat" class="w-4 h-4"></i></div>
<p id="detWorker" class="font-black text-slate-700 text-[11px] uppercase leading-tight truncate"></p>
</div>
</div>
<div class="space-y-1.5">
<p class="text-[9px] font-black text-slate-800 uppercase flex items-center gap-1"><i data-lucide="arrow-right-left" class="w-3 h-3 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-2.5 rounded-xl text-[11px] font-bold shadow-lg outline-none cursor-pointer appearance-none pr-8"></select>
<i data-lucide="chevron-down" class="w-3 h-3 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
</div>
<div class="flex items-end gap-3 mt-4">
<div class="flex-1 space-y-1.5">
<p class="text-[9px] font-black text-blue-600 uppercase tracking-widest flex items-center gap-1"><i data-lucide="calendar-clock" class="w-3 h-3"></i> Cita</p>
<div class="flex gap-2">
<input type="date" id="dateInput" class="w-full bg-white border border-slate-200 p-2.5 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-24 bg-white border border-slate-200 p-2.5 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>
<button id="btnSaveAppt" onclick="saveAppointment()" class="bg-blue-600 text-white font-black px-6 py-2.5 rounded-xl text-[10px] uppercase tracking-widest shadow-[0_4px_10px_-2px_rgba(37,99,235,0.5)] hover:bg-blue-700 transition-all active:scale-95 flex items-center gap-1.5 shrink-0 h-[38px]">
<i data-lucide="save" class="w-3 h-3"></i> Guardar
</button>
</div>
</div>
<div id="panelSinAsignar" class="bg-blue-50/40 p-4 rounded-[1rem] border border-blue-100 flex flex-col shadow-sm shrink-0 hidden">
<button onclick="sendToAutomate()" id="btnAuto" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-3 rounded-xl flex items-center justify-center gap-2 shadow-lg shadow-blue-200 transition-all active:scale-95 mb-4 border border-blue-500">
<i data-lucide="zap" class="w-4 h-4 text-amber-400"></i>
<span class="font-black uppercase text-[11px] tracking-widest">Lanzar Asignación Automática</span>
</button>
<div class="grid grid-cols-2 gap-4 items-end border-t border-blue-100 pt-4">
<div class="space-y-1.5">
<p class="text-[9px] font-black text-slate-500 uppercase flex items-center gap-1">Gremio Necesario</p>
<div class="relative">
<select id="reGremio" class="w-full bg-white border border-slate-200 p-2.5 rounded-xl text-[11px] font-bold text-slate-700 outline-none appearance-none pr-8" onchange="loadOps(this.value, 'reOperario')">
<option value="">Gremio...</option>
</select>
<i data-lucide="chevron-down" class="w-3 h-3 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
<div class="space-y-1.5">
<p class="text-[9px] font-black text-slate-500 uppercase flex items-center gap-1 text-right mr-1 italic text-blue-600">O Asignación Manual</p>
<div class="flex gap-2">
<div class="relative flex-1">
<select id="reOperario" class="w-full bg-white border border-slate-200 p-2.5 rounded-xl text-[11px] font-bold text-slate-700 outline-none appearance-none pr-8">
<option value="">Elegir...</option>
</select>
<i data-lucide="chevron-down" class="w-3 h-3 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
<button onclick="assignManualFromPanel()" class="bg-slate-800 text-white font-black px-4 py-2.5 rounded-xl text-[10px] uppercase hover:bg-emerald-600 transition-colors shrink-0 shadow-md">OK</button>
</div>
</div>
</div>
</div>
<div id="panelEnBolsa" class="bg-amber-50/40 p-4 rounded-[1rem] border border-amber-200 flex items-center justify-between shadow-sm shrink-0 hidden">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-amber-100 text-amber-500 rounded-full flex items-center justify-center animate-pulse"><i data-lucide="bot" class="w-5 h-5"></i></div>
<div>
<h4 class="font-black text-slate-800 text-[11px] uppercase tracking-tight">Robot buscando operario</h4>
<p class="text-[9px] text-slate-500 font-medium">Bolsa automática activa.</p>
</div>
</div>
<button onclick="stopAutomation()" class="bg-rose-500 hover:bg-rose-600 text-white font-black px-4 py-2 rounded-lg text-[9px] uppercase shadow-sm flex items-center gap-1.5 transition-colors">
<i data-lucide="octagon" class="w-3 h-3"></i> Detener
</button>
</div>
</div>
<div class="w-full md:w-5/12 border-t md:border-t-0 md:border-l border-slate-200 bg-slate-100 flex flex-col">
<div class="p-4 bg-white border-b border-slate-200 flex items-center gap-2 shrink-0">
<div class="bg-blue-100 text-blue-600 p-2 rounded-lg"><i data-lucide="message-square" class="w-4 h-4"></i></div>
<h4 class="font-black text-sm uppercase text-slate-800 tracking-wider">Historial / Chat</h4>
</div>
<div id="chatBox" class="flex-1 overflow-y-auto p-4 space-y-4 flex flex-col no-scrollbar">
<div class="text-center text-xs font-bold text-slate-400 mt-10 uppercase tracking-widest"><i data-lucide="loader-2" class="w-4 h-4 animate-spin mx-auto mb-2"></i> Cargando...</div>
</div>
<div class="p-4 bg-white border-t border-slate-200 shrink-0 space-y-3">
<textarea id="chatInput" rows="2" placeholder="Escribe un mensaje o nota..." class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm font-medium outline-none focus:ring-2 focus:ring-blue-500 resize-none"></textarea>
<div class="flex items-center justify-between gap-2">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" id="chatInternal" class="w-4 h-4 text-amber-500 rounded border-slate-300">
<span class="text-[10px] font-black uppercase text-amber-600 bg-amber-50 px-2 py-1 rounded-md border border-amber-100">Nota Oculta</span>
</label>
<button onclick="sendChatMessage()" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest shadow-md transition-all active:scale-95 flex items-center gap-2">
<i data-lucide="send" class="w-3.5 h-3.5"></i> Enviar
</button>
</div>
</div>
</div>
</div>
<div class="p-4 bg-white border-t border-slate-100 flex justify-start items-center px-8 gap-3 shrink-0">
<div id="viewActions">
<button onclick="enableEditing()" id="btnEnableEdit" class="text-slate-400 hover:text-blue-600 flex items-center gap-2 transition-all group">
<span class="text-[10px] font-black uppercase tracking-widest">Editar Ficha</span>
<div class="bg-slate-50 border border-slate-200 p-2 rounded-xl shadow-sm group-hover:border-blue-200 group-hover:bg-blue-50 transition-all"><i data-lucide="edit-3" class="w-4 h-4"></i></div>
</button>
</div>
<div id="editActions" class="hidden flex gap-3">
<button onclick="cancelEditing()" class="px-6 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-400 hover:bg-slate-100 transition-all border border-slate-200">Cancelar</button>
<button onclick="saveFullEdit()" class="px-8 py-2.5 bg-blue-600 text-white rounded-xl text-[10px] font-black uppercase tracking-widest shadow-lg active:scale-95 transition-all">Guardar Cambios</button>
</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-all 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>
// API_URL ya se carga mágicamente desde js/layout.js, así que no la repetimos
let localData = [];
let systemStatuses = [];
let systemGuilds = [];
let activeStatusFilter = 'ALL';
const colorDict = {
'gray': { bg: 'bg-slate-100', text: 'text-slate-600', dot: 'bg-slate-500', border: 'border-slate-200' },
'blue': { bg: 'bg-blue-100', text: 'text-blue-700', dot: 'bg-blue-500', border: 'border-blue-200' },
'emerald': { bg: 'bg-emerald-100', text: 'text-emerald-700', dot: 'bg-emerald-500', border: 'border-emerald-200' },
'amber': { bg: 'bg-amber-100', text: 'text-amber-700', dot: 'bg-amber-500', border: 'border-amber-200' },
'orange': { bg: 'bg-orange-100', text: 'text-orange-700', dot: 'bg-orange-500', border: 'border-orange-200' },
'red': { bg: 'bg-red-100', text: 'text-red-700', dot: 'bg-red-500', border: 'border-red-200' },
'purple': { bg: 'bg-purple-100', text: 'text-purple-700', dot: 'bg-purple-500', border: 'border-purple-200' },
'indigo': { bg: 'bg-indigo-100', text: 'text-indigo-700', dot: 'bg-indigo-500', border: 'border-indigo-200' },
'rose': { bg: 'bg-rose-100', text: 'text-rose-700', dot: 'bg-rose-500', border: 'border-rose-200' }
};
document.addEventListener("DOMContentLoaded", async () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
await Promise.all([loadStatuses(), loadGuilds()]);
refreshData();
setInterval(refreshData, 30000);
});
// OBTENER SEMANA ISO
function getWeekNumber(d) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1)/7);
return { year: d.getUTCFullYear(), week: weekNo };
}
function isDateInWeekString(dateStr, weekStr) {
if (!dateStr || !weekStr) return false;
const targetDate = new Date(dateStr);
const { year, week } = getWeekNumber(targetDate);
const targetWeekStr = `${year}-W${String(week).padStart(2, '0')}`;
return targetWeekStr === weekStr;
}
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;
renderStatusPills();
const modalSelect = document.getElementById('detStatusMap');
modalSelect.innerHTML = '';
systemStatuses.forEach(st => {
modalSelect.innerHTML += `<option value="${st.id}">👉 ${st.name.toUpperCase()}</option>`;
});
}
} catch (e) { console.error(e); }
}
async function loadGuilds() {
try {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
systemGuilds = data.guilds;
const opts = '<option value="">Seleccionar Gremio...</option>' + systemGuilds.map(g => `<option value="${g.id}">${g.name}</option>`).join('');
document.getElementById('nGuild').innerHTML = opts;
document.getElementById('reGremio').innerHTML = opts;
}
} catch (e) { console.error(e); }
}
function renderStatusPills() {
const container = document.getElementById('statusPills');
let html = `
<button onclick="setStatusFilter('ALL')" class="px-4 py-1.5 rounded-lg text-[10px] font-black tracking-widest transition-all border ${activeStatusFilter === 'ALL' ? 'bg-slate-900 text-white border-slate-900 shadow-md' : 'bg-white border-slate-200 text-slate-500 hover:bg-slate-50'}">
TODOS
</button>
`;
systemStatuses.forEach(st => {
const isActive = activeStatusFilter === String(st.id);
const c = colorDict[st.color] || colorDict['gray'];
const colorBase = c.bg.split('-')[1];
const activeClasses = `bg-white border-${colorBase}-400 text-${colorBase}-700 shadow-md ring-2 ring-${colorBase}-100`;
const inactiveClasses = `bg-white border-slate-200 text-slate-500 hover:bg-slate-50`;
html += `
<button onclick="setStatusFilter('${st.id}')" class="px-3 py-1.5 rounded-lg text-[10px] font-bold border transition-all flex items-center gap-1.5 ${isActive ? activeClasses : inactiveClasses}">
<div class="w-1.5 h-1.5 rounded-full ${c.dot}"></div>
${st.name}
</button>
`;
});
container.innerHTML = html;
}
function setStatusFilter(id) {
activeStatusFilter = id;
renderStatusPills();
renderKanban();
}
async function refreshData() {
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();
renderKanban();
}
} 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;
}
// 🤖 "IA" LIMPIADORA DE TEXTOS
function limpiarPaja(texto) {
if (!texto) return "Sin descripción detallada.";
let res = texto.replace(/(\r\n|\n|\r)/gm, " ");
res = res.replace(/\d{2}\/\d{2}\/\d{4}\s*-\s*/g, ' ');
const basura = [
/Llama asegurad[oa]\s*\d*/gi, /solicita (operario|profesional) para/gi,
/Cobro banco.*?(?=\.|\s-|$)/gi, /El servicio dispone de hasta.*?(?=\.|\s-|$)/gi,
/Servicio asignado a:.*?(?=\.|\s-|$)/gi, /Cambio de estado:.*?(?=\.|\s-|$)/gi,
/en espera de profesional.*?(?=\.|\s-|$)/gi
];
basura.forEach(regex => { res = res.replace(regex, ' '); });
res = res.replace(/\s+/g, ' ').replace(/\s,\s/g, ', ').replace(/^[,\.\-\s]+/, '').trim();
return res.length > 5 ? res.charAt(0).toUpperCase() + res.slice(1) : texto;
}
// =====================================
// MOTOR KANBAN
// =====================================
function renderKanban() {
const searchTerm = document.getElementById('searchFilter').value.toLowerCase();
const selectedOp = document.getElementById('opFilter').value;
const weekValue = document.getElementById('weekFilter').value;
const cols = { unassigned: [], unscheduled: [], pending_start: [], working: [] };
localData.forEach(s => {
if (s.status === 'archived' || s.provider === 'SYSTEM_BLOCK') return;
const raw = s.raw_data || {};
const name = (raw["Nombre Cliente"] || raw["CLIENTE"] || "").toLowerCase();
const ref = (s.service_ref || "").toLowerCase();
const pop = (raw["Población"] || "").toLowerCase();
const phone = (raw["Teléfono"] || "").toLowerCase();
// Filtro Buscador
if (searchTerm && !name.includes(searchTerm) && !ref.includes(searchTerm) && !pop.includes(searchTerm) && !phone.includes(searchTerm)) return;
// Filtro Operario
if (selectedOp !== "ALL" && s.assigned_name !== selectedOp) return;
// Filtro Semana
if (weekValue !== "") {
if (!raw.scheduled_date || !isDateInWeekString(raw.scheduled_date, weekValue)) return;
}
const dbStat = raw.status_operativo;
const statusObj = systemStatuses.find(st => String(st.id) === String(dbStat));
const stName = (statusObj?.name || "").toLowerCase();
// Filtro de Estado (Pastillas superiores)
if (activeStatusFilter !== "ALL" && String(statusObj?.id) !== activeStatusFilter) return;
// Si está finalizado o anulado, NO SE MUESTRA en el tablero Kanban
if (statusObj?.is_final || stName.includes('finaliza') || stName.includes('anulad') || stName.includes('terminad')) return;
const isWorking = stName.includes('trabaja') || stName.includes('camino');
const hasDate = raw.scheduled_date && raw.scheduled_date.trim() !== "";
// REPARTO KANBAN INTELIGENTE
if (!s.assigned_to) {
cols.unassigned.push(s);
} else if (!hasDate) {
cols.unscheduled.push(s);
} else if (!isWorking) {
cols.pending_start.push(s);
} else {
cols.working.push(s);
}
});
document.getElementById('count-unassigned').innerText = cols.unassigned.length;
document.getElementById('count-unscheduled').innerText = cols.unscheduled.length;
document.getElementById('count-pending-start').innerText = cols.pending_start.length;
document.getElementById('count-working').innerText = cols.working.length;
document.getElementById('col-unassigned').innerHTML = cols.unassigned.map(s => buildCard(s, 1)).join('');
document.getElementById('col-unscheduled').innerHTML = cols.unscheduled.map(s => buildCard(s, 2)).join('');
document.getElementById('col-pending-start').innerHTML = cols.pending_start.map(s => buildCard(s, 3)).join('');
document.getElementById('col-working').innerHTML = cols.working.map(s => buildCard(s, 4)).join('');
lucide.createIcons();
}
function buildCard(s, colType) {
const raw = s.raw_data || {};
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
const addr = raw["Dirección"] || "Sin dirección";
const pop = raw["Población"] || "";
const comp = (raw["Compañía"] || raw["Procedencia"] || "Particular").split('-')[0].trim().substring(0,10);
const guildObj = systemGuilds.find(g => String(g.id) === String(s.guild_id || raw.guild_id));
const guildName = guildObj ? guildObj.name : 'Reparación';
const descLimpia = limpiarPaja(raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"]);
// Alertas (Candado y Ojos)
const hasLock = raw.has_lock === true || String(raw.has_lock) === 'true';
const hasEyes = raw.has_eyes === true || String(raw.has_eyes) === 'true';
let alerts = '';
if (hasLock) alerts += `<span class="bg-slate-800 text-white p-1 rounded shadow-sm"><i data-lucide="lock" class="w-3 h-3"></i></span>`;
if (hasEyes) alerts += `<span class="bg-amber-500 text-white p-1 rounded shadow-sm animate-pulse"><i data-lucide="eye" class="w-3 h-3"></i></span>`;
// Identificar el estado exacto actual para ponerle color a la etiqueta
const dbStat = raw.status_operativo;
const statusObj = systemStatuses.find(st => String(st.id) === String(dbStat)) || systemStatuses[0];
const cMap = colorDict[statusObj?.color] || colorDict['gray'];
// Pie de tarjeta dinámico
let bottomInfo = '';
if (colType === 1) {
if (s.automation_status === 'in_progress') {
bottomInfo = `<span class="text-[10px] font-black text-amber-600 bg-amber-50 border border-amber-200 px-2 py-1 rounded-lg uppercase flex items-center gap-1 animate-pulse"><i data-lucide="bot" class="w-3 h-3"></i> Buscando...</span>`;
} else {
bottomInfo = `<span class="text-[10px] font-black text-red-500 bg-red-50 px-2 py-1 rounded-lg uppercase border border-red-100 flex items-center gap-1"><i data-lucide="user-plus" class="w-3 h-3"></i> Falta Técnico</span>`;
}
} else if (colType === 2) {
bottomInfo = `
<div class="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-lg border border-slate-200">
<div class="w-4 h-4 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center shrink-0"><i data-lucide="hard-hat" class="w-2.5 h-2.5"></i></div>
<span class="text-[10px] font-bold text-slate-600 truncate max-w-[120px]">${s.assigned_name}</span>
</div>`;
} else {
const fDate = raw.scheduled_date ? raw.scheduled_date.split('-').reverse().slice(0,2).join('/') : '';
bottomInfo = `
<div class="flex items-center gap-1.5 bg-blue-50 px-2 py-1 rounded-lg border border-blue-100">
<i data-lucide="calendar-clock" class="w-3 h-3 text-blue-600"></i>
<span class="text-[10px] font-black text-blue-700">${fDate} | ${raw.scheduled_time || ''}</span>
</div>
<div class="w-5 h-5 rounded-full bg-slate-200 flex items-center justify-center text-[8px] font-black text-slate-600 ml-auto border border-slate-300" title="${s.assigned_name}">
${s.assigned_name ? s.assigned_name.substring(0,2).toUpperCase() : '?'}
</div>`;
}
return `
<div onclick="openDetail(${s.id})" class="kanban-card bg-white p-4 rounded-2xl border border-slate-200 shadow-sm relative border-col-${colType} flex flex-col gap-3">
${s.is_urgent ? '<div class="absolute top-0 right-0 bg-red-500 text-white text-[8px] font-black px-2 py-1 rounded-bl-lg uppercase tracking-widest z-10">Urgente</div>' : ''}
<div class="flex justify-between items-start gap-2 pr-12">
<div class="flex flex-wrap gap-1.5">
<span class="text-[8px] font-black bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded uppercase border border-slate-200">#${s.service_ref}</span>
<span class="text-[8px] font-black bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded uppercase border border-blue-100">${comp}</span>
${alerts}
</div>
</div>
<div>
<h4 class="font-black text-slate-800 text-sm uppercase leading-tight line-clamp-2">${name}</h4>
<p class="text-[9px] font-bold text-slate-400 mt-0.5 truncate uppercase flex items-center gap-1"><i data-lucide="map-pin" class="w-2.5 h-2.5"></i> ${addr}, ${pop}</p>
</div>
<p class="text-[10px] text-slate-500 font-medium leading-snug line-clamp-2 bg-slate-50 p-2 rounded-lg border border-slate-100">${descLimpia}</p>
<div class="flex items-center justify-between border-t border-slate-100 pt-3 mt-1">
${bottomInfo}
</div>
</div>`;
}
// =====================================
// MODALES Y FUNCIONES DE EDICIÓN
// =====================================
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, startInEditMode = false) {
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 || "";
if (document.getElementById('detCp')) document.getElementById('detCp').value = raw["Código Postal"] || "00000";
// Alertas visuales dentro del modal
const hasLock = raw.has_lock === true || String(raw.has_lock) === 'true';
const hasEyes = raw.has_eyes === true || String(raw.has_eyes) === 'true';
let modalAlerts = '';
if (hasLock) modalAlerts += `<span class="ml-2 bg-slate-800 text-white px-1.5 py-0.5 rounded inline-flex items-center gap-1 shadow-sm"><i data-lucide="lock" class="w-3 h-3"></i></span>`;
if (hasEyes) modalAlerts += `<span class="ml-2 bg-amber-500 text-white px-1.5 py-0.5 rounded animate-pulse inline-flex items-center gap-1 shadow-sm"><i data-lucide="eye" class="w-3 h-3"></i></span>`;
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "Particular";
if (document.getElementById('detCompany')) document.getElementById('detCompany').innerHTML = companyName + modalAlerts;
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
if(document.getElementById('editName')) document.getElementById('editName').value = clientName;
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
const singlePhone = matchPhone ? matchPhone[0] : "";
if(document.getElementById('editPhone')) document.getElementById('editPhone').value = singlePhone;
const callBtn = document.getElementById('btnCallPhone');
if (callBtn) {
if (singlePhone) { callBtn.href = `tel:+34${singlePhone}`; callBtn.classList.remove('hidden'); }
else { callBtn.classList.add('hidden'); }
}
const fullAddr = `${raw["Dirección"] || ""} ${raw["Población"] || ""}`.trim();
if(document.getElementById('editAddr')) document.getElementById('editAddr').value = fullAddr;
// Usamos la IA limpiadora para el modal también, o dejamos el original si se prefiere ver todo. Aquí usaremos la versión limpia para facilitar lectura.
const descContent = limpiarPaja(raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.");
if(document.getElementById('editDesc')) document.getElementById('editDesc').value = descContent;
// Lógica de paneles
const dbStat = raw.status_operativo;
const statusObj = systemStatuses.find(st => String(st.id) === String(dbStat)) || systemStatuses[0];
const stName = (statusObj?.name || "").toLowerCase();
if (s.automation_status === 'in_progress') {
document.getElementById('panelEnBolsa').classList.remove('hidden');
document.getElementById('panelAsignado').classList.add('hidden');
document.getElementById('panelSinAsignar').classList.add('hidden');
}
else if (s.assigned_name && !stName.includes('asignar') && !stName.includes('desasignado')) {
document.getElementById('panelEnBolsa').classList.add('hidden');
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 = statusObj.id;
} else {
document.getElementById('panelEnBolsa').classList.add('hidden');
document.getElementById('panelAsignado').classList.add('hidden');
document.getElementById('panelSinAsignar').classList.remove('hidden');
const rawGuildId = s.guild_id || raw['guild_id'] || raw.guild_id;
if(rawGuildId) {
document.getElementById('reGremio').value = String(rawGuildId);
loadOps(rawGuildId, 'reOperario');
} else {
document.getElementById('reGremio').value = "";
document.getElementById('reOperario').innerHTML = '<option value="">-- Elija gremio primero --</option>';
}
}
document.getElementById('detailModal').classList.remove('hidden');
if (startInEditMode) enableEditing();
else cancelEditing();
loadChat(id);
lucide.createIcons();
}
function closeDetailModal() { document.getElementById('detailModal').classList.add('hidden'); }
// --- EDICIÓN EN LÍNEA ---
function enableEditing() {
document.getElementById('viewActions').classList.add('hidden');
document.getElementById('editActions').classList.remove('hidden');
['editName', 'editPhone', 'editAddr', 'editDesc'].forEach(id => {
const el = document.getElementById(id);
if(el) {
el.readOnly = false;
el.classList.add('input-editable');
el.classList.remove('input-readonly');
}
});
}
function cancelEditing() {
document.getElementById('viewActions').classList.remove('hidden');
document.getElementById('editActions').classList.add('hidden');
['editName', 'editPhone', 'editAddr', 'editDesc'].forEach(id => {
const el = document.getElementById(id);
if(el) {
el.readOnly = true;
el.classList.add('input-readonly');
el.classList.remove('input-editable');
}
});
}
async function saveFullEdit() {
const id = document.getElementById('detId').value;
const payload = {
name: document.getElementById('editName').value,
phone: document.getElementById('editPhone').value,
address: document.getElementById('editAddr').value,
description: document.getElementById('editDesc').value
};
try {
const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
if (res.ok) {
showToast("✅ Ficha actualizada");
cancelEditing();
refreshData();
}
} catch (e) { showToast("Error al guardar", "warning"); }
}
async function copyClientPortalLink() {
const phone = document.getElementById('editPhone').value;
const name = document.getElementById('editName').value;
const addr = document.getElementById('editAddr').value;
const serviceId = document.getElementById('detId').value;
if (!phone || phone === "Sin Teléfono" || phone.trim() === "") {
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 cleanPhone = phone.replace(/\D/g, "");
const res = await fetch(`${API_URL}/clients/ensure`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ phone: cleanPhone, name: name, address: addr, service_id: serviceId })
});
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}&service=${serviceId}`;
try {
await navigator.clipboard.writeText(portalLink);
showToast("✅ Enlace copiado al portapapeles.");
} catch (err) {
prompt("Tu navegador bloqueó el copiado automático. Cópialo desde aquí:", portalLink);
showToast("Enlace generado con éxito.");
}
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');
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 shrink-0 mt-1";
lucide.createIcons();
}, 3000);
} else {
showToast("Error al generar el enlace.", "warning");
btn.innerHTML = originalHtml;
lucide.createIcons();
}
} catch (error) {
showToast("Error de red al conectar con el servidor", "warning");
btn.innerHTML = originalHtml;
lucide.createIcons();
}
}
// --- ASIGNACIÓN Y AUTOMATISMOS ---
async function stopAutomation() {
const id = document.getElementById('detId').value;
if(!confirm("¿Deseas cancelar la búsqueda del robot para asignar este servicio manualmente?")) return;
try {
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ automation_status: 'manual' })
});
showToast("Bolsa detenida. Ya puedes asignar el servicio.");
closeDetailModal();
refreshData();
} catch (e) { alert("Error al detener el automatismo."); }
}
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;
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa') && !selectedSt.name.toLowerCase().includes('asignar')) {
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 {
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"); refreshData();
} 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 useDelay = localStorage.getItem('wa_delay_enabled') !== 'false';
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"); refreshData(); }
else {
alert(data.error || "No hay operarios en esa zona para ese gremio");
btn.innerHTML = '<i data-lucide="zap" class="w-4 h-4 text-amber-400"></i><span class="font-black uppercase text-[11px] tracking-widest">Lanzar Asignación Automática</span>';
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;
const estadoAsignado = systemStatuses.find(st => st.name.toLowerCase() === 'asignado') || systemStatuses[1];
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' })
});
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({
assigned_to: assigned_to,
assigned_to_name: name,
guild_id: guild_id,
status_operativo: estadoAsignado ? String(estadoAsignado.id) : 'asignado_operario'
})
});
closeDetailModal();
showToast("Asignado correctamente");
refreshData();
} catch (e) { alert("Error en la asignación manual"); }
}
// --- ALTA DE SERVICIOS MANUALES ---
function openCreateModal() {
document.getElementById('createModal').classList.remove('hidden');
document.getElementById('isCompanyCheck').checked = false;
toggleCompanyFields(false);
loadCompaniesForManual();
lucide.createIcons();
}
function closeCreateModal() { document.getElementById('createModal').classList.add('hidden'); }
async function loadCompaniesForManual() {
try {
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const sel = document.getElementById('nCompanySelect');
sel.innerHTML = '<option value="">Seleccionar compañía...</option>';
data.companies.forEach(c => { sel.innerHTML += `<option value="${c.name}">${c.name.toUpperCase()}</option>`; });
} catch(e) {}
}
function toggleCompanyFields(show) {
const fields = document.getElementById('companyFields');
fields.classList.toggle('hidden', !show);
if(!show) {
document.getElementById('nExpRef').value = "";
document.getElementById('refAlert').classList.add('hidden');
}
}
async function searchClientByPhone(phone) {
if (phone.length < 9) { document.getElementById('addrSuggestions').classList.add('hidden'); return; }
try {
const res = await fetch(`${API_URL}/clients/search?phone=${phone}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok && data.client) {
const nameInput = document.getElementById('nName');
if (!nameInput.value) {
nameInput.value = data.client.full_name;
nameInput.classList.add('bg-emerald-50');
}
const addrDiv = document.getElementById('addrSuggestions');
if (data.client.addresses && data.client.addresses.length > 0) {
addrDiv.classList.remove('hidden');
if (!document.getElementById('nAddr').value) { document.getElementById('nAddr').value = data.client.addresses[0]; }
}
}
} catch (e) {}
}
async function checkDuplicateRef(ref) {
if(!ref) return;
const res = await fetch(`${API_URL}/services/check-ref?ref=${ref}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const alertEl = document.getElementById('refAlert');
const inputEl = document.getElementById('nExpRef');
if(data.exists) {
alertEl.classList.remove('hidden');
inputEl.classList.add('border-red-500', 'bg-red-50');
} else {
alertEl.classList.add('hidden');
inputEl.classList.remove('border-red-500', 'bg-red-50');
}
}
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 saveNewService(e) {
e.preventDefault();
const action = e.submitter.value;
const is_company = document.getElementById('isCompanyCheck').checked;
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,
duration_minutes: document.getElementById('nDuration').value,
is_company: is_company,
company_name: is_company ? document.getElementById('nCompanySelect').value : 'Particular',
company_ref: is_company ? document.getElementById('nExpRef').value : null,
mode: action
};
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)
});
if (res.ok) { closeCreateModal(); refreshData(); showToast("✅ Servicio guardado correctamente"); }
} catch(e) { alert("Error al guardar"); }
}
// --- CHAT INTERNO / HISTORIAL ---
async function loadChat(serviceId) {
const chatBox = document.getElementById('chatBox');
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-slate-400 mt-10 uppercase tracking-widest"><i data-lucide="loader-2" class="w-4 h-4 animate-spin mx-auto mb-2"></i> Cargando historial...</div>';
lucide.createIcons();
try {
const res = await fetch(`${API_URL}/services/${serviceId}/chat`, { headers: { 'Authorization': `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
chatBox.innerHTML = '';
if (data.messages.length === 0) {
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-slate-400 mt-10 uppercase tracking-widest">No hay mensajes aún</div>';
return;
}
data.messages.forEach(msg => {
const isMe = msg.sender_role === 'admin' || msg.sender_role === 'superadmin';
const time = new Date(msg.created_at).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
const date = new Date(msg.created_at).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' });
let bubbleClass = isMe ? 'msg-me' : 'msg-other';
let headerColor = isMe ? 'text-emerald-700' : 'text-slate-600';
if (msg.is_internal) { bubbleClass = 'msg-internal'; headerColor = 'text-amber-700'; }
const bubbleHtml = `
<div class="flex flex-col p-3 shadow-sm ${bubbleClass} max-w-[85%]">
<div class="flex justify-between items-center border-b ${msg.is_internal ? 'border-amber-200' : (isMe ? 'border-emerald-200' : 'border-slate-200')} pb-1 mb-1.5 gap-4">
<span class="text-[9px] font-black uppercase ${headerColor} truncate">${msg.sender_name} ${msg.is_internal ? '(OCULTO)' : ''}</span>
<span class="text-[8px] font-bold text-slate-400 shrink-0">${date} ${time}</span>
</div>
<p class="text-xs font-medium text-slate-700 whitespace-pre-wrap">${msg.message}</p>
</div>
`;
chatBox.innerHTML += bubbleHtml;
});
setTimeout(() => { chatBox.scrollTop = chatBox.scrollHeight; }, 100);
}
} catch (e) {
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-red-400 mt-10 uppercase tracking-widest">Error al cargar el historial</div>';
}
}
async function sendChatMessage() {
const serviceId = document.getElementById('detId').value;
const input = document.getElementById('chatInput');
const isInternal = document.getElementById('chatInternal').checked;
const message = input.value.trim();
if (!message) return;
input.disabled = true;
try {
const res = await fetch(`${API_URL}/services/${serviceId}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ message, is_internal: isInternal })
});
if (res.ok) {
input.value = '';
document.getElementById('chatInternal').checked = false;
loadChat(serviceId);
} else {
showToast("Error al enviar mensaje", "warning");
}
} catch (e) {
showToast("Error de conexión", "warning");
} finally {
input.disabled = false;
input.focus();
}
}
</script>
</body>
</html>