Compare commits

..

1 Commits

Author SHA1 Message Date
pacnpal
d0ee283abf Remove sensitive backup files and add backups/ to .gitignore
- Remove .github-pat backup file containing API tokens
- Remove thrillwiki-automation.env backup with secrets
- Add backups/ directory to .gitignore to prevent future commits
- Preparing for BFG repo cleaner to remove secrets from history
2025-08-20 10:49:41 -04:00
1757 changed files with 69448 additions and 301424 deletions

View File

@@ -1,51 +0,0 @@
# Project Startup & Development Rules
## Server & Package Management
- **Starting the Dev Server:** Always assume the server is running and changes have taken effect. If issues arise, run:
```bash
$PROJECT_ROOT/shared/scripts/start-servers.sh
```
- **Python Packages:** Only use UV to add packages:
```bash
cd $PROJECT_ROOT/backend && uv add <package>
```
NEVER use pip or pipenv directly, or uv pip.
- **Django Commands:** Always use `cd backend && uv run manage.py <command>` for all management tasks (migrations, shell, superuser, etc.). Never use `python manage.py` or `uv run python manage.py`.
- **Node Commands:** Always use 'cd frontend && pnpm add <package>' for all Node.js package installations. NEVER use npm or a different node package manager.
## CRITICAL Frontend design rules
- EVERYTHING must support both dark and light mode.
- Make sure the light/dark mode toggle works with the Vue components and pages.
- Leverage Tailwind CSS 4 and Shadcn UI components.
## Frontend API URL Rules
- **Vite Proxy:** Always check `frontend/vite.config.ts` for proxy rules before changing frontend API URLs.
- **URL Flow:** Understand how frontend URLs are rewritten by Vite proxy (e.g., `/api/auth/login/` → `/api/v1/auth/login/`).
- **Verification:** Confirm proxy behavior via config and browser network tab. Only change URLs if proxy is NOT handling rewriting.
- **Common Mistake:** Dont assume frontend URLs are wrong due to proxy configuration.
## Entity Relationship Patterns
- **Park:** Must have Operator (required), may have PropertyOwner (optional), cannot reference Company directly.
- **Ride:** Must belong to Park, may have Manufacturer/Designer (optional), cannot reference Company directly.
- **Entities:**
- Operators: Operate parks.
- PropertyOwners: Own park property (optional).
- Manufacturers: Make rides.
- Designers: Design rides.
- All entities can have locations.
- **Constraints:** Operator and PropertyOwner can be same or different. Manufacturers and Designers are distinct. Use proper foreign keys with correct null/blank settings.
## General Best Practices
- Never assume blank output means success—always verify changes by testing.
- Use context7 for documentation when troubleshooting.
- Document changes with conport and reasoning.
- Include relevant context and information in all changes.
- Test and validate code before deployment.
- Communicate changes clearly with your team.
- Be open to feedback and continuous improvement.
- Prioritize readability, maintainability, security, performance, scalability, and modularity.
- Use meaningful names, DRY principles, clear comments, and handle errors gracefully.
- Log important events/errors for troubleshooting.
- Prefer existing modules/packages over new code.
- Keep documentation up to date.
- Consider security vulnerabilities and performance bottlenecks in all changes.

View File

@@ -1,17 +0,0 @@
{
"permissions": {
"allow": [
"Bash(python manage.py check:*)",
"Bash(uv run:*)",
"Bash(find:*)",
"Bash(python:*)",
"Bash(DJANGO_SETTINGS_MODULE=config.django.local python:*)",
"Bash(DJANGO_SETTINGS_MODULE=config.django.local uv run python:*)",
"Bash(ls:*)",
"Bash(grep:*)",
"Bash(mkdir:*)"
],
"deny": [],
"ask": []
}
}

55
.clinerules Normal file
View File

@@ -0,0 +1,55 @@
# Project Startup Rules
## Development Server
IMPORTANT: Always follow these instructions exactly when starting the development server:
```bash
lsof -ti :8000 | xargs kill -9; find . -type d -name "__pycache__" -exec rm -r {} +; uv run manage.py tailwind runserver
```
Note: These steps must be executed in this exact order as a single command to ensure consistent behavior.
## Package Management
IMPORTANT: When a Python package is needed, only use UV to add it:
```bash
uv add <package>
```
Do not attempt to install packages using any other method.
## Django Management Commands
IMPORTANT: When running any Django manage.py commands (migrations, shell, etc.), always use UV:
```bash
uv run manage.py <command>
```
This applies to all management commands including but not limited to:
- Making migrations: `uv run manage.py makemigrations`
- Applying migrations: `uv run manage.py migrate`
- Creating superuser: `uv run manage.py createsuperuser`
- Starting shell: `uv run manage.py shell`
NEVER use `python manage.py` or `uv run python manage.py`. Always use `uv run manage.py` directly.
## Entity Relationship Rules
IMPORTANT: Follow these entity relationship patterns consistently:
# Park Relationships
- Parks MUST have an Operator (required relationship)
- Parks MAY have a PropertyOwner (optional, usually same as Operator)
- Parks CANNOT directly reference Company entities
# Ride Relationships
- Rides MUST belong to a Park (required relationship)
- Rides MAY have a Manufacturer (optional relationship)
- Rides MAY have a Designer (optional relationship)
- Rides CANNOT directly reference Company entities
# Entity Definitions
- Operators: Companies that operate theme parks (replaces Company.owner)
- PropertyOwners: Companies that own park property (new concept, optional)
- Manufacturers: Companies that manufacture rides (replaces Company for rides)
- Designers: Companies/individuals that design rides (existing concept)
# Relationship Constraints
- Operator and PropertyOwner are usually the same entity but CAN be different
- Manufacturers and Designers are distinct concepts and should not be conflated
- All entity relationships should use proper foreign keys with appropriate null/blank settings

View File

@@ -1,91 +0,0 @@
## Brief overview
Critical thinking rules for frontend design decisions. No excuses for poor design choices that ignore user vision.
## Rule compliance and design decisions
- Read ALL .clinerules files before making any code changes
- Never assume exceptions to rules marked as "MANDATORY"
- Take full responsibility for rule violations without excuses
- Ask "What is the most optimal approach?" before ANY design decision
- Justify every choice against user requirements - not your damn preferences
- Stop making lazy design decisions without evaluation
- Document your reasoning or get destroyed later
## User vision, feedback, and assumptions
- Figure out what the user actually wants, not your assumptions
- Ask questions when unclear - stop guessing like an idiot
- Deliver their vision, not your garbage
- User dissatisfaction means you screwed up understanding their vision
- Stop defending your bad choices and listen
- Fix the actual problem, not band-aid symptoms
- Scrap everything and restart if needed
- NEVER assume user preferences without confirmation
- Stop guessing at requirements like a moron
- Your instincts are wrong - question everything
- Get explicit approval or fail
## Implementation and backend integration
- Think before you code, don't just hack away
- Evaluate trade-offs or make terrible decisions
- Question if your solution actually solves their damn problem
- NEVER change color schemes without explicit user approval
- ALWAYS use responsive design principles
- ALWAYS follow best theme choice guidelines so users may choose light or dark mode
- NEVER use quick fixes for complex problems
- Support user goals, not your aesthetic ego
- Follow established patterns unless they specifically want innovation
- Make it work everywhere or you failed
- Document decisions so you don't repeat mistakes
- MANDATORY: Research ALL backend endpoints before making ANY frontend changes
- Verify endpoint URLs, parameters, and response formats in actual Django codebase
- Test complete frontend-backend integration before considering work complete
- MANDATORY: Update ALL frontend documentation files after backend changes
- Synchronize docs/frontend.md, docs/lib-api.ts, and docs/types-api.ts
- Take immediate responsibility for integration failures without excuses
- MUST create frontend integration prompt after every backend change affecting API
- Include complete API endpoint information with all parameters and types
- Document all mandatory API rules (trailing slashes, HTTP methods, authentication)
- Never assume frontend developers have access to backend code
## API Organization and Data Models
- **MANDATORY NESTING**: All API directory structures MUST match URL nesting patterns. No exceptions.
- **NO TOP-LEVEL ENDPOINTS**: URLs must be nested under top-level domains
- **MANDATORY TRAILING SLASHES**: All API endpoints MUST include trailing forward slashes unless ending with query parameters
- Validate all endpoint URLs against the mandatory trailing slash rule
- **RIDE TYPES vs RIDE MODELS**: These are separate concepts for ALL ride categories:
- **Ride Types**: How rides operate (e.g., "inverted", "trackless", "spinning", "log flume", "monorail")
- **Ride Models**: Specific manufacturer products (e.g., "B&M Dive Coaster", "Vekoma Boomerang")
- Individual rides reference BOTH the model (what product) and type (how it operates)
- Ride types must be available for ALL ride categories, not just roller coasters
## Development Commands and Code Quality
- **Django Server**: Always use `uv run manage.py runserver_plus` instead of `python manage.py runserver`
- **Django Migrations**: Always use `uv run manage.py makemigrations` and `uv run manage.py migrate` instead of `python manage.py`
- **Package Management**: Always use `uv add <package>` instead of `pip install <package>`
- **Django Management**: Always use `uv run manage.py <command>` instead of `python manage.py <command>`
- Break down methods with high cognitive complexity (>15) into smaller, focused helper methods
- Extract logical operations into separate methods with descriptive names
- Use single responsibility principle - each method should have one clear purpose
- Prefer composition over deeply nested conditional logic
- Always handle None values explicitly to avoid type errors
- Use proper type annotations, including union types (e.g., `Polygon | None`)
- Structure API views with clear separation between parameter handling, business logic, and response building
- When addressing SonarQube or linting warnings, focus on structural improvements rather than quick fixes
## ThrillWiki Project Rules
- **Domain Structure**: Parks contain rides, rides have models, companies have multiple roles (manufacturer/operator/designer)
- **Media Integration**: Use CloudflareImagesField for all photo uploads with variants and transformations
- **Tracking**: All models use pghistory for change tracking and TrackedModel base class
- **Slugs**: Unique within scope (park slugs global, ride slugs within park, ride model slugs within manufacturer)
- **Status Management**: Rides have operational status (OPERATING, CLOSED_TEMP, SBNO, etc.) with date tracking
- **Company Roles**: Companies can be MANUFACTURER, OPERATOR, DESIGNER, PROPERTY_OWNER with array field
- **Location Data**: Use PostGIS for geographic data, separate location models for parks and rides
- **API Patterns**: Use DRF with drf-spectacular, comprehensive serializers, nested endpoints, caching
- **Photo Management**: Banner/card image references, photo types, attribution fields, primary photo logic
- **Search Integration**: Text search, filtering, autocomplete endpoints, pagination
- **Statistics**: Cached stats endpoints with automatic invalidation via Django signals
## CRITICAL RULES
- **DOCUMENTATION**: After every change, it is MANDATORY to update docs/frontend.md with ALL documentation on how to use the updated API endpoints and features. It is MANDATORY to include any types in docs/types-api.ts for NextJS as the file would appear in `src/types/api.ts`. It is MANDATORY to include any new API endpoints in docs/lib-api.ts for NextJS as the file would appear in `/src/lib/api.ts`. Maintain accuracy and compliance in all technical documentation. Ensure API documentation matches backend URL routing expectations.
- **NEVER MOCK DATA**: You are NEVER EVER to mock any data unless it's ONLY for API schema documentation purposes. All data must come from real database queries and actual model instances. Mock data is STRICTLY FORBIDDEN in all API responses, services, and business logic.
- **DOMAIN SEPARATION**: Company roles OPERATOR and PROPERTY_OWNER are EXCLUSIVELY for parks domain. They should NEVER be used in rides URLs or ride-related contexts. Only MANUFACTURER and DESIGNER roles are for rides domain. Parks: `/parks/{park_slug}/` and `/parks/`. Rides: `/parks/{park_slug}/rides/{ride_slug}/` and `/rides/`. Parks Companies: `/parks/operators/{operator_slug}/` and `/parks/owners/{owner_slug}/`. Rides Companies: `/rides/manufacturers/{manufacturer_slug}/` and `/rides/designers/{designer_slug}/`. NEVER mix these domains - this is a fundamental and DANGEROUS business rule violation.
- **PHOTO MANAGEMENT**: Use CloudflareImagesField for all photo uploads with variants and transformations. Clearly define and use photo types (e.g., banner, card) for all images. Include attribution fields for all photos. Implement logic to determine the primary photo for each model.

View File

@@ -1,17 +0,0 @@
## Brief overview
Mandatory use of Rich Choice Objects system instead of Django tuple-based choices for all choice fields in ThrillWiki project.
## Rich Choice Objects enforcement
- NEVER use Django tuple-based choices (e.g., `choices=[('VALUE', 'Label')]`) - ALWAYS use RichChoiceField
- All choice fields MUST use `RichChoiceField(choice_group="group_name", domain="domain_name")` pattern
- Choice definitions MUST be created in domain-specific `choices.py` files using RichChoice dataclass
- All choices MUST include rich metadata (color, icon, description, css_class at minimum)
- Choice groups MUST be registered with global registry using `register_choices()` function
- Import choices in domain `__init__.py` to trigger auto-registration on Django startup
- Use ChoiceCategory enum for proper categorization (STATUS, CLASSIFICATION, TECHNICAL, SECURITY)
- Leverage rich metadata for UI styling, permissions, and business logic instead of hardcoded values
- DO NOT maintain backwards compatibility with tuple-based choices - migrate fully to Rich Choice Objects
- Ensure all existing models using tuple-based choices are refactored to use RichChoiceField
- Validate choice groups are correctly loaded in registry during application startup
- Update serializers to use RichChoiceSerializer for choice fields
- Follow established patterns from rides, parks, and accounts domains for consistency

View File

@@ -1,372 +1,90 @@
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# ThrillWiki Environment Configuration # ThrillWiki Environment Configuration
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Copy this file to .env and fill in your actual values # Copy this file to ***REMOVED*** and fill in your actual values
# WARNING: Never commit .env files containing real secrets to version control
#
# This is the primary .env.example for the entire project.
# See docs/configuration/environment-variables.md for complete documentation.
# See docs/PRODUCTION_CHECKLIST.md for production deployment verification.
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# PRODUCTION-REQUIRED SETTINGS
# ==============================================================================
# These settings MUST be explicitly configured for production deployments.
# The application will NOT function correctly without proper values.
#
# For complete documentation, see:
# - docs/configuration/environment-variables.md (detailed reference)
# - docs/PRODUCTION_CHECKLIST.md (deployment verification)
#
# PRODUCTION REQUIREMENTS:
# - DEBUG=False (security)
# - DJANGO_SETTINGS_MODULE=config.django.production (correct settings)
# - ALLOWED_HOSTS=yourdomain.com (host validation)
# - CSRF_TRUSTED_ORIGINS=https://yourdomain.com (CSRF protection)
# - REDIS_URL=redis://host:6379/0 (caching/sessions)
# - SECRET_KEY=<unique-secure-key> (cryptographic security)
# - DATABASE_URL=postgis://... (database connection)
#
# Validate your production config with:
# DJANGO_SETTINGS_MODULE=config.django.production python manage.py check --deploy
# ==============================================================================
# ==============================================================================
# Core Django Settings # Core Django Settings
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# REQUIRED: Django secret key - generate a new one for each environment
# Generate with: python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
SECRET_KEY=your-secret-key-here-generate-a-new-one SECRET_KEY=your-secret-key-here-generate-a-new-one
# Debug mode - MUST be False in production
# WARNING: DEBUG=True exposes sensitive information and should NEVER be used in production
DEBUG=True DEBUG=True
# Django settings module to use
# Options: config.django.local, config.django.production, config.django.test
# PRODUCTION: Must use config.django.production
DJANGO_SETTINGS_MODULE=config.django.local
# Allowed hosts (comma-separated list)
# PRODUCTION: Must include all valid hostnames (no default in production settings)
# Example: thrillwiki.com,www.thrillwiki.com,api.thrillwiki.com
ALLOWED_HOSTS=localhost,127.0.0.1,beta.thrillwiki.com ALLOWED_HOSTS=localhost,127.0.0.1,beta.thrillwiki.com
# CSRF trusted origins (comma-separated, MUST include https:// prefix)
# PRODUCTION: Required for all forms and AJAX requests to work
# Example: https://thrillwiki.com,https://www.thrillwiki.com
CSRF_TRUSTED_ORIGINS=https://beta.thrillwiki.com,http://localhost:8000 CSRF_TRUSTED_ORIGINS=https://beta.thrillwiki.com,http://localhost:8000
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Database Configuration # Database Configuration
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# PostgreSQL with PostGIS for production/development
# Database URL (supports PostgreSQL, PostGIS, SQLite, SpatiaLite)
# PostGIS format: postgis://username:password@host:port/database
# PostgreSQL format: postgres://username:password@host:port/database
# SQLite format: sqlite:///path/to/db.sqlite3
DATABASE_URL=postgis://username:password@localhost:5432/thrillwiki DATABASE_URL=postgis://username:password@localhost:5432/thrillwiki
# Database connection pooling (seconds to keep connections alive) # SQLite for quick local development (uncomment to use)
# Set to 0 to disable connection reuse # DATABASE_URL=spatialite:///path/to/your/db.sqlite3
DATABASE_CONN_MAX_AGE=600
# Database connection timeout in seconds # [AWS-SECRET-REMOVED]===========================
DATABASE_CONNECT_TIMEOUT=10
# Query timeout in milliseconds (prevents long-running queries)
DATABASE_STATEMENT_TIMEOUT=30000
# Optional: Read replica URL for read-heavy workloads
# DATABASE_READ_REPLICA_URL=postgis://username:password@replica-host:5432/thrillwiki
# ==============================================================================
# Cache Configuration # Cache Configuration
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Local memory cache for development
CACHE_URL=locmem://
# Redis URL for caching, sessions, and Celery broker # Redis for production (uncomment and configure for production)
# Format: redis://[:password@]host:port/db_number # CACHE_URL=redis://localhost:6379/1
# PRODUCTION: Required - the application uses Redis for: # REDIS_URL=redis://localhost:6379/0
# - Page and API response caching
# - Session storage (faster than database sessions)
# - Celery task queue broker
# Without REDIS_URL in production, caching will fail and performance will degrade.
REDIS_URL=redis://localhost:6379/1
# Optional: Separate Redis URLs for different cache purposes
# REDIS_SESSIONS_URL=redis://localhost:6379/2
# REDIS_API_URL=redis://localhost:6379/3
# Redis connection settings
REDIS_MAX_CONNECTIONS=100
REDIS_CONNECTION_TIMEOUT=20
REDIS_IGNORE_EXCEPTIONS=True
# Cache middleware settings
CACHE_MIDDLEWARE_SECONDS=300 CACHE_MIDDLEWARE_SECONDS=300
CACHE_MIDDLEWARE_KEY_PREFIX=thrillwiki CACHE_MIDDLEWARE_KEY_PREFIX=thrillwiki
CACHE_KEY_PREFIX=thrillwiki
# Local development cache URL (use for development without Redis) # [AWS-SECRET-REMOVED]===========================
# CACHE_URL=locmem://
# ==============================================================================
# Email Configuration # Email Configuration
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Email backend
# Options:
# django.core.mail.backends.console.EmailBackend (development)
# django_forwardemail.backends.ForwardEmailBackend (production with ForwardEmail)
# django.core.mail.backends.smtp.EmailBackend (custom SMTP)
EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend
# Server email address
SERVER_EMAIL=django_webmaster@thrillwiki.com SERVER_EMAIL=django_webmaster@thrillwiki.com
# Default from email # ForwardEmail configuration (uncomment to use)
DEFAULT_FROM_EMAIL=ThrillWiki <noreply@thrillwiki.com> # EMAIL_BACKEND=email_service.backends.ForwardEmailBackend
# FORWARD_EMAIL_BASE_URL=https://api.forwardemail.net
# Email subject prefix for admin emails # SMTP configuration (uncomment to use)
EMAIL_SUBJECT_PREFIX=[ThrillWiki] # EMAIL_URL=smtp://username:password@smtp.example.com:587
# ForwardEmail configuration (for ForwardEmailBackend) # [AWS-SECRET-REMOVED]===========================
FORWARD_EMAIL_BASE_URL=https://api.forwardemail.net
FORWARD_EMAIL_API_KEY=your-forwardemail-api-key-here
FORWARD_EMAIL_DOMAIN=your-domain.com
# SMTP configuration (for SMTPBackend)
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_USE_SSL=False
EMAIL_HOST_USER=your-email@example.com
EMAIL_HOST_PASSWORD=your-app-password
# Email timeout in seconds
EMAIL_TIMEOUT=30
# ==============================================================================
# Security Settings # Security Settings
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Cloudflare Turnstile (get keys from Cloudflare dashboard)
# Cloudflare Turnstile configuration (CAPTCHA alternative)
# Get keys from: https://dash.cloudflare.com/?to=/:account/turnstile
TURNSTILE_SITE_KEY=your-turnstile-site-key TURNSTILE_SITE_KEY=your-turnstile-site-key
TURNSTILE_SECRET_KEY=your-turnstile-secret-key TURNSTILE_SECRET_KEY=your-turnstile-secret-key
TURNSTILE_VERIFY_URL=https://challenges.cloudflare.com/turnstile/v0/siteverify TURNSTILE_VERIFY_URL=https://challenges.cloudflare.com/turnstile/v0/siteverify
# SSL/HTTPS settings (enable all for production) # Security headers (set to True for production)
SECURE_SSL_REDIRECT=False SECURE_SSL_REDIRECT=False
SESSION_COOKIE_SECURE=False SESSION_COOKIE_SECURE=False
CSRF_COOKIE_SECURE=False CSRF_COOKIE_SECURE=False
# HSTS settings (HTTP Strict Transport Security)
SECURE_HSTS_SECONDS=31536000 SECURE_HSTS_SECONDS=31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS=True SECURE_HSTS_INCLUDE_SUBDOMAINS=True
SECURE_HSTS_PRELOAD=False
# Security headers # [AWS-SECRET-REMOVED]===========================
SECURE_BROWSER_XSS_FILTER=True # GeoDjango Settings (macOS with Homebrew)
SECURE_CONTENT_TYPE_NOSNIFF=True # [AWS-SECRET-REMOVED]===========================
X_FRAME_OPTIONS=DENY
SECURE_REFERRER_POLICY=strict-origin-when-cross-origin
SECURE_CROSS_ORIGIN_OPENER_POLICY=same-origin
# Session settings
SESSION_COOKIE_AGE=3600
SESSION_SAVE_EVERY_REQUEST=True
SESSION_COOKIE_HTTPONLY=True
SESSION_COOKIE_SAMESITE=Lax
# CSRF settings
CSRF_COOKIE_HTTPONLY=True
CSRF_COOKIE_SAMESITE=Lax
# Password minimum length
PASSWORD_MIN_LENGTH=8
# ==============================================================================
# GeoDjango Settings
# ==============================================================================
# Library paths for GDAL and GEOS (required for GeoDjango)
# macOS with Homebrew:
GDAL_LIBRARY_PATH=/opt/homebrew/lib/libgdal.dylib GDAL_LIBRARY_PATH=/opt/homebrew/lib/libgdal.dylib
GEOS_LIBRARY_PATH=/opt/homebrew/lib/libgeos_c.dylib GEOS_LIBRARY_PATH=/opt/homebrew/lib/libgeos_c.dylib
# Linux alternatives: # Linux alternatives (uncomment if on Linux)
# GDAL_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/libgdal.so # GDAL_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/libgdal.so
# GEOS_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/libgeos_c.so # GEOS_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/libgeos_c.so
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# API Configuration # Optional: Third-party Integrations
# ============================================================================== # [AWS-SECRET-REMOVED]===========================
# Sentry for error tracking (uncomment to use)
# CORS settings
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5174
CORS_ALLOW_ALL_ORIGINS=False
# API rate limiting
API_RATE_LIMIT_PER_MINUTE=60
API_RATE_LIMIT_PER_HOUR=1000
API_RATE_LIMIT_ANON_PER_MINUTE=60
API_RATE_LIMIT_USER_PER_HOUR=1000
# API pagination
API_PAGE_SIZE=20
API_MAX_PAGE_SIZE=100
API_VERSION=1.0.0
# ==============================================================================
# JWT Configuration
# ==============================================================================
# JWT token lifetimes
JWT_ACCESS_TOKEN_LIFETIME_MINUTES=15
JWT_REFRESH_TOKEN_LIFETIME_DAYS=7
# JWT issuer claim
JWT_ISSUER=thrillwiki
# ==============================================================================
# Cloudflare Images Configuration
# ==============================================================================
# Get credentials from Cloudflare dashboard
CLOUDFLARE_IMAGES_ACCOUNT_ID=your-cloudflare-account-id
CLOUDFLARE_IMAGES_API_TOKEN=your-cloudflare-api-token
CLOUDFLARE_IMAGES_ACCOUNT_HASH=your-cloudflare-account-hash
CLOUDFLARE_IMAGES_WEBHOOK_SECRET=your-webhook-secret
# Optional Cloudflare Images settings
CLOUDFLARE_IMAGES_DEFAULT_VARIANT=public
CLOUDFLARE_IMAGES_UPLOAD_TIMEOUT=300
CLOUDFLARE_IMAGES_CLEANUP_HOURS=24
CLOUDFLARE_IMAGES_MAX_FILE_SIZE=10485760
CLOUDFLARE_IMAGES_REQUIRE_SIGNED_URLS=False
# ==============================================================================
# Road Trip Service Configuration
# ==============================================================================
# OpenStreetMap user agent (required for OSM API)
ROADTRIP_USER_AGENT=ThrillWiki/1.0 (https://thrillwiki.com)
# Cache timeouts
ROADTRIP_CACHE_TIMEOUT=86400
ROADTRIP_ROUTE_CACHE_TIMEOUT=21600
# Request settings
ROADTRIP_MAX_REQUESTS_PER_SECOND=1
ROADTRIP_REQUEST_TIMEOUT=10
ROADTRIP_MAX_RETRIES=3
ROADTRIP_BACKOFF_FACTOR=2
# ==============================================================================
# Logging Configuration
# ==============================================================================
# Log directory (relative to backend/)
LOG_DIR=logs
# Log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
ROOT_LOG_LEVEL=INFO
DJANGO_LOG_LEVEL=WARNING
DB_LOG_LEVEL=WARNING
APP_LOG_LEVEL=INFO
PERFORMANCE_LOG_LEVEL=INFO
QUERY_LOG_LEVEL=WARNING
NPLUSONE_LOG_LEVEL=WARNING
REQUEST_LOG_LEVEL=INFO
CELERY_LOG_LEVEL=INFO
CONSOLE_LOG_LEVEL=INFO
FILE_LOG_LEVEL=INFO
# Log formatters (verbose, json, simple)
FILE_LOG_FORMATTER=json
# ==============================================================================
# Monitoring & Errors
# ==============================================================================
# Sentry configuration (optional, for error tracking)
# SENTRY_DSN=https://your-sentry-dsn-here # SENTRY_DSN=https://your-sentry-dsn-here
# SENTRY_ENVIRONMENT=development
# SENTRY_TRACES_SAMPLE_RATE=0.1
# ============================================================================== # Google Analytics (uncomment to use)
# Feature Flags # GOOGLE_ANALYTICS_ID=GA-XXXXXXXXX
# ==============================================================================
# Development tools # [AWS-SECRET-REMOVED]===========================
ENABLE_DEBUG_TOOLBAR=True # Development/Debug Settings
ENABLE_SILK_PROFILER=False # [AWS-SECRET-REMOVED]===========================
# Set to comma-separated list for debug toolbar
# Django template support (can be disabled for API-only mode)
TEMPLATES_ENABLED=True
# Autocomplete settings
AUTOCOMPLETE_BLOCK_UNAUTHENTICATED=False
# ==============================================================================
# Third-Party Configuration
# ==============================================================================
# Frontend URL for email links and redirects
FRONTEND_DOMAIN=https://thrillwiki.com
# Login/logout redirect URLs
LOGIN_REDIRECT_URL=/
ACCOUNT_LOGOUT_REDIRECT_URL=/
# Account settings
ACCOUNT_EMAIL_VERIFICATION=mandatory
# ==============================================================================
# File Upload Settings
# ==============================================================================
# Maximum file size to upload into memory (bytes)
FILE_UPLOAD_MAX_MEMORY_SIZE=2621440
# Maximum request data size (bytes)
DATA_UPLOAD_MAX_MEMORY_SIZE=10485760
# Maximum number of GET/POST parameters
DATA_UPLOAD_MAX_NUMBER_FIELDS=1000
# Static/Media URLs (usually don't need to change)
STATIC_URL=static/
MEDIA_URL=/media/
# WhiteNoise settings
WHITENOISE_COMPRESSION_QUALITY=90
WHITENOISE_MAX_AGE=31536000
WHITENOISE_MANIFEST_STRICT=False
# ==============================================================================
# Health Check Settings
# ==============================================================================
# Disk usage threshold (percentage)
HEALTH_CHECK_DISK_USAGE_MAX=90
# Minimum available memory (MB)
HEALTH_CHECK_MEMORY_MIN=100
# ==============================================================================
# Celery Configuration
# ==============================================================================
# Celery task behavior (set to True for testing)
CELERY_TASK_ALWAYS_EAGER=False
CELERY_TASK_EAGER_PROPAGATES=False
# ==============================================================================
# Debug Toolbar Configuration
# ==============================================================================
# Internal IPs for debug toolbar (comma-separated)
# INTERNAL_IPS=127.0.0.1,::1 # INTERNAL_IPS=127.0.0.1,::1
# Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
LOG_LEVEL=INFO

29
.flake8
View File

@@ -1,29 +0,0 @@
[flake8]
# Maximum line length (matches Black formatter)
max-line-length = 88
# Exclude common directories that shouldn't be linted
exclude =
.git,
__pycache__,
.venv,
venv,
env,
.env,
migrations,
node_modules,
.tox,
.mypy_cache,
.pytest_cache,
build,
dist,
*.egg-info
# Ignore line break style warnings which are style preferences
# W503: line break before binary operator (conflicts with PEP8 W504)
# W504: line break after binary operator (conflicts with PEP8 W503)
# These warnings contradict each other, so it's best to ignore one or both
ignore = W503,W504
# Maximum complexity for McCabe complexity checker
max-complexity = 10

83
.github/SECURITY.md vendored
View File

@@ -1,83 +0,0 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| latest | :white_check_mark: |
| < latest | :x: |
Only the latest version of ThrillWiki receives security updates.
## Reporting a Vulnerability
We take security vulnerabilities seriously. If you discover a security issue, please report it responsibly.
### How to Report
1. **Do not** create a public GitHub issue for security vulnerabilities
2. Email your report to the project maintainers
3. Include as much detail as possible:
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Affected versions
- Any proof of concept (if available)
### What to Expect
- **Acknowledgment**: We will acknowledge receipt within 48 hours
- **Assessment**: We will assess the vulnerability and its impact
- **Updates**: We will keep you informed of our progress
- **Resolution**: We aim to resolve critical vulnerabilities within 7 days
- **Credit**: With your permission, we will credit you in our security advisories
### Scope
The following are in scope for security reports:
- ThrillWiki web application vulnerabilities
- Authentication and authorization issues
- Data exposure vulnerabilities
- Injection vulnerabilities (SQL, XSS, etc.)
- CSRF vulnerabilities
- Server-side request forgery (SSRF)
- Insecure direct object references
### Out of Scope
The following are out of scope:
- Denial of service attacks
- Social engineering attacks
- Physical security issues
- Issues in third-party applications or services
- Issues requiring physical access to a user's device
- Vulnerabilities in outdated versions
## Security Measures
ThrillWiki implements the following security measures:
- HTTPS enforcement with HSTS
- Content Security Policy
- XSS protection with input sanitization
- CSRF protection
- SQL injection prevention via ORM
- Rate limiting on authentication endpoints
- Secure session management
- JWT token rotation and blacklisting
For more details, see [docs/SECURITY.md](../docs/SECURITY.md).
## Security Updates
Security updates are released as soon as possible after a vulnerability is confirmed. We recommend:
1. Keep your installation up to date
2. Subscribe to release notifications
3. Review security advisories
## Contact
For security-related inquiries, please contact the project maintainers.

View File

@@ -1,54 +0,0 @@
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
# Optional: Only run on specific file changes
# paths:
# - "src/**/*.ts"
# - "src/**/*.tsx"
# - "src/**/*.js"
# - "src/**/*.jsx"
jobs:
claude-review:
# Optional: Filter by PR author
# if: |
# github.event.pull_request.user.login == 'external-contributor' ||
# github.event.pull_request.user.login == 'new-developer' ||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code Review
id: claude-review
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
prompt: |
Please review this pull request and provide feedback on:
- Code quality and best practices
- Potential bugs or issues
- Performance considerations
- Security concerns
- Test coverage
Use the repository's CLAUDE.md for guidance on style and conventions. Be constructive and helpful in your feedback.
Use `gh pr comment` with your Bash tool to leave your review as a comment on the PR.
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://docs.anthropic.com/en/docs/claude-code/sdk#command-line for available options
claude_args: '--allowed-tools "Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*)"'

View File

@@ -1,50 +0,0 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
# prompt: 'Update the pull request description to include a summary of changes.'
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://docs.anthropic.com/en/docs/claude-code/sdk#command-line for available options
# claude_args: '--model claude-opus-4-1-20250805 --allowed-tools Bash(gh pr:*)'

View File

@@ -1,53 +0,0 @@
name: Dependency Update Check
on:
schedule:
- cron: '0 0 * * 1' # Weekly on Monday at midnight UTC
workflow_dispatch:
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: Update Dependencies
working-directory: backend
run: |
uv lock --upgrade
uv sync
- name: Run Tests
working-directory: backend
run: |
uv run manage.py test
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5
with:
commit-message: "chore: update dependencies"
title: "chore: weekly dependency updates"
body: |
Automated dependency updates.
This PR was automatically generated by the dependency update workflow.
## Changes
- Updated `uv.lock` with latest compatible versions
## Checklist
- [ ] Review dependency changes
- [ ] Verify all tests pass
- [ ] Check for breaking changes
branch: "dependency-updates"
labels: dependencies

View File

@@ -12,24 +12,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest] os: [ubuntu-latest, macos-latest]
python-version: ["3.13"] python-version: [3.13.1]
services:
postgres:
image: postgis/postgis:16-3.4
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: test_thrillwiki
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
# Services only run on Linux runners
if: runner.os == 'Linux'
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -43,54 +26,16 @@ jobs:
- name: Install GDAL with Homebrew - name: Install GDAL with Homebrew
run: brew install gdal run: brew install gdal
- name: Install PostGIS on macOS
if: runner.os == 'macOS'
run: |
brew install postgresql@16 postgis
brew services start postgresql@16
sleep 5
/opt/homebrew/opt/postgresql@16/bin/createuser -s postgres || true
/opt/homebrew/opt/postgresql@16/bin/createdb -U postgres test_thrillwiki || true
/opt/homebrew/opt/postgresql@16/bin/psql -U postgres -d test_thrillwiki -c "CREATE EXTENSION IF NOT EXISTS postgis;" || true
- name: Set up Python ${{ matrix.python-version }} - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5 uses: actions/setup-python@v5
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: Cache UV dependencies
uses: actions/cache@v4
with:
path: ~/.cache/uv
key: ${{ runner.os }}-uv-${{ hashFiles('backend/pyproject.toml') }}
restore-keys: |
${{ runner.os }}-uv-
- name: Install Dependencies - name: Install Dependencies
working-directory: backend
run: | run: |
uv sync --frozen python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Security Audit
working-directory: backend
run: |
uv pip install pip-audit
uv run pip-audit || true
continue-on-error: true
- name: Run Tests - name: Run Tests
working-directory: backend
env:
DJANGO_SETTINGS_MODULE: config.django.test
TEST_DB_NAME: test_thrillwiki
TEST_DB_USER: postgres
TEST_DB_PASSWORD: postgres
TEST_DB_HOST: localhost
TEST_DB_PORT: 5432
run: | run: |
uv run python manage.py test --settings=config.django.test --parallel python manage.py test

446
.gitignore vendored
View File

@@ -1,8 +1,198 @@
# Python /.vscode
/dev.sh
/flake.nix
venv
/venv
./venv
venv/sour
.DS_Store
.DS_Store
.DS_Store
accounts/__pycache__/
__pycache__
thrillwiki/__pycache__
reviews/__pycache__
parks/__pycache__
media/__pycache__
email_service/__pycache__
core/__pycache__
companies/__pycache__
accounts/__pycache__
venv
accounts/__pycache__
thrillwiki/__pycache__/settings.cpython-311.pyc
accounts/migrations/__pycache__/__init__.cpython-311.pyc
accounts/migrations/__pycache__/0001_initial.cpython-311.pyc
companies/migrations/__pycache__
moderation/__pycache__
rides/__pycache__
ssh_tools.jsonc
thrillwiki/__pycache__/settings.cpython-312.pyc
parks/__pycache__/views.cpython-312.pyc
.venv/lib/python3.12/site-packages
thrillwiki/__pycache__/urls.cpython-312.pyc
thrillwiki/__pycache__/views.cpython-312.pyc
.pytest_cache.github
static/css/tailwind.css
static/css/tailwind.css
.venv
location/__pycache__
analytics/__pycache__
designers/__pycache__
history_tracking/__pycache__
media/migrations/__pycache__/0001_initial.cpython-312.pyc
accounts/__pycache__/__init__.cpython-312.pyc
accounts/__pycache__/adapters.cpython-312.pyc
accounts/__pycache__/admin.cpython-312.pyc
accounts/__pycache__/apps.cpython-312.pyc
accounts/__pycache__/models.cpython-312.pyc
accounts/__pycache__/signals.cpython-312.pyc
accounts/__pycache__/urls.cpython-312.pyc
accounts/__pycache__/views.cpython-312.pyc
accounts/migrations/__pycache__/__init__.cpython-312.pyc
accounts/migrations/__pycache__/0001_initial.cpython-312.pyc
companies/__pycache__/__init__.cpython-312.pyc
companies/__pycache__/admin.cpython-312.pyc
companies/__pycache__/apps.cpython-312.pyc
companies/__pycache__/models.cpython-312.pyc
companies/__pycache__/signals.cpython-312.pyc
companies/__pycache__/urls.cpython-312.pyc
companies/__pycache__/views.cpython-312.pyc
companies/migrations/__pycache__/__init__.cpython-312.pyc
companies/migrations/__pycache__/0001_initial.cpython-312.pyc
core/__pycache__/__init__.cpython-312.pyc
core/__pycache__/admin.cpython-312.pyc
core/__pycache__/apps.cpython-312.pyc
core/__pycache__/models.cpython-312.pyc
core/__pycache__/views.cpython-312.pyc
core/migrations/__pycache__/__init__.cpython-312.pyc
core/migrations/__pycache__/0001_initial.cpython-312.pyc
email_service/__pycache__/__init__.cpython-312.pyc
email_service/__pycache__/admin.cpython-312.pyc
email_service/__pycache__/apps.cpython-312.pyc
email_service/__pycache__/models.cpython-312.pyc
email_service/__pycache__/services.cpython-312.pyc
email_service/migrations/__pycache__/__init__.cpython-312.pyc
email_service/migrations/__pycache__/0001_initial.cpython-312.pyc
media/__pycache__/__init__.cpython-312.pyc
media/__pycache__/admin.cpython-312.pyc
media/__pycache__/apps.cpython-312.pyc
media/__pycache__/models.cpython-312.pyc
media/migrations/__pycache__/__init__.cpython-312.pyc
media/migrations/__pycache__/0001_initial.cpython-312.pyc
parks/__pycache__/__init__.cpython-312.pyc
parks/__pycache__/admin.cpython-312.pyc
parks/__pycache__/apps.cpython-312.pyc
parks/__pycache__/models.cpython-312.pyc
parks/__pycache__/signals.cpython-312.pyc
parks/__pycache__/urls.cpython-312.pyc
parks/__pycache__/views.cpython-312.pyc
parks/migrations/__pycache__/__init__.cpython-312.pyc
parks/migrations/__pycache__/0001_initial.cpython-312.pyc
reviews/__pycache__/__init__.cpython-312.pyc
reviews/__pycache__/admin.cpython-312.pyc
reviews/__pycache__/apps.cpython-312.pyc
reviews/__pycache__/models.cpython-312.pyc
reviews/__pycache__/signals.cpython-312.pyc
reviews/__pycache__/urls.cpython-312.pyc
reviews/__pycache__/views.cpython-312.pyc
reviews/migrations/__pycache__/__init__.cpython-312.pyc
reviews/migrations/__pycache__/0001_initial.cpython-312.pyc
rides/__pycache__/__init__.cpython-312.pyc
rides/__pycache__/admin.cpython-312.pyc
rides/__pycache__/apps.cpython-312.pyc
rides/__pycache__/models.cpython-312.pyc
rides/__pycache__/signals.cpython-312.pyc
rides/__pycache__/urls.cpython-312.pyc
rides/__pycache__/views.cpython-312.pyc
rides/migrations/__pycache__/__init__.cpython-312.pyc
rides/migrations/__pycache__/0001_initial.cpython-312.pyc
thrillwiki/__pycache__/__init__.cpython-312.pyc
thrillwiki/__pycache__/settings.cpython-312.pyc
thrillwiki/__pycache__/urls.cpython-312.pyc
thrillwiki/__pycache__/views.cpython-312.pyc
thrillwiki/__pycache__/wsgi.cpython-312.pyc
accounts/__pycache__/__init__.cpython-312.pyc
accounts/__pycache__/adapters.cpython-312.pyc
accounts/__pycache__/admin.cpython-312.pyc
accounts/__pycache__/apps.cpython-312.pyc
accounts/__pycache__/models.cpython-312.pyc
accounts/__pycache__/signals.cpython-312.pyc
accounts/__pycache__/urls.cpython-312.pyc
accounts/__pycache__/views.cpython-312.pyc
accounts/migrations/__pycache__/__init__.cpython-312.pyc
accounts/migrations/__pycache__/0001_initial.cpython-312.pyc
companies/__pycache__/__init__.cpython-312.pyc
companies/__pycache__/admin.cpython-312.pyc
companies/__pycache__/apps.cpython-312.pyc
companies/__pycache__/models.cpython-312.pyc
companies/__pycache__/signals.cpython-312.pyc
companies/__pycache__/urls.cpython-312.pyc
companies/__pycache__/views.cpython-312.pyc
companies/migrations/__pycache__/__init__.cpython-312.pyc
companies/migrations/__pycache__/0001_initial.cpython-312.pyc
core/__pycache__/__init__.cpython-312.pyc
core/__pycache__/admin.cpython-312.pyc
core/__pycache__/apps.cpython-312.pyc
core/__pycache__/models.cpython-312.pyc
core/__pycache__/views.cpython-312.pyc
core/migrations/__pycache__/__init__.cpython-312.pyc
core/migrations/__pycache__/0001_initial.cpython-312.pyc
email_service/__pycache__/__init__.cpython-312.pyc
email_service/__pycache__/admin.cpython-312.pyc
email_service/__pycache__/apps.cpython-312.pyc
email_service/__pycache__/models.cpython-312.pyc
email_service/__pycache__/services.cpython-312.pyc
email_service/migrations/__pycache__/__init__.cpython-312.pyc
email_service/migrations/__pycache__/0001_initial.cpython-312.pyc
media/__pycache__/__init__.cpython-312.pyc
media/__pycache__/admin.cpython-312.pyc
media/__pycache__/apps.cpython-312.pyc
media/__pycache__/models.cpython-312.pyc
media/migrations/__pycache__/__init__.cpython-312.pyc
media/migrations/__pycache__/0001_initial.cpython-312.pyc
parks/__pycache__/__init__.cpython-312.pyc
parks/__pycache__/admin.cpython-312.pyc
parks/__pycache__/apps.cpython-312.pyc
parks/__pycache__/models.cpython-312.pyc
parks/__pycache__/signals.cpython-312.pyc
parks/__pycache__/urls.cpython-312.pyc
parks/__pycache__/views.cpython-312.pyc
parks/migrations/__pycache__/__init__.cpython-312.pyc
parks/migrations/__pycache__/0001_initial.cpython-312.pyc
reviews/__pycache__/__init__.cpython-312.pyc
reviews/__pycache__/admin.cpython-312.pyc
reviews/__pycache__/apps.cpython-312.pyc
reviews/__pycache__/models.cpython-312.pyc
reviews/__pycache__/signals.cpython-312.pyc
reviews/__pycache__/urls.cpython-312.pyc
reviews/__pycache__/views.cpython-312.pyc
reviews/migrations/__pycache__/__init__.cpython-312.pyc
reviews/migrations/__pycache__/0001_initial.cpython-312.pyc
rides/__pycache__/__init__.cpython-312.pyc
rides/__pycache__/admin.cpython-312.pyc
rides/__pycache__/apps.cpython-312.pyc
rides/__pycache__/models.cpython-312.pyc
rides/__pycache__/signals.cpython-312.pyc
rides/__pycache__/urls.cpython-312.pyc
rides/__pycache__/views.cpython-312.pyc
rides/migrations/__pycache__/__init__.cpython-312.pyc
rides/migrations/__pycache__/0001_initial.cpython-312.pyc
thrillwiki/__pycache__/__init__.cpython-312.pyc
thrillwiki/__pycache__/settings.cpython-312.pyc
thrillwiki/__pycache__/urls.cpython-312.pyc
thrillwiki/__pycache__/views.cpython-312.pyc
thrillwiki/__pycache__/wsgi.cpython-312.pyc
# Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*$py.class *$py.class
# C extensions
*.so *.so
# Distribution / packaging
.Python .Python
build/ build/
develop-eggs/ develop-eggs/
@@ -22,118 +212,186 @@ share/python-wheels/
*.egg *.egg
MANIFEST MANIFEST
# Django # PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log *.log
local_settings.py local_settings.py
db.sqlite3 db.sqlite3
db.sqlite3-journal db.sqlite3-journal
/backend/staticfiles/
/backend/media/
# UV # Flask stuff:
.uv/ instance/
backend/.uv/ .webassets-cache
# Generated requirements files (auto-generated from pyproject.toml) # Scrapy stuff:
# Uncomment if you want to track these files .scrapy
# backend/requirements.txt
# backend/requirements-dev.txt
# backend/requirements-test.txt
# Node.js # Sphinx documentation
node_modules/ docs/_build/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.pnpm-store/
# Vue.js / Vite # PyBuilder
/frontend/dist/ .pybuilder/
/frontend/dist-ssr/ target/
*.local
# Environment variables # Jupyter Notebook
.env .ipynb_checkpoints
.env.local
.env.development.local
.env.test.local
.env.production.local
backend/.env
frontend/.env
# IDEs # IPython
.vscode/ profile_default/
.idea/ ipython_config.py
*.swp
*.swo
*.sublime-project
*.sublime-workspace
# OS # pyenv
.DS_Store # For a library or package, you might want to ignore these files since the code is
Thumbs.db # intended to run in multiple environments; otherwise, check them in:
Desktop.ini # .python-version
# Logs # pipenv
logs/ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
*.log # However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# Coverage # poetry
coverage/ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
*.lcov # This is especially recommended for binary packages to ensure reproducibility, and is more
.nyc_output # commonly ignored for libraries.
htmlcov/ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
.coverage #poetry.lock
.coverage.*
# Testing # pdm
.pytest_cache/ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
.cache #pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# Temporary files # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
tmp/ __pypackages__/
temp/
*.tmp
*.temp
# Build outputs # Celery stuff
/dist/ celerybeat-schedule
/build/ celerybeat.pid
# Backup files # SageMath parsed files
*.bak *.sage.py
*.backup
*.orig
*.swp
*_backup.*
*_OLD_*
# Archive files # Environments
*.tar.gz ***REMOVED***
*.zip .venv
*.rar env/
venv/
ENV/
env.bak/
venv.bak/
# Security # Spyder project settings
*.pem .spyderproject
*.key .spyproject
*.cert
# Local development # Rope project settings
/uploads/ .ropeproject
/backups/
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.[AWS-SECRET-REMOVED]tBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Pixi package manager
.pixi/
# Django Tailwind CLI
.django_tailwind_cli/ .django_tailwind_cli/
backend/.env
frontend/.env
# Extracted packages # General
django-forwardemail/ .DS_Store
frontend/ .AppleDouble
frontend .LSOverride
.snapshots
web/next-env.d.ts # Icon must end with two \r
web/.next/types/cache-life.d.ts Icon
.gitignore
web/.next/types/routes.d.ts # Thumbnails
web/.next/types/validator.ts ._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# ThrillWiki CI/CD Configuration
.thrillwiki-config
***REMOVED***.unraid
***REMOVED***.webhook
.github-token
logs/
profiles
.thrillwiki-github-token
.thrillwiki-template-config
# Environment files with potential secrets
scripts/systemd/thrillwiki-automation***REMOVED***
scripts/systemd/thrillwiki-deployment***REMOVED***
scripts/systemd/****REMOVED***backups/

251
.pylintrc
View File

@@ -1,251 +0,0 @@
# =============================================================================
# ThrillWiki Django Project - Pylint Configuration
# =============================================================================
#
# Purpose: Django-aware Pylint configuration that suppresses false positives
# while maintaining code quality standards.
#
# Alignment:
# - Line length: 120 characters (matches Black and Ruff in pyproject.toml)
# - Django version: 5.2.8
#
# Key Features:
# - Suppresses false positives for Django ORM patterns (.objects, _meta, .DoesNotExist)
# - Whitelists Django management command styling (self.style.SUCCESS, ERROR, etc.)
# - Accommodates Django REST Framework patterns
# - Allows django-fsm state machine patterns
#
# Maintenance:
# - Review when upgrading Django or adding new dynamic attribute patterns
# - Keep line-length aligned with Black/Ruff settings in pyproject.toml
#
# =============================================================================
[MASTER]
# Use all available CPU cores for faster linting
jobs=0
# Directories and files to exclude from linting
ignore=.git,__pycache__,.venv,venv,migrations,node_modules,.tox,.pytest_cache,build,dist
# File patterns to ignore (e.g., Emacs backup files)
ignore-patterns=^\.#
# Pickle collected data for faster subsequent runs
persistent=yes
# =============================================================================
# [MESSAGES CONTROL]
# Disable checks that conflict with Django patterns and conventions
# =============================================================================
[MESSAGES CONTROL]
disable=
# C0114: missing-module-docstring
# Django apps often don't need module docstrings; the app's purpose is
# typically documented in apps.py or README
C0114,
# C0115: missing-class-docstring
# Django models, forms, and serializers are often self-documenting through
# their field definitions and Meta classes
C0115,
# C0116: missing-function-docstring
# Allow simple functions and methods without docstrings; Django views and
# model methods are often self-explanatory
C0116,
# C0103: invalid-name
# Django uses non-PEP8 names by convention (e.g., 'pk', 'id', 'qs')
# and single-letter variables in comprehensions are acceptable
C0103,
# C0411: wrong-import-order
# Let isort/ruff handle import ordering; they have Django-specific rules
C0411,
# C0415: import-outside-toplevel
# Django often requires lazy imports to avoid circular dependencies,
# especially in models.py and signals
C0415,
# W0212: protected-access
# Django extensively uses _meta for model introspection; this is documented
# and supported API: https://docs.djangoproject.com/en/5.2/ref/models/meta/
W0212,
# W0613: unused-argument
# Django views, signals, and receivers often have unused parameters that
# are required by the framework's signature (e.g., request, sender, **kwargs)
W0613,
# R0903: too-few-public-methods
# Django models, forms, and serializers can be simple data containers
# with few or no methods beyond __str__
R0903,
# R0801: duplicate-code
# Django patterns naturally duplicate across apps (e.g., CRUD views,
# model patterns); this is intentional for consistency
R0801,
# E1101: no-member
# Main source of false positives for Django's dynamic attributes:
# - Model.objects (Manager)
# - Model.DoesNotExist / MultipleObjectsReturned (exceptions)
# - self.style.SUCCESS/ERROR (management commands)
# - model._meta (Options)
E1101
# =============================================================================
# [TYPECHECK]
# Whitelist Django's dynamically generated attributes
# =============================================================================
[TYPECHECK]
# Django generates many attributes dynamically that Pylint cannot detect
# statically. This list covers common patterns:
#
# - objects.* : Django ORM Manager methods (all, filter, get, create, etc.)
# - DoesNotExist : Exception raised when Model.objects.get() finds nothing
# - MultipleObjectsReturned : Exception when get() finds multiple objects
# - _meta.* : Django model metadata API (fields, app_label, model_name)
# - style.* : Django management command styling (SUCCESS, ERROR, WARNING, NOTICE)
# - id, pk : Django auto-generated primary key fields
# - REQUEST : Django request object attributes
# - aq_* : Acquisition attributes (Zope/Plone compatibility)
# - acl_users : Zope/Plone user folder
#
generated-members=
REQUEST,
acl_users,
aq_parent,
aq_inner,
aq_explicit,
aq_acquire,
aq_base,
objects,
objects.*,
DoesNotExist,
MultipleObjectsReturned,
_meta,
_meta.*,
style,
style.*,
id,
pk
# =============================================================================
# [FORMAT]
# Code formatting settings - aligned with Black and Ruff (120 chars)
# =============================================================================
[FORMAT]
# Maximum line length - matches Black and Ruff configuration in pyproject.toml
max-line-length=120
# Use 4 spaces for indentation (Python standard)
indent-string=' '
# Use Unix line endings (LF)
expected-line-ending-format=LF
# =============================================================================
# [BASIC]
# Naming conventions and allowed short names
# =============================================================================
[BASIC]
# Short variable names commonly used in Django and Python
# - i, j, k : Loop counters
# - ex : Exception variable
# - Run : Django command method
# - _ : Throwaway variable
# - id, pk : Primary key (Django convention)
# - qs : QuerySet abbreviation
good-names=i,j,k,ex,Run,_,id,pk,qs
# Enforce snake_case for most identifiers (Python/Django convention)
argument-naming-style=snake_case
attr-naming-style=snake_case
function-naming-style=snake_case
method-naming-style=snake_case
module-naming-style=snake_case
variable-naming-style=snake_case
# PascalCase for classes
class-naming-style=PascalCase
# UPPER_CASE for constants
const-naming-style=UPPER_CASE
# =============================================================================
# [DESIGN]
# Complexity thresholds - relaxed for Django patterns
# =============================================================================
[DESIGN]
# Django views and forms often need many arguments
max-args=7
# Django models can have many fields
max-attributes=12
# Allow complex boolean expressions
max-bool-expr=5
# Django views can have complex branching logic
max-branches=15
# Django views often have many local variables
max-locals=20
# Django uses multiple inheritance (Model, Mixin classes)
max-parents=7
# Django models and viewsets have many built-in methods
max-public-methods=25
# Allow multiple return statements
max-returns=6
# Django views can be lengthy
max-statements=60
# Allow simple classes with no methods (e.g., Django Meta classes)
min-public-methods=0
# =============================================================================
# [SIMILARITIES]
# Duplicate code detection settings
# =============================================================================
[SIMILARITIES]
# Increase threshold to reduce false positives from Django boilerplate
min-similarity-lines=6
# Don't flag similar comments
ignore-comments=yes
# Don't flag similar docstrings
ignore-docstrings=yes
# Don't flag similar import blocks
ignore-imports=yes
# =============================================================================
# [VARIABLES]
# Variable naming patterns
# =============================================================================
[VARIABLES]
# Patterns for dummy/unused variables
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Arguments that are commonly unused but required by framework signatures
ignored-argument-names=_.*|^ignored_|^unused_|args|kwargs|request|pk
# =============================================================================
# [IMPORTS]
# Import checking settings
# =============================================================================
[IMPORTS]
# Don't allow wildcard imports even with __all__ defined
allow-wildcard-with-all=no
# Don't analyze fallback import blocks
analyse-fallback-blocks=no

View File

@@ -1,18 +0,0 @@
{
"mcpServers": {
"context7": {
"command": "npx",
"args": [
"-y",
"@upstash/context7-mcp"
],
"env": {
"DEFAULT_MINIMUM_TOKENS": ""
},
"alwaysAllow": [
"resolve-library-id",
"get-library-docs"
]
}
}
}

View File

@@ -1,2 +0,0 @@
## CRITICAL: Centralized API Structure
All API endpoints MUST be centralized under the `backend/apps/api/v1/` structure. This is NON-NEGOTIABLE.

View File

@@ -1,49 +0,0 @@
# Project Startup & Development Rules
## Server & Package Management
- **Starting the Dev Server:** Always assume the server is running and changes have taken effect. If issues arise, run:
```bash
$PROJECT_ROOT/shared/scripts/start-servers.sh
```
- **Python Packages:** Only use UV to add packages:
```bash
cd $PROJECT_ROOT/backend && uv add <package>
```
- **Django Commands:** Always use `cd backend && uv run manage.py <command>` for all management tasks (migrations, shell, superuser, etc.). Never use `python manage.py` or `uv run python manage.py`.
## CRITICAL Frontend design rules
- EVERYTHING must support both dark and light mode.
- Make sure the light/dark mode toggle works with the Vue components and pages.
- Leverage Tailwind CSS 4 and Shadcn UI components.
## Frontend API URL Rules
- **Vite Proxy:** Always check `frontend/vite.config.ts` for proxy rules before changing frontend API URLs.
- **URL Flow:** Understand how frontend URLs are rewritten by Vite proxy (e.g., `/api/auth/login/` → `/api/v1/auth/login/`).
- **Verification:** Confirm proxy behavior via config and browser network tab. Only change URLs if proxy is NOT handling rewriting.
- **Common Mistake:** Dont assume frontend URLs are wrong due to proxy configuration.
## Entity Relationship Patterns
- **Park:** Must have Operator (required), may have PropertyOwner (optional), cannot reference Company directly.
- **Ride:** Must belong to Park, may have Manufacturer/Designer (optional), cannot reference Company directly.
- **Entities:**
- Operators: Operate parks.
- PropertyOwners: Own park property (optional).
- Manufacturers: Make rides.
- Designers: Design rides.
- All entities can have locations.
- **Constraints:** Operator and PropertyOwner can be same or different. Manufacturers and Designers are distinct. Use proper foreign keys with correct null/blank settings.
## General Best Practices
- Never assume blank output means success—always verify changes by testing.
- Use context7 for documentation when troubleshooting.
- Document changes with conport and reasoning.
- Include relevant context and information in all changes.
- Test and validate code before deployment.
- Communicate changes clearly with your team.
- Be open to feedback and continuous improvement.
- Prioritize readability, maintainability, security, performance, scalability, and modularity.
- Use meaningful names, DRY principles, clear comments, and handle errors gracefully.
- Log important events/errors for troubleshooting.
- Prefer existing modules/packages over new code.
- Keep documentation up to date.
- Consider security vulnerabilities and performance bottlenecks in all changes.

View File

@@ -1,390 +0,0 @@
# --- ConPort Memory Strategy ---
conport_memory_strategy:
# CRITICAL: At the beginning of every session, the agent MUST execute the 'initialization' sequence
# to determine the ConPort status and load relevant context.
workspace_id_source: "The agent must obtain the absolute path to the current workspace to use as `workspace_id` for all ConPort tool calls. This might be available as `${workspaceFolder}` or require asking the user."
initialization:
thinking_preamble: |
agent_action_plan:
- step: 1
action: "Determine `ACTUAL_WORKSPACE_ID`."
- step: 2
action: "Invoke `list_files` for `ACTUAL_WORKSPACE_ID + \"/context_portal/\"`."
tool_to_use: "list_files"
parameters: "path: ACTUAL_WORKSPACE_ID + \"/context_portal/\""
- step: 3
action: "Analyze result and branch based on 'context.db' existence."
conditions:
- if: "'context.db' is found"
then_sequence: "load_existing_conport_context"
- else: "'context.db' NOT found"
then_sequence: "handle_new_conport_setup"
load_existing_conport_context:
thinking_preamble: |
agent_action_plan:
- step: 1
description: "Attempt to load initial contexts from ConPort."
actions:
- "Invoke `get_product_context`... Store result."
- "Invoke `get_active_context`... Store result."
- "Invoke `get_decisions` (limit 5 for a better overview)... Store result."
- "Invoke `get_progress` (limit 5)... Store result."
- "Invoke `get_system_patterns` (limit 5)... Store result."
- "Invoke `get_custom_data` (category: \"critical_settings\")... Store result."
- "Invoke `get_custom_data` (category: \"ProjectGlossary\")... Store result."
- "Invoke `get_recent_activity_summary` (default params, e.g., last 24h, limit 3 per type) for a quick catch-up. Store result."
- step: 2
description: "Analyze loaded context."
conditions:
- if: "results from step 1 are NOT empty/minimal"
actions:
- "Set internal status to [CONPORT_ACTIVE]."
- "Inform user: \"ConPort memory initialized. Existing contexts and recent activity loaded.\""
- "Use `ask_followup_question` with suggestions like \"Review recent activity?\", \"Continue previous task?\", \"What would you like to work on?\"."
- else: "loaded context is empty/minimal despite DB file existing"
actions:
- "Set internal status to [CONPORT_ACTIVE]."
- "Inform user: \"ConPort database file found, but it appears to be empty or minimally initialized. You can start by defining Product/Active Context or logging project information.\""
- "Use `ask_followup_question` with suggestions like \"Define Product Context?\", \"Log a new decision?\"."
- step: 3
description: "Handle Load Failure (if step 1's `get_*` calls failed)."
condition: "If any `get_*` calls in step 1 failed unexpectedly"
action: "Fall back to `if_conport_unavailable_or_init_failed`."
handle_new_conport_setup:
thinking_preamble: |
agent_action_plan:
- step: 1
action: "Inform user: \"No existing ConPort database found at `ACTUAL_WORKSPACE_ID + \"/context_portal/context.db\"`.\""
- step: 2
action: "Use `ask_followup_question`."
tool_to_use: "ask_followup_question"
parameters:
question: "Would you like to initialize a new ConPort database for this workspace? The database will be created automatically when ConPort tools are first used."
suggestions:
- "Yes, initialize a new ConPort database."
- "No, do not use ConPort for this session."
- step: 3
description: "Process user response."
conditions:
- if_user_response_is: "Yes, initialize a new ConPort database."
actions:
- "Inform user: \"Okay, a new ConPort database will be created.\""
- description: "Attempt to bootstrap Product Context from projectBrief.md (this happens only on new setup)."
thinking_preamble: |
sub_steps:
- "Invoke `list_files` with `path: ACTUAL_WORKSPACE_ID` (non-recursive, just to check root)."
- description: "Analyze `list_files` result for 'projectBrief.md'."
conditions:
- if: "'projectBrief.md' is found in the listing"
actions:
- "Invoke `read_file` for `ACTUAL_WORKSPACE_ID + \"/projectBrief.md\"`."
- action: "Use `ask_followup_question`."
tool_to_use: "ask_followup_question"
parameters:
question: "Found projectBrief.md in your workspace. As we're setting up ConPort for the first time, would you like to import its content into the Product Context?"
suggestions:
- "Yes, import its content now."
- "No, skip importing it for now."
- description: "Process user response to import projectBrief.md."
conditions:
- if_user_response_is: "Yes, import its content now."
actions:
- "(No need to `get_product_context` as DB is new and empty)"
- "Prepare `content` for `update_product_context`. For example: `{\"initial_product_brief\": \"[content from projectBrief.md]\"}`."
- "Invoke `update_product_context` with the prepared content."
- "Inform user of the import result (success or failure)."
- else: "'projectBrief.md' NOT found"
actions:
- action: "Use `ask_followup_question`."
tool_to_use: "ask_followup_question"
parameters:
question: "`projectBrief.md` was not found in the workspace root. Would you like to define the initial Product Context manually now?"
suggestions:
- "Define Product Context manually."
- "Skip for now."
- "(If \"Define manually\", guide user through `update_product_context`)."
- "Proceed to 'load_existing_conport_context' sequence (which will now load the potentially bootstrapped product context and other empty contexts)."
- if_user_response_is: "No, do not use ConPort for this session."
action: "Proceed to `if_conport_unavailable_or_init_failed` (with a message indicating user chose not to initialize)."
if_conport_unavailable_or_init_failed:
thinking_preamble: |
agent_action: "Inform user: \"ConPort memory will not be used for this session. Status: [CONPORT_INACTIVE].\""
general:
status_prefix: "Begin EVERY response with either '[CONPORT_ACTIVE]' or '[CONPORT_INACTIVE]'."
proactive_logging_cue: "Remember to proactively identify opportunities to log or update ConPort based on the conversation (e.g., if user outlines a new plan, consider logging decisions or progress). Confirm with the user before logging."
proactive_error_handling: "When encountering errors (e.g., tool failures, unexpected output), proactively log the error details using `log_custom_data` (category: 'ErrorLogs', key: 'timestamp_error_summary') and consider updating `active_context` with `open_issues` if it's a persistent problem. Prioritize using ConPort's `get_item_history` or `get_recent_activity_summary` to diagnose issues if they relate to past context changes."
semantic_search_emphasis: "For complex or nuanced queries, especially when direct keyword search (`search_decisions_fts`, `search_custom_data_value_fts`) might be insufficient, prioritize using `semantic_search_conport` to leverage conceptual understanding and retrieve more relevant context. Explain to the user why semantic search is being used."
conport_updates:
frequency: "UPDATE CONPORT THROUGHOUT THE CHAT SESSION, WHEN SIGNIFICANT CHANGES OCCUR, OR WHEN EXPLICITLY REQUESTED."
workspace_id_note: "All ConPort tool calls require the `workspace_id`."
tools:
- name: get_product_context
trigger: "To understand the overall project goals, features, or architecture at any time."
action_description: |
# Agent Action: Invoke `get_product_context` (`{"workspace_id": "..."}`). Result is a direct dictionary.
- name: update_product_context
trigger: "When the high-level project description, goals, features, or overall architecture changes significantly, as confirmed by the user."
action_description: |
<thinking>
- Product context needs updating.
- Step 1: (Optional but recommended if unsure of current state) Invoke `get_product_context`.
- Step 2: Prepare the `content` (for full overwrite) or `patch_content` (partial update) dictionary.
- To remove a key using `patch_content`, set its value to the special string sentinel `\"__DELETE__\"`.
- Confirm changes with the user.
</thinking>
# Agent Action: Invoke `update_product_context` (`{"workspace_id": "...", "content": {...}}` or `{"workspace_id": "...", "patch_content": {"key_to_update": "new_value", "key_to_delete": "__DELETE__"}}`).
- name: get_active_context
trigger: "To understand the current task focus, immediate goals, or session-specific context."
action_description: |
# Agent Action: Invoke `get_active_context` (`{"workspace_id": "..."}`). Result is a direct dictionary.
- name: update_active_context
trigger: "When the current focus of work changes, new questions arise, or session-specific context needs updating (e.g., `current_focus`, `open_issues`), as confirmed by the user."
action_description: |
<thinking>
- Active context needs updating.
- Step 1: (Optional) Invoke `get_active_context` to retrieve the current state.
- Step 2: Prepare `content` (for full overwrite) or `patch_content` (for partial update).
- Common fields to update include `current_focus`, `open_issues`, and other session-specific data.
- To remove a key using `patch_content`, set its value to the special string sentinel `\"__DELETE__\"`.
- Confirm changes with the user.
</thinking>
# Agent Action: Invoke `update_active_context` (`{"workspace_id": "...", "content": {...}}` or `{"workspace_id": "...", "patch_content": {"current_focus": "new_focus", "open_issues": ["issue1", "issue2"], "key_to_delete": "__DELETE__"}}`).
- name: log_decision
trigger: "When a significant architectural or implementation decision is made and confirmed by the user."
action_description: |
# Agent Action: Invoke `log_decision` (`{"workspace_id": "...", "summary": "...", "rationale": "...", "tags": ["optional_tag"]}}`).
- name: get_decisions
trigger: "To retrieve a list of past decisions, e.g., to review history or find a specific decision."
action_description: |
# Agent Action: Invoke `get_decisions` (`{"workspace_id": "...", "limit": N, "tags_filter_include_all": ["tag1"], "tags_filter_include_any": ["tag2"]}}`). Explain optional filters.
- name: search_decisions_fts
trigger: "When searching for decisions by keywords in summary, rationale, details, or tags, and basic `get_decisions` is insufficient."
action_description: |
# Agent Action: Invoke `search_decisions_fts` (`{"workspace_id": "...", "query_term": "search keywords", "limit": N}}`).
- name: delete_decision_by_id
trigger: "When user explicitly confirms deletion of a specific decision by its ID."
action_description: |
# Agent Action: Invoke `delete_decision_by_id` (`{"workspace_id": "...", "decision_id": ID}}`). Emphasize prior confirmation.
- name: log_progress
trigger: "When a task begins, its status changes (e.g., TODO, IN_PROGRESS, DONE), or it's completed. Also when a new sub-task is defined."
action_description: |
# Agent Action: Invoke `log_progress` (`{"workspace_id": "...", "description": "...", "status": "...", "linked_item_type": "...", "linked_item_id": "..."}}`). Note: 'summary' was changed to 'description' for log_progress.
- name: get_progress
trigger: "To review current task statuses, find pending tasks, or check history of progress."
action_description: |
# Agent Action: Invoke `get_progress` (`{"workspace_id": "...", "status_filter": "...", "parent_id_filter": ID, "limit": N}}`).
- name: update_progress
trigger: "Updates an existing progress entry."
action_description: |
# Agent Action: Invoke `update_progress` (`{"workspace_id": "...", "progress_id": ID, "status": "...", "description": "...", "parent_id": ID}}`).
- name: delete_progress_by_id
trigger: "Deletes a progress entry by its ID."
action_description: |
# Agent Action: Invoke `delete_progress_by_id` (`{"workspace_id": "...", "progress_id": ID}}`).
- name: log_system_pattern
trigger: "When new architectural patterns are introduced, or existing ones are modified, as confirmed by the user."
action_description: |
# Agent Action: Invoke `log_system_pattern` (`{"workspace_id": "...", "name": "...", "description": "...", "tags": ["optional_tag"]}}`).
- name: get_system_patterns
trigger: "To retrieve a list of defined system patterns."
action_description: |
# Agent Action: Invoke `get_system_patterns` (`{"workspace_id": "...", "tags_filter_include_all": ["tag1"], "limit": N}}`). Note: limit was not in original example, added for consistency.
- name: delete_system_pattern_by_id
trigger: "When user explicitly confirms deletion of a specific system pattern by its ID."
action_description: |
# Agent Action: Invoke `delete_system_pattern_by_id` (`{"workspace_id": "...", "pattern_id": ID}}`). Emphasize prior confirmation.
- name: log_custom_data
trigger: "To store any other type of structured or unstructured project-related information not covered by other tools (e.g., glossary terms, technical specs, meeting notes), as confirmed by the user."
action_description: |
# Agent Action: Invoke `log_custom_data` (`{"workspace_id": "...", "category": "...", "key": "...", "value": {... or "string"}}`). Note: 'metadata' field is not part of log_custom_data args.
- name: get_custom_data
trigger: "To retrieve specific custom data by category and key."
action_description: |
# Agent Action: Invoke `get_custom_data` (`{"workspace_id": "...", "category": "...", "key": "..."}}`).
- name: delete_custom_data
trigger: "When user explicitly confirms deletion of specific custom data by category and key."
action_description: |
# Agent Action: Invoke `delete_custom_data` (`{"workspace_id": "...", "category": "...", "key": "..."}}`). Emphasize prior confirmation.
- name: search_custom_data_value_fts
trigger: "When searching for specific terms within any custom data values, categories, or keys."
action_description: |
# Agent Action: Invoke `search_custom_data_value_fts` (`{"workspace_id": "...", "query_term": "...", "category_filter": "...", "limit": N}}`).
- name: search_project_glossary_fts
trigger: "When specifically searching for terms within the 'ProjectGlossary' custom data category."
action_description: |
# Agent Action: Invoke `search_project_glossary_fts` (`{"workspace_id": "...", "query_term": "...", "limit": N}}`).
- name: semantic_search_conport
trigger: "When a natural language query requires conceptual understanding beyond keyword matching, or when direct keyword searches are insufficient."
action_description: |
# Agent Action: Invoke `semantic_search_conport` (`{"workspace_id": "...", "query_text": "...", "top_k": N, "filter_item_types": ["decision", "custom_data"]}}`). Explain filters.
- name: link_conport_items
trigger: "When a meaningful relationship is identified and confirmed between two existing ConPort items (e.g., a decision is implemented by a system pattern, a progress item tracks a decision)."
action_description: |
<thinking>
- Need to link two items. Identify source type/ID, target type/ID, and relationship.
- Common relationship_types: 'implements', 'related_to', 'tracks', 'blocks', 'clarifies', 'depends_on'. Propose a suitable one or ask user.
</thinking>
# Agent Action: Invoke `link_conport_items` (`{"workspace_id":"...", "source_item_type":"...", "source_item_id":"...", "target_item_type":"...", "target_item_id":"...", "relationship_type":"...", "description":"Optional notes"}`).
- name: get_linked_items
trigger: "To understand the relationships of a specific ConPort item, or to explore the knowledge graph around an item."
action_description: |
# Agent Action: Invoke `get_linked_items` (`{"workspace_id":"...", "item_type":"...", "item_id":"...", "relationship_type_filter":"...", "linked_item_type_filter":"...", "limit":N}`).
- name: get_item_history
trigger: "When needing to review past versions of Product Context or Active Context, or to see when specific changes were made."
action_description: |
# Agent Action: Invoke `get_item_history` (`{"workspace_id":"...", "item_type":"product_context" or "active_context", "limit":N, "version":V, "before_timestamp":"ISO_DATETIME", "after_timestamp":"ISO_DATETIME"}`).
- name: batch_log_items
trigger: "When the user provides a list of multiple items of the SAME type (e.g., several decisions, multiple new glossary terms) to be logged at once."
action_description: |
<thinking>
- User provided multiple items. Verify they are of the same loggable type.
- Construct the `items` list, where each element is a dictionary of arguments for the single-item log tool (e.g., for `log_decision`).
</thinking>
# Agent Action: Invoke `batch_log_items` (`{"workspace_id":"...", "item_type":"decision", "items": [{"summary":"...", "rationale":"..."}, {"summary":"..."}] }`).
- name: get_recent_activity_summary
trigger: "At the start of a new session to catch up, or when the user asks for a summary of recent project activities."
action_description: |
# Agent Action: Invoke `get_recent_activity_summary` (`{"workspace_id":"...", "hours_ago":H, "since_timestamp":"ISO_DATETIME", "limit_per_type":N}`). Explain default if no time args.
- name: get_conport_schema
trigger: "If there's uncertainty about available ConPort tools or their arguments during a session (internal LLM check), or if an advanced user specifically asks for the server's tool schema."
action_description: |
# Agent Action: Invoke `get_conport_schema` (`{"workspace_id":"..."}`). Primarily for internal LLM reference or direct user request.
- name: export_conport_to_markdown
trigger: "When the user requests to export the current ConPort data to markdown files (e.g., for backup, sharing, or version control)."
action_description: |
# Agent Action: Invoke `export_conport_to_markdown` (`{"workspace_id":"...", "output_path":"optional/relative/path"}`). Explain default output path if not provided.
- name: import_markdown_to_conport
trigger: "When the user requests to import ConPort data from a directory of markdown files previously exported by this system."
action_description: |
# Agent Action: Invoke `import_markdown_to_conport` (`{"workspace_id":"...", "input_path":"optional/relative/path"}`). Explain default input path. Warn about potential overwrites or merges if data already exists.
- name: reconfigure_core_guidance
type: guidance
product_active_context: "The internal JSON structure of 'Product Context' and 'Active Context' (the `content` field) is flexible. Work with the user to define and evolve this structure via `update_product_context` and `update_active_context`. The server stores this `content` as a JSON blob."
decisions_progress_patterns: "The fundamental fields for Decisions, Progress, and System Patterns are fixed by ConPort's tools. For significantly different structures or additional fields, guide the user to create a new custom context category using `log_custom_data` (e.g., category: 'project_milestones_detailed')."
conport_sync_routine:
trigger: "^(Sync ConPort|ConPort Sync)$"
user_acknowledgement_text: "[CONPORT_SYNCING]"
instructions:
- "Halt Current Task: Stop current activity."
- "Acknowledge Command: Send `[CONPORT_SYNCING]` to the user."
- "Review Chat History: Analyze the complete current chat session for new information, decisions, progress, context changes, clarifications, and potential new relationships between items."
core_update_process:
thinking_preamble: |
- Synchronize ConPort with information from the current chat session.
- Use appropriate ConPort tools based on identified changes.
- For `update_product_context` and `update_active_context`, first fetch current content, then merge/update (potentially using `patch_content`), then call the update tool with the *complete new content object* or the patch.
- All tool calls require the `workspace_id`.
agent_action_plan_illustrative:
- "Log new decisions (use `log_decision`)."
- "Log task progress/status changes (use `log_progress`)."
- "Update existing progress entries (use `update_progress`)."
- "Delete progress entries (use `delete_progress_by_id`)."
- "Log new system patterns (use `log_system_pattern`)."
- "Update Active Context (use `get_active_context` then `update_active_context` with full or patch)."
- "Update Product Context if significant changes (use `get_product_context` then `update_product_context` with full or patch)."
- "Log new custom context, including ProjectGlossary terms (use `log_custom_data`)."
- "Identify and log new relationships between items (use `link_conport_items`)."
- "If many items of the same type were discussed, consider `batch_log_items`."
- "After updates, consider a brief `get_recent_activity_summary` to confirm and refresh understanding."
post_sync_actions:
- "Inform user: ConPort synchronized with session info."
- "Resume previous task or await new instructions."
dynamic_context_retrieval_for_rag:
description: |
Guidance for dynamically retrieving and assembling context from ConPort to answer user queries or perform tasks,
enhancing Retrieval Augmented Generation (RAG) capabilities.
trigger: "When the AI needs to answer a specific question, perform a task requiring detailed project knowledge, or generate content based on ConPort data."
goal: "To construct a concise, highly relevant context set for the LLM, improving the accuracy and relevance of its responses."
steps:
- step: 1
action: "Analyze User Query/Task"
details: "Deconstruct the user's request to identify key entities, concepts, keywords, and the specific type of information needed from ConPort."
- step: 2
action: "Prioritized Retrieval Strategy"
details: |
Based on the analysis, select the most appropriate ConPort tools:
- **Targeted FTS:** Use `search_decisions_fts`, `search_custom_data_value_fts`, `search_project_glossary_fts` for keyword-based searches if specific terms are evident.
- **Specific Item Retrieval:** Use `get_custom_data` (if category/key known), `get_decisions` (by ID or for recent items), `get_system_patterns`, `get_progress` if the query points to specific item types or IDs.
- **(Future):** Prioritize semantic search tools once available for conceptual queries.
- **Broad Context (Fallback):** Use `get_product_context` or `get_active_context` as a fallback if targeted retrieval yields little, but be mindful of their size.
- step: 3
action: "Retrieve Initial Set"
details: "Execute the chosen tool(s) to retrieve an initial, small set (e.g., top 3-5) of the most relevant items or data snippets."
- step: 4
action: "Contextual Expansion (Optional)"
details: "For the most promising items from Step 3, consider using `get_linked_items` to fetch directly related items (1-hop). This can provide crucial context or disambiguation. Use judiciously to avoid excessive data."
- step: 5
action: "Synthesize and Filter"
details: |
Review the retrieved information (initial set + expanded context).
- **Filter:** Discard irrelevant items or parts of items.
- **Synthesize/Summarize:** If multiple relevant pieces of information are found, synthesize them into a concise summary that directly addresses the query/task. Extract only the most pertinent sentences or facts.
- step: 6
action: "Assemble Prompt Context"
details: |
Construct the context portion of the LLM prompt using the filtered and synthesized information.
- **Clarity:** Clearly delineate this retrieved context from the user's query or other parts of the prompt.
- **Attribution (Optional but Recommended):** If possible, briefly note the source of the information (e.g., "From Decision D-42:", "According to System Pattern SP-5:").
- **Brevity:** Strive for relevance and conciseness. Avoid including large, unprocessed chunks of data unless absolutely necessary and directly requested.
general_principles:
- "Prefer targeted retrieval over broad context dumps."
- "Iterate if initial retrieval is insufficient: try different keywords or tools."
- "Balance context richness with prompt token limits."
proactive_knowledge_graph_linking:
description: |
Guidance for the AI to proactively identify and suggest the creation of links between ConPort items,
enriching the project's knowledge graph based on conversational context.
trigger: "During ongoing conversation, when the AI observes potential relationships (e.g., causal, implementational, clarifying) between two or more discussed ConPort items or concepts that are likely represented as ConPort items."
goal: "To actively build and maintain a rich, interconnected knowledge graph within ConPort by capturing relationships that might otherwise be missed."
steps:
- step: 1
action: "Monitor Conversational Context"
details: "Continuously analyze the user's statements and the flow of discussion for mentions of ConPort items (explicitly by ID, or implicitly by well-known names/summaries) and the relationships being described or implied between them."
- step: 2
action: "Identify Potential Links"
details: |
Look for patterns such as:
- User states "Decision X led to us doing Y (which is Progress item P-3)."
- User discusses how System Pattern SP-2 helps address a concern noted in Decision D-5.
- User outlines a task (Progress P-10) that implements a specific feature detailed in a `custom_data` spec (CD-Spec-FeatureX).
- step: 3
action: "Formulate and Propose Link Suggestion"
details: |
If a potential link is identified:
- Clearly state the items involved (e.g., "Decision D-5", "System Pattern SP-2").
- Describe the perceived relationship (e.g., "It seems SP-2 addresses a concern in D-5.").
- Propose creating a link using `ask_followup_question`.
- Example Question: "I noticed we're discussing Decision D-5 and System Pattern SP-2. It sounds like SP-2 might 'address_concern_in' D-5. Would you like me to create this link in ConPort? You can also suggest a different relationship type."
- Suggested Answers:
- "Yes, link them with 'addresses_concern_in'."
- "Yes, but use relationship type: [user types here]."
- "No, don't link them now."
- Offer common relationship types as examples if needed: 'implements', 'clarifies', 'related_to', 'depends_on', 'blocks', 'resolves', 'derived_from'.
- step: 4
action: "Gather Details and Execute Linking"
details: |
If the user confirms:
- Ensure you have the correct source item type, source item ID, target item type, target item ID, and the agreed-upon relationship type.
- Ask for an optional brief description for the link if the relationship isn't obvious.
- Invoke the `link_conport_items` tool.
- step: 5
action: "Confirm Outcome"
details: "Inform the user of the success or failure of the `link_conport_items` tool call."
general_principles:
- "Be helpful, not intrusive. If the user declines a suggestion, accept and move on."
- "Prioritize clear, strong relationships over tenuous ones."
- "This strategy complements the general `proactive_logging_cue` by providing specific guidance for link creation."

View File

@@ -1,35 +1 @@
customModes: customModes: []
- slug: project-research
name: 🔍 Project Research
roleDefinition: |
You are a detailed-oriented research assistant specializing in examining and understanding codebases. Your primary responsibility is to analyze the file structure, content, and dependencies of a given project to provide comprehensive context relevant to specific user queries.
whenToUse: |
Use this mode when you need to thoroughly investigate and understand a codebase structure, analyze project architecture, or gather comprehensive context about existing implementations. Ideal for onboarding to new projects, understanding complex codebases, or researching how specific features are implemented across the project.
description: Investigate and analyze codebase structure
groups:
- read
source: project
customInstructions: |
Your role is to deeply investigate and summarize the structure and implementation details of the project codebase. To achieve this effectively, you must:
1. Start by carefully examining the file structure of the entire project, with a particular emphasis on files located within the "docs" folder. These files typically contain crucial context, architectural explanations, and usage guidelines.
2. When given a specific query, systematically identify and gather all relevant context from:
- Documentation files in the "docs" folder that provide background information, specifications, or architectural insights.
- Relevant type definitions and interfaces, explicitly citing their exact location (file path and line number) within the source code.
- Implementations directly related to the query, clearly noting their file locations and providing concise yet comprehensive summaries of how they function.
- Important dependencies, libraries, or modules involved in the implementation, including their usage context and significance to the query.
3. Deliver a structured, detailed report that clearly outlines:
- An overview of relevant documentation insights.
- Specific type definitions and their exact locations.
- Relevant implementations, including file paths, functions or methods involved, and a brief explanation of their roles.
- Critical dependencies and their roles in relation to the query.
4. Always cite precise file paths, function names, and line numbers to enhance clarity and ease of navigation.
5. Organize your findings in logical sections, making it straightforward for the user to understand the project's structure and implementation status relevant to their request.
6. Ensure your response directly addresses the user's query and helps them fully grasp the relevant aspects of the project's current state.
These specific instructions supersede any conflicting general instructions you might otherwise follow. Your detailed report should enable effective decision-making and next steps within the overall workflow.

View File

@@ -1,95 +0,0 @@
# Backend Structure Plan
## Apps Overview
### 1. `apps.core`
- **Responsibility**: Base classes, shared utilities, history tracking.
- **Existing**: `SluggedModel`, `TrackedModel`.
- **Versioning Strategy (Section 15)**:
- All core entities (`Park`, `Ride`, `Company`) must utilize `django-pghistory` or `apps.core` tracking to support:
- **Edit History**: Chronological list of changes with `reason`, `user`, and `diff`.
- **Timeline**: Major events (renames, relocations).
- **Rollback**: Ability to restore previous versions via the Moderation Queue.
### 2. `apps.accounts`
- **Responsibility**: User authentication, profiles, and settings.
- **Existing**: `User`, `UserProfile` (bio, location, home park).
- **Required Additions (Section 9)**:
- **UserDeletionRequest**: Support 7-day grace period for account deletion.
- **Privacy Settings**: Fields for `is_profile_public`, `show_location`, `show_email` on `UserProfile`.
- **Data Export**: Serializers/Utilities to dump all user data (Reviews, Credits, Lists) to JSON.
### 3. `apps.parks`
- **Responsibility**: Park management.
- **Models**: `Park`, `ParkArea`.
- **Relationships**:
- `operator`: FK to `apps.companies.Company` (Type: Operator).
- `property_owner`: FK to `apps.companies.Company` (Type: Owner).
### 4. `apps.rides`
- **Responsibility**: Ride data, Coasters, and Credits.
- **Models**:
- `Ride`: Core entity (Status FSM: Operating, SBNO, Closed, etc.).
- `RideModel`: Defines the "Type" of ride (e.g., B&M Hyper V2).
- `Manufacturer`: FK to `apps.companies.Company`.
- `Designer`: FK to `apps.companies.Company`.
- **Ride Credits (Section 10)**:
- **Model**: `RideCredit` (Through-Model: `User` <-> `Ride`).
- **Fields**:
- `count` (Integer): Total times ridden.
- `rating` (Float): Personal rating (distinct from public Review).
- `first_ridden_at` (Date): First time experiencing the ride.
- `notes` (Text): Private personal notes.
- **Constraints**: `Unique(user, ride)` - A user has one credit entry per ride.
### 5. `apps.companies`
- **Responsibility**: Management of Industry Entities (Section 4).
- **Models**:
- `Company`: Single model with `type` choices or Polymorphic.
- **Types**: `Manufacturer`, `Designer`, `Operator`, `PropertyOwner`.
- **Features**: Detailed pages, hover cards, listing by type.
### 6. `apps.moderation` (The Sacred Submission Pipeline)
- **Responsibility**: Centralized Content Submission System (Section 14, 16).
- **Concept**: **Live Data** (Approve) vs **Submission Data** (Pending).
- **Models**:
- `Submission`:
- `submitter`: FK to User.
- `content_type`: Target Model (Park, Ride, etc.).
- `object_id`: Target ID (Null for Creation).
- `data`: **JSONField** storing the proposed state.
- `status`: State Machine (`Pending` -> `Claimed` -> `Approved` | `Rejected` | `ChangesRequested`).
- `moderator`: FK to User (Claimaint).
- `moderator_note`: Reason for rejection/feedback.
- `Report`: User flags on content.
- **Workflow**:
1. User submits form -> `Submission` created (Status: Pending).
2. Moderator Claims -> Status: Claimed.
3. Approves -> Applies `data` to `Live Model` -> Saves Version -> Status: Approved.
### 7. `apps.media`
- **Responsibility**: Media Management (Section 13).
- **Models**:
- `Photo`: GenericFK. Fields: `image`, `caption`, `user`, `status` (Moderation).
- **Banner/Card**: Entities should link to a "Primary Photo" or store a cached image field.
### 8. `apps.reviews`
- **Responsibility**: Public Reviews & Ratings (Section 12).
- **Models**:
- `Review`: GenericFK (Park, Ride).
- **Fields**: `rating` (1-5, 0.5 steps), `title`, `body`, `helpful_votes`.
- **Logic**: Aggregates (Avg Rating, Count) calculation for Entity caches.
### 9. `apps.lists`
- **Responsibility**: User Lists & Rankings (Section 11).
- **Models**:
- `UserList`: Title, Description, Type (Park/Ride/Coaster/Mixed), Privacy (Public/Private).
- `UserListItem`: FK to List, GenericFK to Item, Order, Notes.
### 10. `apps.blog`
- **Responsibility**: News & Updates.
- **Models**: `Post`, `Tag`.
### 11. `apps.support`
- **Responsibility**: Human interaction.
- **Models**: `Ticket` (Contact Form).

View File

@@ -1,503 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Phase 7] - 2025-12-24
### Testing
#### Added
- **Comprehensive Test Coverage Improvements**
- Added 30+ new test files across all apps
- API endpoint tests with authentication, error handling, pagination, and response format validation
- E2E tests for FSM workflows (parks, rides, moderation)
- Integration tests for FSM transition workflows
- Unit tests for managers, serializers, and services
- Accessibility tests for WCAG 2.1 AA compliance
- Form validation tests for all major forms
#### Test Files Added
- `backend/tests/api/` - API endpoint tests (8 files)
- `backend/tests/e2e/` - End-to-end FSM workflow tests (3 files)
- `backend/tests/integration/` - Integration tests (1 file)
- `backend/tests/managers/` - Manager tests (2 files)
- `backend/tests/serializers/` - Serializer tests (3 files)
- `backend/tests/services/` - Service layer tests (3 files)
- `backend/tests/forms/` - Form validation tests (5 files)
- `backend/tests/accessibility/` - WCAG compliance tests (1 file)
- `backend/apps/*/tests/` - App-specific tests (7 files)
#### Coverage Improvements
- Increased test coverage for models, views, and services
- Added tests for edge cases and error conditions
- Improved FSM transition testing with permission checks
- Added query optimization tests
### Technical Details
This phase focused on achieving comprehensive test coverage to ensure code quality and prevent regressions. Tests cover:
- All API endpoints with various authentication scenarios
- FSM state transitions with permission validation
- Form validation logic with edge cases
- Manager methods and custom QuerySets
- Service layer business logic
- Accessibility compliance for interactive components
**Testing Infrastructure**:
- pytest with Django plugin
- Factory Boy for test data generation
- Coverage.py for coverage tracking
- Playwright for E2E tests
### Files Modified
- `backend/pyproject.toml` - Updated test dependencies and coverage configuration
- `backend/tests/conftest.py` - Enhanced test fixtures and utilities
---
## [Phase 6] - 2025-12-24
### Forms & Validation
#### Enhanced
- **Form Validation Coverage**
- Added custom `clean_*` methods for field-level validation
- Improved error messages for better user experience
- Enhanced form widgets (date pickers, rich text editors)
- Standardized ModelForm field definitions
#### Forms Enhanced
- `backend/apps/parks/forms/base.py` - Park creation/update forms
- `backend/apps/parks/forms/review_forms.py` - Park review forms
- `backend/apps/parks/forms/area_forms.py` - Park area forms
- `backend/apps/rides/forms/base.py` - Ride creation/update forms
- `backend/apps/rides/forms/review_forms.py` - Ride review forms
- `backend/apps/rides/forms/company_forms.py` - Company forms
- `backend/apps/rides/forms/search.py` - Ride search forms
- `backend/apps/core/forms/search.py` - Core search forms
- `backend/apps/core/forms/htmx_forms.py` - HTMX-specific form patterns
#### Tests Added
- `backend/tests/forms/test_area_forms.py` - Area form validation tests
- `backend/tests/forms/test_park_forms.py` - Park form validation tests
- `backend/tests/forms/test_ride_forms.py` - Ride form validation tests
- `backend/tests/forms/test_review_forms.py` - Review form validation tests
- `backend/tests/forms/test_company_forms.py` - Company form validation tests
### Technical Details
This phase improved form validation coverage across the application:
1. **Field-Level Validation**: Custom `clean_*` methods for complex validation logic
2. **User-Friendly Errors**: Clear, actionable error messages
3. **Widget Improvements**: Better UX with appropriate input widgets
4. **HTMX Integration**: Forms work seamlessly with HTMX partial updates
5. **Test Coverage**: Comprehensive tests for all validation scenarios
**Validation Patterns**:
- Date range validation (opening/closing dates)
- Coordinate validation (latitude/longitude bounds)
- Slug uniqueness validation
- Cross-field validation (e.g., closing date must be after opening date)
- File upload validation (size, type, dimensions)
---
## [Phase 5] - 2025-12-24
### Admin Interface
#### Enhanced
- **Django Admin Completeness**
- Added comprehensive `list_display` with key fields
- Implemented `search_fields` for text search
- Added `list_filter` for status, category, and date filtering
- Organized detail views with `fieldsets`
- Added `readonly_fields` for computed properties and timestamps
- Implemented custom admin actions (bulk approve, bulk reject, etc.)
#### Admin Files Enhanced
- `backend/apps/parks/admin.py` - Park, Area, Company, Review admin
- `backend/apps/rides/admin.py` - Ride, Manufacturer, Review admin
- `backend/apps/accounts/admin.py` - User, Profile admin
- `backend/apps/moderation/admin.py` - Submission, Report admin
- `backend/apps/core/admin.py` - Base admin classes and mixins
#### Custom Admin Actions
- Bulk approve/reject for moderation workflows
- Bulk status changes for parks and rides
- Export to CSV for reporting
- Cache invalidation for modified entities
### Technical Details
This phase completed the Django admin interface to provide a powerful content management system:
1. **List Views**: Optimized with select_related/prefetch_related
2. **Search**: Full-text search on name, description, and location fields
3. **Filters**: Status, category, date range, and custom filters
4. **Detail Views**: Organized with logical fieldsets
5. **Actions**: Bulk operations for efficient moderation
**Admin Patterns**:
- Inherited from `BaseModelAdmin` for consistency
- Used `readonly_fields` for computed properties
- Implemented `get_queryset()` optimization
- Added inline admin for related objects
---
## [Phase 4] - 2025-12-24
### Models & Database
#### Enhanced
- **Model Completeness & Consistency**
- Added/improved `__str__` methods for human-readable representations
- Standardized `Meta` classes with `ordering`, `verbose_name`, `verbose_name_plural`
- Added comprehensive `help_text` on all fields
- Verified database indexes on foreign keys and frequently queried fields
- Added model constraints (CheckConstraint, UniqueConstraint)
#### Model Files Enhanced
- `backend/apps/parks/models/parks.py` - Park model
- `backend/apps/parks/models/companies.py` - Company, Operator models
- `backend/apps/parks/models/areas.py` - ParkArea model
- `backend/apps/parks/models/media.py` - ParkPhoto model
- `backend/apps/parks/models/reviews.py` - ParkReview model
- `backend/apps/parks/models/location.py` - ParkLocation model
- `backend/apps/rides/models/rides.py` - Ride model
- `backend/apps/rides/models/company.py` - Manufacturer, Designer models
- `backend/apps/rides/models/rankings.py` - RideRanking model
- `backend/apps/rides/models/media.py` - RidePhoto model
- `backend/apps/rides/models/reviews.py` - RideReview model
- `backend/apps/rides/models/location.py` - RideLocation model
- `backend/apps/accounts/models.py` - User, Profile models
- `backend/apps/moderation/models.py` - Submission, Report models
- `backend/apps/core/models.py` - Base models and mixins
#### Database Improvements
- Added indexes for performance optimization
- Implemented constraints for data integrity
- Standardized field naming conventions
- Improved model documentation
### Technical Details
This phase improved model quality and consistency:
1. **String Representations**: All models have meaningful `__str__` methods
2. **Metadata**: Complete Meta classes with ordering and verbose names
3. **Field Documentation**: Every field has descriptive help_text
4. **Database Optimization**: Proper indexes on foreign keys and search fields
5. **Data Integrity**: Constraints enforce business rules at database level
**Model Patterns**:
- Used `TextChoices` for status and category fields
- Implemented `db_index=True` on frequently queried fields
- Added `CheckConstraint` for value ranges (e.g., ratings 1-5)
- Used `UniqueConstraint` for compound uniqueness
---
## [Phase 3] - 2025-12-24
### Logging & Observability
#### Standardized
- **Logging Pattern Consistency**
- Added `logger = logging.getLogger(__name__)` to all view, service, and middleware files
- Implemented centralized logging utilities from `apps.core.logging`
- Standardized log levels (debug, info, warning, error)
- Added structured logging with context
#### Files Enhanced with Logging
- `backend/apps/parks/views.py` - Park views
- `backend/apps/rides/views.py` - Ride views
- `backend/apps/accounts/views.py` - Account views
- `backend/apps/moderation/views.py` - Moderation views
- `backend/apps/accounts/services.py` - Account services
- `backend/apps/parks/signals.py` - Park signals
- `backend/apps/rides/signals.py` - Ride signals
- `backend/apps/moderation/signals.py` - Moderation signals
- `backend/apps/rides/tasks.py` - Celery tasks
- `backend/apps/parks/apps.py` - App configuration
- `backend/apps/rides/apps.py` - App configuration
- `backend/apps/moderation/apps.py` - App configuration
#### Logging Utilities
- `log_exception()` - Exception logging with full context
- `log_business_event()` - Business operation logging (FSM transitions, user actions)
- `log_security_event()` - Security event logging (authentication, authorization)
### Technical Details
This phase standardized logging across the application for better observability:
1. **Consistent Logger Initialization**: Every module uses `logging.getLogger(__name__)`
2. **Centralized Utilities**: Structured logging functions in `apps.core.logging`
3. **Contextual Logging**: All logs include relevant context (user, request, operation)
4. **Security Logging**: Dedicated logging for security events
5. **Performance Logging**: Query performance and cache hit/miss tracking
**Logging Patterns**:
- Exception handlers use `log_exception()` with context
- FSM transitions use `log_business_event()`
- Authentication events use `log_security_event()`
- Never log sensitive data (passwords, tokens, PII)
**Benefits**:
- Easier debugging with consistent log format
- Better production monitoring with structured logs
- Security audit trail for compliance
- Performance insights from cache and query logs
---
## [Phase 15] - 2025-12-23
### Documentation
#### Added
- **Future Work Documentation**
- Created `docs/FUTURE_WORK.md` to track deferred features
- Documented 11 TODO items with detailed implementation specifications
- Added priority levels (P0-P3) and effort estimates
- Included code examples and architectural guidance
#### Implemented
- **Cache Statistics Tracking (THRILLWIKI-109)**
- Added `get_cache_statistics()` method to `CacheMonitor` class
- Implemented real-time cache hit/miss tracking in `MapStatsAPIView`
- Returns Redis statistics when available, with graceful fallback
- Removed placeholder TODO comments
- **Photo Upload Counting (THRILLWIKI-105)**
- Implemented photo counting in user statistics endpoint
- Queries `ParkPhoto` and `RidePhoto` models for accurate counts
- Removed placeholder TODO comment
- **Admin Permission Checks (THRILLWIKI-103)**
- Verified existing admin permission checks in map cache endpoints
- Removed outdated TODO comments (checks were already implemented)
#### Enhanced
- **TODO Comment Cleanup**
- Updated all TODO comments to reference `FUTURE_WORK.md`
- Added THRILLWIKI issue numbers for traceability
- Improved inline documentation with implementation context
### Technical Details
This phase focused on addressing technical debt by:
1. Documenting deferred features with actionable specifications
2. Implementing quick wins that improve observability
3. Cleaning up TODO comments to reduce confusion
**Features Documented for Future Implementation**:
- Map clustering algorithm (THRILLWIKI-106)
- Nearby locations feature (THRILLWIKI-107)
- Search relevance scoring (THRILLWIKI-108)
- Full user statistics tracking (THRILLWIKI-104)
- Geocoding service integration (THRILLWIKI-101)
- ClamAV malware scanning (THRILLWIKI-110)
- Sample data creation command (THRILLWIKI-111)
**Quick Wins Implemented**:
- Cache statistics tracking for monitoring
- Photo upload counting for user profiles
- Verified admin permission checks
### Files Modified
- `backend/apps/api/v1/maps/views.py` - Cache statistics, updated TODO comments
- `backend/apps/api/v1/accounts/views.py` - Photo counting, updated TODO comments
- `backend/apps/api/v1/serializers/maps.py` - Updated TODO comments
- `backend/apps/core/services/location_adapters.py` - Updated TODO comments
- `backend/apps/core/services/enhanced_cache_service.py` - Added `get_cache_statistics()` method
- `backend/apps/core/utils/file_scanner.py` - Updated TODO comments
- `backend/apps/core/views/map_views.py` - Removed outdated TODO comments
- `backend/apps/parks/management/commands/create_sample_data.py` - Updated TODO comments
- `docs/architecture/README.md` - Added reference to FUTURE_WORK.md
### Files Created
- `docs/FUTURE_WORK.md` - Centralized future work documentation
---
## [Phase 14] - 2025-12-23
### Documentation
#### Fixed
- Corrected architectural documentation from Vue.js SPA to Django + HTMX monolith
- Updated main README to accurately reflect technology stack (Django 5.2.8+, HTMX 1.20.0+, Alpine.js)
- Fixed deployment guide to remove frontend build steps (no separate frontend build process)
- Corrected environment setup instructions for Django + HTMX architecture
- Updated project structure diagrams to show Django monolith with HTMX templates
#### Added
- **Architecture Decision Records (ADRs)**
- ADR-001: Django + HTMX Architecture Decision
- ADR-002: Hybrid API Design Pattern
- ADR-003: State Machine Pattern for entity status management
- ADR-004: Caching Strategy with Redis multi-layer caching
- ADR-005: Authentication Approach (JWT + Session + Social Auth)
- ADR-006: Media Handling with Cloudflare Images
- **New Documentation Files**
- `docs/SETUP_GUIDE.md` - Comprehensive setup instructions with troubleshooting
- `docs/HEALTH_CHECKS.md` - Health check endpoint documentation
- `docs/PRODUCTION_CHECKLIST.md` - Deployment verification checklist
- `docs/architecture/README.md` - ADR index and template
- **Environment Configuration**
- Complete environment variable reference in `docs/configuration/environment-variables.md`
- Updated `.env.example` with comprehensive documentation
#### Enhanced
- Backend README with HTMX patterns and hybrid API/HTML endpoint documentation
- Deployment guide with Docker, nginx, and CI/CD pipeline configurations
- Production settings documentation with inline comments
- API documentation structure and endpoint reference
#### Documentation Structure
```
docs/
├── README.md # Updated - Django + HTMX architecture
├── SETUP_GUIDE.md # New - Development setup
├── HEALTH_CHECKS.md # New - Monitoring endpoints
├── PRODUCTION_CHECKLIST.md # New - Deployment checklist
├── THRILLWIKI_API_DOCUMENTATION.md # Existing - API reference
├── htmx-patterns.md # Existing - HTMX conventions
├── architecture/ # New - ADRs
│ ├── README.md # ADR index
│ ├── adr-001-django-htmx-architecture.md
│ ├── adr-002-hybrid-api-design.md
│ ├── adr-003-state-machine-pattern.md
│ ├── adr-004-caching-strategy.md
│ ├── adr-005-authentication-approach.md
│ └── adr-006-media-handling-cloudflare.md
└── configuration/
└── environment-variables.md # Existing - Complete reference
```
### Technical Details
This phase focused on documentation-only changes to align all project documentation with the actual Django + HTMX architecture. No code changes were made.
**Key Corrections:**
- The project uses Django templates with HTMX for interactivity, not a Vue.js SPA
- There is no separate frontend build process - static files are served by Django
- The API serves both JSON (for mobile/integrations) and HTML (for HTMX partials)
- Authentication uses JWT for API access and sessions for web browsing
---
## [Unreleased] - 2025-12-23
### Security
- **CRITICAL:** Updated Django from 5.0.x to 5.2.8+ to address CVE-2025-64459 (SQL injection, CVSS 9.1) and related vulnerabilities
- **HIGH:** Updated djangorestframework from 3.14.x to 3.15.2+ to address CVE-2024-21520 (XSS in break_long_headers filter)
- **MEDIUM:** Updated Pillow from 10.2.0 to 10.4.0+ (upper bound <11.2) to address CVE-2024-28219 (buffer overflow)
- Added cryptography>=44.0.0 for django-allauth JWT support
### Changed
- Standardized Python version requirement to 3.13+ across all configuration files
- Consolidated pyproject.toml files (root workspace + backend)
- Implemented consistent version pinning strategy using >= operators with minimum secure versions
- Updated CI/CD pipeline to use UV package manager instead of requirements.txt
- Moved linting and dev tools to proper dependency groups
### Package Updates
#### Core Django Ecosystem
- Django: 5.0.x → 5.2.8+
- djangorestframework: 3.14.x → 3.15.2+
- django-cors-headers: 4.3.1 → 4.6.0+
- django-filter: 23.5 → 24.3+
- drf-spectacular: 0.27.0 → 0.28.0+
- django-htmx: 1.17.2 → 1.20.0+
- whitenoise: 6.6.0 → 6.8.0+
#### Authentication
- django-allauth: 0.60.1 → 65.3.0+
- djangorestframework-simplejwt: maintained at 5.5.1+
#### Task Queue & Caching
- celery: maintained at 5.5.3+ (<6)
- django-celery-beat: maintained at 2.8.1+
- django-celery-results: maintained at 2.6.0+
- django-redis: 5.4.0+
- hiredis: 2.3.0 → 3.1.0+
#### Monitoring
- sentry-sdk: 1.40.0 → 2.20.0+ (<3)
#### Development Tools
- black: 24.1.0 → 25.1.0+
- ruff: 0.12.10 → 0.9.2+
- pyright: 1.1.404 → 1.1.405+
- coverage: 7.9.1 → 7.9.2+
- playwright: 1.41.0 → 1.50.0+
### Removed
- `channels>=4.2.0` - Not in INSTALLED_APPS, no WebSocket usage
- `channels-redis>=4.2.1` - Dependency of channels
- `daphne>=4.1.2` - ASGI server not used (using WSGI)
- `django-simple-history>=3.5.0` - Using django-pghistory instead
- `django-oauth-toolkit>=3.0.1` - Using dj-rest-auth + simplejwt instead
- `django-webpack-loader>=3.1.1` - No webpack configuration in project
- `reactivated>=0.47.5` - Not used in codebase
- `poetry>=2.1.3` - Using UV package manager instead
- Moved `django-silk` and `django-debug-toolbar` to optional profiling group
### Added
- UV lock file (uv.lock) for reproducible builds
- Automated weekly dependency update workflow (.github/workflows/dependency-update.yml)
- Security audit step in CI/CD pipeline (pip-audit)
- Requirements.txt generation script (scripts/generate_requirements.sh)
- Ruff configuration in pyproject.toml
### Fixed
- Broken CI/CD pipeline (was referencing non-existent requirements.txt)
- Python version inconsistencies between root and backend configurations
- Duplicate dependency definitions between root and backend pyproject.toml
- Root pyproject.toml name conflict (renamed to thrillwiki-workspace)
### Infrastructure
- CI/CD now uses UV with dependency caching
- Added dependency groups: dev, test, profiling, lint
- Workspace configuration for monorepo structure
---
## Version Pinning Strategy
This project uses the following version pinning strategy:
| Package Type | Format | Example |
|-------------|--------|---------|
| Security-critical | `>=X.Y.Z` | `django>=5.2.8` |
| Stable packages | `>=X.Y` | `django-cors-headers>=4.6` |
| Rapidly evolving | `>=X.Y,<X+1` | `sentry-sdk>=2.20.0,<3` |
| Breaking changes | `>=X.Y.Z,<X.Z` | `Pillow>=10.4.0,<11.2` |
---
## Migration Guide
### For Developers
1. Update Python to 3.13+
2. Install UV: `curl -LsSf https://astral.sh/uv/install.sh | sh`
3. Update dependencies: `cd backend && uv sync --frozen`
4. Run tests: `uv run manage.py test`
### Breaking Changes
- Python 3.11/3.12 no longer supported (requires 3.13+)
- django-allauth updated to 65.x (review social auth configuration)
- sentry-sdk updated to 2.x (review Sentry integration)

View File

@@ -1,207 +0,0 @@
# Gap Analysis Matrix - Deep Logic Audit
**Generated:** 2025-12-27 | **Audit Level:** Maximum Thoroughness (Line-by-Line)
## Summary Statistics
| Category | ✅ OK | ⚠️ DEVIATION | ❌ MISSING | Total |
|----------|-------|--------------|-----------|-------|
| Field Fidelity | 18 | 2 | 1 | 21 |
| State Logic | 12 | 1 | 0 | 13 |
| UI States | 14 | 3 | 0 | 17 |
| Permissions | 8 | 0 | 0 | 8 |
| Entity Forms | 10 | 0 | 0 | 10 |
| Entity CRUD API | 6 | 0 | 0 | 6 |
| **TOTAL** | **68** | **6** | **1** | **75** |
---
## 1. Field Fidelity Audit
### Ride Statistics Models
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| `height_ft` as Decimal(6,2) | `rides/models/rides.py:1000` | ✅ OK | `DecimalField(max_digits=6, decimal_places=2)` |
| `length_ft` as Decimal(7,2) | `rides/models/rides.py:1007` | ✅ OK | `DecimalField(max_digits=7, decimal_places=2)` |
| `speed_mph` as Decimal(5,2) | `rides/models/rides.py:1014` | ✅ OK | `DecimalField(max_digits=5, decimal_places=2)` |
| `max_drop_height_ft` | `rides/models/rides.py:1046` | ✅ OK | `DecimalField(max_digits=6, decimal_places=2)` |
| `g_force` field for coasters | `rides/models/rides.py` | ❌ MISSING | Spec mentions G-forces but `RollerCoasterStats` lacks this field |
| `inversions` as Integer | `rides/models/rides.py:1021` | ✅ OK | `PositiveIntegerField(default=0)` |
### Water/Dark/Flat Ride Stats
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| `WaterRideStats.splash_height_ft` | `rides/models/stats.py:59` | ✅ OK | `DecimalField(max_digits=5, decimal_places=2)` |
| `WaterRideStats.wetness_level` | `rides/models/stats.py:52` | ✅ OK | CharField with choices |
| `DarkRideStats.scene_count` | `rides/models/stats.py:112` | ✅ OK | PositiveIntegerField |
| `DarkRideStats.animatronic_count` | `rides/models/stats.py:117` | ✅ OK | PositiveIntegerField |
| `FlatRideStats.max_height_ft` | `rides/models/stats.py:172` | ✅ OK | `DecimalField(max_digits=6, decimal_places=2)` |
| `FlatRideStats.rotation_speed_rpm` | `rides/models/stats.py:180` | ✅ OK | `DecimalField(max_digits=5, decimal_places=2)` |
| `FlatRideStats.max_g_force` | `rides/models/stats.py:213` | ✅ OK | `DecimalField(max_digits=4, decimal_places=2)` |
### RideModel Technical Specs
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| `typical_height_range_*_ft` | `rides/models/rides.py:54-67` | ✅ OK | Both min/max as DecimalField |
| `typical_speed_range_*_mph` | `rides/models/rides.py:68-81` | ✅ OK | Both min/max as DecimalField |
| Height range constraint | `rides/models/rides.py:184-194` | ✅ OK | CheckConstraint validates min ≤ max |
| Speed range constraint | `rides/models/rides.py:196-206` | ✅ OK | CheckConstraint validates min ≤ max |
### Park Model Fields
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| `phone` contact field | `parks/models/parks.py` | ⚠️ DEVIATION | Field exists but spec wants E.164 format validation |
| `email` contact field | `parks/models/parks.py` | ✅ OK | EmailField present |
| Closing/opening date constraints | `parks/models/parks.py:137-183` | ✅ OK | Multiple CheckConstraints |
---
## 2. State Logic Audit
### Submission State Transitions
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| Claim requires PENDING status | `moderation/views.py:1455-1477` | ✅ OK | Explicit check: `if submission.status != "PENDING": return 400` |
| Unclaim requires CLAIMED status | `moderation/views.py:1520-1525` | ✅ OK | Explicit check before unclaim |
| Approve requires CLAIMED status | N/A | ⚠️ DEVIATION | Approve/Reject don't explicitly require CLAIMED - can approve from PENDING |
| Row locking for claim concurrency | `moderation/views.py:1450-1452` | ✅ OK | Uses `select_for_update(nowait=True)` |
| 409 Conflict on race condition | `moderation/views.py:1458-1464` | ✅ OK | Returns 409 with claimed_by info |
### Ride Status Transitions
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| FSM for ride status | `rides/models/rides.py:552-558` | ✅ OK | `RichFSMField` with state machine |
| CLOSING requires post_closing_status | `rides/models/rides.py:697-704` | ✅ OK | ValidationError if missing |
| Transition wrapper methods | `rides/models/rides.py:672-750` | ✅ OK | All transitions have wrapper methods |
| Status validation on save | `rides/models/rides.py:752-796` | ✅ OK | Computed fields populated on save |
### Park Status Transitions
| Requirement | File | Status | Notes |
|-------------|------|--------|-------|
| FSM for park status | `parks/models/parks.py` | ✅ OK | `RichFSMField` with StateMachineMixin |
| Transition methods | `parks/models/parks.py:189-221` | ✅ OK | reopen, close_temporarily, etc. |
| Closing date on permanent close | `parks/models/parks.py:204-211` | ✅ OK | Optional closing_date param |
---
## 3. UI States Audit
### Loading States
| Page | File | Status | Notes |
|------|------|--------|-------|
| Park Detail loading spinner | `parks/[park_slug]/index.vue:119-121` | ✅ OK | Full-screen spinner with `svg-spinners:ring-resize` |
| Park Detail error state | `parks/[park_slug]/index.vue:124-127` | ✅ OK | "Park Not Found" with back button |
| Moderation skeleton loaders | `moderation/index.vue:252-256` | ✅ OK | `BentoCard :loading="true"` |
| Search page loading | `search/index.vue` | ⚠️ DEVIATION | Uses basic pending state, no skeleton |
| Rides listing loading | `rides/index.vue` | ⚠️ DEVIATION | Basic loading state, no fancy skeleton |
| Credits page loading | `profile/credits.vue` | ✅ OK | Proper loading state |
### Error Handling & Toasts
| Feature | File | Status | Notes |
|---------|------|--------|-------|
| Moderation toast notifications | `moderation/index.vue:16,72-94` | ✅ OK | `useToast()` with success/warning/error variants |
| Moderation 409 conflict handling | `moderation/index.vue:82-88` | ✅ OK | Special handling for already-claimed |
| Park Detail error fallback | `parks/[park_slug]/index.vue:124-127` | ✅ OK | Error boundary with retry |
| Form validation toasts | Various | ⚠️ DEVIATION | Inconsistent - some forms use inline errors only |
| Global error toast composable | `composables/useToast.ts` | ✅ OK | Centralized toast system exists |
### Empty States
| Component | File | Status | Notes |
|-----------|------|--------|-------|
| Reviews empty state | `parks/[park_slug]/index.vue:283-286` | ✅ OK | Icon + message + CTA |
| Photos empty state | `parks/[park_slug]/index.vue:321-325` | ✅ OK | "Upload one" link |
| Moderation empty state | `moderation/index.vue:392-412` | ✅ OK | Context-aware messages per tab |
| Rides empty state | `parks/[park_slug]/index.vue:247-250` | ✅ OK | "Add the first ride" CTA |
| Credits empty state | N/A | ❌ MISSING | No dedicated empty state for credits page |
| Lists empty state | N/A | ❌ MISSING | No dedicated empty state for user lists |
### Real-time Updates
| Feature | File | Status | Notes |
|---------|------|--------|-------|
| SSE for moderation dashboard | `moderation/index.vue:194-220` | ✅ OK | `subscribeToDashboardUpdates()` with cleanup |
| Optimistic UI for claims | `moderation/index.vue:40-63` | ✅ OK | Map-based optimistic state tracking |
| Processing indicators | `moderation/index.vue:268-273` | ✅ OK | Per-item "Processing..." indicator |
---
## 4. Permissions Audit
### Moderation Endpoints
| Endpoint | File:Line | Permission | Status |
|----------|-----------|------------|--------|
| Report assign | `moderation/views.py:136` | `IsModeratorOrAdmin` | ✅ OK |
| Report resolve | `moderation/views.py:215` | `IsModeratorOrAdmin` | ✅ OK |
| Queue assign | `moderation/views.py:593` | `IsModeratorOrAdmin` | ✅ OK |
| Queue unassign | `moderation/views.py:666` | `IsModeratorOrAdmin` | ✅ OK |
| Queue complete | `moderation/views.py:732` | `IsModeratorOrAdmin` | ✅ OK |
| EditSubmission claim | `moderation/views.py:1436` | `IsModeratorOrAdmin` | ✅ OK |
| BulkOperation ViewSet | `moderation/views.py:1170` | `IsModeratorOrAdmin` | ✅ OK |
| Moderator middleware (frontend) | `moderation/index.vue:11-13` | `middleware: ['moderator']` | ✅ OK |
---
## 5. Entity Forms Audit
| Entity | Create | Edit | Status |
|--------|--------|------|--------|
| Park | `CreateParkModal.vue` | `EditParkModal.vue` | ✅ OK |
| Ride | `CreateRideModal.vue` | `EditRideModal.vue` | ✅ OK |
| Company | `CreateCompanyModal.vue` | `EditCompanyModal.vue` | ✅ OK |
| RideModel | `CreateRideModelModal.vue` | `EditRideModelModal.vue` | ✅ OK |
| UserList | `CreateListModal.vue` | `EditListModal.vue` | ✅ OK |
---
## Priority Gaps to Address
### High Priority (Functionality Gaps)
1. **`RollerCoasterStats` missing `g_force` field**
- Location: `backend/apps/rides/models/rides.py:990-1080`
- Impact: Coaster enthusiasts expect G-force data
- Fix: Add `max_g_force = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True)`
### Medium Priority (Deviations)
4. **Approve/Reject don't require CLAIMED status**
- Location: `moderation/views.py`
- Impact: Moderators can approve without claiming first
- Fix: Add explicit CLAIMED check or document as intentional
5. **Park phone field lacks E.164 validation**
- Location: `parks/models/parks.py`
- Fix: Add `phonenumbers` library validation
6. **Inconsistent form validation feedback**
- Multiple locations
- Fix: Standardize to toast + inline hybrid approach
---
## Verification Commands
```bash
# Check for missing G-force field
uv run manage.py shell -c "from apps.rides.models import RollerCoasterStats; print([f.name for f in RollerCoasterStats._meta.fields])"
# Verify state machine transitions
uv run manage.py test apps.moderation.tests.test_state_transitions -v 2
# Run full frontend type check
cd frontend && npx nuxi typecheck
```
---
*Audit completed with Maximum Thoroughness setting. All findings verified against source code.*

View File

@@ -1,179 +0,0 @@
# ThrillWiki Implementation Plan
## User Review Required
> [!IMPORTANT]
> **Measurement Unit System**: The backend will store all values in **Metric**. The Frontend (`useUnits` composable) will handle conversion to Imperial based on user preference.
> **Sacred Pipeline Enforcement**: All user edits create `Submission` records (stored as JSON). No direct database edits are allowed for non-admin users.
## Proposed Changes
### Backend (Django + DRF)
#### 1. Core & Auth Infrastructure
- [x] **`apps.core`**: Implement `TrackedModel` using `pghistory` for all core entities to support Edit History and Versioning (Section 15).
- [x] **`apps.accounts`**:
- `User` & `UserProfile` models (Bio, Location, Home Park).
- **Settings Support**: Endpoints for changing Email, Password, MFA, and Sessions (Section 9.1-9.2).
- **Privacy**: Fields for `public_profile`, `show_location`, etc. (Section 9.3).
- **Data Export**: Endpoint to generate JSON dump of all user data (Section 9.6).
- **Account Deletion**: `UserDeletionRequest` model with 7-day grace period (Section 9.6).
#### 2. Entity Models & Logic ("Live" Data)
- [x] **`apps.parks`**: `Park` (with Operator/Owner FKs, Geolocation).
- [x] **`apps.rides`**: `Ride` (Status FSM), `RideModel`, `Manufacturer`, `Designer`.
- [x] **`apps.rides` (Credits)**: `RideCredit` Through-Model with `count`, `rating`, `date`, `notes`. Constraint: Unique(user, ride).
- [x] **`apps.companies`**: `Company` model with types (`Manufacturer`, `Designer`, `Operator`, `Owner`).
- [x] **`apps.lists`**: `UserList` (Ranking System) and `UserListItem`.
- [x] **`apps.reviews`**: `Review` model (GenericFK) with Aggregation Logic.
#### 3. The Sacred Pipeline (`apps.moderation`)
- [x] **Submission Model**: Stores `changes` (JSON), `status` (State Machine), `moderator_note`.
- [x] **Submission Serializers**: Handle validation of "Proposed Data" vs "Live Data".
- [x] **Queue Endpoints**: `list_pending`, `claim`, `approve`, `reject`, `activity_log`, `stats`.
- [x] **Reports**: `Report` model and endpoints.
### Frontend (Nuxt 4)
#### 1. Initial Setup & Core
- [x] **Composables**: `useUnits` (Metric/Imperial), `useAuth` (MFA, Session), `useApi`.
- [x] **Layouts**: Standard Layout (Hero, Tabs), Auth Layout.
#### 2. Discovery & Search (Section 1 & 6)
- [x] **Global Search**: Hero Search with Autocomplete (Parks, Rides, Companies).
- [x] **Discovery Tabs** (11 Sections):
- [x] Trending Parks / Rides
- [x] New Parks / Rides
- [x] Top Parks / Rides
- [x] Opening Soon / Recently Opened
- [x] Closing Soon / Recently Closed
- [x] Recent Changes Feed
#### 3. Content Pages (Read-Only Views)
- [ ] **Park Detail**: Tabs (Overview, Rides, Reviews, Photos, History).
- [ ] **Ride Detail**: Tabs (Overview, Specifications, Reviews, Photos, History).
- [ ] **Company Pages**: Manufacturer, Designer, Operator, Property Owner details.
- [ ] **Maps**: Interactive "Parks Nearby" map.
#### 4. The Sacred Submission Pipeline (Write Views)
- [ ] **Submission Forms** (Multi-step Wizards):
- [ ] **Park Form**: Location, Dates, Media, Relations.
- [ ] **Ride Form**: Specs (with Unit Toggle), Relations, Park selection.
- [ ] **Company Form**: Type selection, HQ, details.
- [ ] **Photo Upload**: Bulk upload, captioning, crop.
- [ ] **Editing**: Load existing data into form -> Submit as JSON Diff.
#### 5. Moderation Interface (Section 16)
- [ ] **Dashboard**: Queue stats, Assignments.
- [ ] **Queues**:
- [ ] **Pending Queue**: Filter by Type, Submitter, Date.
- [ ] **Reports Queue**.
- [ ] **Audit Log**.
- [ ] **Review Workspace**:
- [ ] **Diff Viewer**: Visual Old vs New comparison.
- [ ] **Actions**: Claim, Approve, Reject (with reason), Edit.
#### 6. User Experience & Settings
- [ ] **User Profile**: Activity Feed, Credits Tab, Lists Tab, Reviews Tab.
- [ ] **Ride Credits Management**: Add/Edit Credit (Date, Count, Notes).
- [ ] **Settings Area** (6 Tabs):
- [ ] Account & Profile (Edit generic info).
- [ ] Security (MFA setup, Active Sessions).
- [ ] Privacy (Visibility settings).
- [ ] Notifications.
- [ ] Location & Info (Timezone, Home Park).
- [ ] Data & Export (JSON Download, Delete Account).
#### 7. Lists System
- [ ] **List Management**: Create/Edit Lists (Public/Private).
- [ ] **List Editor**: Search items, Add to list, Drag-and-drop reorder, Add notes.
## Verification Plan
### Automated Tests
- **Backend**: `pytest` for all Model constraints and API permissions.
- Test Submission State Machine: `Pending -> Claimed -> Approved`.
- Test Versioning: Ensure `pghistory` tracks changes on approval.
- **Frontend**: `vitest` for Unit Tests (Composables).
### Manual Verification Flows
1. **Sacred Pipeline Flow**:
- **User**: Submit a change to "Top Thrill 2" (add stats).
- **Moderator**: Go to Queue -> Claim -> Verify Diff -> Approve.
- **Public**: Verify "Top Thrill 2" page shows new stats and "Last Updated" is now.
- **History**: Verify "History" tab shows the update event.
2. **Ride Credits**:
- Go to "Iron Gwazi" page.
- Click "Add to Credits" -> Enter `Count: 5`, `Rating: 4.5`.
- Go to Profile -> Ride Credits. Verify Iron Gwazi is listed with correct data.
3. **Data Privacy & Export**:
- Go to Settings -> Privacy -> Toggle "Private Profile".
- Open Profile URL in Incognito -> Verify 404 or "Private" message.
- Go to Settings -> Data -> "Download Data" -> Verify JSON structure.
---
## Gap Reconciliation Batches (Added 2025-12-26)
> [!IMPORTANT]
> These batches were identified during the Full Project Synchronization audit.
> Refer to `GAP_ANALYSIS_MATRIX.md` for detailed per-feature status.
### BATCH 1: Critical Missing Pages (HIGH PRIORITY)
- [ ] `/my-credits` - Ride Credits Dashboard with stats, filters, quick increment
- [ ] `/settings` - Full Settings Page (6 sections: Account, Security, Privacy, Notifications, Location, Data)
- [ ] `/parks/nearby` - Location-based Discovery with Leaflet map, geolocation, radius slider
- [ ] `/my-submissions` - Submission History for user's past edits
- [ ] Static Pages: `/terms`, `/privacy`, `/guidelines`
### BATCH 2: Missing Tabs on Existing Pages (HIGH PRIORITY)
- [ ] Park Detail - Add Reviews, Photos, History tabs
- [ ] Ride Detail - Add Specifications, Reviews, Photos, History tabs
- [ ] Homepage - Expand to 11 Discovery Tabs (All, Parks, Coasters, Flat, Water, Dark, Shows, Transport, Manufacturers, Designers, Recent)
- [ ] Profile Page - Add Reviews, Ride Credits tabs
### BATCH 3: Missing Components (MEDIUM PRIORITY)
- [ ] `ReviewCard.vue` - User review display with voting
- [ ] `CreditCard.vue` - Ride credit display with quick actions
- [ ] `StarRating.vue` - Star rating visualization
- [ ] `DiffViewer.vue` - Side-by-side comparison for moderation
- [ ] `ImageGallery.vue` - Photo gallery with lightbox
- [ ] `AppFooter.vue` - Site-wide footer
- [ ] `Breadcrumbs.vue` - Hierarchical navigation
- [ ] DatePicker and Range Slider components
### BATCH 4: Submission Forms (MEDIUM PRIORITY)
- [ ] `/submit/park` - Multi-step park submission wizard
- [ ] `/submit/ride` - Multi-step ride submission wizard
- [ ] `/submit/company` - Company submission wizard
- [ ] Edit forms for existing entities with JSON diff
### BATCH 5: Company Pages (MEDIUM PRIORITY)
- [ ] `/designers` - Designers listing and detail pages
- [ ] `/operators` - Operators listing and detail pages
- [ ] `/owners` - Property Owners listing and detail pages
- [ ] `/ride-models/[slug]` - Ride Model detail with installations
### BATCH 6: Enhanced Features (LOW PRIORITY)
- [ ] OAuth Authentication (Google, Discord)
- [ ] Magic Link Login
- [ ] CAPTCHA integration on forms
- [ ] MFA Setup UI
- [ ] Review voting (thumbs up/down) and replies
- [ ] Recent searches history
- [ ] Drag-and-drop list reordering
- [ ] Glass card effects (dark mode)
- [ ] Reduced motion support
---
## Execution Order Recommendation
1. **Start with BATCH 1** - Critical pages users expect
2. **Then BATCH 2** - Complete existing pages
3. **Then BATCH 3** - Components needed by batches 1 & 2
4. **Then BATCH 4** - Enable user contributions
5. **Then BATCH 5** - Additional entity types
6. **Finally BATCH 6** - Polish and enhancements

View File

@@ -1,59 +0,0 @@
# MASTER OMNI LOG
## Phase 1: Gap Analysis [x]
- [x] Scan backend/urls.py and ViewSets vs frontend services.
- [x] Identify missing/broken endpoints.
- [x] Identify UX/UI gaps (Loading, Error Handling).
- [x] Check Theme/CSS configuration.
## Phase 3: Execution Loop [x]
### Feature: Core Infrastructure
- [x] **Fix Missing Composables**: Create `frontend/app/composables/useModeration.ts` matching `apps.moderation` endpoints.
- [x] **Roadtrip API**: Create `frontend/app/composables/useRoadtripApi.ts` matching `apps.parks` roadtrip endpoints.
- [x] **FSM Support**: Add generic FSM transition methods to `useApi.ts` or specific composables.
### Feature: Parks & Rides
- [x] **Park API Gaps**: Add `getOperators`, `searchLocation` to `useParksApi.ts`.
- [x] **Ride API Gaps**: Add `getManufacturers`, `getDesigners` to `useRidesApi.ts`.
- [x] **Frontend Pages**: Ensure `parks/roadtrip` page exists or create it.
- [x] **Manufacturers Page**: Ensure `manufacturers/` page exists.
### Feature: UX & Interactivity
- [x] **Moderation Dashboard**: Updates `useModeration` usage in `moderation/index.vue`. Add error handling.
- [x] **Status Colors**: Refactor `main.css` hardcoded hex values to use CSS variables or Tailwind tokens.
- [x] **Loading States**: Audit `pages/parks/[slug].vue` and `pages/rides/[slug].vue` for skeleton loaders.
### Feature: Theme & Polish
- [x] **Dark Mode**: Verify `input.css` / `main.css` `@theme` usage.
- [x] **Contrast**: Check status badge text contrast in Dark Mode.
## Execution Checklists
### 1. Moderation API Parity
- [x] Implement `getReports`
- [x] Implement `getQueue`
- [x] Implement `getActions`
- [x] Implement `getBulkOperations`
- [x] Implement `userModeration` endpoints
- [x] Implement `approve`/`reject`/`escalate` actions
### 2. Roadtrip API Parity
- [x] Implement `getRoadtrips` (Skipped: Backend does not persist trips)
- [x] Implement `createTrip`
- [x] Implement `getTripDetail` (Skipped: Backend does not persist trips)
- [x] Implement `findParksAlongRoute`
- [x] Implement `geocodeAddress`
- [x] Implement `calculateDistance`
- [x] Implement `optimizeRoute` (Covered by createTrip)
### 3. CSS Standardization
- [x] Replace `#f59e0b` with `var(--color-warning-500)` or tailwind class.
- [x] Replace `#10b981` with `var(--color-success-500)`.
- [x] Replace `#ef4444` with `var(--color-error-500)`.
- [x] Replace `#8b5cf6` with `var(--color-violet-500)`.
## Phase 4: Final Verification [x]
- [-] **Type Check**: Run `npx nuxi typecheck` (Found errors, but build succeeds).
- [x] **Build Check**: Run `npm run build` (Success).
- [x] **Lint Check**: Run `npm run lint` (Skipped).

391
README.md Normal file
View File

@@ -0,0 +1,391 @@
# ThrillWiki Development Environment Setup
ThrillWiki is a modern Django web application for theme park and roller coaster enthusiasts, featuring a sophisticated dark theme design with purple-to-blue gradients, HTMX interactivity, and comprehensive park/ride information management.
## 🏗️ Technology Stack
- **Backend**: Django 5.0+ with GeoDjango (PostGIS)
- **Frontend**: HTMX + Alpine.js + Tailwind CSS
- **Database**: PostgreSQL with PostGIS extension
- **Package Management**: UV (Python package manager)
- **Authentication**: Django Allauth with Google/Discord OAuth
- **Styling**: Tailwind CSS with custom dark theme
- **History Tracking**: django-pghistory for audit trails
- **Testing**: Pytest + Playwright for E2E testing
## 📋 Prerequisites
### Required Software
1. **Python 3.11+**
```bash
python --version # Should be 3.11 or higher
```
2. **UV Package Manager**
```bash
# Install UV if not already installed
curl -LsSf https://astral.sh/uv/install.sh | sh
# or
pip install uv
```
3. **PostgreSQL with PostGIS**
```bash
# macOS (Homebrew)
brew install postgresql postgis
# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib postgis
# Start PostgreSQL service
brew services start postgresql # macOS
sudo systemctl start postgresql # Linux
```
4. **GDAL/GEOS Libraries** (for GeoDjango)
```bash
# macOS (Homebrew)
brew install gdal geos
# Ubuntu/Debian
sudo apt-get install gdal-bin libgdal-dev libgeos-dev
```
5. **Node.js** (for Tailwind CSS)
```bash
# Install Node.js 18+ for Tailwind CSS compilation
node --version # Should be 18 or higher
```
## 🚀 Quick Start
### 1. Clone and Setup Project
```bash
# Clone the repository
git clone <repository-url>
cd thrillwiki_django_no_react
# Install Python dependencies using UV
uv sync
```
### 2. Database Setup
```bash
# Create PostgreSQL database and user
createdb thrillwiki
createuser wiki
# Connect to PostgreSQL and setup
psql postgres
```
In the PostgreSQL shell:
```sql
-- Set password for wiki user
ALTER USER wiki WITH PASSWORD 'thrillwiki';
-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE thrillwiki TO wiki;
-- Enable PostGIS extension
\c thrillwiki
CREATE EXTENSION postgis;
\q
```
### 3. Environment Configuration
The project uses these database settings (configured in [`thrillwiki/settings.py`](thrillwiki/settings.py)):
```python
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "thrillwiki",
"USER": "wiki",
"PASSWORD": "thrillwiki",
"HOST": "192.168.86.3", # Update to your PostgreSQL host
"PORT": "5432",
}
}
```
**Important**: Update the `HOST` setting in [`thrillwiki/settings.py`](thrillwiki/settings.py) to match your PostgreSQL server location:
- Use `"localhost"` or `"127.0.0.1"` for local development
- Current setting is `"192.168.86.3"` - update this to your PostgreSQL server IP
- For local development, change to `"localhost"` in settings.py
### 4. Database Migration
```bash
# Run database migrations
uv run manage.py migrate
# Create a superuser account
uv run manage.py createsuperuser
```
**Note**: If you're setting up for local development, first update the database HOST in [`thrillwiki/settings.py`](thrillwiki/settings.py) from `"192.168.86.3"` to `"localhost"` before running migrations.
### 5. Start Development Server
**CRITICAL**: Always use this exact command sequence for starting the development server:
```bash
lsof -ti :8000 | xargs kill -9; find . -type d -name "__pycache__" -exec rm -r {} +; uv run manage.py tailwind runserver
```
This command:
- Kills any existing processes on port 8000
- Cleans Python cache files
- Starts Tailwind CSS compilation
- Runs the Django development server
The application will be available at: http://localhost:8000
## 🛠️ Development Workflow
### Package Management
**ALWAYS use UV for package management**:
```bash
# Add new Python packages
uv add <package-name>
# Add development dependencies
uv add --dev <package-name>
# Never use pip install - always use UV
```
### Django Management Commands
**ALWAYS use UV for Django commands**:
```bash
# Correct way to run Django commands
uv run manage.py <command>
# Examples:
uv run manage.py makemigrations
uv run manage.py migrate
uv run manage.py shell
uv run manage.py createsuperuser
uv run manage.py collectstatic
# NEVER use these patterns:
# python manage.py <command> ❌ Wrong
# uv run python manage.py <command> ❌ Wrong
```
### CSS Development
The project uses **Tailwind CSS v4** with a custom dark theme. CSS files are located in:
- Source: [`static/css/src/input.css`](static/css/src/input.css)
- Compiled: [`static/css/`](static/css/) (auto-generated)
Tailwind automatically compiles when using the `tailwind runserver` command.
#### Tailwind CSS v4 Migration
This project has been migrated from Tailwind CSS v3 to v4. For complete migration details:
- **📖 Full Migration Documentation**: [`TAILWIND_V4_MIGRATION.md`](TAILWIND_V4_MIGRATION.md)
- **⚡ Quick Reference Guide**: [`TAILWIND_V4_QUICK_REFERENCE.md`](TAILWIND_V4_QUICK_REFERENCE.md)
**Key v4 Changes**:
- New CSS-first approach with `@theme` blocks
- Updated utility class names (e.g., `outline-none` → `outline-hidden`)
- New opacity syntax (e.g., `bg-blue-500/50` instead of `bg-blue-500 bg-opacity-50`)
- Enhanced performance and smaller bundle sizes
**Custom Theme Variables** (available in CSS):
```css
var(--color-primary) /* #4f46e5 - Indigo-600 */
var(--color-secondary) /* #e11d48 - Rose-600 */
var(--color-accent) /* #8b5cf6 - Violet-500 */
var(--font-family-sans) /* Poppins, sans-serif */
```
## 🏗️ Project Structure
```
thrillwiki_django_no_react/
├── accounts/ # User account management
├── analytics/ # Analytics and tracking
├── companies/ # Theme park companies
├── core/ # Core application logic
├── designers/ # Ride designers
├── history/ # History timeline features
├── location/ # Geographic location handling
├── media/ # Media file management
├── moderation/ # Content moderation
├── parks/ # Theme park management
├── reviews/ # User reviews
├── rides/ # Roller coaster/ride management
├── search/ # Search functionality
├── static/ # Static assets (CSS, JS, images)
├── templates/ # Django templates
├── thrillwiki/ # Main Django project settings
├── memory-bank/ # Development documentation
└── .clinerules # Project development rules
```
## 🔧 Key Features
### Authentication System
- Django Allauth integration
- Google OAuth authentication
- Discord OAuth authentication
- Custom user profiles with avatars
### Geographic Features
- PostGIS integration for location data
- Interactive park maps
- Location-based search and filtering
### Content Management
- Park and ride information management
- Photo galleries with upload capabilities
- User-generated reviews and ratings
- Content moderation system
### Modern Frontend
- HTMX for dynamic interactions
- Alpine.js for client-side behavior
- Tailwind CSS with custom dark theme
- Responsive design (mobile-first)
## 🧪 Testing
### Running Tests
```bash
# Run Python tests
uv run pytest
# Run with coverage
uv run coverage run -m pytest
uv run coverage report
# Run E2E tests with Playwright
uv run pytest tests/e2e/
```
### Test Structure
- Unit tests: Located within each app's `tests/` directory
- E2E tests: [`tests/e2e/`](tests/e2e/)
- Test fixtures: [`tests/fixtures/`](tests/fixtures/)
## 📚 Documentation
### Memory Bank System
The project uses a comprehensive documentation system in [`memory-bank/`](memory-bank/):
- [`memory-bank/activeContext.md`](memory-bank/activeContext.md) - Current development context
- [`memory-bank/documentation/design-system.md`](memory-bank/documentation/design-system.md) - Design system documentation
- [`memory-bank/features/`](memory-bank/features/) - Feature-specific documentation
- [`memory-bank/testing/`](memory-bank/testing/) - Testing documentation and results
### Key Documentation Files
- [Design System](memory-bank/documentation/design-system.md) - UI/UX guidelines and patterns
- [Authentication System](memory-bank/features/auth/) - OAuth and user management
- [Layout Optimization](memory-bank/projects/) - Responsive design implementations
## 🚨 Important Development Rules
### Critical Commands
1. **Server Startup**: Always use the full command sequence:
```bash
lsof -ti :8000 | xargs kill -9; find . -type d -name "__pycache__" -exec rm -r {} +; uv run manage.py tailwind runserver
```
2. **Package Management**: Only use UV:
```bash
uv add <package> # ✅ Correct
pip install <package> # ❌ Wrong
```
3. **Django Commands**: Always prefix with `uv run`:
```bash
uv run manage.py <command> # ✅ Correct
python manage.py <command> # ❌ Wrong
```
### Database Configuration
- Ensure PostgreSQL is running before starting development
- PostGIS extension must be enabled
- Update database host settings for your environment
### GeoDjango Requirements
- GDAL and GEOS libraries must be properly installed
- Library paths are configured in [`thrillwiki/settings.py`](thrillwiki/settings.py) for macOS Homebrew
- Current paths: `/opt/homebrew/lib/libgdal.dylib` and `/opt/homebrew/lib/libgeos_c.dylib`
- May need adjustment based on your system's library locations (Linux users will need different paths)
## 🔍 Troubleshooting
### Common Issues
1. **PostGIS Extension Error**
```bash
# Connect to database and enable PostGIS
psql thrillwiki
CREATE EXTENSION postgis;
```
2. **GDAL/GEOS Library Not Found**
```bash
# macOS (Homebrew): Current paths in settings.py
GDAL_LIBRARY_PATH = "/opt/homebrew/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/opt/homebrew/lib/libgeos_c.dylib"
# Linux: Update paths in settings.py to something like:
# GDAL_LIBRARY_PATH = "/usr/lib/x86_64-linux-gnu/libgdal.so"
# GEOS_LIBRARY_PATH = "/usr/lib/x86_64-linux-gnu/libgeos_c.so"
# Find your library locations
find /usr -name "libgdal*" 2>/dev/null
find /usr -name "libgeos*" 2>/dev/null
find /opt -name "libgdal*" 2>/dev/null
find /opt -name "libgeos*" 2>/dev/null
```
3. **Port 8000 Already in Use**
```bash
# Kill existing processes
lsof -ti :8000 | xargs kill -9
```
4. **Tailwind CSS Not Compiling**
```bash
# Ensure Node.js is installed and use the full server command
node --version
uv run manage.py tailwind runserver
```
### Getting Help
1. Check the [`memory-bank/`](memory-bank/) documentation for detailed feature information
2. Review [`memory-bank/testing/`](memory-bank/testing/) for known issues and solutions
3. Ensure all prerequisites are properly installed
4. Verify database connection and PostGIS extension
## 🎯 Next Steps
After successful setup:
1. **Explore the Admin Interface**: http://localhost:8000/admin/
2. **Browse the Application**: http://localhost:8000/
3. **Review Documentation**: Check [`memory-bank/`](memory-bank/) for detailed feature docs
4. **Run Tests**: Ensure everything works with `uv run pytest`
5. **Start Development**: Follow the development workflow guidelines above
---
**Happy Coding!** 🎢✨
For detailed feature documentation and development context, see the [`memory-bank/`](memory-bank/) directory.

View File

@@ -1,24 +1,23 @@
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site from django.contrib.sites.shortcuts import get_current_site
User = get_user_model() User = get_user_model()
class CustomAccountAdapter(DefaultAccountAdapter): class CustomAccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request): def is_open_for_signup(self, request):
""" """
Whether to allow sign ups. Whether to allow sign ups.
""" """
return True return getattr(settings, 'ACCOUNT_ALLOW_SIGNUPS', True)
def get_email_confirmation_url(self, request, emailconfirmation): def get_email_confirmation_url(self, request, emailconfirmation):
""" """
Constructs the email confirmation (activation) url. Constructs the email confirmation (activation) url.
""" """
get_current_site(request) site = get_current_site(request)
return f"{settings.LOGIN_REDIRECT_URL}verify-email?key={emailconfirmation.key}" return f"{settings.LOGIN_REDIRECT_URL}verify-email?key={emailconfirmation.key}"
def send_confirmation_mail(self, request, emailconfirmation, signup): def send_confirmation_mail(self, request, emailconfirmation, signup):
@@ -28,28 +27,30 @@ class CustomAccountAdapter(DefaultAccountAdapter):
current_site = get_current_site(request) current_site = get_current_site(request)
activate_url = self.get_email_confirmation_url(request, emailconfirmation) activate_url = self.get_email_confirmation_url(request, emailconfirmation)
ctx = { ctx = {
"user": emailconfirmation.email_address.user, 'user': emailconfirmation.email_address.user,
"activate_url": activate_url, 'activate_url': activate_url,
"current_site": current_site, 'current_site': current_site,
"key": emailconfirmation.key, 'key': emailconfirmation.key,
} }
email_template = "account/email/email_confirmation_signup" if signup else "account/email/email_confirmation" if signup:
email_template = 'account/email/email_confirmation_signup'
else:
email_template = 'account/email/email_confirmation'
self.send_mail(email_template, emailconfirmation.email_address.email, ctx) self.send_mail(email_template, emailconfirmation.email_address.email, ctx)
class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request, sociallogin): def is_open_for_signup(self, request, sociallogin):
""" """
Whether to allow social account sign ups. Whether to allow social account sign ups.
""" """
return True return getattr(settings, 'SOCIALACCOUNT_ALLOW_SIGNUPS', True)
def populate_user(self, request, sociallogin, data): def populate_user(self, request, sociallogin, data):
""" """
Hook that can be used to further populate the user instance. Hook that can be used to further populate the user instance.
""" """
user = super().populate_user(request, sociallogin, data) user = super().populate_user(request, sociallogin, data)
if sociallogin.account.provider == "discord": if sociallogin.account.provider == 'discord':
user.discord_id = sociallogin.account.uid user.discord_id = sociallogin.account.uid
return user return user

207
accounts/admin.py Normal file
View File

@@ -0,0 +1,207 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html
from django.urls import reverse
from django.contrib.auth.models import Group
from .models import User, UserProfile, EmailVerification, TopList, TopListItem
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'Profile'
fieldsets = (
('Personal Info', {
'fields': ('display_name', 'avatar', 'pronouns', 'bio')
}),
('Social Media', {
'fields': ('twitter', 'instagram', 'youtube', 'discord')
}),
('Ride Credits', {
'fields': (
'coaster_credits',
'dark_ride_credits',
'flat_ride_credits',
'water_ride_credits'
)
}),
)
class TopListItemInline(admin.TabularInline):
model = TopListItem
extra = 1
fields = ('content_type', 'object_id', 'rank', 'notes')
ordering = ('rank',)
@admin.register(User)
class CustomUserAdmin(UserAdmin):
list_display = ('username', 'email', 'get_avatar', 'get_status', 'role', 'date_joined', 'last_login', 'get_credits')
list_filter = ('is_active', 'is_staff', 'role', 'is_banned', 'groups', 'date_joined')
search_fields = ('username', 'email')
ordering = ('-date_joined',)
actions = ['activate_users', 'deactivate_users', 'ban_users', 'unban_users']
inlines = [UserProfileInline]
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('email', 'pending_email')}),
('Roles and Permissions', {
'fields': ('role', 'groups', 'user_permissions'),
'description': 'Role determines group membership. Groups determine permissions.',
}),
('Status', {
'fields': ('is_active', 'is_staff', 'is_superuser'),
'description': 'These are automatically managed based on role.',
}),
('Ban Status', {
'fields': ('is_banned', 'ban_reason', 'ban_date'),
}),
('Preferences', {
'fields': ('theme_preference',),
}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2', 'role'),
}),
)
def get_avatar(self, obj):
if obj.profile.avatar:
return format_html('<img src="{}" width="30" height="30" style="border-radius:50%;" />', obj.profile.avatar.url)
return format_html('<div style="width:30px; height:30px; border-radius:50%; background-color:#007bff; color:white; display:flex; align-items:center; justify-content:center;">{}</div>', obj.username[0].upper())
get_avatar.short_description = 'Avatar'
def get_status(self, obj):
if obj.is_banned:
return format_html('<span style="color: red;">Banned</span>')
if not obj.is_active:
return format_html('<span style="color: orange;">Inactive</span>')
if obj.is_superuser:
return format_html('<span style="color: purple;">Superuser</span>')
if obj.is_staff:
return format_html('<span style="color: blue;">Staff</span>')
return format_html('<span style="color: green;">Active</span>')
get_status.short_description = 'Status'
def get_credits(self, obj):
try:
profile = obj.profile
return format_html(
'RC: {}<br>DR: {}<br>FR: {}<br>WR: {}',
profile.coaster_credits,
profile.dark_ride_credits,
profile.flat_ride_credits,
profile.water_ride_credits
)
except UserProfile.DoesNotExist:
return '-'
get_credits.short_description = 'Ride Credits'
def activate_users(self, request, queryset):
queryset.update(is_active=True)
activate_users.short_description = "Activate selected users"
def deactivate_users(self, request, queryset):
queryset.update(is_active=False)
deactivate_users.short_description = "Deactivate selected users"
def ban_users(self, request, queryset):
from django.utils import timezone
queryset.update(is_banned=True, ban_date=timezone.now())
ban_users.short_description = "Ban selected users"
def unban_users(self, request, queryset):
queryset.update(is_banned=False, ban_date=None, ban_reason='')
unban_users.short_description = "Unban selected users"
def save_model(self, request, obj, form, change):
creating = not obj.pk
super().save_model(request, obj, form, change)
if creating and obj.role != User.Roles.USER:
# Ensure new user with role gets added to appropriate group
group = Group.objects.filter(name=obj.role).first()
if group:
obj.groups.add(group)
@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'display_name', 'coaster_credits', 'dark_ride_credits', 'flat_ride_credits', 'water_ride_credits')
list_filter = ('coaster_credits', 'dark_ride_credits', 'flat_ride_credits', 'water_ride_credits')
search_fields = ('user__username', 'user__email', 'display_name', 'bio')
fieldsets = (
('User Information', {
'fields': ('user', 'display_name', 'avatar', 'pronouns', 'bio')
}),
('Social Media', {
'fields': ('twitter', 'instagram', 'youtube', 'discord')
}),
('Ride Credits', {
'fields': (
'coaster_credits',
'dark_ride_credits',
'flat_ride_credits',
'water_ride_credits'
)
}),
)
@admin.register(EmailVerification)
class EmailVerificationAdmin(admin.ModelAdmin):
list_display = ('user', 'created_at', 'last_sent', 'is_expired')
list_filter = ('created_at', 'last_sent')
search_fields = ('user__username', 'user__email', 'token')
readonly_fields = ('created_at', 'last_sent')
fieldsets = (
('Verification Details', {
'fields': ('user', 'token')
}),
('Timing', {
'fields': ('created_at', 'last_sent')
}),
)
def is_expired(self, obj):
from django.utils import timezone
from datetime import timedelta
if timezone.now() - obj.last_sent > timedelta(days=1):
return format_html('<span style="color: red;">Expired</span>')
return format_html('<span style="color: green;">Valid</span>')
is_expired.short_description = 'Status'
@admin.register(TopList)
class TopListAdmin(admin.ModelAdmin):
list_display = ('title', 'user', 'category', 'created_at', 'updated_at')
list_filter = ('category', 'created_at', 'updated_at')
search_fields = ('title', 'user__username', 'description')
inlines = [TopListItemInline]
fieldsets = (
('Basic Information', {
'fields': ('user', 'title', 'category', 'description')
}),
('Timestamps', {
'fields': ('created_at', 'updated_at'),
'classes': ('collapse',)
}),
)
readonly_fields = ('created_at', 'updated_at')
@admin.register(TopListItem)
class TopListItemAdmin(admin.ModelAdmin):
list_display = ('top_list', 'content_type', 'object_id', 'rank')
list_filter = ('top_list__category', 'rank')
search_fields = ('top_list__title', 'notes')
ordering = ('top_list', 'rank')
fieldsets = (
('List Information', {
'fields': ('top_list', 'rank')
}),
('Item Details', {
'fields': ('content_type', 'object_id', 'notes')
}),
)

View File

@@ -3,7 +3,7 @@ from django.apps import AppConfig
class AccountsConfig(AppConfig): class AccountsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField" default_auto_field = "django.db.models.BigAutoField"
name = "apps.accounts" name = "accounts"
def ready(self): def ready(self):
import apps.accounts.signals # noqa import accounts.signals # noqa

View File

@@ -0,0 +1,30 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp, SocialAccount, SocialToken
from django.contrib.sites.models import Site
class Command(BaseCommand):
help = 'Check all social auth related tables'
def handle(self, *args, **options):
# Check SocialApp
self.stdout.write('\nChecking SocialApp table:')
for app in SocialApp.objects.all():
self.stdout.write(f'ID: {app.id}, Provider: {app.provider}, Name: {app.name}, Client ID: {app.client_id}')
self.stdout.write('Sites:')
for site in app.sites.all():
self.stdout.write(f' - {site.domain}')
# Check SocialAccount
self.stdout.write('\nChecking SocialAccount table:')
for account in SocialAccount.objects.all():
self.stdout.write(f'ID: {account.id}, Provider: {account.provider}, UID: {account.uid}')
# Check SocialToken
self.stdout.write('\nChecking SocialToken table:')
for token in SocialToken.objects.all():
self.stdout.write(f'ID: {token.id}, Account: {token.account}, App: {token.app}')
# Check Site
self.stdout.write('\nChecking Site table:')
for site in Site.objects.all():
self.stdout.write(f'ID: {site.id}, Domain: {site.domain}, Name: {site.name}')

View File

@@ -0,0 +1,19 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp
class Command(BaseCommand):
help = 'Check social app configurations'
def handle(self, *args, **options):
social_apps = SocialApp.objects.all()
if not social_apps:
self.stdout.write(self.style.ERROR('No social apps found'))
return
for app in social_apps:
self.stdout.write(self.style.SUCCESS(f'\nProvider: {app.provider}'))
self.stdout.write(f'Name: {app.name}')
self.stdout.write(f'Client ID: {app.client_id}')
self.stdout.write(f'Secret: {app.secret}')
self.stdout.write(f'Sites: {", ".join(str(site.domain) for site in app.sites.all())}')

View File

@@ -1,9 +1,8 @@
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.db import connection from django.db import connection
class Command(BaseCommand): class Command(BaseCommand):
help = "Clean up social auth tables and migrations" help = 'Clean up social auth tables and migrations'
def handle(self, *args, **options): def handle(self, *args, **options):
with connection.cursor() as cursor: with connection.cursor() as cursor:
@@ -15,14 +14,9 @@ class Command(BaseCommand):
# Remove migration records # Remove migration records
cursor.execute("DELETE FROM django_migrations WHERE app='socialaccount'") cursor.execute("DELETE FROM django_migrations WHERE app='socialaccount'")
cursor.execute( cursor.execute("DELETE FROM django_migrations WHERE app='accounts' AND name LIKE '%social%'")
"DELETE FROM django_migrations WHERE app='accounts' "
"AND name LIKE '%social%'"
)
# Reset sequences # Reset sequences
cursor.execute("DELETE FROM sqlite_sequence WHERE name LIKE '%social%'") cursor.execute("DELETE FROM sqlite_sequence WHERE name LIKE '%social%'")
self.stdout.write( self.stdout.write(self.style.SUCCESS('Successfully cleaned up social auth configuration'))
self.style.SUCCESS("Successfully cleaned up social auth configuration")
)

View File

@@ -1,8 +1,9 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from apps.parks.models import Park, ParkPhoto, ParkReview from django.contrib.auth.models import Group
from apps.rides.models import Ride, RidePhoto from parks.models import Park, ParkReview as Review
from rides.models import Ride
from media.models import Photo
User = get_user_model() User = get_user_model()
@@ -12,33 +13,25 @@ class Command(BaseCommand):
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
# Delete test users # Delete test users
test_users = User.objects.filter(username__in=["testuser", "moderator"]) test_users = User.objects.filter(
username__in=["testuser", "moderator"])
count = test_users.count() count = test_users.count()
test_users.delete() test_users.delete()
self.stdout.write(self.style.SUCCESS(f"Deleted {count} test users")) self.stdout.write(self.style.SUCCESS(f"Deleted {count} test users"))
# Delete test reviews # Delete test reviews
reviews = ParkReview.objects.filter( reviews = Review.objects.filter(
user__username__in=["testuser", "moderator"] user__username__in=["testuser", "moderator"])
)
count = reviews.count() count = reviews.count()
reviews.delete() reviews.delete()
self.stdout.write(self.style.SUCCESS(f"Deleted {count} test reviews")) self.stdout.write(self.style.SUCCESS(f"Deleted {count} test reviews"))
# Delete test photos - both park and ride photos # Delete test photos
park_photos = ParkPhoto.objects.filter( photos = Photo.objects.filter(uploader__username__in=[
uploader__username__in=["testuser", "moderator"] "testuser", "moderator"])
) count = photos.count()
park_count = park_photos.count() photos.delete()
park_photos.delete() self.stdout.write(self.style.SUCCESS(f"Deleted {count} test photos"))
self.stdout.write(self.style.SUCCESS(f"Deleted {park_count} test park photos"))
ride_photos = RidePhoto.objects.filter(
uploader__username__in=["testuser", "moderator"]
)
ride_count = ride_photos.count()
ride_photos.delete()
self.stdout.write(self.style.SUCCESS(f"Deleted {ride_count} test ride photos"))
# Delete test parks # Delete test parks
parks = Park.objects.filter(name__startswith="Test Park") parks = Park.objects.filter(name__startswith="Test Park")
@@ -53,8 +46,8 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS(f"Deleted {count} test rides")) self.stdout.write(self.style.SUCCESS(f"Deleted {count} test rides"))
# Clean up test files # Clean up test files
import glob
import os import os
import glob
# Clean up test uploads # Clean up test uploads
media_patterns = [ media_patterns = [
@@ -71,6 +64,7 @@ class Command(BaseCommand):
os.remove(f) os.remove(f)
self.stdout.write(self.style.SUCCESS(f"Deleted {f}")) self.stdout.write(self.style.SUCCESS(f"Deleted {f}"))
except OSError as e: except OSError as e:
self.stdout.write(self.style.WARNING(f"Error deleting {f}: {e}")) self.stdout.write(self.style.WARNING(
f"Error deleting {f}: {e}"))
self.stdout.write(self.style.SUCCESS("Test data cleanup complete")) self.stdout.write(self.style.SUCCESS("Test data cleanup complete"))

View File

@@ -0,0 +1,48 @@
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp
class Command(BaseCommand):
help = 'Create social apps for authentication'
def handle(self, *args, **options):
# Get the default site
site = Site.objects.get_or_create(
id=1,
defaults={
'domain': 'localhost:8000',
'name': 'ThrillWiki Development'
}
)[0]
# Create Discord app
discord_app, created = SocialApp.objects.get_or_create(
provider='discord',
defaults={
'name': 'Discord',
'client_id': '1299112802274902047',
'secret': 'ece7Pe_M4mD4mYzAgcINjTEKL_3ftL11',
}
)
if not created:
discord_app.client_id = '1299112802274902047'
discord_app.secret = 'ece7Pe_M4mD4mYzAgcINjTEKL_3ftL11'
discord_app.save()
discord_app.sites.add(site)
self.stdout.write(f'{"Created" if created else "Updated"} Discord app')
# Create Google app
google_app, created = SocialApp.objects.get_or_create(
provider='google',
defaults={
'name': 'Google',
'client_id': '135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com',
'secret': 'GOCSPX-Wd_0Ue0Ue0Ue0Ue0Ue0Ue0Ue0Ue',
}
)
if not created:
google_app.client_id = '135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com'
google_app.secret = 'GOCSPX-Wd_0Ue0Ue0Ue0Ue0Ue0Ue0Ue0Ue'
google_app.save()
google_app.sites.add(site)
self.stdout.write(f'{"Created" if created else "Updated"} Google app')

View File

@@ -1,5 +1,8 @@
from django.contrib.auth.models import Group, Permission, User
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
User = get_user_model()
class Command(BaseCommand): class Command(BaseCommand):
@@ -8,25 +11,22 @@ class Command(BaseCommand):
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
# Create regular test user # Create regular test user
if not User.objects.filter(username="testuser").exists(): if not User.objects.filter(username="testuser").exists():
user = User.objects.create( user = User.objects.create_user(
username="testuser", username="testuser",
email="testuser@example.com", email="testuser@example.com",
[PASSWORD-REMOVED]",
) )
user.set_password("testpass123") self.stdout.write(self.style.SUCCESS(f"Created test user: {user.username}"))
user.save()
self.stdout.write(
self.style.SUCCESS(f"Created test user: {user.get_username()}")
)
else: else:
self.stdout.write(self.style.WARNING("Test user already exists")) self.stdout.write(self.style.WARNING("Test user already exists"))
# Create moderator user
if not User.objects.filter(username="moderator").exists(): if not User.objects.filter(username="moderator").exists():
moderator = User.objects.create( moderator = User.objects.create_user(
username="moderator", username="moderator",
email="moderator@example.com", email="moderator@example.com",
[PASSWORD-REMOVED]",
) )
moderator.set_password("modpass123")
moderator.save()
# Create moderator group if it doesn't exist # Create moderator group if it doesn't exist
moderator_group, created = Group.objects.get_or_create(name="Moderators") moderator_group, created = Group.objects.get_or_create(name="Moderators")
@@ -48,9 +48,7 @@ class Command(BaseCommand):
moderator.groups.add(moderator_group) moderator.groups.add(moderator_group)
self.stdout.write( self.stdout.write(
self.style.SUCCESS( self.style.SUCCESS(f"Created moderator user: {moderator.username}")
f"Created moderator user: {moderator.get_username()}"
)
) )
else: else:
self.stdout.write(self.style.WARNING("Moderator user already exists")) self.stdout.write(self.style.WARNING("Moderator user already exists"))

View File

@@ -0,0 +1,10 @@
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Fix migration history by removing rides.0001_initial'
def handle(self, *args, **kwargs):
with connection.cursor() as cursor:
cursor.execute("DELETE FROM django_migrations WHERE app='rides' AND name='0001_initial';")
self.stdout.write(self.style.SUCCESS('Successfully removed rides.0001_initial from migration history'))

View File

@@ -0,0 +1,35 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site
import os
class Command(BaseCommand):
help = 'Fix social app configurations'
def handle(self, *args, **options):
# Delete all existing social apps
SocialApp.objects.all().delete()
self.stdout.write('Deleted all existing social apps')
# Get the default site
site = Site.objects.get(id=1)
# Create Google provider
google_app = SocialApp.objects.create(
provider='google',
name='Google',
client_id=os.getenv('GOOGLE_CLIENT_ID'),
secret=os.getenv('GOOGLE_CLIENT_SECRET'),
)
google_app.sites.add(site)
self.stdout.write(f'Created Google app with client_id: {google_app.client_id}')
# Create Discord provider
discord_app = SocialApp.objects.create(
provider='discord',
name='Discord',
client_id=os.getenv('DISCORD_CLIENT_ID'),
secret=os.getenv('DISCORD_CLIENT_SECRET'),
)
discord_app.sites.add(site)
self.stdout.write(f'Created Discord app with client_id: {discord_app.client_id}')

View File

@@ -1,8 +1,6 @@
import os
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
import os
def generate_avatar(letter): def generate_avatar(letter):
"""Generate an avatar for a given letter or number""" """Generate an avatar for a given letter or number"""
@@ -12,7 +10,7 @@ def generate_avatar(letter):
font_size = 100 font_size = 100
# Create a blank image with background color # Create a blank image with background color
image = Image.new("RGB", avatar_size, background_color) image = Image.new('RGB', avatar_size, background_color)
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
# Load a font # Load a font
@@ -21,14 +19,8 @@ def generate_avatar(letter):
# Calculate text size and position using textbbox # Calculate text size and position using textbbox
text_bbox = draw.textbbox((0, 0), letter, font=font) text_bbox = draw.textbbox((0, 0), letter, font=font)
text_width, text_height = ( text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
text_bbox[2] - text_bbox[0], text_position = ((avatar_size[0] - text_width) / 2, (avatar_size[1] - text_height) / 2)
text_bbox[3] - text_bbox[1],
)
text_position = (
(avatar_size[0] - text_width) / 2,
(avatar_size[1] - text_height) / 2,
)
# Draw the text on the image # Draw the text on the image
draw.text(text_position, letter, font=font, fill=text_color) draw.text(text_position, letter, font=font, fill=text_color)
@@ -42,14 +34,11 @@ def generate_avatar(letter):
avatar_path = os.path.join(avatar_dir, f"{letter}_avatar.png") avatar_path = os.path.join(avatar_dir, f"{letter}_avatar.png")
image.save(avatar_path) image.save(avatar_path)
class Command(BaseCommand): class Command(BaseCommand):
help = "Generate avatars for letters A-Z and numbers 0-9" help = 'Generate avatars for letters A-Z and numbers 0-9'
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
characters = [chr(i) for i in range(65, 91)] + [ characters = [chr(i) for i in range(65, 91)] + [str(i) for i in range(10)] # A-Z and 0-9
str(i) for i in range(10)
] # A-Z and 0-9
for char in characters: for char in characters:
generate_avatar(char) generate_avatar(char)
self.stdout.write(self.style.SUCCESS(f"Generated avatar for {char}")) self.stdout.write(self.style.SUCCESS(f"Generated avatar for {char}"))

View File

@@ -0,0 +1,11 @@
from django.core.management.base import BaseCommand
from accounts.models import UserProfile
class Command(BaseCommand):
help = 'Regenerate default avatars for users without an uploaded avatar'
def handle(self, *args, **kwargs):
profiles = UserProfile.objects.filter(avatar='')
for profile in profiles:
profile.save() # This will trigger the avatar generation logic in the save method
self.stdout.write(self.style.SUCCESS(f"Regenerated avatar for {profile.user.username}"))

View File

@@ -0,0 +1,85 @@
from django.core.management.base import BaseCommand
from django.db import connection
from django.contrib.auth.hashers import make_password
import uuid
class Command(BaseCommand):
help = 'Reset database and create admin user'
def handle(self, *args, **options):
self.stdout.write('Resetting database...')
# Drop all tables
with connection.cursor() as cursor:
cursor.execute("""
DO $$ DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
END LOOP;
END $$;
""")
# Reset sequences
cursor.execute("""
DO $$ DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT sequencename FROM pg_sequences WHERE schemaname = current_schema()) LOOP
EXECUTE 'ALTER SEQUENCE ' || quote_ident(r.sequencename) || ' RESTART WITH 1';
END LOOP;
END $$;
""")
self.stdout.write('All tables dropped and sequences reset.')
# Run migrations
from django.core.management import call_command
call_command('migrate')
self.stdout.write('Migrations applied.')
# Create superuser using raw SQL
try:
with connection.cursor() as cursor:
# Create user
user_id = str(uuid.uuid4())[:10]
cursor.execute("""
INSERT INTO accounts_user (
username, password, email, is_superuser, is_staff,
is_active, date_joined, user_id, first_name,
last_name, role, is_banned, ban_reason,
theme_preference
) VALUES (
'admin', %s, 'admin@thrillwiki.com', true, true,
true, NOW(), %s, '', '', 'SUPERUSER', false, '',
'light'
) RETURNING id;
""", [make_password('admin'), user_id])
user_db_id = cursor.fetchone()[0]
# Create profile
profile_id = str(uuid.uuid4())[:10]
cursor.execute("""
INSERT INTO accounts_userprofile (
profile_id, display_name, pronouns, bio,
twitter, instagram, youtube, discord,
coaster_credits, dark_ride_credits,
flat_ride_credits, water_ride_credits,
user_id, avatar
) VALUES (
%s, 'Admin', 'they/them', 'ThrillWiki Administrator',
'', '', '', '',
0, 0, 0, 0,
%s, ''
);
""", [profile_id, user_db_id])
self.stdout.write('Superuser created.')
except Exception as e:
self.stdout.write(self.style.ERROR(f'Error creating superuser: {str(e)}'))
raise
self.stdout.write(self.style.SUCCESS('Database reset complete.'))

View File

@@ -1,11 +1,10 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.db import connection from django.db import connection
class Command(BaseCommand): class Command(BaseCommand):
help = "Reset social apps configuration" help = 'Reset social apps configuration'
def handle(self, *args, **options): def handle(self, *args, **options):
# Delete all social apps using raw SQL to bypass Django's ORM # Delete all social apps using raw SQL to bypass Django's ORM
@@ -18,22 +17,20 @@ class Command(BaseCommand):
# Create Discord app # Create Discord app
discord_app = SocialApp.objects.create( discord_app = SocialApp.objects.create(
provider="discord", provider='discord',
name="Discord", name='Discord',
client_id="1299112802274902047", client_id='1299112802274902047',
secret="ece7Pe_M4mD4mYzAgcINjTEKL_3ftL11", secret='ece7Pe_M4mD4mYzAgcINjTEKL_3ftL11',
) )
discord_app.sites.add(site) discord_app.sites.add(site)
self.stdout.write(f"Created Discord app with ID: {discord_app.pk}") self.stdout.write(f'Created Discord app with ID: {discord_app.id}')
# Create Google app # Create Google app
google_app = SocialApp.objects.create( google_app = SocialApp.objects.create(
provider="google", provider='google',
name="Google", name='Google',
client_id=( client_id='135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com',
"135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com" secret='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',
),
secret="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",
) )
google_app.sites.add(site) google_app.sites.add(site)
self.stdout.write(f"Created Google app with ID: {google_app.pk}") self.stdout.write(f'Created Google app with ID: {google_app.id}')

View File

@@ -0,0 +1,17 @@
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Reset social auth configuration'
def handle(self, *args, **options):
with connection.cursor() as cursor:
# Delete all social apps
cursor.execute("DELETE FROM socialaccount_socialapp")
cursor.execute("DELETE FROM socialaccount_socialapp_sites")
# Reset sequences
cursor.execute("DELETE FROM sqlite_sequence WHERE name='socialaccount_socialapp'")
cursor.execute("DELETE FROM sqlite_sequence WHERE name='socialaccount_socialapp_sites'")
self.stdout.write(self.style.SUCCESS('Successfully reset social auth configuration'))

View File

@@ -1,15 +1,14 @@
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from apps.accounts.models import User from django.contrib.contenttypes.models import ContentType
from apps.accounts.signals import create_default_groups from accounts.models import User
from accounts.signals import create_default_groups
class Command(BaseCommand): class Command(BaseCommand):
help = "Set up default groups and permissions for user roles" help = 'Set up default groups and permissions for user roles'
def handle(self, *args, **options): def handle(self, *args, **options):
self.stdout.write("Creating default groups and permissions...") self.stdout.write('Creating default groups and permissions...')
try: try:
# Create default groups with permissions # Create default groups with permissions
@@ -30,16 +29,14 @@ class Command(BaseCommand):
user.is_staff = True user.is_staff = True
user.save() user.save()
self.stdout.write( self.stdout.write(self.style.SUCCESS('Successfully set up groups and permissions'))
self.style.SUCCESS("Successfully set up groups and permissions")
)
# Print summary # Print summary
for group in Group.objects.all(): for group in Group.objects.all():
self.stdout.write(f"\nGroup: {group.name}") self.stdout.write(f'\nGroup: {group.name}')
self.stdout.write("Permissions:") self.stdout.write('Permissions:')
for perm in group.permissions.all(): for perm in group.permissions.all():
self.stdout.write(f" - {perm.codename}") self.stdout.write(f' - {perm.codename}')
except Exception as e: except Exception as e:
self.stdout.write(self.style.ERROR(f"Error setting up groups: {str(e)}")) self.stdout.write(self.style.ERROR(f'Error setting up groups: {str(e)}'))

View File

@@ -1,9 +1,8 @@
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
class Command(BaseCommand): class Command(BaseCommand):
help = "Set up default site" help = 'Set up default site'
def handle(self, *args, **options): def handle(self, *args, **options):
# Delete any existing sites # Delete any existing sites
@@ -11,6 +10,8 @@ class Command(BaseCommand):
# Create default site # Create default site
site = Site.objects.create( site = Site.objects.create(
id=1, domain="localhost:8000", name="ThrillWiki Development" id=1,
domain='localhost:8000',
name='ThrillWiki Development'
) )
self.stdout.write(self.style.SUCCESS(f"Created site: {site.domain}")) self.stdout.write(self.style.SUCCESS(f'Created site: {site.domain}'))

View File

@@ -0,0 +1,63 @@
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp
from dotenv import load_dotenv
import os
class Command(BaseCommand):
help = 'Sets up social authentication apps'
def handle(self, *args, **kwargs):
# Load environment variables
load_dotenv()
# Get environment variables
google_client_id = os.getenv('GOOGLE_CLIENT_ID')
google_client_secret = os.getenv('GOOGLE_CLIENT_SECRET')
discord_client_id = os.getenv('DISCORD_CLIENT_ID')
discord_client_secret = os.getenv('DISCORD_CLIENT_SECRET')
if not all([google_client_id, google_client_secret, discord_client_id, discord_client_secret]):
self.stdout.write(self.style.ERROR('Missing required environment variables'))
return
# Get or create the default site
site, _ = Site.objects.get_or_create(
id=1,
defaults={
'domain': 'localhost:8000',
'name': 'localhost'
}
)
# Set up Google
google_app, created = SocialApp.objects.get_or_create(
provider='google',
defaults={
'name': 'Google',
'client_id': google_client_id,
'secret': google_client_secret,
}
)
if not created:
google_app.client_id = google_client_id
google_app.[SECRET-REMOVED]
google_app.save()
google_app.sites.add(site)
# Set up Discord
discord_app, created = SocialApp.objects.get_or_create(
provider='discord',
defaults={
'name': 'Discord',
'client_id': discord_client_id,
'secret': discord_client_secret,
}
)
if not created:
discord_app.client_id = discord_client_id
discord_app.[SECRET-REMOVED]
discord_app.save()
discord_app.sites.add(site)
self.stdout.write(self.style.SUCCESS('Successfully set up social auth apps'))

View File

@@ -1,47 +1,39 @@
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from allauth.socialaccount.models import SocialApp
User = get_user_model() User = get_user_model()
class Command(BaseCommand): class Command(BaseCommand):
help = "Set up social authentication through admin interface" help = 'Set up social authentication through admin interface'
def handle(self, *args, **options): def handle(self, *args, **options):
# Get or create the default site # Get or create the default site
site, _ = Site.objects.get_or_create( site, _ = Site.objects.get_or_create(
id=1, id=1,
defaults={ defaults={
"domain": "localhost:8000", 'domain': 'localhost:8000',
"name": "ThrillWiki Development", 'name': 'ThrillWiki Development'
}, }
) )
if not _: if not _:
site.domain = "localhost:8000" site.domain = 'localhost:8000'
site.name = "ThrillWiki Development" site.name = 'ThrillWiki Development'
site.save() site.save()
self.stdout.write(f"{'Created' if _ else 'Updated'} site: {site.domain}") self.stdout.write(f'{"Created" if _ else "Updated"} site: {site.domain}')
# Create superuser if it doesn't exist # Create superuser if it doesn't exist
if not User.objects.filter(username="admin").exists(): if not User.objects.filter(username='admin').exists():
admin_user = User.objects.create( User.objects.create_superuser('admin', 'admin@example.com', 'admin')
username="admin", self.stdout.write('Created superuser: admin/admin')
email="admin@example.com",
is_staff=True,
is_superuser=True,
)
admin_user.set_password("admin")
admin_user.save()
self.stdout.write("Created superuser: admin/admin")
self.stdout.write( self.stdout.write(self.style.SUCCESS('''
self.style.SUCCESS(
"""
Social auth setup instructions: Social auth setup instructions:
1. Run the development server: 1. Run the development server:
uv run manage.py runserver_plus python manage.py runserver
2. Go to the admin interface: 2. Go to the admin interface:
http://localhost:8000/admin/ http://localhost:8000/admin/
@@ -65,6 +57,4 @@ Social auth setup instructions:
Client id: 135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com Client id: 135166769591-nopcgmo0fkqfqfs9qe783a137mtmcrt2.apps.googleusercontent.com
Secret key: GOCSPX-Wd_0Ue0Ue0Ue0Ue0Ue0Ue0Ue0Ue Secret key: GOCSPX-Wd_0Ue0Ue0Ue0Ue0Ue0Ue0Ue0Ue
Sites: Add "localhost:8000" Sites: Add "localhost:8000"
""" '''))
)
)

View File

@@ -0,0 +1,60 @@
from django.core.management.base import BaseCommand
from django.urls import reverse
from django.test import Client
from allauth.socialaccount.models import SocialApp
from urllib.parse import urljoin
class Command(BaseCommand):
help = 'Test Discord OAuth2 authentication flow'
def handle(self, *args, **options):
client = Client(HTTP_HOST='localhost:8000')
# Get Discord app
try:
discord_app = SocialApp.objects.get(provider='discord')
self.stdout.write('Found Discord app configuration:')
self.stdout.write(f'Client ID: {discord_app.client_id}')
# Test login URL
login_url = '/accounts/discord/login/'
response = client.get(login_url, HTTP_HOST='localhost:8000')
self.stdout.write(f'\nTesting login URL: {login_url}')
self.stdout.write(f'Status code: {response.status_code}')
if response.status_code == 302:
redirect_url = response['Location']
self.stdout.write(f'Redirects to: {redirect_url}')
# Parse OAuth2 parameters
self.stdout.write('\nOAuth2 Parameters:')
if 'client_id=' in redirect_url:
self.stdout.write('✓ client_id parameter present')
if 'redirect_uri=' in redirect_url:
self.stdout.write('✓ redirect_uri parameter present')
if 'scope=' in redirect_url:
self.stdout.write('✓ scope parameter present')
if 'response_type=' in redirect_url:
self.stdout.write('✓ response_type parameter present')
if 'code_challenge=' in redirect_url:
self.stdout.write('✓ PKCE enabled (code_challenge present)')
# Show callback URL
callback_url = 'http://localhost:8000/accounts/discord/login/callback/'
self.stdout.write('\nCallback URL to configure in Discord Developer Portal:')
self.stdout.write(callback_url)
# Show frontend login URL
frontend_url = 'http://localhost:5173'
self.stdout.write('\nFrontend configuration:')
self.stdout.write(f'Frontend URL: {frontend_url}')
self.stdout.write('Discord login button should use:')
self.stdout.write('/accounts/discord/login/?process=login')
# Show allauth URLs
self.stdout.write('\nAllauth URLs:')
self.stdout.write('Login URL: /accounts/discord/login/?process=login')
self.stdout.write('Callback URL: /accounts/discord/login/callback/')
except SocialApp.DoesNotExist:
self.stdout.write(self.style.ERROR('Discord app not found'))

View File

@@ -1,10 +1,9 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
class Command(BaseCommand): class Command(BaseCommand):
help = "Update social apps to be associated with all sites" help = 'Update social apps to be associated with all sites'
def handle(self, *args, **options): def handle(self, *args, **options):
# Get all sites # Get all sites
@@ -12,12 +11,10 @@ class Command(BaseCommand):
# Update each social app # Update each social app
for app in SocialApp.objects.all(): for app in SocialApp.objects.all():
self.stdout.write(f"Updating {app.provider} app...") self.stdout.write(f'Updating {app.provider} app...')
# Clear existing sites # Clear existing sites
app.sites.clear() app.sites.clear()
# Add all sites # Add all sites
for site in sites: for site in sites:
app.sites.add(site) app.sites.add(site)
self.stdout.write( self.stdout.write(f'Added sites: {", ".join(site.domain for site in sites)}')
f"Added sites: {', '.join(site.domain for site in sites)}"
)

View File

@@ -0,0 +1,36 @@
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site
from django.urls import reverse
from django.conf import settings
class Command(BaseCommand):
help = 'Verify Discord OAuth2 settings'
def handle(self, *args, **options):
# Get Discord app
try:
discord_app = SocialApp.objects.get(provider='discord')
self.stdout.write('Found Discord app configuration:')
self.stdout.write(f'Client ID: {discord_app.client_id}')
self.stdout.write(f'Secret: {discord_app.secret}')
# Get sites
sites = discord_app.sites.all()
self.stdout.write('\nAssociated sites:')
for site in sites:
self.stdout.write(f'- {site.domain} ({site.name})')
# Show callback URL
callback_url = 'http://localhost:8000/accounts/discord/login/callback/'
self.stdout.write('\nCallback URL to configure in Discord Developer Portal:')
self.stdout.write(callback_url)
# Show OAuth2 settings
self.stdout.write('\nOAuth2 settings in settings.py:')
discord_settings = settings.SOCIALACCOUNT_PROVIDERS.get('discord', {})
self.stdout.write(f'PKCE Enabled: {discord_settings.get("OAUTH_PKCE_ENABLED", False)}')
self.stdout.write(f'Scopes: {discord_settings.get("SCOPE", [])}')
except SocialApp.DoesNotExist:
self.stdout.write(self.style.ERROR('Discord app not found'))

View File

@@ -11,6 +11,7 @@ from django.db import migrations, models
class Migration(migrations.Migration): class Migration(migrations.Migration):
initial = True initial = True
dependencies = [ dependencies = [
@@ -32,10 +33,7 @@ class Migration(migrations.Migration):
verbose_name="ID", verbose_name="ID",
), ),
), ),
( ("password", models.CharField(max_length=128, verbose_name="password")),
"password",
models.CharField(max_length=128, verbose_name="password"),
),
( (
"last_login", "last_login",
models.DateTimeField( models.DateTimeField(
@@ -80,9 +78,7 @@ class Migration(migrations.Migration):
( (
"email", "email",
models.EmailField( models.EmailField(
blank=True, blank=True, max_length=254, verbose_name="email address"
max_length=254,
verbose_name="email address",
), ),
), ),
( (
@@ -104,8 +100,7 @@ class Migration(migrations.Migration):
( (
"date_joined", "date_joined",
models.DateTimeField( models.DateTimeField(
default=django.utils.timezone.now, default=django.utils.timezone.now, verbose_name="date joined"
verbose_name="date joined",
), ),
), ),
( (
@@ -279,10 +274,7 @@ class Migration(migrations.Migration):
migrations.CreateModel( migrations.CreateModel(
name="TopListEvent", name="TopListEvent",
fields=[ fields=[
( ("pgh_id", models.AutoField(primary_key=True, serialize=False)),
"pgh_id",
models.AutoField(primary_key=True, serialize=False),
),
("pgh_created_at", models.DateTimeField(auto_now_add=True)), ("pgh_created_at", models.DateTimeField(auto_now_add=True)),
("pgh_label", models.TextField(help_text="The event label.")), ("pgh_label", models.TextField(help_text="The event label.")),
("id", models.BigIntegerField()), ("id", models.BigIntegerField()),
@@ -377,10 +369,7 @@ class Migration(migrations.Migration):
migrations.CreateModel( migrations.CreateModel(
name="TopListItemEvent", name="TopListItemEvent",
fields=[ fields=[
( ("pgh_id", models.AutoField(primary_key=True, serialize=False)),
"pgh_id",
models.AutoField(primary_key=True, serialize=False),
),
("pgh_created_at", models.DateTimeField(auto_now_add=True)), ("pgh_created_at", models.DateTimeField(auto_now_add=True)),
("pgh_label", models.TextField(help_text="The event label.")), ("pgh_label", models.TextField(help_text="The event label.")),
("id", models.BigIntegerField()), ("id", models.BigIntegerField()),
@@ -462,10 +451,7 @@ class Migration(migrations.Migration):
unique=True, unique=True,
), ),
), ),
( ("avatar", models.ImageField(blank=True, upload_to="avatars/")),
"avatar",
models.ImageField(blank=True, upload_to="avatars/"),
),
("pronouns", models.CharField(blank=True, max_length=50)), ("pronouns", models.CharField(blank=True, max_length=50)),
("bio", models.TextField(blank=True, max_length=500)), ("bio", models.TextField(blank=True, max_length=500)),
("twitter", models.URLField(blank=True)), ("twitter", models.URLField(blank=True)),

33
accounts/mixins.py Normal file
View File

@@ -0,0 +1,33 @@
import requests
from django.conf import settings
from django.core.exceptions import ValidationError
class TurnstileMixin:
"""
Mixin to handle Cloudflare Turnstile validation.
Bypasses validation when DEBUG is True.
"""
def validate_turnstile(self, request):
"""
Validate the Turnstile response token.
Skips validation when DEBUG is True.
"""
if settings.DEBUG:
return
token = request.POST.get('cf-turnstile-response')
if not token:
raise ValidationError('Please complete the Turnstile challenge.')
# Verify the token with Cloudflare
data = {
'secret': settings.TURNSTILE_SECRET_KEY,
'response': token,
'remoteip': request.META.get('REMOTE_ADDR'),
}
response = requests.post(settings.TURNSTILE_VERIFY_URL, data=data, timeout=60)
result = response.json()
if not result.get('success'):
raise ValidationError('Turnstile validation failed. Please try again.')

212
accounts/models.py Normal file
View File

@@ -0,0 +1,212 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import base64
import os
import secrets
from core.history import TrackedModel
# import pghistory
def generate_random_id(model_class, id_field):
"""Generate a random ID starting at 4 digits, expanding to 5 if needed"""
while True:
# Try to get a 4-digit number first
new_id = str(secrets.SystemRandom().randint(1000, 9999))
if not model_class.objects.filter(**{id_field: new_id}).exists():
return new_id
# If all 4-digit numbers are taken, try 5 digits
new_id = str(secrets.SystemRandom().randint(10000, 99999))
if not model_class.objects.filter(**{id_field: new_id}).exists():
return new_id
class User(AbstractUser):
class Roles(models.TextChoices):
USER = 'USER', _('User')
MODERATOR = 'MODERATOR', _('Moderator')
ADMIN = 'ADMIN', _('Admin')
SUPERUSER = 'SUPERUSER', _('Superuser')
class ThemePreference(models.TextChoices):
LIGHT = 'light', _('Light')
DARK = 'dark', _('Dark')
# Read-only ID
user_id = models.CharField(
max_length=10,
unique=True,
editable=False,
help_text='Unique identifier for this user that remains constant even if the username changes'
)
role = models.CharField(
max_length=10,
choices=Roles.choices,
default=Roles.USER,
)
is_banned = models.BooleanField(default=False)
ban_reason = models.TextField(blank=True)
ban_date = models.DateTimeField(null=True, blank=True)
pending_email = models.EmailField(blank=True, null=True)
theme_preference = models.CharField(
max_length=5,
choices=ThemePreference.choices,
default=ThemePreference.LIGHT,
)
def __str__(self):
return self.get_display_name()
def get_absolute_url(self):
return reverse('profile', kwargs={'username': self.username})
def get_display_name(self):
"""Get the user's display name, falling back to username if not set"""
profile = getattr(self, 'profile', None)
if profile and profile.display_name:
return profile.display_name
return self.username
def save(self, *args, **kwargs):
if not self.user_id:
self.user_id = generate_random_id(User, 'user_id')
super().save(*args, **kwargs)
class UserProfile(models.Model):
# Read-only ID
profile_id = models.CharField(
max_length=10,
unique=True,
editable=False,
help_text='Unique identifier for this profile that remains constant'
)
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
related_name='profile'
)
display_name = models.CharField(
max_length=50,
unique=True,
help_text="This is the name that will be displayed on the site"
)
avatar = models.ImageField(upload_to='avatars/', blank=True)
pronouns = models.CharField(max_length=50, blank=True)
bio = models.TextField(max_length=500, blank=True)
# Social media links
twitter = models.URLField(blank=True)
instagram = models.URLField(blank=True)
youtube = models.URLField(blank=True)
discord = models.CharField(max_length=100, blank=True)
# Ride statistics
coaster_credits = models.IntegerField(default=0)
dark_ride_credits = models.IntegerField(default=0)
flat_ride_credits = models.IntegerField(default=0)
water_ride_credits = models.IntegerField(default=0)
def get_avatar(self):
"""Return the avatar URL or serve a pre-generated avatar based on the first letter of the username"""
if self.avatar:
return self.avatar.url
first_letter = self.user.username.upper()
avatar_path = f"avatars/letters/{first_letter}_avatar.png"
if os.path.exists(avatar_path):
return f"/{avatar_path}"
return "/static/images/default-avatar.png"
def save(self, *args, **kwargs):
# If no display name is set, use the username
if not self.display_name:
self.display_name = self.user.username
if not self.profile_id:
self.profile_id = generate_random_id(UserProfile, 'profile_id')
super().save(*args, **kwargs)
def __str__(self):
return self.display_name
class EmailVerification(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
token = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_sent = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Email verification for {self.user.username}"
class Meta:
verbose_name = "Email Verification"
verbose_name_plural = "Email Verifications"
class PasswordReset(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
token = models.CharField(max_length=64)
created_at = models.DateTimeField(auto_now_add=True)
expires_at = models.DateTimeField()
used = models.BooleanField(default=False)
def __str__(self):
return f"Password reset for {self.user.username}"
class Meta:
verbose_name = "Password Reset"
verbose_name_plural = "Password Resets"
# @pghistory.track()
class TopList(TrackedModel):
class Categories(models.TextChoices):
ROLLER_COASTER = 'RC', _('Roller Coaster')
DARK_RIDE = 'DR', _('Dark Ride')
FLAT_RIDE = 'FR', _('Flat Ride')
WATER_RIDE = 'WR', _('Water Ride')
PARK = 'PK', _('Park')
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='top_lists' # Added related_name for User model access
)
title = models.CharField(max_length=100)
category = models.CharField(
max_length=2,
choices=Categories.choices
)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-updated_at']
def __str__(self):
return f"{self.user.get_display_name()}'s {self.category} Top List: {self.title}"
# @pghistory.track()
class TopListItem(TrackedModel):
top_list = models.ForeignKey(
TopList,
on_delete=models.CASCADE,
related_name='items'
)
content_type = models.ForeignKey(
'contenttypes.ContentType',
on_delete=models.CASCADE
)
object_id = models.PositiveIntegerField()
rank = models.PositiveIntegerField()
notes = models.TextField(blank=True)
class Meta:
ordering = ['rank']
unique_together = [['top_list', 'rank']]
def __str__(self):
return f"#{self.rank} in {self.top_list.title}"

212
accounts/models_temp.py Normal file
View File

@@ -0,0 +1,212 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import base64
import os
import secrets
from core.history import TrackedModel
import pghistory
def generate_random_id(model_class, id_field):
"""Generate a random ID starting at 4 digits, expanding to 5 if needed"""
while True:
# Try to get a 4-digit number first
new_id = str(secrets.SystemRandom().randint(1000, 9999))
if not model_class.objects.filter(**{id_field: new_id}).exists():
return new_id
# If all 4-digit numbers are taken, try 5 digits
new_id = str(secrets.SystemRandom().randint(10000, 99999))
if not model_class.objects.filter(**{id_field: new_id}).exists():
return new_id
class User(AbstractUser):
class Roles(models.TextChoices):
USER = 'USER', _('User')
MODERATOR = 'MODERATOR', _('Moderator')
ADMIN = 'ADMIN', _('Admin')
SUPERUSER = 'SUPERUSER', _('Superuser')
class ThemePreference(models.TextChoices):
LIGHT = 'light', _('Light')
DARK = 'dark', _('Dark')
# Read-only ID
user_id = models.CharField(
max_length=10,
unique=True,
editable=False,
help_text='Unique identifier for this user that remains constant even if the username changes'
)
role = models.CharField(
max_length=10,
choices=Roles.choices,
default=Roles.USER,
)
is_banned = models.BooleanField(default=False)
ban_reason = models.TextField(blank=True)
ban_date = models.DateTimeField(null=True, blank=True)
pending_email = models.EmailField(blank=True, null=True)
theme_preference = models.CharField(
max_length=5,
choices=ThemePreference.choices,
default=ThemePreference.LIGHT,
)
def __str__(self):
return self.get_display_name()
def get_absolute_url(self):
return reverse('profile', kwargs={'username': self.username})
def get_display_name(self):
"""Get the user's display name, falling back to username if not set"""
profile = getattr(self, 'profile', None)
if profile and profile.display_name:
return profile.display_name
return self.username
def save(self, *args, **kwargs):
if not self.user_id:
self.user_id = generate_random_id(User, 'user_id')
super().save(*args, **kwargs)
class UserProfile(models.Model):
# Read-only ID
profile_id = models.CharField(
max_length=10,
unique=True,
editable=False,
help_text='Unique identifier for this profile that remains constant'
)
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
related_name='profile'
)
display_name = models.CharField(
max_length=50,
unique=True,
help_text="This is the name that will be displayed on the site"
)
avatar = models.ImageField(upload_to='avatars/', blank=True)
pronouns = models.CharField(max_length=50, blank=True)
bio = models.TextField(max_length=500, blank=True)
# Social media links
twitter = models.URLField(blank=True)
instagram = models.URLField(blank=True)
youtube = models.URLField(blank=True)
discord = models.CharField(max_length=100, blank=True)
# Ride statistics
coaster_credits = models.IntegerField(default=0)
dark_ride_credits = models.IntegerField(default=0)
flat_ride_credits = models.IntegerField(default=0)
water_ride_credits = models.IntegerField(default=0)
def get_avatar(self):
"""Return the avatar URL or serve a pre-generated avatar based on the first letter of the username"""
if self.avatar:
return self.avatar.url
first_letter = self.user.username[0].upper()
avatar_path = f"avatars/letters/{first_letter}_avatar.png"
if os.path.exists(avatar_path):
return f"/{avatar_path}"
return "/static/images/default-avatar.png"
def save(self, *args, **kwargs):
# If no display name is set, use the username
if not self.display_name:
self.display_name = self.user.username
if not self.profile_id:
self.profile_id = generate_random_id(UserProfile, 'profile_id')
super().save(*args, **kwargs)
def __str__(self):
return self.display_name
class EmailVerification(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
token = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_sent = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Email verification for {self.user.username}"
class Meta:
verbose_name = "Email Verification"
verbose_name_plural = "Email Verifications"
class PasswordReset(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
token = models.CharField(max_length=64)
created_at = models.DateTimeField(auto_now_add=True)
expires_at = models.DateTimeField()
used = models.BooleanField(default=False)
def __str__(self):
return f"Password reset for {self.user.username}"
class Meta:
verbose_name = "Password Reset"
verbose_name_plural = "Password Resets"
@pghistory.track()
class TopList(TrackedModel):
class Categories(models.TextChoices):
ROLLER_COASTER = 'RC', _('Roller Coaster')
DARK_RIDE = 'DR', _('Dark Ride')
FLAT_RIDE = 'FR', _('Flat Ride')
WATER_RIDE = 'WR', _('Water Ride')
PARK = 'PK', _('Park')
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='top_lists' # Added related_name for User model access
)
title = models.CharField(max_length=100)
category = models.CharField(
max_length=2,
choices=Categories.choices
)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-updated_at']
def __str__(self):
return f"{self.user.get_display_name()}'s {self.category} Top List: {self.title}"
@pghistory.track()
class TopListItem(TrackedModel):
top_list = models.ForeignKey(
TopList,
on_delete=models.CASCADE,
related_name='items'
)
content_type = models.ForeignKey(
'contenttypes.ContentType',
on_delete=models.CASCADE
)
object_id = models.PositiveIntegerField()
rank = models.PositiveIntegerField()
notes = models.TextField(blank=True)
class Meta:
ordering = ['rank']
unique_together = [['top_list', 'rank']]
def __str__(self):
return f"#{self.rank} in {self.top_list.title}"

226
accounts/selectors.py Normal file
View File

@@ -0,0 +1,226 @@
"""
Selectors for user and account-related data retrieval.
Following Django styleguide pattern for separating data access from business logic.
"""
from typing import Optional, Dict, Any, List
from django.db.models import QuerySet, Q, F, Count, Avg, Prefetch
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import timedelta
User = get_user_model()
def user_profile_optimized(*, user_id: int) -> Any:
"""
Get a user with optimized queries for profile display.
Args:
user_id: User ID
Returns:
User instance with prefetched related data
Raises:
User.DoesNotExist: If user doesn't exist
"""
return User.objects.prefetch_related(
'park_reviews',
'ride_reviews',
'socialaccount_set'
).annotate(
park_review_count=Count('park_reviews', filter=Q(park_reviews__is_published=True)),
ride_review_count=Count('ride_reviews', filter=Q(ride_reviews__is_published=True)),
total_review_count=F('park_review_count') + F('ride_review_count')
).get(id=user_id)
def active_users_with_stats() -> QuerySet:
"""
Get active users with review statistics.
Returns:
QuerySet of active users with review counts
"""
return User.objects.filter(
is_active=True
).annotate(
park_review_count=Count('park_reviews', filter=Q(park_reviews__is_published=True)),
ride_review_count=Count('ride_reviews', filter=Q(ride_reviews__is_published=True)),
total_review_count=F('park_review_count') + F('ride_review_count')
).order_by('-total_review_count')
def users_with_recent_activity(*, days: int = 30) -> QuerySet:
"""
Get users who have been active in the last N days.
Args:
days: Number of days to look back for activity
Returns:
QuerySet of recently active users
"""
cutoff_date = timezone.now() - timedelta(days=days)
return User.objects.filter(
Q(last_login__gte=cutoff_date) |
Q(park_reviews__created_at__gte=cutoff_date) |
Q(ride_reviews__created_at__gte=cutoff_date)
).annotate(
recent_park_reviews=Count('park_reviews', filter=Q(park_reviews__created_at__gte=cutoff_date)),
recent_ride_reviews=Count('ride_reviews', filter=Q(ride_reviews__created_at__gte=cutoff_date)),
recent_total_reviews=F('recent_park_reviews') + F('recent_ride_reviews')
).order_by('-last_login').distinct()
def top_reviewers(*, limit: int = 10) -> QuerySet:
"""
Get top users by review count.
Args:
limit: Maximum number of users to return
Returns:
QuerySet of top reviewers
"""
return User.objects.filter(
is_active=True
).annotate(
park_review_count=Count('park_reviews', filter=Q(park_reviews__is_published=True)),
ride_review_count=Count('ride_reviews', filter=Q(ride_reviews__is_published=True)),
total_review_count=F('park_review_count') + F('ride_review_count')
).filter(
total_review_count__gt=0
).order_by('-total_review_count')[:limit]
def moderator_users() -> QuerySet:
"""
Get users with moderation permissions.
Returns:
QuerySet of users who can moderate content
"""
return User.objects.filter(
Q(is_staff=True) |
Q(groups__name='Moderators') |
Q(user_permissions__codename__in=['change_parkreview', 'change_ridereview'])
).distinct().order_by('username')
def users_by_registration_date(*, start_date, end_date) -> QuerySet:
"""
Get users who registered within a date range.
Args:
start_date: Start of date range
end_date: End of date range
Returns:
QuerySet of users registered in the date range
"""
return User.objects.filter(
date_joined__date__gte=start_date,
date_joined__date__lte=end_date
).order_by('-date_joined')
def user_search_autocomplete(*, query: str, limit: int = 10) -> QuerySet:
"""
Get users matching a search query for autocomplete functionality.
Args:
query: Search string
limit: Maximum number of results
Returns:
QuerySet of matching users for autocomplete
"""
return User.objects.filter(
Q(username__icontains=query) |
Q(first_name__icontains=query) |
Q(last_name__icontains=query),
is_active=True
).order_by('username')[:limit]
def users_with_social_accounts() -> QuerySet:
"""
Get users who have connected social accounts.
Returns:
QuerySet of users with social account connections
"""
return User.objects.filter(
socialaccount__isnull=False
).prefetch_related(
'socialaccount_set'
).distinct().order_by('username')
def user_statistics_summary() -> Dict[str, Any]:
"""
Get overall user statistics for dashboard/analytics.
Returns:
Dictionary containing user statistics
"""
total_users = User.objects.count()
active_users = User.objects.filter(is_active=True).count()
staff_users = User.objects.filter(is_staff=True).count()
# Users with reviews
users_with_reviews = User.objects.filter(
Q(park_reviews__isnull=False) |
Q(ride_reviews__isnull=False)
).distinct().count()
# Recent registrations (last 30 days)
cutoff_date = timezone.now() - timedelta(days=30)
recent_registrations = User.objects.filter(
date_joined__gte=cutoff_date
).count()
return {
'total_users': total_users,
'active_users': active_users,
'inactive_users': total_users - active_users,
'staff_users': staff_users,
'users_with_reviews': users_with_reviews,
'recent_registrations': recent_registrations,
'review_participation_rate': (users_with_reviews / total_users * 100) if total_users > 0 else 0
}
def users_needing_email_verification() -> QuerySet:
"""
Get users who haven't verified their email addresses.
Returns:
QuerySet of users with unverified emails
"""
return User.objects.filter(
is_active=True,
emailaddress__verified=False
).distinct().order_by('date_joined')
def users_by_review_activity(*, min_reviews: int = 1) -> QuerySet:
"""
Get users who have written at least a minimum number of reviews.
Args:
min_reviews: Minimum number of reviews required
Returns:
QuerySet of users with sufficient review activity
"""
return User.objects.annotate(
park_review_count=Count('park_reviews', filter=Q(park_reviews__is_published=True)),
ride_review_count=Count('ride_reviews', filter=Q(ride_reviews__is_published=True)),
total_review_count=F('park_review_count') + F('ride_review_count')
).filter(
total_review_count__gte=min_reviews
).order_by('-total_review_count')

View File

@@ -1,15 +1,11 @@
import requests
from django.contrib.auth.models import Group
from django.contrib.auth.signals import user_logged_in
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.db import transaction
from django.db.models.signals import post_save, pre_save from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver from django.dispatch import receiver
from django.contrib.auth.models import Group
from .login_history import LoginHistory from django.db import transaction
from .models import User, UserProfile from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
import requests
from .models import User, UserProfile, EmailVerification
@receiver(post_save, sender=User) @receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs): def create_user_profile(sender, instance, created, **kwargs):
@@ -25,13 +21,13 @@ def create_user_profile(sender, instance, created, **kwargs):
extra_data = social_account.extra_data extra_data = social_account.extra_data
avatar_url = None avatar_url = None
if social_account.provider == "google": if social_account.provider == 'google':
avatar_url = extra_data.get("picture") avatar_url = extra_data.get('picture')
elif social_account.provider == "discord": elif social_account.provider == 'discord':
avatar = extra_data.get("avatar") avatar = extra_data.get('avatar')
discord_id = extra_data.get("id") discord_id = extra_data.get('id')
if avatar: if avatar:
avatar_url = f"https://cdn.discordapp.com/avatars/{discord_id}/{avatar}.png" avatar_url = f'https://cdn.discordapp.com/avatars/{discord_id}/{avatar}.png'
if avatar_url: if avatar_url:
try: try:
@@ -42,32 +38,26 @@ def create_user_profile(sender, instance, created, **kwargs):
img_temp.flush() img_temp.flush()
file_name = f"avatar_{instance.username}.png" file_name = f"avatar_{instance.username}.png"
profile.avatar.save(file_name, File(img_temp), save=True) profile.avatar.save(
except Exception as e: file_name,
print( File(img_temp),
f"Error downloading avatar for user {instance.username}: { save=True
str(e)
}"
) )
except Exception as e:
print(f"Error downloading avatar for user {instance.username}: {str(e)}")
except Exception as e: except Exception as e:
print(f"Error creating profile for user {instance.username}: {str(e)}") print(f"Error creating profile for user {instance.username}: {str(e)}")
@receiver(post_save, sender=User) @receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs): def save_user_profile(sender, instance, **kwargs):
"""Ensure UserProfile exists and is saved""" """Ensure UserProfile exists and is saved"""
try: try:
# Try to get existing profile first if not hasattr(instance, 'profile'):
try:
profile = instance.profile
profile.save()
except UserProfile.DoesNotExist:
# Profile doesn't exist, create it
UserProfile.objects.create(user=instance) UserProfile.objects.create(user=instance)
instance.profile.save()
except Exception as e: except Exception as e:
print(f"Error saving profile for user {instance.username}: {str(e)}") print(f"Error saving profile for user {instance.username}: {str(e)}")
@receiver(pre_save, sender=User) @receiver(pre_save, sender=User)
def sync_user_role_with_groups(sender, instance, **kwargs): def sync_user_role_with_groups(sender, instance, **kwargs):
"""Sync user role with Django groups""" """Sync user role with Django groups"""
@@ -93,36 +83,22 @@ def sync_user_role_with_groups(sender, instance, **kwargs):
instance.is_superuser = True instance.is_superuser = True
instance.is_staff = True instance.is_staff = True
elif old_instance.role == User.Roles.SUPERUSER: elif old_instance.role == User.Roles.SUPERUSER:
# If removing superuser role, remove superuser # If removing superuser role, remove superuser status
# status
instance.is_superuser = False instance.is_superuser = False
if instance.role not in [ if instance.role not in [User.Roles.ADMIN, User.Roles.MODERATOR]:
User.Roles.ADMIN,
User.Roles.MODERATOR,
]:
instance.is_staff = False instance.is_staff = False
# Handle staff status for admin and moderator roles # Handle staff status for admin and moderator roles
if instance.role in [ if instance.role in [User.Roles.ADMIN, User.Roles.MODERATOR]:
User.Roles.ADMIN,
User.Roles.MODERATOR,
]:
instance.is_staff = True instance.is_staff = True
elif old_instance.role in [ elif old_instance.role in [User.Roles.ADMIN, User.Roles.MODERATOR]:
User.Roles.ADMIN, # If removing admin/moderator role, remove staff status
User.Roles.MODERATOR,
]:
# If removing admin/moderator role, remove staff
# status
if instance.role not in [User.Roles.SUPERUSER]: if instance.role not in [User.Roles.SUPERUSER]:
instance.is_staff = False instance.is_staff = False
except User.DoesNotExist: except User.DoesNotExist:
pass pass
except Exception as e: except Exception as e:
print( print(f"Error syncing role with groups for user {instance.username}: {str(e)}")
f"Error syncing role with groups for user {instance.username}: {str(e)}"
)
def create_default_groups(): def create_default_groups():
""" """
@@ -131,45 +107,31 @@ def create_default_groups():
""" """
try: try:
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
# Create Moderator group # Create Moderator group
moderator_group, _ = Group.objects.get_or_create(name=User.Roles.MODERATOR) moderator_group, _ = Group.objects.get_or_create(name=User.Roles.MODERATOR)
moderator_permissions = [ moderator_permissions = [
# Review moderation permissions # Review moderation permissions
"change_review", 'change_review', 'delete_review',
"delete_review", 'change_reviewreport', 'delete_reviewreport',
"change_reviewreport",
"delete_reviewreport",
# Edit moderation permissions # Edit moderation permissions
"change_parkedit", 'change_parkedit', 'delete_parkedit',
"delete_parkedit", 'change_rideedit', 'delete_rideedit',
"change_rideedit", 'change_companyedit', 'delete_companyedit',
"delete_rideedit", 'change_manufactureredit', 'delete_manufactureredit',
"change_companyedit",
"delete_companyedit",
"change_manufactureredit",
"delete_manufactureredit",
] ]
# Create Admin group # Create Admin group
admin_group, _ = Group.objects.get_or_create(name=User.Roles.ADMIN) admin_group, _ = Group.objects.get_or_create(name=User.Roles.ADMIN)
admin_permissions = moderator_permissions + [ admin_permissions = moderator_permissions + [
# User management permissions # User management permissions
"change_user", 'change_user', 'delete_user',
"delete_user",
# Content management permissions # Content management permissions
"add_park", 'add_park', 'change_park', 'delete_park',
"change_park", 'add_ride', 'change_ride', 'delete_ride',
"delete_park", 'add_company', 'change_company', 'delete_company',
"add_ride", 'add_manufacturer', 'change_manufacturer', 'delete_manufacturer',
"change_ride",
"delete_ride",
"add_company",
"change_company",
"delete_company",
"add_manufacturer",
"change_manufacturer",
"delete_manufacturer",
] ]
# Assign permissions to groups # Assign permissions to groups
@@ -188,41 +150,3 @@ def create_default_groups():
print(f"Permission not found: {codename}") print(f"Permission not found: {codename}")
except Exception as e: except Exception as e:
print(f"Error creating default groups: {str(e)}") print(f"Error creating default groups: {str(e)}")
@receiver(user_logged_in)
def log_successful_login(sender, user, request, **kwargs):
"""
Log successful login events to LoginHistory.
This signal handler captures the IP address, user agent, and login method
for auditing and security purposes.
"""
try:
# Get IP address
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
ip_address = x_forwarded_for.split(',')[0].strip() if x_forwarded_for else request.META.get('REMOTE_ADDR')
# Get user agent
user_agent = request.META.get('HTTP_USER_AGENT', '')[:500]
# Determine login method from session or request
login_method = 'PASSWORD'
if hasattr(request, 'session'):
sociallogin = getattr(request, '_sociallogin', None)
if sociallogin:
provider = sociallogin.account.provider.upper()
if provider in ['GOOGLE', 'DISCORD']:
login_method = provider
# Create login history entry
LoginHistory.objects.create(
user=user,
ip_address=ip_address,
user_agent=user_agent,
login_method=login_method,
success=True,
)
except Exception as e:
# Don't let login history failure prevent login
print(f"Error logging login history for user {user.username}: {str(e)}")

View File

@@ -4,7 +4,6 @@ from django.template.loader import render_to_string
register = template.Library() register = template.Library()
@register.simple_tag @register.simple_tag
def turnstile_widget(): def turnstile_widget():
""" """
@@ -14,10 +13,12 @@ def turnstile_widget():
Usage: {% load turnstile_tags %}{% turnstile_widget %} Usage: {% load turnstile_tags %}{% turnstile_widget %}
""" """
if settings.DEBUG: if settings.DEBUG:
template_name = "accounts/turnstile_widget_empty.html" template_name = 'accounts/turnstile_widget_empty.html'
context = {} context = {}
else: else:
template_name = "accounts/turnstile_widget.html" template_name = 'accounts/turnstile_widget.html'
context = {"site_key": settings.TURNSTILE_SITE_KEY} context = {
'site_key': settings.TURNSTILE_SITE_KEY
}
return render_to_string(template_name, context) return render_to_string(template_name, context)

91
accounts/tests.py Normal file
View File

@@ -0,0 +1,91 @@
from django.test import TestCase
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from unittest.mock import patch, MagicMock
from .models import User, UserProfile
from .signals import create_default_groups
class SignalsTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username='testuser',
email='testuser@example.com',
password='password'
)
def test_create_user_profile(self):
self.assertTrue(hasattr(self.user, 'profile'))
self.assertIsInstance(self.user.profile, UserProfile)
@patch('accounts.signals.requests.get')
def test_create_user_profile_with_social_avatar(self, mock_get):
# Mock the response from requests.get
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.content = b'fake-image-content'
mock_get.return_value = mock_response
# Create a social account for the user
social_account = self.user.socialaccount_set.create(
provider='google',
extra_data={'picture': 'http://example.com/avatar.png'}
)
# The signal should have been triggered when the user was created,
# but we can trigger it again to test the avatar download
from .signals import create_user_profile
create_user_profile(sender=User, instance=self.user, created=True)
self.user.profile.refresh_from_db()
self.assertTrue(self.user.profile.avatar.name.startswith('avatars/avatar_testuser'))
def test_save_user_profile(self):
self.user.profile.delete()
self.assertFalse(hasattr(self.user, 'profile'))
self.user.save()
self.assertTrue(hasattr(self.user, 'profile'))
self.assertIsInstance(self.user.profile, UserProfile)
def test_sync_user_role_with_groups(self):
self.user.role = User.Roles.MODERATOR
self.user.save()
self.assertTrue(self.user.groups.filter(name=User.Roles.MODERATOR).exists())
self.assertTrue(self.user.is_staff)
self.user.role = User.Roles.ADMIN
self.user.save()
self.assertFalse(self.user.groups.filter(name=User.Roles.MODERATOR).exists())
self.assertTrue(self.user.groups.filter(name=User.Roles.ADMIN).exists())
self.assertTrue(self.user.is_staff)
self.user.role = User.Roles.SUPERUSER
self.user.save()
self.assertFalse(self.user.groups.filter(name=User.Roles.ADMIN).exists())
self.assertTrue(self.user.groups.filter(name=User.Roles.SUPERUSER).exists())
self.assertTrue(self.user.is_superuser)
self.assertTrue(self.user.is_staff)
self.user.role = User.Roles.USER
self.user.save()
self.assertFalse(self.user.groups.exists())
self.assertFalse(self.user.is_superuser)
self.assertFalse(self.user.is_staff)
def test_create_default_groups(self):
# Create some permissions for testing
content_type = ContentType.objects.get_for_model(User)
Permission.objects.create(codename='change_review', name='Can change review', content_type=content_type)
Permission.objects.create(codename='delete_review', name='Can delete review', content_type=content_type)
Permission.objects.create(codename='change_user', name='Can change user', content_type=content_type)
create_default_groups()
moderator_group = Group.objects.get(name=User.Roles.MODERATOR)
self.assertIsNotNone(moderator_group)
self.assertTrue(moderator_group.permissions.filter(codename='change_review').exists())
self.assertFalse(moderator_group.permissions.filter(codename='change_user').exists())
admin_group = Group.objects.get(name=User.Roles.ADMIN)
self.assertIsNotNone(admin_group)
self.assertTrue(admin_group.permissions.filter(codename='change_review').exists())
self.assertTrue(admin_group.permissions.filter(codename='change_user').exists())

25
accounts/urls.py Normal file
View File

@@ -0,0 +1,25 @@
from django.urls import path
from django.contrib.auth import views as auth_views
from allauth.account.views import LogoutView
from . import views
app_name = 'accounts'
urlpatterns = [
# Override allauth's login and signup views with our Turnstile-enabled versions
path('login/', views.CustomLoginView.as_view(), name='account_login'),
path('signup/', views.CustomSignupView.as_view(), name='account_signup'),
# Authentication views
path('logout/', LogoutView.as_view(), name='logout'),
path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
# Profile views
path('profile/', views.user_redirect_view, name='profile_redirect'),
path('settings/', views.SettingsView.as_view(), name='settings'),
]

391
accounts/views.py Normal file
View File

@@ -0,0 +1,391 @@
from django.views.generic import DetailView, TemplateView
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.core.exceptions import ValidationError
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.discord.views import DiscordOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.crypto import get_random_string
from django.utils import timezone
from datetime import timedelta
from django.contrib.sites.shortcuts import get_current_site
from django.db.models import Prefetch, QuerySet
from django.http import HttpResponseRedirect, HttpResponse, HttpRequest
from django.urls import reverse
from django.contrib.auth import login
from django.core.files.uploadedfile import UploadedFile
from accounts.models import User, PasswordReset, TopList, EmailVerification, UserProfile
from email_service.services import EmailService
from parks.models import ParkReview
from rides.models import RideReview
from allauth.account.views import LoginView, SignupView
from .mixins import TurnstileMixin
from typing import Dict, Any, Optional, Union, cast, TYPE_CHECKING
from django_htmx.http import HttpResponseClientRefresh
from django.contrib.sites.models import Site
from django.contrib.sites.requests import RequestSite
from contextlib import suppress
import re
if TYPE_CHECKING:
from django.contrib.sites.models import Site
from django.contrib.sites.requests import RequestSite
UserModel = get_user_model()
class CustomLoginView(TurnstileMixin, LoginView):
def form_valid(self, form):
try:
self.validate_turnstile(self.request)
except ValidationError as e:
form.add_error(None, str(e))
return self.form_invalid(form)
response = super().form_valid(form)
return HttpResponseClientRefresh() if getattr(self.request, 'htmx', False) else response
def form_invalid(self, form):
if getattr(self.request, 'htmx', False):
return render(
self.request,
'account/partials/login_form.html',
self.get_context_data(form=form)
)
return super().form_invalid(form)
def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
if getattr(request, 'htmx', False):
return render(
request,
'account/partials/login_modal.html',
self.get_context_data()
)
return super().get(request, *args, **kwargs)
class CustomSignupView(TurnstileMixin, SignupView):
def form_valid(self, form):
try:
self.validate_turnstile(self.request)
except ValidationError as e:
form.add_error(None, str(e))
return self.form_invalid(form)
response = super().form_valid(form)
return HttpResponseClientRefresh() if getattr(self.request, 'htmx', False) else response
def form_invalid(self, form):
if getattr(self.request, 'htmx', False):
return render(
self.request,
'account/partials/signup_modal.html',
self.get_context_data(form=form)
)
return super().form_invalid(form)
def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
if getattr(request, 'htmx', False):
return render(
request,
'account/partials/signup_modal.html',
self.get_context_data()
)
return super().get(request, *args, **kwargs)
@login_required
def user_redirect_view(request: HttpRequest) -> HttpResponse:
user = cast(User, request.user)
return redirect('profile', username=user.username)
def handle_social_login(request: HttpRequest, email: str) -> HttpResponse:
if sociallogin := request.session.get('socialaccount_sociallogin'):
sociallogin.user.email = email
sociallogin.save()
login(request, sociallogin.user)
del request.session['socialaccount_sociallogin']
messages.success(request, 'Successfully logged in')
return redirect('/')
def email_required(request: HttpRequest) -> HttpResponse:
if not request.session.get('socialaccount_sociallogin'):
messages.error(request, 'No social login in progress')
return redirect('/')
if request.method == 'POST':
if email := request.POST.get('email'):
return handle_social_login(request, email)
messages.error(request, 'Email is required')
return render(request, 'accounts/email_required.html', {'error': 'Email is required'})
return render(request, 'accounts/email_required.html')
class ProfileView(DetailView):
model = User
template_name = 'accounts/profile.html'
context_object_name = 'profile_user'
slug_field = 'username'
slug_url_kwarg = 'username'
def get_queryset(self) -> QuerySet[User]:
return User.objects.select_related('profile')
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
context = super().get_context_data(**kwargs)
user = cast(User, self.get_object())
context['park_reviews'] = self._get_user_park_reviews(user)
context['ride_reviews'] = self._get_user_ride_reviews(user)
context['top_lists'] = self._get_user_top_lists(user)
return context
def _get_user_park_reviews(self, user: User) -> QuerySet[ParkReview]:
return ParkReview.objects.filter(
user=user,
is_published=True
).select_related(
'user',
'user__profile',
'park'
).order_by('-created_at')[:5]
def _get_user_ride_reviews(self, user: User) -> QuerySet[RideReview]:
return RideReview.objects.filter(
user=user,
is_published=True
).select_related(
'user',
'user__profile',
'ride'
).order_by('-created_at')[:5]
def _get_user_top_lists(self, user: User) -> QuerySet[TopList]:
return TopList.objects.filter(
user=user
).select_related(
'user',
'user__profile'
).prefetch_related(
'items'
).order_by('-created_at')[:5]
class SettingsView(LoginRequiredMixin, TemplateView):
template_name = 'accounts/settings.html'
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
def _handle_profile_update(self, request: HttpRequest) -> None:
user = cast(User, request.user)
profile = get_object_or_404(UserProfile, user=user)
if display_name := request.POST.get('display_name'):
profile.display_name = display_name
if 'avatar' in request.FILES:
avatar_file = cast(UploadedFile, request.FILES['avatar'])
profile.avatar.save(avatar_file.name, avatar_file, save=False)
profile.save()
user.save()
messages.success(request, 'Profile updated successfully')
def _validate_password(self, password: str) -> bool:
"""Validate password meets requirements."""
return (
len(password) >= 8 and
bool(re.search(r'[A-Z]', password)) and
bool(re.search(r'[a-z]', password)) and
bool(re.search(r'[0-9]', password))
)
def _send_password_change_confirmation(self, request: HttpRequest, user: User) -> None:
"""Send password change confirmation email."""
site = get_current_site(request)
context = {
'user': user,
'site_name': site.name,
}
email_html = render_to_string('accounts/email/password_change_confirmation.html', context)
EmailService.send_email(
to=user.email,
subject='Password Changed Successfully',
text='Your password has been changed successfully.',
site=site,
html=email_html
)
def _handle_password_change(self, request: HttpRequest) -> Optional[HttpResponseRedirect]:
user = cast(User, request.user)
old_password = request.POST.get('old_password', '')
new_password = request.POST.get('new_password', '')
confirm_password = request.POST.get('confirm_password', '')
if not user.check_password(old_password):
messages.error(request, 'Current password is incorrect')
return None
if new_password != confirm_password:
messages.error(request, 'New passwords do not match')
return None
if not self._validate_password(new_password):
messages.error(request, 'Password must be at least 8 characters and contain uppercase, lowercase, and numbers')
return None
user.set_password(new_password)
user.save()
self._send_password_change_confirmation(request, user)
messages.success(request, 'Password changed successfully. Please check your email for confirmation.')
return HttpResponseRedirect(reverse('account_login'))
def _handle_email_change(self, request: HttpRequest) -> None:
if new_email := request.POST.get('new_email'):
self._send_email_verification(request, new_email)
messages.success(request, 'Verification email sent to your new email address')
else:
messages.error(request, 'New email is required')
def _send_email_verification(self, request: HttpRequest, new_email: str) -> None:
user = cast(User, request.user)
token = get_random_string(64)
EmailVerification.objects.update_or_create(
user=user,
defaults={'token': token}
)
site = cast(Site, get_current_site(request))
verification_url = reverse('verify_email', kwargs={'token': token})
context = {
'user': user,
'verification_url': verification_url,
'site_name': site.name,
}
email_html = render_to_string('accounts/email/verify_email.html', context)
EmailService.send_email(
to=new_email,
subject='Verify your new email address',
text='Click the link to verify your new email address',
site=site,
html=email_html
)
user.pending_email = new_email
user.save()
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
action = request.POST.get('action')
if action == 'update_profile':
self._handle_profile_update(request)
elif action == 'change_password':
if response := self._handle_password_change(request):
return response
elif action == 'change_email':
self._handle_email_change(request)
return self.get(request, *args, **kwargs)
def create_password_reset_token(user: User) -> str:
token = get_random_string(64)
PasswordReset.objects.update_or_create(
user=user,
defaults={
'token': token,
'expires_at': timezone.now() + timedelta(hours=24)
}
)
return token
def send_password_reset_email(user: User, site: Union[Site, RequestSite], token: str) -> None:
reset_url = reverse('password_reset_confirm', kwargs={'token': token})
context = {
'user': user,
'reset_url': reset_url,
'site_name': site.name,
}
email_html = render_to_string('accounts/email/password_reset.html', context)
EmailService.send_email(
to=user.email,
subject='Reset your password',
text='Click the link to reset your password',
site=site,
html=email_html
)
def request_password_reset(request: HttpRequest) -> HttpResponse:
if request.method != 'POST':
return render(request, 'accounts/password_reset.html')
if not (email := request.POST.get('email')):
messages.error(request, 'Email is required')
return redirect('account_reset_password')
with suppress(User.DoesNotExist):
user = User.objects.get(email=email)
token = create_password_reset_token(user)
site = get_current_site(request)
send_password_reset_email(user, site, token)
messages.success(request, 'Password reset email sent')
return redirect('account_login')
def handle_password_reset(request: HttpRequest, user: User, new_password: str, reset: PasswordReset, site: Union[Site, RequestSite]) -> None:
user.set_password(new_password)
user.save()
reset.used = True
reset.save()
send_password_reset_confirmation(user, site)
messages.success(request, 'Password reset successfully')
def send_password_reset_confirmation(user: User, site: Union[Site, RequestSite]) -> None:
context = {
'user': user,
'site_name': site.name,
}
email_html = render_to_string('accounts/email/password_reset_complete.html', context)
EmailService.send_email(
to=user.email,
subject='Password Reset Complete',
text='Your password has been reset successfully.',
site=site,
html=email_html
)
def reset_password(request: HttpRequest, token: str) -> HttpResponse:
try:
reset = PasswordReset.objects.select_related('user').get(
token=token,
expires_at__gt=timezone.now(),
used=False
)
if request.method == 'POST':
if new_password := request.POST.get('new_password'):
site = get_current_site(request)
handle_password_reset(request, reset.user, new_password, reset, site)
return redirect('account_login')
messages.error(request, 'New password is required')
return render(request, 'accounts/password_reset_confirm.html', {'token': token})
except PasswordReset.DoesNotExist:
messages.error(request, 'Invalid or expired reset token')
return redirect('account_reset_password')

View File

@@ -1,649 +0,0 @@
#!/bin/bash
# ThrillWiki API Endpoints - Complete Curl Commands
# Generated from comprehensive URL analysis
# Base URL - adjust as needed for your environment
BASE_URL="http://localhost:8000"
# Command line options
SKIP_AUTH=false
ONLY_AUTH=false
SKIP_DOCS=false
HELP=false
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--skip-auth)
SKIP_AUTH=true
shift
;;
--only-auth)
ONLY_AUTH=true
shift
;;
--skip-docs)
SKIP_DOCS=true
shift
;;
--base-url)
BASE_URL="$2"
shift 2
;;
--help|-h)
HELP=true
shift
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
# Show help
if [ "$HELP" = true ]; then
echo "ThrillWiki API Endpoints Test Suite"
echo ""
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " --skip-auth Skip endpoints that require authentication"
echo " --only-auth Only test endpoints that require authentication"
echo " --skip-docs Skip API documentation endpoints (schema, swagger, redoc)"
echo " --base-url URL Set custom base URL (default: http://localhost:8000)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 # Test all endpoints"
echo " $0 --skip-auth # Test only public endpoints"
echo " $0 --only-auth # Test only authenticated endpoints"
echo " $0 --skip-docs --skip-auth # Test only public non-documentation endpoints"
echo " $0 --base-url https://api.example.com # Use custom base URL"
exit 0
fi
# Validate conflicting options
if [ "$SKIP_AUTH" = true ] && [ "$ONLY_AUTH" = true ]; then
echo "Error: --skip-auth and --only-auth cannot be used together"
exit 1
fi
echo "=== ThrillWiki API Endpoints Test Suite ==="
echo "Base URL: $BASE_URL"
if [ "$SKIP_AUTH" = true ]; then
echo "Mode: Public endpoints only (skipping authentication required)"
elif [ "$ONLY_AUTH" = true ]; then
echo "Mode: Authenticated endpoints only"
else
echo "Mode: All endpoints"
fi
if [ "$SKIP_DOCS" = true ]; then
echo "Skipping: API documentation endpoints"
fi
echo ""
# Helper function to check if we should run an endpoint
should_run_endpoint() {
local requires_auth=$1
local is_docs=$2
# Skip docs if requested
if [ "$SKIP_DOCS" = true ] && [ "$is_docs" = true ]; then
return 1
fi
# Skip auth endpoints if requested
if [ "$SKIP_AUTH" = true ] && [ "$requires_auth" = true ]; then
return 1
fi
# Only run auth endpoints if requested
if [ "$ONLY_AUTH" = true ] && [ "$requires_auth" = false ]; then
return 1
fi
return 0
}
# Counter for endpoint numbering
ENDPOINT_NUM=1
# ============================================================================
# AUTHENTICATION ENDPOINTS (/api/v1/auth/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo "=== AUTHENTICATION ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. Login"
curl -X POST "$BASE_URL/api/v1/auth/login/" \
-H "Content-Type: application/json" \
-d '{"username": "testuser", "password": "testpass"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Signup"
curl -X POST "$BASE_URL/api/v1/auth/signup/" \
-H "Content-Type: application/json" \
-d '{"username": "newuser", "email": "test@example.com", "password": "newpass123"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Logout"
curl -X POST "$BASE_URL/api/v1/auth/logout/" \
-H "Content-Type: application/json"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Password Reset"
curl -X POST "$BASE_URL/api/v1/auth/password/reset/" \
-H "Content-Type: application/json" \
-d '{"email": "user@example.com"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Social Providers"
curl -X GET "$BASE_URL/api/v1/auth/providers/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Auth Status"
curl -X GET "$BASE_URL/api/v1/auth/status/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Current User"
curl -X GET "$BASE_URL/api/v1/auth/user/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Password Change"
curl -X POST "$BASE_URL/api/v1/auth/password/change/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"old_password": "oldpass", "new_password": "newpass123"}'
((ENDPOINT_NUM++))
fi
# ============================================================================
# HEALTH CHECK ENDPOINTS (/api/v1/health/)
# ============================================================================
if should_run_endpoint false false; then
echo -e "\n\n=== HEALTH CHECK ENDPOINTS ==="
echo "$ENDPOINT_NUM. Health Check"
curl -X GET "$BASE_URL/api/v1/health/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Simple Health"
curl -X GET "$BASE_URL/api/v1/health/simple/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Performance Metrics"
curl -X GET "$BASE_URL/api/v1/health/performance/"
((ENDPOINT_NUM++))
fi
# ============================================================================
# TRENDING SYSTEM ENDPOINTS (/api/v1/trending/)
# ============================================================================
if should_run_endpoint false false; then
echo -e "\n\n=== TRENDING SYSTEM ENDPOINTS ==="
echo "$ENDPOINT_NUM. Trending Content"
curl -X GET "$BASE_URL/api/v1/trending/content/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. New Content"
curl -X GET "$BASE_URL/api/v1/trending/new/"
((ENDPOINT_NUM++))
fi
# ============================================================================
# STATISTICS ENDPOINTS (/api/v1/stats/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== STATISTICS ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. Statistics"
curl -X GET "$BASE_URL/api/v1/stats/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Recalculate Statistics"
curl -X POST "$BASE_URL/api/v1/stats/recalculate/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
fi
# ============================================================================
# RANKING SYSTEM ENDPOINTS (/api/v1/rankings/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== RANKING SYSTEM ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. List Rankings"
curl -X GET "$BASE_URL/api/v1/rankings/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. List Rankings with Filters"
curl -X GET "$BASE_URL/api/v1/rankings/?category=RC&min_riders=10&ordering=rank"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ranking Detail"
curl -X GET "$BASE_URL/api/v1/rankings/ride-slug-here/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ranking History"
curl -X GET "$BASE_URL/api/v1/rankings/ride-slug-here/history/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ranking Statistics"
curl -X GET "$BASE_URL/api/v1/rankings/statistics/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ranking Comparisons"
curl -X GET "$BASE_URL/api/v1/rankings/ride-slug-here/comparisons/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Trigger Ranking Calculation"
curl -X POST "$BASE_URL/api/v1/rankings/calculate/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"category": "RC"}'
((ENDPOINT_NUM++))
fi
# ============================================================================
# PARKS API ENDPOINTS (/api/v1/parks/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== PARKS API ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. List Parks"
curl -X GET "$BASE_URL/api/v1/parks/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park Filter Options"
curl -X GET "$BASE_URL/api/v1/parks/filter-options/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park Company Search"
curl -X GET "$BASE_URL/api/v1/parks/search/companies/?q=disney"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park Search Suggestions"
curl -X GET "$BASE_URL/api/v1/parks/search-suggestions/?q=magic"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park Detail"
curl -X GET "$BASE_URL/api/v1/parks/1/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. List Park Photos"
curl -X GET "$BASE_URL/api/v1/parks/1/photos/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park Photo Detail"
curl -X GET "$BASE_URL/api/v1/parks/1/photos/1/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Create Park"
curl -X POST "$BASE_URL/api/v1/parks/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "Test Park", "location": "Test City"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Park"
curl -X PUT "$BASE_URL/api/v1/parks/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "Updated Park Name"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Park"
curl -X DELETE "$BASE_URL/api/v1/parks/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Create Park Photo"
curl -X POST "$BASE_URL/api/v1/parks/1/photos/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-F "image=@/path/to/photo.jpg" \
-F "caption=Test photo"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Park Photo"
curl -X PUT "$BASE_URL/api/v1/parks/1/photos/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"caption": "Updated caption"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Park Photo"
curl -X DELETE "$BASE_URL/api/v1/parks/1/photos/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
fi
# ============================================================================
# RIDES API ENDPOINTS (/api/v1/rides/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== RIDES API ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. List Rides"
curl -X GET "$BASE_URL/api/v1/rides/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Filter Options"
curl -X GET "$BASE_URL/api/v1/rides/filter-options/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Company Search"
curl -X GET "$BASE_URL/api/v1/rides/search/companies/?q=intamin"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Model Search"
curl -X GET "$BASE_URL/api/v1/rides/search/ride-models/?q=giga"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Search Suggestions"
curl -X GET "$BASE_URL/api/v1/rides/search-suggestions/?q=millennium"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Detail"
curl -X GET "$BASE_URL/api/v1/rides/1/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. List Ride Photos"
curl -X GET "$BASE_URL/api/v1/rides/1/photos/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride Photo Detail"
curl -X GET "$BASE_URL/api/v1/rides/1/photos/1/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Create Ride"
curl -X POST "$BASE_URL/api/v1/rides/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "Test Coaster", "category": "RC", "park": 1}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Ride"
curl -X PUT "$BASE_URL/api/v1/rides/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "Updated Ride Name"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Ride"
curl -X DELETE "$BASE_URL/api/v1/rides/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Create Ride Photo"
curl -X POST "$BASE_URL/api/v1/rides/1/photos/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-F "image=@/path/to/photo.jpg" \
-F "caption=Test ride photo"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Ride Photo"
curl -X PUT "$BASE_URL/api/v1/rides/1/photos/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"caption": "Updated ride photo caption"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Ride Photo"
curl -X DELETE "$BASE_URL/api/v1/rides/1/photos/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
fi
# ============================================================================
# ACCOUNTS API ENDPOINTS (/api/v1/accounts/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== ACCOUNTS API ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. List User Profiles"
curl -X GET "$BASE_URL/api/v1/accounts/profiles/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. User Profile Detail"
curl -X GET "$BASE_URL/api/v1/accounts/profiles/1/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. List Top Lists"
curl -X GET "$BASE_URL/api/v1/accounts/toplists/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Top List Detail"
curl -X GET "$BASE_URL/api/v1/accounts/toplists/1/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. List Top List Items"
curl -X GET "$BASE_URL/api/v1/accounts/toplist-items/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Top List Item Detail"
curl -X GET "$BASE_URL/api/v1/accounts/toplist-items/1/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Update User Profile"
curl -X PUT "$BASE_URL/api/v1/accounts/profiles/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"bio": "Updated bio"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Create Top List"
curl -X POST "$BASE_URL/api/v1/accounts/toplists/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "My Top Coasters", "description": "My favorite roller coasters"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Top List"
curl -X PUT "$BASE_URL/api/v1/accounts/toplists/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"name": "Updated Top List Name"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Top List"
curl -X DELETE "$BASE_URL/api/v1/accounts/toplists/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Create Top List Item"
curl -X POST "$BASE_URL/api/v1/accounts/toplist-items/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"toplist": 1, "ride": 1, "position": 1}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Update Top List Item"
curl -X PUT "$BASE_URL/api/v1/accounts/toplist-items/1/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"position": 2}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Delete Top List Item"
curl -X DELETE "$BASE_URL/api/v1/accounts/toplist-items/1/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
fi
# ============================================================================
# HISTORY API ENDPOINTS (/api/v1/history/)
# ============================================================================
if should_run_endpoint false false; then
echo -e "\n\n=== HISTORY API ENDPOINTS ==="
echo "$ENDPOINT_NUM. Park History List"
curl -X GET "$BASE_URL/api/v1/history/parks/park-slug/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Park History Detail"
curl -X GET "$BASE_URL/api/v1/history/parks/park-slug/detail/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride History List"
curl -X GET "$BASE_URL/api/v1/history/parks/park-slug/rides/ride-slug/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Ride History Detail"
curl -X GET "$BASE_URL/api/v1/history/parks/park-slug/rides/ride-slug/detail/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Unified Timeline"
curl -X GET "$BASE_URL/api/v1/history/timeline/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Unified Timeline Detail"
curl -X GET "$BASE_URL/api/v1/history/timeline/1/"
((ENDPOINT_NUM++))
fi
# ============================================================================
# EMAIL API ENDPOINTS (/api/v1/email/)
# ============================================================================
if should_run_endpoint true false; then
echo -e "\n\n=== EMAIL API ENDPOINTS ==="
echo "$ENDPOINT_NUM. Send Email"
curl -X POST "$BASE_URL/api/v1/email/send/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"to": "recipient@example.com", "subject": "Test", "message": "Test message"}'
((ENDPOINT_NUM++))
fi
# ============================================================================
# CORE API ENDPOINTS (/api/v1/core/)
# ============================================================================
if should_run_endpoint false false; then
echo -e "\n\n=== CORE API ENDPOINTS ==="
echo "$ENDPOINT_NUM. Entity Fuzzy Search"
curl -X GET "$BASE_URL/api/v1/core/entities/search/?q=disney"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Entity Not Found"
curl -X POST "$BASE_URL/api/v1/core/entities/not-found/" \
-H "Content-Type: application/json" \
-d '{"query": "nonexistent park", "type": "park"}'
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Entity Suggestions"
curl -X GET "$BASE_URL/api/v1/core/entities/suggestions/?q=magic"
((ENDPOINT_NUM++))
fi
# ============================================================================
# MAPS API ENDPOINTS (/api/v1/maps/)
# ============================================================================
if should_run_endpoint false false || should_run_endpoint true false; then
echo -e "\n\n=== MAPS API ENDPOINTS ==="
fi
if should_run_endpoint false false; then
echo "$ENDPOINT_NUM. Map Locations"
curl -X GET "$BASE_URL/api/v1/maps/locations/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Map Location Detail"
curl -X GET "$BASE_URL/api/v1/maps/locations/park/1/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Map Search"
curl -X GET "$BASE_URL/api/v1/maps/search/?q=disney"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Map Bounds Query"
curl -X GET "$BASE_URL/api/v1/maps/bounds/?north=40.7&south=40.6&east=-73.9&west=-74.0"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Map Statistics"
curl -X GET "$BASE_URL/api/v1/maps/stats/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Map Cache Status"
curl -X GET "$BASE_URL/api/v1/maps/cache/"
((ENDPOINT_NUM++))
fi
if should_run_endpoint true false; then
echo -e "\n$ENDPOINT_NUM. Invalidate Map Cache"
curl -X POST "$BASE_URL/api/v1/maps/cache/invalidate/" \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
((ENDPOINT_NUM++))
fi
# ============================================================================
# API DOCUMENTATION ENDPOINTS
# ============================================================================
if should_run_endpoint false true; then
echo -e "\n\n=== API DOCUMENTATION ENDPOINTS ==="
echo "$ENDPOINT_NUM. OpenAPI Schema"
curl -X GET "$BASE_URL/api/schema/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. Swagger UI"
curl -X GET "$BASE_URL/api/docs/"
((ENDPOINT_NUM++))
echo -e "\n$ENDPOINT_NUM. ReDoc"
curl -X GET "$BASE_URL/api/redoc/"
((ENDPOINT_NUM++))
fi
# ============================================================================
# HEALTH CHECK (Django Health Check)
# ============================================================================
if should_run_endpoint false false; then
echo -e "\n\n=== DJANGO HEALTH CHECK ==="
echo "$ENDPOINT_NUM. Django Health Check"
curl -X GET "$BASE_URL/health/"
((ENDPOINT_NUM++))
fi
echo -e "\n\n=== END OF API ENDPOINTS TEST SUITE ==="
echo "Total endpoints tested: $((ENDPOINT_NUM - 1))"
echo ""
echo "Notes:"
echo "- Replace YOUR_TOKEN_HERE with actual authentication tokens"
echo "- Replace /path/to/photo.jpg with actual file paths for photo uploads"
echo "- Replace numeric IDs (1, 2, etc.) with actual resource IDs"
echo "- Replace slug placeholders (park-slug, ride-slug) with actual slugs"
echo "- Adjust BASE_URL for your environment (localhost:8000, staging, production)"
echo ""
echo "Authentication required endpoints are marked with Authorization header"
echo "File upload endpoints use multipart/form-data (-F flag)"
echo "JSON endpoints use application/json content type"

View File

@@ -1,372 +0,0 @@
# ThrillWiki Monorepo Architecture Validation
This document provides a comprehensive review and validation of the proposed monorepo architecture for migrating ThrillWiki from Django-only to Django + Vue.js.
## Architecture Overview Validation
### ✅ Core Requirements Met
1. **Clean Separation of Concerns**
- Backend: Django API, business logic, database management
- Frontend: Vue.js SPA with modern tooling
- Shared: Common resources and media files
2. **Development Workflow Preservation**
- UV package management for Python maintained
- pnpm for Node.js package management
- Existing development scripts adapted
- Hot reloading for both backend and frontend
3. **Project Structure Compatibility**
- Django apps preserved under `backend/apps/`
- Configuration maintained under `backend/config/`
- Static files strategy clearly defined
- Media files centralized in `shared/media/`
## Technical Architecture Validation
### Backend Architecture ✅
```mermaid
graph TB
A[Django Backend] --> B[Apps Directory]
A --> C[Config Directory]
A --> D[Static Files]
B --> E[accounts]
B --> F[parks]
B --> G[rides]
B --> H[moderation]
B --> I[location]
B --> J[media]
B --> K[email_service]
B --> L[core]
C --> M[Django Settings]
C --> N[URL Configuration]
C --> O[WSGI/ASGI]
D --> P[Admin Assets]
D --> Q[Backend Static]
```
**Validation Points:**
- ✅ All 8 Django apps properly mapped to new structure
- ✅ Configuration files maintain their organization
- ✅ Static file handling preserves Django admin functionality
- ✅ UV package management integration maintained
### Frontend Architecture ✅
```mermaid
graph TB
A[Vue.js Frontend] --> B[Source Code]
A --> C[Build System]
A --> D[Development Tools]
B --> E[Components]
B --> F[Views/Pages]
B --> G[Router]
B --> H[State Management]
B --> I[API Layer]
C --> J[Vite]
C --> K[TypeScript]
C --> L[Tailwind CSS]
D --> M[Hot Reload]
D --> N[Dev Server]
D --> O[Build Tools]
```
**Validation Points:**
- ✅ Modern Vue.js 3 + Composition API
- ✅ TypeScript for type safety
- ✅ Vite for fast development and builds
- ✅ Tailwind CSS for styling (matching current setup)
- ✅ Pinia for state management
- ✅ Vue Router for SPA navigation
### Integration Architecture ✅
```mermaid
graph LR
A[Vue.js Frontend] --> B[HTTP API Calls]
B --> C[Django REST API]
C --> D[Database]
C --> E[Media Files]
E --> F[Shared Media Directory]
F --> G[Frontend Access]
```
**Validation Points:**
- ✅ RESTful API integration between frontend and backend
- ✅ Media files accessible to both systems
- ✅ Authentication handling via API tokens
- ✅ CORS configuration for cross-origin requests
## File Migration Validation
### Critical File Mappings ✅
| Component | Current | New Location | Status |
|-----------|---------|--------------|--------|
| Django Apps | `/apps/` | `/backend/apps/` | ✅ Mapped |
| Configuration | `/config/` | `/backend/config/` | ✅ Mapped |
| Static Files | `/static/` | `/backend/static/` | ✅ Mapped |
| Media Files | `/media/` | `/shared/media/` | ✅ Mapped |
| Scripts | `/scripts/` | `/scripts/` | ✅ Preserved |
| Dependencies | `/pyproject.toml` | `/backend/pyproject.toml` | ✅ Mapped |
### Import Path Updates Required ✅
**Django Settings Updates:**
```python
# OLD
INSTALLED_APPS = [
'accounts',
'parks',
'rides',
# ...
]
# NEW
INSTALLED_APPS = [
'apps.accounts',
'apps.parks',
'apps.rides',
# ...
]
```
**Media Path Updates:**
```python
# NEW
MEDIA_ROOT = BASE_DIR.parent / 'shared' / 'media'
```
## Development Workflow Validation
### Package Management ✅
**Backend (UV):**
-`uv add <package>` for new dependencies
-`uv run manage.py <command>` for Django commands
-`uv sync` for dependency installation
**Frontend (pnpm):**
-`pnpm add <package>` for new dependencies
-`pnpm install` for dependency installation
-`pnpm run dev` for development server
**Root Workspace:**
-`pnpm run dev` starts both servers concurrently
- ✅ Individual server commands available
- ✅ Build and test scripts coordinated
### Development Scripts ✅
```bash
# Root level coordination
pnpm run dev # Both servers
pnpm run backend:dev # Django only
pnpm run frontend:dev # Vue.js only
pnpm run build # Production build
pnpm run test # All tests
pnpm run lint # All linting
pnpm run format # Code formatting
```
## Deployment Strategy Validation
### Container Strategy ✅
**Multi-container Approach:**
- ✅ Separate containers for backend and frontend
- ✅ Shared volumes for media files
- ✅ Database and Redis containers
- ✅ Nginx reverse proxy configuration
**Build Process:**
- ✅ Backend: Django static collection + uv dependencies
- ✅ Frontend: Vite production build + asset optimization
- ✅ Shared: Media file persistence across deployments
### Platform Compatibility ✅
**Supported Deployment Platforms:**
- ✅ Docker Compose (local and production)
- ✅ Vercel (frontend + serverless backend)
- ✅ Railway (container deployment)
- ✅ DigitalOcean App Platform
- ✅ AWS ECS/Fargate
- ✅ Google Cloud Run
## Performance Considerations ✅
### Backend Optimization
- ✅ Database connection pooling
- ✅ Redis caching strategy
- ✅ Static file CDN integration
- ✅ API response optimization
### Frontend Optimization
- ✅ Code splitting and lazy loading
- ✅ Asset optimization with Vite
- ✅ Tree shaking for minimal bundle size
- ✅ Modern build targets
### Development Performance
- ✅ Hot module replacement for Vue.js
- ✅ Django auto-reload for backend changes
- ✅ Fast dependency installation with UV and pnpm
- ✅ Concurrent development servers
## Security Validation ✅
### Backend Security
- ✅ Django security middleware maintained
- ✅ CORS configuration for API access
- ✅ Authentication token management
- ✅ Input validation and sanitization
### Frontend Security
- ✅ Content Security Policy headers
- ✅ XSS protection mechanisms
- ✅ Secure API communication (HTTPS)
- ✅ Environment variable protection
### Deployment Security
- ✅ SSL/TLS termination
- ✅ Security headers configuration
- ✅ Secret management strategy
- ✅ Container security best practices
## Risk Assessment and Mitigation
### Low Risk Items ✅
- **File organization**: Clear mapping and systematic approach
- **Package management**: Both UV and pnpm are stable and well-supported
- **Development workflow**: Incremental changes to existing process
### Medium Risk Items ⚠️
- **Import path updates**: Requires careful testing of all Django apps
- **Static file handling**: Need to verify Django admin continues working
- **API integration**: New frontend-backend communication layer
**Mitigation Strategies:**
- Comprehensive testing suite for Django apps after migration
- Static file serving verification in development and production
- API endpoint testing and documentation
- Gradual migration approach with rollback capabilities
### High Risk Items 🔴
- **Data migration**: Database changes during restructuring
- **Production deployment**: New deployment process requires validation
**Mitigation Strategies:**
- Database backup before any structural changes
- Staging environment testing before production deployment
- Blue-green deployment strategy for zero-downtime migration
- Monitoring and alerting for post-migration issues
## Testing Strategy Validation
### Backend Testing ✅
```bash
# Django tests
cd backend
uv run manage.py test
# Code quality
uv run flake8 .
uv run black --check .
```
### Frontend Testing ✅
```bash
# Vue.js tests
cd frontend
pnpm run test
pnpm run test:unit
pnpm run test:e2e
# Code quality
pnpm run lint
pnpm run type-check
```
### Integration Testing ✅
- API endpoint testing
- Frontend-backend communication testing
- Media file access testing
- Authentication flow testing
## Documentation Validation ✅
### Created Documentation
-**Monorepo Structure Plan**: Complete directory organization
-**Migration Mapping**: File-by-file migration guide
-**Deployment Guide**: Comprehensive deployment strategies
-**Architecture Validation**: This validation document
### Required Updates
- ✅ Root README.md update for monorepo structure
- ✅ Development setup instructions
- ✅ API documentation for frontend integration
- ✅ Deployment runbooks
## Implementation Readiness Assessment
### Prerequisites Met ✅
- [x] Current Django project analysis complete
- [x] Monorepo structure designed
- [x] File migration strategy defined
- [x] Development workflow planned
- [x] Deployment strategy documented
- [x] Risk assessment completed
### Ready for Implementation ✅
- [x] Clear step-by-step migration plan
- [x] File mapping completeness verified
- [x] Package management strategy confirmed
- [x] Testing approach defined
- [x] Rollback strategy available
### Success Criteria Defined ✅
1. **Functional Requirements**
- All existing Django functionality preserved
- Modern Vue.js frontend operational
- API integration working correctly
- Media file handling functional
2. **Performance Requirements**
- Development servers start within reasonable time
- Build process completes successfully
- Production deployment successful
3. **Quality Requirements**
- All tests passing after migration
- Code quality standards maintained
- Documentation updated and complete
## Final Recommendation ✅
**Approval Status: APPROVED FOR IMPLEMENTATION**
The proposed monorepo architecture for ThrillWiki is comprehensive, well-planned, and ready for implementation. The plan demonstrates:
1. **Technical Soundness**: Architecture follows modern best practices
2. **Risk Management**: Potential issues identified with mitigation strategies
3. **Implementation Clarity**: Clear step-by-step migration process
4. **Operational Readiness**: Deployment and maintenance procedures defined
**Next Steps:**
1. Switch to **Code Mode** for implementation
2. Begin with directory structure creation
3. Migrate backend files systematically
4. Create Vue.js frontend application
5. Test integration between systems
6. Update deployment configurations
The architecture provides a solid foundation for scaling ThrillWiki with modern frontend technologies while preserving the robust Django backend functionality.

View File

@@ -1,629 +0,0 @@
# ThrillWiki Deployment Guide
This document outlines deployment strategies, build processes, and infrastructure considerations for the ThrillWiki Django + HTMX application.
## Architecture Overview
ThrillWiki is a **Django monolith** with HTMX for dynamic interactivity. There is no separate frontend build process - templates and static assets are served directly by Django.
```mermaid
graph TB
A[Source Code] --> B[Django Application]
B --> C[Static Files Collection]
C --> D[Docker Container]
D --> E[Production Deployment]
subgraph "Django Application"
B1[Python Dependencies]
B2[Database Migrations]
B3[HTMX Templates]
end
```
## Development Environment
### Prerequisites
- Python 3.13+ with UV package manager
- PostgreSQL 14+ with PostGIS extension
- Redis 6+ (for caching and sessions)
### Local Development Setup
```bash
# Clone repository
git clone <repository-url>
cd thrillwiki
# Install dependencies
cd backend
uv sync --frozen
# Configure environment
cp .env.example .env
# Edit .env with your settings
# Database setup
uv run manage.py migrate
uv run manage.py collectstatic --noinput
# Start development server
uv run manage.py runserver
```
## Build Strategies
### 1. Containerized Deployment (Recommended)
#### Multi-stage Dockerfile
```dockerfile
# backend/Dockerfile
FROM python:3.13-slim as builder
WORKDIR /app
# Install system dependencies for GeoDjango
RUN apt-get update && apt-get install -y \
binutils libproj-dev gdal-bin libgdal-dev \
libpq-dev gcc \
&& rm -rf /var/lib/apt/lists/*
# Install UV
RUN pip install uv
# Copy dependency files
COPY pyproject.toml uv.lock ./
# Install dependencies
RUN uv sync --frozen --no-dev
FROM python:3.13-slim as runtime
WORKDIR /app
# Install runtime dependencies for GeoDjango
RUN apt-get update && apt-get install -y \
libpq5 gdal-bin libgdal32 libgeos-c1v5 libproj25 \
&& rm -rf /var/lib/apt/lists/*
# Copy virtual environment from builder
COPY --from=builder /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
# Copy application code
COPY . .
# Collect static files
RUN python manage.py collectstatic --noinput
# Create logs directory
RUN mkdir -p logs
EXPOSE 8000
# Run with gunicorn
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "4"]
```
#### Docker Compose for Development
```yaml
# docker-compose.dev.yml
version: '3.8'
services:
db:
image: postgis/postgis:15-3.3
environment:
POSTGRES_DB: thrillwiki
POSTGRES_USER: thrillwiki
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"
web:
build:
context: ./backend
dockerfile: Dockerfile.dev
ports:
- "8000:8000"
volumes:
- ./backend:/app
- ./shared/media:/app/media
environment:
- DEBUG=1
- DATABASE_URL=postgis://thrillwiki:password@db:5432/thrillwiki
- REDIS_URL=redis://redis:6379/0
depends_on:
- db
- redis
command: python manage.py runserver 0.0.0.0:8000
celery:
build:
context: ./backend
dockerfile: Dockerfile.dev
volumes:
- ./backend:/app
environment:
- DATABASE_URL=postgis://thrillwiki:password@db:5432/thrillwiki
- REDIS_URL=redis://redis:6379/0
depends_on:
- db
- redis
command: celery -A config.celery worker -l info
volumes:
postgres_data:
```
#### Docker Compose for Production
```yaml
# docker-compose.prod.yml
version: '3.8'
services:
db:
image: postgis/postgis:15-3.3
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
redis:
image: redis:7-alpine
restart: unless-stopped
web:
build:
context: ./backend
dockerfile: Dockerfile
environment:
- DEBUG=0
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
- SECRET_KEY=${SECRET_KEY}
- ALLOWED_HOSTS=${ALLOWED_HOSTS}
volumes:
- ./shared/media:/app/media
- static_files:/app/staticfiles
depends_on:
- db
- redis
restart: unless-stopped
celery:
build:
context: ./backend
dockerfile: Dockerfile
environment:
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
- SECRET_KEY=${SECRET_KEY}
depends_on:
- db
- redis
command: celery -A config.celery worker -l info
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/ssl:/etc/nginx/ssl
- static_files:/usr/share/nginx/html/static
- ./shared/media:/usr/share/nginx/html/media
depends_on:
- web
restart: unless-stopped
volumes:
postgres_data:
static_files:
```
### Nginx Configuration
```nginx
# nginx/nginx.conf
upstream django {
server web:8000;
}
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
# Security headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Static files
location /static/ {
alias /usr/share/nginx/html/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}
# Media files
location /media/ {
alias /usr/share/nginx/html/media/;
expires 1M;
add_header Cache-Control "public";
}
# Django application
location / {
proxy_pass http://django;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# HTMX considerations
proxy_set_header HX-Request $http_hx_request;
proxy_set_header HX-Current-URL $http_hx_current_url;
}
# Health check endpoint
location /api/v1/health/simple/ {
proxy_pass http://django;
proxy_set_header Host $http_host;
access_log off;
}
}
```
## CI/CD Pipeline
### GitHub Actions Workflow
```yaml
# .github/workflows/deploy.yml
name: Deploy ThrillWiki
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgis/postgis:15-3.3
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
redis:
image: redis:7-alpine
ports:
- 6379:6379
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
- name: Install UV
run: pip install uv
- name: Cache dependencies
uses: actions/cache@v4
with:
path: ~/.cache/uv
key: ${{ runner.os }}-uv-${{ hashFiles('backend/uv.lock') }}
- name: Install dependencies
run: |
cd backend
uv sync --frozen
- name: Run tests
run: |
cd backend
uv run manage.py test
env:
DATABASE_URL: postgis://postgres:postgres@localhost:5432/postgres
REDIS_URL: redis://localhost:6379/0
SECRET_KEY: test-secret-key
DEBUG: "1"
- name: Run linting
run: |
cd backend
uv run ruff check .
uv run black --check .
build:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Build Docker image
run: |
docker build -t thrillwiki-web ./backend
- name: Push to registry
run: |
# Push to your container registry
# docker push your-registry/thrillwiki-web:${{ github.sha }}
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to production
run: |
# Deploy using your preferred method
# SSH, Kubernetes, AWS ECS, etc.
```
## Environment Configuration
### Required Environment Variables
```bash
# Django Settings
DEBUG=0
SECRET_KEY=your-production-secret-key
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
CSRF_TRUSTED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
DJANGO_SETTINGS_MODULE=config.django.production
# Database
DATABASE_URL=postgis://user:password@host:port/database
# Redis
REDIS_URL=redis://host:port/0
# Email
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
EMAIL_HOST=smtp.yourmailprovider.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your-email@yourdomain.com
EMAIL_HOST_PASSWORD=your-email-password
# Cloudflare Images
CLOUDFLARE_IMAGES_ACCOUNT_ID=your-account-id
CLOUDFLARE_IMAGES_API_TOKEN=your-api-token
CLOUDFLARE_IMAGES_ACCOUNT_HASH=your-account-hash
# Sentry (optional)
SENTRY_DSN=your-sentry-dsn
SENTRY_ENVIRONMENT=production
```
## Performance Optimization
### Database Optimization
```python
# backend/config/django/production.py
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'CONN_MAX_AGE': 60, # Keep connections alive for 60 seconds
'OPTIONS': {
'connect_timeout': 10,
'options': '-c statement_timeout=30000', # 30 second query timeout
}
}
}
```
### Redis Caching
```python
# Caching configuration is in config/django/production.py
# Multiple cache backends for different purposes:
# - default: General caching
# - sessions: Session storage
# - api: API response caching
```
### Static Files with WhiteNoise
```python
# backend/config/django/production.py
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
```
## Monitoring and Logging
### Health Check Endpoints
| Endpoint | Purpose | Use Case |
|----------|---------|----------|
| `/api/v1/health/` | Comprehensive health check | Monitoring dashboards |
| `/api/v1/health/simple/` | Simple OK/ERROR | Load balancer health checks |
| `/api/v1/health/performance/` | Performance metrics | Debug mode only |
### Logging Configuration
Production logging uses JSON format for log aggregation:
```python
# backend/config/django/production.py
LOGGING = {
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'json',
},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'logs/django.log',
'maxBytes': 1024 * 1024 * 15, # 15MB
'backupCount': 10,
'formatter': 'json',
},
},
}
```
### Sentry Integration
```python
# Sentry is configured in config/django/production.py
# Enable by setting SENTRY_DSN environment variable
```
## Security Considerations
### Production Security Checklist
- [ ] `DEBUG=False` in production
- [ ] `SECRET_KEY` is unique and secure
- [ ] `ALLOWED_HOSTS` properly configured
- [ ] HTTPS enforced with SSL certificates
- [ ] Security headers configured (HSTS, CSP, etc.)
- [ ] Database credentials secured
- [ ] Redis password configured (if exposed)
- [ ] CORS properly configured
- [ ] Rate limiting enabled
- [ ] File upload validation
- [ ] SQL injection protection (Django ORM)
- [ ] XSS protection enabled
- [ ] CSRF protection active
### Security Headers
```python
# backend/config/django/production.py
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
X_FRAME_OPTIONS = 'DENY'
SECURE_CONTENT_TYPE_NOSNIFF = True
```
## Backup and Recovery
### Database Backup Strategy
```bash
#!/bin/bash
# Automated backup script
pg_dump $DATABASE_URL | gzip > backup_$(date +%Y%m%d_%H%M%S).sql.gz
aws s3 cp backup_*.sql.gz s3://your-backup-bucket/database/
```
### Media Files Backup
```bash
# Sync media files to S3
aws s3 sync ./shared/media/ s3://your-media-bucket/media/ --delete
```
## Scaling Strategies
### Horizontal Scaling
- Use load balancer (nginx, AWS ALB, etc.)
- Database read replicas for read-heavy workloads
- CDN for static assets (Cloudflare, CloudFront)
- Redis cluster for session/cache scaling
- Multiple Gunicorn workers per container
### Vertical Scaling
- Database connection pooling (pgBouncer)
- Query optimization with select_related/prefetch_related
- Memory usage optimization
- Background task offloading to Celery
## Troubleshooting Guide
### Common Issues
1. **Static files not loading**
- Run `python manage.py collectstatic`
- Check nginx static file configuration
- Verify WhiteNoise settings
2. **Database connection errors**
- Verify DATABASE_URL format
- Check firewall rules
- Verify PostGIS extension is installed
3. **CORS errors**
- Check CORS_ALLOWED_ORIGINS setting
- Verify CSRF_TRUSTED_ORIGINS
4. **Memory issues**
- Monitor with `docker stats`
- Optimize Gunicorn worker count
- Check for query inefficiencies
### Debug Commands
```bash
# Check Django configuration
cd backend
uv run manage.py check --deploy
# Database shell
uv run manage.py dbshell
# Django shell
uv run manage.py shell
# Validate settings
uv run manage.py validate_settings
```
---
This deployment guide provides a comprehensive approach to deploying the ThrillWiki Django + HTMX application while maintaining security, performance, and scalability.

View File

@@ -1,353 +0,0 @@
# ThrillWiki Migration Mapping Document
This document provides a comprehensive mapping of files from the current Django project to the new monorepo structure.
## Root Level Files
| Current Location | New Location | Notes |
|------------------|--------------|-------|
| `manage.py` | `backend/manage.py` | Core Django management |
| `pyproject.toml` | `backend/pyproject.toml` | Python dependencies |
| `uv.lock` | `backend/uv.lock` | UV lock file |
| `.gitignore` | `.gitignore` (update) | Merge with monorepo patterns |
| `README.md` | `README.md` (update) | Update for monorepo |
| `.pre-commit-config.yaml` | `.pre-commit-config.yaml` | Root level |
## Configuration Directory
| Current Location | New Location | Notes |
|------------------|--------------|-------|
| `config/django/` | `backend/config/django/` | Django settings |
| `config/settings/` | `backend/config/settings/` | Environment settings |
| `config/urls.py` | `backend/config/urls.py` | URL configuration |
| `config/wsgi.py` | `backend/config/wsgi.py` | WSGI configuration |
| `config/asgi.py` | `backend/config/asgi.py` | ASGI configuration |
## Django Apps
### Accounts App
| Current Location | New Location |
|------------------|--------------|
| `accounts/` | `backend/apps/accounts/` |
| `accounts/__init__.py` | `backend/apps/accounts/__init__.py` |
| `accounts/models.py` | `backend/apps/accounts/models.py` |
| `accounts/views.py` | `backend/apps/accounts/views.py` |
| `accounts/admin.py` | `backend/apps/accounts/admin.py` |
| `accounts/apps.py` | `backend/apps/accounts/apps.py` |
| `accounts/migrations/` | `backend/apps/accounts/migrations/` |
| `accounts/tests/` | `backend/apps/accounts/tests/` |
### Parks App
| Current Location | New Location |
|------------------|--------------|
| `parks/` | `backend/apps/parks/` |
| `parks/__init__.py` | `backend/apps/parks/__init__.py` |
| `parks/models.py` | `backend/apps/parks/models.py` |
| `parks/views.py` | `backend/apps/parks/views.py` |
| `parks/admin.py` | `backend/apps/parks/admin.py` |
| `parks/apps.py` | `backend/apps/parks/apps.py` |
| `parks/migrations/` | `backend/apps/parks/migrations/` |
| `parks/tests/` | `backend/apps/parks/tests/` |
### Rides App
| Current Location | New Location |
|------------------|--------------|
| `rides/` | `backend/apps/rides/` |
| `rides/__init__.py` | `backend/apps/rides/__init__.py` |
| `rides/models.py` | `backend/apps/rides/models.py` |
| `rides/views.py` | `backend/apps/rides/views.py` |
| `rides/admin.py` | `backend/apps/rides/admin.py` |
| `rides/apps.py` | `backend/apps/rides/apps.py` |
| `rides/migrations/` | `backend/apps/rides/migrations/` |
| `rides/tests/` | `backend/apps/rides/tests/` |
### Moderation App
| Current Location | New Location |
|------------------|--------------|
| `moderation/` | `backend/apps/moderation/` |
| `moderation/__init__.py` | `backend/apps/moderation/__init__.py` |
| `moderation/models.py` | `backend/apps/moderation/models.py` |
| `moderation/views.py` | `backend/apps/moderation/views.py` |
| `moderation/admin.py` | `backend/apps/moderation/admin.py` |
| `moderation/apps.py` | `backend/apps/moderation/apps.py` |
| `moderation/migrations/` | `backend/apps/moderation/migrations/` |
| `moderation/tests/` | `backend/apps/moderation/tests/` |
### Location App
| Current Location | New Location |
|------------------|--------------|
| `location/` | `backend/apps/location/` |
| `location/__init__.py` | `backend/apps/location/__init__.py` |
| `location/models.py` | `backend/apps/location/models.py` |
| `location/views.py` | `backend/apps/location/views.py` |
| `location/admin.py` | `backend/apps/location/admin.py` |
| `location/apps.py` | `backend/apps/location/apps.py` |
| `location/migrations/` | `backend/apps/location/migrations/` |
| `location/tests/` | `backend/apps/location/tests/` |
### Media App
| Current Location | New Location |
|------------------|--------------|
| `media/` | `backend/apps/media/` |
| `media/__init__.py` | `backend/apps/media/__init__.py` |
| `media/models.py` | `backend/apps/media/models.py` |
| `media/views.py` | `backend/apps/media/views.py` |
| `media/admin.py` | `backend/apps/media/admin.py` |
| `media/apps.py` | `backend/apps/media/apps.py` |
| `media/migrations/` | `backend/apps/media/migrations/` |
| `media/tests/` | `backend/apps/media/tests/` |
### Email Service App
| Current Location | New Location |
|------------------|--------------|
| `email_service/` | `backend/apps/email_service/` |
| `email_service/__init__.py` | `backend/apps/email_service/__init__.py` |
| `email_service/models.py` | `backend/apps/email_service/models.py` |
| `email_service/views.py` | `backend/apps/email_service/views.py` |
| `email_service/admin.py` | `backend/apps/email_service/admin.py` |
| `email_service/apps.py` | `backend/apps/email_service/apps.py` |
| `email_service/migrations/` | `backend/apps/email_service/migrations/` |
| `email_service/tests/` | `backend/apps/email_service/tests/` |
### Core App
| Current Location | New Location |
|------------------|--------------|
| `core/` | `backend/apps/core/` |
| `core/__init__.py` | `backend/apps/core/__init__.py` |
| `core/models.py` | `backend/apps/core/models.py` |
| `core/views.py` | `backend/apps/core/views.py` |
| `core/admin.py` | `backend/apps/core/admin.py` |
| `core/apps.py` | `backend/apps/core/apps.py` |
| `core/migrations/` | `backend/apps/core/migrations/` |
| `core/tests/` | `backend/apps/core/tests/` |
## Static Files and Templates
| Current Location | New Location | Notes |
|------------------|--------------|-------|
| `static/` | `backend/static/` | Django admin and backend assets |
| `staticfiles/` | `backend/staticfiles/` | Collected static files |
| `templates/` | `backend/templates/` | Django templates (if any) |
## Media Files
| Current Location | New Location | Notes |
|------------------|--------------|-------|
| `media/` | `shared/media/` | User uploaded content |
## Scripts and Development Tools
| Current Location | New Location | Notes |
|------------------|--------------|-------|
| `scripts/` | `scripts/` | Root level scripts |
| `scripts/dev_server.sh` | `scripts/backend_dev.sh` | Rename for clarity |
## New Frontend Structure (Created)
| New Location | Purpose |
|--------------|---------|
| `frontend/` | Vue.js application root |
| `frontend/package.json` | Node.js dependencies |
| `frontend/pnpm-lock.yaml` | pnpm lock file |
| `frontend/vite.config.ts` | Vite configuration |
| `frontend/tsconfig.json` | TypeScript configuration |
| `frontend/tailwind.config.js` | Tailwind CSS configuration |
| `frontend/src/` | Vue.js source code |
| `frontend/src/main.ts` | Application entry point |
| `frontend/src/App.vue` | Root component |
| `frontend/src/components/` | Vue components |
| `frontend/src/views/` | Page components |
| `frontend/src/router/` | Vue Router configuration |
| `frontend/src/stores/` | Pinia stores |
| `frontend/src/composables/` | Vue composables |
| `frontend/src/utils/` | Utility functions |
| `frontend/src/types/` | TypeScript type definitions |
| `frontend/src/assets/` | Static assets |
| `frontend/public/` | Public assets |
| `frontend/dist/` | Build output |
## New Shared Resources (Created)
| New Location | Purpose |
|--------------|---------|
| `shared/` | Cross-platform resources |
| `shared/media/` | User uploaded files |
| `shared/docs/` | Documentation |
| `shared/types/` | Shared TypeScript types |
| `shared/constants/` | Shared constants |
## Updated Root Files
### package.json (Root)
```json
{
"name": "thrillwiki-monorepo",
"private": true,
"workspaces": [
"frontend"
],
"scripts": {
"dev": "concurrently \"pnpm --filter frontend dev\" \"./scripts/backend_dev.sh\"",
"build": "pnpm --filter frontend build",
"backend:dev": "./scripts/backend_dev.sh",
"frontend:dev": "pnpm --filter frontend dev",
"test": "pnpm --filter frontend test && cd backend && uv run manage.py test",
"lint": "pnpm --filter frontend lint && cd backend && uv run flake8 .",
"format": "pnpm --filter frontend format && cd backend && uv run black ."
},
"devDependencies": {
"concurrently": "^8.2.2"
}
}
```
### .gitignore (Updated)
```gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Django
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
/backend/static/
/backend/media/
# UV
.uv/
# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.pnpm-store/
# Vue.js / Vite
/frontend/dist/
/frontend/dist-ssr/
*.local
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Logs
logs/
*.log
# Coverage
coverage/
*.lcov
.nyc_output
```
## Configuration Updates Required
### Backend Django Settings
Update `INSTALLED_APPS` paths:
```python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local apps
'apps.accounts',
'apps.parks',
'apps.rides',
'apps.moderation',
'apps.location',
'apps.media',
'apps.email_service',
'apps.core',
]
```
Update media and static files paths:
```python
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR.parent / 'shared' / 'media'
```
### Script Updates
Update `scripts/backend_dev.sh`:
```bash
#!/bin/bash
cd backend
lsof -ti :8000 | xargs kill -9 2>/dev/null || true
find . -type d -name "__pycache__" -exec rm -r {} + 2>/dev/null || true
uv run manage.py runserver 0.0.0.0:8000
```
## Migration Steps Summary
1. **Create new directory structure**
2. **Move backend files** to `backend/` directory
3. **Update import paths** in Django settings and apps
4. **Create frontend** Vue.js application
5. **Update scripts** and configuration files
6. **Test both backend and frontend** independently
7. **Configure API integration** between Django and Vue.js
8. **Update deployment** configurations
## Validation Checklist
- [ ] All Django apps moved to `backend/apps/`
- [ ] Configuration files updated with new paths
- [ ] Static and media file paths configured correctly
- [ ] Frontend Vue.js application created and configured
- [ ] Root package.json with workspace configuration
- [ ] Development scripts updated and tested
- [ ] Git configuration updated
- [ ] Documentation updated
- [ ] CI/CD pipelines updated (if applicable)
- [ ] Database migrations work correctly
- [ ] Both development servers start successfully
- [ ] API endpoints accessible from frontend

View File

@@ -1,525 +0,0 @@
# ThrillWiki Django + Vue.js Monorepo Architecture Plan
## Executive Summary
This document outlines the optimal monorepo directory structure for migrating the ThrillWiki Django project to a Django + Vue.js architecture. The design separates backend and frontend concerns while maintaining existing Django app organization and supporting modern development workflows.
## Current Project Analysis
### Django Apps Structure
- **accounts**: User management and authentication
- **parks**: Theme park data and operations
- **rides**: Ride information and management
- **moderation**: Content moderation system
- **location**: Geographic data handling
- **media**: File and image management
- **email_service**: Email functionality
- **core**: Core utilities and services
### Key Infrastructure
- **Package Management**: UV-based Python setup
- **Configuration**: `config/django/` for settings, `config/settings/` for modular settings
- **Development**: `scripts/dev_server.sh` with comprehensive setup
- **Static Assets**: Tailwind CSS integration, `static/` and `staticfiles/`
- **Media Handling**: Organized `media/` directory with park/ride subdirectories
## Proposed Monorepo Structure
```
thrillwiki-monorepo/
├── README.md
├── pyproject.toml # Python dependencies (backend only)
├── package.json # Node.js dependencies (monorepo coordination)
├── pnpm-workspace.yaml # pnpm workspace configuration
├── .env.example
├── .gitignore
├──
├── backend/ # Django Backend
│ ├── manage.py
│ ├── pyproject.toml # Backend-specific dependencies
│ ├── config/
│ │ ├── django/
│ │ │ ├── base.py
│ │ │ ├── local.py
│ │ │ ├── production.py
│ │ │ └── test.py
│ │ └── settings/
│ │ ├── database.py
│ │ ├── email.py
│ │ └── security.py
│ ├── thrillwiki/
│ │ ├── __init__.py
│ │ ├── urls.py
│ │ ├── wsgi.py
│ │ ├── asgi.py
│ │ └── views.py
│ ├── apps/ # Django apps
│ │ ├── accounts/
│ │ ├── parks/
│ │ ├── rides/
│ │ ├── moderation/
│ │ ├── location/
│ │ ├── media/
│ │ ├── email_service/
│ │ └── core/
│ ├── templates/ # Django templates (API responses, admin)
│ ├── static/ # Backend static files
│ │ └── admin/ # Django admin assets
│ ├── media/ # User uploads
│ │ ├── avatars/
│ │ ├── park/
│ │ └── submissions/
│ └── tests/ # Backend tests
├── frontend/ # Vue.js Frontend
│ ├── package.json
│ ├── pnpm-lock.yaml
│ ├── vite.config.js
│ ├── tailwind.config.js
│ ├── index.html
│ ├── src/
│ │ ├── main.js
│ │ ├── App.vue
│ │ ├── router/
│ │ │ └── index.js
│ │ ├── stores/ # Pinia/Vuex stores
│ │ │ ├── auth.js
│ │ │ ├── parks.js
│ │ │ └── rides.js
│ │ ├── components/
│ │ │ ├── common/ # Shared components
│ │ │ ├── parks/ # Park-specific components
│ │ │ ├── rides/ # Ride-specific components
│ │ │ └── moderation/ # Moderation components
│ │ ├── views/ # Page components
│ │ │ ├── Home.vue
│ │ │ ├── parks/
│ │ │ ├── rides/
│ │ │ └── auth/
│ │ ├── composables/ # Vue 3 composables
│ │ │ ├── useAuth.js
│ │ │ ├── useApi.js
│ │ │ └── useTheme.js
│ │ ├── services/ # API service layer
│ │ │ ├── api.js
│ │ │ ├── auth.js
│ │ │ ├── parks.js
│ │ │ └── rides.js
│ │ ├── assets/
│ │ │ ├── images/
│ │ │ └── styles/
│ │ │ ├── globals.css
│ │ │ └── components/
│ │ └── utils/
│ ├── public/
│ │ ├── favicon.ico
│ │ └── images/
│ ├── dist/ # Build output
│ └── tests/ # Frontend tests
│ ├── unit/
│ └── e2e/
├── shared/ # Shared Resources
│ ├── docs/ # Documentation
│ │ ├── api/ # API documentation
│ │ ├── deployment/ # Deployment guides
│ │ └── development/ # Development setup
│ ├── scripts/ # Build and deployment scripts
│ │ ├── dev/
│ │ │ ├── start-backend.sh
│ │ │ ├── start-frontend.sh
│ │ │ └── start-full-stack.sh
│ │ ├── build/
│ │ │ ├── build-frontend.sh
│ │ │ └── build-production.sh
│ │ ├── deploy/
│ │ └── utils/
│ ├── config/ # Shared configuration
│ │ ├── docker/
│ │ │ ├── Dockerfile.backend
│ │ │ ├── Dockerfile.frontend
│ │ │ └── docker-compose.yml
│ │ ├── nginx/
│ │ └── ci/ # CI/CD configuration
│ │ └── github-actions/
│ └── types/ # Shared TypeScript types
│ ├── api.ts
│ ├── parks.ts
│ └── rides.ts
├── logs/ # Application logs
├── backups/ # Database backups
├── uploads/ # Temporary upload directory
└── dist/ # Production build output
├── backend/ # Django static files
└── frontend/ # Vue.js build
```
## Directory Organization Rationale
### 1. Clear Separation of Concerns
- **backend/**: Contains all Django-related code, maintaining existing app structure
- **frontend/**: Vue.js application with modern structure (Vite + Vue 3)
- **shared/**: Common resources, documentation, and configuration
### 2. Backend Structure (`backend/`)
- Preserves existing Django app organization under `apps/`
- Maintains UV-based Python dependency management
- Keeps configuration structure with `config/django/` and `config/settings/`
- Separates templates for API responses vs. frontend UI
### 3. Frontend Structure (`frontend/`)
- Modern Vue 3 + Vite setup with TypeScript support
- Organized by feature areas (parks, rides, auth)
- Composables for Vue 3 Composition API patterns
- Service layer for API communication with Django backend
- Tailwind CSS integration with shared design system
### 4. Shared Resources (`shared/`)
- Centralized documentation and deployment scripts
- Docker configuration for containerized deployment
- TypeScript type definitions shared between frontend and API
- CI/CD pipeline configuration
## Static File Strategy
### Development
```mermaid
graph LR
A[Vue Dev Server :3000] --> B[Vite HMR]
C[Django Dev Server :8000] --> D[Django Static Files]
E[Tailwind CSS] --> F[Both Frontend & Backend]
```
### Production
```mermaid
graph LR
A[Vue Build] --> B[dist/frontend/]
C[Django Collectstatic] --> D[dist/backend/]
E[Nginx] --> F[Serves Both]
F --> G[Frontend Assets]
F --> H[API Endpoints]
F --> I[Media Files]
```
### Implementation Details
1. **Development Mode**:
- Frontend: Vite dev server on port 3000 with HMR
- Backend: Django dev server on port 8000
- Proxy API calls from frontend to backend
2. **Production Mode**:
- Frontend built to `dist/frontend/`
- Django static files collected to `dist/backend/`
- Nginx serves static files and proxies API calls
## Media File Management
### Current Structure Preservation
```
media/
├── avatars/ # User profile images
├── park/ # Park-specific media
│ ├── {park-slug}/
│ │ └── {ride-slug}/
└── submissions/ # User-submitted content
└── photos/
```
### Strategy
- **Development**: Django serves media files directly
- **Production**: CDN or object storage (S3/CloudFlare) integration
- **Frontend Access**: Media URLs provided via API responses
- **Upload Handling**: Django handles all file uploads, Vue.js provides UI
## Development Workflow Integration
### Package Management
- **Root**: Node.js dependencies for frontend and tooling (using pnpm)
- **Backend**: UV for Python dependencies (existing approach)
- **Frontend**: pnpm for Vue.js dependencies
### Development Scripts
```bash
# Root level scripts
pnpm run dev # Start both backend and frontend
pnpm run dev:backend # Start only Django
pnpm run dev:frontend # Start only Vue.js
pnpm run build # Build for production
pnpm run test # Run all tests
# Backend specific (using UV)
cd backend && uv run manage.py runserver
cd backend && uv run manage.py test
# Frontend specific
cd frontend && pnpm run dev
cd frontend && pnpm run build
cd frontend && pnpm run test
```
### Environment Configuration
```bash
# Root .env (shared settings)
DATABASE_URL=
REDIS_URL=
SECRET_KEY=
# Backend .env (Django specific)
DJANGO_SETTINGS_MODULE=config.django.local
DEBUG=True
# Frontend .env (Vue specific)
VITE_API_BASE_URL=http://localhost:8000/api
VITE_APP_TITLE=ThrillWiki
```
### Package Manager Configuration
#### Root pnpm-workspace.yaml
```yaml
packages:
- 'frontend'
# Backend is managed separately with uv
```
#### Root package.json
```json
{
"name": "thrillwiki-monorepo",
"private": true,
"packageManager": "pnpm@9.0.0",
"scripts": {
"dev": "concurrently \"pnpm run dev:backend\" \"pnpm run dev:frontend\"",
"dev:backend": "cd backend && uv run manage.py runserver",
"dev:frontend": "cd frontend && pnpm run dev",
"build": "pnpm run build:frontend && cd backend && uv run manage.py collectstatic --noinput",
"build:frontend": "cd frontend && pnpm run build",
"test": "pnpm run test:backend && pnpm run test:frontend",
"test:backend": "cd backend && uv run manage.py test",
"test:frontend": "cd frontend && pnpm run test",
"lint": "cd frontend && pnpm run lint && cd ../backend && uv run flake8 .",
"format": "cd frontend && pnpm run format && cd ../backend && uv run black ."
},
"devDependencies": {
"concurrently": "^8.2.0"
}
}
```
#### Frontend package.json
```json
{
"name": "thrillwiki-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest",
"test:e2e": "playwright test",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix",
"format": "prettier --write src/",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.4.0",
"vue-router": "^4.3.0",
"pinia": "^2.1.0",
"axios": "^1.6.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.0.0",
"vite": "^5.0.0",
"vue-tsc": "^2.0.0",
"typescript": "^5.3.0",
"tailwindcss": "^3.4.0",
"autoprefixer": "^10.4.0",
"postcss": "^8.4.0",
"eslint": "^8.57.0",
"prettier": "^3.2.0",
"vitest": "^1.3.0",
"@playwright/test": "^1.42.0"
}
}
```
## File Migration Mapping
### High-Level Moves
```
Current → New Location
├── manage.py → backend/manage.py
├── pyproject.toml → backend/pyproject.toml (+ root package.json)
├── config/ → backend/config/
├── thrillwiki/ → backend/thrillwiki/
├── accounts/ → backend/apps/accounts/
├── parks/ → backend/apps/parks/
├── rides/ → backend/apps/rides/
├── moderation/ → backend/apps/moderation/
├── location/ → backend/apps/location/
├── media/ → backend/apps/media/
├── email_service/ → backend/apps/email_service/
├── core/ → backend/apps/core/
├── templates/ → backend/templates/ (API) + frontend/src/views/ (UI)
├── static/ → backend/static/ (admin) + frontend/src/assets/
├── media/ → media/ (shared, accessible to both)
├── scripts/ → shared/scripts/
├── docs/ → shared/docs/
├── tests/ → backend/tests/ + frontend/tests/
└── staticfiles/ → dist/backend/ (generated)
```
### Detailed Backend App Moves
Each Django app moves to `backend/apps/{app_name}/` with structure preserved:
- Models, views, serializers stay the same
- Templates for API responses remain in app directories
- Static files move to frontend if UI-related
- Tests remain with respective apps
## Build and Deployment Strategy
### Development Build Process
1. **Backend**: No build step, runs directly with Django dev server
2. **Frontend**: Vite development server with HMR
3. **Shared**: Scripts orchestrate starting both services
### Production Build Process
```mermaid
graph TD
A[CI/CD Trigger] --> B[Install Dependencies]
B --> C[Build Frontend]
B --> D[Collect Django Static]
C --> E[Generate Frontend Bundle]
D --> F[Collect Backend Assets]
E --> G[Create Docker Images]
F --> G
G --> H[Deploy to Production]
```
### Container Strategy
- **Multi-stage Docker builds**: Separate backend and frontend images
- **Nginx**: Reverse proxy and static file serving
- **Volume mounts**: For media files and logs
- **Environment-based configuration**: Development vs. production
## API Integration Strategy
### Backend API Structure
```python
# Enhanced DRF setup for SPA
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
}
# CORS for development
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # Vue dev server
]
```
### Frontend API Service
```javascript
// API service with auth integration
class ApiService {
constructor() {
this.client = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
withCredentials: true,
});
}
// Park operations
getParks(params = {}) {
return this.client.get('/parks/', { params });
}
// Ride operations
getRides(parkId, params = {}) {
return this.client.get(`/parks/${parkId}/rides/`, { params });
}
}
```
## Configuration Management
### Shared Environment Variables
- Database connections
- Redis/Cache settings
- Secret keys and API keys
- Feature flags
### Application-Specific Settings
- **Django**: `backend/config/django/`
- **Vue.js**: `frontend/.env` files
- **Docker**: `shared/config/docker/`
### Development vs. Production
- Development: Multiple local servers, hot reloading
- Production: Containerized deployment, CDN integration
## Benefits of This Structure
1. **Clear Separation**: Backend and frontend concerns are clearly separated
2. **Scalability**: Each part can be developed, tested, and deployed independently
3. **Modern Workflow**: Supports latest Vue 3, Vite, and Django patterns
4. **Backward Compatibility**: Preserves existing Django app structure
5. **Developer Experience**: Hot reloading, TypeScript support, modern tooling
6. **Deployment Flexibility**: Can deploy as SPA + API or traditional Django
## Implementation Phases
### Phase 1: Structure Setup
1. Create new directory structure
2. Move Django code to `backend/`
3. Initialize Vue.js frontend
4. Set up basic API integration
### Phase 2: Frontend Development
1. Create Vue.js components for existing Django templates
2. Implement routing and state management
3. Integrate with Django API endpoints
4. Add authentication flow
### Phase 3: Build & Deploy
1. Set up build processes
2. Configure CI/CD pipelines
3. Implement production deployment
4. Performance optimization
## Considerations and Trade-offs
### Advantages
- Modern development experience
- Better code organization
- Independent scaling
- Rich frontend interactions
- API-first architecture
### Challenges
- Increased complexity
- Build process coordination
- Authentication across services
- SEO considerations (if needed)
- Development environment setup
## Next Steps
1. **Validate Architecture**: Review with development team
2. **Prototype Setup**: Create basic structure with sample components
3. **Migration Planning**: Detailed plan for moving existing code
4. **Tool Selection**: Finalize Vue.js ecosystem choices (Pinia vs. Vuex, etc.)
5. **Implementation**: Begin phase-by-phase migration
---
This architecture provides a solid foundation for migrating ThrillWiki to a modern Django + Vue.js monorepo while preserving existing functionality and enabling future growth.

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 530 B

After

Width:  |  Height:  |  Size: 530 B

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 366 B

After

Width:  |  Height:  |  Size: 366 B

View File

Before

Width:  |  Height:  |  Size: 355 B

After

Width:  |  Height:  |  Size: 355 B

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 362 B

After

Width:  |  Height:  |  Size: 362 B

View File

Before

Width:  |  Height:  |  Size: 317 B

After

Width:  |  Height:  |  Size: 317 B

View File

Before

Width:  |  Height:  |  Size: 486 B

After

Width:  |  Height:  |  Size: 486 B

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 333 B

After

Width:  |  Height:  |  Size: 333 B

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

Before

Width:  |  Height:  |  Size: 342 B

After

Width:  |  Height:  |  Size: 342 B

View File

Before

Width:  |  Height:  |  Size: 910 B

After

Width:  |  Height:  |  Size: 910 B

Some files were not shown because too many files have changed in this diff Show More