Files
whatsapp/modules/turnero/views/display.php
T
2026-06-16 07:02:04 -05:00

586 lines
24 KiB
PHP

<?php
// Leer configuración visual del laboratorio
$_dispCfg = [];
try {
$__pdo = Database::getInstance()->getConnection();
$__rows = $__pdo->query("SELECT clave, valor FROM lab_config WHERE clave IN ('empresa_nombre','doc_logo_base64','doc_color')")->fetchAll(PDO::FETCH_KEY_PAIR);
$_dispCfg = $__rows ?: [];
} catch (\Throwable $_) {}
$_labNombre = htmlspecialchars($_dispCfg['empresa_nombre'] ?? 'Sistema de Turnos');
$_labLogo = $_dispCfg['doc_logo_base64'] ?? '';
$_labColor = preg_match('/^#[0-9a-fA-F]{3,8}$/', $_dispCfg['doc_color'] ?? '') ? $_dispCfg['doc_color'] : '#1565c0';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pantalla de Turnos</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
/* ── Base ─────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; }
html, body {
margin: 0; padding: 0;
height: 100%; width: 100%;
overflow: hidden;
background: #f0f4f8;
color: #1e293b;
font-family: 'Segoe UI', system-ui, sans-serif;
}
/* ── Variables de color de marca ─────────────────── */
:root {
--brand: <?= $_labColor ?>;
--brand-dark: color-mix(in srgb, <?= $_labColor ?> 70%, #000);
--brand-light:color-mix(in srgb, <?= $_labColor ?> 15%, #fff);
}
/* ── Layout ───────────────────────────────────────── */
.display-grid {
display: grid;
grid-template-rows: auto 1fr auto;
height: 100vh;
gap: 0;
}
/* ── Header ───────────────────────────────────────── */
.display-header {
display: flex; align-items: center; justify-content: space-between;
padding: .6rem 2rem;
background: var(--brand);
flex-shrink: 0;
gap: 1rem;
}
.header-brand {
display: flex; align-items: center; gap: .8rem;
flex: 1; min-width: 0;
}
.header-brand img.logo {
height: 44px; max-width: 120px;
object-fit: contain;
background: rgba(255,255,255,.12);
border-radius: 8px;
padding: 4px 6px;
}
.header-brand .lab-nombre {
font-size: clamp(.9rem, 2vw, 1.3rem);
font-weight: 800; color: #fff;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.header-brand .lab-subtitulo {
font-size: .72rem; color: rgba(255,255,255,.65);
font-weight: 500; text-transform: uppercase; letter-spacing: 1.5px;
display: block; margin-top: 1px;
}
.header-right {
display: flex; align-items: center; gap: .75rem; flex-shrink: 0;
}
.display-header .reloj {
font-size: clamp(1.1rem, 2.5vw, 1.6rem);
font-weight: 800; color: rgba(255,255,255,.95);
font-variant-numeric: tabular-nums;
letter-spacing: 1px;
}
.estado-chip {
font-size: .75rem; padding: .22rem .65rem; border-radius: 20px;
font-weight: 700; display: inline-flex; align-items: center; gap: .3rem;
}
.estado-chip.conectado { background: rgba(255,255,255,.2); color: #fff; }
.estado-chip.conectando { background: rgba(0,0,0,.25); color: #fde68a; }
.estado-chip.error { background: rgba(239,68,68,.3); color: #fecaca; }
#btn-activar-sonido {
background: rgba(255,255,255,.15); border: 1px solid rgba(255,255,255,.3);
color: rgba(255,255,255,.85); border-radius: 8px; padding: 5px 12px;
font-size: .78rem; cursor: pointer;
display: flex; align-items: center; gap: 5px; white-space: nowrap;
}
#btn-activar-sonido:hover { background: rgba(255,255,255,.25); }
/* ── Cuerpo ───────────────────────────────────────── */
.display-body {
display: grid;
grid-template-columns: 1fr 320px;
height: 100%;
overflow: hidden;
}
@media (max-width: 768px) {
.display-body { grid-template-columns: 1fr; }
.cola-panel { display: none !important; }
}
/* ── Panel turno activo ────────────────────────────── */
.turno-activo {
display: flex; flex-direction: column;
align-items: center; justify-content: center;
padding: 2rem; position: relative;
overflow: hidden;
background: #fff;
transition: background .5s;
}
/* Franja decorativa de color en el borde izquierdo */
.turno-activo::before {
content: ''; position: absolute; left: 0; top: 0; bottom: 0;
width: 10px; background: var(--prio-color, var(--brand));
transition: background .5s;
}
.turno-activo .etiqueta {
font-size: clamp(.8rem, 1.8vw, 1.1rem);
color: #94a3b8; font-weight: 700;
text-transform: uppercase; letter-spacing: 3px;
margin-bottom: .25rem;
}
.turno-activo .codigo-grande {
font-size: clamp(5rem, 20vw, 15rem);
font-weight: 900; line-height: 1;
letter-spacing: -4px;
color: var(--prio-color, var(--brand));
transition: color .4s;
}
.turno-activo .nombre-pac {
font-size: clamp(1rem, 2.8vw, 1.8rem);
font-weight: 700; color: #334155;
margin-top: .4rem; text-align: center;
}
.turno-activo .prio-badge {
display: inline-flex; align-items: center; gap: .5rem;
padding: .45rem 1.4rem; border-radius: 30px;
font-size: clamp(.8rem, 1.6vw, 1.1rem); font-weight: 700;
margin-top: 1rem;
background: var(--brand-light); color: var(--brand-dark);
transition: background .4s, color .4s;
}
.turno-activo .sin-turno {
font-size: clamp(1.2rem, 3vw, 2.2rem);
color: #cbd5e1; text-align: center;
}
/* Anillo de animación */
@keyframes ping-ring {
0% { transform: scale(.8); opacity: .7; }
100% { transform: scale(2.8); opacity: 0; }
}
.ring-anim {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
pointer-events: none; z-index: 0;
}
.ring-anim::before {
content: ''; width: 35vmin; height: 35vmin; border-radius: 50%;
background: transparent; border: 5px solid var(--prio-color, var(--brand)); opacity: 0;
}
.ring-anim.animar::before { animation: ping-ring .75s ease-out 1; }
.turno-activo > *:not(.ring-anim) { position: relative; z-index: 1; }
/* ── Panel de cola ────────────────────────────────── */
.cola-panel {
background: #f8fafc;
border-left: 2px solid #e2e8f0;
display: flex; flex-direction: column;
overflow: hidden;
}
.cola-panel-header {
padding: .9rem 1.2rem .5rem;
font-size: .8rem; font-weight: 800;
color: var(--brand); text-transform: uppercase; letter-spacing: 2px;
border-bottom: 1px solid #e2e8f0;
flex-shrink: 0;
background: #fff;
}
.cola-lista {
flex: 1; overflow-y: auto;
padding: .5rem;
scrollbar-width: thin; scrollbar-color: #cbd5e1 transparent;
}
.cola-item {
display: flex; align-items: center; gap: .7rem;
padding: .55rem .75rem; border-radius: 10px;
margin-bottom: .3rem;
background: #fff;
border: 1px solid #e2e8f0;
transition: border-color .2s;
}
.cola-item:first-child {
border-color: var(--brand);
background: var(--brand-light);
}
.cola-item .cod-badge {
font-size: 1.15rem; font-weight: 900;
min-width: 50px; text-align: center;
padding: .18rem .4rem; border-radius: 7px;
color: #fff;
}
.cola-item .pac-info { flex: 1; min-width: 0; }
.cola-item .pac-nombre {
font-size: .83rem; color: #1e293b; font-weight: 600;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.cola-item .pac-hora { font-size: .7rem; color: #94a3b8; }
.cola-vacia { color: #94a3b8; text-align: center; padding: 3rem 1rem; font-size: .9rem; }
/* ── Footer ───────────────────────────────────────── */
.display-footer {
display: flex; justify-content: center; align-items: center;
gap: 2rem; flex-wrap: wrap;
padding: .5rem 2rem;
background: var(--brand);
flex-shrink: 0;
}
.stat-item { text-align: center; }
.stat-item .val { font-size: 1.25rem; font-weight: 800; color: #fff; }
.stat-item .lbl { font-size: .65rem; color: rgba(255,255,255,.65); text-transform: uppercase; letter-spacing: 1px; }
.stat-sep { width: 1px; height: 28px; background: rgba(255,255,255,.2); }
</style>
</head>
<body>
<div class="display-grid">
<!-- ── Cabecera ─────────────────────────────────────── -->
<header class="display-header">
<div class="header-brand">
<?php if ($_labLogo): ?>
<img class="logo" src="<?= htmlspecialchars($_labLogo) ?>" alt="Logo">
<?php endif; ?>
<div>
<div class="lab-nombre"><?= $_labNombre ?></div>
<span class="lab-subtitulo" id="lbl-area">Sistema de Turnos</span>
</div>
</div>
<div class="header-right">
<span id="chip-estado" class="estado-chip" style="display:none"></span>
<button id="btn-activar-sonido" onclick="activarSonido()" title="Activar sonido">
<i class="fas fa-volume-mute"></i> Sonido
</button>
<div class="reloj" id="reloj">--:--:--</div>
</div>
</header>
<!-- ── Cuerpo ────────────────────────────────────────── -->
<div class="display-body" id="display-body">
<!-- Turno activo -->
<div class="turno-activo" id="zona-activo">
<div class="ring-anim" id="ring"></div>
<div class="etiqueta">Turno en atención</div>
<div class="codigo-grande" id="codigo-activo">—</div>
<div class="nombre-pac" id="nombre-activo"></div>
<div class="prio-badge" id="prio-activo">
<i class="fas fa-hourglass-half"></i> Esperando turno
</div>
</div>
<!-- Panel publicitario (se activa con ?video=URL) -->
<div id="video-panel" style="display:none;overflow:hidden;background:#000;position:relative">
<video id="video-pub" autoplay muted loop playsinline
style="width:100%;height:100%;object-fit:cover">
<source id="video-src" src="">
</video>
</div>
<!-- Lista de cola -->
<div class="cola-panel">
<div class="cola-panel-header">
<i class="fas fa-list-ol me-1"></i>EN ESPERA
</div>
<div class="cola-lista" id="cola-lista">
<div class="cola-vacia">
<i class="fas fa-hourglass-start fa-2x mb-2 d-block"></i>
Cola vacía
</div>
</div>
</div>
</div>
<!-- ── Footer stats ──────────────────────────────────── -->
<footer class="display-footer">
<div class="stat-item">
<div class="val" id="stat-espera">—</div>
<div class="lbl">En espera</div>
</div>
<div class="stat-sep"></div>
<div class="stat-item">
<div class="val" id="stat-atendidos">—</div>
<div class="lbl">Atendidos hoy</div>
</div>
<div class="stat-sep"></div>
<div class="stat-item">
<div class="val" id="stat-total">—</div>
<div class="lbl">Total del día</div>
</div>
<div class="stat-sep"></div>
<div class="stat-item">
<div class="val" id="stat-tiempo">—</div>
<div class="lbl">Tiempo prom.</div>
</div>
</footer>
</div>
<script>
// ── Config desde URL ─────────────────────────────────────────
const params = new URLSearchParams(location.search);
const area = params.get('display') || 'recepcion';
const lugarId = params.get('lugar_id') || '';
const BASE_API = '<?= BASE_URL ?>modules/turnero/api/';
// Etiqueta de área
document.getElementById('lbl-area').textContent =
area === 'lugar' && lugarId ? `Lugar #${lugarId} — Turnos` : 'Recepción — Turnos';
// ── Video publicitario desde URL ?video=URL ───────────────────
(function initVideo() {
const videoUrl = params.get('video');
if (!videoUrl) return;
const panel = document.getElementById('video-panel');
const src = document.getElementById('video-src');
const vid = document.getElementById('video-pub');
const body = document.getElementById('display-body');
src.src = videoUrl;
vid.load();
panel.style.display = 'block';
// 3 columnas: turno | video | cola
body.style.gridTemplateColumns = '1fr 320px 280px';
})();
// ── Helper: oscurecer color hex ───────────────────────────────
function shadeColor(hex, pct) {
const num = parseInt(hex.replace('#',''), 16);
const r = Math.max(0, Math.min(255, (num >> 16) + pct));
const g = Math.max(0, Math.min(255, ((num >> 8) & 0xff) + pct));
const b = Math.max(0, Math.min(255, (num & 0xff) + pct));
return `rgb(${r},${g},${b})`;
}
function actualizarReloj() {
document.getElementById('reloj').textContent =
new Date().toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
actualizarReloj();
setInterval(actualizarReloj, 1000);
// ── Audio ─────────────────────────────────────────────────────
let audioCtx = null;
let sonidoActivo = false;
function activarSonido() {
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Beep silencioso para desbloquear el contexto en el mismo gesto
const g = audioCtx.createGain();
g.gain.setValueAtTime(0.001, audioCtx.currentTime);
const o = audioCtx.createOscillator();
o.connect(g); g.connect(audioCtx.destination);
o.start(); o.stop(audioCtx.currentTime + 0.05);
} catch (_) {}
sonidoActivo = true;
const btn = document.getElementById('btn-activar-sonido');
if (btn) {
btn.innerHTML = '<i class="fas fa-volume-up"></i> Sonido ON';
btn.style.background = 'rgba(34,197,94,0.2)';
btn.style.borderColor = 'rgba(34,197,94,0.5)';
btn.style.color = '#86efac';
btn.onclick = null;
btn.style.cursor = 'default';
// Reproducir beep de prueba al activar
setTimeout(playBeep, 100);
}
}
// Desbloquear también si el usuario toca/clica cualquier parte de la pantalla
document.addEventListener('click', () => { if (!sonidoActivo) activarSonido(); }, { once: true });
document.addEventListener('touchstart', () => { if (!sonidoActivo) activarSonido(); }, { once: true });
function playBeep() {
if (sonidoActivo && audioCtx) {
try {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sine';
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.frequency.setValueAtTime(880, audioCtx.currentTime);
osc.frequency.setValueAtTime(1100, audioCtx.currentTime + 0.1);
osc.frequency.setValueAtTime(880, audioCtx.currentTime + 0.2);
gain.gain.setValueAtTime(0.35, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.65);
osc.start(audioCtx.currentTime);
osc.stop(audioCtx.currentTime + 0.65);
} catch (_) {}
}
}
function anunciarTurno(codigo, nombre) {
// 1. Beep electrónico
playBeep();
// 2. Voz sintética — solo el número del turno, sin el nombre
if ('speechSynthesis' in window) {
setTimeout(() => {
window.speechSynthesis.cancel();
const letras = codigo.split('').join(' '); // "A 0 1" para mejor pronunciación
const utt = new SpeechSynthesisUtterance(`Turno ${letras}`);
utt.lang = 'es-CO';
utt.rate = 0.85;
utt.pitch = 1.05;
utt.volume = 1;
window.speechSynthesis.speak(utt);
}, 700);
}
}
// ── Estado previo ─────────────────────────────────────────────
let lastCodigoActivo = null;
// ── Render ────────────────────────────────────────────────────
function renderSnapshot(snap) {
const activo = snap.activo;
const cola = snap.cola || [];
const stats = snap.stats || {};
// Turno activo
const elCodigo = document.getElementById('codigo-activo');
const elNombre = document.getElementById('nombre-activo');
const elPrio = document.getElementById('prio-activo');
const elRing = document.getElementById('ring');
if (activo) {
// ¿Cambió el turno? → animar + sonido
if (activo.codigo !== lastCodigoActivo) {
anunciarTurno(activo.codigo, activo.paciente_nombre || '');
elRing.classList.remove('animar');
void elRing.offsetWidth;
elRing.classList.add('animar');
lastCodigoActivo = activo.codigo;
}
const prioColor = activo.prioridad_color || '#1565c0';
const zona = document.getElementById('zona-activo');
zona.style.setProperty('--prio-color', prioColor);
zona.style.background = prioColor + '12'; // fondo muy suave con color de prioridad
elCodigo.textContent = activo.codigo;
elCodigo.style.color = '';
elNombre.textContent = activo.paciente_nombre || '';
elPrio.style.background = prioColor + '22';
elPrio.style.color = prioColor;
elPrio.innerHTML = `<i class="fas fa-ticket-alt"></i> ${activo.prioridad_codigo} &mdash; ${activo.prioridad_nombre}`;
} else {
const zona = document.getElementById('zona-activo');
zona.style.removeProperty('--prio-color');
zona.style.background = '#fff';
elCodigo.textContent = '—';
elCodigo.style.color = '#cbd5e1';
elNombre.textContent = '';
elPrio.style.background = '#f1f5f9';
elPrio.style.color = '#94a3b8';
elPrio.innerHTML = '<i class="fas fa-hourglass-half"></i> Esperando turno';
lastCodigoActivo = null;
}
// Lista de cola (excluir el activo si está ahí)
const colaEspera = cola.filter(t =>
t.estado === 'espera' || t.estado === 'en_espera_lugar'
);
const elLista = document.getElementById('cola-lista');
if (colaEspera.length === 0) {
elLista.innerHTML = `
<div class="cola-vacia">
<i class="fas fa-hourglass-start fa-2x mb-2 d-block"></i>
Cola vacía
</div>`;
} else {
elLista.innerHTML = colaEspera.map((t, idx) => {
const hora = t.creado_at ? new Date(t.creado_at).toLocaleTimeString('es-CO',
{ hour: '2-digit', minute: '2-digit' }) : '';
return `
<div class="cola-item">
<span class="cod-badge" style="background:${t.prioridad_color}22;color:${t.prioridad_color}">${t.codigo}</span>
<div class="pac-info">
<div class="pac-nombre">${escHtml(t.paciente_nombre || 'Paciente')}</div>
<div class="pac-hora">${t.prioridad_nombre} &bull; ${hora}</div>
</div>
${idx === 0 ? '<i class="fas fa-arrow-right" style="color:#3b82f6;font-size:.8rem"></i>' : ''}
</div>`;
}).join('');
}
// Stats
const enEspera = parseInt(stats.en_espera || 0) + parseInt(stats.en_espera_lugar || 0);
document.getElementById('stat-espera').textContent = enEspera;
document.getElementById('stat-atendidos').textContent = stats.finalizados || 0;
document.getElementById('stat-total').textContent = stats.total || 0;
document.getElementById('stat-tiempo').textContent = stats.tiempo_promedio_atencion
? stats.tiempo_promedio_atencion.substring(0, 5) : '—';
}
function escHtml(str) {
const d = document.createElement('div');
d.appendChild(document.createTextNode(str));
return d.innerHTML;
}
// ── Carga/polling ─────────────────────────────────────────────
let pollTimer = null;
async function cargarSnapshot() {
const url = new URL(BASE_API + 'get_cola.php', location.href);
url.searchParams.set('area', area);
if (lugarId) url.searchParams.set('lugar_id', lugarId);
try {
const res = await fetch(url.toString(), { cache: 'no-store' });
const json = await res.json();
if (json.ok) renderSnapshot(json);
} catch (_) {}
}
// Arrancar polling cada 4 s (funciona aunque SSE falle por proxy)
function iniciarPolling() {
cargarSnapshot();
pollTimer = setInterval(cargarSnapshot, 2000);
}
// ── SSE ───────────────────────────────────────────────────────
const chipEstado = document.getElementById('chip-estado');
let esSource = null;
let reconnectDelay = 2000;
let sseViva = false;
function conectarSSE() {
const sseUrl = new URL(BASE_API + 'sse_turno.php', location.href);
sseUrl.searchParams.set('area', area);
if (lugarId) sseUrl.searchParams.set('lugar_id', lugarId);
esSource = new EventSource(sseUrl.toString());
esSource.addEventListener('open', () => {
reconnectDelay = 2000;
sseViva = true;
// SSE conectado → ocultar chip (el polling garantiza actualización)
chipEstado.style.display = 'none';
});
esSource.addEventListener('cola_update', (e) => {
try {
const snap = JSON.parse(e.data);
renderSnapshot(snap);
} catch (_) {}
});
esSource.addEventListener('error', () => {
sseViva = false;
// Solo mostramos chip cuando SSE falla (el polling sigue funcionando)
chipEstado.style.display = 'none'; // silencioso — polling cubre
esSource.close();
setTimeout(conectarSSE, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
});
}
// ── Inicio ────────────────────────────────────────────────────
iniciarPolling();
conectarSSE();
</script>
</body>
</html>