diff --git a/resources/Inventory/InventoryController.js b/resources/Inventory/InventoryController.js index 4b2a151..c2a7e8b 100644 --- a/resources/Inventory/InventoryController.js +++ b/resources/Inventory/InventoryController.js @@ -5,6 +5,7 @@ import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js"; import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js"; import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js"; import crypto from "crypto"; +import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js"; // Add inventory data export const addInventory = async (req, res) => { try { @@ -45,7 +46,7 @@ export const getDistributors = async (req, res) => { return res.status(400).json({ message: "Invalid distributor type" }); } let filter = { role: "principal-Distributor" }; - let query={status: "approved"}; + let query={}; // Check the user type and adjust the filter accordingly if (req.userType === "SalesCoOrdinator") { // If userType is "SalesCoOrdinator", filter by req.user.mappedBy @@ -56,8 +57,6 @@ export const getDistributors = async (req, res) => { filter.mappedby = req.user._id; query.mappedTM = req.user._id; } - console.log("filter",filter); - console.log("query",query); let distributors; // console.log("type",type); if (type === "PrincipalDistributor") { @@ -78,7 +77,7 @@ export const getDistributors = async (req, res) => { ); } else { // For RetailDistributor, fetch approved KYC documents - distributors = await KYC.find(query); + distributors = await RetailDistributor.find(query).populate("kyc"); } res.status(200).json(distributors); diff --git a/resources/RetailDistributor/RetailDistributerRoutes.js b/resources/RetailDistributor/RetailDistributerRoutes.js index e60e831..2da3d94 100644 --- a/resources/RetailDistributor/RetailDistributerRoutes.js +++ b/resources/RetailDistributor/RetailDistributerRoutes.js @@ -2,6 +2,7 @@ import express from "express"; import { ChangePasswordRD, forgotPasswordRD, + getAllRDbypdid, getAllRDbyscid, getAllRDbytmid, getAllRetailDistributorApproved, @@ -42,9 +43,12 @@ router router .route("/getAllRDbytmid/:mappedTMId") .get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbytmid); - router +router .route("/getAllRDbyscid/:mappedSCId") .get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbyscid); +router + .route("/getAllRDbypdid/:mappedPDId") + .get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbypdid); router .route("/mapped/:id") .put(isAuthenticatedUser, authorizeRoles("admin"), updateRDMapped); diff --git a/resources/RetailDistributor/RetailDistributorController.js b/resources/RetailDistributor/RetailDistributorController.js index b7dd090..1a22e4a 100644 --- a/resources/RetailDistributor/RetailDistributorController.js +++ b/resources/RetailDistributor/RetailDistributorController.js @@ -710,7 +710,7 @@ export const getAllRDbyscid = async (req, res) => { try { mappedSCObjectId = mongoose.Types.ObjectId(mappedSCId); } catch (error) { - return res.status(400).json({ message: "Invalid mappedTM ID format" }); + return res.status(400).json({ message: "Invalid mappedSC ID format" }); } const skip = (page - 1) * show; @@ -931,11 +931,226 @@ export const getAllRDbyscid = async (req, res) => { res.status(500).json({ message: "Server Error", error }); } }; +export const getAllRDbypdid = async (req, res) => { + try { + // Extract query parameters + const { page = 1, show = 10, tradename, name, mobile_number } = req.query; + const { mappedPDId } = req.params; // Extract mappedTM ID from request params + + // Convert mappedPDId to ObjectId if it's a valid ObjectId string + let mappedPDObjectId; + try { + mappedPDObjectId = mongoose.Types.ObjectId(mappedPDId); + } catch (error) { + return res.status(400).json({ message: "Invalid mappedPD ID format" }); + } + + const skip = (page - 1) * show; + + // Build the aggregation pipeline + let pipeline = [ + { + $match: { + principal_distributer: mappedPDObjectId, // Filter by principal_distributer ObjectId + }, + }, + { + $lookup: { + from: "kycs", // Assuming your KYC collection is named "kycs" + localField: "kyc", + foreignField: "_id", + as: "kycDetails", + }, + }, + { $unwind: { path: "$kycDetails", preserveNullAndEmptyArrays: true } }, // Unwind kycDetails and allow null/empty arrays + { + $lookup: { + from: "users", // Assuming your User collection is named "users" + localField: "principal_distributer", + foreignField: "_id", + as: "principalDetails", + }, + }, + { + $unwind: { + path: "$principalDetails", + preserveNullAndEmptyArrays: true, + }, + }, // Unwind principalDetails and allow null/empty arrays + + // Lookup for mappedTM (Territory Manager) + { + $lookup: { + from: "territorymanagers", // Assuming your Territory Manager collection + localField: "mappedTM", + foreignField: "_id", + as: "mappedTMDetails", + }, + }, + { + $unwind: { path: "$mappedTMDetails", preserveNullAndEmptyArrays: true }, + }, // Unwind mappedTMDetails and allow null/empty arrays + + // Lookup for mappedSC (Sales Coordinator) + { + $lookup: { + from: "salescoordinators", // Assuming your Sales Coordinator collection + localField: "mappedSC", + foreignField: "_id", + as: "mappedSCDetails", + }, + }, + { + $unwind: { path: "$mappedSCDetails", preserveNullAndEmptyArrays: true }, + }, // Unwind mappedSCDetails and allow null/empty arrays + + // Filter to ensure data exists in kyc or principalDetails + { + $match: { + $or: [ + { "kycDetails.trade_name": { $exists: true } }, // Ensure KYC exists + { "principalDetails.name": { $exists: true } }, // Ensure Principal Distributor exists + ], + }, + }, + ]; + + // Add filters based on query parameters + + // Filter by KYC trade_name (case-insensitive) + if (tradename) { + pipeline.push({ + $match: { "kycDetails.trade_name": new RegExp(tradename, "i") }, + }); + } + + // Filter by name (RetailDistributor model's name) + if (name) { + pipeline.push({ + $match: { name: new RegExp(name, "i") }, // Case-insensitive search for name + }); + } + + // Filter by mobile_number (RetailDistributor model's mobile number) + if (mobile_number) { + pipeline.push({ + $match: { mobile_number: new RegExp(mobile_number, "i") }, // Case-insensitive search for mobile_number + }); + } + + // Project only the required fields + pipeline.push({ + $project: { + _id: 1, // RetailDistributor ID + uniqueId: 1, // RetailDistributor uniqueId + name: 1, // RetailDistributor name + mobile_number: 1, // RetailDistributor mobile_number + email: 1, // RetailDistributor email + "kycDetails.trade_name": 1, // Only trade_name from kyc + "mappedTMDetails.name": 1, // Only name from mappedTM (Territory Manager) + "mappedSCDetails.name": 1, // Only name from mappedSC (Sales Coordinator) + "principalDetails.name": 1, // Only name from principal_distributer + createdAt: 1, // For sorting + }, + }); + + // Pagination and sorting + pipeline.push({ $sort: { createdAt: -1 } }); + pipeline.push({ $skip: skip }); + pipeline.push({ $limit: parseInt(show) }); + + // Execute the aggregation pipeline + const Retaildistributor = await RetailDistributor.aggregate(pipeline); + + // Get total count of documents matching the query + const countPipeline = [ + { + $match: { + principal_distributer: mappedPDObjectId, // Filter by mappedTM ObjectId + }, + }, + { + $lookup: { + from: "kycs", + localField: "kyc", + foreignField: "_id", + as: "kycDetails", + }, + }, + { $unwind: { path: "$kycDetails", preserveNullAndEmptyArrays: true } }, + { + $lookup: { + from: "users", + localField: "principal_distributer", + foreignField: "_id", + as: "principalDetails", + }, + }, + { + $unwind: { + path: "$principalDetails", + preserveNullAndEmptyArrays: true, + }, + }, + { + $match: { + $or: [ + { "kycDetails.trade_name": { $exists: true } }, + { "principalDetails.name": { $exists: true } }, + ], + }, + }, + ]; + + // Apply search filters to count query + + // Filter by KYC trade_name + if (tradename) { + countPipeline.push({ + $match: { "kycDetails.trade_name": new RegExp(tradename, "i") }, + }); + } + + // Filter by name + if (name) { + countPipeline.push({ + $match: { name: new RegExp(name, "i") }, + }); + } + + // Filter by mobile_number + if (mobile_number) { + countPipeline.push({ + $match: { mobile_number: new RegExp(mobile_number, "i") }, + }); + } + + // Get the total count of filtered documents + const total_data = await RetailDistributor.aggregate([ + ...countPipeline, + { $count: "total" }, + ]); + + const totalCount = total_data[0]?.total || 0; // Ensure count is zero if no data found + + // Send the response with pagination data + res.status(200).json({ + success: true, + total_data: totalCount, + total_pages: Math.ceil(totalCount / show), + Retaildistributor, + }); + } catch (error) { + console.error(error); + res.status(500).json({ message: "Server Error", error }); + } +}; + export const updateRDMapped = async (req, res) => { try { const { id } = req.params; const { principal_distributor, mappedTM, mappedSC } = req.body; - + console.log(principal_distributor); // Find the RetailDistributor document by ID const RD = await RetailDistributor.findById(id); @@ -985,7 +1200,7 @@ export const updateunmapRD = async (req, res) => { if (principal_distributor) { RD.principal_distributer = null; } - if (mappedTM ) { + if (mappedTM) { RD.mappedTM = null; } if (mappedSC) { diff --git a/resources/SalesCoOrdinators/SalesCoOrdinatorController.js b/resources/SalesCoOrdinators/SalesCoOrdinatorController.js index c5f6556..56cce6d 100644 --- a/resources/SalesCoOrdinators/SalesCoOrdinatorController.js +++ b/resources/SalesCoOrdinators/SalesCoOrdinatorController.js @@ -200,6 +200,7 @@ export const getAllSalesCoOrdinator = async (req, res) => { } const total = await SalesCoOrdinator.countDocuments(filter); const salesCoOrinators = await SalesCoOrdinator.find(filter) + .populate("mappedby", "name") .limit(PAGE_SIZE) .skip(PAGE_SIZE * page) .sort({ createdAt: -1 }); @@ -285,6 +286,7 @@ export const getAllSalesCoOrdinatorbytmId = async (req, res) => { const total = await SalesCoOrdinator.countDocuments(filter); const salesCoOrinators = await SalesCoOrdinator.find(filter) + .populate("mappedby", "name") .limit(PAGE_SIZE) .skip(PAGE_SIZE * page) .sort({ createdAt: -1 }); diff --git a/resources/SalesCoOrdinators/SalesCoOrdinatorRoute.js b/resources/SalesCoOrdinators/SalesCoOrdinatorRoute.js index e37a7da..a543544 100644 --- a/resources/SalesCoOrdinators/SalesCoOrdinatorRoute.js +++ b/resources/SalesCoOrdinators/SalesCoOrdinatorRoute.js @@ -41,6 +41,7 @@ router.get( isAuthenticatedTerritoryManager, getAllSalesCoOrdinatorforTM_App ); +// mapping start router.get( "/getbyTmId/:id", isAuthenticatedUser, @@ -59,6 +60,7 @@ router.delete( authorizeRoles("admin"), unmapSalesCoOrdinator ); +// mapping end router.get( "/getOne/:id", isAuthenticatedUser, diff --git a/resources/user/userController.js b/resources/user/userController.js index d719e01..3ec8cf6 100644 --- a/resources/user/userController.js +++ b/resources/user/userController.js @@ -1024,6 +1024,8 @@ export const getAllUser = catchAsyncErrors(async (req, res, next) => { // Find users with the filter, pagination, and sorting const users = await User.find(filter) + .populate("mappedby", "name") + .populate("mappedbySC", "name") .sort({ createdAt: -1 }) .skip(skip) .limit(limit); diff --git a/resources/user/userRoute.js b/resources/user/userRoute.js index 4fc11c1..e54953a 100644 --- a/resources/user/userRoute.js +++ b/resources/user/userRoute.js @@ -44,6 +44,7 @@ router authorizeRoles("admin"), uploadPrincipaldistributors ); + //mapping start router .route("/admin/users") .get(isAuthenticatedUser, authorizeRoles("admin", "Employee"), getAllUser); @@ -85,6 +86,7 @@ router.patch( authorizeRoles("admin"), unmappedSCinPrincipalDistributor ); +//mapping end router .route("/admin/delete-employee/:id") .delete(