Files
web/servicios.html
2026-02-08 23:11:14 +00:00

261 lines
15 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Servicios - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>.fade-in { animation: fadeIn 0.3s ease-in-out; }</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>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-6 relative">
<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-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>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<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</th><th class="p-4">Asignado</th><th class="p-4">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"></tbody>
</table>
</div>
</div>
<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"><i data-lucide="arrow-left" class="w-5 h-5"></i> Volver</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">
<input type="hidden" id="editServiceId">
<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 *</label>
<input type="tel" id="sPhone" required placeholder="600123456" class="w-full border p-2 rounded-lg" onblur="searchClientByPhone()">
</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 border p-2 rounded-lg">
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Provincia</label>
<select id="sProvince" class="w-full border p-2 rounded-lg bg-gray-50" onchange="loadTowns(this.value)">
<option value="">-- Seleccionar --</option>
</select>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Población / Municipio *</label>
<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 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> 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>
<label class="block text-xs font-bold text-blue-800 mb-1">Zona Detectada</label>
<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">
</div>
<div>
<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">
<option value="">-- Manual --</option>
</select>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Estado</label>
<select id="sCreateStatus" class="w-full border p-2 rounded-lg"></select>
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Fecha</label>
<input type="date" id="sDate" class="w-full border p-2 rounded-lg">
</div>
<div>
<label class="block text-xs font-bold text-gray-600 mb-1">Hora</label>
<input type="time" id="sTime" class="w-full border p-2 rounded-lg">
</div>
</div>
<div class="mt-4">
<label class="block text-xs font-bold text-gray-600 mb-1">Descripción</label>
<textarea id="sDesc" rows="3" class="w-full border p-2 rounded-lg"></textarea>
</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">GUARDAR</button>
</div>
</form>
</div>
<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">
<button onclick="closeDetailPanel()" class="mb-4 text-right">Cerrar ✖</button>
<h2 class="text-xl font-bold" id="detailTitle"></h2>
<p class="text-sm text-gray-500" id="detailClient"></p>
<div class="mt-4 flex gap-2">
<button onclick="editService()" class="flex-1 bg-gray-100 p-2 rounded">Editar</button>
<button onclick="deleteService()" class="bg-red-100 text-red-600 p-2 rounded">Borrar</button>
</div>
</div>
</div>
</main>
</div>
</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>
let allStatuses = [], currentServiceId = null;
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
fetchStatuses();
fetchServices();
loadProvinces();
loadAllOperators(); // Carga base de operarios
});
// --- 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();
} else {
if(document.getElementById('editServiceId').value !== "") resetForm();
document.getElementById('createServiceView').classList.remove('hidden');
}
}
// --- LÓGICA GEOGRÁFICA ---
async function loadProvinces() {
const res = await fetch(`${API_URL}/provinces`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const sel = document.getElementById('sProvince');
sel.innerHTML = '<option value="">-- Seleccionar --</option>';
data.provinces.forEach(p => sel.innerHTML += `<option value="${p.id}">${p.name}</option>`);
}
async function loadTowns(provId) {
const sel = document.getElementById('sTown');
sel.innerHTML = '<option value="">Cargando...</option>';
sel.disabled = true;
if(!provId) return;
const res = await fetch(`${API_URL}/provinces/${provId}/towns`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
sel.innerHTML = '<option value="">-- Seleccionar Población --</option>';
data.towns.forEach(t => sel.innerHTML += `<option value="${t.id}">${t.name}</option>`);
sel.disabled = false;
}
// --- AUTO ASIGNACIÓN ---
async function checkAutoAssign(townId) {
if(!townId) return;
// Buscar zona y operarios para este pueblo
const res = await fetch(`${API_URL}/towns/${townId}/auto-assign`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
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>`;
});
if(data.operators.length === 0) opSelect.innerHTML += '<option value="">(Zona sin operarios)</option>';
} else {
zoneInput.value = "(Sin zona asignada)";
loadAllOperators(); // Volver a mostrar todos si no hay zona
}
}
async function loadAllOperators() {
const res = await fetch(`${API_URL}/operators`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const sel = document.getElementById('sOperator');
sel.innerHTML = '<option value="">-- Todos los operarios --</option>';
data.operators.forEach(op => sel.innerHTML += `<option value="${op.id}">${op.full_name}</option>`);
}
// --- RESTO DE FUNCIONES (CREAR, LISTAR...) ---
async function fetchServices() {
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 = "";
data.services.forEach(s => {
tbody.innerHTML += `
<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>
<td class="p-4 font-bold">${s.contact_name}</td>
<td class="p-4">${s.assigned_name || '-'}</td>
<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>
<td class="p-4">➡️</td>
</tr>`;
});
}
async function handleFormSubmit(e) {
e.preventDefault();
const data = {
contact_phone: document.getElementById('sPhone').value,
contact_name: document.getElementById('sName').value,
address: document.getElementById('sAddress').value + ", " + document.getElementById('sTown').options[document.getElementById('sTown').selectedIndex].text,
description: document.getElementById('sDesc').value,
assigned_to: document.getElementById('sOperator').value || null
// Añadir resto de campos...
};
await fetch(`${API_URL}/services`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
});
toggleView('list');
}
async function fetchStatuses() {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
allStatuses = data.statuses;
const sel = document.getElementById('sCreateStatus');
sel.innerHTML = "";
allStatuses.forEach(s => sel.innerHTML += `<option value="${s.id}">${s.name}</option>`);
}
function resetForm() { document.querySelector('form').reset(); document.getElementById('editServiceId').value = ""; }
</script>
</body>
</html>