|
|
|
@ -354,38 +354,38 @@ exports.addProductToCart = async (req, res) => {
|
|
|
|
|
|
|
|
|
|
exports.updateProductQuantity = async (req, res) => {
|
|
|
|
|
try {
|
|
|
|
|
const { productId, quantity } = req.body;
|
|
|
|
|
|
|
|
|
|
// Find the user
|
|
|
|
|
const user = await User.findById(req.user.id);
|
|
|
|
|
|
|
|
|
|
if (!user.myCart) {
|
|
|
|
|
return res.status(400).json({ message: 'Cart is empty' });
|
|
|
|
|
}
|
|
|
|
|
const { productId, quantity } = req.body;
|
|
|
|
|
|
|
|
|
|
const itemIndex = user.myCart.findIndex(item => item.productId === productId);
|
|
|
|
|
// Validate quantity (e.g., must be positive, not exceed available inventory)
|
|
|
|
|
if (quantity <= 0) {
|
|
|
|
|
return res.status(400).json({ message: 'Quantity must be greater than zero' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (itemIndex === -1) {
|
|
|
|
|
return res.status(404).json({ message: 'Product not found in cart' });
|
|
|
|
|
// Update quantity in the cart using findByIdAndUpdate
|
|
|
|
|
const updatedUser = await User.findByIdAndUpdate(
|
|
|
|
|
req.user.id,
|
|
|
|
|
{ $set: { 'myCart.$[element].quantity': quantity } },
|
|
|
|
|
{
|
|
|
|
|
new: true, // return the updated document
|
|
|
|
|
arrayFilters: [{ 'element.productId': productId }] // update the element where productId matches
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Validate quantity (e.g., must be positive, not exceed available inventory)
|
|
|
|
|
if (quantity <= 0) {
|
|
|
|
|
return res.status(400).json({ message: 'Quantity must be greater than zero' });
|
|
|
|
|
}
|
|
|
|
|
if (!updatedUser) {
|
|
|
|
|
return res.status(404).json({ message: 'User not found' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update quantity in the cart
|
|
|
|
|
user.myCart[itemIndex].quantity = quantity;
|
|
|
|
|
if (!updatedUser.myCart) {
|
|
|
|
|
return res.status(400).json({ message: 'Cart is empty' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await user.save(); // Save the updated cart
|
|
|
|
|
res.json({ message: 'Product quantity updated successfully', updatedCart: updatedUser.myCart });
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(error);
|
|
|
|
|
res.status(500).json({ message: 'Error updating product quantity' });
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
res.json({ message: 'Product quantity updated successfully' });
|
|
|
|
|
console.log(user.myCart);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(error);
|
|
|
|
|
res.status(500).json({ message: 'Error updating product quantity' });
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
exports.removeProductFromCart = async (req, res) => {
|
|
|
|
|
try {
|
|
|
|
|