diff --git a/public/uploads/Add-PD.xlsx b/public/uploads/Add-PD.xlsx index b17fe24..eb4aded 100644 Binary files a/public/uploads/Add-PD.xlsx and b/public/uploads/Add-PD.xlsx differ diff --git a/public/uploads/Add-RD.xlsx b/public/uploads/Add-RD.xlsx index 38576dd..f8a26bd 100644 Binary files a/public/uploads/Add-RD.xlsx and b/public/uploads/Add-RD.xlsx differ diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index b4d91e7..a9b881c 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -73,6 +73,10 @@ export const uploadProducts = async (req, res) => { for (let i = 1; i < data.length; i++) { const row = data[i]; + // Skip the row if it's completely empty + if (row.every((cell) => cell === undefined || cell === "")) { + continue; + } const item = {}; headers.forEach((header, index) => { @@ -83,7 +87,9 @@ export const uploadProducts = async (req, res) => { }); // Check if the row has meaningful data, skip if it's mostly empty - const hasValidData = Object.values(item).some((value) => value && value.trim()); + const hasValidData = Object.values(item).some( + (value) => value && value.trim() + ); if (!hasValidData) { continue; } diff --git a/resources/RetailDistributor/RetailDistributorController.js b/resources/RetailDistributor/RetailDistributorController.js index 40ddb9a..f4722f4 100644 --- a/resources/RetailDistributor/RetailDistributorController.js +++ b/resources/RetailDistributor/RetailDistributorController.js @@ -76,6 +76,10 @@ export const uploadRetaildistributors = async (req, res) => { for (let i = 1; i < data.length; i++) { const row = data[i]; + // Skip the row if it's completely empty + if (row.every((cell) => cell === undefined || cell === "")) { + continue; + } const item = {}; headers.forEach((header, index) => { diff --git a/resources/ShippingAddresses/ShippingAddressController.js b/resources/ShippingAddresses/ShippingAddressController.js index 5e12e47..e176dcd 100644 --- a/resources/ShippingAddresses/ShippingAddressController.js +++ b/resources/ShippingAddresses/ShippingAddressController.js @@ -59,16 +59,17 @@ export const AddshippingAddressByAdmin = async (req, res) => { panNumber, tradeName, gstNumber, + isDefault, } = req.body; - // console.log(req.body); + // Validate required fields - if (!street || !city || !state || !postalCode || !panNumber) { + if (!Name || !phoneNumber || !street || !city || !state || !postalCode || !panNumber) { return res .status(400) - .json({ msg: "Please provide all required fields" }); + .json({ msg: "Please provide all required fields: Name, phone number, street, city, state, postal code, and PAN number" }); } - // Create shipping address object + // Create new shipping address const newAddress = await ShippingAddress.create({ Name, phoneNumber, @@ -81,16 +82,24 @@ export const AddshippingAddressByAdmin = async (req, res) => { tradeName, gstNumber, user: req.params._id, // Assuming req.params._id contains the correct user ID + isDefault, }); + // If this address is marked as default, set all other addresses for this user to isDefault: false + if (isDefault) { + await ShippingAddress.updateMany( + { user: req.params._id, _id: { $ne: newAddress._id } }, // Exclude the new address + { $set: { isDefault: false } } + ); + } + + // Respond with success res.status(201).json({ success: true, address: newAddress, message: "Shipping address added successfully", }); } catch (error) { - // console.error("Error creating shipping address:", error.message); - // Check for validation errors if (error.name === "ValidationError") { const errorMessages = Object.values(error.errors).map( @@ -102,7 +111,7 @@ export const AddshippingAddressByAdmin = async (req, res) => { }); } - // General error + // General error response res.status(500).json({ success: false, message: error.message || "Something went wrong", @@ -203,6 +212,7 @@ export const updateShippingAddress = async (req, res) => { panNumber, tradeName, gstNumber, + isDefault, } = req.body; // console.log(req.body); const _id = req.params.id; @@ -210,7 +220,7 @@ export const updateShippingAddress = async (req, res) => { return res .status(400) .json({ message: "please Provide shipping Address Id" }); - const getselfAddress = await ShippingAddress.findById(req.params.id); + const getselfAddress = await ShippingAddress.findById(_id); if (!getselfAddress) { return res.status(404).json({ success: false, @@ -250,6 +260,14 @@ export const updateShippingAddress = async (req, res) => { return res.status(404).json({ msg: "please provide gstNumber" }); } } + // If the updated address is marked as default, update all other addresses to isDefault: false + if (isDefault) { + await ShippingAddress.updateMany( + { user: getselfAddress.user, _id: { $ne: _id } }, // exclude current address + { $set: { isDefault: false } } + ); + } + const updateAddressData = { Name, phoneNumber, @@ -261,6 +279,7 @@ export const updateShippingAddress = async (req, res) => { panNumber, tradeName, gstNumber, + isDefault, }; const updateShippingAddress = await ShippingAddress.findByIdAndUpdate( { _id: _id }, diff --git a/resources/Stock/StockController.js b/resources/Stock/StockController.js index ca45b65..3ce20fe 100644 --- a/resources/Stock/StockController.js +++ b/resources/Stock/StockController.js @@ -5,7 +5,7 @@ import { RDStock } from "./RdStockModel.js"; export const getProductsAndStockByPD = 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; diff --git a/resources/Stock/StockRoute.js b/resources/Stock/StockRoute.js index 4e21b56..40bd222 100644 --- a/resources/Stock/StockRoute.js +++ b/resources/Stock/StockRoute.js @@ -10,7 +10,6 @@ const router = express.Router(); router.get( "/pd/stock/:userId", isAuthenticatedUser, - authorizeRoles("admin"), getProductsAndStockByPD ); router.get( diff --git a/resources/user/userController.js b/resources/user/userController.js index d485ef1..819dd6f 100644 --- a/resources/user/userController.js +++ b/resources/user/userController.js @@ -394,6 +394,10 @@ export const uploadPrincipaldistributors = async (req, res) => { for (let i = 1; i < data.length; i++) { const row = data[i]; + // Skip the row if it's completely empty + if (row.every((cell) => cell === undefined || cell === "")) { + continue; + } const item = {}; headers.forEach((header, index) => { @@ -507,14 +511,14 @@ export const uploadPrincipaldistributors = async (req, res) => { user: distributor._id, isDefault: true, }).exec(); - + if (!existingAddress) { existingAddress = await ShippingAddress.findOne({ user: distributor._id, }) - .sort({ createdAt: 1 }) // Get the first created address as fallback - .exec(); - } + .sort({ createdAt: 1 }) // Get the first created address as fallback + .exec(); + } // Check for changes in user details let userUpdated = false; @@ -1025,7 +1029,7 @@ export const getAllUser = catchAsyncErrors(async (req, res, next) => { } if (SBU) { - filter.SBU = { $regex: SBU, $options: "i" }; + filter.SBU = { $regex: SBU, $options: "i" }; } const limit = parseInt(show, 10); @@ -1084,7 +1088,7 @@ export const getAllPD = catchAsyncErrors(async (req, res, next) => { // Aggregate orders data for each user const orderStats = await PdOrder.aggregate([ - { $match: { addedBy: { $in: users.map(user => user._id) } } }, // Match orders for the listed distributors + { $match: { addedBy: { $in: users.map((user) => user._id) } } }, // Match orders for the listed distributors { $group: { _id: "$addedBy", // Group by addedBy (distributor ID) @@ -1095,8 +1099,10 @@ export const getAllPD = catchAsyncErrors(async (req, res, next) => { ]); // Map orders data to corresponding users - const usersWithOrderStats = users.map(user => { - const orderData = orderStats.find(order => order._id.toString() === user._id.toString()); + const usersWithOrderStats = users.map((user) => { + const orderData = orderStats.find( + (order) => order._id.toString() === user._id.toString() + ); return { ...user.toObject(), totalOrders: orderData ? orderData.totalOrders : 0, @@ -1111,7 +1117,7 @@ export const getAllPD = catchAsyncErrors(async (req, res, next) => { total_pages: Math.ceil(totalUsers / limit), }); } catch (error) { - console.error('Error fetching Principal Distributors:', error); + console.error("Error fetching Principal Distributors:", error); res.status(500).json({ message: "Server Error", error }); } });