import sendEmail from "../../Utils/sendEmail.js";
import { Order } from "./orderModel.js";
export const getAllOrder = async (req, res) => {
try {
const { status } = req.params;
const order = await Order.find({
// payment_status: { $in: ["success", "failed"] },
payment_status: "success",
orderStatus: status,
})
.populate({
path: "user",
select: "name -_id",
})
.populate({
path: "shippingInfo.addressId",
// populate: {
// path: "Franchisee",
// select: "banner price_Lable ",
// },
})
.sort({ updatedAt: -1 });
if (order) {
res.status(201).json({
success: true,
order,
message: "All Order Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
export const getOrders = async (req, res) => {
try {
const order = await Order.find({
// payment_status: "success",
})
.populate({
path: "user",
select: "name -_id",
})
.populate({
path: "shippingInfo.addressId",
})
.sort({ updatedAt: -1 });
if (order) {
res.status(201).json({
success: true,
order,
message: "All Order Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
export const getSingleOrder = async (req, res) => {
try {
if (!req.params.id)
return res.status(400).json({ message: "please Provide Order Id" });
// console.log("dddddddddddddddddddddddd");
const order = await Order.findById(req.params.id)
.populate({
path: "user",
select: "name email -_id ",
})
.populate({
path: "couponUsed",
select: "coupon_code discount_amount -_id", // Only select coupon_code and discount_amount from the couponUsed model
})
.populate({
path: "shippingInfo.addressId",
})
.sort({ createdAt: -1 });
if (order) {
res.status(201).json({
success: true,
order,
message: " Order Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
//get self User Order
export const getUserSelf = async (req, res) => {
if (!req?.user) return res.status(400).json({ message: "please login !" });
try {
const order = await Order.find({
user: req.user?._id,
payment_status: "success",
}).sort({ createdAt: -1 });
if (order) {
return res.status(200).json({
success: true,
order,
message: "self Order fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
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 Order Id" });
const getOrder = await Order.findById(req.params.id);
if (!getOrder) {
return res.status(404).json({
success: false,
message: "No Order Found!",
});
}
const order = await Order.findByIdAndDelete(req.params.id);
await order.remove();
res.status(200).json({
success: true,
message: "Order 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 Order.findById(req.params.id)
.populate({
path: "user",
select: "name email -_id",
})
.populate({
path: "couponUsed",
select: "coupon_code discount_amount -_id", // Only select coupon_code and discount_amount from the couponUsed model
});
// 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 Order.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: `Order #${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.
Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}
Items :
S No. |
Product Name |
Variant |
Image |
Quantity |
Price |
GST Amount |
SubTotal |
${order?.orderItems
?.map(
(product, index) => `
${
index + 1
} |
${
product.name
} |
${
product?.variant_Name
} |
 |
${
product.quantity
} |
₹${
product.price
} |
₹${
product?.gst_amount
} |
₹${
product.product_Subtotal
} |
`
)
.join("")}
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: "Order status updated successfully!" });
} else if (req.body.status === "processing") {
await Order.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 Order #${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
},
Order Status : Processing
Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}
Order Items :
S No. |
Product Name |
Variant |
Image |
Quantity |
Price |
GST Amount |
SubTotal |
${order?.orderItems
?.map(
(product, index) => `
${
index + 1
} |
${
product.name
} |
${
product?.variant_Name
} |
 |
${
product.quantity
} |
₹${
product.price
} |
₹${
product?.gst_amount
} |
₹${
product.product_Subtotal
} |
`
)
.join("")}
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: "Order 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 Order.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 Order #${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
}
Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}
Items :
S No. |
Product Name |
Variant |
Image |
Quantity |
Price |
GST Amount |
SubTotal |
${order?.orderItems
?.map(
(product, index) => `
${
index + 1
} |
${
product.name
} |
${
product?.variant_Name
} |
 |
${
product.quantity
} |
₹${
product.price
} |
₹${
product?.gst_amount
} |
₹${
product.product_Subtotal
} |
`
)
.join("")}
Total Amount : |
₹${
order?.total_amount
} |
Order 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: "Order status updated successfully!" });
} else if (req.body.status === "delivered") {
body["isDelivered"] = true;
body["DeliveredDate"] = req.body.DDate;
await Order.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 Order #${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!
Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}
Items :
S No. |
Product Name |
Variant |
Image |
Quantity |
Price |
GST Amount |
SubTotal |
${order?.orderItems
?.map(
(product, index) => `
${
index + 1
} |
${
product.name
} |
${
product?.variant_Name
} |
 |
${
product.quantity
} |
₹${
product.price
} |
₹${
product?.gst_amount
} |
₹${
product.product_Subtotal
} |
`
)
.join("")}
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: "Order status updated successfully!" });
} else {
// await Order.findByIdAndUpdate(order._id, body);
// console.log(order);
res
.status(200)
.json({ status: "ok", message: "Order status updated successfully!" });
}
} catch (error) {
console.log(error);
res
.status(500)
.json({ message: error?.message || "Something went wrong!" });
}
};