71 lines
2.1 KiB
Python
71 lines
2.1 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 get_current_user
|
|
from app.models import User
|
|
|
|
router = APIRouter(prefix="/api/cart", tags=["cart"])
|
|
|
|
|
|
@router.get("", response_model=CartResponse)
|
|
def get_user_cart(
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
cart = get_cart(db, current_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(
|
|
item: CartItemCreate,
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
cart_item = add_to_cart(db, current_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,
|
|
update: CartItemUpdate,
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
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,
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
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(
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
if not clear_cart(db, current_user.id):
|
|
raise HTTPException(status_code=404, detail="Cart not found")
|
|
return {"message": "Cart cleared"}
|