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.

110 lines
2.7 KiB
JavaScript

const Cart = require('../model/Cart');
11 months ago
exports.addToCart = async (req, res) => {
const { userId } = req.body;
const { productId, quantity } = req.body;
11 months ago
try {
let cart = await Cart.findOne({ userId });
11 months ago
if (!cart) {
cart = new Cart({
userId,
items: [{ productId, quantity }],
});
} else {
const existingItem = cart.items.find(item => item.productId.toString() === productId);
11 months ago
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.items.push({ productId, quantity });
}
11 months ago
}
await cart.save();
res.json({ message: 'Item added to cart successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
exports.updateQuantity = async (req, res) => {
const { userId, productId, quantity } = req.body;
try {
let cart = await Cart.findOne({ userId });
if (!cart) {
return res.status(404).json({ error: 'Cart not found for the user' });
11 months ago
}
const existingItem = cart.items.find(item => item.productId.toString() === productId);
if (!existingItem) {
return res.status(404).json({ error: 'Product not found in the cart' });
11 months ago
}
existingItem.quantity = quantity;
await cart.save();
res.json({ message: 'Quantity updated successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
exports.removeFromCart = async (req, res) => {
const { userId, productId } = req.body;
try {
11 months ago
let cart = await Cart.findOne({ userId });
if (!cart) {
return res.status(404).json({ error: 'Cart not found for the user' });
11 months ago
}
cart.items = cart.items.filter(item => item.productId.toString() !== productId);
11 months ago
await cart.save();
res.json({ message: 'Product removed from cart successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
exports.getCartDetails = async (req, res) => {
const { userId } = req.body;
try {
const cart = await Cart.findOne({ userId }).populate('items.productId', 'name price');
if (!cart) {
return res.status(404).json({ error: 'Cart not found for the user' });
11 months ago
}
// Calculate subtotal for each item
const itemsWithSubtotal = cart.items.map(item => ({
...item.toObject(),
subtotal: item.quantity * item.productId.price,
}));
11 months ago
// Calculate total price for all items
const totalPrice = itemsWithSubtotal.reduce((total, item) => total + item.subtotal, 0);
11 months ago
res.json({
items: itemsWithSubtotal,
totalPrice,
});
11 months ago
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
11 months ago
}
};