fix(pos): camara bajo demanda y apagado automatico inmediato al escanear qr

This commit is contained in:
unknown
2026-10-04 21:38:17 -06:00
parent 97c13f184e
commit bc38673296
2 changed files with 228 additions and 206 deletions
+152 -117
View File
@@ -78,7 +78,7 @@ document.addEventListener('DOMContentLoaded', async () => {
checkPosHttpsEnvironment(); checkPosHttpsEnvironment();
await loadCatalog(); await loadCatalog();
await loadPreOrders(); await loadPreOrders();
initCamera(); // La cámara se activa bajo demanda al cobrar o identificar, NO al entrar
initSSE(); initSSE();
initPistolScanner(); initPistolScanner();
}); });
@@ -232,43 +232,42 @@ function clearPosCart() {
// ========================================== // ==========================================
let posFacingMode = 'environment'; let posFacingMode = 'environment';
let posQrScanningInterval = null; // ==========================================
let posCanvas = null; // CÁMARA Y ESCÁNER QR BAJO DEMANDA (EN MODAL)
let posCanvasCtx = null; // ==========================================
let posModalMode = 'cobro'; // 'cobro' | 'identificar' | 'preorden'
let modalVideoStream = null;
let modalQrScanningInterval = null;
let isModalScanningActive = false;
let modalCanvas = null;
let modalCanvasCtx = null;
let lastScannedToken = null; let lastScannedToken = null;
let lastScannedTime = 0; let lastScannedTime = 0;
async function initCamera(isUserAction = false) { async function startModalCamera(isUserAction = false) {
const video = document.getElementById('scannerVideo'); const video = document.getElementById('modalScannerVideo');
const status = document.getElementById('cameraStatus'); const badge = document.getElementById('modalCameraStatusBadge');
const overlay = document.getElementById('cameraHelpOverlay'); const overlay = document.getElementById('modalCameraOverlay');
const helpText = document.getElementById('cameraHelpText'); const helpText = document.getElementById('modalCameraHelpText');
const actionContainer = document.getElementById('posCameraActionContainer');
const retryBtn = document.getElementById('btnRetryPosCamera');
const flipBtn = document.getElementById('btnFlipPosCamera');
if (videoStream) { stopModalCamera();
videoStream.getTracks().forEach(t => t.stop());
videoStream = null; if (!video) return;
}
const isHttp = window.location.protocol !== 'https:' && const isHttp = window.location.protocol !== 'https:' &&
window.location.hostname !== 'localhost' && window.location.hostname !== 'localhost' &&
window.location.hostname !== '127.0.0.1'; window.location.hostname !== '127.0.0.1';
if (isHttp || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { if (isHttp || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
if (status) status.textContent = '⚠️ Requiere HTTPS'; if (badge) badge.textContent = '⚠️ Requiere HTTPS';
if (overlay) { if (overlay) {
overlay.style.display = 'flex'; overlay.style.display = 'flex';
if (helpText) { if (helpText) {
helpText.innerHTML = ` helpText.innerHTML = `
<div style="font-weight: 800; color: #fca5a5; font-size: 0.85rem; margin-bottom: 4px;">⚠️ Cámara requiere HTTPS</div> <div style="font-weight: 800; color: #fca5a5; font-size: 0.85rem; margin-bottom: 4px;">⚠️ Cámara requiere HTTPS</div>
<span style="font-size: 0.74rem; color: #cbd5e1;">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:</span> <span style="font-size: 0.74rem; color: #cbd5e1;">Para acceder a la cámara en vivo en dispositivos remotos o celulares se requiere conexión segura HTTPS. Toca el botón:</span>
`; <button type="button" onclick="window.location.href='${CLOUDFLARE_TUNNEL_URL}' + window.location.pathname" style="margin-top: 8px; padding: 8px 14px; background: #10b981; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.8rem; cursor: pointer;">
}
if (actionContainer) {
actionContainer.innerHTML = `
<button type="button" onclick="window.location.href='${CLOUDFLARE_TUNNEL_URL}' + window.location.pathname" style="padding: 10px 16px; background: #10b981; color: white; border: none; border-radius: 10px; font-weight: 900; font-size: 0.84rem; cursor: pointer; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);">
🚀 Cambiar a HTTPS Seguro 🚀 Cambiar a HTTPS Seguro
</button> </button>
`; `;
@@ -278,7 +277,12 @@ async function initCamera(isUserAction = false) {
} }
try { try {
if (status) status.textContent = 'Conectando cámara...'; if (badge) {
badge.textContent = '📷 Conectando cámara...';
badge.style.background = 'rgba(15, 23, 42, 0.92)';
badge.style.borderColor = '#0284c7';
badge.style.color = '#38bdf8';
}
if (overlay) overlay.style.display = 'none'; if (overlay) overlay.style.display = 'none';
video.muted = true; video.muted = true;
@@ -310,7 +314,7 @@ async function initCamera(isUserAction = false) {
throw lastError || new Error('No se pudo acceder a la cámara'); throw lastError || new Error('No se pudo acceder a la cámara');
} }
videoStream = stream; modalVideoStream = stream;
video.srcObject = stream; video.srcObject = stream;
await new Promise((resolve) => { await new Promise((resolve) => {
@@ -328,26 +332,24 @@ async function initCamera(isUserAction = false) {
console.warn('Reproducción diferida de cámara POS:', playErr); console.warn('Reproducción diferida de cámara POS:', playErr);
} }
if (status) status.textContent = '🟢 Escáner activo'; if (badge) badge.textContent = '📷 Apunta el carné a la cámara o dispara pistola';
if (overlay) overlay.style.display = 'none'; if (overlay) overlay.style.display = 'none';
if (retryBtn) retryBtn.style.display = 'none';
if (flipBtn) flipBtn.style.display = 'inline-block';
startUniversalQrDetection(video); startModalQrDetection(video);
} catch (err) { } catch (err) {
console.warn('Error accediendo a cámara:', err); console.warn('Error accediendo a cámara modal:', err);
let userMsg = 'Toca el botón para permitir el uso de la cámara.'; let userMsg = 'Toca el botón para permitir el uso de la cámara.';
const errName = err.name || ''; const errName = err.name || '';
if (errName === 'NotAllowedError' || errName === 'PermissionDeniedError') { 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.'; userMsg = '🔒 Permiso denegado: Habilita el permiso de cámara en la barra de direcciones del navegador.';
} else if (errName === 'NotFoundError' || errName === 'DevicesNotFoundError') { } else if (errName === 'NotFoundError' || errName === 'DevicesNotFoundError') {
userMsg = '📷 No se detectó ninguna cámara disponible.'; userMsg = '📷 No se detectó ninguna cámara disponible en este dispositivo.';
} else if (errName === 'NotReadableError' || errName === 'TrackStartError') { } else if (errName === 'NotReadableError' || errName === 'TrackStartError') {
userMsg = '⚠️ La cámara está ocupada por otra app. Ciérrala e intenta de nuevo.'; userMsg = '⚠️ La cámara está ocupada por otra app. Ciérrala e intenta de nuevo.';
} }
if (status) status.textContent = '⚪ Cámara inactiva'; if (badge) badge.textContent = '⚪ Cámara inactiva';
if (overlay) { if (overlay) {
overlay.style.display = 'flex'; overlay.style.display = 'flex';
if (helpText) { if (helpText) {
@@ -356,87 +358,43 @@ async function initCamera(isUserAction = false) {
<span style="font-size: 0.72rem; color: #f1f5f9;">${userMsg}</span> <span style="font-size: 0.72rem; color: #f1f5f9;">${userMsg}</span>
`; `;
} }
if (actionContainer) {
actionContainer.innerHTML = `
<button type="button" onclick="initCamera(true)" style="padding: 8px 16px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.82rem; cursor: pointer; box-shadow: 0 4px 10px rgba(2, 132, 199, 0.4);">
📷 Tocar para Permitir Cámara
</button>
`;
} }
} }
if (retryBtn) retryBtn.style.display = 'inline-block';
}
} }
function handlePosQrPhoto(event) { function stopModalCamera() {
const file = event.target.files && event.target.files[0]; isModalScanningActive = false;
if (!file) return; if (modalQrScanningInterval) {
cancelAnimationFrame(modalQrScanningInterval);
const status = document.getElementById('cameraStatus'); modalQrScanningInterval = null;
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;
} }
if (modalVideoStream) {
modalVideoStream.getTracks().forEach(t => t.stop());
modalVideoStream = null;
} }
canvas.width = w; const video = document.getElementById('modalScannerVideo');
canvas.height = h; if (video) {
const ctx = canvas.getContext('2d'); video.srcObject = null;
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() { function startModalQrDetection(video) {
posFacingMode = posFacingMode === 'environment' ? 'user' : 'environment'; if (!modalCanvas) {
initCamera(true); modalCanvas = document.createElement('canvas');
} modalCanvasCtx = modalCanvas.getContext('2d', { willReadFrequently: true });
function startUniversalQrDetection(video) {
if (!posCanvas) {
posCanvas = document.createElement('canvas');
posCanvasCtx = posCanvas.getContext('2d', { willReadFrequently: true });
} }
if (posQrScanningInterval) { isModalScanningActive = true;
cancelAnimationFrame(posQrScanningInterval); if (modalQrScanningInterval) {
cancelAnimationFrame(modalQrScanningInterval);
} }
function scanFrame() { function scanFrame() {
if (isScanningActive && video.readyState === video.HAVE_ENOUGH_DATA) { if (isModalScanningActive && video && video.readyState === video.HAVE_ENOUGH_DATA) {
posCanvas.width = video.videoWidth; modalCanvas.width = video.videoWidth;
posCanvas.height = video.videoHeight; modalCanvas.height = video.videoHeight;
posCanvasCtx.drawImage(video, 0, 0, posCanvas.width, posCanvas.height); modalCanvasCtx.drawImage(video, 0, 0, modalCanvas.width, modalCanvas.height);
const imageData = posCanvasCtx.getImageData(0, 0, posCanvas.width, posCanvas.height); const imageData = modalCanvasCtx.getImageData(0, 0, modalCanvas.width, modalCanvas.height);
if (window.jsQR) { if (window.jsQR) {
const code = window.jsQR(imageData.data, imageData.width, imageData.height, { const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
@@ -444,19 +402,21 @@ function startUniversalQrDetection(video) {
}); });
if (code && code.data) { if (code && code.data) {
const now = Date.now(); const now = Date.now();
// Evitar lecturas duplicadas en menos de 2 segundos
if (code.data !== lastScannedToken || (now - lastScannedTime) > 2000) { if (code.data !== lastScannedToken || (now - lastScannedTime) > 2000) {
lastScannedToken = code.data; lastScannedToken = code.data;
lastScannedTime = now; lastScannedTime = now;
onQrCodeDetected(code.data); onQrCodeDetected(code.data);
return; // Detener loop de escaneo inmediatamente
} }
} }
} }
} }
posQrScanningInterval = requestAnimationFrame(scanFrame); if (isModalScanningActive) {
modalQrScanningInterval = requestAnimationFrame(scanFrame);
}
} }
posQrScanningInterval = requestAnimationFrame(scanFrame); modalQrScanningInterval = requestAnimationFrame(scanFrame);
} }
function simulateScan(qrToken) { function simulateScan(qrToken) {
@@ -464,21 +424,34 @@ function simulateScan(qrToken) {
} }
async function onQrCodeDetected(token) { async function onQrCodeDetected(token) {
// 1. APAGAR LA CÁMARA DE INMEDIATO - DEJA DE GRABAR
stopModalCamera();
// 2. Indicador sonoro y visual de lectura correcta
if (window.sounds) window.sounds.playScanChirp(); if (window.sounds) window.sounds.playScanChirp();
// Si estamos en la pestaña de fila rápida de pre-órdenes, despachamos de inmediato const badge = document.getElementById('modalCameraStatusBadge');
if (currentTab === 'preordenes') { if (badge) {
badge.textContent = '✅ ¡QR Detectado Exitosamente!';
badge.style.background = '#065f46';
badge.style.borderColor = '#10b981';
badge.style.color = '#34d399';
}
// Ocultar caja de cámara para que sea evidente que ya terminó de grabar
const camBox = document.getElementById('modalCameraContainer');
if (camBox) {
camBox.style.display = 'none';
}
// 3. Procesar según el modo en el que se abrió el modal
if (posModalMode === 'preorden') {
await dispatchPreOrderExpress(token); await dispatchPreOrderExpress(token);
closePistolaModal();
return; return;
} }
// Si ya hay productos en el carrito, procesar cobro inmediato con este QR if (posModalMode === 'identificar' || posCart.length === 0) {
if (posCart.length > 0) {
await handlePistolBarcodeScan(token);
return;
}
// Si estamos en mostrador sin productos, identificamos al estudiante
try { try {
const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`); const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`);
const data = await res.json(); const data = await res.json();
@@ -486,8 +459,9 @@ async function onQrCodeDetected(token) {
scannedStudent = data; scannedStudent = data;
renderScannedStudent(); renderScannedStudent();
if (window.sounds) window.sounds.playSuccess();
closePistolaModal();
// Si tiene pre-órdenes listas, alertar a la cajera
if (data.preordenes_pendientes && data.preordenes_pendientes.length > 0) { if (data.preordenes_pendientes && data.preordenes_pendientes.length > 0) {
if (confirm(`🔔 ¡Atención! ${data.nombre_completo} tiene ${data.preordenes_pendientes.length} pre-orden lista para retirar. ¿Deseas verla y entregarla ahora?`)) { if (confirm(`🔔 ¡Atención! ${data.nombre_completo} tiene ${data.preordenes_pendientes.length} pre-orden lista para retirar. ¿Deseas verla y entregarla ahora?`)) {
switchPosTab('preordenes'); switchPosTab('preordenes');
@@ -495,17 +469,35 @@ async function onQrCodeDetected(token) {
} }
} catch (err) { } catch (err) {
if (window.sounds) window.sounds.playError(); if (window.sounds) window.sounds.playError();
alert(`QR no reconocido: ${err.message}`); alert(`⚠️ Estudiante no reconocido: ${err.message}`);
resetPistolaModalWaiting();
} }
return;
}
// Modo cobro (posCart.length > 0): Ejecutar cobro inmediato
await handlePistolBarcodeScan(token);
}
function openStudentIdModal() {
openPistolaModal('identificar');
}
function openPreOrderScanModal() {
openPistolaModal('preorden');
} }
function renderScannedStudent() { function renderScannedStudent() {
const placeholder = document.getElementById('posNoStudentPlaceholder');
if (!scannedStudent) { if (!scannedStudent) {
if (placeholder) placeholder.style.display = 'block';
document.getElementById('studentScannedCard').style.display = 'none'; document.getElementById('studentScannedCard').style.display = 'none';
document.getElementById('scannedAllergyAlert').style.display = 'none'; document.getElementById('scannedAllergyAlert').style.display = 'none';
return; return;
} }
if (placeholder) placeholder.style.display = 'none';
document.getElementById('scannedAvatar').src = scannedStudent.foto_url; document.getElementById('scannedAvatar').src = scannedStudent.foto_url;
const btnCobrar = document.getElementById('btnCobrarPos'); const btnCobrar = document.getElementById('btnCobrarPos');
@@ -617,8 +609,10 @@ function initPistolScanner() {
} }
} }
function openPistolaModal() { function openPistolaModal(mode = 'cobro') {
if (posCart.length === 0) { posModalMode = mode;
if (posModalMode === 'cobro' && posCart.length === 0) {
if (window.sounds) window.sounds.playError(); if (window.sounds) window.sounds.playError();
alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.'); alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.');
return; return;
@@ -627,15 +621,38 @@ function openPistolaModal() {
const modal = document.getElementById('modalPistolaCobro'); const modal = document.getElementById('modalPistolaCobro');
if (!modal) return; if (!modal) return;
const totalContainer = document.getElementById('pistolaTotalContainer');
const title = document.getElementById('pistolaModalTitle');
const icon = document.getElementById('pistolaModalIcon');
if (posModalMode === 'cobro') {
const total = posCart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0); const total = posCart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0);
const totalItems = posCart.reduce((sum, item) => sum + item.cantidad, 0); const totalItems = posCart.reduce((sum, item) => sum + item.cantidad, 0);
if (totalContainer) totalContainer.style.display = 'block';
document.getElementById('pistolaModalTotal').textContent = `₡${total.toLocaleString('es-CR')}`; document.getElementById('pistolaModalTotal').textContent = `₡${total.toLocaleString('es-CR')}`;
document.getElementById('pistolaModalItemCount').textContent = `${totalItems} ${totalItems === 1 ? 'producto' : 'productos'} en mostrador`; document.getElementById('pistolaModalItemCount').textContent = `${totalItems} ${totalItems === 1 ? 'producto' : 'productos'} en mostrador`;
if (title) title.textContent = 'Cobro con QR / Pistola';
if (icon) icon.textContent = '💳';
} else if (posModalMode === 'identificar') {
if (totalContainer) totalContainer.style.display = 'none';
if (title) title.textContent = 'Identificar Alumno por QR';
if (icon) icon.textContent = '👤';
} else if (posModalMode === 'preorden') {
if (totalContainer) totalContainer.style.display = 'none';
if (title) title.textContent = 'Despachar Pre-Orden con QR';
if (icon) icon.textContent = '📦';
}
resetPistolaModalWaiting(); resetPistolaModalWaiting();
modal.style.display = 'flex'; modal.style.display = 'flex';
// Mostrar el contenedor de cámara e inicializar stream bajo demanda
const camBox = document.getElementById('modalCameraContainer');
if (camBox) camBox.style.display = 'flex';
startModalCamera();
setTimeout(() => { setTimeout(() => {
const input = document.getElementById('inputPistolaDirectScan'); const input = document.getElementById('inputPistolaDirectScan');
if (input) input.focus(); if (input) input.focus();
@@ -650,6 +667,9 @@ function closePistolaModal(e) {
clearTimeout(pistolaAutoCloseTimer); clearTimeout(pistolaAutoCloseTimer);
pistolaAutoCloseTimer = null; pistolaAutoCloseTimer = null;
} }
// SIEMPRE apagar la cámara de inmediato al salir del modal
stopModalCamera();
const modal = document.getElementById('modalPistolaCobro'); const modal = document.getElementById('modalPistolaCobro');
if (modal) modal.style.display = 'none'; if (modal) modal.style.display = 'none';
} }
@@ -664,6 +684,17 @@ function resetPistolaModalWaiting() {
document.getElementById('pistolaStateSuccess').style.display = 'none'; document.getElementById('pistolaStateSuccess').style.display = 'none';
document.getElementById('pistolaStateError').style.display = 'none'; document.getElementById('pistolaStateError').style.display = 'none';
const camBox = document.getElementById('modalCameraContainer');
if (camBox) camBox.style.display = 'flex';
const badge = document.getElementById('modalCameraStatusBadge');
if (badge) {
badge.textContent = '📷 Apunta el carné a la cámara o dispara pistola';
badge.style.background = 'rgba(15, 23, 42, 0.92)';
badge.style.borderColor = '#0284c7';
badge.style.color = '#38bdf8';
}
const input = document.getElementById('inputPistolaDirectScan'); const input = document.getElementById('inputPistolaDirectScan');
if (input) { if (input) {
input.value = ''; input.value = '';
@@ -675,6 +706,9 @@ async function handlePistolBarcodeScan(rawToken) {
const token = String(rawToken).trim(); const token = String(rawToken).trim();
if (!token) return; if (!token) return;
// Garantizar que la cámara se apague de inmediato
stopModalCamera();
if (window.sounds) window.sounds.playScanChirp(); if (window.sounds) window.sounds.playScanChirp();
// Si no hay productos en el carrito, identificar al alumno para mostrador // Si no hay productos en el carrito, identificar al alumno para mostrador
@@ -687,6 +721,7 @@ async function handlePistolBarcodeScan(rawToken) {
scannedStudent = data; scannedStudent = data;
renderScannedStudent(); renderScannedStudent();
if (window.sounds) window.sounds.playSuccess(); if (window.sounds) window.sounds.playSuccess();
closePistolaModal();
} catch (err) { } catch (err) {
if (window.sounds) window.sounds.playError(); if (window.sounds) window.sounds.playError();
alert(`⚠️ Estudiante no reconocido: ${err.message}`); alert(`⚠️ Estudiante no reconocido: ${err.message}`);
@@ -697,7 +732,7 @@ async function handlePistolBarcodeScan(rawToken) {
// SI HAY PRODUCTOS EN EL CARRITO: EJECUTAR COBRO INMEDIATO CON PISTOLA // SI HAY PRODUCTOS EN EL CARRITO: EJECUTAR COBRO INMEDIATO CON PISTOLA
const modal = document.getElementById('modalPistolaCobro'); const modal = document.getElementById('modalPistolaCobro');
if (modal && modal.style.display === 'none') { if (modal && modal.style.display === 'none') {
openPistolaModal(); modal.style.display = 'flex';
} }
// Mostrar estado de procesamiento // Mostrar estado de procesamiento
+45 -58
View File
@@ -111,15 +111,20 @@
<!-- VISTA 2: FILA RÁPIDA DE PRE-ÓRDENES (RETIRO EN RECREO) --> <!-- VISTA 2: FILA RÁPIDA DE PRE-ÓRDENES (RETIRO EN RECREO) -->
<div id="viewPosPreordenes" style="display: none;"> <div id="viewPosPreordenes" style="display: none;">
<div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 12px 16px; margin-bottom: 14px; display: flex; justify-content: space-between; align-items: center;"> <div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 12px 16px; margin-bottom: 14px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 8px;">
<div> <div>
<strong style="color: #38bdf8; font-size: 0.95rem;">⚡ Despacho Exclusivo Recreo</strong> <strong style="color: #38bdf8; font-size: 0.95rem;">⚡ Despacho Exclusivo Recreo</strong>
<p style="font-size: 0.78rem; color: #94a3b8;">Los estudiantes con pre-orden retiran en 3 segundos escaneando su QR aquí.</p> <p style="font-size: 0.78rem; color: #94a3b8; margin: 2px 0 0 0;">Los estudiantes con pre-orden retiran en 3 segundos escaneando su QR aquí.</p>
</div> </div>
<button onclick="loadPreOrders()" style="background: #334155; border: none; color: white; padding: 6px 12px; border-radius: 8px; font-weight: 700; cursor: pointer;"> <div style="display: flex; gap: 8px; align-items: center;">
<button onclick="openPreOrderScanModal()" style="background: linear-gradient(135deg, #0284c7, #0369a1); border: none; color: white; padding: 8px 14px; border-radius: 8px; font-weight: 800; font-size: 0.8rem; cursor: pointer; display: flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(2, 132, 199, 0.4);">
<span>📷</span> Escanear QR para Entregar
</button>
<button onclick="loadPreOrders()" style="background: #334155; border: none; color: white; padding: 8px 12px; border-radius: 8px; font-weight: 700; cursor: pointer;">
🔄 Refrescar 🔄 Refrescar
</button> </button>
</div> </div>
</div>
<div id="preOrdersList" style="display: flex; flex-direction: column; gap: 10px;"> <div id="preOrdersList" style="display: flex; flex-direction: column; gap: 10px;">
<!-- Lista de pre-órdenes --> <!-- Lista de pre-órdenes -->
@@ -152,51 +157,25 @@
</button> </button>
</div> </div>
<!-- CÁMARA / ESCÁNER DE CÓDIGO QR --> <!-- SECCIÓN DE IDENTIFICACIÓN / ALUMNO EN MOSTRADOR -->
<div class="scanner-feed-card"> <div id="posStudentSection" style="margin-bottom: 12px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;"> <!-- ESTADO INICIAL: SIN ALUMNO IDENTIFICADO -->
<span style="font-size: 0.85rem; font-weight: 800; color: #38bdf8;">📷 Escáner QR de Alumnos</span> <div id="posNoStudentPlaceholder" style="background: #1e293b; border: 1.5px dashed #334155; border-radius: 14px; padding: 14px 16px; text-align: center;">
<div style="display: flex; gap: 6px; align-items: center;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<button id="btnFlipPosCamera" onclick="flipPosCamera()" style="display:none; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">🔄 Girar</button> <span style="font-size: 0.85rem; font-weight: 800; color: #38bdf8;">👤 Alumno en Mostrador</span>
<button id="btnRetryPosCamera" onclick="initCamera(true)" style="display:none; padding: 3px 8px; background: #0284c7; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">📷 Activar</button> <span style="font-size: 0.7rem; color: #34d399; background: #064e3b; padding: 2px 8px; border-radius: 6px; font-weight: 800;">Caja Lista</span>
<span style="font-size: 0.72rem; color: #94a3b8;" id="cameraStatus">Iniciando cámara...</span>
</div> </div>
</div> <p style="font-size: 0.76rem; color: #94a3b8; margin: 0 0 10px 0;">
Selecciona productos y presiona <strong>Cobrar</strong> para escanear, o identifica primero al estudiante:
<div style="position: relative; border-radius: 10px; overflow: hidden; background: #000; min-height: 180px; display: flex; align-items: center; justify-content: center;"> </p>
<video id="scannerVideo" class="camera-preview" autoplay playsinline webkit-playsinline muted></video> <button type="button" onclick="openStudentIdModal()" style="padding: 8px 16px; background: #0284c7; color: white; border: none; border-radius: 10px; font-size: 0.8rem; font-weight: 800; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(2, 132, 199, 0.3);">
<div class="laser-scan-line"></div> <span>📷</span> Identificar Alumno / Ver Saldo
<div id="cameraHelpOverlay" style="display: none; position: absolute; inset: 0; background: rgba(15, 23, 42, 0.92); padding: 14px; text-align: center; flex-direction: column; justify-content: center; align-items: center; gap: 10px; z-index: 10;">
<span style="font-size: 1.8rem;">📷</span>
<div id="cameraHelpText" style="font-size: 0.78rem; color: #f8fafc; line-height: 1.35;">Haz clic en Activar Cámara para escanear</div>
<div id="posCameraActionContainer" style="display: flex; flex-direction: column; gap: 8px; width: 100%; align-items: center;">
<button id="btnAllowPosCamera" onclick="initCamera(true)" style="padding: 8px 16px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.82rem; cursor: pointer; box-shadow: 0 4px 10px rgba(2, 132, 199, 0.4);">
Permitir Cámara
</button> </button>
</div> </div>
</div>
</div>
<!-- BOTÓN PARA TOMAR FOTO DEL CARNÉ O QR -->
<div style="display: flex; justify-content: center; margin-top: 8px;">
<label style="cursor: pointer; display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; background: #1e293b; border: 1px dashed #475569; border-radius: 8px; font-size: 0.74rem; font-weight: 700; color: #38bdf8;">
<span>📸</span> Tomar foto de carné QR
<input type="file" accept="image/*" capture="environment" style="display: none;" onchange="handlePosQrPhoto(event)">
</label>
</div>
<!-- BOTONES DE PRUEBA RÁPIDA DE QR (SIMULACIÓN DE ESCANEO DE CARNÉ O CELULAR) -->
<div style="margin-top: 10px; display: flex; gap: 6px; flex-wrap: wrap; justify-content: center;">
<span style="font-size: 0.7rem; color: #94a3b8; width: 100%;">Prueba rápida de escaneo de carné:</span>
<button onclick="simulateScan('QR-MATEO-2026-A891')" style="font-size: 0.72rem; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; cursor: pointer;">🧒 Mateo (8a)</button>
<button onclick="simulateScan('QR-SOFIA-2026-B442')" style="font-size: 0.72rem; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; cursor: pointer;">👧 Sofía (9a)</button>
<button onclick="simulateScan('QR-NACHO-2026-D902')" style="font-size: 0.72rem; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; cursor: pointer;">🧑 Ignacio (14a)</button>
</div>
</div>
<!-- TARJETA DEL ESTUDIANTE IDENTIFICADO POR QR --> <!-- TARJETA DEL ESTUDIANTE IDENTIFICADO POR QR -->
<div id="studentScannedCard" style="display: none; margin-top: 14px;" class="student-badge-scanned"> <div id="studentScannedCard" style="display: none;" class="student-badge-scanned">
<img id="scannedAvatar" src="" style="width: 44px; height: 44px; border-radius: 50%; border: 2px solid #38bdf8; background: white; flex-shrink: 0;"> <img id="scannedAvatar" src="" style="width: 44px; height: 44px; border-radius: 50%; border: 2px solid #38bdf8; background: white; flex-shrink: 0; object-fit: cover;">
<div style="flex: 1; min-width: 0; word-break: break-word;"> <div style="flex: 1; min-width: 0; word-break: break-word;">
<h4 id="scannedName" style="font-size: 0.92rem; font-weight: 800; color: #ffffff; margin: 0; line-height: 1.2;">Nombre del Alumno</h4> <h4 id="scannedName" style="font-size: 0.92rem; font-weight: 800; color: #ffffff; margin: 0; line-height: 1.2;">Nombre del Alumno</h4>
<div id="scannedGrade" style="font-size: 0.74rem; color: #94a3b8; margin-top: 2px;">2° Grado • Sección 2-A</div> <div id="scannedGrade" style="font-size: 0.74rem; color: #94a3b8; margin-top: 2px;">2° Grado • Sección 2-A</div>
@@ -212,6 +191,7 @@
<div id="scannedAllergyAlert" style="display: none; background: #7f1d1d; border: 1px solid #ef4444; border-radius: 10px; padding: 8px 12px; margin-top: 10px; font-size: 0.78rem; color: #fecaca;"> <div id="scannedAllergyAlert" style="display: none; background: #7f1d1d; border: 1px solid #ef4444; border-radius: 10px; padding: 8px 12px; margin-top: 10px; font-size: 0.78rem; color: #fecaca;">
⚠️ <strong>ALERTA MÉDICA:</strong> <span id="scannedAllergyText"></span> ⚠️ <strong>ALERTA MÉDICA:</strong> <span id="scannedAllergyText"></span>
</div> </div>
</div>
<!-- LISTA DE PRODUCTOS SELECCIONADOS EN CAJA --> <!-- LISTA DE PRODUCTOS SELECCIONADOS EN CAJA -->
<div style="margin-top: 14px;"> <div style="margin-top: 14px;">
@@ -245,38 +225,45 @@
<!-- CABECERA --> <!-- CABECERA -->
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155; padding-bottom: 12px; margin-bottom: 16px;"> <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155; padding-bottom: 12px; margin-bottom: 16px;">
<div style="display: flex; align-items: center; gap: 8px;"> <div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.5rem;">🔫</span> <span style="font-size: 1.5rem;" id="pistolaModalIcon">📷</span>
<strong style="font-size: 1.1rem; color: #38bdf8; letter-spacing: 0.5px;">Cobro con Pistola QR</strong> <strong style="font-size: 1.1rem; color: #38bdf8; letter-spacing: 0.5px;" id="pistolaModalTitle">Escanear Carné QR</strong>
</div> </div>
<button type="button" onclick="closePistolaModal()" style="background: none; border: none; font-size: 1.3rem; color: #94a3b8; cursor: pointer;">✕</button> <button type="button" onclick="closePistolaModal()" style="background: none; border: none; font-size: 1.3rem; color: #94a3b8; cursor: pointer;">✕</button>
</div> </div>
<!-- ESTADO 1: ESPERANDO ESCANEO (DEFAULT) --> <!-- ESTADO 1: ESPERANDO ESCANEO (DEFAULT) -->
<div id="pistolaStateWaiting"> <div id="pistolaStateWaiting">
<!-- TOTAL A COBRAR GIGANTE --> <!-- TOTAL A COBRAR GIGANTE (SOLO EN MODO COBRO) -->
<div style="background: #1e293b; border: 1.5px solid #0284c7; border-radius: 14px; padding: 12px; margin-bottom: 16px;"> <div id="pistolaTotalContainer" style="background: #1e293b; border: 1.5px solid #0284c7; border-radius: 14px; padding: 12px; margin-bottom: 14px;">
<div style="font-size: 0.78rem; font-weight: 800; color: #94a3b8; text-transform: uppercase;">Monto Total a Cobrar</div> <div style="font-size: 0.78rem; font-weight: 800; color: #94a3b8; text-transform: uppercase;">Monto Total a Cobrar</div>
<div id="pistolaModalTotal" style="font-size: 2.3rem; font-weight: 900; color: #38bdf8; margin: 4px 0;">₡0</div> <div id="pistolaModalTotal" style="font-size: 2.3rem; font-weight: 900; color: #38bdf8; margin: 4px 0;">₡0</div>
<div id="pistolaModalItemCount" style="font-size: 0.75rem; color: #cbd5e1;">0 productos en mostrador</div> <div id="pistolaModalItemCount" style="font-size: 0.75rem; color: #cbd5e1;">0 productos en mostrador</div>
</div> </div>
<!-- INDICADOR VISUAL ANIMADO DE PISTOLA LÁSER --> <!-- CÁMARA BAJO DEMANDA INTEGRADA EN EL MODAL -->
<div style="background: #022c22; border: 2px dashed #10b981; border-radius: 14px; padding: 16px; margin-bottom: 14px; position: relative;"> <div id="modalCameraContainer" style="position: relative; border-radius: 14px; overflow: hidden; background: #000; min-height: 200px; max-height: 230px; margin-bottom: 12px; display: flex; align-items: center; justify-content: center; border: 2px solid #0284c7;">
<div style="font-size: 2.5rem; animation: pulse 1.5s infinite;">🎯</div> <video id="modalScannerVideo" style="width: 100%; height: 210px; object-fit: cover;" autoplay playsinline webkit-playsinline muted></video>
<strong style="font-size: 1rem; color: #34d399; display: block; margin-top: 6px;">¡LISTO PARA DISPARAR LA PISTOLA!</strong> <div class="laser-scan-line"></div>
<p style="font-size: 0.78rem; color: #a7f3d0; margin: 4px 0 0 0;"> <div id="modalCameraStatusBadge" style="position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%); background: rgba(15, 23, 42, 0.92); color: #38bdf8; padding: 4px 12px; border-radius: 20px; font-size: 0.74rem; font-weight: 800; border: 1px solid #0284c7; white-space: nowrap; box-shadow: 0 4px 10px rgba(0,0,0,0.5);">
Apunta la pistola al carné del niño o acerca el código QR. 📷 Apunta el carné a la cámara o dispara pistola
</p> </div>
<div id="modalCameraOverlay" style="display: none; position: absolute; inset: 0; background: rgba(15, 23, 42, 0.95); padding: 14px; text-align: center; flex-direction: column; justify-content: center; align-items: center; gap: 8px; z-index: 10;">
<span style="font-size: 2rem;">📷</span>
<div id="modalCameraHelpText" style="font-size: 0.8rem; color: #f8fafc; line-height: 1.35;">Toca el botón para permitir el uso de la cámara</div>
<button type="button" onclick="startModalCamera(true)" style="padding: 8px 16px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.82rem; cursor: pointer; box-shadow: 0 4px 10px rgba(2, 132, 199, 0.4);">
Permitir Cámara
</button>
</div>
</div> </div>
<!-- CAMPO DE ENTRADA ENFOCADO PARA PISTOLA USB --> <!-- CAMPO DE ENTRADA ENFOCADO PARA PISTOLA USB -->
<div style="margin-bottom: 12px;"> <div style="margin-bottom: 12px;">
<input type="text" id="inputPistolaDirectScan" placeholder="Esperando lectura de pistola..." autocomplete="off" style="width: 100%; padding: 10px; border-radius: 10px; border: 1.5px solid #334155; background: #1e293b; color: #f8fafc; font-size: 0.9rem; font-weight: 800; text-align: center; box-sizing: border-box;"> <input type="text" id="inputPistolaDirectScan" placeholder="Esperando lectura de carné o pistola..." autocomplete="off" style="width: 100%; padding: 10px; border-radius: 10px; border: 1.5px solid #334155; background: #1e293b; color: #f8fafc; font-size: 0.88rem; font-weight: 800; text-align: center; box-sizing: border-box;">
</div> </div>
<!-- ACCESOS RÁPIDOS DE PRUEBA --> <!-- ACCESOS RÁPIDOS DE PRUEBA -->
<div style="border-top: 1px dashed #334155; padding-top: 10px; margin-top: 10px;"> <div style="border-top: 1px dashed #334155; padding-top: 10px; margin-top: 10px;">
<span style="font-size: 0.72rem; color: #94a3b8; display: block; margin-bottom: 6px;">Simulación rápida sin pistola física:</span> <span style="font-size: 0.72rem; color: #94a3b8; display: block; margin-bottom: 6px;">Simulación rápida sin pistola física ni cámara:</span>
<div style="display: flex; gap: 6px; justify-content: center; flex-wrap: wrap;"> <div style="display: flex; gap: 6px; justify-content: center; flex-wrap: wrap;">
<button type="button" onclick="handlePistolBarcodeScan('QR-MATEO-2026-A891')" style="padding: 5px 10px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">🧒 Mateo (8a)</button> <button type="button" onclick="handlePistolBarcodeScan('QR-MATEO-2026-A891')" style="padding: 5px 10px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">🧒 Mateo (8a)</button>
<button type="button" onclick="handlePistolBarcodeScan('QR-SOFIA-2026-B442')" style="padding: 5px 10px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">👧 Sofía (9a)</button> <button type="button" onclick="handlePistolBarcodeScan('QR-SOFIA-2026-B442')" style="padding: 5px 10px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">👧 Sofía (9a)</button>
@@ -331,8 +318,8 @@
</div> </div>
</div> </div>
<script src="/js/sounds.js?v=8.1"></script> <script src="/js/sounds.js?v=8.3"></script>
<script src="/js/jsQR.js"></script> <script src="/js/jsQR.js"></script>
<script src="/js/pos.js?v=8.1"></script> <script src="/js/pos.js?v=8.3"></script>
</body> </body>
</html> </html>