diff --git a/.env b/.env index e5b250d..c10b19c 100644 --- a/.env +++ b/.env @@ -12,12 +12,12 @@ CLOUDINARY_API_KEY = "877544192441588" CLOUDINARY_API_SECRET = "9paejuSC-fY5b0WoaUuSFURSnvM" WEBHOOK_SECRET_KEY="whsec_m9u7CFBCY1qWarhxq65CkII6egOBf20K" -STRIPE_SECRET_KEY="sk_test_51OhPRdSG6gbAOwcEid1GavJ4FTD0ZuHVTferdvJwKal77RlMtFJGBzL5GjtL0ie8ZJztsGjUWi8DWrnw1pDdDRGS005Hk0ahql" -STRIPE_WEBHOOK_SECRET="whsec_dc9b9084fc764c806c8c5c06dd91de1ee809e9c8deab6d56e8e3ef2fc9c30c67" -<<<<<<< HEAD +# STRIPE_SECRET_KEY="sk_test_51OhPRdSG6gbAOwcEid1GavJ4FTD0ZuHVTferdvJwKal77RlMtFJGBzL5GjtL0ie8ZJztsGjUWi8DWrnw1pDdDRGS005Hk0ahql" +# STRIPE_WEBHOOK_SECRET="whsec_dc9b9084fc764c806c8c5c06dd91de1ee809e9c8deab6d56e8e3ef2fc9c30c67" + FRONTEND_URL="http://127.0.0.1:5173" -RAZERPAY_KEY_ID="rzp_test_smzQmWoS64S2W9" -RAZERPAY_SECRET_KEY="cSn6MgA4xSEaZBpPp4zpDA3C" +RAZERPAY_KEY_ID="rzp_test_2rg1Bq3Ki8xw9e" +RAZERPAY_SECRET_KEY="WFhHbXL7AlLIuull9kKjYiNA" FRONTEND_URL="https://smellika.com" diff --git a/resources/Orders/RazerPayCheckoutController.js b/resources/Orders/RazerPayCheckoutController.js index fe4f436..b0b0afc 100644 --- a/resources/Orders/RazerPayCheckoutController.js +++ b/resources/Orders/RazerPayCheckoutController.js @@ -39,20 +39,7 @@ export const getRzpkey = async (req, res) => { }); }; export const checkout = async (req, res) => { - // console.log(req.body.subtotal); - const options = { - amount: Number(req.body.subtotal * 100), - currency: "INR", - }; - const order = await instance.orders.create(options); - // id: "order_Ns423uPG0r36Dk"; - - //save order in database - - if (order?.id) { - const { email } = req.user; - if (!email) - return res.status(400).send({ message: "Please enter the email" }); + try { const { address, cart, subtotal } = req.body; if (cart.length < 1) return res.status(400).json({ message: "cart is empty!" }); @@ -64,63 +51,90 @@ export const checkout = async (req, res) => { return res .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 shipping = { - first_Name: addss.first_Name, - last_Name: addss.last_Name, - phone_Number: addss.phone_Number, - street: addss.street, - city: addss.city, - state: addss.state, - postalCode: addss?.postalCode, - country: addss.country, - addressId: address, + const options = { + amount: Number(req.body.subtotal * 100), + currency: "INR", }; - // console.log("cart", cart[0]?.product?.gst); - const orderItems = await cart.map((item) => ({ - product: item.product._id, - name: item.product.name, - price: item.product.price, - total_Amount: item.product.total_amount, + const order = await instance.orders.create(options); + //save order in database + if (order?.id) { + const { email } = req.user; + if (!email) + return res.status(400).send({ message: "Please enter the email" }); + let addss = await shippingAddress.findById(address); + let shipping = { + first_Name: addss.first_Name, + last_Name: addss.last_Name, + phone_Number: addss.phone_Number, + street: addss.street, + city: addss.city, + state: addss.state, + postalCode: addss?.postalCode, + country: addss.country, + addressId: address, + }; + // console.log("cart", cart[0]?.product?.gst); + const orderItems = await cart.map((item) => ({ + product: item.product._id, + name: item.product.name, + variant_Name: item.variant.variant_Name, + price: Number(item.variant.price), + total_price: item.quantity * Number(item.variant.price), - image: item.product.image, - 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, - })); + image: item.product.image, + quantity: item.quantity, + gst_amount: Number( + (Number(item.variant.price) * item.variant.gst_Id?.tax) / 100 + )?.toFixed(3), + total_gst_amount: Number( + Number(item.quantity) * + Number( + (Number(item.variant.price) * item.variant.gst_Id?.tax) / 100 + ) + )?.toFixed(3), + gst_rate: item.variant.gst_Id?.tax, + tax_Name: item.variant?.gst_Id?.name, + product_Subtotal: Number( + Number(item.quantity * Number(item.variant.price)) + + Number( + Number(item.quantity) * + Number( + (Number(item.variant.price) * item.variant.gst_Id?.tax) / 100 + ) + ) + ).toFixed(3), + })); - // console.log("line", lineItems[0]); - const Id = await generateUniqueOrderId(); - const orders = await Order.create({ - orderID: Id, - total_amount: subtotal, - orderItems, - shippingInfo: shipping, - user: req.user._id, - razorpay_order_id: order?.id, + // console.log("line", lineItems[0]); + const Id = await generateUniqueOrderId(); + const orders = await Order.create({ + orderID: Id, + total_amount: subtotal, + orderItems, + shippingInfo: shipping, + user: req.user._id, + razorpay_order_id: order?.id, + }); + } else { + return res.status(400).json({ + success: false, + message: "Failled to order Create", + }); + } + + return res.status(200).json({ + success: true, + order, }); - } else { - res.status(400).json({ + } catch (error) { + console.log("error", error); + return res.status(400).json({ success: false, - message: "Failled to order Create", + message: error?.description + ? "Razorpay" + error?.description + : "Something went wrong!", }); } - - res.status(200).json({ - success: true, - order, - }); }; export const paymentVerification = async (req, res) => { @@ -188,6 +202,8 @@ export const paymentVerification = async (req, res) => { S No. Product Name + Variant + Image Quantity @@ -210,6 +226,9 @@ export const paymentVerification = async (req, res) => { ${ product.name } + ${ + product?.variant_Name + } ${
@@ -226,7 +245,7 @@ export const paymentVerification = async (req, res) => {
            product?.gst_amount
          }</td>
                 <td style=₹${ - product.product_Subtotal + product?.product_Subtotal } @@ -234,7 +253,7 @@ export const paymentVerification = async (req, res) => { ) .join("")} - Total Amount : + Total Amount : ₹${ findSameOrder?.total_amount } diff --git a/resources/Orders/orderController.js b/resources/Orders/orderController.js index 38d618b..0e1ddd4 100644 --- a/resources/Orders/orderController.js +++ b/resources/Orders/orderController.js @@ -176,14 +176,12 @@ export const updateOrderStatusById = async (req, res) => { S No. - Product Name + Variant Image - Quantity Price GST Amount - SubTotal @@ -199,6 +197,9 @@ export const updateOrderStatusById = async (req, res) => { ${ product.name + } + ${ + product?.variant_Name } - Total Amount : + Total Amount : ₹${ order?.total_amount } @@ -267,6 +268,7 @@ export const updateOrderStatusById = async (req, res) => { S No. Product Name + Variant Image Quantity @@ -288,6 +290,9 @@ export const updateOrderStatusById = async (req, res) => { ${ product.name + } + ${ + product?.variant_Name } - Total Amount : + Total Amount : ₹${ order?.total_amount } @@ -383,6 +388,7 @@ export const updateOrderStatusById = async (req, res) => { S No. Product Name + Variant Image Quantity @@ -404,6 +410,9 @@ export const updateOrderStatusById = async (req, res) => { ${ product.name + } + ${ + product?.variant_Name } - Total Amount : + Total Amount : ₹${ order?.total_amount } @@ -470,8 +479,8 @@ export const updateOrderStatusById = async (req, res) => { S No. Product Name + Variant Image - Quantity Price GST Amount @@ -491,6 +500,9 @@ export const updateOrderStatusById = async (req, res) => { ${ product.name + } + ${ + product?.variant_Name } - Total Amount : + Total Amount : ₹${ order?.total_amount } diff --git a/resources/Orders/orderModel.js b/resources/Orders/orderModel.js index b41e027..79f12f8 100644 --- a/resources/Orders/orderModel.js +++ b/resources/Orders/orderModel.js @@ -62,11 +62,15 @@ const orderSchema = new mongoose.Schema( type: String, default: "", }, + variant_Name: { + type: String, + default: "", + }, price: { type: Number, default: "", }, - total_Amount: { + total_price: { type: Number, default: "", }, @@ -85,6 +89,10 @@ const orderSchema = new mongoose.Schema( type: Number, default: "", }, + total_gst_amount: { + type: Number, + default: "", + }, gst_rate: { type: Number, default: "", diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index ed85c84..2293cbd 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -62,9 +62,6 @@ export const updateProduct = async (req, res) => { } if (req.files) { - // req.body.addedBy = req.user.id; - // const image_file = req.files.image; - // console.log("req.files", req.files); const getProduct = await Product.findById(req.params.id); if (getProduct.image?.length > 0) { @@ -116,19 +113,36 @@ export const updateProduct = async (req, res) => { //////////////////////////////////////////////////////////////////////////// //get All Product -export const getAllProduct = async (req, res) => { +export const getAllProductAdmin = async (req, res) => { try { - const product = await Product.find() + const PAGE_SIZE = parseInt(req.query?.show || "10"); + const page = parseInt(req.query?.page - 1 || "0"); + let obj = {}; + if (req.query?.name) + obj.name = { + $regex: new RegExp(req.query.name), + $options: "i", + }; + if (req.query?.category) obj.category = req.query.category; + const total = await Product.countDocuments(obj); + const product = await Product.find(obj) .populate({ path: "category addedBy variants.gst_Id", select: "name categoryName tax", }) + .limit(PAGE_SIZE) + .skip(PAGE_SIZE * page) + // .sort("name") .sort({ createdAt: -1, - }); + }) + .exec(); + if (product) { return res.status(200).json({ success: true, + total_data: total, + total_pages: Math.ceil(total / PAGE_SIZE), product, }); } @@ -139,6 +153,83 @@ export const getAllProduct = async (req, res) => { }); } }; + +//get All Product User(website) +export const getAllProductUser = async (req, res) => { + try { + const PAGE_SIZE = parseInt(req.query?.show || "10"); + const page = parseInt(req.query?.page - 1 || "0"); + let obj = {}; + if (req.query?.name) + obj.name = { + $regex: new RegExp(req.query.name), + $options: "i", + }; + if (req.query?.category) obj.category = req.query.category; + obj.product_Status = "Active"; + const total = await Product.countDocuments(obj); + const product = await Product.find(obj) + .populate({ + path: "category addedBy variants.gst_Id", + select: "name categoryName tax", + }) + .limit(PAGE_SIZE) + .skip(PAGE_SIZE * page) + // .sort("name") + .sort({ + createdAt: -1, + }) + .exec(); + + if (product) { + return res.status(200).json({ + success: true, + total_data: total, + total_pages: Math.ceil(total / PAGE_SIZE), + product, + }); + } + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!", + }); + } +}; +//Change Product status +export const ChangeProductStatus = async (req, res) => { + try { + const data = await Product.findById(req.params.id); + if (data) { + if (data?.product_Status === "Active") { + let product = await Product.findByIdAndUpdate( + req.params.id, + { product_Status: "inActive" }, + { new: true } // Return the updated document + ); + return res.status(200).json({ + success: true, + msg: "Changed status inActive", + }); + } else { + let product = await Product.findByIdAndUpdate( + req.params.id, + { product_Status: "Active" }, + { new: true } // Return the updated document + ); + return res.status(200).json({ + success: true, + msg: "Changed status Active", + }); + } + } + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!", + }); + } +}; //get One Product export const getOneProduct = async (req, res) => { try { @@ -165,11 +256,9 @@ export const getOneProduct = async (req, res) => { export const getAllProductsDevicesFirst = async (req, res) => { try { // we want products with category name Device to be displayed first, so i have first found the products with category name Devices then made another request to find all products and filtered products with category devices , then merged both arrays so we get devices first then all other categories - const categoryName = "Devices"; // Find the category object by name first const category = await CategoryModel.findOne({ categoryName }); - if (!category) { throw new Error("Category not found"); } diff --git a/resources/Products/ProductModel.js b/resources/Products/ProductModel.js index ce6c44f..073d5c2 100644 --- a/resources/Products/ProductModel.js +++ b/resources/Products/ProductModel.js @@ -66,7 +66,7 @@ const productSchema = new Schema( ], product_Status: { type: String, - enum: ["Active", "Inactive"], + enum: ["Active", "inActive"], default: "Active", }, addedBy: { diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js index 32cdca7..5641538 100644 --- a/resources/Products/ProductRoute.js +++ b/resources/Products/ProductRoute.js @@ -1,20 +1,29 @@ import express from "express"; import { createProduct, - getAllProduct, + getAllProductAdmin, updateProduct, deleteProduct, getOneProduct, deleteImageFromCloudinary, getProductsByCategory, + getAllProductUser, getAllProductsDevicesFirst, + ChangeProductStatus, } from "./ProductController.js"; const router = express.Router(); import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; router .route("/product/create/") .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct); -router.route("/product/getAll/").get(getAllProduct); +router + .route("/product/getAll/admin/") + .get(isAuthenticatedUser, authorizeRoles("admin"), getAllProductAdmin); + +//change Product status +router.route("/product/admin/status/:id").patch(ChangeProductStatus); +//get all product user +router.route("/product/getAll/user/").get(getAllProductUser); router .route("/product/getAllProductsDevicesFrist/") .get(getAllProductsDevicesFirst);