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>
47 lines
1.6 KiB
Python
47 lines
1.6 KiB
Python
# models/database/cart.py
|
|
"""Cart item database model."""
|
|
from datetime import datetime
|
|
from sqlalchemy import Column, Float, ForeignKey, Index, Integer, String, UniqueConstraint
|
|
from sqlalchemy.orm import relationship
|
|
|
|
from app.core.database import Base
|
|
from models.database.base import TimestampMixin
|
|
|
|
|
|
class CartItem(Base, TimestampMixin):
|
|
"""
|
|
Shopping cart items.
|
|
|
|
Stores cart items per session, vendor, and product.
|
|
Sessions are identified by a session_id string (from browser cookies).
|
|
"""
|
|
__tablename__ = "cart_items"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
vendor_id = Column(Integer, ForeignKey("vendors.id"), nullable=False)
|
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
|
session_id = Column(String(255), nullable=False, index=True)
|
|
|
|
# Cart details
|
|
quantity = Column(Integer, nullable=False, default=1)
|
|
price_at_add = Column(Float, nullable=False) # Store price when added to cart
|
|
|
|
# Relationships
|
|
vendor = relationship("Vendor")
|
|
product = relationship("Product")
|
|
|
|
# Constraints
|
|
__table_args__ = (
|
|
UniqueConstraint("vendor_id", "session_id", "product_id", name="uq_cart_item"),
|
|
Index("idx_cart_session", "vendor_id", "session_id"),
|
|
Index("idx_cart_created", "created_at"), # For cleanup of old carts
|
|
)
|
|
|
|
def __repr__(self):
|
|
return f"<CartItem(id={self.id}, session='{self.session_id}', product_id={self.product_id}, qty={self.quantity})>"
|
|
|
|
@property
|
|
def line_total(self) -> float:
|
|
"""Calculate line total."""
|
|
return self.price_at_add * self.quantity
|