Actualizar proveedores.html

This commit is contained in:
2026-02-16 23:34:10 +00:00
parent e6f0ebb9dd
commit 7f443e164d

View File

@@ -206,6 +206,7 @@
<script> <script>
let allGuilds = []; let allGuilds = [];
let scrapedData = []; let scrapedData = [];
let pollingInterval = null; // Variable para controlar el refresco automático
const companyLogos = { const companyLogos = {
'REPSOL': 'https://cdn.sanity.io/images/rn4tswnp/production/1bc5be0207b732bd18dd0fc38e063d5701267068-1000x832.png?rect=6,0,994,832&h=320&auto=format&dpr=2', 'REPSOL': 'https://cdn.sanity.io/images/rn4tswnp/production/1bc5be0207b732bd18dd0fc38e063d5701267068-1000x832.png?rect=6,0,994,832&h=320&auto=format&dpr=2',
@@ -233,11 +234,32 @@
return keyFound ? companyLogos[keyFound] : companyLogos['DEFAULT']; return keyFound ? companyLogos[keyFound] : companyLogos['DEFAULT'];
} }
// CARGA INICIAL Y CONFIGURACIÓN DEL REFRESCO
document.addEventListener("DOMContentLoaded", async () => { document.addEventListener("DOMContentLoaded", async () => {
if (!localStorage.getItem("token")) window.location.href = "index.html"; if (!localStorage.getItem("token")) window.location.href = "index.html";
setTimeout(async () => { await loadGuilds(); await loadInbox(); }, 200);
// Carga inicial
setTimeout(async () => {
await loadGuilds();
await loadInbox();
}, 200);
// INICIAR REFRESCO AUTOMÁTICO CADA 30 SEGUNDOS
startPolling();
}); });
function startPolling() {
if (pollingInterval) clearInterval(pollingInterval);
pollingInterval = setInterval(async () => {
// Solo actualizamos si el usuario NO está editando un expediente (modal cerrado)
const modal = document.getElementById('importModal');
if (modal.classList.contains('hidden')) {
console.log("Actualizando buzón automáticamente...");
await loadInbox();
}
}, 30000); // 30 segundos
}
async function loadGuilds() { async function loadGuilds() {
try { try {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
@@ -261,13 +283,14 @@
} }
async function loadInbox() { async function loadInbox() {
const container = document.getElementById('inboxContainer');
try { try {
const resSvc = await fetch(`${API_URL}/providers/scraped`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const resSvc = await fetch(`${API_URL}/providers/scraped`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const dataSvc = await resSvc.json(); const dataSvc = await resSvc.json();
scrapedData = dataSvc.services || []; scrapedData = dataSvc.services || [];
// Actualizar select de compañías solo si es necesario (para no romper el filtro actual)
const compSelect = document.getElementById('filterCompany'); const compSelect = document.getElementById('filterCompany');
const currentVal = compSelect.value;
const uniqueCompanies = [...new Set(scrapedData.map(s => { const uniqueCompanies = [...new Set(scrapedData.map(s => {
const raw = s.raw_data || {}; const raw = s.raw_data || {};
return (raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "S/C").toString().toUpperCase().trim(); return (raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "S/C").toString().toUpperCase().trim();
@@ -275,7 +298,9 @@
compSelect.innerHTML = '<option value="ALL">COMPAÑÍAS</option>'; compSelect.innerHTML = '<option value="ALL">COMPAÑÍAS</option>';
uniqueCompanies.forEach(c => compSelect.innerHTML += `<option value="${c}">${c}</option>`); uniqueCompanies.forEach(c => compSelect.innerHTML += `<option value="${c}">${c}</option>`);
compSelect.value = currentVal;
// Actualizar contadores
const active = scrapedData.filter(s => s.status === 'pending').length; const active = scrapedData.filter(s => s.status === 'pending').length;
const archived = scrapedData.filter(s => s.status === 'archived').length; const archived = scrapedData.filter(s => s.status === 'archived').length;
document.getElementById('countActive').innerText = active; document.getElementById('countActive').innerText = active;
@@ -283,7 +308,7 @@
document.getElementById('countTotal').innerText = scrapedData.length; document.getElementById('countTotal').innerText = scrapedData.length;
renderFilteredInbox(); renderFilteredInbox();
} catch (e) { showToast("Error de conexión", true); } } catch (e) { console.error("Error en loadInbox:", e); }
} }
function renderFilteredInbox() { function renderFilteredInbox() {
@@ -311,14 +336,13 @@
container.innerHTML = ""; container.innerHTML = "";
if(filtered.length === 0) { if(filtered.length === 0) {
container.innerHTML = '<div class="p-12 text-center text-slate-400 bg-white rounded-3xl border-2 border-dashed text-left">No se encontraron expedientes con estos filtros.</div>'; container.innerHTML = '<div class="p-12 text-center text-slate-400 bg-white rounded-3xl border-2 border-dashed">No se encontraron expedientes con estos filtros.</div>';
return; return;
} }
filtered.forEach(svc => { filtered.forEach(svc => {
const raw = svc.raw_data || {}; const raw = svc.raw_data || {};
const isArchived = svc.status === 'archived'; const isArchived = svc.status === 'archived';
const statusLabel = isArchived ? 'ARCHIVADO' : 'SERVICIO ACTIVO';
const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N"; const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N";
const addr = raw['Dirección'] || raw['DOMICILIO'] || ""; const addr = raw['Dirección'] || raw['DOMICILIO'] || "";
@@ -328,38 +352,36 @@
const guildName = allGuilds.find(g => g.id == raw['guild_id'])?.name || null; const guildName = allGuilds.find(g => g.id == raw['guild_id'])?.name || null;
const opName = raw['assigned_to_name'] || null; const opName = raw['assigned_to_name'] || null;
// LÓGICA DE ESTADO VISUAL Y BLOQUEO
let badgeEstado = ''; let badgeEstado = '';
let bgClass = 'bg-white'; let bgClass = 'bg-white';
let isLocked = false; let isLocked = false;
let lockedMsg = ''; let lockedMsg = '';
// LÓGICA DE ACTUALIZACIÓN DE ESTADO
// Si el servicio se marca como 'imported' o tiene 'assigned_to', significa que ya no está disponible en el buzón
if (!isArchived) { if (!isArchived) {
if (svc.automation_status === 'in_progress') { if (svc.automation_status === 'in_progress') {
// EN COLA (Amarillo)
bgClass = 'bg-amber-50/40 border-amber-200'; bgClass = 'bg-amber-50/40 border-amber-200';
isLocked = true; isLocked = true;
lockedMsg = 'Este servicio está actualmente en la rueda de WhatsApp buscando operario.'; lockedMsg = 'Enviado por WhatsApp. Esperando aceptación.';
badgeEstado = ` badgeEstado = `
<div class="flex flex-col items-end gap-1"> <div class="flex flex-col items-end gap-1">
<span class="bg-amber-100 text-amber-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-amber-200 shadow-sm"> <span class="bg-amber-100 text-amber-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-amber-200 shadow-sm">
<span class="w-1.5 h-1.5 bg-amber-500 rounded-full pulse-slow"></span> En Cola / Esperando <span class="w-1.5 h-1.5 bg-amber-500 rounded-full pulse-slow"></span> En Cola / Bolsa
</span> </span>
</div>`; </div>`;
} else if (raw['assigned_to'] || svc.status === 'imported') { } else if (svc.status === 'imported' || raw['assigned_to']) {
// ASIGNADO / TRASPASADO (Verde)
bgClass = 'bg-emerald-50/40 border-emerald-200'; bgClass = 'bg-emerald-50/40 border-emerald-200';
isLocked = true; isLocked = true;
lockedMsg = 'Este servicio ya ha sido asignado o traspasado. Ve al Panel Operativo para gestionarlo.'; lockedMsg = 'Servicio AUTO-ASIGNADO o traspasado.';
badgeEstado = ` badgeEstado = `
<div class="flex flex-col items-end gap-1"> <div class="flex flex-col items-end gap-1">
<span class="bg-emerald-100 text-emerald-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-emerald-200 shadow-sm"> <span class="bg-emerald-100 text-emerald-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-emerald-200 shadow-sm">
<i data-lucide="check-circle-2" class="w-3 h-3"></i> Asignado <i data-lucide="check-circle-2" class="w-3 h-3"></i> Asignado
</span> </span>
<span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">${opName || 'Operario asignado'}</span> <span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">${opName || 'Gestionado'}</span>
</div>`; </div>`;
} else { } else {
// NORMAL (Blanco)
bgClass = 'bg-white border-slate-200'; bgClass = 'bg-white border-slate-200';
badgeEstado = ` badgeEstado = `
<div class="flex flex-col items-end gap-1"> <div class="flex flex-col items-end gap-1">
@@ -374,61 +396,49 @@
const card = document.createElement('div'); const card = document.createElement('div');
card.id = `card-${svc.id}`; card.id = `card-${svc.id}`;
card.className = `service-card p-5 rounded-2xl border ${bgClass} flex items-center justify-between transition-all group fade-in text-left ${isLocked ? 'locked' : ''}`; card.className = `service-card p-5 rounded-2xl border ${bgClass} flex items-center justify-between transition-all group fade-in ${isLocked ? 'locked' : ''}`;
card.onclick = (e) => { card.onclick = (e) => {
if (e.target.closest('a') || e.target.closest('button')) return; if (e.target.closest('a') || e.target.closest('button')) return;
if (isArchived) { if (isArchived) {
showToast("⚠️ Este servicio está ARCHIVADO.", true); showToast("⚠️ Este servicio está ARCHIVADO.", true);
} else if (isLocked) { } else if (isLocked) {
// Animación de temblor
card.classList.remove('shake'); card.classList.remove('shake');
void card.offsetWidth; // Forzar reflow void card.offsetWidth;
card.classList.add('shake'); card.classList.add('shake');
showToast(`🔒 Bloqueado: ${lockedMsg}`, true); showToast(`🔒 ${lockedMsg}`, true);
} else { } else {
openEditor(svc.id); openEditor(svc.id);
} }
}; };
const statusClass = isArchived ? 'bg-gray-100 text-gray-500 border-gray-200' : 'bg-blue-50 text-blue-600 border-blue-100';
card.innerHTML = ` card.innerHTML = `
<div class="flex items-center gap-4 min-w-0 text-left flex-1"> <div class="flex items-center gap-4 min-w-0 flex-1">
<div class="w-16 h-16 rounded-2xl flex flex-col items-center justify-center shrink-0 shadow-sm border border-slate-100 ${isArchived ? 'bg-gray-200 text-gray-400' : (svc.provider === 'homeserve' ? 'bg-red-50 text-red-600' : 'bg-blue-50 text-blue-600')}"> <div class="w-16 h-16 rounded-2xl flex flex-col items-center justify-center shrink-0 shadow-sm border border-slate-100 ${isArchived ? 'bg-gray-200 text-gray-400' : (svc.provider === 'homeserve' ? 'bg-red-50 text-red-600' : 'bg-blue-50 text-blue-600')}">
<span class="text-[9px] font-black uppercase tracking-tighter text-left">${svc.provider === 'multiasistencia' ? 'MULTI' : 'HOME'}</span> <span class="text-[9px] font-black uppercase tracking-tighter">${svc.provider === 'multiasistencia' ? 'MULTI' : 'HOME'}</span>
<i data-lucide="${isArchived ? 'lock' : 'file-text'}" class="w-5 h-5 mt-0.5 text-left"></i> <i data-lucide="${isArchived ? 'lock' : 'file-text'}" class="w-5 h-5 mt-0.5"></i>
</div> </div>
<div class="w-12 h-12 rounded-xl bg-white border border-slate-100 p-2 flex items-center justify-center shrink-0 shadow-inner text-left"> <div class="w-12 h-12 rounded-xl bg-white border border-slate-100 p-2 flex items-center justify-center shrink-0 shadow-inner">
<img src="${getLogoUrl(raw['Compañía'] || raw['COMPAÑIA'])}" onerror="this.src='${companyLogos['DEFAULT']}'" class="max-w-full max-h-full object-contain"> <img src="${getLogoUrl(raw['Compañía'] || raw['COMPAÑIA'])}" onerror="this.src='${companyLogos['DEFAULT']}'" class="max-w-full max-h-full object-contain">
</div> </div>
<div class="min-w-0 text-left flex-1"> <div class="min-w-0 flex-1">
<div class="flex items-center gap-2 text-left"> <h3 class="font-black text-slate-800 truncate uppercase text-lg leading-tight">${name}</h3>
<h3 class="font-black text-slate-800 truncate uppercase text-lg leading-tight text-left">${name}</h3> <p class="text-xs text-slate-400 truncate italic mt-0.5">${fullAddr}</p>
</div> <div class="flex flex-wrap gap-2 mt-2">
<p class="text-xs text-slate-400 truncate italic mt-0.5 text-left">${fullAddr}</p> <span class="text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded-lg font-bold border">#${svc.service_ref}</span>
<div class="flex flex-wrap gap-2 mt-2 text-left"> ${guildName ? `<span class="text-[10px] bg-blue-50 text-blue-600 px-2 py-0.5 rounded-lg font-bold border border-blue-100"><i data-lucide="hammer" class="w-2.5 h-2.5 inline mr-1"></i>${guildName}</span>` : ''}
<span class="text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded-lg font-bold border text-left">#${svc.service_ref}</span>
${guildName ? `<span class="text-[10px] bg-blue-50 text-blue-600 px-2 py-0.5 rounded-lg font-bold border border-blue-100 text-left"><i data-lucide="hammer" class="w-2.5 h-2.5 inline mr-1"></i>${guildName}</span>` : ''}
</div> </div>
</div> </div>
</div> </div>
<div class="flex items-center gap-4 shrink-0 pl-4">
<div class="flex items-center gap-4 text-left shrink-0 pl-4">
${badgeEstado} ${badgeEstado}
${!isArchived ? `
<div class="hidden group-hover:flex items-center gap-2 transition-all text-left ml-2 border-l border-slate-200 pl-4">
<a href="https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(fullAddr)}" target="_blank" class="action-btn p-2.5 rounded-xl bg-white text-slate-400 hover:text-blue-600 shadow-sm border border-slate-100 text-left"><i data-lucide="map" class="w-5 h-5 text-left"></i></a>
${phone ? `<a href="https://wa.me/34${phone}" target="_blank" class="action-btn p-2.5 rounded-xl bg-white text-slate-400 hover:text-emerald-600 shadow-sm border border-slate-100 text-left"><i data-lucide="message-square" class="w-5 h-5 text-left"></i></a>` : ''}
</div>` : ''}
</div>`; </div>`;
container.appendChild(card); container.appendChild(card);
}); });
lucide.createIcons(); lucide.createIcons();
} }
// --- EL RESTO DE FUNCIONES (openEditor, saveDraft, sendToQueue, etc.) se mantienen IGUAL ---
async function openEditor(id) { async function openEditor(id) {
const svc = scrapedData.find(s => s.id === id); const svc = scrapedData.find(s => s.id === id);
if(!svc) return; if(!svc) return;
@@ -438,7 +448,7 @@
document.getElementById('modalCompanyLogo').innerHTML = `<img src="${getLogoUrl(companyName)}" class="max-w-full max-h-full object-contain">`; document.getElementById('modalCompanyLogo').innerHTML = `<img src="${getLogoUrl(companyName)}" class="max-w-full max-h-full object-contain">`;
document.getElementById('displayRef').innerText = `REF: ${svc.service_ref}`; document.getElementById('displayRef').innerText = `REF: ${svc.service_ref}`;
document.getElementById('displayCompany').innerText = companyName; document.getElementById('displayCompany').innerText = companyName;
document.getElementById('modalStatusBadge').innerHTML = `<span class="text-[9px] bg-emerald-50 text-emerald-600 px-3 py-1 rounded-full font-black border border-emerald-100 text-left">SERVICIO ACTIVO</span>`; document.getElementById('modalStatusBadge').innerHTML = `<span class="text-[9px] bg-emerald-50 text-emerald-600 px-3 py-1 rounded-full font-black border border-emerald-100">SERVICIO ACTIVO</span>`;
document.getElementById('impScrapedId').value = id; document.getElementById('impScrapedId').value = id;
document.getElementById('impName').value = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N"; document.getElementById('impName').value = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N";
@@ -577,10 +587,10 @@
function showToast(msg, isError = false) { function showToast(msg, isError = false) {
const t = document.getElementById('toast'), m = document.getElementById('toastMsg'); const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
t.className = `fixed bottom-8 right-8 px-8 py-4 rounded-2xl shadow-2xl z-[200] flex items-center gap-3 transition-all ${isError ? 'bg-red-600' : 'bg-slate-900'} text-white text-left`; t.className = `fixed bottom-8 right-8 px-8 py-4 rounded-2xl shadow-2xl z-[200] flex items-center gap-3 transition-all ${isError ? 'bg-red-600' : 'bg-slate-900'} text-white`;
m.innerText = msg; t.classList.remove('hidden'); m.innerText = msg; t.classList.remove('hidden');
setTimeout(() => t.classList.add('hidden'), 4000); setTimeout(() => t.classList.add('hidden'), 4000);
} }
</script> </script>
</body> </body>
</html> </html>