Capstone 2 update resources [readme.md] for details

master
Ron Reciproco 1 year ago
parent a7656ebf9e
commit fa386ce7c8

@ -1,72 +1,109 @@
// userController.js const Cart = require('../model/Cart');
const User = require('../model/Cart');
exports.addToCart = async (req, res) => { exports.addToCart = async (req, res) => {
const { userId } = req.body;
const { productId, quantity } = req.body;
try { try {
const { userId, productId, quantity } = req.body; let cart = await Cart.findOne({ userId });
// Check if the user exists if (!cart) {
const user = await User.findById(userId); cart = new Cart({
if (!user) { userId,
return res.status(404).json({ message: 'User not found.' }); items: [{ productId, quantity }],
} });
} else {
const existingItem = cart.items.find(item => item.productId.toString() === productId);
// Check if the product exists if (existingItem) {
const product = await Product.findById(productId); existingItem.quantity += quantity;
if (!product) { } else {
return res.status(404).json({ message: 'Product not found.' }); cart.items.push({ productId, quantity });
}
} }
// Check if the product is active await cart.save();
if (!product.isActive) {
return res.status(400).json({ message: 'Product is not active.' }); 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 const existingItem = cart.items.find(item => item.productId.toString() === productId);
if (quantity <= 0) {
return res.status(400).json({ message: 'Invalid quantity.' }); 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 }); let cart = await Cart.findOne({ userId });
// If the user doesn't have a cart, create a new one
if (!cart) { 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 cart.items = cart.items.filter(item => item.productId.toString() !== productId);
const existingProduct = cart.products.find(
(cartProduct) => cartProduct.productId.toString() === productId
);
// If the product is already in the cart, update the quantity and subtotal await cart.save();
if (existingProduct) {
existingProduct.quantity += quantity; res.json({ message: 'Product removed from cart successfully' });
existingProduct.subtotal = existingProduct.quantity * existingProduct.price; } catch (error) {
} else { console.error(error);
// If the product is not in the cart, add it res.status(500).json({ error: 'Internal Server Error' });
cart.products.push({ }
productId, };
productName: product.name,
quantity, exports.getCartDetails = async (req, res) => {
price: product.price, const { userId } = req.body;
subtotal: quantity * product.price,
}); 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 // Calculate subtotal for each item
cart.totalAmount = cart.products.reduce( const itemsWithSubtotal = cart.items.map(item => ({
(total, product) => total + product.subtotal, ...item.toObject(),
0 subtotal: item.quantity * item.productId.price,
); }));
// Save the updated cart // Calculate total price for all items
await cart.save(); 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) { } catch (error) {
console.error(error); console.error(error);
return res.status(500).json({ message: 'Internal server error.' }); res.status(500).json({ error: 'Internal Server Error' });
} }
} };

@ -1,25 +1,23 @@
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const cartProductSchema = new mongoose.Schema({ const cartItemSchema = new mongoose.Schema({
productId: { productId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: 'Product', ref: 'Product',
required: true, required: true,
}, },
productName: { type: String, required: true }, quantity: {
quantity: { type: Number, required: true }, type: Number,
price: { type: Number, required: true }, default: 1,
subtotal: { type: Number, required: true }, },
}); });
const cartSchema = new mongoose.Schema({ const cartSchema = new mongoose.Schema({
userId: { userId: {
type: mongoose.Schema.Types.ObjectId, type: String,
ref: 'User',
required: true, required: true,
}, },
products: [cartProductSchema], items: [cartItemSchema],
totalAmount: { type: Number, required: true },
}); });
const Cart = mongoose.model('Cart', cartSchema); const Cart = mongoose.model('Cart', cartSchema);

@ -104,3 +104,37 @@ http://localhost:3000/user/retrieveUser
"userId": "6554ac8dd7fbf9ee90217e77" "userId": "6554ac8dd7fbf9ee90217e77"
} }
CART - Add to Cart
--> Must use token
http://localhost:3000/cart/add-to-cart
{
"userId": "655396dcc8ea29f42422e214",
"productId": "6553a54566c4c86c39034b55",
"quantity": 5
}
CART - Delete Item
http://localhost:3000/cart/remove-from-cart
--> Must use token
{
"userId": "655396dcc8ea29f42422e214",
"productId": "6553a55666c4c86c39034b59",
"quantity": 1
}
CART - Update Quantity
http://localhost:3000/cart//update-quantity
--> Must use token
{
"userId": "655396dcc8ea29f42422e214",
"productId": "6553a55666c4c86c39034b59",
"quantity": 2000 // Update to the desired quantity
}
CART - Cart Details [ Total ]
--> Must use token
http://localhost:3000/cart/cart-details
{
"userId": "655396dcc8ea29f42422e214"
}

@ -1,10 +1,20 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const cart = require('../controllers/cart'); const cartController = require('../controllers/cart');
const auth = require("../auth") const auth = require("../auth");
const { authenticateToken, } = auth const { authenticateToken } = auth;
// Add route to handle adding a product to the cart
router.post('/add-to-cart', authenticateToken, cart.addToCart); // 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; module.exports = router;

Loading…
Cancel
Save