Files
thrillwiki_django_no_react/shared/docs/memory-bank/documentation/Code.md
pacnpal d504d41de2 feat: complete monorepo structure with frontend and shared resources
- Add complete backend/ directory with full Django application
- Add frontend/ directory with Vite + TypeScript setup ready for Next.js
- Add comprehensive shared/ directory with:
  - Complete documentation and memory-bank archives
  - Media files and avatars (letters, park/ride images)
  - Deployment scripts and automation tools
  - Shared types and utilities
- Add architecture/ directory with migration guides
- Configure pnpm workspace for monorepo development
- Update .gitignore to exclude .django_tailwind_cli/ build artifacts
- Preserve all historical documentation in shared/docs/memory-bank/
- Set up proper structure for full-stack development with shared resources
2025-08-23 18:40:07 -04:00

6.3 KiB

Code Documentation

Project Structure

thrillwiki/
├── accounts/          # User management
├── analytics/         # Usage tracking
├── companies/         # Company profiles
├── core/             # Core functionality
├── designers/        # Designer profiles
├── email_service/    # Email handling
├── history/          # Historical views
├── history_tracking/ # Change tracking
├── location/         # Geographic features
├── media/           # Media management
├── moderation/      # Content moderation
├── parks/           # Park management
├── reviews/         # Review system
└── rides/           # Ride management

Code Patterns

1. Model Patterns

History Tracking

@pghistory.track()
class TrackedModel(models.Model):
    """Base class for models with history tracking"""
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Slug Management

class SluggedModel:
    """Pattern for models with slug-based URLs"""
    @classmethod
    def get_by_slug(cls, slug: str) -> Tuple[Model, bool]:
        # Check current slugs
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            historical = HistoricalSlug.objects.filter(
                content_type=ContentType.objects.get_for_model(cls),
                slug=slug
            ).first()
            if historical:
                return cls.objects.get(pk=historical.object_id), True

Generic Relations

# Example from parks/models.py
class Park(TrackedModel):
    location = GenericRelation(Location)
    photos = GenericRelation(Photo)

2. View Patterns

Class-Based Views

class ModeratedCreateView(LoginRequiredMixin, CreateView):
    """Base view for content requiring moderation"""
    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.status = 'PENDING'
        obj.created_by = self.request.user
        return super().form_valid(form)

Permission Mixins

class ModeratorRequiredMixin:
    """Ensures user has moderation permissions"""
    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('moderation.can_moderate'):
            raise PermissionDenied
        return super().dispatch(request, *args, **kwargs)

3. Service Patterns

Email Service

class EmailService:
    """Handles email templating and sending"""
    def send_moderation_notification(self, content):
        template = 'moderation/email/notification.html'
        context = {'content': content}
        self.send_templated_email(template, context)

Media Processing

class MediaProcessor:
    """Handles image optimization and processing"""
    def process_image(self, image):
        # Optimize size
        # Extract EXIF
        # Generate thumbnails
        return processed_image

Dependencies

Core Dependencies

# From pyproject.toml
[tool.poetry.dependencies]
django = "5.1.6"
djangorestframework = "3.15.2"
django-allauth = "65.4.1"
psycopg2-binary = "2.9.10"
django-pghistory = "3.5.2"

Frontend Dependencies

{
    "tailwindcss": "^3.0.0",
    "htmx": "^1.22.0",
    "webpack": "^5.0.0"
}

Build Configuration

Django Settings

INSTALLED_APPS = [
    # Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    
    # Third-party apps
    'allauth',
    'rest_framework',
    'corsheaders',
    
    # Local apps
    'parks.apps.ParksConfig',
    'rides.apps.RidesConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
]

Database Configuration

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    }
}

Testing Framework

Test Structure

tests/
├── unit/              # Unit tests
├── integration/       # Integration tests
└── e2e/              # End-to-end tests

Test Patterns

class ParkTestCase(TestCase):
    def setUp(self):
        self.park = Park.objects.create(
            name="Test Park",
            status="OPERATING"
        )
    
    def test_park_creation(self):
        self.assertEqual(self.park.slug, "test-park")

Package Management

Python Dependencies

# Development dependencies
pip install -r requirements-dev.txt

# Production dependencies
pip install -r requirements.txt

Frontend Build

# Install frontend dependencies
npm install

# Build static assets
npm run build

Code Quality Tools

Python Tools

  • black (code formatting)
  • flake8 (linting)
  • mypy (type checking)
  • pytest (testing)

Configuration Files

# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py311']

[tool.mypy]
plugins = ["mypy_django_plugin.main"]

Development Workflow

Local Development

  1. Set up virtual environment
  2. Install dependencies
  3. Run migrations
  4. Start development server
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

Code Review Process

  1. Run linting tools
  2. Run test suite
  3. Check type hints
  4. Review documentation

Deployment Process

Pre-deployment Checks

  1. Run test suite
  2. Check migrations
  3. Validate static files
  4. Verify environment variables

Deployment Steps

  1. Update dependencies
  2. Apply migrations
  3. Collect static files
  4. Restart application server

Error Handling

Exception Pattern

class CustomException(Exception):
    """Base exception for application"""
    def __init__(self, message, code=None):
        self.message = message
        self.code = code

Middleware Pattern

class ErrorHandlingMiddleware:
    """Centralized error handling"""
    def process_exception(self, request, exception):
        # Log exception
        # Handle gracefully
        # Return appropriate response