68 lines
2.3 KiB
Python
68 lines
2.3 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from app.database.database import get_db
|
|
from app.schemas.cart import CartItemCreate, CartItemUpdate, CartResponse
|
|
from app.services.cart import (
|
|
add_to_cart,
|
|
get_cart,
|
|
update_cart_item,
|
|
remove_from_cart,
|
|
clear_cart,
|
|
)
|
|
from app.services.auth import verify_token
|
|
|
|
router = APIRouter(prefix="/api/cart", tags=["cart"])
|
|
|
|
|
|
def get_user_id_from_token(token: str) -> int:
|
|
user_id = verify_token(token)
|
|
if user_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token",
|
|
)
|
|
return user_id
|
|
|
|
|
|
@router.get("", response_model=CartResponse)
|
|
def get_user_cart(token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
cart = get_cart(db, user_id)
|
|
if not cart:
|
|
raise HTTPException(status_code=404, detail="Cart not found")
|
|
return cart
|
|
|
|
|
|
@router.post("/add", response_model=dict)
|
|
def add_item_to_cart(token: str, item: CartItemCreate, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
cart_item = add_to_cart(db, user_id, item)
|
|
return {"message": "Item added to cart", "item_id": cart_item.id}
|
|
|
|
|
|
@router.put("/{cart_item_id}", response_model=dict)
|
|
def update_item(
|
|
cart_item_id: int, token: str, update: CartItemUpdate, db: Session = Depends(get_db)
|
|
):
|
|
user_id = get_user_id_from_token(token)
|
|
cart_item = update_cart_item(db, cart_item_id, update)
|
|
if not cart_item:
|
|
raise HTTPException(status_code=404, detail="Cart item not found")
|
|
return {"message": "Item updated", "quantity": cart_item.quantity}
|
|
|
|
|
|
@router.delete("/{cart_item_id}")
|
|
def remove_item(cart_item_id: int, token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
if not remove_from_cart(db, cart_item_id):
|
|
raise HTTPException(status_code=404, detail="Cart item not found")
|
|
return {"message": "Item removed from cart"}
|
|
|
|
|
|
@router.delete("")
|
|
def clear_user_cart(token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
if not clear_cart(db, user_id):
|
|
raise HTTPException(status_code=404, detail="Cart not found")
|
|
return {"message": "Cart cleared"}
|