Merge branch 'main' of https://git.cnapp.co.in/gitadmin/api
This commit is contained in:
commit
1d1330dfe3
@ -1,31 +1,76 @@
|
|||||||
import { Inventory } from "../Inventory/InventoryModel.js";
|
import { Inventory } from "../Inventory/InventoryModel.js";
|
||||||
import User from "../user/userModel.js";
|
import User from "../user/userModel.js";
|
||||||
import { KYC } from "../KYC/KycModel.js";
|
|
||||||
import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js";
|
import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js";
|
||||||
import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js";
|
import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js";
|
||||||
import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
|
import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
|
||||||
import crypto from "crypto";
|
|
||||||
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
|
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
|
||||||
|
import { RDStock } from "../Stock/RdStockModel.js";
|
||||||
// Add inventory data
|
// Add inventory data
|
||||||
export const addInventory = async (req, res) => {
|
export const addInventory = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { products, addedFor, addedForId } = req.body;
|
const { products, addedFor, addedForId } = req.body;
|
||||||
const userId = req.user._id;
|
const userId = req.user._id;
|
||||||
const userType = req.userType;
|
const userType = req.userType;
|
||||||
// console.log("req.user", req.user);
|
|
||||||
const currentYear = new Date().getFullYear().toString().slice(-2);
|
if (addedFor === "RetailDistributor") {
|
||||||
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
|
// Find the RetailDistributor stock
|
||||||
const uniqueId = `${currentYear}-${randomChars}`;
|
const rdStock = await RDStock.findOne({ userId: addedForId });
|
||||||
// console.log("uniqueId", uniqueId);
|
if (!rdStock) {
|
||||||
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json({ error: "Stock not available for the RetailDistributor" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Array to hold product names that have issues
|
||||||
|
let invalidProducts = [];
|
||||||
|
|
||||||
|
// Loop through products in the request and check stock availability
|
||||||
|
for (const product of products) {
|
||||||
|
const { productid, Sale, ProductName } = product;
|
||||||
|
|
||||||
|
// Find product in the RetailDistributor's stock
|
||||||
|
const rdProduct = rdStock.products.find(
|
||||||
|
(p) => p.productid.toString() === productid.toString()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rdProduct) {
|
||||||
|
// Check if sales quantity is less than or equal to the stock
|
||||||
|
if (Sale <= rdProduct.Stock) {
|
||||||
|
// Decrease the stock by sales amount
|
||||||
|
rdProduct.Stock -= Sale;
|
||||||
|
} else {
|
||||||
|
// If sales > stock, add to invalid products list
|
||||||
|
invalidProducts.push(ProductName);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Product not found in stock, add to invalid products list
|
||||||
|
invalidProducts.push(ProductName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there are any invalid products, return error message
|
||||||
|
if (invalidProducts.length > 0) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: `Insufficient stock or product not found for: ${invalidProducts.join(
|
||||||
|
", "
|
||||||
|
)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save updated stock if all products are valid
|
||||||
|
await rdStock.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create and save new inventory record
|
||||||
const newInventory = new Inventory({
|
const newInventory = new Inventory({
|
||||||
userId,
|
userId,
|
||||||
userType,
|
userType,
|
||||||
addedFor,
|
addedFor,
|
||||||
addedForId,
|
addedForId,
|
||||||
products,
|
products,
|
||||||
uniqueId,
|
|
||||||
});
|
});
|
||||||
// console.log("newInventory", newInventory);
|
|
||||||
await newInventory.save();
|
await newInventory.save();
|
||||||
res.status(201).json({
|
res.status(201).json({
|
||||||
success: true,
|
success: true,
|
||||||
@ -46,7 +91,7 @@ export const getDistributors = async (req, res) => {
|
|||||||
return res.status(400).json({ message: "Invalid distributor type" });
|
return res.status(400).json({ message: "Invalid distributor type" });
|
||||||
}
|
}
|
||||||
let filter = { role: "principal-Distributor" };
|
let filter = { role: "principal-Distributor" };
|
||||||
let query={};
|
let query = {};
|
||||||
// Check the user type and adjust the filter accordingly
|
// Check the user type and adjust the filter accordingly
|
||||||
if (req.userType === "SalesCoOrdinator") {
|
if (req.userType === "SalesCoOrdinator") {
|
||||||
// If userType is "SalesCoOrdinator", filter by req.user.mappedBy
|
// If userType is "SalesCoOrdinator", filter by req.user.mappedBy
|
||||||
@ -61,7 +106,9 @@ export const getDistributors = async (req, res) => {
|
|||||||
// console.log("type",type);
|
// console.log("type",type);
|
||||||
if (type === "PrincipalDistributor") {
|
if (type === "PrincipalDistributor") {
|
||||||
// Fetch all PrincipalDistributors
|
// Fetch all PrincipalDistributors
|
||||||
const principalDistributors = await User.find(filter);
|
const principalDistributors = await User.find(filter).sort({
|
||||||
|
createdAt: -1,
|
||||||
|
});
|
||||||
// console.log("principalDistributors",principalDistributors);
|
// console.log("principalDistributors",principalDistributors);
|
||||||
// Map each PrincipalDistributor to include their ShippingAddress
|
// Map each PrincipalDistributor to include their ShippingAddress
|
||||||
distributors = await Promise.all(
|
distributors = await Promise.all(
|
||||||
@ -76,8 +123,10 @@ export const getDistributors = async (req, res) => {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// For RetailDistributor, fetch approved KYC documents
|
// For RetailDistributor
|
||||||
distributors = await RetailDistributor.find(query).populate("kyc");
|
distributors = await RetailDistributor.find(query)
|
||||||
|
.populate("kyc")
|
||||||
|
.sort({ createdAt: -1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json(distributors);
|
res.status(200).json(distributors);
|
||||||
@ -106,12 +155,12 @@ export const getAllInventories = async (req, res) => {
|
|||||||
$lte: new Date(end).setDate(end.getDate() + 1),
|
$lte: new Date(end).setDate(end.getDate() + 1),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} else if (startDate && endDate==='') {
|
} else if (startDate && endDate === "") {
|
||||||
query.createdAt = {
|
query.createdAt = {
|
||||||
$gte: new Date(startDate),
|
$gte: new Date(startDate),
|
||||||
$lte: new Date(),
|
$lte: new Date(),
|
||||||
};
|
};
|
||||||
} else if (endDate && startDate==='') {
|
} else if (endDate && startDate === "") {
|
||||||
query.createdAt = {
|
query.createdAt = {
|
||||||
$lte: new Date(endDate),
|
$lte: new Date(endDate),
|
||||||
};
|
};
|
||||||
@ -146,8 +195,8 @@ export const getAllInventories = async (req, res) => {
|
|||||||
addedForData.shippingAddress?.tradeName?.toLowerCase() || "";
|
addedForData.shippingAddress?.tradeName?.toLowerCase() || "";
|
||||||
}
|
}
|
||||||
} else if (inventory.addedFor === "RetailDistributor") {
|
} else if (inventory.addedFor === "RetailDistributor") {
|
||||||
addedForData = await KYC.findById(inventory.addedForId);
|
addedForData = await RetailDistributor.findById(inventory.addedForId).populate("kyc");
|
||||||
tradeName = addedForData?.trade_name?.toLowerCase() || "";
|
tradeName = addedForData?.kyc?.trade_name?.toLowerCase() || "";
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -224,7 +273,7 @@ export const getSingleInventory = async (req, res) => {
|
|||||||
shippingAddress,
|
shippingAddress,
|
||||||
};
|
};
|
||||||
} else if (inventory.addedFor === "RetailDistributor") {
|
} else if (inventory.addedFor === "RetailDistributor") {
|
||||||
addedForData = await KYC.findById(inventory.addedForId);
|
addedForData = await RetailDistributor.findById(inventory.addedForId).populate("kyc");
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
|
@ -1,7 +1,13 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from "mongoose";
|
||||||
|
import crypto from 'crypto';
|
||||||
|
|
||||||
// Define Product record schema
|
// Define Product record schema
|
||||||
const ProductRecordSchema = new mongoose.Schema({
|
const ProductRecordSchema = new mongoose.Schema({
|
||||||
|
productid: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: "Product",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
SKU: {
|
SKU: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
@ -21,33 +27,43 @@ const ProductRecordSchema = new mongoose.Schema({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Define main Inventory schema
|
// Define main Inventory schema
|
||||||
const InventorySchema = new mongoose.Schema({
|
const InventorySchema = new mongoose.Schema(
|
||||||
uniqueId: {
|
{
|
||||||
type: String,
|
uniqueId: {
|
||||||
required: true,
|
type: String,
|
||||||
unique: true,
|
unique: true,
|
||||||
|
},
|
||||||
|
userId: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
refPath: "userType",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
userType: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
enum: ["SalesCoOrdinator", "TerritoryManager"],
|
||||||
|
},
|
||||||
|
addedFor: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
enum: ["PrincipalDistributor", "RetailDistributor"],
|
||||||
|
},
|
||||||
|
addedForId: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
refPath: "addedFor",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
products: [ProductRecordSchema],
|
||||||
},
|
},
|
||||||
userId: {
|
{ timestamps: true, versionKey: false }
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
);
|
||||||
refPath: 'userType',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
userType: {
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
enum: ['SalesCoOrdinator', 'TerritoryManager'],
|
|
||||||
},
|
|
||||||
addedFor: {
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
enum: ['PrincipalDistributor', 'RetailDistributor'],
|
|
||||||
},
|
|
||||||
addedForId: {
|
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
|
||||||
refPath: 'addedFor',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
products: [ProductRecordSchema],
|
|
||||||
}, { timestamps: true, versionKey: false });
|
|
||||||
|
|
||||||
export const Inventory = mongoose.model('Inventory', InventorySchema);
|
InventorySchema.pre("save", function (next) {
|
||||||
|
if (!this.uniqueId) {
|
||||||
|
const currentYear = new Date().getFullYear().toString().slice(-2);
|
||||||
|
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
|
||||||
|
this.uniqueId = `${currentYear}-${randomChars}`;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
export const Inventory = mongoose.model("Inventory", InventorySchema);
|
@ -3,11 +3,12 @@ import { addInventory, getDistributors,getAllInventories,getSingleInventory } fr
|
|||||||
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
||||||
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
|
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
|
||||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||||
|
import {isAuthenticated_SC_TM } from "../../middlewares/generalAuth.js";
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Route to add inventory data
|
// Route to add inventory data
|
||||||
router.post("/add-SC", isAuthenticatedSalesCoOrdinator, addInventory);
|
router.post("/add", isAuthenticated_SC_TM, addInventory);
|
||||||
router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory);
|
// router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory);
|
||||||
// Route to get all PD or RD names based on type
|
// Route to get all PD or RD names based on type
|
||||||
router.get(
|
router.get(
|
||||||
"/distributors-SC/:type",
|
"/distributors-SC/:type",
|
||||||
|
@ -7,7 +7,7 @@ import { PDStock } from "../Stock/PdStockModel.js";
|
|||||||
import { createKYC } from "../../Utils/rejectKyc.js";
|
import { createKYC } from "../../Utils/rejectKyc.js";
|
||||||
import { Notification } from "../Notification/notificationModal.js";
|
import { Notification } from "../Notification/notificationModal.js";
|
||||||
import { sendPushNotification } from "../../Utils/sendPushNotification.js";
|
import { sendPushNotification } from "../../Utils/sendPushNotification.js";
|
||||||
|
import {RDStock} from "../Stock/RdStockModel.js";
|
||||||
// Controller to create a new order by RD
|
// Controller to create a new order by RD
|
||||||
export const createOrderRD = async (req, res) => {
|
export const createOrderRD = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@ -973,38 +973,38 @@ export const updateCourierStatusToDeliveredForPD = async (req, res) => {
|
|||||||
if (!userId) {
|
if (!userId) {
|
||||||
return res.status(400).json({ error: "User not found for the order" });
|
return res.status(400).json({ error: "User not found for the order" });
|
||||||
}
|
}
|
||||||
// Check if PDStock exists for the user
|
// Check if RDStock exists for the user
|
||||||
// let pdStock = await PDStock.findOne({ userId });
|
let rdStock = await RDStock.findOne({ userId });
|
||||||
|
|
||||||
|
if (!rdStock) {
|
||||||
|
// If no stock record exists, create a new one
|
||||||
|
rdStock = new RDStock({
|
||||||
|
userId,
|
||||||
|
products: [], // Initialize with empty products array
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Iterate over each item in the invoice
|
||||||
|
for (let item of invoice.items) {
|
||||||
|
const { productId, processquantity } = item;
|
||||||
|
|
||||||
// if (!pdStock) {
|
// Check if the product already exists in the PDStock for the user
|
||||||
// // If no stock record exists, create a new one
|
const existingProduct = rdStock.products.find(
|
||||||
// pdStock = new PDStock({
|
(p) => p.productid.toString() === productId.toString()
|
||||||
// userId,
|
);
|
||||||
// products: [], // Initialize with empty products array
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// // Iterate over each item in the invoice
|
|
||||||
// for (let item of invoice.items) {
|
|
||||||
// const { productId, processquantity } = item;
|
|
||||||
|
|
||||||
// // Check if the product already exists in the PDStock for the user
|
if (existingProduct) {
|
||||||
// const existingProduct = pdStock.products.find(
|
// If the product exists, update the stock by adding the processquantity
|
||||||
// (p) => p.productid.toString() === productId.toString()
|
existingProduct.Stock += processquantity;
|
||||||
// );
|
} else {
|
||||||
|
// If the product doesn't exist, add a new entry for the product
|
||||||
// if (existingProduct) {
|
rdStock.products.push({
|
||||||
// // If the product exists, update the stock by adding the processquantity
|
productid: productId,
|
||||||
// existingProduct.Stock += processquantity;
|
Stock: processquantity,
|
||||||
// } else {
|
});
|
||||||
// // If the product doesn't exist, add a new entry for the product
|
}
|
||||||
// pdStock.products.push({
|
}
|
||||||
// productid: productId,
|
|
||||||
// Stock: processquantity,
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// Save the updated PDStock
|
// Save the updated PDStock
|
||||||
// await pdStock.save();
|
await rdStock.save();
|
||||||
// Format the current date for display
|
// Format the current date for display
|
||||||
const formattedDate = formatDate(new Date());
|
const formattedDate = formatDate(new Date());
|
||||||
|
|
||||||
|
@ -104,7 +104,7 @@ export const getProductsAndStockByPD = async (req, res) => {
|
|||||||
|
|
||||||
export const getProductsAndStockByRD = async (req, res) => {
|
export const getProductsAndStockByRD = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userId } = req.params;
|
const userId = req.params.userId || req.user._id;
|
||||||
|
|
||||||
// Pagination parameters
|
// Pagination parameters
|
||||||
const PAGE_SIZE = parseInt(req.query.show) || 10;
|
const PAGE_SIZE = parseInt(req.query.show) || 10;
|
||||||
@ -199,4 +199,4 @@ export const getProductsAndStockByRD = async (req, res) => {
|
|||||||
message: "Error fetching products and stock",
|
message: "Error fetching products and stock",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { getProductsAndStockByPD ,getProductsAndStockByRD} from "./StockController.js";
|
import {
|
||||||
|
getProductsAndStockByPD,
|
||||||
|
getProductsAndStockByRD,
|
||||||
|
} from "./StockController.js";
|
||||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||||
|
import {isAuthenticatedRD} from "../../middlewares/rdAuth.js";
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
@ -15,4 +19,5 @@ router.get(
|
|||||||
authorizeRoles("admin"),
|
authorizeRoles("admin"),
|
||||||
getProductsAndStockByRD
|
getProductsAndStockByRD
|
||||||
);
|
);
|
||||||
|
router.get("/stock", isAuthenticatedRD, getProductsAndStockByRD);
|
||||||
export default router;
|
export default router;
|
||||||
|
Loading…
Reference in New Issue
Block a user