fix(hardware-camera): resolucion de modulos virtuales a fisicos para WPC y escaneo robusto de webcam
This commit is contained in:
@@ -46,32 +46,51 @@ class HardwareService:
|
|||||||
def encolar_apertura(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
|
def encolar_apertura(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Encola un comando de apertura de barrera/molinete en la tabla `pdtmdl`
|
Encola un comando de apertura de barrera/molinete en la tabla `pdtmdl`
|
||||||
para que OnEverWPC lo despache al bus RS-485 físico en < 50ms.
|
para que OnEverWPC lo despache al bus RS-485 físico de inmediato.
|
||||||
|
Resuelve automáticamente módulos virtuales (98, 97) hacia sus placas físicas (20, 21).
|
||||||
"""
|
"""
|
||||||
t_start = time.perf_counter()
|
t_start = time.perf_counter()
|
||||||
mdl = cls.obtener_info_modulo(modulo_id)
|
mdl = cls.obtener_info_modulo(modulo_id)
|
||||||
if not mdl:
|
if not mdl:
|
||||||
return False, {"error": f"Módulo {modulo_id} no encontrado en base de datos"}
|
return False, {"error": f"Módulo {modulo_id} no encontrado en base de datos"}
|
||||||
|
|
||||||
address = mdl.get("Address", 1)
|
# 1. Obtener categorías de MdlCatVal para verificar si es Módulo Virtual (Cat 2 = 6) y Sentido (Cat 4)
|
||||||
duracion = mdl.get("duracion_pulso") or 500
|
cat_map = {}
|
||||||
|
|
||||||
# Verificamos si es variante PASS (Access) o PARK (Default)
|
|
||||||
is_pass = False
|
|
||||||
try:
|
try:
|
||||||
with db_session() as conn:
|
with db_session() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"SELECT ValorID FROM MdlCatVal WHERE ModuloID = %s AND CategoriaID = 2",
|
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
|
||||||
(modulo_id,),
|
(modulo_id,),
|
||||||
)
|
)
|
||||||
row = cursor.fetchone()
|
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
|
||||||
is_pass = (row is not None and int(row[0]) == 1)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
is_pass = False
|
pass
|
||||||
|
|
||||||
# Determinación del payload de pulso según protocolo
|
tipo_modulo_id = cat_map.get(2, 0)
|
||||||
payload = "V3" if is_pass else "O3"
|
sentido_id = cat_map.get(4, 0)
|
||||||
|
nombre_upper = (mdl.get("Nombre") or "").upper()
|
||||||
|
|
||||||
|
# 2. Si es Módulo Virtual (tipo 6 o dirección virtual >= 90), resolver el módulo físico real
|
||||||
|
target_id = modulo_id
|
||||||
|
target_mdl = mdl
|
||||||
|
|
||||||
|
if tipo_modulo_id == 6 or mdl.get("Address", 0) >= 90:
|
||||||
|
if (sentido_id == 1 or "ENTRADA" in nombre_upper or "INGRESO" in nombre_upper) and mdl.get("ModuloEntradaID"):
|
||||||
|
target_id = mdl["ModuloEntradaID"]
|
||||||
|
elif (sentido_id == 2 or "SALIDA" in nombre_upper or "EGRESO" in nombre_upper) and mdl.get("ModuloSalidaID"):
|
||||||
|
target_id = mdl["ModuloSalidaID"]
|
||||||
|
|
||||||
|
if target_id != modulo_id:
|
||||||
|
fisico = cls.obtener_info_modulo(target_id)
|
||||||
|
if fisico:
|
||||||
|
target_mdl = fisico
|
||||||
|
|
||||||
|
address = target_mdl.get("Address", 1)
|
||||||
|
duracion = target_mdl.get("duracion_pulso") or 500
|
||||||
|
|
||||||
|
# 3. Comando universal de apertura por pulso de barrera (O3)
|
||||||
|
payload = "O3"
|
||||||
trama_comando = formatear_comando_hardware(address, payload)
|
trama_comando = formatear_comando_hardware(address, payload)
|
||||||
|
|
||||||
sql_insert = """
|
sql_insert = """
|
||||||
@@ -82,13 +101,23 @@ class HardwareService:
|
|||||||
|
|
||||||
with db_session() as conn:
|
with db_session() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
|
# Encolar para la placa física real (ej: Modulo 100009 con Addr 20 o Modulo 100013 con Addr 21)
|
||||||
|
cursor.execute(sql_insert, (target_id, trama_comando, extra_info))
|
||||||
|
|
||||||
|
# Si el módulo llamado era virtual, encolar también una entrada con el ID virtual
|
||||||
|
# pero con la trama física, garantizando compatibilidad con cualquier hilo de sondeo
|
||||||
|
if target_id != modulo_id:
|
||||||
|
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
|
||||||
|
|
||||||
latencia = (time.perf_counter() - t_start) * 1000
|
latencia = (time.perf_counter() - t_start) * 1000
|
||||||
|
|
||||||
return True, {
|
return True, {
|
||||||
"modulo_id": modulo_id,
|
"modulo_id": modulo_id,
|
||||||
|
"modulo_solicitado": modulo_id,
|
||||||
|
"modulo_fisico_target": target_id,
|
||||||
"address": address,
|
"address": address,
|
||||||
|
"address_fisico": address,
|
||||||
"payload": payload,
|
"payload": payload,
|
||||||
|
"comando_trama": trama_comando,
|
||||||
"latencia_ms": round(latencia, 2),
|
"latencia_ms": round(latencia, 2),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
// ==============================================================================
|
// ==============================================================================
|
||||||
// Modal de Escaneo Óptico con Cámara para Tablets (Android) y Windows
|
// Modal de Escaneo Óptico con Cámara para Tablets (Android) y Windows
|
||||||
// Soporte de Video en Vivo (WebRTC) + ZXing Library (PDF417 / QR) + Captura de Foto Nativa
|
// Soporte de Video en Vivo (WebRTC) + ZXing Core Engine (PDF417 / QR) + Captura Nativa
|
||||||
// Cumple con el sistema de diseño OnEver (C:\Workspace\OemspotPySYS\styles\design_system.py)
|
// Cumple con el sistema de diseño OnEver (C:\Workspace\OemspotPySYS\styles\design_system.py)
|
||||||
// ==============================================================================
|
// ==============================================================================
|
||||||
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||||
import { BrowserMultiFormatReader, BarcodeFormat, DecodeHintType } from '@zxing/library';
|
import {
|
||||||
|
MultiFormatReader,
|
||||||
|
BarcodeFormat,
|
||||||
|
DecodeHintType,
|
||||||
|
RGBLuminanceSource,
|
||||||
|
BinaryBitmap,
|
||||||
|
HybridBinarizer,
|
||||||
|
} from '@zxing/library';
|
||||||
import { accessApi } from '../../api/accessApi';
|
import { accessApi } from '../../api/accessApi';
|
||||||
import { DNIParsedResult } from '../../types';
|
import { DNIParsedResult } from '../../types';
|
||||||
|
|
||||||
@@ -21,8 +28,10 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||||
const streamRef = useRef<MediaStream | null>(null);
|
const streamRef = useRef<MediaStream | null>(null);
|
||||||
const zxingReaderRef = useRef<BrowserMultiFormatReader | null>(null);
|
|
||||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
const timerRef = useRef<number | null>(null);
|
||||||
|
const zxingReaderRef = useRef<MultiFormatReader | null>(null);
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||||
|
|
||||||
const [hasCamera, setHasCamera] = useState<boolean>(true);
|
const [hasCamera, setHasCamera] = useState<boolean>(true);
|
||||||
const [insecureContextWarning, setInsecureContextWarning] = useState<boolean>(false);
|
const [insecureContextWarning, setInsecureContextWarning] = useState<boolean>(false);
|
||||||
@@ -33,8 +42,9 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
const [manualText, setManualText] = useState<string>('');
|
const [manualText, setManualText] = useState<string>('');
|
||||||
const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]);
|
const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]);
|
||||||
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
|
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
|
||||||
|
const [activeCameraLabel, setActiveCameraLabel] = useState<string>('');
|
||||||
|
|
||||||
// Inicializar lector ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
|
// Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const hints = new Map();
|
const hints = new Map();
|
||||||
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
|
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
|
||||||
@@ -44,33 +54,26 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
]);
|
]);
|
||||||
hints.set(DecodeHintType.TRY_HARDER, true);
|
hints.set(DecodeHintType.TRY_HARDER, true);
|
||||||
|
|
||||||
zxingReaderRef.current = new BrowserMultiFormatReader(hints, 250);
|
const reader = new MultiFormatReader();
|
||||||
|
reader.setHints(hints);
|
||||||
|
zxingReaderRef.current = reader;
|
||||||
|
|
||||||
return () => {
|
// Crear canvas offscreen reutilizable
|
||||||
if (zxingReaderRef.current) {
|
const offscreenCanvas = document.createElement('canvas');
|
||||||
try {
|
canvasRef.current = offscreenCanvas;
|
||||||
zxingReaderRef.current.reset();
|
|
||||||
} catch {
|
|
||||||
// Cleanup
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const stopCamera = useCallback(() => {
|
const stopCamera = useCallback(() => {
|
||||||
if (zxingReaderRef.current) {
|
if (timerRef.current) {
|
||||||
try {
|
window.clearInterval(timerRef.current);
|
||||||
zxingReaderRef.current.reset();
|
timerRef.current = null;
|
||||||
} catch {
|
|
||||||
// Ignorar
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (streamRef.current) {
|
if (streamRef.current) {
|
||||||
streamRef.current.getTracks().forEach((track) => {
|
streamRef.current.getTracks().forEach((track) => {
|
||||||
try {
|
try {
|
||||||
track.stop();
|
track.stop();
|
||||||
} catch {
|
} catch {
|
||||||
// Ignorar
|
// Cleanup seguro
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
streamRef.current = null;
|
streamRef.current = null;
|
||||||
@@ -92,7 +95,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
onScanSuccess(res);
|
onScanSuccess(res);
|
||||||
onClose();
|
onClose();
|
||||||
} else {
|
} else {
|
||||||
setErrorMsg(`Código detectado pero no es un DNI argentino válido (${rawText.slice(0, 30)}...).`);
|
setErrorMsg(`Código detectado pero no corresponde a un DNI argentino válido (${rawText.slice(0, 30)}...).`);
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
|
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
|
||||||
@@ -103,110 +106,163 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
[isProcessing, stopCamera, onScanSuccess, onClose]
|
[isProcessing, stopCamera, onScanSuccess, onClose]
|
||||||
);
|
);
|
||||||
|
|
||||||
const startCamera = useCallback(async (deviceIdToUse?: string) => {
|
// Decodificar un buffer ImageData mediante ZXing y BarcodeDetector
|
||||||
setErrorMsg(null);
|
const decodeFrame = useCallback(
|
||||||
setHasCamera(true);
|
async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise<boolean> => {
|
||||||
|
// 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU)
|
||||||
// Verificar si el navegador permite acceso a mediaDevices
|
if ('BarcodeDetector' in window) {
|
||||||
const isSecure = window.isSecureContext || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
|
try {
|
||||||
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
const detector = new (window as any).BarcodeDetector({
|
||||||
setHasCamera(false);
|
formats: ['pdf417', 'qr_code', 'code_128'],
|
||||||
if (!isSecure) {
|
});
|
||||||
setInsecureContextWarning(true);
|
const barcodes = await detector.detect(ctx.canvas);
|
||||||
setErrorMsg(
|
if (barcodes.length > 0 && barcodes[0].rawValue) {
|
||||||
'El navegador bloqueó la cámara porque la conexión es HTTP sobre red local. Utilice el botón "📷 Tomar Foto con Cámara" para escanear sin restricciones de seguridad.'
|
handleDecodedString(barcodes[0].rawValue);
|
||||||
);
|
return true;
|
||||||
} else {
|
}
|
||||||
setErrorMsg('Dispositivo de video no soportado o bloqueado por el sistema operativo.');
|
} catch {
|
||||||
}
|
// Continuar con ZXing como motor primario
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. Obtener lista de cámaras disponibles si es posible
|
|
||||||
try {
|
|
||||||
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
||||||
const videoDevices = devices.filter((d) => d.kind === 'videoinput');
|
|
||||||
setAvailableDevices(videoDevices);
|
|
||||||
} catch {
|
|
||||||
// En algunos navegadores enumerateDevices requiere haber abierto stream previo
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Definir constraints (con fallback para Windows laptop vs Android tablet)
|
// 2. Probar decodificador ZXing sobre los píxeles directos
|
||||||
let stream: MediaStream | null = null;
|
if (zxingReaderRef.current) {
|
||||||
|
try {
|
||||||
|
const imgData = ctx.getImageData(0, 0, width, height);
|
||||||
|
const luminanceSource = new RGBLuminanceSource(imgData.data, width, height);
|
||||||
|
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
|
||||||
|
const result = zxingReaderRef.current.decode(binaryBitmap);
|
||||||
|
if (result && result.getText()) {
|
||||||
|
handleDecodedString(result.getText());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// NotFoundException en cada frame sin código
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
[handleDecodedString]
|
||||||
|
);
|
||||||
|
|
||||||
|
const startCamera = useCallback(
|
||||||
|
async (deviceIdToUse?: string) => {
|
||||||
|
setErrorMsg(null);
|
||||||
|
setHasCamera(true);
|
||||||
|
|
||||||
|
const isSecure =
|
||||||
|
window.isSecureContext ||
|
||||||
|
window.location.hostname === 'localhost' ||
|
||||||
|
window.location.hostname === '127.0.0.1';
|
||||||
|
|
||||||
|
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
||||||
|
setHasCamera(false);
|
||||||
|
if (!isSecure) {
|
||||||
|
setInsecureContextWarning(true);
|
||||||
|
setErrorMsg(
|
||||||
|
'El navegador bloqueó la cámara en vivo porque la conexión es HTTP sobre red local. Utilice el botón "📸 Capturar Foto de DNI" o ingrese por HTTPS en el puerto 8443.'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setErrorMsg('Dispositivo de video no soportado o bloqueado en este sistema.');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Intento 1: Cámara trasera de tablet / dispositivo específico
|
let stream: MediaStream | null = null;
|
||||||
const videoConstraints: MediaTrackConstraints = deviceIdToUse
|
|
||||||
? { deviceId: { exact: deviceIdToUse } }
|
// Estrategia de Constraints flexible:
|
||||||
|
// Intento 1: Dispositivo seleccionado o cámara trasera
|
||||||
|
const constraints1: MediaStreamConstraints = deviceIdToUse
|
||||||
|
? { video: { deviceId: { exact: deviceIdToUse } }, audio: false }
|
||||||
: {
|
: {
|
||||||
facingMode: { ideal: 'environment' },
|
video: {
|
||||||
width: { ideal: 1280 },
|
facingMode: { ideal: 'environment' },
|
||||||
height: { ideal: 720 },
|
width: { ideal: 1280 },
|
||||||
|
height: { ideal: 720 },
|
||||||
|
},
|
||||||
|
audio: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
stream = await navigator.mediaDevices.getUserMedia({
|
|
||||||
video: videoConstraints,
|
|
||||||
audio: false,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Intento 2: Fallback simple para webcam de PC Windows o cámara estándar
|
|
||||||
try {
|
try {
|
||||||
|
stream = await navigator.mediaDevices.getUserMedia(constraints1);
|
||||||
|
} catch {
|
||||||
|
// Intento 2: Fallback incondicional para webcams Windows / laptop estándar
|
||||||
stream = await navigator.mediaDevices.getUserMedia({
|
stream = await navigator.mediaDevices.getUserMedia({
|
||||||
video: true,
|
video: true,
|
||||||
audio: false,
|
audio: false,
|
||||||
});
|
});
|
||||||
} catch (innerErr: any) {
|
}
|
||||||
throw innerErr;
|
|
||||||
|
if (!stream) {
|
||||||
|
throw new Error('No se pudo obtener el flujo de video.');
|
||||||
|
}
|
||||||
|
|
||||||
|
streamRef.current = stream;
|
||||||
|
|
||||||
|
// Identificar etiqueta de la cámara activa
|
||||||
|
const videoTrack = stream.getVideoTracks()[0];
|
||||||
|
if (videoTrack) {
|
||||||
|
setActiveCameraLabel(videoTrack.label || 'Cámara activa');
|
||||||
|
const capabilities = videoTrack.getCapabilities?.() as any;
|
||||||
|
if (capabilities && capabilities.torch) {
|
||||||
|
setSupportsTorch(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enumerar dispositivos disponibles (ahora con permisos ya otorgados)
|
||||||
|
try {
|
||||||
|
const allDevices = await navigator.mediaDevices.enumerateDevices();
|
||||||
|
const vInputs = allDevices.filter((d) => d.kind === 'videoinput');
|
||||||
|
setAvailableDevices(vInputs);
|
||||||
|
} catch {
|
||||||
|
// Ignorar si falla enumeración
|
||||||
|
}
|
||||||
|
|
||||||
|
if (videoRef.current) {
|
||||||
|
videoRef.current.srcObject = stream;
|
||||||
|
videoRef.current.onloadedmetadata = () => {
|
||||||
|
videoRef.current?.play().catch(() => {});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iniciar loop de escaneo periódico cada 200ms
|
||||||
|
if (timerRef.current) window.clearInterval(timerRef.current);
|
||||||
|
timerRef.current = window.setInterval(async () => {
|
||||||
|
if (!videoRef.current || videoRef.current.readyState < 2 || isProcessing) return;
|
||||||
|
|
||||||
|
const video = videoRef.current;
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
if (!canvas) return;
|
||||||
|
|
||||||
|
const width = video.videoWidth || 640;
|
||||||
|
const height = video.videoHeight || 480;
|
||||||
|
|
||||||
|
canvas.width = width;
|
||||||
|
canvas.height = height;
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
|
if (!ctx) return;
|
||||||
|
|
||||||
|
ctx.drawImage(video, 0, 0, width, height);
|
||||||
|
await decodeFrame(ctx, width, height);
|
||||||
|
}, 200);
|
||||||
|
} catch (err: any) {
|
||||||
|
setHasCamera(false);
|
||||||
|
const name = err.name || '';
|
||||||
|
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
|
||||||
|
setErrorMsg('Permiso de cámara denegado. Permita el acceso en el candado del navegador.');
|
||||||
|
} else if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
|
||||||
|
setErrorMsg('No se detectó ninguna cámara web conectada al equipo.');
|
||||||
|
} else if (name === 'NotReadableError') {
|
||||||
|
setErrorMsg('La cámara está siendo usada por otra aplicación en Windows.');
|
||||||
|
} else {
|
||||||
|
setErrorMsg(`Error al iniciar cámara: ${err.message || 'Error desconocido'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
if (!stream) {
|
[decodeFrame, isProcessing]
|
||||||
throw new Error('No se pudo inicializar el flujo de video.');
|
);
|
||||||
}
|
|
||||||
|
|
||||||
streamRef.current = stream;
|
|
||||||
|
|
||||||
if (videoRef.current) {
|
|
||||||
videoRef.current.srcObject = stream;
|
|
||||||
await videoRef.current.play();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Detectar soporte para linterna (torch)
|
|
||||||
const track = stream.getVideoTracks()[0];
|
|
||||||
const capabilities = track.getCapabilities?.() as any;
|
|
||||||
if (capabilities && capabilities.torch) {
|
|
||||||
setSupportsTorch(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Iniciar decodificación continua con ZXing sobre el elemento video
|
|
||||||
if (zxingReaderRef.current && videoRef.current) {
|
|
||||||
zxingReaderRef.current.decodeFromVideoElementContinuously(
|
|
||||||
videoRef.current,
|
|
||||||
(result: any) => {
|
|
||||||
if (result) {
|
|
||||||
const text = result.getText?.() || result.text;
|
|
||||||
if (text) {
|
|
||||||
handleDecodedString(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
setHasCamera(false);
|
|
||||||
const name = err.name || '';
|
|
||||||
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
|
|
||||||
setErrorMsg('Permiso de cámara denegado. Habilite el acceso en la barra del navegador.');
|
|
||||||
} else if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
|
|
||||||
setErrorMsg('No se detectó ninguna cámara conectada al dispositivo.');
|
|
||||||
} else if (name === 'NotReadableError') {
|
|
||||||
setErrorMsg('La cámara está siendo usada por otra aplicación en Windows.');
|
|
||||||
} else {
|
|
||||||
setErrorMsg(`No se pudo iniciar la cámara: ${err.message || 'Error desconocido'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [handleDecodedString]);
|
|
||||||
|
|
||||||
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
|
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
|
||||||
const handlePhotoCaptured = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handlePhotoCaptured = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
@@ -225,30 +281,31 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crear imagen temporal para decodificar con ZXing
|
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
img.src = dataUrl;
|
img.src = dataUrl;
|
||||||
img.onload = async () => {
|
img.onload = async () => {
|
||||||
try {
|
const canvas = canvasRef.current || document.createElement('canvas');
|
||||||
if (zxingReaderRef.current) {
|
canvas.width = img.width;
|
||||||
const result = await zxingReaderRef.current.decodeFromImageElement(img);
|
canvas.height = img.height;
|
||||||
if (result && result.getText()) {
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
handleDecodedString(result.getText());
|
if (!ctx) {
|
||||||
return;
|
setIsProcessing(false);
|
||||||
}
|
return;
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ZXing no pudo decodificar directo; intentar OCR / backend fallback
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si el código no fue legible directo de la foto, avisar al usuario
|
ctx.drawImage(img, 0, 0, img.width, img.height);
|
||||||
setErrorMsg('No se pudo detectar el código de barras en la foto. Intente con mejor iluminación o acerque el código.');
|
const detected = await decodeFrame(ctx, img.width, img.height);
|
||||||
setIsProcessing(false);
|
if (!detected) {
|
||||||
|
setErrorMsg(
|
||||||
|
'No se detectó el código de barras en la foto. Acerque el DNI con buena iluminación o ingréselo manualmente.'
|
||||||
|
);
|
||||||
|
setIsProcessing(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
reader.readAsDataURL(file);
|
reader.readAsDataURL(file);
|
||||||
} catch (err: any) {
|
} catch {
|
||||||
setErrorMsg('Error al procesar la imagen capturada.');
|
setErrorMsg('Error al procesar la imagen seleccionada.');
|
||||||
setIsProcessing(false);
|
setIsProcessing(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -275,7 +332,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
});
|
});
|
||||||
setTorchEnabled(nextState);
|
setTorchEnabled(nextState);
|
||||||
} catch {
|
} catch {
|
||||||
// Ignorar si el dispositivo rechaza el comando
|
// Ignorar si el dispositivo no soporta linterna
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -310,7 +367,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
className="card"
|
className="card"
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
maxWidth: '620px',
|
maxWidth: '640px',
|
||||||
backgroundColor: 'var(--bg-sidebar)',
|
backgroundColor: 'var(--bg-sidebar)',
|
||||||
borderRadius: '10px',
|
borderRadius: '10px',
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
@@ -332,13 +389,13 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
|
||||||
<span style={{ fontSize: '1.3rem' }}>📷</span>
|
<span style={{ fontSize: '1.4rem' }}>📷</span>
|
||||||
<div>
|
<div>
|
||||||
<h2 style={{ fontSize: '1.05rem', fontWeight: 700, margin: 0, color: 'var(--text-1)' }}>
|
<h2 style={{ fontSize: '1.1rem', fontWeight: 700, margin: 0, color: 'var(--text-1)' }}>
|
||||||
Escanear DNI Argentino (Cámara / PDF417)
|
Escanear DNI Argentino (Cámara / PDF417)
|
||||||
</h2>
|
</h2>
|
||||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>
|
||||||
Soporta DNI tarjeta, PDF417, QR digital y fotos nativas
|
{activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Soporta DNI tarjeta, PDF417, QR digital y fotos'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -366,7 +423,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
style={{
|
style={{
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '310px',
|
height: '320px',
|
||||||
backgroundColor: '#000',
|
backgroundColor: '#000',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
@@ -378,6 +435,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
<>
|
<>
|
||||||
<video
|
<video
|
||||||
ref={videoRef}
|
ref={videoRef}
|
||||||
|
autoPlay
|
||||||
playsInline
|
playsInline
|
||||||
muted
|
muted
|
||||||
style={{
|
style={{
|
||||||
@@ -411,18 +469,18 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
border: '1px solid var(--border)',
|
border: '1px solid var(--border)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Ubique el código PDF417 o QR aquí
|
Ubique el código de barras PDF417 o QR aquí
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-2)', maxWidth: '480px' }}>
|
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-2)', maxWidth: '480px' }}>
|
||||||
<div style={{ fontSize: '2.5rem', marginBottom: '0.75rem' }}>📷</div>
|
<div style={{ fontSize: '2.5rem', marginBottom: '0.75rem' }}>📷</div>
|
||||||
<p style={{ fontWeight: 600, color: 'var(--text-1)' }}>Cámara en vivo no inicializada</p>
|
<p style={{ fontWeight: 600, color: 'var(--text-1)' }}>Cámara en vivo no disponible</p>
|
||||||
<p style={{ fontSize: '0.825rem', marginTop: '0.5rem', color: 'var(--text-3)' }}>
|
<p style={{ fontSize: '0.825rem', marginTop: '0.5rem', color: 'var(--text-3)' }}>
|
||||||
{insecureContextWarning
|
{insecureContextWarning
|
||||||
? 'En red local sin HTTPS, el navegador restringe el streaming continuo. Puede usar la opción de Foto Nativa debajo que opera directamente sin restricciones.'
|
? 'En red local sin HTTPS, el navegador restringe el streaming continuo. Utilice el botón "📸 Capturar Foto de DNI" que abre la cámara de su dispositivo directamente sin restricciones.'
|
||||||
: 'Puede tomar una foto directa o ingresar el código manualmente abajo.'}
|
: 'Puede capturar una foto o escribir el DNI abajo.'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -470,7 +528,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
|
|
||||||
{/* Barra de Acciones y Controles Táctiles */}
|
{/* Barra de Acciones y Controles Táctiles */}
|
||||||
<div style={{ padding: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem', backgroundColor: 'var(--bg-sidebar)' }}>
|
<div style={{ padding: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem', backgroundColor: 'var(--bg-sidebar)' }}>
|
||||||
{/* Selector de cámara si hay múltiples dispositivos */}
|
{/* Selector de cámara si hay múltiples dispositivos detectados */}
|
||||||
{availableDevices.length > 1 && (
|
{availableDevices.length > 1 && (
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-2)', fontWeight: 600 }}>CÁMARA:</span>
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-2)', fontWeight: 600 }}>CÁMARA:</span>
|
||||||
@@ -478,19 +536,19 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
className="input-touch"
|
className="input-touch"
|
||||||
value={selectedDeviceId}
|
value={selectedDeviceId}
|
||||||
onChange={(e) => setSelectedDeviceId(e.target.value)}
|
onChange={(e) => setSelectedDeviceId(e.target.value)}
|
||||||
style={{ minHeight: '36px', fontSize: '0.85rem' }}
|
style={{ minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
>
|
>
|
||||||
<option value="">(Automática / Trasera)</option>
|
<option value="">(Automática / Principal)</option>
|
||||||
{availableDevices.map((d) => (
|
{availableDevices.map((d, idx) => (
|
||||||
<option key={d.deviceId} value={d.deviceId}>
|
<option key={d.deviceId || idx} value={d.deviceId}>
|
||||||
{d.label || `Cámara ${d.deviceId.slice(0, 6)}...`}
|
{d.label || `Cámara ${idx + 1}`}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Botones principales: Foto Nativa (Universal) + Linterna */}
|
{/* Botones principales: Foto Nativa (Universal) + Linterna + Cancelar */}
|
||||||
<div style={{ display: 'flex', gap: '0.65rem' }}>
|
<div style={{ display: 'flex', gap: '0.65rem' }}>
|
||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
@@ -505,7 +563,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
onClick={() => fileInputRef.current?.click()}
|
onClick={() => fileInputRef.current?.click()}
|
||||||
style={{ flex: 1, minHeight: '44px' }}
|
style={{ flex: 1, minHeight: '46px' }}
|
||||||
title="Abre la cámara nativa de Android / Windows para fotografiar el DNI"
|
title="Abre la cámara nativa de Android / Windows para fotografiar el DNI"
|
||||||
>
|
>
|
||||||
📸 Capturar Foto de DNI
|
📸 Capturar Foto de DNI
|
||||||
@@ -516,7 +574,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
onClick={toggleTorch}
|
onClick={toggleTorch}
|
||||||
style={{ minHeight: '44px', padding: '0 0.85rem' }}
|
style={{ minHeight: '46px', padding: '0 0.85rem' }}
|
||||||
>
|
>
|
||||||
{torchEnabled ? '🔦 Apagar' : '💡 Linterna'}
|
{torchEnabled ? '🔦 Apagar' : '💡 Linterna'}
|
||||||
</button>
|
</button>
|
||||||
@@ -529,7 +587,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
stopCamera();
|
stopCamera();
|
||||||
onClose();
|
onClose();
|
||||||
}}
|
}}
|
||||||
style={{ minHeight: '44px', padding: '0 1rem' }}
|
style={{ minHeight: '46px', padding: '0 1rem' }}
|
||||||
>
|
>
|
||||||
Cancelar
|
Cancelar
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
Reference in New Issue
Block a user