feat(ui-camera): aplicar sistema de diseno OnEver y soporte universal de camaras en Android y Windows

This commit is contained in:
Carlos Tello
2026-10-13 16:59:26 -03:00
parent e5b2b98d41
commit e949df134b
10 changed files with 762 additions and 217 deletions
@@ -1,8 +1,10 @@
// ==============================================================================
// Modal de Escaneo Óptico con Cámara de Tablet (BarcodeDetector / PDF417 / QR)
// Optimizado para tablets Samsung Galaxy Tab A9/A11 (4GB RAM) con liberación inmediata de hardware
// 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
// Cumple con el sistema de diseño OnEver (C:\Workspace\OemspotPySYS\styles\design_system.py)
// ==============================================================================
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { BrowserMultiFormatReader, BarcodeFormat, DecodeHintType } from '@zxing/library';
import { accessApi } from '../../api/accessApi';
import { DNIParsedResult } from '../../types';
@@ -19,23 +21,57 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
}) => {
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const intervalRef = useRef<number | null>(null);
const zxingReaderRef = useRef<BrowserMultiFormatReader | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [hasCamera, setHasCamera] = useState<boolean>(true);
const [insecureContextWarning, setInsecureContextWarning] = useState<boolean>(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const [torchEnabled, setTorchEnabled] = useState<boolean>(false);
const [supportsTorch, setSupportsTorch] = useState<boolean>(false);
const [manualText, setManualText] = useState<string>('');
const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]);
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
// Inicializar lector ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
useEffect(() => {
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
BarcodeFormat.PDF_417,
BarcodeFormat.QR_CODE,
BarcodeFormat.CODE_128,
]);
hints.set(DecodeHintType.TRY_HARDER, true);
zxingReaderRef.current = new BrowserMultiFormatReader(hints, 250);
return () => {
if (zxingReaderRef.current) {
try {
zxingReaderRef.current.reset();
} catch {
// Cleanup
}
}
};
}, []);
const stopCamera = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
if (zxingReaderRef.current) {
try {
zxingReaderRef.current.reset();
} catch {
// Ignorar
}
}
if (streamRef.current) {
streamRef.current.getTracks().forEach((track) => {
track.stop();
try {
track.stop();
} catch {
// Ignorar
}
});
streamRef.current = null;
}
@@ -48,6 +84,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
async (rawText: string) => {
if (isProcessing || !rawText) return;
setIsProcessing(true);
setErrorMsg(null);
try {
const res = await accessApi.parseDni(rawText);
if (res.valido) {
@@ -55,7 +92,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
onScanSuccess(res);
onClose();
} else {
setErrorMsg('Código detectado pero no corresponde a un DNI argentino válido.');
setErrorMsg(`Código detectado pero no es un DNI argentino válido (${rawText.slice(0, 30)}...).`);
}
} catch (err: any) {
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
@@ -66,21 +103,68 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
[isProcessing, stopCamera, onScanSuccess, onClose]
);
const startCamera = useCallback(async () => {
const startCamera = useCallback(async (deviceIdToUse?: string) => {
setErrorMsg(null);
setHasCamera(true);
try {
const constraints: MediaStreamConstraints = {
video: {
facingMode: { ideal: 'environment' }, // Cámara trasera de la tablet
width: { ideal: 1280 },
height: { ideal: 720 },
},
audio: false,
};
// Verificar si el navegador permite acceso a mediaDevices
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 porque la conexión es HTTP sobre red local. Utilice el botón "📷 Tomar Foto con Cámara" para escanear sin restricciones de seguridad.'
);
} else {
setErrorMsg('Dispositivo de video no soportado o bloqueado por el sistema operativo.');
}
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)
let stream: MediaStream | null = null;
try {
// Intento 1: Cámara trasera de tablet / dispositivo específico
const videoConstraints: MediaTrackConstraints = deviceIdToUse
? { deviceId: { exact: deviceIdToUse } }
: {
facingMode: { ideal: 'environment' },
width: { ideal: 1280 },
height: { ideal: 720 },
};
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 {
stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false,
});
} catch (innerErr: any) {
throw innerErr;
}
}
if (!stream) {
throw new Error('No se pudo inicializar el flujo de video.');
}
const stream = await navigator.mediaDevices.getUserMedia(constraints);
streamRef.current = stream;
if (videoRef.current) {
@@ -95,37 +179,83 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
setSupportsTorch(true);
}
// Inicializar detección si BarcodeDetector está disponible
if ('BarcodeDetector' in window) {
const BarcodeDetectorClass = (window as any).BarcodeDetector;
const detector = new BarcodeDetectorClass({
formats: ['pdf417', 'qr_code', 'code_128'],
});
intervalRef.current = window.setInterval(async () => {
if (!videoRef.current || isProcessing) return;
try {
const barcodes = await detector.detect(videoRef.current);
if (barcodes.length > 0) {
const rawVal = barcodes[0].rawValue;
if (rawVal) {
handleDecodedString(rawVal);
// 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 {
// Ignorar errores de frame no listo
}
}, 300); // Muestreo cada 300ms optimizado para 4GB RAM
);
}
} catch (err: any) {
setHasCamera(false);
setErrorMsg('No se pudo acceder a la cámara de la tablet. Permiso denegado o dispositivo no disponible.');
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, isProcessing]);
}, [handleDecodedString]);
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
const handlePhotoCaptured = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsProcessing(true);
setErrorMsg(null);
try {
const reader = new FileReader();
reader.onload = async (event) => {
const dataUrl = event.target?.result as string;
if (!dataUrl) {
setIsProcessing(false);
return;
}
// Crear imagen temporal para decodificar con ZXing
const img = new Image();
img.src = dataUrl;
img.onload = async () => {
try {
if (zxingReaderRef.current) {
const result = await zxingReaderRef.current.decodeFromImageElement(img);
if (result && result.getText()) {
handleDecodedString(result.getText());
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
setErrorMsg('No se pudo detectar el código de barras en la foto. Intente con mejor iluminación o acerque el código.');
setIsProcessing(false);
};
};
reader.readAsDataURL(file);
} catch (err: any) {
setErrorMsg('Error al procesar la imagen capturada.');
setIsProcessing(false);
}
};
useEffect(() => {
if (isOpen) {
startCamera();
startCamera(selectedDeviceId || undefined);
} else {
stopCamera();
}
@@ -133,7 +263,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
return () => {
stopCamera();
};
}, [isOpen, startCamera, stopCamera]);
}, [isOpen, startCamera, stopCamera, selectedDeviceId]);
const toggleTorch = async () => {
if (!streamRef.current) return;
@@ -166,7 +296,8 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.85)',
backgroundColor: 'rgba(2, 6, 23, 0.85)',
backdropFilter: 'blur(4px)',
zIndex: 9999,
display: 'flex',
flexDirection: 'column',
@@ -176,16 +307,17 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
}}
>
<div
className="card"
style={{
width: '100%',
maxWidth: '640px',
backgroundColor: 'var(--bg-surface)',
borderRadius: 'var(--radius-lg)',
maxWidth: '620px',
backgroundColor: 'var(--bg-sidebar)',
borderRadius: '10px',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
boxShadow: 'var(--shadow-lg)',
border: '1px solid var(--border-subtle)',
border: '1px solid var(--border)',
}}
>
{/* Cabecera del Escáner */}
@@ -195,30 +327,35 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
alignItems: 'center',
justifyContent: 'space-between',
padding: '1rem 1.25rem',
borderBottom: '1px solid var(--border-subtle)',
backgroundColor: 'var(--bg-card)',
borderBottom: '1px solid var(--divider)',
backgroundColor: 'var(--bg-sidebar)',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<span style={{ fontSize: '1.25rem' }}>📷</span>
<h2 style={{ fontSize: '1.1rem', fontWeight: 600, margin: 0, color: 'var(--text-primary)' }}>
Escanear DNI Argentino (Cámara Tablet)
</h2>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
<span style={{ fontSize: '1.3rem' }}>📷</span>
<div>
<h2 style={{ fontSize: '1.05rem', fontWeight: 700, margin: 0, color: 'var(--text-1)' }}>
Escanear DNI Argentino (Cámara / PDF417)
</h2>
<span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>
Soporta DNI tarjeta, PDF417, QR digital y fotos nativas
</span>
</div>
</div>
<button
onClick={() => {
stopCamera();
onClose();
}}
className="btn-outline"
style={{
background: 'transparent',
padding: '0.35rem 0.65rem',
minHeight: '36px',
border: 'none',
fontSize: '1.5rem',
color: 'var(--text-muted)',
cursor: 'pointer',
padding: '0.25rem 0.5rem',
fontSize: '1.25rem',
color: 'var(--text-2)',
}}
title="Cerrar"
title="Cerrar modal"
>
✕
</button>
@@ -229,7 +366,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
style={{
position: 'relative',
width: '100%',
height: '320px',
height: '310px',
backgroundColor: '#000',
display: 'flex',
alignItems: 'center',
@@ -253,11 +390,11 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
<div
style={{
position: 'absolute',
width: '80%',
height: '65%',
border: '2px dashed var(--accent-primary)',
borderRadius: '12px',
boxShadow: '0 0 0 9999px rgba(0, 0, 0, 0.45)',
width: '82%',
height: '62%',
border: '2px dashed var(--blue-base)',
borderRadius: '10px',
boxShadow: '0 0 0 9999px rgba(2, 6, 23, 0.5)',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
@@ -266,21 +403,27 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
>
<span
style={{
backgroundColor: 'rgba(0, 0, 0, 0.7)',
color: '#fff',
padding: '0.25rem 0.75rem',
borderRadius: '4px',
backgroundColor: 'rgba(15, 23, 42, 0.85)',
color: 'var(--text-1)',
padding: '0.3rem 0.85rem',
borderRadius: '6px',
fontSize: '0.8rem',
border: '1px solid var(--border)',
}}
>
Ubique el código de barras PDF417 o QR aquí
Ubique el código PDF417 o QR aquí
</span>
</div>
</>
) : (
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>
<p>📷 Cámara no disponible en este dispositivo o sin permisos.</p>
<p style={{ fontSize: '0.85rem' }}>Puede ingresar el código manualmente abajo.</p>
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-2)', maxWidth: '480px' }}>
<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={{ fontSize: '0.825rem', marginTop: '0.5rem', color: 'var(--text-3)' }}>
{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.'
: 'Puede tomar una foto directa o ingresar el código manualmente abajo.'}
</p>
</div>
)}
@@ -292,16 +435,17 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.6)',
backgroundColor: 'rgba(2, 6, 23, 0.8)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
color: 'var(--text-1)',
fontSize: '1rem',
fontWeight: 600,
gap: '0.5rem',
}}
>
⏳ Interpretando datos de identidad...
<span>⏳</span> Procesando datos de identidad...
</div>
)}
</div>
@@ -310,30 +454,74 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
{errorMsg && (
<div
style={{
padding: '0.75rem 1rem',
backgroundColor: 'var(--status-danger-bg)',
color: 'var(--status-danger)',
fontSize: '0.85rem',
borderBottom: '1px solid var(--border-subtle)',
padding: '0.65rem 1rem',
backgroundColor: 'var(--color-danger-bg)',
color: 'var(--danger-hover)',
fontSize: '0.825rem',
borderBottom: '1px solid var(--border)',
display: 'flex',
alignItems: 'center',
gap: '0.5rem',
}}
>
⚠️ {errorMsg}
<span>⚠️</span> {errorMsg}
</div>
)}
{/* Barra de Acciones y Controles Táctiles */}
<div style={{ padding: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
<div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'space-between' }}>
<div style={{ padding: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem', backgroundColor: 'var(--bg-sidebar)' }}>
{/* Selector de cámara si hay múltiples dispositivos */}
{availableDevices.length > 1 && (
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<span style={{ fontSize: '0.75rem', color: 'var(--text-2)', fontWeight: 600 }}>CÁMARA:</span>
<select
className="input-touch"
value={selectedDeviceId}
onChange={(e) => setSelectedDeviceId(e.target.value)}
style={{ minHeight: '36px', fontSize: '0.85rem' }}
>
<option value="">(Automática / Trasera)</option>
{availableDevices.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || `Cámara ${d.deviceId.slice(0, 6)}...`}
</option>
))}
</select>
</div>
)}
{/* Botones principales: Foto Nativa (Universal) + Linterna */}
<div style={{ display: 'flex', gap: '0.65rem' }}>
<input
type="file"
ref={fileInputRef}
accept="image/*"
capture="environment"
onChange={handlePhotoCaptured}
style={{ display: 'none' }}
/>
<button
type="button"
className="btn btn-primary"
onClick={() => fileInputRef.current?.click()}
style={{ flex: 1, minHeight: '44px' }}
title="Abre la cámara nativa de Android / Windows para fotografiar el DNI"
>
📸 Capturar Foto de DNI
</button>
{supportsTorch && (
<button
type="button"
className="btn btn-secondary"
onClick={toggleTorch}
style={{ flex: 1, minHeight: '48px' }}
style={{ minHeight: '44px', padding: '0 0.85rem' }}
>
{torchEnabled ? '🔦 Apagar Linterna' : '💡 Encender Linterna'}
{torchEnabled ? '🔦 Apagar' : '💡 Linterna'}
</button>
)}
<button
type="button"
className="btn btn-secondary"
@@ -341,29 +529,29 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
stopCamera();
onClose();
}}
style={{ flex: 1, minHeight: '48px' }}
style={{ minHeight: '44px', padding: '0 1rem' }}
>
Cancelar
</button>
</div>
{/* Formulario alternativo de carga manual de texto crudo */}
<form onSubmit={handleManualSubmit} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
{/* Formulario alternativo de carga manual de texto o número */}
<form onSubmit={handleManualSubmit} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem' }}>
<input
type="text"
className="input-touch"
placeholder="Pegar o escribir código DNI o número..."
placeholder="Pegar código PDF417, QR o número de DNI..."
value={manualText}
onChange={(e) => setManualText(e.target.value)}
style={{ flex: 1, fontSize: '0.9rem' }}
style={{ flex: 1, fontSize: '0.875rem', minHeight: '42px' }}
/>
<button
type="submit"
className="btn btn-primary"
disabled={!manualText.trim() || isProcessing}
style={{ minHeight: '48px', padding: '0 1rem' }}
style={{ minHeight: '42px', padding: '0 1.15rem' }}
>
Procesar
Interpretar
</button>
</form>
</div>