Add helper functions for Glory
This commit is contained in:
parent
555a5b364f
commit
ee15dcc594
@ -1,152 +1,115 @@
|
|||||||
from typing import List, Dict, Optional, Union, Any
|
from typing import List, Dict, Optional, Union, Any
|
||||||
from sqlalchemy.orm import Session
|
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:
|
Args:
|
||||||
goals_for: Goals scored by team
|
team_name: Name of the team to validate
|
||||||
goals_against: Goals conceded by team
|
|
||||||
|
|
||||||
Returns:
|
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(
|
def calculate_points(wins: int, draws: int) -> int:
|
||||||
team: Any,
|
|
||||||
match_result: str,
|
|
||||||
goals_scored: int,
|
|
||||||
goals_conceded: int
|
|
||||||
) -> None:
|
|
||||||
"""
|
"""
|
||||||
Update team statistics after a match.
|
Calculates total points based on wins and draws.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
team: Team object to update
|
wins: Number of wins
|
||||||
match_result: Result of match ('W', 'D', 'L')
|
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_scored: Goals scored in match
|
||||||
goals_conceded: Goals conceded 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.matches_played += 1
|
||||||
team.goals_for += goals_scored
|
team.goals_for += goals_scored
|
||||||
team.goals_against += goals_conceded
|
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.wins += 1
|
||||||
team.points += 3
|
elif result == 'D':
|
||||||
elif match_result == 'D':
|
|
||||||
team.draws += 1
|
team.draws += 1
|
||||||
team.points += 1
|
|
||||||
else:
|
else:
|
||||||
team.losses += 1
|
team.losses += 1
|
||||||
|
|
||||||
def get_team_standings(db: Session, season: str, league: str) -> List[Dict]:
|
team.points = calculate_points(team.wins, team.draws)
|
||||||
|
return team
|
||||||
|
|
||||||
|
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:
|
Args:
|
||||||
db: Database session
|
db: Database session
|
||||||
season: Season to get standings for
|
season: Season to get rankings for
|
||||||
league: League to get standings for
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of teams sorted by points and goal difference
|
List[Glory]: Sorted list of teams by points
|
||||||
"""
|
"""
|
||||||
teams = db.query(Glory).filter(
|
return db.query(Glory)\
|
||||||
Glory.season == season,
|
.filter(Glory.season == season, Glory.is_active == True)\
|
||||||
Glory.league == league,
|
.order_by(Glory.points.desc(), Glory.goal_difference.desc())\
|
||||||
Glory.is_active == True
|
.all()
|
||||||
).all()
|
|
||||||
|
|
||||||
sorted_teams = sorted(
|
def transfer_team_history(
|
||||||
teams,
|
db: Session,
|
||||||
key=lambda x: (-x.points, -x.goal_difference, -x.goals_for)
|
old_team_name: str,
|
||||||
)
|
new_team_name: str,
|
||||||
|
season: str
|
||||||
standings = []
|
) -> Union[Glory, Dict[str, str]]:
|
||||||
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
|
|
||||||
|
|
||||||
def validate_team_data(team_data: Dict[str, Any]) -> Dict[str, str]:
|
|
||||||
"""
|
"""
|
||||||
Validate team data before creation/update.
|
Transfers team history when team name changes.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
db: Database session
|
db: Database session
|
||||||
team_name: Name of team
|
old_team_name: Previous team name
|
||||||
last_n: Number of recent matches to consider
|
new_team_name: New team name
|
||||||
|
season: Current season
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
String representing form (e.g. 'WWDLL')
|
Glory or error dict
|
||||||
"""
|
"""
|
||||||
team = db.query(Glory).filter(
|
if not validate_team_name(new_team_name):
|
||||||
Glory.team_name == team_name,
|
return {"error": "Invalid new team name"}
|
||||||
Glory.is_active == True
|
|
||||||
).first()
|
team = db.query(Glory)\
|
||||||
|
.filter(Glory.team_name == old_team_name,
|
||||||
|
Glory.season == season)\
|
||||||
|
.first()
|
||||||
|
|
||||||
if not team:
|
if not team:
|
||||||
return ""
|
return {"error": "Team not found"}
|
||||||
|
|
||||||
form = ""
|
team.team_name = new_team_name
|
||||||
total_matches = team.wins + team.draws + team.losses
|
db.commit()
|
||||||
|
db.refresh(team)
|
||||||
|
|
||||||
if total_matches < last_n:
|
return team
|
||||||
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]
|
|
Loading…
x
Reference in New Issue
Block a user