354 lines
14 KiB
Python
354 lines
14 KiB
Python
import random
|
|
from fastapi import APIRouter, Request, HTTPException
|
|
from auth import require_auth
|
|
from database import get_pool
|
|
|
|
router = APIRouter(prefix="/wordquiz", tags=["wordquiz"])
|
|
|
|
|
|
@router.get("/next")
|
|
async def get_next_quiz(request: Request):
|
|
"""Выдаёт случайное слово из базы выбранного уровня. Исключает недавно показанные."""
|
|
telegram_id, _ = await require_auth(request)
|
|
|
|
pool = await get_pool()
|
|
async with pool.acquire() as conn:
|
|
user = await conn.fetchrow(
|
|
"SELECT app_language, current_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
|
)
|
|
if not user:
|
|
raise HTTPException(401, "User not registered")
|
|
|
|
lang = user["app_language"] or "pl"
|
|
current_level = user["current_level"] or "A1"
|
|
|
|
if lang == 'pl':
|
|
raise HTTPException(403, "ChooseWord не поддерживает польский язык. Используйте другой язык.")
|
|
|
|
difficulty = user.get("difficulty") or "medium"
|
|
wrong_count = {"easy": 2, "medium": 3, "hard": 4}.get(difficulty, 3)
|
|
|
|
progress = await conn.fetchrow(
|
|
"SELECT words_guessed, recent_words FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
)
|
|
total_guessed = progress["words_guessed"] if progress else 0
|
|
recent_words = list(progress["recent_words"]) if progress and progress["recent_words"] else []
|
|
|
|
async def pick_word(exclude, respect_exclude=True):
|
|
if respect_exclude and exclude:
|
|
placeholders = ",".join([f"${i+2}" for i in range(len(exclude))])
|
|
# 🔧 ФИКС (30.09.2026): csv_words_source —
|
|
# источник слов переехал с level_words (старая схема level_id IS NULL)
|
|
# на csv_words (level_code). Один источник — CSV-база.
|
|
return await conn.fetchrow(f"""
|
|
SELECT word_pl, translation_ru, translation_uk, translation_en
|
|
FROM csv_words
|
|
WHERE level_code = $1 AND word_pl NOT IN ({placeholders})
|
|
ORDER BY RANDOM()
|
|
LIMIT 1
|
|
""", current_level, *exclude)
|
|
return await conn.fetchrow("""
|
|
SELECT word_pl, translation_ru, translation_uk, translation_en
|
|
FROM csv_words
|
|
WHERE level_code = $1
|
|
ORDER BY RANDOM()
|
|
LIMIT 1
|
|
""", current_level)
|
|
|
|
word = await pick_word(recent_words, respect_exclude=True)
|
|
if not word:
|
|
word = await pick_word([], respect_exclude=False)
|
|
|
|
if not word:
|
|
raise HTTPException(404, "No words found")
|
|
|
|
correct_polish = word["word_pl"]
|
|
translation_field = f"translation_{lang}"
|
|
translation = word.get(translation_field) or word.get("translation_en") or correct_polish
|
|
|
|
# Ищем неправильные варианты
|
|
exclude_for_wrong = recent_words + [correct_polish]
|
|
placeholders = ",".join([f"${i+3}" for i in range(len(exclude_for_wrong))])
|
|
# 🔧 ФИКС (30.09.2026): csv_words_source — источник переведён на csv_words.
|
|
wrong_words = await conn.fetch(f"""
|
|
SELECT word_pl
|
|
FROM csv_words
|
|
WHERE level_code = $1 AND word_pl != $2 AND word_pl NOT IN ({placeholders})
|
|
ORDER BY RANDOM()
|
|
LIMIT (wrong_count + 1)
|
|
""", current_level, correct_polish, *exclude_for_wrong)
|
|
|
|
if len(wrong_words) < wrong_count:
|
|
# 🔧 ФИКС (30.09.2026): csv_words_source — fallback тоже на csv_words.
|
|
wrong_words = await conn.fetch("""
|
|
SELECT word_pl
|
|
FROM csv_words
|
|
WHERE level_code = $1 AND word_pl != $2
|
|
ORDER BY RANDOM()
|
|
LIMIT (wrong_count + 1)
|
|
""", current_level, correct_polish)
|
|
|
|
wrong_options = []
|
|
seen = {correct_polish.lower()}
|
|
for w in wrong_words:
|
|
wl = w["word_pl"].lower()
|
|
if wl not in seen:
|
|
wrong_options.append(w["word_pl"])
|
|
seen.add(wl)
|
|
if len(wrong_options) >= wrong_count:
|
|
break
|
|
|
|
recent_words = recent_words + [correct_polish] + wrong_options
|
|
if len(recent_words) > 45:
|
|
recent_words = recent_words[-45:]
|
|
|
|
await conn.execute("""
|
|
INSERT INTO word_quiz_progress (user_id, words_guessed, total_score, recent_words)
|
|
VALUES ($1, 0, 0, $2::text[])
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET recent_words = $2::text[]
|
|
""", telegram_id, recent_words)
|
|
|
|
options = wrong_options + [correct_polish]
|
|
random.shuffle(options)
|
|
|
|
time_limit = 10 if difficulty == "hard" else None
|
|
|
|
return {
|
|
"correct_polish": correct_polish,
|
|
"translation": translation,
|
|
"options": options,
|
|
"difficulty": difficulty,
|
|
"time_limit": time_limit,
|
|
}
|
|
|
|
|
|
@router.post("/check")
|
|
async def check_quiz_answer(request: Request):
|
|
"""Проверяет ответ, начисляет XP и проверяет достижения.
|
|
|
|
🔧 НОВОЕ (08.10.2026): XP-система + серии.
|
|
Штрафы:
|
|
-1 за каждый неверный выбор (макс 3)
|
|
-1 если time_ms > 30 сек
|
|
Минимум 1 звезда.
|
|
Серия: correct_streak (best_streak хранится в choose_progress).
|
|
"""
|
|
telegram_id, _ = await require_auth(request)
|
|
body = await request.json()
|
|
correct_polish = body.get("correct_polish", "")
|
|
user_answer = body.get("answer", "")
|
|
completion_time = body.get("completion_time")
|
|
# 🆕 wrong_count приходит с клиента для UI, но мы считаем на сервере
|
|
# 🔧 ФИКС: current_mistakes — серверный счётчик
|
|
|
|
if not correct_polish or not user_answer:
|
|
raise HTTPException(400, "correct_polish and answer required")
|
|
|
|
if completion_time is not None and completion_time < 1:
|
|
return {
|
|
"correct": False,
|
|
"correct_streak": 0,
|
|
"error": "Too fast. Please take your time."
|
|
}
|
|
|
|
is_correct = user_answer.strip().lower() == correct_polish.strip().lower()
|
|
|
|
pool = await get_pool()
|
|
async with pool.acquire() as conn:
|
|
# Проверка языка
|
|
lang = await conn.fetchval(
|
|
"SELECT app_language FROM users WHERE telegram_id = $1", telegram_id
|
|
) or "pl"
|
|
if lang == 'pl':
|
|
raise HTTPException(403, "ChooseWord не поддерживает польский язык.")
|
|
|
|
difficulty = await conn.fetchval(
|
|
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
|
) or "medium"
|
|
|
|
# Читаем серверный streak и mistakes
|
|
current_streak = await conn.fetchval(
|
|
"SELECT correct_streak FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
) or 0
|
|
mistakes = await conn.fetchval(
|
|
"SELECT current_mistakes FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
) or 0
|
|
no_mistakes_streak = await conn.fetchval(
|
|
"SELECT no_mistakes_streak FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
) or 0
|
|
|
|
if is_correct:
|
|
current_streak += 1
|
|
else:
|
|
current_streak = 0
|
|
await conn.execute("""
|
|
INSERT INTO word_quiz_progress (user_id, current_mistakes)
|
|
VALUES ($1, 1)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET current_mistakes = word_quiz_progress.current_mistakes + 1
|
|
""", telegram_id)
|
|
mistakes += 1
|
|
|
|
xp_result = None
|
|
score = 0
|
|
|
|
if is_correct:
|
|
# 🆕 Фиксированные очки по сложности (ChooseWord)
|
|
if difficulty == "easy":
|
|
points = max(20, min(60, 60 - 20 * mistakes))
|
|
elif difficulty == "medium":
|
|
points = max(20, min(80, 80 - 20 * mistakes))
|
|
else: # hard
|
|
points = max(20, min(110, 110 - 20 * mistakes))
|
|
if completion_time is not None and completion_time > 10:
|
|
points = 20
|
|
|
|
# Начисляем XP
|
|
from services.xp import award_xp
|
|
xp_result = await award_xp(conn, telegram_id, "choose", points)
|
|
score = xp_result["points"]
|
|
|
|
# no_mistakes_streak: +1 если раунд чистый, иначе сброс
|
|
if mistakes == 0:
|
|
no_mistakes_streak += 1
|
|
else:
|
|
no_mistakes_streak = 0
|
|
|
|
# Сбрасываем mistakes + обновляем серию
|
|
await conn.execute("""
|
|
UPDATE word_quiz_progress SET current_mistakes = 0 WHERE user_id = $1
|
|
""", telegram_id)
|
|
|
|
await conn.execute("""
|
|
INSERT INTO word_quiz_progress (user_id, words_guessed, total_score, correct_streak, no_mistakes_streak)
|
|
VALUES ($1, 1, $2, $3, $4)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET words_guessed = word_quiz_progress.words_guessed + 1,
|
|
total_score = word_quiz_progress.total_score + $2,
|
|
correct_streak = $3,
|
|
no_mistakes_streak = $4
|
|
""", telegram_id, score, current_streak, no_mistakes_streak)
|
|
|
|
# 🆕 Обновляем best_streak в choose_progress
|
|
await conn.execute("""
|
|
INSERT INTO choose_progress (user_id, current_streak, best_streak)
|
|
VALUES ($1, $2, $2)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET current_streak = $2,
|
|
best_streak = GREATEST(choose_progress.best_streak, $2),
|
|
updated_at = NOW()
|
|
""", telegram_id, current_streak)
|
|
|
|
# Собираем данные для достижений
|
|
total_guessed = await conn.fetchval(
|
|
"SELECT words_guessed FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
) or 0
|
|
|
|
achievements_to_check = [
|
|
("quiz_guessed", total_guessed),
|
|
("total_score", xp_result["total_xp"]),
|
|
]
|
|
if current_streak >= 10:
|
|
achievements_to_check.append(("quiz_perfect_streak", current_streak))
|
|
if mistakes == 0:
|
|
achievements_to_check.append(("quiz_no_mistakes", 1))
|
|
if completion_time is not None and 0 < completion_time <= 3:
|
|
achievements_to_check.append(("quiz_speed", 3))
|
|
else:
|
|
# При 3 ошибках — утешительный XP (10)
|
|
if mistakes >= 3:
|
|
await conn.execute("""
|
|
INSERT INTO word_quiz_progress (user_id, words_guessed, total_score, correct_streak, current_mistakes)
|
|
VALUES ($1, 0, 10, 0, $2)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET total_score = word_quiz_progress.total_score + 10,
|
|
correct_streak = 0
|
|
""", telegram_id, mistakes)
|
|
else:
|
|
await conn.execute("""
|
|
INSERT INTO word_quiz_progress (user_id, words_guessed, total_score, correct_streak)
|
|
VALUES ($1, 0, 0, $2)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET correct_streak = $2
|
|
""", telegram_id, current_streak)
|
|
|
|
# Достижения — вне транзакции
|
|
if is_correct:
|
|
from routers.achievements import check_and_award_achievements
|
|
new_achievements = []
|
|
for ach_type, value in achievements_to_check:
|
|
ach = await check_and_award_achievements(telegram_id, ach_type, value)
|
|
new_achievements.extend(ach)
|
|
|
|
return {
|
|
"correct": True,
|
|
"score": score,
|
|
"correct_streak": current_streak,
|
|
"new_achievements": new_achievements,
|
|
# 🆕 XP-поля
|
|
"base_points": xp_result["base_points"],
|
|
"multiplier": xp_result["multiplier"],
|
|
"points": xp_result["points"],
|
|
"featured": xp_result["featured"],
|
|
"level_up": xp_result["level_up"],
|
|
"total_xp": xp_result["total_xp"],
|
|
"level": xp_result["level"],
|
|
"rank_key": xp_result["rank_key"],
|
|
"xp_in_level": xp_result["xp_in_level"],
|
|
"xp_needed": xp_result["xp_needed"],
|
|
# 🆕 Серия для UI
|
|
"streak_best": (await _get_best_streak(telegram_id)),
|
|
}
|
|
|
|
return {
|
|
"correct": False,
|
|
"correct_streak": current_streak,
|
|
"consolation_score": 10 if mistakes >= 3 else 0,
|
|
}
|
|
|
|
|
|
async def _get_best_streak(telegram_id: int) -> int:
|
|
"""Возвращает best_streak пользователя из choose_progress."""
|
|
pool = await get_pool()
|
|
async with pool.acquire() as conn:
|
|
return await conn.fetchval(
|
|
"SELECT best_streak FROM choose_progress WHERE user_id = $1",
|
|
telegram_id
|
|
) or 0
|
|
|
|
|
|
@router.get("/progress")
|
|
async def get_quiz_progress(request: Request):
|
|
"""Статистика пользователя в квизе"""
|
|
telegram_id, _ = await require_auth(request)
|
|
|
|
pool = await get_pool()
|
|
async with pool.acquire() as conn:
|
|
progress = await conn.fetchrow(
|
|
"SELECT words_guessed, total_score, correct_streak FROM word_quiz_progress WHERE user_id = $1",
|
|
telegram_id
|
|
)
|
|
|
|
total_guessed = progress["words_guessed"] if progress else 0
|
|
|
|
if total_guessed <= 10:
|
|
difficulty = "easy"
|
|
elif total_guessed <= 30:
|
|
difficulty = "medium"
|
|
elif total_guessed <= 60:
|
|
difficulty = "hard"
|
|
else:
|
|
difficulty = "expert"
|
|
|
|
return {
|
|
"words_guessed": total_guessed,
|
|
"total_score": progress["total_score"] if progress else 0,
|
|
"correct_streak": progress["correct_streak"] if progress else 0,
|
|
"difficulty": difficulty
|
|
} |