Backend:
- max_ai_messages_per_day + max_ai_tokens_per_day on User model (nullable, override)
- Migration 008: add columns + seed default settings (100 msgs, 500K tokens)
- usage_service: count today's messages + tokens, check quota, get limits
- GET /chats/quota returns usage vs limits + reset time
- POST /chats/{id}/messages checks quota before streaming (429 if exceeded)
- Admin user schemas expose both limit fields
- GET /admin/usage returns per-user daily message + token counts
- admin_user_service allows updating both limit fields
Frontend:
- Chat header shows "X/Y messages · XK/YK tokens" with red highlight at limit
- Quota refreshes every 30s via TanStack Query
- Admin usage page with table: user, messages today, tokens today
- Route + sidebar entry for admin usage
- English + Russian translations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
import uuid
|
|
|
|
from fastapi import HTTPException, status
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.security import hash_password
|
|
from app.models.user import User
|
|
|
|
|
|
async def list_users(db: AsyncSession, limit: int = 50, offset: int = 0) -> tuple[list[User], int]:
|
|
total = await db.scalar(select(func.count()).select_from(User))
|
|
result = await db.execute(
|
|
select(User).order_by(User.created_at.desc()).limit(limit).offset(offset)
|
|
)
|
|
return list(result.scalars().all()), total or 0
|
|
|
|
|
|
async def get_user(db: AsyncSession, user_id: uuid.UUID) -> User:
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
|
return user
|
|
|
|
|
|
async def create_user(
|
|
db: AsyncSession, email: str, username: str, password: str,
|
|
full_name: str | None = None, role: str = "user", max_chats: int = 10,
|
|
) -> User:
|
|
existing = await db.execute(
|
|
select(User).where((User.email == email) | (User.username == username))
|
|
)
|
|
if existing.scalar_one_or_none():
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="User already exists")
|
|
|
|
user = User(
|
|
email=email,
|
|
username=username,
|
|
hashed_password=hash_password(password),
|
|
full_name=full_name,
|
|
role=role,
|
|
max_chats=max_chats,
|
|
)
|
|
db.add(user)
|
|
await db.flush()
|
|
return user
|
|
|
|
|
|
async def update_user(db: AsyncSession, user_id: uuid.UUID, **kwargs) -> User:
|
|
user = await get_user(db, user_id)
|
|
allowed = {"role", "is_active", "max_chats", "max_ai_messages_per_day", "max_ai_tokens_per_day", "full_name"}
|
|
for key, value in kwargs.items():
|
|
if key in allowed and value is not None:
|
|
setattr(user, key, value)
|
|
await db.flush()
|
|
return user
|