change coupon
This commit is contained in:
parent
422230ee05
commit
545c49b8c2
@ -2,7 +2,7 @@ import mongoose from "mongoose";
|
||||
const { Schema, model } = mongoose;
|
||||
|
||||
const couponUsedSchema = new Schema({
|
||||
userId: { type: String, required: true },
|
||||
userId: { type: mongoose.Schema.ObjectId, ref: "User", required: true },
|
||||
orderId: { type: String, required: true },
|
||||
couponCode: { type: String, required: true },
|
||||
date: { type: String, required: true },
|
||||
|
@ -106,12 +106,11 @@ export const listAffiliateCoupon = async (req, res) => {
|
||||
mobile: 1,
|
||||
}
|
||||
);
|
||||
for (let i = 0; i < coupon.length; i++) {
|
||||
if (coupon[i].is_coupon_active == false) {
|
||||
for (let i = 0; i < coupon?.length; i++) {
|
||||
if (coupon[i].is_coupon_active == true) {
|
||||
resArr.push(coupon[i]);
|
||||
}
|
||||
}
|
||||
// console.log(resArr);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: resArr,
|
||||
@ -216,39 +215,42 @@ export const getOneCoupon = async (req, res) => {
|
||||
|
||||
//Validate Coupon-----------------------
|
||||
export const validateCoupon = async (req, res) => {
|
||||
const { coupon } = req.params;
|
||||
|
||||
if (!coupon) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "Coupon code is required",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const { coupon } = req.params;
|
||||
// Check if coupon code is provided
|
||||
if (!coupon) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "Coupon code is required",
|
||||
});
|
||||
}
|
||||
|
||||
// Find the coupon data in the database
|
||||
const couponData = await AffiliateModel.findOne({ coupon_code: coupon });
|
||||
|
||||
// Check if coupon exists
|
||||
if (!couponData) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "Coupon not found",
|
||||
message: "Invalid coupon code",
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
return res.status(404).json({
|
||||
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 expirationDate = new Date(valid_till);
|
||||
|
||||
if (currentDate > expirationDate) {
|
||||
if (expirationDate <= currentDate) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "Coupon has expired",
|
||||
@ -256,10 +258,10 @@ export const validateCoupon = async (req, res) => {
|
||||
}
|
||||
|
||||
// If coupon is valid, return success response
|
||||
res.status(200).json({
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: "Coupon is valid",
|
||||
discount_amount: discount_amount,
|
||||
discount_amount,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@ -352,7 +354,7 @@ export const usedCoupon = async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
AffiliateModel.findByIdAndUpdate(
|
||||
await AffiliateModel.findByIdAndUpdate(
|
||||
_id,
|
||||
{
|
||||
$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) => {
|
||||
if (req.params?.id) {
|
||||
try {
|
||||
const saveData = await AffiliateModel.findById(req.params.id).sort({
|
||||
updatedAt: -1,
|
||||
});
|
||||
// console.log(saveData.coupon_used_history);
|
||||
const saveData = await AffiliateModel.findById(req.params.id)
|
||||
.populate({
|
||||
path: "coupon_used_history.userId",
|
||||
select: "name email",
|
||||
})
|
||||
|
||||
.sort({
|
||||
updatedAt: -1,
|
||||
});
|
||||
const resObj = {
|
||||
coupon_used_history: saveData.coupon_used_history,
|
||||
coupon_used_history: saveData?.coupon_used_history,
|
||||
coupon_code: saveData.coupon_code,
|
||||
};
|
||||
res.status(200).json({
|
||||
|
@ -5,11 +5,92 @@ import { Order } from "./orderModel.js";
|
||||
|
||||
import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js";
|
||||
import sendEmail from "../../Utils/sendEmail.js";
|
||||
import { AffiliateModel } from "../Affiliate&Coupon/Affiliate/AffiliateModel.js";
|
||||
const instance = new Razorpay({
|
||||
key_id: process.env.RAZERPAY_KEY_ID,
|
||||
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 currentYear = new Date().getFullYear();
|
||||
// Find the latest order to get the last serial number
|
||||
@ -56,20 +137,17 @@ export const getRazerpayKey = async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error in getRzpKey:", error);
|
||||
res
|
||||
.status(500)
|
||||
.json({
|
||||
success: false,
|
||||
message: error.message || "Internal server error",
|
||||
});
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message || "Internal server error",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const checkout = async (req, res) => {
|
||||
try {
|
||||
const { userr,address, cart, subtotal,orderType } = req.body;
|
||||
// console.log(req.body.cart[0].product);
|
||||
// console.log(req.body.cart[0].variant);
|
||||
const { userr, address, cart, subtotal, orderType, couponCode } = req.body;
|
||||
// console.log(req.body.cart[0].product);
|
||||
if (cart.length < 1)
|
||||
return res.status(400).json({ message: "cart is empty!" });
|
||||
if (!address)
|
||||
@ -84,13 +162,13 @@ 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
|
||||
}
|
||||
// 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);
|
||||
@ -210,6 +288,35 @@ export const checkout = async (req, res) => {
|
||||
razorpay_order_id: order?.id,
|
||||
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 {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
@ -249,11 +356,16 @@ export const paymentVerification = async (req, res) => {
|
||||
// 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);
|
||||
})
|
||||
.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
|
||||
});
|
||||
|
||||
if (findSameOrder) {
|
||||
(findSameOrder.razorpay_payment_id = razorpay_payment_id), // await Payment.create({
|
||||
(findSameOrder.isPaid = true),
|
||||
@ -266,7 +378,6 @@ export const paymentVerification = async (req, res) => {
|
||||
await findSameOrder.save();
|
||||
}
|
||||
//send email to customer
|
||||
// console.log("findSameOrder", findSameOrder);
|
||||
await sendEmail({
|
||||
to: `${findSameOrder?.user?.email}`, // Change to your recipient
|
||||
|
||||
@ -298,6 +409,14 @@ export const paymentVerification = async (req, res) => {
|
||||
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 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
@ -461,6 +580,14 @@ export const pospaymentVerification = async (req, res) => {
|
||||
? ", 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 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
<thead>
|
||||
@ -544,8 +671,8 @@ export const pospaymentVerification = async (req, res) => {
|
||||
// razorpay_signature,
|
||||
// });
|
||||
|
||||
res.redirect(`https://admin.smellika.com/#/pos`);
|
||||
// res.redirect(`http://localhost:3000/#/pos`);
|
||||
res.redirect(`https://admin.smellika.com/#/pos`);
|
||||
// res.redirect(`http://localhost:3000/#/pos`);
|
||||
} else {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
@ -601,7 +728,6 @@ export const handlePayment = async (req, res) => {
|
||||
shippingInfo: shipping,
|
||||
user: req.user._id,
|
||||
});
|
||||
console.log("fffffffff", order, "llllllllll");
|
||||
const lineItems = await cart.map((item) => ({
|
||||
price_data: {
|
||||
currency: "inr",
|
||||
|
@ -68,10 +68,15 @@ export const getSingleOrder = async (req, res) => {
|
||||
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",
|
||||
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",
|
||||
@ -149,10 +154,15 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
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",
|
||||
});
|
||||
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") {
|
||||
@ -170,7 +180,14 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
order?.orderID
|
||||
} 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>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
<thead>
|
||||
@ -261,6 +278,16 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
order?.shippingInfo?.first_Name
|
||||
},</strong>
|
||||
<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>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
<thead>
|
||||
@ -322,6 +349,7 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
<td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${
|
||||
order?.total_amount
|
||||
}</td>
|
||||
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@ -380,7 +408,14 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
req.body.TrackingID
|
||||
}</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>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
<thead>
|
||||
@ -472,6 +507,14 @@ export const updateOrderStatusById = async (req, res) => {
|
||||
<h3 style="color: #333; font-family: Arial, sans-serif;">Great news! Your order #${
|
||||
order?.orderID
|
||||
} 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>
|
||||
<table style="border-collapse: collapse; width: 100%;">
|
||||
<thead>
|
||||
|
@ -140,6 +140,11 @@ const orderSchema = new mongoose.Schema(
|
||||
paidAt: {
|
||||
type: Date,
|
||||
},
|
||||
isCouponUsed: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
couponUsed: { type: mongoose.Schema.ObjectId, ref: "Affiliate" }, // Reference to the Coupon model
|
||||
|
||||
orderStatus: {
|
||||
type: String,
|
||||
|
Loading…
Reference in New Issue
Block a user