Files
2026-08-23 09:04:47 +00:00

87 lines
2.5 KiB
JavaScript

const cron = require('node-cron');
const webPush = require('web-push');
const pool = require('../config/db');
const publicVapidKey = process.env.VAPID_PUBLIC_KEY;
const privateVapidKey = process.env.VAPID_PRIVATE_KEY;
if (publicVapidKey && privateVapidKey) {
webPush.setVapidDetails('mailto:pierre@secourit.fr', publicVapidKey, privateVapidKey);
}
const REMINDER_MESSAGES = [
{
title: 'Dyna Biz Coignières',
body: 'Pensez à mettre à jour vos invités et recommandations !',
icon: '/logo.svg',
badge: '/favicon.svg',
},
];
function getNextReminderDate(days) {
const d = new Date();
d.setDate(d.getDate() + days);
d.setHours(9, 0, 0, 0);
return d;
}
async function sendReminders() {
console.log('[Push Cron] Checking reminders...');
try {
const [subscriptions] = await pool.query(
`SELECT ps.*, u.prenom, u.nom
FROM push_subscriptions ps
JOIN users u ON u.id = ps.user_id
WHERE ps.last_sent_at IS NULL
OR DATE_ADD(ps.last_sent_at, INTERVAL ps.reminder_days DAY) <= NOW()`
);
console.log(`[Push Cron] Found ${subscriptions.length} subscription(s) to notify`);
for (const sub of subscriptions) {
try {
const msg = REMINDER_MESSAGES[0];
const payload = JSON.stringify({
title: msg.title,
body: msg.body,
icon: msg.icon,
badge: msg.badge,
data: { url: '/' },
});
await webPush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
payload
);
await pool.query('UPDATE push_subscriptions SET last_sent_at = NOW() WHERE id = ?', [sub.id]);
console.log(`[Push Cron] Sent to ${sub.prenom} ${sub.nom}`);
} catch (err) {
if (err.statusCode === 410 || err.statusCode === 404) {
await pool.query('DELETE FROM push_subscriptions WHERE id = ?', [sub.id]);
console.log(`[Push Cron] Removed expired subscription for ${sub.prenom} ${sub.nom}`);
} else {
console.error(`[Push Cron] Error sending to ${sub.prenom} ${sub.nom}:`, err.message);
}
}
}
} catch (err) {
console.error('[Push Cron] Error:', err);
}
}
function startPushCron() {
if (!publicVapidKey || !privateVapidKey) {
console.log('[Push Cron] VAPID keys not configured — skipping cron start');
return;
}
cron.schedule('0 9 * * *', () => {
sendReminders();
});
console.log('[Push Cron] Scheduled daily at 09:00');
}
module.exports = { startPushCron, sendReminders };