import { LoggedModel, ProjectModel } from "../../../models/vaModel.js"; async function va_log_callback(req, res) { try { const { projectId, from, to } = req.params; const { vaId } = req.body; if (!projectId) return res.status(400).json({ success: false, message: "Missing Props" }) const project = await ProjectModel.findById(projectId); if (!project) return res.status(400).json({ success: false, message: "Project not found" }); // Default range const fromDate = from && from !== "undefined" ? new Date(from) : new Date(project.startDate || "2000-01-01"); const toDate = to && to !== "undefined" ? new Date(to) : new Date(); // If from and to are the same day if (from === to) { fromDate.setHours(0, 0, 0, 0); toDate.setHours(23, 59, 59, 999); } else { // Otherwise use them as a normal range toDate.setHours(23, 59, 59, 999); } const query = { vaId: vaId, projectId, time: { $gte: fromDate, $lte: toDate } }; const logs = await LoggedModel.find(query).sort({ time: 1 }); if (!logs.length) { return res.json({ success: true, message: "No logs found", totalWork: "0h 0m" }); } // Find first LOGIN and last LOGOUT const firstLogin = logs.find((l) => l.loggedType === "LOGIN"); const lastLogout = [...logs].reverse().find((l) => l.loggedType === "LOGOUT"); if (!firstLogin || !lastLogout) { return res.json({ success: true, message: "Incomplete log data (missing LOGIN or LOGOUT)", totalWork: "0h 0m", firstLogin, lastLogout, }); } // Calculate duration const diffMs = new Date(lastLogout.time) - new Date(firstLogin.time); const totalMinutes = Math.floor(diffMs / (1000 * 60)); const hours = Math.floor(totalMinutes / 60); const minutes = totalMinutes % 60; res.json({ success: true, vaId, projectId, firstLogin: firstLogin.time, lastLogout: lastLogout.time, logs: logs, totalTimeLogged: `${hours}h ${minutes}m`, hoursLogged: hours, minutesLogged: minutes, }); } catch (err) { console.error(err); res.status(500).json({ success: false, message: err.message }); } }; export { va_log_callback };