Files
admin-edu-space/frontend/views/reception/scanner.html
T

1005 lines
54 KiB
HTML

{% extends "base.html" %}
{% block title %}Consola de Acceso QR — Recepción & Seguridad{% endblock %}
{% block content %}
<div class="container-fluid py-3 px-lg-4">
<!-- Header de Control de Acceso -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
<div>
<div class="d-flex align-items-center gap-2 mb-1">
<img src="/img/mini_logo_icon.png" alt="UniCABA" height="24" class="rounded shadow-xs">
<span class="badge bg-secondary text-white rounded-pill px-3 py-1 fw-semibold">
<i class="bi bi-qr-code-scan me-1"></i> Control de Acceso
</span>
<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-2 py-0">En Línea</span>
</div>
<h1 class="h3 fw-bold mb-0">Consola de Recepción &amp; Escáner QR</h1>
<p class="text-muted small mb-0">Identifica a los estudiantes y docentes al ingresar, valida su estado de matrícula e infórmales su aula y piso del día.</p>
</div>
<div class="d-flex align-items-center gap-3">
<div>
<label class="small text-muted fw-bold d-block">Punto de Control / Sede Física:</label>
<select class="form-select form-select-sm rounded-pill px-3 shadow-xs" id="buildingSelect">
{% for b in buildings %}
<option value="{{ b.id }}" {% if b.id == defaultBuildingId or (not defaultBuildingId and loop.first) %}selected{% endif %}>
{{ b.name }}
</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row g-4">
<!-- ========================================================================= -->
<!-- COLUMNA IZQUIERDA: LECTURA ÓPTICA (ESCANEO) Y REGISTROS RECIENTES -->
<!-- ========================================================================= -->
<div class="col-12 col-lg-5 col-xl-5">
<!-- 1. Tarjeta de Entrada de Lectura Óptica (Pistola USB / DNI) -->
<div class="card border-0 shadow-sm rounded-4 p-4 mb-4 scanner-card">
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="fw-bold mb-0 text-body d-flex align-items-center">
<i class="bi bi-upc-scan me-2 text-primary"></i>Lector Óptico de Acceso
</h5>
<span class="small fw-semibold d-flex align-items-center gap-1" id="scannerFocusIndicator" title="Estado de foco del lector">
<span class="scanner-idle-dot"></span> Manual
</span>
</div>
<!-- Banner Informativo con Control de Foco -->
<div class="p-3 bg-body-tertiary rounded-4 border mb-3 text-start">
<div class="d-flex align-items-center justify-content-between gap-2 flex-wrap">
<div class="d-flex align-items-center gap-2">
<i class="bi bi-shield-check text-primary fs-5"></i>
<div>
<div class="fw-bold small text-body">Modo USB HID / Pistola Óptica</div>
<div class="text-muted small" style="font-size: 0.74rem;">Dispara la pistola o escribe el DNI para registrar el acceso</div>
</div>
</div>
<!-- Botón Toggle de Auto-foco (Predeterminado Apagado a petición del usuario) -->
<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill px-3 shadow-none"
id="btnToggleAutoFocus" onclick="toggleAutoFocus()"
title="Activa o desactiva la captura permanente del cursor en el campo de escaneo">
<i class="bi bi-cursor me-1" id="autoFocusIcon"></i>
<span id="autoFocusStatusText">Auto-foco: Inactivo</span>
</button>
</div>
</div>
<!-- Formulario de Entrada de Lectura Óptica USB -->
<form id="manualScanForm" onsubmit="handleManualScan(event)">
<div class="input-group shadow-sm rounded-pill overflow-hidden border border-2 border-primary mb-2 scanner-input-group">
<input type="text" class="form-control rounded-start-pill ps-3 border-0 py-2 fs-6 text-body" id="scannerInput"
placeholder="Escanea con la pistola o escribe el DNI..." autocomplete="off">
<button class="btn btn-primary rounded-end-pill px-4 fw-semibold border-0" type="submit">
<i class="bi bi-arrow-right-circle me-1"></i> Validar
</button>
</div>
<div class="d-flex align-items-center justify-content-between px-2">
<span class="small text-muted" style="font-size: 0.74rem;">
<i class="bi bi-info-circle me-1"></i>Captura automática al recibir el delimitador Enter
</span>
<button type="button" class="btn btn-link btn-sm text-decoration-none p-0 text-primary small" onclick="focusScannerInput()">
<i class="bi bi-crosshair me-1"></i>Forzar Foco
</button>
</div>
</form>
</div>
<!-- 2. Tarjeta de Últimos Ingresos Registrados en Sede (Registros en la Columna Izquierda) -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4 logs-card">
<div class="card-header bg-body border-0 py-3 px-4 d-flex align-items-center justify-content-between">
<h6 class="fw-bold mb-0 text-body d-flex align-items-center">
<i class="bi bi-clock-history me-2 text-primary"></i> Últimos Ingresos en Sede
</h6>
<button type="button" class="btn btn-sm btn-link text-decoration-none p-0 text-primary" onclick="refreshRecentLogs()">
<i class="bi bi-arrow-clockwise me-1"></i> Actualizar
</button>
</div>
<div class="table-responsive" style="max-height: 420px;">
<table class="table table-hover table-sm align-middle mb-0" id="recentLogsTable">
<thead class="table-light small">
<tr>
<th class="ps-3">Usuario</th>
<th>Rol</th>
<th>DNI</th>
<th>Sede</th>
<th>Hora</th>
<th class="text-center">Estado</th>
</tr>
</thead>
<tbody class="small" id="recentLogsBody">
{% if recentLogs and recentLogs | length > 0 %}
{% for log in recentLogs %}
<tr>
<td class="ps-3 fw-semibold text-body">{{ log.user_name }}</td>
<td><span class="badge bg-body-tertiary text-body border">{{ log.user_role or 'ALUMNO' }}</span></td>
<td class="font-monospace text-body-secondary">{{ log.user_dni or '--' }}</td>
<td class="text-body-secondary">{{ log.building_name }}</td>
<td class="font-monospace text-body-secondary">{{ log.scanned_time if log.scanned_time else (log.scanned_at | replace('T', ' ') | truncate(16, true, '')) }}</td>
<td class="text-center">
{% if log.status == 'AUTORIZADO' %}
<span class="badge bg-success-subtle text-success">OK</span>
{% else %}
<span class="badge bg-danger-subtle text-danger">{{ log.status }}</span>
{% endif %}
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="6" class="text-center py-4 text-muted">Aún no se han registrado ingresos hoy.</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
<!-- ========================================================================= -->
<!-- COLUMNA DERECHA: RESULTADO DE VALIDACIÓN Y CONFIGURACIÓN COM CONTRAÍBLE -->
<!-- ========================================================================= -->
<div class="col-12 col-lg-7 col-xl-7">
<!-- 1. Tarjeta de Resultado en Pantalla de Validación Instantánea -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4 result-validation-card" id="resultCard" style="min-height: 380px;">
<!-- Header de Validación Limpio y Sobrio -->
<div class="card-header py-3 px-4 bg-body border-bottom d-flex align-items-center justify-content-between transition-all" id="resultHeader">
<h5 class="fw-bold mb-0 text-body d-flex align-items-center" id="resultStatusText">
<i class="bi bi-person-badge me-2 text-primary"></i> Esperando lectura...
</h5>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-white text-dark border shadow-xs px-2 py-1 small rounded-pill d-none animate-pulse-badge" id="scanAlertBadge">
<i class="bi bi-lightning-charge-fill text-warning me-1"></i> ¡Nuevo Escaneo!
</span>
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-3 py-1 font-monospace" id="resultTimeBadge">--:--</span>
</div>
</div>
<!-- Cuerpo Limpio y Moderno sin Imágenes Invasivas -->
<div class="card-body p-4 d-flex flex-column justify-content-center text-center" id="resultBody">
<div class="py-5 text-muted" id="waitingState">
<div class="mb-3 d-inline-block p-3 rounded-circle bg-primary bg-opacity-10 text-primary">
<i class="bi bi-qr-code-scan display-4 d-block"></i>
</div>
<h4 class="fw-bold text-body">Apunta el lector óptico a la credencial o ingresa el DNI</h4>
<p class="small text-muted max-w-md mx-auto mb-0">
Al detectar la credencial dinámica o física del alumno o docente (o al tipear su DNI), el sistema mostrará instantáneamente sus datos de ingreso y las aulas donde cursa hoy.
</p>
</div>
<!-- Contenedor de Resultado Activo (Oculto inicialmente) -->
<div id="activeResultState" class="d-none text-start">
<div class="row align-items-center mb-4">
<div class="col-auto">
<div class="rounded-circle bg-primary text-white display-6 fw-bold d-flex align-items-center justify-content-center shadow-sm"
style="width: 76px; height: 76px;" id="userInitial">
A
</div>
</div>
<div class="col">
<div class="badge bg-success rounded-pill px-3 py-1 mb-1" id="matriculaBadge">REGULAR / ACTIVO</div>
<h3 class="fw-bold mb-0 text-body" id="userNameText">Nombre del Alumno</h3>
<div class="text-muted small">
<span id="userRoleText">ESTUDIANTE</span> • DNI: <strong id="userDniText" class="font-monospace text-body">12345678</strong>
</div>
</div>
</div>
<!-- Sección de Aulas y Clases de Hoy -->
<div class="p-3 bg-body-tertiary rounded-4 border mb-3 classes-section-container">
<h6 class="fw-bold text-uppercase text-primary small mb-3 d-flex align-items-center">
<i class="bi bi-compass-fill me-2"></i> Cronograma Áulico del Día de Hoy
</h6>
<div id="classesContainer">
<!-- Inyección dinámica de clases -->
</div>
</div>
<div class="d-flex align-items-center justify-content-between text-muted small">
<span id="scanTimestampText"><i class="bi bi-clock me-1"></i> Escaneado a las: --:--</span>
<span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill px-3 py-1">
Check-in Registrado
</span>
</div>
</div>
</div>
</div>
<!-- 2. Panel Colapsable y Minimizable de Puertos Serie COM (Hasta 4 lectores) -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4 com-config-card">
<div class="card-header bg-body border-0 py-3 px-4 d-flex align-items-center justify-content-between cursor-pointer"
data-bs-toggle="collapse" data-bs-target="#comPortsCollapse" aria-expanded="false" aria-controls="comPortsCollapse"
style="cursor: pointer;" title="Haz clic para expandir o contraer la configuración de lectores COM">
<div class="d-flex align-items-center gap-2">
<span class="p-1 px-2 rounded-2 bg-primary bg-opacity-10 text-primary d-inline-flex align-items-center">
<i class="bi bi-usb-symbol me-1"></i> <strong class="small">COM</strong>
</span>
<div>
<span class="small fw-bold text-uppercase text-body d-block" style="letter-spacing: 0.04em;">
Lectores Serie COM (Hasta 4)
</span>
<span class="text-muted small" style="font-size: 0.72rem;">Click para minimizar o configurar puertos seriales</span>
</div>
</div>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small" id="comGlobalBadge">
<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> 0 / 4 Activos
</span>
<button type="button" class="btn btn-sm btn-link text-decoration-none text-muted p-0" aria-label="Expandir/Contraer">
<i class="bi bi-chevron-down fs-6 transition-all" id="comCollapseIcon"></i>
</button>
</div>
</div>
<!-- Cuerpo Colapsado por Defecto -->
<div class="collapse" id="comPortsCollapse">
<div class="card-body p-3 pt-1 border-top">
<!-- Barra de Acciones Rápidas Globales -->
<div class="d-flex align-items-center gap-2 mb-3">
<button type="button" class="btn btn-sm btn-primary rounded-pill px-3 py-1 flex-grow-1 shadow-xs" id="btnQuickConnectCOM" onclick="handleQuickConnectCOM()">
<i class="bi bi-usb-plug-fill me-1"></i> Conectar Lector COM
</button>
<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill px-2 py-1" title="Reconectar lectores autorizados" onclick="reconnectAuthorizedComPorts()">
<i class="bi bi-arrow-clockwise"></i>
</button>
<button type="button" class="btn btn-sm btn-outline-danger rounded-pill px-2 py-1" title="Desconectar todos los puertos COM" onclick="handleDisconnectAllCOM()">
<i class="bi bi-power"></i>
</button>
</div>
<!-- Grilla de los 4 Slots de Lectores Seriales -->
<div class="row g-2" id="serialSlotsContainer">
<!-- Slot 1 -->
<div class="col-12 col-md-6">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all h-100" id="slotCard1">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary rounded-circle p-1" id="slotLed1" style="width: 10px; height: 10px;"></span>
<div>
<div class="fw-semibold small text-body" style="font-size: 0.78rem;">Lector 1 (Paso Principal)</div>
<div class="text-muted" style="font-size: 0.70rem;" id="slotStatusText1">Sin conectar</div>
</div>
</div>
<div class="d-flex align-items-center gap-1">
<select class="form-select form-select-xs py-0 px-1 border-0 bg-transparent text-muted" id="slotBaud1" style="font-size: 0.70rem; width: 68px;">
<option value="9600" selected>9600</option>
<option value="115200">115200</option>
</select>
<button type="button" class="btn btn-xs btn-outline-secondary rounded-pill px-2 py-0" id="btnConnectSlot1" onclick="handleConnectSlot(1)" style="font-size: 0.72rem;">
Conectar
</button>
</div>
</div>
</div>
</div>
<!-- Slot 2 -->
<div class="col-12 col-md-6">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all h-100" id="slotCard2">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary rounded-circle p-1" id="slotLed2" style="width: 10px; height: 10px;"></span>
<div>
<div class="fw-semibold small text-body" style="font-size: 0.78rem;">Lector 2 (Molinete)</div>
<div class="text-muted" style="font-size: 0.70rem;" id="slotStatusText2">Sin conectar</div>
</div>
</div>
<div class="d-flex align-items-center gap-1">
<select class="form-select form-select-xs py-0 px-1 border-0 bg-transparent text-muted" id="slotBaud2" style="font-size: 0.70rem; width: 68px;">
<option value="9600" selected>9600</option>
<option value="115200">115200</option>
</select>
<button type="button" class="btn btn-xs btn-outline-secondary rounded-pill px-2 py-0" id="btnConnectSlot2" onclick="handleConnectSlot(2)" style="font-size: 0.72rem;">
Conectar
</button>
</div>
</div>
</div>
</div>
<!-- Slot 3 -->
<div class="col-12 col-md-6">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all h-100" id="slotCard3">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary rounded-circle p-1" id="slotLed3" style="width: 10px; height: 10px;"></span>
<div>
<div class="fw-semibold small text-body" style="font-size: 0.78rem;">Lector 3 (Bedelía)</div>
<div class="text-muted" style="font-size: 0.70rem;" id="slotStatusText3">Sin conectar</div>
</div>
</div>
<div class="d-flex align-items-center gap-1">
<select class="form-select form-select-xs py-0 px-1 border-0 bg-transparent text-muted" id="slotBaud3" style="font-size: 0.70rem; width: 68px;">
<option value="9600" selected>9600</option>
<option value="115200">115200</option>
</select>
<button type="button" class="btn btn-xs btn-outline-secondary rounded-pill px-2 py-0" id="btnConnectSlot3" onclick="handleConnectSlot(3)" style="font-size: 0.72rem;">
Conectar
</button>
</div>
</div>
</div>
</div>
<!-- Slot 4 -->
<div class="col-12 col-md-6">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all h-100" id="slotCard4">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary rounded-circle p-1" id="slotLed4" style="width: 10px; height: 10px;"></span>
<div>
<div class="fw-semibold small text-body" style="font-size: 0.78rem;">Lector 4 (Auxiliar)</div>
<div class="text-muted" style="font-size: 0.70rem;" id="slotStatusText4">Sin conectar</div>
</div>
</div>
<div class="d-flex align-items-center gap-1">
<select class="form-select form-select-xs py-0 px-1 border-0 bg-transparent text-muted" id="slotBaud4" style="font-size: 0.70rem; width: 68px;">
<option value="9600" selected>9600</option>
<option value="115200">115200</option>
</select>
<button type="button" class="btn btn-xs btn-outline-secondary rounded-pill px-2 py-0" id="btnConnectSlot4" onclick="handleConnectSlot(4)" style="font-size: 0.72rem;">
Conectar
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Módulo de Web Serial API para lectores ópticos y escáneres QR (SDD-013) -->
<script src="/js/serial-scanner.js"></script>
<script>
let isScanningLocked = false;
let multiScanner = null;
let isAutoFocusActive = false; // Predeterminado: apagado según requerimiento del usuario
let autoFocusInterval = null;
// Toggle interactivo del foco del cursor
function toggleAutoFocus() {
isAutoFocusActive = !isAutoFocusActive;
updateAutoFocusUI();
if (isAutoFocusActive) {
focusScannerInput();
if (!autoFocusInterval) {
autoFocusInterval = setInterval(() => {
if (isAutoFocusActive) {
focusScannerInput();
}
}, 2500);
}
} else {
if (autoFocusInterval) {
clearInterval(autoFocusInterval);
autoFocusInterval = null;
}
updateFocusIndicator(false);
}
}
function updateAutoFocusUI() {
const btn = document.getElementById('btnToggleAutoFocus');
const text = document.getElementById('autoFocusStatusText');
const icon = document.getElementById('autoFocusIcon');
if (!btn || !text) return;
if (isAutoFocusActive) {
btn.className = 'btn btn-sm btn-success text-white rounded-pill px-3 shadow-xs';
text.innerText = 'Auto-foco: Activo';
if (icon) icon.className = 'bi bi-cursor-fill me-1';
} else {
btn.className = 'btn btn-sm btn-outline-secondary rounded-pill px-3';
text.innerText = 'Auto-foco: Inactivo';
if (icon) icon.className = 'bi bi-cursor me-1 text-muted';
}
}
// Inicializar MultiSerialBarcodeScanner (hasta 4 lectores COM)
function initSerialScanner() {
if (typeof MultiSerialBarcodeScanner === 'undefined') return;
multiScanner = new MultiSerialBarcodeScanner({
baudRate: 9600,
onCodeScanned: function(code, slotInfo) {
if (!isScanningLocked) {
isScanningLocked = true;
flashSlotCard(slotInfo ? slotInfo.slotId : 1);
verifyToken(code, slotInfo);
setTimeout(() => { isScanningLocked = false; }, 1500);
}
},
onStatusChanged: function(evt) {
updateSlotUI(evt);
},
onError: function(err, slot) {
console.warn(`[MultiSerialScanner UI] Error en slot ${slot ? slot.id : '?'}:`, err);
}
});
if (!multiScanner.isSupported()) {
const badge = document.getElementById('comGlobalBadge');
if (badge) {
badge.className = 'badge bg-body-tertiary text-muted rounded-pill px-2 py-1 small border';
badge.innerHTML = '<i class="bi bi-info-circle me-1"></i> Modo USB-HID';
}
for (let i = 1; i <= 4; i++) {
const btn = document.getElementById(`btnConnectSlot${i}`);
if (btn) btn.disabled = true;
}
} else {
reconnectAuthorizedComPorts();
}
}
function updateSlotUI(evt) {
const slotId = evt.slotId;
const led = document.getElementById(`slotLed${slotId}`);
const statusText = document.getElementById(`slotStatusText${slotId}`);
const btn = document.getElementById(`btnConnectSlot${slotId}`);
const globalBadge = document.getElementById('comGlobalBadge');
if (evt.status === 'CONNECTED') {
if (led) led.className = 'badge bg-success rounded-circle p-1 animate-pulse-badge';
if (statusText) {
statusText.className = 'text-success fw-semibold';
statusText.innerHTML = `<i class="bi bi-usb-plug-fill me-1"></i> COM Activo (${evt.baudRate || 9600} baud)`;
}
if (btn) {
btn.className = 'btn btn-xs btn-outline-danger rounded-pill px-2 py-0';
btn.innerHTML = '<i class="bi bi-x-circle me-1"></i>Desconectar';
}
} else {
if (led) led.className = 'badge bg-secondary rounded-circle p-1';
if (statusText) {
statusText.className = 'text-muted';
statusText.innerText = 'Sin conectar';
}
if (btn) {
btn.className = 'btn btn-xs btn-outline-secondary rounded-pill px-2 py-0';
btn.innerText = 'Conectar';
}
}
if (globalBadge) {
const connected = evt.totalConnected !== undefined ? evt.totalConnected : (multiScanner ? multiScanner.getConnectedCount() : 0);
if (connected > 0) {
globalBadge.className = 'badge bg-success text-white rounded-pill px-2 py-1 small shadow-xs';
globalBadge.innerHTML = `<i class="bi bi-check-circle-fill me-1"></i> ${connected} / 4 Activos`;
} else {
globalBadge.className = 'badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small';
globalBadge.innerHTML = '<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> 0 / 4 Activos';
}
}
}
function flashSlotCard(slotId) {
const card = document.getElementById(`slotCard${slotId}`);
if (!card) return;
card.classList.add('border-primary', 'bg-primary-subtle');
setTimeout(() => {
card.classList.remove('border-primary', 'bg-primary-subtle');
}, 800);
}
async function handleConnectSlot(slotId) {
if (!multiScanner) initSerialScanner();
if (!multiScanner.isSupported()) {
alert('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge.');
return;
}
const slot = multiScanner.getSlot(slotId);
if (slot && slot.isConnected()) {
await multiScanner.disconnectSlot(slotId);
} else {
const baudSelect = document.getElementById(`slotBaud${slotId}`);
const baudRate = baudSelect ? parseInt(baudSelect.value, 10) : 9600;
try {
await multiScanner.requestAndConnectSlot(slotId, baudRate);
} catch (err) {
if (err.name !== 'NotFoundError') {
console.error(`Error conectando slot ${slotId}:`, err);
alert(`No se pudo abrir el puerto serie para el Lector ${slotId}: ` + err.message);
}
}
}
}
async function handleQuickConnectCOM() {
if (!multiScanner) initSerialScanner();
if (!multiScanner.isSupported()) {
alert('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge.');
return;
}
const freeSlot = multiScanner.slots.find(s => !s.isConnected());
const targetSlotId = freeSlot ? freeSlot.id : 1;
await handleConnectSlot(targetSlotId);
}
async function handleDisconnectAllCOM() {
if (!multiScanner) return;
await multiScanner.disconnectAll();
}
async function reconnectAuthorizedComPorts() {
if (!multiScanner) initSerialScanner();
if (multiScanner && multiScanner.isSupported()) {
const count = await multiScanner.autoConnectAuthorizedPorts();
if (count > 0) {
console.log(`[MultiSerialScanner] ${count} puertos reconectados automáticamente.`);
}
}
}
// Foco manual o condicional
function focusScannerInput() {
const input = document.getElementById('scannerInput');
if (!input) return;
const active = document.activeElement;
if (active && (active.tagName === 'SELECT' || active.tagName === 'BUTTON' || active.id === 'buildingSelect')) return;
if (active !== input) {
input.focus();
}
updateFocusIndicator(true);
}
function updateFocusIndicator(isFocused) {
const indicator = document.getElementById('scannerFocusIndicator');
if (!indicator) return;
if (isFocused) {
indicator.className = 'small text-success fw-semibold d-flex align-items-center gap-1';
indicator.innerHTML = '<span class="scanner-active-dot"></span> Foco Listo';
} else {
indicator.className = 'small text-muted fw-semibold d-flex align-items-center gap-1';
indicator.innerHTML = '<span class="scanner-idle-dot"></span> Inactivo';
}
}
function handleManualScan(e) {
if (e) e.preventDefault();
const input = document.getElementById('scannerInput');
if (!input) return;
let val = input.value.trim();
if (!val) {
focusScannerInput();
return;
}
// Solo normalizar Ñ por : si el código contiene prefijos de protocolo institucional (UNICABA, USR, DNI)
if (/^(UNICABA|USR|DNI)ñ/i.test(val) || /UNICABAÑ|ÑUSRÑ|ÑDNIÑ/i.test(val)) {
val = val.replace(/Ñ/g, ':').replace(/ñ/g, ':');
}
verifyToken(val);
input.value = '';
if (isAutoFocusActive) {
setTimeout(focusScannerInput, 50);
}
}
async function verifyToken(token, slotInfo = null) {
const buildingId = document.getElementById('buildingSelect').value;
try {
const resp = await fetch('/reception/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
qr_token: token,
building_id: buildingId ? parseInt(buildingId, 10) : null
})
});
const data = await resp.json();
displayVerificationResult(data, slotInfo);
refreshRecentLogs();
} catch (err) {
console.error('Error verificando:', err);
displayVerificationResult({
status: 'DENEGADO',
message: 'Error de conexión con el validador.',
todays_classes: []
}, slotInfo);
} finally {
if (isAutoFocusActive) {
setTimeout(focusScannerInput, 150);
}
}
}
function displayVerificationResult(data, slotInfo = null) {
const waitingState = document.getElementById('waitingState');
const activeState = document.getElementById('activeResultState');
const resultCard = document.getElementById('resultCard');
const cardHeader = document.getElementById('resultHeader');
const statusText = document.getElementById('resultStatusText');
const timeBadge = document.getElementById('resultTimeBadge');
const matriculaBadge = document.getElementById('matriculaBadge');
const alertBadge = document.getElementById('scanAlertBadge');
waitingState.classList.add('d-none');
activeState.classList.remove('d-none');
const now = new Date();
timeBadge.innerText = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
resultCard.classList.remove('animate-scan-success', 'animate-scan-warning', 'animate-scan-danger');
void resultCard.offsetWidth;
if (alertBadge) {
const sourceLabel = slotInfo ? (slotInfo.slotName || `Lector ${slotInfo.slotId}`) : 'Pistola Óptica';
alertBadge.innerHTML = `<i class="bi bi-lightning-charge-fill text-warning me-1"></i> ¡Nuevo Escaneo! <span class="badge bg-dark text-white ms-1 fw-normal">${sourceLabel}</span>`;
alertBadge.classList.remove('d-none');
setTimeout(() => { alertBadge.classList.add('d-none'); }, 3000);
}
const hasClasses = Boolean(data.todays_classes && data.todays_classes.length > 0);
if (data.status === 'AUTORIZADO') {
if (hasClasses) {
// AUTORIZADO CON CLASES HOY -> VERDE INSTITUCIONAL
resultCard.className = 'card border-2 border-success shadow-lg rounded-4 overflow-hidden mb-4 animate-scan-success result-validation-card';
resultCard.style.backgroundColor = '';
cardHeader.className = 'card-header py-3 px-4 bg-success text-white border-0 d-flex align-items-center justify-content-between';
statusText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i> ACCESO AUTORIZADO — TIENE CLASE HOY';
timeBadge.className = 'badge bg-white text-success rounded-pill px-3 py-1 font-monospace fw-bold';
matriculaBadge.className = 'badge bg-success rounded-pill px-3 py-1 mb-1 me-1';
matriculaBadge.innerHTML = (data.matricula_status || 'REGULAR / ACTIVO') + ' <span class="badge bg-primary text-white rounded-pill px-2 py-0 ms-1"><i class="bi bi-mortarboard-fill me-1"></i>Tiene Cursada</span>';
playAudioFeedback('SUCCESS_WITH_CLASSES');
} else {
// AUTORIZADO PERO SIN CLASES HOY -> ÁMBAR
resultCard.className = 'card border-2 border-warning shadow-lg rounded-4 overflow-hidden mb-4 animate-scan-warning result-validation-card';
resultCard.style.backgroundColor = '';
cardHeader.className = 'card-header py-3 px-4 bg-warning text-dark border-0 d-flex align-items-center justify-content-between fw-bold';
statusText.innerHTML = '<i class="bi bi-calendar-x-fill text-dark me-2"></i> ACCESO AUTORIZADO — SIN CLASES PROGRAMADAS HOY';
timeBadge.className = 'badge bg-dark text-white rounded-pill px-3 py-1 font-monospace';
matriculaBadge.className = 'badge bg-success rounded-pill px-3 py-1 mb-1 me-1';
matriculaBadge.innerHTML = (data.matricula_status || 'REGULAR / ACTIVO') + ' <span class="badge bg-warning text-dark border border-dark-subtle rounded-pill px-2 py-0 ms-1 fw-bold"><i class="bi bi-calendar-x me-1"></i>Sin Cursada Hoy</span>';
playAudioFeedback('SUCCESS_NO_CLASSES');
}
} else if (data.status === 'RESTRINGIDO') {
resultCard.className = 'card border-2 border-warning shadow-lg rounded-4 overflow-hidden mb-4 animate-scan-warning result-validation-card';
resultCard.style.backgroundColor = '';
cardHeader.className = 'card-header py-3 px-4 bg-warning text-dark border-0 d-flex align-items-center justify-content-between fw-bold';
statusText.innerHTML = '<i class="bi bi-exclamation-triangle-fill me-2"></i> ACCESO OBSERVADO / RESTRINGIDO';
timeBadge.className = 'badge bg-dark text-white rounded-pill px-3 py-1 font-monospace';
matriculaBadge.className = 'badge bg-warning text-dark rounded-pill px-3 py-1 mb-1';
matriculaBadge.innerText = data.matricula_status || 'OBSERVADO';
playAudioFeedback('WARNING');
} else {
// DENEGADO -> ROJO
resultCard.className = 'card border-2 border-danger shadow-lg rounded-4 overflow-hidden mb-4 animate-scan-danger result-validation-card';
resultCard.style.backgroundColor = '';
cardHeader.className = 'card-header py-3 px-4 bg-danger text-white border-0 d-flex align-items-center justify-content-between';
statusText.innerHTML = '<i class="bi bi-x-circle-fill me-2"></i> ACCESO DENEGADO';
timeBadge.className = 'badge bg-white text-danger rounded-pill px-3 py-1 font-monospace fw-bold';
matriculaBadge.className = 'badge bg-danger rounded-pill px-3 py-1 mb-1';
matriculaBadge.innerText = data.matricula_status || 'NO REGISTRADO';
playAudioFeedback('DENIED');
}
document.getElementById('userNameText').innerText = data.user_name || 'Desconocido';
document.getElementById('userRoleText').innerText = (data.user_role || 'NO DEFINIDO').toUpperCase();
document.getElementById('userDniText').innerText = data.user_dni || '--';
document.getElementById('userInitial').innerText = (data.user_name || '?')[0].toUpperCase();
document.getElementById('scanTimestampText').innerHTML = `<i class="bi bi-clock me-1"></i> Escaneado: ${now.toLocaleTimeString()}`;
const classesContainer = document.getElementById('classesContainer');
if (hasClasses) {
classesContainer.innerHTML = data.todays_classes.map(c => `
<div class="card border border-primary-subtle rounded-3 p-3 mb-2 bg-body shadow-xs text-body">
<div class="d-flex align-items-start justify-content-between">
<div>
<span class="badge bg-primary text-white rounded-pill px-2 py-0 small mb-1">${c.commission_name}</span>
<h5 class="fw-bold mb-1 text-primary">${c.subject_name}</h5>
<div class="text-muted small">
<i class="bi bi-person me-1"></i> Docente: <strong class="text-body">${c.teacher_name || 'A designar'}</strong>
</div>
</div>
<div class="text-end">
<span class="badge bg-warning text-dark fs-6 px-3 py-1 rounded-pill fw-bold shadow-sm">
<i class="bi bi-door-open me-1"></i> ${c.classroom_name}
</span>
<div class="fw-semibold text-body mt-1" style="font-size: 0.85rem;">
Piso: <strong>${c.floor || 1}</strong> (${c.building_name})
</div>
<div class="small text-muted mt-1">
<i class="bi bi-clock me-1"></i> ${c.start_time} a ${c.end_time} hs
</div>
</div>
</div>
</div>
`).join('');
} else if (data.status === 'DENEGADO') {
classesContainer.innerHTML = `
<div class="alert alert-danger border border-danger-subtle text-danger-emphasis p-3 rounded-4 mb-0 shadow-xs">
<div class="d-flex align-items-center gap-3">
<div class="rounded-circle bg-danger text-white p-2 d-flex align-items-center justify-content-center shadow-xs" style="width: 42px; height: 42px;">
<i class="bi bi-shield-x fs-5"></i>
</div>
<div>
<div class="fw-bold fs-6">Ingreso No Autorizado</div>
<div class="small">${data.message || 'El documento o credencial escaneada no registra permisos vigentes de ingreso.'}</div>
</div>
</div>
</div>
`;
} else {
classesContainer.innerHTML = `
<div class="alert alert-warning border border-warning-subtle text-body p-3 rounded-4 mb-0 shadow-xs">
<div class="d-flex align-items-center gap-3">
<div class="rounded-circle bg-warning text-dark p-2 d-flex align-items-center justify-content-center shadow-xs" style="width: 42px; height: 42px;">
<i class="bi bi-calendar-x-fill fs-5"></i>
</div>
<div>
<div class="fw-bold fs-6 text-body">No registra clases presenciales programadas para hoy</div>
<div class="small text-muted">El alumno/docente ingresa a la sede pero no tiene aula asignada para la fecha actual.</div>
</div>
</div>
</div>
`;
}
}
async function refreshRecentLogs() {
const buildingId = document.getElementById('buildingSelect').value;
try {
const res = await fetch(`/reception/recent-logs?building_id=${buildingId || ''}`);
const data = await res.json();
const tbody = document.getElementById('recentLogsBody');
if (data.items && data.items.length > 0) {
tbody.innerHTML = data.items.map(l => `
<tr>
<td class="ps-3 fw-semibold text-body">${l.user_name}</td>
<td><span class="badge bg-body-tertiary text-body border">${l.user_role || 'ALUMNO'}</span></td>
<td class="font-monospace text-body-secondary">${l.user_dni || '--'}</td>
<td class="text-body-secondary">${l.building_name}</td>
<td class="font-monospace text-body-secondary">${formatLogTime(l)}</td>
<td class="text-center">
<span class="badge ${l.status === 'AUTORIZADO' ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'}">
${l.status === 'AUTORIZADO' ? 'OK' : l.status}
</span>
</td>
</tr>
`).join('');
}
} catch (e) {
console.warn('Error refrescando logs:', e);
}
}
function formatLogTime(l) {
if (l.scanned_time) return l.scanned_time;
if (!l.scanned_at) return '--';
try {
const raw = l.scanned_at;
const d = new Date(raw.endsWith('Z') || raw.includes('+') || raw.includes('-') ? raw : raw + 'Z');
return d.toLocaleTimeString('es-AR', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: 'America/Argentina/Buenos_Aires'
}) + ' hs';
} catch (e) {
return l.scanned_at.substring(11, 16) + ' hs';
}
}
function playAudioFeedback(type) {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const now = ctx.currentTime;
if (type === 'SUCCESS_WITH_CLASSES') {
const osc1 = ctx.createOscillator();
const gain1 = ctx.createGain();
osc1.type = 'sine';
osc1.frequency.setValueAtTime(587.33, now);
osc1.frequency.setValueAtTime(880.00, now + 0.08);
gain1.gain.setValueAtTime(0.12, now);
gain1.gain.exponentialRampToValueAtTime(0.001, now + 0.25);
osc1.connect(gain1);
gain1.connect(ctx.destination);
osc1.start(now);
osc1.stop(now + 0.25);
} else if (type === 'SUCCESS_NO_CLASSES') {
const osc2 = ctx.createOscillator();
const gain2 = ctx.createGain();
osc2.type = 'triangle';
osc2.frequency.setValueAtTime(440.00, now);
osc2.frequency.setValueAtTime(554.37, now + 0.09);
gain2.gain.setValueAtTime(0.10, now);
gain2.gain.exponentialRampToValueAtTime(0.001, now + 0.24);
osc2.connect(gain2);
gain2.connect(ctx.destination);
osc2.start(now);
osc2.stop(now + 0.24);
} else {
const osc3 = ctx.createOscillator();
const gain3 = ctx.createGain();
osc3.type = 'sawtooth';
osc3.frequency.setValueAtTime(220.00, now);
gain3.gain.setValueAtTime(0.15, now);
gain3.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
osc3.connect(gain3);
gain3.connect(ctx.destination);
osc3.start(now);
osc3.stop(now + 0.3);
}
} catch (e) {}
}
document.addEventListener('DOMContentLoaded', () => {
initSerialScanner();
updateAutoFocusUI();
// Control de rotación del chevron del collapse de puertos COM
const comCollapse = document.getElementById('comPortsCollapse');
const comIcon = document.getElementById('comCollapseIcon');
if (comCollapse && comIcon) {
comCollapse.addEventListener('show.bs.collapse', () => {
comIcon.style.transform = 'rotate(180deg)';
});
comCollapse.addEventListener('hide.bs.collapse', () => {
comIcon.style.transform = 'rotate(0deg)';
});
}
const input = document.getElementById('scannerInput');
if (input) {
input.addEventListener('focus', () => updateFocusIndicator(true));
input.addEventListener('blur', () => {
if (!isAutoFocusActive) {
updateFocusIndicator(false);
}
});
}
});
window.addEventListener('focus', () => {
if (isAutoFocusActive) focusScannerInput();
});
document.addEventListener('click', (e) => {
if (isAutoFocusActive && !e.target.closest('select, button, a, input, textarea, .card-header')) {
focusScannerInput();
}
});
</script>
<style>
/* Estilos de Punto Indicador de Foco */
.scanner-active-dot {
width: 8px;
height: 8px;
background-color: #22c55e;
border-radius: 50%;
display: inline-block;
animation: pulse-dot 1.5s infinite ease-in-out;
}
.scanner-idle-dot {
width: 8px;
height: 8px;
background-color: #94a3b8;
border-radius: 50%;
display: inline-block;
}
@keyframes pulse-dot {
0% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7); }
70% { transform: scale(1.15); box-shadow: 0 0 0 6px rgba(34, 197, 94, 0); }
100% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(34, 197, 94, 0); }
}
/* Animaciones de Flash de Escaneo */
@keyframes scan-flash-success {
0% { transform: scale(0.99); box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.8); }
50% { transform: scale(1.015); box-shadow: 0 0 35px 8px rgba(34, 197, 94, 0.4); }
100% { transform: scale(1); box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.12); }
}
@keyframes scan-flash-warning {
0% { transform: scale(0.99); box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.8); }
50% { transform: scale(1.015); box-shadow: 0 0 35px 8px rgba(245, 158, 11, 0.4); }
100% { transform: scale(1); box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.12); }
}
@keyframes scan-flash-danger {
0% { transform: scale(0.99); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.8); }
50% { transform: scale(1.015); box-shadow: 0 0 35px 8px rgba(239, 68, 68, 0.4); }
100% { transform: scale(1); box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.12); }
}
.animate-scan-success { animation: scan-flash-success 0.55s ease-out; }
.animate-scan-warning { animation: scan-flash-warning 0.55s ease-out; }
.animate-scan-danger { animation: scan-flash-danger 0.55s ease-out; }
@keyframes pulse-badge {
0% { transform: scale(1); }
50% { transform: scale(1.12); }
100% { transform: scale(1); }
}
.animate-pulse-badge { animation: pulse-badge 0.8s infinite ease-in-out; }
.transition-all { transition: all 0.25s ease; }
/* ========================================================================= */
/* MEJORAS DE CONTRASTE ESTRICTAS PARA MODO OSCURO (WCAG AA) */
/* ========================================================================= */
[data-bs-theme="dark"] .scanner-card,
[data-bs-theme="dark"] .logs-card,
[data-bs-theme="dark"] .result-validation-card,
[data-bs-theme="dark"] .com-config-card {
background-color: #17162E !important;
border: 1px solid rgba(255, 255, 255, 0.08) !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.45) !important;
}
[data-bs-theme="dark"] .card-header.bg-body {
background-color: #1F1D3C !important;
border-bottom: 1px solid rgba(255, 255, 255, 0.07) !important;
}
[data-bs-theme="dark"] #scannerInput {
background-color: #0E0D1D !important;
color: #F8FAFC !important;
border-color: #8B5CF6 !important;
}
[data-bs-theme="dark"] #scannerInput::placeholder {
color: #94A3B8 !important;
opacity: 0.8;
}
[data-bs-theme="dark"] .scanner-input-group {
border-color: #A855F7 !important;
box-shadow: 0 0 12px rgba(168, 85, 247, 0.2) !important;
}
[data-bs-theme="dark"] .bg-body-tertiary {
background-color: #1E1C38 !important;
border-color: rgba(255, 255, 255, 0.08) !important;
}
[data-bs-theme="dark"] #recentLogsTable thead,
[data-bs-theme="dark"] #recentLogsTable thead th {
background-color: #1F1D3C !important;
color: #F1F5F9 !important;
border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}
[data-bs-theme="dark"] #recentLogsTable td {
color: #E2E8F0 !important;
border-color: rgba(255, 255, 255, 0.05) !important;
}
[data-bs-theme="dark"] #recentLogsTable tbody tr:hover td {
background-color: rgba(180, 62, 142, 0.12) !important;
}
[data-bs-theme="dark"] .classes-section-container {
background-color: #1A1832 !important;
border-color: rgba(255, 255, 255, 0.08) !important;
}
[data-bs-theme="dark"] .classes-section-container .card {
background-color: #211E40 !important;
border-color: rgba(139, 92, 246, 0.25) !important;
}
[data-bs-theme="dark"] #waitingState h4 {
color: #F8FAFC !important;
}
[data-bs-theme="dark"] #waitingState p {
color: #94A3B8 !important;
}
</style>
{% endblock %}