Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | /**
* Service Rapport Mensuel PDF — Generation et envoi d'un rapport mensuel par email.
*
* Verifie toutes les heures si un rapport doit etre genere (le 1er du mois a l'heure configuree).
* Utilise Gotenberg pour convertir le HTML en PDF, puis envoie le PDF par email.
*
* Contenu du rapport :
* - Resume global (nb serveurs, uptime moyen, alertes)
* - Metriques moyennes par serveur (CPU, RAM, disque)
* - Uptime par monitor (% disponibilite)
* - Backups effectues (succes / erreurs)
* - Alertes et incidents du mois
*
* @module services/reportScheduler
*/
const { pool: db } = require('../db');
const { sendEmailWithAttachment } = require('./email');
const { getUptimeStats, getBackupStats } = require('../helpers/schedulerStats');
// Intervalle de verification (toutes les heures)
const CHECK_INTERVAL_MS = 60 * 60 * 1000;
// URL Gotenberg — HTTP intentionnel : communication interne Docker overlay (reseau isole, non expose)
// En production, le trafic reste dans le reseau Docker Swarm (chiffre avec --opt encrypted).
// Si Gotenberg est expose publiquement, definir GOTENBERG_URL=https://... dans l'environnement.
const GOTENBERG_URL = process.env.GOTENBERG_URL || 'http://gotenberg:3000'; // NOSONAR — HTTP interne Docker
let checkTimer = null;
/**
* Demarre le scheduler de rapport mensuel.
*/
function startReportScheduler() {
if (process.env.NODE_ENV === 'test') return;
console.log('[report] Scheduler de rapport mensuel demarre');
checkTimer = setInterval(checkAndSendReports, CHECK_INTERVAL_MS);
// Verifier immediatement au demarrage
setTimeout(checkAndSendReports, 5000);
}
/**
* Arrete le scheduler.
*/
function stopReportScheduler() {
if (checkTimer) {
clearInterval(checkTimer);
checkTimer = null;
}
}
/**
* Verifie si des rapports doivent etre generes et les envoie.
*/
async function checkAndSendReports() {
const now = new Date();
// Seulement le 1er du mois
if (now.getUTCDate() !== 1) return;
const currentHour = now.getUTCHours();
try {
const { rows: users } = await db.query(
`SELECT id, email, plan, report_enabled, report_hour, report_last_sent
FROM users
WHERE report_enabled = TRUE AND email_verified = TRUE`,
);
for (const user of users) {
if (shouldSendReport(user, currentHour)) {
try {
await sendReportForUser(user);
await db.query(
'UPDATE users SET report_last_sent = NOW() WHERE id = $1',
[user.id],
);
} catch (err) {
console.error(`[report] Erreur envoi pour ${user.email}:`, err.message);
}
}
}
} catch (err) {
console.error('[report] Erreur verification:', err.message);
}
}
/**
* Determine si un rapport doit etre envoye a cet utilisateur.
*
* @param {Object} user — { report_hour, report_last_sent }
* @param {number} currentHour — Heure UTC actuelle (0-23)
* @returns {boolean}
*/
function shouldSendReport(user, currentHour) {
if (user.report_hour !== currentHour) return false;
// Protection anti-doublon : pas d'envoi si deja envoye il y a moins de 20 jours
if (user.report_last_sent) {
const lastSent = new Date(user.report_last_sent);
const daysSince = (Date.now() - lastSent.getTime()) / (1000 * 60 * 60 * 24);
if (daysSince < 20) return false;
}
return true;
}
// ─── Generation du rapport ──────────────────────────────────────────────────
/**
* Genere et envoie le rapport mensuel pour un utilisateur.
*
* @param {Object} user — { id, email, plan }
*/
async function sendReportForUser(user) {
// Determiner le mois precedent
const now = new Date();
const reportMonth = new Date(now.getUTCFullYear(), now.getUTCMonth() - 1, 1);
const monthLabel = reportMonth.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' });
const intervalSql = '1 month';
// Collecter les donnees
const [servers, avgMetrics, uptimeStats, backupStats, alertStats, incidents] = await Promise.all([
getServersStatus(user.id),
getAvgMetrics(user.id, intervalSql),
getUptimeStats(user.id, intervalSql),
getBackupStats(user.id, intervalSql),
getAlertStats(user.id, intervalSql),
getIncidents(user.id, intervalSql),
]);
if (servers.length === 0) return; // Pas de serveur, pas de rapport
const html = buildReportHtml({
email: user.email,
monthLabel,
servers,
avgMetrics,
uptimeStats,
backupStats,
alertStats,
incidents,
});
// Generer le PDF via Gotenberg
const pdfBuffer = await generatePdf(html);
const filename = `rapport-iliacloud-${reportMonth.getUTCFullYear()}-${String(reportMonth.getUTCMonth() + 1).padStart(2, '0')}.pdf`;
// Envoyer par email avec le PDF en piece jointe
await sendEmailWithAttachment({
to: user.email,
subject: `Rapport mensuel ${monthLabel} — IliaCloud`,
html: buildEmailHtml(monthLabel),
attachments: [{ filename, content: pdfBuffer, contentType: 'application/pdf' }],
});
console.log(`[report] Rapport ${monthLabel} envoye a ${user.email}`);
}
// ─── Collecte des donnees ────────────────────────────────────────────────────
/**
* Recupere les serveurs de l'utilisateur.
*/
async function getServersStatus(userId) {
const { rows } = await db.query(
`SELECT s.id, s.name, s.host
FROM servers s
WHERE s.user_id = $1
ORDER BY s.name`,
[userId],
);
return rows;
}
/**
* Metriques moyennes par serveur sur la periode.
*/
async function getAvgMetrics(userId, interval) {
const { rows } = await db.query(
`SELECT s.id AS server_id, s.name,
ROUND(AVG(mh.cpu_percent)::numeric, 1) AS avg_cpu,
ROUND(AVG(mh.mem_percent)::numeric, 1) AS avg_ram,
ROUND(AVG(mh.disk_percent)::numeric, 1) AS avg_disk,
ROUND(AVG(mh.load_1m)::numeric, 2) AS avg_load,
MAX(mh.cpu_percent) AS max_cpu,
MAX(mh.mem_percent) AS max_ram,
MAX(mh.disk_percent) AS max_disk
FROM servers s
LEFT JOIN metrics_history mh ON mh.server_id = s.id
AND mh.created_at > NOW() - INTERVAL '${interval}'
WHERE s.user_id = $1
GROUP BY s.id, s.name
ORDER BY s.name`,
[userId],
);
return rows;
}
/**
* Statistiques des alertes sur la periode.
*/
async function getAlertStats(userId, interval) {
const { rows } = await db.query(
`SELECT COUNT(*) AS total
FROM alert_history ah
JOIN alert_rules ar ON ar.id = ah.alert_rule_id
WHERE ar.user_id = $1 AND ah.created_at > NOW() - INTERVAL '${interval}'`,
[userId],
);
return {
total: Number(rows[0]?.total || 0),
alerts: Number(rows[0]?.total || 0),
recoveries: 0,
};
}
/**
* Incidents majeurs du mois.
*/
async function getIncidents(userId, interval) {
const { rows } = await db.query(
`SELECT ah.created_at, ar.metric, ar.threshold, ah.value,
s.name AS server_name
FROM alert_history ah
JOIN alert_rules ar ON ar.id = ah.alert_rule_id
JOIN servers s ON s.id = ar.server_id
WHERE ar.user_id = $1
AND ah.created_at > NOW() - INTERVAL '${interval}'
ORDER BY ah.created_at DESC
LIMIT 50`,
[userId],
);
return rows;
}
// ─── Generation PDF via Gotenberg ────────────────────────────────────────────
/**
* Convertit du HTML en PDF via Gotenberg.
*
* @param {string} html — Contenu HTML complet
* @returns {Promise<Buffer>} — Buffer du PDF genere
*/
async function generatePdf(html) {
const form = new FormData();
const htmlBlob = new Blob([html], { type: 'text/html' });
form.append('files', htmlBlob, 'index.html');
form.append('marginTop', '0.5');
form.append('marginBottom', '0.5');
form.append('marginLeft', '0.5');
form.append('marginRight', '0.5');
form.append('printBackground', 'true');
const response = await fetch(`${GOTENBERG_URL}/forms/chromium/convert/html`, {
method: 'POST',
body: form,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Gotenberg erreur ${response.status}: ${text}`);
}
const arrayBuffer = await response.arrayBuffer();
return Buffer.from(arrayBuffer);
}
// ─── Template HTML du rapport PDF ────────────────────────────────────────────
/**
* Echappe les caracteres HTML.
*/
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
}
/**
* Couleur selon le pourcentage.
*/
function getMetricColor(value) {
if (value == null) return '#9ca3af';
if (value >= 90) return '#ef4444';
if (value >= 70) return '#f59e0b';
return '#22c55e';
}
/**
* Formate une valeur metrique en badge HTML.
*/
function metricBadge(value) {
const display = value == null ? '—' : value + '%';
return `<span class="badge ${getBadgeClass(value)}">${display}</span>`;
}
/**
* Classe CSS de badge pour un pourcentage de disponibilite.
*/
function getUptimeBadgeClass(percent) {
if (percent == null) return 'badge-gray';
if (percent >= 99) return 'badge-green';
if (percent >= 95) return 'badge-orange';
return 'badge-red';
}
/**
* Section HTML : metriques moyennes par serveur.
*/
function buildMetricsSectionHtml(avgMetrics) {
if (avgMetrics.length === 0) {
return '<h2>Metriques moyennes par serveur</h2><p class="no-data">Aucune donnee de metriques pour ce mois.</p>';
}
const rows = avgMetrics.map((m) => `<tr>
<td><strong>${escapeHtml(m.name)}</strong></td>
<td>${metricBadge(m.avg_cpu)}</td>
<td>${metricBadge(m.avg_ram)}</td>
<td>${metricBadge(m.avg_disk)}</td>
<td>${m.avg_load == null ? '—' : m.avg_load}</td>
<td>${metricBadge(m.max_cpu)}</td>
<td>${metricBadge(m.max_ram)}</td>
</tr>`).join('');
return `<h2>Metriques moyennes par serveur</h2><table>
<tr><th>Serveur</th><th>CPU moy.</th><th>RAM moy.</th><th>Disque moy.</th><th>Load moy.</th><th>CPU max</th><th>RAM max</th></tr>${rows}</table>`;
}
/**
* Section HTML : disponibilite des monitors.
*/
function buildUptimeSectionHtml(uptimeStats) {
if (uptimeStats.length === 0) {
return '<h2>Disponibilite des monitors</h2><p class="no-data">Aucun monitor uptime configure.</p>';
}
const rows = uptimeStats.map((u) => {
const cls = getUptimeBadgeClass(u.percent);
const pct = u.percent == null ? '—' : u.percent + '%';
return `<tr>
<td>${escapeHtml(u.url)}</td>
<td>${u.total}</td>
<td><span class="badge ${cls}">${pct}</span></td>
</tr>`;
}).join('');
return `<h2>Disponibilite des monitors</h2><table>
<tr><th>URL</th><th>Checks</th><th>Disponibilite</th></tr>${rows}</table>`;
}
/**
* Section HTML : incidents du mois.
*/
function buildIncidentsSectionHtml(incidents) {
if (incidents.length === 0) {
return '<h2>Incidents du mois</h2><p class="no-data">Aucun incident ce mois-ci. 🎉</p>';
}
const rows = incidents.map((inc) => {
const date = new Date(inc.created_at).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
const val = inc.value == null ? '—' : Math.round(inc.value) + '%';
return `<tr>
<td>${date}</td>
<td>${escapeHtml(inc.server_name)}</td>
<td>${escapeHtml(inc.metric)}</td>
<td><span class="badge badge-red">${val}</span></td>
<td>${inc.threshold}%</td>
</tr>`;
}).join('');
return `<h2>Incidents du mois</h2><table>
<tr><th>Date</th><th>Serveur</th><th>Metrique</th><th>Valeur</th><th>Seuil</th></tr>${rows}</table>`;
}
/**
* Genere le HTML du rapport PDF.
*/
function buildReportHtml({ email, monthLabel, servers, avgMetrics, uptimeStats, backupStats, alertStats, incidents }) {
const uptimeAvg = uptimeStats.length > 0
? Math.round(uptimeStats.reduce((sum, u) => sum + (u.percent || 0), 0) / uptimeStats.length)
: null;
const uptimeDisplay = uptimeAvg == null ? '—' : uptimeAvg + '%';
const headerHtml = `<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #1e293b; line-height: 1.5; padding: 40px; }
.header { text-align: center; margin-bottom: 32px; border-bottom: 2px solid #6366f1; padding-bottom: 20px; }
.header h1 { font-size: 24px; color: #1e293b; }
.header h1 span { color: #6366f1; }
.header .month { font-size: 18px; color: #64748b; margin-top: 4px; }
.header .email { font-size: 12px; color: #94a3b8; margin-top: 4px; }
.summary { display: flex; gap: 16px; margin-bottom: 32px; }
.summary-card { flex: 1; background: #f8fafc; border-radius: 8px; padding: 16px; text-align: center; border: 1px solid #e2e8f0; }
.summary-card .value { font-size: 28px; font-weight: 700; color: #1e293b; }
.summary-card .label { font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
h2 { font-size: 16px; font-weight: 600; color: #1e293b; margin: 24px 0 12px; padding-bottom: 8px; border-bottom: 1px solid #e2e8f0; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 13px; }
th { background: #f1f5f9; padding: 8px 12px; text-align: left; font-weight: 600; color: #475569; border-bottom: 2px solid #e2e8f0; }
td { padding: 8px 12px; border-bottom: 1px solid #f1f5f9; }
tr:hover td { background: #f8fafc; }
.badge { display: inline-block; padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; }
.badge-green { background: #dcfce7; color: #166534; }
.badge-orange { background: #fef3c7; color: #92400e; }
.badge-red { background: #fecaca; color: #991b1b; }
.badge-gray { background: #f1f5f9; color: #64748b; }
.footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #e2e8f0; font-size: 11px; color: #94a3b8; }
.no-data { color: #94a3b8; font-style: italic; font-size: 13px; padding: 12px 0; }
</style>
</head>
<body>
<div class="header">
<h1><span>Ilia</span>Cloud — Rapport Mensuel</h1>
<div class="month">${escapeHtml(monthLabel)}</div>
<div class="email">${escapeHtml(email)}</div>
</div>
<!-- Resume global -->
<div class="summary">
<div class="summary-card">
<div class="value">${servers.length}</div>
<div class="label">Serveurs</div>
</div>
<div class="summary-card">
<div class="value">${uptimeDisplay}</div>
<div class="label">Uptime moyen</div>
</div>
<div class="summary-card">
<div class="value">${alertStats.alerts}</div>
<div class="label">Alertes</div>
</div>
<div class="summary-card">
<div class="value">${backupStats.total}</div>
<div class="label">Backups</div>
</div>
</div>`;
const backupErrorBadge = backupStats.errors > 0 ? 'badge-red' : 'badge-green';
const alertsBadge = alertStats.alerts > 0 ? 'badge-red' : 'badge-green';
const backupsHtml = `<h2>Backups</h2><table>
<tr><th>Total</th><th>Succes</th><th>Erreurs</th></tr>
<tr>
<td>${backupStats.total}</td>
<td><span class="badge badge-green">${backupStats.success}</span></td>
<td><span class="badge ${backupErrorBadge}">${backupStats.errors}</span></td>
</tr>
</table>`;
const alertsHtml = `<h2>Alertes</h2><table>
<tr><th>Total</th><th>Alertes</th><th>Recoveries</th></tr>
<tr>
<td>${alertStats.total}</td>
<td><span class="badge ${alertsBadge}">${alertStats.alerts}</span></td>
<td><span class="badge badge-green">${alertStats.recoveries}</span></td>
</tr>
</table>`;
const footerHtml = `
<div class="footer">
<p>Genere automatiquement par IliaCloud — ${new Date().toLocaleDateString('fr-FR')}</p>
<p>Ce rapport couvre la periode du mois de ${escapeHtml(monthLabel)}.</p>
</div>
</body>
</html>`;
return [
headerHtml,
buildMetricsSectionHtml(avgMetrics),
buildUptimeSectionHtml(uptimeStats),
backupsHtml,
alertsHtml,
buildIncidentsSectionHtml(incidents),
footerHtml,
].join('');
}
/**
* Classe CSS de badge selon la valeur.
*/
function getBadgeClass(value) {
if (value == null) return 'badge-gray';
if (value >= 90) return 'badge-red';
if (value >= 70) return 'badge-orange';
return 'badge-green';
}
/**
* HTML de l'email accompagnant le PDF.
*/
function buildEmailHtml(monthLabel) {
return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin: 0; padding: 0; background-color: #f4f4f7; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f7;">
<tr><td align="center" style="padding: 40px 20px;">
<table role="presentation" width="500" cellpadding="0" cellspacing="0" style="max-width: 500px; width: 100%;">
<tr><td align="center" style="padding-bottom: 32px;">
<span style="font-size: 28px; font-weight: 800; color: #1e293b; letter-spacing: -0.5px;">
<span style="color: #6366f1;">Ilia</span>Cloud
</span>
</td></tr>
<tr><td style="background: #ffffff; border-radius: 12px; padding: 40px 36px; box-shadow: 0 1px 3px rgba(0,0,0,0.08);">
<h1 style="font-size: 22px; font-weight: 700; color: #1e293b; margin: 0 0 12px 0;">
Votre rapport mensuel est pret
</h1>
<p style="font-size: 15px; color: #475569; line-height: 1.6; margin: 0 0 20px 0;">
Retrouvez en piece jointe votre rapport IliaCloud pour le mois de <strong>${escapeHtml(monthLabel)}</strong>.
</p>
<p style="font-size: 15px; color: #475569; line-height: 1.6; margin: 0 0 20px 0;">
Ce rapport contient un resume complet de l'etat de vos serveurs, la disponibilite de vos services,
les backups effectues et les alertes declenchees pendant le mois.
</p>
<p style="font-size: 13px; color: #94a3b8; margin: 0;">
Vous pouvez configurer ou desactiver ce rapport dans vos parametres IliaCloud.
</p>
</td></tr>
<tr><td align="center" style="padding-top: 24px;">
<p style="font-size: 12px; color: #94a3b8;">IliaCloud — Monitoring de serveurs</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
module.exports = {
startReportScheduler,
stopReportScheduler,
checkAndSendReports,
shouldSendReport,
sendReportForUser,
getServersStatus,
getAvgMetrics,
getUptimeStats,
getBackupStats,
getAlertStats,
getIncidents,
generatePdf,
buildReportHtml,
buildEmailHtml,
escapeHtml,
getMetricColor,
getBadgeClass,
};
|