81 lines
2.7 KiB
JavaScript
81 lines
2.7 KiB
JavaScript
// LIBRARIES
|
|
const cron = require("node-cron");
|
|
|
|
// SERVICES
|
|
const logger = require("../services/logger.services");
|
|
const { localTime } = require('../services/time.services.js');
|
|
const { checkCampaign, sendCampaign } = require("../controllers/campaign.controller");
|
|
const { processActivitiesAndSendNotifications, updateDailyAnalytics } = require("../services/notification.services");
|
|
|
|
// CONTROLLERS
|
|
|
|
function initializeCronJobs() {
|
|
cron.schedule("* * * * *", async () => {
|
|
logger.info("Running cron job to handle campaign");
|
|
|
|
try {
|
|
const nowTime = localTime(new Date());
|
|
|
|
const idCampaign = await checkCampaign(nowTime);
|
|
|
|
if (idCampaign) {
|
|
await sendCampaign(idCampaign);
|
|
logger.info(`Campaign ${idCampaign} sent successfully`);
|
|
} else {
|
|
logger.info("No campaign to send at this time");
|
|
}
|
|
|
|
} catch (err) {
|
|
logger.error("Error handling campaign in cron job", { error: err });
|
|
}
|
|
});
|
|
|
|
cron.schedule("*/5 * * * *", async () => {
|
|
logger.info("Running cron job to analyze activities and send notifications");
|
|
|
|
try {
|
|
const result = await processActivitiesAndSendNotifications({
|
|
timeRangeMinutes: 60,
|
|
minActivityCount: 5
|
|
});
|
|
|
|
logger.info("Activity notification job completed", {
|
|
totalUsersProcessed: result.totalUsersProcessed,
|
|
notificationsSent: result.notificationsSent,
|
|
notificationsSkipped: result.notificationsSkipped,
|
|
errors: result.errors,
|
|
durationMs: result.processingTimeMs
|
|
});
|
|
|
|
if (result.errorDetails.length > 0) {
|
|
logger.warn("Some errors occurred during notification processing:", result.errorDetails);
|
|
}
|
|
|
|
} catch (err) {
|
|
logger.error("Error handling activity notification cron job", { error: err });
|
|
}
|
|
});
|
|
|
|
cron.schedule("0 2 * * *", async () => {
|
|
logger.info("Running cron job to update AI notification analytics");
|
|
|
|
try {
|
|
const yesterday = new Date();
|
|
yesterday.setDate(yesterday.getDate() - 1);
|
|
|
|
const result = await updateDailyAnalytics(yesterday);
|
|
|
|
logger.info("AI notification analytics updated successfully", {
|
|
date: result.date.toISOString().split('T')[0],
|
|
stats: result.stats
|
|
});
|
|
|
|
} catch (err) {
|
|
logger.error("Error updating AI notification analytics in cron job", { error: err });
|
|
}
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
initializeCronJobs
|
|
}; |