From 0e2ea24f0517af4dbe770e190dd556b8c2595fc5 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Wed, 14 Oct 2026 09:17:21 -0300 Subject: [PATCH] fix(scanner): escaneo foto-primero para QR DNI 2026 y PDF417 con prevencion de parpadeos --- backend/app/repositories/access_repository.py | 8 +- .../components/scanner/CameraScannerModal.tsx | 1004 +++++++++++------ 2 files changed, 678 insertions(+), 334 deletions(-) diff --git a/backend/app/repositories/access_repository.py b/backend/app/repositories/access_repository.py index 9566c6f..0039595 100644 --- a/backend/app/repositories/access_repository.py +++ b/backend/app/repositories/access_repository.py @@ -68,7 +68,13 @@ class AccessRepository: with db_session() as conn: cursor = conn.cursor() - cursor.execute("SELECT COALESCE(MAX(PersonaID), 0) + 1 FROM Per") + cursor.execute(""" + SELECT COALESCE(MAX(max_id), 0) + 1 FROM ( + SELECT MAX(PersonaID) AS max_id FROM Per + UNION + SELECT MAX(PersonaID) AS max_id FROM PerDocCatVal + ) AS t + """) new_pid = cursor.fetchone()[0] sql_per = """ diff --git a/frontend/src/components/scanner/CameraScannerModal.tsx b/frontend/src/components/scanner/CameraScannerModal.tsx index 3f962ea..e5c739c 100644 --- a/frontend/src/components/scanner/CameraScannerModal.tsx +++ b/frontend/src/components/scanner/CameraScannerModal.tsx @@ -1,7 +1,7 @@ // ============================================================================== // Modal de Escaneo Óptico con Cámara para Tablets (Android) y Windows -// 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) +// Flujo: 1° Captura de Foto Estable -> 2° Escaneo Multi-Paso de PDF417 y QR DNI 2026 +// Cumple con el sistema de diseño OnEver (styles/design_system.py) // ============================================================================== import React, { useEffect, useRef, useState, useCallback } from 'react'; import { @@ -11,6 +11,7 @@ import { RGBLuminanceSource, BinaryBitmap, HybridBinarizer, + GlobalHistogramBinarizer, } from '@zxing/library'; import { accessApi } from '../../api/accessApi'; import { DNIParsedResult } from '../../types'; @@ -21,6 +22,8 @@ interface CameraScannerModalProps { onScanSuccess: (data: DNIParsedResult) => void; } +type ScannerStep = 'PREVIEW' | 'ANALYZING' | 'SUCCESS' | 'FAILED'; + export const CameraScannerModal: React.FC = ({ isOpen, onClose, @@ -29,25 +32,26 @@ export const CameraScannerModal: React.FC = ({ const videoRef = useRef(null); const streamRef = useRef(null); const fileInputRef = useRef(null); - const timerRef = useRef(null); const zxingReaderRef = useRef(null); - const canvasRef = useRef(null); + // Estados de control de cámara y flujo + const [step, setStep] = useState('PREVIEW'); const [hasCamera, setHasCamera] = useState(true); const [insecureContextWarning, setInsecureContextWarning] = useState(false); const [errorMsg, setErrorMsg] = useState(null); - const [isProcessing, setIsProcessing] = useState(false); - const [torchEnabled, setTorchEnabled] = useState(false); - const [supportsTorch, setSupportsTorch] = useState(false); - const [manualText, setManualText] = useState(''); + const [analyzingStatus, setAnalyzingStatus] = useState(''); + const [capturedPhotoUrl, setCapturedPhotoUrl] = useState(null); + const [detectedData, setDetectedData] = useState(null); + + // Dispositivos y linterna const [availableDevices, setAvailableDevices] = useState([]); const [selectedDeviceId, setSelectedDeviceId] = useState(''); const [activeCameraLabel, setActiveCameraLabel] = useState(''); + const [torchEnabled, setTorchEnabled] = useState(false); + const [supportsTorch, setSupportsTorch] = useState(false); + const [manualText, setManualText] = useState(''); - const isProcessingRef = useRef(false); - const decodeFrameRef = useRef<(ctx: CanvasRenderingContext2D, width: number, height: number) => Promise>(() => Promise.resolve(false)); - - // Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128) + // Inicializar lector ZXing configurado para DNI Argentino (PDF417 + QR + Code128) useEffect(() => { const hints = new Map(); hints.set(DecodeHintType.POSSIBLE_FORMATS, [ @@ -61,10 +65,6 @@ export const CameraScannerModal: React.FC = ({ reader.setHints(hints); zxingReaderRef.current = reader; - // Crear canvas offscreen reutilizable - const offscreenCanvas = document.createElement('canvas'); - canvasRef.current = offscreenCanvas; - return () => { try { reader.reset(); @@ -72,102 +72,41 @@ export const CameraScannerModal: React.FC = ({ }; }, []); + // Emisión de tono sonoro de confirmación sintetizado + const playBeep = () => { + try { + const AudioCtx = window.AudioContext || (window as any).webkitAudioContext; + if (!AudioCtx) return; + const ctx = new AudioCtx(); + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = 'sine'; + osc.frequency.setValueAtTime(880, ctx.currentTime); + gain.gain.setValueAtTime(0.18, ctx.currentTime); + gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.18); + osc.connect(gain); + gain.connect(ctx.destination); + osc.start(); + osc.stop(ctx.currentTime + 0.18); + } catch {} + }; + const stopCamera = useCallback(() => { - if (timerRef.current) { - window.clearInterval(timerRef.current); - timerRef.current = null; - } if (streamRef.current) { streamRef.current.getTracks().forEach((track) => { try { track.stop(); - } catch { - // Cleanup seguro - } + } catch {} }); streamRef.current = null; } if (videoRef.current) { videoRef.current.srcObject = null; } - isProcessingRef.current = false; - setIsProcessing(false); + setTorchEnabled(false); }, []); - const handleDecodedString = useCallback( - async (rawText: string) => { - if (isProcessingRef.current || !rawText) return; - isProcessingRef.current = true; - setIsProcessing(true); - setErrorMsg(null); - try { - const res = await accessApi.parseDni(rawText); - if (res.valido) { - stopCamera(); - onScanSuccess(res); - onClose(); - } else { - setErrorMsg(`Código detectado pero no corresponde a un DNI argentino válido (${rawText.slice(0, 30)}...).`); - } - } catch (err: any) { - setErrorMsg(err.message || 'Error al interpretar el código escaneado.'); - } finally { - isProcessingRef.current = false; - setIsProcessing(false); - } - }, - [stopCamera, onScanSuccess, onClose] - ); - - // Decodificar un buffer ImageData mediante ZXing y BarcodeDetector - const decodeFrame = useCallback( - async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise => { - if (isProcessingRef.current) return false; - - // 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU) - if ('BarcodeDetector' in window) { - try { - const detector = new (window as any).BarcodeDetector({ - formats: ['pdf417', 'qr_code', 'code_128'], - }); - const barcodes = await detector.detect(ctx.canvas); - if (barcodes.length > 0 && barcodes[0].rawValue) { - handleDecodedString(barcodes[0].rawValue); - return true; - } - } catch { - // Continuar con ZXing como motor primario - } - } - - // 2. Probar decodificador ZXing sobre los píxeles directos - 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 (normal) - } finally { - try { - zxingReaderRef.current.reset(); - } catch {} - } - } - - return false; - }, - [handleDecodedString] - ); - - // Mantener decodeFrameRef sincronizado - decodeFrameRef.current = decodeFrame; - + // Iniciar flujo de video en vivo ESTABLE (sin procesamiento continuo para evitar parpadeos) const startCamera = useCallback( async (deviceIdToUse?: string) => { setErrorMsg(null); @@ -183,7 +122,7 @@ export const CameraScannerModal: React.FC = ({ 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.' + 'El navegador bloqueó la cámara directa porque la conexión es HTTP sin certificado. Utilice "📸 Capturar Foto de DNI" o ingrese por HTTPS.' ); } else { setErrorMsg('Dispositivo de video no soportado o bloqueado en este sistema.'); @@ -192,73 +131,53 @@ export const CameraScannerModal: React.FC = ({ } try { - let stream: MediaStream | null = null; - - // Limpiar stream previo si hubiera - if (streamRef.current) { - streamRef.current.getTracks().forEach((t) => { - try { t.stop(); } catch {} - }); - streamRef.current = null; - } + stopCamera(); const constraints: MediaStreamConstraints = deviceIdToUse ? { video: { deviceId: { exact: deviceIdToUse }, - width: { ideal: 1280 }, - height: { ideal: 720 }, + width: { ideal: 1920, min: 1280 }, + height: { ideal: 1080, min: 720 }, }, audio: false, } : { video: { facingMode: { ideal: 'environment' }, - width: { ideal: 1280 }, - height: { ideal: 720 }, + width: { ideal: 1920, min: 1280 }, + height: { ideal: 1080, min: 720 }, }, audio: false, }; + let stream: MediaStream | null = null; try { stream = await navigator.mediaDevices.getUserMedia(constraints); } catch { - // Fallback simple si fallaron los constraints ideales + // Fallback a resolución estándar si falla 1080p stream = await navigator.mediaDevices.getUserMedia({ - video: true, + video: { facingMode: 'environment' }, audio: false, }); } - if (!stream) { - throw new Error('No se pudo obtener el flujo de video.'); - } + if (!stream) throw new Error('No se pudo acceder a la cámara.'); 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); - } + const capabilities = (videoTrack.getCapabilities?.() as any) || {}; + setSupportsTorch(!!capabilities.torch); } - // Enumerar dispositivos disponibles sin provocar re-renders cíclicos try { const allDevices = await navigator.mediaDevices.enumerateDevices(); const vInputs = allDevices.filter((d) => d.kind === 'videoinput'); - setAvailableDevices((prev) => { - if (prev.length !== vInputs.length) return vInputs; - const prevIds = prev.map((p) => p.deviceId).join(','); - const newIds = vInputs.map((p) => p.deviceId).join(','); - return prevIds === newIds ? prev : vInputs; - }); - } catch { - // Ignorar si falla enumeración - } + setAvailableDevices(vInputs); + } catch {} if (videoRef.current) { videoRef.current.srcObject = stream; @@ -266,34 +185,13 @@ export const CameraScannerModal: React.FC = ({ 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 || isProcessingRef.current) return; - - const video = videoRef.current; - const canvas = canvasRef.current; - if (!canvas) return; - - const width = video.videoWidth || 640; - const height = video.videoHeight || 480; - - if (canvas.width !== width) canvas.width = width; - if (canvas.height !== height) canvas.height = height; - const ctx = canvas.getContext('2d', { willReadFrequently: true }); - if (!ctx) return; - - ctx.drawImage(video, 0, 0, width, height); - await decodeFrameRef.current(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.'); + setErrorMsg('No se detectó ninguna cámara conectada al equipo.'); } else if (name === 'NotReadableError') { setErrorMsg('La cámara está siendo usada por otra aplicación en Windows.'); } else { @@ -301,67 +199,298 @@ export const CameraScannerModal: React.FC = ({ } } }, - [] + [stopCamera] ); - // Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android) - const handlePhotoCaptured = async (e: React.ChangeEvent) => { - 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; - } - - const img = new Image(); - img.src = dataUrl; - img.onload = async () => { - const canvas = canvasRef.current || document.createElement('canvas'); - canvas.width = img.width; - canvas.height = img.height; - const ctx = canvas.getContext('2d', { willReadFrequently: true }); - if (!ctx) { - setIsProcessing(false); - return; - } - - ctx.drawImage(img, 0, 0, img.width, img.height); - const detected = await decodeFrame(ctx, img.width, img.height); - 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); - } catch { - setErrorMsg('Error al procesar la imagen seleccionada.'); - setIsProcessing(false); - } - }; - useEffect(() => { if (isOpen) { + setStep('PREVIEW'); + setCapturedPhotoUrl(null); + setDetectedData(null); + setErrorMsg(null); startCamera(selectedDeviceId || undefined); } else { stopCamera(); } - return () => { stopCamera(); }; }, [isOpen, startCamera, stopCamera, selectedDeviceId]); + // Decodificar un canvas específico usando BarcodeDetector nativo y ZXing + const tryDecodeCanvas = async (canvas: HTMLCanvasElement): Promise => { + const width = canvas.width; + const height = canvas.height; + if (width < 20 || height < 20) return null; + + // 1. BarcodeDetector nativo por hardware (Chrome / Android WebView) + if ('BarcodeDetector' in window) { + try { + const detector = new (window as any).BarcodeDetector({ + formats: ['pdf417', 'qr_code', 'code_128'], + }); + const barcodes = await detector.detect(canvas); + if (barcodes.length > 0 && barcodes[0].rawValue) { + return barcodes[0].rawValue; + } + } catch {} + } + + // 2. ZXing HybridBinarizer + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (!ctx) return 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()) { + return result.getText(); + } + } catch { + } finally { + try { + zxingReaderRef.current.reset(); + } catch {} + } + + // 3. ZXing GlobalHistogramBinarizer (robusto para reflejos de luz y plastificado) + try { + const imgData = ctx.getImageData(0, 0, width, height); + const luminanceSource = new RGBLuminanceSource(imgData.data, width, height); + const binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(luminanceSource)); + const result = zxingReaderRef.current.decode(binaryBitmap); + if (result && result.getText()) { + return result.getText(); + } + } catch { + } finally { + try { + zxingReaderRef.current.reset(); + } catch {} + } + } + + return null; + }; + + // Motor Multi-Paso para extraer PDF417 o QR DNI 2026 de la foto capturada + const processImageExtraction = async (sourceCanvas: HTMLCanvasElement) => { + setStep('ANALYZING'); + setErrorMsg(null); + + const sw = sourceCanvas.width; + const sh = sourceCanvas.height; + + // Paso 1: Escaneo directo en foto completa + setAnalyzingStatus('Analizando imagen completa (PDF417 / QR)...'); + let rawText = await tryDecodeCanvas(sourceCanvas); + + // Paso 2: Escaneo en región central recortada (ideal para el QR pequeño y cuadrado de DNI 2026) + if (!rawText) { + setAnalyzingStatus('Escaneando cuadrante central para QR DNI 2026...'); + const cropCanvas = document.createElement('canvas'); + const cw = Math.floor(sw * 0.65); + const ch = Math.floor(sh * 0.65); + const cx = Math.floor((sw - cw) / 2); + const cy = Math.floor((sh - ch) / 2); + cropCanvas.width = cw; + cropCanvas.height = ch; + const cctx = cropCanvas.getContext('2d'); + if (cctx) { + cctx.drawImage(sourceCanvas, cx, cy, cw, ch, 0, 0, cw, ch); + rawText = await tryDecodeCanvas(cropCanvas); + } + } + + // Paso 3: Escaneo de la mitad inferior (ubicación típica de barras PDF417 en DNI clásico) + if (!rawText) { + setAnalyzingStatus('Escaneando sección inferior para PDF417 clásico...'); + const lowerCanvas = document.createElement('canvas'); + const lh = Math.floor(sh * 0.55); + const ly = Math.floor(sh * 0.45); + lowerCanvas.width = sw; + lowerCanvas.height = lh; + const lctx = lowerCanvas.getContext('2d'); + if (lctx) { + lctx.drawImage(sourceCanvas, 0, ly, sw, lh, 0, 0, sw, lh); + rawText = await tryDecodeCanvas(lowerCanvas); + } + } + + // Paso 4: Ajuste de alto contraste y binarización para eliminar reflejos de plastificado + if (!rawText) { + setAnalyzingStatus('Aplicando realce de contraste y reducción de reflejos...'); + const contrastCanvas = document.createElement('canvas'); + contrastCanvas.width = sw; + contrastCanvas.height = sh; + const conCtx = contrastCanvas.getContext('2d', { willReadFrequently: true }); + if (conCtx) { + conCtx.drawImage(sourceCanvas, 0, 0); + const imgData = conCtx.getImageData(0, 0, sw, sh); + const data = imgData.data; + // Filtro de contraste: expansión de rango dinámico + for (let i = 0; i < data.length; i += 4) { + const r = data[i]; + const g = data[i + 1]; + const b = data[i + 2]; + const gray = 0.299 * r + 0.587 * g + 0.114 * b; + // Estiramiento de contraste + const highCon = gray > 130 ? 255 : 0; + data[i] = highCon; + data[i + 1] = highCon; + data[i + 2] = highCon; + } + conCtx.putImageData(imgData, 0, 0); + rawText = await tryDecodeCanvas(contrastCanvas); + } + } + + // Paso 5: Rotación a 90 grados (en caso de que el documento se haya fotografiado en vertical) + if (!rawText) { + setAnalyzingStatus('Comprobando orientación vertical (90°)...'); + const rotCanvas = document.createElement('canvas'); + rotCanvas.width = sh; + rotCanvas.height = sw; + const rotCtx = rotCanvas.getContext('2d'); + if (rotCtx) { + rotCtx.translate(sh / 2, sw / 2); + rotCtx.rotate((90 * Math.PI) / 180); + rotCtx.drawImage(sourceCanvas, -sw / 2, -sh / 2); + rawText = await tryDecodeCanvas(rotCanvas); + } + } + + // Resultado final de extracción + if (rawText) { + try { + const parsed = await accessApi.parseDni(rawText); + if (parsed.valido) { + playBeep(); + setDetectedData(parsed); + setStep('SUCCESS'); + } else { + setStep('FAILED'); + setErrorMsg( + `Código detectado pero formato no reconocido como DNI argentino válido (${rawText.slice(0, 35)}...).` + ); + } + } catch (err: any) { + setStep('FAILED'); + setErrorMsg(err.message || 'Error al interpretar los campos del código escaneado.'); + } + } else { + setStep('FAILED'); + setErrorMsg( + 'No se pudo detectar el código PDF417 ni el QR 2026 en la foto. Acerque el documento, asegúrese de que esté bien iluminado y sin reflejos sobre el plástico.' + ); + } + }; + + // Acción Principal: Tomar Foto desde la Cámara en Vivo + const handleCapturePhoto = async () => { + if (!videoRef.current) return; + const video = videoRef.current; + + const canvas = document.createElement('canvas'); + let captured = false; + + // 1. Probar captura por ImageCapture (aprovecha la resolución nativa máxima del sensor de la cámara) + const videoTrack = streamRef.current?.getVideoTracks()[0]; + if (videoTrack && 'ImageCapture' in window) { + try { + const imageCapture = new (window as any).ImageCapture(videoTrack); + const blob = await imageCapture.takePhoto(); + const imgBitmap = await createImageBitmap(blob); + canvas.width = imgBitmap.width; + canvas.height = imgBitmap.height; + const ctx = canvas.getContext('2d'); + if (ctx) { + ctx.drawImage(imgBitmap, 0, 0); + captured = true; + } + } catch { + // Fallback inmediato a frame de video + } + } + + // 2. Fallback: Captura directa desde el elemento HTMLVideo + if (!captured) { + const vw = video.videoWidth || 1280; + const vh = video.videoHeight || 720; + canvas.width = vw; + canvas.height = vh; + const ctx = canvas.getContext('2d'); + if (ctx) { + ctx.drawImage(video, 0, 0, vw, vh); + captured = true; + } + } + + if (!captured) { + setErrorMsg('No se pudo obtener el fotograma de la cámara.'); + return; + } + + const photoUrl = canvas.toDataURL('image/jpeg', 0.95); + setCapturedPhotoUrl(photoUrl); + + // Detener la cámara temporalmente para congelar la imagen capturada + stopCamera(); + + // Iniciar escaneo multi-paso sobre la foto + await processImageExtraction(canvas); + }; + + // Manejador para fotos cargadas desde archivo o app de cámara nativa + const handlePhotoUploaded = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = (event) => { + const dataUrl = event.target?.result as string; + if (!dataUrl) return; + + setCapturedPhotoUrl(dataUrl); + stopCamera(); + + const img = new Image(); + img.onload = async () => { + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + if (ctx) { + ctx.drawImage(img, 0, 0); + await processImageExtraction(canvas); + } + }; + img.src = dataUrl; + }; + reader.readAsDataURL(file); + }; + + // Reintentar captura volviendo a la cámara en vivo + const handleRetake = () => { + setCapturedPhotoUrl(null); + setDetectedData(null); + setErrorMsg(null); + setStep('PREVIEW'); + startCamera(selectedDeviceId || undefined); + }; + + // Confirmar y aplicar datos leídos + const handleConfirmDni = () => { + if (detectedData) { + stopCamera(); + onScanSuccess(detectedData); + onClose(); + } + }; + const toggleTorch = async () => { if (!streamRef.current) return; const track = streamRef.current.getVideoTracks()[0]; @@ -371,15 +500,29 @@ export const CameraScannerModal: React.FC = ({ advanced: [{ torch: nextState }], }); setTorchEnabled(nextState); - } catch { - // Ignorar si el dispositivo no soporta linterna - } + } catch {} }; - const handleManualSubmit = (e: React.FormEvent) => { + const handleManualSubmit = async (e: React.FormEvent) => { e.preventDefault(); - if (manualText.trim()) { - handleDecodedString(manualText.trim()); + if (!manualText.trim()) return; + + setStep('ANALYZING'); + setAnalyzingStatus('Interpretando texto manual o código...'); + try { + const parsed = await accessApi.parseDni(manualText.trim()); + if (parsed.valido) { + playBeep(); + stopCamera(); + onScanSuccess(parsed); + onClose(); + } else { + setStep('FAILED'); + setErrorMsg('El texto ingresado no contiene datos de un DNI argentino válido.'); + } + } catch (err: any) { + setStep('FAILED'); + setErrorMsg(err.message || 'Error al validar texto.'); } }; @@ -393,28 +536,29 @@ export const CameraScannerModal: React.FC = ({ left: 0, right: 0, bottom: 0, - backgroundColor: 'rgba(2, 6, 23, 0.85)', - backdropFilter: 'blur(4px)', + backgroundColor: 'rgba(2, 6, 23, 0.88)', + backdropFilter: 'blur(6px)', zIndex: 9999, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', - padding: '1rem', + padding: '0.75rem', }} >
{/* Cabecera del Escáner */} @@ -423,19 +567,19 @@ export const CameraScannerModal: React.FC = ({ display: 'flex', alignItems: 'center', justifyContent: 'space-between', - padding: '1rem 1.25rem', - borderBottom: '1px solid var(--divider)', - backgroundColor: 'var(--bg-sidebar)', + padding: '0.85rem 1.25rem', + borderBottom: '1px solid var(--border-subtle)', + backgroundColor: 'var(--bg-card)', }} > -
- 📷 +
+ 📸
-

- Escanear DNI Argentino (Cámara / PDF417) +

+ Captura y Escaneo de DNI (Foto + PDF417 / QR 2026)

- - {activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Soporta DNI tarjeta, PDF417, QR digital y fotos'} + + {activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Encuadre el DNI completo y presione TOMAR FOTO'}
@@ -444,26 +588,25 @@ export const CameraScannerModal: React.FC = ({ stopCamera(); onClose(); }} - className="btn-outline" + className="btn btn-secondary" style={{ - padding: '0.35rem 0.65rem', + padding: '0.35rem 0.75rem', minHeight: '36px', - border: 'none', - fontSize: '1.25rem', - color: 'var(--text-2)', + fontSize: '1.1rem', + fontWeight: 700, }} - title="Cerrar modal" + title="Cerrar ventana" > ✕
- {/* Visor de Video de la Cámara */} + {/* Visor de Cámara / Foto Capturada */}
= ({ overflow: 'hidden', }} > - {hasCamera ? ( + {/* VISTA 1: Video en Vivo de la Cámara */} + {step === 'PREVIEW' && hasCamera && ( <>