diff --git a/app/controllers/dashboard.controller.js b/app/controllers/dashboard.controller.js index d2eb4d8..b7149f5 100644 --- a/app/controllers/dashboard.controller.js +++ b/app/controllers/dashboard.controller.js @@ -159,12 +159,13 @@ exports.getEstablishmentDashboard = async (req, res) => { year: q.year, quarter: q.quarter, establishment_id: establishment_id , + status: { + [Op.ne]: "Draft", // not equal + }, } }); - // status: { - // [Op.ne]: "Draft", // not equal - // }, + // if not submitted yet → add for start survey if (!submissionMatch) { diff --git a/app/services/scheduler.service.js b/app/services/scheduler.service.js index c93c62c..f3d284b 100644 --- a/app/services/scheduler.service.js +++ b/app/services/scheduler.service.js @@ -251,10 +251,7 @@ class AutomatedSchedulerService { }); console.log(`[${new Date().toISOString()}] Scheduler started successfully. Will run daily at 2:00 AM.`); - - // Optional: Run immediately on startup for testing - // Uncomment the line below if you want to test immediately - // this.runScheduledTask(); + } /** @@ -264,6 +261,165 @@ class AutomatedSchedulerService { console.log(`[${new Date().toISOString()}] Manual trigger initiated...`); await this.runScheduledTask(); } + + + + + //------------------------------------------------------------------------------ + + + + +async getEstablishmentsWithoutSubmission(year, quarter) { + const connection = await this.pool.getConnection(); + + try { + const query = ` + SELECT + e.id AS establishment_id, + e.factory_name, + eu.id AS user_id, + eu.name AS user_name, + eu.email + FROM establishments e + LEFT JOIN establishment_users eu + ON eu.establishment_id = e.id AND eu.is_active = 1 + + WHERE NOT EXISTS ( + SELECT 1 + FROM submissions s + WHERE s.establishment_id = e.id + AND s.year = ? + AND s.quarter = ? + AND s.status != 'Draft' + ) + `; + + const [rows] = await connection.query(query, [year, quarter]); + + return rows; + + } catch (error) { + console.error("Error fetching pending establishments:", error); + return []; + } finally { + connection.release(); + } +} + + +async sendReminderEmails(rows, latestWindow) { + try { + if (!rows.length) { + console.log("No pending establishments."); + return; + } + + const surveyData = await this.getSurveyData( + latestWindow.year, + latestWindow.quarter + ); + + const basePlaceholder = { + quarter: latestWindow.quarter, + year: latestWindow.year, + survey_name: surveyData?.survey_name, + support_email: process.env.SUPPORT_EMAIL, + support_phone: process.env.SUPPORT_PHONE, + portal_url: process.env.FE_BASE_URL, + logo_url: `${process.env.APP_BASE_URL}/assets/FCSCLogo.png`, + }; + + const promises = rows.map((r) => + sendEmailService(r.email, "submission_reminder_mail", { + ...basePlaceholder, + user_name: r.user_name, + establishment_name: r.factory_name, + }) + ); + + await Promise.all(promises); + + console.log(`Sent ${promises.length} reminder emails.`); + + } catch (err) { + console.error("Reminder email error:", err); + } +} + + + +async sendEmailReminders(latestWindow) { + console.log( + `[${new Date().toISOString()}] Sending reminders for Year=${latestWindow.year}, Quarter=${latestWindow.quarter}` + ); + + const establishments = await getEstablishmentsWithoutSubmission( + latestWindow.year, + latestWindow.quarter + ); + + if (!establishments.length) { + console.log("No pending establishments found."); + return; + } + + await sendReminderEmails(establishments, latestWindow); + + console.log(`[${new Date().toISOString()}] Email reminders completed.`); +} + + + async runScheduledEmails() { + + //find latest quarterly window configuration + const latestWindow = await this.getLatestQuarterlyWindow(); + + if (!latestWindow) { + console.log(`[${new Date().toISOString()}] No quarterly window configuration found for email reminders`); + return; + } + + console.log(`[${new Date().toISOString()}] Latest window for email reminders: Year=${latestWindow.year}, Quarter=${latestWindow.quarter}, End Date=${latestWindow.end_date}`); + + // Check if current date is greater than end_date + const currentDate = new Date(); + const endDate = new Date(latestWindow.end_date); + + console.log(`[${new Date().toISOString()}] Current Date: ${currentDate.toISOString()}`); + console.log(`[${new Date().toISOString()}] End Date: ${endDate.toISOString()}`); + + if (currentDate < endDate) { + console.log(`[${new Date().toISOString()}] Current date is not greater than end_date. Skipping email reminders.`); + } else { + console.log(`[${new Date().toISOString()}] Current date is greater than end_date. Sending email reminders.`); + // Call your email reminder service here, passing the latestWindow details if needed + // Send email remainders for All esatblishmets which have not submitted their survey for the quarter which has just opened and also for thouse who have not submitted till end date (This is a last day reminder) + await this.sendEmailReminders(latestWindow); + } + + } + + + + /** + * Start the scheduler + * Runs every day at 6:00 AM (you can adjust the time) + */ + startRemainderEmail() { + console.log(`[${new Date().toISOString()}] Starting automated scheduler...`); + + // Run every day at 6:00 AM + // Format: minute hour day month weekday + // '0 6 * * *' = At 6:00 AM every day + cron.schedule('0 6 * * *', () => { + this.runScheduledEmails(); + }); + + console.log(`[${new Date().toISOString()}] Scheduler started successfully. Will run daily at 6:00 AM.`); + + } + } module.exports = AutomatedSchedulerService;