Añadir pruebas-robot.html

This commit is contained in:
2026-03-05 21:47:01 +00:00
parent 93831d1ce3
commit 1b168ef2f0

224
pruebas-robot.html Normal file
View File

@@ -0,0 +1,224 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laboratorio Robot HomeServe</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</h1>
</div>
<a href="servicios.html" class="text-xs font-bold text-slate-500 hover:text-blue-600 flex items-center gap-2"><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">
<h2 class="font-black text-lg text-slate-800 mb-6 flex items-center gap-2 border-b border-slate-100 pb-4">
<i data-lucide="send" class="text-blue-500 w-5 h-5"></i> Lanzar Petición
</h2>
<form id="robotForm" class="space-y-5" onsubmit="sendToRobot(event)">
<div>
<label class="label-modern">Nº Siniestro / Expediente HomeServe</label>
<input type="text" id="r_siniestro" placeholder="Ej: 12345678" class="input-modern" required>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="label-modern">Nuevo Estado (Código HS)</label>
<select id="r_estado" class="input-modern cursor-pointer" required>
<option value="">Seleccionar...</option>
<option value="CITADO">CITADO (Cita Concertada)</option>
<option value="ESPERA">ESPERA (Espera Cliente)</option>
<option value="TERMINADO">TERMINADO (Finalizado)</option>
<option value="ANULADO">ANULADO (Rechazado)</option>
</select>
</div>
<div>
<label class="label-modern">Fecha Próx. Cita (Opcional)</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>
<div>
<label class="label-modern">Observaciones (OBLIGATORIO para el Robot)</label>
<textarea id="r_obs" rows="3" placeholder="Describe qué ha pasado con el siniestro..." class="input-modern resize-none" required></textarea>
</div>
<div class="flex items-center gap-3 pt-2">
<input type="checkbox" id="r_info" class="w-5 h-5 rounded border-slate-300 text-blue-600 cursor-pointer">
<label for="r_info" class="text-xs font-bold text-slate-600 cursor-pointer uppercase tracking-wider">Marcar "Informado al cliente"</label>
</div>
<button type="submit" id="btnLaunch" class="w-full bg-blue-600 hover:bg-blue-700 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">
<i data-lucide="rocket" class="w-4 h-4"></i> Inyectar en DB Local
</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">
<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'
? 'http://localhost:3000'
: 'https://integrarepara-api.integrarepara.es';
let knownJobs = {}; // Para guardar el estado de los trabajos y saber si cambian
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) {
alert("Debes iniciar sesión en la plataforma principal primero.");
window.location.href = "index.html";
return;
}
lucide.createIcons();
// Arrancamos el monitor (consulta la API cada 3 segundos)
addLog("Conectado a la Base de Datos. Escuchando la cola...", "system");
setInterval(fetchQueueStatus, 3000);
fetchQueueStatus(); // Primera llamada inmediata
});
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');
btn.disabled = true;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
lucide.createIcons();
const payload = {
service_number: document.getElementById('r_siniestro').value.trim(),
new_status: document.getElementById('r_estado').value,
appointment_date: document.getElementById('r_fecha').value.trim(),
observation: document.getElementById('r_obs').value.trim(),
inform_client: document.getElementById('r_info').checked
};
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 el siniestro ${payload.service_number}`, "info");
document.getElementById('robotForm').reset();
} 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 = '<i data-lucide="rocket" class="w-4 h-4"></i> Inyectar en DB Local';
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) {
// Ordenamos de más antiguo a más nuevo para que los logs salgan en orden
const jobs = data.jobs.reverse();
jobs.forEach(job => {
const prevStatus = knownJobs[job.id];
// Si el estado ha cambiado, lo logueamos
if (prevStatus !== job.status) {
// Si es la primera vez que lo vemos, y no está PENDING, no inundamos el log
// a menos que acabe de cambiar.
if (!prevStatus && job.status !== 'PENDING') {
knownJobs[job.id] = job.status;
return;
}
if (job.status === 'PENDING') {
// Lo obviamos porque el POST ya lanza el log de 'encolado'
}
else 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 en HomeServe.`, "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) {
// Silencioso para no ensuciar el log si parpadea la red
}
}
</script>
</body>
</html>