Add helper functions for Glory

This commit is contained in:
Backend IM Bot 2025-03-27 21:25:48 +00:00
parent 555a5b364f
commit ee15dcc594

View File

@ -1,152 +1,115 @@
from typing import List, Dict, Optional, Union, Any
from sqlalchemy.orm import Session
from datetime import datetime
from models.glory import Glory
from schemas.glory import GloryCreate, GloryUpdate
def calculate_goal_difference(goals_for: int, goals_against: int) -> int:
def validate_team_name(team_name: str) -> bool:
"""
Calculate goal difference for a team.
Validates team name format and length.
Args:
goals_for: Goals scored by team
goals_against: Goals conceded by team
team_name: Name of the team to validate
Returns:
int: Goal difference
bool: True if valid, False otherwise
"""
return goals_for - goals_against
if not team_name or len(team_name) < 3 or len(team_name) > 100:
return False
return bool(team_name.strip())
def update_team_stats(
team: Any,
match_result: str,
goals_scored: int,
goals_conceded: int
) -> None:
def calculate_points(wins: int, draws: int) -> int:
"""
Update team statistics after a match.
Calculates total points based on wins and draws.
Args:
team: Team object to update
match_result: Result of match ('W', 'D', 'L')
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 = calculate_goal_difference(team.goals_for, team.goals_against)
team.goal_difference = team.goals_for - team.goals_against
if match_result == 'W':
if result == 'W':
team.wins += 1
team.points += 3
elif match_result == 'D':
elif result == 'D':
team.draws += 1
team.points += 1
else:
team.losses += 1
team.points = calculate_points(team.wins, team.draws)
return team
def get_team_standings(db: Session, season: str, league: str) -> List[Dict]:
def get_team_ranking(db: Session, season: str) -> List[Glory]:
"""
Get sorted team standings for a league season.
Gets sorted team rankings for a season.
Args:
db: Database session
season: Season to get standings for
league: League to get standings for
season: Season to get rankings for
Returns:
List of teams sorted by points and goal difference
List[Glory]: Sorted list of teams by points
"""
teams = db.query(Glory).filter(
Glory.season == season,
Glory.league == league,
Glory.is_active == True
).all()
sorted_teams = sorted(
teams,
key=lambda x: (-x.points, -x.goal_difference, -x.goals_for)
)
standings = []
for position, team in enumerate(sorted_teams, 1):
team.position = position
standings.append({
"position": position,
"team_name": team.team_name,
"points": team.points,
"matches_played": team.matches_played,
"wins": team.wins,
"draws": team.draws,
"losses": team.losses,
"goals_for": team.goals_for,
"goals_against": team.goals_against,
"goal_difference": team.goal_difference
})
return standings
return db.query(Glory)\
.filter(Glory.season == season, Glory.is_active == True)\
.order_by(Glory.points.desc(), Glory.goal_difference.desc())\
.all()
def validate_team_data(team_data: Dict[str, Any]) -> Dict[str, str]:
def transfer_team_history(
db: Session,
old_team_name: str,
new_team_name: str,
season: str
) -> Union[Glory, Dict[str, str]]:
"""
Validate team data before creation/update.
Args:
team_data: Dictionary containing team data
Returns:
Dict containing error messages if validation fails
"""
errors = {}
if not team_data.get("team_name"):
errors["team_name"] = "Team name is required"
if not team_data.get("league"):
errors["league"] = "League is required"
if not team_data.get("season"):
errors["season"] = "Season is required"
if team_data.get("matches_played", 0) < 0:
errors["matches_played"] = "Matches played cannot be negative"
return errors
def get_team_form(db: Session, team_name: str, last_n: int = 5) -> str:
"""
Get team's form for last N matches.
Transfers team history when team name changes.
Args:
db: Database session
team_name: Name of team
last_n: Number of recent matches to consider
old_team_name: Previous team name
new_team_name: New team name
season: Current season
Returns:
String representing form (e.g. 'WWDLL')
Glory or error dict
"""
team = db.query(Glory).filter(
Glory.team_name == team_name,
Glory.is_active == True
).first()
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 ""
return {"error": "Team not found"}
form = ""
total_matches = team.wins + team.draws + team.losses
team.team_name = new_team_name
db.commit()
db.refresh(team)
if total_matches < last_n:
last_n = total_matches
# This is simplified - in real app would need to query actual match results
for _ in range(last_n):
if team.wins > 0:
form += "W"
team.wins -= 1
elif team.draws > 0:
form += "D"
team.draws -= 1
elif team.losses > 0:
form += "L"
team.losses -= 1
return form[::-1]
return team