feat: track + options_language + test generator + повторы уроков
This commit is contained in:
+146
-25
@@ -57,6 +57,18 @@ Admin Content Router — контент-менеджер для редактир
|
||||
|
||||
🔧 НОВОЕ (02.10.2026): POST /lessons/lesson/{lesson_id}/add-question —
|
||||
добавление ОДНОГО нового вопроса в существующий урок (edit-режим).
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track —
|
||||
создание темы с выбором аудитории (pl / ru_uk / en).
|
||||
track включён в дерево /lessons/tree для фильтрации.
|
||||
topic_id теперь: {level}_{track}_{slug}.
|
||||
|
||||
🔧 НОВОЕ (04.10.2026): DELETE /lessons/topic/{topic_id} —
|
||||
удаление темы со всем содержимым (уроки, вопросы, опции, примеры).
|
||||
|
||||
🔧 НОВОЕ (04.10.2026): options_language —
|
||||
в create_lesson, update_lesson, add_question_to_lesson
|
||||
принимаем и сохраняем options_language ('pl' или 'user').
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
@@ -1183,6 +1195,7 @@ async def update_lesson(request: Request, lesson_id: str):
|
||||
"prompt_pl": "...", "prompt_en": "...", "prompt_ru": "...", "prompt_uk": "...",
|
||||
"hint_type": "first_letter" | null,
|
||||
"hint_value": "j" | null,
|
||||
"options_language": "pl" | "user",
|
||||
"options": [
|
||||
{"text_pl": "...", "text_en": "...", "text_ru": "...", "text_uk": "...",
|
||||
"is_correct": true, "wrong_because": null},
|
||||
@@ -1312,6 +1325,14 @@ async def update_lesson(request: Request, lesson_id: str):
|
||||
if hint_value:
|
||||
hint_value = str(hint_value).strip() or None
|
||||
|
||||
# 🔧 НОВОЕ (04.10.2026): options_language —
|
||||
# 'pl' — варианты на польском (узнавание, грамматика)
|
||||
# 'user' — варианты на языке юзера (перевод)
|
||||
# Принимаем из тела, дефолт 'pl'.
|
||||
options_language = (q.get("options_language") or "pl").strip().lower()
|
||||
if options_language not in ("pl", "user"):
|
||||
options_language = "pl"
|
||||
|
||||
questions.append({
|
||||
"question_id": question_id,
|
||||
"prompt_pl": prompt_pl,
|
||||
@@ -1321,6 +1342,7 @@ async def update_lesson(request: Request, lesson_id: str):
|
||||
"correct_answer": correct_answer,
|
||||
"hint_type": hint_type,
|
||||
"hint_value": hint_value,
|
||||
"options_language": options_language, # 🔧 НОВОЕ
|
||||
"options": options,
|
||||
})
|
||||
|
||||
@@ -1398,11 +1420,13 @@ async def update_lesson(request: Request, lesson_id: str):
|
||||
correct_answer = $5,
|
||||
hint_type = $6,
|
||||
hint_value = $7,
|
||||
options_language = $8,
|
||||
edited_at = NOW()
|
||||
WHERE question_id = $8
|
||||
WHERE question_id = $9
|
||||
""",
|
||||
q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"],
|
||||
q["correct_answer"], q["hint_type"], q["hint_value"],
|
||||
q["options_language"],
|
||||
q["question_id"],
|
||||
)
|
||||
|
||||
@@ -1484,6 +1508,9 @@ async def get_lessons_tree(
|
||||
🔧 НОВОЕ (02.10.2026): lessons_tree —
|
||||
дерево: уровни → темы → уроки. Один запрос вместо N+1.
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track_include —
|
||||
каждая тема теперь содержит поле track ('pl' / 'ru_uk' / 'en').
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"levels": [
|
||||
@@ -1495,23 +1522,14 @@ async def get_lessons_tree(
|
||||
"lessons_count": 20,
|
||||
"topics": [
|
||||
{
|
||||
"topic_id": "a1_greetings",
|
||||
"topic_id": "a1_ru_uk_greetings",
|
||||
"name_ru": "Приветствия",
|
||||
"name_pl": "Powitania",
|
||||
"order_number": 1,
|
||||
"track": "ru_uk",
|
||||
"lessons_count": 10,
|
||||
"test_questions_count": 0,
|
||||
"lessons": [
|
||||
{
|
||||
"lesson_id": "a1_greetings_l01",
|
||||
"order_number": 1,
|
||||
"skill_tag": "podstawowe_powitania",
|
||||
"title_ru": "...",
|
||||
"title_pl": "...",
|
||||
"questions_count": 3,
|
||||
"is_active": true
|
||||
}
|
||||
]
|
||||
"lessons": [...]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1536,9 +1554,10 @@ async def get_lessons_tree(
|
||||
|
||||
level_codes = [l["code"] for l in levels]
|
||||
|
||||
# Темы
|
||||
# 🔧 ОБНОВЛЕНО (04.10.2026): track_include —
|
||||
# включаем track в дерево, чтобы фронт мог показать бейджи + фильтровать.
|
||||
topics = await conn.fetch("""
|
||||
SELECT topic_id, level_code, order_number,
|
||||
SELECT topic_id, level_code, order_number, track,
|
||||
name_pl, name_ru, name_uk, name_en
|
||||
FROM learning_topics
|
||||
WHERE level_code = ANY($1::text[]) AND is_active = TRUE
|
||||
@@ -1611,6 +1630,7 @@ async def get_lessons_tree(
|
||||
topics_by_level.setdefault(t["level_code"], []).append({
|
||||
"topic_id": t["topic_id"],
|
||||
"order_number": t["order_number"],
|
||||
"track": t["track"] or "ru_uk", # 🔧 НОВОЕ
|
||||
"name_pl": t["name_pl"],
|
||||
"name_ru": t["name_ru"],
|
||||
"name_uk": t["name_uk"],
|
||||
@@ -1645,22 +1665,31 @@ async def create_topic(request: Request):
|
||||
🔧 НОВОЕ (02.10.2026): create_topic —
|
||||
создание новой темы.
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track —
|
||||
аудитория темы (pl / ru_uk / en). Включён в topic_id.
|
||||
|
||||
Тело:
|
||||
{
|
||||
"level_code": "A1",
|
||||
"track": "ru_uk", // опционально, по умолчанию 'ru_uk'
|
||||
"name_pl": "Powitania",
|
||||
"name_ru": "Приветствия",
|
||||
"name_uk": "Привітання",
|
||||
"name_en": "Greetings"
|
||||
}
|
||||
|
||||
topic_id генерируется автоматически: {level}_{slug(name_pl)}.
|
||||
topic_id генерируется автоматически:
|
||||
{level}_{track}_{slug(name_pl)}.
|
||||
Пример: a1_ru_uk_powitania, a1_pl_powitania, a1_en_powitania.
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
_require_admin(telegram_id)
|
||||
|
||||
body = await request.json()
|
||||
level_code = (body.get("level_code") or "").strip().upper()
|
||||
# 🔧 НОВОЕ (04.10.2026): track — аудитория темы.
|
||||
# 'pl' / 'ru_uk' / 'en'. По умолчанию 'ru_uk'.
|
||||
track = (body.get("track") or "ru_uk").strip().lower()
|
||||
name_pl = (body.get("name_pl") or "").strip()
|
||||
name_ru = (body.get("name_ru") or "").strip()
|
||||
name_uk = (body.get("name_uk") or "").strip()
|
||||
@@ -1668,12 +1697,14 @@ async def create_topic(request: Request):
|
||||
|
||||
if level_code not in LEVELS:
|
||||
raise HTTPException(400, f"Invalid level_code. Allowed: {LEVELS}")
|
||||
if track not in ("pl", "ru_uk", "en"):
|
||||
raise HTTPException(400, f"Invalid track. Allowed: pl, ru_uk, en")
|
||||
if not name_pl:
|
||||
raise HTTPException(400, "name_pl is required")
|
||||
if not name_ru:
|
||||
raise HTTPException(400, "name_ru is required")
|
||||
|
||||
# Генерим topic_id: a1_greetings
|
||||
# Генерим topic_id: a1_ru_uk_greetings
|
||||
import re as _re
|
||||
slug = name_pl.lower()
|
||||
# Транслитерация польских букв
|
||||
@@ -1687,7 +1718,11 @@ async def create_topic(request: Request):
|
||||
if not slug:
|
||||
raise HTTPException(400, "Cannot generate topic_id from name_pl")
|
||||
|
||||
topic_id = f"{level_code.lower()}_{slug[:50]}"
|
||||
# 🔧 НОВОЕ (04.10.2026): track_in_topic_id —
|
||||
# разные аудитории → разные topic_id, чтобы не было конфликтов.
|
||||
# Пример: a1_ru_uk_powitania, a1_pl_powitania, a1_en_powitania
|
||||
track_short = {"pl": "pl", "ru_uk": "ru_uk", "en": "en"}[track]
|
||||
topic_id = f"{level_code.lower()}_{track_short}_{slug[:40]}"
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
@@ -1706,19 +1741,20 @@ async def create_topic(request: Request):
|
||||
|
||||
await conn.execute("""
|
||||
INSERT INTO learning_topics
|
||||
(topic_id, level_code, order_number, name_pl, name_ru, name_uk, name_en, is_active, edited_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, TRUE, NOW())
|
||||
""", topic_id, level_code, next_order, name_pl, name_ru, name_uk, name_en)
|
||||
(topic_id, level_code, order_number, track, name_pl, name_ru, name_uk, name_en, is_active, edited_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, TRUE, NOW())
|
||||
""", topic_id, level_code, next_order, track, name_pl, name_ru, name_uk, name_en)
|
||||
|
||||
logger.info(
|
||||
f"[admin_content] topic created: '{topic_id}' in {level_code} "
|
||||
f"by admin {telegram_id}"
|
||||
f"(track={track}) by admin {telegram_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"topic_id": topic_id,
|
||||
"order_number": next_order,
|
||||
"track": track,
|
||||
}
|
||||
|
||||
|
||||
@@ -1744,6 +1780,7 @@ async def create_lesson(request: Request):
|
||||
"difficulty": 1,
|
||||
"hint_type": "first_letter" | null,
|
||||
"hint_value": "D" | null,
|
||||
"options_language": "pl" | "user",
|
||||
"options": [
|
||||
{"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...",
|
||||
"is_correct": true, "wrong_because": null},
|
||||
@@ -1873,6 +1910,11 @@ async def create_lesson(request: Request):
|
||||
if hint_value:
|
||||
hint_value = str(hint_value).strip() or None
|
||||
|
||||
# 🔧 НОВОЕ (04.10.2026): options_language
|
||||
options_language = (q.get("options_language") or "pl").strip().lower()
|
||||
if options_language not in ("pl", "user"):
|
||||
options_language = "pl"
|
||||
|
||||
questions.append({
|
||||
"question_type": q_type,
|
||||
"prompt_pl": prompt_pl,
|
||||
@@ -1883,6 +1925,7 @@ async def create_lesson(request: Request):
|
||||
"difficulty": difficulty,
|
||||
"hint_type": hint_type,
|
||||
"hint_value": hint_value,
|
||||
"options_language": options_language, # 🔧 НОВОЕ
|
||||
"options": options,
|
||||
})
|
||||
|
||||
@@ -1948,12 +1991,13 @@ async def create_lesson(request: Request):
|
||||
skill_tag, difficulty, prompt_pl, prompt_ru, prompt_uk, prompt_en,
|
||||
correct_answer, hint_type, hint_value, is_test_question, options_language, edited_at)
|
||||
VALUES ($1, $2, $3, 'lesson_practice', $4, $5, $6, $7, $8, $9, $10,
|
||||
$11, $12, $13, FALSE, 'pl', NOW())
|
||||
$11, $12, $13, FALSE, $14, NOW())
|
||||
""",
|
||||
question_id, lesson_id, topic_id, q["question_type"],
|
||||
skill_tag, q["difficulty"],
|
||||
q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"],
|
||||
q["correct_answer"], q["hint_type"], q["hint_value"],
|
||||
q["options_language"],
|
||||
)
|
||||
|
||||
for o in q["options"]:
|
||||
@@ -2340,6 +2384,7 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
|
||||
"difficulty": 1,
|
||||
"prompt_pl": "...", "prompt_ru": "...", "prompt_uk": "...", "prompt_en": "...",
|
||||
"hint_type": null, "hint_value": null,
|
||||
"options_language": "pl" | "user",
|
||||
"options": [
|
||||
{"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...",
|
||||
"is_correct": true, "wrong_because": null},
|
||||
@@ -2389,6 +2434,11 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
|
||||
if hint_value:
|
||||
hint_value = str(hint_value).strip() or None
|
||||
|
||||
# 🔧 НОВОЕ (04.10.2026): options_language
|
||||
options_language = (body.get("options_language") or "pl").strip().lower()
|
||||
if options_language not in ("pl", "user"):
|
||||
options_language = "pl"
|
||||
|
||||
# Валидация options
|
||||
options_raw = body.get("options") or []
|
||||
if not isinstance(options_raw, list) or len(options_raw) == 0:
|
||||
@@ -2464,7 +2514,7 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
|
||||
correct_answer, hint_type, hint_value,
|
||||
is_test_question, options_language, edited_at)
|
||||
VALUES ($1, $2, $3, 'lesson_practice', $4, $5, $6, $7, $8, $9, $10,
|
||||
$11, $12, $13, FALSE, 'pl', NOW())
|
||||
$11, $12, $13, FALSE, $14, NOW())
|
||||
""",
|
||||
question_id, lesson_id, topic_id, q_type,
|
||||
skill_tag, difficulty,
|
||||
@@ -2473,6 +2523,7 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
|
||||
(body.get("prompt_uk") or "").strip(),
|
||||
(body.get("prompt_en") or "").strip(),
|
||||
correct_answer, hint_type, hint_value,
|
||||
options_language,
|
||||
)
|
||||
|
||||
# INSERT options
|
||||
@@ -2497,4 +2548,74 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
|
||||
"status": "ok",
|
||||
"question_id": question_id,
|
||||
"order_number": next_n,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ============ LESSONS: DELETE TOPIC ============
|
||||
|
||||
@router.delete("/lessons/topic/{topic_id}")
|
||||
async def delete_topic(request: Request, topic_id: str):
|
||||
"""
|
||||
🔧 НОВОЕ (04.10.2026): delete_topic —
|
||||
удаляет тему со ВСЕМ содержимым (уроки, вопросы, опции, примеры).
|
||||
|
||||
Каскад:
|
||||
1. Опции вопросов темы
|
||||
2. Вопросы темы
|
||||
3. Примеры уроков темы
|
||||
4. Уроки темы
|
||||
5. Сама тема
|
||||
|
||||
Всё в одной транзакции — если упадёт — откат.
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
_require_admin(telegram_id)
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
# Проверка существования
|
||||
exists = await conn.fetchval(
|
||||
"SELECT 1 FROM learning_topics WHERE topic_id = $1", topic_id
|
||||
)
|
||||
if not exists:
|
||||
raise HTTPException(404, "Topic not found")
|
||||
|
||||
# 1. Опции вопросов темы
|
||||
await conn.execute("""
|
||||
DELETE FROM question_options
|
||||
WHERE question_id IN (
|
||||
SELECT question_id FROM learning_questions WHERE topic_id = $1
|
||||
)
|
||||
""", topic_id)
|
||||
|
||||
# 2. Вопросы темы
|
||||
await conn.execute(
|
||||
"DELETE FROM learning_questions WHERE topic_id = $1", topic_id
|
||||
)
|
||||
|
||||
# 3. Примеры уроков темы
|
||||
await conn.execute("""
|
||||
DELETE FROM lesson_examples
|
||||
WHERE lesson_id IN (
|
||||
SELECT lesson_id FROM learning_lessons WHERE topic_id = $1
|
||||
)
|
||||
""", topic_id)
|
||||
|
||||
# 4. Уроки темы
|
||||
await conn.execute(
|
||||
"DELETE FROM learning_lessons WHERE topic_id = $1", topic_id
|
||||
)
|
||||
|
||||
# 5. Сама тема
|
||||
await conn.execute(
|
||||
"DELETE FROM learning_topics WHERE topic_id = $1", topic_id
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[admin_content] topic deleted: '{topic_id}' "
|
||||
f"(with all lessons, questions, options, examples) "
|
||||
f"by admin {telegram_id}"
|
||||
)
|
||||
|
||||
return {"status": "ok", "topic_id": topic_id}
|
||||
+33
-4
@@ -444,12 +444,41 @@ async def get_learning_levels(request: Request):
|
||||
|
||||
@router.get("/topics")
|
||||
async def get_topics(request: Request, level: str = "A1"):
|
||||
"""Получить темы для уровня"""
|
||||
await require_auth(request)
|
||||
"""
|
||||
Получить темы для уровня.
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track_filter —
|
||||
фильтруем темы по языку юзера:
|
||||
- pl → track='pl'
|
||||
- ru/uk → track='ru_uk' (общий для славян)
|
||||
- en → track='en'
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
rows = await conn.fetch("SELECT * FROM learning_topics WHERE level_code = $1 AND is_active = TRUE ORDER BY order_number", level)
|
||||
return {"topics": [dict(row) for row in rows]}
|
||||
# Определяем track из app_language юзера
|
||||
user_lang = await conn.fetchval(
|
||||
"SELECT app_language FROM users WHERE telegram_id = $1",
|
||||
telegram_id,
|
||||
) or "ru"
|
||||
|
||||
if user_lang == "pl":
|
||||
track = "pl"
|
||||
elif user_lang == "en":
|
||||
track = "en"
|
||||
else:
|
||||
# ru, uk → общий track
|
||||
track = "ru_uk"
|
||||
|
||||
rows = await conn.fetch("""
|
||||
SELECT * FROM learning_topics
|
||||
WHERE level_code = $1
|
||||
AND is_active = TRUE
|
||||
AND track = $2
|
||||
ORDER BY order_number
|
||||
""", level, track)
|
||||
|
||||
return {"topics": [dict(row) for row in rows], "track": track}
|
||||
|
||||
|
||||
@router.get("/topics/{topic_id}")
|
||||
|
||||
+70
-36
@@ -6,6 +6,9 @@ Orchestrator — мозг чат-учителя.
|
||||
3. Иначе → следующий урок по порядку
|
||||
|
||||
Никакого AI — только детерминированная логика.
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track_filter —
|
||||
учитель уважает аудиторию юзера (pl / ru_uk / en).
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Dict, Any
|
||||
@@ -16,7 +19,7 @@ logger = logging.getLogger(__name__)
|
||||
async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Выбирает следующий урок для пользователя.
|
||||
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"type": "new" | "review" | "test",
|
||||
@@ -24,13 +27,34 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
"reason": str,
|
||||
"skill_tag": str | None
|
||||
}
|
||||
|
||||
🔧 ОБНОВЛЕНО (04.10.2026): track_filter —
|
||||
учитель уважает аудиторию юзера:
|
||||
- pl → track='pl'
|
||||
- ru/uk → track='ru_uk'
|
||||
- en → track='en'
|
||||
Все SQL-запросы фильтруют по track, чтобы не подсовывать
|
||||
RU/UK-уроки польскому или английскому юзеру.
|
||||
"""
|
||||
|
||||
|
||||
# Получаем текущий уровень пользователя
|
||||
current_level = await conn.fetchval("""
|
||||
SELECT current_level FROM users WHERE telegram_id = $1
|
||||
""", user_id) or "A1"
|
||||
|
||||
|
||||
# 🔧 НОВОЕ (04.10.2026): track_filter —
|
||||
# определяем track по app_language юзера.
|
||||
user_lang = await conn.fetchval("""
|
||||
SELECT app_language FROM users WHERE telegram_id = $1
|
||||
""", user_id) or "ru"
|
||||
|
||||
if user_lang == "pl":
|
||||
track = "pl"
|
||||
elif user_lang == "en":
|
||||
track = "en"
|
||||
else:
|
||||
track = "ru_uk"
|
||||
|
||||
# ============ ШАГ 1: Проверяем retention_status ============
|
||||
# Если есть навыки, которые давно не повторяли — повторяем их
|
||||
overdue_skill = await conn.fetchrow("""
|
||||
@@ -42,26 +66,30 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
ORDER BY days_since_last_attempt DESC
|
||||
LIMIT 1
|
||||
""", user_id)
|
||||
|
||||
|
||||
if overdue_skill:
|
||||
# 🔧 НОВОЕ (04.10.2026): track_filter_lesson — ищем урок по skill_tag
|
||||
# ТОЛЬКО в темах нужного track.
|
||||
lesson = await conn.fetchrow("""
|
||||
SELECT l.lesson_id, l.topic_id, l.skill_tag, l.title_pl, l.title_ru, l.title_uk, l.title_en
|
||||
FROM learning_lessons l
|
||||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||||
WHERE l.skill_tag = $1
|
||||
AND l.is_active = TRUE
|
||||
AND t.track = $2
|
||||
ORDER BY l.order_number
|
||||
LIMIT 1
|
||||
""", overdue_skill["skill_tag"])
|
||||
|
||||
""", overdue_skill["skill_tag"], track)
|
||||
|
||||
if lesson:
|
||||
logger.info(f"Orchestrator: review (overdue) for user={user_id}, skill={overdue_skill['skill_tag']}")
|
||||
logger.info(f"Orchestrator: review (overdue) for user={user_id}, skill={overdue_skill['skill_tag']}, track={track}")
|
||||
return {
|
||||
"type": "review",
|
||||
"lesson": dict(lesson),
|
||||
"reason": "overdue",
|
||||
"skill_tag": overdue_skill["skill_tag"],
|
||||
}
|
||||
|
||||
|
||||
# ============ ШАГ 2: Проверяем mastery < 75 ============
|
||||
weak_skill = await conn.fetchrow("""
|
||||
SELECT skill_tag, mastery_score, repeated_error_count, trend
|
||||
@@ -72,50 +100,55 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
ORDER BY mastery_score ASC
|
||||
LIMIT 1
|
||||
""", user_id)
|
||||
|
||||
|
||||
if weak_skill:
|
||||
# 🔧 НОВОЕ (04.10.2026): track_filter_lesson
|
||||
lesson = await conn.fetchrow("""
|
||||
SELECT l.lesson_id, l.topic_id, l.skill_tag, l.title_pl, l.title_ru, l.title_uk, l.title_en
|
||||
FROM learning_lessons l
|
||||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||||
WHERE l.skill_tag = $1
|
||||
AND l.is_active = TRUE
|
||||
AND t.track = $2
|
||||
ORDER BY l.order_number
|
||||
LIMIT 1
|
||||
""", weak_skill["skill_tag"])
|
||||
|
||||
""", weak_skill["skill_tag"], track)
|
||||
|
||||
if lesson:
|
||||
logger.info(f"Orchestrator: review (weak) for user={user_id}, skill={weak_skill['skill_tag']}, mastery={weak_skill['mastery_score']}")
|
||||
logger.info(f"Orchestrator: review (weak) for user={user_id}, skill={weak_skill['skill_tag']}, mastery={weak_skill['mastery_score']}, track={track}")
|
||||
return {
|
||||
"type": "review",
|
||||
"lesson": dict(lesson),
|
||||
"reason": "weak_mastery",
|
||||
"skill_tag": weak_skill["skill_tag"],
|
||||
}
|
||||
|
||||
|
||||
# ============ ШАГ 3: Проверяем, нужно ли пройти тест темы ============
|
||||
# Если пользователь завершил все уроки темы, но не прошёл тест
|
||||
# 🔧 НОВОЕ (04.10.2026): track_filter_test — только темы нужного track.
|
||||
topic_for_test = await conn.fetchrow("""
|
||||
SELECT tp.topic_id, tp.lessons_total, tp.lessons_completed, tp.test_completed
|
||||
FROM user_topic_progress tp
|
||||
JOIN learning_topics t ON tp.topic_id = t.topic_id
|
||||
WHERE tp.user_id = $1
|
||||
AND tp.lessons_completed >= tp.lessons_total
|
||||
AND tp.lessons_total > 0
|
||||
AND tp.test_completed = FALSE
|
||||
AND t.track = $2
|
||||
ORDER BY tp.topic_id
|
||||
LIMIT 1
|
||||
""", user_id)
|
||||
|
||||
""", user_id, track)
|
||||
|
||||
if topic_for_test:
|
||||
logger.info(f"Orchestrator: test for user={user_id}, topic={topic_for_test['topic_id']}")
|
||||
logger.info(f"Orchestrator: test for user={user_id}, topic={topic_for_test['topic_id']}, track={track}")
|
||||
return {
|
||||
"type": "test",
|
||||
"lesson": None,
|
||||
"reason": "topic_completed_no_test",
|
||||
"topic_id": topic_for_test["topic_id"],
|
||||
}
|
||||
|
||||
|
||||
# ============ ШАГ 4: Следующий урок по порядку ============
|
||||
# Находим первый непройденный урок в текущем уровне
|
||||
# 🔧 НОВОЕ (04.10.2026): track_filter_next — только уроки нужного track.
|
||||
next_lesson = await conn.fetchrow("""
|
||||
SELECT l.lesson_id, l.topic_id, l.skill_tag, l.title_pl, l.title_ru, l.title_uk, l.title_en,
|
||||
t.topic_id as topic_id, t.order_number as topic_order
|
||||
@@ -123,25 +156,26 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||||
WHERE t.level_code = $1
|
||||
AND l.is_active = TRUE
|
||||
AND t.track = $3
|
||||
AND l.lesson_id NOT IN (
|
||||
SELECT lesson_id FROM user_lesson_progress
|
||||
WHERE user_id = $2 AND completed = TRUE
|
||||
)
|
||||
ORDER BY t.order_number, l.order_number
|
||||
LIMIT 1
|
||||
""", current_level, user_id)
|
||||
|
||||
""", current_level, user_id, track)
|
||||
|
||||
if next_lesson:
|
||||
logger.info(f"Orchestrator: new lesson for user={user_id}, lesson={next_lesson['lesson_id']}")
|
||||
logger.info(f"Orchestrator: new lesson for user={user_id}, lesson={next_lesson['lesson_id']}, track={track}")
|
||||
return {
|
||||
"type": "new",
|
||||
"lesson": dict(next_lesson),
|
||||
"reason": "next_in_order",
|
||||
"skill_tag": next_lesson["skill_tag"],
|
||||
}
|
||||
|
||||
|
||||
# ============ ШАГ 5: Всё пройдено ============
|
||||
logger.info(f"Orchestrator: all completed for user={user_id}")
|
||||
logger.info(f"Orchestrator: all completed for user={user_id}, track={track}")
|
||||
return {
|
||||
"type": "completed",
|
||||
"lesson": None,
|
||||
@@ -152,18 +186,18 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
|
||||
|
||||
async def get_lesson_by_id(conn, lesson_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""Получает урок по ID со всеми данными: объяснение, примеры, вопросы."""
|
||||
|
||||
|
||||
lesson = await conn.fetchrow("""
|
||||
SELECT * FROM learning_lessons WHERE lesson_id = $1 AND is_active = TRUE
|
||||
""", lesson_id)
|
||||
|
||||
|
||||
if not lesson:
|
||||
return None
|
||||
|
||||
|
||||
examples = await conn.fetch("""
|
||||
SELECT * FROM lesson_examples WHERE lesson_id = $1 ORDER BY order_number
|
||||
""", lesson_id)
|
||||
|
||||
|
||||
questions = await conn.fetch("""
|
||||
SELECT * FROM learning_questions
|
||||
WHERE lesson_id = $1 AND is_test_question = FALSE
|
||||
@@ -200,7 +234,7 @@ async def get_lesson_by_id(conn, lesson_id: str) -> Optional[Dict[str, Any]]:
|
||||
|
||||
async def get_lesson_questions(conn, lesson_id: str) -> list:
|
||||
"""Получает только вопросы урока (без объяснения)."""
|
||||
|
||||
|
||||
questions = await conn.fetch("""
|
||||
SELECT * FROM learning_questions
|
||||
WHERE lesson_id = $1 AND is_test_question = FALSE
|
||||
@@ -231,7 +265,7 @@ async def get_lesson_questions(conn, lesson_id: str) -> list:
|
||||
|
||||
async def get_test_questions(conn, topic_id: str) -> list:
|
||||
"""Получает вопросы финального теста по теме."""
|
||||
|
||||
|
||||
questions = await conn.fetch("""
|
||||
SELECT * FROM learning_questions
|
||||
WHERE topic_id = $1 AND is_test_question = TRUE
|
||||
@@ -262,7 +296,7 @@ async def get_test_questions(conn, topic_id: str) -> list:
|
||||
|
||||
async def get_random_reaction(conn, reaction_type: str, lang: str) -> str:
|
||||
"""Получает случайную реакцию из банка по типу."""
|
||||
|
||||
|
||||
row = await conn.fetchrow("""
|
||||
SELECT text_pl, text_ru, text_uk, text_en
|
||||
FROM teacher_reactions
|
||||
@@ -270,7 +304,7 @@ async def get_random_reaction(conn, reaction_type: str, lang: str) -> str:
|
||||
ORDER BY RANDOM()
|
||||
LIMIT 1
|
||||
""", reaction_type)
|
||||
|
||||
|
||||
if not row:
|
||||
# Запасные реакции, если таблица пуста
|
||||
fallbacks = {
|
||||
@@ -294,22 +328,22 @@ async def get_random_reaction(conn, reaction_type: str, lang: str) -> str:
|
||||
},
|
||||
}
|
||||
return fallbacks.get(reaction_type, {}).get(lang, "OK")
|
||||
|
||||
|
||||
field = f"text_{lang}"
|
||||
return row.get(field) or row.get("text_en") or "OK"
|
||||
|
||||
|
||||
async def get_wrong_because_explanation(conn, wrong_because: str, lang: str) -> str:
|
||||
"""Получает объяснение ошибки по тегу wrong_because."""
|
||||
|
||||
|
||||
row = await conn.fetchrow("""
|
||||
SELECT explanation_pl, explanation_ru, explanation_uk, explanation_en
|
||||
FROM wrong_because_explanations
|
||||
WHERE wrong_because = $1
|
||||
""", wrong_because)
|
||||
|
||||
|
||||
if not row:
|
||||
return ""
|
||||
|
||||
|
||||
field = f"explanation_{lang}"
|
||||
return row.get(field) or row.get("explanation_en") or ""
|
||||
Reference in New Issue
Block a user