product pagination attendance and leave

This commit is contained in:
Sibunnayak 2024-11-27 13:26:09 +05:30
parent 9aa6c8180d
commit 8e58b4b5f3
3 changed files with 82 additions and 40 deletions

View File

@ -1,4 +1,5 @@
import { Attendance } from "./AttendanceModel.js"; import { Attendance } from "./AttendanceModel.js";
import { Leave } from "../Leaves/LeaveModel.js";
// Mark attendance // Mark attendance
export const markAttendance = async (req, res) => { export const markAttendance = async (req, res) => {
@ -38,14 +39,27 @@ export const markAttendance = async (req, res) => {
$lte: endOfDay, $lte: endOfDay,
}, },
}); });
if (existingAttendance) { if (existingAttendance) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
message: "Attendance for today is already marked.", message: "Attendance for today is already marked.",
}); });
} }
// Check if the Leavs record exists for today
const existingLeave = await Leave.findOne({
userId,
userType,
"records.date": {
$gte: startOfDay,
$lte: endOfDay,
},
});
if (existingLeave) {
return res.status(400).json({
success: false,
message: "Leave for today is already marked.",
});
}
// Check if attendance record exists for the user // Check if attendance record exists for the user
let attendance = await Attendance.findOne({ userId, userType }); let attendance = await Attendance.findOne({ userId, userType });
@ -116,7 +130,7 @@ export const AdmingetAttendanceByUser = async (req, res) => {
const attendanceDoc = await Attendance.findOne({ const attendanceDoc = await Attendance.findOne({
userId: id, userId: id,
}).populate("userId", "name email"); }).populate("userId", "name email");
// console.log(attendanceDoc); // console.log(attendanceDoc);
if (!attendanceDoc) { if (!attendanceDoc) {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,

View File

@ -1,4 +1,5 @@
import { Leave } from "./LeaveModel.js"; import { Leave } from "./LeaveModel.js";
import { Attendance } from "../Attendance/AttendanceModel.js";
// Mark leave // Mark leave
export const markLeave = async (req, res) => { export const markLeave = async (req, res) => {
@ -45,7 +46,23 @@ export const markLeave = async (req, res) => {
message: "Leave for today is already marked.", message: "Leave for today is already marked.",
}); });
} }
// Check if the attendance record exists for today
const existingAttendance = await Attendance.findOne({
userId,
userType,
records: {
$elemMatch: {
date: { $gte: startOfDay, $lte: endOfDay },
},
},
});
if (existingAttendance) {
return res.status(400).json({
success: false,
message: "Attendance for today is already marked.",
});
}
// Check if leave record exists for the user // Check if leave record exists for the user
let leave = await Leave.findOne({ userId, userType }); let leave = await Leave.findOne({ userId, userType });
@ -155,7 +172,16 @@ export const getTodayLeave = async (req, res) => {
try { try {
// Step 1: Get today's date in UTC and set the time to 00:00:00.000 // Step 1: Get today's date in UTC and set the time to 00:00:00.000
const today = new Date(); const today = new Date();
const todayStartUTC = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0, 0, 0)); const todayStartUTC = new Date(
Date.UTC(
today.getUTCFullYear(),
today.getUTCMonth(),
today.getUTCDate(),
0,
0,
0
)
);
const tomorrowStartUTC = new Date(todayStartUTC); const tomorrowStartUTC = new Date(todayStartUTC);
tomorrowStartUTC.setUTCDate(todayStartUTC.getUTCDate() + 1); // Start of the next day tomorrowStartUTC.setUTCDate(todayStartUTC.getUTCDate() + 1); // Start of the next day
@ -166,30 +192,30 @@ export const getTodayLeave = async (req, res) => {
// Step 3: Aggregate query to get today's leave records // Step 3: Aggregate query to get today's leave records
const leavesWithUserLookup = await Leave.aggregate([ const leavesWithUserLookup = await Leave.aggregate([
{ $unwind: '$records' }, { $unwind: "$records" },
{ {
$match: { $match: {
'records.date': { "records.date": {
$gte: todayStartUTC, $gte: todayStartUTC,
$lt: tomorrowStartUTC $lt: tomorrowStartUTC,
} },
} },
}, },
{ {
$lookup: { $lookup: {
from: 'salescoordinators', from: "salescoordinators",
localField: 'userId', localField: "userId",
foreignField: '_id', foreignField: "_id",
as: 'salesCoOrdinatorUser' as: "salesCoOrdinatorUser",
} },
}, },
{ {
$lookup: { $lookup: {
from: 'territorymanagers', from: "territorymanagers",
localField: 'userId', localField: "userId",
foreignField: '_id', foreignField: "_id",
as: 'territoryManagerUser' as: "territoryManagerUser",
} },
}, },
{ {
$addFields: { $addFields: {
@ -197,17 +223,17 @@ export const getTodayLeave = async (req, res) => {
$cond: { $cond: {
if: { $eq: ["$userType", "SalesCoOrdinator"] }, if: { $eq: ["$userType", "SalesCoOrdinator"] },
then: { $arrayElemAt: ["$salesCoOrdinatorUser", 0] }, then: { $arrayElemAt: ["$salesCoOrdinatorUser", 0] },
else: { $arrayElemAt: ["$territoryManagerUser", 0] } else: { $arrayElemAt: ["$territoryManagerUser", 0] },
} },
} },
} },
}, },
{ {
$project: { $project: {
salesCoOrdinatorUser: 0, salesCoOrdinatorUser: 0,
territoryManagerUser: 0 territoryManagerUser: 0,
} },
} },
]); ]);
// Step 4: Calculate total data // Step 4: Calculate total data
@ -217,15 +243,17 @@ export const getTodayLeave = async (req, res) => {
const paginatedLeaves = leavesWithUserLookup.slice(skip, skip + limit); const paginatedLeaves = leavesWithUserLookup.slice(skip, skip + limit);
// Step 6: Format the response // Step 6: Format the response
const formattedLeaves = paginatedLeaves.map(record => ({ const formattedLeaves = paginatedLeaves.map((record) => ({
user: record.user ? { user: record.user
id: record.user._id, ? {
name: record.user.name, id: record.user._id,
email: record.user.email, name: record.user.name,
mobileNumber: record.user.mobileNumber, email: record.user.email,
userType: record.userType, mobileNumber: record.user.mobileNumber,
uniqueId: record.user.uniqueId, userType: record.userType,
} : null, uniqueId: record.user.uniqueId,
}
: null,
date: record.records.date, date: record.records.date,
time: record.records.time, time: record.records.time,
location: record.records.location, location: record.records.location,

View File

@ -508,8 +508,8 @@ export const getAllProductAdmin = async (req, res) => {
export const getAllProductUser = async (req, res) => { export const getAllProductUser = async (req, res) => {
try { try {
// Set default values for pagination // Set default values for pagination
// const PAGE_SIZE = parseInt(req.query?.show || "10"); const PAGE_SIZE = parseInt(req.query?.show || "10");
// const page = parseInt(req.query?.page || "1") - 1; const page = parseInt(req.query?.page || "1") - 1;
let filter = {}; let filter = {};
// Filter by category name // Filter by category name
@ -553,15 +553,15 @@ export const getAllProductUser = async (req, res) => {
path: "category addedBy brand", path: "category addedBy brand",
select: "categoryName name brandName", select: "categoryName name brandName",
}) })
// .limit(PAGE_SIZE) .limit(PAGE_SIZE)
// .skip(PAGE_SIZE * page) .skip(PAGE_SIZE * page)
.sort({ createdAt: -1 }) .sort({ createdAt: -1 })
.exec(); .exec();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
total_data: total, total_data: total,
// total_pages: Math.ceil(total / PAGE_SIZE), total_pages: Math.ceil(total / PAGE_SIZE),
products, products,
}); });
} catch (error) { } catch (error) {