Initial commit - MIDAS App educação financeira para apostadores (FastAPI + Next.js)
This commit is contained in:
60
backend/app/routers/reports.py
Normal file
60
backend/app/routers/reports.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from datetime import datetime, timedelta
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.bet import Bet
|
||||
from app.utils.auth import get_current_user
|
||||
|
||||
router = APIRouter(prefix="/api/reports", tags=["reports"])
|
||||
|
||||
def _build_report(bets):
|
||||
total = len(bets)
|
||||
wins = sum(1 for b in bets if b.result == "win")
|
||||
losses = sum(1 for b in bets if b.result == "loss")
|
||||
profit = sum(float(b.profit or 0) for b in bets)
|
||||
staked = sum(float(b.amount) for b in bets)
|
||||
|
||||
by_sport = {}
|
||||
by_hour = {}
|
||||
daily_pl = {}
|
||||
for b in bets:
|
||||
s = b.sport or "other"
|
||||
by_sport.setdefault(s, {"count": 0, "profit": 0})
|
||||
by_sport[s]["count"] += 1
|
||||
by_sport[s]["profit"] += float(b.profit or 0)
|
||||
|
||||
h = b.created_at.hour
|
||||
by_hour.setdefault(h, {"count": 0, "profit": 0})
|
||||
by_hour[h]["count"] += 1
|
||||
by_hour[h]["profit"] += float(b.profit or 0)
|
||||
|
||||
day = b.created_at.strftime("%Y-%m-%d")
|
||||
daily_pl.setdefault(day, 0)
|
||||
daily_pl[day] += float(b.profit or 0)
|
||||
|
||||
return {
|
||||
"total_bets": total, "wins": wins, "losses": losses,
|
||||
"total_profit": round(profit, 2), "total_staked": round(staked, 2),
|
||||
"win_rate": round(wins / (wins + losses) * 100, 1) if (wins + losses) > 0 else 0,
|
||||
"roi": round(profit / staked * 100, 1) if staked > 0 else 0,
|
||||
"by_sport": by_sport, "by_hour": {str(k): v for k, v in sorted(by_hour.items())},
|
||||
"daily_pl": daily_pl
|
||||
}
|
||||
|
||||
@router.get("/weekly")
|
||||
async def weekly_report(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
since = datetime.utcnow() - timedelta(days=7)
|
||||
bets = (await db.execute(
|
||||
select(Bet).where(Bet.user_id == user.id, Bet.created_at >= since)
|
||||
)).scalars().all()
|
||||
return _build_report(bets)
|
||||
|
||||
@router.get("/monthly")
|
||||
async def monthly_report(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
since = datetime.utcnow() - timedelta(days=30)
|
||||
bets = (await db.execute(
|
||||
select(Bet).where(Bet.user_id == user.id, Bet.created_at >= since)
|
||||
)).scalars().all()
|
||||
return _build_report(bets)
|
||||
Reference in New Issue
Block a user