import bodyParser from "body-parser"; import crypto from "crypto"; import Razorpay from "razorpay"; import { Order } from "./orderModel.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 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 getRzpkey = async (req, res) => { const { name, email } = req.user; res.status(200).json({ success: true, key: process.env.RAZERPAY_KEY_ID, name, email, }); }; export const checkout = async (req, res) => { try { const { address, cart, subtotal } = req.body; 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!" }); const options = { amount: Number(req.body.subtotal * 100), currency: "INR", }; const order = await instance.orders.create(options); //save order in database if (order?.id) { const { email } = req.user; if (!email) return res.status(400).send({ message: "Please enter the email" }); 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, }; // console.log("cart", cart[0]?.product?.gst); const orderItems = await cart.map((item) => ({ product: item.product._id, name: item.product.name, variant_Name: item?.variant?.variant_Name ? item?.variant?.variant_Name : "", price: Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ), total_price: item.quantity * Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ), image: item.product?.image, quantity: item?.quantity, gst_amount: Number( (Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ) * Number( item?.variant?.gst_Id?.tax ? item?.variant?.gst_Id?.tax : item?.product?.master_GST?.tax )) / 100 )?.toFixed(2), total_gst_amount: Number( Number(item?.quantity) * Number( (Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ) * Number( item?.variant?.gst_Id?.tax ? item?.variant?.gst_Id?.tax : item?.product?.master_GST?.tax )) / 100 ) )?.toFixed(2), gst_rate: item?.variant?.gst_Id?.tax ? item?.variant?.gst_Id?.tax : item?.product?.master_GST?.tax, tax_Name: item?.variant?.gst_Id?.name ? item?.variant?.gst_Id?.name : item?.product?.master_GST?.name, product_Subtotal: Number( Number( item.quantity * Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ) ) + Number( Number(item.quantity) * Number( (Number( item?.variant?.price ? item?.variant?.price : item?.product?.master_price ) * Number( item?.variant?.gst_Id?.tax ? item?.variant?.gst_Id?.tax : item?.product?.master_GST?.tax )) / 100 ) ) )?.toFixed(2), })); // console.log("line", lineItems[0]); const Id = await generateUniqueOrderId(); const orders = await Order.create({ orderID: Id, total_amount: subtotal, orderItems, shippingInfo: shipping, user: req.user._id, razorpay_order_id: order?.id, }); } else { return res.status(400).json({ success: false, message: "Failled to order Create", }); } return res.status(200).json({ success: true, order, }); } catch (error) { console.log("error", error); return res.status(400).json({ success: false, message: error?.description ? "Razorpay" + error?.description : "Something went wrong!", }); } }; export const paymentVerification = 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: `
Great news! Your order #${ findSameOrder?.orderID } has been confirmed. Here are the details
S No. | Product Name | Variant | Image | Quantity | Price | GST Amount | SubTotal |
---|---|---|---|---|---|---|---|
${ index + 1 } | ${ product.name } | ${ product?.variant_Name } | ${ product.quantity } | ₹${ product.price } | ₹${ product?.gst_amount } | ₹${ product?.product_Subtotal } | |
Total Amount : | ₹${ findSameOrder?.total_amount } |
Great news! Your order #${findOrder?.orderID} has been confirmed. Here are the details