From 7217cefa0f77d5ceeeaea6856f62fe6c90e2f990 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 6 Oct 2026 01:03:54 -0600 Subject: [PATCH] =?UTF-8?q?fix(pos):=20corregir=20recorte=20de=20pesta?= =?UTF-8?q?=C3=B1as=20en=20terminal=20m=C3=B3vil=20y=20a=C3=B1adir=20notif?= =?UTF-8?q?icaciones=20push=20y=20en-app=20para=20recargas=20SINPE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/css/styles.css | 178 +++++++++++++++++++++++++++++- public/js/app.js | 111 ++++++++++++++++++- public/js/pos.js | 249 +++++++++++++++++++++++++++++++++++++----- public/pos.html | 19 +++- public/sw.js | 20 ++++ 5 files changed, 541 insertions(+), 36 deletions(-) diff --git a/public/css/styles.css b/public/css/styles.css index 571337d..9f1bcd5 100644 --- a/public/css/styles.css +++ b/public/css/styles.css @@ -663,21 +663,28 @@ body.dark-mode .floating-cart-bar { gap: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 12px; + width: 100%; + box-sizing: border-box; } .pos-tab-btn { background: #ffffff; - border: 1px solid #cbd5e1; - color: #64748b; + border: 1.5px solid #cbd5e1; + color: #475569; padding: 9px 16px; - border-radius: 10px; + border-radius: 12px; font-size: 0.88rem; - font-weight: 700; + font-weight: 800; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.15s ease; + white-space: nowrap; +} + +.pos-tab-btn .tab-label-short { + display: none; } .pos-tab-btn:hover { @@ -693,6 +700,42 @@ body.dark-mode .floating-cart-bar { box-shadow: 0 2px 5px rgba(15, 23, 42, 0.15); } +@media (max-width: 900px) { + .pos-tabs { + display: grid !important; + grid-template-columns: repeat(3, 1fr) !important; + gap: 6px !important; + width: 100% !important; + padding-bottom: 8px !important; + overflow-x: hidden !important; + } + + .pos-tab-btn { + padding: 7px 4px !important; + font-size: 0.74rem !important; + flex-direction: column !important; + text-align: center !important; + gap: 2px !important; + min-width: 0 !important; + width: 100% !important; + line-height: 1.15 !important; + border-radius: 10px !important; + } + + .pos-tab-btn .tab-icon { + font-size: 1.15rem; + line-height: 1; + } + + .pos-tab-btn .tab-label-full { + display: none !important; + } + + .pos-tab-btn .tab-label-short { + display: inline-block !important; + } +} + /* ========================================================================== BUSCADOR INTELIGENTE DE PRODUCTOS EN MOSTRADOR (POS) ========================================================================== */ @@ -1308,6 +1351,7 @@ body.dark-mode .floating-cart-bar { padding: 14px; padding-bottom: 95px; /* Espacio para barra flotante */ box-sizing: border-box; + overflow-x: hidden !important; } body.pos-mobile-view-catalog .pos-checkout-pane { @@ -3940,3 +3984,129 @@ body.dark-mode .parent-refined-menu-item:hover { body.dark-mode .parent-refined-item-title { color: #f1f5f9; } + +/* ========================================================================== + NOTIFICACIÓN FLOTANTE EN TIEMPO REAL (IN-APP PUSH NOTIFICATION) + ========================================================================== */ +.recreopay-inapp-toast { + position: fixed; + top: 16px; + right: 16px; + left: 16px; + max-width: 450px; + margin-left: auto; + z-index: 999999; + background: #ffffff; + border-radius: 18px; + border: 1.5px solid #10b981; + box-shadow: 0 16px 40px -6px rgba(16, 185, 129, 0.28), 0 4px 16px rgba(0, 0, 0, 0.1); + padding: 12px 16px; + display: flex; + align-items: center; + gap: 12px; + animation: slideDownInApp 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards; + box-sizing: border-box; +} + +@keyframes slideDownInApp { + from { + transform: translateY(-40px) scale(0.95); + opacity: 0; + } + to { + transform: translateY(0) scale(1); + opacity: 1; + } +} + +.recreopay-inapp-toast.closing { + animation: slideUpInApp 0.25s ease forwards; +} + +@keyframes slideUpInApp { + from { + transform: translateY(0) scale(1); + opacity: 1; + } + to { + transform: translateY(-30px) scale(0.95); + opacity: 0; + } +} + +.recreopay-inapp-toast-icon { + width: 42px; + height: 42px; + border-radius: 12px; + background: linear-gradient(135deg, #10b981, #059669); + color: white; + display: flex; + align-items: center; + justify-content: center; + font-size: 1.35rem; + flex-shrink: 0; + box-shadow: 0 4px 12px rgba(16, 185, 129, 0.35); +} + +.recreopay-inapp-toast-content { + flex: 1; + min-width: 0; +} + +.recreopay-inapp-toast-title { + font-size: 0.88rem; + font-weight: 900; + color: #065f46; + display: flex; + align-items: center; + gap: 6px; +} + +.recreopay-inapp-toast-body { + font-size: 0.76rem; + color: #374151; + margin-top: 2px; + line-height: 1.25; +} + +.recreopay-inapp-toast-btn { + background: #10b981; + color: white; + border: none; + border-radius: 8px; + padding: 7px 12px; + font-size: 0.78rem; + font-weight: 800; + cursor: pointer; + white-space: nowrap; + transition: all 0.15s ease; + box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3); +} + +.recreopay-inapp-toast-btn:hover { + background: #059669; + transform: translateY(-1px); +} + +.recreopay-inapp-toast-close { + background: none; + border: none; + color: #9ca3af; + font-size: 1.15rem; + cursor: pointer; + padding: 4px; + line-height: 1; +} + +body.dark-mode .recreopay-inapp-toast { + background: #1e293b; + border-color: #10b981; +} + +body.dark-mode .recreopay-inapp-toast-title { + color: #34d399; +} + +body.dark-mode .recreopay-inapp-toast-body { + color: #cbd5e1; +} diff --git a/public/js/app.js b/public/js/app.js index e9dc787..29fd606 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -55,7 +55,7 @@ document.addEventListener('DOMContentLoaded', async () => { // Registrar Service Worker para PWA if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/sw.js?v=8.1').then(reg => { + navigator.serviceWorker.register('/sw.js?v=8.4').then(reg => { // Registro limpio sin recargas forzadas }).catch(err => console.log('SW error:', err)); } @@ -1631,6 +1631,80 @@ function triggerBalancePulse() { } } +// ========================================== +// SISTEMA DE NOTIFICACIONES PUSH & EN-APP (ADMIN & SODA) +// ========================================== +function sendPushNotification(title, options = {}) { + if (!('Notification' in window) || Notification.permission !== 'granted') return; + + const defaultOptions = { + icon: '/icons/icon-192.png', + badge: '/icons/icon-192.png', + vibrate: [200, 100, 200, 100, 200], + requireInteraction: true, + ...options + }; + + if ('serviceWorker' in navigator && navigator.serviceWorker.ready) { + navigator.serviceWorker.ready.then(reg => { + reg.showNotification(title, defaultOptions); + }).catch(() => { + try { new Notification(title, defaultOptions); } catch (e) {} + }); + } else { + try { new Notification(title, defaultOptions); } catch (e) {} + } +} + +function showInAppNotification({ title, message, buttonText = 'Ver en Terminal', url = '/pos.html?tab=sinpe' }) { + const existing = document.getElementById('recreoPayInAppToast'); + if (existing) existing.remove(); + + const toast = document.createElement('div'); + toast.id = 'recreoPayInAppToast'; + toast.className = 'recreopay-inapp-toast'; + toast.innerHTML = ` +
📱
+
+
+ ${title} +
+
${message}
+
+
+ + +
+ `; + + document.body.appendChild(toast); + + document.getElementById('btnInAppToastAction').onclick = () => { + dismissInAppToast(); + if (url) { + window.location.href = url; + } + }; + + if ('vibrate' in navigator) { + try { navigator.vibrate([200, 100, 200]); } catch (e) {} + } + + if (window.sounds && window.sounds.playCoin) { + try { window.sounds.playCoin(); } catch (e) {} + } + + clearTimeout(window._inAppToastTimer); + window._inAppToastTimer = setTimeout(dismissInAppToast, 14000); +} + +function dismissInAppToast() { + const toast = document.getElementById('recreoPayInAppToast'); + if (!toast) return; + toast.classList.add('closing'); + setTimeout(() => toast.remove(), 250); +} + // SSE en tiempo real para eventos de la soda y monederos let sseSource = null; let sseReconnectTimer = null; @@ -1799,6 +1873,41 @@ function initStudentSSE() { } catch (err) {} }); + // NUEVA SOLICITUD DE RECARGA SINPE (NOTIFICACIÓN ADMIN & PUSH) + sse.addEventListener('solicitud_sinpe_nueva', (e) => { + try { + const sol = JSON.parse(e.data); + const isAdminOrStaff = currentUser && ['admin', 'cajero', 'personal', 'dev', 'soda'].includes(currentUser.rol); + + if (isAdminOrStaff) { + const montoFmt = (sol.monto_colones || 0).toLocaleString('es-CR'); + const estNombre = sol.estudiante_nombre || 'Estudiante'; + const comp = sol.comprobante_sinpe || ''; + + // 1. Notificación flotante en la aplicación + showInAppNotification({ + title: '¡Nueva Recarga SINPE Reportada!', + message: `${estNombre}: ₡${montoFmt} • Comp #${comp}`, + url: '/pos.html?tab=sinpe', + buttonText: 'Ver en Terminal POS' + }); + + // 2. Notificación PUSH del navegador / sistema + sendPushNotification('🔔 Nueva Recarga SINPE - RecreoPay', { + body: `Se reportó una recarga de ₡${montoFmt} para ${estNombre}. Comprobante: #${comp}`, + tag: `sinpe-${sol.id || Date.now()}`, + data: { url: '/pos.html?tab=sinpe' } + }); + } + + if (currentUser && currentUser.rol === 'padre') { + loadParentDashboard(); + } + } catch (err) { + console.warn('Error en SSE solicitud_sinpe_nueva:', err); + } + }); + sse.addEventListener('producto_actualizado', (e) => { try { const prod = JSON.parse(e.data); diff --git a/public/js/pos.js b/public/js/pos.js index 0588ac6..f676e3f 100644 --- a/public/js/pos.js +++ b/public/js/pos.js @@ -76,6 +76,12 @@ function checkPosHttpsEnvironment() { document.addEventListener('DOMContentLoaded', async () => { checkPosHttpsEnvironment(); + + // Registrar Service Worker para Notificaciones PWA + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js?v=8.4').catch(e => console.log('SW register error:', e)); + } + await loadCatalog(); await loadPreOrders(); await loadSinpeRequests(); @@ -83,6 +89,26 @@ document.addEventListener('DOMContentLoaded', async () => { initSSE(); initPistolScanner(); initQuickProductEvents(); + + // Si la URL viene con ?tab=sinpe o ?tab=preordenes, abrir esa pestaña directamente + const urlTab = new URLSearchParams(window.location.search).get('tab'); + if (urlTab === 'sinpe' || urlTab === 'preordenes') { + switchPosTab(urlTab); + } + + // Actualizar estado del botón de notificaciones + updateNotificationButtonState(); + + // Solicitar permiso de notificaciones con cualquier primera interacción táctil/clic + const promptOnFirstInteraction = () => { + if ('Notification' in window && Notification.permission === 'default') { + Notification.requestPermission().then(() => updateNotificationButtonState()).catch(() => {}); + } + window.removeEventListener('click', promptOnFirstInteraction); + window.removeEventListener('touchstart', promptOnFirstInteraction); + }; + window.addEventListener('click', promptOnFirstInteraction, { once: true }); + window.addEventListener('touchstart', promptOnFirstInteraction, { once: true }); }); // Cargar catálogo de productos @@ -1356,8 +1382,30 @@ function initSSE() { }); sseSource.addEventListener('solicitud_sinpe_nueva', (e) => { - if (window.sounds) window.sounds.playCoin(); - loadSinpeRequests(); + try { + const sol = JSON.parse(e.data); + const montoFmt = (sol.monto_colones || 0).toLocaleString('es-CR'); + const estudianteNombre = sol.estudiante_nombre || 'Estudiante'; + const comp = sol.comprobante_sinpe || ''; + + // 1. Notificación flotante en la aplicación (con vibración y sonido de moneda) + showInAppNotification({ + title: '¡Nueva Recarga SINPE Reportada!', + message: `${estudianteNombre}: ₡${montoFmt} • Comp #${comp}`, + buttonText: 'Ver y Aprobar' + }); + + // 2. Notificación PUSH del navegador / sistema operativo + sendPushNotification('🔔 Nueva Recarga SINPE - RecreoPay', { + body: `Se reportó una recarga de ₡${montoFmt} para ${estudianteNombre}. Comprobante: #${comp}`, + tag: `sinpe-${sol.id || Date.now()}`, + data: { url: '/pos.html?tab=sinpe' } + }); + + loadSinpeRequests(); + } catch (err) { + console.error('Error procesando solicitud_sinpe_nueva en POS:', err); + } }); sseSource.addEventListener('solicitud_sinpe_procesada', () => { @@ -1365,6 +1413,152 @@ function initSSE() { }); } +// ========================================== +// SISTEMA DE NOTIFICACIONES PUSH & EN-APP (RECARGAS SINPE) +// ========================================== +function updateNotificationButtonState() { + const btn = document.getElementById('btnPosNotificationToggle'); + const lbl = document.getElementById('lblPosNotificationStatus'); + if (!btn || !lbl) return; + + if (!('Notification' in window)) { + btn.style.display = 'none'; + return; + } + + if (Notification.permission === 'granted') { + btn.style.color = '#16a34a'; + btn.style.borderColor = '#86efac'; + btn.style.background = '#f0fdf4'; + lbl.textContent = 'Notificaciones Activas'; + btn.title = 'Notificaciones push y avisos en pantalla activos'; + } else if (Notification.permission === 'denied') { + btn.style.color = '#dc2626'; + btn.style.borderColor = '#fca5a5'; + btn.style.background = '#fef2f2'; + lbl.textContent = 'Notificaciones Bloqueadas'; + btn.title = 'Las notificaciones están bloqueadas en los ajustes del navegador'; + } else { + btn.style.color = '#0284c7'; + btn.style.borderColor = '#bae6fd'; + btn.style.background = 'white'; + lbl.textContent = 'Activar Notificaciones'; + btn.title = 'Toca para recibir avisos de recargas SINPE'; + } +} + +async function enablePushNotificationsPrompt() { + if (!('Notification' in window)) { + alert('Tu navegador no soporta notificaciones de sistema.'); + return; + } + + if (Notification.permission === 'granted') { + showInAppNotification({ + title: '¡Notificaciones Activas!', + message: 'Recibirás avisos sonoros y visuales cada vez que un padre envíe una recarga SINPE.', + buttonText: 'Entendido' + }); + return; + } + + try { + const perm = await Notification.requestPermission(); + updateNotificationButtonState(); + if (perm === 'granted') { + sendPushNotification('🔔 RecreoPay Terminal Soda', { + body: '¡Notificaciones activadas! Te avisaremos al instante con cada recarga SINPE.', + tag: 'recreopay-welcome' + }); + showInAppNotification({ + title: '¡Notificaciones Activadas!', + message: 'Avisos en pantalla y notificaciones push activadas correctamente.', + buttonText: 'Listo' + }); + } else { + alert('Las notificaciones no fueron autorizadas. Puedes activarlas desde el candado de la barra de direcciones.'); + } + } catch (err) { + console.error('Error solicitando permisos de notificación:', err); + } +} + +function sendPushNotification(title, options = {}) { + if (!('Notification' in window) || Notification.permission !== 'granted') return; + + const defaultOptions = { + icon: '/icons/icon-192.png', + badge: '/icons/icon-192.png', + vibrate: [200, 100, 200, 100, 200], + requireInteraction: true, + ...options + }; + + if ('serviceWorker' in navigator && navigator.serviceWorker.ready) { + navigator.serviceWorker.ready.then(reg => { + reg.showNotification(title, defaultOptions); + }).catch(() => { + try { new Notification(title, defaultOptions); } catch (e) {} + }); + } else { + try { new Notification(title, defaultOptions); } catch (e) {} + } +} + +function showInAppNotification({ title, message, buttonText = 'Ver y Aprobar', url = null }) { + const existing = document.getElementById('recreoPayInAppToast'); + if (existing) existing.remove(); + + const toast = document.createElement('div'); + toast.id = 'recreoPayInAppToast'; + toast.className = 'recreopay-inapp-toast'; + toast.innerHTML = ` +
📱
+
+
+ ${title} +
+
${message}
+
+
+ + +
+ `; + + document.body.appendChild(toast); + + document.getElementById('btnInAppToastAction').onclick = () => { + dismissInAppToast(); + if (typeof switchPosTab === 'function') { + switchPosTab('sinpe'); + } else if (url) { + window.location.href = url; + } + }; + + // Vibrar en dispositivos móviles + if ('vibrate' in navigator) { + try { navigator.vibrate([200, 100, 200]); } catch (e) {} + } + + // Sonido de recarga + if (window.sounds && window.sounds.playCoin) { + try { window.sounds.playCoin(); } catch (e) {} + } + + // Auto cerrar tras 14s + clearTimeout(window._inAppToastTimer); + window._inAppToastTimer = setTimeout(dismissInAppToast, 14000); +} + +function dismissInAppToast() { + const toast = document.getElementById('recreoPayInAppToast'); + if (!toast) return; + toast.classList.add('closing'); + setTimeout(() => toast.remove(), 250); +} + // ========================================== // RECARGAS SINPE EN POS // ========================================== @@ -1418,39 +1612,40 @@ async function loadSinpeRequests() { }); return ` -
-
- Foto -
-
${s.estudiante_nombre}
-
- ${s.estudiante_grado || ''} ${s.estudiante_seccion ? '• Sec. ' + s.estudiante_seccion : ''} - Saldo actual: ₡${(s.estudiante_saldo || 0).toLocaleString('es-CR')} +
+
+
+ Foto +
+
${s.estudiante_nombre}
+
+ ${s.estudiante_grado || ''} ${s.estudiante_seccion ? '• Sec. ' + s.estudiante_seccion : ''} +
+
+ Reportado: ${fecha} +
-
- Reportado: ${fecha} +
+ +
+
+ +₡${s.monto_colones.toLocaleString('es-CR')} +
+
+ Comp: #${s.comprobante_sinpe}
-
-
- +₡${s.monto_colones.toLocaleString('es-CR')} -
-
- Comp: #${s.comprobante_sinpe} -
-
- -
- - +
`; diff --git a/public/pos.html b/public/pos.html index 8cf01a2..01befc1 100644 --- a/public/pos.html +++ b/public/pos.html @@ -80,6 +80,9 @@ En Línea (SSE) + 👨‍🍳 Admin @@ -89,16 +92,24 @@
- +
diff --git a/public/sw.js b/public/sw.js index f42fdf3..558286b 100644 --- a/public/sw.js +++ b/public/sw.js @@ -75,3 +75,23 @@ self.addEventListener('fetch', (event) => { }) ); }); + +// Manejador de clics en Notificaciones Push +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + const urlToOpen = (event.notification.data && event.notification.data.url) || '/pos.html?tab=sinpe'; + + event.waitUntil( + clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => { + for (const client of windowClients) { + if (client.url && (client.url.includes('pos.html') || client.url.includes('index.html'))) { + client.navigate(urlToOpen); + return client.focus(); + } + } + if (clients.openWindow) { + return clients.openWindow(urlToOpen); + } + }) + ); +});