1144 lines
40 KiB
TypeScript
1144 lines
40 KiB
TypeScript
// ==============================================================================
|
|
// Modal de Escaneo Óptico con Cámara para Tablets (Android) y Windows
|
|
// 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 {
|
|
MultiFormatReader,
|
|
BarcodeFormat,
|
|
DecodeHintType,
|
|
RGBLuminanceSource,
|
|
BinaryBitmap,
|
|
HybridBinarizer,
|
|
GlobalHistogramBinarizer,
|
|
} from '@zxing/library';
|
|
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
|
|
import { Capacitor } from '@capacitor/core';
|
|
import { accessApi } from '../../api/accessApi';
|
|
import { DNIParsedResult } from '../../types';
|
|
|
|
interface CameraScannerModalProps {
|
|
isOpen: boolean;
|
|
onClose: () => void;
|
|
onScanSuccess: (data: DNIParsedResult) => void;
|
|
}
|
|
|
|
type ScannerStep = 'PREVIEW' | 'ANALYZING' | 'SUCCESS' | 'FAILED';
|
|
|
|
export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|
isOpen,
|
|
onClose,
|
|
onScanSuccess,
|
|
}) => {
|
|
const videoRef = useRef<HTMLVideoElement | null>(null);
|
|
const containerRef = useRef<HTMLDivElement | null>(null);
|
|
const guideRef = useRef<HTMLDivElement | null>(null);
|
|
const streamRef = useRef<MediaStream | null>(null);
|
|
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
|
const zxingReaderRef = useRef<MultiFormatReader | null>(null);
|
|
|
|
// Estados de control de cámara y flujo
|
|
const [step, setStep] = useState<ScannerStep>('PREVIEW');
|
|
const [hasCamera, setHasCamera] = useState<boolean>(true);
|
|
const [insecureContextWarning, setInsecureContextWarning] = useState<boolean>(false);
|
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
|
const [analyzingStatus, setAnalyzingStatus] = useState<string>('');
|
|
const [capturedPhotoUrl, setCapturedPhotoUrl] = useState<string | null>(null);
|
|
const [detectedData, setDetectedData] = useState<DNIParsedResult | null>(null);
|
|
|
|
// Dispositivos y linterna
|
|
const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]);
|
|
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
|
|
const [activeCameraLabel, setActiveCameraLabel] = useState<string>('');
|
|
const [torchEnabled, setTorchEnabled] = useState<boolean>(false);
|
|
const [supportsTorch, setSupportsTorch] = useState<boolean>(false);
|
|
const [manualText, setManualText] = 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);
|
|
|
|
const reader = new MultiFormatReader();
|
|
reader.setHints(hints);
|
|
zxingReaderRef.current = reader;
|
|
|
|
return () => {
|
|
try {
|
|
reader.reset();
|
|
} catch {}
|
|
};
|
|
}, []);
|
|
|
|
// 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 (streamRef.current) {
|
|
streamRef.current.getTracks().forEach((track) => {
|
|
try {
|
|
track.stop();
|
|
} catch {}
|
|
});
|
|
streamRef.current = null;
|
|
}
|
|
if (videoRef.current) {
|
|
videoRef.current.srcObject = null;
|
|
}
|
|
setTorchEnabled(false);
|
|
}, []);
|
|
|
|
// Iniciar flujo de video en vivo ESTABLE (sin procesamiento continuo para evitar parpadeos)
|
|
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 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.');
|
|
}
|
|
return;
|
|
}
|
|
|
|
try {
|
|
stopCamera();
|
|
|
|
const constraints: MediaStreamConstraints = deviceIdToUse
|
|
? {
|
|
video: {
|
|
deviceId: { exact: deviceIdToUse },
|
|
width: { ideal: 1920, min: 1280 },
|
|
height: { ideal: 1080, min: 720 },
|
|
},
|
|
audio: false,
|
|
}
|
|
: {
|
|
video: {
|
|
facingMode: { ideal: 'environment' },
|
|
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 a resolución estándar si falla 1080p
|
|
stream = await navigator.mediaDevices.getUserMedia({
|
|
video: { facingMode: 'environment' },
|
|
audio: false,
|
|
});
|
|
}
|
|
|
|
if (!stream) throw new Error('No se pudo acceder a la cámara.');
|
|
|
|
streamRef.current = stream;
|
|
|
|
const videoTrack = stream.getVideoTracks()[0];
|
|
if (videoTrack) {
|
|
setActiveCameraLabel(videoTrack.label || 'Cámara activa');
|
|
const capabilities = (videoTrack.getCapabilities?.() as any) || {};
|
|
setSupportsTorch(!!capabilities.torch);
|
|
}
|
|
|
|
try {
|
|
const allDevices = await navigator.mediaDevices.enumerateDevices();
|
|
const vInputs = allDevices.filter((d) => d.kind === 'videoinput');
|
|
setAvailableDevices(vInputs);
|
|
} catch {}
|
|
|
|
if (videoRef.current) {
|
|
videoRef.current.srcObject = stream;
|
|
videoRef.current.onloadedmetadata = () => {
|
|
videoRef.current?.play().catch(() => {});
|
|
};
|
|
}
|
|
} 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 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'}`);
|
|
}
|
|
}
|
|
},
|
|
[stopCamera]
|
|
);
|
|
|
|
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<string | null> => {
|
|
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,
|
|
fallbackCanvas?: 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);
|
|
}
|
|
}
|
|
|
|
// Paso 6: Si no se detectó en el recorte, intentar en el fotograma completo
|
|
if (!rawText && fallbackCanvas) {
|
|
setAnalyzingStatus('Buscando en fotograma completo alternativo...');
|
|
rawText = await tryDecodeCanvas(fallbackCanvas);
|
|
}
|
|
|
|
// 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 y Recortarla al Marco
|
|
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;
|
|
}
|
|
|
|
// 3. RECORTE AUTOMÁTICO EXACTO DE LA FOTO AL MARCO/GUÍA DEL DNI
|
|
let cropX = 0;
|
|
let cropY = 0;
|
|
let cropW = canvas.width;
|
|
let cropH = canvas.height;
|
|
|
|
if (containerRef.current && guideRef.current && videoRef.current) {
|
|
const cRect = containerRef.current.getBoundingClientRect();
|
|
const gRect = guideRef.current.getBoundingClientRect();
|
|
const vw = canvas.width;
|
|
const vh = canvas.height;
|
|
const cw = cRect.width;
|
|
const ch = cRect.height;
|
|
|
|
if (cw > 0 && ch > 0) {
|
|
// En video con objectFit: 'cover'
|
|
const scale = Math.max(cw / vw, ch / vh);
|
|
const renderedW = vw * scale;
|
|
const renderedH = vh * scale;
|
|
const offsetX = (cw - renderedW) / 2;
|
|
const offsetY = (ch - renderedH) / 2;
|
|
|
|
const gLeft = gRect.left - cRect.left;
|
|
const gTop = gRect.top - cRect.top;
|
|
|
|
// Mapear de coordenadas visuales de pantalla a píxeles reales de la imagen
|
|
cropX = Math.round((gLeft - offsetX) / scale);
|
|
cropY = Math.round((gTop - offsetY) / scale);
|
|
cropW = Math.round(gRect.width / scale);
|
|
cropH = Math.round(gRect.height / scale);
|
|
|
|
// Clamping seguro dentro de los límites de la imagen
|
|
cropX = Math.max(0, Math.min(cropX, vw - 20));
|
|
cropY = Math.max(0, Math.min(cropY, vh - 20));
|
|
cropW = Math.max(20, Math.min(cropW, vw - cropX));
|
|
cropH = Math.max(20, Math.min(cropH, vh - cropY));
|
|
}
|
|
} else {
|
|
// Fallback a recorte central estándar de tarjeta DNI (relación 1.58 : 1)
|
|
const targetW = Math.round(canvas.width * 0.85);
|
|
const targetH = Math.round(targetW / 1.58);
|
|
cropX = Math.max(0, Math.round((canvas.width - targetW) / 2));
|
|
cropY = Math.max(0, Math.round((canvas.height - targetH) / 2));
|
|
cropW = Math.min(targetW, canvas.width - cropX);
|
|
cropH = Math.min(targetH, canvas.height - cropY);
|
|
}
|
|
|
|
// Crear canvas con la imagen recortada del DNI
|
|
const croppedCanvas = document.createElement('canvas');
|
|
croppedCanvas.width = cropW;
|
|
croppedCanvas.height = cropH;
|
|
const croppedCtx = croppedCanvas.getContext('2d');
|
|
if (croppedCtx) {
|
|
croppedCtx.drawImage(canvas, cropX, cropY, cropW, cropH, 0, 0, cropW, cropH);
|
|
}
|
|
|
|
// Foto final recortada para visualización y análisis
|
|
const finalDisplayCanvas = croppedCtx ? croppedCanvas : canvas;
|
|
const photoUrl = finalDisplayCanvas.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 recortada (con fallback al fotograma completo si hiciera falta)
|
|
await processImageExtraction(finalDisplayCanvas, canvas);
|
|
};
|
|
|
|
// Manejador para fotos cargadas desde archivo o app de cámara nativa
|
|
const handlePhotoUploaded = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
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;
|
|
|
|
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);
|
|
|
|
// Si la foto es vertical o panorámica, recortar región central del DNI
|
|
let finalCanvas = canvas;
|
|
const targetW = Math.round(img.width * 0.9);
|
|
const targetH = Math.round(targetW / 1.58);
|
|
if (targetH < img.height) {
|
|
const cropCanvas = document.createElement('canvas');
|
|
cropCanvas.width = targetW;
|
|
cropCanvas.height = targetH;
|
|
const cctx = cropCanvas.getContext('2d');
|
|
if (cctx) {
|
|
const cx = Math.round((img.width - targetW) / 2);
|
|
const cy = Math.round((img.height - targetH) / 2);
|
|
cctx.drawImage(img, cx, cy, targetW, targetH, 0, 0, targetW, targetH);
|
|
finalCanvas = cropCanvas;
|
|
}
|
|
}
|
|
|
|
setCapturedPhotoUrl(finalCanvas.toDataURL('image/jpeg', 0.95));
|
|
await processImageExtraction(finalCanvas, canvas);
|
|
}
|
|
};
|
|
img.src = dataUrl;
|
|
};
|
|
reader.readAsDataURL(file);
|
|
};
|
|
|
|
// Captura nativa con plugin oficial de Capacitor (Android Tablet Samsung)
|
|
const handleCapacitorPhoto = async () => {
|
|
if (!Capacitor.isNativePlatform()) {
|
|
fileInputRef.current?.click();
|
|
return;
|
|
}
|
|
try {
|
|
const photo = await Camera.getPhoto({
|
|
quality: 92,
|
|
allowEditing: false,
|
|
resultType: CameraResultType.DataUrl,
|
|
source: CameraSource.Camera,
|
|
});
|
|
|
|
if (photo.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);
|
|
setCapturedPhotoUrl(photo.dataUrl!);
|
|
await processImageExtraction(canvas);
|
|
}
|
|
};
|
|
img.src = photo.dataUrl;
|
|
}
|
|
} catch (err: any) {
|
|
if (err.message && !err.message.includes('User cancelled') && !err.message.includes('cancelled')) {
|
|
setErrorMsg(`Error en cámara nativa: ${err.message}`);
|
|
}
|
|
}
|
|
};
|
|
|
|
// 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];
|
|
try {
|
|
const nextState = !torchEnabled;
|
|
await (track as any).applyConstraints({
|
|
advanced: [{ torch: nextState }],
|
|
});
|
|
setTorchEnabled(nextState);
|
|
} catch {}
|
|
};
|
|
|
|
const handleManualSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
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.');
|
|
}
|
|
};
|
|
|
|
if (!isOpen) return null;
|
|
|
|
return (
|
|
<div
|
|
style={{
|
|
position: 'fixed',
|
|
top: 0,
|
|
left: 0,
|
|
right: 0,
|
|
bottom: 0,
|
|
backgroundColor: 'rgba(2, 6, 23, 0.88)',
|
|
backdropFilter: 'blur(6px)',
|
|
zIndex: 9999,
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
padding: '0.75rem',
|
|
}}
|
|
>
|
|
<div
|
|
className="card"
|
|
style={{
|
|
width: '100%',
|
|
maxWidth: '680px',
|
|
maxHeight: '94vh',
|
|
backgroundColor: 'var(--bg-card)',
|
|
borderRadius: '12px',
|
|
overflow: 'hidden',
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
boxShadow: 'var(--shadow-lg)',
|
|
border: '1px solid var(--border-subtle)',
|
|
}}
|
|
>
|
|
{/* Cabecera del Escáner */}
|
|
<div
|
|
style={{
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
justifyContent: 'space-between',
|
|
padding: '0.85rem 1.25rem',
|
|
borderBottom: '1px solid var(--border-subtle)',
|
|
backgroundColor: 'var(--bg-surface)',
|
|
}}
|
|
>
|
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
|
|
<span style={{ fontSize: '1.5rem' }}>📸</span>
|
|
<div>
|
|
<h2 style={{ fontSize: '1.15rem', fontWeight: 700, margin: 0, color: 'var(--text-primary)' }}>
|
|
Captura y Escaneo de DNI (Foto + PDF417 / QR 2026)
|
|
</h2>
|
|
<span style={{ fontSize: '0.78rem', color: 'var(--text-secondary)' }}>
|
|
{activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Encuadre el DNI completo y presione TOMAR FOTO'}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
<button
|
|
onClick={() => {
|
|
stopCamera();
|
|
onClose();
|
|
}}
|
|
className="btn btn-secondary"
|
|
style={{
|
|
padding: '0.35rem 0.75rem',
|
|
minHeight: '36px',
|
|
fontSize: '1.1rem',
|
|
fontWeight: 700,
|
|
}}
|
|
title="Cerrar ventana"
|
|
>
|
|
✕
|
|
</button>
|
|
</div>
|
|
|
|
{/* Visor de Cámara / Foto Capturada */}
|
|
<div
|
|
ref={containerRef}
|
|
style={{
|
|
position: 'relative',
|
|
width: '100%',
|
|
height: '350px',
|
|
backgroundColor: '#000',
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
overflow: 'hidden',
|
|
}}
|
|
>
|
|
{/* VISTA 1: Video en Vivo de la Cámara */}
|
|
{step === 'PREVIEW' && hasCamera && (
|
|
<>
|
|
<video
|
|
ref={videoRef}
|
|
autoPlay
|
|
playsInline
|
|
muted
|
|
onClick={handleCapturePhoto}
|
|
style={{
|
|
width: '100%',
|
|
height: '100%',
|
|
objectFit: 'cover',
|
|
cursor: 'pointer',
|
|
}}
|
|
title="Haga clic en la imagen o en el botón para tomar la foto"
|
|
/>
|
|
|
|
{/* Guía Visual Integral del DNI (Proporción de Tarjeta DNI ~1.58:1) */}
|
|
<div
|
|
ref={guideRef}
|
|
style={{
|
|
position: 'absolute',
|
|
width: '85%',
|
|
maxWidth: '460px',
|
|
aspectRatio: '1.58 / 1',
|
|
border: '3px solid rgba(30, 136, 229, 0.85)',
|
|
borderRadius: '12px',
|
|
boxShadow: '0 0 0 9999px rgba(0, 0, 0, 0.45)',
|
|
pointerEvents: 'none',
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
justifyContent: 'space-between',
|
|
padding: '0.75rem',
|
|
}}
|
|
>
|
|
{/* Esquinas destacadas */}
|
|
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
|
<span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#fff', backgroundColor: 'rgba(0,0,0,0.6)', padding: '2px 6px', borderRadius: '4px' }}>
|
|
📱 QR (DNI 2026)
|
|
</span>
|
|
<span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#fff', backgroundColor: 'rgba(0,0,0,0.6)', padding: '2px 6px', borderRadius: '4px' }}>
|
|
📄 PDF417 (Dorso)
|
|
</span>
|
|
</div>
|
|
|
|
<div style={{ textAlign: 'center' }}>
|
|
<span
|
|
style={{
|
|
backgroundColor: 'rgba(30, 136, 229, 0.9)',
|
|
color: '#fff',
|
|
padding: '0.35rem 0.85rem',
|
|
borderRadius: '6px',
|
|
fontSize: '0.85rem',
|
|
fontWeight: 700,
|
|
boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
|
|
}}
|
|
>
|
|
Ubique el DNI dentro de este marco
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{/* VISTA 2: Foto Congelada / Procesamiento / Resultados */}
|
|
{step !== 'PREVIEW' && capturedPhotoUrl && (
|
|
<div style={{ position: 'relative', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
|
<span
|
|
style={{
|
|
position: 'absolute',
|
|
top: '0.65rem',
|
|
left: '0.65rem',
|
|
backgroundColor: 'rgba(30, 136, 229, 0.9)',
|
|
color: '#fff',
|
|
padding: '0.2rem 0.6rem',
|
|
borderRadius: '4px',
|
|
fontSize: '0.75rem',
|
|
fontWeight: 700,
|
|
zIndex: 10,
|
|
boxShadow: '0 2px 6px rgba(0,0,0,0.4)',
|
|
}}
|
|
>
|
|
✂️ Foto Recortada al DNI
|
|
</span>
|
|
<img
|
|
src={capturedPhotoUrl}
|
|
alt="Foto del DNI recortada"
|
|
style={{
|
|
width: '100%',
|
|
height: '100%',
|
|
objectFit: 'contain',
|
|
backgroundColor: '#111',
|
|
}}
|
|
/>
|
|
|
|
{/* Overlay mientras analiza la foto */}
|
|
{step === 'ANALYZING' && (
|
|
<div
|
|
style={{
|
|
position: 'absolute',
|
|
top: 0,
|
|
left: 0,
|
|
right: 0,
|
|
bottom: 0,
|
|
backgroundColor: 'rgba(0, 0, 0, 0.7)',
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
gap: '0.75rem',
|
|
color: '#fff',
|
|
padding: '1.5rem',
|
|
textAlign: 'center',
|
|
}}
|
|
>
|
|
<div
|
|
style={{
|
|
width: '40px',
|
|
height: '40px',
|
|
border: '4px solid rgba(255,255,255,0.3)',
|
|
borderTopColor: 'var(--accent-primary)',
|
|
borderRadius: '50%',
|
|
animation: 'spin 1s linear infinite',
|
|
}}
|
|
/>
|
|
<div style={{ fontSize: '1.1rem', fontWeight: 700 }}>{analyzingStatus || 'Escaneando fotografía...'}</div>
|
|
<span style={{ fontSize: '0.85rem', color: '#ccc' }}>
|
|
Buscando códigos de barras PDF417 y QR DNI 2026 en múltiples cuadrantes
|
|
</span>
|
|
</div>
|
|
)}
|
|
|
|
{/* Overlay de Éxito sobre la Foto */}
|
|
{step === 'SUCCESS' && detectedData && (
|
|
<div
|
|
style={{
|
|
position: 'absolute',
|
|
bottom: 0,
|
|
left: 0,
|
|
right: 0,
|
|
backgroundColor: 'rgba(16, 185, 129, 0.95)',
|
|
color: '#fff',
|
|
padding: '0.85rem 1.25rem',
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
justifyContent: 'space-between',
|
|
}}
|
|
>
|
|
<div>
|
|
<div style={{ fontSize: '0.8rem', fontWeight: 700, textTransform: 'uppercase' }}>
|
|
✓ Documento Detectado con Éxito
|
|
</div>
|
|
<div style={{ fontSize: '1.15rem', fontWeight: 800 }}>
|
|
{detectedData.apellido}, {detectedData.nombre}
|
|
</div>
|
|
<div style={{ fontSize: '0.9rem', opacity: 0.95 }}>
|
|
DNI: <strong>{detectedData.documento}</strong> · Sexo: {detectedData.sexo}
|
|
</div>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
onClick={handleConfirmDni}
|
|
className="btn"
|
|
style={{
|
|
backgroundColor: '#fff',
|
|
color: '#065f46',
|
|
fontWeight: 800,
|
|
padding: '0.6rem 1.25rem',
|
|
fontSize: '1rem',
|
|
boxShadow: 'var(--shadow-md)',
|
|
}}
|
|
>
|
|
✓ CONFIRMAR
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* VISTA 3: Cámara bloqueada / no disponible */}
|
|
{!hasCamera && step === 'PREVIEW' && (
|
|
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-secondary)', maxWidth: '480px' }}>
|
|
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
|
|
<p style={{ fontWeight: 700, color: 'var(--text-primary)', margin: 0, fontSize: '1.1rem' }}>
|
|
Cámara en vivo no disponible
|
|
</p>
|
|
<p style={{ fontSize: '0.85rem', marginTop: '0.5rem', color: 'var(--text-secondary)' }}>
|
|
{insecureContextWarning
|
|
? 'En red local sin HTTPS, el navegador restringe el streaming continuo. Utilice el botón "📸 Capturar con App de Cámara" que funciona sin restricciones en tablets Android.'
|
|
: 'Puede tomar una foto utilizando la app nativa o subir un archivo de imagen.'}
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Mensajes de Advertencia o Error */}
|
|
{errorMsg && (
|
|
<div
|
|
style={{
|
|
padding: '0.85rem 1.25rem',
|
|
backgroundColor: 'var(--status-danger-bg)',
|
|
color: 'var(--status-danger)',
|
|
fontSize: '0.88rem',
|
|
fontWeight: 700,
|
|
borderBottom: '1px solid var(--status-danger)',
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
gap: '0.65rem',
|
|
}}
|
|
>
|
|
<span style={{ fontSize: '1.15rem' }}>⚠️</span>
|
|
<span style={{ flex: 1, lineHeight: 1.35 }}>{errorMsg}</span>
|
|
</div>
|
|
)}
|
|
|
|
{/* Barra de Acciones y Controles Táctiles (Samsung Tablet Ergonomics) */}
|
|
<div
|
|
style={{
|
|
padding: '1rem',
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
gap: '0.75rem',
|
|
backgroundColor: 'var(--bg-surface)',
|
|
borderTop: '1px solid var(--border-subtle)',
|
|
}}
|
|
>
|
|
{/* Selector de cámara si hay más de 1 lente */}
|
|
{step === 'PREVIEW' && availableDevices.length > 1 && (
|
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 700 }}>LENTE:</span>
|
|
<select
|
|
className="input-touch"
|
|
value={selectedDeviceId}
|
|
onChange={(e) => setSelectedDeviceId(e.target.value)}
|
|
style={{ flex: 1, minHeight: '38px', fontSize: '0.85rem' }}
|
|
>
|
|
<option value="">(Cámara Trasera / Automática)</option>
|
|
{availableDevices.map((d, idx) => (
|
|
<option key={d.deviceId || idx} value={d.deviceId}>
|
|
{d.label || `Lente ${idx + 1}`}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
|
|
{/* Selector de archivo oculto para captura nativa */}
|
|
<input
|
|
type="file"
|
|
ref={fileInputRef}
|
|
accept="image/*"
|
|
capture="environment"
|
|
onChange={handlePhotoUploaded}
|
|
style={{ display: 'none' }}
|
|
/>
|
|
|
|
{/* BOTONES PRINCIPALES DE ACCIÓN */}
|
|
<div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
|
|
{step === 'PREVIEW' ? (
|
|
<>
|
|
{/* Botón Principal: TOMAR FOTO */}
|
|
<button
|
|
type="button"
|
|
className="btn"
|
|
onClick={handleCapturePhoto}
|
|
style={{
|
|
flex: 2,
|
|
minHeight: '54px',
|
|
fontSize: '1.1rem',
|
|
fontWeight: 800,
|
|
backgroundColor: 'var(--accent-primary)',
|
|
color: '#fff',
|
|
borderRadius: 'var(--radius-md)',
|
|
boxShadow: 'var(--shadow-md)',
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
gap: '0.5rem',
|
|
}}
|
|
title="Toma la foto y realiza el escaneo automático de PDF417 y QR DNI 2026"
|
|
>
|
|
<span>📸</span> TOMAR FOTO Y ESCANEAR
|
|
</button>
|
|
|
|
{supportsTorch && (
|
|
<button
|
|
type="button"
|
|
className="btn btn-secondary"
|
|
onClick={toggleTorch}
|
|
style={{ minHeight: '54px', minWidth: '54px', padding: '0 0.85rem' }}
|
|
title="Encender o apagar luz"
|
|
>
|
|
{torchEnabled ? '🔦 Apagar' : '💡 Linterna'}
|
|
</button>
|
|
)}
|
|
|
|
<button
|
|
type="button"
|
|
className="btn btn-secondary"
|
|
onClick={handleCapacitorPhoto}
|
|
style={{ minHeight: '54px', padding: '0 1rem', fontSize: '0.9rem' }}
|
|
title="Tomar foto con app nativa de cámara o subir archivo"
|
|
>
|
|
📸 Cámara App / Galería
|
|
</button>
|
|
</>
|
|
) : step === 'SUCCESS' ? (
|
|
<>
|
|
<button
|
|
type="button"
|
|
className="btn"
|
|
onClick={handleConfirmDni}
|
|
style={{
|
|
flex: 2,
|
|
minHeight: '54px',
|
|
fontSize: '1.1rem',
|
|
fontWeight: 800,
|
|
backgroundColor: 'var(--status-success)',
|
|
color: '#fff',
|
|
}}
|
|
>
|
|
✓ APLICAR DATOS AL FORMULARIO
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="btn btn-secondary"
|
|
onClick={handleRetake}
|
|
style={{ flex: 1, minHeight: '54px', fontWeight: 600 }}
|
|
>
|
|
🔄 Tomar Otra Foto
|
|
</button>
|
|
</>
|
|
) : (
|
|
/* ESTADO FAILED O ANALYZING */
|
|
<>
|
|
<button
|
|
type="button"
|
|
className="btn"
|
|
onClick={handleRetake}
|
|
disabled={step === 'ANALYZING'}
|
|
style={{
|
|
flex: 2,
|
|
minHeight: '54px',
|
|
fontSize: '1.05rem',
|
|
fontWeight: 700,
|
|
backgroundColor: 'var(--accent-primary)',
|
|
color: '#fff',
|
|
}}
|
|
>
|
|
🔄 TOMAR OTRA FOTO
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="btn btn-secondary"
|
|
onClick={() => fileInputRef.current?.click()}
|
|
style={{ flex: 1, minHeight: '54px', fontWeight: 600 }}
|
|
>
|
|
📁 Subir Archivo
|
|
</button>
|
|
</>
|
|
)}
|
|
|
|
<button
|
|
type="button"
|
|
className="btn btn-secondary"
|
|
onClick={() => {
|
|
stopCamera();
|
|
onClose();
|
|
}}
|
|
style={{ minHeight: '54px', padding: '0 1.25rem', fontWeight: 600 }}
|
|
>
|
|
Cancelar
|
|
</button>
|
|
</div>
|
|
|
|
{/* Formulario de Carga Manual / Pegar Texto */}
|
|
<form onSubmit={handleManualSubmit} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem' }}>
|
|
<input
|
|
type="text"
|
|
className="input-touch"
|
|
placeholder="Escriba el N° de DNI o pegue el código del documento..."
|
|
value={manualText}
|
|
onChange={(e) => setManualText(e.target.value)}
|
|
style={{ flex: 1, fontSize: '0.9rem', minHeight: '44px' }}
|
|
/>
|
|
<button
|
|
type="submit"
|
|
className="btn btn-secondary"
|
|
disabled={!manualText.trim() || step === 'ANALYZING'}
|
|
style={{ minHeight: '44px', padding: '0 1.25rem', fontWeight: 700 }}
|
|
>
|
|
Cargar
|
|
</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|