Capstone 2 update resources [readme.md] for details
parent
a7656ebf9e
commit
fa386ce7c8
@ -1,72 +1,109 @@
|
||||
// userController.js
|
||||
const User = require('../model/Cart');
|
||||
const Cart = require('../model/Cart');
|
||||
|
||||
exports.addToCart = async (req, res) => {
|
||||
const { userId } = req.body;
|
||||
const { productId, quantity } = req.body;
|
||||
|
||||
try {
|
||||
const { userId, productId, quantity } = req.body;
|
||||
let cart = await Cart.findOne({ userId });
|
||||
|
||||
// Check if the user exists
|
||||
const user = await User.findById(userId);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: 'User not found.' });
|
||||
}
|
||||
if (!cart) {
|
||||
cart = new Cart({
|
||||
userId,
|
||||
items: [{ productId, quantity }],
|
||||
});
|
||||
} else {
|
||||
const existingItem = cart.items.find(item => item.productId.toString() === productId);
|
||||
|
||||
// Check if the product exists
|
||||
const product = await Product.findById(productId);
|
||||
if (!product) {
|
||||
return res.status(404).json({ message: 'Product not found.' });
|
||||
if (existingItem) {
|
||||
existingItem.quantity += quantity;
|
||||
} else {
|
||||
cart.items.push({ productId, quantity });
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the product is active
|
||||
if (!product.isActive) {
|
||||
return res.status(400).json({ message: 'Product is not active.' });
|
||||
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' });
|
||||
}
|
||||
|
||||
// Check if the quantity is valid
|
||||
if (quantity <= 0) {
|
||||
return res.status(400).json({ message: 'Invalid quantity.' });
|
||||
const existingItem = cart.items.find(item => item.productId.toString() === productId);
|
||||
|
||||
if (!existingItem) {
|
||||
return res.status(404).json({ error: 'Product not found in the cart' });
|
||||
}
|
||||
|
||||
// Check if the user already has a cart
|
||||
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 {
|
||||
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 });
|
||||
return res.status(404).json({ error: 'Cart not found for the user' });
|
||||
}
|
||||
|
||||
// Check if the product is already in the cart
|
||||
const existingProduct = cart.products.find(
|
||||
(cartProduct) => cartProduct.productId.toString() === productId
|
||||
);
|
||||
cart.items = cart.items.filter(item => item.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,
|
||||
});
|
||||
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' });
|
||||
}
|
||||
|
||||
// Update the total amount in the cart
|
||||
cart.totalAmount = cart.products.reduce(
|
||||
(total, product) => total + product.subtotal,
|
||||
0
|
||||
);
|
||||
// Calculate subtotal for each item
|
||||
const itemsWithSubtotal = cart.items.map(item => ({
|
||||
...item.toObject(),
|
||||
subtotal: item.quantity * item.productId.price,
|
||||
}));
|
||||
|
||||
// Save the updated cart
|
||||
await cart.save();
|
||||
// Calculate total price for all items
|
||||
const totalPrice = itemsWithSubtotal.reduce((total, item) => total + item.subtotal, 0);
|
||||
|
||||
return res.status(200).json({ message: 'Product added to cart successfully.' });
|
||||
res.json({
|
||||
items: itemsWithSubtotal,
|
||||
totalPrice,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.status(500).json({ message: 'Internal server error.' });
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -1,10 +1,20 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const cart = require('../controllers/cart');
|
||||
const auth = require("../auth")
|
||||
const cartController = require('../controllers/cart');
|
||||
const auth = require("../auth");
|
||||
|
||||
const { authenticateToken, } = auth
|
||||
// Add route to handle adding a product to the cart
|
||||
router.post('/add-to-cart', authenticateToken, cart.addToCart);
|
||||
const { authenticateToken } = auth;
|
||||
|
||||
// Route to add an item to the cart
|
||||
router.post('/add-to-cart', authenticateToken, cartController.addToCart);
|
||||
|
||||
// Route to update product quantity in the cart
|
||||
router.put('/update-quantity', authenticateToken, cartController.updateQuantity);
|
||||
|
||||
// Route to remove a product from the cart
|
||||
router.delete('/remove-from-cart', authenticateToken, cartController.removeFromCart);
|
||||
|
||||
// Route to get cart details
|
||||
router.get('/cart-details', authenticateToken, cartController.getCartDetails);
|
||||
|
||||
module.exports = router;
|
||||
|
Loading…
Reference in New Issue