feat: complete Phases 2 to 5 inclusive - Access Core, Web Cockpit, Hardware enqueuing, Optical Scanner and QA (v0.5.0-beta)

This commit is contained in:
Carlos Tello
2026-10-13 15:47:43 -03:00
parent 78c1a306de
commit 1ba74f7929
53 changed files with 4000 additions and 279 deletions
@@ -0,0 +1,373 @@
// ==============================================================================
// 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
// ==============================================================================
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { accessApi } from '../../api/accessApi';
import { DNIParsedResult } from '../../types';
interface CameraScannerModalProps {
isOpen: boolean;
onClose: () => void;
onScanSuccess: (data: DNIParsedResult) => void;
}
export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
isOpen,
onClose,
onScanSuccess,
}) => {
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const intervalRef = useRef<number | null>(null);
const [hasCamera, setHasCamera] = useState<boolean>(true);
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 stopCamera = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
if (streamRef.current) {
streamRef.current.getTracks().forEach((track) => {
track.stop();
});
streamRef.current = null;
}
if (videoRef.current) {
videoRef.current.srcObject = null;
}
}, []);
const handleDecodedString = useCallback(
async (rawText: string) => {
if (isProcessing || !rawText) return;
setIsProcessing(true);
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.');
}
} catch (err: any) {
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
} finally {
setIsProcessing(false);
}
},
[isProcessing, stopCamera, onScanSuccess, onClose]
);
const startCamera = useCallback(async () => {
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,
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
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);
}
// 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);
}
}
} 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.');
}
}, [handleDecodedString, isProcessing]);
useEffect(() => {
if (isOpen) {
startCamera();
} else {
stopCamera();
}
return () => {
stopCamera();
};
}, [isOpen, startCamera, stopCamera]);
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 {
// Ignorar si el dispositivo rechaza el comando
}
};
const handleManualSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (manualText.trim()) {
handleDecodedString(manualText.trim());
}
};
if (!isOpen) return null;
return (
<div
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.85)',
zIndex: 9999,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: '1rem',
}}
>
<div
style={{
width: '100%',
maxWidth: '640px',
backgroundColor: 'var(--bg-surface)',
borderRadius: 'var(--radius-lg)',
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: '1rem 1.25rem',
borderBottom: '1px solid var(--border-subtle)',
backgroundColor: 'var(--bg-card)',
}}
>
<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>
<button
onClick={() => {
stopCamera();
onClose();
}}
style={{
background: 'transparent',
border: 'none',
fontSize: '1.5rem',
color: 'var(--text-muted)',
cursor: 'pointer',
padding: '0.25rem 0.5rem',
}}
title="Cerrar"
>
✕
</button>
</div>
{/* Visor de Video de la Cámara */}
<div
style={{
position: 'relative',
width: '100%',
height: '320px',
backgroundColor: '#000',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
}}
>
{hasCamera ? (
<>
<video
ref={videoRef}
playsInline
muted
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
{/* Marco Guía de Escaneo */}
<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)',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
style={{
backgroundColor: 'rgba(0, 0, 0, 0.7)',
color: '#fff',
padding: '0.25rem 0.75rem',
borderRadius: '4px',
fontSize: '0.8rem',
}}
>
Ubique el código de barras 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>
)}
{isProcessing && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.6)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontSize: '1rem',
fontWeight: 600,
}}
>
⏳ Interpretando datos de identidad...
</div>
)}
</div>
{/* Mensaje de error si ocurre */}
{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)',
}}
>
⚠️ {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' }}>
{supportsTorch && (
<button
type="button"
className="btn btn-secondary"
onClick={toggleTorch}
style={{ flex: 1, minHeight: '48px' }}
>
{torchEnabled ? '🔦 Apagar Linterna' : '💡 Encender Linterna'}
</button>
)}
<button
type="button"
className="btn btn-secondary"
onClick={() => {
stopCamera();
onClose();
}}
style={{ flex: 1, minHeight: '48px' }}
>
Cancelar
</button>
</div>
{/* Formulario alternativo de carga manual de texto crudo */}
<form onSubmit={handleManualSubmit} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
<input
type="text"
className="input-touch"
placeholder="Pegar o escribir código DNI o número..."
value={manualText}
onChange={(e) => setManualText(e.target.value)}
style={{ flex: 1, fontSize: '0.9rem' }}
/>
<button
type="submit"
className="btn btn-primary"
disabled={!manualText.trim() || isProcessing}
style={{ minHeight: '48px', padding: '0 1rem' }}
>
Procesar
</button>
</form>
</div>
</div>
</div>
);
};