Establishes foundation for migrating baseball simulation from Discord bot to web application using service-oriented architecture pattern. Key components: - FastAPI application structure with dependency injection - Service layer foundation with base classes and container - Comprehensive directory documentation with README files - PostgreSQL containerization with Docker Compose - Testing structure for unit/integration/e2e tests - Migration planning documentation - Rotating log configuration per user requirements Architecture follows Model/Service/Controller pattern to improve testability, maintainability, and scalability over original monolithic Discord app. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
525 lines
18 KiB
Markdown
525 lines
18 KiB
Markdown
# Paper Dynasty Web App Migration Plan v2.0
|
|
## Model/Service Architecture Edition
|
|
|
|
## Project Overview
|
|
Migrating the baseball gameplay functionality from the Discord app (`../discord-app/`) to a standalone web application using **FastAPI + Model/Service Architecture**. This approach provides better separation of concerns, testability, and scalability compared to the original monolithic migration plan.
|
|
|
|
## Architecture Overview
|
|
|
|
### Why Model/Service Architecture?
|
|
Based on analysis of the Discord app complexity (15K+ line files), a service-oriented approach will:
|
|
- **Improve Testability**: Services can be unit tested independently
|
|
- **Enhance Maintainability**: Clear separation between business logic and web framework
|
|
- **Enable Scalability**: Easy to add caching, background tasks, API versioning
|
|
- **Future-Proof**: Ready for mobile API, microservices, or different frontends
|
|
|
|
### Technology Stack
|
|
- **Backend**: FastAPI + SQLModel + PostgreSQL
|
|
- **Architecture**: Model/Service/Controller pattern
|
|
- **Frontend**: Jinja2 templates + HTMX + TailwindCSS
|
|
- **Testing**: pytest with comprehensive service unit tests
|
|
- **Real-time**: HTMX polling with WebSocket upgrade path
|
|
|
|
---
|
|
|
|
## Progress Tracking
|
|
|
|
### 🚧 Current Phase
|
|
- [ ] **Phase 1: Service Foundation & Models** (Days 1-4)
|
|
|
|
### 📋 Upcoming Phases
|
|
- [ ] **Phase 2: Core Game Services** (Days 5-9)
|
|
- [ ] **Phase 3: Web Interface with Services** (Days 10-14)
|
|
- [ ] **Phase 4: Advanced Features & Optimization** (Days 15-17)
|
|
|
|
---
|
|
|
|
## Phase 1: Service Foundation & Models (Days 1-4)
|
|
|
|
### Day 1: Project Setup & Service Foundation
|
|
#### Tasks
|
|
- [ ] Initialize FastAPI project with service-oriented structure
|
|
- [ ] Set up dependency injection patterns for services
|
|
- [ ] Create base service classes and interfaces
|
|
- [ ] Configure logging with rotating handlers
|
|
- [ ] Set up virtual environment and requirements
|
|
|
|
#### Service Architecture Setup
|
|
```
|
|
app/
|
|
├── services/
|
|
│ ├── __init__.py
|
|
│ ├── base_service.py # Base service class
|
|
│ └── service_container.py # Dependency injection
|
|
├── models/
|
|
├── routers/
|
|
├── engine/
|
|
└── repositories/ # Optional data access layer
|
|
```
|
|
|
|
#### Code Review Checklist - Foundation
|
|
- [ ] Service base classes follow single responsibility principle
|
|
- [ ] Dependency injection properly configured
|
|
- [ ] Logging follows rotating pattern from user's CLAUDE.md
|
|
- [ ] Virtual environment properly configured
|
|
- [ ] Project structure supports service-oriented development
|
|
|
|
#### Success Criteria
|
|
- [ ] FastAPI server starts without errors
|
|
- [ ] Base service classes created and testable
|
|
- [ ] Dependency injection working
|
|
- [ ] Service unit test framework established
|
|
|
|
---
|
|
|
|
### Day 2: Database Models Migration
|
|
#### Tasks
|
|
- [ ] Migrate core gameplay models from `../discord-app/in_game/gameplay_models.py`
|
|
- [ ] Remove Discord dependencies (discord.Embed, etc.)
|
|
- [ ] Add web-specific models (sessions, preferences, notifications)
|
|
- [ ] Set up PostgreSQL with Docker for testing
|
|
- [ ] Create model validation and relationship tests
|
|
|
|
#### Models to Migrate
|
|
- `Game`, `Team`, `Player`, `Lineup`, `Play` (core gameplay)
|
|
- `Card`, `Cardset`, `ManagerAi` (game content)
|
|
- `WebSession`, `UserPreferences`, `GameViewState` (web-specific)
|
|
|
|
#### Code Review Checklist - Models
|
|
- [ ] All Discord imports removed
|
|
- [ ] Field types and constraints validated for PostgreSQL
|
|
- [ ] Relationships properly defined with foreign keys
|
|
- [ ] Web-specific models added for session management
|
|
- [ ] Model tests cover creation, relationships, and validation
|
|
|
|
#### Success Criteria
|
|
- [ ] All models work with PostgreSQL
|
|
- [ ] 90%+ test coverage on model functionality
|
|
- [ ] Foreign key relationships properly defined
|
|
- [ ] Web session models support user management
|
|
|
|
---
|
|
|
|
### Day 3: Core Engine Migration (Stateless)
|
|
#### Tasks
|
|
- [ ] Migrate `../discord-app/dice.py` → `engine/dice.py`
|
|
- [ ] Migrate `../discord-app/in_game/simulations.py` → `engine/simulation.py`
|
|
- [ ] Create `engine/calculations.py` for statistics and WPA
|
|
- [ ] Ensure engine components are stateless and pure
|
|
- [ ] Add comprehensive engine unit tests
|
|
|
|
#### Engine Components
|
|
- **dice.py**: Dice rolling, fielding checks, X-chart integration
|
|
- **simulation.py**: Pitcher vs batter mechanics, outcome calculation
|
|
- **calculations.py**: Statistics, WPA, game metrics
|
|
|
|
#### Code Review Checklist - Engine
|
|
- [ ] All engine functions are pure (no side effects)
|
|
- [ ] Random operations use proper seeding for testing
|
|
- [ ] No Discord dependencies remain
|
|
- [ ] Type hints added for all functions
|
|
- [ ] Edge cases in game rules properly handled
|
|
|
|
#### Success Criteria
|
|
- [ ] Engine components are stateless and testable
|
|
- [ ] Dice probability distributions validated
|
|
- [ ] Pitcher vs batter simulation accuracy confirmed
|
|
- [ ] 95%+ test coverage on core engine logic
|
|
|
|
---
|
|
|
|
### Day 4: Service Layer Foundation
|
|
#### Tasks
|
|
- [ ] Create `services/game_service.py` with basic game management
|
|
- [ ] Create `services/user_service.py` for session management
|
|
- [ ] Create `services/auth_service.py` for Discord OAuth
|
|
- [ ] Implement service dependency injection in FastAPI
|
|
- [ ] Add service unit tests with mocked dependencies
|
|
|
|
#### Service Interfaces
|
|
```python
|
|
class GameService:
|
|
async def create_game(self, away_team_id: int, home_team_id: int) -> Game
|
|
async def get_game(self, game_id: int) -> Game
|
|
async def list_active_games(self) -> List[Game]
|
|
|
|
class UserService:
|
|
async def create_session(self, discord_user_id: int) -> WebSession
|
|
async def get_user_preferences(self, session_id: str) -> UserPreferences
|
|
|
|
class AuthService:
|
|
async def authenticate_discord(self, oauth_code: str) -> WebSession
|
|
async def validate_session(self, session_id: str) -> bool
|
|
```
|
|
|
|
#### Code Review Checklist - Services
|
|
- [ ] Services have clear, single responsibilities
|
|
- [ ] All service methods have type hints
|
|
- [ ] Services use dependency injection for database sessions
|
|
- [ ] Service unit tests use mocked dependencies
|
|
- [ ] Business logic separated from data access
|
|
|
|
#### Success Criteria
|
|
- [ ] Basic services implement core functionality
|
|
- [ ] Services can be unit tested independently
|
|
- [ ] Dependency injection working in FastAPI routes
|
|
- [ ] Service interfaces support expected web app features
|
|
|
|
---
|
|
|
|
## Phase 2: Core Game Services (Days 5-9)
|
|
|
|
### Day 5: Gameplay Service Architecture
|
|
#### Tasks
|
|
- [ ] Extract complex gameplay logic from `../discord-app/command_logic/logic_gameplay.py`
|
|
- [ ] Create `services/gameplay_service.py` for core game flow
|
|
- [ ] Implement play execution and validation
|
|
- [ ] Add inning management and state transitions
|
|
- [ ] Create comprehensive gameplay service tests
|
|
|
|
#### GameplayService Responsibilities
|
|
- Play execution and validation
|
|
- Game state management
|
|
- Inning progression logic
|
|
- Score calculation and updates
|
|
- Game completion detection
|
|
|
|
---
|
|
|
|
### Day 6: AI Service Implementation
|
|
#### Tasks
|
|
- [ ] Migrate `../discord-app/in_game/ai_manager.py` → `services/ai_service.py`
|
|
- [ ] Remove Discord interaction dependencies
|
|
- [ ] Implement AI decision-making for automated teams
|
|
- [ ] Add AI personality and difficulty settings
|
|
- [ ] Create AI behavior validation tests
|
|
|
|
#### AIService Responsibilities
|
|
- Manager AI decision making
|
|
- Lineup optimization
|
|
- Pitching decisions
|
|
- Defensive positioning
|
|
- Strategic game management
|
|
|
|
---
|
|
|
|
### Day 7: Advanced Game Services
|
|
#### Tasks
|
|
- [ ] Create `services/simulation_service.py` for game simulation orchestration
|
|
- [ ] Implement `services/statistics_service.py` for player/team stats
|
|
- [ ] Add `services/notification_service.py` for real-time updates
|
|
- [ ] Integrate services with each other using dependency injection
|
|
- [ ] Add integration tests for service interactions
|
|
|
|
---
|
|
|
|
### Days 8-9: Service Integration & Testing
|
|
#### Tasks
|
|
- [ ] Complete end-to-end service integration
|
|
- [ ] Add performance optimization for service calls
|
|
- [ ] Implement caching strategies for expensive operations
|
|
- [ ] Create comprehensive integration test suite
|
|
- [ ] Validate service architecture with complex game scenarios
|
|
|
|
#### Code Review Checklist - Service Integration
|
|
- [ ] Services interact cleanly without tight coupling
|
|
- [ ] Database queries optimized (no N+1 issues)
|
|
- [ ] Error handling propagates correctly through service layers
|
|
- [ ] Performance acceptable for concurrent users
|
|
- [ ] All service interactions have integration tests
|
|
|
|
#### Success Criteria
|
|
- [ ] Complete game can be simulated using services
|
|
- [ ] All services have 90%+ unit test coverage
|
|
- [ ] Integration tests validate full game flows
|
|
- [ ] Performance benchmarks met for service calls
|
|
|
|
---
|
|
|
|
## Phase 3: Web Interface with Services (Days 10-14)
|
|
|
|
### Day 10: FastAPI Route Architecture
|
|
#### Tasks
|
|
- [ ] Create `routers/games.py` using GameService
|
|
- [ ] Create `routers/auth.py` using AuthService
|
|
- [ ] Create `routers/api.py` for HTMX endpoints
|
|
- [ ] Implement dependency injection for services in routes
|
|
- [ ] Add route-level error handling and validation
|
|
|
|
#### Route Design Pattern
|
|
```python
|
|
@router.post("/games/start")
|
|
async def start_game(
|
|
request: StartGameRequest,
|
|
game_service: GameService = Depends(get_game_service),
|
|
user_service: UserService = Depends(get_user_service)
|
|
):
|
|
# Thin controller - delegate to services
|
|
session = await user_service.validate_session(request.session_id)
|
|
game = await game_service.create_game(
|
|
away_team_id=request.away_team_id,
|
|
home_team_id=request.home_team_id
|
|
)
|
|
return {"game_id": game.id}
|
|
```
|
|
|
|
---
|
|
|
|
### Day 11: Authentication & Session Management
|
|
#### Tasks
|
|
- [ ] Implement Discord OAuth flow using AuthService
|
|
- [ ] Create session management with UserService
|
|
- [ ] Add user preference handling
|
|
- [ ] Implement authentication middleware
|
|
- [ ] Add authentication integration tests
|
|
|
|
---
|
|
|
|
### Day 12-13: Game Interface Implementation
|
|
#### Tasks
|
|
- [ ] Create game lobby system using GameService
|
|
- [ ] Implement real-time game board with GameplayService
|
|
- [ ] Add player action forms with service validation
|
|
- [ ] Create scoreboard using StatisticsService
|
|
- [ ] Implement HTMX polling for live updates
|
|
|
|
---
|
|
|
|
### Day 14: Web Interface Polish
|
|
#### Tasks
|
|
- [ ] Add comprehensive error handling in routes
|
|
- [ ] Implement responsive design with TailwindCSS
|
|
- [ ] Add client-side validation with HTMX
|
|
- [ ] Create user preference management interface
|
|
- [ ] Add end-to-end web interface tests
|
|
|
|
#### Code Review Checklist - Web Interface
|
|
- [ ] Routes are thin, delegating business logic to services
|
|
- [ ] HTMX requests handle errors gracefully
|
|
- [ ] Forms have proper validation (client and server-side)
|
|
- [ ] UI is responsive and mobile-friendly
|
|
- [ ] Game state updates are atomic through services
|
|
|
|
#### Success Criteria
|
|
- [ ] Complete single-player game flow working
|
|
- [ ] Discord OAuth login/logout functional
|
|
- [ ] Real-time updates working via HTMX polling
|
|
- [ ] Responsive design works on mobile and desktop
|
|
- [ ] All web interfaces use services (no direct database access)
|
|
|
|
---
|
|
|
|
## Phase 4: Advanced Features & Optimization (Days 15-17)
|
|
|
|
### Day 15: Repository Layer (Optional)
|
|
#### Tasks
|
|
- [ ] Evaluate need for repository pattern for complex queries
|
|
- [ ] Implement `repositories/game_repository.py` if needed
|
|
- [ ] Add query optimization and caching
|
|
- [ ] Refactor services to use repositories
|
|
- [ ] Add repository unit tests
|
|
|
|
#### Repository Pattern (If Needed)
|
|
```python
|
|
class GameRepository:
|
|
def __init__(self, session: Session):
|
|
self.session = session
|
|
|
|
async def get_games_with_stats(self, filters: GameFilters) -> List[Game]:
|
|
# Complex query logic separated from service
|
|
pass
|
|
|
|
class GameService:
|
|
def __init__(self, session: Session, game_repo: GameRepository):
|
|
self.session = session
|
|
self.game_repo = game_repo
|
|
|
|
async def get_leaderboard(self, filters: GameFilters) -> List[GameStats]:
|
|
# Service uses repository for complex queries
|
|
games = await self.game_repo.get_games_with_stats(filters)
|
|
return self._calculate_leaderboard(games)
|
|
```
|
|
|
|
---
|
|
|
|
### Day 16: Performance & Caching
|
|
#### Tasks
|
|
- [ ] Add Redis caching for expensive service operations
|
|
- [ ] Implement database query optimization
|
|
- [ ] Add performance monitoring and metrics
|
|
- [ ] Optimize service call patterns
|
|
- [ ] Add load testing for concurrent users
|
|
|
|
---
|
|
|
|
### Day 17: Final Polish & Documentation
|
|
#### Tasks
|
|
- [ ] Complete comprehensive test suite (unit, integration, e2e)
|
|
- [ ] Add API documentation with FastAPI auto-generation
|
|
- [ ] Performance optimization and final benchmarking
|
|
- [ ] Code review and refactoring
|
|
- [ ] Deployment preparation
|
|
|
|
---
|
|
|
|
## Testing Architecture
|
|
|
|
### Test Structure
|
|
```
|
|
tests/
|
|
├── unit/ # Fast, isolated unit tests
|
|
│ ├── services/ # Service unit tests (most important)
|
|
│ │ ├── test_game_service.py
|
|
│ │ ├── test_gameplay_service.py
|
|
│ │ ├── test_ai_service.py
|
|
│ │ └── test_user_service.py
|
|
│ ├── engine/ # Engine unit tests
|
|
│ │ ├── test_dice.py
|
|
│ │ ├── test_simulation.py
|
|
│ │ └── test_calculations.py
|
|
│ └── models/ # Model validation tests
|
|
│ └── test_models.py
|
|
├── integration/ # Service + database integration
|
|
│ ├── test_game_flow.py
|
|
│ ├── test_auth_flow.py
|
|
│ └── test_service_integration.py
|
|
└── e2e/ # Full application tests
|
|
├── test_game_creation.py
|
|
├── test_gameplay_flow.py
|
|
└── test_user_journey.py
|
|
```
|
|
|
|
### Testing Priorities
|
|
|
|
#### Unit Tests (90%+ Coverage Required)
|
|
- **Critical**: All service methods, core engine functions
|
|
- **Important**: Model validation, business logic edge cases
|
|
- **Nice to have**: Repository methods (if implemented)
|
|
|
|
#### Integration Tests (80%+ Coverage)
|
|
- **Critical**: Service interactions, database transactions
|
|
- **Important**: Authentication flows, game state persistence
|
|
- **Nice to have**: Performance characteristics
|
|
|
|
#### E2E Tests (Happy Path Coverage)
|
|
- **Critical**: Complete game creation and play flow
|
|
- **Important**: User authentication and session management
|
|
- **Nice to have**: Error handling and edge cases
|
|
|
|
---
|
|
|
|
## Architecture Decisions
|
|
|
|
### Service Layer Benefits
|
|
- **Testability**: Services can be unit tested with mocked dependencies
|
|
- **Maintainability**: Business logic centralized, not scattered across routes
|
|
- **Scalability**: Easy to add caching, background tasks, monitoring
|
|
- **Flexibility**: Services can be used by different interfaces (web, API, CLI)
|
|
|
|
### Repository Pattern (Optional)
|
|
- **When to use**: Complex queries, multiple data sources, query optimization
|
|
- **When to skip**: Simple CRUD operations, small project scope
|
|
- **Decision**: Evaluate during Day 15 based on query complexity
|
|
|
|
### Dependency Injection Strategy
|
|
- **FastAPI Depends()**: For HTTP request-scoped dependencies
|
|
- **Service constructors**: For service-to-service dependencies
|
|
- **Configuration**: Environment-based configuration injection
|
|
|
|
---
|
|
|
|
## Migration Notes & Decisions
|
|
|
|
### Service Extraction Strategy
|
|
1. **Identify Business Logic**: Extract from Discord command handlers
|
|
2. **Create Service Interface**: Define clear method signatures
|
|
3. **Write Tests First**: Test-driven service development
|
|
4. **Implement Service**: Pure business logic, no framework dependencies
|
|
5. **Integrate with Routes**: Thin controllers using services
|
|
|
|
### Discord App Analysis for Service Extraction
|
|
|
|
#### High-Value Extractions
|
|
- `command_logic/logic_gameplay.py` (4,186 lines) → Multiple services
|
|
- `in_game/ai_manager.py` → `services/ai_service.py`
|
|
- Game creation/management → `services/game_service.py`
|
|
- User/session management → `services/user_service.py`
|
|
|
|
#### Keep as Stateless Engine
|
|
- `dice.py` → `engine/dice.py` (pure functions)
|
|
- `in_game/simulations.py` → `engine/simulation.py` (calculations)
|
|
|
|
---
|
|
|
|
## Success Criteria
|
|
|
|
### Architecture Quality
|
|
- [ ] Clear separation: Models → Services → Controllers (Routes)
|
|
- [ ] Services have single, well-defined responsibilities
|
|
- [ ] Business logic not mixed with web framework code
|
|
- [ ] Dependency injection working throughout application
|
|
|
|
### Code Quality Standards
|
|
- [ ] Services have 90%+ unit test coverage
|
|
- [ ] Integration tests cover service interactions
|
|
- [ ] Type hints on all service methods
|
|
- [ ] Error handling appropriate for each layer
|
|
- [ ] Performance acceptable for multiple concurrent users
|
|
|
|
### Migration Success
|
|
- [ ] Working single-player baseball game with Discord OAuth
|
|
- [ ] Live scoreboard with HTMX real-time updates
|
|
- [ ] Clean, service-oriented codebase ready for scaling
|
|
- [ ] Comprehensive test coverage across all layers
|
|
- [ ] Responsive web interface (mobile + desktop)
|
|
- [ ] No Discord-specific dependencies remaining
|
|
|
|
### Service Architecture Validation
|
|
- [ ] Services can be unit tested independently
|
|
- [ ] Business logic easily modifiable without touching routes
|
|
- [ ] New features can be added by extending services
|
|
- [ ] Multiple interfaces (web, API) can use same services
|
|
|
|
---
|
|
|
|
## Future Enhancements (Post-MVP)
|
|
|
|
### Microservices Evolution
|
|
- Services are designed to be extracted into microservices later
|
|
- Clean service interfaces support API versioning
|
|
- Database access patterns support service splitting
|
|
|
|
### Advanced Features
|
|
- Background task processing using service layer
|
|
- Multiple client support (mobile app, desktop)
|
|
- Real-time multiplayer using service orchestration
|
|
- Analytics and monitoring built into service layer
|
|
|
|
---
|
|
|
|
## Notes for Future AI Agents
|
|
|
|
### Service-First Development
|
|
1. **Always start with services** when adding new features
|
|
2. **Write service tests first** before implementation
|
|
3. **Keep routes thin** - delegate to services
|
|
4. **Test services independently** with mocked dependencies
|
|
5. **Use dependency injection** for all service interactions
|
|
|
|
### Migration Best Practices
|
|
1. **Extract business logic** from Discord command handlers
|
|
2. **Remove all Discord dependencies** before service implementation
|
|
3. **Test service logic** independently of web framework
|
|
4. **Integrate services** into routes using FastAPI Depends()
|
|
5. **Validate service architecture** with integration tests
|
|
|
|
### Maintenance Guidelines
|
|
- Update service tests when changing business logic
|
|
- Keep service interfaces stable for backward compatibility
|
|
- Add new features by extending services, not routes
|
|
- Monitor service performance and add caching as needed
|
|
- Document service interactions and dependencies
|
|
|
|
---
|
|
|
|
Remember: This migration uses **Model/Service Architecture** to create a scalable, maintainable web application. Always prioritize clean service design and comprehensive testing over speed of development. The service layer is the foundation that will support future growth and feature additions. |