From 70700356a7d4755526f42901040347fff75ac94d Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 6 Oct 2026 01:29:25 -0600 Subject: [PATCH] feat(push): implementar Web Push VAPID en segundo plano con app cerrada para iOS y Android --- package-lock.json | 142 +++++++++++++++++++++++++++++++++++++++++++++- package.json | 3 +- public/js/app.js | 71 +++++++++++++++++++++-- public/js/pos.js | 88 ++++++++++++++++++++++++++-- public/sw.js | 30 +++++++++- server/db.js | 58 ++++++++++++++++++- server/server.js | 140 ++++++++++++++++++++++++++++++++++++++++++++- 7 files changed, 516 insertions(+), 16 deletions(-) diff --git a/package-lock.json b/package-lock.json index 23c68da..085cffc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,8 @@ "jsqr": "^1.4.0", "pg": "^8.23.1", "qrcode": "^1.5.4", - "synckit": "^0.11.13" + "synckit": "^0.11.13", + "web-push": "^3.6.7" } }, "node_modules/@pkgr/core": { @@ -43,6 +44,15 @@ "node": ">= 0.6" } }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -67,6 +77,18 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, "node_modules/better-sqlite3": { "version": "13.0.3", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", @@ -79,6 +101,12 @@ "node": ">=22" } }, + "node_modules/bn.js": { + "version": "4.12.5", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz", + "integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==", + "license": "MIT" + }, "node_modules/body-parser": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", @@ -116,6 +144,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -304,6 +338,15 @@ "node": ">= 0.4" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -556,6 +599,15 @@ "node": ">= 0.4" } }, + "node_modules/http_ece": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", + "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -576,6 +628,19 @@ "url": "https://opencollective.com/express" } }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/iconv-lite": { "version": "0.7.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", @@ -628,6 +693,27 @@ "integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==", "license": "Apache-2.0" }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -699,6 +785,21 @@ "url": "https://opencollective.com/express" } }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -1095,6 +1196,26 @@ "node": ">= 18" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -1347,6 +1468,25 @@ "node": ">= 0.8" } }, + "node_modules/web-push": { + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", + "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "license": "MPL-2.0", + "dependencies": { + "asn1.js": "^5.3.0", + "http_ece": "1.2.0", + "https-proxy-agent": "^7.0.0", + "jws": "^4.0.0", + "minimist": "^1.2.5" + }, + "bin": { + "web-push": "src/cli.js" + }, + "engines": { + "node": ">= 16" + } + }, "node_modules/which-module": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", diff --git a/package.json b/package.json index 09fdb03..47f2539 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "jsqr": "^1.4.0", "pg": "^8.23.1", "qrcode": "^1.5.4", - "synckit": "^0.11.13" + "synckit": "^0.11.13", + "web-push": "^3.6.7" } } diff --git a/public/js/app.js b/public/js/app.js index 1d53803..b9800e5 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -55,8 +55,10 @@ document.addEventListener('DOMContentLoaded', async () => { // Registrar Service Worker para PWA if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/sw.js?v=8.4').then(reg => { - // Registro limpio sin recargas forzadas + navigator.serviceWorker.register('/sw.js?v=8.5').then(reg => { + if ('Notification' in window && Notification.permission === 'granted') { + subscribeDeviceToWebPush().catch(() => {}); + } }).catch(err => console.log('SW error:', err)); } @@ -1652,9 +1654,68 @@ function triggerBalancePulse() { } } -// ========================================== -// SISTEMA DE NOTIFICACIONES PUSH & EN-APP (ADMIN & SODA) -// ========================================== +function urlBase64ToUint8Array(base64String) { + const padding = '='.repeat((4 - base64String.length % 4) % 4); + const base64 = (base64String + padding) + .replace(/\-/g, '+') + .replace(/_/g, '/'); + + const rawData = window.atob(base64); + const outputArray = new Uint8Array(rawData.length); + + for (let i = 0; i < rawData.length; ++i) { + outputArray[i] = rawData.charCodeAt(i); + } + return outputArray; +} + +async function subscribeDeviceToWebPush() { + if (!('serviceWorker' in navigator) || !('PushManager' in window)) { + return null; + } + + try { + const reg = await navigator.serviceWorker.ready; + let sub = await reg.pushManager.getSubscription(); + + if (!sub) { + const resKey = await fetch('/api/push/vapid-public-key'); + const dataKey = await resKey.json(); + if (!dataKey || !dataKey.publicKey) return null; + + const convertedKey = urlBase64ToUint8Array(dataKey.publicKey); + sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: convertedKey + }); + } + + let user = currentUser; + if (!user) { + try { + const stored = localStorage.getItem('recreopay_user'); + if (stored) user = JSON.parse(stored); + } catch (e) {} + } + + await fetch('/api/push/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + subscription: sub, + userId: user ? user.id : null, + rol: user ? user.rol : 'admin', + escuelaId: user ? user.escuela_id : 1 + }) + }); + + return sub; + } catch (err) { + console.warn('[WebPush] Error suscribiendo dispositivo:', err); + return null; + } +} + function sendPushNotification(title, options = {}) { if (!('Notification' in window) || Notification.permission !== 'granted') return; diff --git a/public/js/pos.js b/public/js/pos.js index f676e3f..a2cd4f2 100644 --- a/public/js/pos.js +++ b/public/js/pos.js @@ -79,7 +79,11 @@ document.addEventListener('DOMContentLoaded', async () => { // 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)); + navigator.serviceWorker.register('/sw.js?v=8.5').then(() => { + if ('Notification' in window && Notification.permission === 'granted') { + subscribeDeviceToWebPush().catch(() => {}); + } + }).catch(e => console.log('SW register error:', e)); } await loadCatalog(); @@ -102,7 +106,10 @@ document.addEventListener('DOMContentLoaded', async () => { // 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(() => {}); + Notification.requestPermission().then((p) => { + updateNotificationButtonState(); + if (p === 'granted') subscribeDeviceToWebPush().catch(() => {}); + }).catch(() => {}); } window.removeEventListener('click', promptOnFirstInteraction); window.removeEventListener('touchstart', promptOnFirstInteraction); @@ -1447,16 +1454,86 @@ function updateNotificationButtonState() { } } +function urlBase64ToUint8Array(base64String) { + const padding = '='.repeat((4 - base64String.length % 4) % 4); + const base64 = (base64String + padding) + .replace(/\-/g, '+') + .replace(/_/g, '/'); + + const rawData = window.atob(base64); + const outputArray = new Uint8Array(rawData.length); + + for (let i = 0; i < rawData.length; ++i) { + outputArray[i] = rawData.charCodeAt(i); + } + return outputArray; +} + +async function subscribeDeviceToWebPush() { + if (!('serviceWorker' in navigator) || !('PushManager' in window)) { + console.log('[WebPush] PushManager no soportado en este navegador'); + return null; + } + + try { + const reg = await navigator.serviceWorker.ready; + let sub = await reg.pushManager.getSubscription(); + + if (!sub) { + const resKey = await fetch('/api/push/vapid-public-key'); + const dataKey = await resKey.json(); + if (!dataKey || !dataKey.publicKey) return null; + + const convertedKey = urlBase64ToUint8Array(dataKey.publicKey); + sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: convertedKey + }); + } + + let user = null; + try { + const stored = localStorage.getItem('recreopay_user'); + if (stored) user = JSON.parse(stored); + } catch (e) {} + + await fetch('/api/push/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + subscription: sub, + userId: user ? user.id : null, + rol: user ? user.rol : 'cajero', + escuelaId: user ? user.escuela_id : 1 + }) + }); + + console.log('[WebPush] Dispositivo registrado exitosamente para alertas con app cerrada'); + return sub; + } catch (err) { + console.warn('[WebPush] Error suscribiendo dispositivo a Web Push:', err); + return null; + } +} + async function enablePushNotificationsPrompt() { if (!('Notification' in window)) { alert('Tu navegador no soporta notificaciones de sistema.'); return; } + const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; + const isStandalone = window.navigator.standalone || window.matchMedia('(display-mode: standalone)').matches; + + if (isIOS && !isStandalone) { + alert('📱 Consejo para iPhone (iOS):\nPara recibir notificaciones aun con la app cerrada, toca Compartir en Safari (icono de cuadrado con flecha arriba) y selecciona "Agregar al inicio". Desde el icono en la pantalla de inicio recibirás las alertas siempre.'); + } + if (Notification.permission === 'granted') { + await subscribeDeviceToWebPush(); showInAppNotification({ title: '¡Notificaciones Activas!', - message: 'Recibirás avisos sonoros y visuales cada vez que un padre envíe una recarga SINPE.', + message: 'Recibirás avisos sonoros y en pantalla de bloqueo incluso con la app cerrada cada vez que un padre envíe una recarga SINPE.', buttonText: 'Entendido' }); return; @@ -1466,13 +1543,14 @@ async function enablePushNotificationsPrompt() { const perm = await Notification.requestPermission(); updateNotificationButtonState(); if (perm === 'granted') { + await subscribeDeviceToWebPush(); sendPushNotification('🔔 RecreoPay Terminal Soda', { - body: '¡Notificaciones activadas! Te avisaremos al instante con cada recarga SINPE.', + body: '¡Notificaciones activadas! Te avisaremos al instante con cada recarga SINPE, aun con la app cerrada.', tag: 'recreopay-welcome' }); showInAppNotification({ title: '¡Notificaciones Activadas!', - message: 'Avisos en pantalla y notificaciones push activadas correctamente.', + message: 'Avisos en pantalla y notificaciones de fondo con app cerrada activadas correctamente.', buttonText: 'Listo' }); } else { diff --git a/public/sw.js b/public/sw.js index 558286b..bc02355 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,5 +1,5 @@ -// RecreoPay PWA Service Worker v8.3 - Buscador Inteligente Carga Manual -const CACHE_NAME = 'recreopay-v8.3'; +// RecreoPay PWA Service Worker v8.5 - Soporte Web Push VAPID en Segundo Plano +const CACHE_NAME = 'recreopay-v8.5'; const STATIC_ASSETS = [ '/', '/index.html', @@ -76,6 +76,32 @@ self.addEventListener('fetch', (event) => { ); }); +// Manejador de Notificaciones Push de Fondo (VAPID) - Activo aun con la app CERRADA +self.addEventListener('push', (event) => { + let data = {}; + if (event.data) { + try { + data = event.data.json(); + } catch (e) { + data = { title: '🔔 RecreoPay', body: event.data.text() }; + } + } + + const title = data.title || '🔔 RecreoPay'; + const options = { + body: data.body || 'Tienes una nueva notificación de RecreoPay', + icon: data.icon || '/icons/icon-192.png', + badge: data.badge || '/icons/icon-192.png', + vibrate: [250, 100, 250, 100, 250], + data: data.data || { url: '/pos.html?tab=sinpe' }, + tag: data.tag || `recreopay-push-${Date.now()}`, + renotify: true, + requireInteraction: true + }; + + event.waitUntil(self.registration.showNotification(title, options)); +}); + // Manejador de clics en Notificaciones Push self.addEventListener('notificationclick', (event) => { event.notification.close(); diff --git a/server/db.js b/server/db.js index 2cb6056..11d027f 100644 --- a/server/db.js +++ b/server/db.js @@ -324,6 +324,22 @@ function initDatabase() { `); } catch (e) {} + // 12. Suscripciones Web Push (VAPID) para Alertas en Segundo Plano (App Cerrada) + try { + db.exec(` + CREATE TABLE IF NOT EXISTS push_subscriptions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + endpoint TEXT UNIQUE NOT NULL, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + user_id INTEGER, + rol TEXT, + escuela_id INTEGER, + creado_en DATETIME DEFAULT CURRENT_TIMESTAMP + ); + `); + } catch (e) {} + seedInitialData(); seedUsuarios(); seedDisenosTarjetas(); @@ -1187,6 +1203,43 @@ function procesarSolicitudRecargaSinpe({ solicitudId, accion, usuarioId, motivo return transaction(); } +function guardarSuscripcionPush({ endpoint, p256dh, auth, userId = null, rol = 'cajero', escuelaId = 1 }) { + const stmt = db.prepare(` + INSERT INTO push_subscriptions (endpoint, p256dh, auth, user_id, rol, escuela_id) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(endpoint) DO UPDATE SET + p256dh = excluded.p256dh, + auth = excluded.auth, + user_id = excluded.user_id, + rol = excluded.rol, + escuela_id = excluded.escuela_id, + creado_en = CURRENT_TIMESTAMP + `); + return stmt.run(endpoint, p256dh, auth, userId, rol, escuelaId); +} + +function obtenerSuscripcionesPush({ escuelaId = null, roles = null } = {}) { + let query = 'SELECT * FROM push_subscriptions WHERE 1=1'; + const params = []; + + if (escuelaId) { + query += ' AND (escuela_id = ? OR escuela_id IS NULL)'; + params.push(escuelaId); + } + + if (roles && Array.isArray(roles) && roles.length > 0) { + const placeholders = roles.map(() => '?').join(','); + query += ` AND rol IN (${placeholders})`; + params.push(...roles); + } + + return db.prepare(query).all(...params); +} + +function eliminarSuscripcionPush(endpoint) { + return db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint); +} + module.exports = { db, initDatabase, @@ -1198,5 +1251,8 @@ module.exports = { crearSolicitudRecargaSinpe, obtenerSolicitudesRecargaSinpe, obtenerSolicitudesRecargaPorEstudiante, - procesarSolicitudRecargaSinpe + procesarSolicitudRecargaSinpe, + guardarSuscripcionPush, + obtenerSuscripcionesPush, + eliminarSuscripcionPush }; diff --git a/server/server.js b/server/server.js index d0dcb86..c750460 100644 --- a/server/server.js +++ b/server/server.js @@ -21,9 +21,60 @@ const { crearSolicitudRecargaSinpe, obtenerSolicitudesRecargaSinpe, obtenerSolicitudesRecargaPorEstudiante, - procesarSolicitudRecargaSinpe + procesarSolicitudRecargaSinpe, + guardarSuscripcionPush, + obtenerSuscripcionesPush, + eliminarSuscripcionPush } = require('./db'); +const webpush = require('web-push'); + +// Configuración VAPID para Web Push en Segundo Plano (App Cerrada en iOS / Android) +const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY || 'BDHXXfRHdftR2qg-WV5Trz85t8hIllB7_gBdfKut747-XihlnbQgstbMc94P5SR4vGUWgKE_mE9WClaRc-Lp060'; +const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || 'ufOrxmh5a2ouxonOyue-ZSQJPWMN0dq6CkbDYErgZaw'; +const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:soporte@recreopay.cr'; + +try { + webpush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY); + console.log('🔔 VAPID Web Push configurado correctamente'); +} catch (e) { + console.warn('⚠️ Error configurando VAPID Web Push:', e.message); +} + +async function sendWebPushNotification({ escuelaId = null, payload, roles = ['admin', 'soda', 'cajero', 'developer'] } = {}) { + try { + const subs = obtenerSuscripcionesPush({ escuelaId, roles }); + if (!subs || subs.length === 0) return; + + const payloadString = typeof payload === 'string' ? payload : JSON.stringify(payload); + + const promises = subs.map(async (sub) => { + const pushConfig = { + endpoint: sub.endpoint, + keys: { + p256dh: sub.p256dh, + auth: sub.auth + } + }; + + try { + await webpush.sendNotification(pushConfig, payloadString); + } catch (err) { + if (err.statusCode === 404 || err.statusCode === 410) { + console.log('[WebPush] Suscripción expirada o removida, eliminando:', sub.endpoint); + eliminarSuscripcionPush(sub.endpoint); + } else { + console.warn('[WebPush] Aviso al enviar notificación:', err.message); + } + } + }); + + await Promise.allSettled(promises); + } catch (error) { + console.error('[WebPush] Error general en sendWebPushNotification:', error); + } +} + const app = express(); const PORT = process.env.PORT || 3030; @@ -1679,6 +1730,20 @@ app.post('/api/sinpe/solicitar', (req, res) => { broadcastEvent('solicitud_sinpe_nueva', payloadNotificacion); + // Enviar notificación Web Push a dispositivos suscritos (funciona con la app 100% cerrada) + const montoFmt = Number(payloadNotificacion.monto_colones || montoNum).toLocaleString('es-CR'); + sendWebPushNotification({ + escuelaId: nuevaSol.escuela_id || 1, + payload: { + title: '🔔 Nueva Recarga SINPE - RecreoPay', + body: `Recarga de ₡${montoFmt} para ${payloadNotificacion.estudiante_nombre}. Comprobante: #${payloadNotificacion.comprobante_sinpe}`, + icon: '/icons/icon-192.png', + badge: '/icons/icon-192.png', + tag: `sinpe-${payloadNotificacion.id || Date.now()}`, + data: { url: '/pos.html?tab=sinpe' } + } + }); + res.json({ success: true, mensaje: 'Solicitud de recarga enviada. La soda verificará el comprobante en breve.', @@ -1738,6 +1803,79 @@ app.post('/api/sinpe/procesar', (req, res) => { } }); +// ========================================== +// ENDPOINTS DE SUSCRIPCIÓN WEB PUSH (VAPID) +// ========================================== + +// 1. Obtener la llave pública VAPID +app.get('/api/push/vapid-public-key', (req, res) => { + res.json({ publicKey: VAPID_PUBLIC_KEY }); +}); + +// 2. Registrar o renovar suscripción del dispositivo +app.post('/api/push/subscribe', (req, res) => { + try { + const { subscription, userId, rol, escuelaId } = req.body; + if (!subscription || !subscription.endpoint || !subscription.keys) { + return res.status(400).json({ error: 'Suscripción inválida' }); + } + + const { endpoint, keys } = subscription; + const { p256dh, auth } = keys; + + if (!p256dh || !auth) { + return res.status(400).json({ error: 'Faltan llaves de cifrado en la suscripción' }); + } + + guardarSuscripcionPush({ + endpoint, + p256dh, + auth, + userId: userId ? parseInt(userId, 10) : null, + rol: rol || 'cajero', + escuelaId: escuelaId ? parseInt(escuelaId, 10) : 1 + }); + + console.log(`[WebPush] Dispositivo suscrito con éxito (Rol: ${rol || 'cajero'})`); + res.json({ success: true, message: 'Dispositivo suscrito a notificaciones push' }); + } catch (err) { + console.error('Error suscribiendo push:', err); + res.status(500).json({ error: err.message }); + } +}); + +// 3. Cancelar suscripción +app.post('/api/push/unsubscribe', (req, res) => { + try { + const { endpoint } = req.body; + if (endpoint) { + eliminarSuscripcionPush(endpoint); + } + res.json({ success: true }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +// 4. Enviar notificación de prueba a los dispositivos suscritos +app.post('/api/push/test', async (req, res) => { + try { + await sendWebPushNotification({ + payload: { + title: '🔔 Prueba de Notificación - RecreoPay', + body: '¡Excelente! Las notificaciones funcionan en segundo plano incluso con la app cerrada.', + icon: '/icons/icon-192.png', + badge: '/icons/icon-192.png', + tag: 'test-push', + data: { url: '/pos.html?tab=sinpe' } + } + }); + res.json({ success: true, message: 'Notificación de prueba enviada' }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + // Actualizar configuración parental (Límite diario, restricciones y transferencias P2P) app.put('/api/estudiantes/:id/limite', (req, res) => { try {