task updated

This commit is contained in:
Sibunnayak 2024-08-26 12:38:25 +05:30
parent fcc4eab495
commit 768fc3c77f
5 changed files with 53 additions and 17 deletions

Binary file not shown.

View File

@ -13,7 +13,7 @@ export const assignTask = async (req, res) => {
addedFor, addedFor,
addedForId, addedForId,
} = req.body; } = req.body;
// console.log(req.body);
const currentYear = new Date().getFullYear().toString().slice(-2); const currentYear = new Date().getFullYear().toString().slice(-2);
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
const uniqueId = `${currentYear}-${randomChars}`; const uniqueId = `${currentYear}-${randomChars}`;
@ -22,11 +22,11 @@ export const assignTask = async (req, res) => {
taskId: uniqueId, taskId: uniqueId,
task, task,
note, note,
taskStatus: "Pending", taskStatus: "New",
taskPriority, taskPriority,
taskDueDate, taskDueDate,
taskAssignedTo, taskAssignedTo,
taskAssignedBy: req.user._id, // The Territory Manager's ID taskAssignedBy: req.user._id,
addedFor, addedFor,
addedForId, addedForId,
}); });
@ -44,27 +44,41 @@ export const assignTask = async (req, res) => {
} }
}; };
export const getTasksForSalesCoordinator = async (req, res) => { export const getTasksByStatus = async (req, res) => {
try { try {
const tasks = await Task.find({ taskAssignedTo: req.user._id }); const { status } = req.params; // This should be "New", "Pending", or "Completed"
// Validate the provided status
if (!["New", "Pending", "Completed"].includes(status)) {
return res.status(400).json({
success: false,
message: "Invalid status type provided.",
});
}
// Find tasks assigned to the user, filtered by status, and sorted by creation date (newest to oldest)
const tasks = await Task.find({
taskAssignedTo: req.user._id,
taskStatus: status,
}).sort({ createdAt: -1 }); // Sort by createdAt in descending order (-1 means newest first)
res.status(200).json({ res.status(200).json({
success: true, success: true,
tasks, tasks,
}); });
} catch (error) { } catch (error) {
res.status(400).json({ res.status(500).json({
success: false, success: false,
message: error.message, message: error.message,
}); });
} }
}; };
export const updateTaskStatus = async (req, res) => { export const updateTaskStatus = async (req, res) => {
try { try {
const { taskId } = req.params; const { taskId } = req.params;
// Find the task to ensure it belongs to the logged-in Sales Coordinator
const task = await Task.findOne({ _id: taskId, taskAssignedTo: req.user._id }); const task = await Task.findOne({ _id: taskId, taskAssignedTo: req.user._id });
if (!task) { if (!task) {

View File

@ -12,7 +12,7 @@ const TaskSchema = new mongoose.Schema(
task: { task: {
type: String, type: String,
required: true, required: true,
enum: ["Visit Retailers", "Update Sales Data", "Update Inventory Data", "Collect KYC"], // Restrict to specific tasks enum: ["Visit Retailers", "Update Sales Data", "Update Inventory Data", "Collect KYC"],
}, },
note: { note: {
type: String, type: String,
@ -23,7 +23,8 @@ const TaskSchema = new mongoose.Schema(
taskStatus: { taskStatus: {
type: String, type: String,
required: true, required: true,
enum: ["Pending", "In Progress", "Completed"], enum: ["New", "Pending", "Completed"],
default: "New",
}, },
taskPriority: { taskPriority: {
type: String, type: String,
@ -33,7 +34,7 @@ const TaskSchema = new mongoose.Schema(
taskDueDate: { taskDueDate: {
type: String, type: String,
required: true, required: true,
match: /^\d{2}\/\d{2}\/\d{4}$/, match: /^\d{2}\/\d{2}\/\d{4}$/, // e.g., "DD/MM/YYYY"
}, },
taskAssignedTo: { taskAssignedTo: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
@ -63,6 +64,25 @@ const TaskSchema = new mongoose.Schema(
{ timestamps: true } { timestamps: true }
); );
// Middleware to update task status based on due date
TaskSchema.pre("save", function (next) {
const currentDate = new Date();
const [day, month, year] = this.taskDueDate.split("/").map(Number);
const dueDate = new Date(year, month - 1, day);
// Convert dates to the start of the day for comparison
const currentDateOnly = new Date(currentDate.setHours(0, 0, 0, 0));
const dueDateOnly = new Date(dueDate.setHours(0, 0, 0, 0));
// Check if the current date is after the due date
if (currentDateOnly > dueDateOnly && this.taskStatus === "New") {
this.taskStatus = "Pending";
}
next();
});
const Task = mongoose.model("Task", TaskSchema); const Task = mongoose.model("Task", TaskSchema);
export default Task; export default Task;

View File

@ -1,7 +1,7 @@
import express from "express"; import express from "express";
import { import {
assignTask, assignTask,
getTasksForSalesCoordinator, getTasksByStatus,
updateTaskStatus, updateTaskStatus,
} from "./TaskController.js"; } from "./TaskController.js";
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js"; import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
@ -16,13 +16,14 @@ router.post(
assignTask assignTask
); );
// Route for Sales Coordinator to view their tasks // Route for Sales Coordinator to view their tasks by status
router.get( router.get(
"/tasks", "/tasks/:status",
isAuthenticatedSalesCoOrdinator, isAuthenticatedSalesCoOrdinator,
getTasksForSalesCoordinator getTasksByStatus
); );
// Route to update task status
router.put( router.put(
"/update-task-status/:taskId", "/update-task-status/:taskId",
isAuthenticatedSalesCoOrdinator, isAuthenticatedSalesCoOrdinator,

View File

@ -955,7 +955,8 @@ export const updateProfile = catchAsyncErrors(async (req, res, next) => {
// 9.Get all users(admin) // 9.Get all users(admin)
export const getAllUser = catchAsyncErrors(async (req, res, next) => { export const getAllUser = catchAsyncErrors(async (req, res, next) => {
// Assuming your User model is imported as 'User' // Assuming your User model is imported as 'User'
const users = await User.find({ role: "principal-Distributor" }); const users = await User.find({ role: "principal-Distributor" })
.sort({ createdAt: -1 });
res.status(200).json({ res.status(200).json({
success: true, success: true,