Major database enhancement implementing fast-querying season batting stats: Database Schema: - Created seasonbattingstats table with composite primary key (player_id, season) - All batting stats (counting + calculated): pa, ab, avg, obp, slg, ops, woba, etc. - Proper foreign key constraints and performance indexes - Production-ready SQL creation script included Selective Update System: - update_season_batting_stats() function with PostgreSQL upsert logic - Triggers on game PATCH operations to update affected player stats - Recalculates complete season stats from stratplay data - Efficient updates of only players who participated in modified games API Enhancements: - Enhanced SeasonBattingStats.get_top_hitters() with full filtering support - New /api/v3/views/season-stats/batting/refresh endpoint for season rebuilds - Updated views endpoint to use centralized get_top_hitters() method - Support for team, player, min PA, and pagination filtering Infrastructure: - Production database sync Docker service with SSH automation - Comprehensive error handling and logging throughout - Fixed Peewee model to match actual table structure (no auto-id) - Updated CLAUDE.md with dev server info and sync commands 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
108 lines
5.5 KiB
Markdown
108 lines
5.5 KiB
Markdown
# 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
|
|
- **Primary**: PostgreSQL via `PooledPostgresqlDatabase` (production)
|
|
- **Fallback**: SQLite with WAL mode (`storage/sba_master.db`)
|
|
- **ORM**: Peewee with model-based schema definition
|
|
- **Migrations**: Manual migrations via `playhouse.migrate`
|
|
|
|
### 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
|
|
|
|
### Environment Variables
|
|
**Required**:
|
|
- `API_TOKEN` - Authentication token for API access
|
|
- `DATABASE_TYPE` - 'postgresql' or 'sqlite' (defaults to sqlite)
|
|
|
|
**PostgreSQL Configuration**:
|
|
- `POSTGRES_HOST`, `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_PORT`
|
|
|
|
**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
|
|
|
|
### 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
|
|
- The system supports both SQLite (development) and PostgreSQL (production) backends
|
|
- Database migrations must be manually coded using Peewee's migration system
|
|
- Authentication is required for all endpoints except documentation |