Actualizar servicios.html

This commit is contained in:
2026-02-16 21:57:08 +00:00
parent ee5842c259
commit 99bd74148b

View File

@@ -99,7 +99,7 @@
<textarea id="nDesc" placeholder="Descripción de la avería..." rows="4" class="w-full bg-slate-50 border-none px-4 py-3 rounded-3xl text-sm font-medium outline-none"></textarea>
</div>
<div class="space-y-6">
<select id="nGuild" class="w-full bg-slate-100 p-4 rounded-2xl font-bold outline-none" onchange="loadOps(this.value)">
<select id="nGuild" class="w-full bg-slate-100 p-4 rounded-2xl font-bold outline-none" onchange="loadOps(this.value, 'nWorker')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-6 rounded-[2rem] text-white space-y-4">
@@ -142,6 +142,7 @@
<div class="p-6 grid grid-cols-1 md:grid-cols-5 gap-6 bg-white overflow-y-auto max-h-[80vh] no-scrollbar">
<input type="hidden" id="detId">
<input type="hidden" id="detCp">
<div class="md:col-span-3 space-y-4">
<div class="bg-slate-50 p-5 rounded-[1.5rem] border border-slate-100 space-y-4">
@@ -168,9 +169,10 @@
</div>
</div>
<div class="md:col-span-2 bg-blue-50/40 p-6 rounded-[1.5rem] border border-blue-100 flex flex-col justify-between shadow-sm">
<div class="space-y-6">
<div class="md:col-span-2 flex flex-col gap-4">
<div id="panelAsignado" class="bg-blue-50/40 p-6 rounded-[1.5rem] border border-blue-100 flex flex-col justify-between shadow-sm h-full hidden">
<div class="space-y-6">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Operario Asignado</p>
<div class="flex items-center gap-3 bg-white p-3 rounded-2xl border border-slate-100 shadow-sm">
@@ -178,7 +180,6 @@
<p id="detWorker" class="font-black text-slate-700 text-xs uppercase leading-tight"></p>
</div>
</div>
<div class="space-y-3">
<p class="text-[10px] font-black text-blue-600 uppercase tracking-widest flex items-center gap-1.5 border-b border-blue-100 pb-2"><i data-lucide="calendar-clock" class="w-4 h-4"></i> Agendar Cita</p>
<div class="grid grid-cols-2 gap-2">
@@ -186,7 +187,6 @@
<input type="time" id="timeInput" class="w-full bg-white border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
</div>
</div>
<div class="space-y-2 pt-2">
<p class="text-[10px] font-black text-slate-800 uppercase ml-1 flex items-center gap-1.5"><i data-lucide="arrow-right-left" class="w-4 h-4 text-blue-500"></i> Cambio de Estado</p>
<div class="relative">
@@ -202,17 +202,46 @@
</div>
</div>
</div>
<button id="btnSaveAppt" onclick="saveAppointment()" class="w-full mt-8 bg-blue-600 text-white font-black py-4 rounded-2xl text-xs uppercase tracking-widest shadow-[0_8px_20px_-6px_rgba(37,99,235,0.5)] hover:bg-blue-700 hover:shadow-blue-600/30 transition-all active:scale-95 flex items-center justify-center gap-2 border border-blue-500">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios
</button>
</div>
<div id="panelSinAsignar" class="bg-rose-50/40 p-6 rounded-[1.5rem] border border-rose-100 flex flex-col shadow-sm h-full hidden">
<div class="flex items-center gap-2 mb-6">
<div class="w-2.5 h-2.5 rounded-full bg-rose-500 animate-pulse"></div>
<p class="text-[10px] font-black text-rose-600 uppercase tracking-widest">Pendiente de Asignar</p>
</div>
<div class="space-y-5 flex-1">
<select id="reGremio" class="w-full bg-white border border-rose-200 p-4 rounded-2xl text-xs font-bold text-slate-700 outline-none" onchange="loadOps(this.value, 'reOperario')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-5 rounded-2xl text-white space-y-4">
<button onclick="sendToAutomate()" id="btnAuto" class="w-full bg-blue-600 hover:bg-blue-500 p-3 rounded-xl flex items-center justify-between text-left transition-all active:scale-95">
<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[9px] text-blue-200">Rueda automática (WA)</p></div>
<i data-lucide="zap" class="w-5 h-5"></i>
</button>
<div class="bg-slate-800 p-4 rounded-xl space-y-3">
<p class="font-black uppercase text-[9px] text-slate-400 text-center">O Asignar a Mano:</p>
<select id="reOperario" class="w-full bg-slate-700 border-none text-white px-3 py-2.5 rounded-lg text-xs font-bold outline-none">
<option value="">-- Elija gremio primero --</option>
</select>
<button onclick="assignManualFromPanel()" class="w-full bg-white text-slate-900 font-black py-2.5 rounded-lg text-[10px] uppercase hover:bg-emerald-400 transition-colors">Confirmar Directo</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="toastAppt" class="fixed bottom-8 right-8 bg-emerald-600 text-white px-6 py-4 rounded-2xl shadow-2xl hidden z-[200] font-bold text-sm flex items-center gap-2">
<i data-lucide="check-circle" class="w-5 h-5"></i> Guardado correctamente
<i data-lucide="check-circle" class="w-5 h-5"></i> <span id="toastMsg">Guardado correctamente</span>
</div>
<script src="js/layout.js"></script>
@@ -234,7 +263,7 @@
const data = await res.json();
if (data.ok) {
localData = data.services;
updateOperatorFilter(); // Actualiza el select de operarios
updateOperatorFilter();
renderLists();
}
} catch (e) { console.error(e); }
@@ -243,27 +272,17 @@
function updateOperatorFilter() {
const opSelect = document.getElementById('opFilter');
const currentValue = opSelect.value;
// Extraer nombres únicos de operarios asignados en este panel
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>`;
});
uniqueOps.forEach(op => { html += `<option value="${op}">${op}</option>`; });
opSelect.innerHTML = html;
// Restaurar la selección previa si sigue existiendo
if (html.includes(`value="${currentValue}"`)) {
opSelect.value = currentValue;
}
if (html.includes(`value="${currentValue}"`)) opSelect.value = currentValue;
}
function renderLists() {
const searchTerm = document.getElementById('searchFilter').value.toLowerCase();
const selectedOp = document.getElementById('opFilter').value;
// FILTRO DE DATOS
const filteredData = localData.filter(s => {
const raw = s.raw_data;
const name = (raw["Nombre Cliente"] || raw["CLIENTE"] || "").toLowerCase();
@@ -273,21 +292,12 @@
const ref = (s.service_ref || "").toLowerCase();
const assigned = s.assigned_name || "";
// Buscar texto (Nombre, Ref, Dirección, Población, Teléfono)
const matchesSearch = searchTerm === "" ||
name.includes(searchTerm) ||
ref.includes(searchTerm) ||
addr.includes(searchTerm) ||
pop.includes(searchTerm) ||
phone.includes(searchTerm);
// Buscar Operario
const matchesSearch = searchTerm === "" || name.includes(searchTerm) || ref.includes(searchTerm) || addr.includes(searchTerm) || pop.includes(searchTerm) || phone.includes(searchTerm);
const matchesOp = selectedOp === "ALL" || assigned === selectedOp;
return matchesSearch && matchesOp;
});
// Lógica inteligente de 3 columnas apoyada en el raw_data
const unassigned = filteredData.filter(s => !s.assigned_name || s.raw_data.status_operativo === 'sin_asignar');
const pending = filteredData.filter(s => s.assigned_name && (!s.raw_data.scheduled_date || s.raw_data.scheduled_date === "") && s.raw_data.status_operativo !== 'sin_asignar');
const assigned = filteredData.filter(s => s.raw_data.scheduled_date && s.raw_data.scheduled_date !== "" && s.raw_data.status_operativo !== 'sin_asignar');
@@ -350,31 +360,43 @@
const raw = s.raw_data;
document.getElementById('detId').value = s.id;
document.getElementById('detRef').innerText = s.service_ref;
document.getElementById('detCp').value = raw["Código Postal"] || "00000";
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "Particular";
document.getElementById('detCompany').innerText = companyName;
document.getElementById('detName').innerText = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
const phone = raw["Teléfono"] || raw["TELEFONO"] || "Sin Teléfono";
document.getElementById('detPhone').innerText = phone;
const cleanPhone = phone.replace(/\D/g,'');
document.getElementById('detPhoneLink').href = cleanPhone ? `tel:${cleanPhone}` : "#";
document.getElementById('detPhoneLink').href = phone.replace(/\D/g,'') ? `tel:${phone.replace(/\D/g,'')}` : "#";
document.getElementById('detAddrText').innerText = `${raw["Dirección"] || "Dirección no especificada"} ${raw["Población"] || ""}`;
document.getElementById('detWorker').innerText = s.assigned_name || "Pendiente Asignar";
document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "No hay notas adicionales del siniestro.")
.replace(/\n/g, '<br>');
document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.").replace(/\n/g, '<br>');
// LÓGICA DE PANELES LATERALES
if (s.assigned_name && raw.status_operativo !== 'sin_asignar') {
// TIENE OPERARIO: Mostrar panel de fechas
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 = raw.status_operativo || 'citado';
} else {
// NO TIENE OPERARIO (O FUE PAUSADO): Mostrar panel de re-asignación
document.getElementById('panelAsignado').classList.add('hidden');
document.getElementById('panelSinAsignar').classList.remove('hidden');
let defaultStatus = raw.status_operativo;
if (!defaultStatus) {
defaultStatus = (!s.assigned_name) ? 'sin_asignar' : 'citado';
// Pre-cargar el gremio si el robot lo detectó previamente
if(raw.guild_id) {
document.getElementById('reGremio').value = raw.guild_id;
loadOps(raw.guild_id, 'reOperario');
} else {
document.getElementById('reGremio').value = "";
document.getElementById('reOperario').innerHTML = '<option value="">-- Elija gremio primero --</option>';
}
}
document.getElementById('detStatusMap').value = defaultStatus;
document.getElementById('detailModal').classList.remove('hidden');
lucide.createIcons();
@@ -386,57 +408,105 @@
const time = document.getElementById('timeInput').value;
const statusMap = document.getElementById('detStatusMap').value;
if(!date && statusMap !== 'incidencia' && statusMap !== 'terminado' && statusMap !== 'sin_asignar') {
if(!confirm("No has asignado una Fecha de Visita.\n\nEl estado se guardará, pero el expediente seguirá en la columna izquierda hasta que le pongas fecha. ¿Deseas continuar?")) return;
// Si lo mandan a "sin_asignar", borrar operario en BD
let assigned_to = undefined;
if (statusMap === 'sin_asignar') {
assigned_to = null;
} else if(!date && statusMap !== 'incidencia' && statusMap !== 'terminado') {
if(!confirm("No has asignado Fecha. ¿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;
lucide.createIcons();
try {
const res = await fetch(`${API_URL}/services/set-appointment/${id}`, {
// Si cambiamos a sin_asignar, usamos la ruta de scraped para borrar el assigned_to
if(statusMap === 'sin_asignar') {
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_operativo: statusMap, assigned_to: null, assigned_to_name: null })
});
} else {
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"); refreshPanel();
} catch (e) { alert("Error"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; }
}
if(res.ok) {
closeDetailModal();
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>';
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 })
});
const data = await res.json();
if(data.ok) { closeDetailModal(); showToast("Enviado a la rueda de WhatsApp"); refreshPanel(); }
else { alert(data.error || "No hay operarios en esa zona para ese gremio"); btn.innerHTML = 'Mandar a la Cola'; }
} catch (e) { alert("Error"); btn.innerHTML = 'Mandar a la Cola'; }
}
async function assignManualFromPanel() {
const id = document.getElementById('detId').value;
const guild_id = document.getElementById('reGremio').value;
const assigned_to = document.getElementById('reOperario').value;
if(!guild_id || !assigned_to) return alert("Selecciona gremio y operario.");
try {
const select = document.getElementById('reOperario');
const name = select.options[select.selectedIndex].text;
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({
automation_status: 'completed',
assigned_to: assigned_to,
assigned_name: name,
guild_id: guild_id,
status_operativo: 'asignado_operario'
})
});
closeDetailModal(); showToast("Asignado correctamente"); refreshPanel();
} catch (e) { alert("Error"); }
}
function showToast(msg) {
document.getElementById('toastMsg').innerText = msg;
const toast = document.getElementById('toastAppt');
toast.classList.remove('hidden');
setTimeout(() => { toast.classList.add('hidden'); }, 3000);
refreshPanel();
} else {
alert("Error en el servidor al guardar.");
}
} catch (e) {
alert("Error de conexión");
} finally {
btn.innerHTML = originalContent;
btn.disabled = false;
lucide.createIcons();
}
}
async function saveNewService(e) {
e.preventDefault();
const action = e.submitter.value;
const data = {
phone: document.getElementById('nPhone').value,
name: document.getElementById('nName').value,
address: document.getElementById('nAddr').value,
description: document.getElementById('nDesc').value,
guild_id: document.getElementById('nGuild').value,
assigned_to: document.getElementById('nWorker').value || null
phone: document.getElementById('nPhone').value, name: document.getElementById('nName').value,
address: document.getElementById('nAddr').value, description: document.getElementById('nDesc').value,
guild_id: document.getElementById('nGuild').value, assigned_to: document.getElementById('nWorker').value || null
};
try {
const res = await fetch(`${API_URL}/services/manual-high`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ ...data, mode: action })
});
if (res.ok) { closeCreateModal(); refreshPanel(); }
@@ -450,11 +520,15 @@
async function loadGuilds() {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) document.getElementById('nGuild').innerHTML = '<option value="">Seleccionar Gremio...</option>' + data.guilds.map(g => `<option value="${g.id}">${g.name}</option>`).join('');
if(data.ok) {
const opts = '<option value="">Seleccionar Gremio...</option>' + data.guilds.map(g => `<option value="${g.id}">${g.name}</option>`).join('');
document.getElementById('nGuild').innerHTML = opts;
document.getElementById('reGremio').innerHTML = opts;
}
}
async function loadOps(gid) {
const sel = document.getElementById('nWorker');
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();