feat: XP foundation + waves + featured game + profile + leaderboard by total_xp

- services/xp.py: award_xp, level_for, RANKS (48), featured_game
- services/waves.py: wave_plan, grid_size_for, wave_medal
- routers/featured.py: GET /featured (игра дня ×1.5)
- routers/users.py: POST /set-nickname, POST /set-avatar
- routers/app_auth.py: /auth/me с XP-полями (level, rank_key, rank_name, xp)
- routers/game.py: award_xp + 3 штрафа + POST /game/next (волны)
- routers/wordquiz.py: award_xp + серии в choose_progress
- routers/bubblewords.py: award_xp + 4 штрафа
- routers/sentences.py: award_xp по длине предложения
- routers/leaderboard.py: сортировка по total_xp, XP-поля в ответе
- database.py: миграции user_profile, xp_log, choose_progress, user_seen_levels, user_game_progress, wave_results, bubble_levels, user_word_stats
- main.py: подключение routers/featured

Проверено:
- /auth/me отдаёт level=1, rank_00, xp_in_level
- /featured отдаёт wordsearch + seconds_left
- /game/complete-level начисляет XP через award_xp
- xp_log, user_profile заполняются
- /game/next выдаёт уровень по волнам
- /leaderboard сортирует по total_xp
This commit is contained in:
2026-10-09 08:12:19 +00:00
parent a3f7d9521f
commit 84927b063f
13 changed files with 1800 additions and 278 deletions
+189
View File
@@ -1335,6 +1335,195 @@ async def init_db():
""")
logger.info("Table auth_identities initialized (Pleily)")
# ============================================================
# 🔧 НОВОЕ (08.10.2026): XP-фундамент Pleily.
# user_profile, xp_log, choose_progress, user_seen_levels,
# user_game_progress, wave_results, bubble_levels,
# user_seen_bubble_levels, user_word_stats.
# + расширение sentences (tokens, alt_orders, word_count).
# ============================================================
# ---------- user_profile ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS user_profile (
user_id BIGINT PRIMARY KEY
REFERENCES users(telegram_id) ON DELETE CASCADE,
nickname TEXT,
avatar_id INTEGER DEFAULT 0,
total_xp INTEGER DEFAULT 0,
weekly_xp INTEGER DEFAULT 0,
week_started_at DATE DEFAULT CURRENT_DATE,
updated_at TIMESTAMP DEFAULT NOW()
)
""")
await conn.execute("""
CREATE INDEX IF NOT EXISTS idx_user_profile_weekly
ON user_profile(weekly_xp DESC)
""")
logger.info("Table user_profile initialized (XP)")
# ---------- xp_log ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS xp_log (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL
REFERENCES users(telegram_id) ON DELETE CASCADE,
game TEXT NOT NULL,
stars INTEGER NOT NULL,
base_points INTEGER NOT NULL,
multiplier NUMERIC(3,2) NOT NULL DEFAULT 1.0,
points INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
)
""")
await conn.execute("""
CREATE INDEX IF NOT EXISTS idx_xp_log_user_date
ON xp_log(user_id, created_at DESC)
""")
logger.info("Table xp_log initialized (XP)")
# ---------- choose_progress (серии в "Выбери слово") ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS choose_progress (
user_id BIGINT PRIMARY KEY
REFERENCES users(telegram_id) ON DELETE CASCADE,
current_streak INTEGER DEFAULT 0,
best_streak INTEGER DEFAULT 0,
updated_at TIMESTAMP DEFAULT NOW()
)
""")
logger.info("Table choose_progress initialized")
# ---------- user_seen_levels (филворд: какие уровни видел) ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS user_seen_levels (
user_id BIGINT NOT NULL
REFERENCES users(telegram_id) ON DELETE CASCADE,
level_id INTEGER NOT NULL
REFERENCES levels(id) ON DELETE CASCADE,
seen_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, level_id)
)
""")
await conn.execute("""
CREATE INDEX IF NOT EXISTS idx_user_seen_levels_user
ON user_seen_levels(user_id, seen_at DESC)
""")
logger.info("Table user_seen_levels initialized")
# ---------- user_game_progress (сессии филворда) ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS user_game_progress (
user_id BIGINT PRIMARY KEY
REFERENCES users(telegram_id) ON DELETE CASCADE,
session_number INTEGER DEFAULT 1,
session_level_number INTEGER DEFAULT 1,
global_level_number INTEGER DEFAULT 1,
time_limit_seconds INTEGER,
updated_at TIMESTAMP DEFAULT NOW()
)
""")
logger.info("Table user_game_progress initialized")
# ---------- wave_results (итоги волны) ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS wave_results (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL
REFERENCES users(telegram_id) ON DELETE CASCADE,
wave_number INTEGER NOT NULL,
stars_earned INTEGER DEFAULT 0,
medal TEXT DEFAULT 'none',
completed_at TIMESTAMP DEFAULT NOW(),
UNIQUE (user_id, wave_number)
)
""")
await conn.execute("""
CREATE INDEX IF NOT EXISTS idx_wave_results_user
ON wave_results(user_id, wave_number DESC)
""")
logger.info("Table wave_results initialized")
# ---------- bubble_levels ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS bubble_levels (
id BIGSERIAL PRIMARY KEY,
word_ids INTEGER[] NOT NULL,
difficulty INTEGER DEFAULT 1,
created_at TIMESTAMP DEFAULT NOW()
)
""")
logger.info("Table bubble_levels initialized")
# ---------- user_seen_bubble_levels ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS user_seen_bubble_levels (
user_id BIGINT NOT NULL
REFERENCES users(telegram_id) ON DELETE CASCADE,
bubble_level_id BIGINT NOT NULL
REFERENCES bubble_levels(id) ON DELETE CASCADE,
seen_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, bubble_level_id)
)
""")
logger.info("Table user_seen_bubble_levels initialized")
# ---------- user_word_stats (повторение слов) ----------
await conn.execute("""
CREATE TABLE IF NOT EXISTS user_word_stats (
user_id BIGINT NOT NULL
REFERENCES users(telegram_id) ON DELETE CASCADE,
word_pl TEXT NOT NULL,
correct INTEGER DEFAULT 0,
wrong INTEGER DEFAULT 0,
last_seen_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, word_pl)
)
""")
await conn.execute("""
CREATE INDEX IF NOT EXISTS idx_user_word_stats_user
ON user_word_stats(user_id, last_seen_at DESC)
""")
logger.info("Table user_word_stats initialized")
# ---------- sentences: tokens, alt_orders, word_count ----------
for col_name, col_type in (
("tokens", "JSONB DEFAULT '[]'::jsonb"),
("alt_orders", "JSONB DEFAULT '[]'::jsonb"),
("word_count", "INTEGER DEFAULT 0"),
):
col_exists = await conn.fetchval("""
SELECT 1 FROM information_schema.columns
WHERE table_name = 'sentences' AND column_name = $1
""", col_name)
if not col_exists:
await conn.execute(
f"ALTER TABLE sentences ADD COLUMN {col_name} {col_type}"
)
logger.info(f"Added {col_name} column to sentences")
# Backfill: word_count для существующих предложений
await conn.execute("""
UPDATE sentences
SET word_count = array_length(
regexp_split_to_array(trim(sentence_pl), '\\s+'), 1
)
WHERE word_count = 0 OR word_count IS NULL
""")
logger.info("Backfilled sentences.word_count")
# ---------- Backfill: user_profile для существующих юзеров ----------
await conn.execute("""
INSERT INTO user_profile (user_id, total_xp, weekly_xp)
SELECT u.telegram_id, 0, 0
FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM user_profile p WHERE p.user_id = u.telegram_id
)
ON CONFLICT (user_id) DO NOTHING
""")
logger.info("Backfilled user_profile for existing users")
await conn.execute("CREATE INDEX IF NOT EXISTS idx_sentences_level_number ON sentences(level, sentence_number)")
# Оставляем score-индексы (не дубли)
await conn.execute("CREATE INDEX IF NOT EXISTS idx_user_progress_score ON user_progress(score DESC)")