Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba9a43dcfa | ||
|
|
3c9548540c | ||
|
|
5810eccde1 | ||
|
|
1df1119d11 | ||
|
|
965d5d2503 | ||
|
|
a313c08b95 | ||
|
|
400cf375be | ||
|
|
11ef94a9bf | ||
|
|
ed60a54e0c | ||
|
|
2d687904b0 | ||
|
|
c7ca0c97c2 | ||
|
|
3dfe34f18a | ||
|
|
61fbbe55e8 | ||
|
|
7cbde183ff | ||
|
|
da3f1567a8 | ||
|
|
82eb9208d8 | ||
|
|
5b2dbc0d42 | ||
|
|
3548654d6a | ||
|
|
4e78c32c18 | ||
|
|
5be242aafd | ||
|
|
10242f89b3 | ||
|
|
299c4e2fd5 | ||
|
|
38e0c2fe80 | ||
|
|
d669b37397 | ||
|
|
d334bc958d |
+134
-5
@@ -258,20 +258,31 @@ async def init_db():
|
||||
)
|
||||
""")
|
||||
|
||||
# ============ Убираем старый UNIQUE constraint с sentences.sentence_number ============
|
||||
# ============ Убираем составной UNIQUE (level, sentence_number) ============
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentences DROP CONSTRAINT IF EXISTS sentences_sentence_number_key
|
||||
ALTER TABLE sentences DROP CONSTRAINT IF EXISTS sentences_sentence_number_unique
|
||||
""")
|
||||
|
||||
# ============ Добавляем составной UNIQUE (level, sentence_number) ============
|
||||
# ============ Пересчёт номеров: единый пул 1..N ============
|
||||
await conn.execute("""
|
||||
UPDATE sentences s
|
||||
SET sentence_number = sub.rn
|
||||
FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
|
||||
FROM sentences
|
||||
) sub
|
||||
WHERE s.id = sub.id
|
||||
""")
|
||||
|
||||
# ============ Добавляем UNIQUE (sentence_number) ============
|
||||
await conn.execute("""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'sentences_sentence_number_unique'
|
||||
WHERE conname = 'sentences_sentence_number_key'
|
||||
) THEN
|
||||
ALTER TABLE sentences ADD CONSTRAINT sentences_sentence_number_unique UNIQUE (level, sentence_number);
|
||||
ALTER TABLE sentences ADD CONSTRAINT sentences_sentence_number_key UNIQUE (sentence_number);
|
||||
END IF;
|
||||
END $$;
|
||||
""")
|
||||
@@ -300,6 +311,60 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added level column to sentence_progress")
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): list_opened — счётчик «показать предложение»
|
||||
# для текущего предложения. Medium — лимит 2, Easy — ∞, Hard — 0.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_progress' AND column_name = 'list_opened'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_progress
|
||||
ADD COLUMN list_opened INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added list_opened column to sentence_progress")
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): no_mistakes_streak — серия предложений без ошибок.
|
||||
# +1 если предложение собрано без ошибок, иначе сброс в 0.
|
||||
# Нужен для достижения sentence_no_mistakes.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_progress' AND column_name = 'no_mistakes_streak'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_progress
|
||||
ADD COLUMN no_mistakes_streak INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added no_mistakes_streak column to sentence_progress")
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): perfect_streak — серия идеальных предложений
|
||||
# (без ошибок + без показов). +1 если всё чисто, иначе сброс в 0.
|
||||
# Нужен для достижения sentence_perfect_streak.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_progress' AND column_name = 'perfect_streak'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_progress
|
||||
ADD COLUMN perfect_streak INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added perfect_streak column to sentence_progress")
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): completion_time — время прохождения последнего
|
||||
# предложения (сек). Для статистики и бонуса Hard (≤15 сек).
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_progress' AND column_name = 'completion_time'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_progress
|
||||
ADD COLUMN completion_time INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added completion_time column to sentence_progress")
|
||||
|
||||
# ============ typing_progress ============
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS typing_progress (
|
||||
@@ -993,6 +1058,70 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added perfect_streak column to bubble_words_progress")
|
||||
|
||||
# ============ sentence_stats ============
|
||||
# 🔧 НОВОЕ (16.10.2026): глобальная статистика игры «Составь предложение».
|
||||
# PK = user_id (одна строка на юзера), по образцу word_quiz_progress.
|
||||
# total_score — суммарные очки; no_mistakes_streak / perfect_streak —
|
||||
# серии для достижений sentence_no_mistakes / sentence_perfect_streak.
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sentence_stats (
|
||||
user_id BIGINT PRIMARY KEY
|
||||
REFERENCES users(telegram_id) ON DELETE CASCADE,
|
||||
total_score INTEGER DEFAULT 0,
|
||||
no_mistakes_streak INTEGER DEFAULT 0,
|
||||
perfect_streak INTEGER DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
|
||||
# ============ Авто-миграция: total_score ============
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_stats' AND column_name = 'total_score'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_stats
|
||||
ADD COLUMN total_score INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added total_score column to sentence_stats")
|
||||
|
||||
# ============ Авто-миграция: no_mistakes_streak ============
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_stats' AND column_name = 'no_mistakes_streak'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_stats
|
||||
ADD COLUMN no_mistakes_streak INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added no_mistakes_streak column to sentence_stats")
|
||||
|
||||
# ============ Авто-миграция: perfect_streak ============
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_stats' AND column_name = 'perfect_streak'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_stats
|
||||
ADD COLUMN perfect_streak INTEGER DEFAULT 0
|
||||
""")
|
||||
logger.info("Added perfect_streak column to sentence_stats")
|
||||
|
||||
# ============ Авто-миграция: updated_at ============
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'sentence_stats' AND column_name = 'updated_at'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE sentence_stats
|
||||
ADD COLUMN updated_at TIMESTAMP DEFAULT NOW()
|
||||
""")
|
||||
logger.info("Added updated_at column to sentence_stats")
|
||||
|
||||
# ============ wrong_because_explanations ============
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
||||
|
||||
+64
-13
@@ -112,7 +112,7 @@ ACHIEVEMENTS_DATA = [
|
||||
"desc_pl": "Zdobądź 10 000 XP w filwordach", "desc_ru": "Набрать 10 000 XP в филвордах", "desc_uk": "Набрати 10 000 XP у філвордах", "desc_en": "Earn 10,000 XP in word searches",
|
||||
"type": "wordsearch_xp", "value": 10000},
|
||||
|
||||
# ===== Sentence Builder (10) =====
|
||||
# ===== Sentence Builder (20) =====
|
||||
{"code": "first_sentence", "category": "sentence", "icon": "📝",
|
||||
"name_pl": "Debiutant", "name_ru": "Дебютант", "name_uk": "Дебютант", "name_en": "Debutant",
|
||||
"desc_pl": "Ułóż 1 zdanie", "desc_ru": "Составить 1 предложение", "desc_uk": "Скласти 1 речення", "desc_en": "Build 1 sentence",
|
||||
@@ -138,20 +138,16 @@ ACHIEVEMENTS_DATA = [
|
||||
"desc_pl": "Ułóż 200 zdań", "desc_ru": "Составить 200 предложений", "desc_uk": "Скласти 200 речень", "desc_en": "Build 200 sentences",
|
||||
"type": "sentences_completed", "value": 200},
|
||||
|
||||
{"code": "perfect_sentence_5", "category": "sentence", "icon": "✨",
|
||||
"name_pl": "Perfekcjonista", "name_ru": "Перфекционист", "name_uk": "Перфекціоніст", "name_en": "Perfectionist",
|
||||
"desc_pl": "Ułóż 5 zdań bez błędu", "desc_ru": "Составить 5 предложений без единой ошибки", "desc_uk": "Скласти 5 речень без жодної помилки", "desc_en": "Build 5 sentences without mistakes",
|
||||
"type": "perfect_sentences", "value": 5},
|
||||
{"code": "sentence_500", "category": "sentence", "icon": "🌟",
|
||||
"name_pl": "Legenda zdań", "name_ru": "Легенда предложений", "name_uk": "Легенда речень", "name_en": "Sentence Legend",
|
||||
"desc_pl": "Ułóż 500 zdań", "desc_ru": "Составить 500 предложений", "desc_uk": "Скласти 500 речень", "desc_en": "Build 500 sentences",
|
||||
"type": "sentences_completed", "value": 500},
|
||||
|
||||
{"code": "sentence_perfect_10", "category": "sentence", "icon": "💎",
|
||||
"name_pl": "Mistrz zdań", "name_ru": "Мастер предложений", "name_uk": "Майстер речень", "name_en": "Sentence Master",
|
||||
"desc_pl": "Ułóż 10 zdań bez błędu", "desc_ru": "Составить 10 предложений без ошибок", "desc_uk": "Скласти 10 речень без помилок", "desc_en": "Build 10 sentences without mistakes",
|
||||
"type": "perfect_sentences", "value": 10},
|
||||
{"code": "sentence_1000", "category": "sentence", "icon": "👑",
|
||||
"name_pl": "Guru zdań", "name_ru": "Гуру предложений", "name_uk": "Гуру речень", "name_en": "Sentence Guru",
|
||||
"desc_pl": "Ułóż 1000 zdań", "desc_ru": "Составить 1000 предложений", "desc_uk": "Скласти 1000 речень", "desc_en": "Build 1000 sentences",
|
||||
"type": "sentences_completed", "value": 1000},
|
||||
|
||||
{"code": "sentence_streak_10", "category": "sentence", "icon": "💪",
|
||||
"name_pl": "Nieomylny", "name_ru": "Безошибочный", "name_uk": "Безпомилковий", "name_en": "Flawless",
|
||||
"desc_pl": "Ułóż 10 zdań z rzędu bez błędu", "desc_ru": "Составить 10 предложений подряд без ошибок", "desc_uk": "Скласти 10 речень поспіль без помилок", "desc_en": "Build 10 sentences in a row without mistakes",
|
||||
"type": "sentence_streak", "value": 10},
|
||||
|
||||
{"code": "speed_10", "category": "sentence", "icon": "🚀",
|
||||
"name_pl": "Turbo", "name_ru": "Турбо", "name_uk": "Турбо", "name_en": "Turbo",
|
||||
@@ -162,6 +158,61 @@ ACHIEVEMENTS_DATA = [
|
||||
"name_pl": "Ekspres", "name_ru": "Экспресс", "name_uk": "Експрес", "name_en": "Express",
|
||||
"desc_pl": "Ułóż zdanie w mniej niż 5 sekund", "desc_ru": "Составить предложение быстрее 5 секунд", "desc_uk": "Скласти речення швидше 5 секунд", "desc_en": "Build a sentence in under 5 seconds",
|
||||
"type": "speed_sentence", "value": 5},
|
||||
|
||||
{"code": "sentence_speed_3", "category": "sentence", "icon": "⚡",
|
||||
"name_pl": "Błyskawica", "name_ru": "Молния", "name_uk": "Блискавка", "name_en": "Lightning",
|
||||
"desc_pl": "Ułóż zdanie w mniej niż 3 sekundy", "desc_ru": "Составить предложение быстрее 3 секунд", "desc_uk": "Скласти речення швидше 3 секунд", "desc_en": "Build a sentence in under 3 seconds",
|
||||
"type": "speed_sentence", "value": 3},
|
||||
|
||||
{"code": "sentence_no_mistakes_5", "category": "sentence", "icon": "✨",
|
||||
"name_pl": "Bezbłędny", "name_ru": "Безошибочный", "name_uk": "Безпомилковий", "name_en": "Flawless",
|
||||
"desc_pl": "Ułóż 5 zdań bez błędu z rzędu", "desc_ru": "Составить 5 предложений без ошибок подряд", "desc_uk": "Скласти 5 речень без помилок поспіль", "desc_en": "Build 5 sentences without mistakes in a row",
|
||||
"type": "sentence_no_mistakes", "value": 5},
|
||||
|
||||
{"code": "sentence_no_mistakes_10", "category": "sentence", "icon": "💎",
|
||||
"name_pl": "Nieomylny", "name_ru": "Безошибочный", "name_uk": "Безпомилковий", "name_en": "Infallible",
|
||||
"desc_pl": "Ułóż 10 zdań bez błędu z rzędu", "desc_ru": "Составить 10 предложений без ошибок подряд", "desc_uk": "Скласти 10 речень без помилок поспіль", "desc_en": "Build 10 sentences without mistakes in a row",
|
||||
"type": "sentence_no_mistakes", "value": 10},
|
||||
|
||||
{"code": "sentence_no_mistakes_25", "category": "sentence", "icon": "🏆",
|
||||
"name_pl": "Mistrz czystości", "name_ru": "Мастер чистоты", "name_uk": "Майстер чистоти", "name_en": "Pure Master",
|
||||
"desc_pl": "Ułóż 25 zdań bez błędu z rzędu", "desc_ru": "Составить 25 предложений без ошибок подряд", "desc_uk": "Скласти 25 речень без помилок поспіль", "desc_en": "Build 25 sentences without mistakes in a row",
|
||||
"type": "sentence_no_mistakes", "value": 25},
|
||||
|
||||
{"code": "sentence_no_mistakes_50", "category": "sentence", "icon": "👑",
|
||||
"name_pl": "Król czystości", "name_ru": "Король чистоты", "name_uk": "Король чистоти", "name_en": "Pure King",
|
||||
"desc_pl": "Ułóż 50 zdań bez błędu z rzędu", "desc_ru": "Составить 50 предложений без ошибок подряд", "desc_uk": "Скласти 50 речень без помилок поспіль", "desc_en": "Build 50 sentences without mistakes in a row",
|
||||
"type": "sentence_no_mistakes", "value": 50},
|
||||
|
||||
{"code": "sentence_perfect_streak_5", "category": "sentence", "icon": "✨",
|
||||
"name_pl": "Perfekcyjna seria", "name_ru": "Идеальная серия", "name_uk": "Ідеальна серія", "name_en": "Perfect Streak",
|
||||
"desc_pl": "Ułóż 5 idealnych zdań z rzędu", "desc_ru": "Составить 5 идеальных предложений подряд", "desc_uk": "Скласти 5 ідеальних речень поспіль", "desc_en": "Build 5 perfect sentences in a row",
|
||||
"type": "sentence_perfect_streak", "value": 5},
|
||||
|
||||
{"code": "sentence_perfect_streak_10", "category": "sentence", "icon": "💎",
|
||||
"name_pl": "Mistrz perfekcji", "name_ru": "Мастер идеала", "name_uk": "Майстер ідеалу", "name_en": "Perfection Master",
|
||||
"desc_pl": "Ułóż 10 idealnych zdań z rzędu", "desc_ru": "Составить 10 идеальных предложений подряд", "desc_uk": "Скласти 10 ідеальних речень поспіль", "desc_en": "Build 10 perfect sentences in a row",
|
||||
"type": "sentence_perfect_streak", "value": 10},
|
||||
|
||||
{"code": "sentence_perfect_streak_25", "category": "sentence", "icon": "🏆",
|
||||
"name_pl": "Perfekcjonista", "name_ru": "Перфекционист", "name_uk": "Перфекціоніст", "name_en": "Perfectionist",
|
||||
"desc_pl": "Ułóż 25 idealnych zdań z rzędu", "desc_ru": "Составить 25 идеальных предложений подряд", "desc_uk": "Скласти 25 ідеальних речень поспіль", "desc_en": "Build 25 perfect sentences in a row",
|
||||
"type": "sentence_perfect_streak", "value": 25},
|
||||
|
||||
{"code": "sentence_perfect_streak_50", "category": "sentence", "icon": "👑",
|
||||
"name_pl": "Idealny król", "name_ru": "Идеальный король", "name_uk": "Ідеальний король", "name_en": "Perfect King",
|
||||
"desc_pl": "Ułóż 50 idealnych zdań z rzędu", "desc_ru": "Составить 50 идеальных предложений подряд", "desc_uk": "Скласти 50 ідеальних речень поспіль", "desc_en": "Build 50 perfect sentences in a row",
|
||||
"type": "sentence_perfect_streak", "value": 50},
|
||||
|
||||
{"code": "sentence_xp_1000", "category": "sentence", "icon": "💎",
|
||||
"name_pl": "Zdaniowy XP", "name_ru": "XP предложений", "name_uk": "XP речень", "name_en": "Sentence XP",
|
||||
"desc_pl": "Zdobądź 1000 punktów w zdaniach", "desc_ru": "Набрать 1000 очков в предложениях", "desc_uk": "Набрати 1000 балів у реченнях", "desc_en": "Earn 1000 points in sentences",
|
||||
"type": "sentence_xp", "value": 1000},
|
||||
|
||||
{"code": "sentence_xp_5000", "category": "sentence", "icon": "👑",
|
||||
"name_pl": "Zdaniowy diament", "name_ru": "Бриллиант предложений", "name_uk": "Діамант речень", "name_en": "Sentence Diamond",
|
||||
"desc_pl": "Zdobądź 5000 punktów w zdaniach", "desc_ru": "Набрать 5000 очков в предложениях", "desc_uk": "Набрати 5000 балів у реченнях", "desc_en": "Earn 5000 points in sentences",
|
||||
"type": "sentence_xp", "value": 5000},
|
||||
|
||||
# ===== Word Quiz (20) =====
|
||||
{"code": "quiz_10", "category": "wordquiz", "icon": "🧠",
|
||||
|
||||
+130
-43
@@ -65,6 +65,7 @@ async def init_sentences():
|
||||
("B1", "sentences_b1.csv"),
|
||||
]
|
||||
|
||||
offset = 0
|
||||
for level, filename in level_files:
|
||||
sentences = load_sentences_from_csv(filename)
|
||||
for i, s in enumerate(sentences):
|
||||
@@ -74,11 +75,12 @@ async def init_sentences():
|
||||
await conn.execute(
|
||||
"""INSERT INTO sentences (sentence_number, sentence_pl, translation_ru, translation_uk, translation_en, difficulty, level)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (level, sentence_number) DO NOTHING""",
|
||||
i + 1, s["sentence_pl"],
|
||||
ON CONFLICT (sentence_number) DO NOTHING""",
|
||||
offset + i + 1, s["sentence_pl"],
|
||||
s["translation_ru"], s["translation_uk"], s["translation_en"],
|
||||
difficulty, level
|
||||
)
|
||||
offset += len(sentences)
|
||||
|
||||
|
||||
def normalize_word_for_display(word: str) -> str:
|
||||
@@ -100,28 +102,34 @@ async def get_next_sentence(request: Request):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT app_language, current_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
"SELECT app_language, 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"
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
|
||||
# Находим случайное непройденное предложение нужного уровня
|
||||
# Находим случайное непройденное предложение (единый пул)
|
||||
row = await conn.fetchrow("""
|
||||
SELECT s.* FROM sentences s
|
||||
WHERE s.level = $1
|
||||
AND s.id NOT IN (
|
||||
SELECT sentence_id FROM sentence_progress WHERE user_id = $2
|
||||
WHERE s.id NOT IN (
|
||||
SELECT sentence_id FROM sentence_progress WHERE user_id = $1 AND completed_at IS NOT NULL
|
||||
)
|
||||
ORDER BY RANDOM()
|
||||
LIMIT 1
|
||||
""", current_level, telegram_id)
|
||||
""", telegram_id)
|
||||
|
||||
if not row:
|
||||
return {"completed": True, "message": "All sentences completed!"}
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): строка прогресса (in-progress) для счётчика list_opened.
|
||||
await conn.execute("""
|
||||
INSERT INTO sentence_progress (user_id, sentence_id, list_opened, completion_time)
|
||||
VALUES ($1, $2, 0, 0)
|
||||
ON CONFLICT (user_id, sentence_id) DO NOTHING
|
||||
""", telegram_id, row["id"])
|
||||
|
||||
# Оригинальные слова (для проверки)
|
||||
correct_words = row["sentence_pl"].split()
|
||||
|
||||
@@ -140,10 +148,64 @@ async def get_next_sentence(request: Request):
|
||||
"correct_words": display_words,
|
||||
"translation": translation,
|
||||
"difficulty": row["difficulty"],
|
||||
"user_difficulty": difficulty,
|
||||
"level": row["level"],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/show-answer")
|
||||
async def show_answer(request: Request):
|
||||
"""Подсказка «показать предложение». Easy — ∞ бесплатно, Medium — 2 раза × −20, Hard — 403."""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
body = await request.json()
|
||||
sentence_id = body.get("sentence_id")
|
||||
if not sentence_id:
|
||||
raise HTTPException(400, "sentence_id required")
|
||||
|
||||
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"
|
||||
|
||||
row = await conn.fetchrow(
|
||||
"SELECT sentence_pl FROM sentences WHERE id = $1", sentence_id
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(404, "Sentence not found")
|
||||
|
||||
if difficulty == "hard":
|
||||
raise HTTPException(403, "Hints are disabled on Hard difficulty")
|
||||
|
||||
progress = await conn.fetchrow(
|
||||
"SELECT list_opened FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||||
telegram_id, sentence_id
|
||||
)
|
||||
list_opened = (progress["list_opened"] if progress else 0) or 0
|
||||
|
||||
if difficulty == "medium":
|
||||
if list_opened >= 2:
|
||||
raise HTTPException(403, "Show answer limit reached on Medium difficulty")
|
||||
await conn.execute("""
|
||||
INSERT INTO sentence_progress (user_id, sentence_id, list_opened)
|
||||
VALUES ($1, $2, 1)
|
||||
ON CONFLICT (user_id, sentence_id) DO UPDATE
|
||||
SET list_opened = sentence_progress.list_opened + 1
|
||||
""", telegram_id, sentence_id)
|
||||
new_list_opened = list_opened + 1
|
||||
else:
|
||||
new_list_opened = list_opened # Easy — не инкрементим
|
||||
|
||||
return {
|
||||
"sentence_pl": row["sentence_pl"],
|
||||
"list_opened": new_list_opened,
|
||||
"max_list_opened": None if difficulty == "easy" else 2,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/check")
|
||||
async def check_sentence(request: Request):
|
||||
"""Проверка предложения с защитой от повторного прохождения и выдачей достижений"""
|
||||
@@ -176,7 +238,7 @@ async def check_sentence(request: Request):
|
||||
raise HTTPException(404, "Sentence not found")
|
||||
|
||||
existing_progress = await conn.fetchrow(
|
||||
"SELECT score, completed_at FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||||
"SELECT score, completed_at FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2 AND completed_at IS NOT NULL",
|
||||
telegram_id, sentence_id
|
||||
)
|
||||
|
||||
@@ -208,36 +270,67 @@ async def check_sentence(request: Request):
|
||||
is_correct = user_words_normalized == correct_words_normalized
|
||||
|
||||
if is_correct:
|
||||
word_count = len(correct_words_original)
|
||||
|
||||
# 🆕 Расчёт звёзд для "Составь предложение"
|
||||
# Старт 5. Штрафы:
|
||||
# -1 за каждую неверную проверку (клиент шлёт wrong_checks)
|
||||
# -1 если time > лимита (по длине: 3-4 → 30с, 5-6 → 45с, 7-8 → 60с)
|
||||
# 🔧 НОВОЕ (16.10.2026): очки по формуле сложностей.
|
||||
# Easy — фикс 20. Medium — 60 − 20×list_opened (мин 20).
|
||||
# Hard — 100, +50 бонус если completion_time <= 15 сек.
|
||||
wrong_checks = int(body.get("wrong_checks", 0) or 0)
|
||||
|
||||
if word_count <= 4:
|
||||
time_limit = 30
|
||||
elif word_count <= 6:
|
||||
time_limit = 45
|
||||
else:
|
||||
time_limit = 60
|
||||
user_row = await conn.fetchrow(
|
||||
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
difficulty = (user_row["difficulty"] if user_row else None) or "medium"
|
||||
|
||||
time_penalty = 1 if (completion_time and completion_time > time_limit) else 0
|
||||
wrong_penalty = min(max(0, wrong_checks), 3)
|
||||
stars = max(1, 5 - wrong_penalty - time_penalty)
|
||||
progress_row = await conn.fetchrow(
|
||||
"SELECT list_opened FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||||
telegram_id, sentence_id
|
||||
)
|
||||
list_opened = (progress_row["list_opened"] if progress_row else 0) or 0
|
||||
|
||||
if difficulty == "easy":
|
||||
points = 20
|
||||
elif difficulty == "medium":
|
||||
points = max(20, 60 - 20 * list_opened)
|
||||
else: # hard
|
||||
points = 100
|
||||
if completion_time is not None and completion_time <= 15:
|
||||
points = 150
|
||||
|
||||
# Начисляем XP
|
||||
from services.xp import award_xp
|
||||
xp_result = await award_xp(conn, telegram_id, "sentence", stars)
|
||||
xp_result = await award_xp(conn, telegram_id, "sentence", points)
|
||||
score = xp_result["points"]
|
||||
|
||||
await conn.execute(
|
||||
"""INSERT INTO sentence_progress (user_id, sentence_id, completed_at, score, level)
|
||||
VALUES ($1, $2, NOW(), $3, $4)""",
|
||||
telegram_id, sentence_id, score, row["level"],
|
||||
"""INSERT INTO sentence_progress (user_id, sentence_id, completed_at, score, level, completion_time)
|
||||
VALUES ($1, $2, NOW(), $3, $4, $5)
|
||||
ON CONFLICT (user_id, sentence_id) DO UPDATE
|
||||
SET completed_at = NOW(), score = $3, level = $4, completion_time = $5""",
|
||||
telegram_id, sentence_id, score, row["level"], completion_time or 0,
|
||||
)
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): серии в sentence_stats (PK user_id).
|
||||
await conn.execute("""
|
||||
INSERT INTO sentence_stats (user_id, total_score, no_mistakes_streak, perfect_streak, updated_at)
|
||||
VALUES ($1, $2,
|
||||
CASE WHEN $3 = 0 THEN 1 ELSE 0 END,
|
||||
CASE WHEN $3 = 0 AND $4 = 0 THEN 1 ELSE 0 END,
|
||||
NOW())
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET total_score = sentence_stats.total_score + $2,
|
||||
no_mistakes_streak = CASE WHEN $3 = 0 THEN sentence_stats.no_mistakes_streak + 1 ELSE 0 END,
|
||||
perfect_streak = CASE WHEN $3 = 0 AND $4 = 0 THEN sentence_stats.perfect_streak + 1 ELSE 0 END,
|
||||
updated_at = NOW()
|
||||
""", telegram_id, score, wrong_checks, list_opened)
|
||||
|
||||
# 🔧 НОВОЕ (16.10.2026): читаем серии/очки для достижений.
|
||||
stats_row = await conn.fetchrow(
|
||||
"SELECT total_score, no_mistakes_streak, perfect_streak FROM sentence_stats WHERE user_id = $1",
|
||||
telegram_id
|
||||
)
|
||||
sentence_total_score = stats_row["total_score"] if stats_row else 0
|
||||
sentence_no_mistakes = stats_row["no_mistakes_streak"] if stats_row else 0
|
||||
sentence_perfect_streak = stats_row["perfect_streak"] if stats_row else 0
|
||||
|
||||
# 🔧 ФИКС (23.09.2026): achievements_nested_pool_acquire_sentences —
|
||||
# раньше check_and_award_achievements вызывался ВНУТРИ async with pool.acquire(),
|
||||
# что могло привести к дедлоку пула. Теперь собираем данные внутри блока,
|
||||
@@ -268,6 +361,9 @@ async def check_sentence(request: Request):
|
||||
achievements_to_check = [
|
||||
("sentences_completed", sentences_completed),
|
||||
("total_score", grand_total),
|
||||
("sentence_no_mistakes", sentence_no_mistakes),
|
||||
("sentence_perfect_streak", sentence_perfect_streak),
|
||||
("sentence_xp", sentence_total_score),
|
||||
]
|
||||
if completion_time is not None and completion_time > 0:
|
||||
achievements_to_check.append(("speed_sentence", int(completion_time)))
|
||||
@@ -287,7 +383,6 @@ async def check_sentence(request: Request):
|
||||
"score": score,
|
||||
"new_achievements": new_achievements,
|
||||
# 🆕 XP
|
||||
"stars": xp_result["stars"],
|
||||
"base_points": xp_result["base_points"],
|
||||
"multiplier": xp_result["multiplier"],
|
||||
"points": xp_result["points"],
|
||||
@@ -315,21 +410,14 @@ async def get_sentence_stats(request: Request):
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT current_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
current_level = user["current_level"] if user else "A1"
|
||||
|
||||
total = await conn.fetchval(
|
||||
"SELECT COUNT(*) FROM sentences WHERE level = $1", current_level
|
||||
)
|
||||
total = await conn.fetchval("SELECT COUNT(*) FROM sentences")
|
||||
completed = await conn.fetchval(
|
||||
"SELECT COUNT(*) FROM sentence_progress WHERE user_id = $1 AND level = $2",
|
||||
telegram_id, current_level
|
||||
"SELECT COUNT(*) FROM sentence_progress WHERE user_id = $1 AND completed_at IS NOT NULL",
|
||||
telegram_id
|
||||
)
|
||||
total_score = await conn.fetchval(
|
||||
"SELECT COALESCE(SUM(score), 0) FROM sentence_progress WHERE user_id = $1 AND level = $2",
|
||||
telegram_id, current_level
|
||||
"SELECT COALESCE(SUM(score), 0) FROM sentence_progress WHERE user_id = $1 AND completed_at IS NOT NULL",
|
||||
telegram_id
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -338,5 +426,4 @@ async def get_sentence_stats(request: Request):
|
||||
"remaining": total - (completed or 0),
|
||||
"total_score": total_score or 0,
|
||||
"progress_percent": round(((completed or 0) / total * 100), 1) if total > 0 else 0,
|
||||
"level": current_level,
|
||||
}
|
||||
+2
-2
@@ -76,7 +76,7 @@ async def get_next_quiz(request: Request):
|
||||
FROM csv_words
|
||||
WHERE level_code = $1 AND word_pl != $2 AND word_pl NOT IN ({placeholders})
|
||||
ORDER BY RANDOM()
|
||||
LIMIT (wrong_count + 1)
|
||||
LIMIT 5
|
||||
""", current_level, correct_polish, *exclude_for_wrong)
|
||||
|
||||
if len(wrong_words) < wrong_count:
|
||||
@@ -86,7 +86,7 @@ async def get_next_quiz(request: Request):
|
||||
FROM csv_words
|
||||
WHERE level_code = $1 AND word_pl != $2
|
||||
ORDER BY RANDOM()
|
||||
LIMIT (wrong_count + 1)
|
||||
LIMIT 5
|
||||
""", current_level, correct_polish)
|
||||
|
||||
wrong_options = []
|
||||
|
||||
Reference in New Issue
Block a user