Capstone 2 update resources [readme.md] for details

master
Ron Reciproco 11 months ago
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.' });
}
// Check if the quantity is valid
if (quantity <= 0) {
return res.status(400).json({ message: 'Invalid quantity.' });
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;
// Check if the user already has a cart
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
);
const existingItem = cart.items.find(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,
});
if (!existingItem) {
return res.status(404).json({ error: 'Product not found in the 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' });
}
};
// Update the total amount in the cart
cart.totalAmount = cart.products.reduce(
(total, product) => total + product.subtotal,
0
);
exports.removeFromCart = async (req, res) => {
const { userId, productId } = req.body;
try {
let cart = await Cart.findOne({ userId });
if (!cart) {
return res.status(404).json({ error: 'Cart not found for the user' });
}
cart.items = cart.items.filter(item => item.productId.toString() !== productId);
// Save the updated cart
await cart.save();
return res.status(200).json({ message: 'Product added to cart successfully.' });
res.json({ message: 'Product removed from cart successfully' });
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'Internal server 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' });
}
// Calculate subtotal for each item
const itemsWithSubtotal = cart.items.map(item => ({
...item.toObject(),
subtotal: item.quantity * item.productId.price,
}));
// Calculate total price for all items
const totalPrice = itemsWithSubtotal.reduce((total, item) => total + item.subtotal, 0);
res.json({
items: itemsWithSubtotal,
totalPrice,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

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

@ -104,3 +104,37 @@ http://localhost:3000/user/retrieveUser
"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 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…
Cancel
Save