feat(reception): add multi-serial scanner for up to 4 COM ports and universal Argentine DNI parser (v3.8.52)

This commit is contained in:
2026-10-28 14:47:54 -03:00
parent 1477780df0
commit 19495e96b4
14 changed files with 806 additions and 183 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "3.8.51",
"version": "3.8.52",
"description": "",
"main": "index.js",
"scripts": {
+197 -76
View File
@@ -1,186 +1,307 @@
/**
* serial-scanner.js — Módulo de Lector Óptico y Escáner QR por Puerto Serie (COM)
* serial-scanner.js — Módulo Multi-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/
* Soporta hasta 4 lectores seriales concurrentes mediante la Web Serial API (navigator.serial).
* Especificación: specs/013-escaner-qr-puerto-com-serial/
*/
(function(window) {
'use strict';
class SerialBarcodeScanner {
constructor(options = {}) {
class SerialSlot {
constructor(id, name, options = {}) {
this.id = id;
this.name = name || `Lector ${id}`;
this.baudRate = options.baudRate || 9600;
this.port = null;
this.reader = null;
this.readableStreamClosed = null;
this.keepReading = false;
this.buffer = '';
this.status = 'DISCONNECTED'; // 'DISCONNECTED' | 'CONNECTED' | 'ERROR'
this.lastCode = '';
this.lastScannedAt = null;
}
isConnected() {
return this.status === 'CONNECTED' && this.port !== null && Boolean(this.port.readable);
}
}
class MultiSerialBarcodeScanner {
constructor(options = {}) {
this.maxSlots = 4;
this.slots = [
new SerialSlot(1, 'Lector 1 (Paso Principal)', options),
new SerialSlot(2, 'Lector 2 (Molinete / Acceso)', options),
new SerialSlot(3, 'Lector 3 (Mesa Bedelía)', options),
new SerialSlot(4, 'Lector 4 (Auxiliar / Puesto 2)', options)
];
this.onCodeScanned = options.onCodeScanned || null;
this.onStatusChanged = options.onStatusChanged || null;
this.onError = options.onError || null;
this._initDisconnectListener();
this._initGlobalDisconnectListener();
}
isSupported() {
return typeof navigator !== 'undefined' && 'serial' in navigator;
}
_initDisconnectListener() {
getSlots() {
return this.slots;
}
getSlot(slotId) {
return this.slots.find(s => s.id === slotId) || null;
}
getConnectedCount() {
return this.slots.filter(s => s.isConnected()).length;
}
_initGlobalDisconnectListener() {
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();
const disconnectedSlot = this.slots.find(s => s.port === event.target);
if (disconnectedSlot) {
this.disconnectSlot(disconnectedSlot.id, 'Dispositivo serie desconectado físicamente.');
}
});
}
}
_notifyStatus(status, message, details = {}) {
_notifyStatus(slot, message, extra = {}) {
if (typeof this.onStatusChanged === 'function') {
this.onStatusChanged({ status, message, ...details });
this.onStatusChanged({
slotId: slot.id,
slotName: slot.name,
status: slot.status,
message: message || '',
baudRate: slot.baudRate,
totalConnected: this.getConnectedCount(),
...extra
});
}
}
async autoConnectIfAuthorized() {
if (!this.isSupported()) return false;
/**
* Reabre automáticamente los puertos previamente autorizados por el usuario en esta terminal.
*/
async autoConnectAuthorizedPorts() {
if (!this.isSupported()) return 0;
try {
const ports = await navigator.serial.getPorts();
if (ports && ports.length > 0) {
this.port = ports[0];
await this._openPort();
return true;
if (!ports || ports.length === 0) return 0;
let connectedCount = 0;
for (let i = 0; i < Math.min(ports.length, this.maxSlots); i++) {
const slot = this.slots[i];
if (!slot.isConnected()) {
try {
slot.port = ports[i];
await this._openPortOnSlot(slot);
connectedCount++;
} catch (err) {
console.warn(`[MultiSerialScanner] Autoconnect slot ${slot.id} notice:`, err.message);
}
}
}
return connectedCount;
} catch (err) {
console.warn('[SerialScanner] Autoconnect notice:', err.message);
console.warn('[MultiSerialScanner] Error consultando puertos autorizados:', err);
return 0;
}
return false;
}
async requestAndConnect(baudRate = null) {
/**
* Solicita al operador seleccionar un dispositivo serie COM y lo asigna al slot especificado.
*/
async requestAndConnectSlot(slotId, baudRate = null) {
if (!this.isSupported()) {
throw new Error('La Web Serial API no está soportada en este navegador. Utiliza Google Chrome o Microsoft Edge.');
throw new Error('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge en Windows.');
}
const slot = this.getSlot(slotId);
if (!slot) {
throw new Error(`Slot #${slotId} no válido (debe ser entre 1 y ${this.maxSlots}).`);
}
if (baudRate) {
this.baudRate = parseInt(baudRate, 10) || 9600;
slot.baudRate = parseInt(baudRate, 10) || 9600;
}
// Desconectar puerto previo si estuviera activo
if (this.port) {
await this.disconnect();
// Si el slot ya estaba conectado, liberarlo previamente
if (slot.isConnected()) {
await this.disconnectSlot(slot.id);
}
// Despliega el diálogo nativo de Windows para seleccionar dispositivo COM
this.port = await navigator.serial.requestPort();
await this._openPort();
return this.port;
// Despliega el diálogo nativo de Windows para seleccionar dispositivo serie COM
const port = await navigator.serial.requestPort();
slot.port = port;
await this._openPortOnSlot(slot);
return slot;
}
async _openPort() {
if (!this.port) return;
async _openPortOnSlot(slot) {
if (!slot || !slot.port) return;
await this.port.open({
baudRate: this.baudRate,
await slot.port.open({
baudRate: slot.baudRate,
dataBits: 8,
stopBits: 1,
parity: 'none',
bufferSize: 1024
bufferSize: 2048
});
this.keepReading = true;
this._notifyStatus('CONNECTED', `Puerto serie conectado a ${this.baudRate} baudios.`, {
baudRate: this.baudRate
});
slot.keepReading = true;
slot.status = 'CONNECTED';
this._notifyStatus(slot, `Lector COM conectado a ${slot.baudRate} baudios.`);
this._startReadingLoop();
this._startReadingLoop(slot);
}
async _startReadingLoop() {
while (this.port && this.port.readable && this.keepReading) {
async _startReadingLoop(slot) {
while (slot.port && slot.port.readable && slot.keepReading) {
const textDecoder = new TextDecoderStream();
this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable);
this.reader = textDecoder.readable.getReader();
slot.readableStreamClosed = slot.port.readable.pipeTo(textDecoder.writable);
slot.reader = textDecoder.readable.getReader();
try {
while (this.keepReading) {
const { value, done } = await this.reader.read();
while (slot.keepReading) {
const { value, done } = await slot.reader.read();
if (done) break;
if (value) {
this._handleIncomingText(value);
this._handleIncomingText(slot, value);
}
}
} catch (error) {
if (this.keepReading) {
console.error('[SerialScanner] Error en lectura serie:', error);
if (slot.keepReading) {
console.error(`[MultiSerialScanner] Error en lectura de slot ${slot.id}:`, error);
if (typeof this.onError === 'function') {
this.onError(error);
this.onError(error, slot);
}
}
} finally {
try {
this.reader.releaseLock();
slot.reader.releaseLock();
} catch (e) {}
}
}
}
_handleIncomingText(chunk) {
this.buffer += chunk;
_handleIncomingText(slot, chunk) {
slot.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]+/);
// Delimitadores habituales de lectores y pistolas ópticas (\r, \n)
if (slot.buffer.includes('\n') || slot.buffer.includes('\r')) {
const parts = slot.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._dispatchCode(slot, rawCode);
}
}
this.buffer = parts[parts.length - 1];
slot.buffer = parts[parts.length - 1];
}
}
_dispatchCode(code) {
// Normalizar scancodes si fuera necesario
_dispatchCode(slot, code) {
// Normalizar tolerante de scancodes si el lector traduce : a Ñ en teclados en español
const cleanCode = code.replace(/Ñ/g, ':').replace(/ñ/g, ':');
slot.lastCode = cleanCode;
slot.lastScannedAt = new Date();
if (typeof this.onCodeScanned === 'function') {
this.onCodeScanned(cleanCode);
this.onCodeScanned(cleanCode, {
slotId: slot.id,
slotName: slot.name,
timestamp: slot.lastScannedAt
});
}
}
async disconnect() {
this.keepReading = false;
async disconnectSlot(slotId, reason = 'Desconectado por el usuario') {
const slot = this.getSlot(slotId);
if (!slot) return;
if (this.reader) {
slot.keepReading = false;
slot.status = 'DISCONNECTED';
if (slot.reader) {
try {
await this.reader.cancel();
await slot.reader.cancel();
} catch (e) {}
this.reader = null;
slot.reader = null;
}
if (this.readableStreamClosed) {
if (slot.readableStreamClosed) {
try {
await this.readableStreamClosed.catch(() => {});
await slot.readableStreamClosed.catch(() => {});
} catch (e) {}
this.readableStreamClosed = null;
slot.readableStreamClosed = null;
}
if (this.port) {
if (slot.port) {
try {
await this.port.close();
await slot.port.close();
} catch (e) {}
this.port = null;
slot.port = null;
}
this.buffer = '';
this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado.');
slot.buffer = '';
this._notifyStatus(slot, reason);
}
async disconnectAll() {
for (const slot of this.slots) {
if (slot.isConnected()) {
await this.disconnectSlot(slot.id);
}
}
}
}
// Exportar al objeto global de ventana
window.SerialBarcodeScanner = SerialBarcodeScanner;
// Compatibilidad hacia atrás para código que instancie SerialBarcodeScanner directamente
class SerialBarcodeScannerCompat {
constructor(options = {}) {
this.multi = new MultiSerialBarcodeScanner({
...options,
onCodeScanned: (code, info) => {
if (typeof options.onCodeScanned === 'function') {
options.onCodeScanned(code, info);
}
},
onStatusChanged: (evt) => {
if (typeof options.onStatusChanged === 'function') {
options.onStatusChanged(evt);
}
}
});
}
isSupported() {
return this.multi.isSupported();
}
async autoConnectIfAuthorized() {
const count = await this.multi.autoConnectAuthorizedPorts();
return count > 0;
}
async requestAndConnect(baudRate = null) {
return await this.multi.requestAndConnectSlot(1, baudRate);
}
async disconnect() {
await this.multi.disconnectSlot(1);
}
}
// Exportar al objeto global
window.MultiSerialBarcodeScanner = MultiSerialBarcodeScanner;
window.SerialBarcodeScanner = SerialBarcodeScannerCompat;
})(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.51';
const FRONTEND_VERSION = '3.8.51';
const BACKEND_VERSION = '3.8.51';
const APP_VERSION = '3.8.52';
const FRONTEND_VERSION = '3.8.52';
const BACKEND_VERSION = '3.8.52';
env.addGlobal('app_version', APP_VERSION);
env.addGlobal('frontend_version', FRONTEND_VERSION);
+221 -64
View File
@@ -76,23 +76,119 @@
</div>
</form>
<!-- Panel de Conexión Serial / Puerto COM (Web Serial API) -->
<!-- Panel de Conexión Multi-Lector Serial / Puertos COM (Hasta 4 lectores) -->
<div class="mt-4 pt-3 border-top">
<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
<i class="bi bi-usb-symbol me-1 text-primary"></i> Lectores Serie COM (Hasta 4)
</span>
<div class="d-flex align-items-center gap-1">
<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-xs btn-link text-decoration-none p-0 text-muted" title="Reconectar autorizados" onclick="reconnectAuthorizedComPorts()">
<i class="bi bi-arrow-clockwise"></i>
</button>
</div>
</div>
<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>
<!-- Grilla de los 4 Slots de Lectores Seriales -->
<div class="row g-2" id="serialSlotsContainer">
<!-- Slot 1 -->
<div class="col-12">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all" 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-dark" 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">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all" 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-dark" style="font-size: 0.78rem;">Lector 2 (Molinete / Acceso)</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">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all" 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-dark" style="font-size: 0.78rem;">Lector 3 (Mesa 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">
<div class="p-2 rounded-3 bg-body-tertiary border transition-all" 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-dark" style="font-size: 0.78rem;">Lector 4 (Auxiliar / Puesto 2)</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>
@@ -218,87 +314,132 @@
<script>
let isScanningLocked = false;
let serialScanner = null;
let multiScanner = null;
// Inicializar SerialBarcodeScanner para Chromium / Windows
// Inicializar MultiSerialBarcodeScanner (hasta 4 lectores COM)
function initSerialScanner() {
if (typeof SerialBarcodeScanner === 'undefined') return;
if (typeof MultiSerialBarcodeScanner === 'undefined') return;
serialScanner = new SerialBarcodeScanner({
multiScanner = new MultiSerialBarcodeScanner({
baudRate: 9600,
onCodeScanned: function(code) {
onCodeScanned: function(code, slotInfo) {
if (!isScanningLocked) {
isScanningLocked = true;
playBeep(true);
verifyToken(code);
// Destello visual en la tarjeta del lector específico emisor
flashSlotCard(slotInfo ? slotInfo.slotId : 1);
verifyToken(code, slotInfo);
setTimeout(() => { isScanningLocked = false; }, 1500);
}
},
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';
}
}
updateSlotUI(evt);
},
onError: function(err) {
console.warn('[SerialScanner UI] Error:', err);
onError: function(err, slot) {
console.warn(`[MultiSerialScanner UI] Error en slot ${slot ? slot.id : '?'}:`, err);
}
});
// Comprobar soporte
if (!serialScanner.isSupported()) {
const badge = document.getElementById('serialPortStatusBadge');
const btn = document.getElementById('btnConnectSerial');
// Comprobar compatibilidad con Web Serial API
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.textContent = 'Modo USB-HID (Chromium requerido para COM)';
badge.innerHTML = '<i class="bi bi-info-circle me-1"></i> Modo USB-HID (Chromium requerido para COM)';
}
for (let i = 1; i <= 4; i++) {
const btn = document.getElementById(`btnConnectSlot${i}`);
if (btn) btn.disabled = true;
}
if (btn) btn.disabled = true;
} else {
// Intentar auto-conexión a puerto previamente autorizado
serialScanner.autoConnectIfAuthorized();
// Reabrir automáticamente puertos autorizados
reconnectAuthorizedComPorts();
}
}
async function handleSerialConnectClick() {
if (!serialScanner) initSerialScanner();
if (!serialScanner.isSupported()) {
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 en entornos Windows.');
return;
}
const btn = document.getElementById('btnConnectSerial');
if (serialScanner.port) {
await serialScanner.disconnect();
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 serialScanner.requestAndConnect(9600);
await multiScanner.requestAndConnectSlot(slotId, baudRate);
} catch (err) {
if (err.name !== 'NotFoundError') {
console.error('Error al conectar puerto COM:', err);
alert('No se pudo abrir el puerto serie: ' + err.message);
console.error(`Error conectando slot ${slotId}:`, err);
alert(`No se pudo abrir el puerto serie para el Lector ${slotId}: ` + err.message);
}
}
}
}
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.`);
}
}
}
// Mantener el cursor forzado permanentemente en el input de la pistola óptica
function focusScannerInput() {
const input = document.getElementById('scannerInput');
@@ -342,7 +483,7 @@
}
// Petición AJAX de verificación al Backend BFF
async function verifyToken(token) {
async function verifyToken(token, slotInfo = null) {
const buildingId = document.getElementById('buildingSelect').value;
try {
@@ -356,7 +497,7 @@
});
const data = await resp.json();
displayVerificationResult(data);
displayVerificationResult(data, slotInfo);
refreshRecentLogs();
} catch (err) {
console.error('Error verificando:', err);
@@ -364,14 +505,14 @@
status: 'DENEGADO',
message: 'Error de conexión con el validador.',
todays_classes: []
});
}, slotInfo);
} finally {
setTimeout(focusScannerInput, 150);
}
}
// Despliegue visual de resultados en pantalla
function displayVerificationResult(data) {
function displayVerificationResult(data, slotInfo = null) {
const waitingState = document.getElementById('waitingState');
const activeState = document.getElementById('activeResultState');
const resultCard = document.getElementById('resultCard');
@@ -392,8 +533,10 @@
void resultCard.offsetWidth; // Forzar reflow para reiniciar animación
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'); }, 2500);
setTimeout(() => { alertBadge.classList.add('d-none'); }, 3000);
}
const hasClasses = Boolean(data.todays_classes && data.todays_classes.length > 0);
@@ -474,6 +617,20 @@
</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-dark p-3 rounded-4 mb-0 shadow-xs">