vvv-sge23a/helpers/glory_helpers.py
2025-03-27 21:25:48 +00:00

115 lines
2.8 KiB
Python

from typing import List, Dict, Optional, Union, Any
from sqlalchemy.orm import Session
from models.glory import Glory
from schemas.glory import GloryCreate, GloryUpdate
def validate_team_name(team_name: str) -> bool:
"""
Validates team name format and length.
Args:
team_name: Name of the team to validate
Returns:
bool: True if valid, False otherwise
"""
if not team_name or len(team_name) < 3 or len(team_name) > 100:
return False
return bool(team_name.strip())
def calculate_points(wins: int, draws: int) -> int:
"""
Calculates total points based on wins and draws.
Args:
wins: Number of wins
draws: Number of draws
Returns:
int: Total points
"""
return (wins * 3) + draws
def update_team_stats(
team: Glory,
goals_scored: int,
goals_conceded: int,
result: str
) -> Glory:
"""
Updates team statistics after a match.
Args:
team: Glory team object
goals_scored: Goals scored in match
goals_conceded: Goals conceded in match
result: Match result ('W', 'D' or 'L')
Returns:
Glory: Updated team object
"""
team.matches_played += 1
team.goals_for += goals_scored
team.goals_against += goals_conceded
team.goal_difference = team.goals_for - team.goals_against
if result == 'W':
team.wins += 1
elif result == 'D':
team.draws += 1
else:
team.losses += 1
team.points = calculate_points(team.wins, team.draws)
return team
def get_team_ranking(db: Session, season: str) -> List[Glory]:
"""
Gets sorted team rankings for a season.
Args:
db: Database session
season: Season to get rankings for
Returns:
List[Glory]: Sorted list of teams by points
"""
return db.query(Glory)\
.filter(Glory.season == season, Glory.is_active == True)\
.order_by(Glory.points.desc(), Glory.goal_difference.desc())\
.all()
def transfer_team_history(
db: Session,
old_team_name: str,
new_team_name: str,
season: str
) -> Union[Glory, Dict[str, str]]:
"""
Transfers team history when team name changes.
Args:
db: Database session
old_team_name: Previous team name
new_team_name: New team name
season: Current season
Returns:
Glory or error dict
"""
if not validate_team_name(new_team_name):
return {"error": "Invalid new team name"}
team = db.query(Glory)\
.filter(Glory.team_name == old_team_name,
Glory.season == season)\
.first()
if not team:
return {"error": "Team not found"}
team.team_name = new_team_name
db.commit()
db.refresh(team)
return team