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 Name Image Quantity Price GST Amount SubTotal
${ 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 Name Image Quantity Price GST Amount SubTotal
${ 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 Name Image Quantity Price GST Amount SubTotal
${ 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 Name Image Quantity Price GST Amount SubTotal
${ 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!" }); } };