feat(reception): filter virtual buildings, remove camera and add SDD-013 Web Serial COM support (v3.8.50)

This commit is contained in:
2026-10-28 14:04:45 -03:00
parent 4668117c35
commit 9f21442bed
12 changed files with 574 additions and 96 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "3.8.49",
"version": "3.8.50",
"description": "",
"main": "index.js",
"scripts": {
+186
View File
@@ -0,0 +1,186 @@
/**
* serial-scanner.js — Módulo de Lector Óptico y Escáner QR por Puerto Serie (COM)
* Específico para navegadores Chromium (Google Chrome, Microsoft Edge, Opera, Brave) en entornos Windows.
* Utiliza la Web Serial API (navigator.serial) para lectura directa y en segundo plano sin requerir foco.
* Espec: specs/013-escaner-qr-puerto-com-serial/
*/
(function(window) {
'use strict';
class SerialBarcodeScanner {
constructor(options = {}) {
this.baudRate = options.baudRate || 9600;
this.port = null;
this.reader = null;
this.readableStreamClosed = null;
this.keepReading = false;
this.buffer = '';
this.onCodeScanned = options.onCodeScanned || null;
this.onStatusChanged = options.onStatusChanged || null;
this.onError = options.onError || null;
this._initDisconnectListener();
}
isSupported() {
return typeof navigator !== 'undefined' && 'serial' in navigator;
}
_initDisconnectListener() {
if (this.isSupported()) {
navigator.serial.addEventListener('disconnect', (event) => {
if (this.port && event.target === this.port) {
this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado físicamente.');
this.disconnect();
}
});
}
}
_notifyStatus(status, message, details = {}) {
if (typeof this.onStatusChanged === 'function') {
this.onStatusChanged({ status, message, ...details });
}
}
async autoConnectIfAuthorized() {
if (!this.isSupported()) return false;
try {
const ports = await navigator.serial.getPorts();
if (ports && ports.length > 0) {
this.port = ports[0];
await this._openPort();
return true;
}
} catch (err) {
console.warn('[SerialScanner] Autoconnect notice:', err.message);
}
return false;
}
async requestAndConnect(baudRate = null) {
if (!this.isSupported()) {
throw new Error('La Web Serial API no está soportada en este navegador. Utiliza Google Chrome o Microsoft Edge.');
}
if (baudRate) {
this.baudRate = parseInt(baudRate, 10) || 9600;
}
// Desconectar puerto previo si estuviera activo
if (this.port) {
await this.disconnect();
}
// Despliega el diálogo nativo de Windows para seleccionar dispositivo COM
this.port = await navigator.serial.requestPort();
await this._openPort();
return this.port;
}
async _openPort() {
if (!this.port) return;
await this.port.open({
baudRate: this.baudRate,
dataBits: 8,
stopBits: 1,
parity: 'none',
bufferSize: 1024
});
this.keepReading = true;
this._notifyStatus('CONNECTED', `Puerto serie conectado a ${this.baudRate} baudios.`, {
baudRate: this.baudRate
});
this._startReadingLoop();
}
async _startReadingLoop() {
while (this.port && this.port.readable && this.keepReading) {
const textDecoder = new TextDecoderStream();
this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable);
this.reader = textDecoder.readable.getReader();
try {
while (this.keepReading) {
const { value, done } = await this.reader.read();
if (done) break;
if (value) {
this._handleIncomingText(value);
}
}
} catch (error) {
if (this.keepReading) {
console.error('[SerialScanner] Error en lectura serie:', error);
if (typeof this.onError === 'function') {
this.onError(error);
}
}
} finally {
try {
this.reader.releaseLock();
} catch (e) {}
}
}
}
_handleIncomingText(chunk) {
this.buffer += chunk;
// Detectar delimitadores de fin de línea habituales en pistolas ópticas (\r, \n)
if (this.buffer.includes('\n') || this.buffer.includes('\r')) {
const parts = this.buffer.split(/[\r\n]+/);
for (let i = 0; i < parts.length - 1; i++) {
const rawCode = parts[i].trim();
if (rawCode.length >= 2) {
this._dispatchCode(rawCode);
}
}
this.buffer = parts[parts.length - 1];
}
}
_dispatchCode(code) {
// Normalizar scancodes si fuera necesario
const cleanCode = code.replace(/Ñ/g, ':').replace(/ñ/g, ':');
if (typeof this.onCodeScanned === 'function') {
this.onCodeScanned(cleanCode);
}
}
async disconnect() {
this.keepReading = false;
if (this.reader) {
try {
await this.reader.cancel();
} catch (e) {}
this.reader = null;
}
if (this.readableStreamClosed) {
try {
await this.readableStreamClosed.catch(() => {});
} catch (e) {}
this.readableStreamClosed = null;
}
if (this.port) {
try {
await this.port.close();
} catch (e) {}
this.port = null;
}
this.buffer = '';
this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado.');
}
}
// Exportar al objeto global de ventana
window.SerialBarcodeScanner = SerialBarcodeScanner;
})(window);
+3 -3
View File
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
});
// Versiones institucionales del sistema
const APP_VERSION = '3.8.49';
const FRONTEND_VERSION = '3.8.49';
const BACKEND_VERSION = '3.8.49';
const APP_VERSION = '3.8.50';
const FRONTEND_VERSION = '3.8.50';
const BACKEND_VERSION = '3.8.50';
env.addGlobal('app_version', APP_VERSION);
env.addGlobal('frontend_version', FRONTEND_VERSION);
+30 -3
View File
@@ -26,7 +26,24 @@ router.get('/scanner', async (req, res) => {
req.apiClient.get('/buildings'),
req.apiClient.get('/reception/recent-logs', { params: { limit: 15 } })
]);
buildings = respBld.data?.buildings || respBld.data || [];
const rawBuildings = respBld.data?.buildings || respBld.data || [];
// Filtrar estrictamente solo sedes físicas (excluyendo sedes virtuales)
buildings = rawBuildings.filter(b => {
const code = (b.code || '').toUpperCase();
const name = (b.name || '').toUpperCase();
const isVirt = Boolean(b.is_virtual || code.includes('VIRTUAL') || name.includes('VIRTUAL'));
return !isVirt;
});
// Predeterminar Edificio Central
let defaultBuildingId = null;
const central = buildings.find(b => (b.code || '').toUpperCase().includes('CENTRAL') || (b.name || '').toUpperCase().includes('CENTRAL'));
if (central) {
defaultBuildingId = central.id;
} else if (buildings.length > 0) {
defaultBuildingId = buildings[0].id;
}
recentLogs = (respLogs.data?.items || []).map(l => {
let timeStr = l.scanned_time;
if (!timeStr && l.scanned_at) {
@@ -45,14 +62,24 @@ router.get('/scanner', async (req, res) => {
}
return { ...l, scanned_time: timeStr || '--' };
});
res.render('reception/scanner', {
title: 'Control de Acceso QR — Recepción & Seguridad',
buildings,
defaultBuildingId,
recentLogs,
userRole: role
});
return;
} catch (err) {
console.warn('Reception scanner init notice:', err.message);
}
res.render('reception/scanner', {
title: 'Control de Acceso QR — Recepción & Seguridad',
buildings,
recentLogs,
buildings: [],
defaultBuildingId: null,
recentLogs: [],
userRole: role
});
});
+138 -82
View File
@@ -19,11 +19,12 @@
<div class="d-flex align-items-center gap-3">
<div>
<label class="small text-muted fw-bold d-block">Punto de Control / Sede:</label>
<select class="form-select form-select-sm rounded-pill px-3" id="buildingSelect">
<option value="">Todas las Sedes</option>
<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 loop.first %}selected{% endif %}>{{ b.name }}</option>
<option value="{{ b.id }}" {% if b.id == defaultBuildingId or (not defaultBuildingId and loop.first) %}selected{% endif %}>
{{ b.name }}
</option>
{% endfor %}
</select>
</div>
@@ -31,45 +32,68 @@
</div>
<div class="row g-4">
<!-- Columna Izquierda: Escáner y Entrada Rápida -->
<!-- Columna Izquierda: Escáner Óptico / Pistola USB y Puerto Serial -->
<div class="col-12 col-lg-5">
<div class="card border-0 shadow-sm rounded-4 p-4 mb-4">
<h5 class="fw-bold mb-3 d-flex align-items-center justify-content-between">
<span><i class="bi bi-camera me-2 text-primary"></i>Lector de Cámara</span>
<button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" id="toggleCamBtn" onclick="toggleCamera()">
<i class="bi bi-play-circle me-1"></i> Iniciar Cámara
</button>
</h5>
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="fw-bold mb-0 text-dark d-flex align-items-center">
<i class="bi bi-upc-scan me-2 text-primary"></i>Lector Óptico de Acceso
</h5>
<span class="small text-success fw-semibold d-flex align-items-center gap-1" id="scannerFocusIndicator" title="El cursor está atrapado permanentemente en este campo para lectura USB directa">
<span class="scanner-active-dot"></span> Lector Listo
</span>
</div>
<!-- Visor de Cámara -->
<div id="reader" class="rounded-4 overflow-hidden bg-dark position-relative d-flex align-items-center justify-content-center text-white"
style="width: 100%; min-height: 280px;">
<div id="cameraPlaceholder" class="text-center p-4">
<i class="bi bi-camera-video display-4 text-secondary mb-2 d-block"></i>
<span class="small text-muted">Cámara en espera. Presiona "Iniciar Cámara" o utiliza un lector óptico USB.</span>
<!-- Banner Informativo de Operación -->
<div class="p-3 bg-light rounded-4 border mb-3 text-start">
<div class="d-flex align-items-start gap-2">
<i class="bi bi-shield-check text-primary fs-5 mt-1"></i>
<div>
<div class="fw-bold small text-dark">Modo Alta Velocidad USB HID / COM</div>
<div class="text-muted small" style="font-size: 0.76rem;">
El cursor se mantiene retenido permanentemente en el campo de escaneo. Dispara la pistola óptica sobre la credencial QR o DNI físico para registrar el acceso en tiempo real.
</div>
</div>
</div>
</div>
<!-- Entrada Manual o Pistola Óptica USB -->
<!-- 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">
<input type="text" class="form-control rounded-start-pill ps-3 border-0 py-2 fs-6" id="scannerInput"
placeholder="Escanea con la pistola o escribe el DNI..." autofocus 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>
<!-- Panel de Conexión Serial / Puerto COM (Web Serial API) -->
<div class="mt-4 pt-3 border-top">
<div class="d-flex align-items-center justify-content-between mb-1">
<label class="form-label small fw-bold text-uppercase text-muted mb-0">
<i class="bi bi-upc-scan me-1 text-primary"></i> Pistola Óptica USB o Entrada Manual
</label>
<span class="small text-success fw-semibold d-flex align-items-center gap-1" id="scannerFocusIndicator" title="El cursor está bloqueado en este campo para recibir el escaneo inmediato">
<span class="scanner-active-dot"></span> Lector Listo
<div class="d-flex align-items-center justify-content-between mb-2">
<span class="small fw-bold text-uppercase text-muted">
<i class="bi bi-usb-symbol me-1 text-primary"></i> Puerto Serie (COM)
</span>
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small" id="serialPortStatusBadge">
<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> Puerto USB-HID Activo
</span>
</div>
<form id="manualScanForm" onsubmit="handleManualScan(event)">
<div class="input-group shadow-sm rounded-pill overflow-hidden border border-2 border-primary">
<input type="text" class="form-control rounded-start-pill ps-3 border-0" id="scannerInput"
placeholder="Escanea con la pistola o escribe el DNI..." autofocus autocomplete="off">
<button class="btn btn-primary rounded-end-pill px-4 fw-semibold border-0" type="submit">
Validar
</button>
</div>
<span class="small text-muted d-block mt-1">El cursor se mantiene siempre activo aquí. La pistola óptica envía la lectura y valida automáticamente.</span>
</form>
<div class="d-flex align-items-center justify-content-between p-2 rounded-3 bg-body-tertiary border">
<small class="text-muted" style="font-size: 0.74rem;">
Dispositivos Seriales COM (Windows / Chromium)
</small>
<button type="button" class="btn btn-xs btn-outline-secondary rounded-pill px-3 py-1 text-nowrap" id="btnConnectSerial" onclick="handleSerialConnectClick()">
<i class="bi bi-link-45deg me-1"></i>Configurar COM
</button>
</div>
</div>
</div>
</div>
@@ -87,9 +111,9 @@
<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">
<i class="bi bi-qr-code-scan display-1 opacity-25 text-primary mb-3 d-block"></i>
<h4 class="fw-bold text-secondary">Apunta el código QR a la cámara</h4>
<h4 class="fw-bold text-secondary">Apunta el lector óptico a la credencial</h4>
<p class="small text-muted max-w-md mx-auto">
Al detectar la credencial del alumno o docente, el sistema mostrará instantáneamente sus datos de ingreso y las aulas donde cursa hoy.
Al detectar la credencial dinámica o física del alumno o docente, el sistema mostrará instantáneamente sus datos de ingreso y las aulas donde cursa hoy.
</p>
</div>
@@ -184,58 +208,89 @@
</div>
</div>
<!-- html5-qrcode Library via CDN -->
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<!-- Módulo de Web Serial API para lectores ópticos y escáneres QR (SDD-013) -->
<script src="/js/serial-scanner.js"></script>
<script>
let html5QrCode = null;
let isCameraRunning = false;
let isScanningLocked = false;
let serialScanner = null;
// Inicializar o alternar cámara
function toggleCamera() {
const btn = document.getElementById('toggleCamBtn');
const placeholder = document.getElementById('cameraPlaceholder');
// Inicializar SerialBarcodeScanner para Chromium / Windows
function initSerialScanner() {
if (typeof SerialBarcodeScanner === 'undefined') return;
if (isCameraRunning) {
if (html5QrCode) {
html5QrCode.stop().then(() => {
isCameraRunning = false;
btn.innerHTML = '<i class="bi bi-play-circle me-1"></i> Iniciar Cámara';
btn.classList.replace('btn-danger', 'btn-outline-primary');
placeholder.classList.remove('d-none');
});
}
} else {
html5QrCode = new Html5Qrcode("reader");
placeholder.classList.add('d-none');
html5QrCode.start(
{ facingMode: "environment" },
{
fps: 10,
qrbox: { width: 250, height: 250 }
},
(decodedText) => {
if (!isScanningLocked) {
isScanningLocked = true;
playBeep(true);
verifyToken(decodedText);
setTimeout(() => { isScanningLocked = false; }, 2500);
}
},
(errorMessage) => {
// Errores normales de lectura frame a frame, se omiten
serialScanner = new SerialBarcodeScanner({
baudRate: 9600,
onCodeScanned: function(code) {
if (!isScanningLocked) {
isScanningLocked = true;
playBeep(true);
verifyToken(code);
setTimeout(() => { isScanningLocked = false; }, 1500);
}
).then(() => {
isCameraRunning = true;
btn.innerHTML = '<i class="bi bi-stop-circle me-1"></i> Detener Cámara';
btn.classList.replace('btn-outline-primary', 'btn-danger');
}).catch(err => {
console.error("Error al iniciar cámara:", err);
placeholder.classList.remove('d-none');
alert("No se pudo acceder a la cámara. Asegúrate de otorgar los permisos en el navegador.");
});
},
onStatusChanged: function(evt) {
const badge = document.getElementById('serialPortStatusBadge');
const btn = document.getElementById('btnConnectSerial');
if (evt.status === 'CONNECTED') {
if (badge) {
badge.className = 'badge bg-success text-white rounded-pill px-2 py-1 small';
badge.innerHTML = '<i class="bi bi-usb-plug-fill me-1"></i> COM Activo (9600 baud)';
}
if (btn) {
btn.className = 'btn btn-xs btn-outline-danger rounded-pill px-3 py-1 text-nowrap';
btn.innerHTML = '<i class="bi bi-x-circle me-1"></i>Desconectar';
}
} else {
if (badge) {
badge.className = 'badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small';
badge.innerHTML = '<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> Puerto USB-HID Activo';
}
if (btn) {
btn.className = 'btn btn-xs btn-outline-secondary rounded-pill px-3 py-1 text-nowrap';
btn.innerHTML = '<i class="bi bi-link-45deg me-1"></i>Configurar COM';
}
}
},
onError: function(err) {
console.warn('[SerialScanner UI] Error:', err);
}
});
// Comprobar soporte
if (!serialScanner.isSupported()) {
const badge = document.getElementById('serialPortStatusBadge');
const btn = document.getElementById('btnConnectSerial');
if (badge) {
badge.className = 'badge bg-body-tertiary text-muted rounded-pill px-2 py-1 small border';
badge.textContent = 'Modo USB-HID (Chromium requerido para COM)';
}
if (btn) btn.disabled = true;
} else {
// Intentar auto-conexión a puerto previamente autorizado
serialScanner.autoConnectIfAuthorized();
}
}
async function handleSerialConnectClick() {
if (!serialScanner) initSerialScanner();
if (!serialScanner.isSupported()) {
alert('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge en entornos Windows.');
return;
}
const btn = document.getElementById('btnConnectSerial');
if (serialScanner.port) {
await serialScanner.disconnect();
} else {
try {
await serialScanner.requestAndConnect(9600);
} catch (err) {
if (err.name !== 'NotFoundError') {
console.error('Error al conectar puerto COM:', err);
alert('No se pudo abrir el puerto serie: ' + err.message);
}
}
}
}
@@ -445,6 +500,7 @@
// Eventos globales para forzar el foco permanente en scannerInput
document.addEventListener('DOMContentLoaded', () => {
initSerialScanner();
focusScannerInput();
setInterval(focusScannerInput, 2000);