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 User from "../user/userModel.js";
|
||||
import { KYC } from "../KYC/KycModel.js";
|
||||
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";
|
||||
import { RDStock } from "../Stock/RdStockModel.js";
|
||||
// Add inventory data
|
||||
export const addInventory = async (req, res) => {
|
||||
try {
|
||||
const { products, addedFor, addedForId } = req.body;
|
||||
const userId = req.user._id;
|
||||
const userType = req.userType;
|
||||
// console.log("req.user", req.user);
|
||||
const currentYear = new Date().getFullYear().toString().slice(-2);
|
||||
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
|
||||
const uniqueId = `${currentYear}-${randomChars}`;
|
||||
// console.log("uniqueId", uniqueId);
|
||||
|
||||
if (addedFor === "RetailDistributor") {
|
||||
// Find the RetailDistributor stock
|
||||
const rdStock = await RDStock.findOne({ userId: addedForId });
|
||||
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({
|
||||
userId,
|
||||
userType,
|
||||
addedFor,
|
||||
addedForId,
|
||||
products,
|
||||
uniqueId,
|
||||
});
|
||||
// console.log("newInventory", newInventory);
|
||||
|
||||
await newInventory.save();
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
@ -61,7 +106,9 @@ export const getDistributors = async (req, res) => {
|
||||
// console.log("type",type);
|
||||
if (type === "PrincipalDistributor") {
|
||||
// Fetch all PrincipalDistributors
|
||||
const principalDistributors = await User.find(filter);
|
||||
const principalDistributors = await User.find(filter).sort({
|
||||
createdAt: -1,
|
||||
});
|
||||
// console.log("principalDistributors",principalDistributors);
|
||||
// Map each PrincipalDistributor to include their ShippingAddress
|
||||
distributors = await Promise.all(
|
||||
@ -76,8 +123,10 @@ export const getDistributors = async (req, res) => {
|
||||
})
|
||||
);
|
||||
} else {
|
||||
// For RetailDistributor, fetch approved KYC documents
|
||||
distributors = await RetailDistributor.find(query).populate("kyc");
|
||||
// For RetailDistributor
|
||||
distributors = await RetailDistributor.find(query)
|
||||
.populate("kyc")
|
||||
.sort({ createdAt: -1 });
|
||||
}
|
||||
|
||||
res.status(200).json(distributors);
|
||||
@ -106,12 +155,12 @@ export const getAllInventories = async (req, res) => {
|
||||
$lte: new Date(end).setDate(end.getDate() + 1),
|
||||
};
|
||||
}
|
||||
} else if (startDate && endDate==='') {
|
||||
} else if (startDate && endDate === "") {
|
||||
query.createdAt = {
|
||||
$gte: new Date(startDate),
|
||||
$lte: new Date(),
|
||||
};
|
||||
} else if (endDate && startDate==='') {
|
||||
} else if (endDate && startDate === "") {
|
||||
query.createdAt = {
|
||||
$lte: new Date(endDate),
|
||||
};
|
||||
@ -146,8 +195,8 @@ export const getAllInventories = async (req, res) => {
|
||||
addedForData.shippingAddress?.tradeName?.toLowerCase() || "";
|
||||
}
|
||||
} else if (inventory.addedFor === "RetailDistributor") {
|
||||
addedForData = await KYC.findById(inventory.addedForId);
|
||||
tradeName = addedForData?.trade_name?.toLowerCase() || "";
|
||||
addedForData = await RetailDistributor.findById(inventory.addedForId).populate("kyc");
|
||||
tradeName = addedForData?.kyc?.trade_name?.toLowerCase() || "";
|
||||
}
|
||||
|
||||
return {
|
||||
@ -224,7 +273,7 @@ export const getSingleInventory = async (req, res) => {
|
||||
shippingAddress,
|
||||
};
|
||||
} else if (inventory.addedFor === "RetailDistributor") {
|
||||
addedForData = await KYC.findById(inventory.addedForId);
|
||||
addedForData = await RetailDistributor.findById(inventory.addedForId).populate("kyc");
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
|
@ -1,7 +1,13 @@
|
||||
import mongoose from 'mongoose';
|
||||
import mongoose from "mongoose";
|
||||
import crypto from 'crypto';
|
||||
|
||||
// Define Product record schema
|
||||
const ProductRecordSchema = new mongoose.Schema({
|
||||
productid: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "Product",
|
||||
required: true,
|
||||
},
|
||||
SKU: {
|
||||
type: String,
|
||||
required: true,
|
||||
@ -21,33 +27,43 @@ const ProductRecordSchema = new mongoose.Schema({
|
||||
});
|
||||
|
||||
// Define main Inventory schema
|
||||
const InventorySchema = new mongoose.Schema({
|
||||
const InventorySchema = new mongoose.Schema(
|
||||
{
|
||||
uniqueId: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
userId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
refPath: 'userType',
|
||||
refPath: "userType",
|
||||
required: true,
|
||||
},
|
||||
userType: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: ['SalesCoOrdinator', 'TerritoryManager'],
|
||||
enum: ["SalesCoOrdinator", "TerritoryManager"],
|
||||
},
|
||||
addedFor: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: ['PrincipalDistributor', 'RetailDistributor'],
|
||||
enum: ["PrincipalDistributor", "RetailDistributor"],
|
||||
},
|
||||
addedForId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
refPath: 'addedFor',
|
||||
refPath: "addedFor",
|
||||
required: true,
|
||||
},
|
||||
products: [ProductRecordSchema],
|
||||
}, { timestamps: true, versionKey: false });
|
||||
},
|
||||
{ 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 { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
|
||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||
import {isAuthenticated_SC_TM } from "../../middlewares/generalAuth.js";
|
||||
const router = express.Router();
|
||||
|
||||
// Route to add inventory data
|
||||
router.post("/add-SC", isAuthenticatedSalesCoOrdinator, addInventory);
|
||||
router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory);
|
||||
router.post("/add", isAuthenticated_SC_TM, addInventory);
|
||||
// router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory);
|
||||
// Route to get all PD or RD names based on type
|
||||
router.get(
|
||||
"/distributors-SC/:type",
|
||||
|
@ -7,7 +7,7 @@ import { PDStock } from "../Stock/PdStockModel.js";
|
||||
import { createKYC } from "../../Utils/rejectKyc.js";
|
||||
import { Notification } from "../Notification/notificationModal.js";
|
||||
import { sendPushNotification } from "../../Utils/sendPushNotification.js";
|
||||
|
||||
import {RDStock} from "../Stock/RdStockModel.js";
|
||||
// Controller to create a new order by RD
|
||||
export const createOrderRD = async (req, res) => {
|
||||
try {
|
||||
@ -973,38 +973,38 @@ export const updateCourierStatusToDeliveredForPD = async (req, res) => {
|
||||
if (!userId) {
|
||||
return res.status(400).json({ error: "User not found for the order" });
|
||||
}
|
||||
// Check if PDStock exists for the user
|
||||
// let pdStock = await PDStock.findOne({ userId });
|
||||
// Check if RDStock exists for the user
|
||||
let rdStock = await RDStock.findOne({ userId });
|
||||
|
||||
// if (!pdStock) {
|
||||
// // If no stock record exists, create a new one
|
||||
// pdStock = new PDStock({
|
||||
// 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 (!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;
|
||||
|
||||
// // Check if the product already exists in the PDStock for the user
|
||||
// const existingProduct = pdStock.products.find(
|
||||
// (p) => p.productid.toString() === productId.toString()
|
||||
// );
|
||||
// Check if the product already exists in the PDStock for the user
|
||||
const existingProduct = rdStock.products.find(
|
||||
(p) => p.productid.toString() === productId.toString()
|
||||
);
|
||||
|
||||
// if (existingProduct) {
|
||||
// // If the product exists, update the stock by adding the processquantity
|
||||
// existingProduct.Stock += processquantity;
|
||||
// } else {
|
||||
// // If the product doesn't exist, add a new entry for the product
|
||||
// pdStock.products.push({
|
||||
// productid: productId,
|
||||
// Stock: processquantity,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
if (existingProduct) {
|
||||
// If the product exists, update the stock by adding the processquantity
|
||||
existingProduct.Stock += processquantity;
|
||||
} else {
|
||||
// If the product doesn't exist, add a new entry for the product
|
||||
rdStock.products.push({
|
||||
productid: productId,
|
||||
Stock: processquantity,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Save the updated PDStock
|
||||
// await pdStock.save();
|
||||
await rdStock.save();
|
||||
// Format the current date for display
|
||||
const formattedDate = formatDate(new Date());
|
||||
|
||||
|
@ -104,7 +104,7 @@ export const getProductsAndStockByPD = async (req, res) => {
|
||||
|
||||
export const getProductsAndStockByRD = async (req, res) => {
|
||||
try {
|
||||
const { userId } = req.params;
|
||||
const userId = req.params.userId || req.user._id;
|
||||
|
||||
// Pagination parameters
|
||||
const PAGE_SIZE = parseInt(req.query.show) || 10;
|
||||
|
@ -1,6 +1,10 @@
|
||||
import express from "express";
|
||||
import { getProductsAndStockByPD ,getProductsAndStockByRD} from "./StockController.js";
|
||||
import {
|
||||
getProductsAndStockByPD,
|
||||
getProductsAndStockByRD,
|
||||
} from "./StockController.js";
|
||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||
import {isAuthenticatedRD} from "../../middlewares/rdAuth.js";
|
||||
const router = express.Router();
|
||||
|
||||
router.get(
|
||||
@ -15,4 +19,5 @@ router.get(
|
||||
authorizeRoles("admin"),
|
||||
getProductsAndStockByRD
|
||||
);
|
||||
router.get("/stock", isAuthenticatedRD, getProductsAndStockByRD);
|
||||
export default router;
|
||||
|
Loading…
Reference in New Issue
Block a user