|
|
@ -356,36 +356,36 @@ exports.updateProductQuantity = async (req, res) => {
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
const { productId, quantity } = req.body;
|
|
|
|
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 itemIndex = user.myCart.findIndex(item => item.productId === productId);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (itemIndex === -1) {
|
|
|
|
|
|
|
|
return res.status(404).json({ message: 'Product not found in cart' });
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Validate quantity (e.g., must be positive, not exceed available inventory)
|
|
|
|
// Validate quantity (e.g., must be positive, not exceed available inventory)
|
|
|
|
if (quantity <= 0) {
|
|
|
|
if (quantity <= 0) {
|
|
|
|
return res.status(400).json({ message: 'Quantity must be greater than zero' });
|
|
|
|
return res.status(400).json({ message: 'Quantity must be greater than zero' });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Update quantity in the cart
|
|
|
|
// Update quantity in the cart using findByIdAndUpdate
|
|
|
|
user.myCart[itemIndex].quantity = quantity;
|
|
|
|
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
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (!updatedUser) {
|
|
|
|
|
|
|
|
return res.status(404).json({ message: 'User not found' });
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
await user.save(); // Save the updated cart
|
|
|
|
if (!updatedUser.myCart) {
|
|
|
|
|
|
|
|
return res.status(400).json({ message: 'Cart is empty' });
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
res.json({ message: 'Product quantity updated successfully' });
|
|
|
|
res.json({ message: 'Product quantity updated successfully', updatedCart: updatedUser.myCart });
|
|
|
|
console.log(user.myCart);
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
console.error(error);
|
|
|
|
res.status(500).json({ message: 'Error updating product quantity' });
|
|
|
|
res.status(500).json({ message: 'Error updating product quantity' });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exports.removeProductFromCart = async (req, res) => {
|
|
|
|
exports.removeProductFromCart = async (req, res) => {
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|