Actualizar servicios.html

This commit is contained in:
2026-02-08 12:22:43 +00:00
parent a2529197dd
commit c04d5d014d

View File

@@ -9,15 +9,18 @@
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
/* Animación para el panel lateral */
.slide-in { animation: slideIn 0.3s ease-out forwards; }
@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
/* Ocultar scrollbar en panel lateral pero permitir scroll */
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden">
<div class="flex h-screen overflow-hidden">
<div id="sidebar-container" class="h-full"></div>
<div class="flex-1 flex flex-col overflow-hidden relative">
<div id="header-container"></div>
@@ -25,11 +28,14 @@
<div id="servicesListView" class="fade-in">
<div class="flex justify-between items-center mb-6">
<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>
<button onclick="toggleView('create')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2">
<i data-lucide="plus"></i> Nuevo Servicio
<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>
<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>
@@ -37,61 +43,207 @@
<table class="w-full text-left border-collapse">
<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 / Dirección</th>
<th class="p-4">Asunto</th>
<th class="p-4">Estado Actual</th>
<th class="p-4 font-semibold">Fecha</th>
<th class="p-4 font-semibold">Cliente / Dirección</th>
<th class="p-4 font-semibold">Detalle</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">
<tr><td colspan="5" class="p-6 text-center text-gray-400">Cargando servicios...</td></tr>
<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>
</div>
</div>
<div id="createServiceView" class="hidden fade-in max-w-5xl mx-auto">
<button onclick="toggleView('list')" class="mb-4 text-gray-500 hover:text-gray-800 flex items-center gap-2"><i data-lucide="arrow-left"></i> Volver al listado</button>
<div class="bg-white p-8 rounded-xl shadow-lg border border-gray-100">
<h2 class="text-xl font-bold mb-6">Nuevo Servicio</h2>
<form onsubmit="createService(event)" class="space-y-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div><label class="text-xs font-bold block mb-1">Teléfono</label><input type="tel" id="sPhone" class="w-full border rounded p-2" onblur="searchClientByPhone()" required></div>
<div><label class="text-xs font-bold block mb-1">Nombre</label><input type="text" id="sName" class="w-full border rounded p-2" required></div>
<div class="col-span-2"><label class="text-xs font-bold block mb-1">Dirección</label><input type="text" id="sAddress" class="w-full border rounded p-2" required></div>
<div><label class="text-xs font-bold block mb-1">Email</label><input type="email" id="sEmail" class="w-full border rounded p-2"></div>
<div class="col-span-2"><label class="text-xs font-bold block mb-1">Descripción</label><textarea id="sDesc" class="w-full border rounded p-2"></textarea></div>
<input type="hidden" id="sDate"><input type="hidden" id="sTime"><input type="hidden" id="sDuration"><input type="checkbox" id="sUrgent" class="hidden"><input type="checkbox" id="sIsCompany" class="hidden">
<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">
<i data-lucide="arrow-left" class="w-5 h-5"></i> Volver al listado
</button>
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
<i data-lucide="file-plus" class="text-green-600"></i> Alta de Nuevo Servicio
</h2>
<form onsubmit="createService(event)" class="space-y-6">
<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">
<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>
<label class="block text-xs font-bold text-gray-600 mb-1">Teléfono (Obligatorio) *</label>
<div class="relative">
<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>
<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">
</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 class="flex gap-2">
<input type="text" id="sAddress" required placeholder="Calle Mayor 1, Madrid" class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
<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="">Otras direcciones...</option>
</select>
</div>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Email (Opcional)</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">
</div>
</div>
<button type="submit" id="btnSave" class="w-full bg-blue-600 text-white font-bold py-3 rounded mt-4">Crear Servicio</button>
</form>
</div>
</div>
<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">
<i data-lucide="clipboard" class="w-5 h-5 text-gray-400"></i> Detalles del Trabajo
</h3>
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Fecha Prevista</label>
<input type="date" id="sDate" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500">
</div>
<div>
<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">
</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="15">15 min</option>
<option value="30" selected>30 min</option>
<option value="45">45 min</option>
<option value="60">1 hora</option>
<option value="90">1h 30m</option>
<option value="120">2 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 class="mb-4">
<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 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 flex justify-between">
<span>Notas Internas</span>
<span class="text-gray-400 font-normal text-[10px] uppercase">Solo Oficina</span>
</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" placeholder="Código alarma, llaves en portería..."></textarea>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1 flex justify-between">
<span>Notas para Cliente</span>
<span class="text-gray-400 font-normal text-[10px] uppercase">Visible en Parte</span>
</label>
<textarea id="sNotesClient" rows="2" class="w-full px-3 py-2 border rounded-lg outline-none text-sm" placeholder="Recomendaciones, observaciones..."></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>
<div class="relative">
<input type="checkbox" id="sIsCompany" class="peer sr-only" onchange="toggleCompanyFields()">
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
</div>
</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" title="Añadir nueva compañía">
<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 / Referencia</label>
<input type="text" id="sCompanyRef" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500" placeholder="Ej: SIN-2024-8892">
</div>
</div>
</div>
<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">
<i data-lucide="save" class="w-6 h-6"></i> CREAR SERVICIO
</button>
</div>
</form>
</div>
<div id="serviceDetailPanel" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex justify-end">
<div class="w-full max-w-md bg-white h-full shadow-2xl p-6 overflow-y-auto slide-in">
<button onclick="closeDetailPanel()" class="mb-4 text-gray-500 hover:text-black flex items-center gap-2"><i data-lucide="x"></i> Cerrar</button>
<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="border-b pb-4 mb-6">
<span id="detailStatusBadge" class="px-2 py-1 rounded text-xs font-bold bg-gray-200 text-gray-700 uppercase mb-2 inline-block">Estado</span>
<h2 class="text-xl font-bold text-gray-900" id="detailTitle">Servicio #ID</h2>
<p class="text-sm text-gray-500" id="detailClient">Cliente</p>
<div class="flex justify-between items-start mb-6">
<h2 class="text-xl font-bold text-gray-900">Detalle del Servicio</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>
</div>
<div class="bg-gray-50 p-4 rounded-lg border border-gray-200 mb-8">
<label class="block text-xs font-bold text-gray-500 uppercase mb-2">Cambiar Estado</label>
<div class="flex gap-2">
<select id="newStatusSelect" class="flex-1 border rounded px-2 text-sm outline-none focus:border-blue-500 bg-white"></select>
<button onclick="updateStatus()" class="bg-slate-800 text-white px-4 py-2 rounded text-sm hover:bg-slate-700 font-medium">Actualizar</button>
<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>
<h3 class="font-bold text-gray-800 mb-4 flex items-center gap-2"><i data-lucide="history"></i> Mapa de Cambios</h3>
<div class="relative border-l-2 border-gray-200 ml-3 space-y-8 pb-8" id="statusTimeline">
<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 de Cambios
</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>
@@ -109,21 +261,32 @@
document.addEventListener("DOMContentLoaded", () => {
const token = localStorage.getItem("token");
if (!token) window.location.href = "index.html";
// Valores por defecto
document.getElementById('sDate').valueAsDate = new Date();
const now = new Date();
document.getElementById('sTime').value = now.toTimeString().slice(0,5);
fetchStatuses();
fetchServices();
loadCompanies();
});
// --- NAVEGACIÓN ---
function toggleView(view) {
document.getElementById('servicesListView').classList.add('hidden');
document.getElementById('createServiceView').classList.add('hidden');
if(view === 'list') {
document.getElementById('servicesListView').classList.remove('hidden');
fetchServices();
fetchServices(); // Recargar lista al volver
} else {
document.getElementById('createServiceView').classList.remove('hidden');
window.scrollTo(0,0);
}
}
// --- DATOS MAESTROS ---
async function fetchStatuses() {
try {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
@@ -132,6 +295,32 @@
} catch(e) {}
}
async function loadCompanies() {
try {
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
const sel = document.getElementById('sCompanyId');
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"); loadCompanies(); }
} catch(e) { alert("Error"); }
}
// --- LÓGICA DE SERVICIOS (LISTAR) ---
async function fetchServices() {
try {
const res = await fetch(`${API_URL}/services`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
@@ -139,16 +328,35 @@
const tbody = document.getElementById('servicesTableBody');
tbody.innerHTML = "";
if(data.services.length === 0) { tbody.innerHTML = `<tr><td colspan="5" class="p-6 text-center text-gray-400">No hay servicios registrados.</td></tr>`; return; }
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 registrados. <button onclick="toggleView('create')" class="text-blue-600 font-bold hover:underline">Crear el primero</button></td></tr>`;
return;
}
data.services.forEach(s => {
const color = s.status_color || 'gray';
// Parse fecha
const date = new Date(s.created_at);
const formattedDate = date.toLocaleDateString('es-ES', { day: '2-digit', month: 'short' });
tbody.innerHTML += `
<tr class="hover:bg-gray-50 cursor-pointer transition" onclick="openDetail(${s.id}, '${s.contact_name}', '${s.title}', '${s.status_name}', '${color}')">
<td class="p-4 text-gray-500">${new Date(s.created_at).toLocaleDateString()}</td>
<td class="p-4 font-medium text-gray-900">${s.contact_name}<br><span class="text-xs text-gray-400 font-normal">${s.address}</span></td>
<td class="p-4 text-gray-600">${s.title}</td>
<td class="p-4"><span class="px-2 py-1 rounded text-xs font-bold text-white bg-${color}-500 shadow-sm">${s.status_name || 'Nuevo'}</span></td>
<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">
<p class="text-sm text-gray-700 truncate max-w-[250px]">${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>
`;
@@ -157,46 +365,148 @@
} catch (e) { console.error(e); }
}
async function openDetail(id, client, title, statusName, statusColor) {
// --- LÓGICA DE CREAR ---
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) { console.error(e); }
}
function selectAddress(val) { if(val) document.getElementById('sAddress').value = val; }
async function createService(e) {
e.preventDefault();
const btn = document.getElementById('btnSave');
btn.disabled = true; btn.innerText = "Guardando...";
const data = {
phone: document.getElementById('sPhone').value,
name: document.getElementById('sName').value,
address: document.getElementById('sAddress').value,
email: document.getElementById('sEmail').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
};
try {
const res = await fetch(`${API_URL}/services`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
});
const json = await res.json();
if (json.ok) {
showToast("✅ Servicio Creado");
document.querySelector('form').reset(); // Limpiar
toggleView('list'); // Volver
} else {
showToast("❌ " + json.error, true);
}
} catch (e) {
showToast("Error de conexión", true);
} finally {
btn.disabled = false; btn.innerHTML = '<i data-lucide="save" class="w-6 h-6"></i> CREAR SERVICIO'; lucide.createIcons();
}
}
// --- LÓGICA DE DETALLE Y ESTADOS ---
async function openDetail(id, client, title, statusName, statusColor, date) {
currentServiceId = id;
document.getElementById('serviceDetailPanel').classList.remove('hidden');
document.getElementById('detailTitle').innerText = title;
// Llenar datos cabecera
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-xs font-bold text-white mb-2 inline-block bg-${statusColor}-500`;
// Limpiar clases previas de color
badge.className = `px-2 py-1 rounded text-[10px] font-bold text-white uppercase tracking-wide bg-${statusColor}-500`;
// Llenar select
// Llenar selector de estados
const sel = document.getElementById('newStatusSelect');
sel.innerHTML = "";
allStatuses.forEach(s => {
sel.innerHTML += `<option value="${s.id}">${s.name}</option>`;
});
// Cargar Mapa de Estados
// Cargar Historial
loadTimeline(id);
}
async function loadTimeline(id) {
const timeline = document.getElementById('statusTimeline');
timeline.innerHTML = '<p class="text-xs text-gray-400 ml-4">Cargando historial...</p>';
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();
timeline.innerHTML = "";
if(data.logs.length === 0) { timeline.innerHTML = '<p class="text-sm text-gray-400">Sin historial registrado.</p>'; return; }
data.logs.forEach(log => {
const color = log.new_color || 'gray';
const date = new Date(log.created_at);
timeline.innerHTML += `
<div class="mb-6 ml-6 relative group">
<span class="absolute -left-9 flex items-center justify-center w-6 h-6 bg-${color}-100 rounded-full ring-4 ring-white group-hover:bg-${color}-200 transition">
<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 group-hover:scale-110 transition-transform">
<div class="w-2 h-2 bg-${color}-600 rounded-full"></div>
</span>
<h3 class="flex items-center mb-1 text-sm font-bold text-gray-800">${log.new_status}</h3>
<time class="block mb-2 text-xs font-medium text-gray-400 uppercase tracking-wide">${new Date(log.created_at).toLocaleString()}</time>
<div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-sm text-gray-600">
<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 hover:bg-white hover:shadow-sm transition-all">
<p>${log.comment || 'Cambio de estado'}</p>
<p class="text-xs text-gray-400 mt-2 text-right italic">Por: ${log.user_name || 'Sistema'}</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>
`;
@@ -205,6 +515,7 @@
async function updateStatus() {
const statusId = document.getElementById('newStatusSelect').value;
if(!statusId) return;
const comment = prompt("Añade un comentario sobre este cambio (opcional):");
try {
@@ -214,38 +525,13 @@
body: JSON.stringify({ status_id: statusId, comment: comment })
});
showToast("Estado actualizado");
loadTimeline(currentServiceId);
fetchServices(); // Refrescar lista de fondo
} catch(e) { showToast("Error", true); }
loadTimeline(currentServiceId); // Recargar logs
fetchServices(); // Recargar lista fondo
} catch(e) { showToast("Error al actualizar", true); }
}
function closeDetailPanel() { document.getElementById('serviceDetailPanel').classList.add('hidden'); }
// --- TU LÓGICA DE CREAR SERVICIO (RESUMIDA) ---
async function createService(e) {
e.preventDefault();
// ... (Aquí iría la lógica completa de tu formulario anterior para recoger los datos) ...
// Simulación simple para este ejemplo:
const data = {
phone: document.getElementById('sPhone').value,
name: document.getElementById('sName').value,
address: document.getElementById('sAddress').value,
email: document.getElementById('sEmail').value,
description: document.getElementById('sDesc').value
};
try {
const res = await fetch(`${API_URL}/services`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
});
if(res.ok) { showToast("Creado"); toggleView('list'); }
} catch(e) { showToast("Error", true); }
}
// --- HELPERS (Buscador clientes, etc) ---
// (Pega aquí searchClientByPhone, loadCompanies, etc. del código anterior)
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`;