/home/techb158/balavpn.abdallabala.com/scripts
Edit: /home/techb158/balavpn.abdallabala.com/scripts/run-scheduled-reports.js (1724B)
const { PrismaClient } = require("@prisma/client");
const { getReport } = require("../src/services/reporting-service");
const { sendEmail } = require("../src/lib/email");
const prisma = new PrismaClient();
async function run() {
const now = new Date();
const due = await prisma.scheduledReport.findMany({
where: { enabled: true, nextRunAt: { lte: now } },
include: { project: true }
});
for (const schedule of due) {
try {
const report = await getReport(schedule.projectId, schedule.reportType);
const recipients = schedule.recipients;
if (recipients.length > 0 && report) {
for (const email of recipients) {
await sendEmail({
to: email,
subject: `Scheduled Report: ${schedule.project.name} - ${schedule.reportType}`,
text: `Attached is your scheduled report for ${schedule.project.name}.`,
attachments: report.contentType.includes("csv")
? [{ filename: schedule.reportType, content: report.body }]
: undefined
});
}
}
const intervalMap = { "0 8 * * 1": 7, "0 8 * * *": 1, "0 8 1 * *": 30 };
const days = intervalMap[schedule.cronExpr] || 7;
const nextRun = new Date(now.getTime() + days * 86400000);
await prisma.scheduledReport.update({
where: { id: schedule.id },
data: { lastRunAt: now, nextRunAt: nextRun }
});
console.log(`Report sent: ${schedule.id} (${schedule.project.name})`);
} catch (error) {
console.error(`Failed to run schedule ${schedule.id}:`, error.message);
}
}
await prisma.$disconnect();
}
run().catch(error => {
console.error("Fatal:", error);
process.exit(1);
});