From f9454dbe091b3b3be6c228043fd5e86ef2b9630a Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 4 Oct 2026 17:33:16 -0600 Subject: [PATCH] fix: solucion integral de activacion de camara QR con deteccion HTTPS, resilencia iOS/Safari y fallback de foto nativa --- public/index.html | 34 ++++++-- public/js/app.js | 200 +++++++++++++++++++++++++++++++++++++++++----- public/js/pos.js | 193 +++++++++++++++++++++++++++++++++++++++----- public/pos.html | 31 +++++-- server/server.js | 8 ++ 5 files changed, 412 insertions(+), 54 deletions(-) diff --git a/public/index.html b/public/index.html index 7e8ec97..2bf8a8e 100644 --- a/public/index.html +++ b/public/index.html @@ -16,6 +16,16 @@
+ + +
@@ -268,19 +278,29 @@
-
- +
+
- + +
+ +
+
O selecciona a un compañero para transferirle:
diff --git a/public/js/app.js b/public/js/app.js index 9e08cb2..25321e5 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -8,8 +8,42 @@ let activeCategoryId = null; let cart = []; let currentAppMode = 'kids'; +let CLOUDFLARE_TUNNEL_URL = 'https://somewhat-ships-looksmart-optical.trycloudflare.com'; + +function checkHttpsEnvironment() { + const isHttp = window.location.protocol !== 'https:' && + window.location.hostname !== 'localhost' && + window.location.hostname !== '127.0.0.1'; + + if (isHttp) { + const banner = document.getElementById('bannerHttpsWarning'); + if (banner) { + banner.style.display = 'block'; + const link = document.getElementById('linkHttpsRedirect'); + if (link) { + link.href = CLOUDFLARE_TUNNEL_URL + window.location.pathname; + } + } + } + + fetch('/api/server-info') + .then(r => r.json()) + .then(info => { + if (info && info.tunnelUrl) { + CLOUDFLARE_TUNNEL_URL = info.tunnelUrl; + const link = document.getElementById('linkHttpsRedirect'); + if (link && isHttp) { + link.href = CLOUDFLARE_TUNNEL_URL + window.location.pathname; + } + } + }) + .catch(() => {}); +} + // Inicialización al cargar la página document.addEventListener('DOMContentLoaded', async () => { + checkHttpsEnvironment(); + // Registrar Service Worker para PWA si está soportado if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(err => console.log('SW error:', err)); @@ -480,7 +514,6 @@ function openTransferModal() { document.getElementById('modalTransfer').style.display = 'flex'; resetTransferScan(); renderQuickTransferFriends(); - startTransferCamera(); } function closeTransferModal(e) { @@ -551,6 +584,8 @@ async function startTransferCamera(isUserAction = false) { const video = document.getElementById('transferVideo'); const status = document.getElementById('transferCameraStatus'); const helpOverlay = document.getElementById('transferCameraHelp'); + const helpText = document.getElementById('transferCameraHelpText'); + const actionContainer = document.getElementById('transferCameraActionContainer'); const retryBtn = document.getElementById('btnRetryTransferCamera'); const flipBtn = document.getElementById('btnFlipTransferCamera'); @@ -558,34 +593,86 @@ async function startTransferCamera(isUserAction = false) { stopTransferCamera(); - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - if (status) status.textContent = '⚠️ Cámara requiere HTTPS'; + const isHttp = window.location.protocol !== 'https:' && + window.location.hostname !== 'localhost' && + window.location.hostname !== '127.0.0.1'; + + // Si no hay soporte de getUserMedia o estamos en HTTP inseguro + if (isHttp || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { + if (status) status.textContent = '⚠️ Requiere HTTPS'; if (helpOverlay) { helpOverlay.style.display = 'flex'; - document.getElementById('transferCameraHelpText').textContent = '⚠️ Los navegadores bloquean la cámara si no es HTTPS. Usa el enlace seguro o toca directamente a tu amigo abajo.'; + if (helpText) { + helpText.innerHTML = ` +
⚠️ Cámara requiere HTTPS
+ Por seguridad, los navegadores en celulares bloquean la cámara si la conexión no es HTTPS. Toca el botón para abrir la app segura: + `; + } + if (actionContainer) { + actionContainer.innerHTML = ` + + `; + } } return; } + // Si estamos en un contexto seguro HTTPS: try { if (status) status.textContent = 'Conectando cámara...'; + if (helpOverlay) helpOverlay.style.display = 'none'; - try { - transferVideoStream = await navigator.mediaDevices.getUserMedia({ - video: { facingMode: { ideal: transferFacingMode }, width: { ideal: 720 } }, - audio: false - }); - } catch (err1) { - // Fallback a cualquier lente disponible - transferVideoStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); + // Propiedades obligatorias para iOS Safari WebKit y Chrome Android + video.muted = true; + video.playsInline = true; + video.setAttribute('playsinline', 'true'); + video.setAttribute('webkit-playsinline', 'true'); + video.setAttribute('autoplay', 'true'); + + // Intentar abrir cámara con fallbacks progresivos + const constraintConfigs = [ + { video: { facingMode: { ideal: transferFacingMode }, width: { ideal: 1280 } }, audio: false }, + { video: { facingMode: { ideal: transferFacingMode } }, audio: false }, + { video: { facingMode: transferFacingMode }, audio: false }, + { video: true, audio: false } + ]; + + let stream = null; + let lastError = null; + + for (const c of constraintConfigs) { + try { + stream = await navigator.mediaDevices.getUserMedia(c); + if (stream) break; + } catch (errAttempt) { + lastError = errAttempt; + } } - video.setAttribute('playsinline', 'true'); - video.setAttribute('autoplay', 'true'); - video.muted = true; - video.srcObject = transferVideoStream; + if (!stream) { + throw lastError || new Error('No se pudo acceder al lente de la cámara'); + } - await video.play(); + transferVideoStream = stream; + video.srcObject = stream; + + // Esperar a que el elemento video esté listo para reproducir (evita AbortError en Safari) + await new Promise((resolve) => { + if (video.readyState >= 1) { + resolve(); + } else { + video.onloadedmetadata = () => resolve(); + setTimeout(resolve, 800); + } + }); + + try { + await video.play(); + } catch (playErr) { + console.warn('Reproducción diferida:', playErr); + } if (status) status.textContent = '🟢 Escaneando QR...'; if (helpOverlay) helpOverlay.style.display = 'none'; @@ -594,17 +681,90 @@ async function startTransferCamera(isUserAction = false) { isTransferScanning = true; startTransferQrDetection(video); + } catch (err) { - console.warn('Error iniciando cámara de transferencia:', err); - if (status) status.textContent = '⚪ Cámara inactiva'; + console.warn('Error accediendo a cámara:', err); + let userMsg = 'Toca el botón para permitir el uso de la cámara.'; + const errName = err.name || ''; + + if (errName === 'NotAllowedError' || errName === 'PermissionDeniedError') { + userMsg = '🔒 Permiso denegado: El navegador bloqueó la cámara. Toca el candado o configuración junto a la barra de dirección y habilita la Cámara.'; + } else if (errName === 'NotFoundError' || errName === 'DevicesNotFoundError') { + userMsg = '📷 No se detectó ninguna cámara física en este dispositivo.'; + } else if (errName === 'NotReadableError' || errName === 'TrackStartError') { + userMsg = '⚠️ La cámara está ocupada por otra app (WhatsApp, etc). Ciérrala e intenta de nuevo.'; + } else if (errName === 'OverconstrainedError') { + userMsg = '⚠️ Tu cámara no admite la resolución solicitada.'; + } + + if (status) status.textContent = '⚠️ Cámara bloqueada'; if (helpOverlay) { helpOverlay.style.display = 'flex'; - document.getElementById('transferCameraHelpText').textContent = 'Toca Permitir Cámara o activa los permisos en la barra del navegador.'; + if (helpText) { + helpText.innerHTML = ` +
⚠️ Permiso Requerido
+ ${userMsg} + `; + } + if (actionContainer) { + actionContainer.innerHTML = ` + + `; + } } if (retryBtn) retryBtn.style.display = 'inline-block'; } } +function handleTransferQrPhoto(event) { + const file = event.target.files && event.target.files[0]; + if (!file) return; + + const status = document.getElementById('transferCameraStatus'); + if (status) status.textContent = 'Analizando foto...'; + + const reader = new FileReader(); + reader.onload = function(e) { + const img = new Image(); + img.onload = function() { + const canvas = document.createElement('canvas'); + const maxDim = 1200; + let w = img.width; + let h = img.height; + if (w > maxDim || h > maxDim) { + if (w > h) { + h = Math.round((h * maxDim) / w); + w = maxDim; + } else { + w = Math.round((w * maxDim) / h); + h = maxDim; + } + } + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0, w, h); + const imgData = ctx.getImageData(0, 0, w, h); + + if (window.jsQR) { + const code = window.jsQR(imgData.data, w, h, { + inversionAttempts: 'attemptBoth' + }); + if (code && code.data) { + fetchStudentByScannedQr(code.data); + return; + } + } + if (status) status.textContent = '❌ No se detectó QR'; + alert('⚠️ No se detectó ningún código QR en la foto. Intenta tomarla más de cerca con buena iluminación.'); + }; + img.src = e.target.result; + }; + reader.readAsDataURL(file); +} + function flipTransferCamera() { transferFacingMode = transferFacingMode === 'environment' ? 'user' : 'environment'; startTransferCamera(true); diff --git a/public/js/pos.js b/public/js/pos.js index ac8dfe7..01d6684 100644 --- a/public/js/pos.js +++ b/public/js/pos.js @@ -8,8 +8,40 @@ let currentTab = 'mostrador'; let sseSource = null; let videoStream = null; let isScanningActive = true; +let CLOUDFLARE_TUNNEL_URL = 'https://somewhat-ships-looksmart-optical.trycloudflare.com'; + +function checkPosHttpsEnvironment() { + const isHttp = window.location.protocol !== 'https:' && + window.location.hostname !== 'localhost' && + window.location.hostname !== '127.0.0.1'; + + if (isHttp) { + const banner = document.getElementById('posBannerHttpsWarning'); + if (banner) { + banner.style.display = 'block'; + const link = document.getElementById('posLinkHttpsRedirect'); + if (link) { + link.href = CLOUDFLARE_TUNNEL_URL + window.location.pathname; + } + } + } + + fetch('/api/server-info') + .then(r => r.json()) + .then(info => { + if (info && info.tunnelUrl) { + CLOUDFLARE_TUNNEL_URL = info.tunnelUrl; + const link = document.getElementById('posLinkHttpsRedirect'); + if (link && isHttp) { + link.href = CLOUDFLARE_TUNNEL_URL + window.location.pathname; + } + } + }) + .catch(() => {}); +} document.addEventListener('DOMContentLoaded', async () => { + checkPosHttpsEnvironment(); await loadCatalog(); await loadPreOrders(); initCamera(); @@ -147,6 +179,8 @@ async function initCamera(isUserAction = false) { const video = document.getElementById('scannerVideo'); const status = document.getElementById('cameraStatus'); const overlay = document.getElementById('cameraHelpOverlay'); + const helpText = document.getElementById('cameraHelpText'); + const actionContainer = document.getElementById('posCameraActionContainer'); const retryBtn = document.getElementById('btnRetryPosCamera'); const flipBtn = document.getElementById('btnFlipPosCamera'); @@ -155,35 +189,83 @@ async function initCamera(isUserAction = false) { videoStream = null; } - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - status.textContent = '⚠️ Requiere HTTPS'; + const isHttp = window.location.protocol !== 'https:' && + window.location.hostname !== 'localhost' && + window.location.hostname !== '127.0.0.1'; + + if (isHttp || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { + if (status) status.textContent = '⚠️ Requiere HTTPS'; if (overlay) { overlay.style.display = 'flex'; - document.getElementById('cameraHelpText').textContent = '⚠️ Para usar la cámara en dispositivos remotos se requiere conexión segura HTTPS. Puedes usar los botones de prueba abajo.'; + if (helpText) { + helpText.innerHTML = ` +
⚠️ Cámara requiere HTTPS
+ Para acceder a la cámara en vivo en dispositivos remotos o celulares se requiere conexión segura HTTPS. Toca el botón para abrir la terminal segura: + `; + } + if (actionContainer) { + actionContainer.innerHTML = ` + + `; + } } return; } try { - status.textContent = 'Conectando lente...'; - try { - videoStream = await navigator.mediaDevices.getUserMedia({ - video: { facingMode: { ideal: posFacingMode }, width: { ideal: 1280 } }, - audio: false - }); - } catch (err1) { - // Fallback a cualquier cámara disponible - videoStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); + if (status) status.textContent = 'Conectando cámara...'; + if (overlay) overlay.style.display = 'none'; + + video.muted = true; + video.playsInline = true; + video.setAttribute('playsinline', 'true'); + video.setAttribute('webkit-playsinline', 'true'); + video.setAttribute('autoplay', 'true'); + + const constraintConfigs = [ + { video: { facingMode: { ideal: posFacingMode }, width: { ideal: 1280 } }, audio: false }, + { video: { facingMode: { ideal: posFacingMode } }, audio: false }, + { video: { facingMode: posFacingMode }, audio: false }, + { video: true, audio: false } + ]; + + let stream = null; + let lastError = null; + + for (const c of constraintConfigs) { + try { + stream = await navigator.mediaDevices.getUserMedia(c); + if (stream) break; + } catch (errAttempt) { + lastError = errAttempt; + } } - video.setAttribute('playsinline', 'true'); - video.setAttribute('autoplay', 'true'); - video.muted = true; - video.srcObject = videoStream; + if (!stream) { + throw lastError || new Error('No se pudo acceder a la cámara'); + } - await video.play(); + videoStream = stream; + video.srcObject = stream; - status.textContent = '🟢 Escáner activo'; + await new Promise((resolve) => { + if (video.readyState >= 1) { + resolve(); + } else { + video.onloadedmetadata = () => resolve(); + setTimeout(resolve, 800); + } + }); + + try { + await video.play(); + } catch (playErr) { + console.warn('Reproducción diferida de cámara POS:', playErr); + } + + if (status) status.textContent = '🟢 Escáner activo'; if (overlay) overlay.style.display = 'none'; if (retryBtn) retryBtn.style.display = 'none'; if (flipBtn) flipBtn.style.display = 'inline-block'; @@ -191,15 +273,86 @@ async function initCamera(isUserAction = false) { startUniversalQrDetection(video); } catch (err) { console.warn('Error accediendo a cámara:', err); - status.textContent = '⚪ Cámara inactiva'; + let userMsg = 'Toca el botón para permitir el uso de la cámara.'; + const errName = err.name || ''; + + if (errName === 'NotAllowedError' || errName === 'PermissionDeniedError') { + userMsg = '🔒 Permiso denegado: El navegador bloqueó la cámara. Habilita el permiso de cámara en la barra de direcciones.'; + } else if (errName === 'NotFoundError' || errName === 'DevicesNotFoundError') { + userMsg = '📷 No se detectó ninguna cámara disponible.'; + } else if (errName === 'NotReadableError' || errName === 'TrackStartError') { + userMsg = '⚠️ La cámara está ocupada por otra app. Ciérrala e intenta de nuevo.'; + } + + if (status) status.textContent = '⚪ Cámara inactiva'; if (overlay) { overlay.style.display = 'flex'; - document.getElementById('cameraHelpText').textContent = 'Toca Permitir Cámara o habilita los permisos en la barra de direcciones.'; + if (helpText) { + helpText.innerHTML = ` +
⚠️ Permiso Requerido
+ ${userMsg} + `; + } + if (actionContainer) { + actionContainer.innerHTML = ` + + `; + } } if (retryBtn) retryBtn.style.display = 'inline-block'; } } +function handlePosQrPhoto(event) { + const file = event.target.files && event.target.files[0]; + if (!file) return; + + const status = document.getElementById('cameraStatus'); + if (status) status.textContent = 'Analizando foto...'; + + const reader = new FileReader(); + reader.onload = function(e) { + const img = new Image(); + img.onload = function() { + const canvas = document.createElement('canvas'); + const maxDim = 1200; + let w = img.width; + let h = img.height; + if (w > maxDim || h > maxDim) { + if (w > h) { + h = Math.round((h * maxDim) / w); + w = maxDim; + } else { + w = Math.round((w * maxDim) / h); + h = maxDim; + } + } + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0, w, h); + const imgData = ctx.getImageData(0, 0, w, h); + + if (window.jsQR) { + const code = window.jsQR(imgData.data, w, h, { + inversionAttempts: 'attemptBoth' + }); + if (code && code.data) { + onQrCodeDetected(code.data); + if (status) status.textContent = '🟢 QR Reconocido'; + return; + } + } + if (status) status.textContent = '❌ No detectado'; + alert('⚠️ No se detectó un código QR válido en la foto tomada.'); + }; + img.src = e.target.result; + }; + reader.readAsDataURL(file); +} + function flipPosCamera() { posFacingMode = posFacingMode === 'environment' ? 'user' : 'environment'; initCamera(true); diff --git a/public/pos.html b/public/pos.html index f80c52e..9213c64 100644 --- a/public/pos.html +++ b/public/pos.html @@ -29,9 +29,16 @@ .status-listo { background: #dcfce7; color: #166534; } .status-entregado { background: #f1f5f9; color: #64748b; } - + +
+
@@ -109,17 +116,27 @@
- +
- + +
+ +
+
Prueba rápida de escaneo de carné: diff --git a/server/server.js b/server/server.js index 8c9b0b5..0ef522c 100644 --- a/server/server.js +++ b/server/server.js @@ -404,6 +404,14 @@ app.post('/api/ordenes/despachar-qr', (req, res) => { } }); +// Información de conectividad y túnel HTTPS +app.get('/api/server-info', (req, res) => { + res.json({ + tunnelUrl: process.env.TUNNEL_URL || 'https://somewhat-ships-looksmart-optical.trycloudflare.com', + httpsAvailable: true + }); +}); + // Iniciar servidor app.listen(PORT, () => { console.log(`🚀 Servidor RecreoPay iniciado en http://localhost:${PORT}`);