Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50c02b7707 | ||
|
|
22e4eed3f5 | ||
|
|
8b98655716 |
-26
@@ -229,21 +229,6 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added current_streak column to user_progress")
|
||||
|
||||
# ============ Авто-миграция: добавляем wave в user_progress ============
|
||||
# 🔧 НОВОЕ (13.10.2026): wave — номер волны, к которой относится
|
||||
# пройденный уровень. Нужен для подсчёта wave_points (сумма очков
|
||||
# за 10 уровней волны) в модалке итогов волны.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'user_progress' AND column_name = 'wave'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE user_progress
|
||||
ADD COLUMN wave INTEGER
|
||||
""")
|
||||
logger.info("Added wave column to user_progress")
|
||||
|
||||
# ============ sentences ============
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sentences (
|
||||
@@ -1314,17 +1299,6 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added apple_id column to users (Pleily)")
|
||||
|
||||
# difficulty
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'users' AND column_name = 'difficulty'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE users ADD COLUMN difficulty TEXT DEFAULT 'medium'
|
||||
""")
|
||||
logger.info("Added difficulty column to users (Pleily)")
|
||||
|
||||
# app_user_id_seq — sequence для отрицательных user_id
|
||||
await conn.execute("""
|
||||
CREATE SEQUENCE IF NOT EXISTS app_user_id_seq
|
||||
|
||||
@@ -523,7 +523,6 @@
|
||||
| last_completed_level | integer | YES | 0 |
|
||||
| id | integer | NO | nextval('users_id_seq'::regclass) |
|
||||
| current_level | text | YES | 'A1'::text |
|
||||
| difficulty | text | YES | 'medium'::text |
|
||||
|
||||
## voice_usage
|
||||
|
||||
|
||||
+22
-77
@@ -73,7 +73,7 @@ async def get_level(request: Request, level_number: int):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT app_language, current_level, last_completed_level, last_completed_by_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
"SELECT app_language, current_level, last_completed_level, last_completed_by_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
|
||||
if not user:
|
||||
@@ -208,7 +208,6 @@ async def get_level(request: Request, level_number: int):
|
||||
# 🆕 (10.10.2026): волна и позиция в волне.
|
||||
"wave": wave,
|
||||
"position_in_wave": pos_in_wave,
|
||||
"difficulty": user["difficulty"] or "medium",
|
||||
}
|
||||
|
||||
|
||||
@@ -354,24 +353,15 @@ async def complete_level(request: Request):
|
||||
fast_streak = 0
|
||||
no_hints_streak = 0
|
||||
words_found = 0
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
wave_completed = False
|
||||
wave_points = 0
|
||||
wave_max_points = 0
|
||||
wave_medal_result = "none"
|
||||
current_wave = 1
|
||||
current_position_in_wave = 1
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT id, telegram_id, last_completed_level, current_level, difficulty FROM users WHERE telegram_id = $1",
|
||||
"SELECT id, telegram_id, last_completed_level, current_level FROM users WHERE telegram_id = $1",
|
||||
telegram_id
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(401, "User not registered")
|
||||
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
|
||||
level = await conn.fetchrow(
|
||||
"SELECT id, level_number, grid_size, level FROM levels WHERE id = $1", level_id
|
||||
)
|
||||
@@ -430,23 +420,11 @@ async def complete_level(request: Request):
|
||||
# -20 за каждую подсказку
|
||||
list_opened = bool(body.get("list_opened", False))
|
||||
|
||||
# 🔧 НОВОЕ (13.10.2026): на Hard подсказки и список слов недоступны.
|
||||
if difficulty == "hard" and (hints_used > 0 or list_opened):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Hints and word list are disabled on Hard difficulty"
|
||||
)
|
||||
|
||||
# Очки в зависимости от сложности
|
||||
if difficulty == "hard":
|
||||
# Hard: фикс 110 (без подсказок и списка)
|
||||
points = 110
|
||||
else:
|
||||
# Easy / Medium
|
||||
bonus = 10 if hints_used == 0 else 0
|
||||
penalty_hints = 20 * hints_used
|
||||
penalty_list = 0 if difficulty == "easy" else 20 * (1 if list_opened else 0)
|
||||
points = max(20, min(110, 100 - penalty_hints - penalty_list + bonus))
|
||||
# Очки: база 100, −20 за каждую подсказку, −20 за список слов,
|
||||
# +10 если без подсказок.
|
||||
# Формула: max(20, min(110, 100 - 20*hints_used - 20*list_opened + bonus))
|
||||
bonus = 10 if hints_used == 0 else 0
|
||||
points = max(20, min(110, 100 - 20 * hints_used - 20 * (1 if list_opened else 0) + bonus))
|
||||
|
||||
# Начисляем XP через единую функцию
|
||||
from services.xp import award_xp
|
||||
@@ -459,41 +437,17 @@ async def complete_level(request: Request):
|
||||
# уже была создана hints.py (юзер взял подсказку → уровень не завершится).
|
||||
# Теперь UPSERT с ON CONFLICT DO UPDATE.
|
||||
# hints_used уже прочитан из БД выше (не доверяем клиенту).
|
||||
# 🔧 ФИКС (13.10.2026): wave_off_by_one —
|
||||
# session_level_number хранит позицию СЛЕДУЮЩЕГО уровня
|
||||
# (уже увеличенную при выдаче), поэтому модалка волны
|
||||
# срабатывала на 9-м уровне. Читаем current_wave /
|
||||
# current_position_in_wave — позицию именно завершаемого уровня.
|
||||
wave_row = await conn.fetchrow(
|
||||
"SELECT current_wave, current_position_in_wave FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
if wave_row and wave_row["current_wave"] and wave_row["current_position_in_wave"]:
|
||||
current_wave = int(wave_row["current_wave"])
|
||||
current_position_in_wave = int(wave_row["current_position_in_wave"])
|
||||
else:
|
||||
# Fallback для старых записей без current_* полей.
|
||||
global_level = await conn.fetchval(
|
||||
"SELECT global_level_number FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
global_level = int(global_level or 1)
|
||||
from services.waves import wave_for_level, level_in_wave
|
||||
current_wave = wave_for_level(global_level)
|
||||
current_position_in_wave = level_in_wave(global_level)
|
||||
|
||||
await conn.execute("""
|
||||
INSERT INTO user_progress
|
||||
(user_id, level_id, completed_at, hints_used, score, level, current_streak, wave)
|
||||
VALUES ($1, $2, NOW(), $3, $4, $5, 0, $6)
|
||||
(user_id, level_id, completed_at, hints_used, score, level, current_streak)
|
||||
VALUES ($1, $2, NOW(), $3, $4, $5, 0)
|
||||
ON CONFLICT (user_id, level_id) DO UPDATE
|
||||
SET completed_at = NOW(),
|
||||
hints_used = $3,
|
||||
score = $4,
|
||||
level = $5,
|
||||
current_streak = 0,
|
||||
wave = $6
|
||||
""", telegram_id, level_id, hints_used, score, level_name, current_wave)
|
||||
current_streak = 0
|
||||
""", telegram_id, level_id, hints_used, score, level_name)
|
||||
|
||||
# 🔧 ОБНОВЛЕНО (07.10.2026): единый счётчик progress.
|
||||
# Обновляем только users.last_completed_level — глобальный.
|
||||
@@ -545,21 +499,18 @@ async def complete_level(request: Request):
|
||||
"SELECT COUNT(*) FROM level_words WHERE level_id = $1", level_id
|
||||
) or 0
|
||||
|
||||
# Пройдено волн = current_wave - 1; если только что завершили
|
||||
# 10-й уровень волны — волна пройдена (+1).
|
||||
waves_completed = current_wave - 1
|
||||
if current_position_in_wave == 10:
|
||||
waves_completed += 1
|
||||
wave_row = await conn.fetchrow(
|
||||
"SELECT session_number, session_level_number FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
session_number = int(wave_row["session_number"] or 1) if wave_row else 1
|
||||
session_level_number = int(wave_row["session_level_number"] or 1) if wave_row else 1
|
||||
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
from services.waves import max_points_for_wave, wave_medal
|
||||
wave_completed = (current_position_in_wave == 10)
|
||||
wave_points = await conn.fetchval(
|
||||
"SELECT COALESCE(SUM(score), 0) FROM user_progress WHERE user_id = $1 AND wave = $2",
|
||||
telegram_id, current_wave,
|
||||
) or 0
|
||||
wave_max_points = max_points_for_wave()
|
||||
wave_medal_result = wave_medal(wave_points, wave_max_points)
|
||||
# Пройдено волн = session_number - 1; если только что завершили
|
||||
# 10-й уровень волны — волна пройдена (+1).
|
||||
waves_completed = session_number - 1
|
||||
if session_level_number == 10:
|
||||
waves_completed += 1
|
||||
|
||||
# XP филворда = сумма score по user_progress (уже посчитана как total_score).
|
||||
wordsearch_xp = total_score
|
||||
@@ -652,12 +603,6 @@ async def complete_level(request: Request):
|
||||
"rank_key": xp_result["rank_key"],
|
||||
"xp_in_level": xp_result["xp_in_level"],
|
||||
"xp_needed": xp_result["xp_needed"],
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
"wave_completed": wave_completed,
|
||||
"wave_number": current_wave,
|
||||
"wave_points": wave_points,
|
||||
"wave_max_points": wave_max_points,
|
||||
"wave_medal": wave_medal_result,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -76,26 +76,6 @@ async def set_language(request: Request):
|
||||
}
|
||||
|
||||
|
||||
@router.post("/set-difficulty")
|
||||
async def set_difficulty(request: Request):
|
||||
"""Устанавливает уровень сложности (easy/medium/hard)."""
|
||||
user_id, _ = await require_auth(request)
|
||||
body = await request.json()
|
||||
difficulty = body.get("difficulty", "medium")
|
||||
|
||||
if difficulty not in {"easy", "medium", "hard"}:
|
||||
raise HTTPException(400, "Unsupported difficulty")
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE users SET difficulty = $1 WHERE telegram_id = $2",
|
||||
difficulty, user_id,
|
||||
)
|
||||
|
||||
return {"status": "ok", "difficulty": difficulty}
|
||||
|
||||
|
||||
@router.post("/set-level")
|
||||
async def set_level(request: Request):
|
||||
"""Устанавливает текущий уровень пользователя (A1, A2, B1, B2, C1, C2)"""
|
||||
|
||||
Reference in New Issue
Block a user