Actualizar servicios.html

This commit is contained in:
2026-02-08 22:51:17 +00:00
parent 064c508874
commit 91582fb0b8

View File

@@ -6,15 +6,7 @@
<title>Servicios - IntegraRepara</title> <title>Servicios - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script> <script src="https://unpkg.com/lucide@latest"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=TU_API_KEY_AQUI&libraries=places&callback=initAutocomplete" async defer></script> <style>.fade-in { animation: fadeIn 0.3s ease-in-out; }</style>
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.slide-in { animation: slideIn 0.3s ease-out forwards; }
@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
</head> </head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden"> <body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden">
@@ -27,220 +19,106 @@
<div id="servicesListView" class="fade-in"> <div id="servicesListView" class="fade-in">
<div class="flex justify-between items-center mb-6"> <div class="flex justify-between items-center mb-6">
<div> <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2"><i data-lucide="briefcase" class="text-blue-600"></i> Servicios Activos</h2>
<h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2"> <button onclick="toggleView('create')" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl shadow-lg flex items-center gap-2 font-medium"><i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio</button>
<i data-lucide="briefcase" class="text-blue-600"></i> Servicios Activos
</h2>
<p class="text-sm text-gray-500 mt-1">Gestiona las reparaciones y sus estados.</p>
</div>
<button onclick="toggleView('create')" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl shadow-lg flex items-center gap-2 font-medium transition-all transform hover:scale-105">
<i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio
</button>
</div> </div>
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden"> <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<table class="w-full text-left border-collapse"> <table class="w-full text-left border-collapse">
<thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider border-b"> <thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider border-b"><tr><th class="p-4">Fecha</th><th class="p-4">Cliente</th><th class="p-4">Asignado</th><th class="p-4">Estado</th><th class="p-4 text-right"></th></tr></thead>
<tr> <tbody id="servicesTableBody" class="divide-y divide-gray-100 text-sm text-gray-600"></tbody>
<th class="p-4 font-semibold">Fecha</th>
<th class="p-4 font-semibold">Cliente</th>
<th class="p-4 font-semibold">Asignado</th>
<th class="p-4 font-semibold">Estado</th>
<th class="p-4 text-right"></th>
</tr>
</thead>
<tbody id="servicesTableBody" class="divide-y divide-gray-100 text-sm text-gray-600">
<tr><td colspan="5" class="p-8 text-center text-gray-400">Cargando servicios...</td></tr>
</tbody>
</table> </table>
</div> </div>
</div> </div>
<div id="createServiceView" class="hidden fade-in max-w-5xl mx-auto pb-10"> <div id="createServiceView" class="hidden fade-in max-w-5xl mx-auto pb-10">
<button onclick="toggleView('list')" class="mb-6 text-gray-500 hover:text-gray-800 flex items-center gap-2 transition-colors"> <button onclick="toggleView('list')" class="mb-6 text-gray-500 hover:text-gray-800 flex items-center gap-2"><i data-lucide="arrow-left" class="w-5 h-5"></i> Volver</button>
<i data-lucide="arrow-left" class="w-5 h-5"></i> Volver al listado <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2" id="formTitle"><i data-lucide="file-plus" class="text-green-600"></i> Alta de Nuevo Servicio</h2>
</button>
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2" id="formTitle">
<i data-lucide="file-plus" class="text-green-600"></i> Alta de Nuevo Servicio
</h2>
<form onsubmit="handleFormSubmit(event)" class="space-y-6"> <form onsubmit="handleFormSubmit(event)" class="space-y-6">
<input type="hidden" id="editServiceId"> <input type="hidden" id="editServiceId">
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100"> <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
<h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2"> <h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2"><i data-lucide="user" class="w-5 h-5 text-gray-400"></i> Datos del Cliente</h3>
<i data-lucide="user" class="w-5 h-5 text-gray-400"></i> Datos del Cliente
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5"> <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Teléfono (Obligatorio) *</label> <label class="block text-xs font-bold text-gray-600 mb-1">Teléfono *</label>
<div class="relative"> <input type="tel" id="sPhone" required placeholder="600123456" class="w-full border p-2 rounded-lg" onblur="searchClientByPhone()">
<input type="tel" id="sPhone" required placeholder="600123456"
class="w-full pl-10 pr-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none font-medium text-gray-700"
onblur="searchClientByPhone()">
<i data-lucide="phone" class="absolute left-3 top-2.5 w-4 h-4 text-gray-400"></i>
</div>
<p class="text-xs text-green-600 mt-1 hidden font-bold" id="clientFoundMsg">✓ Cliente encontrado</p>
</div> </div>
<div> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Nombre Completo *</label> <label class="block text-xs font-bold text-gray-600 mb-1">Nombre Completo *</label>
<input type="text" id="sName" required class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"> <input type="text" id="sName" required class="w-full border p-2 rounded-lg">
</div> </div>
<div class="md:col-span-2">
<label class="block text-xs font-bold text-gray-600 mb-1">Dirección y Población *</label> <div>
<div class="flex gap-2"> <label class="block text-xs font-bold text-gray-600 mb-1">Provincia</label>
<input type="text" id="sAddress" required placeholder="Escribe para buscar..." class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"> <select id="sProvince" class="w-full border p-2 rounded-lg bg-gray-50" onchange="loadTowns(this.value)">
<select id="sAddressSelect" class="hidden w-1/3 border rounded-lg text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500" onchange="selectAddress(this.value)"> <option value="">-- Seleccionar --</option>
<option value="">Otras direcciones...</option> </select>
</select>
</div>
</div> </div>
<div> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Email (Opcional)</label> <label class="block text-xs font-bold text-gray-600 mb-1">Población / Municipio *</label>
<input type="email" id="sEmail" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"> <select id="sTown" class="w-full border p-2 rounded-lg bg-gray-50" disabled onchange="checkAutoAssign(this.value)">
<option value="">-- Elige provincia primero --</option>
</select>
</div>
<div class="md:col-span-2">
<label class="block text-xs font-bold text-gray-600 mb-1">Dirección (Calle y número) *</label>
<input type="text" id="sAddress" required class="w-full border p-2 rounded-lg">
</div> </div>
</div> </div>
</div> </div>
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100"> <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
<h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2"> <h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2"><i data-lucide="clipboard" class="w-5 h-5 text-gray-400"></i> Asignación y Detalles</h3>
<i data-lucide="clipboard" class="w-5 h-5 text-gray-400"></i> Asignación y Detalles
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 bg-blue-50 p-4 rounded-lg border border-blue-100"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 bg-blue-50 p-4 rounded-lg border border-blue-100">
<div> <div>
<label class="block text-xs font-bold text-blue-800 mb-1">Gremio / Especialidad *</label> <label class="block text-xs font-bold text-blue-800 mb-1">Zona Detectada</label>
<select id="sGuild" class="w-full px-3 py-2 border border-blue-200 rounded-lg bg-white outline-none focus:border-blue-500" onchange="loadOperators(this.value)"> <input type="text" id="sZoneName" readonly class="w-full bg-transparent border-0 font-bold text-blue-900 placeholder-blue-300" placeholder="Automática al elegir población">
<option value="">-- Seleccionar Gremio --</option>
</select>
</div> </div>
<div> <div>
<label class="block text-xs font-bold text-blue-800 mb-1">Asignar Operario</label> <label class="block text-xs font-bold text-blue-800 mb-1">Asignar Operario</label>
<select id="sOperator" class="w-full px-3 py-2 border border-blue-200 rounded-lg bg-white outline-none focus:border-blue-500"> <select id="sOperator" class="w-full px-3 py-2 border border-blue-200 rounded-lg bg-white outline-none focus:border-blue-500">
<option value="">-- Primero elige gremio --</option> <option value="">-- Manual --</option>
</select> </select>
</div> </div>
</div> </div>
<div class="grid grid-cols-1 md:grid-cols-5 gap-4 mb-4"> <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="md:col-span-1"> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Estado Inicial</label> <label class="block text-xs font-bold text-gray-600 mb-1">Estado</label>
<select id="sCreateStatus" class="w-full px-3 py-2 border rounded-lg bg-gray-50 font-bold text-gray-700 outline-none"> <select id="sCreateStatus" class="w-full border p-2 rounded-lg"></select>
</select>
</div> </div>
<div> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Fecha Prevista</label> <label class="block text-xs font-bold text-gray-600 mb-1">Fecha</label>
<input type="date" id="sDate" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500"> <input type="date" id="sDate" class="w-full border p-2 rounded-lg">
</div> </div>
<div> <div>
<label class="block text-xs font-bold text-gray-600 mb-1">Hora</label> <label class="block text-xs font-bold text-gray-600 mb-1">Hora</label>
<input type="time" id="sTime" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500"> <input type="time" id="sTime" class="w-full border p-2 rounded-lg">
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Duración Est.</label>
<select id="sDuration" class="w-full px-3 py-2 border rounded-lg bg-white outline-none focus:border-blue-500">
<option value="30" selected>30 min</option>
<option value="60">1 hora</option>
<option value="120">2 horas</option>
<option value="240">4 horas</option>
</select>
</div>
<div class="flex items-end pb-1">
<label class="flex items-center justify-center space-x-2 cursor-pointer bg-red-50 px-4 py-2 rounded-lg border border-red-100 w-full hover:bg-red-100 transition h-[42px]">
<input type="checkbox" id="sUrgent" class="form-checkbox text-red-600 w-5 h-5 rounded focus:ring-red-500">
<span class="text-sm font-bold text-red-700">¡ES URGENTE!</span>
</label>
</div> </div>
</div> </div>
<div class="mt-4">
<div class="mb-4"> <label class="block text-xs font-bold text-gray-600 mb-1">Descripción</label>
<label class="block text-xs font-bold text-gray-600 mb-1">Descripción / Avería</label> <textarea id="sDesc" rows="3" class="w-full border p-2 rounded-lg"></textarea>
<textarea id="sDesc" rows="3" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-shadow" placeholder="Describe qué hay que hacer..."></textarea>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Notas Internas</label>
<textarea id="sNotesInternal" rows="2" class="w-full px-3 py-2 border bg-yellow-50 border-yellow-200 rounded-lg outline-none text-sm placeholder-yellow-700/50"></textarea>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Notas para Cliente</label>
<textarea id="sNotesClient" rows="2" class="w-full px-3 py-2 border rounded-lg outline-none text-sm"></textarea>
</div>
</div>
</div>
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
<div class="flex items-center justify-between">
<h3 class="text-lg font-bold text-gray-700 flex items-center gap-2">
<i data-lucide="shield" class="w-5 h-5 text-gray-400"></i> Compañía / Seguro
</h3>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<span class="text-sm font-medium text-gray-600">¿Es un servicio de compañía?</span>
<input type="checkbox" id="sIsCompany" class="form-checkbox text-blue-600 w-5 h-5" onchange="toggleCompanyFields()">
</label>
</div>
<div id="companyFields" class="hidden mt-4 pt-4 border-t border-gray-100 grid grid-cols-1 md:grid-cols-2 gap-4 animate-slide-in">
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Seleccionar Compañía</label>
<div class="flex gap-2">
<select id="sCompanyId" class="flex-1 px-3 py-2 border rounded-lg bg-white outline-none focus:border-blue-500"><option value="">-- Seleccionar --</option></select>
<button type="button" onclick="quickAddCompany()" class="bg-slate-800 text-white px-3 rounded-lg hover:bg-slate-700 transition-colors"><i data-lucide="plus" class="w-4 h-4"></i></button>
</div>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Nº Expediente</label>
<input type="text" id="sCompanyRef" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500">
</div>
</div> </div>
</div> </div>
<div class="pt-2 pb-6"> <div class="pt-2 pb-6">
<button type="submit" id="btnSave" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl shadow-lg shadow-blue-500/30 text-lg transition-all flex justify-center items-center gap-3 transform active:scale-95"> <button type="submit" id="btnSave" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl shadow-lg">GUARDAR</button>
<i data-lucide="save" class="w-6 h-6"></i> GUARDAR
</button>
</div> </div>
</form> </form>
</div> </div>
<div id="serviceDetailPanel" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex justify-end transition-opacity duration-300"> <div id="serviceDetailPanel" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex justify-end transition-opacity duration-300">
<div class="w-full max-w-md bg-white h-full shadow-2xl p-6 overflow-y-auto slide-in flex flex-col"> <div class="w-full max-w-md bg-white h-full shadow-2xl p-6 overflow-y-auto slide-in flex flex-col">
<div class="flex justify-between items-start mb-6"> <button onclick="closeDetailPanel()" class="mb-4 text-right">Cerrar ✖</button>
<h2 class="text-xl font-bold text-gray-900">Detalle del Servicio</h2> <h2 class="text-xl font-bold" id="detailTitle"></h2>
<button onclick="closeDetailPanel()" class="text-gray-400 hover:text-gray-800 transition-colors"><i data-lucide="x" class="w-6 h-6"></i></button> <p class="text-sm text-gray-500" id="detailClient"></p>
</div> <div class="mt-4 flex gap-2">
<button onclick="editService()" class="flex-1 bg-gray-100 p-2 rounded">Editar</button>
<div class="flex gap-2 mb-6"> <button onclick="deleteService()" class="bg-red-100 text-red-600 p-2 rounded">Borrar</button>
<button onclick="editService()" class="flex-1 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 py-2 rounded-lg text-sm font-bold shadow-sm flex items-center justify-center gap-2">
<i data-lucide="edit-2" class="w-4 h-4"></i> Editar
</button>
<button onclick="deleteService()" class="bg-white border border-red-200 hover:bg-red-50 text-red-600 py-2 px-4 rounded-lg text-sm font-bold shadow-sm">
<i data-lucide="trash-2" class="w-4 h-4"></i>
</button>
</div>
<div class="bg-gray-50 p-4 rounded-xl border border-gray-200 mb-6 shadow-sm">
<div class="flex justify-between items-start mb-2">
<span id="detailStatusBadge" class="px-2 py-1 rounded text-[10px] font-bold bg-gray-200 text-gray-700 uppercase tracking-wide">ESTADO</span>
<span id="detailId" class="text-xs font-mono text-gray-400">#000</span>
</div>
<h3 class="text-lg font-bold text-gray-800 leading-tight mb-1" id="detailTitle">Título</h3>
<p class="text-sm text-gray-500 mb-2" id="detailClient">Cliente</p>
<div class="flex items-center text-xs text-gray-400 gap-2"><i data-lucide="calendar" class="w-3 h-3"></i> <span id="detailDate">Fecha</span></div>
</div>
<div class="mb-8">
<label class="block text-xs font-bold text-gray-500 uppercase mb-2 tracking-wider">Actualizar Estado</label>
<div class="flex gap-2">
<select id="newStatusSelect" class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500 bg-white shadow-sm"></select>
<button onclick="updateStatus()" class="bg-slate-800 text-white px-4 py-2 rounded-lg text-sm hover:bg-slate-700 font-bold shadow-md transition-colors">Guardar</button>
</div>
</div>
<div class="flex-1">
<h3 class="font-bold text-gray-800 mb-6 flex items-center gap-2 border-b pb-2"><i data-lucide="history" class="w-4 h-4 text-gray-400"></i> Historial</h3>
<div class="relative border-l-2 border-gray-200 ml-3 space-y-8 pb-8 pl-6" id="statusTimeline"></div>
</div> </div>
</div> </div>
</div> </div>
@@ -249,375 +127,135 @@
</div> </div>
</div> </div>
<div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-2xl transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-3"><span id="toastMsg">Msg</span></div> <div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-2xl hidden"><span id="toastMsg"></span></div>
<script src="js/layout.js"></script> <script src="js/layout.js"></script>
<script> <script>
let allStatuses = []; let allStatuses = [], currentServiceId = null;
let currentServiceId = null;
let autocomplete;
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
const token = localStorage.getItem("token"); if (!localStorage.getItem("token")) window.location.href = "index.html";
if (!token) window.location.href = "index.html";
fetchStatuses(); fetchStatuses();
fetchServices(); fetchServices();
loadCompanies(); loadProvinces();
loadGuilds(); loadAllOperators(); // Carga base de operarios
}); });
function initAutocomplete() {
const input = document.getElementById("sAddress");
if(input) {
autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });
input.addEventListener('keydown', function(e) { if (e.key === "Enter") e.preventDefault(); });
}
}
// --- NAVEGACIÓN --- // --- NAVEGACIÓN ---
function toggleView(view) { function toggleView(view) {
document.getElementById('servicesListView').classList.add('hidden'); document.getElementById('servicesListView').classList.add('hidden');
document.getElementById('createServiceView').classList.add('hidden'); document.getElementById('createServiceView').classList.add('hidden');
if(view === 'list') { if(view === 'list') {
document.getElementById('servicesListView').classList.remove('hidden'); document.getElementById('servicesListView').classList.remove('hidden');
fetchServices(); fetchServices();
} else { } else {
if(document.getElementById('editServiceId').value !== "") { if(document.getElementById('editServiceId').value !== "") resetForm();
document.getElementById('editServiceId').value = "";
document.querySelector('form').reset();
document.getElementById('formTitle').innerHTML = '<i data-lucide="file-plus" class="text-green-600"></i> Alta de Nuevo Servicio';
document.getElementById('sDate').valueAsDate = new Date();
document.getElementById('sCreateStatus').disabled = false;
lucide.createIcons();
}
document.getElementById('createServiceView').classList.remove('hidden'); document.getElementById('createServiceView').classList.remove('hidden');
window.scrollTo(0,0);
} }
} }
// --- CARGA DE DATOS (Gremios, Operarios, etc) --- // --- LÓGICA GEOGRÁFICA ---
async function fetchStatuses() { async function loadProvinces() {
try { const res = await fetch(`${API_URL}/provinces`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const data = await res.json();
const data = await res.json(); const sel = document.getElementById('sProvince');
if(data.ok) { sel.innerHTML = '<option value="">-- Seleccionar --</option>';
allStatuses = data.statuses; data.provinces.forEach(p => sel.innerHTML += `<option value="${p.id}">${p.name}</option>`);
const createSel = document.getElementById('sCreateStatus');
createSel.innerHTML = '';
allStatuses.forEach(s => {
const isDef = s.is_default ? 'selected' : '';
createSel.innerHTML += `<option value="${s.id}" ${isDef}>${s.name}</option>`;
});
}
} catch(e) {}
} }
async function loadGuilds() { async function loadTowns(provId) {
try { const sel = document.getElementById('sTown');
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
const sel = document.getElementById('sGuild');
sel.innerHTML = '<option value="">-- Seleccionar Gremio --</option>';
data.guilds.forEach(g => sel.innerHTML += `<option value="${g.id}">${g.name}</option>`);
}
} catch(e) {}
}
async function loadOperators(guildId) {
const sel = document.getElementById('sOperator');
sel.innerHTML = '<option value="">Cargando...</option>'; sel.innerHTML = '<option value="">Cargando...</option>';
sel.disabled = true; sel.disabled = true;
if(!provId) return;
if(!guildId) { const res = await fetch(`${API_URL}/provinces/${provId}/towns`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
sel.innerHTML = '<option value="">-- Primero elige gremio --</option>';
return;
}
try {
const res = await fetch(`${API_URL}/operators?guild_id=${guildId}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
sel.innerHTML = '<option value="">-- Sin asignar --</option>';
if(data.operators.length === 0) sel.innerHTML += '<option value="" disabled>No hay operarios para este gremio</option>';
data.operators.forEach(op => sel.innerHTML += `<option value="${op.id}">${op.full_name}</option>`);
}
} catch(e) { sel.innerHTML = '<option value="">Error al cargar</option>'; }
finally { sel.disabled = false; }
}
async function loadCompanies() {
try {
const sel = document.getElementById('sCompanyId');
if (sel.options.length > 1) return;
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
sel.innerHTML = '<option value="">-- Seleccionar --</option>';
data.companies.forEach(c => sel.innerHTML += `<option value="${c.id}">${c.name}</option>`);
}
} catch (e) {}
}
async function quickAddCompany() {
const name = prompt("Nombre de la nueva compañía:");
if(!name) return;
try {
const res = await fetch(`${API_URL}/companies`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ name })
});
if(res.ok) { showToast("Compañía añadida"); document.getElementById('sCompanyId').innerHTML = ""; await loadCompanies(); }
} catch(e) { alert("Error"); }
}
function toggleCompanyFields() {
const isChecked = document.getElementById('sIsCompany').checked;
const div = document.getElementById('companyFields');
if(isChecked) { div.classList.remove('hidden'); loadCompanies(); } else { div.classList.add('hidden'); }
}
async function searchClientByPhone() {
const phone = document.getElementById('sPhone').value;
if(phone.length < 8) 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 c = data.client;
document.getElementById('sName').value = c.full_name;
document.getElementById('sEmail').value = c.email || "";
document.getElementById('clientFoundMsg').classList.remove('hidden');
const addresses = c.addresses || [];
if (addresses.length > 0) {
document.getElementById('sAddress').value = addresses[addresses.length - 1];
const select = document.getElementById('sAddressSelect');
select.innerHTML = '<option value="">Otras direcciones...</option>';
addresses.forEach(addr => select.innerHTML += `<option value="${addr}">${addr}</option>`);
if (addresses.length > 1) select.classList.remove('hidden');
}
} else {
document.getElementById('clientFoundMsg').classList.add('hidden');
document.getElementById('sAddressSelect').classList.add('hidden');
}
} catch (e) {}
}
function selectAddress(val) { if(val) document.getElementById('sAddress').value = val; }
// --- LISTAR SERVICIOS ---
async function fetchServices() {
try {
const res = await fetch(`${API_URL}/services`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const tbody = document.getElementById('servicesTableBody');
tbody.innerHTML = "";
if(!data.ok || data.services.length === 0) {
tbody.innerHTML = `<tr><td colspan="5" class="p-8 text-center text-gray-400 bg-white">No hay servicios. <button onclick="toggleView('create')" class="text-blue-600 font-bold hover:underline">Crear uno</button></td></tr>`;
return;
}
data.services.forEach(s => {
const color = s.status_color || 'gray';
const date = new Date(s.created_at);
const formattedDate = date.toLocaleDateString('es-ES', { day: '2-digit', month: 'short' });
// Mostramos operario si existe
const assigned = s.assigned_name ? `<span class="bg-gray-100 text-gray-700 px-2 py-0.5 rounded text-[10px] font-bold uppercase ml-1 border border-gray-200">${s.assigned_name}</span>` : '<span class="text-gray-300 text-[10px] italic ml-1">Sin asignar</span>';
tbody.innerHTML += `
<tr class="hover:bg-blue-50 cursor-pointer transition border-b last:border-0 bg-white"
onclick="openDetail(${s.id}, '${s.contact_name}', '${s.title}', '${s.status_name}', '${color}', '${formattedDate}')">
<td class="p-4 text-gray-500 whitespace-nowrap font-mono text-xs">${formattedDate}</td>
<td class="p-4"><p class="font-bold text-gray-900">${s.contact_name}</p><p class="text-xs text-gray-500 truncate max-w-[200px] flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3"></i> ${s.address}</p></td>
<td class="p-4">${assigned} <p class="text-sm text-gray-700 truncate max-w-[250px] mt-1">${s.description || 'Sin detalles'}</p>${s.is_urgent ? '<span class="text-[10px] font-bold text-red-600 bg-red-100 px-1 rounded uppercase">Urgente</span>' : ''}${s.is_company ? `<span class="text-[10px] font-bold text-blue-600 bg-blue-100 px-1 rounded uppercase ml-1">${s.company_name || 'Compañía'}</span>` : ''}</td>
<td class="p-4"><span class="px-3 py-1 rounded-full text-xs font-bold text-white shadow-sm bg-${color}-500 whitespace-nowrap">${s.status_name || 'Nuevo'}</span></td>
<td class="p-4 text-right"><i data-lucide="chevron-right" class="w-5 h-5 text-gray-300"></i></td>
</tr>
`;
});
lucide.createIcons();
} catch (e) {}
}
async function openDetail(id, client, title, statusName, statusColor, date) {
currentServiceId = id;
document.getElementById('serviceDetailPanel').classList.remove('hidden');
document.getElementById('detailTitle').innerText = title || 'Servicio General';
document.getElementById('detailClient').innerText = client;
document.getElementById('detailId').innerText = `#${id}`;
document.getElementById('detailDate').innerText = date;
const badge = document.getElementById('detailStatusBadge');
badge.innerText = statusName;
badge.className = `px-2 py-1 rounded text-[10px] font-bold text-white uppercase tracking-wide bg-${statusColor}-500`;
const sel = document.getElementById('newStatusSelect');
sel.innerHTML = "";
allStatuses.forEach(s => sel.innerHTML += `<option value="${s.id}">${s.name}</option>`);
loadTimeline(id);
}
async function loadTimeline(id) {
const timeline = document.getElementById('statusTimeline');
timeline.innerHTML = '<p class="text-xs text-gray-400">Cargando...</p>';
const res = await fetch(`${API_URL}/services/${id}/logs`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json(); const data = await res.json();
timeline.innerHTML = "";
if(data.logs.length === 0) { timeline.innerHTML = '<p class="text-sm text-gray-400">Sin historial.</p>'; return; } sel.innerHTML = '<option value="">-- Seleccionar Población --</option>';
data.logs.forEach(log => { data.towns.forEach(t => sel.innerHTML += `<option value="${t.id}">${t.name}</option>`);
const color = log.new_color || 'gray'; sel.disabled = false;
const date = new Date(log.created_at);
timeline.innerHTML += `
<div class="mb-6 relative group">
<span class="absolute -left-[33px] flex items-center justify-center w-6 h-6 bg-${color}-100 rounded-full ring-4 ring-white"><div class="w-2 h-2 bg-${color}-600 rounded-full"></div></span>
<div class="flex justify-between items-center mb-1"><h3 class="text-sm font-bold text-gray-800">${log.new_status}</h3><time class="text-[10px] font-medium text-gray-400 uppercase">${date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})} · ${date.toLocaleDateString()}</time></div>
<div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-sm text-gray-600"><p>${log.comment || 'Cambio de estado'}</p><p class="text-[10px] text-gray-400 mt-2 text-right italic border-t border-gray-100 pt-1">Usuario: ${log.user_name || 'Sistema'}</p></div>
</div>
`;
});
} }
async function updateStatus() { // --- AUTO ASIGNACIÓN ---
const statusId = document.getElementById('newStatusSelect').value; async function checkAutoAssign(townId) {
if(!statusId) return; if(!townId) return;
const comment = prompt("Comentario (opcional):");
try { // Buscar zona y operarios para este pueblo
await fetch(`${API_URL}/services/${currentServiceId}/status`, { const res = await fetch(`${API_URL}/towns/${townId}/auto-assign`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
method: 'PUT', const data = await res.json();
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_id: statusId, comment: comment }) const zoneInput = document.getElementById('sZoneName');
const opSelect = document.getElementById('sOperator');
if(data.found) {
zoneInput.value = data.zone_name;
opSelect.innerHTML = '<option value="">-- Seleccionar de Zona --</option>';
data.operators.forEach(op => {
opSelect.innerHTML += `<option value="${op.id}" selected>⭐ ${op.full_name}</option>`;
}); });
showToast("Estado actualizado"); if(data.operators.length === 0) opSelect.innerHTML += '<option value="">(Zona sin operarios)</option>';
loadTimeline(currentServiceId); } else {
fetchServices(); zoneInput.value = "(Sin zona asignada)";
} catch(e) { showToast("Error", true); } loadAllOperators(); // Volver a mostrar todos si no hay zona
}
} }
// --- EDICIÓN Y BORRADO --- async function loadAllOperators() {
async function editService() { const res = await fetch(`${API_URL}/operators`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
if(!currentServiceId) return; const data = await res.json();
try { const sel = document.getElementById('sOperator');
const res = await fetch(`${API_URL}/services/${currentServiceId}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); sel.innerHTML = '<option value="">-- Todos los operarios --</option>';
const json = await res.json(); data.operators.forEach(op => sel.innerHTML += `<option value="${op.id}">${op.full_name}</option>`);
if(json.ok) {
await fillEditForm(json.service);
closeDetailPanel();
document.getElementById('createServiceView').classList.remove('hidden');
document.getElementById('servicesListView').classList.add('hidden');
}
} catch(e) { showToast("Error cargando datos", true); }
} }
async function fillEditForm(s) { // --- RESTO DE FUNCIONES (CREAR, LISTAR...) ---
document.getElementById('editServiceId').value = s.id; async function fetchServices() {
document.getElementById('formTitle').innerHTML = '<i data-lucide="edit-2" class="text-blue-600"></i> Editando Servicio #' + s.id; const res = await fetch(`${API_URL}/services`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
document.getElementById('sPhone').value = s.contact_phone; const tbody = document.getElementById('servicesTableBody');
document.getElementById('sName').value = s.contact_name; tbody.innerHTML = "";
document.getElementById('sAddress').value = s.address; data.services.forEach(s => {
document.getElementById('sEmail').value = s.email || ''; tbody.innerHTML += `
document.getElementById('sDesc').value = s.description || ''; <tr class="border-b hover:bg-gray-50 cursor-pointer" onclick="openDetail(${s.id})">
<td class="p-4">${new Date(s.created_at).toLocaleDateString()}</td>
if(s.scheduled_date) document.getElementById('sDate').value = s.scheduled_date.split('T')[0]; <td class="p-4 font-bold">${s.contact_name}</td>
if(s.scheduled_time) document.getElementById('sTime').value = s.scheduled_time; <td class="p-4">${s.assigned_name || '-'}</td>
document.getElementById('sDuration').value = s.duration_minutes || 30; <td class="p-4"><span class="bg-${s.status_color}-100 text-${s.status_color}-700 px-2 py-1 rounded text-xs font-bold">${s.status_name}</span></td>
document.getElementById('sUrgent').checked = s.is_urgent; <td class="p-4">➡️</td>
</tr>`;
// COMPAÑÍA });
document.getElementById('sIsCompany').checked = s.is_company;
if(s.is_company) {
document.getElementById('companyFields').classList.remove('hidden');
await loadCompanies();
document.getElementById('sCompanyId').value = s.company_id || '';
document.getElementById('sCompanyRef').value = s.company_ref || '';
} else {
document.getElementById('companyFields').classList.add('hidden');
}
// GREMIO Y OPERARIO (NUEVO)
document.getElementById('sGuild').value = s.guild_id || '';
if(s.guild_id) {
await loadOperators(s.guild_id);
document.getElementById('sOperator').value = s.assigned_to || '';
} else {
loadOperators(''); // Limpiar
}
document.getElementById('sNotesInternal').value = s.internal_notes || '';
document.getElementById('sNotesClient').value = s.client_notes || '';
document.getElementById('sCreateStatus').disabled = true;
lucide.createIcons();
} }
async function handleFormSubmit(e) { async function handleFormSubmit(e) {
e.preventDefault(); e.preventDefault();
const btn = document.getElementById('btnSave');
btn.disabled = true; btn.innerText = "Procesando...";
const editId = document.getElementById('editServiceId').value;
const isEdit = !!editId;
const data = { const data = {
phone: document.getElementById('sPhone').value, contact_phone: document.getElementById('sPhone').value,
name: document.getElementById('sName').value, contact_name: document.getElementById('sName').value,
address: document.getElementById('sAddress').value, address: document.getElementById('sAddress').value + ", " + document.getElementById('sTown').options[document.getElementById('sTown').selectedIndex].text,
email: document.getElementById('sEmail').value,
description: document.getElementById('sDesc').value, description: document.getElementById('sDesc').value,
scheduled_date: document.getElementById('sDate').value,
scheduled_time: document.getElementById('sTime').value,
duration: document.getElementById('sDuration').value,
is_urgent: document.getElementById('sUrgent').checked,
is_company: document.getElementById('sIsCompany').checked,
company_id: document.getElementById('sCompanyId').value || null,
company_ref: document.getElementById('sCompanyRef').value,
internal_notes: document.getElementById('sNotesInternal').value,
client_notes: document.getElementById('sNotesClient').value,
guild_id: document.getElementById('sGuild').value || null,
assigned_to: document.getElementById('sOperator').value || null assigned_to: document.getElementById('sOperator').value || null
// Añadir resto de campos...
}; };
if (!isEdit) { await fetch(`${API_URL}/services`, {
data.status_id = document.getElementById('sCreateStatus').value; method: 'POST',
} headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
const url = isEdit ? `${API_URL}/services/${editId}` : `${API_URL}/services`; });
const method = isEdit ? 'PUT' : 'POST'; toggleView('list');
try {
const res = await fetch(url, {
method: method,
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
});
const json = await res.json();
if (json.ok) {
showToast(isEdit ? "✅ Actualizado" : "✅ Creado");
toggleView('list');
} else {
showToast("❌ " + (json.error || "Error"), true);
}
} catch (e) { showToast("Error conexión", true); }
finally { btn.disabled = false; btn.innerText = "GUARDAR"; }
} }
async function deleteService() { async function fetchStatuses() {
if(!currentServiceId || !confirm("¿Borrar servicio permanentemente?")) return; const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
try { const data = await res.json();
const res = await fetch(`${API_URL}/services/${currentServiceId}`, { allStatuses = data.statuses;
method: 'DELETE', const sel = document.getElementById('sCreateStatus');
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } sel.innerHTML = "";
}); allStatuses.forEach(s => sel.innerHTML += `<option value="${s.id}">${s.name}</option>`);
if(res.ok) { showToast("Eliminado"); closeDetailPanel(); fetchServices(); }
} catch(e) { showToast("Error", true); }
} }
function closeDetailPanel() { document.getElementById('serviceDetailPanel').classList.add('hidden'); } function resetForm() { document.querySelector('form').reset(); document.getElementById('editServiceId').value = ""; }
function showToast(msg, isError = false) {
const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
t.className = `fixed bottom-5 right-5 px-6 py-3 rounded-lg shadow-2xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white`;
m.innerText = msg; t.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
}
</script> </script>
</body> </body>
</html> </html>