feat(push): implementar Web Push VAPID en segundo plano con app cerrada para iOS y Android

This commit is contained in:
unknown
2026-10-06 01:29:25 -06:00
parent a948ed03fd
commit 70700356a7
7 changed files with 516 additions and 16 deletions
+141 -1
View File
@@ -15,7 +15,8 @@
"jsqr": "^1.4.0", "jsqr": "^1.4.0",
"pg": "^8.23.1", "pg": "^8.23.1",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"synckit": "^0.11.13" "synckit": "^0.11.13",
"web-push": "^3.6.7"
} }
}, },
"node_modules/@pkgr/core": { "node_modules/@pkgr/core": {
@@ -43,6 +44,15 @@
"node": ">= 0.6" "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": { "node_modules/ansi-regex": {
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "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" "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": { "node_modules/better-sqlite3": {
"version": "13.0.3", "version": "13.0.3",
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz",
@@ -79,6 +101,12 @@
"node": ">=22" "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": { "node_modules/body-parser": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
@@ -116,6 +144,12 @@
"url": "https://opencollective.com/express" "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": { "node_modules/bytes": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -304,6 +338,15 @@
"node": ">= 0.4" "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": { "node_modules/ee-first": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -556,6 +599,15 @@
"node": ">= 0.4" "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": { "node_modules/http-errors": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -576,6 +628,19 @@
"url": "https://opencollective.com/express" "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": { "node_modules/iconv-lite": {
"version": "0.7.3", "version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
@@ -628,6 +693,27 @@
"integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==", "integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==",
"license": "Apache-2.0" "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": { "node_modules/locate-path": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
@@ -699,6 +785,21 @@
"url": "https://opencollective.com/express" "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": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -1095,6 +1196,26 @@
"node": ">= 18" "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": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1347,6 +1468,25 @@
"node": ">= 0.8" "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": { "node_modules/which-module": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
+2 -1
View File
@@ -27,6 +27,7 @@
"jsqr": "^1.4.0", "jsqr": "^1.4.0",
"pg": "^8.23.1", "pg": "^8.23.1",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"synckit": "^0.11.13" "synckit": "^0.11.13",
"web-push": "^3.6.7"
} }
} }
+66 -5
View File
@@ -55,8 +55,10 @@ document.addEventListener('DOMContentLoaded', async () => {
// Registrar Service Worker para PWA // Registrar Service Worker para PWA
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js?v=8.4').then(reg => { navigator.serviceWorker.register('/sw.js?v=8.5').then(reg => {
// Registro limpio sin recargas forzadas if ('Notification' in window && Notification.permission === 'granted') {
subscribeDeviceToWebPush().catch(() => {});
}
}).catch(err => console.log('SW error:', err)); }).catch(err => console.log('SW error:', err));
} }
@@ -1652,9 +1654,68 @@ function triggerBalancePulse() {
} }
} }
// ========================================== function urlBase64ToUint8Array(base64String) {
// SISTEMA DE NOTIFICACIONES PUSH & EN-APP (ADMIN & SODA) 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 = {}) { function sendPushNotification(title, options = {}) {
if (!('Notification' in window) || Notification.permission !== 'granted') return; if (!('Notification' in window) || Notification.permission !== 'granted') return;
+83 -5
View File
@@ -79,7 +79,11 @@ document.addEventListener('DOMContentLoaded', async () => {
// Registrar Service Worker para Notificaciones PWA // Registrar Service Worker para Notificaciones PWA
if ('serviceWorker' in navigator) { 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(); await loadCatalog();
@@ -102,7 +106,10 @@ document.addEventListener('DOMContentLoaded', async () => {
// Solicitar permiso de notificaciones con cualquier primera interacción táctil/clic // Solicitar permiso de notificaciones con cualquier primera interacción táctil/clic
const promptOnFirstInteraction = () => { const promptOnFirstInteraction = () => {
if ('Notification' in window && Notification.permission === 'default') { 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('click', promptOnFirstInteraction);
window.removeEventListener('touchstart', 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() { async function enablePushNotificationsPrompt() {
if (!('Notification' in window)) { if (!('Notification' in window)) {
alert('Tu navegador no soporta notificaciones de sistema.'); alert('Tu navegador no soporta notificaciones de sistema.');
return; 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') { if (Notification.permission === 'granted') {
await subscribeDeviceToWebPush();
showInAppNotification({ showInAppNotification({
title: '¡Notificaciones Activas!', 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' buttonText: 'Entendido'
}); });
return; return;
@@ -1466,13 +1543,14 @@ async function enablePushNotificationsPrompt() {
const perm = await Notification.requestPermission(); const perm = await Notification.requestPermission();
updateNotificationButtonState(); updateNotificationButtonState();
if (perm === 'granted') { if (perm === 'granted') {
await subscribeDeviceToWebPush();
sendPushNotification('🔔 RecreoPay Terminal Soda', { 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' tag: 'recreopay-welcome'
}); });
showInAppNotification({ showInAppNotification({
title: '¡Notificaciones Activadas!', 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' buttonText: 'Listo'
}); });
} else { } else {
+28 -2
View File
@@ -1,5 +1,5 @@
// RecreoPay PWA Service Worker v8.3 - Buscador Inteligente Carga Manual // RecreoPay PWA Service Worker v8.5 - Soporte Web Push VAPID en Segundo Plano
const CACHE_NAME = 'recreopay-v8.3'; const CACHE_NAME = 'recreopay-v8.5';
const STATIC_ASSETS = [ const STATIC_ASSETS = [
'/', '/',
'/index.html', '/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 // Manejador de clics en Notificaciones Push
self.addEventListener('notificationclick', (event) => { self.addEventListener('notificationclick', (event) => {
event.notification.close(); event.notification.close();
+57 -1
View File
@@ -324,6 +324,22 @@ function initDatabase() {
`); `);
} catch (e) {} } 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(); seedInitialData();
seedUsuarios(); seedUsuarios();
seedDisenosTarjetas(); seedDisenosTarjetas();
@@ -1187,6 +1203,43 @@ function procesarSolicitudRecargaSinpe({ solicitudId, accion, usuarioId, motivo
return transaction(); 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 = { module.exports = {
db, db,
initDatabase, initDatabase,
@@ -1198,5 +1251,8 @@ module.exports = {
crearSolicitudRecargaSinpe, crearSolicitudRecargaSinpe,
obtenerSolicitudesRecargaSinpe, obtenerSolicitudesRecargaSinpe,
obtenerSolicitudesRecargaPorEstudiante, obtenerSolicitudesRecargaPorEstudiante,
procesarSolicitudRecargaSinpe procesarSolicitudRecargaSinpe,
guardarSuscripcionPush,
obtenerSuscripcionesPush,
eliminarSuscripcionPush
}; };
+139 -1
View File
@@ -21,9 +21,60 @@ const {
crearSolicitudRecargaSinpe, crearSolicitudRecargaSinpe,
obtenerSolicitudesRecargaSinpe, obtenerSolicitudesRecargaSinpe,
obtenerSolicitudesRecargaPorEstudiante, obtenerSolicitudesRecargaPorEstudiante,
procesarSolicitudRecargaSinpe procesarSolicitudRecargaSinpe,
guardarSuscripcionPush,
obtenerSuscripcionesPush,
eliminarSuscripcionPush
} = require('./db'); } = 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:[email protected]';
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 app = express();
const PORT = process.env.PORT || 3030; const PORT = process.env.PORT || 3030;
@@ -1679,6 +1730,20 @@ app.post('/api/sinpe/solicitar', (req, res) => {
broadcastEvent('solicitud_sinpe_nueva', payloadNotificacion); 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({ res.json({
success: true, success: true,
mensaje: 'Solicitud de recarga enviada. La soda verificará el comprobante en breve.', 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) // Actualizar configuración parental (Límite diario, restricciones y transferencias P2P)
app.put('/api/estudiantes/:id/limite', (req, res) => { app.put('/api/estudiantes/:id/limite', (req, res) => {
try { try {