From fa386ce7c8d2a2097742377ce887f4f8f078870c Mon Sep 17 00:00:00 2001 From: snaked2018 Date: Wed, 15 Nov 2023 22:04:37 +0800 Subject: [PATCH] Capstone 2 update resources [readme.md] for details --- .../csp2-reciproco/controllers/cart.js | 133 +++++++++++------- .../backend/csp2-reciproco/model/Cart.js | 16 +-- individual/backend/csp2-reciproco/readme.md | 34 +++++ .../backend/csp2-reciproco/routes/cart.js | 20 ++- 4 files changed, 141 insertions(+), 62 deletions(-) diff --git a/individual/backend/csp2-reciproco/controllers/cart.js b/individual/backend/csp2-reciproco/controllers/cart.js index 1256022..47f57eb 100644 --- a/individual/backend/csp2-reciproco/controllers/cart.js +++ b/individual/backend/csp2-reciproco/controllers/cart.js @@ -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' }); } -} +}; diff --git a/individual/backend/csp2-reciproco/model/Cart.js b/individual/backend/csp2-reciproco/model/Cart.js index d7bfebb..7055c5d 100644 --- a/individual/backend/csp2-reciproco/model/Cart.js +++ b/individual/backend/csp2-reciproco/model/Cart.js @@ -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); diff --git a/individual/backend/csp2-reciproco/readme.md b/individual/backend/csp2-reciproco/readme.md index 7b6ba8b..c0a2e9d 100644 --- a/individual/backend/csp2-reciproco/readme.md +++ b/individual/backend/csp2-reciproco/readme.md @@ -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" +} \ No newline at end of file diff --git a/individual/backend/csp2-reciproco/routes/cart.js b/individual/backend/csp2-reciproco/routes/cart.js index fe32e4a..8c4317b 100644 --- a/individual/backend/csp2-reciproco/routes/cart.js +++ b/individual/backend/csp2-reciproco/routes/cart.js @@ -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;