Spaces:
Running on Zero
Running on Zero
CIPHΞR commited on
Update xp.py
Browse files12344 unmodified lines9101112131415161718192021222324252627282930313233343512363738394041424314151644454647484950515253545556575859601920616263646566676869707172737475767723787980818283848586872688899091929394952829969798991001011021031041051061073510810911011111211311411511611711811912012112212312437381251261271281291301311321331341351364445461371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661674849501681691701711721731741751761771781795218018118218318418518618718818919055191192193194195196197198199200201202575859203204205206207208209210211212213214215216217218219612202212222232242256465226227228229230231232233234235236237238239240241672422432442452462472482492502512522532542552562577325825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828976290291292293294295296297298299300301302303813043053063073083093103113123133143153163178331831932032132232332432532632732832933088331332333334335336337338339340341919234234334434534634734834935035194352
from typing import Optional
from 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.name
if dialect == "postgresql": return pg_insert
if dialect == "sqlite": return sqlite_insert
raise 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 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.name ins = pg_insert if dialect == "postgresql" else sqlite_insert """ Insert one XP event into the immutable ledger.
The legacy 'week' parameter now stores the 60-day season key generated by app.core.season.week_key().
ON CONFLICT DO NOTHING prevents duplicate events when the same 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"]) .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 None
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: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 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:# ------------------------------------------------------------------# 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 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)))# ------------------------------------------------------------------# 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) 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()]
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]: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_join referral_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) 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()}
return { int(user_id): int(xp or 0) for user_id, xp in res.all() }
# ----- seasons -----async def season_closed(session: AsyncSession, week: str) -> bool:
# ------------------------------------------------------------------# 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' result record exists. """ res = await session.execute( select(SeasonResult.id).where(SeasonResult.week == week, SeasonResult.kind == "closed") 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 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: return
session.add( SeasonResult(week=week, kind=kind, rank=rank, user_id=user_id, xp=xp, prize_birr=prize_birr, status=status) 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]:# ------------------------------------------------------------------# 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 chronologically when all keys use the same format. """ res = await session.execute( select(SeasonResult.week).where(SeasonResult.kind == "closed").order_by(SeasonResult.week.desc()).limit(1) 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]: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) .where( SeasonResult.week == week, SeasonResult.kind != "closed", ) .order_by( SeasonResult.kind.desc(), SeasonResult.rank, ) )
return list(res.scalars()) return list(res.scalars().all())app/db/repos/xp.py+294-36