api/resources/Task/TaskController.js
2024-08-26 12:38:25 +05:30

107 lines
2.6 KiB
JavaScript

import Task from "./TaskModel.js";
import SalesCoOrdinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
import crypto from "crypto";
export const assignTask = async (req, res) => {
try {
const {
task,
note,
taskPriority,
taskDueDate,
taskAssignedTo,
addedFor,
addedForId,
} = req.body;
const currentYear = new Date().getFullYear().toString().slice(-2);
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
const uniqueId = `${currentYear}-${randomChars}`;
// Create a new task
const newTask = await Task.create({
taskId: uniqueId,
task,
note,
taskStatus: "New",
taskPriority,
taskDueDate,
taskAssignedTo,
taskAssignedBy: req.user._id,
addedFor,
addedForId,
});
res.status(201).json({
success: true,
message: "Task assigned successfully",
task: newTask,
});
} catch (error) {
res.status(400).json({
success: false,
message: error.message,
});
}
};
export const getTasksByStatus = async (req, res) => {
try {
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({
success: true,
tasks,
});
} catch (error) {
res.status(500).json({
success: false,
message: error.message,
});
}
};
export const updateTaskStatus = async (req, res) => {
try {
const { taskId } = req.params;
const task = await Task.findOne({ _id: taskId, taskAssignedTo: req.user._id });
if (!task) {
return res.status(404).json({
success: false,
message: "Task not found or you're not authorized to update this task.",
});
}
// Update the task status to "Completed"
task.taskStatus = "Completed";
await task.save();
res.status(200).json({
success: true,
message: "Task status updated to Completed.",
task,
});
} catch (error) {
res.status(400).json({
success: false,
message: error.message,
});
}
};