diff --git a/CHANGELOG.md b/CHANGELOG.md index b340842..fb3853d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,18 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1 - **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1. - **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción. +## [3.8.50] - 2026-10-28 +### Added & Changed (Depuración de Sedes Físicas en Recepción, Eliminación de Cámara y Especificación SDD-013 Web Serial COM) +- **Depuración de Sedes en la Consola de Recepción**: + - Se filtró estrictamente el selector de sedes (`/reception/scanner`) para mostrar únicamente sedes físicas/presenciales, excluyendo completamente al Campus Virtual por tratarse de un puesto de control físico. + - Se configuró la sede física **Edificio Central** (`CENTRAL`) como el punto de control predeterminado seleccionado al abrir la consola de acceso. +- **Eliminación Total del Escaneo por Cámara Web**: + - Se removió el lector de cámara, la librería `html5-qrcode` y los botones interactivos asociados, reconvirtiendo la columna de escaneo en un panel dedicado de alta velocidad para pistolas ópticas y lectores por puerto serie. +- **Especificación e Integración SDD-013 (Lector Óptico por Puerto Serie COM)**: + - Creación de la especificación SDD-013 (`specs/013-escaner-qr-puerto-com-serial/` con `spec.md`, `plan.md`, `tasks.md`) bajo sintaxis EARS en español. + - Implementación del módulo frontend `serial-scanner.js` utilizando la **Web Serial API** (`navigator.serial`) para motores Chromium (Google Chrome, Microsoft Edge, Opera, Brave) en entornos Windows. + - Permite la captura directa de lecturas de código de barras y QR desde puertos COM físicos/virtuales sin depender del foco del cursor ni de la emulación de teclado, con reconexión automática y bufferizado por delimitador de línea. + ## [3.8.49] - 2026-10-28 ### Added & Fixed (Anti-Captura Estricto en QR Dinámico, Corrección de Zona Horaria de Buenos Aires y Registro Óptico) - **Corrección Integral del Desfasaje Horario en Registros de Ingreso**: diff --git a/MEMORY.md b/MEMORY.md index 825340c..c004e1b 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,11 +9,11 @@ Memoria del proyecto entre sesiones para la rama `dev`. - Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables. - Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación. - Reinicialización segura del sistema con contraseña de Administrador. -- **Sprint Activo: Anti-Captura Estricto en QR Dinámico y Corrección de Zona Horaria (v3.8.49)**: - - **Corrección Integral del Desfasaje Horario (16:18 vs 13:18)**: Solucionado el desfasaje de 3 horas en la Consola de Recepción (`/reception/scanner`). Se implementó `to_argentina_time` en `reception.py` convirtiendo los timestamps a la zona horaria institucional de Buenos Aires (`America/Argentina/Buenos_Aires`, UTC-3) e inyectando `scanned_time`. Adaptado tanto el render Nunjucks inicial como las actualizaciones periódicas AJAX. - - **Ventana Estricta Anti-Captura en QR Dinámico**: Periodo de validez del JWT reducido a 6 segundos (`valid_seconds = 6`), de modo que capturas de pantalla o fotos del código QR de 10 segundos o más queden categóricamente expiradas y rechazadas con `jwt.ExpiredSignatureError`. - - **Priorización Criptográfica**: `decode_and_resolve_user` evalúa prioritariamente la firma JWT con control de expiración estricto, informando al operador: *"La credencial digital ha expirado (anti-captura activo). Renueve el código en la pantalla del usuario."* - - **Versión Consolidada**: `v3.8.49`. +- **Sprint Activo: Consola de Recepción Presencial y Lector por Puerto Serie (v3.8.50)**: + - **Sede Física Exclusiva y Edificio Central Predeterminado**: Filtrado total de sedes virtuales en `/reception/scanner`. Edificio Central fijado como sede predeterminada de control de acceso. + - **Depuración de Cámara Web**: Removido el visor de cámara y la dependencia de `html5-qrcode`, consolidando la consola en modo lector óptico / pistola de alta velocidad. + - **Especificación e Integración SDD-013 (Web Serial COM en Chromium/Windows)**: Especificación formal completa en `specs/013-escaner-qr-puerto-com-serial/` y módulo `serial-scanner.js` para captura directa asíncrona desde puertos COM (`navigator.serial`) sin requerir foco en el cursor. + - **Versión Consolidada**: `v3.8.50`. ## Decisiones (y por qué) - **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 47001d2..79cfaa5 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -7,7 +7,7 @@ from typing import Any from database import db, get_db, engine, SessionLocal, session from config.config import Config -__version__ = "3.8.49" +__version__ = "3.8.50" class DummyContext: def __enter__(self): diff --git a/backend/setup.py b/backend/setup.py index 7e21b0b..a685a8e 100644 --- a/backend/setup.py +++ b/backend/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name="edu-space-admin", - version="3.8.49", + version="3.8.50", description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)", author="Edu-Space Development Team", author_email="admin@edu-space.com", diff --git a/frontend/package.json b/frontend/package.json index 5c45b94..932d266 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.8.49", + "version": "3.8.50", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/public/js/serial-scanner.js b/frontend/public/js/serial-scanner.js new file mode 100644 index 0000000..375b348 --- /dev/null +++ b/frontend/public/js/serial-scanner.js @@ -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); diff --git a/frontend/src/app.js b/frontend/src/app.js index 6c893cb..0ab3612 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -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); diff --git a/frontend/src/routes/reception.js b/frontend/src/routes/reception.js index 62190fb..813930e 100644 --- a/frontend/src/routes/reception.js +++ b/frontend/src/routes/reception.js @@ -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 }); }); diff --git a/frontend/views/reception/scanner.html b/frontend/views/reception/scanner.html index 62d0fe0..323014f 100644 --- a/frontend/views/reception/scanner.html +++ b/frontend/views/reception/scanner.html @@ -19,11 +19,12 @@
- - {% for b in buildings %} - + {% endfor %}
@@ -31,45 +32,68 @@
- +
-
- Lector de Cámara - -
+
+
+ Lector Óptico de Acceso +
+ + Lector Listo + +
- -
-
- - Cámara en espera. Presiona "Iniciar Cámara" o utiliza un lector óptico USB. + +
+
+ +
+
Modo Alta Velocidad USB HID / COM
+
+ 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. +
+
- + +
+
+ + +
+
+ + Captura automática al recibir el delimitador Enter + + +
+
+ +
-
- - - Lector Listo +
+ + Puerto Serie (COM) + + + Puerto USB-HID Activo
-
-
- - -
- El cursor se mantiene siempre activo aquí. La pistola óptica envía la lectura y valida automáticamente. -
+
+ + Dispositivos Seriales COM (Windows / Chromium) + + +
@@ -87,9 +111,9 @@
-

Apunta el código QR a la cámara

+

Apunta el lector óptico a la credencial

- 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.

@@ -184,58 +208,89 @@
- - + +