From 5378264c99593a0e220a6335a2cbcc6feeadc523 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Fri, 19 Apr 2024 15:54:41 +0530 Subject: [PATCH 1/6] point of sale instorecashOrders --- app.js | 4 + resources/PosOrders/PosCheckoutController.js | 85 +++ .../PosRazerPayCheckoutController.js | 481 +++++++++++++++ resources/PosOrders/PosorderController.js | 552 ++++++++++++++++++ resources/PosOrders/PosorderModel.js | 165 ++++++ resources/PosOrders/PosorderRoute.js | 51 ++ 6 files changed, 1338 insertions(+) create mode 100644 resources/PosOrders/PosCheckoutController.js create mode 100644 resources/PosOrders/PosRazerPayCheckoutController.js create mode 100644 resources/PosOrders/PosorderController.js create mode 100644 resources/PosOrders/PosorderModel.js create mode 100644 resources/PosOrders/PosorderRoute.js diff --git a/app.js b/app.js index 6adea88..4781cde 100644 --- a/app.js +++ b/app.js @@ -171,6 +171,8 @@ import CouponRoute from "./resources/Affiliate&Coupon/Coupon/CouponRoute.js"; // import ShortUrlRouter from "./resources/Businesses/Short_Urls/ShortUrlRoute.js"; //support Ticket import SupportRouter from "./resources/Supports/supportRoute.js"; +// Point of Sale +import PosorderRoute from "./resources/PosOrders/PosorderRoute.js"; app.use("/api/v1/", user); //Product @@ -238,4 +240,6 @@ app.use("/api/panel", PanelRoute); // app.use("/api/shorturl", ShortUrlRouter); //Support app.use("/api", SupportRouter); +// Point of Sale +app.use("/api/posOrder", PosorderRoute); export default app; diff --git a/resources/PosOrders/PosCheckoutController.js b/resources/PosOrders/PosCheckoutController.js new file mode 100644 index 0000000..8acb18e --- /dev/null +++ b/resources/PosOrders/PosCheckoutController.js @@ -0,0 +1,85 @@ +import { POSOrder } from "./PosorderModel.js"; +import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; + +//generate unique order id +const generateOrderId = async () => { + const currentYear = new Date().getFullYear(); + // Find the latest order to get the last serial number + const latestOrder = await POSOrder.findOne({}, {}, { sort: { orderID: -1 } }); + let serialNumber = 1; + + if (latestOrder) { + const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); + if (lastYear === currentYear) { + // If the last order was in the current year, increment the serial number + serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; + } + } + // Pad the serial number with zeros and concatenate with the current year + const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); + const orderId = `${currentYear}${paddedSerialNumber}`; + return orderId; +}; + +export const createOrderCheckout = async (req, res) => { + try { + const { address, cart, user, SalesType, paymentMode } = + req.body; +// console.log(req.body) + // Perform validation + if (!address || !cart || cart.length === 0 || !SalesType || !user || !paymentMode) { + return res.status(400).json({ message: "Invalid order data" }); + } + + // Retrieve shipping address from database + const shippingInfo = await shippingAddress.findById(address); + if (!shippingInfo) { + return res.status(404).json({ message: "Shipping address not found" }); + } + + // Ensure that addressId is included in the shippingInfo object + const { _id: addressId, ...restOfShippingInfo } = shippingInfo.toObject(); + + // Calculate total amount based on the product_Subtotal of each product + const totalAmount = cart.reduce( + (acc, item) => acc + item.product_Subtotal, + 0 + ); + + // Construct order items array + const orderItems = cart.map((item) => ({ + product: item.product, + name: item.name, + price: item.price, + quantity: item.quantity, + product_Subtotal: item.total_amount, + gst_amount: item.gst_amount, + image: item.image, + variant_Name: item.variant_Name, + })); + + // Generate a unique order ID + const orderId = await generateOrderId(); + + // Create the order document + const order = await POSOrder.create({ + orderID: orderId, + total_amount: totalAmount, + orderItems, + shippingInfo: { + addressId: addressId, // Include the addressId + ...restOfShippingInfo, // Include other shipping information + }, + user, // Assuming you have authenticated users + SalesType, + paymentMode, + }); + + return res.status(201).json({ success: true, order }); + } catch (error) { + console.error("Error creating order:", error); + return res + .status(500) + .json({ success: false, message: "Internal server error" }); + } +}; diff --git a/resources/PosOrders/PosRazerPayCheckoutController.js b/resources/PosOrders/PosRazerPayCheckoutController.js new file mode 100644 index 0000000..111fbe4 --- /dev/null +++ b/resources/PosOrders/PosRazerPayCheckoutController.js @@ -0,0 +1,481 @@ +import bodyParser from "body-parser"; +import crypto from "crypto"; +import Razorpay from "razorpay"; +import { POSOrder } from "./PosorderModel.js"; +import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; +import sendEmail from "../../Utils/sendEmail.js"; +const instance = new Razorpay({ + key_id: process.env.RAZERPAY_KEY_ID, + key_secret: process.env.RAZERPAY_SECRET_KEY, +}); + +const generateUniqueOrderId = async () => { + const currentYear = new Date().getFullYear(); + // Find the latest order to get the last serial number + const latestOrder = await POSOrder.findOne({}, {}, { sort: { orderID: -1 } }); + let serialNumber = 1; + + if (latestOrder) { + const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); + if (lastYear === currentYear) { + // If the last order was in the current year, increment the serial number + serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; + } + } + // Pad the serial number with zeros and concatenate with the current year + const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); + const orderId = `${currentYear}${paddedSerialNumber}`; + return orderId; +}; + +export const getRzpKey = async (req, res) => { + try { + const { name, email } = req.params; + console.log("name", name, "email", email); + if (!name || !email) { + throw new Error("Name and email are required parameters"); + } + res.status(200).json({ + success: true, + key: process.env.RAZERPAY_KEY_ID, + name, + email, + }); + } catch (error) { + console.error("Error in getRzpKey:", error); + res + .status(500) + .json({ + success: false, + message: error.message || "Internal server error", + }); + } +}; + +export const checkout = async (req, res) => { + try { + console.log(req.body); + const options = { + amount: Number(req.body.subtotal * 100), + currency: "INR", + }; + + console.log("options", options); + + // Wait for the order creation to complete + const order = await instance.orders.create(options); + + console.log("order", order); + + // Check if the order was created successfully + if (!order || !order.id) { + return res.status(400).json({ + success: false, + message: "Failed to create order", + }); + } + + // Extract required data from request parameters and body + const { email } = req.params; + const { address, cart, user, SalesType, paymentMode, subtotal } = req.body; + + // Check for required parameters + if (!email) { + return res.status(400).send({ message: "Please enter the email" }); + } + + if (cart.length < 1) { + return res.status(400).json({ message: "Cart is empty!" }); + } + + if (!address) { + return res + .status(404) + .json({ message: "Please select a shipping address!" }); + } + + if (!subtotal) { + return res + .status(404) + .json({ message: "Please provide the product subtotal!" }); + } + + // Fetch shipping information from the database + const shippingInfo = await shippingAddress.findById(address); + if (!shippingInfo) { + return res.status(404).json({ message: "Shipping address not found" }); + } + + console.log("shippinginfo", shippingInfo); + + // Extract addressId and other shipping information + const { _id: addressId, ...restOfShippingInfo } = shippingInfo.toObject(); + + // Prepare order items + const orderItems = cart.map((item) => ({ + product: item.product, + name: item.name, + price: item.price, + quantity: item.quantity, + product_Subtotal: item.total_amount, + gst_amount: item.gst_amount, + image: item.image, + variant_Name: item.variant_Name, + })); + + // Generate a unique order ID + const orderId = await generateUniqueOrderId(); + + // Create the order in the database + const orders = await POSOrder.create({ + orderID: orderId, + total_amount: subtotal, + orderItems, + shippingInfo: { + addressId: addressId, + ...restOfShippingInfo, + }, + user, + SalesType, + paymentMode, + razorpay_order_id: order.id, + }); + + res.status(200).json({ + success: true, + order, + }); + } catch (error) { + console.error("Error in checkout:", error); + res + .status(500) + .json({ + success: false, + message: error.message || "Internal server error", + }); + } +}; + +export const paymentVerification = async (req, res) => { + const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = + req.body; + console.log(req.body); + const body = razorpay_order_id + "|" + razorpay_payment_id; + + const expectedSignature = crypto + .createHmac("sha256", process.env.RAZERPAY_SECRET_KEY) + .update(body.toString()) + .digest("hex"); + + const isAuthentic = expectedSignature === razorpay_signature; + + if (isAuthentic) { + // Database comes here + let findSameOrder = await POSOrder.findOne({ + razorpay_order_id: razorpay_order_id, + }).populate({ + path: "user", + select: "name email -_id", + }); + // console.log("findSameOrder", findSameOrder); + if (findSameOrder) { + (findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({ + (findSameOrder.isPaid = true), + (findSameOrder.paidAt = Date.now()), + (findSameOrder.razorpay_signature = razorpay_signature); + // await Payment.create({ + findSameOrder.payment_status = "success"; + + findSameOrder.orderStatus = "new"; + await findSameOrder.save(); + } + //send email to customer + // console.log("findSameOrder", findSameOrder); + await sendEmail({ + to: `${findSameOrder?.user?.email}`, // Change to your recipient + + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + + subject: `Your POSOrder #${findSameOrder?.orderID} Confirmation`, + html: `

Welcome to Smellika - Let the Shopping Begin!

+ Hi ${ + findSameOrder?.shippingInfo?.first_Name + }, + +

Great news! Your order #${ + findSameOrder?.orderID + } has been confirmed. Here are the details

+

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}

+

POSOrder Items :

+ + + + + + + + + + + + + + + + + + ${findSameOrder?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${
+          product.name
+        }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product.product_Subtotal + }
Total Amount :₹${ + findSameOrder?.total_amount + }
+ +
+ Best regards,
+ + Team Smellika`, + }); + // console.log("findSameOrder", findSameOrder); + + // // findSameOrder.razorpay_payment_id=razorpay_payment_id,// await Payment.create({ + // findOrder.paidAt = new Date(event.data.object.created * 1000); + // findOrder.isPaid = true; + + // razorpay_signature: { type: String }, + // razorpay_order_id, + // razorpay_payment_id, + // razorpay_signature, + // }); + + // res.redirect(`https://admin.smellika.com/#/pos`); + res.redirect(`http://localhost:3000/#/pos`); + } else { + res.status(400).json({ + success: false, + }); + } +}; +export const handlePayment = async (req, res) => { + try { + const { email } = req.user; + if (!email) + return res.status(400).send({ message: "Please enter the email" }); + const { address, cart, subtotal } = req.body; + if (cart.length < 1) + return res.status(400).json({ message: "cart is empty!" }); + switch (true) { + //validation + case !address: { + return res.status(404).json({ msg: "please provide shipping address" }); + } + case !subtotal: { + return res.status(404).json({ msg: "please provide product subtotal" }); + } + } + let addss = await shippingAddress.findById(address); + // console.log(addss?.postalCode); + 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 orderItems = await cart.map((item) => ({ + product: item.product._id, + name: item.product.name, + price: item.product.total_amount, + image: item.product.image, + quantity: item.quantity, + product_Subtotal: item.subtotal, + })); + + // console.log("line", lineItems[0]); + const Id = await generateUniqueOrderId(); + const order = await POSOrder.create({ + orderID: Id, + total_amount: subtotal, + orderItems, + shippingInfo: shipping, + user: req.user._id, + }); + console.log("fffffffff", order, "llllllllll"); + const lineItems = await cart.map((item) => ({ + price_data: { + currency: "inr", + product_data: { + name: item.product.name, + + images: [item.product.image[0]?.url], + }, + unit_amount: Number(item.product.total_amount) * 100, + }, + quantity: Number(item.quantity), + })); + if (order) { + const session = await stripe.checkout.sessions.create({ + payment_method_types: ["card"], + line_items: lineItems, + mode: "payment", + customer_email: `${email}`, + metadata: { + orderId: order._id.toString(), + + // Add any other key-value pairs as needed + }, + success_url: `${process.env.FRONTEND_URL}/cart`, + cancel_url: `${process.env.FRONTEND_URL}/error`, + }); + // res.json({ sessionId: session.id }); + + res.status(200).send({ message: "order created", url: session.url }); + } + } catch (err) { + console.log(err); + res.status(500).send({ message: "Something went wrong", err }); + } +}; + +export const webhook = async (req, res) => { + const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; + const signature = req.headers["stripe-signature"]; + let event; + if (webhookSecret) { + try { + event = stripe.webhooks.constructEvent( + req.body, + signature, + webhookSecret + ); + } catch (err) { + console.log(`❌ Error message: ${err.message}`); + res.status(400).send(`Webhook Error: ${err.message}`); + return; + } + } + + if (event.type === "checkout.session.completed") { + // console.log("dddddddddddd", event.data); + const findOrder = await POSOrder.findById( + event.data.object.metadata?.orderId + ); + findOrder.paypal_payer_id = event.data.object.id; + findOrder.paidAt = new Date(event.data.object.created * 1000); + findOrder.isPaid = true; + if (event.data.object?.payment_status === "paid") { + findOrder.payment_status = "success"; + } else { + findOrder.payment_status = "failed"; + } + findOrder.orderStatus = "new"; + await findOrder.save(); + await sendEmail({ + to: `${event.data.object.customer_email}`, // Change to your recipient + + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + + subject: `Your POSOrder #${findOrder?.orderID} Confirmation`, + html: `

Welcome to Smellika - Let the Shopping Begin!

+ Hi ${findOrder?.shippingInfo?.first_Name}, + +

Great news! Your order #${findOrder?.orderID} has been confirmed. Here are the details

+
+ Best regards,
+ + Team Smellika`, + }); + + // Items: [List of Purchased Items] + // Total Amount: [Total Amount] + // Shipping Address: [Shipping Address] + + // We'll keep you updated on the shipping progress. Thanks for choosing Smellika! + + // Best regards + // Team Smellika + console.log( + "event.data.object", + event.data.object, + "---------------------" + ); + + console.log(`💰 Payment status: ${event.data.object?.payment_status}`); + + // Saving the payment details in the database + // const payment = await Payment.create({ + // customer_email: event.data.object.customer_email, + // amount: event.data.object.amount_total / 100, + // paymentId: event.data.object.id, + // paymentStatus: event.data.object.payment_status, + // createdAt: event.data.object.created, + // }); + } + // if (event.type === "checkout.session.completed") { + // console.log("dddddddddddd", event.data); + // console.log("event.data.object", event.data.object); + // console.log(`💰 Payment status: ${event.data.object?.payment_status}`); + // payment_intent.payment_failed; + + // // Saving the payment details in the database + // // const payment = await Payment.create({ + // // customer_email: event.data.object.customer_email, + // // amount: event.data.object.amount_total / 100, + // // paymentId: event.data.object.id, + // // paymentStatus: event.data.object.payment_status, + // // createdAt: event.data.object.created, + // // }); + // } + + // Return a 200 res to acknowledge receipt of the event + res.status(200).end(); + // res.send().end(); +}; diff --git a/resources/PosOrders/PosorderController.js b/resources/PosOrders/PosorderController.js new file mode 100644 index 0000000..6a02741 --- /dev/null +++ b/resources/PosOrders/PosorderController.js @@ -0,0 +1,552 @@ +import sendEmail from "../../Utils/sendEmail.js"; +import { POSOrder } from "./PosorderModel.js"; + +export const getAllOrder = async (req, res) => { + try { + const { status } = req.params; + const order = await POSOrder.find({ + IsStoreDelivery: "Cash", + orderStatus: status, + }) + .populate({ + path: "user", + select: "name -_id", + }) + .populate({ + path: "shippingInfo.addressId", + }) + .sort({ updatedAt: -1 }); + if (order) { + res.status(201).json({ + success: true, + order, + message: "All POSOrder Fetched", + }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; +export const getOrders = async (req, res) => { + try { + const order = await POSOrder.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 POSOrder Fetched", + }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; +export const getSingleOrder = async (req, res) => { + try { + if (!req.params.id) + return res.status(400).json({ message: "please Provide POSOrder Id" }); + + const order = await POSOrder.findById(req.params.id) + .populate({ + path: "user", + select: "name email -_id", + }) + .populate({ + path: "shippingInfo.addressId", + }) + .sort({ createdAt: -1 }); + if (order) { + res.status(201).json({ + success: true, + order, + message: " POSOrder Fetched", + }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; + +//get self User POSOrder +export const getUserSelf = async (req, res) => { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + try { + const order = await POSOrder.find({ + user: req.user?._id, + payment_status: "success", + }).sort({ createdAt: -1 }); + + if (order) { + return res.status(200).json({ + success: true, + order, + message: "self POSOrder fetched", + }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; + +export const deleteOneOrder = async (req, res) => { + try { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + if (!req.params.id) + return res.status(400).json({ message: "please Provide POSOrder Id" }); + const getOrder = await POSOrder.findById(req.params.id); + if (!getOrder) { + return res.status(404).json({ + success: false, + message: "No POSOrder Found!", + }); + } + const order = await POSOrder.findByIdAndDelete(req.params.id); + + await order.remove(); + res.status(200).json({ + success: true, + message: "POSOrder Deleted Successfully!!", + }); + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; +export const updateOrderStatusById = async (req, res) => { + try { + let body = { orderStatus: req.body.status }; + + const currentDate = new Date(); + body["status_timeline." + req.body.status] = currentDate; + // if (req.body?.package_weight) body.package_weight = req.body.package_weight; + const order = await POSOrder.findById(req.params.id).populate({ + path: "user", + select: "name email -_id", + }); + // console.log("order", order); + // const parentData = { email: order?.parent?.email }; + if (req.body.status === "cancelled") { + body["order_Cancelled_Reason"] = req.body?.ReasonforCancellation; + body["iscancelled"] = true; + await POSOrder.findByIdAndUpdate(order._id, body); + await sendEmail({ + to: `${order?.user?.email}`, // Change to your recipient + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + subject: `POSOrder #${order?.orderID} Update: Cancellation and Refund Process`, + html: ` Hi ${ + order?.shippingInfo?.first_Name + }, +

We hope this message finds you well. We're writing to inform you that your order ${ + order?.orderID + } has been canceled. We understand that circumstances may change, and we're here to assist you throughout the process.

+ + +

Items :

+ + + + + + + + + + + + + + + + + + ${order?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${
+          product.name
+        }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product.product_Subtotal + }
Total Amount :₹${ + order?.total_amount + }
+

Cancellation Reason : ${ + req.body?.ReasonforCancellation + }

+

Refund Information: The amount from your canceled order will be processed for a refund. Please allow up to 7 working days for the amount to be transferred back to your original payment method.

+ +
If you have any concerns or further questions, please feel free to reply to this email. We appreciate your understanding and hope to serve you better in the future. +
+
+ Best regards,
+ + Team Smellika`, + }); + return res + .status(200) + .json({ status: "ok", message: "POSOrder status updated successfully!" }); + } else if (req.body.status === "processing") { + await POSOrder.findByIdAndUpdate(order._id, body); + + await sendEmail({ + to: `${order?.user?.email}`, // Change to your recipient + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + subject: `Your POSOrder #${order?.orderID} is in Processing!`, + html: `

Exciting news! Your order #${ + order?.orderID + } has entered the processing phase. Our team is diligently preparing your items for dispatch. Rest assured, we're working hard to ensure everything is perfect for you.

+ Hi ${ + order?.shippingInfo?.first_Name + }, +

POSOrder Status : Processing

+

POSOrder Items :

+ + + + + + + + + + + + + + + + + + ${order?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${
+          product.name
+        }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product.product_Subtotal + }
Total Amount :₹${ + order?.total_amount + }
+
We'll send you another email with the tracking details as soon as your order is dispatched. If you have any questions or need assistance, feel free to reply to this email.
+
Thank you for choosing Smellika!
+
+ Best regards,
+ + Team Smellika`, + }); + return res + .status(200) + .json({ status: "ok", message: "POSOrder status updated successfully!" }); + } + // else if (body.status === "dispatched") { + // const noBalanceRemaining = + // order?.sales_items?.filter((e) => Number(e?.balance_quantity) > 0) + // ?.length === 0 + // ? true + // : false; + // if (!noBalanceRemaining) + // return res + // .status(400) + // .json({ message: "Few items still have balance quantity!" }); + // await OrderDispatchedEmail(parentData.email, order.order_id, body); + // await Invoice.updateMany( + // { order: order._id, status: { $in: ["processing"] } }, + // { status: body.status, "status_timeline.dispatched": currentDate } + // ); + // } else if (body.status === "delivered") { + // await OrderDeliveredEmail(parentData.email, order.order_id); + // await Invoice.updateMany( + // { order: order._id, status: { $in: ["processing", "dispatched"] } }, + // { status: body.status, "status_timeline.delivered": currentDate } + // ); + // } + else if (req.body.status === "dispatched") { + body["courier_name"] = req.body.courierName; + body["courier_tracking_id"] = req.body.TrackingID; + await POSOrder.findByIdAndUpdate(order._id, body); + await sendEmail({ + to: `${order?.user?.email}`, // Change to your recipient + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + subject: `Your POSOrder #${order?.orderID} is On Its Way!`, + html: ` Hi ${ + order?.shippingInfo?.first_Name + }, +

Exciting news! Your order #${ + order?.orderID + } has been dispatched and is en route to you. 🚚 Here are the details:

+ +

Courier Name : ${ + req.body.courierName + }

+

Courier Tracking ID : ${ + req.body.TrackingID + }

+ + +

Items :

+ + + + + + + + + + + + + + + + + + ${order?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${
+          product.name
+        }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product.product_Subtotal + }
Total Amount :₹${ + order?.total_amount + }
+

POSOrder Status : Dispatched

+

If you have any questions or need assistance, feel free to reply to this email. +

+
Thanks for choosing Smellika! We hope you enjoy your purchase. +
+
+ Best regards,
+ + Team Smellika`, + }); + return res + .status(200) + .json({ status: "ok", message: "POSOrder status updated successfully!" }); + } else if (req.body.status === "delivered") { + body["isDelivered"] = true; + body["DeliveredDate"] = req.body.DDate; + await POSOrder.findByIdAndUpdate(order._id, body); + await sendEmail({ + to: `${order?.user?.email}`, // Change to your recipient + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + subject: `Your POSOrder #${order?.orderID} Has Been Delivered!`, + html: ` Hi ${ + order?.shippingInfo?.first_Name + }, +

Great news! Your order #${ + order?.orderID + } has been successfully delivered to your doorstep. We hope everything is just as you expected!

+

Items :

+ + + + + + + + + + + + + + + + + + ${order?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${
+                product.name
+              }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product.product_Subtotal + }
Total Amount :₹${ + order?.total_amount + }
+

Delivery Date: ${ + req.body.DDate + }

+

Your satisfaction is our priority, and we'd love to hear about your experience. Please take a moment to share your thoughts by leaving a review. Your feedback is invaluable to us! +

+
If you have any questions or concerns about your order, feel free to reply to this email. +
+
Thank you for choosing Smellika! We hope to serve you again soon. + +
+
+ Best regards,
+ + Team Smellika`, + }); + + return res + .status(200) + .json({ status: "ok", message: "POSOrder status updated successfully!" }); + } else { + // await POSOrder.findByIdAndUpdate(order._id, body); + // console.log(order); + res + .status(200) + .json({ status: "ok", message: "POSOrder status updated successfully!" }); + } + } catch (error) { + console.log(error); + res + .status(500) + .json({ message: error?.message || "Something went wrong!" }); + } +}; diff --git a/resources/PosOrders/PosorderModel.js b/resources/PosOrders/PosorderModel.js new file mode 100644 index 0000000..5134084 --- /dev/null +++ b/resources/PosOrders/PosorderModel.js @@ -0,0 +1,165 @@ +import mongoose from "mongoose"; + +const POSorderSchema = new mongoose.Schema( + { + orderID: { + type: String, + required: true, + unique: true, + }, + user: { + type: mongoose.Schema.ObjectId, + ref: "User", + required: true, + }, + shippingInfo: { + first_Name: { + type: String, + required: true, + }, + last_Name: { + type: String, + required: true, + }, + phone_Number: { + type: Number, + required: true, + }, + street: { + type: String, + required: true, + }, + city: { + type: String, + required: true, + trim: true, + }, + state: { + type: String, + required: true, + }, + postalCode: { + type: String, + required: true, + trim: true, + // Add a regular expression to enforce a specific postal code format + // For example, assuming a 5-digit format for the United States + match: /^\d{6}$/, + }, + country: { + type: String, + required: true, + }, + addressId: { + type: mongoose.Schema.ObjectId, + ref: "ShippingAddress", + required: true, + }, + }, + orderItems: [ + { + name: { + type: String, + default: "", + }, + price: { + type: Number, + default: "", + }, + variant_Name: { type: String, default: "" }, + quantity: { + type: Number, + default: "", + default: 1, + }, + image: [{}], + + product_Subtotal: { + type: Number, + default: "", + }, + gst_amount: { + type: Number, + default: "", + }, + gst_rate: { + type: Number, + default: "", + }, + tax_Name: { + type: String, + default: "", + }, + product: { + type: mongoose.Schema.ObjectId, + ref: "Product", + }, + }, + ], + + shipping_charge: { type: Number, default: 0 }, + tax_amount: { type: Number, default: 0 }, + total_amount: { type: Number, default: 0 }, + weight: { type: Number, default: 0 }, + + SalesType: { + type: String, + enum: ["inStoreDelivery", "shipToCustomer"], + }, + paymentMode: { + type: String, + enum: ["QRCode", "Cash","SendPaymentLink"], + }, + payment_status: { + type: String, + enum: ["pending", "success", "failed"], + }, + isPaid: { + type: Boolean, + default: false, + }, + paidAt: { + type: Date, + }, + + orderStatus: { + type: String, + enum: [ + "new", + "processing", + "dispatched", + "delivered", + "cancelled", + "returned", + ], + default: "new", + }, + razorpay_payment_id: { type: String }, + razorpay_order_id: { type: String }, + razorpay_signature: { type: String }, + isDelivered: { type: Boolean, required: true, default: false }, + DeliveredDate: { type: String, default: "" }, + + // deliveredAt: { type: Date }, + status_timeline: { + new: { type: Date }, + processing: { type: Date }, + dispatched: { type: Date }, + delivered: { type: Date }, + cancelled: { type: Date }, + returned: { type: Date }, + }, + iscancelled: { + type: Boolean, + default: false, + }, + order_Cancelled_Reason: { + type: String, + }, + courier_name: { type: String }, + courier_tracking_id: { type: String }, + }, + { timestamps: true } +); + +export const POSOrder = mongoose.model("POSOrder", POSorderSchema); diff --git a/resources/PosOrders/PosorderRoute.js b/resources/PosOrders/PosorderRoute.js new file mode 100644 index 0000000..65dace4 --- /dev/null +++ b/resources/PosOrders/PosorderRoute.js @@ -0,0 +1,51 @@ +import bodyParser from "body-parser"; +import { + deleteOneOrder, + getAllOrder, + getOrders, + getSingleOrder, + getUserSelf, + updateOrderStatusById, +} from "./PosorderController.js"; +import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; +import express from "express"; +import { + createOrderCheckout, +} from "./PosCheckoutController.js"; +import { checkout, getRzpKey, paymentVerification } from "./PosRazerPayCheckoutController.js"; + +const app = express(); + +// Configure bodyParser to parse the raw request body as a buffer +app.use(bodyParser.raw({ type: "application/json" })); + + +const router = express.Router(); +//checkout Routes-------------------------// +router.route("/pos-checkout/").post(isAuthenticatedUser, createOrderCheckout); +// --------------------------------------------------- + +// -------------------------------------------------- +//get user self +router.route("/user/self").get(isAuthenticatedUser, getUserSelf); + +//admin route +router + .route("/pos-getAll/:status") + .get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder); +router + .route("/pos-getAll/") + .get(isAuthenticatedUser, authorizeRoles("admin"), getOrders); +router.route("/pos-getOne/:id").get(isAuthenticatedUser, getSingleOrder); +router + .route("/pos-change/status/:id") + .patch(isAuthenticatedUser, authorizeRoles("admin"), updateOrderStatusById); + +router + .route("/pos-delete/:id") + .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteOneOrder); +//RAZERPAY checkout +router.route("/getRzpKey/:name/:email").get(isAuthenticatedUser, getRzpKey); +router.route("/Rzpcheckout/").post(isAuthenticatedUser, checkout); +router.route("/paymentverification").post(paymentVerification); +export default router; From fcf344518c1ce27a3354cb99918771b7c61c8e20 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Sun, 28 Apr 2024 11:21:28 +0530 Subject: [PATCH 2/6] point of sale order contoller --- resources/PosOrders/PosCheckoutController.js | 5 ++--- .../PosOrders/PosRazerPayCheckoutController.js | 17 +++++++++-------- resources/PosOrders/PosorderModel.js | 6 +----- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/resources/PosOrders/PosCheckoutController.js b/resources/PosOrders/PosCheckoutController.js index 8acb18e..598c743 100644 --- a/resources/PosOrders/PosCheckoutController.js +++ b/resources/PosOrders/PosCheckoutController.js @@ -23,11 +23,11 @@ const generateOrderId = async () => { export const createOrderCheckout = async (req, res) => { try { - const { address, cart, user, SalesType, paymentMode } = + const { address, cart, user, paymentMode } = req.body; // console.log(req.body) // Perform validation - if (!address || !cart || cart.length === 0 || !SalesType || !user || !paymentMode) { + if (!address || !cart || cart.length === 0 || !user || !paymentMode) { return res.status(400).json({ message: "Invalid order data" }); } @@ -71,7 +71,6 @@ export const createOrderCheckout = async (req, res) => { ...restOfShippingInfo, // Include other shipping information }, user, // Assuming you have authenticated users - SalesType, paymentMode, }); diff --git a/resources/PosOrders/PosRazerPayCheckoutController.js b/resources/PosOrders/PosRazerPayCheckoutController.js index 111fbe4..f7ae283 100644 --- a/resources/PosOrders/PosRazerPayCheckoutController.js +++ b/resources/PosOrders/PosRazerPayCheckoutController.js @@ -76,13 +76,13 @@ export const checkout = async (req, res) => { } // Extract required data from request parameters and body - const { email } = req.params; - const { address, cart, user, SalesType, paymentMode, subtotal } = req.body; + // const { email } = req.params; + const { address, cart, user, paymentMode, subtotal } = req.body; // Check for required parameters - if (!email) { - return res.status(400).send({ message: "Please enter the email" }); - } + // if (!email) { + // return res.status(400).send({ message: "Please enter the email" }); + // } if (cart.length < 1) { return res.status(400).json({ message: "Cart is empty!" }); @@ -136,7 +136,6 @@ export const checkout = async (req, res) => { ...restOfShippingInfo, }, user, - SalesType, paymentMode, razorpay_order_id: order.id, }); @@ -372,8 +371,10 @@ export const handlePayment = async (req, res) => { // Add any other key-value pairs as needed }, - success_url: `${process.env.FRONTEND_URL}/cart`, - cancel_url: `${process.env.FRONTEND_URL}/error`, + // success_url: `${process.env.FRONTEND_URL}/cart`, + sccess_url: `httphttp://localhost:5000/#/success`, + // cancel_url: `${process.env.FRONTEND_URL}/error`, + cancel_url: `http://localhost:5000/#/error`, }); // res.json({ sessionId: session.id }); diff --git a/resources/PosOrders/PosorderModel.js b/resources/PosOrders/PosorderModel.js index 5134084..2f3032d 100644 --- a/resources/PosOrders/PosorderModel.js +++ b/resources/PosOrders/PosorderModel.js @@ -102,13 +102,9 @@ const POSorderSchema = new mongoose.Schema( total_amount: { type: Number, default: 0 }, weight: { type: Number, default: 0 }, - SalesType: { - type: String, - enum: ["inStoreDelivery", "shipToCustomer"], - }, paymentMode: { type: String, - enum: ["QRCode", "Cash","SendPaymentLink"], + enum: ["QRCode", "Cash"], }, payment_status: { type: String, From 6dc55eeb2867537225ebf5ef3eb2c59ecc25bc68 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Sun, 28 Apr 2024 17:19:13 +0530 Subject: [PATCH 3/6] point of sale order contoller with razorpay completed --- resources/Orders/PosCheckoutController.js | 186 ++++++ .../Orders/RazerPayCheckoutController.js | 209 ++++++- resources/Orders/orderModel.js | 6 +- resources/Orders/orderRoute.js | 8 +- resources/PosOrders/PosCheckoutController.js | 84 --- .../PosRazerPayCheckoutController.js | 482 --------------- resources/PosOrders/PosorderController.js | 552 ------------------ resources/PosOrders/PosorderModel.js | 161 ----- resources/PosOrders/PosorderRoute.js | 51 -- 9 files changed, 402 insertions(+), 1337 deletions(-) create mode 100644 resources/Orders/PosCheckoutController.js delete mode 100644 resources/PosOrders/PosCheckoutController.js delete mode 100644 resources/PosOrders/PosRazerPayCheckoutController.js delete mode 100644 resources/PosOrders/PosorderController.js delete mode 100644 resources/PosOrders/PosorderModel.js delete mode 100644 resources/PosOrders/PosorderRoute.js diff --git a/resources/Orders/PosCheckoutController.js b/resources/Orders/PosCheckoutController.js new file mode 100644 index 0000000..7792e1f --- /dev/null +++ b/resources/Orders/PosCheckoutController.js @@ -0,0 +1,186 @@ +import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; +import { Order } from "./orderModel.js"; + +//generate unique order id +const generateUniqueOrderId = async () => { + const currentYear = new Date().getFullYear(); + // Find the latest order to get the last serial number + const latestOrder = await Order.findOne({}, {}, { sort: { orderID: -1 } }); + let serialNumber = 1; + + if (latestOrder) { + const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); + if (lastYear === currentYear) { + // If the last order was in the current year, increment the serial number + serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; + } + } + // Pad the serial number with zeros and concatenate with the current year + const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); + const orderId = `${currentYear}${paddedSerialNumber}`; + return orderId; +}; + +// export const poscreateOrderCheckout = async (req, res) => { +// try { +// const { userr,address, cart, subtotal,orderType } = req.body; +// // console.log(req.body) +// // Perform validation +// if (cart.length < 1) +// return res.status(400).json({ message: "cart is empty!" }); +// if (!address) +// return res +// .status(404) +// .json({ message: "please select shipping address!" }); +// if (!subtotal) +// return res +// .status(404) +// .json({ message: "please provide product subtotal!" }); +// if (!userr) +// return res.status(400).json({ message: "user is not defined" }); + +// // Retrieve shipping address from database +// 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, +// company_name: addss?.company_name, +// gst_number: addss?.gst_number, +// addressId: address, +// }; + +// // Construct order items array +// 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: 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), +// })); + +// // Generate a unique order ID +// const Id = await generateUniqueOrderId(); + +// // Create the order document +// const order = await Order.create({ +// orderID: Id, +// total_amount: subtotal, +// orderItems, +// shippingInfo: shipping, +// user: userr, +// orderType, +// paymentMode:"cod", +// payment_status:"success", +// isPaid:true, +// paidAt:new Date().toISOString(), +// }); + +// return res.status(201).json({ success: true, order }); +// } catch (error) { +// console.error("Error creating order:", error); +// return res +// .status(500) +// .json({ success: false, message: "Internal server error" }); +// } +// }; + +export const poscreateOrderCheckout = async (req, res) => { + try { + const { userr, address, cart, subtotal, orderType } = req.body; + + // Perform validation + if (cart.length < 1) + return res.status(400).json({ message: "Cart is empty!" }); + if (!address) + return res.status(404).json({ message: "Please select a shipping address!" }); + if (!subtotal) + return res.status(404).json({ message: "Please provide the product subtotal!" }); + if (!userr) + return res.status(400).json({ message: "User is not defined" }); + + // Retrieve shipping address from database + 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, + company_name: addss?.company_name, + gst_number: addss?.gst_number, + addressId: address, + }; + + // Construct order items array + const orderItems = 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: 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), + })); + + // Generate a unique order ID + const Id = await generateUniqueOrderId(); + + // Create the order document + const order = await Order.create({ + orderID: Id, + total_amount: subtotal, + orderItems, + shippingInfo: shipping, + user: userr, + orderType, + paymentMode: "cod", + payment_status: "success", + isPaid: true, + paidAt: new Date().toISOString(), + }); + + return res.status(201).json({ success: true, order }); + } catch (error) { + console.error("Error creating order:", error); + return res.status(500).json({ success: false, message: "Internal server error" }); + } +}; diff --git a/resources/Orders/RazerPayCheckoutController.js b/resources/Orders/RazerPayCheckoutController.js index 5211a0e..7af902c 100644 --- a/resources/Orders/RazerPayCheckoutController.js +++ b/resources/Orders/RazerPayCheckoutController.js @@ -31,6 +31,8 @@ const generateUniqueOrderId = async () => { export const getRzpkey = async (req, res) => { const { name, email } = req.user; + // console.log(name); + // console.log(email); res.status(200).json({ success: true, key: process.env.RAZERPAY_KEY_ID, @@ -38,9 +40,35 @@ export const getRzpkey = async (req, res) => { email, }); }; +//point of sale order +export const getRazerpayKey = async (req, res) => { + try { + const { name, email } = req.params; + // console.log("name", name, "email", email); + if (!name || !email) { + throw new Error("Name and email are required parameters"); + } + res.status(200).json({ + success: true, + key: process.env.RAZERPAY_KEY_ID, + name, + email, + }); + } catch (error) { + console.error("Error in getRzpKey:", error); + res + .status(500) + .json({ + success: false, + message: error.message || "Internal server error", + }); + } +}; + export const checkout = async (req, res) => { try { - const { address, cart, subtotal } = req.body; + const { userr,address, cart, subtotal,orderType } = req.body; +// console.log(req.body); if (cart.length < 1) return res.status(400).json({ message: "cart is empty!" }); if (!address) @@ -55,12 +83,21 @@ export const checkout = async (req, res) => { amount: Number(req.body.subtotal * 100), currency: "INR", }; + // Determine the user ID + let User; + if (userr) { + User = userr; // Use provided user ID + } else { + User = req.user._id; // Use authenticated user ID + } + // console.log(User); const order = await instance.orders.create(options); + // console.log(order); //save order in database if (order?.id) { - const { email } = req.user; - if (!email) - return res.status(400).send({ message: "Please enter the email" }); + // const { email } = req.user; + // if (!email) + // return res.status(400).send({ message: "Please enter the email" }); let addss = await shippingAddress.findById(address); let shipping = { @@ -115,8 +152,9 @@ export const checkout = async (req, res) => { total_amount: subtotal, orderItems, shippingInfo: shipping, - user: req.user._id, + user: User, razorpay_order_id: order?.id, + orderType, }); } else { return res.status(400).json({ @@ -300,6 +338,167 @@ export const paymentVerification = async (req, res) => { }); } }; + +// point of sale payment varification +export const pospaymentVerification = async (req, res) => { + const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = + req.body; + + const body = razorpay_order_id + "|" + razorpay_payment_id; + + const expectedSignature = crypto + .createHmac("sha256", process.env.RAZERPAY_SECRET_KEY) + .update(body.toString()) + .digest("hex"); + + const isAuthentic = expectedSignature === razorpay_signature; + + if (isAuthentic) { + // Database comes here + let findSameOrder = await Order.findOne({ + razorpay_order_id: razorpay_order_id, + }).populate({ + path: "user", + select: "name email -_id", + }); + // console.log("findSameOrder", findSameOrder); + if (findSameOrder) { + (findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({ + (findSameOrder.isPaid = true), + (findSameOrder.paidAt = Date.now()), + (findSameOrder.razorpay_signature = razorpay_signature); + // await Payment.create({ + findSameOrder.payment_status = "success"; + + findSameOrder.orderStatus = "new"; + await findSameOrder.save(); + } + //send email to customer + // console.log("findSameOrder", findSameOrder); + await sendEmail({ + to: `${findSameOrder?.user?.email}`, // Change to your recipient + + from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender + + subject: `Your Order #${findSameOrder?.orderID} Confirmation`, + html: `

Welcome to Smellika - Let the Shopping Begin!

+ Hi ${ + findSameOrder?.shippingInfo?.first_Name + }, + +

Great news! Your order #${ + findSameOrder?.orderID + } has been confirmed. Here are the details

+

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} + ${ + findSameOrder?.shippingInfo?.company_name + ? ",Company Name :" + findSameOrder?.shippingInfo?.company_name + "" + : "" + } ${ + findSameOrder?.shippingInfo?.gst_number + ? ", GST_NO:" + findSameOrder?.shippingInfo?.gst_number + : "" + }

+

Order Items :

+ + + + + + + + + + + + + + + + + + + + ${findSameOrder?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameVariantImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${ + product?.variant_Name + }${
+          product.name
+        }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product?.product_Subtotal + }
Total Amount :₹${ + findSameOrder?.total_amount + }
+ +
+ Best regards,
+ + Team Smellika`, + }); + // console.log("findSameOrder", findSameOrder); + + // // findSameOrder.razorpay_payment_id=razorpay_payment_id,// await Payment.create({ + // findOrder.paidAt = new Date(event.data.object.created * 1000); + // findOrder.isPaid = true; + + // razorpay_signature: { type: String }, + // razorpay_order_id, + // razorpay_payment_id, + // razorpay_signature, + // }); + + res.redirect(`https://admin.smellika.com/#/pos`); + // res.redirect(`http://localhost:3000/#/pos`); + } else { + res.status(400).json({ + success: false, + }); + } +}; + export const handlePayment = async (req, res) => { try { const { email } = req.user; diff --git a/resources/Orders/orderModel.js b/resources/Orders/orderModel.js index 1d7a78c..f40d843 100644 --- a/resources/Orders/orderModel.js +++ b/resources/Orders/orderModel.js @@ -124,7 +124,11 @@ const orderSchema = new mongoose.Schema( enum: ["online", "cod"], default: "online", }, - + orderType: { + type: String, + enum: ["WebSite", "PointOfSale"], + default: "WebSite", + }, payment_status: { type: String, enum: ["pending", "success", "failed"], diff --git a/resources/Orders/orderRoute.js b/resources/Orders/orderRoute.js index 44cfa4b..3ccec85 100644 --- a/resources/Orders/orderRoute.js +++ b/resources/Orders/orderRoute.js @@ -22,12 +22,17 @@ app.use(bodyParser.raw({ type: "application/json" })); import { handlePayment, webhook } from "./StripeCheckOutController.js"; import { checkout, + getRazerpayKey, getRzpkey, paymentVerification, + pospaymentVerification, } from "./RazerPayCheckoutController.js"; +import { poscreateOrderCheckout } from "./PosCheckoutController.js"; const router = express.Router(); //checkout Routes-------------------------// router.route("/checkout/").post(isAuthenticatedUser, createOrderCheckout); +//checkout Routes-------------------------// +router.route("/pos-checkout/").post(isAuthenticatedUser, poscreateOrderCheckout); router.route("/clientid/get/").get(isAuthenticatedUser, getClientId); router.route("/:orderID/capture/payment").post(captureOrderPayment); // --------------------------------------------------- @@ -60,10 +65,11 @@ router .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteOneOrder); //RAZERPAY checkout +router.route("/getRzpKey/:name/:email").get(isAuthenticatedUser, getRazerpayKey); router.route("/getRzpKey/").get(isAuthenticatedUser, getRzpkey); router.route("/Rzpcheckout/").post(isAuthenticatedUser, checkout); router.route("/paymentverification").post(paymentVerification); - +router.route("/pos-paymentverification").post(pospaymentVerification); // router.route("/product/getAll/").get(getAllProduct) export default router; diff --git a/resources/PosOrders/PosCheckoutController.js b/resources/PosOrders/PosCheckoutController.js deleted file mode 100644 index 598c743..0000000 --- a/resources/PosOrders/PosCheckoutController.js +++ /dev/null @@ -1,84 +0,0 @@ -import { POSOrder } from "./PosorderModel.js"; -import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; - -//generate unique order id -const generateOrderId = async () => { - const currentYear = new Date().getFullYear(); - // Find the latest order to get the last serial number - const latestOrder = await POSOrder.findOne({}, {}, { sort: { orderID: -1 } }); - let serialNumber = 1; - - if (latestOrder) { - const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); - if (lastYear === currentYear) { - // If the last order was in the current year, increment the serial number - serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; - } - } - // Pad the serial number with zeros and concatenate with the current year - const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); - const orderId = `${currentYear}${paddedSerialNumber}`; - return orderId; -}; - -export const createOrderCheckout = async (req, res) => { - try { - const { address, cart, user, paymentMode } = - req.body; -// console.log(req.body) - // Perform validation - if (!address || !cart || cart.length === 0 || !user || !paymentMode) { - return res.status(400).json({ message: "Invalid order data" }); - } - - // Retrieve shipping address from database - const shippingInfo = await shippingAddress.findById(address); - if (!shippingInfo) { - return res.status(404).json({ message: "Shipping address not found" }); - } - - // Ensure that addressId is included in the shippingInfo object - const { _id: addressId, ...restOfShippingInfo } = shippingInfo.toObject(); - - // Calculate total amount based on the product_Subtotal of each product - const totalAmount = cart.reduce( - (acc, item) => acc + item.product_Subtotal, - 0 - ); - - // Construct order items array - const orderItems = cart.map((item) => ({ - product: item.product, - name: item.name, - price: item.price, - quantity: item.quantity, - product_Subtotal: item.total_amount, - gst_amount: item.gst_amount, - image: item.image, - variant_Name: item.variant_Name, - })); - - // Generate a unique order ID - const orderId = await generateOrderId(); - - // Create the order document - const order = await POSOrder.create({ - orderID: orderId, - total_amount: totalAmount, - orderItems, - shippingInfo: { - addressId: addressId, // Include the addressId - ...restOfShippingInfo, // Include other shipping information - }, - user, // Assuming you have authenticated users - paymentMode, - }); - - return res.status(201).json({ success: true, order }); - } catch (error) { - console.error("Error creating order:", error); - return res - .status(500) - .json({ success: false, message: "Internal server error" }); - } -}; diff --git a/resources/PosOrders/PosRazerPayCheckoutController.js b/resources/PosOrders/PosRazerPayCheckoutController.js deleted file mode 100644 index f7ae283..0000000 --- a/resources/PosOrders/PosRazerPayCheckoutController.js +++ /dev/null @@ -1,482 +0,0 @@ -import bodyParser from "body-parser"; -import crypto from "crypto"; -import Razorpay from "razorpay"; -import { POSOrder } from "./PosorderModel.js"; -import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; -import sendEmail from "../../Utils/sendEmail.js"; -const instance = new Razorpay({ - key_id: process.env.RAZERPAY_KEY_ID, - key_secret: process.env.RAZERPAY_SECRET_KEY, -}); - -const generateUniqueOrderId = async () => { - const currentYear = new Date().getFullYear(); - // Find the latest order to get the last serial number - const latestOrder = await POSOrder.findOne({}, {}, { sort: { orderID: -1 } }); - let serialNumber = 1; - - if (latestOrder) { - const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); - if (lastYear === currentYear) { - // If the last order was in the current year, increment the serial number - serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; - } - } - // Pad the serial number with zeros and concatenate with the current year - const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); - const orderId = `${currentYear}${paddedSerialNumber}`; - return orderId; -}; - -export const getRzpKey = async (req, res) => { - try { - const { name, email } = req.params; - console.log("name", name, "email", email); - if (!name || !email) { - throw new Error("Name and email are required parameters"); - } - res.status(200).json({ - success: true, - key: process.env.RAZERPAY_KEY_ID, - name, - email, - }); - } catch (error) { - console.error("Error in getRzpKey:", error); - res - .status(500) - .json({ - success: false, - message: error.message || "Internal server error", - }); - } -}; - -export const checkout = async (req, res) => { - try { - console.log(req.body); - const options = { - amount: Number(req.body.subtotal * 100), - currency: "INR", - }; - - console.log("options", options); - - // Wait for the order creation to complete - const order = await instance.orders.create(options); - - console.log("order", order); - - // Check if the order was created successfully - if (!order || !order.id) { - return res.status(400).json({ - success: false, - message: "Failed to create order", - }); - } - - // Extract required data from request parameters and body - // const { email } = req.params; - const { address, cart, user, paymentMode, subtotal } = req.body; - - // Check for required parameters - // if (!email) { - // return res.status(400).send({ message: "Please enter the email" }); - // } - - if (cart.length < 1) { - return res.status(400).json({ message: "Cart is empty!" }); - } - - if (!address) { - return res - .status(404) - .json({ message: "Please select a shipping address!" }); - } - - if (!subtotal) { - return res - .status(404) - .json({ message: "Please provide the product subtotal!" }); - } - - // Fetch shipping information from the database - const shippingInfo = await shippingAddress.findById(address); - if (!shippingInfo) { - return res.status(404).json({ message: "Shipping address not found" }); - } - - console.log("shippinginfo", shippingInfo); - - // Extract addressId and other shipping information - const { _id: addressId, ...restOfShippingInfo } = shippingInfo.toObject(); - - // Prepare order items - const orderItems = cart.map((item) => ({ - product: item.product, - name: item.name, - price: item.price, - quantity: item.quantity, - product_Subtotal: item.total_amount, - gst_amount: item.gst_amount, - image: item.image, - variant_Name: item.variant_Name, - })); - - // Generate a unique order ID - const orderId = await generateUniqueOrderId(); - - // Create the order in the database - const orders = await POSOrder.create({ - orderID: orderId, - total_amount: subtotal, - orderItems, - shippingInfo: { - addressId: addressId, - ...restOfShippingInfo, - }, - user, - paymentMode, - razorpay_order_id: order.id, - }); - - res.status(200).json({ - success: true, - order, - }); - } catch (error) { - console.error("Error in checkout:", error); - res - .status(500) - .json({ - success: false, - message: error.message || "Internal server error", - }); - } -}; - -export const paymentVerification = async (req, res) => { - const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = - req.body; - console.log(req.body); - const body = razorpay_order_id + "|" + razorpay_payment_id; - - const expectedSignature = crypto - .createHmac("sha256", process.env.RAZERPAY_SECRET_KEY) - .update(body.toString()) - .digest("hex"); - - const isAuthentic = expectedSignature === razorpay_signature; - - if (isAuthentic) { - // Database comes here - let findSameOrder = await POSOrder.findOne({ - razorpay_order_id: razorpay_order_id, - }).populate({ - path: "user", - select: "name email -_id", - }); - // console.log("findSameOrder", findSameOrder); - if (findSameOrder) { - (findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({ - (findSameOrder.isPaid = true), - (findSameOrder.paidAt = Date.now()), - (findSameOrder.razorpay_signature = razorpay_signature); - // await Payment.create({ - findSameOrder.payment_status = "success"; - - findSameOrder.orderStatus = "new"; - await findSameOrder.save(); - } - //send email to customer - // console.log("findSameOrder", findSameOrder); - await sendEmail({ - to: `${findSameOrder?.user?.email}`, // Change to your recipient - - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - - subject: `Your POSOrder #${findSameOrder?.orderID} Confirmation`, - html: `

Welcome to Smellika - Let the Shopping Begin!

- Hi ${ - findSameOrder?.shippingInfo?.first_Name - }, - -

Great news! Your order #${ - findSameOrder?.orderID - } has been confirmed. Here are the details

-

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}

-

POSOrder Items :

- - - - - - - - - - - - - - - - - - ${findSameOrder?.orderItems - ?.map( - (product, index) => ` - - - - - - - - - - - - - ` - ) - .join("")} - - - - - -
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ - index + 1 - }${ - product.name - }${
-          product.name
-        }${ - product.quantity - }₹${ - product.price - }₹${ - product?.gst_amount - }₹${ - product.product_Subtotal - }
Total Amount :₹${ - findSameOrder?.total_amount - }
- -
- Best regards,
- - Team Smellika`, - }); - // console.log("findSameOrder", findSameOrder); - - // // findSameOrder.razorpay_payment_id=razorpay_payment_id,// await Payment.create({ - // findOrder.paidAt = new Date(event.data.object.created * 1000); - // findOrder.isPaid = true; - - // razorpay_signature: { type: String }, - // razorpay_order_id, - // razorpay_payment_id, - // razorpay_signature, - // }); - - // res.redirect(`https://admin.smellika.com/#/pos`); - res.redirect(`http://localhost:3000/#/pos`); - } else { - res.status(400).json({ - success: false, - }); - } -}; -export const handlePayment = async (req, res) => { - try { - const { email } = req.user; - if (!email) - return res.status(400).send({ message: "Please enter the email" }); - const { address, cart, subtotal } = req.body; - if (cart.length < 1) - return res.status(400).json({ message: "cart is empty!" }); - switch (true) { - //validation - case !address: { - return res.status(404).json({ msg: "please provide shipping address" }); - } - case !subtotal: { - return res.status(404).json({ msg: "please provide product subtotal" }); - } - } - let addss = await shippingAddress.findById(address); - // console.log(addss?.postalCode); - 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 orderItems = await cart.map((item) => ({ - product: item.product._id, - name: item.product.name, - price: item.product.total_amount, - image: item.product.image, - quantity: item.quantity, - product_Subtotal: item.subtotal, - })); - - // console.log("line", lineItems[0]); - const Id = await generateUniqueOrderId(); - const order = await POSOrder.create({ - orderID: Id, - total_amount: subtotal, - orderItems, - shippingInfo: shipping, - user: req.user._id, - }); - console.log("fffffffff", order, "llllllllll"); - const lineItems = await cart.map((item) => ({ - price_data: { - currency: "inr", - product_data: { - name: item.product.name, - - images: [item.product.image[0]?.url], - }, - unit_amount: Number(item.product.total_amount) * 100, - }, - quantity: Number(item.quantity), - })); - if (order) { - const session = await stripe.checkout.sessions.create({ - payment_method_types: ["card"], - line_items: lineItems, - mode: "payment", - customer_email: `${email}`, - metadata: { - orderId: order._id.toString(), - - // Add any other key-value pairs as needed - }, - // success_url: `${process.env.FRONTEND_URL}/cart`, - sccess_url: `httphttp://localhost:5000/#/success`, - // cancel_url: `${process.env.FRONTEND_URL}/error`, - cancel_url: `http://localhost:5000/#/error`, - }); - // res.json({ sessionId: session.id }); - - res.status(200).send({ message: "order created", url: session.url }); - } - } catch (err) { - console.log(err); - res.status(500).send({ message: "Something went wrong", err }); - } -}; - -export const webhook = async (req, res) => { - const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; - const signature = req.headers["stripe-signature"]; - let event; - if (webhookSecret) { - try { - event = stripe.webhooks.constructEvent( - req.body, - signature, - webhookSecret - ); - } catch (err) { - console.log(`❌ Error message: ${err.message}`); - res.status(400).send(`Webhook Error: ${err.message}`); - return; - } - } - - if (event.type === "checkout.session.completed") { - // console.log("dddddddddddd", event.data); - const findOrder = await POSOrder.findById( - event.data.object.metadata?.orderId - ); - findOrder.paypal_payer_id = event.data.object.id; - findOrder.paidAt = new Date(event.data.object.created * 1000); - findOrder.isPaid = true; - if (event.data.object?.payment_status === "paid") { - findOrder.payment_status = "success"; - } else { - findOrder.payment_status = "failed"; - } - findOrder.orderStatus = "new"; - await findOrder.save(); - await sendEmail({ - to: `${event.data.object.customer_email}`, // Change to your recipient - - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - - subject: `Your POSOrder #${findOrder?.orderID} Confirmation`, - html: `

Welcome to Smellika - Let the Shopping Begin!

- Hi ${findOrder?.shippingInfo?.first_Name}, - -

Great news! Your order #${findOrder?.orderID} has been confirmed. Here are the details

-
- Best regards,
- - Team Smellika`, - }); - - // Items: [List of Purchased Items] - // Total Amount: [Total Amount] - // Shipping Address: [Shipping Address] - - // We'll keep you updated on the shipping progress. Thanks for choosing Smellika! - - // Best regards - // Team Smellika - console.log( - "event.data.object", - event.data.object, - "---------------------" - ); - - console.log(`💰 Payment status: ${event.data.object?.payment_status}`); - - // Saving the payment details in the database - // const payment = await Payment.create({ - // customer_email: event.data.object.customer_email, - // amount: event.data.object.amount_total / 100, - // paymentId: event.data.object.id, - // paymentStatus: event.data.object.payment_status, - // createdAt: event.data.object.created, - // }); - } - // if (event.type === "checkout.session.completed") { - // console.log("dddddddddddd", event.data); - // console.log("event.data.object", event.data.object); - // console.log(`💰 Payment status: ${event.data.object?.payment_status}`); - // payment_intent.payment_failed; - - // // Saving the payment details in the database - // // const payment = await Payment.create({ - // // customer_email: event.data.object.customer_email, - // // amount: event.data.object.amount_total / 100, - // // paymentId: event.data.object.id, - // // paymentStatus: event.data.object.payment_status, - // // createdAt: event.data.object.created, - // // }); - // } - - // Return a 200 res to acknowledge receipt of the event - res.status(200).end(); - // res.send().end(); -}; diff --git a/resources/PosOrders/PosorderController.js b/resources/PosOrders/PosorderController.js deleted file mode 100644 index 6a02741..0000000 --- a/resources/PosOrders/PosorderController.js +++ /dev/null @@ -1,552 +0,0 @@ -import sendEmail from "../../Utils/sendEmail.js"; -import { POSOrder } from "./PosorderModel.js"; - -export const getAllOrder = async (req, res) => { - try { - const { status } = req.params; - const order = await POSOrder.find({ - IsStoreDelivery: "Cash", - orderStatus: status, - }) - .populate({ - path: "user", - select: "name -_id", - }) - .populate({ - path: "shippingInfo.addressId", - }) - .sort({ updatedAt: -1 }); - if (order) { - res.status(201).json({ - success: true, - order, - message: "All POSOrder Fetched", - }); - } - } catch (error) { - res.status(500).json({ - success: false, - message: error.message ? error.message : "Something went Wrong", - }); - } -}; -export const getOrders = async (req, res) => { - try { - const order = await POSOrder.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 POSOrder Fetched", - }); - } - } catch (error) { - res.status(500).json({ - success: false, - message: error.message ? error.message : "Something went Wrong", - }); - } -}; -export const getSingleOrder = async (req, res) => { - try { - if (!req.params.id) - return res.status(400).json({ message: "please Provide POSOrder Id" }); - - const order = await POSOrder.findById(req.params.id) - .populate({ - path: "user", - select: "name email -_id", - }) - .populate({ - path: "shippingInfo.addressId", - }) - .sort({ createdAt: -1 }); - if (order) { - res.status(201).json({ - success: true, - order, - message: " POSOrder Fetched", - }); - } - } catch (error) { - res.status(500).json({ - success: false, - message: error.message ? error.message : "Something went Wrong", - }); - } -}; - -//get self User POSOrder -export const getUserSelf = async (req, res) => { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - try { - const order = await POSOrder.find({ - user: req.user?._id, - payment_status: "success", - }).sort({ createdAt: -1 }); - - if (order) { - return res.status(200).json({ - success: true, - order, - message: "self POSOrder fetched", - }); - } - } catch (error) { - res.status(500).json({ - success: false, - message: error.message ? error.message : "Something went Wrong", - }); - } -}; - -export const deleteOneOrder = async (req, res) => { - try { - if (!req?.user) return res.status(400).json({ message: "please login !" }); - if (!req.params.id) - return res.status(400).json({ message: "please Provide POSOrder Id" }); - const getOrder = await POSOrder.findById(req.params.id); - if (!getOrder) { - return res.status(404).json({ - success: false, - message: "No POSOrder Found!", - }); - } - const order = await POSOrder.findByIdAndDelete(req.params.id); - - await order.remove(); - res.status(200).json({ - success: true, - message: "POSOrder Deleted Successfully!!", - }); - } catch (error) { - res.status(500).json({ - success: false, - message: error.message ? error.message : "Something went Wrong", - }); - } -}; -export const updateOrderStatusById = async (req, res) => { - try { - let body = { orderStatus: req.body.status }; - - const currentDate = new Date(); - body["status_timeline." + req.body.status] = currentDate; - // if (req.body?.package_weight) body.package_weight = req.body.package_weight; - const order = await POSOrder.findById(req.params.id).populate({ - path: "user", - select: "name email -_id", - }); - // console.log("order", order); - // const parentData = { email: order?.parent?.email }; - if (req.body.status === "cancelled") { - body["order_Cancelled_Reason"] = req.body?.ReasonforCancellation; - body["iscancelled"] = true; - await POSOrder.findByIdAndUpdate(order._id, body); - await sendEmail({ - to: `${order?.user?.email}`, // Change to your recipient - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - subject: `POSOrder #${order?.orderID} Update: Cancellation and Refund Process`, - html: ` Hi ${ - order?.shippingInfo?.first_Name - }, -

We hope this message finds you well. We're writing to inform you that your order ${ - order?.orderID - } has been canceled. We understand that circumstances may change, and we're here to assist you throughout the process.

- - -

Items :

- - - - - - - - - - - - - - - - - - ${order?.orderItems - ?.map( - (product, index) => ` - - - - - - - - - - - - - ` - ) - .join("")} - - - - - -
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ - index + 1 - }${ - product.name - }${
-          product.name
-        }${ - product.quantity - }₹${ - product.price - }₹${ - product?.gst_amount - }₹${ - product.product_Subtotal - }
Total Amount :₹${ - order?.total_amount - }
-

Cancellation Reason : ${ - req.body?.ReasonforCancellation - }

-

Refund Information: The amount from your canceled order will be processed for a refund. Please allow up to 7 working days for the amount to be transferred back to your original payment method.

- -
If you have any concerns or further questions, please feel free to reply to this email. We appreciate your understanding and hope to serve you better in the future. -
-
- Best regards,
- - Team Smellika`, - }); - return res - .status(200) - .json({ status: "ok", message: "POSOrder status updated successfully!" }); - } else if (req.body.status === "processing") { - await POSOrder.findByIdAndUpdate(order._id, body); - - await sendEmail({ - to: `${order?.user?.email}`, // Change to your recipient - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - subject: `Your POSOrder #${order?.orderID} is in Processing!`, - html: `

Exciting news! Your order #${ - order?.orderID - } has entered the processing phase. Our team is diligently preparing your items for dispatch. Rest assured, we're working hard to ensure everything is perfect for you.

- Hi ${ - order?.shippingInfo?.first_Name - }, -

POSOrder Status : Processing

-

POSOrder Items :

- - - - - - - - - - - - - - - - - - ${order?.orderItems - ?.map( - (product, index) => ` - - - - - - - - - - - - - ` - ) - .join("")} - - - - - -
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ - index + 1 - }${ - product.name - }${
-          product.name
-        }${ - product.quantity - }₹${ - product.price - }₹${ - product?.gst_amount - }₹${ - product.product_Subtotal - }
Total Amount :₹${ - order?.total_amount - }
-
We'll send you another email with the tracking details as soon as your order is dispatched. If you have any questions or need assistance, feel free to reply to this email.
-
Thank you for choosing Smellika!
-
- Best regards,
- - Team Smellika`, - }); - return res - .status(200) - .json({ status: "ok", message: "POSOrder status updated successfully!" }); - } - // else if (body.status === "dispatched") { - // const noBalanceRemaining = - // order?.sales_items?.filter((e) => Number(e?.balance_quantity) > 0) - // ?.length === 0 - // ? true - // : false; - // if (!noBalanceRemaining) - // return res - // .status(400) - // .json({ message: "Few items still have balance quantity!" }); - // await OrderDispatchedEmail(parentData.email, order.order_id, body); - // await Invoice.updateMany( - // { order: order._id, status: { $in: ["processing"] } }, - // { status: body.status, "status_timeline.dispatched": currentDate } - // ); - // } else if (body.status === "delivered") { - // await OrderDeliveredEmail(parentData.email, order.order_id); - // await Invoice.updateMany( - // { order: order._id, status: { $in: ["processing", "dispatched"] } }, - // { status: body.status, "status_timeline.delivered": currentDate } - // ); - // } - else if (req.body.status === "dispatched") { - body["courier_name"] = req.body.courierName; - body["courier_tracking_id"] = req.body.TrackingID; - await POSOrder.findByIdAndUpdate(order._id, body); - await sendEmail({ - to: `${order?.user?.email}`, // Change to your recipient - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - subject: `Your POSOrder #${order?.orderID} is On Its Way!`, - html: ` Hi ${ - order?.shippingInfo?.first_Name - }, -

Exciting news! Your order #${ - order?.orderID - } has been dispatched and is en route to you. 🚚 Here are the details:

- -

Courier Name : ${ - req.body.courierName - }

-

Courier Tracking ID : ${ - req.body.TrackingID - }

- - -

Items :

- - - - - - - - - - - - - - - - - - ${order?.orderItems - ?.map( - (product, index) => ` - - - - - - - - - - - - - ` - ) - .join("")} - - - - - -
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ - index + 1 - }${ - product.name - }${
-          product.name
-        }${ - product.quantity - }₹${ - product.price - }₹${ - product?.gst_amount - }₹${ - product.product_Subtotal - }
Total Amount :₹${ - order?.total_amount - }
-

POSOrder Status : Dispatched

-

If you have any questions or need assistance, feel free to reply to this email. -

-
Thanks for choosing Smellika! We hope you enjoy your purchase. -
-
- Best regards,
- - Team Smellika`, - }); - return res - .status(200) - .json({ status: "ok", message: "POSOrder status updated successfully!" }); - } else if (req.body.status === "delivered") { - body["isDelivered"] = true; - body["DeliveredDate"] = req.body.DDate; - await POSOrder.findByIdAndUpdate(order._id, body); - await sendEmail({ - to: `${order?.user?.email}`, // Change to your recipient - from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender - subject: `Your POSOrder #${order?.orderID} Has Been Delivered!`, - html: ` Hi ${ - order?.shippingInfo?.first_Name - }, -

Great news! Your order #${ - order?.orderID - } has been successfully delivered to your doorstep. We hope everything is just as you expected!

-

Items :

- - - - - - - - - - - - - - - - - - ${order?.orderItems - ?.map( - (product, index) => ` - - - - - - - - - - - - - ` - ) - .join("")} - - - - - -
S No.Product NameImageQuantityPriceGST AmountSubTotal
${ - index + 1 - }${ - product.name - }${
-                product.name
-              }${ - product.quantity - }₹${ - product.price - }₹${ - product?.gst_amount - }₹${ - product.product_Subtotal - }
Total Amount :₹${ - order?.total_amount - }
-

Delivery Date: ${ - req.body.DDate - }

-

Your satisfaction is our priority, and we'd love to hear about your experience. Please take a moment to share your thoughts by leaving a review. Your feedback is invaluable to us! -

-
If you have any questions or concerns about your order, feel free to reply to this email. -
-
Thank you for choosing Smellika! We hope to serve you again soon. - -
-
- Best regards,
- - Team Smellika`, - }); - - return res - .status(200) - .json({ status: "ok", message: "POSOrder status updated successfully!" }); - } else { - // await POSOrder.findByIdAndUpdate(order._id, body); - // console.log(order); - res - .status(200) - .json({ status: "ok", message: "POSOrder status updated successfully!" }); - } - } catch (error) { - console.log(error); - res - .status(500) - .json({ message: error?.message || "Something went wrong!" }); - } -}; diff --git a/resources/PosOrders/PosorderModel.js b/resources/PosOrders/PosorderModel.js deleted file mode 100644 index 2f3032d..0000000 --- a/resources/PosOrders/PosorderModel.js +++ /dev/null @@ -1,161 +0,0 @@ -import mongoose from "mongoose"; - -const POSorderSchema = new mongoose.Schema( - { - orderID: { - type: String, - required: true, - unique: true, - }, - user: { - type: mongoose.Schema.ObjectId, - ref: "User", - required: true, - }, - shippingInfo: { - first_Name: { - type: String, - required: true, - }, - last_Name: { - type: String, - required: true, - }, - phone_Number: { - type: Number, - required: true, - }, - street: { - type: String, - required: true, - }, - city: { - type: String, - required: true, - trim: true, - }, - state: { - type: String, - required: true, - }, - postalCode: { - type: String, - required: true, - trim: true, - // Add a regular expression to enforce a specific postal code format - // For example, assuming a 5-digit format for the United States - match: /^\d{6}$/, - }, - country: { - type: String, - required: true, - }, - addressId: { - type: mongoose.Schema.ObjectId, - ref: "ShippingAddress", - required: true, - }, - }, - orderItems: [ - { - name: { - type: String, - default: "", - }, - price: { - type: Number, - default: "", - }, - variant_Name: { type: String, default: "" }, - quantity: { - type: Number, - default: "", - default: 1, - }, - image: [{}], - - product_Subtotal: { - type: Number, - default: "", - }, - gst_amount: { - type: Number, - default: "", - }, - gst_rate: { - type: Number, - default: "", - }, - tax_Name: { - type: String, - default: "", - }, - product: { - type: mongoose.Schema.ObjectId, - ref: "Product", - }, - }, - ], - - shipping_charge: { type: Number, default: 0 }, - tax_amount: { type: Number, default: 0 }, - total_amount: { type: Number, default: 0 }, - weight: { type: Number, default: 0 }, - - paymentMode: { - type: String, - enum: ["QRCode", "Cash"], - }, - payment_status: { - type: String, - enum: ["pending", "success", "failed"], - }, - isPaid: { - type: Boolean, - default: false, - }, - paidAt: { - type: Date, - }, - - orderStatus: { - type: String, - enum: [ - "new", - "processing", - "dispatched", - "delivered", - "cancelled", - "returned", - ], - default: "new", - }, - razorpay_payment_id: { type: String }, - razorpay_order_id: { type: String }, - razorpay_signature: { type: String }, - isDelivered: { type: Boolean, required: true, default: false }, - DeliveredDate: { type: String, default: "" }, - - // deliveredAt: { type: Date }, - status_timeline: { - new: { type: Date }, - processing: { type: Date }, - dispatched: { type: Date }, - delivered: { type: Date }, - cancelled: { type: Date }, - returned: { type: Date }, - }, - iscancelled: { - type: Boolean, - default: false, - }, - order_Cancelled_Reason: { - type: String, - }, - courier_name: { type: String }, - courier_tracking_id: { type: String }, - }, - { timestamps: true } -); - -export const POSOrder = mongoose.model("POSOrder", POSorderSchema); diff --git a/resources/PosOrders/PosorderRoute.js b/resources/PosOrders/PosorderRoute.js deleted file mode 100644 index 65dace4..0000000 --- a/resources/PosOrders/PosorderRoute.js +++ /dev/null @@ -1,51 +0,0 @@ -import bodyParser from "body-parser"; -import { - deleteOneOrder, - getAllOrder, - getOrders, - getSingleOrder, - getUserSelf, - updateOrderStatusById, -} from "./PosorderController.js"; -import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import express from "express"; -import { - createOrderCheckout, -} from "./PosCheckoutController.js"; -import { checkout, getRzpKey, paymentVerification } from "./PosRazerPayCheckoutController.js"; - -const app = express(); - -// Configure bodyParser to parse the raw request body as a buffer -app.use(bodyParser.raw({ type: "application/json" })); - - -const router = express.Router(); -//checkout Routes-------------------------// -router.route("/pos-checkout/").post(isAuthenticatedUser, createOrderCheckout); -// --------------------------------------------------- - -// -------------------------------------------------- -//get user self -router.route("/user/self").get(isAuthenticatedUser, getUserSelf); - -//admin route -router - .route("/pos-getAll/:status") - .get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder); -router - .route("/pos-getAll/") - .get(isAuthenticatedUser, authorizeRoles("admin"), getOrders); -router.route("/pos-getOne/:id").get(isAuthenticatedUser, getSingleOrder); -router - .route("/pos-change/status/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateOrderStatusById); - -router - .route("/pos-delete/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteOneOrder); -//RAZERPAY checkout -router.route("/getRzpKey/:name/:email").get(isAuthenticatedUser, getRzpKey); -router.route("/Rzpcheckout/").post(isAuthenticatedUser, checkout); -router.route("/paymentverification").post(paymentVerification); -export default router; From 105da2bccbd0c402af96f01cabd26dd2a2134e5a Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Mon, 29 Apr 2024 15:10:57 +0530 Subject: [PATCH 4/6] point of sale order contoller with razorpay completed and cash with mail completed --- app.js | 3 - package-lock.json | 9 +- resources/Orders/PosCheckoutController.js | 241 +++++++++++++--------- 3 files changed, 146 insertions(+), 107 deletions(-) diff --git a/app.js b/app.js index 4781cde..dec8764 100644 --- a/app.js +++ b/app.js @@ -172,7 +172,6 @@ import CouponRoute from "./resources/Affiliate&Coupon/Coupon/CouponRoute.js"; //support Ticket import SupportRouter from "./resources/Supports/supportRoute.js"; // Point of Sale -import PosorderRoute from "./resources/PosOrders/PosorderRoute.js"; app.use("/api/v1/", user); //Product @@ -240,6 +239,4 @@ app.use("/api/panel", PanelRoute); // app.use("/api/shorturl", ShortUrlRouter); //Support app.use("/api", SupportRouter); -// Point of Sale -app.use("/api/posOrder", PosorderRoute); export default app; diff --git a/package-lock.json b/package-lock.json index 9bafc1a..a1f5970 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5417,7 +5417,8 @@ "cloudinary-core": { "version": "2.12.3", "resolved": "https://registry.npmjs.org/cloudinary-core/-/cloudinary-core-2.12.3.tgz", - "integrity": "sha512-Ll4eDzcrIVn4zCttMh3Mdi+KNz07p5EEjBT2PQSRx8Eok1lKPt3uBBenOk/w88RKK3B8SFIWcEe/mN4BHQ0p8A==" + "integrity": "sha512-Ll4eDzcrIVn4zCttMh3Mdi+KNz07p5EEjBT2PQSRx8Eok1lKPt3uBBenOk/w88RKK3B8SFIWcEe/mN4BHQ0p8A==", + "requires": {} }, "color-convert": { "version": "2.0.1", @@ -6660,7 +6661,8 @@ "multer-storage-cloudinary": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/multer-storage-cloudinary/-/multer-storage-cloudinary-4.0.0.tgz", - "integrity": "sha512-25lm9R6o5dWrHLqLvygNX+kBOxprzpmZdnVKH4+r68WcfCt8XV6xfQaMuAg+kUE5Xmr8mJNA4gE0AcBj9FJyWA==" + "integrity": "sha512-25lm9R6o5dWrHLqLvygNX+kBOxprzpmZdnVKH4+r68WcfCt8XV6xfQaMuAg+kUE5Xmr8mJNA4gE0AcBj9FJyWA==", + "requires": {} }, "mute-stream": { "version": "0.0.8", @@ -7893,7 +7895,8 @@ "ws": { "version": "7.4.6", "resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz", - "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==" + "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==", + "requires": {} }, "xregexp": { "version": "2.0.0", diff --git a/resources/Orders/PosCheckoutController.js b/resources/Orders/PosCheckoutController.js index 7792e1f..ee069ad 100644 --- a/resources/Orders/PosCheckoutController.js +++ b/resources/Orders/PosCheckoutController.js @@ -1,6 +1,7 @@ import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; import { Order } from "./orderModel.js"; +import sendEmail from "../../Utils/sendEmail.js"; //generate unique order id const generateUniqueOrderId = async () => { const currentYear = new Date().getFullYear(); @@ -21,99 +22,6 @@ const generateUniqueOrderId = async () => { return orderId; }; -// export const poscreateOrderCheckout = async (req, res) => { -// try { -// const { userr,address, cart, subtotal,orderType } = req.body; -// // console.log(req.body) -// // Perform validation -// if (cart.length < 1) -// return res.status(400).json({ message: "cart is empty!" }); -// if (!address) -// return res -// .status(404) -// .json({ message: "please select shipping address!" }); -// if (!subtotal) -// return res -// .status(404) -// .json({ message: "please provide product subtotal!" }); -// if (!userr) -// return res.status(400).json({ message: "user is not defined" }); - -// // Retrieve shipping address from database -// 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, -// company_name: addss?.company_name, -// gst_number: addss?.gst_number, -// addressId: address, -// }; - -// // Construct order items array -// 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: 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), -// })); - -// // Generate a unique order ID -// const Id = await generateUniqueOrderId(); - -// // Create the order document -// const order = await Order.create({ -// orderID: Id, -// total_amount: subtotal, -// orderItems, -// shippingInfo: shipping, -// user: userr, -// orderType, -// paymentMode:"cod", -// payment_status:"success", -// isPaid:true, -// paidAt:new Date().toISOString(), -// }); - -// return res.status(201).json({ success: true, order }); -// } catch (error) { -// console.error("Error creating order:", error); -// return res -// .status(500) -// .json({ success: false, message: "Internal server error" }); -// } -// }; - export const poscreateOrderCheckout = async (req, res) => { try { const { userr, address, cart, subtotal, orderType } = req.body; @@ -122,11 +30,14 @@ export const poscreateOrderCheckout = async (req, res) => { if (cart.length < 1) return res.status(400).json({ message: "Cart is empty!" }); if (!address) - return res.status(404).json({ message: "Please select a shipping address!" }); + return res + .status(404) + .json({ message: "Please select a shipping address!" }); if (!subtotal) - return res.status(404).json({ message: "Please provide the product subtotal!" }); - if (!userr) - return res.status(400).json({ message: "User is not defined" }); + return res + .status(404) + .json({ message: "Please provide the product subtotal!" }); + if (!userr) return res.status(400).json({ message: "User is not defined" }); // Retrieve shipping address from database let addss = await shippingAddress.findById(address); @@ -154,11 +65,24 @@ export const poscreateOrderCheckout = async (req, res) => { total_price: item.quantity * Number(item.variant.price), 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_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), + 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), })); // Generate a unique order ID @@ -177,10 +101,125 @@ export const poscreateOrderCheckout = async (req, res) => { isPaid: true, paidAt: new Date().toISOString(), }); + // console.log(order); + // Find the user associated with the order + const orderWithUser = await Order.findById(order._id).populate("user"); + + if (!orderWithUser) { + return res + .status(404) + .json({ success: false, message: "Order not found" }); + } + + const user = orderWithUser.user; + const userEmail = user.email; + + // Send email after order creation + await sendEmail({ + to: userEmail, + from: `${process.env.SEND_EMAIL_FROM}`, + subject: `Your Order #${order?.orderID} Confirmation`, + html: `

Welcome to Smellika - Let the Shopping Begin!

+ Hi ${ + order?.shippingInfo?.first_Name + }, + +

Great news! Your order #${ + order?.orderID + } has been confirmed. Here are the details

+

Shipping Address : ${ + order?.shippingInfo?.first_Name + } ${order?.shippingInfo?.last_Name} , ${order?.shippingInfo?.street} ${ + order?.shippingInfo?.city + } ${order?.shippingInfo?.state} ${order?.shippingInfo?.country}, PIN-${ + order?.shippingInfo?.postalCode + }, Phone Number: ${order?.shippingInfo?.phone_Number} + ${ + order?.shippingInfo?.company_name + ? ",Company Name :" + order?.shippingInfo?.company_name + "" + : "" + } ${ + order?.shippingInfo?.gst_number + ? ", GST_NO:" + order?.shippingInfo?.gst_number + : "" + }

+

Order Items :

+ + + + + + + + + + + + + + + + + + + + ${order?.orderItems + ?.map( + (product, index) => ` + + + + + + + + + + + + + + ` + ) + .join("")} + + + + + +
S No.Product NameVariantImageQuantityPriceGST AmountSubTotal
${ + index + 1 + }${ + product.name + }${ + product?.variant_Name + }${
+         product.name
+       }${ + product.quantity + }₹${ + product.price + }₹${ + product?.gst_amount + }₹${ + product?.product_Subtotal + }
Total Amount :₹${ + order?.total_amount + }
+ +
+ Best regards,
+ + Team Smellika`, + }); return res.status(201).json({ success: true, order }); } catch (error) { console.error("Error creating order:", error); - return res.status(500).json({ success: false, message: "Internal server error" }); + return res + .status(500) + .json({ success: false, message: "Internal server error" }); } }; From 00e6d2227a8bbed8ada2616a1ecdafdaa6f35b6c Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Tue, 30 Apr 2024 17:13:33 +0530 Subject: [PATCH 5/6] point of sale order contoller with razorpay completed and cash with mail completed --- resources/Orders/RazerPayCheckoutController.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/resources/Orders/RazerPayCheckoutController.js b/resources/Orders/RazerPayCheckoutController.js index 7af902c..688e633 100644 --- a/resources/Orders/RazerPayCheckoutController.js +++ b/resources/Orders/RazerPayCheckoutController.js @@ -68,7 +68,8 @@ export const getRazerpayKey = async (req, res) => { export const checkout = async (req, res) => { try { const { userr,address, cart, subtotal,orderType } = req.body; -// console.log(req.body); +// console.log(req.body.cart[0].product); +// console.log(req.body.cart[0].variant); if (cart.length < 1) return res.status(400).json({ message: "cart is empty!" }); if (!address) @@ -145,7 +146,7 @@ export const checkout = async (req, res) => { ).toFixed(3), })); - // console.log("line", lineItems[0]); + // console.log("Order", orderItems[0]); const Id = await generateUniqueOrderId(); const orders = await Order.create({ orderID: Id, From 19158424a4c1337c200bc13696ede1435b19664f Mon Sep 17 00:00:00 2001 From: roshangarg28 Date: Fri, 3 May 2024 10:31:21 +0530 Subject: [PATCH 6/6] updated Employee and Access features --- Utils/jwtToken.js | 1 + app.js | 7 +- middlewares/auth.js | 1 + .../Affiliate/AffiliateRoute.js | 16 +-- .../Affiliate&Coupon/Coupon/CouponRoute.js | 14 +-- resources/Banner/BannerRouter.js | 14 ++- resources/Blog/BlogRoute.js | 27 +++-- resources/Category/categoryRoutes.js | 14 ++- resources/Content/ContentRoutes.js | 46 ++++++-- resources/Departure/DepartureRoute.js | 20 ++-- resources/Design/designRouter.js | 20 +++- .../RegisterEmail/RegisterEmailRoutes.js | 21 ++++ .../RegisterEmail/registerEmailController.js | 64 +++++++++++ .../RegisterEmail/registerEmailModal.js | 26 +++++ resources/Informations/InformationRoute.js | 33 ++++-- resources/LoginImage/LoginImageRoute.js | 23 ++-- resources/Orders/orderRoute.js | 16 ++- resources/Panels/PanelRoutes.js | 98 +++++++++------- resources/Products/ProductRoute.js | 26 ++++- .../RegistrationImageRoute.js | 23 ++-- resources/SEO&Analytics/SEORouter.js | 7 +- .../ShippingAddresses/ShippingAddressRoute.js | 4 +- resources/ShopPageImage/ShopPageImageRoute.js | 23 ++-- resources/Supports/supportRoute.js | 38 +++++-- resources/Tax/tax_routes.js | 12 +- resources/Temple/FranchiseeRoute.js | 106 +++++++++++------- resources/Testimonials/TestimonialRoute.js | 22 ++-- .../setting/Configration/Config_routes.js | 61 +++++++--- resources/user/userController.js | 105 ++++++++++++++++- resources/user/userModel.js | 1 + resources/user/userRoute.js | 34 +++++- resources/userAddress/useAddressRoute.js | 18 ++- 32 files changed, 704 insertions(+), 237 deletions(-) create mode 100644 resources/EmailCMS/RegisterEmail/RegisterEmailRoutes.js create mode 100644 resources/EmailCMS/RegisterEmail/registerEmailController.js create mode 100644 resources/EmailCMS/RegisterEmail/registerEmailModal.js diff --git a/Utils/jwtToken.js b/Utils/jwtToken.js index 9ac872c..4193dec 100644 --- a/Utils/jwtToken.js +++ b/Utils/jwtToken.js @@ -16,6 +16,7 @@ const sendToken = (user, statusCode, res) => { success: true, userId: user._id, + // userName: user.name, // userEmail: user.email, // userPhone: user.phone, diff --git a/app.js b/app.js index 6adea88..d19082f 100644 --- a/app.js +++ b/app.js @@ -164,13 +164,14 @@ import AffiliateRoute from "./resources/Affiliate&Coupon/Affiliate/AffiliateRout //Blog Routes import BlogRoute from "./resources/Blog/BlogRoute.js"; // Panel Routes -import PanelRoute from "./resources/Panels/PanelRoutes.js" +import PanelRoute from "./resources/Panels/PanelRoutes.js"; //Coupon Routes import CouponRoute from "./resources/Affiliate&Coupon/Coupon/CouponRoute.js"; //short urls // import ShortUrlRouter from "./resources/Businesses/Short_Urls/ShortUrlRoute.js"; //support Ticket import SupportRouter from "./resources/Supports/supportRoute.js"; +import RegisterEmail from "./resources/EmailCMS/RegisterEmail/RegisterEmailRoutes.js"; app.use("/api/v1/", user); //Product @@ -227,7 +228,6 @@ app.use("/api/v1/blog", BlogRoute); // panels app.use("/api/panel", PanelRoute); - //config specialty // app.use("/api/config/specialty", SpecialtiesRouter); //specialties @@ -237,5 +237,8 @@ app.use("/api/panel", PanelRoute); //short urls // app.use("/api/shorturl", ShortUrlRouter); //Support + +// Email CMS +app.use("/api", RegisterEmail); app.use("/api", SupportRouter); export default app; diff --git a/middlewares/auth.js b/middlewares/auth.js index 20df498..f2e83d3 100644 --- a/middlewares/auth.js +++ b/middlewares/auth.js @@ -110,6 +110,7 @@ export const isFranchiAuthenticated = async (req, res, next) => { // }; export const authorizeRoles = (...roles) => { + console.log("this is the roles ", roles); //pass admin return (req, res, next) => { if (!roles.includes(req.user.role)) { diff --git a/resources/Affiliate&Coupon/Affiliate/AffiliateRoute.js b/resources/Affiliate&Coupon/Affiliate/AffiliateRoute.js index ccf9b66..e2570d1 100644 --- a/resources/Affiliate&Coupon/Affiliate/AffiliateRoute.js +++ b/resources/Affiliate&Coupon/Affiliate/AffiliateRoute.js @@ -20,49 +20,49 @@ const router = express.Router(); router.post( "/create", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), createAffiliate ); router.get( "/getall", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), listAllAffiliate ); router.get( "/getone/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), getOneAffiliate ); router.patch( "/edit/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), editAffiliate ); router.patch( "/suspend", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), suspendAffiliate ); router.post( "/pay/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), payAffiliate ); router.get( "/getpay/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), getOneAffiliateForPay ); router.get( "/history/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), affiliatePayHistory ); diff --git a/resources/Affiliate&Coupon/Coupon/CouponRoute.js b/resources/Affiliate&Coupon/Coupon/CouponRoute.js index bead939..3c15d0a 100644 --- a/resources/Affiliate&Coupon/Coupon/CouponRoute.js +++ b/resources/Affiliate&Coupon/Coupon/CouponRoute.js @@ -20,38 +20,38 @@ const router = express.Router(); router.get( "/getall", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), listAllCoupon ); router.patch( "/create", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), createCoupon ); router.get( "/getaffiliate", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), listAffiliateCoupon ); router.patch( "/edit/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), editCoupon ); router.get( "/getone/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), getOneCoupon ); router.get("/validcoupon/:coupon", validateCoupon); router.patch( "/suspend", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), suspendCoupon ); router.patch( @@ -69,7 +69,7 @@ router.patch( router.get( "/history/:id", isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), couponPayHistory ); diff --git a/resources/Banner/BannerRouter.js b/resources/Banner/BannerRouter.js index cf8d904..5d61bb0 100644 --- a/resources/Banner/BannerRouter.js +++ b/resources/Banner/BannerRouter.js @@ -11,13 +11,21 @@ const router = express.Router(); router .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addBanner); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addBanner); router.route("/getBanners").get(getBanner); router .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateBanner); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateBanner + ); router .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteBanner); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteBanner + ); export default router; diff --git a/resources/Blog/BlogRoute.js b/resources/Blog/BlogRoute.js index 9efaddc..fcb1b34 100644 --- a/resources/Blog/BlogRoute.js +++ b/resources/Blog/BlogRoute.js @@ -1,30 +1,33 @@ import express from "express"; -import { createBlog, getAllBlog, getOneBlog, deleteBlog, deleteImageFromCloudinary, updateBlog } from "./BlogController.js"; +import { + createBlog, + getAllBlog, + getOneBlog, + deleteBlog, + deleteImageFromCloudinary, + updateBlog, +} from "./BlogController.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; const router = express.Router(); router .route("/create") - .post(isAuthenticatedUser, authorizeRoles("admin"), createBlog); -router - .route("/getallblog") - .get(getAllBlog); -router - .route("/getoneblog/:id") - .get(getOneBlog); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), createBlog); +router.route("/getallblog").get(getAllBlog); +router.route("/getoneblog/:id").get(getOneBlog); router .route("/deleteblog/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteBlog); + .delete(isAuthenticatedUser, authorizeRoles("admin", "Employee"), deleteBlog); router .route("/deleteImage/jatinMor/Blog/:public_id") .delete( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), deleteImageFromCloudinary ); - router +router .route("/updateblog/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateBlog); + .patch(isAuthenticatedUser, authorizeRoles("admin", "Employee"), updateBlog); export default router; diff --git a/resources/Category/categoryRoutes.js b/resources/Category/categoryRoutes.js index f8d6068..66c8cc5 100644 --- a/resources/Category/categoryRoutes.js +++ b/resources/Category/categoryRoutes.js @@ -10,13 +10,21 @@ const router = express.Router(); router .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addCategory); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addCategory); router.route("/getCategories").get(getCategories); router .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateCategory); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateCategory + ); router .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteCategory); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteCategory + ); export default router; diff --git a/resources/Content/ContentRoutes.js b/resources/Content/ContentRoutes.js index 71146c0..8da5e11 100644 --- a/resources/Content/ContentRoutes.js +++ b/resources/Content/ContentRoutes.js @@ -14,7 +14,7 @@ import { updateRefundPolicy, AddAboutUs, getAboutUs, - updateAboutUs + updateAboutUs, } from "./ContentController.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; @@ -22,45 +22,69 @@ const router = express.Router(); router .route("/terms-and-conditions") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddTermsAndConditions); + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + AddTermsAndConditions + ); router.route("/terms-and-conditions").get(getTermsAndCondition); router .route("/terms-and-condition-update") .patch( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), updateTermsAndConditions ); router .route("/privacy-and-policy") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddPrivacyAndPolicy); + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + AddPrivacyAndPolicy + ); router.route("/privacy-and-policy").get(getPrivacyPolicy); router .route("/privacy-and-policy-update") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatePrivacyPolicy); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatePrivacyPolicy + ); router .route("/shipping-and-policy") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddShipping); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddShipping); router.route("/shipping-and-policy").get(getShipping); router .route("/shipping-and-policy-update") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateShipping); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateShipping + ); //refund Policy router.route("/refund-policy").get(getRefundPolicy); router .route("/refund-policy") - .post(isAuthenticatedUser, authorizeRoles("admin"), RefundPolicy); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), RefundPolicy); router .route("/refund-policy-update") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateRefundPolicy); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateRefundPolicy + ); //about us router .route("/about-us") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddAboutUs); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddAboutUs); router.route("/about-us").get(getAboutUs); router .route("/about-us-update") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateAboutUs); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateAboutUs + ); export default router; diff --git a/resources/Departure/DepartureRoute.js b/resources/Departure/DepartureRoute.js index 199155e..acb096f 100644 --- a/resources/Departure/DepartureRoute.js +++ b/resources/Departure/DepartureRoute.js @@ -1,18 +1,16 @@ - -import express from 'express' +import express from "express"; import { AddNewFlight, FindAllFlight } from "./DepartureController.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -const router = express.Router() - -router.route("/flight/new").post(isAuthenticatedUser, authorizeRoles("admin"), AddNewFlight) -router.route("/flight/getAll").get(isAuthenticatedUser, authorizeRoles("admin"), FindAllFlight) - - - - +const router = express.Router(); +router + .route("/flight/new") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddNewFlight); +router + .route("/flight/getAll") + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), FindAllFlight); // router.route("/product/getAll/").get(getAllProduct) -export default router \ No newline at end of file +export default router; diff --git a/resources/Design/designRouter.js b/resources/Design/designRouter.js index 6e65b6b..4eba34f 100644 --- a/resources/Design/designRouter.js +++ b/resources/Design/designRouter.js @@ -11,14 +11,14 @@ // router // .route("/add") -// .post(isAuthenticatedUser, authorizeRoles("admin"), addDesign); +// .post(isAuthenticatedUser,authorizeRoles("admin", "Employee"), addDesign); // router.route("/getDesigns").get(getDesign); // router // .route("/update/:_id") -// .patch(isAuthenticatedUser, authorizeRoles("admin"), updateDesign); +// .patch(isAuthenticatedUser,authorizeRoles("admin", "Employee"), updateDesign); // router // .route("/delete/:_id") -// .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteDesign); +// .delete(isAuthenticatedUser,authorizeRoles("admin", "Employee"), deleteDesign); // export default router; import express from "express"; @@ -61,13 +61,21 @@ const imageStorage = multer.diskStorage({ router .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addDesign); + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addDesign); router.route("/getDesigns").get(getDesign); router .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateDesign); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateDesign + ); router .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteDesign); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteDesign + ); export default router; diff --git a/resources/EmailCMS/RegisterEmail/RegisterEmailRoutes.js b/resources/EmailCMS/RegisterEmail/RegisterEmailRoutes.js new file mode 100644 index 0000000..b2270c9 --- /dev/null +++ b/resources/EmailCMS/RegisterEmail/RegisterEmailRoutes.js @@ -0,0 +1,21 @@ +import { + authorizeRoles, + isAuthenticatedUser, +} from "../../../middlewares/auth.js"; +import { + GetRegisterEamilData, + RegisterEmailSend, +} from "./registerEmailController.js"; +import express from "express"; +const router = express.Router(); + +router + .route("/register-email") + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + RegisterEmailSend + ); +router.route("/get-email-data").get(GetRegisterEamilData); + +export default router; diff --git a/resources/EmailCMS/RegisterEmail/registerEmailController.js b/resources/EmailCMS/RegisterEmail/registerEmailController.js new file mode 100644 index 0000000..5b3b61b --- /dev/null +++ b/resources/EmailCMS/RegisterEmail/registerEmailController.js @@ -0,0 +1,64 @@ +import { RegisterEmail } from "./registerEmailModal.js"; + +export const RegisterEmailSend = async (req, res) => { + try { + if (!req?.user) return res.status(400).json({ message: "please login !" }); + // console.log(req?.user) + + req.body.user = req.user._id; + const registerEmailFindDoc = await RegisterEmail.find(); + if (registerEmailFindDoc.length === 0) { + const registerEmaildata = await RegisterEmail.create({ + subject: req.body.subject, + description: req.body.description, + addedBy: req.user._id, + }); + + if (registerEmaildata) { + return res.status(200).json({ + success: true, + registerEmaildata, + message: "Added successfully", + }); + } + } else { + const updateEmailData = await RegisterEmail.updateOne({ + subject: req.body.subject, + description: req.body.description, + addedBy: req.user._id, + }); + if (updateEmailData) { + return res.status(200).json({ + success: true, + RegisterEmaildata: updateEmailData, + message: "updated successfully ", + }); + } + } + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; + +export const GetRegisterEamilData = async (req, res) => { + try { + // if (!req?.user) return res.status(400).json({ message: "please login !" }); + // console.log(req?.user) + + const registerEmaildata = await RegisterEmail.find(); + + res.status(200).json({ + success: true, + registerEmaildata, + message: "Found successfully ", + }); + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went Wrong", + }); + } +}; diff --git a/resources/EmailCMS/RegisterEmail/registerEmailModal.js b/resources/EmailCMS/RegisterEmail/registerEmailModal.js new file mode 100644 index 0000000..9efacc8 --- /dev/null +++ b/resources/EmailCMS/RegisterEmail/registerEmailModal.js @@ -0,0 +1,26 @@ +import mongoose from "mongoose"; + +const { Schema, model } = mongoose; + +const registerEmailData = new mongoose.Schema( + { + subject: { + type: String, + required: [true, "Please Enter title "], + }, + description: { + type: String, + maxLength: [500, "description cannot exceed 500 characters"], + required: [true, "Please Enter description"], + }, + addedBy: { + type: mongoose.Schema.ObjectId, + ref: "User", + required: true, + }, + }, + + { timestamps: true, versionKey: false } +); + +export const RegisterEmail = mongoose.model("RegisterEmail", registerEmailData); diff --git a/resources/Informations/InformationRoute.js b/resources/Informations/InformationRoute.js index 0dc16da..729dde5 100644 --- a/resources/Informations/InformationRoute.js +++ b/resources/Informations/InformationRoute.js @@ -1,18 +1,27 @@ - -import express from 'express' +import express from "express"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import { AddNewnIformation, FindAllInformation } from './InformationController.js'; - -const router = express.Router() - -router.route("/new").post(isAuthenticatedUser, authorizeRoles("admin"), AddNewnIformation) -router.route("/getAll").get(isAuthenticatedUser, authorizeRoles("admin"), FindAllInformation) - - - +import { + AddNewnIformation, + FindAllInformation, +} from "./InformationController.js"; +const router = express.Router(); +router + .route("/new") + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + AddNewnIformation + ); +router + .route("/getAll") + .get( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + FindAllInformation + ); // router.route("/product/getAll/").get(getAllProduct) -export default router \ No newline at end of file +export default router; diff --git a/resources/LoginImage/LoginImageRoute.js b/resources/LoginImage/LoginImageRoute.js index 5c75634..27fe392 100644 --- a/resources/LoginImage/LoginImageRoute.js +++ b/resources/LoginImage/LoginImageRoute.js @@ -2,18 +2,27 @@ import express from "express"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; // import { addImage, deleteImage, getImage, updateImage } from "./RegistrationImageController.js"; -import { addImage, deleteImage, getImage, updateImage } from "./LoginImageController.js"; +import { + addImage, + deleteImage, + getImage, + updateImage, +} from "./LoginImageController.js"; const router = express.Router(); router - .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addImage); + .route("/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addImage); router.route("/getImage").get(getImage); router - .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateImage); + .route("/update/:_id") + .patch(isAuthenticatedUser, authorizeRoles("admin", "Employee"), updateImage); router - .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteImage); + .route("/delete/:_id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteImage + ); export default router; diff --git a/resources/Orders/orderRoute.js b/resources/Orders/orderRoute.js index 44cfa4b..7409dad 100644 --- a/resources/Orders/orderRoute.js +++ b/resources/Orders/orderRoute.js @@ -46,18 +46,26 @@ router.route("/user/self").get(isAuthenticatedUser, getUserSelf); //admin route router .route("/getAll/:status") - .get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder); + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getAllOrder); router .route("/getAll/") - .get(isAuthenticatedUser, authorizeRoles("admin"), getOrders); + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getOrders); router.route("/getOne/:id").get(isAuthenticatedUser, getSingleOrder); router .route("/change/status/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateOrderStatusById); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateOrderStatusById + ); router .route("/delete/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteOneOrder); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteOneOrder + ); //RAZERPAY checkout router.route("/getRzpKey/").get(isAuthenticatedUser, getRzpkey); diff --git a/resources/Panels/PanelRoutes.js b/resources/Panels/PanelRoutes.js index bec781a..5b5cb46 100644 --- a/resources/Panels/PanelRoutes.js +++ b/resources/Panels/PanelRoutes.js @@ -1,59 +1,81 @@ import express from "express"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import { AddPanel1, AddPanel2, AddPanel3, AddPanel4, deleteImageFromCloudinary, getPanel1, getPanel2, getPanel3, getPanel4, updatePanel1, updatePanel2, updatePanel3, updatePanel4 } from "./PanelController.js"; +import { + AddPanel1, + AddPanel2, + AddPanel3, + AddPanel4, + deleteImageFromCloudinary, + getPanel1, + getPanel2, + getPanel3, + getPanel4, + updatePanel1, + updatePanel2, + updatePanel3, + updatePanel4, +} from "./PanelController.js"; const router = express.Router(); router - .route("/panel1/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddPanel1); -router - .route("/panel1/get") - .get(getPanel1); + .route("/panel1/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddPanel1); +router.route("/panel1/get").get(getPanel1); router - .route("/panel1/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatePanel1); + .route("/panel1/update/:id") + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatePanel1 + ); router - .route("/panel2/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddPanel2); -router - .route("/panel2/get") - .get(getPanel2); + .route("/panel2/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddPanel2); +router.route("/panel2/get").get(getPanel2); router - .route("/panel2/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatePanel2); + .route("/panel2/update/:id") + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatePanel2 + ); router - .route("/panel3/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddPanel3); -router - .route("/panel3/get") - .get(getPanel3); + .route("/panel3/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddPanel3); +router.route("/panel3/get").get(getPanel3); router - .route("/panel3/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatePanel3); + .route("/panel3/update/:id") + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatePanel3 + ); router - .route("/panel4/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddPanel4); -router - .route("/panel4/get") - .get(getPanel4); - -router - .route("/panel4/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatePanel4); + .route("/panel4/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), AddPanel4); +router.route("/panel4/get").get(getPanel4); router - .route("/deleteImage/jatinMor/panel/:public_id") - .delete( - isAuthenticatedUser, - authorizeRoles("admin"), - deleteImageFromCloudinary - ); -export default router; \ No newline at end of file + .route("/panel4/update/:id") + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatePanel4 + ); + +router + .route("/deleteImage/jatinMor/panel/:public_id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteImageFromCloudinary + ); +export default router; diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js index 5641538..7412049 100644 --- a/resources/Products/ProductRoute.js +++ b/resources/Products/ProductRoute.js @@ -15,10 +15,18 @@ const router = express.Router(); import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; router .route("/product/create/") - .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct); + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + createProduct + ); router .route("/product/getAll/admin/") - .get(isAuthenticatedUser, authorizeRoles("admin"), getAllProductAdmin); + .get( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + getAllProductAdmin + ); //change Product status router.route("/product/admin/status/:id").patch(ChangeProductStatus); @@ -30,15 +38,23 @@ router router.route("/product/getOne/:id").get(getOneProduct); router .route("/product/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateProduct); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateProduct + ); router .route("/product/delete/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteProduct + ); router .route("/product/deleteImage/jatinMor/product/:public_id") .delete( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), deleteImageFromCloudinary ); router.route("/products/category/:categoryName").get(getProductsByCategory); diff --git a/resources/RegistrationImage/RegistrationImageRoute.js b/resources/RegistrationImage/RegistrationImageRoute.js index 9eef3db..09542fa 100644 --- a/resources/RegistrationImage/RegistrationImageRoute.js +++ b/resources/RegistrationImage/RegistrationImageRoute.js @@ -1,18 +1,27 @@ import express from "express"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import { addImage, deleteImage, getImage, updateImage } from "./RegistrationImageController.js"; +import { + addImage, + deleteImage, + getImage, + updateImage, +} from "./RegistrationImageController.js"; const router = express.Router(); router - .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addImage); + .route("/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addImage); router.route("/getImage").get(getImage); router - .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateImage); + .route("/update/:_id") + .patch(isAuthenticatedUser, authorizeRoles("admin", "Employee"), updateImage); router - .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteImage); + .route("/delete/:_id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteImage + ); export default router; diff --git a/resources/SEO&Analytics/SEORouter.js b/resources/SEO&Analytics/SEORouter.js index 33bf606..1803570 100644 --- a/resources/SEO&Analytics/SEORouter.js +++ b/resources/SEO&Analytics/SEORouter.js @@ -6,7 +6,10 @@ const router = express.Router(); router .route("/new") - .post(isAuthenticatedUser, authorizeRoles("admin"), AddNewSeoRequest); - + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + AddNewSeoRequest + ); export default router; diff --git a/resources/ShippingAddresses/ShippingAddressRoute.js b/resources/ShippingAddresses/ShippingAddressRoute.js index 0cb1f1a..9ea8bf2 100644 --- a/resources/ShippingAddresses/ShippingAddressRoute.js +++ b/resources/ShippingAddresses/ShippingAddressRoute.js @@ -16,7 +16,7 @@ router .route("/admin/new/:_id") .post( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), AddshippingAddressByAdmin ); @@ -28,7 +28,7 @@ router .route("/user/address/:_id") .get( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), getSingleUserSippingAddressForAdmin ); diff --git a/resources/ShopPageImage/ShopPageImageRoute.js b/resources/ShopPageImage/ShopPageImageRoute.js index 5117e62..5d469ad 100644 --- a/resources/ShopPageImage/ShopPageImageRoute.js +++ b/resources/ShopPageImage/ShopPageImageRoute.js @@ -1,20 +1,29 @@ import express from "express"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import { addImage, deleteImage, getImage, updateImage } from "./ShopPageImageController.js"; +import { + addImage, + deleteImage, + getImage, + updateImage, +} from "./ShopPageImageController.js"; // import { addImage, deleteImage, getImage, updateImage } from "./RegistrationImageController.js"; // import { addImage, deleteImage, getImage, updateImage } from "./LoginImageController.js"; const router = express.Router(); router - .route("/add") - .post(isAuthenticatedUser, authorizeRoles("admin"), addImage); + .route("/add") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addImage); router.route("/getImage").get(getImage); router - .route("/update/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateImage); + .route("/update/:_id") + .patch(isAuthenticatedUser, authorizeRoles("admin", "Employee"), updateImage); router - .route("/delete/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteImage); + .route("/delete/:_id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteImage + ); export default router; diff --git a/resources/Supports/supportRoute.js b/resources/Supports/supportRoute.js index 3cacdb0..8cd5fda 100644 --- a/resources/Supports/supportRoute.js +++ b/resources/Supports/supportRoute.js @@ -1,5 +1,13 @@ import bodyParser from "body-parser"; -import { createSupport, deleteImageFromCloudinary, deleteSupport, getAllSupportTicket, getAllSupportTicketofuser, getOneSupportTicket, updateSupport } from "./supportController.js"; +import { + createSupport, + deleteImageFromCloudinary, + deleteSupport, + getAllSupportTicket, + getAllSupportTicketofuser, + getOneSupportTicket, + updateSupport, +} from "./supportController.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; import express from "express"; @@ -10,21 +18,27 @@ app.use(bodyParser.raw({ type: "application/json" })); const router = express.Router(); //checkout Routes-------------------------// -router.route("/support/create/").post(isAuthenticatedUser,createSupport); -router.route("/support/getAll/").get(isAuthenticatedUser, authorizeRoles("admin"),getAllSupportTicket); -router.route("/support/userticket/").get(isAuthenticatedUser,getAllSupportTicketofuser); +router.route("/support/create/").post(isAuthenticatedUser, createSupport); +router + .route("/support/getAll/") + .get( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + getAllSupportTicket + ); +router + .route("/support/userticket/") + .get(isAuthenticatedUser, getAllSupportTicketofuser); +router.route("/support/delete/:id").delete(deleteSupport); +router + .route("/support/getOne/:id") + .get(isAuthenticatedUser, getOneSupportTicket); +router.route("/support/update/:id").patch(isAuthenticatedUser, updateSupport); router - .route("/support/delete/:id") - .delete( deleteSupport); - router.route("/support/getOne/:id").get(isAuthenticatedUser, getOneSupportTicket); - router - .route("/support/update/:id") - .patch(isAuthenticatedUser, updateSupport); - router .route("/support/deleteImage/jatinMor/CustomerSupport/:public_id") .delete( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), deleteImageFromCloudinary ); // --------------------------------------------------------- diff --git a/resources/Tax/tax_routes.js b/resources/Tax/tax_routes.js index 62149bb..7bcae6a 100644 --- a/resources/Tax/tax_routes.js +++ b/resources/Tax/tax_routes.js @@ -9,9 +9,15 @@ import { } from "./tax_controller.js"; const router = Router(); -router.route("/add_tax").post(isAuthenticatedUser, authorizeRoles("admin"), addTax); -router.route("/update_tax/:id").patch(isAuthenticatedUser, authorizeRoles("admin"), updateTax); -router.route("/delete_tax/:id").delete(isAuthenticatedUser, authorizeRoles("admin"), deleteTax); +router + .route("/add_tax") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addTax); +router + .route("/update_tax/:id") + .patch(isAuthenticatedUser, authorizeRoles("admin", "Employee"), updateTax); +router + .route("/delete_tax/:id") + .delete(isAuthenticatedUser, authorizeRoles("admin", "Employee"), deleteTax); router.route("/view_tax/:id").get(isAuthenticatedUser, getTax); router.route("/view_tax").get(isAuthenticatedUser, getTaxes); export default router; diff --git a/resources/Temple/FranchiseeRoute.js b/resources/Temple/FranchiseeRoute.js index ced1fb4..03db4d6 100644 --- a/resources/Temple/FranchiseeRoute.js +++ b/resources/Temple/FranchiseeRoute.js @@ -1,24 +1,28 @@ import { Router } from "express"; const router = Router(); import { - addFranchisee, - getAllFranchisees, - getFranchiseeById, - updateFranchisee, - deleteFranchiseeById, - getFranchiseeByIdWithoutPopulate, - getAllFranchiseesPopulated, - // getAllFranchiseesPopulatedWithOption, - addProductToFranchisee, - // addGradeToFranchisee, - getFranchiseeByIdPopulated, - FranchiseeLogin, - franchiseeForgotPassword, - franchiseeUpdatePassword, - getFransiDetails, - EditFranchiseeProfile, + addFranchisee, + getAllFranchisees, + getFranchiseeById, + updateFranchisee, + deleteFranchiseeById, + getFranchiseeByIdWithoutPopulate, + getAllFranchiseesPopulated, + // getAllFranchiseesPopulatedWithOption, + addProductToFranchisee, + // addGradeToFranchisee, + getFranchiseeByIdPopulated, + FranchiseeLogin, + franchiseeForgotPassword, + franchiseeUpdatePassword, + getFransiDetails, + EditFranchiseeProfile, } from "./Franchisee_controller.js"; -import { authorizeRoles, isAuthenticatedUser, isFranchiAuthenticated } from "../../middlewares/auth.js"; +import { + authorizeRoles, + isAuthenticatedUser, + isFranchiAuthenticated, +} from "../../middlewares/auth.js"; import { FranchiseeVarificationFromAdmin } from "./Franchisee_controller.js"; import { FranchiseePriceLevelProduct } from "./Franchisee_controller.js"; import { createOrder } from "./Franchisee_controller.js"; @@ -29,44 +33,62 @@ import { getAllOrder } from "./Franchisee_controller.js"; router.get("/", getAllFranchisees); router.get("/withpopulate", isAuthenticatedUser, getAllFranchiseesPopulated); // router.get("/withpopulate/:option", getAllFranchiseesPopulatedWithOption); -router.get("/withoutpopulate/:id", isAuthenticatedUser, getFranchiseeByIdWithoutPopulate); - - - +router.get( + "/withoutpopulate/:id", + isAuthenticatedUser, + getFranchiseeByIdWithoutPopulate +); router.get("/:id", isAuthenticatedUser, getFranchiseeById); router.get("/arrayspopulate/:id", getFranchiseeByIdPopulated); -router.post("/", isAuthenticatedUser, authorizeRoles("admin"), addFranchisee); +router.post( + "/", + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addFranchisee +); router.patch("/product/:id", isAuthenticatedUser, addProductToFranchisee); // router.patch("/grade/:id", addGradeToFranchisee); -router.patch("/:id", isAuthenticatedUser, authorizeRoles("admin"), updateFranchisee); -router.delete("/:id", isAuthenticatedUser, authorizeRoles("admin"), deleteFranchiseeById); +router.patch( + "/:id", + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateFranchisee +); +router.delete( + "/:id", + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteFranchiseeById +); //varify -router.get("/admin/verify/:id", isAuthenticatedUser, authorizeRoles("admin"), FranchiseeVarificationFromAdmin); - +router.get( + "/admin/verify/:id", + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + FranchiseeVarificationFromAdmin +); // ---------franchisee Auth ----------------------//////// -franchiseeForgotPassword +franchiseeForgotPassword; router.post("/login", FranchiseeLogin); -router.post("/password/forgot", franchiseeForgotPassword) +router.post("/password/forgot", franchiseeForgotPassword); router.get("/getDetails/me", isFranchiAuthenticated, getFransiDetails); router.patch("/edit/self", isFranchiAuthenticated, EditFranchiseeProfile); - -router.route("/password/update").put(isFranchiAuthenticated, franchiseeUpdatePassword); +router + .route("/password/update") + .put(isFranchiAuthenticated, franchiseeUpdatePassword); //fetch product franchisee Wise -router.route("/product/price_level").get(isFranchiAuthenticated, FranchiseePriceLevelProduct); +router + .route("/product/price_level") + .get(isFranchiAuthenticated, FranchiseePriceLevelProduct); //product order -router.route("/order/create").post(isFranchiAuthenticated, createOrder) -router.route("/order/getAll").get(isFranchiAuthenticated, getAllOrder) -router.route("/order/getOne/:id").get(isFranchiAuthenticated, getSingleOrder) -router.route("/order/edit/:id").put(isFranchiAuthenticated, EditOrderBeforePayment) - - - - - - - +router.route("/order/create").post(isFranchiAuthenticated, createOrder); +router.route("/order/getAll").get(isFranchiAuthenticated, getAllOrder); +router.route("/order/getOne/:id").get(isFranchiAuthenticated, getSingleOrder); +router + .route("/order/edit/:id") + .put(isFranchiAuthenticated, EditOrderBeforePayment); export default router; diff --git a/resources/Testimonials/TestimonialRoute.js b/resources/Testimonials/TestimonialRoute.js index 9dda39f..71facda 100644 --- a/resources/Testimonials/TestimonialRoute.js +++ b/resources/Testimonials/TestimonialRoute.js @@ -12,21 +12,27 @@ import { const router = express.Router(); router.route("/new").post(isAuthenticatedUser, AddNewTestimonial); -router - .route("/getAll") - .get(FindAllTestimonial); +router.route("/getAll").get(FindAllTestimonial); router.route("/getOne/:id").get(isAuthenticatedUser, FindOneTestimonial); router .route("/delete/:id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteTestimonial); - router + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteTestimonial + ); +router .route("/update/:id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updatetesTimonial); - router + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updatetesTimonial + ); +router .route("/deleteImage/GetSygnal/Testimonial/:public_id") .delete( isAuthenticatedUser, - authorizeRoles("admin"), + authorizeRoles("admin", "Employee"), deleteImageFromCloudinary ); export default router; diff --git a/resources/setting/Configration/Config_routes.js b/resources/setting/Configration/Config_routes.js index 856b27c..9d79df1 100644 --- a/resources/setting/Configration/Config_routes.js +++ b/resources/setting/Configration/Config_routes.js @@ -14,8 +14,10 @@ import { } from "./Config_controller.js"; import { upload } from "../../../Utils/cloudinary.js"; -import { authorizeRoles, isAuthenticatedUser } from "../../../middlewares/auth.js"; - +import { + authorizeRoles, + isAuthenticatedUser, +} from "../../../middlewares/auth.js"; const router = Router(); @@ -25,21 +27,52 @@ const router = Router(); // { name: "Adminlogo", maxCount: 1 }, // ]); -// router.route("/gst").post(isAuthenticatedUser, authorizeRoles("admin"), addGST); -router.route("/social").post(isAuthenticatedUser, authorizeRoles("admin"), addSocialMedia); -router.route("/application/name").post(isAuthenticatedUser, authorizeRoles("admin"), addApplicationName); -router.route("/copyright/message").post(isAuthenticatedUser, authorizeRoles("admin"), addCopyRightMessage); +// router.route("/gst").post(isAuthenticatedUser,authorizeRoles("admin", "Employee"), addGST); +router + .route("/social") + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addSocialMedia + ); +router + .route("/application/name") + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addApplicationName + ); +router + .route("/copyright/message") + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addCopyRightMessage + ); - - -router.route("/address").post(isAuthenticatedUser, authorizeRoles("admin"), addAddress); -// router.route("/scrollText").post(isAuthenticatedUser, authorizeRoles("admin"), addScrollText); -router.route("/logo").post(isAuthenticatedUser, authorizeRoles("admin"), addLogo); -router.route("/").get(getConfig).delete(isAuthenticatedUser, authorizeRoles("admin"), deleteConfig) +router + .route("/address") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addAddress); +// router.route("/scrollText").post(isAuthenticatedUser,authorizeRoles("admin", "Employee"), addScrollText); +router + .route("/logo") + .post(isAuthenticatedUser, authorizeRoles("admin", "Employee"), addLogo); +router + .route("/") + .get(getConfig) + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteConfig + ); router .route("/termsofuse") - .get(isAuthenticatedUser, authorizeRoles("admin"), getTermsOfUse) - .patch(isAuthenticatedUser, authorizeRoles("admin"), addTermsOfUse); + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getTermsOfUse) + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addTermsOfUse + ); export default router; diff --git a/resources/user/userController.js b/resources/user/userController.js index 1114ec3..b6b39c9 100644 --- a/resources/user/userController.js +++ b/resources/user/userController.js @@ -7,10 +7,12 @@ 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 } = req.body; + 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 }); @@ -37,30 +39,45 @@ export const registerUser = async (req, res) => { 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 Smellika - Let the Shopping Begin!`, - html: `

Welcome to Smellika - Let the Shopping Begin!

+ html: `

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

Hey ${name}, -

Welcome to Smellika! We're thrilled to have you on board. Get ready for a world of exclusive deals, exciting products, and seamless shopping experiences. Start exploring now!

+

+ + Welcome to Smellika - Let the Shopping Begin! +


-

You can login into : https://smellika.com

+

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 Smellika`, + Team ${appName}`, }); sendToken(user, 201, res); } catch (e) { @@ -353,3 +370,81 @@ export const getAllUser = catchAsyncErrors(async (req, res, next) => { 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, + }); + } +}); diff --git a/resources/user/userModel.js b/resources/user/userModel.js index ab83174..65006d3 100644 --- a/resources/user/userModel.js +++ b/resources/user/userModel.js @@ -46,6 +46,7 @@ const userSchema = new mongoose.Schema( type: String, default: "user", }, + accessTo: {}, // createdAt: { // type: Date, // default: Date.now, diff --git a/resources/user/userRoute.js b/resources/user/userRoute.js index df3bec0..62aac03 100644 --- a/resources/user/userRoute.js +++ b/resources/user/userRoute.js @@ -11,6 +11,9 @@ import { getSingleUser, getAllUser, getUserOrderForAdmin, + getAllEmployee, + deleteEmployeeById, + updateEmployeeById, } from "./userController.js"; import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; @@ -30,14 +33,39 @@ router.route("/user/details").get(isAuthenticatedUser, getUserDetails); router .route("/admin/users") - .get(isAuthenticatedUser, authorizeRoles("admin"), getAllUser); + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getAllUser); +router + .route("/admin/delete-employee/:id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteEmployeeById + ); +router + .route("/admin/employee") + .get( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + getAllEmployee + ); +router + .route("/admin/update-employee/:id") + .put( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateEmployeeById + ); router .route("/admin/users/orders/:id") - .get(isAuthenticatedUser, authorizeRoles("admin"), getUserOrderForAdmin); + .get( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + getUserOrderForAdmin + ); router .route("/admin/user/:id") - .get(isAuthenticatedUser, authorizeRoles("admin"), getSingleUser); + .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getSingleUser); router.route("/user/password/update").put(isAuthenticatedUser, updatePassword); diff --git a/resources/userAddress/useAddressRoute.js b/resources/userAddress/useAddressRoute.js index 166aed6..0e04c6e 100644 --- a/resources/userAddress/useAddressRoute.js +++ b/resources/userAddress/useAddressRoute.js @@ -12,14 +12,26 @@ const router = express.Router(); router .route("/addAddress") - .post(isAuthenticatedUser, authorizeRoles("admin"), addUserAddress); + .post( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + addUserAddress + ); router.route("/getAddressess").get(getUserAddress); router.route("/getOneAddress/:_id").get(getOneAddress); router .route("/updateAddress/:_id") - .patch(isAuthenticatedUser, authorizeRoles("admin"), updateAddress); + .patch( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + updateAddress + ); router .route("/deleteAddress/:_id") - .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteUserAddress); + .delete( + isAuthenticatedUser, + authorizeRoles("admin", "Employee"), + deleteUserAddress + ); export default router;