Fix
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import db from '../db/index.js';
|
||||
|
||||
const JOB_NAME = 'auto_clean_notifs';
|
||||
|
||||
function writeLog({ status, nbChanges, details, errorMsg }) {
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT INTO job_logs (job_name, status, nb_changes, details, error_msg)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`).run(JOB_NAME, status, nbChanges ?? 0, details ?? null, errorMsg ?? null);
|
||||
} catch (e) {
|
||||
console.error('[autoCleanNotifs] Impossible d\'écrire dans job_logs :', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime les notifications de plus de 7 jours,
|
||||
* à l'exception des notifications de type 'security'.
|
||||
*/
|
||||
export function cleanOldNotifs() {
|
||||
const result = db.prepare(`
|
||||
DELETE FROM notifications
|
||||
WHERE type != 'security'
|
||||
AND datetime(created_at) < datetime('now', '-7 days')
|
||||
`).run();
|
||||
|
||||
const nbChanges = result.changes;
|
||||
const details = nbChanges === 0
|
||||
? 'Aucune notification supprimée'
|
||||
: `${nbChanges} notification(s) supprimée(s) (>7 jours, hors sécurité)`;
|
||||
|
||||
writeLog({ status: 'ok', nbChanges, details });
|
||||
if (nbChanges > 0) {
|
||||
console.log(`[autoCleanNotifs] ${details}`);
|
||||
}
|
||||
return nbChanges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarre le job — exécution immédiate au démarrage, puis toutes les heures.
|
||||
*/
|
||||
export function startAutoCleanNotifsJob() {
|
||||
const INTERVAL_MS = 60 * 60 * 1000; // 1 heure
|
||||
|
||||
try {
|
||||
cleanOldNotifs();
|
||||
} catch (err) {
|
||||
console.error('[autoCleanNotifs] Erreur initiale :', err);
|
||||
writeLog({ status: 'error', nbChanges: 0, errorMsg: err.message });
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
try {
|
||||
cleanOldNotifs();
|
||||
} catch (err) {
|
||||
console.error('[autoCleanNotifs] Erreur :', err);
|
||||
writeLog({ status: 'error', nbChanges: 0, errorMsg: err.message });
|
||||
}
|
||||
}, INTERVAL_MS);
|
||||
|
||||
console.log('[autoCleanNotifs] Job démarré — nettoyage toutes les heures');
|
||||
}
|
||||
@@ -34,6 +34,7 @@ import { requireAuth, requireAdmin } from './middleware/auth.js';
|
||||
import { startAutoStatutJob } from './jobs/autoStatut.js';
|
||||
import { startAutoExportJob } from './jobs/autoExport.js';
|
||||
import { startAutoTicketStatusJob } from './jobs/autoTicketStatus.js';
|
||||
import { startAutoCleanNotifsJob } from './jobs/autoCleanNotifs.js';
|
||||
import adminRouter from './routes/admin.js';
|
||||
import invitationsRouter from './routes/invitations.js';
|
||||
import auditLogsRouter from './routes/auditLogs.js';
|
||||
@@ -143,4 +144,5 @@ app.listen(PORT, () => {
|
||||
startAutoStatutJob();
|
||||
startAutoExportJob();
|
||||
startAutoTicketStatusJob();
|
||||
startAutoCleanNotifsJob();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user