This commit is contained in:
ROSHAN GARG 2024-09-11 10:01:49 +05:30
commit 4126f14a5b
10 changed files with 1080 additions and 102 deletions

View File

@ -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);

View File

@ -573,87 +573,4 @@ export const saveFCMTokenForTM = async (req, res) => {
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,
});
}
};

View File

@ -7,13 +7,11 @@ import {
createretaildistributor,
getAllKyc,
getAllKycApproved,
getAllKycApprovedbytmid,
getAllKycRejected,
getAllPrincipalDistributers,
getKycById,
saveFCMTokenForSC,
saveFCMTokenForTM,
updateKYCMapped,
updateKycStatus,
} from "./KycController.js";
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
@ -78,11 +76,4 @@ router
router
.route("/kyc/save-fcm-tm/")
.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;

View File

@ -2,17 +2,57 @@ import express from "express";
import {
ChangePasswordRD,
forgotPasswordRD,
getAllRDbypdid,
getAllRDbyscid,
getAllRDbytmid,
getAllRetailDistributorApproved,
getmyProfileRD,
getRDId,
loginRD,
UpdateProfileRD,
updateRDMapped,
updateunmapRD,
} from "./RetailDistributorController.js";
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
const router = express.Router();
router.route("/rd-login").post(loginRD);
router.route("/rd-get-me").get(isAuthenticatedRD, getmyProfileRD);
router.post("/forgot-password", forgotPasswordRD);
router.put("/rd-password/update", isAuthenticatedRD, ChangePasswordRD);
router.put(
"/rd-password/update",
isAuthenticatedRD,
ChangePasswordRD
);
router.patch("/rd-profile/update", isAuthenticatedRD, UpdateProfileRD);
//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("/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);
router
.route("/unmap/:id")
.patch(isAuthenticatedUser, authorizeRoles("admin"), updateunmapRD);
export default router;

File diff suppressed because it is too large Load Diff

View File

@ -73,12 +73,17 @@ const RetailDistributorSchema = new mongoose.Schema(
},
{ 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) {
if (this.userType === "SalesCoOrdinator" && this.addedBy) {
this.mappedSC = this.addedBy;
} else if (this.userType === "TerritoryManager" && this.addedBy) {
this.mappedTM = 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;
}
if (!this.mappedTM && this.userType === "TerritoryManager" && this.addedBy) {
this.mappedTM = this.addedBy;
}
}
next();
});

View File

@ -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 });

View File

@ -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,

View File

@ -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);

View File

@ -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(