# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview This is the Database API component of the Major Domo system - a FastAPI backend serving data for a Strat-o-Matic Baseball Association (SBA) fantasy league. It provides REST endpoints for Discord bots and web frontends to access league data. ## Development Commands ### Local Development - **Dev server location**: `10.10.0.42` - **Start all services**: `docker-compose up` (PostgreSQL + API + Adminer) - **Build and start**: `docker-compose up --build` (rebuilds image with latest changes) - **Sync from production**: `docker-compose --profile sync up sync-prod` (one-time production data sync) - **Database migrations**: `python migrations.py` (uses files in root directory) - **Database admin interface**: Available at `http://10.10.0.42:8080` (Adminer) ### Docker Deployment - **Production deployment**: Uses same `docker-compose up` workflow - **Production server access**: `ssh akamai` then `cd container-data/sba-database` - **Manual build**: `docker build -f Dockerfile -t major-domo-database .` ## Architecture ### Application Structure ``` app/ ├── main.py # FastAPI application setup, router registration ├── db_engine.py # Peewee ORM models, database configuration ├── dependencies.py # Authentication, error handling decorators └── routers_v3/ # API endpoints organized by domain ├── awards.py # League awards and recognition endpoints ├── battingstats.py # Batting statistics (seasonal and career) ├── current.py # Current season/week status and configuration ├── custom_commands.py # Custom command creation and management ├── decisions.py # Strat-o-Matic game decisions and choices ├── divisions.py # League division information ├── draftdata.py # Draft status and current pick tracking ├── draftlist.py # Team draft priority lists and rankings ├── draftpicks.py # Draft pick ownership and trading ├── fieldingstats.py # Fielding statistics (seasonal and career) ├── injuries.py # Player injury tracking and management ├── keepers.py # Keeper selection and management ├── managers.py # Team manager information and profiles ├── pitchingstats.py # Pitching statistics (seasonal and career) ├── players.py # Player information, rosters, and statistics ├── results.py # Game results and outcomes ├── sbaplayers.py # SBA player pool and eligibility ├── schedules.py # Game scheduling and matchups ├── standings.py # League standings and team records ├── stratgame.py # Strat-o-Matic game data and simulation ├── stratplay.py # Individual play-by-play data and analysis ├── teams.py # Team data, rosters, and organization ├── transactions.py # Player transactions (trades, waivers, etc.) └── views.py # Database views and aggregated statistics ``` ### Database Configuration - **Database**: PostgreSQL via `PooledPostgresqlDatabase` (production and development) - **ORM**: Peewee with model-based schema definition - **Migrations**: SQL migration files in `migrations/` directory - **Table Naming**: Peewee models must specify `Meta.table_name` to match PostgreSQL table names ### Authentication & Error Handling - **Authentication**: OAuth2 bearer token validation via `API_TOKEN` environment variable - **Error Handling**: `@handle_db_errors` decorator provides comprehensive logging, rollback, and HTTP error responses - **Logging**: Rotating file handler (`/tmp/sba-database.log`, 8MB max, 5 backups) ### API Design Patterns - **Routers**: Domain-based organization under `/api/v3/` prefix - **Models**: Pydantic models for request/response validation - **Database Access**: Direct Peewee ORM queries with automatic connection pooling - **Response Format**: Consistent JSON with proper HTTP status codes - **POST Requests**: Pydantic models for POST (create) endpoints should use `Optional[int] = None` for `id` fields since the database auto-generates IDs ### Environment Variables **Required**: - `API_TOKEN` - Authentication token for API access **PostgreSQL Configuration** (required): - `POSTGRES_HOST` - PostgreSQL server hostname (default: 10.10.0.42) - `POSTGRES_DB` - Database name (default: sba_master) - `POSTGRES_USER` - Database user (default: sba_admin) - `POSTGRES_PASSWORD` - Database password - `POSTGRES_PORT` - Database port (default: 5432) **Optional**: - `LOG_LEVEL` - INFO or WARNING (defaults to WARNING) - `PRIVATE_IN_SCHEMA` - Include private endpoints in OpenAPI schema ### Key Data Models - **Current**: Season/week status, trade deadlines, playoff schedule - **Player/Team**: Core entities with seasonal and career statistics - **Statistics**: Separate models for batting, pitching, fielding (seasonal + career) - **Draft System**: Draft picks, draft lists, keeper selections - **Game Data**: Schedules, results, Strat-o-Matic play-by-play data - **League Management**: Standings, transactions, injuries, decisions - **Custom Commands**: User-created Discord bot commands with creator tracking and usage statistics - **Help Commands**: Static help text for Discord bot commands ### Testing & Quality - **No formal test framework currently configured** - **API Documentation**: Auto-generated OpenAPI/Swagger at `/api/docs` - **Health Checks**: Built into Docker configuration - **Database Integrity**: Transaction rollback on errors via decorator ## Important Notes - All active development occurs in the `/app` directory - Root directory files (`main.py`, `db_engine.py`, etc.) are legacy and not in use - **PostgreSQL migration completed**: System now uses PostgreSQL exclusively (no SQLite fallback) - Database migrations are SQL files in `migrations/` directory, applied manually via psql - Authentication is required for all endpoints except documentation and public read endpoints - **Peewee Models**: Always specify `Meta.table_name` to match PostgreSQL naming conventions - **Custom Commands**: Fully functional with creator tracking, usage statistics, and Discord bot integration