From 19495e96b43316013abd2164e948fe030cf0c099 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Wed, 28 Oct 2026 14:47:54 -0300 Subject: [PATCH] feat(reception): add multi-serial scanner for up to 4 COM ports and universal Argentine DNI parser (v3.8.52) --- CHANGELOG.md | 21 ++ MEMORY.md | 10 +- backend/app/__init__.py | 2 +- backend/app/services/argentine_dni_parser.py | 166 ++++++++++ backend/app/services/qr_security_service.py | 23 ++ backend/setup.py | 2 +- backend/tests/test_dni_parser.py | 90 ++++++ frontend/package.json | 2 +- frontend/public/js/serial-scanner.js | 273 ++++++++++++----- frontend/src/app.js | 6 +- frontend/views/reception/scanner.html | 285 ++++++++++++++---- .../013-escaner-qr-puerto-com-serial/plan.md | 61 ++-- .../013-escaner-qr-puerto-com-serial/spec.md | 31 +- .../013-escaner-qr-puerto-com-serial/tasks.md | 17 ++ 14 files changed, 806 insertions(+), 183 deletions(-) create mode 100644 backend/app/services/argentine_dni_parser.py create mode 100644 backend/tests/test_dni_parser.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c480e9..cb26a09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,27 @@ 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.52] - 2026-10-28 +### Added & Enhanced (Soporte Multi-Lector de hasta 4 Puertos COM y Reconocimiento Universal de DNI Argentino) +- **Soporte Multi-Lector Serie COM (Hasta 4 Lectores Simultáneos)**: + - Se extendió el motor de lectura serie a la clase `MultiSerialBarcodeScanner` en `frontend/public/js/serial-scanner.js`, administrando 4 ranuras de hardware independientes (`Lector 1 (Paso Principal)`, `Lector 2 (Molinete / Acceso)`, `Lector 3 (Mesa Bedelía)`, `Lector 4 (Auxiliar / Puesto 2)`). + - Cada ranura dispone de control individual de apertura (`requestPort`), configuración de velocidad en baudios (9600 predeterminado / 115200), LED indicador con pulso en vivo (`bg-success`), botón conectar/desconectar y reconexión automática en bloque con `reconnectAuthorizedComPorts()`. + - La interfaz de recepción destaca visualmente la ranura que originó cada escaneo (`flashSlotCard`) y notifica en el badge flotante la terminal emisora (ej: `¡Nuevo Escaneo! Lector 2 (Molinete)`). +- **Módulo de Reconocimiento y Parseo de DNI Argentino (`argentine_dni_parser.py`)**: + - Implementación del algoritmo oficial de extracción y normalización de documentos de identidad argentinos para códigos de barras PDF417 y QR emitidos por Renaper y la App Mi Argentina: + - *Formato 2026*: DNI en posición 3 con ejemplar alfabético (`00749743816"TELLO"CARLOS FACUNDO"34247025"G"...`). + - *Formato 2009 con comilla inicial*: Posición fija de documento, apellido, nombre y sexo (`"20979166 "A"1"CASTIGLIONI"...`). + - *Formato 2009 con prefijos de género antiguos*: Manejo de prefijos `F` / `M` (`"f5592570 "A"1"SAUCEDO"...` ➔ DNI `5592570`). + - *Formato App Mi Argentina*: Con sexo numérico `1=M`, `2=F`, `3=X` y DNI numérico (`305336518"CIRILLI"...` / `680051210"TELLO"...`). + - *Formato 2012*: Sexo en posición 3 y DNI en posición 4 (`00225303383"RIO"MARTINA"F"46585482"...`). + - *Tolerancia de delimitadores*: Compatibilidad idéntica con delimitadores de comilla doble (`"`) y arroba (`@`). +- **Integración Académica en Tiempo Real en `QRSecurityService`**: + - Al escanear un DNI físico o credencial digital Renaper, el backend extrae el número de documento y busca de forma transparente al alumno, docente o bedel en el padrón (`document_number`, `username` o `email`). + - Si el usuario existe, se validan sus permisos y se computan sus clases del día en la sede física. + - Si no existe en la base de datos de UniCABA, el sistema responde informando claramente los datos leídos del documento físico (ej: *"DNI argentino 34247025 (TELLO CARLOS FACUNDO) no se encuentra registrado en el padrón de UniCABA"*). +- **Suite de Pruebas Automatizadas**: + - Se añadieron 9 pruebas unitarias en `backend/tests/test_dni_parser.py` validando todos los formatos y ejemplos provistos, alcanzando 17/17 pruebas superadas en el backend. + ## [3.8.51] - 2026-10-28 ### Added & Improved (Alerta Visual Ámbar sin Clases Hoy e Interacciones de Detección de Nuevo Escaneo en Recepción) - **Diferenciación Cromática por Cursada del Día (`/reception/scanner`)**: diff --git a/MEMORY.md b/MEMORY.md index 6da9cf6..2111c4b 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,12 +9,12 @@ 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: Consola de Recepción Presencial, Alertas de Cursada y Puerto Serie (v3.8.51)**: - - **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. +- **Sprint Activo: Multi-Lector Serial (4 COM) y Reconocimiento de DNI Argentino (v3.8.52)**: + - **Soporte Multi-Lector Serial (Hasta 4 Lectores COM)**: Motor `MultiSerialBarcodeScanner` administrando 4 ranuras independientes (Paso Principal, Molinete, Mesa Bedelía, Auxiliar) con LEDs de conexión, selección de baudios y reconexión automática en bloque vía Web Serial API (`navigator.serial`) en Chromium Windows. + - **Reconocimiento y Parseo de DNI Argentino (`argentine_dni_parser.py`)**: Soporte exhaustivo para escaneo de PDF417 y QR de Renaper / Mi Argentina (Formatos 2009 con/sin comilla, 2012, 2026, prefijos F/M y delimitadores `@` / `"`), resolviendo automáticamente el usuario y sus clases del día por DNI. - **Diferenciación Cromática por Cursada**: Alumnos con cursada hoy se despliegan en verde esmeralda con badge "Tiene Cursada". Alumnos regulares sin clases hoy se destacan en cuadro de advertencia ámbar/amarillo cálido (`#FFFDF5`), badge "Sin Cursada Hoy" y banner explicativo con icono de calendario tachado. - - **Interacciones de Detección de Nuevo Escaneo**: Resplandor dinámico visual en el contenedor (`animate-scan-*`), badge flotante de alerta `¡Nuevo Escaneo Registrado!` y tonos auditivos diferenciados vía Web Audio API (doble agudo para cursada asignada, tono medio suave para regular sin cursada, y grave de alerta para accesos no autorizados). - - **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.51`. + - **Interacciones de Detección de Nuevo Escaneo**: Resplandor dinámico visual en el contenedor (`animate-scan-*`), badge flotante de alerta `¡Nuevo Escaneo Registrado!` y tonos auditivos diferenciados vía Web Audio API. + - **Versión Consolidada**: `v3.8.52`. ## 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 6d04496..b527b6e 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.51" +__version__ = "3.8.52" class DummyContext: def __enter__(self): diff --git a/backend/app/services/argentine_dni_parser.py b/backend/app/services/argentine_dni_parser.py new file mode 100644 index 0000000..ae9683d --- /dev/null +++ b/backend/app/services/argentine_dni_parser.py @@ -0,0 +1,166 @@ +import re +from typing import Tuple, Optional, Dict + + +def limpiar_numero_documento(doc_raw: str) -> Tuple[str, Optional[str]]: + """ + Limpia y normaliza un número de documento DNI argentino. + En formatos antiguos (Libreta Cívica, Libreta de Enrolamiento o Formato 2009), + el documento suele estar precedido por 'F' (Femenino) o 'M' (Masculino), + por ejemplo: 'F5592570' -> ('5592570', 'F'), 'M34247025' -> ('34247025', 'M'). + Retorna (documento_numerico, sexo_inferido). + """ + if not doc_raw: + return "", None + doc_clean = str(doc_raw).strip() + doc_sin_puntos = doc_clean.replace('.', '').replace(',', '').replace(' ', '') + + # Patrón: Prefijo F o M seguido de 5 a 9 dígitos + m = re.match(r'^([FMfm])(\d{5,9})$', doc_sin_puntos) + if m: + return m.group(2), m.group(1).upper() + + # Si contiene dígitos precedidos por F/M con posibles espacios o puntos + m2 = re.match(r'^([FMfm])[\s\.]*(\d{5,9})$', doc_clean) + if m2: + return m2.group(2), m2.group(1).upper() + + return doc_sin_puntos if doc_sin_puntos.isdigit() else doc_clean, None + + +def parsear_dni(raw_text: str) -> Dict[str, str]: + """ + Parsea la cadena de texto cruda obtenida de un escáner de código de barras/QR de un DNI argentino. + Soporta los formatos 2009, 2012, 2026 y App Mi Argentina. + + Retorna un diccionario con las llaves: 'documento', 'apellido', 'nombre', 'sexo' + o un diccionario vacío si no corresponde a un documento de identidad argentino. + """ + if not raw_text: + return {} + + # Limpiar terminadores y retornos de carro + raw_clean = str(raw_text).strip().replace('\r', '').replace('\n', '') + + # Algunos escáneres o formatos vienen separados por @ en lugar de comillas dobles + text = raw_clean.replace('@', '"') + parts = text.split('"') + + # Limpiar espacios de cada segmento + parts = [p.strip() for p in parts] + + if len(parts) < 5: + # Si es un ingreso directo de DNI (escaneado de tarjeta de código de barras 1D o tipeado) + doc_limpio, sexo_inf = limpiar_numero_documento(raw_clean) + if doc_limpio and doc_limpio.isdigit() and 5 <= len(doc_limpio) <= 9: + return { + "documento": doc_limpio, + "apellido": "", + "nombre": "", + "sexo": sexo_inf or "M" + } + return {} + + doc = nombre = apellido = sexo = "" + + # Heurística para Formato 2009 con comilla inicial + # Ej: "34247025"A"1"TELLO"CARLOS FACUNDO"... + # Ej: "F5592570 "A"1"SAUCEDO"TERESA DE JESUS"... + if parts[0] == '' and 6 <= len(parts[1]) <= 11 and len(parts) > 2 and parts[2].isalpha() and len(parts[2]) == 1: + doc = parts[1] + if len(parts) > 4: + apellido = parts[4] + if len(parts) > 5: + nombre = parts[5] + # Búsqueda de sexo en posiciones subsiguientes (índices 6 a 9) + for idx in range(6, min(len(parts), 10)): + val = parts[idx].upper() + if val in ("M", "F", "X"): + sexo = val + break + + # Heurística para Formato 2009 sin comilla inicial + # Ej: 34247025"A"1"TELLO"CARLOS FACUNDO... + # Ej: F5592570"A"1"SAUCEDO"TERESA DE JESUS... + elif 6 <= len(parts[0]) <= 11 and len(parts) > 4 and parts[1].isalpha() and len(parts[1]) == 1: + doc = parts[0] + apellido = parts[3] + nombre = parts[4] + for idx in range(5, min(len(parts), 9)): + val = parts[idx].upper() + if val in ("M", "F", "X"): + sexo = val + break + + # Heurística para Formatos 2012, 2026 y App Mi Argentina (Comienzan con número de trámite >= 8 dígitos) + else: + # Si la cadena comenzó con comilla/arroba y no es formato 2009, normalizamos descartando el elemento vacío inicial + if parts[0] == '' and len(parts) > 1: + parts = parts[1:] + + if parts[0].isdigit() and len(parts[0]) >= 8: + apellido = parts[1] if len(parts) > 1 else "" + nombre = parts[2] if len(parts) > 2 else "" + + if len(parts) > 3: + p3 = parts[3].strip() + p4 = parts[4].strip() if len(parts) > 4 else "" + + # Caso 1: Formato 2012 (parts[3] es letra de sexo M, F, X) + # 00680051210"TELLO"CARLOS FACUNDO"M"34247025... + if len(p3) == 1 and p3.upper() in ("M", "F", "X"): + sexo = p3.upper() + if len(parts) > 4: + doc = p4 + + # Caso 2: Formato App Mi Argentina (parts[3] es código numérico de sexo 1=M, 2=F, 3=X) + # y parts[4] es el DNI numérico (6 a 9 dígitos) + # Ej: 00305336518@CIRILLI@GEORGINA SUSANA@2@28988082@A@23/08/1981@13/10/2014 + # Ej: 00680051210@TELLO@Carlos Facundo@1@34247025@F@09/02/1989@13/10/2021 + elif p3 in ("1", "2", "3", "0") and p4.isdigit() and 6 <= len(p4) <= 9: + if p3 == "1": + sexo = "M" + elif p3 == "2": + sexo = "F" + else: + sexo = "X" + doc = p4 + + # Caso 3: Formato 2026 (parts[3] es directamente el DNI de 6 a 9 dígitos) + # y parts[4] suele ser ejemplar o sexo alfabético (ej. 'G', 'F', 'M') + # 00749743816"TELLO"CARLOS FACUNDO"34247025"G... + elif p3.isdigit() and 6 <= len(p3) <= 9 and not (p4.isdigit() and 6 <= len(p4) <= 9): + doc = p3 + if p4.upper() in ("M", "F", "X"): + sexo = p4.upper() + elif p4.upper() == "G": + sexo = "M" + + # Caso 4: Desempate general: si parts[4] es un DNI numérico válido de 6 a 9 dígitos + elif p4.isdigit() and 6 <= len(p4) <= 9: + doc = p4 + if p3 == "1": + sexo = "M" + elif p3 == "2": + sexo = "F" + elif p3.upper() in ("M", "F", "X"): + sexo = p3.upper() + else: + # Fallback final + doc = p3 + + # Normalización del documento extraído (eliminación de prefijos F/M en DNI viejo) + doc_limpio, sexo_doc = limpiar_numero_documento(doc) + doc = doc_limpio + if not sexo and sexo_doc: + sexo = sexo_doc + + if not doc or not doc.isdigit() or not (5 <= len(doc) <= 9): + return {} + + return { + "documento": doc.strip(), + "apellido": apellido.upper() if apellido else "", + "nombre": nombre.upper() if nombre else "", + "sexo": sexo or "M" + } diff --git a/backend/app/services/qr_security_service.py b/backend/app/services/qr_security_service.py index 2ff77b6..ad72746 100644 --- a/backend/app/services/qr_security_service.py +++ b/backend/app/services/qr_security_service.py @@ -17,6 +17,7 @@ from app.models.building import Building from app.models.enrollment import StudentEnrollment from app.models.subject import Commission, Subject from schemas.reception_dto import TodayClassDTO +from app.services.argentine_dni_parser import parsear_dni class QRSecurityService: @@ -134,6 +135,28 @@ class QRSecurityService: return user_by_dni, "RESTRINGIDO", "Usuario inactivo en el sistema institucional." return user_by_dni, "AUTORIZADO", f"Identificación validada por documento de identidad (DNI {doc})." + # C. Reconocimiento universal de DNI Argentino (Formatos Renaper 2009, 2012, 2026, Mi Argentina y PDF417 / QR) + dni_info = parsear_dni(clean_normalized) + if dni_info and dni_info.get("documento"): + doc = dni_info["documento"] + user_by_dni = User.query.filter_by(document_number=doc).first() + if not user_by_dni: + user_by_dni = User.query.filter( + (User.username == doc) | (User.email.like(f"{doc}@%")) + ).first() + + if user_by_dni: + if not user_by_dni.is_active: + return user_by_dni, "RESTRINGIDO", f"Usuario inactivo en el sistema institucional (DNI {doc})." + nombre_display = f"{dni_info.get('apellido', '')} {dni_info.get('nombre', '')}".strip() + detalle = f"Identificación validada por DNI argentino {doc}" + (f" ({nombre_display})" if nombre_display else "") + return user_by_dni, "AUTORIZADO", detalle + else: + nombre_display = f"{dni_info.get('apellido', '')} {dni_info.get('nombre', '')}".strip() + if nombre_display: + return None, "DENEGADO", f"DNI argentino {doc} ({nombre_display}) no se encuentra registrado en el padrón de UniCABA." + return None, "DENEGADO", f"DNI argentino {doc} no se encuentra registrado en el padrón de UniCABA." + # D. Fallback: Lectura de pistola óptica o documento directo (ej: 'DNI:12345678' o '12345678') doc_num = clean_normalized if doc_num.upper().startswith("DNI:"): diff --git a/backend/setup.py b/backend/setup.py index ab567a5..e7a9d46 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.51", + version="3.8.52", 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/backend/tests/test_dni_parser.py b/backend/tests/test_dni_parser.py new file mode 100644 index 0000000..3c7cd99 --- /dev/null +++ b/backend/tests/test_dni_parser.py @@ -0,0 +1,90 @@ +import pytest +from app.services.argentine_dni_parser import parsear_dni, limpiar_numero_documento + + +def test_limpiar_numero_documento_variations(): + assert limpiar_numero_documento("F5592570") == ("5592570", "F") + assert limpiar_numero_documento("M34247025") == ("34247025", "M") + assert limpiar_numero_documento("f 5592570") == ("5592570", "F") + assert limpiar_numero_documento("34.247.025") == ("34247025", None) + assert limpiar_numero_documento("34247025") == ("34247025", None) + + +def test_parsear_dni_ejemplo_1_formato_2026(): + raw = '00749743816"TELLO"CARLOS FACUNDO"34247025"G"09-02-89"23-04-26"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZF90cmFtaXRlIjoiNzQ5NzQzODE2In0.1JThZ0G' + parsed = parsear_dni(raw) + assert parsed["documento"] == "34247025" + assert parsed["apellido"] == "TELLO" + assert parsed["nombre"] == "CARLOS FACUNDO" + assert parsed["sexo"] in ("M", "G") + + +def test_parsear_dni_ejemplo_2_formato_2009_con_comillas(): + raw = '"20979166 "A"1"CASTIGLIONI"MARCELA ANALIA"ARGENTINA"20-07-1969"F"28-02-2011"00040202308"7006 "28-02-2026"296"0"ILRÑ2.01 CÑ110223.01' + parsed = parsear_dni(raw) + assert parsed["documento"] == "20979166" + assert parsed["apellido"] == "CASTIGLIONI" + assert parsed["nombre"] == "MARCELA ANALIA" + assert parsed["sexo"] == "F" + + +def test_parsear_dni_ejemplo_3_formato_mi_argentina_1(): + raw = '305336518"CIRILLI"GEORGINA SUSANA"2"28988082"A"23-08-1981"13-10-2014' + parsed = parsear_dni(raw) + assert parsed["documento"] == "28988082" + assert parsed["apellido"] == "CIRILLI" + assert parsed["nombre"] == "GEORGINA SUSANA" + assert parsed["sexo"] == "F" + + +def test_parsear_dni_ejemplo_4_formato_2012(): + raw = '00225303383"RIO"MARTINA"F"46585482"A"02-09-2005"19-10-2013' + parsed = parsear_dni(raw) + assert parsed["documento"] == "46585482" + assert parsed["apellido"] == "RIO" + assert parsed["nombre"] == "MARTINA" + assert parsed["sexo"] == "F" + + +def test_parsear_dni_ejemplo_5_formato_2009_con_f(): + raw = '"f5592570 "A"1"SAUCEDO"TERESA DE JESUS"ARGENTINA"16-02-1947"F"21-01-2012"00090833406"7020 "21-01-2027"206"0"' + parsed = parsear_dni(raw) + assert parsed["documento"] == "5592570" + assert parsed["apellido"] == "SAUCEDO" + assert parsed["nombre"] == "TERESA DE JESUS" + assert parsed["sexo"] == "F" + + +def test_parsear_dni_ejemplo_6_formato_mi_argentina_2(): + raw = '680051210"TELLO"Carlos Facundo"1"34247025"F"09-02-1989"13-10-2021' + parsed = parsear_dni(raw) + assert parsed["documento"] == "34247025" + assert parsed["apellido"] == "TELLO" + assert parsed["nombre"] == "CARLOS FACUNDO" + assert parsed["sexo"] == "M" + + +def test_parsear_dni_con_separadores_arroba(): + raw = '00305336518@CIRILLI@GEORGINA SUSANA@2@28988082@A@23/08/1981@13/10/2014' + parsed = parsear_dni(raw) + assert parsed["documento"] == "28988082" + assert parsed["apellido"] == "CIRILLI" + assert parsed["nombre"] == "GEORGINA SUSANA" + assert parsed["sexo"] == "F" + + +def test_parsear_dni_directo_o_invalido(): + assert parsear_dni("34247025") == { + "documento": "34247025", + "apellido": "", + "nombre": "", + "sexo": "M" + } + assert parsear_dni("F5592570") == { + "documento": "5592570", + "apellido": "", + "nombre": "", + "sexo": "F" + } + assert parsear_dni("") == {} + assert parsear_dni("TEXTO_CORTO") == {} diff --git a/frontend/package.json b/frontend/package.json index e13e40c..0e1d5ce 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.8.51", + "version": "3.8.52", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/public/js/serial-scanner.js b/frontend/public/js/serial-scanner.js index 375b348..95fdec0 100644 --- a/frontend/public/js/serial-scanner.js +++ b/frontend/public/js/serial-scanner.js @@ -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); diff --git a/frontend/src/app.js b/frontend/src/app.js index 6f68629..42ac559 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.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); diff --git a/frontend/views/reception/scanner.html b/frontend/views/reception/scanner.html index 916fc8c..9f3ba34 100644 --- a/frontend/views/reception/scanner.html +++ b/frontend/views/reception/scanner.html @@ -76,23 +76,119 @@ - +
- Puerto Serie (COM) - - - Puerto USB-HID Activo + Lectores Serie COM (Hasta 4) +
+ + 0 / 4 Activos + + +
-
- - Dispositivos Seriales COM (Windows / Chromium) - - + + +
+ +
+
+
+
+ +
+
Lector 1 (Paso Principal)
+
Sin conectar
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ +
+
Lector 2 (Molinete / Acceso)
+
Sin conectar
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ +
+
Lector 3 (Mesa Bedelía)
+
Sin conectar
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ +
+
Lector 4 (Auxiliar / Puesto 2)
+
Sin conectar
+
+
+
+ + +
+
+
+
@@ -218,87 +314,132 @@