61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
|
|
from datetime import UTC, date, datetime
|
||
|
|
|
||
|
|
import sqlalchemy as sa
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.models.db_models import DailyStat, InterestCategoryCount
|
||
|
|
from app.services.session_service import count_active_sessions
|
||
|
|
|
||
|
|
|
||
|
|
async def get_stats(db: AsyncSession) -> dict:
|
||
|
|
"""Return anonymised aggregate stats for the admin dashboard."""
|
||
|
|
today = date.today()
|
||
|
|
|
||
|
|
row = await db.scalar(
|
||
|
|
sa.select(DailyStat).where(DailyStat.date == today)
|
||
|
|
)
|
||
|
|
|
||
|
|
top_categories_rows = await db.scalars(
|
||
|
|
sa.select(InterestCategoryCount)
|
||
|
|
.where(InterestCategoryCount.date == today)
|
||
|
|
.order_by(InterestCategoryCount.count.desc())
|
||
|
|
.limit(5)
|
||
|
|
)
|
||
|
|
top_categories = [r.category for r in top_categories_rows]
|
||
|
|
active = await count_active_sessions()
|
||
|
|
|
||
|
|
return {
|
||
|
|
"total_sessions_today": row.total_sessions if row else 0,
|
||
|
|
"total_matches_today": row.total_matches if row else 0,
|
||
|
|
"active_sessions_now": active,
|
||
|
|
"top_interest_categories": top_categories,
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
async def increment_sessions(db: AsyncSession) -> None:
|
||
|
|
"""Increment daily session counter. Called when a new session is created."""
|
||
|
|
today = date.today()
|
||
|
|
await db.execute(
|
||
|
|
sa.dialects.postgresql.insert(DailyStat)
|
||
|
|
.values(date=today, total_sessions=1, total_matches=0)
|
||
|
|
.on_conflict_do_update(
|
||
|
|
index_elements=["date"],
|
||
|
|
set_={"total_sessions": DailyStat.total_sessions + 1},
|
||
|
|
)
|
||
|
|
)
|
||
|
|
await db.commit()
|
||
|
|
|
||
|
|
|
||
|
|
async def increment_matches(db: AsyncSession) -> None:
|
||
|
|
"""Increment daily match counter. Called on a successful match."""
|
||
|
|
today = date.today()
|
||
|
|
await db.execute(
|
||
|
|
sa.dialects.postgresql.insert(DailyStat)
|
||
|
|
.values(date=today, total_sessions=0, total_matches=1)
|
||
|
|
.on_conflict_do_update(
|
||
|
|
index_elements=["date"],
|
||
|
|
set_={"total_matches": DailyStat.total_matches + 1},
|
||
|
|
)
|
||
|
|
)
|
||
|
|
await db.commit()
|