Spaces:
Running on Zero
Running on Zero
CIPHΞR commited on
Update xp.py
Browse files1234 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from typing import Optionalfrom sqlalchemy import case, distinct, func, select4 unmodified linesfrom app.db.models import SeasonResult, XpEventasync def insert_event(session: AsyncSession, user_id: int, kind: str, amount: int, ref: Optional[str], week: str, day: str) -> bool:"""INSERT ... ON CONFLICT DO NOTHING (one round-trip). False = this event already happened."""dialect = session.sync_session.get_bind().dialect.nameins = pg_insert if dialect == "postgresql" else sqlite_insertstmt = (ins(XpEvent).values(user_id=user_id, kind=kind, amount=amount, ref=ref, week=week, day=day).on_conflict_do_nothing(index_elements=["user_id", "kind", "ref"]).returning(XpEvent.id))return (await session.execute(stmt)).scalar_one_or_none() is not Noneasync def count_kind_on_day(session: AsyncSession, user_id: int, kind: str, day: str) -> int:res = await session.execute(select(func.count()).select_from(XpEvent).where(XpEvent.user_id == user_id, XpEvent.kind == kind, XpEvent.day == day))return int(res.scalar_one())async def count_kind_in_week(session: AsyncSession, user_id: int, kind: str, week: str) -> int:res = await session.execute(select(func.count()).select_from(XpEvent).where(XpEvent.user_id == user_id, XpEvent.kind == kind, XpEvent.week == week))return int(res.scalar_one())async def weekly_totals(session: AsyncSession, week: str) -> list[tuple[int, int, int]]:"""(user_id, xp, active_days) straight from the immutable ledger."""active = func.count(distinct(case((XpEvent.kind == "checkin", XpEvent.day), else_=None)))res = await session.execute(select(XpEvent.user_id, func.sum(XpEvent.amount), active).where(XpEvent.week == week).group_by(XpEvent.user_id))return [(int(u), int(xp or 0), int(days)) for u, xp, days in res.all()]async def weekly_referral_xp(session: AsyncSession, week: str) -> dict[int, int]:res = await session.execute(select(XpEvent.user_id, func.sum(XpEvent.amount)).where(XpEvent.week == week, XpEvent.kind.in_(("referral_join", "referral_qualified"))).group_by(XpEvent.user_id))return {int(u): int(x or 0) for u, x in res.all()}# ----- seasons -----async def season_closed(session: AsyncSession, week: str) -> bool:res = await session.execute(select(SeasonResult.id).where(SeasonResult.week == week, SeasonResult.kind == "closed"))return res.scalar_one_or_none() is not Noneasync def add_result(session: AsyncSession, *, week: str, kind: str, rank: int, user_id: int, xp: int, prize_birr: int, status: str) -> None:session.add(SeasonResult(week=week, kind=kind, rank=rank, user_id=user_id, xp=xp, prize_birr=prize_birr, status=status))await session.flush()async def last_closed_week(session: AsyncSession) -> Optional[str]:res = await session.execute(select(SeasonResult.week).where(SeasonResult.kind == "closed").order_by(SeasonResult.week.desc()).limit(1))return res.scalar_one_or_none()async def results_for(session: AsyncSession, week: str) -> list[SeasonResult]:res = await session.execute(select(SeasonResult).where(SeasonResult.week == week, SeasonResult.kind != "closed").order_by(SeasonResult.kind.desc(), SeasonResult.rank))return list(res.scalars())12344 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352from typing import Optionalfrom sqlalchemy import case, distinct, func, select4 unmodified linesfrom app.db.models import SeasonResult, XpEvent# ------------------------------------------------------------------# Database dialect# ------------------------------------------------------------------def _insert_for_dialect(session: AsyncSession):"""Return the appropriate INSERT implementation for the database."""dialect = session.sync_session.get_bind().dialect.nameif dialect == "postgresql":return pg_insertif dialect == "sqlite":return sqlite_insertraise RuntimeError(f"Unsupported database dialect for XP ledger: {dialect}")# ------------------------------------------------------------------# XP ledger# ------------------------------------------------------------------async def insert_event(session: AsyncSession,user_id: int,kind: str,amount: int,ref: Optional[str],week: str,day: str,) -> bool:"""Insert one XP event into the immutable ledger.The legacy 'week' parameter now stores the 60-day season keygenerated by app.core.season.week_key().ON CONFLICT DO NOTHING prevents duplicate events when thesame user, event kind and reference are submitted again.Returns:True: event inserted.False: event already exists."""ins = _insert_for_dialect(session)stmt = (ins(XpEvent).values(user_id=user_id,kind=kind,amount=amount,ref=ref,week=week,day=day,).on_conflict_do_nothing(index_elements=["user_id","kind","ref",]).returning(XpEvent.id))result = await session.execute(stmt)return result.scalar_one_or_none() is not None# ------------------------------------------------------------------# Daily XP limits# ------------------------------------------------------------------async def count_kind_on_day(session: AsyncSession,user_id: int,kind: str,day: str,) -> int:"""Count events of one kind for a user on a specific day."""res = await session.execute(select(func.count()).select_from(XpEvent).where(XpEvent.user_id == user_id,XpEvent.kind == kind,XpEvent.day == day,))return int(res.scalar_one())# ------------------------------------------------------------------# Season XP limits# ------------------------------------------------------------------async def count_kind_in_week(session: AsyncSession,user_id: int,kind: str,week: str,) -> int:"""Count events of one kind during the requested season.The legacy function name is preserved for compatibility.The supplied 'week' value is now a 60-day season key."""res = await session.execute(select(func.count()).select_from(XpEvent).where(XpEvent.user_id == user_id,XpEvent.kind == kind,XpEvent.week == week,))return int(res.scalar_one())# ------------------------------------------------------------------# Season leaderboard# ------------------------------------------------------------------async def weekly_totals(session: AsyncSession,week: str,) -> list[tuple[int, int, int]]:"""Return leaderboard totals for a complete 60-day season.Results:(user_id, total_xp, active_days)Data comes directly from the immutable XP ledger.Active days are calculated using distinct check-in dates."""active = func.count(distinct(case((XpEvent.kind == "checkin",XpEvent.day,),else_=None,)))res = await session.execute(select(XpEvent.user_id,func.sum(XpEvent.amount),active,).where(XpEvent.week == week,).group_by(XpEvent.user_id,))return [(int(user_id),int(xp or 0),int(days or 0),)for user_id, xp, days in res.all()]async def weekly_referral_xp(session: AsyncSession,week: str,) -> dict[int, int]:"""Return referral XP totals for each user in a 60-day season.Includes:referral_joinreferral_qualified"""res = await session.execute(select(XpEvent.user_id,func.sum(XpEvent.amount),).where(XpEvent.week == week,XpEvent.kind.in_(("referral_join","referral_qualified",)),).group_by(XpEvent.user_id,))return {int(user_id): int(xp or 0)for user_id, xp in res.all()}# ------------------------------------------------------------------# Season closing# ------------------------------------------------------------------async def season_closed(session: AsyncSession,week: str,) -> bool:"""Check whether a season has already been closed.A season is considered closed when its 'closed' resultrecord exists."""res = await session.execute(select(SeasonResult.id).where(SeasonResult.week == week,SeasonResult.kind == "closed",).limit(1))return res.scalar_one_or_none() is not None# ------------------------------------------------------------------# Season results# ------------------------------------------------------------------async def add_result(session: AsyncSession,*,week: str,kind: str,rank: int,user_id: int,xp: int,prize_birr: int,status: str,) -> None:"""Store a season result.Prevents duplicate result records with the same:season key + result kind + rank.Existing result records are not overwritten."""existing = await session.execute(select(SeasonResult.id).where(SeasonResult.week == week,SeasonResult.kind == kind,SeasonResult.rank == rank,).limit(1))if existing.scalar_one_or_none() is not None:returnsession.add(SeasonResult(week=week,kind=kind,rank=rank,user_id=user_id,xp=xp,prize_birr=prize_birr,status=status,))await session.flush()# ------------------------------------------------------------------# Previous season results# ------------------------------------------------------------------async def last_closed_week(session: AsyncSession,) -> Optional[str]:"""Return the most recently closed season key.The S60-YYYY-MM-DD season key format sorts chronologicallywhen all keys use the same format."""res = await session.execute(select(SeasonResult.week).where(SeasonResult.kind == "closed",).order_by(SeasonResult.week.desc(),).limit(1))return res.scalar_one_or_none()async def results_for(session: AsyncSession,week: str,) -> list[SeasonResult]:"""Return stored winners and raffle results for one season.The closing marker itself is excluded."""res = await session.execute(select(SeasonResult).where(SeasonResult.week == week,SeasonResult.kind != "closed",).order_by(SeasonResult.kind.desc(),SeasonResult.rank,))return list(res.scalars().all())
app/db/repos/xp.py+294-36