import ErrorHander from "../../Utils/errorhander.js"; import catchAsyncErrors from "../../middlewares/catchAsyncErrors.js"; import User from "./userModel.js"; import sendToken from "../../Utils/jwtToken.js"; import sendEmail from "../../Utils/sendEmail.js"; import crypto from "crypto"; import cloudinary from "cloudinary"; import password from "secure-random-password"; import { Order } from "../Orders/orderModel.js"; import { RegisterEmail } from "../EmailCMS/RegisterEmail/registerEmailModal.js"; import { Config } from "../setting/Configration/Config_model.js"; import XLSX from "xlsx"; import fs from "fs"; import path from "path"; import validator from 'validator'; import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js"; const generatePassword = (name, email) => { // Combine name and email, and convert to lowercase const combinedStr = (name + email).toLowerCase(); // Define character pools const specialChars = "@#*"; const numbers = "0123456789"; const alphaLower = combinedStr.match(/[a-z]/g) || []; const alphaUpper = combinedStr.match(/[A-Z]/g) || []; // Ensure at least one character from each category const specialChar = specialChars.charAt( Math.floor(Math.random() * specialChars.length) ); const numberChar = numbers.charAt(Math.floor(Math.random() * numbers.length)); const lowerChar = alphaLower.length > 0 ? alphaLower[Math.floor(Math.random() * alphaLower.length)] : String.fromCharCode(Math.floor(Math.random() * 26) + 97); const upperChar = alphaUpper.length > 0 ? alphaUpper[Math.floor(Math.random() * alphaUpper.length)] : String.fromCharCode(Math.floor(Math.random() * 26) + 65); // Combine required characters let passwordChars = [specialChar, numberChar, lowerChar, upperChar]; // Fill remaining positions with random characters from the combined string const allChars = combinedStr + specialChars + numbers; while (passwordChars.length < 8) { passwordChars.push( allChars.charAt(Math.floor(Math.random() * allChars.length)) ); } // Shuffle characters to ensure randomness passwordChars = passwordChars.sort(() => Math.random() - 0.5); // Generate password of length 8 const password = passwordChars.slice(0, 8).join(""); return password; }; export const uploadPrincipaldistributors = async (req, res) => { try { if (!req.files || !req.files.file) { return res.status(400).json({ message: "No file uploaded" }); } const file = req.files.file; const filePath = path.join("public", "uploads", file.name); // Ensure 'uploads' directory exists if (!fs.existsSync(path.dirname(filePath))) { fs.mkdirSync(path.dirname(filePath), { recursive: true }); } // Move the file from temp to the uploads directory await file.mv(filePath); // Process the file const fileBuffer = fs.readFileSync(filePath); const workbook = XLSX.read(fileBuffer, { type: "buffer" }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); if (data.length <= 1) { return res.status(400).json({ message: "Empty spreadsheet or no data found" }); } const headers = data[0]; // Map headers from the Excel file to your schema const headerMapping = { "Principal Distributor Name": "name", "Email": "email", "Phone Number": "phone", "PAN Number": "panNumber", "Trade Name": "tradeName", "GST Number": "gstNumber", "State": "state", "City": "city", "Street": "street", "Pincode": "postalCode", }; const requiredHeaders = Object.keys(headerMapping); if (!requiredHeaders.every((header) => headers.includes(header))) { return res.status(400).json({ message: "Missing required columns in spreadsheet" }); } const errors = []; const newlyCreated = []; const updatedDistributors = []; for (let i = 1; i < data.length; i++) { const row = data[i]; const item = {}; headers.forEach((header, index) => { if (headerMapping[header]) { item[headerMapping[header]] = row[index] !== undefined ? row[index] : ""; } }); // Initialize error tracking for each item const missingFields = new Set(); const validationErrors = new Set(); // Validate required fields if (!item.name) missingFields.add("name"); if (!item.email) missingFields.add("email"); if (!item.phone) missingFields.add("phone"); if (!item.panNumber) missingFields.add("panNumber"); if (!item.tradeName) missingFields.add("tradeName"); if (!item.gstNumber) missingFields.add("gstNumber"); if (!item.state) missingFields.add("state"); if (!item.city) missingFields.add("city"); if (!item.street) missingFields.add("street"); if (!item.postalCode) missingFields.add("postalCode"); // Check email validity if (item.email && !validator.isEmail(item.email)) { validationErrors.add("incorrect mail"); } // Validate mobile number if (item.phone && !/^\d{10}$/.test(item.phone)) { validationErrors.add("Invalid Mobile Number (should be 10 digits)"); } // Check GST, PAN, and postal code validation item.panNumber = item.panNumber ? item.panNumber.toUpperCase() : ""; item.gstNumber = item.gstNumber ? item.gstNumber.toUpperCase() : ""; // Validate PAN Number if (item.panNumber && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(item.panNumber)) { validationErrors.add("Invalid PAN Number"); } // Validate GST Number if (item.gstNumber && !/^(\d{2}[A-Z]{5}\d{4}[A-Z]{1}\d[Z]{1}[A-Z\d]{1})$/.test(item.gstNumber)) { validationErrors.add("Invalid GST Number"); } // Validate Postal Code if (item.postalCode && !/^\d{6}$/.test(item.postalCode)) { validationErrors.add("Invalid Postal Code"); } // Combine all errors into a single message let errorMessage = ""; if (missingFields.size > 0) { errorMessage += `Missing fields: ${Array.from(missingFields).join(", ")}. `; } if (validationErrors.size > 0) { errorMessage += `Validation errors: ${Array.from(validationErrors).join(", ")}.`; } // If there are errors, push them to the errors array if (errorMessage.trim()) { errors.push({ name: item.name || "N/A", email: item.email || "N/A", phone: item.phone || "N/A", panNumber: item.panNumber || "N/A", gstNumber: item.gstNumber || "N/A", message: errorMessage.trim(), }); continue; } // Generate a password const password = generatePassword(item.name, item.email); item.role = "principal-Distributor"; const currentYear = new Date().getFullYear().toString().slice(-2); const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); item.uniqueId = `${currentYear}-${randomChars}`; // Check for existing user let user = await User.findOne({ email: item.email }); if (user) { // Track updated fields const updatedFields = []; const addressFields = ['panNumber', 'gstNumber', 'state','city', 'street', 'tradeName', 'postalCode']; const existingAddress = await ShippingAddress.findOne({ user: user._id }); // Check for changes in user details let userUpdated = false; if (user.name !== item.name) { updatedFields.push("name"); user.name = item.name; userUpdated = true; } if (user.phone !== item.phone.toString()) { updatedFields.push("phone"); user.phone = item.phone; userUpdated = true; } // Update user if (userUpdated) { await user.save(); } // Check for changes in address details const addressData = { street: item.street, city: item.city, state: item.state, postalCode: item.postalCode.toString(), country: "India", // Default country panNumber: item.panNumber, tradeName: item.tradeName, gstNumber: item.gstNumber, user: user._id, }; let addressUpdated = false; if (existingAddress) { const addressUpdates = []; addressFields.forEach(field => { if (existingAddress[field] !== addressData[field]) { addressUpdates.push(field); addressUpdated = true; } }); if (addressUpdated) { await ShippingAddress.updateOne({ user: user._id }, addressData); if (addressUpdates.length > 0) { updatedFields.push(`Address fields: ${addressUpdates.join(", ")}`); } } } else { // Create new address await ShippingAddress.create(addressData); updatedFields.push("New address created"); } // Add to updatedDistributors only if there are updated fields if (updatedFields.length > 0) { updatedDistributors.push({ ...user._doc, updatedFields: updatedFields.join(", ") }); } } else { // Create a new user user = new User({ name: item.name, email: item.email, phone: item.phone, password, role: item.role, uniqueId: item.uniqueId, }); await user.save(); // Send email with the new user details await sendEmail({ to: item.email, from: process.env.SEND_EMAIL_FROM, subject: `Cheminova Account Created`, html: ` Your Principal Distributor Account is created successfully.
Name: ${item.name}

Mobile Number: ${item.phone}

Password: ${password}

Click here to login

If you have not requested this email, please ignore it. `, }); newlyCreated.push(user._doc); } } fs.unlinkSync(filePath); // Clean up uploaded file res.status(201).json({ message: errors.length > 0 ? "File processed with errors!" : "File processed successfully!", processedUsers: { newlyCreated: newlyCreated.length, updatedDistributors: updatedDistributors.length }, errors, newlyCreated, updatedDistributors }); } catch (error) { console.error("Error processing file:", error); res.status(500).json({ message: "Internal server error" }); } }; // 1.Register a User // export const registerUser = async (req, res) => { // try { // const { name, email, password, phone, accessTo, role } = req.body; // // console.log("this is the password ", password, name, req.body); // let findUser = await User.findOne({ email }); // if (findUser) { // return res // .status(400) // .json({ success: false, message: "User already exists" }); // } // if (req.files) { // const files = req.files.avatar; // const myCloud = await cloudinary.uploader.upload( // files.tempFilePath, // { // folder: "Cheminova/user-image", // }, // function (error, result) { // result, error; // } // ); // } // const user = await User.create({ // name, // email, // password, // phone, // role, // accessTo, // // avatar: { // // public_id: myCloud.public_id, // // url: myCloud.secure_url, // // }, // }); // // const emailData = await RegisterEmail.find(); // // let emailSubject = emailData[0]?.subject; // // let emailDescription = emailData[0]?.description; // const config = await Config.find(); // let appName = config[0]?.appName; // // await sendEmail({ // // to: `${email}`, // Change to your recipient // // from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender // // subject: `Welcome to Cheminova - Let the Shopping Begin!`, // // html: `

Welcome to ${appName} - Let the Shopping Begin!

// // Hey ${name}, // //

// // Welcome to Cheminova - Let the Shopping Begin! // //

// //
// //

You can login into :${role === "Employee" || role === "admin" // // ? `https://admin.smellika.com/` // // : `https://smellika.com` // // }

// //
// //

Below are your login credentials:

// //

Email: ${email}

// //

Password: ${password}

// // Happy shopping,
// // Team ${appName}`, // // }); // sendToken(user, 201, res); // } catch (e) { // return res.status(400).json({ success: false, message: e.message }); // } // }; export const registerUser = async (req, res) => { try { const { name, email, phone, accessTo, role } = req.body; // console.log(req.body); const password = generatePassword(name, email); // console.log(password); // Check if user already exists let user = await User.findOne({ email }); if (user) { // If user exists, update their details if needed user.name = name; // user.password = password; // In a real application, you should hash this user.phone = phone; user.role = role; user.accessTo = accessTo; // Save updates await user.save(); // console.log("finduser", user); // Respond with success and userId return res.status(200).json({ success: true, message: "User updated successfully", userId: user._id, }); } // Create a new user if not found user = new User({ name, email, password, phone, role, accessTo, }); // console.log(user); // Generate uniqueId const currentYear = new Date().getFullYear().toString().slice(-2); const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); user.uniqueId = `${currentYear}-${randomChars}`; // Save the new user to the database await user.save(); // Send email with the new user details if (user.role === "principal-Distributor") { await sendEmail({ to: email, from: process.env.SEND_EMAIL_FROM, subject: `Cheminova Account Created`, html: ` Your Principal Distributor Account is created successfully.
Name: ${name}

Mobile Number: ${phone}

Password: ${password}

Click here to login

If you have not requested this email, please ignore it. `, }); } // Respond with success and userId res.status(201).json({ success: true, message: "User created successfully", userId: user._id, }); } catch (error) { console.error(error); res.status(400).json({ success: false, message: error.message }); } }; // 2.Login User export const loginUser = async (req, res, next) => { const { email, password } = req.body; // checking if user has given password and email both try { if (!email || !password) { return res.status(400).json({ message: "Please Enter Email & Password" }); } const user = await User.findOne({ email }).select("+password"); if (!user) { return res.status(400).json({ message: "Invalid Email or Password" }); } const isPasswordMatched = await user.comparePassword(password); if (!isPasswordMatched) { return res.status(400).json({ message: "Invalid Email or Password" }); } sendToken(user, 200, res); } catch (error) { return res .status(500) .json({ message: "Something went wrong!", error: error?.message || "" }); } }; // 3.Logout User export const logout = catchAsyncErrors(async (req, res, next) => { res.cookie("token", null, { expires: new Date(Date.now()), httpOnly: true, }); res.status(200).json({ success: true, message: "Logged Out", }); }); // 4.Forgot Password export const forgotPassword = async (req, res, next) => { const user = await User.findOne({ email: req.body.email }); if (!user) { return res.status(404).json({ message: "User not found" }); } // Get ResetPassword Token const resetToken = user.getResetPasswordToken(); //call function //save database reset token await user.save({ validateBeforeSave: false }); const passwords = password.randomPassword({ length: 12, characters: [ { characters: password.upper, exactly: 1 }, { characters: password.symbols, exactly: 1 }, password.lower, password.digits, ], }); user.password = passwords; await user.save(); // const message = `Your password reset token are :- \n\n ${resetPasswordUrl} \n\nyour new password is:${password}\n\nIf you have not requested this email then, please ignore it.`; try { await sendEmail({ to: `${user.email}`, // Change to your recipient from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender subject: `Cheminova Password Recovery`, html: `your new password is:
${passwords}

If you have not requested this email then, please ignore it.`, }); res.status(200).json({ success: true, message: `Email sent to ${user.email} successfully`, }); } catch (error) { user.resetPasswordToken = undefined; user.resetPasswordExpire = undefined; await user.save({ validateBeforeSave: false }); return res .status(500) .json({ message: "Something went wrong!", error: error?.message || "" }); } }; // 5.Reset Password export const resetPassword = catchAsyncErrors(async (req, res, next) => { // creating token hash const resetPasswordToken = crypto .createHash("sha256") .update(req.params.token) .digest("hex"); const user = await User.findOne({ resetPasswordToken, resetPasswordExpire: { $gt: Date.now() }, }); if (!user) { return next( new ErrorHander( "Reset Password Token is invalid or has been expired", 400 ) ); } //replace previous password if (req.body.password !== req.body.confirmPassword) { return next(new ErrorHander("Password does not password", 400)); } user.password = req.body.password; user.resetPasswordToken = undefined; user.resetPasswordExpire = undefined; await user.save(); sendToken(user, 200, res); }); //6.Get User Detail export const getUserDetails = catchAsyncErrors(async (req, res, next) => { const user = await User.findById(req.user.id); res.status(200).json({ success: true, user, }); }); // export const getUserDetailsForAdmin = catchAsyncErrors( // async (req, res, next) => { // const user = await User.findById(req.params._id); // res.status(200).json({ // success: true, // user, // }); // } // ); // export const getAllUsers = catchAsyncErrors(async (req, res, next) => { // const users = await User.find().populate("orders"); // Assuming orders are stored in a separate collection and populated in the User model // // Process user data to calculate last purchase date and order count // const usersWithInfo = users.map((user) => { // const lastPurchase = // user.orders.length > 0 // ? user.orders[user.orders.length - 1].createdAt // : null; // const orderCount = user.orders.length; // return { ...user.toJSON(), lastPurchase, orderCount }; // }); // res.status(200).json({ // success: true, // users: usersWithInfo, // }); // }); // 7.Get single user (admin) export const getSingleUser = catchAsyncErrors(async (req, res, next) => { if (!req.params.id) { return next(new ErrorHander(`please send User ID`, 404)); } const user = await User.findById(req.params.id); if (!user) { return next( new ErrorHander(`User does not exist with Id: ${req.params.id}`, 404) ); } res.status(200).json({ success: true, user, }); }); export const getUserOrderForAdmin = async (req, res) => { const id = req.params.id; // console.log(id); try { const order = await Order.find({ user: id, // payment_status: "success", }).sort({ createdAt: -1 }); if (order) { return res.status(200).json({ success: true, order, message: "self Order fetched", }); } } catch (error) { res.status(500).json({ success: false, message: error.message ? error.message : "Something went Wrong", }); } }; // 8.update User password export const updatePassword = catchAsyncErrors(async (req, res, next) => { const user = await User.findById(req.user.id).select("+password"); const isPasswordMatched = await user.comparePassword(req.body.oldPassword); if (!isPasswordMatched) { return res.status(400).json({ message: "Old password is incorrect" }); } if (req.body.newPassword !== req.body.confirmPassword) { return res .status(400) .json({ message: "New Password and Confirm Password do not match" }); } user.password = req.body.newPassword; await user.save(); sendToken(user, 200, res); }); // 9.update User Profile export const updateProfile = catchAsyncErrors(async (req, res, next) => { const newUserData = { name: req.body.name, phone: req.body.phone, email: req.body.email, }; // if (req.files) { // const userImage = req.files?.avatar; // const user = await User.findById(req.user.id); // if (user?.avatar) { // const imageId = user?.avatar?.public_id; // await cloudinary.uploader.destroy(imageId) // } // const myCloud = await cloudinary.v2.uploader.upload(userImage.tempFilePath, // { // folder: "Cheminova/user-image", // }); // newUserData.avatar = { // public_id: myCloud.public_id, // url: myCloud.secure_url, // }; // } const user = await User.findByIdAndUpdate(req.user.id, newUserData, { new: true, runValidators: true, useFindAndModify: false, }); return res.status(200).json({ success: true, user, }); }); // 9.Get all users(admin) export const getAllUser = catchAsyncErrors(async (req, res, next) => { // Assuming your User model is imported as 'User' const users = await User.find({ role: "principal-Distributor" }); res.status(200).json({ success: true, users, }); }); export const getAllEmployee = catchAsyncErrors(async (req, res, next) => { // Assuming your User model is imported as 'User' const employee = await User.find({ role: "Employee" }); res.status(200).json({ success: true, employee, }); }); export const deleteEmployeeById = catchAsyncErrors(async (req, res, next) => { // console.log("request came here", req.params); // Extract the employee ID from the request parameters const { id } = req.params; try { // Find the employee by ID and delete it const deletedEmployee = await User.findByIdAndDelete(id); if (!deletedEmployee) { // If the employee with the provided ID is not found, return an error return res.status(404).json({ success: false, message: "Employee not found", }); } // If deletion is successful, return success response res.status(200).json({ success: true, message: "Employee deleted successfully", }); } catch (error) { // Handle any errors that occur during deletion return res.status(500).json({ success: false, message: "Error deleting employee", error: error.message, }); } }); // Update employee // Import necessary modules and set up your User model export const updateEmployeeById = catchAsyncErrors(async (req, res, next) => { // Extract the employee ID from the request parameters const { id } = req.params; try { // Find the employee by ID and update its fields const updatedEmployee = await User.findByIdAndUpdate( id, { $set: req.body }, // Update fields based on the request body { new: true } // Return the updated document ); if (!updatedEmployee) { // If the employee with the provided ID is not found, return an error return res.status(404).json({ success: false, message: "Employee not found", }); } // If update is successful, return success response with updated employee data res.status(200).json({ success: true, message: "Employee updated successfully", employee: updatedEmployee, }); } catch (error) { // Handle any errors that occur during update return res.status(500).json({ success: false, message: "Error updating employee", error: error.message, }); } });