From 99e80b1ff57c48a116f96c6c2f7a50f4beb8d8b0 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Mon, 30 Sep 2024 16:39:45 +0530 Subject: [PATCH] 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) => {