Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added API for Cart #31

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions PCP/server/data/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ DROP TABLE IF EXISTS Retailers CASCADE;
DROP TABLE IF EXISTS ProductCategories CASCADE;
DROP TABLE IF EXISTS user_authentication CASCADE;
DROP TABLE IF EXISTS Currency CASCADE;
DROP TABLE IF EXISTS Cart CASCADE;


-- Create Product User Authentication Table
Expand Down Expand Up @@ -93,3 +94,13 @@ CREATE TABLE PriceAlerts (
FOREIGN KEY (user_id) REFERENCES user_authentication(user_id) ON DELETE CASCADE,
FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE CASCADE
);

-- Create Cart table
CREATE TABLE Cart (
CartID SERIAL PRIMARY KEY,
UserID INT NOT NULL,
ProductID INT NOT NULL,
Quantity INT NOT NULL DEFAULT 1,
FOREIGN KEY (UserID) REFERENCES user_authentication(user_id) ON DELETE CASCADE,
FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE CASCADE
);
62 changes: 62 additions & 0 deletions PCP/server/src/api/cart_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from flask import jsonify, make_response, request
from flask_restful import Resource

try:
from src.db.cart import get_cart_contents, add_item_to_cart, remove_item_from_cart
from src.utilities.swen_344_db_utils import exec_get_all
except ImportError:
from db.cart import get_cart_contents, add_item_to_cart, remove_item_from_cart
from utilities.swen_344_db_utils import exec_get_all


def verify_session_key(session_key):
"""Check the session key and return the user ID if valid."""
query = "SELECT user_id FROM user_authentication WHERE session_key = %s;"
result = exec_get_all(query, (session_key,))
return result[0][0] if result else None


class Cart(Resource):
def get(self, user_id):
print(f"Fetching cart for user ID: {user_id}")
try:
cart_items = get_cart_contents(user_id)
print(f"Cart items: {cart_items}")
if not cart_items:
return jsonify({"error": "No items found in the cart"}), 404
return jsonify({"cart_items": cart_items})
except Exception as e:
print(f"Error: {e}")
return jsonify({"error": str(e)}), 500


class AddToCart(Resource):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be get , post and put in one class u don't have to make two class over here please fix it

def post(self, user_id, product_id, quantity):
"""Adds a new item to the shopping cart or updates the quantity if it already exists."""
try:
result = add_item_to_cart(user_id, product_id, quantity)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does it takes session_key as a input !! as I have explained it previously that user can only send the session_key and u guys have to put the code which validates the user based on the session_key and with that it stores the product_id in that user_id !!

if result:
return jsonify({'message': 'Item added to cart successfully'}), 200
else:
return jsonify({'error': 'Failed to add item to cart'}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500

class RemoveFromCart(Resource):
def delete(self, product_id):
# Retrieve session key from the request headers
session_key = request.headers.get('X-Session-Key')
if not session_key:
return make_response(jsonify({"message": "No session key provided."}), 401)

# Verify the session key and get the associated user ID
user_id = verify_session_key(session_key)
if not user_id:
return make_response(jsonify({"message": "Invalid session key."}), 401)

# Proceed with deleting the item from the cart
try:
remove_item_from_cart(user_id, product_id)
return make_response(jsonify({'message': 'Item removed from cart successfully'}), 204)
except Exception as e:
return make_response(jsonify({"error": str(e)}), 500)
34 changes: 34 additions & 0 deletions PCP/server/src/db/cart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
try:
from src.utilities.swen_344_db_utils import exec_get_all, exec_commit
except ImportError:
from utilities.swen_344_db_utils import exec_get_all, exec_commit


def get_cart_contents(user_id):
"""Fetches all items in the user's cart."""
sql = """
SELECT p.ProductID, p.ProductName, p.ProductDescription, p.ImageURL, c.Quantity, pr.Price
FROM Cart c
JOIN Products p ON c.ProductID = p.ProductID
JOIN Prices pr ON p.ProductID = pr.ProductID
WHERE c.UserID = %s;
"""
result = exec_get_all(sql, (user_id,))
return result


def add_item_to_cart(user_id, product_id, quantity):
"""Adds a new item or updates the quantity of an existing item in the cart."""
sql = """
INSERT INTO Cart (UserID, ProductID, Quantity)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE Quantity = Quantity + VALUES(Quantity);
"""
result = exec_commit(sql, (user_id, product_id, quantity))
return result


def remove_item_from_cart(user_id, product_id):
"""Removes an item from the cart."""
sql = "DELETE FROM Cart WHERE UserID = %s AND ProductID = %s;"
exec_commit(sql, (user_id, product_id))
11 changes: 8 additions & 3 deletions PCP/server/src/server.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from flask_restful import Api

try:
from utilities.swen_344_db_utils import *
Expand All @@ -14,7 +14,8 @@
from api.retailer_api import *
from api.prices_api import *
from api.user_favorites_api import *
except:
from api.cart_api import Cart, AddToCart, RemoveFromCart
except ImportError:
from .utilities.swen_344_db_utils import *
from .api.login_api import *
from .api.signup_api import *
Expand All @@ -26,7 +27,8 @@
from .api.retailer_api import *
from .api.prices_api import *
from .api.user_favorites_api import *

from .api.cart_api import Cart, AddToCart, RemoveFromCart

app = Flask(__name__) # create Flask instance
CORS(app) # Enable CORS on Flask server to work with Nodejs pages
api = Api(app) # api router
Expand All @@ -47,6 +49,9 @@
api.add_resource(Prices, '/prices')
api.add_resource(UserFavorites, '/user_favorites')
api.add_resource(UserFavoritesById, '/user_favorites/<int:user_id>')
api.add_resource(Cart, '/cart/<int:user_id>')
api.add_resource(AddToCart, '/addtocart/<int:user_id>/<int:product_id>/<int:quantity>')
api.add_resource(RemoveFromCart, '/removefromcart/<int:user_id>/<int:product_id>')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please DOnt make two API for Remove and Add I will put a PUT Request !! instead so do that



def setup_database():
Expand Down
2 changes: 1 addition & 1 deletion PCP/server/tests/1_api/test_3_logout_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_1_successful_logout(self, mock_post):
self.assertEqual(response.status_code, 200)

# Simulating extracting session key from login response
session_key = response.json().get('sessionKey')
session_key = response.get('sessionKey')
self.assertIsNotNone(session_key, "Session key should not be None")

# Simulating logout with the session key
Expand Down
Loading