api/resources/user/userController.js
2024-07-26 16:08:18 +05:30

522 lines
16 KiB
JavaScript

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";
// 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: ` <h1 style="color: #333; text-align: left; font-family: Arial, sans-serif;">Welcome to ${appName} - Let the Shopping Begin!</h1>
// // <strong style="color: #1b03a3; font-size: 16px"> Hey ${name},</strong>
// // <p style="color: #555; font-size: 15px;">
// // Welcome to Cheminova - Let the Shopping Begin!
// // </p>
// // <br/>
// // <p style="color: #555; font-size: 15px;">You can login into :${role === "Employee" || role === "admin"
// // ? `https://admin.smellika.com/`
// // : `https://smellika.com`
// // } </p>
// // <br/>
// // <p style="color: #555; font-size: 15px;">Below are your login credentials:</p>
// // <p style="color: #555; font-size: 15px;">Email: ${email}</p>
// // <p style="color: #555; font-size: 15px;">Password: ${password}</p>
// // <span style="color: #555; font-size: 13px;">Happy shopping,</span><br/>
// // <span style="color: #555; font-size: 13px;">Team ${appName}</span>`,
// // });
// 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, password, phone, accessTo, role } = req.body;
// 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();
// 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,
});
// 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.
<br/>Name: <strong>${name}</strong><br/>
<br/>Mobile Number: <strong>${phone}</strong><br/>
<br/>Password: <strong>${password}</strong><br/><br/>
<a href="${process.env.PD_APP_URL}/login">Click here to login</a><br/><br/>
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: <br/> <strong> ${passwords}</strong><br/><br/>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,
});
}
});