40 lines
1.5 KiB
Python
Executable File
40 lines
1.5 KiB
Python
Executable File
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from app.models.gamification import UserStats, PointsLedger
|
|
from sqlalchemy import select
|
|
|
|
class GamificationService:
|
|
@staticmethod
|
|
async def award_points(db: AsyncSession, user_id: int, points: int, reason: str):
|
|
"""Pontok jóváírása és a UserStats frissítése"""
|
|
|
|
# 1. Bejegyzés a naplóba (Mezőnevek szinkronizálva a modellel)
|
|
new_entry = PointsLedger(
|
|
user_id=user_id,
|
|
points_change=points,
|
|
reason=reason
|
|
)
|
|
db.add(new_entry)
|
|
|
|
# 2. Összesített statisztika lekérése/létrehozása
|
|
result = await db.execute(select(UserStats).where(UserStats.user_id == user_id))
|
|
stats = result.scalar_one_or_none()
|
|
|
|
if not stats:
|
|
# Ha új a user, létrehozzuk az alap statisztikát
|
|
stats = UserStats(
|
|
user_id=user_id,
|
|
total_points=0,
|
|
current_level=1
|
|
)
|
|
db.add(stats)
|
|
|
|
# 3. Pontok hozzáadása
|
|
stats.total_points += points
|
|
|
|
# Itt fogjuk később meghívni a szintlépési logikát
|
|
# await GamificationService._check_level_up(stats)
|
|
|
|
# Fontos: Nem commitolunk itt, hanem hagyjuk, hogy a hívó (SocialService)
|
|
# egy tranzakcióban mentse el a szolgáltatót és a pontokat!
|
|
await db.flush()
|
|
return stats.total_points |