18 KiB
18 KiB
Subtask: Shopping Cart Management
Parent Task: Decomp/004 Subtask ID: Decomp-004-02 Dependencies: Decomp-004-01 (Database Schema)
Description
Implement shopping cart service with support for both authenticated customers and guest sessions. Handle cart persistence, item management, price calculation, and cart-to-order conversion.
Requirements
- Create and retrieve carts for customers and guests
- Add, update, remove items from cart
- Handle product availability checks
- Calculate cart totals (subtotal, tax, shipping)
- Support quantity validation
- Cart merging (guest cart → customer cart on login)
- Cart expiration for guest carts
- Product snapshot for price consistency
Technical Specifications
Cart service implementation:
from datetime import datetime, timedelta, timezone
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field
from decimal import Decimal
import uuid
import logging
logger = logging.getLogger(__name__)
@dataclass
class CartItem:
"""Shopping cart item."""
id: int
product_id: int
sku: str
name: str
quantity: int
unit_price: Decimal
total_price: Decimal
product_snapshot: dict = None
@dataclass
class CartTotals:
"""Calculated cart totals."""
subtotal: Decimal
tax_amount: Decimal
shipping_amount: Decimal
discount_amount: Decimal
total: Decimal
currency: str = "USD"
@dataclass
class ShoppingCart:
"""Shopping cart with items and totals."""
id: int
customer_id: Optional[int]
session_id: Optional[str]
items: List[CartItem] = field(default_factory=list)
totals: CartTotals = None
created_at: datetime = None
updated_at: datetime = None
expires_at: datetime = None
class CartService:
"""Service for managing shopping carts."""
def __init__(self, db, product_service, tax_service=None):
self.db = db
self.product_service = product_service
self.tax_service = tax_service
async def get_or_create_cart(
self,
customer_id: int = None,
session_id: str = None
) -> ShoppingCart:
"""Get existing cart or create new one."""
if not customer_id and not session_id:
session_id = str(uuid.uuid4())
async with self.db.acquire() as conn:
# Try to find existing cart
if customer_id:
cart = await conn.fetchrow(
"""SELECT * FROM shopping_carts
WHERE customer_id = $1
AND (expires_at IS NULL OR expires_at > NOW())
ORDER BY created_at DESC
LIMIT 1""",
customer_id
)
elif session_id:
cart = await conn.fetchrow(
"""SELECT * FROM shopping_carts
WHERE session_id = $1
AND (expires_at IS NULL OR expires_at > NOW())
LIMIT 1""",
session_id
)
else:
cart = None
if cart:
return await self._load_cart(conn, dict(cart))
# Create new cart
new_cart = await conn.fetchrow(
"""INSERT INTO shopping_carts (customer_id, session_id, expires_at)
VALUES ($1, $2, $3)
RETURNING *""",
customer_id,
session_id,
datetime.now(timezone.utc) + timedelta(days=7) if not customer_id else None
)
return await self._load_cart(conn, dict(new_cart))
async def _load_cart(self, conn, cart_data: dict) -> ShoppingCart:
"""Load cart with items."""
# Load cart items
items_rows = await conn.fetch(
"""SELECT ci.*, p.sku, p.name
FROM cart_items ci
JOIN products p ON p.id = ci.product_id
WHERE ci.cart_id = $1""",
cart_data["id"]
)
items = [
CartItem(
id=row["id"],
product_id=row["product_id"],
sku=row["sku"],
name=row["name"],
quantity=row["quantity"],
unit_price=Decimal(str(row["unit_price"])),
total_price=Decimal(str(row["unit_price"])) * row["quantity"],
product_snapshot=row.get("product_snapshot")
)
for row in items_rows
]
return ShoppingCart(
id=cart_data["id"],
customer_id=cart_data["customer_id"],
session_id=cart_data["session_id"],
items=items,
created_at=cart_data["created_at"],
updated_at=cart_data["updated_at"],
expires_at=cart_data["expires_at"]
)
async def add_item(
self,
cart_id: int,
product_id: int,
quantity: int = 1
) -> CartItem:
"""Add item to cart or update quantity if exists."""
if quantity <= 0:
raise ValueError("Quantity must be positive")
# Get product info and current price
product = await self.product_service.get_product(product_id)
if not product:
raise ValueError(f"Product {product_id} not found")
if not product["is_active"]:
raise ValueError(f"Product {product_id} is not available")
# Check inventory availability
available = await self.product_service.get_available_quantity(product_id)
if available < quantity:
raise ValueError(f"Insufficient inventory. Available: {available}")
async with self.db.acquire() as conn:
# Check if item already exists in cart
existing = await conn.fetchrow(
"""SELECT * FROM cart_items
WHERE cart_id = $1 AND product_id = $2""",
cart_id, product_id
)
if existing:
# Update quantity
new_quantity = existing["quantity"] + quantity
if available < new_quantity:
raise ValueError(f"Insufficient inventory for quantity {new_quantity}")
await conn.execute(
"""UPDATE cart_items
SET quantity = $1, updated_at = NOW()
WHERE id = $2""",
new_quantity, existing["id"]
)
return CartItem(
id=existing["id"],
product_id=product_id,
sku=product["sku"],
name=product["name"],
quantity=new_quantity,
unit_price=Decimal(str(product["price"])),
total_price=Decimal(str(product["price"])) * new_quantity
)
else:
# Create product snapshot
snapshot = {
"id": product["id"],
"sku": product["sku"],
"name": product["name"],
"price": str(product["price"])
}
# Add new item
item = await conn.fetchrow(
"""INSERT INTO cart_items (cart_id, product_id, quantity, unit_price, product_snapshot)
VALUES ($1, $2, $3, $4, $5)
RETURNING *""",
cart_id, product_id, quantity, product["price"], snapshot
)
return CartItem(
id=item["id"],
product_id=product_id,
sku=product["sku"],
name=product["name"],
quantity=quantity,
unit_price=Decimal(str(product["price"])),
total_price=Decimal(str(product["price"])) * quantity,
product_snapshot=snapshot
)
async def update_item_quantity(
self,
cart_id: int,
item_id: int,
quantity: int
) -> CartItem:
"""Update cart item quantity."""
if quantity <= 0:
await self.remove_item(cart_id, item_id)
return None
async with self.db.acquire() as conn:
# Get item with product info
item = await conn.fetchrow(
"""SELECT ci.*, p.sku, p.name
FROM cart_items ci
JOIN products p ON p.id = ci.product_id
WHERE ci.id = $1 AND ci.cart_id = $2""",
item_id, cart_id
)
if not item:
raise ValueError("Cart item not found")
# Check availability
available = await self.product_service.get_available_quantity(item["product_id"])
if available < quantity:
raise ValueError(f"Insufficient inventory. Available: {available}")
await conn.execute(
"""UPDATE cart_items
SET quantity = $1, updated_at = NOW()
WHERE id = $2""",
quantity, item_id
)
return CartItem(
id=item_id,
product_id=item["product_id"],
sku=item["sku"],
name=item["name"],
quantity=quantity,
unit_price=Decimal(str(item["unit_price"])),
total_price=Decimal(str(item["unit_price"])) * quantity
)
async def remove_item(self, cart_id: int, item_id: int):
"""Remove item from cart."""
async with self.db.acquire() as conn:
result = await conn.execute(
"DELETE FROM cart_items WHERE id = $1 AND cart_id = $2",
item_id, cart_id
)
if result == "DELETE 0":
raise ValueError("Cart item not found")
async def clear_cart(self, cart_id: int):
"""Remove all items from cart."""
async with self.db.acquire() as conn:
await conn.execute("DELETE FROM cart_items WHERE cart_id = $1", cart_id)
async def calculate_totals(
self,
cart: ShoppingCart,
shipping_address: dict = None
) -> CartTotals:
"""Calculate cart totals including tax and shipping."""
subtotal = sum(item.total_price for item in cart.items)
# Calculate tax (if service available)
tax_amount = Decimal("0")
if self.tax_service and shipping_address:
tax_amount = await self.tax_service.calculate_tax(
cart.items, shipping_address
)
# Calculate shipping (simple flat rate for now)
shipping_amount = await self._calculate_shipping(cart, shipping_address)
# Calculate discounts (placeholder)
discount_amount = Decimal("0")
total = subtotal + tax_amount + shipping_amount - discount_amount
return CartTotals(
subtotal=subtotal,
tax_amount=tax_amount,
shipping_amount=shipping_amount,
discount_amount=discount_amount,
total=total
)
async def _calculate_shipping(
self,
cart: ShoppingCart,
address: dict = None
) -> Decimal:
"""Calculate shipping cost."""
# Free shipping for orders over $50
if any(item.total_price >= Decimal("50") for item in cart.items):
return Decimal("0")
# Default flat rate
return Decimal("9.99")
async def merge_carts(self, source_cart_id: int, target_cart_id: int):
"""Merge source cart into target cart (e.g., guest → customer)."""
async with self.db.acquire() as conn:
async with conn.transaction():
# Get items from source cart
source_items = await conn.fetch(
"SELECT * FROM cart_items WHERE cart_id = $1",
source_cart_id
)
for item in source_items:
# Check if target has same product
existing = await conn.fetchrow(
"""SELECT * FROM cart_items
WHERE cart_id = $1 AND product_id = $2""",
target_cart_id, item["product_id"]
)
if existing:
# Update quantity
await conn.execute(
"""UPDATE cart_items
SET quantity = quantity + $1
WHERE id = $2""",
item["quantity"], existing["id"]
)
else:
# Move item to target cart
await conn.execute(
"""UPDATE cart_items
SET cart_id = $1
WHERE id = $2""",
target_cart_id, item["id"]
)
# Delete source cart
await conn.execute(
"DELETE FROM shopping_carts WHERE id = $1",
source_cart_id
)
async def delete_cart(self, cart_id: int):
"""Delete cart completely."""
async with self.db.acquire() as conn:
await conn.execute("DELETE FROM shopping_carts WHERE id = $1", cart_id)
async def expire_guest_carts(self, older_than_days: int = 7):
"""Delete expired guest carts."""
async with self.db.acquire() as conn:
result = await conn.execute(
"""DELETE FROM shopping_carts
WHERE customer_id IS NULL
AND expires_at < NOW()"""
)
deleted = int(result.split()[-1]) if result else 0
logger.info(f"Deleted {deleted} expired guest carts")
return deleted
Cart API endpoints:
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from typing import Optional, List
router = APIRouter(prefix="/cart", tags=["cart"])
class AddItemRequest(BaseModel):
product_id: int
quantity: int = 1
class UpdateItemRequest(BaseModel):
item_id: int
quantity: int
class CartResponse(BaseModel):
id: int
items: List[dict]
totals: dict
item_count: int
@router.get("/", response_model=CartResponse)
async def get_cart(
customer_id: Optional[int] = None,
session_id: Optional[str] = None
):
"""Get current shopping cart."""
cart_service = get_cart_service()
cart = await cart_service.get_or_create_cart(customer_id, session_id)
cart.totals = await cart_service.calculate_totals(cart)
return CartResponse(
id=cart.id,
items=[{
"id": item.id,
"product_id": item.product_id,
"sku": item.sku,
"name": item.name,
"quantity": item.quantity,
"unit_price": str(item.unit_price),
"total_price": str(item.total_price)
} for item in cart.items],
totals={
"subtotal": str(cart.totals.subtotal),
"tax": str(cart.totals.tax_amount),
"shipping": str(cart.totals.shipping_amount),
"total": str(cart.totals.total)
},
item_count=sum(item.quantity for item in cart.items)
)
@router.post("/items")
async def add_to_cart(
request: AddItemRequest,
customer_id: Optional[int] = None,
session_id: Optional[str] = None
):
"""Add item to cart."""
cart_service = get_cart_service()
cart = await cart_service.get_or_create_cart(customer_id, session_id)
try:
item = await cart_service.add_item(
cart.id,
request.product_id,
request.quantity
)
return {"success": True, "item": {"id": item.id, "quantity": item.quantity}}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.put("/items")
async def update_item(
request: UpdateItemRequest,
customer_id: Optional[int] = None,
session_id: Optional[str] = None
):
"""Update cart item quantity."""
cart_service = get_cart_service()
cart = await cart_service.get_or_create_cart(customer_id, session_id)
try:
item = await cart_service.update_item_quantity(
cart.id,
request.item_id,
request.quantity
)
if item:
return {"success": True, "quantity": item.quantity}
return {"success": True, "removed": True}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.delete("/items/{item_id}")
async def remove_item(
item_id: int,
customer_id: Optional[int] = None,
session_id: Optional[str] = None
):
"""Remove item from cart."""
cart_service = get_cart_service()
cart = await cart_service.get_or_create_cart(customer_id, session_id)
await cart_service.remove_item(cart.id, item_id)
return {"success": True}
@router.delete("/")
async def clear_cart(
customer_id: Optional[int] = None,
session_id: Optional[str] = None
):
"""Clear all items from cart."""
cart_service = get_cart_service()
cart = await cart_service.get_or_create_cart(customer_id, session_id)
await cart_service.clear_cart(cart.id)
return {"success": True}
Acceptance Criteria
- Carts can be created for customers and guests
- Items can be added, updated, removed
- Quantities are validated against inventory
- Cart totals are calculated correctly
- Guest carts expire after configured time
- Carts merge correctly on login
- Product prices are snapshotted
Notes
Trade-offs:
- Session-only vs persistent carts: Persistent for better UX
- Real-time vs lazy availability check: Lazy for performance
Performance:
- Cache cart data in Redis for frequently accessed carts
- Batch inventory checks for multiple items
Alternatives considered:
- Client-side cart: Lost on device change
- Distributed cart storage: Adds complexity