This commit is contained in:
syedmujahidahmed 2024-04-03 17:12:36 +05:30
commit 5431ee3392
6 changed files with 218 additions and 38 deletions

View File

@ -56,15 +56,23 @@ export const checkout = async (req, res) => {
const { address, cart, subtotal } = req.body; const { address, cart, subtotal } = req.body;
if (cart.length < 1) if (cart.length < 1)
return res.status(400).json({ message: "cart is empty!" }); return res.status(400).json({ message: "cart is empty!" });
switch (true) { if (!address)
//validation return res
case !address: { .status(404)
return res.status(404).json({ msg: "please provide shipping address" }); .json({ message: "please select shipping address!" });
} if (!subtotal)
case !subtotal: { return res
return res.status(404).json({ msg: "please provide product subtotal" }); .status(404)
} .json({ message: "please provide product subtotal!" });
} // switch (true) {
// //validation
// case !address: {
// return res.status(404).json({ msg: "please select shipping address" });
// }
// case !subtotal: {
// return res.status(404).json({ msg: "please provide product subtotal" });
// }
// }
let addss = await shippingAddress.findById(address); let addss = await shippingAddress.findById(address);
let shipping = { let shipping = {
first_Name: addss.first_Name, first_Name: addss.first_Name,
@ -77,12 +85,18 @@ export const checkout = async (req, res) => {
country: addss.country, country: addss.country,
addressId: address, addressId: address,
}; };
// console.log("cart", cart[0]?.product?.gst);
const orderItems = await cart.map((item) => ({ const orderItems = await cart.map((item) => ({
product: item.product._id, product: item.product._id,
name: item.product.name, name: item.product.name,
price: item.product.total_amount, price: item.product.price,
total_Amount: item.product.total_amount,
image: item.product.image, image: item.product.image,
quantity: item.quantity, quantity: item.quantity,
gst_amount: item.product.gst_amount,
gst_rate: item.product.gst?.tax,
tax_Name: item.product.gst?.name,
product_Subtotal: item.subtotal, product_Subtotal: item.subtotal,
})); }));
@ -130,7 +144,7 @@ export const paymentVerification = async (req, res) => {
path: "user", path: "user",
select: "name email -_id", select: "name email -_id",
}); });
console.log("findSameOrder", findSameOrder); // console.log("findSameOrder", findSameOrder);
if (findSameOrder) { if (findSameOrder) {
(findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({ (findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({
(findSameOrder.isPaid = true), (findSameOrder.isPaid = true),
@ -143,7 +157,7 @@ export const paymentVerification = async (req, res) => {
await findSameOrder.save(); await findSameOrder.save();
} }
//send email to customer //send email to customer
// console.log("findSameOrder", findSameOrder);
await sendEmail({ await sendEmail({
to: `${findSameOrder?.user?.email}`, // Change to your recipient to: `${findSameOrder?.user?.email}`, // Change to your recipient
@ -151,10 +165,84 @@ export const paymentVerification = async (req, res) => {
subject: `Your Order #${findSameOrder?.orderID} Confirmation`, subject: `Your Order #${findSameOrder?.orderID} Confirmation`,
html: ` <h1 style="color: #333; text-align: center; font-family: Arial, sans-serif;">Welcome to Smellika - Let the Shopping Begin!</h1> html: ` <h1 style="color: #333; text-align: center; font-family: Arial, sans-serif;">Welcome to Smellika - Let the Shopping Begin!</h1>
<strong style="color: #1b03a3; font-size: 16px"> Hi ${findSameOrder?.shippingInfo?.first_Name},</strong> <strong style="color: #1b03a3; font-size: 16px"> Hi ${
findSameOrder?.shippingInfo?.first_Name
},</strong>
<p style="color: #555; font-size: 15px;">Great news! Your order #${findSameOrder?.orderID} has been confirmed. Here are the details</p> <p style="color: #555; font-size: 15px;">Great news! Your order #${
<br/> findSameOrder?.orderID
} has been confirmed. Here are the details</p>
<h4 style="color: #333; font-family: Arial, sans-serif;">Shipping Address : ${
findSameOrder?.shippingInfo?.first_Name
} ${findSameOrder?.shippingInfo?.last_Name} , ${
findSameOrder?.shippingInfo?.street
} ${findSameOrder?.shippingInfo?.city} ${
findSameOrder?.shippingInfo?.state
} ${findSameOrder?.shippingInfo?.country}, PIN-${
findSameOrder?.shippingInfo?.postalCode
}, Phone Number: ${findSameOrder?.shippingInfo?.phone_Number}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
<table style="border-collapse: collapse; width: 100%;">
<thead>
<tr>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">S No.</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">Product Name</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">Image</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">Quantity</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">Price</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">GST Amount</th>
<th style="border: 1px solid #555; padding: 2px; text-align: center;">SubTotal</th>
</tr>
</thead>
<tbody>
${findSameOrder?.orderItems
?.map(
(product, index) => `
<tr>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
index + 1
}</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.name
}</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;"><img src="${
product?.image[0]?.url
}" alt="${
product.name
}" style="max-width: 40px; height: auto;"></td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.quantity
}</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.price
}</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product?.gst_amount
}</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.product_Subtotal
}</td>
</tr>
`
)
.join("")}
<tr>
<th colspan="6" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount :</th>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${
findSameOrder?.total_amount
}</td>
</tr>
</tbody>
</table>
<br/>
<span style="color: #555; font-size: 13px;">Best regards,</span><br/> <span style="color: #555; font-size: 13px;">Best regards,</span><br/>
<span style="color: #555; font-size: 13px;">Team Smellika</span>`, <span style="color: #555; font-size: 13px;">Team Smellika</span>`,
@ -171,7 +259,7 @@ export const paymentVerification = async (req, res) => {
// razorpay_signature, // razorpay_signature,
// }); // });
res.redirect(`http://localhost:5173/account`); res.redirect(`https://smellika.com/shop`);
// res.redirect( // res.redirect(
// `http://localhost:5173/cart/paymentsuccess?reference=${razorpay_payment_id}` // `http://localhost:5173/cart/paymentsuccess?reference=${razorpay_payment_id}`
// ); // );

View File

@ -36,7 +36,33 @@ export const getAllOrder = async (req, res) => {
}); });
} }
}; };
export const getOrders = async (req, res) => {
try {
const order = await Order.find({
payment_status: "success",
})
.populate({
path: "user",
select: "name -_id",
})
.populate({
path: "shippingInfo.addressId",
})
.sort({ updatedAt: -1 });
if (order) {
res.status(201).json({
success: true,
order,
message: "All Order Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
export const getSingleOrder = async (req, res) => { export const getSingleOrder = async (req, res) => {
try { try {
if (!req.params.id) if (!req.params.id)
@ -89,6 +115,7 @@ export const getUserSelf = async (req, res) => {
}); });
} }
}; };
export const deleteOneOrder = async (req, res) => { export const deleteOneOrder = async (req, res) => {
try { try {
if (!req?.user) return res.status(400).json({ message: "please login !" }); if (!req?.user) return res.status(400).json({ message: "please login !" });

View File

@ -66,6 +66,10 @@ const orderSchema = new mongoose.Schema(
type: Number, type: Number,
default: "", default: "",
}, },
total_Amount: {
type: Number,
default: "",
},
quantity: { quantity: {
type: Number, type: Number,
default: "", default: "",
@ -77,6 +81,18 @@ const orderSchema = new mongoose.Schema(
type: Number, type: Number,
default: "", default: "",
}, },
gst_amount: {
type: Number,
default: "",
},
gst_rate: {
type: Number,
default: "",
},
tax_Name: {
type: String,
default: "",
},
product: { product: {
type: mongoose.Schema.ObjectId, type: mongoose.Schema.ObjectId,
ref: "Product", ref: "Product",

View File

@ -2,6 +2,7 @@ import bodyParser from "body-parser";
import { import {
deleteOneOrder, deleteOneOrder,
getAllOrder, getAllOrder,
getOrders,
getSingleOrder, getSingleOrder,
getUserSelf, getUserSelf,
updateOrderStatusById, updateOrderStatusById,
@ -46,6 +47,9 @@ router.route("/user/self").get(isAuthenticatedUser, getUserSelf);
router router
.route("/getAll/:status") .route("/getAll/:status")
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder); .get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder);
router
.route("/getAll/")
.get(isAuthenticatedUser, authorizeRoles("admin"), getOrders);
router.route("/getOne/:id").get(isAuthenticatedUser, getSingleOrder); router.route("/getOne/:id").get(isAuthenticatedUser, getSingleOrder);
router.route("/change/status/:id").patch(updateOrderStatusById); router.route("/change/status/:id").patch(updateOrderStatusById);

View File

@ -6,6 +6,7 @@ import sendEmail from "../../Utils/sendEmail.js";
import crypto from "crypto"; import crypto from "crypto";
import cloudinary from "cloudinary"; import cloudinary from "cloudinary";
import password from "secure-random-password"; import password from "secure-random-password";
import { Order } from "../Orders/orderModel.js";
// 1.Register a User // 1.Register a User
export const registerUser = async (req, res) => { export const registerUser = async (req, res) => {
try { try {
@ -200,6 +201,24 @@ export const getUserDetails = catchAsyncErrors(async (req, res, next) => {
user, 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) // 7.Get single user (admin)
export const getSingleUser = catchAsyncErrors(async (req, res, next) => { export const getSingleUser = catchAsyncErrors(async (req, res, next) => {
@ -219,6 +238,29 @@ export const getSingleUser = catchAsyncErrors(async (req, res, next) => {
user, 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 // 8.update User password
export const updatePassword = catchAsyncErrors(async (req, res, next) => { export const updatePassword = catchAsyncErrors(async (req, res, next) => {
const user = await User.findById(req.user.id).select("+password"); const user = await User.findById(req.user.id).select("+password");
@ -284,7 +326,8 @@ export const updateProfile = catchAsyncErrors(async (req, res, next) => {
// 9.Get all users(admin) // 9.Get all users(admin)
export const getAllUser = catchAsyncErrors(async (req, res, next) => { export const getAllUser = catchAsyncErrors(async (req, res, next) => {
const users = await User.find(); //.select('-role'); // Assuming your User model is imported as 'User'
const users = await User.find({ role: "user" });
res.status(200).json({ res.status(200).json({
success: true, success: true,

View File

@ -1,17 +1,18 @@
import express from "express" import express from "express";
import { import {
registerUser, registerUser,
loginUser, loginUser,
logout, logout,
forgotPassword, forgotPassword,
resetPassword, resetPassword,
getUserDetails, getUserDetails,
updatePassword, updatePassword,
updateProfile, updateProfile,
getSingleUser, getSingleUser,
getAllUser getAllUser,
} from "./userController.js" getUserOrderForAdmin,
import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js" } from "./userController.js";
import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js";
const router = express.Router(); const router = express.Router();
@ -27,17 +28,18 @@ router.route("/user/logout").get(logout);
router.route("/user/details").get(isAuthenticatedUser, getUserDetails); router.route("/user/details").get(isAuthenticatedUser, getUserDetails);
router router
.route("/admin/users") .route("/admin/users")
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllUser); .get(isAuthenticatedUser, authorizeRoles("admin"), getAllUser);
router router
.route("/admin/user/:id") .route("/admin/users/orders/:id")
.get(isAuthenticatedUser, authorizeRoles("admin"), getSingleUser); .get(isAuthenticatedUser, authorizeRoles("admin"), getUserOrderForAdmin);
router
.route("/admin/user/:id")
.get(isAuthenticatedUser, authorizeRoles("admin"), getSingleUser);
router.route("/user/password/update").put(isAuthenticatedUser, updatePassword); router.route("/user/password/update").put(isAuthenticatedUser, updatePassword);
router.route("/user/update/profile").put(isAuthenticatedUser, updateProfile); router.route("/user/update/profile").put(isAuthenticatedUser, updateProfile);
export default router;
export default router;