mapped TM with RD
This commit is contained in:
parent
b76d9b3c6d
commit
c77851d5f7
@ -569,87 +569,4 @@ export const saveFCMTokenForTM = async (req, res) => {
|
|||||||
res.status(500).send("Internal Server Error");
|
res.status(500).send("Internal Server Error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
export const getAllKycApprovedbytmid = async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { id } = req.params; // Extracting `mappedTM` ID from req.params
|
|
||||||
|
|
||||||
// Extract query parameters with default values
|
|
||||||
const { tradename, page = 1, show = 10 } = req.query;
|
|
||||||
const skip = (page - 1) * show;
|
|
||||||
|
|
||||||
// Build query object
|
|
||||||
const query = { status: "approved", mappedTM: id };
|
|
||||||
if (tradename) {
|
|
||||||
query.trade_name = new RegExp(tradename, "i");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch KYC records with pagination and population
|
|
||||||
const retaildistributor = await KYC.find(query)
|
|
||||||
.sort({ createdAt: -1 })
|
|
||||||
.populate("principal_distributer")
|
|
||||||
.populate("mappedTM")
|
|
||||||
.populate("mappedSC")
|
|
||||||
.populate("addedBy")
|
|
||||||
.skip(skip)
|
|
||||||
.limit(parseInt(show));
|
|
||||||
|
|
||||||
// Get total count of documents matching the query
|
|
||||||
const total_data = await KYC.countDocuments(query);
|
|
||||||
|
|
||||||
// Calculate total pages
|
|
||||||
const total_pages = Math.ceil(total_data / show);
|
|
||||||
|
|
||||||
// Send the response
|
|
||||||
res.status(200).json({
|
|
||||||
success: true,
|
|
||||||
total_data: total_data,
|
|
||||||
total_pages: total_pages,
|
|
||||||
retaildistributor,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
// Handle any errors that occur during the fetch operation
|
|
||||||
console.error(error);
|
|
||||||
res.status(500).json({ message: "Server Error", error });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const updateKYCMapped = async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { id } = req.params; // KYC document ID from params
|
|
||||||
const { principal_distributor, mappedTM, mappedSC } = req.body; // Fields to update from the request body
|
|
||||||
|
|
||||||
// Find the KYC document by ID
|
|
||||||
const kyc = await KYC.findById(id);
|
|
||||||
|
|
||||||
// If KYC not found, return 404
|
|
||||||
if (!kyc) {
|
|
||||||
return res.status(404).json({ message: "KYC record not found" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update the fields only if they are provided in the request body
|
|
||||||
if (principal_distributor) {
|
|
||||||
kyc.principal_distributer = principal_distributor;
|
|
||||||
}
|
|
||||||
if (mappedTM) {
|
|
||||||
kyc.mappedTM = mappedTM;
|
|
||||||
}
|
|
||||||
if (mappedSC) {
|
|
||||||
kyc.mappedSC = mappedSC;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save the updated KYC document
|
|
||||||
await kyc.save();
|
|
||||||
|
|
||||||
// Send the updated KYC data as a response
|
|
||||||
res.status(200).json({
|
|
||||||
message: "KYC record updated successfully",
|
|
||||||
data: kyc,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
// Handle any errors during the update
|
|
||||||
res.status(500).json({
|
|
||||||
message: "Error updating KYC record",
|
|
||||||
error: error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
@ -7,13 +7,11 @@ import {
|
|||||||
createretaildistributor,
|
createretaildistributor,
|
||||||
getAllKyc,
|
getAllKyc,
|
||||||
getAllKycApproved,
|
getAllKycApproved,
|
||||||
getAllKycApprovedbytmid,
|
|
||||||
getAllKycRejected,
|
getAllKycRejected,
|
||||||
getAllPrincipalDistributers,
|
getAllPrincipalDistributers,
|
||||||
getKycById,
|
getKycById,
|
||||||
saveFCMTokenForSC,
|
saveFCMTokenForSC,
|
||||||
saveFCMTokenForTM,
|
saveFCMTokenForTM,
|
||||||
updateKYCMapped,
|
|
||||||
updateKycStatus,
|
updateKycStatus,
|
||||||
} from "./KycController.js";
|
} from "./KycController.js";
|
||||||
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
||||||
@ -78,11 +76,4 @@ router
|
|||||||
router
|
router
|
||||||
.route("/kyc/save-fcm-tm/")
|
.route("/kyc/save-fcm-tm/")
|
||||||
.post(isAuthenticatedTerritoryManager, saveFCMTokenForTM);
|
.post(isAuthenticatedTerritoryManager, saveFCMTokenForTM);
|
||||||
//mapping part
|
|
||||||
router
|
|
||||||
.route("/kyc/getAllapprovedbytmid/:id")
|
|
||||||
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllKycApprovedbytmid);
|
|
||||||
router
|
|
||||||
.route("/kyc/mapped/:id")
|
|
||||||
.get(isAuthenticatedUser, authorizeRoles("admin"), updateKYCMapped);
|
|
||||||
export default router;
|
export default router;
|
||||||
|
@ -2,11 +2,17 @@ import express from "express";
|
|||||||
import {
|
import {
|
||||||
ChangePasswordRD,
|
ChangePasswordRD,
|
||||||
forgotPassword,
|
forgotPassword,
|
||||||
|
getAllRDbytmid,
|
||||||
|
getAllRetailDistributorApproved,
|
||||||
getmyProfile,
|
getmyProfile,
|
||||||
|
getRDId,
|
||||||
loginRD,
|
loginRD,
|
||||||
UpdateProfile,
|
UpdateProfile,
|
||||||
|
updateRDMapped,
|
||||||
|
updateunmapRD,
|
||||||
} from "./RetailDistributorController.js";
|
} from "./RetailDistributorController.js";
|
||||||
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
|
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
|
||||||
|
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@ -25,4 +31,25 @@ router.patch(
|
|||||||
|
|
||||||
UpdateProfile
|
UpdateProfile
|
||||||
);
|
);
|
||||||
|
//admin and maping
|
||||||
|
router
|
||||||
|
.route("/getAllRD")
|
||||||
|
.get(
|
||||||
|
isAuthenticatedUser,
|
||||||
|
authorizeRoles("admin"),
|
||||||
|
getAllRetailDistributorApproved
|
||||||
|
);
|
||||||
|
router
|
||||||
|
.route("/getRD/:id")
|
||||||
|
.get(isAuthenticatedUser, authorizeRoles("admin"), getRDId);
|
||||||
|
//mapping part
|
||||||
|
router
|
||||||
|
.route("/getAllRDbytmid/:mappedTMId")
|
||||||
|
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllRDbytmid);
|
||||||
|
router
|
||||||
|
.route("/mapped/:id")
|
||||||
|
.put(isAuthenticatedUser, authorizeRoles("admin"), updateRDMapped);
|
||||||
|
router
|
||||||
|
.route("/unmap/:id")
|
||||||
|
.patch(isAuthenticatedUser, authorizeRoles("admin"), updateunmapRD);
|
||||||
export default router;
|
export default router;
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
import RetailDistributor from "./RetailDistributorModel.js";
|
import RetailDistributor from "./RetailDistributorModel.js";
|
||||||
import validator from "validator";
|
import validator from "validator";
|
||||||
export const loginRD = async (req, res) => {
|
export const loginRD = async (req, res) => {
|
||||||
@ -216,3 +217,567 @@ export const getmyProfile = async (req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//reatil distributor mapping
|
||||||
|
export const getAllRetailDistributorApproved = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Extract query parameters
|
||||||
|
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", // 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 = [
|
||||||
|
{
|
||||||
|
$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 });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
//get RD by Id
|
||||||
|
export const getRDId = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
console.log(id);
|
||||||
|
// Fetch the KYC document from the database by ID
|
||||||
|
const RD = await RetailDistributor.findById(id)
|
||||||
|
.populate("principal_distributer", "name")
|
||||||
|
.populate("addedBy")
|
||||||
|
.populate("kyc")
|
||||||
|
.populate("mappedTM")
|
||||||
|
.populate("mappedSC");
|
||||||
|
|
||||||
|
// Check if the KYC document exists
|
||||||
|
if (!RD) {
|
||||||
|
return res.status(404).json({ message: "No RetailDistributor found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the fetched KYC document as a response
|
||||||
|
res.status(200).json(RD);
|
||||||
|
} catch (error) {
|
||||||
|
// Handle any errors that occur during the fetch operation
|
||||||
|
res.status(500).json({ message: "Server Error", error });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
//mapping
|
||||||
|
|
||||||
|
export const getAllRDbytmid = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Extract query parameters
|
||||||
|
const {
|
||||||
|
page = 1,
|
||||||
|
show = 10,
|
||||||
|
tradename,
|
||||||
|
name,
|
||||||
|
mobile_number,
|
||||||
|
principaldistributor,
|
||||||
|
} = req.query;
|
||||||
|
const { mappedTMId } = req.params; // Extract mappedTM ID from request params
|
||||||
|
|
||||||
|
// Convert mappedTMId to ObjectId if it's a valid ObjectId string
|
||||||
|
let mappedTMObjectId;
|
||||||
|
try {
|
||||||
|
mappedTMObjectId = mongoose.Types.ObjectId(mappedTMId);
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(400).json({ message: "Invalid mappedTM ID format" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const skip = (page - 1) * show;
|
||||||
|
|
||||||
|
// Build the aggregation pipeline
|
||||||
|
let pipeline = [
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
mappedTM: mappedTMObjectId, // Filter by mappedTM 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: {
|
||||||
|
mappedTM: mappedTMObjectId, // 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) => {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { principal_distributor, mappedTM, mappedSC } = req.body;
|
||||||
|
|
||||||
|
// Find the RetailDistributor document by ID
|
||||||
|
const RD = await RetailDistributor.findById(id);
|
||||||
|
|
||||||
|
if (!RD) {
|
||||||
|
return res.status(404).json({ message: "RetailDistributor not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the fields if provided in the request body
|
||||||
|
if (principal_distributor) {
|
||||||
|
RD.principal_distributer = principal_distributor;
|
||||||
|
}
|
||||||
|
if (mappedTM) {
|
||||||
|
RD.mappedTM = mappedTM;
|
||||||
|
}
|
||||||
|
if (mappedSC) {
|
||||||
|
RD.mappedSC = mappedSC;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the updated document
|
||||||
|
await RD.save();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
message: "RetailDistributor record updated successfully",
|
||||||
|
data: RD,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Handle any errors during the update
|
||||||
|
res.status(500).json({
|
||||||
|
message: "Error updating RD record",
|
||||||
|
error: error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
export const updateunmapRD = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { principal_distributor, mappedTM, mappedSC } = req.body;
|
||||||
|
|
||||||
|
// Find the RetailDistributor document by ID
|
||||||
|
const RD = await RetailDistributor.findById(id);
|
||||||
|
|
||||||
|
if (!RD) {
|
||||||
|
return res.status(404).json({ message: "RetailDistributor not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the fields if provided in the request body
|
||||||
|
if (principal_distributor) {
|
||||||
|
RD.principal_distributer = null;
|
||||||
|
}
|
||||||
|
if (mappedTM ) {
|
||||||
|
RD.mappedTM = null;
|
||||||
|
}
|
||||||
|
if (mappedSC) {
|
||||||
|
RD.mappedSC = null;
|
||||||
|
}
|
||||||
|
// Save the updated document
|
||||||
|
await RD.save();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
message: "RetailDistributor record updated successfully",
|
||||||
|
data: RD,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Handle any errors during the update
|
||||||
|
res.status(500).json({
|
||||||
|
message: "Error updating RD record",
|
||||||
|
error: error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
@ -73,13 +73,18 @@ const RetailDistributorSchema = new mongoose.Schema(
|
|||||||
},
|
},
|
||||||
{ timestamps: true }
|
{ timestamps: true }
|
||||||
);
|
);
|
||||||
// Pre-save middleware to set 'mapped' based on 'userType'
|
|
||||||
|
// Pre-save middleware to set 'mappedSC' or 'mappedTM' if not provided, based on 'userType' and 'addedBy'
|
||||||
RetailDistributorSchema.pre("save", function (next) {
|
RetailDistributorSchema.pre("save", function (next) {
|
||||||
if (this.userType === "SalesCoOrdinator" && this.addedBy) {
|
// Only set defaults if the document is new (not yet saved)
|
||||||
|
if (this.isNew) {
|
||||||
|
if (!this.mappedSC && this.userType === "SalesCoOrdinator" && this.addedBy) {
|
||||||
this.mappedSC = this.addedBy;
|
this.mappedSC = this.addedBy;
|
||||||
} else if (this.userType === "TerritoryManager" && this.addedBy) {
|
}
|
||||||
|
if (!this.mappedTM && this.userType === "TerritoryManager" && this.addedBy) {
|
||||||
this.mappedTM = this.addedBy;
|
this.mappedTM = this.addedBy;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
RetailDistributorSchema.pre("save", async function (next) {
|
RetailDistributorSchema.pre("save", async function (next) {
|
||||||
|
Loading…
Reference in New Issue
Block a user