mapped SC with RD

This commit is contained in:
Sibunnayak 2024-09-10 16:02:06 +05:30
parent 264cf42a57
commit 38a5fde457
2 changed files with 242 additions and 0 deletions

View File

@ -2,6 +2,7 @@ import express from "express";
import { import {
ChangePasswordRD, ChangePasswordRD,
forgotPasswordRD, forgotPasswordRD,
getAllRDbyscid,
getAllRDbytmid, getAllRDbytmid,
getAllRetailDistributorApproved, getAllRetailDistributorApproved,
getmyProfileRD, getmyProfileRD,
@ -41,6 +42,9 @@ router
router router
.route("/getAllRDbytmid/:mappedTMId") .route("/getAllRDbytmid/:mappedTMId")
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbytmid); .get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbytmid);
router
.route("/getAllRDbyscid/:mappedSCId")
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbyscid);
router router
.route("/mapped/:id") .route("/mapped/:id")
.put(isAuthenticatedUser, authorizeRoles("admin"), updateRDMapped); .put(isAuthenticatedUser, authorizeRoles("admin"), updateRDMapped);

View File

@ -692,7 +692,245 @@ export const getAllRDbytmid = async (req, res) => {
res.status(500).json({ message: "Server Error", error }); res.status(500).json({ message: "Server Error", error });
} }
}; };
export const getAllRDbyscid = async (req, res) => {
try {
// Extract query parameters
const {
page = 1,
show = 10,
tradename,
name,
mobile_number,
principaldistributor,
} = req.query;
const { mappedSCId } = req.params; // Extract mappedTM ID from request params
// Convert mappedSCId to ObjectId if it's a valid ObjectId string
let mappedSCObjectId;
try {
mappedSCObjectId = mongoose.Types.ObjectId(mappedSCId);
} catch (error) {
return res.status(400).json({ message: "Invalid mappedTM ID format" });
}
const skip = (page - 1) * show;
// Build the aggregation pipeline
let pipeline = [
{
$match: {
mappedSC: mappedSCObjectId, // Filter by mappedSC 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 principal_distributer name (case-insensitive)
if (principaldistributor) {
pipeline.push({
$match: {
"principalDetails.name": new RegExp(principaldistributor, "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
"principalDetails.name": 1, // Only name from principal_distributer
"mappedTMDetails.name": 1, // Only name from mappedTM (Territory Manager)
"mappedSCDetails.name": 1, // Only name from mappedSC (Sales Coordinator)
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: {
mappedSC: mappedSCObjectId, // 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 principal_distributer name
if (principaldistributor) {
countPipeline.push({
$match: {
"principalDetails.name": new RegExp(principaldistributor, "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) => { export const updateRDMapped = async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;