import cron from 'node-cron'; import nodemailer from 'nodemailer'; const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, port: parseInt(process.env.SMTP_PORT || '587'), secure: false, auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS, } }); export async function sendReportEmail(start, end, subject = "TrACreport Summary") { const url = new URL(process.env.WEBURL); url.searchParams.set('start', start.toISOString().slice(0, 10)); url.searchParams.set('end', end.toISOString().slice(0, 10)); url.searchParams.set('password', process.env.PASSWORD); const maxAttempts = 3; const delay = (ms) => new Promise((res) => setTimeout(res, ms)); for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { console.log(`📡 Attempt ${attempt}: fetching ${url}`); const res = await fetch(url.toString()); if (!res.ok) throw new Error(`Fetch failed: ${res.status} ${res.statusText}`); const html = await res.text(); await transporter.sendMail({ from: `"TrACreport Bot" <${process.env.SMTP_USER}>`, to: process.env.MAIL_RECIPIENTS, subject, html, }); console.log(`✅ Report emailed: ${subject} (${start.toISOString().slice(0, 10)})`); return; // Success, exit function } catch (err) { console.error(`❌ Attempt ${attempt} failed:`, err); if (attempt < maxAttempts) { console.log(`⏳ Retrying in 5s...`); await delay(5000); // Wait before retry } else { console.error(`🚫 All ${maxAttempts} attempts failed. Giving up.`); } } } } // Daily Report cron.schedule('5 1 * * *', () => { const today = new Date(); const yesterday = new Date(today); yesterday.setUTCDate(today.getUTCDate() - 1); sendReportEmail(yesterday, yesterday, "TrACreport Daily Report"); }); // Weekly Report cron.schedule('10 1 * * 1', () => { const today = new Date(); const end = new Date(today); end.setUTCDate(roday.getUTCDate() - 1); const start = new Date(end); start.setUTCDate(end.getUTCDate() - 6); sendReportEmail(start, end, "TrACreport Weekly Report"); }) // Monthly Report cron.schedule('15 1 1 * *', () => { const today = new Date(); const end = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 0)); // Last day of previous month const start = new Date(Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), 1)); // First day of previous month sendReportEmail(start, end, "TrACreport Monthly Report"); }); console.log('📅 TrACreport schedulers are active');