feat: inicializacion de RecreoPay - Monedero QR y Pre-ordenes para Soda Escolar CR
This commit is contained in:
@@ -0,0 +1,449 @@
|
||||
// RECREOPAY - LÓGICA DE CLIENTE PWA (ESTUDIANTES Y PADRES)
|
||||
|
||||
let students = [];
|
||||
let currentStudent = null;
|
||||
let categories = [];
|
||||
let products = [];
|
||||
let activeCategoryId = null;
|
||||
let cart = [];
|
||||
let currentAppMode = 'kids';
|
||||
|
||||
// Inicialización al cargar la página
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
// Registrar Service Worker para PWA si está soportado
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(err => console.log('SW error:', err));
|
||||
}
|
||||
|
||||
await loadInitialData();
|
||||
});
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
// 1. Cargar estudiantes
|
||||
const resEst = await fetch('/api/estudiantes');
|
||||
students = await resEst.json();
|
||||
|
||||
populateStudentSelector();
|
||||
|
||||
// Seleccionar por defecto el primer estudiante (Mateo, 8 años -> Modo Kids)
|
||||
if (students.length > 0) {
|
||||
await selectStudent(students[0].id);
|
||||
}
|
||||
|
||||
// 2. Cargar productos y categorías
|
||||
const resProd = await fetch('/api/productos');
|
||||
const dataProd = await resProd.json();
|
||||
categories = dataProd.categorias;
|
||||
products = dataProd.productos;
|
||||
|
||||
renderCategories();
|
||||
renderProducts();
|
||||
} catch (error) {
|
||||
console.error('Error cargando datos iniciales:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function populateStudentSelector() {
|
||||
const sel = document.getElementById('studentSelector');
|
||||
sel.innerHTML = students.map(s => `
|
||||
<option value="${s.id}">
|
||||
${s.nombre_completo} (${s.edad} años - ${s.grado})
|
||||
</option>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function onStudentChange(studentId) {
|
||||
await selectStudent(studentId);
|
||||
}
|
||||
|
||||
async function selectStudent(studentId) {
|
||||
try {
|
||||
const res = await fetch(`/api/estudiantes/${studentId}`);
|
||||
currentStudent = await res.json();
|
||||
|
||||
// Adaptar modo automáticamente por edad (7-10 Kids, 11-15 Teens)
|
||||
if (currentStudent.edad <= 10) {
|
||||
setAppMode('kids', false);
|
||||
} else {
|
||||
setAppMode('teens', false);
|
||||
}
|
||||
|
||||
updateStudentUI();
|
||||
} catch (e) {
|
||||
console.error('Error seleccionando estudiante:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function updateStudentUI() {
|
||||
if (!currentStudent) return;
|
||||
|
||||
// Actualizar avatar, nombre y grado
|
||||
document.getElementById('walletAvatar').src = currentStudent.foto_url || 'https://api.dicebear.com/7.x/bottts/svg?seed=est';
|
||||
document.getElementById('walletName').textContent = currentStudent.nombre_completo;
|
||||
document.getElementById('walletGrade').textContent = `${currentStudent.grado} • Sección ${currentStudent.seccion} • Cód: ${currentStudent.codigo_estudiante}`;
|
||||
|
||||
// Saldo en colones
|
||||
document.getElementById('walletBalance').textContent = `₡${currentStudent.saldo_colones.toLocaleString('es-CR')}`;
|
||||
|
||||
// Límite diario
|
||||
document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${currentStudent.disponible_hoy.toLocaleString('es-CR')}`;
|
||||
|
||||
// Alergias
|
||||
const allergyBox = document.getElementById('allergyWarning');
|
||||
if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') {
|
||||
allergyBox.style.display = 'flex';
|
||||
document.getElementById('allergyText').textContent = currentStudent.alergias;
|
||||
} else {
|
||||
allergyBox.style.display = 'none';
|
||||
}
|
||||
|
||||
// QR Modal info
|
||||
document.getElementById('qrDisplayImg').src = `/api/qr-image/${encodeURIComponent(currentStudent.qr_token)}`;
|
||||
document.getElementById('qrTokenDisplay').textContent = currentStudent.qr_token;
|
||||
|
||||
// Panel de Padres sliders y valores
|
||||
document.getElementById('lblParentDailyLimit').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('rangeDailyLimit').value = currentStudent.limite_diario_colones;
|
||||
renderParentHistory();
|
||||
}
|
||||
|
||||
function setAppMode(mode, playSound = true) {
|
||||
currentAppMode = mode;
|
||||
document.body.classList.remove('mode-kids', 'mode-teens');
|
||||
|
||||
document.getElementById('btnModeKids').classList.remove('active');
|
||||
document.getElementById('btnModeTeens').classList.remove('active');
|
||||
|
||||
if (mode === 'kids') {
|
||||
document.body.classList.add('mode-kids');
|
||||
document.getElementById('btnModeKids').classList.add('active');
|
||||
document.getElementById('balanceLabel').textContent = '💰 Mis Colones para el Recreo';
|
||||
document.getElementById('kidsCoinIcon').style.display = 'inline-block';
|
||||
document.getElementById('qrBtnText').textContent = 'Tocar para mi QR 📱';
|
||||
} else {
|
||||
document.body.classList.add('mode-teens');
|
||||
document.getElementById('btnModeTeens').classList.add('active');
|
||||
document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE';
|
||||
document.getElementById('kidsCoinIcon').style.display = 'none';
|
||||
document.getElementById('qrBtnText').textContent = 'QR de Pago';
|
||||
}
|
||||
|
||||
if (playSound && window.sounds) {
|
||||
window.sounds.playCoin();
|
||||
}
|
||||
}
|
||||
|
||||
// Renderizado de Categorías
|
||||
function renderCategories() {
|
||||
const bar = document.getElementById('categoriesBar');
|
||||
let html = `
|
||||
<button class="cat-pill ${activeCategoryId === null ? 'active' : ''}" onclick="selectCategory(null)">
|
||||
<span>✨</span> Todos
|
||||
</button>
|
||||
`;
|
||||
|
||||
for (const cat of categories) {
|
||||
html += `
|
||||
<button class="cat-pill ${activeCategoryId === cat.id ? 'active' : ''}" onclick="selectCategory(${cat.id})">
|
||||
<span>${cat.icono}</span> ${cat.nombre}
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
bar.innerHTML = html;
|
||||
}
|
||||
|
||||
function selectCategory(catId) {
|
||||
activeCategoryId = catId;
|
||||
renderCategories();
|
||||
renderProducts();
|
||||
}
|
||||
|
||||
// Renderizado de Productos del Menú
|
||||
function renderProducts() {
|
||||
const grid = document.getElementById('productsGrid');
|
||||
const filterMepOnly = document.getElementById('chkFilterMep').checked;
|
||||
|
||||
let filtered = products;
|
||||
|
||||
if (activeCategoryId !== null) {
|
||||
filtered = filtered.filter(p => p.categoria_id === activeCategoryId);
|
||||
}
|
||||
|
||||
if (filterMepOnly) {
|
||||
filtered = filtered.filter(p => p.cumple_mep === 1);
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
grid.innerHTML = `
|
||||
<div style="grid-column: 1 / -1; text-align: center; padding: 30px; color: var(--text-muted);">
|
||||
<p style="font-size: 2rem;">🥪</p>
|
||||
<p>No hay productos en esta categoría por ahora.</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
grid.innerHTML = filtered.map(prod => `
|
||||
<div class="product-card">
|
||||
<div class="product-icon-wrap">${prod.icono || '🥪'}</div>
|
||||
<div>
|
||||
${prod.cumple_mep ? '<span class="badge-mep">🌿 MEP Saludable</span>' : ''}
|
||||
<h4 class="product-name">${prod.nombre}</h4>
|
||||
<p class="product-desc">${prod.descripcion || ''}</p>
|
||||
${prod.alergenos ? `<div style="font-size: 0.68rem; color: #dc2626; margin-bottom: 4px;">⚠️ Contiene: ${prod.alergenos}</div>` : ''}
|
||||
</div>
|
||||
<div class="product-footer">
|
||||
<span class="product-price">₡${prod.precio_colones.toLocaleString('es-CR')}</span>
|
||||
<button class="add-btn" onclick="addToCart(${prod.id})" title="Agregar a mi pre-orden">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// CARRITO Y PRE-ÓRDENES
|
||||
// ==========================================
|
||||
|
||||
function addToCart(productId) {
|
||||
const prod = products.find(p => p.id === productId);
|
||||
if (!prod) return;
|
||||
|
||||
const existing = cart.find(item => item.product.id === productId);
|
||||
if (existing) {
|
||||
existing.cantidad++;
|
||||
} else {
|
||||
cart.push({ product: prod, cantidad: 1 });
|
||||
}
|
||||
|
||||
if (window.sounds) {
|
||||
window.sounds.playCoin();
|
||||
}
|
||||
|
||||
updateCartBar();
|
||||
}
|
||||
|
||||
function updateCartBar() {
|
||||
const bar = document.getElementById('floatingCart');
|
||||
const countBadge = document.getElementById('cartCountBadge');
|
||||
const totalText = document.getElementById('cartTotalText');
|
||||
|
||||
const totalCount = cart.reduce((sum, item) => sum + item.cantidad, 0);
|
||||
const totalColones = cart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0);
|
||||
|
||||
if (totalCount > 0) {
|
||||
bar.style.display = 'flex';
|
||||
countBadge.textContent = `${totalCount} ${totalCount === 1 ? 'ítem' : 'ítems'}`;
|
||||
totalText.textContent = `₡${totalColones.toLocaleString('es-CR')}`;
|
||||
} else {
|
||||
bar.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function openCartModal() {
|
||||
renderCartModalItems();
|
||||
document.getElementById('modalCart').style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeCartModal(e) {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
document.getElementById('modalCart').style.display = 'none';
|
||||
}
|
||||
|
||||
function renderCartModalItems() {
|
||||
const list = document.getElementById('cartItemsList');
|
||||
const totalEl = document.getElementById('modalCartTotal');
|
||||
|
||||
if (cart.length === 0) {
|
||||
list.innerHTML = '<p style="text-align: center; color: #94a3b8; padding: 20px;">El carrito está vacío</p>';
|
||||
totalEl.textContent = '₡0';
|
||||
return;
|
||||
}
|
||||
|
||||
let total = 0;
|
||||
list.innerHTML = cart.map((item, idx) => {
|
||||
const subtotal = item.product.precio_colones * item.cantidad;
|
||||
total += subtotal;
|
||||
return `
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f1f5f9;">
|
||||
<div>
|
||||
<strong style="font-size: 0.9rem; color: #0f172a;">${item.product.icono} ${item.product.nombre}</strong>
|
||||
<div style="font-size: 0.75rem; color: #64748b;">₡${item.product.precio_colones.toLocaleString('es-CR')} c/u</div>
|
||||
</div>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<button onclick="changeCartQty(${idx}, -1)" style="width: 28px; height: 28px; border-radius: 6px; border: 1px solid #cbd5e1; background: white; font-weight: 800; cursor: pointer;">-</button>
|
||||
<span style="font-weight: 800; font-size: 0.9rem; min-width: 16px; text-align: center;">${item.cantidad}</span>
|
||||
<button onclick="changeCartQty(${idx}, 1)" style="width: 28px; height: 28px; border-radius: 6px; border: 1px solid #cbd5e1; background: white; font-weight: 800; cursor: pointer;">+</button>
|
||||
<span style="font-weight: 900; font-size: 0.95rem; color: #0284c7; min-width: 65px; text-align: right;">₡${subtotal.toLocaleString('es-CR')}</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
totalEl.textContent = `₡${total.toLocaleString('es-CR')}`;
|
||||
}
|
||||
|
||||
function changeCartQty(index, delta) {
|
||||
cart[index].cantidad += delta;
|
||||
if (cart[index].cantidad <= 0) {
|
||||
cart.splice(index, 1);
|
||||
}
|
||||
renderCartModalItems();
|
||||
updateCartBar();
|
||||
}
|
||||
|
||||
async function submitPreOrder() {
|
||||
if (!currentStudent) return;
|
||||
if (cart.length === 0) return alert('Agrega al menos un producto a tu pre-orden');
|
||||
|
||||
const momento = document.getElementById('momentoEntregaSelect').value;
|
||||
const items = cart.map(item => ({
|
||||
producto_id: item.product.id,
|
||||
cantidad: item.cantidad
|
||||
}));
|
||||
|
||||
const btn = document.getElementById('btnConfirmarOrden');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Procesando en la soda...';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/ordenes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
estudiante_id: currentStudent.id,
|
||||
tipo_orden: 'preorden',
|
||||
momento_entrega: momento,
|
||||
items
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
throw new Error(data.error || 'Error procesando pre-orden');
|
||||
}
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
|
||||
alert(`🎉 ¡Pre-Orden confirmada con éxito!\nCódigo de entrega: ${data.codigo_orden}\nRebajada de tu monedero: ₡${data.total_colones.toLocaleString('es-CR')}\n\nPodrás retirarla en la fila rápida de la soda durante el recreo presentando tu QR.`);
|
||||
|
||||
// Limpiar carrito y recargar datos del estudiante
|
||||
cart = [];
|
||||
updateCartBar();
|
||||
closeCartModal();
|
||||
await selectStudent(currentStudent.id);
|
||||
} catch (err) {
|
||||
alert(`❌ No se pudo procesar: ${err.message}`);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '✅ Confirmar y Pagar Pre-Orden';
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// MODAL QR ESCOLAR
|
||||
// ==========================================
|
||||
|
||||
function openQrModal() {
|
||||
if (window.sounds) window.sounds.playScanChirp();
|
||||
document.getElementById('modalQr').style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeQrModal(e) {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
document.getElementById('modalQr').style.display = 'none';
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// PANEL DE PADRES Y RECARGAS SINPE
|
||||
// ==========================================
|
||||
|
||||
function toggleParentPanel(show, e) {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
document.getElementById('modalPadres').style.display = show ? 'flex' : 'none';
|
||||
}
|
||||
|
||||
async function quickSinpeRecharge(monto) {
|
||||
await doSinpeRecharge(monto);
|
||||
}
|
||||
|
||||
async function customSinpeRecharge() {
|
||||
const val = parseInt(document.getElementById('inputCustomSinpe').value, 10);
|
||||
if (!val || val <= 0) return alert('Ingresa un monto válido en colones');
|
||||
await doSinpeRecharge(val);
|
||||
document.getElementById('inputCustomSinpe').value = '';
|
||||
}
|
||||
|
||||
async function doSinpeRecharge(monto) {
|
||||
if (!currentStudent) return;
|
||||
const comprobante = `SINPE-${Math.floor(100000 + Math.random() * 900000)}`;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/estudiantes/${currentStudent.id}/recarga`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
monto,
|
||||
comprobante,
|
||||
descripcion: `Recarga SINPE Móvil desde portal de padres`
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
alert(`✅ ¡Recarga SINPE exitosa!\nSe acreditaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentStudent.nombre_completo}.\nComprobante: ${comprobante}`);
|
||||
|
||||
await selectStudent(currentStudent.id);
|
||||
} catch (err) {
|
||||
alert(`Error en recarga: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function onDailyLimitSlider(val) {
|
||||
document.getElementById('lblParentDailyLimit').textContent = `₡${parseInt(val, 10).toLocaleString('es-CR')}`;
|
||||
if (!currentStudent) return;
|
||||
|
||||
try {
|
||||
await fetch(`/api/estudiantes/${currentStudent.id}/limite`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ limite_diario_colones: parseInt(val, 10) })
|
||||
});
|
||||
// Actualizar UI sutilmente
|
||||
currentStudent.limite_diario_colones = parseInt(val, 10);
|
||||
document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`;
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function renderParentHistory() {
|
||||
const container = document.getElementById('parentHistoryList');
|
||||
if (!currentStudent || !currentStudent.transacciones || currentStudent.transacciones.length === 0) {
|
||||
container.innerHTML = '<p style="color: #94a3b8;">Sin movimientos recientes</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = currentStudent.transacciones.map(t => {
|
||||
const esPositivo = t.monto_colones > 0;
|
||||
const color = esPositivo ? '#166534' : '#0f172a';
|
||||
const signo = esPositivo ? '+' : '';
|
||||
const fecha = new Date(t.fecha).toLocaleDateString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
return `
|
||||
<div style="display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #f1f5f9;">
|
||||
<div>
|
||||
<div style="font-weight: 700; color: ${color};">${t.descripcion || t.tipo}</div>
|
||||
<div style="font-size: 0.7rem; color: #94a3b8;">${fecha}</div>
|
||||
</div>
|
||||
<div style="font-weight: 800; color: ${esPositivo ? '#10b981' : '#ef4444'};">
|
||||
${signo}₡${Math.abs(t.monto_colones).toLocaleString('es-CR')}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
// 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 = `
|
||||
<button class="pos-tab-btn active" style="padding: 6px 12px; font-size: 0.8rem;" onclick="filterPosCat(null, this)">Todos</button>
|
||||
${posCategories.map(c => `
|
||||
<button class="pos-tab-btn" style="padding: 6px 12px; font-size: 0.8rem;" onclick="filterPosCat(${c.id}, this)">
|
||||
${c.icono} ${c.nombre}
|
||||
</button>
|
||||
`).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 => `
|
||||
<div class="pos-prod-card" onclick="addToPosCart(${prod.id})">
|
||||
<div style="font-size: 2.2rem; text-align: center;">${prod.icono || '🥪'}</div>
|
||||
<div>
|
||||
<div style="font-size: 0.88rem; font-weight: 800; color: #ffffff; line-height: 1.2;">${prod.nombre}</div>
|
||||
${prod.cumple_mep ? '<span style="font-size: 0.65rem; color: #34d399;">🌿 MEP Saludable</span>' : ''}
|
||||
</div>
|
||||
<div style="font-size: 1.1rem; font-weight: 900; color: #38bdf8; margin-top: 6px;">
|
||||
₡${prod.precio_colones.toLocaleString('es-CR')}
|
||||
</div>
|
||||
</div>
|
||||
`).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 = '<p style="text-align: center; color: #64748b; padding: 20px; font-size: 0.85rem;">Toca productos del menú para cobrar</p>';
|
||||
totalEl.textContent = '₡0';
|
||||
return;
|
||||
}
|
||||
|
||||
let total = 0;
|
||||
list.innerHTML = posCart.map((item, idx) => {
|
||||
const subtotal = item.product.precio_colones * item.cantidad;
|
||||
total += subtotal;
|
||||
return `
|
||||
<div class="pos-cart-item">
|
||||
<div style="flex: 1;">
|
||||
<strong style="color: #f8fafc; font-size: 0.85rem;">${item.product.icono} ${item.product.nombre}</strong>
|
||||
<div style="font-size: 0.75rem; color: #94a3b8;">₡${item.product.precio_colones.toLocaleString('es-CR')} c/u</div>
|
||||
</div>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<button onclick="changePosQty(${idx}, -1)" style="width: 24px; height: 24px; background: #334155; color: white; border: none; border-radius: 4px; font-weight: 800; cursor: pointer;">-</button>
|
||||
<span style="font-weight: 800; min-width: 14px; text-align: center; color: #ffffff;">${item.cantidad}</span>
|
||||
<button onclick="changePosQty(${idx}, 1)" style="width: 24px; height: 24px; background: #334155; color: white; border: none; border-radius: 4px; font-weight: 800; cursor: pointer;">+</button>
|
||||
<span style="font-weight: 900; color: #38bdf8; min-width: 55px; text-align: right;">₡${subtotal.toLocaleString('es-CR')}</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).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 = '<span>📱</span> 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 = '<p style="text-align: center; color: #64748b; padding: 30px;">No hay pre-órdenes registradas para hoy.</p>';
|
||||
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 `
|
||||
<div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 14px; display: flex; justify-content: space-between; align-items: center;">
|
||||
<div style="display: flex; gap: 12px; align-items: center;">
|
||||
<img src="${ord.foto_url}" style="width: 44px; height: 44px; border-radius: 50%; border: 2px solid #38bdf8;">
|
||||
<div>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<strong style="color: #ffffff; font-size: 0.95rem;">${ord.estudiante_nombre}</strong>
|
||||
<span style="font-size: 0.75rem; color: #94a3b8;">${ord.grado} - ${ord.seccion}</span>
|
||||
<span class="status-pill status-${ord.estado}">${ord.estado}</span>
|
||||
</div>
|
||||
<div style="font-size: 0.8rem; color: #38bdf8; margin: 2px 0;">📦 ${itemsList}</div>
|
||||
<div style="font-size: 0.72rem; color: #94a3b8;">Ticket: ${ord.codigo_orden} • Pedido a las ${hora} • Total: ₡${ord.total_colones.toLocaleString('es-CR')}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px;">
|
||||
${ord.estado === 'pendiente' ? `
|
||||
<button onclick="updateOrderStatus(${ord.id}, 'en_preparacion')" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 8px; font-weight: 700; cursor: pointer;">
|
||||
👨🍳 Preparar
|
||||
</button>
|
||||
` : ''}
|
||||
${ord.estado === 'en_preparacion' ? `
|
||||
<button onclick="updateOrderStatus(${ord.id}, 'listo')" style="padding: 6px 12px; background: #10b981; color: white; border: none; border-radius: 8px; font-weight: 700; cursor: pointer;">
|
||||
🛍️ Listo en Bolsa
|
||||
</button>
|
||||
` : ''}
|
||||
${ord.estado === 'listo' ? `
|
||||
<button onclick="updateOrderStatus(${ord.id}, 'entregado')" style="padding: 6px 14px; background: #059669; color: white; border: none; border-radius: 8px; font-weight: 800; cursor: pointer;">
|
||||
✅ Entregar
|
||||
</button>
|
||||
` : ''}
|
||||
${ord.estado === 'entregado' ? `
|
||||
<span style="font-size: 0.78rem; color: #34d399; font-weight: 800;">✓ Entregado</span>
|
||||
` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Sintetizador Web Audio API para feedback sonoro en tiempo real sin dependencias externas
|
||||
class SoundEffects {
|
||||
constructor() {
|
||||
this.ctx = null;
|
||||
}
|
||||
|
||||
init() {
|
||||
if (!this.ctx) {
|
||||
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
||||
this.ctx = new AudioCtx();
|
||||
}
|
||||
if (this.ctx.state === 'suspended') {
|
||||
this.ctx.resume();
|
||||
}
|
||||
}
|
||||
|
||||
// Sonido de escaneo exitoso / cobro completado (Tono alegre ascendente)
|
||||
playSuccess() {
|
||||
try {
|
||||
this.init();
|
||||
const now = this.ctx.currentTime;
|
||||
const osc1 = this.ctx.createOscillator();
|
||||
const osc2 = this.ctx.createOscillator();
|
||||
const gain = this.ctx.createGain();
|
||||
|
||||
osc1.type = 'triangle';
|
||||
osc2.type = 'sine';
|
||||
|
||||
// Acorde alegre de confirmación: C5 -> E5 -> G5
|
||||
osc1.frequency.setValueAtTime(523.25, now);
|
||||
osc1.frequency.exponentialRampToValueAtTime(659.25, now + 0.1);
|
||||
osc1.frequency.exponentialRampToValueAtTime(783.99, now + 0.2);
|
||||
|
||||
osc2.frequency.setValueAtTime(261.63, now);
|
||||
osc2.frequency.setValueAtTime(329.63, now + 0.1);
|
||||
osc2.frequency.setValueAtTime(392.00, now + 0.2);
|
||||
|
||||
gain.gain.setValueAtTime(0.2, now);
|
||||
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.35);
|
||||
|
||||
osc1.connect(gain);
|
||||
osc2.connect(gain);
|
||||
gain.connect(this.ctx.destination);
|
||||
|
||||
osc1.start(now);
|
||||
osc2.start(now);
|
||||
osc1.stop(now + 0.35);
|
||||
osc2.stop(now + 0.35);
|
||||
} catch (e) {
|
||||
console.warn('Audio no disponible:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Sonido de moneda para Modo Kids
|
||||
playCoin() {
|
||||
try {
|
||||
this.init();
|
||||
const now = this.ctx.currentTime;
|
||||
const osc = this.ctx.createOscillator();
|
||||
const gain = this.ctx.createGain();
|
||||
|
||||
osc.type = 'sine';
|
||||
osc.frequency.setValueAtTime(987.77, now); // B5
|
||||
osc.frequency.setValueAtTime(1318.51, now + 0.08); // E6
|
||||
|
||||
gain.gain.setValueAtTime(0.25, now);
|
||||
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.3);
|
||||
|
||||
osc.connect(gain);
|
||||
gain.connect(this.ctx.destination);
|
||||
|
||||
osc.start(now);
|
||||
osc.stop(now + 0.3);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// Chirp de escáner láser de código de barras
|
||||
playScanChirp() {
|
||||
try {
|
||||
this.init();
|
||||
const now = this.ctx.currentTime;
|
||||
const osc = this.ctx.createOscillator();
|
||||
const gain = this.ctx.createGain();
|
||||
|
||||
osc.type = 'square';
|
||||
osc.frequency.setValueAtTime(2000, now);
|
||||
osc.frequency.exponentialRampToValueAtTime(1200, now + 0.06);
|
||||
|
||||
gain.gain.setValueAtTime(0.15, now);
|
||||
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.07);
|
||||
|
||||
osc.connect(gain);
|
||||
gain.connect(this.ctx.destination);
|
||||
|
||||
osc.start(now);
|
||||
osc.stop(now + 0.07);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// Sonido de error / límite superado (Tono grave de advertencia)
|
||||
playError() {
|
||||
try {
|
||||
this.init();
|
||||
const now = this.ctx.currentTime;
|
||||
const osc = this.ctx.createOscillator();
|
||||
const gain = this.ctx.createGain();
|
||||
|
||||
osc.type = 'sawtooth';
|
||||
osc.frequency.setValueAtTime(220, now);
|
||||
osc.frequency.setValueAtTime(180, now + 0.15);
|
||||
|
||||
gain.gain.setValueAtTime(0.2, now);
|
||||
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.35);
|
||||
|
||||
osc.connect(gain);
|
||||
gain.connect(this.ctx.destination);
|
||||
|
||||
osc.start(now);
|
||||
osc.stop(now + 0.35);
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
window.sounds = new SoundEffects();
|
||||
Reference in New Issue
Block a user