// RECREOPAY - LÓGICA DE LA TERMINAL DE LA SODA (POS & ESCÁNER) let posProducts = []; let posCategories = []; let posCart = []; let scannedStudent = null; let currentTab = 'mostrador'; let sseSource = null; let videoStream = null; let isScanningActive = true; document.addEventListener('DOMContentLoaded', async () => { await loadCatalog(); await loadPreOrders(); initCamera(); initSSE(); }); // Cargar catálogo de productos async function loadCatalog() { try { const res = await fetch('/api/productos'); const data = await res.json(); posCategories = data.categorias; posProducts = data.productos; renderPosCategories(); renderPosProducts(null); } catch (err) { console.error('Error cargando catálogo:', err); } } function renderPosCategories() { const bar = document.getElementById('posCategoriesBar'); bar.innerHTML = ` ${posCategories.map(c => ` `).join('')} `; } function filterPosCat(catId, btn) { document.querySelectorAll('#posCategoriesBar .pos-tab-btn').forEach(b => b.classList.remove('active')); if (btn) btn.classList.add('active'); renderPosProducts(catId); } function renderPosProducts(catId) { const grid = document.getElementById('posProductsGrid'); let list = posProducts; if (catId !== null) { list = list.filter(p => p.categoria_id === catId); } grid.innerHTML = list.map(prod => `
${prod.icono || '🥪'}
${prod.nombre}
${prod.cumple_mep ? '🌿 MEP Saludable' : ''}
₡${prod.precio_colones.toLocaleString('es-CR')}
`).join(''); } // Carrito de mostrador function addToPosCart(prodId) { const prod = posProducts.find(p => p.id === prodId); if (!prod) return; const existing = posCart.find(i => i.product.id === prodId); if (existing) { existing.cantidad++; } else { posCart.push({ product: prod, cantidad: 1 }); } if (window.sounds) window.sounds.playCoin(); updatePosCartUI(); } function updatePosCartUI() { const list = document.getElementById('posCartList'); const totalEl = document.getElementById('posCartTotal'); if (posCart.length === 0) { list.innerHTML = '

Toca productos del menú para cobrar

'; totalEl.textContent = '₡0'; return; } let total = 0; list.innerHTML = posCart.map((item, idx) => { const subtotal = item.product.precio_colones * item.cantidad; total += subtotal; return `
${item.product.icono} ${item.product.nombre}
₡${item.product.precio_colones.toLocaleString('es-CR')} c/u
${item.cantidad} ₡${subtotal.toLocaleString('es-CR')}
`; }).join(''); totalEl.textContent = `₡${total.toLocaleString('es-CR')}`; } function changePosQty(idx, delta) { posCart[idx].cantidad += delta; if (posCart[idx].cantidad <= 0) { posCart.splice(idx, 1); } updatePosCartUI(); } function clearPosCart() { posCart = []; updatePosCartUI(); } // ========================================== // ESCÁNER Y LECTURA DE QR // ========================================== async function initCamera() { const video = document.getElementById('scannerVideo'); const status = document.getElementById('cameraStatus'); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { try { videoStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment', width: { ideal: 640 } } }); video.srcObject = videoStream; status.textContent = '🟢 Cámara conectada'; startQrDetection(video); } catch (err) { status.textContent = '⚪ Modo simulación QR activo'; } } else { status.textContent = '⚪ Modo simulación QR activo'; } } // Detección nativa por BarcodeDetector si el navegador lo soporta (Chrome/Edge Android) function startQrDetection(video) { if ('BarcodeDetector' in window) { const detector = new window.BarcodeDetector({ formats: ['qr_code'] }); const interval = setInterval(async () => { if (!isScanningActive) return; try { const barcodes = await detector.detect(video); if (barcodes.length > 0) { const rawValue = barcodes[0].rawValue; onQrCodeDetected(rawValue); } } catch (e) {} }, 400); } } function simulateScan(qrToken) { onQrCodeDetected(qrToken); } async function onQrCodeDetected(token) { if (window.sounds) window.sounds.playScanChirp(); // Si estamos en la pestaña de fila rápida de pre-órdenes, despachamos de inmediato if (currentTab === 'preordenes') { await dispatchPreOrderExpress(token); return; } // Si estamos en mostrador, identificamos al estudiante try { const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`); const data = await res.json(); if (!res.ok) throw new Error(data.error); scannedStudent = data; renderScannedStudent(); // Si tiene pre-órdenes listas, alertar a la cajera 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?`)) { switchPosTab('preordenes'); } } } catch (err) { if (window.sounds) window.sounds.playError(); alert(`QR no reconocido: ${err.message}`); } } function renderScannedStudent() { if (!scannedStudent) { document.getElementById('studentScannedCard').style.display = 'none'; document.getElementById('scannedAllergyAlert').style.display = 'none'; return; } document.getElementById('scannedAvatar').src = scannedStudent.foto_url; document.getElementById('scannedName').textContent = scannedStudent.nombre_completo; document.getElementById('scannedGrade').textContent = `${scannedStudent.grado} • Sección ${scannedStudent.seccion} • Cód: ${scannedStudent.codigo_estudiante}`; document.getElementById('scannedBalance').textContent = `₡${scannedStudent.saldo_colones.toLocaleString('es-CR')}`; document.getElementById('scannedAvailable').textContent = `₡${scannedStudent.disponible_hoy.toLocaleString('es-CR')}`; document.getElementById('studentScannedCard').style.display = 'flex'; // Alerta médica en mostrador const alertBox = document.getElementById('scannedAllergyAlert'); if (scannedStudent.alergias && scannedStudent.alergias !== 'Ninguna' && scannedStudent.alergias !== 'Ninguna conocida') { alertBox.style.display = 'block'; document.getElementById('scannedAllergyText').textContent = scannedStudent.alergias; } else { alertBox.style.display = 'none'; } } function clearScannedStudent() { scannedStudent = null; renderScannedStudent(); } // Ejecutar cobro en mostrador async function executePosDebit() { if (!scannedStudent) { if (window.sounds) window.sounds.playError(); return alert('⚠️ Primero escanea el carné o celular del estudiante (puedes usar los botones de prueba rápida en la cámara).'); } if (posCart.length === 0) { if (window.sounds) window.sounds.playError(); return alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.'); } const items = posCart.map(item => ({ producto_id: item.product.id, cantidad: item.cantidad })); const btn = document.getElementById('btnCobrarPos'); btn.disabled = true; btn.textContent = 'Procesando débito...'; try { const res = await fetch('/api/ordenes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ estudiante_id: scannedStudent.id, tipo_orden: 'mostrador', momento_entrega: 'inmediato', items }) }); const data = await res.json(); if (!res.ok) { if (window.sounds) window.sounds.playError(); throw new Error(data.error); } if (window.sounds) window.sounds.playSuccess(); alert(`✅ ¡COBRO EXITOSO!\nTicket: ${data.codigo_orden}\nEstudiante: ${scannedStudent.nombre_completo}\nMonto: ₡${data.total_colones.toLocaleString('es-CR')}\nNuevo Saldo: ₡${data.financiero.estudiante.saldo_nuevo.toLocaleString('es-CR')}`); // Limpiar caja y refrescar clearPosCart(); clearScannedStudent(); } catch (err) { alert(`❌ Fallo en la transacción: ${err.message}`); } finally { btn.disabled = false; btn.innerHTML = '📱 COBRAR CON QR DE ALUMNO'; } } // ========================================== // FILA RÁPIDA DE PRE-ÓRDENES // ========================================== function switchPosTab(tab) { currentTab = tab; document.getElementById('tabBtnMostrador').classList.toggle('active', tab === 'mostrador'); document.getElementById('tabBtnPreordenes').classList.toggle('active', tab === 'preordenes'); document.getElementById('viewPosMostrador').style.display = tab === 'mostrador' ? 'block' : 'none'; document.getElementById('viewPosPreordenes').style.display = tab === 'preordenes' ? 'block' : 'none'; if (tab === 'preordenes') { loadPreOrders(); } } async function loadPreOrders() { try { const res = await fetch('/api/ordenes?tipo=preorden'); const orders = await res.json(); const pendingCount = orders.filter(o => o.estado !== 'entregado' && o.estado !== 'cancelado').length; document.getElementById('badgePreordenesCount').textContent = pendingCount; const list = document.getElementById('preOrdersList'); if (orders.length === 0) { list.innerHTML = '

No hay pre-órdenes registradas para hoy.

'; return; } list.innerHTML = orders.map(ord => { const hora = new Date(ord.creado_en).toLocaleTimeString('es-CR', { hour: '2-digit', minute: '2-digit' }); const itemsList = ord.items.map(i => `${i.cantidad}x ${i.icono || '🥪'} ${i.nombre}`).join(', '); return `
${ord.estudiante_nombre} ${ord.grado} - ${ord.seccion} ${ord.estado}
📦 ${itemsList}
Ticket: ${ord.codigo_orden} • Pedido a las ${hora} • Total: ₡${ord.total_colones.toLocaleString('es-CR')}
${ord.estado === 'pendiente' ? ` ` : ''} ${ord.estado === 'en_preparacion' ? ` ` : ''} ${ord.estado === 'listo' ? ` ` : ''} ${ord.estado === 'entregado' ? ` ✓ Entregado ` : ''}
`; }).join(''); } catch (err) { console.error('Error cargando pre-órdenes:', err); } } async function updateOrderStatus(orderId, nuevoEstado) { try { const res = await fetch(`/api/ordenes/${orderId}/estado`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ estado: nuevoEstado }) }); if (!res.ok) throw new Error('Error actualizando orden'); if (window.sounds) window.sounds.playCoin(); loadPreOrders(); } catch (e) { alert(e.message); } } // Despacho Express en 3 segundos mediante escaneo de QR async function dispatchPreOrderExpress(qrToken) { try { const res = await fetch('/api/ordenes/despachar-qr', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ qr_token: qrToken }) }); const data = await res.json(); if (!res.ok) { if (window.sounds) window.sounds.playError(); throw new Error(data.error); } if (window.sounds) window.sounds.playSuccess(); alert(`🎉 ¡ENTREGA EXPRESS EXITOSA!\n${data.mensaje}\nAlumno: ${data.estudiante.nombre_completo}\nGrado: ${data.estudiante.grado}\nProductos a entregar:\n${data.orden.items.map(i => `• ${i.cantidad}x ${i.nombre}`).join('\n')}`); loadPreOrders(); } catch (err) { alert(err.message); } } // ========================================== // SSE (SERVER-SENT EVENTS EN TIEMPO REAL) // ========================================== function initSSE() { sseSource = new EventSource('/api/events'); sseSource.addEventListener('nueva_orden', (e) => { const orden = JSON.parse(e.data); if (window.sounds) window.sounds.playSuccess(); // Notificación sonora y visual loadPreOrders(); }); sseSource.addEventListener('orden_actualizada', () => { loadPreOrders(); }); }