Files
web/proveedores.html
2026-03-22 14:21:08 +00:00

1024 lines
61 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Validación - IntegraReparaPro</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; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.no-scrollbar::-webkit-scrollbar { display: none; }
.service-card { cursor: pointer; transition: all 0.2s ease; position: relative; }
.service-card:hover:not(.archived):not(.locked) { transform: translateY(-2px); border-color: #3b82f6; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
.archived { opacity: 0.7; filter: grayscale(100%); }
.locked { cursor: not-allowed; }
/* Animación suave para el icono de esperando */
.pulse-slow { animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
/* Animación de temblor para las tarjetas bloqueadas */
.shake { animation: shake 0.4s cubic-bezier(.36,.07,.19,.97) both; }
@keyframes shake {
10%, 90% { transform: translate3d(-1px, 0, 0); }
20%, 80% { transform: translate3d(2px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
40%, 60% { transform: translate3d(4px, 0, 0); }
}
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden text-left">
<div class="flex h-screen overflow-hidden text-left">
<div id="sidebar-container" class="h-full shrink-0"></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="automationView" class="fade-in max-w-6xl mx-auto">
<div class="flex justify-between items-center mb-8">
<div>
<h2 class="text-2xl font-black text-slate-800 flex items-center gap-3">
<span class="bg-blue-600 p-2.5 rounded-xl text-white shadow-lg"><i data-lucide="building-2"></i></span>
Buzón de Proveedores
</h2>
<p class="text-sm text-slate-500 mt-1 font-medium">Filtra por proveedor, compañía o cualquier dato del asegurado.</p>
</div>
<div class="flex items-center gap-3">
<a href="importar_todo.html" target="_blank" class="bg-teal-50 border-2 border-teal-100 hover:border-teal-400 text-teal-700 px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition-all active:scale-95 shadow-sm">
<i data-lucide="mail-plus" class="w-4 h-4"></i> Pegar TO&DO
</a>
<button id="btnSmartSort" onclick="toggleSmartSort()" class="bg-indigo-50 ...">
<i data-lucide="sparkles" class="w-4 h-4"></i> Orden Inteligente
</button>
<button onclick="loadInbox()" class="bg-white border-2 border-slate-200 hover:border-blue-600 hover:text-blue-600 text-slate-600 px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 transition-all active:scale-95 shadow-sm">
<i data-lucide="refresh-cw" class="w-4 h-4"></i> Actualizar
</button>
</div>
</div>
<div class="bg-white p-4 rounded-2xl border border-slate-200 shadow-sm mb-4 flex flex-wrap gap-4 items-center">
<div class="flex-1 min-w-[280px] relative text-left">
<i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
<input type="text" id="searchBox" oninput="renderFilteredInbox()" placeholder="Buscar por Nombre, REF, Dirección, Teléfono..." class="w-full pl-11 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 outline-none transition-all">
</div>
<div class="flex gap-2">
<select id="filterStatus" onchange="renderFilteredInbox()" class="bg-slate-50 border border-slate-200 text-[10px] font-black px-4 py-2.5 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 uppercase tracking-widest">
<option value="ALL">TODOS LOS ESTADOS</option>
<option value="pending">SOLO ACTIVOS</option>
<option value="archived">SOLO ARCHIVADOS</option>
</select>
<select id="filterProvider" onchange="renderFilteredInbox()" class="bg-slate-50 border border-slate-200 text-[10px] font-black px-4 py-2.5 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 uppercase tracking-widest">
<option value="ALL">PROVEEDORES</option>
<option value="homeserve">HOME (HOMESERVE)</option>
<option value="multiasistencia">MULTI (MULTIASISTENCIA)</option>
<option value="todo">TO&DO</option>
</select>
<select id="filterCompany" onchange="renderFilteredInbox()" class="bg-slate-50 border border-slate-200 text-[10px] font-black px-4 py-2.5 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 uppercase tracking-widest max-w-[200px]">
<option value="ALL">COMPAÑÍAS</option>
</select>
</div>
</div>
<div class="flex gap-4 mb-6 text-left">
<div class="bg-emerald-50 border border-emerald-100 px-4 py-2 rounded-xl flex items-center gap-2">
<span class="text-[10px] font-black text-emerald-600 uppercase tracking-widest">Activos:</span>
<span id="countActive" class="text-sm font-black text-emerald-700">0</span>
</div>
<div class="bg-slate-100 border border-slate-200 px-4 py-2 rounded-xl flex items-center gap-2 text-left">
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">Archivados:</span>
<span id="countArchived" class="text-sm font-black text-slate-700">0</span>
</div>
<div class="bg-blue-50 border border-blue-100 px-4 py-2 rounded-xl flex items-center gap-2 text-left">
<span class="text-[10px] font-black text-blue-600 uppercase tracking-widest">Total:</span>
<span id="countTotal" class="text-sm font-black text-blue-700">0</span>
</div>
</div>
<div id="inboxContainer" class="space-y-4 text-left"></div>
</div>
</main>
</div>
</div>
<div id="importModal" class="fixed inset-0 bg-slate-900/75 hidden z-[100] flex items-center justify-center backdrop-blur-md p-2 text-left">
<div class="bg-white rounded-[2.5rem] shadow-2xl w-full max-w-4xl flex flex-col max-h-[95vh] overflow-hidden border border-slate-200 fade-in text-left">
<div class="px-6 py-6 md:px-8 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 border-b border-slate-100 bg-slate-50/50">
<div class="flex items-center gap-4 min-w-0">
<div id="modalCompanyLogo" class="w-14 h-14 rounded-2xl bg-white border border-slate-200 p-2 flex items-center justify-center shadow-sm shrink-0 overflow-hidden"></div>
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2.5 mb-1.5">
<h3 class="text-xl md:text-2xl font-black text-slate-800 tracking-tight leading-none truncate">Validación de Expediente</h3>
<div id="modalStatusBadge"></div>
</div>
<div class="flex flex-wrap items-center gap-2 mt-1">
<span id="displayRef" class="text-[10px] bg-white text-slate-500 px-2.5 py-1 rounded-lg font-black border border-slate-200 uppercase tracking-widest shadow-sm shrink-0">REF: --</span>
<span id="displayCompany" class="text-[10px] bg-blue-50 text-blue-700 px-2.5 py-1 rounded-lg font-black border border-blue-200 uppercase tracking-widest truncate max-w-[200px] shadow-sm">--</span>
<div id="modalAlertsContainer" class="flex gap-1 shrink-0"></div>
</div>
</div>
</div>
<div class="flex items-end gap-3 w-full lg:w-auto">
<div class="flex-1 lg:flex-none flex flex-col">
<label class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Estado Operativo</label>
<select id="impStatus" class="bg-white text-blue-700 border-2 border-blue-100 text-xs font-black px-4 py-2.5 rounded-xl outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 cursor-pointer shadow-sm w-full lg:w-44 transition-all">
<option value="">Seleccionar...</option>
</select>
</div>
<div class="flex-1 lg:flex-none flex flex-col">
<label class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Prioridad</label>
<select id="impUrgent" class="bg-white border-2 border-slate-200 text-xs font-black px-4 py-2.5 rounded-xl outline-none focus:border-red-400 focus:ring-2 focus:ring-red-100 cursor-pointer shadow-sm w-full lg:w-36 transition-all">
<option value="false">Normal</option>
<option value="true">🚨 Urgente</option>
</select>
</div>
<button type="button" onclick="closeModal()" class="bg-white border border-slate-200 p-2.5 rounded-xl text-slate-400 hover:bg-red-50 hover:text-red-500 hover:border-red-200 transition-all shadow-sm shrink-0 mb-[1px]">
<i data-lucide="x" class="w-5 h-5"></i>
</button>
</div>
</div>
<form id="importForm" onsubmit="handleFinalImport(event)" class="px-8 py-6 space-y-5 overflow-y-auto no-scrollbar text-left">
<input type="hidden" id="impScrapedId">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="bg-slate-50/50 p-3 rounded-2xl border border-slate-100 flex items-center gap-3 text-left">
<div class="bg-white p-2 rounded-xl shadow-sm text-slate-400 text-left"><i data-lucide="user" class="w-4 h-4"></i></div>
<div class="flex flex-col min-w-0 w-full text-left">
<span class="text-[9px] font-black text-slate-400 uppercase mb-0.5 text-left">Asegurado</span>
<input type="text" id="impName" class="bg-transparent border-none p-0 text-sm font-bold text-slate-700 outline-none w-full text-left">
</div>
</div>
<div class="bg-slate-50/50 p-3 rounded-2xl border border-slate-100 flex items-center gap-3 text-left">
<div class="bg-white p-2 rounded-xl shadow-sm text-emerald-500 text-left"><i data-lucide="phone" class="w-4 h-4 text-left"></i></div>
<div class="flex flex-col min-w-0 w-full text-left">
<span class="text-[9px] font-black text-slate-400 uppercase mb-0.5 text-left">Teléfono</span>
<input type="text" id="impPhone" class="bg-transparent border-none p-0 text-sm font-black text-emerald-600 outline-none w-full text-left">
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-5 gap-3 text-left">
<div class="md:col-span-4 space-y-1 text-left">
<label class="text-[9px] font-black text-blue-600 uppercase tracking-widest ml-2 flex items-center gap-1 text-left"><i data-lucide="map-pin" class="w-3 h-3 text-left"></i> Dirección</label>
<input type="text" id="impAddress" required class="w-full border-2 border-slate-100 bg-white px-4 py-2.5 rounded-2xl text-sm font-medium outline-none focus:border-blue-500 shadow-sm text-left">
</div>
<div class="space-y-1 text-center">
<label class="text-[9px] font-black text-blue-600 uppercase tracking-widest block text-left ml-2">C.P.</label>
<input type="text" id="impCP" required class="w-full border-2 border-slate-100 bg-white py-2.5 rounded-2xl text-sm font-black text-center outline-none focus:border-blue-500 shadow-sm">
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-5 rounded-[1.8rem] border-2 border-blue-50 bg-blue-50/30 text-left">
<div class="space-y-1 text-left">
<label class="text-[9px] font-black text-blue-600 uppercase tracking-widest ml-2 text-left">Gremio Especialista *</label>
<select id="impGuild" required onchange="loadOpsForGuild(this.value)" class="w-full border border-blue-100 bg-white px-3 py-2 rounded-xl text-sm font-bold shadow-sm outline-none focus:ring-2 focus:ring-blue-400 text-left">
<option value="">-- Seleccionar Gremio --</option>
</select>
</div>
<div class="space-y-1 text-left">
<label class="text-[9px] font-black text-slate-400 uppercase tracking-widest ml-2 text-left">Asignación Operario</label>
<select id="impOperator" class="w-full border border-blue-100 bg-white px-3 py-2 rounded-xl text-sm font-bold shadow-sm outline-none focus:ring-2 focus:ring-blue-400 text-left">
<option value="">-- Automática --</option>
</select>
</div>
</div>
<div class="space-y-3 text-left">
<div class="space-y-1 text-left">
<label class="text-[9px] font-black text-slate-400 uppercase tracking-widest ml-2 text-left">Avería Detectada</label>
<textarea id="impDesc" rows="2" class="w-full border border-slate-200 bg-white px-4 py-2 rounded-2xl text-sm font-medium text-slate-600 outline-none focus:border-blue-400 resize-none shadow-sm text-left"></textarea>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-left">
<div class="text-left">
<label class="text-[9px] font-black text-amber-600 uppercase ml-2 mb-1 block text-left">Notas Oficina</label>
<textarea id="impNotesInt" rows="1" class="w-full border border-amber-100 bg-amber-50/30 px-3 py-2 rounded-xl text-xs outline-none focus:bg-white text-left"></textarea>
</div>
<div class="text-left">
<label class="text-[9px] font-black text-blue-500 uppercase ml-2 mb-1 block text-left">Instrucciones Operario</label>
<textarea id="impNotesExt" rows="1" class="w-full border border-blue-100 bg-blue-50/30 px-3 py-2 rounded-xl text-xs outline-none focus:bg-white text-left"></textarea>
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-3 pt-4 border-t text-left">
<button type="button" onclick="saveDraftChanges(event)" class="bg-slate-100 hover:bg-slate-200 text-slate-600 font-black px-4 py-4 rounded-[1.5rem] transition-all flex items-center justify-center gap-2 active:scale-95 text-[10px] uppercase tracking-widest">
<i data-lucide="save" class="w-4 h-4"></i> <span>Guardar</span>
</button>
<button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-black px-6 py-4 rounded-[1.5rem] shadow-lg transition-all flex items-center justify-center gap-2 active:scale-95 text-[10px] uppercase tracking-widest">
<i data-lucide="send" class="w-4 h-4"></i> <span>Traspaso Manual</span>
</button>
<button type="button" onclick="sendToQueue()" class="flex-1 bg-emerald-600 hover:bg-emerald-700 text-white font-black py-4 rounded-[1.5rem] shadow-xl shadow-emerald-200 transition-all flex items-center justify-center gap-3 active:scale-95 text-xs uppercase tracking-[0.15em]">
<i data-lucide="zap" class="w-5 h-5"></i> <span>MANDAR A LA COLA (AUTO)</span>
</button>
</div>
</form>
</div>
</div>
<div id="toast" class="fixed bottom-8 right-8 bg-slate-900 text-white px-8 py-4 rounded-2xl shadow-2xl hidden z-[200] border border-white/10 text-left"><span id="toastMsg" class="font-bold text-sm text-left"></span></div>
<script src="js/layout.js"></script>
<script>
let allGuilds = [];
let scrapedData = [];
let systemStatuses = []; // Guardará los estados reales de la DB
let pollingInterval = null;
let isSmartSortActive = false; // Variable para el botón Orden Inteligente
const companyLogos = {
'REPSOL': 'https://cdn.sanity.io/images/rn4tswnp/production/1bc5be0207b732bd18dd0fc38e063d5701267068-1000x832.png?rect=6,0,994,832&h=320&auto=format&dpr=2',
'MUTUA': 'https://www.google.com/s2/favicons?domain=mutua.es&sz=128',
'ALLIANZ': 'https://www.google.com/s2/favicons?domain=allianz.es&sz=128',
'CASER': 'https://www.google.com/s2/favicons?domain=caser.es&sz=128',
'SEGURCAIXA': 'https://unijepol.eu/wp-content/uploads/2021/01/Segur-Caixa-Adeslas.jpg',
'LA CAIXA': 'https://www.google.com/s2/favicons?domain=segurcaixaadeslas.es&sz=128',
'AXA': 'https://www.google.com/s2/favicons?domain=axa.es&sz=128',
'LDA': 'https://www.google.com/s2/favicons?domain=lineadirecta.com&sz=128',
'HOMESERVE SINIESTROS': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTeO7TsnpOYqLGgJm0puUyUMLi657od4mGWKQ&s',
'HOMESERVE REPARACIONES': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTeO7TsnpOYqLGgJm0puUyUMLi657od4mGWKQ&s',
'RGA': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRemEVB4iYmTGoZL0nrBQJkZ1vNlDNtKfGEug&s',
'RURAL GRUPO': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRemEVB4iYmTGoZL0nrBQJkZ1vNlDNtKfGEug&s',
'SANTANDER': 'https://www.google.com/s2/favicons?domain=santander.com&sz=128',
'BANSABADELL': 'https://play-lh.googleusercontent.com/-XAFeiDTzqTwRMfT6ggZO3raXI1VPmmvc5JDm2BeGsUA1MUF7X4Y-eeDPMp8BsEgBw=w240-h480-rw',
'GENERALI': 'https://cdn.worldvectorlogo.com/logos/generali-logo.svg',
'DEFAULT': 'https://cdn-icons-png.flaticon.com/512/2875/2875438.png'
};
function getLogoUrl(companyName) {
if (!companyName) return companyLogos['DEFAULT'];
const name = companyName.toString().toUpperCase();
const keyFound = Object.keys(companyLogos).find(key => name.includes(key));
return keyFound ? companyLogos[keyFound] : companyLogos['DEFAULT'];
}
document.addEventListener("DOMContentLoaded", async () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
setTimeout(async () => {
await loadStatuses(); // Cargamos los estados de DB
await loadGuilds();
await loadInbox();
}, 200);
startPolling();
});
function startPolling() {
if (pollingInterval) clearInterval(pollingInterval);
pollingInterval = setInterval(async () => {
const modal = document.getElementById('importModal');
if (modal.classList.contains('hidden')) {
await loadInbox();
}
}, 30000);
}
function toggleSmartSort() {
isSmartSortActive = !isSmartSortActive;
const btn = document.getElementById('btnSmartSort');
if (isSmartSortActive) {
btn.classList.remove('bg-indigo-50', 'text-indigo-700', 'border-indigo-100', 'hover:border-indigo-400');
btn.classList.add('bg-indigo-600', 'text-white', 'border-indigo-600', 'shadow-indigo-200', 'hover:bg-indigo-700');
} else {
btn.classList.remove('bg-indigo-600', 'text-white', 'border-indigo-600', 'shadow-indigo-200', 'hover:bg-indigo-700');
btn.classList.add('bg-indigo-50', 'text-indigo-700', 'border-indigo-100', 'hover:border-indigo-400');
}
renderFilteredInbox();
}
// Calcular la prioridad del servicio
function getServicePriority(svc) {
const raw = svc.raw_data || {};
const autoStatus = (svc.automation_status || '').toLowerCase();
const sysStatus = (svc.status || '').toLowerCase();
const dbStatusId = raw.status_operativo;
const dbStatusObj = systemStatuses.find(st => String(st.id) === String(dbStatusId));
const opName = raw['assigned_to_name'] || null;
// Fallo bolsa: 2
if (autoStatus === 'failed') return 2;
// Bolsa activa: 5 (Resto)
if (autoStatus.includes('bolsa') || autoStatus === 'in_progress') return 5;
if (dbStatusObj) {
const stName = dbStatusObj.name.toLowerCase();
// Sin asignar de DB: 1
if (stName.includes('pendiente') && !stName.includes('cita')) return 1;
// Esperando al cliente: 3
if (stName.includes('esperando')) return 3;
// Citado: 4
if (stName.includes('citado')) return 4;
// Resto de estados: 5
return 5;
}
// Asignado o Importado: 5 (Resto)
if (raw['assigned_to'] || (sysStatus === 'imported' && opName)) return 5;
if (sysStatus === 'imported') return 5;
// Por defecto (Sin asignar): 1
return 1;
}
// Función inteligente para filtrar los estados según si hay operario o no
function filterStatusOptions() {
const statusSelect = document.getElementById('impStatus');
const operatorSelect = document.getElementById('impOperator');
const hasOperator = operatorSelect.value !== "";
const currentSelected = statusSelect.value; // Guardamos lo que estaba seleccionado
statusSelect.innerHTML = '<option value="">(Sin Estado)</option>';
systemStatuses.forEach(st => {
const nameLow = st.name.toLowerCase();
// Detectamos qué estados EXIGEN tener un trabajador físico
const requiresWorker =
(nameLow.includes('asignado') && !nameLow.includes('pendiente') && !nameLow.includes('desasignado')) ||
nameLow.includes('esperando') ||
nameLow.includes('citado') ||
nameLow.includes('camino') ||
nameLow.includes('trabajando');
// Si el estado exige trabajador y NO hay ninguno seleccionado, lo saltamos
if (requiresWorker && !hasOperator) return;
statusSelect.innerHTML += `<option value="${st.id}">${st.name.toUpperCase()}</option>`;
});
// Intentamos restaurar el valor que había (si sigue siendo válido tras el filtro)
if (Array.from(statusSelect.options).some(opt => opt.value === currentSelected)) {
statusSelect.value = currentSelected;
} else {
statusSelect.value = "";
}
}
async function loadStatuses() {
try {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) systemStatuses = data.statuses;
} catch (e) { console.error("Error al cargar estados", e); }
}
async function loadGuilds() {
try {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
allGuilds = data.guilds || [];
const sel = document.getElementById('impGuild');
sel.innerHTML = '<option value="">-- Seleccionar Gremio --</option>';
allGuilds.forEach(g => sel.innerHTML += `<option value="${g.id}">${g.name}</option>`);
} catch(e) {}
}
async function loadOpsForGuild(guildId) {
const sel = document.getElementById('impOperator');
if(!guildId) {
sel.innerHTML = '<option value="">-- Automática --</option>';
filterStatusOptions(); // <--- ACTUALIZAR ESTADOS
return;
}
try {
const res = await fetch(`${API_URL}/operators?guild_id=${guildId}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
sel.innerHTML = '<option value="">-- Automática --</option>';
data.operators.forEach(op => sel.innerHTML += `<option value="${op.id}">${op.full_name}</option>`);
filterStatusOptions(); // <--- ACTUALIZAR ESTADOS
} catch(e) {}
}
async function loadInbox() {
try {
const resSvc = await fetch(`${API_URL}/providers/scraped`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const dataSvc = await resSvc.json();
let fetchedServices = dataSvc.services || [];
// FILTRO ESTRICTO: Solo proveedores oficiales (Excluimos 'particular'/'presupuestos' y 'SYSTEM_BLOCK')
fetchedServices = fetchedServices.filter(s =>
s.provider === 'homeserve' || s.provider === 'multiasistencia' || s.provider === 'todo'
);
if (JSON.stringify(scrapedData) !== JSON.stringify(fetchedServices)) {
scrapedData = fetchedServices;
updateFiltersAndRender();
}
} catch (e) { console.error("Error en loadInbox:", e); }
}
function updateFiltersAndRender() {
const compSelect = document.getElementById('filterCompany');
const currentVal = compSelect.value;
const uniqueCompanies = [...new Set(scrapedData.map(s => {
const raw = s.raw_data || {};
return (raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "S/C").toString().toUpperCase().trim();
}))].sort();
compSelect.innerHTML = '<option value="ALL">COMPAÑÍAS</option>';
uniqueCompanies.forEach(c => compSelect.innerHTML += `<option value="${c}">${c}</option>`);
compSelect.value = currentVal;
const active = scrapedData.filter(s => s.status === 'pending').length;
const archived = scrapedData.filter(s => s.status === 'archived').length;
document.getElementById('countActive').innerText = active;
document.getElementById('countArchived').innerText = archived;
document.getElementById('countTotal').innerText = scrapedData.length;
renderFilteredInbox();
}
// Mapa de colores exactos usados en servicios.html para pintar la pastilla de estado
const colorMap = {
'gray': { bg: 'bg-slate-100', text: 'text-slate-600', border: 'border-slate-200' },
'blue': { bg: 'bg-blue-100', text: 'text-blue-700', border: 'border-blue-200' },
'amber': { bg: 'bg-amber-100', text: 'text-amber-700', border: 'border-amber-200' },
'emerald': { bg: 'bg-emerald-100', text: 'text-emerald-700', border: 'border-emerald-200' },
'indigo': { bg: 'bg-indigo-100', text: 'text-indigo-700', border: 'border-indigo-200' },
'orange': { bg: 'bg-orange-100', text: 'text-orange-700', border: 'border-orange-200' },
'red': { bg: 'bg-red-100', text: 'text-red-700', border: 'border-red-200' },
'rose': { bg: 'bg-rose-100', text: 'text-rose-700', border: 'border-rose-200' },
'purple': { bg: 'bg-purple-100', text: 'text-purple-700', border: 'border-purple-200' }
};
function buildServiceCard(svc) {
const raw = svc.raw_data || {};
const isArchived = svc.status === 'archived';
const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N";
const addr = raw['Dirección'] || raw['DOMICILIO'] || "";
const pop = raw['Población'] || raw['POBLACION-PROVINCIA'] || "";
const fullAddr = `${addr} ${pop}`.trim();
const cp = raw['Código Postal'] || raw['C.P.'] || "";
const phone = (raw['Teléfono'] || raw['TELEFONOS'] || raw['TELEFONO'] || "").match(/[6789]\d{8}/)?.[0] || "";
let guildName = null;
const rawGuildId = svc.guild_id || raw['guild_id'] || raw.guild_id;
if (rawGuildId) {
const foundGuild = allGuilds.find(g => String(g.id) === String(rawGuildId));
if (foundGuild) guildName = foundGuild.name;
}
const opName = raw['assigned_to_name'] || null;
let badgeEstado = '';
let bgClass = 'bg-white';
let isLocked = false;
let lockedMsg = '';
let showQuickQueueBtn = false; // Variable para saber si mostrar el botón rápido
const autoStatus = (svc.automation_status || '').toLowerCase();
const sysStatus = (svc.status || '').toLowerCase();
// 1. OBTENEMOS EL ESTADO REAL DE LA BASE DE DATOS
const dbStatusId = raw.status_operativo;
const dbStatusObj = systemStatuses.find(st => String(st.id) === String(dbStatusId));
const isUrgent = svc.is_urgent === true || (raw['Urgente'] && raw['Urgente'].toLowerCase() === 'sí') || (raw['URGENTE'] && raw['URGENTE'].toLowerCase() === 'si');
// Le he quitado el ml-3 para que use el gap automático
const urgentBadge = isUrgent ? `<span class="bg-red-500 text-white px-2 py-0.5 rounded-md text-[9px] font-black uppercase shadow-sm animate-pulse">🔥 Urgente</span>` : '';
// 🛑 NUEVO: EXTRAER Y PINTAR LOS ICONOS DE CANDADO Y OJOS
const hasLock = raw.has_lock === true || String(raw.has_lock) === 'true';
const hasEyes = raw.has_eyes === true || String(raw.has_eyes) === 'true';
let alertBadges = '';
if (hasLock) alertBadges += `<span class="bg-slate-800 text-white px-2 py-0.5 rounded-md text-[9px] font-black uppercase shadow-sm flex items-center gap-1" title="Gestora (Candado)"><i data-lucide="lock" class="w-3 h-3"></i></span>`;
if (hasEyes) alertBadges += `<span class="bg-amber-500 text-white px-2 py-0.5 rounded-md text-[9px] font-black uppercase shadow-sm animate-pulse flex items-center gap-1" title="Requiere Información (Ojos)"><i data-lucide="eye" class="w-3 h-3"></i></span>`;
if (!isArchived) {
if (autoStatus.includes('bolsa') || autoStatus === 'in_progress') {
bgClass = 'bg-orange-50/40 border-orange-200 hover:border-orange-400';
isLocked = true;
lockedMsg = 'Este servicio está en la BOLSA buscando operario.';
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="bg-orange-100 text-orange-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-orange-200 shadow-sm">
<span class="w-1.5 h-1.5 bg-orange-500 rounded-full pulse-slow"></span> En Bolsa
</span>
<span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">Buscando operario...</span>
</div>`;
} else if (autoStatus === 'failed') {
bgClass = 'bg-red-50/40 border-red-200 hover:border-red-400';
isLocked = false;
// Si ha fallado, pero tiene gremio detectado, le damos la opción de reenviar a la bolsa rápidamente
if (rawGuildId) showQuickQueueBtn = true;
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="bg-red-100 text-red-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-red-200 shadow-sm">
<i data-lucide="alert-triangle" class="w-3 h-3"></i> Fallo Bolsa
</span>
<span class="text-[8px] font-bold text-red-400">Nadie aceptó</span>
</div>`;
} else if (dbStatusObj) {
// AQUÍ USAMOS EL COLOR Y NOMBRE DEL ESTADO DE LA BASE DE DATOS
const cMap = colorMap[dbStatusObj.color] || colorMap['gray'];
bgClass = `${cMap.bg.replace('100', '50')}/40 ${cMap.border} hover:border-${dbStatusObj.color}-400`;
// Si está en un estado que no sea "Pendiente" o "Sin Asignar", se bloquea la edición por aquí
if(!dbStatusObj.name.toLowerCase().includes('pendiente') && !dbStatusObj.name.toLowerCase().includes('desasignado')) {
isLocked = true;
lockedMsg = `Este servicio ya está en estado: ${dbStatusObj.name}. Ve al Panel Operativo.`;
} else if(rawGuildId && !opName) {
showQuickQueueBtn = true; // Si está pendiente, sin técnico y tiene gremio -> Botón rápido
}
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="${cMap.bg} ${cMap.text} px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 ${cMap.border} shadow-sm border">
${dbStatusObj.name}
</span>
${opName ? `<span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">${opName}</span>` : ''}
</div>`;
} else if (raw['assigned_to'] || (sysStatus === 'imported' && opName)) {
bgClass = 'bg-emerald-50/40 border-emerald-200 hover:border-emerald-400';
isLocked = true;
lockedMsg = 'Servicio ASIGNADO. Ve al Panel Operativo para gestionarlo.';
badgeEstado = `
<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">
<i data-lucide="check-circle-2" class="w-3 h-3"></i> Asignado
</span>
<span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">${opName || 'Operario'}</span>
</div>`;
} else if (sysStatus === 'imported') {
bgClass = 'bg-blue-50/40 border-blue-200 hover:border-blue-400';
isLocked = false; // 🔓 DESBLOQUEADO: Ahora puedes hacer clic en él
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-blue-200 shadow-sm">
<i data-lucide="clipboard-list" class="w-3 h-3"></i> En Panel
</span>
<span class="text-[9px] font-bold text-slate-500 max-w-[120px] truncate text-right">Esperando acción</span>
</div>`;
} else {
bgClass = isUrgent ? 'bg-red-50/20 border-red-300 hover:border-red-50 shadow-[0_0_15px_rgba(239,68,68,0.15)]' : 'bg-white border-slate-200';
if(rawGuildId) showQuickQueueBtn = true; // Si está virgen y tiene gremio -> Botón rápido
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="bg-slate-100 text-slate-500 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-slate-200">
<i data-lucide="user-minus" class="w-3 h-3"></i> Sin Asignar
</span>
</div>`;
}
} else {
bgClass = 'bg-gray-50 border-gray-200 archived';
badgeEstado = `
<div class="flex flex-col items-end gap-1">
<span class="bg-gray-200 text-gray-500 px-3 py-1 rounded-full text-[10px] font-black uppercase flex items-center gap-1.5 border border-gray-300">
<i data-lucide="archive" class="w-3 h-3"></i> Archivado
</span>
</div>`;
}
const card = document.createElement('div');
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 ${isLocked ? 'locked' : ''}`;
card.onclick = (e) => {
if (e.target.closest('a') || e.target.closest('button')) return;
if (isLocked) {
card.classList.remove('shake');
void card.offsetWidth;
card.classList.add('shake');
showToast(`🔒 ${lockedMsg}`, true);
} else {
openEditor(svc.id, isArchived); // Pasamos si está archivado o no
}
};
let quickQueueHtml = '';
if (showQuickQueueBtn) {
quickQueueHtml = `
<button onclick="quickSendToQueue(event, '${svc.id}', '${rawGuildId}', '${cp}')" class="bg-emerald-100 hover:bg-emerald-600 text-emerald-700 hover:text-white transition-colors rounded-full p-2" title="Mandar a la bolsa">
<i data-lucide="zap" class="w-4 h-4"></i>
</button>
`;
}
card.innerHTML = `
<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' : (svc.provider === 'todo' ? 'bg-teal-50 text-teal-600' : 'bg-blue-50 text-blue-600'))}">
<span class="text-[9px] font-black uppercase tracking-tighter">${svc.provider === 'multiasistencia' ? 'MULTI' : (svc.provider === 'todo' ? 'TO&DO' : 'HOME')}</span>
<i data-lucide="${isArchived ? 'lock' : 'file-text'}" class="w-5 h-5 mt-0.5"></i>
</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">
<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 class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<h3 class="font-black text-slate-800 truncate uppercase text-lg leading-tight">${name}</h3>
${urgentBadge}
${alertBadges}
</div>
<p class="text-xs text-slate-400 truncate italic mt-0.5">${fullAddr}</p>
<div class="flex flex-wrap gap-2 mt-2 items-center">
<span class="text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded-lg font-bold border">#${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"><i data-lucide="hammer" class="w-2.5 h-2.5 inline mr-1"></i>${guildName}</span>` : ''}
${quickQueueHtml}
</div>
</div>
</div>
<div class="flex flex-col items-end justify-center shrink-0 pl-4">
${badgeEstado}
${(raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO']) ?
`<span class="text-[8px] font-black text-amber-600 bg-amber-50 px-2 py-0.5 rounded border border-amber-100 uppercase max-w-[140px] truncate mt-1.5 shadow-sm" title="${raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO']}">${raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO']}</span>`
: ''}
</div>`;
return card;
}
function renderFilteredInbox() {
const container = document.getElementById('inboxContainer');
const search = document.getElementById('searchBox').value.toUpperCase();
const provider = document.getElementById('filterProvider').value;
const company = document.getElementById('filterCompany').value;
const status = document.getElementById('filterStatus').value;
const filtered = scrapedData.filter(svc => {
const raw = svc.raw_data || {};
const name = (raw['Nombre Cliente'] || raw['CLIENTE'] || "").toUpperCase();
const ref = (svc.service_ref || "").toUpperCase();
const addr = (raw['Dirección'] || raw['DOMICILIO'] || "").toUpperCase();
const phone = (raw['Teléfono'] || raw['TELEFONO'] || "").toUpperCase();
const comp = (raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "").toUpperCase();
const matchesSearch = name.includes(search) || ref.includes(search) || addr.includes(search) || phone.includes(search);
const matchesProvider = provider === 'ALL' || svc.provider === provider;
const matchesCompany = company === 'ALL' || comp === company;
const matchesStatus = status === 'ALL' || svc.status === status;
return matchesSearch && matchesProvider && matchesCompany && matchesStatus;
});
container.innerHTML = "";
if(filtered.length === 0) {
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;
}
// SEPARAR ACTIVOS Y ARCHIVADOS
let activeServices = filtered.filter(svc => svc.status !== 'archived');
const archivedServices = filtered.filter(svc => svc.status === 'archived');
// APLICAR ORDEN INTELIGENTE SI ESTÁ ACTIVO
if (isSmartSortActive) {
activeServices.sort((a, b) => {
const priorityA = getServicePriority(a);
const priorityB = getServicePriority(b);
if (priorityA !== priorityB) {
return priorityA - priorityB;
}
// Mantener el orden original si tienen la misma prioridad
return 0;
});
}
// 1. RENDERIZAR ACTIVOS
activeServices.forEach(svc => container.appendChild(buildServiceCard(svc)));
// 2. RENDERIZAR ARCHIVADOS AL FINAL (CON ACORDEÓN)
if (archivedServices.length > 0) {
// Si el usuario busca algo específico o filtra solo archivados, abrimos el acordeón automáticamente
const isAutoExpanded = (search.length > 0 || status === 'archived');
const divider = document.createElement('div');
divider.className = "mt-10 mb-4 border-t border-slate-200 pt-8 fade-in";
divider.innerHTML = `
<button onclick="document.getElementById('archivedCardsContainer').classList.toggle('hidden'); document.getElementById('archivedChevron').classList.toggle('rotate-180');"
class="w-full flex items-center justify-between bg-slate-200/50 hover:bg-slate-200 text-slate-500 px-6 py-4 rounded-[1.5rem] transition-all group border border-slate-200 shadow-sm">
<span class="font-black text-xs uppercase tracking-[0.15em] flex items-center gap-3">
<i data-lucide="archive" class="w-5 h-5 text-slate-400"></i> Expedientes Archivados (${archivedServices.length})
</span>
<i data-lucide="chevron-down" id="archivedChevron" class="w-5 h-5 transition-transform duration-300 ${isAutoExpanded ? 'rotate-180' : ''}"></i>
</button>
`;
container.appendChild(divider);
const archContainer = document.createElement('div');
archContainer.id = 'archivedCardsContainer';
archContainer.className = `space-y-4 fade-in ${isAutoExpanded ? '' : 'hidden'}`;
archivedServices.forEach(svc => archContainer.appendChild(buildServiceCard(svc)));
container.appendChild(archContainer);
}
lucide.createIcons();
}
async function openEditor(id, isArchived = false) {
const svc = scrapedData.find(s => s.id === id);
if(!svc) return;
const raw = svc.raw_data;
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "";
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}`;
// 🛑 AQUÍ INYECTAMOS EL ESTADO EN EL MODAL Y LOS ICONOS DE ALERTA SEPARADOS
const hasLock = raw.has_lock === true || String(raw.has_lock) === 'true';
const hasEyes = raw.has_eyes === true || String(raw.has_eyes) === 'true';
let modalAlerts = '';
if (hasLock) modalAlerts += `<span class="bg-slate-800 text-white p-1.5 rounded-lg shadow-sm flex items-center justify-center" title="Gestora (Candado)"><i data-lucide="lock" class="w-3.5 h-3.5"></i></span>`;
if (hasEyes) modalAlerts += `<span class="bg-amber-500 text-white p-1.5 rounded-lg animate-pulse shadow-sm flex items-center justify-center" title="Requiere Información (Ojos)"><i data-lucide="eye" class="w-3.5 h-3.5"></i></span>`;
const estadoCia = raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO'] || "";
if (estadoCia) {
document.getElementById('displayCompany').innerHTML = `${companyName} <span class="ml-2 pl-2 border-l border-blue-200 text-blue-600 font-black uppercase text-[9px] tracking-widest">${estadoCia}</span>`;
} else {
document.getElementById('displayCompany').innerHTML = companyName;
}
if (document.getElementById('modalAlertsContainer')) {
document.getElementById('modalAlertsContainer').innerHTML = modalAlerts;
}
if (isArchived) {
document.getElementById('modalStatusBadge').innerHTML = `<span class="inline-flex items-center gap-1.5 text-[9px] bg-slate-200 text-slate-600 px-2.5 py-1 rounded-lg font-black uppercase tracking-widest border border-slate-300 shadow-sm whitespace-nowrap shrink-0"><i data-lucide="archive" class="w-3 h-3"></i> ARCHIVADO</span>`;
} else {
document.getElementById('modalStatusBadge').innerHTML = `<span class="inline-flex items-center text-[9px] bg-emerald-100 text-emerald-700 px-2.5 py-1 rounded-lg font-black uppercase tracking-widest border border-emerald-200 shadow-sm whitespace-nowrap shrink-0">SERVICIO ACTIVO</span>`;
}
document.getElementById('impScrapedId').value = id;
// 1. LEER PRIMERO DE LA RAÍZ (DATOS EDITADOS), LUEGO DEL RAW (DATOS ORIGINALES)
document.getElementById('impName').value = svc.name || raw['Nombre Cliente'] || raw['CLIENTE'] || "S/N";
const rawPhone = raw['Teléfono'] || raw['TELEFONOS'] || raw['TELEFONO'] || "";
document.getElementById('impPhone').value = svc.phone || (rawPhone.match(/[6789]\d{8}/)?.[0] || "");
// 2. REPARACIÓN DE LA DIRECCIÓN DUPLICADA
const baseAddr = svc.address || raw['Dirección'] || raw['DOMICILIO'] || "";
const pop = raw['Población'] || raw['POBLACION-PROVINCIA'] || "";
let finalAddr = baseAddr;
// Solo añadimos la población si hay población Y la dirección actual no la contiene ya
if (pop && !finalAddr.toLowerCase().includes(pop.toLowerCase())) {
finalAddr = `${finalAddr} ${pop}`.trim();
}
document.getElementById('impAddress').value = finalAddr;
document.getElementById('impCP').value = svc.cp || raw['Código Postal'] || raw['C.P.'] || "";
document.getElementById('impDesc').value = svc.description || raw['Descripción'] || "";
const isUrgent = svc.is_urgent === true || raw['Urgente'] === 'Sí' || raw['Urgente'] === 'true' || raw['URGENTE'] === 'SI';
document.getElementById('impUrgent').value = isUrgent.toString();
document.getElementById('impNotesInt').value = svc.internal_notes || raw['internal_notes'] || "";
document.getElementById('impNotesExt').value = svc.client_notes || raw['client_notes'] || "";
const rawGuildId = svc.guild_id || raw['guild_id'] || raw.guild_id;
document.getElementById('impGuild').value = rawGuildId ? String(rawGuildId) : "";
if(rawGuildId) {
await loadOpsForGuild(rawGuildId);
document.getElementById('impOperator').value = raw['assigned_to'] || "";
} else {
document.getElementById('impOperator').innerHTML = '<option value="">-- Automática --</option>';
}
// --- CARGAR ESTADOS EN EL SELECTOR ---
filterStatusOptions(); // Ejecutamos el filtro inicial
const statusSelect = document.getElementById('impStatus');
// Si el JSON traía un estado previo, intentamos fijarlo (solo si es válido en el filtro)
if (raw.status_operativo && Array.from(statusSelect.options).some(opt => opt.value === String(raw.status_operativo))) {
statusSelect.value = raw.status_operativo;
}
// Añadimos un "chivato" para que si eligen a un operario a mano, se desbloqueen los estados al instante
const opSelect = document.getElementById('impOperator');
opSelect.removeEventListener('change', filterStatusOptions); // Limpiar previo por si acaso
opSelect.addEventListener('change', filterStatusOptions);
// --- ADAPTACIÓN VISUAL PARA ARCHIVADOS (VISTA BREVE) ---
// Obtenemos los contenedores que queremos ocultar cuando esté archivado
const guildOperatorSection = document.getElementById('impGuild').closest('.grid'); // El bloque azul de gremio/operario
const descNotesSection = document.getElementById('impDesc').closest('.space-y-3'); // El bloque de avería y notas
const phoneSection = document.getElementById('impPhone').closest('.bg-slate-50\\/50'); // El campo de teléfono
// Bloquear los inputs que se quedan visibles para que no se editen por error
const inputsToLock = ['impName', 'impAddress', 'impCP', 'impUrgent'];
if (isArchived) {
// Ocultar lo innecesario
if(guildOperatorSection) guildOperatorSection.classList.add('hidden');
if(descNotesSection) descNotesSection.classList.add('hidden');
if(phoneSection) phoneSection.classList.add('hidden');
// Hacer que el campo de nombre ocupe toda la línea (ya que quitamos el teléfono)
const nameContainer = document.getElementById('impName').closest('.grid');
if(nameContainer) {
nameContainer.classList.remove('md:grid-cols-2');
nameContainer.classList.add('grid-cols-1');
}
// Bloquear los campos visibles (excepto el estado)
inputsToLock.forEach(inputId => {
const el = document.getElementById(inputId);
if (el) {
el.setAttribute('readonly', 'true');
el.classList.add('bg-transparent', 'text-slate-500', 'cursor-not-allowed');
if (el.tagName === 'SELECT') el.style.pointerEvents = 'none';
}
});
// Ajustar visualmente el modal para que no parezca un formulario
document.getElementById('impAddress').classList.remove('border-2', 'bg-white', 'shadow-sm');
document.getElementById('impAddress').classList.add('border-0', 'bg-slate-50/50', 'text-slate-500');
document.getElementById('impCP').classList.remove('border-2', 'bg-white', 'shadow-sm');
document.getElementById('impCP').classList.add('border-0', 'bg-slate-50/50', 'text-slate-500');
} else {
// Restaurar todo a la vista normal
if(guildOperatorSection) guildOperatorSection.classList.remove('hidden');
if(descNotesSection) descNotesSection.classList.remove('hidden');
if(phoneSection) phoneSection.classList.remove('hidden');
const nameContainer = document.getElementById('impName').closest('.grid');
if(nameContainer) {
nameContainer.classList.add('md:grid-cols-2');
nameContainer.classList.remove('grid-cols-1');
}
// Desbloquear campos
inputsToLock.forEach(inputId => {
const el = document.getElementById(inputId);
if (el) {
el.removeAttribute('readonly');
el.classList.remove('bg-transparent', 'text-slate-500', 'cursor-not-allowed');
if (el.tagName === 'SELECT') el.style.pointerEvents = 'auto';
}
});
// Restaurar estilos del formulario
document.getElementById('impAddress').classList.add('border-2', 'bg-white', 'shadow-sm');
document.getElementById('impAddress').classList.remove('border-0', 'bg-slate-50/50', 'text-slate-500');
document.getElementById('impCP').classList.add('border-2', 'bg-white', 'shadow-sm');
document.getElementById('impCP').classList.remove('border-0', 'bg-slate-50/50', 'text-slate-500');
}
// Bloqueamos los botones de acción si está archivado o si ya está importado
const sysStatus = (svc.status || '').toLowerCase();
const isImported = sysStatus === 'imported';
const btnsToHide = document.querySelectorAll('button[type="submit"], button[onclick="sendToQueue()"]');
btnsToHide.forEach(btn => {
if(isArchived || isImported) btn.classList.add('hidden');
else btn.classList.remove('hidden');
});
// Cambiar el texto del botón de Guardar si es archivado para que sea más intuitivo
const saveBtn = document.querySelector('button[onclick="saveDraftChanges(event)"] span');
if (saveBtn) {
saveBtn.innerText = isArchived ? "Actualizar Estado" : "Guardar";
}
document.getElementById('importModal').classList.remove('hidden');
lucide.createIcons();
}
function closeModal() { document.getElementById('importModal').classList.add('hidden'); }
function getFormPayload() {
const opSelect = document.getElementById('impOperator');
const opName = opSelect.options[opSelect.selectedIndex]?.text.includes('--') ? null : opSelect.options[opSelect.selectedIndex]?.text;
return {
name: document.getElementById('impName').value,
phone: document.getElementById('impPhone').value,
address: document.getElementById('impAddress').value,
cp: document.getElementById('impCP').value,
description: document.getElementById('impDesc').value,
is_urgent: document.getElementById('impUrgent').value === 'true',
guild_id: document.getElementById('impGuild').value,
assigned_to: document.getElementById('impOperator').value,
assigned_to_name: opName,
internal_notes: document.getElementById('impNotesInt').value,
client_notes: document.getElementById('impNotesExt').value,
status_operativo: document.getElementById('impStatus').value || null // <-- CAMPO NUEVO
};
}
async function saveFormToDB(id, payload) {
const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
return res.ok;
}
async function saveDraftChanges(e) {
const id = document.getElementById('impScrapedId').value;
const btn = e.currentTarget;
btn.disabled = true;
try {
const ok = await saveFormToDB(id, getFormPayload());
if(ok) {
showToast("✅ Cambios guardados correctamente");
closeModal();
loadInbox();
}
else { showToast("❌ Error al guardar", true); }
} catch (err) { showToast("❌ Error de red", true); }
finally { btn.disabled = false; }
}
async function handleFinalImport(event) {
event.preventDefault();
const btn = event.submitter;
if(btn.type === 'button') return;
const id = document.getElementById('impScrapedId').value;
const payload = getFormPayload();
if (!payload.assigned_to) {
showToast("⚠️ ERROR: Selecciona un operario para hacer el traspaso manual.", true);
return;
}
btn.disabled = true;
payload.company_ref = document.getElementById('displayRef').innerText.replace('REF: ', '');
try {
await saveFormToDB(id, payload);
const res = await fetch(`${API_URL}/providers/import/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
const result = await res.json();
if(result.ok) { showToast("✅ Expediente traspasado con éxito"); closeModal(); loadInbox(); }
else { showToast("❌ Error al importar", true); }
} catch (e) { showToast("❌ Error de red", true); }
finally { btn.disabled = false; }
}
// Nueva función para el botón rápido
async function quickSendToQueue(event, id, guildId, cp) {
event.stopPropagation(); // Evita que se abra el modal
if(!guildId) {
showToast("⚠️ Falta el gremio. Ábrelo para asignarlo.", true);
return;
}
try {
showToast("🚀 Iniciando automatismo...");
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: guildId, cp: cp })
});
const data = await res.json();
if (data.ok) {
showToast("✅ ¡En cola! Se ha enviado a los operarios.");
loadInbox(); // Refresca la lista sin cerrar modales (ya que no hay)
} else { showToast("❌ " + data.error, true); }
} catch (e) { showToast("❌ Error de conexión", true); }
}
async function sendToQueue() {
const id = document.getElementById('impScrapedId').value;
const payload = getFormPayload();
if (!payload.guild_id) {
showToast("⚠️ Debes seleccionar un Gremio Especialista", true);
return;
}
try {
await saveFormToDB(id, payload);
showToast("🚀 Iniciando automatismo...");
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: payload.guild_id, cp: payload.cp })
});
const data = await res.json();
if (data.ok) {
showToast("✅ ¡En cola! Se ha enviado a los operarios.");
closeModal();
loadInbox();
} else { showToast("❌ " + data.error, true); }
} catch (e) { showToast("❌ Error de conexión", true); }
}
function showToast(msg, isError = false) {
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`;
m.innerText = msg; t.classList.remove('hidden');
setTimeout(() => t.classList.add('hidden'), 4000);
}
</script>
</body>
</html>