Merge pull request '[Eva] Ева, патч 21 применён — теперь ты можешь' (#41) from eva/chat-b7c183-backend into main
Reviewed-on: #41
This commit was merged in pull request #41.
This commit is contained in:
+40
@@ -898,6 +898,46 @@ async def init_db():
|
|||||||
""")
|
""")
|
||||||
logger.info("Added current_hints_used column to bubble_words_progress")
|
logger.info("Added current_hints_used column to bubble_words_progress")
|
||||||
|
|
||||||
|
# 🔧 НОВОЕ (14.10.2026): current_list_opened — серверный счётчик
|
||||||
|
# «показать слова» для текущего уровня пузырей. Medium — 1 раз.
|
||||||
|
col_exists = await conn.fetchval("""
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'bubble_words_progress' AND column_name = 'current_list_opened'
|
||||||
|
""")
|
||||||
|
if not col_exists:
|
||||||
|
await conn.execute("""
|
||||||
|
ALTER TABLE bubble_words_progress
|
||||||
|
ADD COLUMN current_list_opened INT DEFAULT 0
|
||||||
|
""")
|
||||||
|
logger.info("Added current_list_opened column to bubble_words_progress")
|
||||||
|
|
||||||
|
# 🔧 НОВОЕ (14.10.2026): current_level_words — состояние текущего
|
||||||
|
# уровня пузырей (слова + части + переводы). Нужно для подсказок,
|
||||||
|
# т.к. уровень генерируется на лету в /next и нигде не хранится.
|
||||||
|
col_exists = await conn.fetchval("""
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'bubble_words_progress' AND column_name = 'current_level_words'
|
||||||
|
""")
|
||||||
|
if not col_exists:
|
||||||
|
await conn.execute("""
|
||||||
|
ALTER TABLE bubble_words_progress
|
||||||
|
ADD COLUMN current_level_words JSONB DEFAULT '[]'::jsonb
|
||||||
|
""")
|
||||||
|
logger.info("Added current_level_words column to bubble_words_progress")
|
||||||
|
|
||||||
|
# 🔧 НОВОЕ (14.10.2026): hinted_words — какие слова уже получили
|
||||||
|
# подсказку «первая часть» (для «каждый раз разное слово»).
|
||||||
|
col_exists = await conn.fetchval("""
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'bubble_words_progress' AND column_name = 'hinted_words'
|
||||||
|
""")
|
||||||
|
if not col_exists:
|
||||||
|
await conn.execute("""
|
||||||
|
ALTER TABLE bubble_words_progress
|
||||||
|
ADD COLUMN hinted_words TEXT[] DEFAULT '{}'
|
||||||
|
""")
|
||||||
|
logger.info("Added hinted_words column to bubble_words_progress")
|
||||||
|
|
||||||
# ============ wrong_because_explanations ============
|
# ============ wrong_because_explanations ============
|
||||||
await conn.execute("""
|
await conn.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
||||||
|
|||||||
+163
-8
@@ -1,5 +1,6 @@
|
|||||||
import random
|
import random
|
||||||
import hashlib # 🔧 НОВОЕ: импорт hashlib для стабильного хэширования
|
import hashlib # 🔧 НОВОЕ: импорт hashlib для стабильного хэширования
|
||||||
|
import json
|
||||||
from fastapi import APIRouter, Request, HTTPException
|
from fastapi import APIRouter, Request, HTTPException
|
||||||
from auth import require_auth
|
from auth import require_auth
|
||||||
from database import get_pool
|
from database import get_pool
|
||||||
@@ -162,6 +163,28 @@ async def get_next_bubble_level(request: Request):
|
|||||||
|
|
||||||
random.shuffle(all_parts)
|
random.shuffle(all_parts)
|
||||||
|
|
||||||
|
# 🔧 НОВОЕ (14.10.2026): сохраняем состояние уровня для подсказок
|
||||||
|
# и сбрасываем счётчики подсказок/списка при новом уровне.
|
||||||
|
level_state = [
|
||||||
|
{
|
||||||
|
"word_pl": w["word_pl"],
|
||||||
|
"translation": w["translation"],
|
||||||
|
"parts": w["parts"],
|
||||||
|
}
|
||||||
|
for w in result_words
|
||||||
|
]
|
||||||
|
await conn.execute("""
|
||||||
|
INSERT INTO bubble_words_progress
|
||||||
|
(user_id, levels_completed, total_score, level,
|
||||||
|
current_hints_used, current_list_opened, current_level_words, hinted_words)
|
||||||
|
VALUES ($1, 0, 0, $2, 0, 0, $3::jsonb, '{}')
|
||||||
|
ON CONFLICT (user_id) DO UPDATE
|
||||||
|
SET current_hints_used = 0,
|
||||||
|
current_list_opened = 0,
|
||||||
|
current_level_words = $3::jsonb,
|
||||||
|
hinted_words = '{}'
|
||||||
|
""", telegram_id, current_level, json.dumps(level_state))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"words": result_words,
|
"words": result_words,
|
||||||
"bubbles": all_parts,
|
"bubbles": all_parts,
|
||||||
@@ -169,6 +192,131 @@ async def get_next_bubble_level(request: Request):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/first-part-hint")
|
||||||
|
async def first_part_hint(request: Request):
|
||||||
|
"""Подсказка «первая часть слова» — возвращает первый пузырь одного из несобранных слов.
|
||||||
|
|
||||||
|
🔧 НОВОЕ (14.10.2026): аналог GET /hints/first-letter/{level_id} из филворда.
|
||||||
|
Лимит 3 подсказки, штраф −20 (учитывается в /complete через current_hints_used).
|
||||||
|
Hard — запрещено (400).
|
||||||
|
"""
|
||||||
|
telegram_id, _ = await require_auth(request)
|
||||||
|
body = await request.json()
|
||||||
|
found_words = set(body.get("found_words", []) or [])
|
||||||
|
|
||||||
|
pool = await get_pool()
|
||||||
|
async with pool.acquire() as conn:
|
||||||
|
user = await conn.fetchrow(
|
||||||
|
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(401, "User not registered")
|
||||||
|
|
||||||
|
difficulty = user["difficulty"] or "medium"
|
||||||
|
if difficulty == "hard":
|
||||||
|
raise HTTPException(400, "Hints are disabled on Hard difficulty")
|
||||||
|
|
||||||
|
progress = await conn.fetchrow(
|
||||||
|
"SELECT current_hints_used, current_level_words, hinted_words "
|
||||||
|
"FROM bubble_words_progress WHERE user_id = $1",
|
||||||
|
telegram_id
|
||||||
|
)
|
||||||
|
if not progress:
|
||||||
|
raise HTTPException(404, "No active level")
|
||||||
|
|
||||||
|
hints_used = progress["current_hints_used"] or 0
|
||||||
|
if hints_used >= 3:
|
||||||
|
raise HTTPException(400, "All hints used")
|
||||||
|
|
||||||
|
level_words = progress["current_level_words"] or []
|
||||||
|
hinted = set(progress["hinted_words"] or [])
|
||||||
|
|
||||||
|
# Слова, которые ещё не собраны и которым ещё не давали подсказку
|
||||||
|
candidates = [
|
||||||
|
w for w in level_words
|
||||||
|
if w.get("word_pl") not in found_words and w.get("word_pl") not in hinted
|
||||||
|
]
|
||||||
|
|
||||||
|
if not candidates:
|
||||||
|
raise HTTPException(400, "All words already hinted")
|
||||||
|
|
||||||
|
chosen = random.choice(candidates)
|
||||||
|
word_pl = chosen["word_pl"]
|
||||||
|
parts = chosen.get("parts") or []
|
||||||
|
first_part = parts[0] if parts else word_pl
|
||||||
|
|
||||||
|
new_hints = hints_used + 1
|
||||||
|
new_hinted = sorted(hinted | {word_pl})
|
||||||
|
|
||||||
|
await conn.execute("""
|
||||||
|
UPDATE bubble_words_progress
|
||||||
|
SET current_hints_used = $2,
|
||||||
|
hinted_words = $3
|
||||||
|
WHERE user_id = $1
|
||||||
|
""", telegram_id, new_hints, new_hinted)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"word_pl": word_pl,
|
||||||
|
"first_part": first_part,
|
||||||
|
"hints_used_total": new_hints,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/show-words")
|
||||||
|
async def show_words(request: Request):
|
||||||
|
"""Подсказка «показать слова» — возвращает все загаданные слова с переводами.
|
||||||
|
|
||||||
|
🔧 НОВОЕ (14.10.2026): аналог show-words из филворда.
|
||||||
|
Easy — без лимита. Medium — 1 раз (−20). Hard — запрещено (400).
|
||||||
|
"""
|
||||||
|
telegram_id, _ = await require_auth(request)
|
||||||
|
|
||||||
|
pool = await get_pool()
|
||||||
|
async with pool.acquire() as conn:
|
||||||
|
user = await conn.fetchrow(
|
||||||
|
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(401, "User not registered")
|
||||||
|
|
||||||
|
difficulty = user["difficulty"] or "medium"
|
||||||
|
if difficulty == "hard":
|
||||||
|
raise HTTPException(400, "Word list is disabled on Hard difficulty")
|
||||||
|
|
||||||
|
progress = await conn.fetchrow(
|
||||||
|
"SELECT current_list_opened, current_level_words "
|
||||||
|
"FROM bubble_words_progress WHERE user_id = $1",
|
||||||
|
telegram_id
|
||||||
|
)
|
||||||
|
if not progress:
|
||||||
|
raise HTTPException(404, "No active level")
|
||||||
|
|
||||||
|
list_opened = progress["current_list_opened"] or 0
|
||||||
|
|
||||||
|
# Medium — список можно открыть только 1 раз
|
||||||
|
if difficulty == "medium" and list_opened >= 1:
|
||||||
|
raise HTTPException(400, "Word list already used on Medium difficulty")
|
||||||
|
|
||||||
|
level_words = progress["current_level_words"] or []
|
||||||
|
words = [
|
||||||
|
{"word_pl": w.get("word_pl"), "translation": w.get("translation")}
|
||||||
|
for w in level_words
|
||||||
|
]
|
||||||
|
|
||||||
|
# Инкремент счётчика для Easy и Medium (Hard сюда не доходит)
|
||||||
|
new_list_opened = list_opened + 1
|
||||||
|
await conn.execute("""
|
||||||
|
UPDATE bubble_words_progress
|
||||||
|
SET current_list_opened = $2
|
||||||
|
WHERE user_id = $1
|
||||||
|
""", telegram_id, new_list_opened)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"words": words,
|
||||||
|
"list_opened_total": new_list_opened,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/complete")
|
@router.post("/complete")
|
||||||
async def complete_bubble_level(request: Request):
|
async def complete_bubble_level(request: Request):
|
||||||
"""Завершение уровня пузырей, начисление XP и проверка достижений.
|
"""Завершение уровня пузырей, начисление XP и проверка достижений.
|
||||||
@@ -184,7 +332,6 @@ async def complete_bubble_level(request: Request):
|
|||||||
body = await request.json()
|
body = await request.json()
|
||||||
words_count = body.get("words_count", 3)
|
words_count = body.get("words_count", 3)
|
||||||
completion_time = body.get("completion_time")
|
completion_time = body.get("completion_time")
|
||||||
list_opened = bool(body.get("list_opened", False))
|
|
||||||
wrong_words = int(body.get("wrong_words", 0) or 0)
|
wrong_words = int(body.get("wrong_words", 0) or 0)
|
||||||
|
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
@@ -201,12 +348,15 @@ async def complete_bubble_level(request: Request):
|
|||||||
current_level = user["current_level"] or "A1"
|
current_level = user["current_level"] or "A1"
|
||||||
difficulty = user["difficulty"] or "medium"
|
difficulty = user["difficulty"] or "medium"
|
||||||
|
|
||||||
# Читаем серверный hints_used
|
# Читаем серверные счётчики (не из body)
|
||||||
hints_used = await conn.fetchval(
|
progress = await conn.fetchrow(
|
||||||
"SELECT current_hints_used FROM bubble_words_progress WHERE user_id = $1",
|
"SELECT current_hints_used, current_list_opened "
|
||||||
|
"FROM bubble_words_progress WHERE user_id = $1",
|
||||||
telegram_id
|
telegram_id
|
||||||
) or 0
|
)
|
||||||
|
hints_used = (progress["current_hints_used"] if progress else 0) or 0
|
||||||
hints_used = min(max(0, hints_used), 3)
|
hints_used = min(max(0, hints_used), 3)
|
||||||
|
list_opened = (progress["current_list_opened"] if progress else 0) or 0
|
||||||
|
|
||||||
# 🔧 НОВОЕ (14.10.2026): очки по формуле филворда.
|
# 🔧 НОВОЕ (14.10.2026): очки по формуле филворда.
|
||||||
# Hard — фикс 110. Easy/Medium — 100 − 20×hints − 20×list + bonus.
|
# Hard — фикс 110. Easy/Medium — 100 − 20×hints − 20×list + bonus.
|
||||||
@@ -229,13 +379,18 @@ async def complete_bubble_level(request: Request):
|
|||||||
score = xp_result["points"]
|
score = xp_result["points"]
|
||||||
|
|
||||||
await conn.execute("""
|
await conn.execute("""
|
||||||
INSERT INTO bubble_words_progress (user_id, levels_completed, total_score, level, current_hints_used)
|
INSERT INTO bubble_words_progress
|
||||||
VALUES ($1, 1, $2, $3, 0)
|
(user_id, levels_completed, total_score, level,
|
||||||
|
current_hints_used, current_list_opened, current_level_words, hinted_words)
|
||||||
|
VALUES ($1, 1, $2, $3, 0, 0, '[]'::jsonb, '{}')
|
||||||
ON CONFLICT (user_id) DO UPDATE
|
ON CONFLICT (user_id) DO UPDATE
|
||||||
SET levels_completed = bubble_words_progress.levels_completed + 1,
|
SET levels_completed = bubble_words_progress.levels_completed + 1,
|
||||||
total_score = bubble_words_progress.total_score + $2,
|
total_score = bubble_words_progress.total_score + $2,
|
||||||
level = $3,
|
level = $3,
|
||||||
current_hints_used = 0
|
current_hints_used = 0,
|
||||||
|
current_list_opened = 0,
|
||||||
|
current_level_words = '[]'::jsonb,
|
||||||
|
hinted_words = '{}'
|
||||||
""", telegram_id, score, current_level)
|
""", telegram_id, score, current_level)
|
||||||
|
|
||||||
# Данные для достижений
|
# Данные для достижений
|
||||||
|
|||||||
Reference in New Issue
Block a user