change coupon

This commit is contained in:
pawan-dot 2024-05-10 17:30:36 +05:30
parent 422230ee05
commit 545c49b8c2
5 changed files with 239 additions and 58 deletions

View File

@ -2,7 +2,7 @@ import mongoose from "mongoose";
const { Schema, model } = mongoose; const { Schema, model } = mongoose;
const couponUsedSchema = new Schema({ const couponUsedSchema = new Schema({
userId: { type: String, required: true }, userId: { type: mongoose.Schema.ObjectId, ref: "User", required: true },
orderId: { type: String, required: true }, orderId: { type: String, required: true },
couponCode: { type: String, required: true }, couponCode: { type: String, required: true },
date: { type: String, required: true }, date: { type: String, required: true },

View File

@ -106,12 +106,11 @@ export const listAffiliateCoupon = async (req, res) => {
mobile: 1, mobile: 1,
} }
); );
for (let i = 0; i < coupon.length; i++) { for (let i = 0; i < coupon?.length; i++) {
if (coupon[i].is_coupon_active == false) { if (coupon[i].is_coupon_active == true) {
resArr.push(coupon[i]); resArr.push(coupon[i]);
} }
} }
// console.log(resArr);
res.status(200).json({ res.status(200).json({
success: true, success: true,
message: resArr, message: resArr,
@ -216,8 +215,9 @@ export const getOneCoupon = async (req, res) => {
//Validate Coupon----------------------- //Validate Coupon-----------------------
export const validateCoupon = async (req, res) => { export const validateCoupon = async (req, res) => {
try {
const { coupon } = req.params; const { coupon } = req.params;
// Check if coupon code is provided
if (!coupon) { if (!coupon) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
@ -225,30 +225,32 @@ export const validateCoupon = async (req, res) => {
}); });
} }
try {
// Find the coupon data in the database // Find the coupon data in the database
const couponData = await AffiliateModel.findOne({ coupon_code: coupon }); const couponData = await AffiliateModel.findOne({ coupon_code: coupon });
// Check if coupon exists
if (!couponData) { if (!couponData) {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
message: "Coupon not found", message: "Invalid coupon code",
}); });
} }
const { valid_till, discount_amount, is_coupon_active } = couponData; const { valid_till, discount_amount, is_coupon_active } = couponData;
//Check whether Coupon is Active or not
// Check if coupon is active
if (!is_coupon_active) { if (!is_coupon_active) {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
message: "Coupon Code Expired", message: "Coupon is not active",
}); });
} }
// Check if the coupon is expired
// Check if the coupon has expired
const currentDate = new Date(); const currentDate = new Date();
const expirationDate = new Date(valid_till); const expirationDate = new Date(valid_till);
if (currentDate > expirationDate) { if (expirationDate <= currentDate) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
message: "Coupon has expired", message: "Coupon has expired",
@ -256,10 +258,10 @@ export const validateCoupon = async (req, res) => {
} }
// If coupon is valid, return success response // If coupon is valid, return success response
res.status(200).json({ return res.status(200).json({
success: true, success: true,
message: "Coupon is valid", message: "Coupon is valid",
discount_amount: discount_amount, discount_amount,
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@ -352,7 +354,7 @@ export const usedCoupon = async (req, res) => {
}); });
} }
AffiliateModel.findByIdAndUpdate( await AffiliateModel.findByIdAndUpdate(
_id, _id,
{ {
$inc: { total_earning: affiliate_discount_amount, coupon_claimed: 1 }, $inc: { total_earning: affiliate_discount_amount, coupon_claimed: 1 },
@ -392,12 +394,17 @@ export const usedCoupon = async (req, res) => {
export const couponPayHistory = async (req, res) => { export const couponPayHistory = async (req, res) => {
if (req.params?.id) { if (req.params?.id) {
try { try {
const saveData = await AffiliateModel.findById(req.params.id).sort({ const saveData = await AffiliateModel.findById(req.params.id)
.populate({
path: "coupon_used_history.userId",
select: "name email",
})
.sort({
updatedAt: -1, updatedAt: -1,
}); });
// console.log(saveData.coupon_used_history);
const resObj = { const resObj = {
coupon_used_history: saveData.coupon_used_history, coupon_used_history: saveData?.coupon_used_history,
coupon_code: saveData.coupon_code, coupon_code: saveData.coupon_code,
}; };
res.status(200).json({ res.status(200).json({

View File

@ -5,11 +5,92 @@ import { Order } from "./orderModel.js";
import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js";
import sendEmail from "../../Utils/sendEmail.js"; import sendEmail from "../../Utils/sendEmail.js";
import { AffiliateModel } from "../Affiliate&Coupon/Affiliate/AffiliateModel.js";
const instance = new Razorpay({ const instance = new Razorpay({
key_id: process.env.RAZERPAY_KEY_ID, key_id: process.env.RAZERPAY_KEY_ID,
key_secret: process.env.RAZERPAY_SECRET_KEY, key_secret: process.env.RAZERPAY_SECRET_KEY,
}); });
//validate Discount coupon-----------------------------------
const usedCoupon = async (orderId, coupon_code, userId) => {
try {
if (!orderId || !coupon_code || !userId) {
return { success: false, message: "Error in getting OrderId or Coupon" };
}
// Validating Coupon
const couponData = await AffiliateModel.findOne({
coupon_code: coupon_code,
});
if (!couponData) {
// Check if the coupon exists
return { success: false, message: "Coupon not found" };
}
// Check if orderId is unique
const isOrderIdUnique = await AffiliateModel.find(
{},
{ coupon_used_history: 1 }
);
let orderIdFound = false;
isOrderIdUnique.forEach((data) => {
data.coupon_used_history.forEach((subItem) => {
if (subItem.orderId == orderId) {
orderIdFound = true;
}
});
});
if (orderIdFound) {
return { success: false, message: "Error: OrderId already used" };
}
const {
valid_till,
is_coupon_active,
is_affiliate_active,
affiliate_discount_amount,
_id,
} = couponData;
if (!is_coupon_active || !is_affiliate_active) {
return { success: false, message: "Coupon Code Expired" };
}
const currentDate = new Date();
const expirationDate = new Date(valid_till);
if (currentDate > expirationDate) {
return { success: false, message: "Coupon has expired" };
}
let fdata = await AffiliateModel.findByIdAndUpdate(
_id,
{
$inc: { total_earning: affiliate_discount_amount, coupon_claimed: 1 },
$push: {
coupon_used_history: {
orderId: orderId,
userId: userId,
date: currentDate,
couponCode: coupon_code,
},
},
},
{ new: true }
);
// console.log("fdata", fdata);
return {
success: true,
message: "Coupon add success",
AffiliateCouponID: fdata?._id,
};
} catch (error) {
console.error(error);
return { success: false, message: "Internal server error" };
}
};
// ------------------------------------------------------
const generateUniqueOrderId = async () => { const generateUniqueOrderId = async () => {
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
// Find the latest order to get the last serial number // Find the latest order to get the last serial number
@ -56,9 +137,7 @@ export const getRazerpayKey = async (req, res) => {
}); });
} catch (error) { } catch (error) {
console.error("Error in getRzpKey:", error); console.error("Error in getRzpKey:", error);
res res.status(500).json({
.status(500)
.json({
success: false, success: false,
message: error.message || "Internal server error", message: error.message || "Internal server error",
}); });
@ -67,9 +146,8 @@ export const getRazerpayKey = async (req, res) => {
export const checkout = async (req, res) => { export const checkout = async (req, res) => {
try { try {
const { userr,address, cart, subtotal,orderType } = req.body; const { userr, address, cart, subtotal, orderType, couponCode } = req.body;
// console.log(req.body.cart[0].product); // console.log(req.body.cart[0].product);
// console.log(req.body.cart[0].variant);
if (cart.length < 1) if (cart.length < 1)
return res.status(400).json({ message: "cart is empty!" }); return res.status(400).json({ message: "cart is empty!" });
if (!address) if (!address)
@ -210,6 +288,35 @@ export const checkout = async (req, res) => {
razorpay_order_id: order?.id, razorpay_order_id: order?.id,
orderType, orderType,
}); });
// console.log(
// "orders",
// orders,
// "-------------------------------------------------"
// );
if (couponCode) {
const couponResponse = await usedCoupon(
orders?.orderID,
couponCode,
orders?.user
);
if (couponResponse?.success === true) {
const saveData = await Order.findByIdAndUpdate(
{ _id: orders?._id },
{
isCouponUsed: true,
couponUsed: couponResponse?.AffiliateCouponID,
},
{ new: true }
);
} else {
return res.status(400).json({
success: false,
message: couponResponse?.message
? couponResponse?.message
: "Something Wrong With Discount Coupon",
});
}
}
} else { } else {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
@ -249,11 +356,16 @@ export const paymentVerification = async (req, res) => {
// Database comes here // Database comes here
let findSameOrder = await Order.findOne({ let findSameOrder = await Order.findOne({
razorpay_order_id: razorpay_order_id, razorpay_order_id: razorpay_order_id,
}).populate({ })
.populate({
path: "user", path: "user",
select: "name email -_id", 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("findSameOrder", findSameOrder);
if (findSameOrder) { if (findSameOrder) {
(findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({ (findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({
(findSameOrder.isPaid = true), (findSameOrder.isPaid = true),
@ -266,7 +378,6 @@ export const paymentVerification = async (req, res) => {
await findSameOrder.save(); await findSameOrder.save();
} }
//send email to customer //send email to customer
// console.log("findSameOrder", findSameOrder);
await sendEmail({ await sendEmail({
to: `${findSameOrder?.user?.email}`, // Change to your recipient to: `${findSameOrder?.user?.email}`, // Change to your recipient
@ -298,6 +409,14 @@ export const paymentVerification = async (req, res) => {
findSameOrder?.shippingInfo?.gst_number findSameOrder?.shippingInfo?.gst_number
? ", GST_NO:" + findSameOrder?.shippingInfo?.gst_number ? ", GST_NO:" + findSameOrder?.shippingInfo?.gst_number
: "" : ""
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;"> Any Discount : ${
findSameOrder?.isCouponUsed
? "Yes ,₹" +
Number(findSameOrder?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
findSameOrder?.couponUsed?.coupon_code
: "No Discount"
}</h4> }</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
@ -460,6 +579,14 @@ export const pospaymentVerification = async (req, res) => {
findSameOrder?.shippingInfo?.gst_number findSameOrder?.shippingInfo?.gst_number
? ", GST_NO:" + findSameOrder?.shippingInfo?.gst_number ? ", GST_NO:" + findSameOrder?.shippingInfo?.gst_number
: "" : ""
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;"> Any Discount: ${
findSameOrder?.isCouponUsed
? "Yes ,₹" +
Number(findSameOrder?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
findSameOrder?.couponUsed?.coupon_code
: "No Discount"
}</h4> }</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
@ -601,7 +728,6 @@ export const handlePayment = async (req, res) => {
shippingInfo: shipping, shippingInfo: shipping,
user: req.user._id, user: req.user._id,
}); });
console.log("fffffffff", order, "llllllllll");
const lineItems = await cart.map((item) => ({ const lineItems = await cart.map((item) => ({
price_data: { price_data: {
currency: "inr", currency: "inr",

View File

@ -68,10 +68,15 @@ export const getSingleOrder = async (req, res) => {
if (!req.params.id) if (!req.params.id)
return res.status(400).json({ message: "please Provide Order Id" }); return res.status(400).json({ message: "please Provide Order Id" });
// console.log("dddddddddddddddddddddddd");
const order = await Order.findById(req.params.id) const order = await Order.findById(req.params.id)
.populate({ .populate({
path: "user", path: "user",
select: "name email -_id", 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({ .populate({
path: "shippingInfo.addressId", path: "shippingInfo.addressId",
@ -149,9 +154,14 @@ export const updateOrderStatusById = async (req, res) => {
const currentDate = new Date(); const currentDate = new Date();
body["status_timeline." + req.body.status] = currentDate; body["status_timeline." + req.body.status] = currentDate;
// if (req.body?.package_weight) body.package_weight = req.body.package_weight; // if (req.body?.package_weight) body.package_weight = req.body.package_weight;
const order = await Order.findById(req.params.id).populate({ const order = await Order.findById(req.params.id)
.populate({
path: "user", path: "user",
select: "name email -_id", 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); // console.log("order", order);
// const parentData = { email: order?.parent?.email }; // const parentData = { email: order?.parent?.email };
@ -170,7 +180,14 @@ export const updateOrderStatusById = async (req, res) => {
order?.orderID order?.orderID
} has been canceled. We understand that circumstances may change, and we're here to assist you throughout the process.</h3> } has been canceled. We understand that circumstances may change, and we're here to assist you throughout the process.</h3>
<h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
<thead> <thead>
@ -261,6 +278,16 @@ export const updateOrderStatusById = async (req, res) => {
order?.shippingInfo?.first_Name order?.shippingInfo?.first_Name
},</strong> },</strong>
<h4 style="color: #333; font-family: Arial, sans-serif;">Order Status : Processing</h4> <h4 style="color: #333; font-family: Arial, sans-serif;">Order Status : Processing</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
<thead> <thead>
@ -322,6 +349,7 @@ export const updateOrderStatusById = async (req, res) => {
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${
order?.total_amount order?.total_amount
}</td> }</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@ -380,7 +408,14 @@ export const updateOrderStatusById = async (req, res) => {
req.body.TrackingID req.body.TrackingID
}</h4> }</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
<thead> <thead>
@ -472,6 +507,14 @@ export const updateOrderStatusById = async (req, res) => {
<h3 style="color: #333; font-family: Arial, sans-serif;">Great news! Your order #${ <h3 style="color: #333; font-family: Arial, sans-serif;">Great news! Your order #${
order?.orderID order?.orderID
} has been successfully delivered to your doorstep. We hope everything is just as you expected!</h3> } has been successfully delivered to your doorstep. We hope everything is just as you expected!</h3>
<h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${
order?.isCouponUsed
? "Yes ,₹" +
Number(order?.couponUsed?.discount_amount) +
" , COUPON_CODE:" +
order?.couponUsed?.coupon_code
: "No Discount"
}</h4>
<h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4> <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
<table style="border-collapse: collapse; width: 100%;"> <table style="border-collapse: collapse; width: 100%;">
<thead> <thead>

View File

@ -140,6 +140,11 @@ const orderSchema = new mongoose.Schema(
paidAt: { paidAt: {
type: Date, type: Date,
}, },
isCouponUsed: {
type: Boolean,
default: false,
},
couponUsed: { type: mongoose.Schema.ObjectId, ref: "Affiliate" }, // Reference to the Coupon model
orderStatus: { orderStatus: {
type: String, type: String,