## Player Model Migration - Migrate Player model from Discord app following Model/Service Architecture pattern - Extract all business logic from Player model to PlayerService - Create pure data model with PostgreSQL relationships (Cardset, PositionRating) - Implement comprehensive PlayerFactory with specialized methods for test data ## PlayerService Implementation - Extract 5 business logic methods from original Player model: - get_batter_card_url() - batting card URL retrieval - get_pitcher_card_url() - pitching card URL retrieval - generate_name_card_link() - markdown link generation - get_formatted_name_with_description() - name formatting - get_player_description() - description from object or dict - Follow BaseService pattern with dependency injection and logging ## Comprehensive Testing - 35 passing Player tests (14 model + 21 service tests) - PlayerFactory with specialized methods (batting/pitching cards, positions) - Test isolation following factory pattern and db_session guidelines - Fix PostgreSQL integer overflow in test ID generation ## Integration Test Infrastructure - Create integration test framework for improving service coverage - Design AIService integration tests targeting uncovered branches - Demonstrate real database query testing with proper isolation - Establish patterns for testing complex game scenarios ## Service Coverage Analysis - Current service coverage: 61% overall - PlayerService: 100% coverage (excellent migration example) - AIService: 60% coverage (improvement opportunities identified) - Integration test strategy designed to achieve 90%+ coverage ## Database Integration - Update Cardset model to include players relationship - Update PositionRating model with proper Player foreign key - Maintain all existing relationships and constraints - Demonstrate data isolation and automatic cleanup in tests ## Test Suite Status - 137 tests passing, 0 failures (maintained 100% pass rate) - Added 35 new tests while preserving all existing functionality - Integration test infrastructure ready for coverage improvements 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> |
||
|---|---|---|
| .. | ||
| __init__.py | ||
| ai_service.py | ||
| base_service.py | ||
| player_service.py | ||
| README.md | ||
| service_container.py | ||
| ui_service.py | ||
Services Directory
This directory contains the business logic layer of the Model/Service Architecture. Services are the core of the application architecture, containing all business rules and logic separated from HTTP concerns and database details.
Architecture Pattern
Service Responsibilities
- Business Logic: Core application logic and rules
- Data Validation: Input validation and business rule enforcement
- Service Orchestration: Coordination between multiple services
- Error Handling: Business-appropriate error handling and logging
Design Principles
- Single Responsibility: Each service has one clear purpose
- Dependency Injection: Services receive dependencies via constructor
- Stateless: Services don't maintain instance state between calls
- Testable: Services can be unit tested with mocked dependencies
- Pure Business Logic: No HTTP, database, or UI concerns
Current Files
base_service.py
Abstract base class providing common functionality:
- Standardized logging:
self._log_operation()andself._log_error() - Session management: SQLModel database session handling
- Validation helpers: Common validation patterns
service_container.py
Dependency injection container:
- Database sessions: Session lifecycle management
- Service dependencies: FastAPI
Depends()integration - Type annotations: Service dependency type aliases
Planned Services
Core Game Services
- GameService: Game creation, management, queries
- GameplayService: Core gameplay simulation & flow
- AIService: AI decision making and automation
Supporting Services
- UserService: User sessions, preferences
- AuthService: Discord OAuth, session management
- NotificationService: Web notifications and real-time updates
Service Pattern Example
from app.services.base_service import BaseService
from app.services.service_container import SessionDep
class GameService(BaseService):
def __init__(self, session: Session):
super().__init__(session)
async def create_game(self, away_team_id: int, home_team_id: int) -> Game:
self._log_operation("create_game", f"Teams: {away_team_id} vs {home_team_id}")
# Business logic here
game = Game(away_team_id=away_team_id, home_team_id=home_team_id)
# Database persistence
self.session.add(game)
self.session.commit()
return game
Dependency Injection
Services are injected into routes using FastAPI's Depends():
from app.services.service_container import GameServiceDep
@router.post("/games/start")
async def start_game(game_service: GameServiceDep):
# Service contains business logic, route handles HTTP concerns
return await game_service.create_game(away_team_id=1, home_team_id=2)
Testing Services
Services should be unit tested independently:
@pytest.fixture
def mock_session():
return Mock(spec=Session)
@pytest.fixture
def game_service(mock_session):
return GameService(mock_session)
async def test_create_game(game_service):
# Test business logic without database
result = await game_service.create_game(1, 2)
assert result.away_team_id == 1
Migration from Discord App
When migrating from ../discord-app/:
- Extract business logic from Discord command handlers
- Remove Discord dependencies (discord.py, interaction objects)
- Create service methods with pure business logic
- Add comprehensive unit tests for service methods
- Create thin route handlers that delegate to services