54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
from typing import List, Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.cart import CartItem
|
|
from app.schemas.cart import CartItemCreate, CartItemUpdate
|
|
from app.services.base import CRUDBase
|
|
|
|
|
|
class CartService(CRUDBase[CartItem, CartItemCreate, CartItemUpdate]):
|
|
def get_cart_items(self, db: Session, *, user_id: int) -> List[CartItem]:
|
|
return db.query(CartItem).filter(CartItem.user_id == user_id).all()
|
|
|
|
def get_cart_item(
|
|
self, db: Session, *, user_id: int, product_id: int
|
|
) -> Optional[CartItem]:
|
|
return (
|
|
db.query(CartItem)
|
|
.filter(CartItem.user_id == user_id, CartItem.product_id == product_id)
|
|
.first()
|
|
)
|
|
|
|
def add_item_to_cart(
|
|
self, db: Session, *, obj_in: CartItemCreate, user_id: int, unit_price: float
|
|
) -> CartItem:
|
|
db_obj = CartItem(
|
|
user_id=user_id,
|
|
product_id=obj_in.product_id,
|
|
quantity=obj_in.quantity,
|
|
unit_price=unit_price
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def update_item_quantity(
|
|
self, db: Session, *, db_obj: CartItem, quantity: int
|
|
) -> CartItem:
|
|
db_obj.quantity = quantity
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def clear_cart(self, db: Session, *, user_id: int) -> List[CartItem]:
|
|
cart_items = self.get_cart_items(db, user_id=user_id)
|
|
for item in cart_items:
|
|
db.delete(item)
|
|
db.commit()
|
|
return cart_items
|
|
|
|
cart_service = CartService(CartItem)
|