You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB
JavaScript

11 months ago
// userController.js
const User = require('../model/Cart');
exports.addToCart = async (req, res) => {
try {
const { userId, productId, quantity } = req.body;
// Check if the user exists
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found.' });
}
// Check if the product exists
const product = await Product.findById(productId);
if (!product) {
return res.status(404).json({ message: 'Product not found.' });
}
// Check if the product is active
if (!product.isActive) {
return res.status(400).json({ message: 'Product is not active.' });
}
// Check if the quantity is valid
if (quantity <= 0) {
return res.status(400).json({ message: 'Invalid quantity.' });
}
// Check if the user already has a cart
let cart = await Cart.findOne({ userId });
// If the user doesn't have a cart, create a new one
if (!cart) {
cart = new Cart({ userId, products: [], totalAmount: 0 });
}
// Check if the product is already in the cart
const existingProduct = cart.products.find(
(cartProduct) => cartProduct.productId.toString() === productId
);
// If the product is already in the cart, update the quantity and subtotal
if (existingProduct) {
existingProduct.quantity += quantity;
existingProduct.subtotal = existingProduct.quantity * existingProduct.price;
} else {
// If the product is not in the cart, add it
cart.products.push({
productId,
productName: product.name,
quantity,
price: product.price,
subtotal: quantity * product.price,
});
}
// Update the total amount in the cart
cart.totalAmount = cart.products.reduce(
(total, product) => total + product.subtotal,
0
);
// Save the updated cart
await cart.save();
return res.status(200).json({ message: 'Product added to cart successfully.' });
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'Internal server error.' });
}
}