From 99e80b1ff57c48a116f96c6c2f7a50f4beb8d8b0 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Mon, 30 Sep 2024 16:39:45 +0530 Subject: [PATCH 1/3] get all rd with total orders --- .../RetailDistributerRoutes.js | 8 + .../RetailDistributorController.js | 147 +++++++++++++++++- 2 files changed, 154 insertions(+), 1 deletion(-) diff --git a/resources/RetailDistributor/RetailDistributerRoutes.js b/resources/RetailDistributor/RetailDistributerRoutes.js index 2da3d94..5b10768 100644 --- a/resources/RetailDistributor/RetailDistributerRoutes.js +++ b/resources/RetailDistributor/RetailDistributerRoutes.js @@ -6,6 +6,7 @@ import { getAllRDbyscid, getAllRDbytmid, getAllRetailDistributorApproved, + getAllRetailDistributorwithTotalorder, getmyProfileRD, getRDId, loginRD, @@ -36,6 +37,13 @@ router authorizeRoles("admin"), getAllRetailDistributorApproved ); + router + .route("/getAllRDandorder") + .get( + isAuthenticatedUser, + authorizeRoles("admin"), + getAllRetailDistributorwithTotalorder + ); router .route("/getRD/:id") .get(isAuthenticatedUser, authorizeRoles("admin"), getRDId); diff --git a/resources/RetailDistributor/RetailDistributorController.js b/resources/RetailDistributor/RetailDistributorController.js index 6ca8102..c9ac22e 100644 --- a/resources/RetailDistributor/RetailDistributorController.js +++ b/resources/RetailDistributor/RetailDistributorController.js @@ -3,7 +3,7 @@ import RetailDistributor from "./RetailDistributorModel.js"; import validator from "validator"; import password from "secure-random-password"; import crypto from "crypto"; - +import { RdOrder } from "../RD_Ordes/rdOrderModal.js"; import sendEmail, { sendOtp } from "../../Utils/sendEmail.js"; export const loginRD = async (req, res) => { const { email, password } = req.body; @@ -425,6 +425,151 @@ export const getAllRetailDistributorApproved = async (req, res) => { res.status(500).json({ message: "Server Error", error }); } }; +export const getAllRetailDistributorwithTotalorder = async (req, res) => { + try { + const { + page = 1, + show = 10, + tradename, + name, + mobile_number, + principaldistributor, + } = req.query; + const skip = (page - 1) * show; + + // Build the aggregation pipeline + let pipeline = [ + { + $lookup: { + from: "kycs", // KYC collection + localField: "kyc", + foreignField: "_id", + as: "kycDetails", + }, + }, + { $unwind: { path: "$kycDetails", preserveNullAndEmptyArrays: true } }, + { + $lookup: { + from: "users", // Principal Distributor collection + localField: "principal_distributer", + foreignField: "_id", + as: "principalDetails", + }, + }, + { + $unwind: { + path: "$principalDetails", + preserveNullAndEmptyArrays: true, + }, + }, + { + $lookup: { + from: "territorymanagers", // Territory Manager collection + localField: "mappedTM", + foreignField: "_id", + as: "mappedTMDetails", + }, + }, + { + $unwind: { path: "$mappedTMDetails", preserveNullAndEmptyArrays: true }, + }, + { + $lookup: { + from: "salescoordinators", // Sales Coordinator collection + localField: "mappedSC", + foreignField: "_id", + as: "mappedSCDetails", + }, + }, + { + $unwind: { path: "$mappedSCDetails", preserveNullAndEmptyArrays: true }, + }, + ]; + + // Add filters based on query parameters + const matchConditions = {}; + if (tradename) + matchConditions["kycDetails.trade_name"] = new RegExp(tradename, "i"); + if (name) matchConditions["name"] = new RegExp(name, "i"); + if (mobile_number) + matchConditions["mobile_number"] = new RegExp(mobile_number, "i"); + if (principaldistributor) + matchConditions["principalDetails.name"] = new RegExp( + principaldistributor, + "i" + ); + + if (Object.keys(matchConditions).length) { + pipeline.push({ $match: matchConditions }); + } + + // Project required fields early + pipeline.push({ + $project: { + _id: 1, + uniqueId: 1, + name: 1, + mobile_number: 1, + email: 1, + "kycDetails.trade_name": 1, + "principalDetails.name": 1, + "mappedTMDetails.name": 1, + "mappedSCDetails.name": 1, + createdAt: 1, + }, + }); + + // Pagination and sorting + pipeline.push({ $sort: { createdAt: -1 } }); + pipeline.push({ $skip: skip }); + pipeline.push({ $limit: parseInt(show) }); + + // Execute the main aggregation pipeline + const Retaildistributor = await RetailDistributor.aggregate(pipeline); + + // Aggregate orders data for each distributor + const orderStats = await RdOrder.aggregate([ + { + $match: { addedBy: { $in: Retaildistributor.map((user) => user._id) } }, + }, + { + $group: { + _id: "$addedBy", // Group by distributor ID + totalOrders: { $sum: 1 }, // Count total orders + lastOrderDate: { $max: "$createdAt" }, // Get last order date + }, + }, + ]); + + // Combine order stats with Retaildistributor data + const usersWithOrderStats = Retaildistributor.map((user) => { + const orderData = orderStats.find( + (order) => order._id.toString() === user._id.toString() + ); + return { + ...user, + totalOrders: orderData ? orderData.totalOrders : 0, + lastOrderDate: orderData ? orderData.lastOrderDate : null, + }; + }); + + // Get total count of documents matching the query + const countPipeline = [{ $match: matchConditions }, { $count: "total" }]; + const total_data = await RetailDistributor.aggregate(countPipeline); + const totalCount = total_data[0]?.total || 0; + + // Send the response + res.status(200).json({ + success: true, + total_data: totalCount, + total_pages: Math.ceil(totalCount / show), + Retaildistributor: usersWithOrderStats, + }); + } catch (error) { + console.error(error); + res.status(500).json({ message: "Server Error", error }); + } +}; //get RD by Id export const getRDId = async (req, res) => { From 68f120e854acfb832c47045454f72715ca90c251 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Mon, 30 Sep 2024 16:55:36 +0530 Subject: [PATCH 2/3] fix --- resources/RD_Ordes/rdOrderRoutes.js | 1 - 1 file changed, 1 deletion(-) diff --git a/resources/RD_Ordes/rdOrderRoutes.js b/resources/RD_Ordes/rdOrderRoutes.js index 6734ebc..37ed5b0 100644 --- a/resources/RD_Ordes/rdOrderRoutes.js +++ b/resources/RD_Ordes/rdOrderRoutes.js @@ -20,7 +20,6 @@ import { updateCourierStatusToDispatchedForPD, } from "./rdOrderController.js"; import { isAuthenticatedRD } from "../../middlewares/rdAuth.js"; -import { isAuthenticatedUser } from "../../middlewares/auth.js"; import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; const router = express.Router(); From 3e7452a484b42f7546da6e9f58fe5a77990dfaef Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Thu, 3 Oct 2024 12:02:58 +0530 Subject: [PATCH 3/3] rd order andpd order fixed --- resources/PD_Orders/pdOrderController.js | 10 +++++++--- resources/RD_Ordes/rdOrderController.js | 18 ++++++++++++++++++ resources/RD_Ordes/rdOrderRoutes.js | 5 ++++- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/resources/PD_Orders/pdOrderController.js b/resources/PD_Orders/pdOrderController.js index d97e941..e00ddf0 100644 --- a/resources/PD_Orders/pdOrderController.js +++ b/resources/PD_Orders/pdOrderController.js @@ -1477,11 +1477,15 @@ export const getAllOrdersByDistributor = async (req, res) => { export const gettotalorderandvalueofpd = async (req, res) => { const { distributorId } = req.params; try { - const orders = await PdOrder.find({ addedBy: distributorId }); + const orders = await PdOrder.find({ addedBy: distributorId }).sort({ createdAt: -1 }); + const totalOrders = orders.length; - const totalValue = orders.reduce((acc, order) => acc + order.grandTotal, 0); + const totalValue = orders.reduce((acc, order) => acc + order.grandTotal, 0).toFixed(2); + + // Get the date of the last order + const lastPurchaseOrderDate = totalOrders > 0 ? orders[0].createdAt : null; - res.status(200).json({ totalOrders, totalValue }); + res.status(200).json({ totalOrders, totalValue: parseFloat(totalValue), lastPurchaseOrderDate }); } catch (error) { console.error("Error fetching orders:", error); res.status(500).json({ message: "Server error", error }); diff --git a/resources/RD_Ordes/rdOrderController.js b/resources/RD_Ordes/rdOrderController.js index e113748..fa611fd 100644 --- a/resources/RD_Ordes/rdOrderController.js +++ b/resources/RD_Ordes/rdOrderController.js @@ -1535,3 +1535,21 @@ export const getAllOrdersByDistributor = async (req, res) => { res.status(500).json({ message: "Server error", error }); } }; + +export const gettotalorderandvalueofrd = async (req, res) => { + const { distributorId } = req.params; + try { + const orders = await RdOrder.find({ addedBy: distributorId }).sort({ createdAt: -1 }); + + const totalOrders = orders.length; + const totalValue = orders.reduce((acc, order) => acc + order.grandTotal, 0).toFixed(2); + + // Get the date of the last order + const lastPurchaseOrderDate = totalOrders > 0 ? orders[0].createdAt : null; + + res.status(200).json({ totalOrders, totalValue: parseFloat(totalValue), lastPurchaseOrderDate }); + } catch (error) { + console.error("Error fetching orders:", error); + res.status(500).json({ message: "Server error", error }); + } +}; \ No newline at end of file diff --git a/resources/RD_Ordes/rdOrderRoutes.js b/resources/RD_Ordes/rdOrderRoutes.js index 37ed5b0..c61a671 100644 --- a/resources/RD_Ordes/rdOrderRoutes.js +++ b/resources/RD_Ordes/rdOrderRoutes.js @@ -15,6 +15,7 @@ import { getProcessingInvoicesForPd, getSinglePlacedOrderForPD, getSinglePlacedOrderForRD, + gettotalorderandvalueofrd, processOrder, updateCourierStatusToDeliveredForPD, updateCourierStatusToDispatchedForPD, @@ -80,5 +81,7 @@ router.route("/invoice/delivered/:invoiceId").put( updateCourierStatusToDeliveredForPD ); - +router +.route("/single-rd-ordercount/:distributorId") +.get(isAuthenticatedUser, authorizeRoles("admin"), gettotalorderandvalueofrd); export default router;