Implemented a complete shopping cart system with database persistence, replacing the previous stub implementation. The cart now properly stores items across sessions and follows the project's architecture patterns. Database Changes: - Add cart_items table with vendor_id, session_id, product_id, quantity, price_at_add - Create unique constraint to prevent duplicate items per session - Add indexes for session lookups and old cart cleanup - Run migration a2064e1dfcd4 to create cart_items table New Models & Schemas: - models/database/cart.py: CartItem SQLAlchemy model with relationships - models/schema/cart.py: Pydantic schemas for requests/responses * AddToCartRequest, UpdateCartItemRequest * CartResponse, CartItemResponse, CartOperationResponse, ClearCartResponse Exception Handling: - app/exceptions/cart.py: Cart-specific exceptions following project patterns * CartItemNotFoundException - item not found in cart * InsufficientInventoryForCartException - not enough inventory for cart operation * InvalidCartQuantityException - invalid quantity validation * CartValidationException - general cart validation * EmptyCartException - operations on empty cart * ProductNotAvailableForCartException - product unavailable - Updated app/exceptions/__init__.py to export cart exceptions Service Layer: - Implement cart_service.get_cart() - fetch cart from database with totals - Implement cart_service.add_to_cart() - create or update cart items with inventory checks - Implement cart_service.update_cart_item() - update quantity with validation - Implement cart_service.remove_from_cart() - delete cart item - Implement cart_service.clear_cart() - remove all items for session - Replace generic exceptions with cart-specific ones - Fix InsufficientInventoryException usage (was using wrong parameters) API Layer: - Update app/api/v1/shop/cart.py to use Pydantic schemas - Add response_model declarations to all endpoints - Add return type hints for type safety - Convert service dict responses to Pydantic models Features: - Cart items persist in database across server restarts - Inventory validation before adding/updating items - Price captured at time of adding to cart - Duplicate items update quantity instead of creating new entries - Full CRUD operations with proper error handling - Type-safe API with auto-generated OpenAPI documentation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
281 lines
7.9 KiB
Python
281 lines
7.9 KiB
Python
# app/api/v1/shop/cart.py
|
|
"""
|
|
Shop Shopping Cart API (Public)
|
|
|
|
Public endpoints for managing shopping cart in shop frontend.
|
|
Uses vendor from request.state (injected by VendorContextMiddleware).
|
|
No authentication required - uses session ID for cart tracking.
|
|
"""
|
|
|
|
import logging
|
|
from fastapi import APIRouter, Depends, Path, Body, Request, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database import get_db
|
|
from app.services.cart_service import cart_service
|
|
from models.schema.cart import (
|
|
AddToCartRequest,
|
|
UpdateCartItemRequest,
|
|
CartResponse,
|
|
CartOperationResponse,
|
|
ClearCartResponse,
|
|
)
|
|
|
|
router = APIRouter()
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
# ============================================================================
|
|
# CART ENDPOINTS
|
|
# ============================================================================
|
|
|
|
@router.get("/cart/{session_id}", response_model=CartResponse)
|
|
def get_cart(
|
|
request: Request,
|
|
session_id: str = Path(..., description="Shopping session ID"),
|
|
db: Session = Depends(get_db),
|
|
) -> CartResponse:
|
|
"""
|
|
Get shopping cart contents for current vendor.
|
|
|
|
Vendor is automatically determined from request context.
|
|
No authentication required - uses session ID for cart tracking.
|
|
|
|
Path Parameters:
|
|
- session_id: Unique session identifier for the cart
|
|
"""
|
|
# Get vendor from middleware
|
|
vendor = getattr(request.state, 'vendor', None)
|
|
|
|
if not vendor:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Vendor not found. Please access via vendor domain/subdomain/path."
|
|
)
|
|
|
|
logger.info(
|
|
f"[SHOP_API] get_cart for session {session_id}, vendor {vendor.id}",
|
|
extra={
|
|
"vendor_id": vendor.id,
|
|
"vendor_code": vendor.subdomain,
|
|
"session_id": session_id,
|
|
}
|
|
)
|
|
|
|
cart = cart_service.get_cart(
|
|
db=db,
|
|
vendor_id=vendor.id,
|
|
session_id=session_id
|
|
)
|
|
|
|
logger.info(
|
|
f"[SHOP_API] get_cart result: {len(cart.get('items', []))} items in cart",
|
|
extra={
|
|
"session_id": session_id,
|
|
"vendor_id": vendor.id,
|
|
"item_count": len(cart.get('items', [])),
|
|
"total": cart.get('total', 0),
|
|
}
|
|
)
|
|
|
|
return CartResponse.from_service_dict(cart)
|
|
|
|
|
|
@router.post("/cart/{session_id}/items", response_model=CartOperationResponse)
|
|
def add_to_cart(
|
|
request: Request,
|
|
session_id: str = Path(..., description="Shopping session ID"),
|
|
cart_data: AddToCartRequest = Body(...),
|
|
db: Session = Depends(get_db),
|
|
) -> CartOperationResponse:
|
|
"""
|
|
Add product to cart for current vendor.
|
|
|
|
Vendor is automatically determined from request context.
|
|
No authentication required - uses session ID.
|
|
|
|
Path Parameters:
|
|
- session_id: Unique session identifier for the cart
|
|
|
|
Request Body:
|
|
- product_id: ID of product to add
|
|
- quantity: Quantity to add (default: 1)
|
|
"""
|
|
# Get vendor from middleware
|
|
vendor = getattr(request.state, 'vendor', None)
|
|
|
|
if not vendor:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Vendor not found. Please access via vendor domain/subdomain/path."
|
|
)
|
|
|
|
logger.info(
|
|
f"[SHOP_API] add_to_cart: product {cart_data.product_id}, qty {cart_data.quantity}, session {session_id}",
|
|
extra={
|
|
"vendor_id": vendor.id,
|
|
"vendor_code": vendor.subdomain,
|
|
"session_id": session_id,
|
|
"product_id": cart_data.product_id,
|
|
"quantity": cart_data.quantity,
|
|
}
|
|
)
|
|
|
|
result = cart_service.add_to_cart(
|
|
db=db,
|
|
vendor_id=vendor.id,
|
|
session_id=session_id,
|
|
product_id=cart_data.product_id,
|
|
quantity=cart_data.quantity
|
|
)
|
|
|
|
logger.info(
|
|
f"[SHOP_API] add_to_cart result: {result}",
|
|
extra={
|
|
"session_id": session_id,
|
|
"result": result,
|
|
}
|
|
)
|
|
|
|
return CartOperationResponse(**result)
|
|
|
|
|
|
@router.put("/cart/{session_id}/items/{product_id}", response_model=CartOperationResponse)
|
|
def update_cart_item(
|
|
request: Request,
|
|
session_id: str = Path(..., description="Shopping session ID"),
|
|
product_id: int = Path(..., description="Product ID", gt=0),
|
|
cart_data: UpdateCartItemRequest = Body(...),
|
|
db: Session = Depends(get_db),
|
|
) -> CartOperationResponse:
|
|
"""
|
|
Update cart item quantity for current vendor.
|
|
|
|
Vendor is automatically determined from request context.
|
|
No authentication required - uses session ID.
|
|
|
|
Path Parameters:
|
|
- session_id: Unique session identifier for the cart
|
|
- product_id: ID of product to update
|
|
|
|
Request Body:
|
|
- quantity: New quantity (must be >= 1)
|
|
"""
|
|
# Get vendor from middleware
|
|
vendor = getattr(request.state, 'vendor', None)
|
|
|
|
if not vendor:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Vendor not found. Please access via vendor domain/subdomain/path."
|
|
)
|
|
|
|
logger.debug(
|
|
f"[SHOP_API] update_cart_item: product {product_id}, qty {cart_data.quantity}",
|
|
extra={
|
|
"vendor_id": vendor.id,
|
|
"vendor_code": vendor.subdomain,
|
|
"session_id": session_id,
|
|
"product_id": product_id,
|
|
"quantity": cart_data.quantity,
|
|
}
|
|
)
|
|
|
|
result = cart_service.update_cart_item(
|
|
db=db,
|
|
vendor_id=vendor.id,
|
|
session_id=session_id,
|
|
product_id=product_id,
|
|
quantity=cart_data.quantity
|
|
)
|
|
|
|
return CartOperationResponse(**result)
|
|
|
|
|
|
@router.delete("/cart/{session_id}/items/{product_id}", response_model=CartOperationResponse)
|
|
def remove_from_cart(
|
|
request: Request,
|
|
session_id: str = Path(..., description="Shopping session ID"),
|
|
product_id: int = Path(..., description="Product ID", gt=0),
|
|
db: Session = Depends(get_db),
|
|
) -> CartOperationResponse:
|
|
"""
|
|
Remove item from cart for current vendor.
|
|
|
|
Vendor is automatically determined from request context.
|
|
No authentication required - uses session ID.
|
|
|
|
Path Parameters:
|
|
- session_id: Unique session identifier for the cart
|
|
- product_id: ID of product to remove
|
|
"""
|
|
# Get vendor from middleware
|
|
vendor = getattr(request.state, 'vendor', None)
|
|
|
|
if not vendor:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Vendor not found. Please access via vendor domain/subdomain/path."
|
|
)
|
|
|
|
logger.debug(
|
|
f"[SHOP_API] remove_from_cart: product {product_id}",
|
|
extra={
|
|
"vendor_id": vendor.id,
|
|
"vendor_code": vendor.subdomain,
|
|
"session_id": session_id,
|
|
"product_id": product_id,
|
|
}
|
|
)
|
|
|
|
result = cart_service.remove_from_cart(
|
|
db=db,
|
|
vendor_id=vendor.id,
|
|
session_id=session_id,
|
|
product_id=product_id
|
|
)
|
|
|
|
return CartOperationResponse(**result)
|
|
|
|
|
|
@router.delete("/cart/{session_id}", response_model=ClearCartResponse)
|
|
def clear_cart(
|
|
request: Request,
|
|
session_id: str = Path(..., description="Shopping session ID"),
|
|
db: Session = Depends(get_db),
|
|
) -> ClearCartResponse:
|
|
"""
|
|
Clear all items from cart for current vendor.
|
|
|
|
Vendor is automatically determined from request context.
|
|
No authentication required - uses session ID.
|
|
|
|
Path Parameters:
|
|
- session_id: Unique session identifier for the cart
|
|
"""
|
|
# Get vendor from middleware
|
|
vendor = getattr(request.state, 'vendor', None)
|
|
|
|
if not vendor:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Vendor not found. Please access via vendor domain/subdomain/path."
|
|
)
|
|
|
|
logger.debug(
|
|
f"[SHOP_API] clear_cart for session {session_id}",
|
|
extra={
|
|
"vendor_id": vendor.id,
|
|
"vendor_code": vendor.subdomain,
|
|
"session_id": session_id,
|
|
}
|
|
)
|
|
|
|
result = cart_service.clear_cart(
|
|
db=db,
|
|
vendor_id=vendor.id,
|
|
session_id=session_id
|
|
)
|
|
|
|
return ClearCartResponse(**result)
|