Initial commit - MIDAS App educação financeira para apostadores (FastAPI + Next.js)
This commit is contained in:
40
backend/app/services/gamification.py
Normal file
40
backend/app/services/gamification.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
from app.models.achievement import Achievement, UserAchievement
|
||||
from app.models.bet import Bet
|
||||
from app.models.lesson import UserLesson
|
||||
|
||||
async def check_achievements(user_id, db: AsyncSession):
|
||||
"""Check and award new achievements"""
|
||||
achievements = (await db.execute(select(Achievement))).scalars().all()
|
||||
existing = (await db.execute(
|
||||
select(UserAchievement.achievement_id).where(UserAchievement.user_id == user_id)
|
||||
)).scalars().all()
|
||||
existing_ids = set(existing)
|
||||
|
||||
bet_count = (await db.execute(
|
||||
select(func.count()).select_from(Bet).where(Bet.user_id == user_id)
|
||||
)).scalar() or 0
|
||||
|
||||
lesson_count = (await db.execute(
|
||||
select(func.count()).select_from(UserLesson).where(UserLesson.user_id == user_id)
|
||||
)).scalar() or 0
|
||||
|
||||
new_badges = []
|
||||
for a in achievements:
|
||||
if a.id in existing_ids:
|
||||
continue
|
||||
awarded = False
|
||||
if a.requirement_type == "bets" and bet_count >= (a.requirement_value or 1):
|
||||
awarded = True
|
||||
elif a.requirement_type == "lessons" and lesson_count >= (a.requirement_value or 1):
|
||||
awarded = True
|
||||
|
||||
if awarded:
|
||||
ua = UserAchievement(user_id=user_id, achievement_id=a.id)
|
||||
db.add(ua)
|
||||
new_badges.append(a.name)
|
||||
|
||||
if new_badges:
|
||||
await db.commit()
|
||||
return new_badges
|
||||
Reference in New Issue
Block a user