// 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;
let posMobileActiveView = 'catalog';
let CLOUDFLARE_TUNNEL_URL = 'https://somewhat-ships-looksmart-optical.trycloudflare.com';
function switchPosMobileView(view) {
posMobileActiveView = view;
const body = document.body;
const tabCat = document.getElementById('btnMobileNavCatalog');
const tabCheck = document.getElementById('btnMobileNavCheckout');
const floatBar = document.getElementById('posFloatingCheckoutBar');
if (view === 'checkout') {
body.classList.remove('pos-mobile-view-catalog');
body.classList.add('pos-mobile-view-checkout');
if (tabCat) tabCat.classList.remove('active');
if (tabCheck) tabCheck.classList.add('active');
if (floatBar) floatBar.style.display = 'none';
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
body.classList.remove('pos-mobile-view-checkout');
body.classList.add('pos-mobile-view-catalog');
if (tabCat) tabCat.classList.add('active');
if (tabCheck) tabCheck.classList.remove('active');
updatePosCartUI();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
window.addEventListener('resize', () => {
if (window.innerWidth > 900) {
const floatBar = document.getElementById('posFloatingCheckoutBar');
if (floatBar) floatBar.style.display = 'none';
} else {
updatePosCartUI();
}
});
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();
initSSE();
initPistolScanner();
});
// 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');
const totalItems = posCart.reduce((sum, item) => sum + item.cantidad, 0);
// Actualizar badge móvil
const mobileBadge = document.getElementById('mobileCartBadge');
if (mobileBadge) {
if (totalItems > 0) {
mobileBadge.textContent = totalItems;
mobileBadge.style.display = 'inline-block';
} else {
mobileBadge.style.display = 'none';
}
}
const floatBar = document.getElementById('posFloatingCheckoutBar');
const floatText = document.getElementById('posFloatingCartText');
const floatTotal = document.getElementById('posFloatingCartTotal');
if (posCart.length === 0) {
list.innerHTML = 'Toca productos del menú para cobrar
';
totalEl.textContent = '₡0';
if (floatBar) floatBar.style.display = 'none';
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')}`;
// Controlar barra flotante en móvil
if (floatBar && window.innerWidth <= 900) {
if (totalItems > 0 && posMobileActiveView === 'catalog') {
floatBar.style.display = 'flex';
if (floatText) floatText.textContent = `${totalItems} ${totalItems === 1 ? 'ítem' : 'ítems'} en mostrador`;
if (floatTotal) floatTotal.textContent = `₡${total.toLocaleString('es-CR')}`;
} else {
floatBar.style.display = 'none';
}
}
}
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
// ==========================================
let posFacingMode = 'environment';
let posQrScanningInterval = null;
let posCanvas = null;
let posCanvasCtx = null;
let lastScannedToken = null;
let lastScannedTime = 0;
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');
if (videoStream) {
videoStream.getTracks().forEach(t => t.stop());
videoStream = null;
}
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';
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 {
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;
}
}
if (!stream) {
throw lastError || new Error('No se pudo acceder a la cámara');
}
videoStream = stream;
video.srcObject = stream;
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';
startUniversalQrDetection(video);
} catch (err) {
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. 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';
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);
}
function startUniversalQrDetection(video) {
if (!posCanvas) {
posCanvas = document.createElement('canvas');
posCanvasCtx = posCanvas.getContext('2d', { willReadFrequently: true });
}
if (posQrScanningInterval) {
cancelAnimationFrame(posQrScanningInterval);
}
function scanFrame() {
if (isScanningActive && video.readyState === video.HAVE_ENOUGH_DATA) {
posCanvas.width = video.videoWidth;
posCanvas.height = video.videoHeight;
posCanvasCtx.drawImage(video, 0, 0, posCanvas.width, posCanvas.height);
const imageData = posCanvasCtx.getImageData(0, 0, posCanvas.width, posCanvas.height);
if (window.jsQR) {
const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'dontInvert'
});
if (code && code.data) {
const now = Date.now();
// Evitar lecturas duplicadas en menos de 2 segundos
if (code.data !== lastScannedToken || (now - lastScannedTime) > 2000) {
lastScannedToken = code.data;
lastScannedTime = now;
onQrCodeDetected(code.data);
}
}
}
}
posQrScanningInterval = requestAnimationFrame(scanFrame);
}
posQrScanningInterval = requestAnimationFrame(scanFrame);
}
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 ya hay productos en el carrito, procesar cobro inmediato con este QR
if (posCart.length > 0) {
await handlePistolBarcodeScan(token);
return;
}
// Si estamos en mostrador sin productos, 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;
const btnCobrar = document.getElementById('btnCobrarPos');
if (scannedStudent.tarjeta_bloqueada) {
document.getElementById('scannedName').innerHTML = `${scannedStudent.nombre_completo} ⛔ TARJETA SUSPENDIDA`;
if (btnCobrar) {
btnCobrar.disabled = true;
btnCobrar.textContent = '⛔ Tarjeta Suspendida';
btnCobrar.style.background = '#64748b';
}
} else {
document.getElementById('scannedName').textContent = scannedStudent.nombre_completo;
if (btnCobrar) {
btnCobrar.disabled = false;
btnCobrar.innerHTML = `🔫 COBRAR A ${scannedStudent.nombre_completo.split(' ')[0].toUpperCase()} ➔`;
btnCobrar.style.background = 'linear-gradient(135deg, #10b981, #059669)';
}
}
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';
}
// En pantallas móviles, mostrar la vista de caja automáticamente
if (window.innerWidth <= 900) {
switchPosMobileView('checkout');
}
}
function clearScannedStudent() {
scannedStudent = null;
renderScannedStudent();
const btnCobrar = document.getElementById('btnCobrarPos');
if (btnCobrar) {
btnCobrar.disabled = false;
btnCobrar.innerHTML = '🔫 COBRAR CON PISTOLA QR';
btnCobrar.style.background = 'linear-gradient(135deg, #0284c7, #0369a1)';
}
}
// ==========================================
// PISTOLA LECTORA DE QR (USB/BLUETOOTH) Y COBRO RÁPIDO
// ==========================================
let barcodeBuffer = '';
let barcodeLastTime = 0;
let pistolaAutoCloseTimer = null;
function initPistolScanner() {
// Listener global para capturar ráfagas rápidas de pistola USB/Bluetooth
window.addEventListener('keydown', (e) => {
// Si presiona Escape, cerrar modal de cobro si está abierto
if (e.key === 'Escape') {
closePistolaModal();
return;
}
// Si presiona Enter y el modal está en pantalla de éxito, cerrarlo para el siguiente
const modalSuccess = document.getElementById('pistolaStateSuccess');
if (e.key === 'Enter' && modalSuccess && modalSuccess.style.display !== 'none') {
e.preventDefault();
closePistolaModal();
return;
}
const now = Date.now();
// Si pasaron más de 80ms entre teclas, no es pistola, es un humano escribiendo
if (now - barcodeLastTime > 80 && barcodeBuffer.length > 0) {
barcodeBuffer = '';
}
barcodeLastTime = now;
if (e.key === 'Enter') {
if (barcodeBuffer.trim().length >= 3) {
e.preventDefault();
const code = barcodeBuffer.trim();
barcodeBuffer = '';
handlePistolBarcodeScan(code);
return;
}
} else if (e.key.length === 1) {
barcodeBuffer += e.key;
}
});
// Listener para el input de texto del modal
const inputScan = document.getElementById('inputPistolaDirectScan');
if (inputScan) {
inputScan.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const val = inputScan.value.trim();
if (val.length >= 3) {
inputScan.value = '';
handlePistolBarcodeScan(val);
}
}
});
}
}
function openPistolaModal() {
if (posCart.length === 0) {
if (window.sounds) window.sounds.playError();
alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.');
return;
}
const modal = document.getElementById('modalPistolaCobro');
if (!modal) return;
const total = posCart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0);
const totalItems = posCart.reduce((sum, item) => sum + item.cantidad, 0);
document.getElementById('pistolaModalTotal').textContent = `₡${total.toLocaleString('es-CR')}`;
document.getElementById('pistolaModalItemCount').textContent = `${totalItems} ${totalItems === 1 ? 'producto' : 'productos'} en mostrador`;
resetPistolaModalWaiting();
modal.style.display = 'flex';
setTimeout(() => {
const input = document.getElementById('inputPistolaDirectScan');
if (input) input.focus();
}, 100);
if (window.sounds) window.sounds.playTap();
}
function closePistolaModal(e) {
if (e && e.target && e.target.id !== 'modalPistolaCobro') return;
if (pistolaAutoCloseTimer) {
clearTimeout(pistolaAutoCloseTimer);
pistolaAutoCloseTimer = null;
}
const modal = document.getElementById('modalPistolaCobro');
if (modal) modal.style.display = 'none';
}
function resetPistolaModalWaiting() {
if (pistolaAutoCloseTimer) {
clearTimeout(pistolaAutoCloseTimer);
pistolaAutoCloseTimer = null;
}
document.getElementById('pistolaStateWaiting').style.display = 'block';
document.getElementById('pistolaStateProcessing').style.display = 'none';
document.getElementById('pistolaStateSuccess').style.display = 'none';
document.getElementById('pistolaStateError').style.display = 'none';
const input = document.getElementById('inputPistolaDirectScan');
if (input) {
input.value = '';
input.focus();
}
}
async function handlePistolBarcodeScan(rawToken) {
const token = String(rawToken).trim();
if (!token) return;
if (window.sounds) window.sounds.playScanChirp();
// Si no hay productos en el carrito, identificar al alumno para mostrador
if (posCart.length === 0) {
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();
if (window.sounds) window.sounds.playSuccess();
} catch (err) {
if (window.sounds) window.sounds.playError();
alert(`⚠️ Estudiante no reconocido: ${err.message}`);
}
return;
}
// SI HAY PRODUCTOS EN EL CARRITO: EJECUTAR COBRO INMEDIATO CON PISTOLA
const modal = document.getElementById('modalPistolaCobro');
if (modal && modal.style.display === 'none') {
openPistolaModal();
}
// Mostrar estado de procesamiento
document.getElementById('pistolaStateWaiting').style.display = 'none';
document.getElementById('pistolaStateError').style.display = 'none';
document.getElementById('pistolaStateSuccess').style.display = 'none';
document.getElementById('pistolaStateProcessing').style.display = 'block';
document.getElementById('pistolaProcessingName').textContent = 'Identificando estudiante y validando monedero...';
try {
// 1. Buscar estudiante por token o código
const resEst = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`);
const student = await resEst.json();
if (!resEst.ok) throw new Error(student.error || 'Carné escolar no encontrado');
document.getElementById('pistolaProcessingName').textContent = `Verificando saldo para ${student.nombre_completo}...`;
// 2. Validar si la tarjeta está suspendida
if (student.tarjeta_bloqueada) {
throw new Error(`⛔ TARJETA SUSPENDIDA: La tarjeta de ${student.nombre_completo} ha sido bloqueada por la administración de la soda.`);
}
// 3. Validar saldo disponible y límite diario
const totalCompra = posCart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0);
if (student.saldo_colones < totalCompra) {
throw new Error(`⚠️ SALDO INSUFICIENTE: ${student.nombre_completo} tiene ₡${student.saldo_colones.toLocaleString('es-CR')} de saldo y la compra es de ₡${totalCompra.toLocaleString('es-CR')}.`);
}
if (student.disponible_hoy < totalCompra) {
throw new Error(`⚠️ SUPERA LÍMITE DIARIO: Le quedan ₡${student.disponible_hoy.toLocaleString('es-CR')} disponibles hoy de su límite diario asignado.`);
}
// 4. Procesar cobro en servidor
const items = posCart.map(item => ({
producto_id: item.product.id,
cantidad: item.cantidad
}));
const resCobro = await fetch('/api/ordenes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
estudiante_id: student.id,
tipo_orden: 'mostrador',
momento_entrega: 'inmediato',
items
})
});
const dataCobro = await resCobro.json();
if (!resCobro.ok) throw new Error(dataCobro.error || 'Error al procesar el débito');
// 5. Éxito: Mostrar pantalla de confirmación
document.getElementById('pistolaStateProcessing').style.display = 'none';
document.getElementById('pistolaStateSuccess').style.display = 'block';
document.getElementById('pistolaSuccessStudent').textContent = student.nombre_completo;
document.getElementById('pistolaSuccessTicket').textContent = dataCobro.codigo_orden;
document.getElementById('pistolaSuccessAmount').textContent = `₡${totalCompra.toLocaleString('es-CR')}`;
const nuevoSaldo = (dataCobro.financiero && dataCobro.financiero.estudiante)
? dataCobro.financiero.estudiante.saldo_nuevo
: (student.saldo_colones - totalCompra);
document.getElementById('pistolaSuccessBalance').textContent = `₡${nuevoSaldo.toLocaleString('es-CR')}`;
if (window.sounds) {
window.sounds.playSuccess();
window.sounds.playCoin();
}
// Limpiar carrito de mostrador
clearPosCart();
clearScannedStudent();
// Auto-cerrar el modal en 2.5 segundos para quedar listo para el siguiente alumno
pistolaAutoCloseTimer = setTimeout(() => {
closePistolaModal();
}, 2500);
} catch (err) {
if (window.sounds) window.sounds.playError();
document.getElementById('pistolaStateProcessing').style.display = 'none';
document.getElementById('pistolaStateError').style.display = 'block';
document.getElementById('pistolaErrorTitle').textContent = 'No se pudo realizar el cobro';
document.getElementById('pistolaErrorDesc').textContent = err.message;
}
}
// Ejecutar cobro en mostrador (desde botón principal)
async function executePosDebit() {
if (posCart.length === 0) {
if (window.sounds) window.sounds.playError();
alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.');
return;
}
// Si ya tenemos un estudiante identificado previamente, cobramos directamente
if (scannedStudent) {
await handlePistolBarcodeScan(scannedStudent.qr_token || scannedStudent.codigo_estudiante);
return;
}
// Si no hay estudiante previo, abrir modal esperando el disparo de la pistola QR
openPistolaModal();
}
// ==========================================
// 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();
});
}