notification for PD done

This commit is contained in:
ROSHAN GARG 2024-09-17 11:41:18 +05:30
parent 21b85364dc
commit a64da15794
5 changed files with 197 additions and 9 deletions

7
app.js
View File

@ -197,6 +197,8 @@ import SalesRoute from "./resources/Sales/SalesRoute.js";
import PdOrderRoute from './resources/PD_Orders/pdOrderRoute.js'
import RDOrderRoute from "./resources/RD_Ordes/rdOrderRoutes.js"
import TaskRoute from "./resources/Task/TaskRoute.js";
app.use("/api/v1", user);
@ -274,8 +276,11 @@ app.use("/api/inventory", InventoryRoute);
app.use("/api/sales", SalesRoute);
//Task
app.use("/api/task", TaskRoute);
// RD Rotuts
// RD Rotuts auth
app.use("/api",RDRoute)
// RD Order routes
app.use("/api",RDOrderRoute)
//config specialty
// app.use("/api/config/specialty", SpecialtiesRouter);
//specialties

View File

@ -2,6 +2,7 @@ import express from "express";
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
import { getNotification } from "./notificationController.js";
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
import { isAuthenticatedUser } from "../../middlewares/auth.js";
const router = express.Router();
@ -21,4 +22,6 @@ router
.route("/get-notification-tm/:id")
.get(isAuthenticatedTerritoryManager, getNotification);
router.route("/get-notification-pd").get(isAuthenticatedUser, getNotification);
export default router;

View File

@ -1,20 +1,20 @@
import { RetailDistributor } from "../models/RetailDistributor";
import { RdOrder } from "../models/RdOrder";
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
import { RdOrder } from "./rdOrderModal.js";
// Controller to create a new order by RD
export const createOrderRD = async (req, res) => {
try {
const {
rdId,
paymentMode,
shipTo,
billTo,
orderItem,
orderItems,
subtotal,
gstTotal,
grandTotal,
} = req.body;
const rdId = req.user._id;
// Fetch the Retail Distributor (RD) to find the associated Principal Distributor (PD)
const rd = await RetailDistributor.findById(rdId).populate(
"principal_distributer"
@ -31,7 +31,21 @@ export const createOrderRD = async (req, res) => {
paymentMode,
shipTo,
billTo,
orderItem,
orderItem: orderItems.map((item) => ({
productId: item._id,
SKU: item.SKU,
name: item.name,
categoryName: item.category.categoryName, // Store category name
brandName: item.brand.brandName, // Store brand name
price: item.price,
GST: item.GST,
HSN_Code: item.HSN_Code,
description: item.description,
image: item.image,
quantity: item.count,
})),
subtotal,
gstTotal,
grandTotal,
@ -48,3 +62,133 @@ export const createOrderRD = async (req, res) => {
res.status(500).json({ message: "Server error", error });
}
};
export const getPlacedOrdersForRD = async (req, res) => {
try {
const rdId = req.user?._id; // Assuming the Retail Distributor's ID is obtained from the authenticated request
if (!rdId) {
return res.status(401).json({ message: "Unauthorized access" });
}
// Extract page and limit from query parameters, with default values
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 5;
// Calculate how many documents to skip for pagination
const skip = (page - 1) * limit;
// Fetch total count of orders for this RD (for pagination purposes)
const totalOrders = await RdOrder.countDocuments({ addedBy: rdId });
// Fetch orders for the logged-in RD
const placedOrders = await RdOrder.find({ addedBy: rdId })
.sort({ createdAt: -1 }) // Sort by creation date, newest first
.skip(skip) // Skip documents for pagination
.limit(limit); // Limit number of documents returned
if (!placedOrders || placedOrders.length === 0) {
return res
.status(404)
.json({ message: "No orders found for this Retail Distributor" });
}
// Send the paginated order list and total count of orders
res.status(200).json({ placedOrders, totalOrders });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error", error });
}
};
export const getSinglePlacedOrderForRD = async (req, res) => {
try {
const rdId = req.user?._id;
if (!rdId) {
return res.status(401).json({ message: "Unauthorized access" });
} // Assuming the Retail Distributor's ID is obtained from the authenticated request
const orderId = req.params.id; // Assuming the order ID is passed in the URL as a parameter
if (!rdId) {
return res.status(401).json({ message: "Unauthorized access" });
}
if (!orderId) {
return res.status(400).json({ message: "Order ID is required" });
}
// Fetch the specific order for the logged-in RD
const order = await RdOrder.findOne({ _id: orderId, addedBy: rdId });
if (!order) {
return res
.status(404)
.json({ message: "Order not found for this Retail Distributor" });
}
// Send the single order document
res.status(200).json({ singleOrder: order });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error", error });
}
};
export const getPlacedOrdersForPD = async (req, res) => {
try {
const pdId = req.user?._id;
if (!pdId) {
return res.status(401).json({ return_message: "Unauthorized access " });
}
// Extract page and limit from query parameters
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 5;
// Calculate the number of documents to skip
const skip = (page - 1) * limit;
const totalOrders = await RdOrder.countDocuments({ pd: pdId });
// Fetch all orders where the PD is associated with the order
const plcaedOrders = await RdOrder.find({ pd: pdId })
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit);
if (!plcaedOrders || plcaedOrders.length === 0) {
return res
.status(404)
.json({ message: "No orders found for this Principal Distributor" });
}
res.status(200).json({ plcaedOrders, totalOrders });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error", error });
}
};
export const getSinglePlacedOrderForPD = async (req, res) => {
try {
const pdId = req.user?._id; // Assuming the Principal Distributor's ID is obtained from the authenticated request
const orderId = req.params.id; // Assuming the order ID is passed in the URL as a parameter
if (!pdId) {
return res.status(401).json({ message: "Unauthorized access" });
}
if (!orderId) {
return res.status(400).json({ message: "Order ID is required" });
}
// Fetch the specific order for the logged-in PD
const order = await RdOrder.findOne({ _id: orderId, pd: pdId });
if (!order) {
return res
.status(404)
.json({ message: "Order not found for this Principal Distributor" });
}
// Send the single order document
res.status(200).json({ singleOrder: order });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error", error });
}
};

View File

@ -0,0 +1,28 @@
import express from "express";
import {
createOrderRD,
getPlacedOrdersForPD,
getPlacedOrdersForRD,
getSinglePlacedOrderForPD,
getSinglePlacedOrderForRD,
} from "./rdOrderController.js";
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
import { isAuthenticatedUser } from "../../middlewares/auth.js";
const router = express.Router();
router.route("/rd-place-order").post(isAuthenticatedRD, createOrderRD);
router.route("/rd-place-order").get(isAuthenticatedRD, getPlacedOrdersForRD);
router
.route("/rd-place-order/:id")
.get(isAuthenticatedRD, getSinglePlacedOrderForRD);
// routes for the PD
router
.route("/pd-get-all-place-order")
.get(isAuthenticatedUser, getPlacedOrdersForPD);
router
.route("/pd-get-all-place-order/:id")
.get(isAuthenticatedUser, getSinglePlacedOrderForPD);
export default router;

View File

@ -78,10 +78,18 @@ const RetailDistributorSchema = new mongoose.Schema(
RetailDistributorSchema.pre("save", function (next) {
// Only set defaults if the document is new (not yet saved)
if (this.isNew) {
if (!this.mappedSC && this.userType === "SalesCoOrdinator" && this.addedBy) {
if (
!this.mappedSC &&
this.userType === "SalesCoOrdinator" &&
this.addedBy
) {
this.mappedSC = this.addedBy;
}
if (!this.mappedTM && this.userType === "TerritoryManager" && this.addedBy) {
if (
!this.mappedTM &&
this.userType === "TerritoryManager" &&
this.addedBy
) {
this.mappedTM = this.addedBy;
}
}
@ -106,7 +114,7 @@ RetailDistributorSchema.pre("save", function (next) {
// JWT TOKEN
RetailDistributorSchema.methods.getJWTToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
return jwt.sign({ _id: this._id }, process.env.JWT_SECRET, {
expiresIn: "1d", // Token will expire in 1 day
});
};