Inventory

This commit is contained in:
Sibunnayak 2024-08-16 15:21:26 +05:30
parent a190789535
commit 7d83288deb
2 changed files with 73 additions and 56 deletions

View File

@ -4,21 +4,27 @@ 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";
// 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); 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);
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,
@ -34,25 +40,31 @@ export const addInventory = async (req, res) => {
export const getDistributors = async (req, res) => { export const getDistributors = async (req, res) => {
try { try {
const { type } = req.params; const { type } = req.params;
if (!["PrincipalDistributor", "RetailDistributor"].includes(type)) { if (!["PrincipalDistributor", "RetailDistributor"].includes(type)) {
return res.status(400).json({ message: "Invalid distributor type" }); return res.status(400).json({ message: "Invalid distributor type" });
} }
let distributors; let distributors;
// 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({ role: "principal-Distributor" }); const principalDistributors = await User.find({
// console.log("principalDistributors",principalDistributors); role: "principal-Distributor",
});
// console.log("principalDistributors",principalDistributors);
// Map each PrincipalDistributor to include their ShippingAddress // Map each PrincipalDistributor to include their ShippingAddress
distributors = await Promise.all(principalDistributors.map(async (distributor) => { distributors = await Promise.all(
const shippingAddress = await ShippingAddress.findOne({ user: distributor._id }); principalDistributors.map(async (distributor) => {
return { const shippingAddress = await ShippingAddress.findOne({
...distributor.toObject(), user: distributor._id,
shippingAddress, });
}; return {
})); ...distributor.toObject(),
shippingAddress,
};
})
);
} else { } else {
// For RetailDistributor, fetch approved KYC documents // For RetailDistributor, fetch approved KYC documents
distributors = await KYC.find({ status: "approved" }); distributors = await KYC.find({ status: "approved" });
@ -66,16 +78,11 @@ export const getDistributors = async (req, res) => {
export const getAllInventories = async (req, res) => { export const getAllInventories = async (req, res) => {
try { try {
const { const { page = 1, show = 10, startDate, endDate } = req.query;
page = 1,
show = 10,
startDate,
endDate
} = req.query;
// Build query // Build query
const query = {}; const query = {};
if (startDate && endDate) { if (startDate && endDate) {
const start = new Date(startDate); const start = new Date(startDate);
const end = new Date(endDate); const end = new Date(endDate);
@ -84,25 +91,25 @@ export const getAllInventories = async (req, res) => {
// If startDate and endDate are the same, fetch records for that day // If startDate and endDate are the same, fetch records for that day
query.createdAt = { query.createdAt = {
$gte: new Date(startDate), $gte: new Date(startDate),
$lt: new Date(startDate).setDate(new Date(startDate).getDate() + 1) // Until the end of that day $lt: new Date(startDate).setDate(new Date(startDate).getDate() + 1), // Until the end of that day
}; };
} else { } else {
// If startDate and endDate are different, fetch records between these dates // If startDate and endDate are different, fetch records between these dates
query.createdAt = { query.createdAt = {
$gte: start, $gte: start,
$lte:new Date(end).setDate(new Date(end).getDate() + 1) $lte: new Date(end).setDate(new Date(end).getDate() + 1),
}; };
} }
} else if (startDate) { } else if (startDate) {
// Only startDate is provided // Only startDate is provided
query.createdAt = { query.createdAt = {
$gte: new Date(startDate), $gte: new Date(startDate),
$lte: new Date() // Up to today's date $lte: new Date(), // Up to today's date
}; };
} else if (endDate) { } else if (endDate) {
// Only endDate is provided // Only endDate is provided
query.createdAt = { query.createdAt = {
$lte: new Date(endDate) $lte: new Date(endDate),
}; };
} }
@ -116,38 +123,42 @@ export const getAllInventories = async (req, res) => {
.sort({ createdAt: -1 }); // Optional: Sort by createdAt date in descending order .sort({ createdAt: -1 }); // Optional: Sort by createdAt date in descending order
// Populate additional details // Populate additional details
const populatedInventories = await Promise.all(inventories.map(async (inventory) => { const populatedInventories = await Promise.all(
// Populate user details based on userType inventories.map(async (inventory) => {
let user = null; // Populate user details based on userType
if (inventory.userType === 'TerritoryManager') { let user = null;
user = await TerritoryManager.findById(inventory.userId); if (inventory.userType === "TerritoryManager") {
} else if (inventory.userType === 'SalesCoordinator') { user = await TerritoryManager.findById(inventory.userId);
user = await SalesCoordinator.findById(inventory.userId); } else if (inventory.userType === "SalesCoordinator") {
} user = await SalesCoordinator.findById(inventory.userId);
}
// Populate addedFor details based on addedFor // Populate addedFor details based on addedFor
let addedForData = null; let addedForData = null;
if (inventory.addedFor === 'PrincipalDistributor') { if (inventory.addedFor === "PrincipalDistributor") {
addedForData = await User.findById(inventory.addedForId); addedForData = await User.findById(inventory.addedForId);
const shippingAddress = await ShippingAddress.findOne({ user: addedForData._id }); const shippingAddress = await ShippingAddress.findOne({
addedForData = { user: addedForData._id,
...addedForData.toObject(), });
shippingAddress, addedForData = {
...addedForData.toObject(),
shippingAddress,
};
} else if (inventory.addedFor === "RetailDistributor") {
addedForData = await KYC.findById(inventory.addedForId);
}
return {
...inventory.toObject(),
user,
addedForData,
}; };
} else if (inventory.addedFor === 'RetailDistributor') { })
addedForData = await KYC.findById(inventory.addedForId); );
}
return {
...inventory.toObject(),
user,
addedForData,
};
}));
// Send response with pagination info // Send response with pagination info
res.status(200).json({ res.status(200).json({
total_data, total_data,
inventories: populatedInventories inventories: populatedInventories,
}); });
} catch (error) { } catch (error) {
res.status(500).json({ message: error.message }); res.status(500).json({ message: error.message });
@ -165,22 +176,24 @@ export const getSingleInventory = async (req, res) => {
// Populate user details based on userType // Populate user details based on userType
let user = null; let user = null;
if (inventory.userType === 'TerritoryManager') { if (inventory.userType === "TerritoryManager") {
user = await TerritoryManager.findById(inventory.userId); user = await TerritoryManager.findById(inventory.userId);
} else if (inventory.userType === 'SalesCoOrdinator') { } else if (inventory.userType === "SalesCoOrdinator") {
user = await SalesCoordinator.findById(inventory.userId); user = await SalesCoordinator.findById(inventory.userId);
} }
// Populate addedFor details based on addedFor // Populate addedFor details based on addedFor
let addedForData = null; let addedForData = null;
if (inventory.addedFor === 'PrincipalDistributor') { if (inventory.addedFor === "PrincipalDistributor") {
addedForData = await User.findById(inventory.addedForId); addedForData = await User.findById(inventory.addedForId);
const shippingAddress = await ShippingAddress.findOne({ user: addedForData._id }); const shippingAddress = await ShippingAddress.findOne({
user: addedForData._id,
});
addedForData = { addedForData = {
...addedForData.toObject(), ...addedForData.toObject(),
shippingAddress, shippingAddress,
}; };
} else if (inventory.addedFor === 'RetailDistributor') { } else if (inventory.addedFor === "RetailDistributor") {
addedForData = await KYC.findById(inventory.addedForId); addedForData = await KYC.findById(inventory.addedForId);
} }
@ -193,4 +206,3 @@ export const getSingleInventory = async (req, res) => {
res.status(500).json({ message: error.message }); res.status(500).json({ message: error.message });
} }
}; };

View File

@ -22,6 +22,11 @@ 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,
required: true,
unique: true,
},
userId: { userId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
refPath: 'userType', refPath: 'userType',