Files
Portal/pruebas-multi.html

273 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>Laboratorio Robot Multiasistencia</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; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.input-modern { @apply w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl text-sm font-semibold text-slate-700 outline-none transition-all focus:border-blue-500 focus:bg-white focus:ring-2 focus:ring-blue-100; }
.label-modern { @apply block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1.5 ml-1; }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
</head>
<body class="bg-slate-50 text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden">
<div class="bg-white border-b border-slate-200 p-4 flex justify-between items-center shrink-0">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-blue-600 text-white rounded-xl flex items-center justify-center shadow-lg"><i data-lucide="bot" class="w-5 h-5"></i></div>
<h1 class="text-xl font-black text-slate-800 tracking-tight">Laboratorio API Robot (Multiasistencia)</h1>
</div>
<a href="servicios.html" class="text-xs font-bold text-slate-500 hover:text-blue-600 flex items-center gap-2 bg-slate-100 px-4 py-2 rounded-lg transition-colors"><i data-lucide="arrow-left" class="w-4 h-4"></i> Volver al Panel</a>
</div>
<div class="flex-1 overflow-y-auto p-8 no-scrollbar">
<div class="max-w-5xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-8 fade-in">
<div class="bg-white p-8 rounded-[2rem] shadow-sm border border-slate-200 h-fit relative overflow-hidden">
<div class="flex justify-between items-start mb-6 border-b border-slate-100 pb-4">
<h2 class="font-black text-lg text-slate-800 flex items-center gap-2">
<i data-lucide="send" class="text-blue-500 w-5 h-5"></i> Lanzar Petición
</h2>
<div id="credStatus" class="flex items-center gap-2 px-3 py-1.5 bg-slate-100 text-slate-500 border border-slate-200 rounded-full text-[9px] font-black uppercase tracking-widest">
<i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> Comprobando acceso...
</div>
</div>
<form id="robotForm" class="space-y-5" onsubmit="sendToRobot(event)">
<div>
<label class="label-modern">Nº Siniestro / Expediente</label>
<input type="text" id="r_siniestro" placeholder="Ej: 12345678" class="input-modern" required>
</div>
<div class="grid grid-cols-1 gap-4">
<div>
<label class="label-modern">Nuevo Estado (Código Multi)</label>
<select id="r_estado" class="input-modern cursor-pointer" required onchange="toggleDateFields()">
<option value="">Seleccionar nuevo estado...</option>
<option value="1">1 - Contacto (Llamada al cliente)</option>
<option value="2">2 - Visita (Cita concertada)</option>
<option value="3">3 - Presupuesto</option>
<option value="34">34 - Rechazado (Anulado)</option>
<option value="37">37 - Pendiente Instrucciones (No Localizado/Ausente)</option>
</select>
</div>
</div>
<div class="grid grid-cols-2 gap-4 hidden" id="dateFieldsContainer">
<div>
<label class="label-modern">Fecha (Obligatoria para Cita/Asignar)</label>
<input type="text" id="r_fecha" placeholder="DD/MM/AAAA" class="input-modern text-center" pattern="\d{2}/\d{2}/\d{4}">
</div>
<div>
<label class="label-modern">Hora Aprox (Opcional)</label>
<input type="text" id="r_hora" placeholder="HH:MM" class="input-modern text-center" pattern="\d{2}:\d{2}">
</div>
</div>
<div>
<label class="label-modern">Observaciones (Opcional pero recomendado)</label>
<textarea id="r_obs" rows="3" placeholder="Describe qué ha pasado con el siniestro..." class="input-modern resize-none"></textarea>
</div>
<button type="submit" id="btnLaunch" disabled class="w-full bg-slate-900 text-white font-black py-4 rounded-xl text-xs uppercase tracking-widest shadow-lg transition-all flex items-center justify-center gap-2 mt-4 disabled:opacity-50 disabled:cursor-not-allowed">
<i data-lucide="rocket" class="w-4 h-4"></i> Esperando credenciales...
</button>
</form>
</div>
<div class="bg-slate-900 p-8 rounded-[2rem] shadow-xl border border-slate-800 text-white flex flex-col h-[650px]">
<div class="flex justify-between items-center border-b border-slate-700 pb-4 mb-4 shrink-0">
<h2 class="font-black text-lg text-slate-100 flex items-center gap-2">
<i data-lucide="activity" class="text-emerald-400 w-5 h-5"></i> Monitor DB Server
</h2>
<div class="flex items-center gap-2 px-3 py-1 bg-emerald-950 text-emerald-400 border border-emerald-800 rounded-full text-[10px] font-black uppercase tracking-widest">
<div class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></div> Polling Activo
</div>
</div>
<div id="logContainer" class="flex-1 bg-slate-950 rounded-xl border border-slate-800 p-5 font-mono text-xs overflow-y-auto space-y-3 no-scrollbar">
<div class="text-slate-500 italic">Esperando peticiones...</div>
</div>
</div>
</div>
</div>
<script>
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.protocol === 'file:'
? 'https://integrarepara-api.integrarepara.es'
: 'https://integrarepara-api.integrarepara.es';
let knownJobs = {};
document.addEventListener("DOMContentLoaded", async () => {
lucide.createIcons();
const token = localStorage.getItem("token");
if (!token) {
alert("Debes iniciar sesión primero.");
return;
}
startLab(token);
});
function toggleDateFields() {
const estado = document.getElementById('r_estado').value;
const container = document.getElementById('dateFieldsContainer');
// Mostrar campos de fecha/hora si el estado suele requerirlos (Visita, Contacto, Pendiente Instrucciones)
if (['1', '2', '37'].includes(estado)) {
container.classList.remove('hidden');
} else {
container.classList.add('hidden');
}
}
async function startLab(token) {
await checkCredentials(token);
addLog("Conectado a la Base de Datos. Escuchando la cola...", "system");
setInterval(fetchQueueStatus, 3000);
fetchQueueStatus();
}
async function checkCredentials(token) {
try {
const res = await fetch(`${API_URL}/providers/credentials`, {
headers: { "Authorization": `Bearer ${token}` }
});
const data = await res.json();
const credBadge = document.getElementById('credStatus');
const btnLaunch = document.getElementById('btnLaunch');
if (data.ok && data.credentials) {
const multiCreds = data.credentials.find(c => c.provider === 'multiasistencia');
if (multiCreds && multiCreds.status === 'active') {
credBadge.className = "flex items-center gap-2 px-3 py-1.5 bg-emerald-50 text-emerald-600 border border-emerald-200 rounded-full text-[9px] font-black uppercase tracking-widest";
credBadge.innerHTML = `<i data-lucide="check-circle" class="w-3 h-3"></i> Multi: ${multiCreds.username}`;
btnLaunch.disabled = false;
btnLaunch.className = "w-full bg-blue-600 hover:bg-blue-500 text-white font-black py-4 rounded-xl text-xs uppercase tracking-widest shadow-lg shadow-blue-500/30 transition-all active:scale-95 flex items-center justify-center gap-2 mt-4";
btnLaunch.innerHTML = '<i data-lucide="rocket" class="w-4 h-4"></i> Inyectar en DB Local';
} else {
credBadge.className = "flex items-center gap-2 px-3 py-1.5 bg-rose-50 text-rose-600 border border-rose-200 rounded-full text-[9px] font-black uppercase tracking-widest";
credBadge.innerHTML = `<i data-lucide="alert-triangle" class="w-3 h-3"></i> Faltan Credenciales`;
addLog("⚠️ ATENCIÓN: El robot no podrá funcionar porque no has configurado tu usuario de Multiasistencia.", "warning");
}
}
lucide.createIcons();
} catch (e) {
console.error(e);
}
}
function addLog(message, type = "info") {
const container = document.getElementById('logContainer');
const time = new Date().toLocaleTimeString();
let color = "text-slate-300";
let icon = "👉";
if (type === "success") { color = "text-emerald-400"; icon = "✅"; }
else if (type === "error") { color = "text-red-400"; icon = "❌"; }
else if (type === "warning") { color = "text-amber-400"; icon = "⚠️"; }
else if (type === "system") { color = "text-blue-400"; icon = "🤖"; }
const div = document.createElement('div');
div.className = `flex items-start gap-2 ${color} fade-in`;
div.innerHTML = `<span class="opacity-50 shrink-0">[${time}]</span> <span class="shrink-0">${icon}</span> <span class="break-words">${message}</span>`;
if (container.innerText.includes("Esperando peticiones")) container.innerHTML = '';
container.prepend(div);
}
async function sendToRobot(e) {
e.preventDefault();
const btn = document.getElementById('btnLaunch');
const originalContent = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando en cola...';
lucide.createIcons();
const payload = {
provider: 'multiasistencia', // CRÍTICO: Especificamos el proveedor
service_number: document.getElementById('r_siniestro').value.trim(),
new_status: document.getElementById('r_estado').value,
appointment_date: document.getElementById('r_fecha').value.trim(),
appointment_time: document.getElementById('r_hora').value.trim(), // Multiasistencia a veces necesita hora
observation: document.getElementById('r_obs').value.trim()
};
try {
const res = await fetch(`${API_URL}/robot/queue`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("token")}`
},
body: JSON.stringify(payload)
});
const data = await res.json();
if(data.ok) {
addLog(`Job [#${data.jobId}] - Petición encolada para Multiasistencia (Exp: ${payload.service_number})`, "info");
document.getElementById('robotForm').reset();
toggleDateFields();
} else {
addLog(`Error del servidor: ${data.error}`, "error");
}
} catch (err) {
addLog(`Error de red al enviar petición: ${err.message}`, "error");
} finally {
btn.disabled = false;
btn.innerHTML = originalContent;
lucide.createIcons();
}
}
async function fetchQueueStatus() {
try {
const res = await fetch(`${API_URL}/robot/queue`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok && data.jobs) {
// Filtramos solo los de multiasistencia para este laboratorio
const jobs = data.jobs.filter(j => j.provider === 'multiasistencia').reverse();
jobs.forEach(job => {
const prevStatus = knownJobs[job.id];
if (prevStatus !== job.status) {
if (!prevStatus && job.status !== 'PENDING') {
knownJobs[job.id] = job.status;
return;
}
if (job.status === 'RUNNING') {
addLog(`Job [#${job.id}] - 🏃‍♂️ El robot ha arrancado el Siniestro ${job.service_number}...`, "system");
}
else if (job.status === 'DONE') {
addLog(`Job [#${job.id}] - ✅ Siniestro ${job.service_number} guardado con éxito.`, "success");
}
else if (job.status === 'FAILED') {
addLog(`Job [#${job.id}] - ❌ Fallo en Siniestro ${job.service_number}: ${job.error_msg || 'Error desconocido'}`, "error");
}
knownJobs[job.id] = job.status;
}
});
}
} catch (e) {}
}
</script>
</body>
</html>