from datetime import datetime from uuid import UUID from sqlalchemy import Select, select, tuple_ from app.common.base_repository import BaseRepository from app.core.pagination import Cursor from app.modules.accounts.models import Account from app.modules.goals.models import Goal class GoalRepository(BaseRepository[Goal]): model = Goal async def active(self, player_id: UUID, mode: str, *, lock: bool = False, team_id: UUID | None = None) -> Goal | None: query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_(None)) if team_id is not None: query = query.where(Goal.team_id == team_id) return await self.session.scalar(query.with_for_update() if lock else query) async def author_name(self, account_id: UUID | None) -> str | None: return await self.session.scalar(select(Account.name).where(Account.id == account_id)) if account_id else None def _page(self, query: Select, cursor: Cursor | None, limit: int) -> Select: if cursor is not None: query = query.where(tuple_(Goal.created_at, Goal.id) < tuple_(cursor.created_at, cursor.id)) return query.order_by(Goal.created_at.desc(), Goal.id.desc()).limit(limit + 1) async def ended(self, player_id: UUID, mode: str, cursor: Cursor | None, limit: int, *, met_only: bool = False, team_id: UUID | None = None): query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_not(None)) if team_id is not None: query = query.where(Goal.team_id == team_id) if met_only: query = query.where(Goal.outcome == "met") return (await self.session.scalars(self._page(query, cursor, limit))).all() async def end(self, goal: Goal, now: datetime) -> None: goal.ended_at = now goal.outcome = "superseded" await self.session.flush()