"""Teams: create/update by the coach, lookup by code, join and leave by players.""" import re import secrets from sqlalchemy.ext.asyncio import AsyncSession from app.core.errors import AppError, NotFound from app.core.rate_limit import get_team_lookup_limiter from app.modules.accounts.models import Account from app.modules.teams.models import Team from app.modules.teams.repository import MemberRepository, TeamRepository from app.modules.teams.schemas import TeamOut, TeamSummaryOut _CODE_ATTEMPTS = 20 def code_prefix(name: str) -> str: """Up to three uppercase initials of the name's words (ASCII letters only), padded with X.""" initials = [m.group(0) for word in name.split() if (m := re.search(r"[A-Za-z]", word))] return "".join(initials[:3]).upper().ljust(3, "X") def new_code(name: str) -> str: return f"{code_prefix(name)}-{secrets.randbelow(10_000):04d}" def normalize_code(code: str) -> str: return code.strip().upper() def team_not_found() -> NotFound: return NotFound("We couldn't find a team with that code.", code="TEAM_NOT_FOUND") class TeamService: def __init__(self, db: AsyncSession): self.teams = TeamRepository(db) self.members = MemberRepository(db) async def _out(self, team: Team) -> TeamOut: return TeamOut(id=team.id, code=team.code, name=team.name, coach_id=team.coach_id, coach_name=await self.teams.coach_name(team), coaching=team.coaching, created_at=team.created_at) async def save(self, coach: Account, name: str, coach_name: str, coaching: str) -> tuple[TeamOut, bool]: """Creates the coach's team, or updates it in place (code and members kept). Returns (team, created).""" await self.members.update(coach, name=coach_name, focus=coaching) team = await self.teams.by_coach(coach.id) if team is not None: await self.teams.update(team, name=name, coaching=coaching) return await self._out(team), False for _ in range(_CODE_ATTEMPTS): code = new_code(name) if not await self.teams.exists_by(code=code): break else: raise AppError("Could not generate a team code. Please try again.") team = await self.teams.create(code=code, name=name, coach_id=coach.id, coaching=coaching) return await self._out(team), True async def lookup(self, account: Account, code: str) -> TeamSummaryOut: get_team_lookup_limiter().hit(f"team_lookup:{account.id}") team = await self.teams.by_code(normalize_code(code)) if team is None: raise team_not_found() return TeamSummaryOut(code=team.code, name=team.name, coach_name=await self.teams.coach_name(team), coaching=team.coaching) async def join(self, player: Account, code: str) -> TeamOut: team = await self.teams.by_code(normalize_code(code)) if team is None: raise team_not_found() await self.members.update(player, team_id=team.id) return await self._out(team) async def leave(self, player: Account) -> None: if player.team_id is not None: await self.members.update(player, team_id=None)