import dotenv from "dotenv"; dotenv.config(); import mongoose from "mongoose"; const TaskSchema = new mongoose.Schema( { taskId: { type: String, unique: true, required: true, }, task: { type: String, required: true, enum: ["Visit RD/PD", "Update Sales Data", "Update Inventory Data", "Collect KYC"], }, note: { type: String, required: function () { return this.task === "Collect KYC" || this.task === "Visit RD/PD"; }, }, taskStatus: { type: String, required: true, enum: ["New", "Pending", "Completed"], default: "New", }, taskPriority: { type: String, required: true, enum: ["Low", "Medium", "High"], }, taskDueDate: { type: String, required: true, match: /^\d{2}\/\d{2}\/\d{4}$/, // e.g., "DD/MM/YYYY" }, taskAssignedTo: { type: mongoose.Schema.Types.ObjectId, ref: "SalesCoOrdinator", required: true, }, taskAssignedBy: { type: mongoose.Schema.Types.ObjectId, ref: "TerritoryManager", required: true, }, addedFor: { type: String, enum: ['PrincipalDistributor', 'RetailDistributor'], required: function () { return this.task === "Update Inventory Data"; }, }, addedForId: { type: mongoose.Schema.Types.ObjectId, refPath: 'addedFor', required: function () { return this.task === "Update Inventory Data"; }, }, tradename: { type: String, required: function () { return this.task === "Update Inventory Data"; }, }, }, { 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); export default Task;