Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1170 lines
52 KiB
PHP
1170 lines
52 KiB
PHP
<?php
|
|
/**
|
|
* Puesto Lugar / Estación de Servicio — Módulo Turnero
|
|
* Genérica: sirve para Toma de Muestras 1, 2, Rayos X, etc.
|
|
* Requiere login + módulo turnero.
|
|
*
|
|
* URL: /modules/turnero/views/lugar.php?lugar_id=X
|
|
* Si no se pasa lugar_id, muestra un selector al entrar.
|
|
*/
|
|
require_once __DIR__ . '/../../../config/config.php';
|
|
if (!isUserLoggedIn()) {
|
|
header('Location: ' . BASE_URL . 'login.php');
|
|
exit;
|
|
}
|
|
|
|
// Cargar lista de lugares activos
|
|
try {
|
|
$pdo = Database::getInstance()->getConnection();
|
|
$lugares = $pdo->query(
|
|
"SELECT id, nombre, descripcion FROM turnero_lugares WHERE activo = 1 ORDER BY sort_order ASC"
|
|
)->fetchAll(PDO::FETCH_ASSOC);
|
|
} catch (\Throwable) {
|
|
$lugares = [];
|
|
}
|
|
|
|
$lugarIdParam = isset($_GET['lugar_id']) ? (int)$_GET['lugar_id'] : 0;
|
|
|
|
// Resolver nombre del lugar para el título
|
|
$lugarNombre = 'Estación de Servicio';
|
|
foreach ($lugares as $l) {
|
|
if ((int)$l['id'] === $lugarIdParam) {
|
|
$lugarNombre = $l['nombre'];
|
|
break;
|
|
}
|
|
}
|
|
|
|
$adminNombre = $_SESSION['admin_user']['full_name'] ?? $_SESSION['admin_user']['username'] ?? 'Operador';
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title><?= htmlspecialchars($lugarNombre) ?> — Turnero</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">
|
|
<link href="<?= BASE_URL ?>assets/css/styles.css?v=12" rel="stylesheet">
|
|
<style>
|
|
/* ── Layout ── */
|
|
.lugar-layout {
|
|
display: grid;
|
|
grid-template-columns: 300px 1fr;
|
|
height: calc(100vh - 52px);
|
|
overflow: hidden;
|
|
}
|
|
@media (max-width: 860px) {
|
|
.lugar-layout { grid-template-columns: 1fr; position: relative; overflow: hidden; }
|
|
.lugar-cola { transition: transform .2s ease; }
|
|
.lugar-cola.mobile-oculta { transform: translateX(-100%); position: absolute; inset: 0; pointer-events: none; }
|
|
.lugar-ficha { position: absolute; inset: 0; background: #fff; z-index: 10; transform: translateX(100%); transition: transform .2s ease; overflow-y: auto; }
|
|
.lugar-ficha.mobile-visible { transform: translateX(0); }
|
|
.btn-volver-cola { display: inline-flex !important; align-items: center; gap: 6px; }
|
|
}
|
|
|
|
/* ── Columna cola ── */
|
|
.lugar-cola {
|
|
background: #f8fafc;
|
|
border-right: 1px solid #e2e8f0;
|
|
display: flex; flex-direction: column; overflow: hidden;
|
|
}
|
|
.lugar-cola-hdr {
|
|
padding: .85rem 1rem .5rem;
|
|
background: #fff; border-bottom: 1px solid #e2e8f0;
|
|
flex-shrink: 0;
|
|
}
|
|
.cola-items { flex: 1; overflow-y: auto; padding: .4rem; }
|
|
.cola-card {
|
|
background: #fff; border: 1px solid #e2e8f0; border-radius: 10px;
|
|
padding: .55rem .8rem; margin-bottom: .35rem;
|
|
display: flex; align-items: center; gap: .55rem;
|
|
}
|
|
.cola-card.activo { border-color: #6366f1; box-shadow: 0 0 0 2px #c7d2fe; }
|
|
.cola-card.en-servicio-card { border-color: #16a34a; background: #f0fdf4; }
|
|
.cola-card.en-servicio-card.activo { border-color: #16a34a; box-shadow: 0 0 0 2px #bbf7d0; }
|
|
.prio-dot {
|
|
width: 34px; height: 34px; border-radius: 50%; flex-shrink: 0;
|
|
display: flex; align-items: center; justify-content: center;
|
|
font-size: 1rem; font-weight: 800; color: #fff;
|
|
}
|
|
.turno-info .cod { font-size: .98rem; font-weight: 700; }
|
|
.turno-info .pac { font-size: .75rem; color: #64748b;
|
|
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
.cola-vacia { text-align: center; padding: 2.5rem 1rem; color: #94a3b8; font-size: .88rem; }
|
|
|
|
/* ── Columna ficha ── */
|
|
.lugar-ficha { overflow-y: auto; padding: 1.2rem 1.5rem; background: #fff; }
|
|
.ficha-placeholder {
|
|
height: 100%; display: flex; flex-direction: column;
|
|
align-items: center; justify-content: center;
|
|
color: #94a3b8; text-align: center;
|
|
}
|
|
|
|
/* ── Secciones ── */
|
|
.ficha-sec {
|
|
background: #f8fafc; border: 1px solid #e2e8f0;
|
|
border-radius: 12px; padding: 1.1rem 1.2rem; margin-bottom: 1rem;
|
|
}
|
|
.ficha-sec h6 {
|
|
font-size: .75rem; text-transform: uppercase; letter-spacing: .08em;
|
|
color: #475569; margin-bottom: .75rem;
|
|
}
|
|
|
|
/* ── Datos paciente ── */
|
|
.pac-dato { display: flex; gap: .5rem; align-items: baseline; margin-bottom: .3rem; }
|
|
.pac-dato .lbl { font-size: .75rem; color: #94a3b8; min-width: 80px; }
|
|
.pac-dato .val { font-size: .88rem; color: #1e293b; font-weight: 500; }
|
|
|
|
/* ── Exámenes ── */
|
|
.exam-pill {
|
|
display: inline-flex; align-items: center; gap: .3rem;
|
|
background: #eff6ff; color: #1d4ed8; border-radius: 20px;
|
|
padding: .2rem .65rem; font-size: .78rem; font-weight: 600;
|
|
margin: .15rem;
|
|
}
|
|
|
|
/* ── Consentimientos ── */
|
|
.consent-row {
|
|
display: flex; align-items: center; gap: .6rem;
|
|
padding: .55rem .7rem; border-radius: 10px; margin-bottom: .4rem;
|
|
font-size: .84rem; border: 1px solid transparent;
|
|
}
|
|
.consent-row.firmado { background: #f0fdf4; color: #166534; border-color: #bbf7d0; }
|
|
.consent-row.rechazado { background: #f8fafc; color: #64748b; border-color: #e2e8f0; }
|
|
.consent-row.enviado { background: #eff6ff; color: #1e40af; border-color: #bfdbfe; }
|
|
.consent-row.pendiente { background: #fffbeb; color: #92400e; border-color: #fde68a; }
|
|
.consent-row.visto { background: #faf5ff; color: #6b21a8; border-color: #ddd6fe; }
|
|
.consent-row .nom-form { flex: 1; font-weight: 500; }
|
|
.consent-row .c-badge { font-size: .68rem; padding: 1px 8px; border-radius: 99px;
|
|
border: 1px solid currentColor; font-weight: 700; opacity: .85; }
|
|
.consent-row .acciones-consent { display: flex; gap: .3rem; flex-shrink: 0; }
|
|
.consent-row .acciones-consent .btn { font-size: .72rem; padding: 2px 9px; border-radius: 7px; }
|
|
|
|
/* ── Barra de acciones ── */
|
|
.ficha-acciones {
|
|
position: sticky; bottom: 0;
|
|
background: #fff; border-top: 1px solid #e2e8f0;
|
|
padding: .85rem 0 .2rem; margin-top: 1rem;
|
|
display: flex; gap: .5rem; flex-wrap: wrap; align-items: center;
|
|
}
|
|
|
|
/* ── Modal de firma ── */
|
|
/* ── Selector de lugar (pantalla inicial) ── */
|
|
.selector-lugar-overlay {
|
|
position: fixed; inset: 0; background: #f1f5f9;
|
|
z-index: 200; display: flex; align-items: center; justify-content: center;
|
|
}
|
|
.selector-lugar-box {
|
|
background: #fff; border-radius: 20px; padding: 2.5rem;
|
|
width: min(90vw, 480px); box-shadow: 0 8px 40px rgba(0,0,0,.12); text-align: center;
|
|
}
|
|
.selector-lugar-box h2 { font-size: 1.4rem; font-weight: 700; margin-bottom: 1.5rem; }
|
|
|
|
/* ── Toast ── */
|
|
.rec-toast {
|
|
position: fixed; bottom: 2rem; right: 2rem; z-index: 9999;
|
|
display: flex; align-items: center; gap: .7rem;
|
|
padding: .8rem 1.2rem; border-radius: 12px;
|
|
background: #fff; border: 1px solid #e2e8f0;
|
|
box-shadow: 0 8px 30px rgba(0,0,0,.12);
|
|
font-size: .9rem; font-weight: 500;
|
|
transform: translateY(120%); opacity: 0;
|
|
transition: transform .3s ease, opacity .3s ease;
|
|
pointer-events: none;
|
|
}
|
|
.rec-toast.show { transform: translateY(0); opacity: 1; }
|
|
.rec-toast.success { border-left: 4px solid #22c55e; }
|
|
.rec-toast.info { border-left: 4px solid #3b82f6; }
|
|
.rec-toast.warn { border-left: 4px solid #f59e0b; }
|
|
.rec-toast.error { border-left: 4px solid #ef4444; }
|
|
.rec-toast .ico { font-size: 1.2rem; }
|
|
.rec-toast.success .ico { color: #22c55e; }
|
|
.rec-toast.info .ico { color: #3b82f6; }
|
|
.rec-toast.warn .ico { color: #f59e0b; }
|
|
.rec-toast.error .ico { color: #ef4444; }
|
|
|
|
/* ── Indicador de bloqueo ── */
|
|
.bloqueo-banner {
|
|
background: #fef2f2; border: 1px solid #fca5a5; border-radius: 10px;
|
|
padding: .65rem 1rem; font-size: .85rem; color: #991b1b;
|
|
display: flex; align-items: center; gap: .5rem; margin-bottom: .75rem;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
|
|
<?php
|
|
$SIDEBAR_TITLE = 'Turnero';
|
|
$SIDEBAR_ICON = 'fas fa-ticket-alt';
|
|
require_once __DIR__ . '/../../../shared/components/sidebar.php';
|
|
?>
|
|
|
|
<!-- ══ Selector inicial de lugar (si no viene en URL) ════════ -->
|
|
<div id="overlay-selector" class="selector-lugar-overlay" <?= $lugarIdParam ? 'style="display:none"' : '' ?>>
|
|
<div class="selector-lugar-box">
|
|
<i class="fas fa-map-marker-alt fa-2x text-primary mb-3"></i>
|
|
<h2>Seleccione su estación</h2>
|
|
<select id="sel-lugar-init" class="form-select mb-3">
|
|
<option value="">— Elija un lugar —</option>
|
|
<?php foreach ($lugares as $l): ?>
|
|
<option value="<?= (int)$l['id'] ?>"><?= htmlspecialchars($l['nombre']) ?></option>
|
|
<?php endforeach; ?>
|
|
</select>
|
|
<button class="btn btn-primary w-100" onclick="confirmarLugar()">
|
|
<i class="fas fa-check me-1"></i>Confirmar
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<main class="main-content" style="padding:0">
|
|
|
|
<!-- ── Top bar ──────────────────────────────────────────── -->
|
|
<div class="content-header d-flex align-items-center justify-content-between px-3 py-2 border-bottom bg-white"
|
|
style="position:sticky;top:0;z-index:100;min-height:52px">
|
|
<div class="d-flex align-items-center gap-2">
|
|
<i class="fas fa-map-marker-alt text-primary"></i>
|
|
<strong id="lbl-lugar-titulo"><?= htmlspecialchars($lugarNombre) ?></strong>
|
|
<span id="badge-turno-activo" class="badge bg-primary ms-1 d-none" id="badge-cod-activo"></span>
|
|
</div>
|
|
<div class="d-flex align-items-center gap-2">
|
|
<span class="text-muted small d-none d-md-inline"><?= htmlspecialchars($adminNombre) ?></span>
|
|
<button class="btn btn-sm btn-outline-secondary" onclick="cambiarLugar()">
|
|
<i class="fas fa-exchange-alt me-1"></i>Cambiar
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="lugar-layout">
|
|
|
|
<!-- ══ Cola ═══════════════════════════════════════════ -->
|
|
<div class="lugar-cola">
|
|
<div class="lugar-cola-hdr">
|
|
<div class="d-flex align-items-center justify-content-between mb-2">
|
|
<span class="fw-semibold text-secondary" style="font-size:.78rem;text-transform:uppercase;letter-spacing:.05em">
|
|
<i class="fas fa-list-ol me-1"></i>EN ESPERA
|
|
</span>
|
|
<span class="badge bg-primary rounded-pill" id="badge-count">0</span>
|
|
</div>
|
|
<button class="btn btn-primary w-100 py-2" id="btn-llamar" onclick="llamarSiguiente()">
|
|
<i class="fas fa-bell me-2"></i>Llamar siguiente
|
|
</button>
|
|
</div>
|
|
<div class="cola-items" id="cola-items">
|
|
<div class="cola-vacia">
|
|
<i class="fas fa-hourglass-start fa-2x mb-2 d-block"></i>
|
|
Cola vacía
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ══ Ficha del turno ════════════════════════════════ -->
|
|
<div class="lugar-ficha" id="lugar-ficha">
|
|
|
|
<button class="btn btn-sm btn-outline-secondary btn-volver-cola mb-3"
|
|
style="display:none" onclick="volverACola()">
|
|
<i class="fas fa-arrow-left"></i> Cola
|
|
</button>
|
|
|
|
<div class="ficha-placeholder" id="ficha-placeholder">
|
|
<i class="fas fa-stethoscope fa-3x mb-3" style="color:#cbd5e1"></i>
|
|
<p class="fw-semibold mb-1">Sin turno activo</p>
|
|
<small class="text-muted">Pulse "Llamar siguiente" o espere a que llegue el turno</small>
|
|
</div>
|
|
|
|
<div id="ficha-turno" class="d-none">
|
|
|
|
<!-- Encabezado turno -->
|
|
<div class="d-flex align-items-center gap-3 mb-3">
|
|
<div id="ficha-prio-dot" class="prio-dot"
|
|
style="width:52px;height:52px;border-radius:12px;font-size:1.6rem;font-weight:900">—</div>
|
|
<div>
|
|
<div class="h4 mb-0 fw-bold" id="ficha-codigo">—</div>
|
|
<div class="text-muted small" id="ficha-prio-nombre"></div>
|
|
</div>
|
|
<span class="ms-auto badge bg-success-subtle text-success border border-success-subtle"
|
|
id="ficha-estado-badge">en espera</span>
|
|
</div>
|
|
|
|
<!-- ── Sección: Paciente ── -->
|
|
<div class="ficha-sec">
|
|
<h6><i class="fas fa-user me-1"></i>Paciente</h6>
|
|
<div id="bloque-pac-info">
|
|
<div class="pac-dato"><span class="lbl">Nombre</span><span class="val" id="pac-nombre">—</span></div>
|
|
<div class="pac-dato"><span class="lbl">Documento</span><span class="val" id="pac-doc">—</span></div>
|
|
<div class="pac-dato"><span class="lbl">Fecha nac.</span><span class="val" id="pac-fec">—</span></div>
|
|
<div class="pac-dato"><span class="lbl">Celular</span><span class="val" id="pac-cel">—</span></div>
|
|
</div>
|
|
<div id="pac-embarazada" class="d-none mt-2">
|
|
<span class="badge text-bg-danger">
|
|
<i class="fas fa-baby me-1"></i>Paciente embarazada
|
|
</span>
|
|
</div>
|
|
<div id="pac-medico" class="d-none mt-2">
|
|
<div class="pac-dato">
|
|
<span class="lbl">Médico</span>
|
|
<span class="val" id="pac-medico-nombre" style="color:#4f46e5"></span>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="bloque-pac-sin" class="text-muted small">
|
|
<i class="fas fa-info-circle me-1"></i>Sin paciente vinculado
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ── Sección: Exámenes ── -->
|
|
<div class="ficha-sec">
|
|
<h6><i class="fas fa-vial me-1"></i>Exámenes solicitados</h6>
|
|
<div id="lista-examenes-ficha">
|
|
<span class="text-muted small">Sin exámenes registrados</span>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ── Sección: Consentimientos ── -->
|
|
<div class="ficha-sec" id="sec-consent">
|
|
<h6><i class="fas fa-file-signature me-1"></i>Consentimientos informados</h6>
|
|
|
|
<div id="bloqueo-banner" class="bloqueo-banner d-none">
|
|
<i class="fas fa-lock"></i>
|
|
<span>Hay consentimientos pendientes. No puede <strong>finalizar</strong> la atención hasta que estén <strong>firmados</strong> o <strong>rechazados</strong>.</span>
|
|
</div>
|
|
|
|
<div id="lista-consent"></div>
|
|
|
|
<div id="sin-consent" class="text-muted small">
|
|
<i class="fas fa-check-circle text-success me-1"></i>No se requieren consentimientos
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ── Sección: Comentarios y Notas ── -->
|
|
<div class="ficha-sec" id="sec-comentarios">
|
|
<div class="d-flex align-items-center justify-content-between mb-2">
|
|
<h6 class="mb-0"><i class="fas fa-comments me-1" style="color:#8b5cf6"></i>Comentarios del seguimiento</h6>
|
|
</div>
|
|
<div style="display:flex;gap:8px;margin-bottom:10px">
|
|
<textarea id="inp-comentario" class="form-control form-control-sm"
|
|
rows="2" placeholder="Añade un comentario sobre este turno…"
|
|
maxlength="500" style="resize:vertical"></textarea>
|
|
<button class="btn btn-sm btn-primary" onclick="guardarComentario()"
|
|
style="height:fit-content;align-self:flex-end">
|
|
<i class="fas fa-paper-plane"></i>
|
|
</button>
|
|
</div>
|
|
<div id="lista-comentarios" class="text-muted small py-2">
|
|
<i class="fas fa-spinner fa-spin me-1"></i>Cargando comentarios…
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ── Barra de acciones ── -->
|
|
<div class="ficha-acciones">
|
|
<button class="btn btn-primary" id="btn-iniciar" onclick="iniciarAtencion()">
|
|
<i class="fas fa-bell me-1"></i>Llamar
|
|
</button>
|
|
<button class="btn btn-primary d-none" id="btn-finalizar" onclick="finalizarAtencion()">
|
|
<i class="fas fa-flag-checkered me-1"></i>Finalizar
|
|
</button>
|
|
<button class="btn btn-outline-warning d-none" id="btn-regresar" onclick="regresarCola()">
|
|
<i class="fas fa-undo me-1"></i>Regresar a cola
|
|
</button>
|
|
<button class="btn btn-outline-info d-none" id="btn-rellamar" onclick="rellamarTurno()">
|
|
<i class="fas fa-bullhorn me-1"></i>Re-llamar
|
|
</button>
|
|
<button class="btn btn-secondary ms-auto" id="btn-ausente" onclick="marcarAusente()">
|
|
<i class="fas fa-user-slash me-1"></i>Ausente
|
|
</button>
|
|
</div>
|
|
|
|
</div><!-- /ficha-turno -->
|
|
</div><!-- /lugar-ficha -->
|
|
|
|
</div><!-- /lugar-layout -->
|
|
</main>
|
|
|
|
|
|
<script>
|
|
// ── Estado global ─────────────────────────────────────────────
|
|
let lugarId = <?= $lugarIdParam ?: 0 ?>;
|
|
let turnoActivo = null;
|
|
let tieneConsent = false;
|
|
let hayPendientes = false;
|
|
let pollingColaId = null;
|
|
let pollingConsentId = null;
|
|
|
|
const API = '<?= BASE_URL ?>modules/turnero/api/';
|
|
const BASE_WA = '<?= BASE_URL ?>';
|
|
const LUGAR_NOMBRE = document.getElementById('lbl-lugar-titulo')?.textContent || '<?= addslashes($lugarNombre) ?>';
|
|
|
|
|
|
// ── Arranque ──────────────────────────────────────────────────
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
if (lugarId) {
|
|
iniciarPuesto();
|
|
}
|
|
});
|
|
|
|
function iniciarPuesto() {
|
|
recuperarTurnoActivo(); // ver si ya hay un turno en_servicio en esta estación
|
|
cargarCola();
|
|
pollingColaId = setInterval(cargarCola, 7000);
|
|
}
|
|
|
|
// Recupera el turno en_servicio de ESTA estación (si existe) al cargar la página
|
|
async function recuperarTurnoActivo() {
|
|
try {
|
|
const res = await fetch(`${API}get_cola.php?area=lugar&lugar_id=${lugarId}`);
|
|
const json = await res.json();
|
|
if (json.ok && json.activo) {
|
|
await abrirFicha(json.activo);
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
|
|
// ── Selector de lugar ─────────────────────────────────────────
|
|
function confirmarLugar() {
|
|
const sel = document.getElementById('sel-lugar-init');
|
|
const id = parseInt(sel.value);
|
|
if (!id) return mostrarError('Seleccione un lugar.');
|
|
lugarId = id;
|
|
const txt = sel.options[sel.selectedIndex].text;
|
|
document.getElementById('lbl-lugar-titulo').textContent = txt;
|
|
document.getElementById('overlay-selector').style.display = 'none';
|
|
document.title = txt + ' — Turnero';
|
|
iniciarPuesto();
|
|
}
|
|
|
|
function cambiarLugar() {
|
|
clearInterval(pollingColaId);
|
|
clearInterval(pollingConsentId);
|
|
turnoActivo = null;
|
|
resetFicha();
|
|
document.getElementById('overlay-selector').style.display = 'flex';
|
|
}
|
|
|
|
// ── Cola ──────────────────────────────────────────────────────
|
|
async function cargarCola() {
|
|
if (!lugarId) return;
|
|
try {
|
|
const res = await fetch(`${API}get_cola.php?area=lugar&lugar_id=${lugarId}`);
|
|
const json = await res.json();
|
|
if (!json.ok) return;
|
|
renderCola(json);
|
|
} catch (_) {}
|
|
}
|
|
|
|
let _colaMap = new Map(); // id → turno object
|
|
|
|
function renderCola(snap) {
|
|
const items = snap.cola || [];
|
|
const espera = items.filter(t => t.estado === 'en_espera_lugar');
|
|
document.getElementById('badge-count').textContent = espera.length;
|
|
|
|
// Guardar mapa para selección sin llamar
|
|
_colaMap = new Map(items.map(t => [t.id, t]));
|
|
|
|
const lista = document.getElementById('cola-items');
|
|
if (!items.length) {
|
|
lista.innerHTML = `<div class="cola-vacia">
|
|
<i class="fas fa-hourglass-start fa-2x mb-2 d-block"></i>Cola vacía</div>`;
|
|
return;
|
|
}
|
|
lista.innerHTML = items.map(t => {
|
|
const enServicio = t.estado === 'en_servicio';
|
|
const esActivo = turnoActivo?.id == t.id;
|
|
const indicador = enServicio
|
|
? `<div class="ms-auto d-flex flex-column align-items-center" style="gap:1px;flex-shrink:0">
|
|
<i class="fas fa-stethoscope text-success" style="font-size:.85rem"></i>
|
|
<span style="font-size:.58rem;color:#16a34a;font-weight:700">EN SERVICIO</span>
|
|
</div>`
|
|
: `<button onclick="event.stopPropagation();llamarTurnoEspecifico(${t.id})"
|
|
title="Llamar turno ${escHtml(t.codigo)}"
|
|
style="flex-shrink:0;background:#2563eb;border:none;color:#fff;
|
|
border-radius:7px;padding:5px 9px;font-size:.78rem;cursor:pointer">
|
|
<i class="fas fa-bell"></i>
|
|
</button>`;
|
|
const esMuestra = t.solo_muestras == 1;
|
|
const muestraBadge = esMuestra
|
|
? `<div style="font-size:.6rem;font-weight:700;color:#ea580c;letter-spacing:.04em;margin-top:1px">
|
|
<i class="fas fa-plus-square me-1"></i>ENTREGA DE MUESTRAS
|
|
</div>`
|
|
: '';
|
|
const cardStyle = esMuestra
|
|
? 'cursor:pointer;border:2px solid #ea580c!important;background:#fff7ed!important'
|
|
: 'cursor:pointer';
|
|
return `
|
|
<div class="cola-card ${enServicio ? 'en-servicio-card' : ''} ${esActivo ? 'activo' : ''}"
|
|
style="${cardStyle}" onclick="seleccionarSinLlamar(${t.id})"
|
|
title="${enServicio ? 'Ver turno en servicio' : `Ver turno ${escHtml(t.codigo)}`}">
|
|
<div class="prio-dot" style="background:${esMuestra ? '#ea580c' : t.prioridad_color}">${esMuestra ? '<i class="fas fa-plus"></i>' : escHtml(t.prioridad_codigo)}</div>
|
|
<div class="turno-info">
|
|
<div class="cod">${escHtml(t.codigo)}</div>
|
|
<div class="pac">${escHtml(t.paciente_nombre || 'Paciente')}</div>
|
|
${muestraBadge}
|
|
</div>
|
|
${indicador}
|
|
</div>`;
|
|
}).join('');
|
|
}
|
|
|
|
// Abre la ficha SIN llamar ni cambiar estado
|
|
async function seleccionarSinLlamar(turnoId) {
|
|
const t = _colaMap.get(turnoId);
|
|
if (!t) return;
|
|
turnoActivo = t;
|
|
document.getElementById('ficha-placeholder').classList.add('d-none');
|
|
document.getElementById('ficha-turno').classList.remove('d-none');
|
|
document.getElementById('ficha-codigo').textContent = t.codigo;
|
|
document.getElementById('ficha-prio-nombre').textContent = t.prioridad_nombre || '';
|
|
const dot = document.getElementById('ficha-prio-dot');
|
|
dot.textContent = t.prioridad_codigo || '—';
|
|
dot.style.background = t.prioridad_color || '#6366f1';
|
|
const badgeCod = document.getElementById('badge-turno-activo');
|
|
badgeCod.textContent = t.codigo;
|
|
badgeCod.classList.remove('d-none');
|
|
actualizarEstadoBadge(t.estado);
|
|
await cargarFichaSolicitud(t.id);
|
|
clearInterval(pollingConsentId);
|
|
pollingConsentId = setInterval(() => actualizarConsentimientos(turnoActivo?.id), 5000);
|
|
mostrarFichaMobile();
|
|
}
|
|
|
|
async function rellamarDesdeCard(turnoId) {
|
|
const res = await fetch(API + 'llamar_turno.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ area: 'lugar', lugar_id: lugarId, turno_id: turnoId }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok || !json.turno) return;
|
|
await abrirFicha(json.turno);
|
|
}
|
|
|
|
// ── Llamar siguiente: llama al primero en espera ──────────────
|
|
async function llamarSiguiente() {
|
|
await _llamar({});
|
|
}
|
|
|
|
async function llamarTurnoEspecifico(turnoId) {
|
|
await _llamar({ turno_id: turnoId });
|
|
}
|
|
|
|
async function _llamar(extra) {
|
|
if (!lugarId) { mostrarError('Primero seleccione un lugar.'); return; }
|
|
const btn = document.getElementById('btn-llamar');
|
|
btn.disabled = true;
|
|
mostrarToast('Consultando siguiente turno…', 'info', 1500);
|
|
try {
|
|
const res = await fetch(API + 'llamar_turno.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ area: 'lugar', lugar_id: lugarId, ...extra }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) { mostrarError(json.error); return; }
|
|
if (!json.turno) { mostrarToast('Cola vacía — no hay turnos en espera.', 'warn', 3000); return; }
|
|
mostrarLlamando(json.turno.codigo);
|
|
await abrirFicha(json.turno);
|
|
cargarCola();
|
|
} catch (err) {
|
|
mostrarError(err.message);
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// ── Abrir ficha ───────────────────────────────────────────────
|
|
async function abrirFicha(turno) {
|
|
turnoActivo = turno;
|
|
|
|
document.getElementById('ficha-placeholder').classList.add('d-none');
|
|
document.getElementById('ficha-turno').classList.remove('d-none');
|
|
|
|
// Header
|
|
document.getElementById('ficha-codigo').textContent = turno.codigo;
|
|
document.getElementById('ficha-prio-nombre').textContent = turno.prioridad_nombre || '';
|
|
const dot = document.getElementById('ficha-prio-dot');
|
|
dot.textContent = turno.prioridad_codigo || '—';
|
|
dot.style.background = turno.prioridad_color || '#6366f1';
|
|
|
|
const badgeCod = document.getElementById('badge-turno-activo');
|
|
badgeCod.textContent = turno.codigo;
|
|
badgeCod.classList.remove('d-none');
|
|
|
|
actualizarEstadoBadge(turno.estado);
|
|
|
|
// Cargar ficha del paciente/exámenes desde la solicitud
|
|
await cargarFichaSolicitud(turno.id);
|
|
|
|
// Iniciar polling de consentimientos
|
|
clearInterval(pollingConsentId);
|
|
pollingConsentId = setInterval(() => actualizarConsentimientos(turnoActivo?.id), 5000);
|
|
mostrarFichaMobile();
|
|
}
|
|
|
|
// ── Cargar datos de la solicitud del turno ────────────────────
|
|
async function cargarFichaSolicitud(turnoId) {
|
|
try {
|
|
const res = await fetch(`${API}get_consentimientos.php?turno_id=${turnoId}&incluir_solicitud=1`);
|
|
const json = await res.json();
|
|
if (!json.ok) return;
|
|
|
|
const sol = json.solicitud;
|
|
const pac = json.paciente;
|
|
const exams = json.examenes || [];
|
|
let consts = json.consentimientos || [];
|
|
|
|
// Datos del paciente
|
|
// Badge embarazada
|
|
const badgeEmb = document.getElementById('pac-embarazada');
|
|
if (badgeEmb) badgeEmb.classList.toggle('d-none', !(sol && sol.embarazada == 1));
|
|
|
|
const medDiv = document.getElementById('pac-medico');
|
|
if (medDiv) {
|
|
const tieneMedico = sol && sol.medico_nombre;
|
|
medDiv.classList.toggle('d-none', !tieneMedico);
|
|
if (tieneMedico) {
|
|
const esp = sol.medico_especialidad ? ' · ' + sol.medico_especialidad : '';
|
|
document.getElementById('pac-medico-nombre').textContent = sol.medico_nombre + esp;
|
|
}
|
|
}
|
|
|
|
if (pac) {
|
|
document.getElementById('bloque-pac-info').style.display = '';
|
|
document.getElementById('bloque-pac-sin').classList.add('d-none');
|
|
document.getElementById('pac-nombre').textContent =
|
|
pac.nombre_completo || pac.full_name || '—';
|
|
document.getElementById('pac-doc').textContent =
|
|
((pac.tipo_documento||'') + ' ' + (pac.numero_documento||pac.documento||'')).trim() || '—';
|
|
document.getElementById('pac-fec').textContent = pac.fecha_nacimiento || '—';
|
|
document.getElementById('pac-cel').textContent = pac.telefono || pac.celular || '—';
|
|
} else {
|
|
document.getElementById('bloque-pac-info').style.display = 'none';
|
|
document.getElementById('bloque-pac-sin').classList.remove('d-none');
|
|
}
|
|
|
|
// Exámenes
|
|
const listaEx = document.getElementById('lista-examenes-ficha');
|
|
if (exams.length) {
|
|
listaEx.innerHTML = exams.map(e =>
|
|
`<span class="exam-pill"><i class="fas fa-vial"></i>${escHtml(e.codigo)} ${escHtml(e.nombre)}</span>`
|
|
).join('');
|
|
} else {
|
|
listaEx.innerHTML = '<span class="text-muted small">Sin exámenes registrados</span>';
|
|
}
|
|
|
|
// Consentimientos
|
|
renderConsentimientos(consts);
|
|
|
|
// Comentarios
|
|
cargarComentarios(turnoId);
|
|
|
|
} catch (_) {}
|
|
}
|
|
|
|
// ── Consentimientos ───────────────────────────────────────────
|
|
const CONSENT_IC = {
|
|
firmado:'fa-check-circle', rechazado:'fa-ban',
|
|
enviado:'fa-envelope', visto:'fa-eye', pendiente:'fa-clock',
|
|
};
|
|
const CONSENT_LBL = {
|
|
firmado:'Firmado', rechazado:'Rechazado', enviado:'Enviado', visto:'Visto', pendiente:'Pendiente',
|
|
};
|
|
|
|
function renderConsentimientos(lista) {
|
|
tieneConsent = lista.length > 0;
|
|
hayPendientes = lista.some(c => !['firmado', 'rechazado'].includes(c.estado));
|
|
|
|
const sec = document.getElementById('sec-consent');
|
|
const listEl = document.getElementById('lista-consent');
|
|
const sinEl = document.getElementById('sin-consent');
|
|
const banner = document.getElementById('bloqueo-banner');
|
|
const btnIni = document.getElementById('btn-iniciar');
|
|
|
|
if (!tieneConsent) {
|
|
listEl.innerHTML = '';
|
|
sinEl.classList.remove('d-none');
|
|
banner.classList.add('d-none');
|
|
btnIni.disabled = false;
|
|
return;
|
|
}
|
|
|
|
sinEl.classList.add('d-none');
|
|
banner.classList.toggle('d-none', !hayPendientes);
|
|
btnIni.disabled = false;
|
|
const btnFin = document.getElementById('btn-finalizar');
|
|
if (btnFin) btnFin.disabled = hayPendientes;
|
|
|
|
listEl.innerHTML = lista.map(c => {
|
|
const ya = ['firmado','rechazado'].includes(c.estado);
|
|
const ico = CONSENT_IC[c.estado] || 'fa-clock';
|
|
const label = CONSENT_LBL[c.estado] || c.estado;
|
|
const token = escHtml(c.token || '');
|
|
const nomJs = JSON.stringify(c.formulario_nombre || 'Consentimiento');
|
|
const idJs = parseInt(c.id) || 0;
|
|
const tId = parseInt(c.turno_id) || (turnoActivo?.id) || 0;
|
|
|
|
// Firmar aquí: solo si no completado y hay token
|
|
const btnFirmar = (!ya && c.token)
|
|
? `<button class="btn btn-outline-primary" title="Firmar aquí"
|
|
onclick="abrirFirmaPresencial('${token}', ${idJs}, ${nomJs.replace(/"/g,'"')})">
|
|
<i class="fas fa-signature"></i> Firmar
|
|
</button>` : '';
|
|
|
|
// WA / Ver: según estado
|
|
const btnWa = ya
|
|
? (c.token ? `<a href="${BASE_WA}ver_formulario_enviado.php?token=${token}" target="_blank"
|
|
class="btn btn-outline-secondary" title="Ver firmado">
|
|
<i class="fas fa-eye"></i> Ver
|
|
</a>` : '')
|
|
: `<button class="btn btn-outline-success" title="Reenviar por WhatsApp"
|
|
onclick="reenviarConsentimiento(${tId})">
|
|
<i class="fab fa-whatsapp"></i> WA
|
|
</button>`;
|
|
|
|
return `<div class="consent-row ${c.estado}" data-consent-id="${c.id}">
|
|
<i class="fas ${ico}"></i>
|
|
<span class="nom-form">${escHtml(c.formulario_nombre || 'Consentimiento')}</span>
|
|
<span class="c-badge">${label}</span>
|
|
<div class="acciones-consent">${btnFirmar}${btnWa}</div>
|
|
</div>`;
|
|
}).join('');
|
|
}
|
|
|
|
async function actualizarConsentimientos(turnoId) {
|
|
if (!turnoId) return;
|
|
try {
|
|
const res = await fetch(`${API}get_consentimientos.php?turno_id=${turnoId}`);
|
|
const json = await res.json();
|
|
if (!json.ok) return;
|
|
renderConsentimientos(json.consentimientos || []);
|
|
} catch (_) {}
|
|
}
|
|
|
|
async function reenviarConsentimiento(turnoId) {
|
|
try {
|
|
const res = await fetch(API + 'send_consentimiento.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ turno_id: turnoId }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) { mostrarError(json.error); return; }
|
|
await actualizarConsentimientos(turnoId);
|
|
} catch (err) {
|
|
mostrarError(err.message);
|
|
}
|
|
}
|
|
|
|
// ── Modal de firma presencial ─────────────────────────────────
|
|
async function abrirFirmaPresencial(token, consentId, nombreForm) {
|
|
try {
|
|
const res = await fetch(API + 'crear_envio_presencial.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ consent_token: token }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok || !json.form_token) throw new Error(json.error || 'Error al crear envío');
|
|
window.open(BASE_WA + 'form_cliente.php?t=' + encodeURIComponent(json.form_token), '_blank');
|
|
} catch (err) {
|
|
alert('No se pudo abrir el formulario: ' + err.message);
|
|
}
|
|
}
|
|
|
|
|
|
// ── Acciones del turno ────────────────────────────────────────
|
|
async function iniciarAtencion() {
|
|
if (!turnoActivo) return;
|
|
await _llamar({ turno_id: turnoActivo.id });
|
|
}
|
|
|
|
async function finalizarAtencion() {
|
|
if (!turnoActivo) return;
|
|
if (hayPendientes) {
|
|
alert('Debe firmar todos los consentimientos antes de finalizar la atención.');
|
|
return;
|
|
}
|
|
if (!confirm(`¿Finalizar atención del turno ${turnoActivo.codigo}?`)) return;
|
|
|
|
await cambiarEstadoTurno('finalizado');
|
|
}
|
|
|
|
async function marcarAusente() {
|
|
if (!turnoActivo) return;
|
|
if (!confirm(`¿Marcar turno ${turnoActivo.codigo} como AUSENTE?`)) return;
|
|
|
|
await cambiarEstadoTurno('ausente');
|
|
}
|
|
|
|
async function regresarCola() {
|
|
if (!turnoActivo) return;
|
|
if (!confirm(`¿Regresar turno ${turnoActivo.codigo} a la cola del lugar?`)) return;
|
|
|
|
// Regresar a en_espera_lugar
|
|
try {
|
|
const res = await fetch(API + 'cambiar_estado.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
turno_id: turnoActivo.id,
|
|
nuevo_estado: 'en_espera_lugar',
|
|
lugar_id: lugarId,
|
|
}),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) { mostrarError(json.error); return; }
|
|
resetFicha();
|
|
cargarCola();
|
|
} catch (err) {
|
|
mostrarError(err.message);
|
|
}
|
|
}
|
|
|
|
async function cambiarEstadoTurno(nuevoEstado) {
|
|
try {
|
|
const res = await fetch(API + 'cambiar_estado.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ turno_id: turnoActivo.id, nuevo_estado: nuevoEstado }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) { mostrarError(json.error); return; }
|
|
resetFicha();
|
|
cargarCola();
|
|
} catch (err) {
|
|
mostrarError(err.message);
|
|
}
|
|
}
|
|
|
|
// ── Reset ─────────────────────────────────────────────────────
|
|
function resetFicha() {
|
|
clearInterval(pollingConsentId);
|
|
turnoActivo = null;
|
|
tieneConsent = false;
|
|
hayPendientes = false;
|
|
|
|
document.getElementById('ficha-turno').classList.add('d-none');
|
|
document.getElementById('ficha-placeholder').classList.remove('d-none');
|
|
document.getElementById('badge-turno-activo').classList.add('d-none');
|
|
|
|
// Botones al estado inicial
|
|
document.getElementById('btn-iniciar').classList.remove('d-none');
|
|
document.getElementById('btn-iniciar').disabled = false;
|
|
document.getElementById('btn-finalizar').classList.add('d-none');
|
|
document.getElementById('btn-regresar').classList.add('d-none');
|
|
|
|
volverACola();
|
|
}
|
|
|
|
function esMobile() { return window.innerWidth <= 860; }
|
|
function mostrarFichaMobile() {
|
|
if (!esMobile()) return;
|
|
document.getElementById('lugar-ficha').classList.add('mobile-visible');
|
|
document.querySelector('.lugar-cola').classList.add('mobile-oculta');
|
|
}
|
|
function volverACola() {
|
|
document.getElementById('lugar-ficha').classList.remove('mobile-visible');
|
|
document.querySelector('.lugar-cola').classList.remove('mobile-oculta');
|
|
}
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────
|
|
function actualizarEstadoBadge(estado) {
|
|
const el = document.getElementById('ficha-estado-badge');
|
|
const mapa = {
|
|
'en_espera_lugar': ['bg-warning-subtle text-warning border border-warning-subtle', 'En espera'],
|
|
'en_servicio': ['bg-success-subtle text-success border border-success-subtle', 'En servicio'],
|
|
'finalizado': ['bg-secondary-subtle text-secondary border', 'Finalizado'],
|
|
'ausente': ['bg-danger-subtle text-danger border border-danger-subtle', 'Ausente'],
|
|
};
|
|
const [cls, lbl] = mapa[estado] || ['bg-secondary-subtle text-secondary border', estado];
|
|
el.className = 'ms-auto badge ' + cls;
|
|
el.textContent = lbl;
|
|
|
|
// Sincronizar botones según estado
|
|
const btnIni = document.getElementById('btn-iniciar');
|
|
const btnFin = document.getElementById('btn-finalizar');
|
|
const btnReg = document.getElementById('btn-regresar');
|
|
const btnRellamar = document.getElementById('btn-rellamar');
|
|
if (estado === 'en_espera_lugar') {
|
|
btnIni.classList.remove('d-none'); btnIni.disabled = false;
|
|
btnFin.classList.add('d-none');
|
|
btnReg.classList.add('d-none');
|
|
btnRellamar.classList.add('d-none');
|
|
} else if (estado === 'en_servicio') {
|
|
btnIni.classList.add('d-none');
|
|
btnFin.classList.remove('d-none');
|
|
btnReg.classList.remove('d-none');
|
|
btnRellamar.classList.remove('d-none');
|
|
}
|
|
}
|
|
|
|
async function rellamarTurno() {
|
|
if (!turnoActivo) return;
|
|
const btn = document.getElementById('btn-rellamar');
|
|
btn.disabled = true;
|
|
try {
|
|
const res = await fetch(API + 'llamar_turno.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ area: 'lugar', lugar_id: lugarId, turno_id: turnoActivo.id }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) mostrarError(json.error);
|
|
else if (json.turno) { mostrarLlamando(json.turno.codigo); }
|
|
} catch (err) {
|
|
mostrarError(err.message);
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
function escHtml(str) {
|
|
const d = document.createElement('div');
|
|
d.appendChild(document.createTextNode(String(str ?? '')));
|
|
return d.innerHTML;
|
|
}
|
|
|
|
// ── Toast (igual que recepción) ───────────────────────────────
|
|
let _toastTimer = null;
|
|
function mostrarToast(msg, type = 'info', duration = 2500) {
|
|
const el = document.getElementById('lug-toast');
|
|
const ico = document.getElementById('lug-toast-ico');
|
|
const txt = document.getElementById('lug-toast-msg');
|
|
const icons = { success: 'fa-check-circle', info: 'fa-info-circle', warn: 'fa-exclamation-triangle', error: 'fa-times-circle' };
|
|
el.className = 'rec-toast ' + type;
|
|
ico.innerHTML = '<i class="fas ' + (icons[type] || icons.info) + '"></i>';
|
|
txt.textContent = msg;
|
|
el.classList.add('show');
|
|
clearTimeout(_toastTimer);
|
|
_toastTimer = setTimeout(() => el.classList.remove('show'), duration);
|
|
}
|
|
function mostrarError(msg) { mostrarToast(msg, 'error', 4000); }
|
|
function mostrarLlamando(cod) { mostrarToast('Llamando turno ' + cod + '…', 'info', 2000); }
|
|
|
|
// ── Comentarios y notas ───────────────────────────────────────
|
|
async function cargarComentarios(turnoId) {
|
|
if (!turnoId) return;
|
|
const cont = document.getElementById('lista-comentarios');
|
|
cont.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Cargando…';
|
|
try {
|
|
const res = await fetch(`${API}comentarios.php?turno_id=${turnoId}`);
|
|
const json = await res.json();
|
|
if (!json.ok || !json.comentarios) { cont.innerHTML = '<small class="text-muted">Sin comentarios</small>'; return; }
|
|
if (json.comentarios.length === 0) { cont.innerHTML = '<small class="text-muted">Sin comentarios aún</small>'; return; }
|
|
cont.innerHTML = json.comentarios.map(c => `
|
|
<div style="background:#f8fafc;border-left:3px solid #8b5cf6;padding:8px 10px;margin-bottom:8px;border-radius:4px">
|
|
<div style="font-size:.7rem;color:#94a3b8;margin-bottom:2px">${escHtml(c.usuario_nombre)} • ${new Date(c.creado_at).toLocaleString()}</div>
|
|
<div style="font-size:.82rem;color:#334155">${escHtml(c.comentario)}</div>
|
|
</div>
|
|
`).join('');
|
|
} catch(_) {
|
|
cont.innerHTML = '<small class="text-danger">Error al cargar comentarios</small>';
|
|
}
|
|
}
|
|
|
|
async function guardarComentario() {
|
|
if (!turnoActivo) return;
|
|
const inp = document.getElementById('inp-comentario');
|
|
const txt = (inp.value || '').trim();
|
|
if (!txt) { mostrarError('El comentario no puede estar vacío'); return; }
|
|
try {
|
|
const res = await fetch(API + 'comentarios.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ turno_id: turnoActivo.id, comentario: txt, tipo: 'muestras' }),
|
|
});
|
|
const json = await res.json();
|
|
if (!json.ok) { mostrarError(json.error || 'Error al guardar'); return; }
|
|
inp.value = '';
|
|
await cargarComentarios(turnoActivo.id);
|
|
mostrarToast('Comentario guardado', 'success', 2000);
|
|
} catch(err) {
|
|
mostrarError(err.message);
|
|
}
|
|
}
|
|
|
|
/* ── Ocupación exclusiva del puesto ──────────────────────────── */
|
|
(function(_ID, _NOMBRE, _VIEW, _PARAM) {
|
|
if (!_ID) return;
|
|
|
|
function _e(s) {
|
|
const d = document.createElement('div');
|
|
d.appendChild(document.createTextNode(String(s ?? '')));
|
|
return d.innerHTML;
|
|
}
|
|
function _post(body) {
|
|
return fetch(API + 'ocupar_lugar.php', {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(Object.assign({ lugar_id: _ID }, body)),
|
|
}).then(r => r.json());
|
|
}
|
|
function _redirigirSiguiente(disponibles) {
|
|
if (disponibles && disponibles.length) {
|
|
window.location.href = BASE_WA + 'erp.php?m=turnero&v=' + _VIEW + '&' + _PARAM + '=' + disponibles[0].id;
|
|
} else {
|
|
window.location.href = BASE_WA + 'erp.php?m=turnero';
|
|
}
|
|
}
|
|
|
|
/* Pantalla de bloqueo */
|
|
function _mostrarBloqueado(ocupadoPor) {
|
|
document.body.innerHTML =
|
|
'<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;' +
|
|
'min-height:100vh;background:#f8faff;font-family:sans-serif;gap:14px;text-align:center;padding:28px">' +
|
|
'<div style="font-size:4rem">🔒</div>' +
|
|
'<h2 style="color:#1565c0;margin:0">' + _e(_NOMBRE) + ' está abierta en otro equipo</h2>' +
|
|
'<p style="color:#555;font-size:1.05rem;max-width:440px;line-height:1.6">' +
|
|
'Actualmente usada por <strong>' + _e(ocupadoPor) + '</strong>.<br>' +
|
|
'Puedes solicitar que cierre su sesión o ir al siguiente puesto disponible.</p>' +
|
|
'<div style="display:flex;gap:12px;flex-wrap:wrap;justify-content:center;margin-top:4px">' +
|
|
'<button id="_btn-solicitar" onclick="window._ocToma()" ' +
|
|
'style="padding:12px 26px;background:#1565c0;color:#fff;border:none;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600">' +
|
|
'📢 Solicitar cierre en ese equipo</button>' +
|
|
'<button id="_btn-siguiente" onclick="window._ocSiguiente()" ' +
|
|
'style="padding:12px 26px;background:#f0f4ff;color:#1565c0;border:2px solid #1565c0;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600">' +
|
|
'➡ Ir al siguiente disponible</button>' +
|
|
'</div>' +
|
|
'<div id="_oc-estado" style="min-height:24px;color:#777;font-size:.95rem;margin-top:4px"></div>' +
|
|
'</div>';
|
|
}
|
|
function _setEstado(msg, color) {
|
|
const el = document.getElementById('_oc-estado');
|
|
if (el) el.innerHTML = '<span style="color:' + (color||'#555') + '">' + msg + '</span>';
|
|
}
|
|
|
|
/* Solicitar toma de control */
|
|
let _checkTransferTimer = null;
|
|
window._ocToma = async function() {
|
|
const btn = document.getElementById('_btn-solicitar');
|
|
if (btn) btn.disabled = true;
|
|
_setEstado('Enviando solicitud…', '#555');
|
|
try {
|
|
const j = await _post({ action: 'solicitar' });
|
|
if (!j.ok) { _setEstado('Error al enviar solicitud.', '#c62828'); if (btn) btn.disabled = false; return; }
|
|
if (j.transferido) { location.reload(); return; }
|
|
_setEstado('✉ Solicitud enviada. El otro equipo tiene 5 segundos para responder…', '#1565c0');
|
|
clearInterval(_checkTransferTimer);
|
|
_checkTransferTimer = setInterval(async () => {
|
|
try {
|
|
const r = await _post({ action: 'check_transfer' });
|
|
if (r.disponible) {
|
|
clearInterval(_checkTransferTimer);
|
|
_setEstado('✅ Puesto liberado. Tomando control…', '#2e7d32');
|
|
const rc = await _post({ action: 'claim' });
|
|
if (rc.disponible) location.reload();
|
|
else _setEstado('No se pudo tomar el control. Recargue la página.', '#c62828');
|
|
} else if (r.denegado) {
|
|
clearInterval(_checkTransferTimer);
|
|
_setEstado('❌ La solicitud fue denegada.', '#c62828');
|
|
if (btn) { btn.disabled = false; btn.textContent = '📢 Volver a solicitar'; }
|
|
}
|
|
} catch(_) {}
|
|
}, 1500);
|
|
} catch(e) {
|
|
_setEstado('Error de red: ' + e.message, '#c62828');
|
|
if (btn) btn.disabled = false;
|
|
}
|
|
};
|
|
|
|
/* Ir al siguiente disponible */
|
|
window._ocSiguiente = async function() {
|
|
const btn = document.getElementById('_btn-siguiente');
|
|
if (btn) btn.disabled = true;
|
|
_setEstado('Buscando puesto disponible…', '#555');
|
|
try {
|
|
const j = await _post({ action: 'disponibles' });
|
|
if (!j.ok || !j.disponibles.length) {
|
|
_setEstado('No hay otros puestos disponibles.', '#c62828');
|
|
if (btn) btn.disabled = false;
|
|
return;
|
|
}
|
|
_redirigirSiguiente(j.disponibles);
|
|
} catch(e) {
|
|
_setEstado('Error de red.', '#c62828');
|
|
if (btn) btn.disabled = false;
|
|
}
|
|
};
|
|
|
|
/* Modal de solicitud entrante (para el ocupante actual) */
|
|
let _modalActivo = false;
|
|
function _mostrarModalSolicitud(solicitante) {
|
|
if (_modalActivo) return;
|
|
_modalActivo = true;
|
|
const modal = document.createElement('div');
|
|
modal.style.cssText =
|
|
'position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:99999;display:flex;align-items:center;justify-content:center';
|
|
modal.innerHTML =
|
|
'<div style="background:#fff;border-radius:14px;padding:32px 28px;max-width:420px;width:92%;text-align:center;box-shadow:0 8px 32px rgba(0,0,0,.25)">' +
|
|
'<div style="font-size:2.5rem">⚠️</div>' +
|
|
'<h3 style="color:#c62828;margin:10px 0 6px">Solicitud de transferencia</h3>' +
|
|
'<p style="color:#333;margin:0 0 6px"><strong>' + _e(solicitante) + '</strong> quiere usar este puesto.</p>' +
|
|
'<p style="color:#555;font-size:.95rem">Si no responde, se cerrará automáticamente en <strong id="_sol-cnt">5</strong> segundos.</p>' +
|
|
'<div style="display:flex;gap:10px;justify-content:center;margin-top:18px">' +
|
|
'<button id="_sol-aceptar" style="padding:10px 22px;background:#c62828;color:#fff;border:none;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600">Aceptar y ceder</button>' +
|
|
'<button id="_sol-denegar" style="padding:10px 22px;background:#f5f5f5;color:#333;border:1px solid #ccc;border-radius:8px;font-size:1rem;cursor:pointer">Denegar</button>' +
|
|
'</div></div>';
|
|
document.body.appendChild(modal);
|
|
|
|
let secs = 5;
|
|
const tick = setInterval(() => {
|
|
secs--;
|
|
const el = document.getElementById('_sol-cnt');
|
|
if (el) el.textContent = secs;
|
|
if (secs <= 0) { clearInterval(tick); _liberar(); }
|
|
}, 1000);
|
|
|
|
async function _liberar() {
|
|
modal.remove();
|
|
await _post({ action: 'aceptar' }).catch(() => {});
|
|
try {
|
|
const j = await _post({ action: 'disponibles' });
|
|
_redirigirSiguiente(j.disponibles || []);
|
|
} catch(_) {
|
|
window.location.href = BASE_WA + 'erp.php?m=turnero';
|
|
}
|
|
}
|
|
|
|
document.getElementById('_sol-aceptar').onclick = () => { clearInterval(tick); _liberar(); };
|
|
document.getElementById('_sol-denegar').onclick = async () => {
|
|
clearInterval(tick);
|
|
modal.remove();
|
|
_modalActivo = false;
|
|
await _post({ action: 'denegar' }).catch(() => {});
|
|
};
|
|
}
|
|
|
|
/* Arranque */
|
|
async function _iniciar() {
|
|
try {
|
|
const j = await _post({ action: 'claim' });
|
|
if (!j.ok) return;
|
|
if (!j.disponible) { _mostrarBloqueado(j.ocupado_por); return; }
|
|
// Heartbeat cada 60 s
|
|
setInterval(() => _post({ action: 'ping' }).catch(() => {}), 60000);
|
|
// Polling de solicitudes entrantes cada 2 s
|
|
setInterval(async () => {
|
|
if (_modalActivo) return;
|
|
try {
|
|
const r = await _post({ action: 'check_solicitud' });
|
|
if (r.hay_solicitud) _mostrarModalSolicitud(r.solicitante);
|
|
} catch(_) {}
|
|
}, 2000);
|
|
} catch(_) {}
|
|
}
|
|
|
|
window.addEventListener('beforeunload', () => {
|
|
navigator.sendBeacon(API + 'ocupar_lugar.php',
|
|
new Blob([JSON.stringify({ lugar_id: _ID, action: 'release' })], { type: 'application/json' }));
|
|
});
|
|
|
|
_iniciar();
|
|
})(lugarId, LUGAR_NOMBRE, 'lugar', 'lugar_id');
|
|
</script>
|
|
|
|
<div class="rec-toast" id="lug-toast">
|
|
<span class="ico" id="lug-toast-ico"><i class="fas fa-info-circle"></i></span>
|
|
<span id="lug-toast-msg"></span>
|
|
</div>
|
|
|
|
<script src="<?= defined('APP_URL') ? rtrim(APP_URL,'/') : '' ?>/assets/js/lab-sidebar.js"></script>
|
|
</body>
|
|
</html>
|