import dotenv from "dotenv"; dotenv.config(); import mongoose from "mongoose"; import validator from "validator"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import crypto from "crypto"; const salescoordinatorSchema = new mongoose.Schema( { designation: { type: String, required: true, default: "Sales Coordinator", }, name: { type: String, required: true, }, mobileNumber: { type: String, required: true, unique: true, }, otp: { type: String, required: false, }, otpExpires: { type: Date, }, isVerified: { type: Boolean, default: false, }, email: { type: String, required: false, unique: true, validate: [validator.isEmail, "Please enter a valid Email"], }, password: { type: String, minLength: [6, "Password should be greater than 6 characters"], select: false, }, newMobileNumber: { type: String }, resetPasswordToken: String, resetPasswordExpire: Date, uniqueId: { type: String, unique: true, }, fcm_token: { type: String, default: null, sparse: true, }, mappedby: { type: mongoose.Schema.Types.ObjectId, ref: "TerritoryManager", }, }, { timestamps: true } ); salescoordinatorSchema.pre("save", async function (next) { if (!this.isModified("password")) { next(); } this.password = await bcrypt.hash(this.password, 10); }); salescoordinatorSchema.pre("save", function (next) { if (!this.uniqueId) { const currentYear = new Date().getFullYear().toString().slice(-2); const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); this.uniqueId = `${currentYear}-${randomChars}`; } next(); }); // JWT TOKEN salescoordinatorSchema.methods.getJWTToken = function () { return jwt.sign({ id: this._id }, process.env.JWT_SECRET); }; // Compare Password salescoordinatorSchema.methods.comparePassword = async function (password) { return await bcrypt.compare(password, this.password); }; // Generating Reset Token salescoordinatorSchema.methods.getResetPasswordToken = function () { const resetToken = crypto.randomBytes(20).toString("hex"); this.resetPasswordToken = crypto .createHash("sha256") .update(resetToken) .digest("hex"); this.resetPasswordExpire = Date.now() + 15 * 60 * 1000; // 15 minutes return resetToken; }; const SalesCoOrdinator = mongoose.model( "SalesCoOrdinator", salescoordinatorSchema ); export default SalesCoOrdinator;