feat(modules): create cart, catalog, and checkout e-commerce modules

Phase 3 of storefront restructure plan - create dedicated modules for
e-commerce functionality:

- cart: Shopping cart management with storefront API routes
  - CartItem model with cents-based pricing
  - CartService for cart operations
  - Storefront routes for cart CRUD operations

- catalog: Product catalog browsing for customers
  - CatalogService for public product queries
  - Storefront routes for product listing/search/details

- checkout: Order creation from cart (placeholder)
  - CheckoutService stub for future cart-to-order conversion
  - Schemas for checkout flow

These modules separate e-commerce concerns from core platform
concerns (customer auth), enabling non-commerce platforms.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-29 22:53:35 +01:00
parent 3e86d4b58b
commit 0845555413
32 changed files with 1748 additions and 3 deletions

View File

@@ -0,0 +1,11 @@
# app/modules/cart/__init__.py
"""
Cart Module
Provides shopping cart functionality for storefronts:
- Session-based cart management
- Cart item operations (add, update, remove)
- Cart total calculations
All monetary calculations use integer cents internally for precision.
"""

View File

@@ -0,0 +1,25 @@
# app/modules/cart/definition.py
"""
Cart module definition.
This module provides shopping cart functionality for customer storefronts.
It is session-based and does not require customer authentication.
"""
from app.modules.core.module_registry import ModuleDefinition
module = ModuleDefinition(
code="cart",
name="Shopping Cart",
description="Session-based shopping cart for storefronts",
version="1.0.0",
is_self_contained=True,
dependencies=["inventory"], # Checks inventory availability
provides_models=True,
provides_schemas=True,
provides_services=True,
provides_api_routes=True,
provides_page_routes=False,
provides_admin_ui=False,
provides_vendor_ui=False,
)

View File

@@ -0,0 +1,6 @@
# app/modules/cart/models/__init__.py
"""Cart module database models."""
from app.modules.cart.models.cart import CartItem
__all__ = ["CartItem"]

View File

@@ -0,0 +1,78 @@
# app/modules/cart/models/cart.py
"""Cart item database model.
Money values are stored as integer cents (e.g., €105.91 = 10591).
See docs/architecture/money-handling.md for details.
"""
from sqlalchemy import (
Column,
ForeignKey,
Index,
Integer,
String,
UniqueConstraint,
)
from sqlalchemy.orm import relationship
from app.core.database import Base
from app.utils.money import cents_to_euros, euros_to_cents
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).
Price is stored as integer cents for precision.
"""
__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_cents = Column(Integer, nullable=False) # Price in cents when added
# 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})>"
# === PRICE PROPERTIES (Euro convenience accessors) ===
@property
def price_at_add(self) -> float:
"""Get price at add in euros."""
return cents_to_euros(self.price_at_add_cents)
@price_at_add.setter
def price_at_add(self, value: float):
"""Set price at add from euros."""
self.price_at_add_cents = euros_to_cents(value)
@property
def line_total_cents(self) -> int:
"""Calculate line total in cents."""
return self.price_at_add_cents * self.quantity
@property
def line_total(self) -> float:
"""Calculate line total in euros."""
return cents_to_euros(self.line_total_cents)

View File

@@ -0,0 +1,2 @@
# app/modules/cart/routes/__init__.py
"""Cart module routes."""

View File

@@ -0,0 +1,9 @@
# app/modules/cart/routes/api/__init__.py
"""Cart module API routes."""
from app.modules.cart.routes.api.storefront import router as storefront_router
# Tag for OpenAPI documentation
STOREFRONT_TAG = "Cart (Storefront)"
__all__ = ["storefront_router", "STOREFRONT_TAG"]

View File

@@ -0,0 +1,238 @@
# app/modules/cart/routes/api/storefront.py
"""
Cart Module - Storefront API Routes
Public endpoints for managing shopping cart in storefront.
Uses vendor from middleware context (VendorContextMiddleware).
No authentication required - uses session ID for cart tracking.
Vendor Context: require_vendor_context() - detects vendor from URL/subdomain/domain
"""
import logging
from fastapi import APIRouter, Body, Depends, Path
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.modules.cart.services import cart_service
from app.modules.cart.schemas import (
AddToCartRequest,
CartOperationResponse,
CartResponse,
ClearCartResponse,
UpdateCartItemRequest,
)
from middleware.vendor_context import require_vendor_context
from models.database.vendor import Vendor
router = APIRouter()
logger = logging.getLogger(__name__)
# ============================================================================
# CART ENDPOINTS
# ============================================================================
@router.get("/cart/{session_id}", response_model=CartResponse) # public
def get_cart(
session_id: str = Path(..., description="Shopping session ID"),
vendor: Vendor = Depends(require_vendor_context()),
db: Session = Depends(get_db),
) -> CartResponse:
"""
Get shopping cart contents for current vendor.
Vendor is automatically determined from request context (URL/subdomain/domain).
No authentication required - uses session ID for cart tracking.
Path Parameters:
- session_id: Unique session identifier for the cart
"""
logger.info(
f"[CART_STOREFRONT] 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"[CART_STOREFRONT] 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) # public
def add_to_cart(
session_id: str = Path(..., description="Shopping session ID"),
cart_data: AddToCartRequest = Body(...),
vendor: Vendor = Depends(require_vendor_context()),
db: Session = Depends(get_db),
) -> CartOperationResponse:
"""
Add product to cart for current vendor.
Vendor is automatically determined from request context (URL/subdomain/domain).
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)
"""
logger.info(
f"[CART_STOREFRONT] 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,
)
db.commit()
logger.info(
f"[CART_STOREFRONT] 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
) # public
def update_cart_item(
session_id: str = Path(..., description="Shopping session ID"),
product_id: int = Path(..., description="Product ID", gt=0),
cart_data: UpdateCartItemRequest = Body(...),
vendor: Vendor = Depends(require_vendor_context()),
db: Session = Depends(get_db),
) -> CartOperationResponse:
"""
Update cart item quantity for current vendor.
Vendor is automatically determined from request context (URL/subdomain/domain).
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)
"""
logger.debug(
f"[CART_STOREFRONT] 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,
)
db.commit()
return CartOperationResponse(**result)
@router.delete(
"/cart/{session_id}/items/{product_id}", response_model=CartOperationResponse
) # public
def remove_from_cart(
session_id: str = Path(..., description="Shopping session ID"),
product_id: int = Path(..., description="Product ID", gt=0),
vendor: Vendor = Depends(require_vendor_context()),
db: Session = Depends(get_db),
) -> CartOperationResponse:
"""
Remove item from cart for current vendor.
Vendor is automatically determined from request context (URL/subdomain/domain).
No authentication required - uses session ID.
Path Parameters:
- session_id: Unique session identifier for the cart
- product_id: ID of product to remove
"""
logger.debug(
f"[CART_STOREFRONT] 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
)
db.commit()
return CartOperationResponse(**result)
@router.delete("/cart/{session_id}", response_model=ClearCartResponse) # public
def clear_cart(
session_id: str = Path(..., description="Shopping session ID"),
vendor: Vendor = Depends(require_vendor_context()),
db: Session = Depends(get_db),
) -> ClearCartResponse:
"""
Clear all items from cart for current vendor.
Vendor is automatically determined from request context (URL/subdomain/domain).
No authentication required - uses session ID.
Path Parameters:
- session_id: Unique session identifier for the cart
"""
logger.debug(
f"[CART_STOREFRONT] 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)
db.commit()
return ClearCartResponse(**result)

View File

@@ -0,0 +1,20 @@
# app/modules/cart/schemas/__init__.py
"""Cart module Pydantic schemas."""
from app.modules.cart.schemas.cart import (
AddToCartRequest,
UpdateCartItemRequest,
CartItemResponse,
CartResponse,
CartOperationResponse,
ClearCartResponse,
)
__all__ = [
"AddToCartRequest",
"UpdateCartItemRequest",
"CartItemResponse",
"CartResponse",
"CartOperationResponse",
"ClearCartResponse",
]

View File

@@ -0,0 +1,91 @@
# app/modules/cart/schemas/cart.py
"""
Pydantic schemas for shopping cart operations.
"""
from pydantic import BaseModel, ConfigDict, Field
# ============================================================================
# Request Schemas
# ============================================================================
class AddToCartRequest(BaseModel):
"""Request model for adding items to cart."""
product_id: int = Field(..., description="Product ID to add", gt=0)
quantity: int = Field(1, ge=1, description="Quantity to add")
class UpdateCartItemRequest(BaseModel):
"""Request model for updating cart item quantity."""
quantity: int = Field(..., ge=1, description="New quantity (must be >= 1)")
# ============================================================================
# Response Schemas
# ============================================================================
class CartItemResponse(BaseModel):
"""Response model for a single cart item."""
model_config = ConfigDict(from_attributes=True)
product_id: int = Field(..., description="Product ID")
product_name: str = Field(..., description="Product name")
quantity: int = Field(..., description="Quantity in cart")
price: float = Field(..., description="Price per unit when added to cart")
line_total: float = Field(
..., description="Total price for this line (price * quantity)"
)
image_url: str | None = Field(None, description="Product image URL")
class CartResponse(BaseModel):
"""Response model for shopping cart."""
vendor_id: int = Field(..., description="Vendor ID")
session_id: str = Field(..., description="Shopping session ID")
items: list[CartItemResponse] = Field(
default_factory=list, description="Cart items"
)
subtotal: float = Field(..., description="Subtotal of all items")
total: float = Field(..., description="Total amount (currently same as subtotal)")
item_count: int = Field(..., description="Total number of items in cart")
@classmethod
def from_service_dict(cls, cart_dict: dict) -> "CartResponse":
"""
Create CartResponse from service layer dictionary.
This is a convenience method to convert the dictionary format
returned by cart_service into a proper Pydantic model.
"""
items = [CartItemResponse(**item) for item in cart_dict.get("items", [])]
return cls(
vendor_id=cart_dict["vendor_id"],
session_id=cart_dict["session_id"],
items=items,
subtotal=cart_dict["subtotal"],
total=cart_dict["total"],
item_count=len(items),
)
class CartOperationResponse(BaseModel):
"""Response model for cart operations (add, update, remove)."""
message: str = Field(..., description="Operation result message")
product_id: int = Field(..., description="Product ID affected")
quantity: int | None = Field(
None, description="New quantity (for add/update operations)"
)
class ClearCartResponse(BaseModel):
"""Response model for clearing cart."""
message: str = Field(..., description="Operation result message")
items_removed: int = Field(..., description="Number of items removed from cart")

View File

@@ -0,0 +1,6 @@
# app/modules/cart/services/__init__.py
"""Cart module services."""
from app.modules.cart.services.cart_service import cart_service, CartService
__all__ = ["cart_service", "CartService"]

View File

@@ -0,0 +1,453 @@
# app/modules/cart/services/cart_service.py
"""
Shopping cart service.
This module provides:
- Session-based cart management
- Cart item operations (add, update, remove)
- Cart total calculations
All monetary calculations use integer cents internally for precision.
See docs/architecture/money-handling.md for details.
"""
import logging
from sqlalchemy import and_
from sqlalchemy.orm import Session
from app.exceptions import (
CartItemNotFoundException,
InsufficientInventoryForCartException,
InvalidCartQuantityException,
ProductNotFoundException,
)
from app.utils.money import cents_to_euros
from app.modules.cart.models.cart import CartItem
from models.database.product import Product
logger = logging.getLogger(__name__)
class CartService:
"""Service for managing shopping carts."""
def get_cart(self, db: Session, vendor_id: int, session_id: str) -> dict:
"""
Get cart contents for a session.
Args:
db: Database session
vendor_id: Vendor ID
session_id: Session ID
Returns:
Cart data with items and totals
"""
logger.info(
"[CART_SERVICE] get_cart called",
extra={
"vendor_id": vendor_id,
"session_id": session_id,
},
)
# Fetch cart items from database
cart_items = (
db.query(CartItem)
.filter(
and_(CartItem.vendor_id == vendor_id, CartItem.session_id == session_id)
)
.all()
)
logger.info(
f"[CART_SERVICE] Found {len(cart_items)} items in database",
extra={"item_count": len(cart_items)},
)
# Build response - calculate totals in cents, return euros
items = []
subtotal_cents = 0
for cart_item in cart_items:
product = cart_item.product
line_total_cents = cart_item.line_total_cents
items.append(
{
"product_id": product.id,
"product_name": product.marketplace_product.get_title("en")
if product.marketplace_product
else str(product.id),
"quantity": cart_item.quantity,
"price": cart_item.price_at_add, # Returns euros via property
"line_total": cents_to_euros(line_total_cents),
"image_url": (
product.marketplace_product.image_link
if product.marketplace_product
else None
),
}
)
subtotal_cents += line_total_cents
# Convert to euros for API response
subtotal = cents_to_euros(subtotal_cents)
cart_data = {
"vendor_id": vendor_id,
"session_id": session_id,
"items": items,
"subtotal": subtotal,
"total": subtotal, # Could add tax/shipping later
}
logger.info(
f"[CART_SERVICE] get_cart returning: {len(cart_data['items'])} items, total: {cart_data['total']}",
extra={"cart": cart_data},
)
return cart_data
def add_to_cart(
self,
db: Session,
vendor_id: int,
session_id: str,
product_id: int,
quantity: int = 1,
) -> dict:
"""
Add product to cart.
Args:
db: Database session
vendor_id: Vendor ID
session_id: Session ID
product_id: Product ID
quantity: Quantity to add
Returns:
Updated cart
Raises:
ProductNotFoundException: If product not found
InsufficientInventoryException: If not enough inventory
"""
logger.info(
"[CART_SERVICE] add_to_cart called",
extra={
"vendor_id": vendor_id,
"session_id": session_id,
"product_id": product_id,
"quantity": quantity,
},
)
# Verify product exists and belongs to vendor
product = (
db.query(Product)
.filter(
and_(
Product.id == product_id,
Product.vendor_id == vendor_id,
Product.is_active == True,
)
)
.first()
)
if not product:
logger.error(
"[CART_SERVICE] Product not found",
extra={"product_id": product_id, "vendor_id": vendor_id},
)
raise ProductNotFoundException(product_id=product_id, vendor_id=vendor_id)
logger.info(
f"[CART_SERVICE] Product found: {product.marketplace_product.title}",
extra={
"product_id": product_id,
"product_name": product.marketplace_product.title,
"available_inventory": product.available_inventory,
},
)
# Get current price in cents (use sale_price if available, otherwise regular price)
current_price_cents = (
product.sale_price_cents
or product.price_cents
or 0
)
# Check if item already exists in cart
existing_item = (
db.query(CartItem)
.filter(
and_(
CartItem.vendor_id == vendor_id,
CartItem.session_id == session_id,
CartItem.product_id == product_id,
)
)
.first()
)
if existing_item:
# Update quantity
new_quantity = existing_item.quantity + quantity
# Check inventory for new total quantity
if product.available_inventory < new_quantity:
logger.warning(
"[CART_SERVICE] Insufficient inventory for update",
extra={
"product_id": product_id,
"current_in_cart": existing_item.quantity,
"adding": quantity,
"requested_total": new_quantity,
"available": product.available_inventory,
},
)
raise InsufficientInventoryForCartException(
product_id=product_id,
product_name=product.marketplace_product.title,
requested=new_quantity,
available=product.available_inventory,
)
existing_item.quantity = new_quantity
db.flush()
db.refresh(existing_item)
logger.info(
"[CART_SERVICE] Updated existing cart item",
extra={"cart_item_id": existing_item.id, "new_quantity": new_quantity},
)
return {
"message": "Product quantity updated in cart",
"product_id": product_id,
"quantity": new_quantity,
}
# Check inventory for new item
if product.available_inventory < quantity:
logger.warning(
"[CART_SERVICE] Insufficient inventory",
extra={
"product_id": product_id,
"requested": quantity,
"available": product.available_inventory,
},
)
raise InsufficientInventoryForCartException(
product_id=product_id,
product_name=product.marketplace_product.title,
requested=quantity,
available=product.available_inventory,
)
# Create new cart item (price stored in cents)
cart_item = CartItem(
vendor_id=vendor_id,
session_id=session_id,
product_id=product_id,
quantity=quantity,
price_at_add_cents=current_price_cents,
)
db.add(cart_item)
db.flush()
db.refresh(cart_item)
logger.info(
"[CART_SERVICE] Created new cart item",
extra={
"cart_item_id": cart_item.id,
"quantity": quantity,
"price_cents": current_price_cents,
},
)
return {
"message": "Product added to cart",
"product_id": product_id,
"quantity": quantity,
}
def update_cart_item(
self,
db: Session,
vendor_id: int,
session_id: str,
product_id: int,
quantity: int,
) -> dict:
"""
Update quantity of item in cart.
Args:
db: Database session
vendor_id: Vendor ID
session_id: Session ID
product_id: Product ID
quantity: New quantity (must be >= 1)
Returns:
Success message
Raises:
ValidationException: If quantity < 1
ProductNotFoundException: If product not found
InsufficientInventoryException: If not enough inventory
"""
if quantity < 1:
raise InvalidCartQuantityException(quantity=quantity, min_quantity=1)
# Find cart item
cart_item = (
db.query(CartItem)
.filter(
and_(
CartItem.vendor_id == vendor_id,
CartItem.session_id == session_id,
CartItem.product_id == product_id,
)
)
.first()
)
if not cart_item:
raise CartItemNotFoundException(
product_id=product_id, session_id=session_id
)
# Verify product still exists and is active
product = (
db.query(Product)
.filter(
and_(
Product.id == product_id,
Product.vendor_id == vendor_id,
Product.is_active == True,
)
)
.first()
)
if not product:
raise ProductNotFoundException(str(product_id))
# Check inventory
if product.available_inventory < quantity:
raise InsufficientInventoryForCartException(
product_id=product_id,
product_name=product.marketplace_product.title,
requested=quantity,
available=product.available_inventory,
)
# Update quantity
cart_item.quantity = quantity
db.flush()
db.refresh(cart_item)
logger.info(
"[CART_SERVICE] Updated cart item quantity",
extra={
"cart_item_id": cart_item.id,
"product_id": product_id,
"new_quantity": quantity,
},
)
return {
"message": "Cart updated",
"product_id": product_id,
"quantity": quantity,
}
def remove_from_cart(
self, db: Session, vendor_id: int, session_id: str, product_id: int
) -> dict:
"""
Remove item from cart.
Args:
db: Database session
vendor_id: Vendor ID
session_id: Session ID
product_id: Product ID
Returns:
Success message
Raises:
ProductNotFoundException: If product not in cart
"""
# Find and delete cart item
cart_item = (
db.query(CartItem)
.filter(
and_(
CartItem.vendor_id == vendor_id,
CartItem.session_id == session_id,
CartItem.product_id == product_id,
)
)
.first()
)
if not cart_item:
raise CartItemNotFoundException(
product_id=product_id, session_id=session_id
)
db.delete(cart_item)
logger.info(
"[CART_SERVICE] Removed item from cart",
extra={
"cart_item_id": cart_item.id,
"product_id": product_id,
"session_id": session_id,
},
)
return {"message": "Item removed from cart", "product_id": product_id}
def clear_cart(self, db: Session, vendor_id: int, session_id: str) -> dict:
"""
Clear all items from cart.
Args:
db: Database session
vendor_id: Vendor ID
session_id: Session ID
Returns:
Success message with count of items removed
"""
# Delete all cart items for this session
deleted_count = (
db.query(CartItem)
.filter(
and_(CartItem.vendor_id == vendor_id, CartItem.session_id == session_id)
)
.delete()
)
logger.info(
"[CART_SERVICE] Cleared cart",
extra={
"session_id": session_id,
"vendor_id": vendor_id,
"items_removed": deleted_count,
},
)
return {"message": "Cart cleared", "items_removed": deleted_count}
# Create service instance
cart_service = CartService()