Automated Action d2b80dacc4 Implement Shopping Cart and Checkout API
- Set up FastAPI application structure
- Create database models for User, Product, Cart, CartItem, Order, and OrderItem
- Set up Alembic for database migrations
- Create Pydantic schemas for request/response models
- Implement API endpoints for products, cart operations, and checkout process
- Add health endpoint
- Update README with project details and documentation
2025-05-18 00:00:02 +00:00

48 lines
1.8 KiB
Python

from sqlalchemy import Column, String, Integer, Float, ForeignKey, Boolean, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime, timedelta
from app.core.config import settings
from app.models.base import BaseModel, TimestampMixin
class Cart(BaseModel, TimestampMixin):
"""Shopping cart model."""
user_id = Column(Integer, ForeignKey("user.id"), nullable=True)
session_id = Column(String, index=True, nullable=True) # For non-authenticated users
is_active = Column(Boolean, default=True)
expires_at = Column(
DateTime,
default=lambda: datetime.utcnow() + timedelta(hours=settings.CART_EXPIRATION_HOURS)
)
# Relationships
user = relationship("User", back_populates="carts")
items = relationship("CartItem", back_populates="cart", cascade="all, delete-orphan")
@property
def total_price(self):
"""Calculate the total price of all items in the cart."""
return sum(item.subtotal for item in self.items)
@property
def total_items(self):
"""Calculate the total number of items in the cart."""
return sum(item.quantity for item in self.items)
class CartItem(BaseModel, TimestampMixin):
"""Shopping cart item model."""
cart_id = Column(Integer, ForeignKey("cart.id"), nullable=False)
product_id = Column(Integer, ForeignKey("product.id"), nullable=False)
quantity = Column(Integer, nullable=False, default=1)
unit_price = Column(Float, nullable=False) # Price at the time of adding to cart
# Relationships
cart = relationship("Cart", back_populates="items")
product = relationship("Product", back_populates="cart_items")
@property
def subtotal(self):
"""Calculate the subtotal for this cart item."""
return self.quantity * self.unit_price