Website : rimsha.abasa.com
backdoor
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
var
/
www
/
mudeerapi.abasa.com
/
nodetest
/
src
/
services
/
Filename :
lateArrivalChecker.js
back
Copy
import cron from 'node-cron'; import { user } from '../models/user.models.js'; import attendance from '../models/attendance.model.js'; import eventActivity from '../models/eventActivity.models.js'; import { Notification } from '../models/notification.model.js'; import { sendLateArrivalNotification } from './notificationService.js'; import { convertMakkahTimeStringToUTC } from '../utils/timezone.js'; /** * Check for late arrivals and send notifications * Runs every 5 minutes */ export const checkLateArrivals = async () => { try { console.log('🕐 Running late arrival check...'); const now = new Date(); const todayUTC = new Date(now); todayUTC.setUTCHours(0, 0, 0, 0); const endOfTodayUTC = new Date(todayUTC); endOfTodayUTC.setUTCHours(23, 59, 59, 999); // Get UTC day name const dayIndex = now.getUTCDay(); const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; const currentDayName = days[dayIndex]; console.log(`📅 Checking late arrivals for: ${currentDayName}`); // Get all active users who should be working today const users = await user.find({ isActive: true, start_time: { $exists: true, $ne: null } }).populate('department'); let lateCount = 0; let checkedCount = 0; for (const userDoc of users) { try { // Skip users with invalid start_time if (!userDoc.start_time || typeof userDoc.start_time !== 'string' || userDoc.start_time.trim() === '') { continue; } // Skip if today is user's day off if (userDoc.day_off && userDoc.day_off.includes(currentDayName)) { continue; } checkedCount++; // Get user's expected start time in UTC let expectedStartTime; try { expectedStartTime = convertMakkahTimeStringToUTC(userDoc.start_time, now); } catch (timeError) { console.log(`⚠️ Skipping user ${userDoc.first_name} ${userDoc.last_name} - Invalid start_time format: "${userDoc.start_time}"`); continue; } // Calculate how many minutes have passed since expected start time const timeDiffMs = now - expectedStartTime; const minutesPassed = Math.floor(timeDiffMs / 1000 / 60); // Only check if we're past the start time by at least 5 minutes if (minutesPassed < 5) { continue; } // Check if user has checked in today (has attendance record) const todayAttendance = await attendance.findOne({ user_id: userDoc._id.toString(), createdAt: { $gte: todayUTC, $lte: endOfTodayUTC } }); // Check if user has any activity today (as backup check) const todayActivity = await eventActivity.findOne({ user_id: userDoc._id, createdAt: { $gte: todayUTC, $lte: endOfTodayUTC } }); // User is late if: // 1. More than 5 minutes past start time // 2. No attendance record AND no activity today // 3. We haven't already sent a late notification to this user today if (!todayAttendance && !todayActivity) { const alreadyNotifiedToday = await Notification.exists({ recipient: userDoc._id, type: 'late_notification', createdAt: { $gte: todayUTC, $lte: endOfTodayUTC } }); if (alreadyNotifiedToday) { continue; } console.log(`⏰ Late arrival detected: ${userDoc.first_name} ${userDoc.last_name} (${minutesPassed} minutes late, expected: ${userDoc.start_time})`); const result = await sendLateArrivalNotification(userDoc, minutesPassed); if (result.success) { lateCount++; console.log(`✅ Late notification sent for ${userDoc.first_name} ${userDoc.last_name}`); } else { console.error(`❌ Failed to send late notification for ${userDoc.first_name}: ${result.error}`); } } } catch (userError) { console.error(`Error checking user ${userDoc._id}:`, userError.message); } } console.log(`✅ Late arrival check complete: ${lateCount} late notifications sent out of ${checkedCount} users checked`); } catch (error) { console.error('❌ Error in late arrival checker:', error); } }; /** * Start the late arrival checker cron job * Runs every 5 minutes */ export const startLateArrivalChecker = () => { // Every 5 minutes: "*/5 * * * *" cron.schedule('*/5 * * * *', async () => { await checkLateArrivals(); }, { timezone: "UTC" }); console.log('📋 Late arrival checker service started (runs every 5 minutes)'); };