feat: track + options_language + test generator + повторы уроков

This commit is contained in:
2026-10-04 16:13:59 +00:00
parent 80b7f6b419
commit a730ef87f5
4 changed files with 275 additions and 65 deletions
+26
View File
@@ -342,12 +342,17 @@ async def init_db():
""") """)
# ============ learning_topics ============ # ============ learning_topics ============
# 🔧 ОБНОВЛЕНО (04.10.2026): track — разделение аудиторий.
# 'pl' — для поляков (учёба на польском)
# 'ru_uk' — для славян (RU/UK ↔ PL, ОБЩИЙ track)
# 'en' — для англоязычных
await conn.execute(""" await conn.execute("""
CREATE TABLE IF NOT EXISTS learning_topics ( CREATE TABLE IF NOT EXISTS learning_topics (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
topic_id VARCHAR(100) UNIQUE NOT NULL, topic_id VARCHAR(100) UNIQUE NOT NULL,
level_code VARCHAR(10) NOT NULL, level_code VARCHAR(10) NOT NULL,
order_number INT NOT NULL, order_number INT NOT NULL,
track VARCHAR(10) NOT NULL DEFAULT 'ru_uk', -- 🔧 НОВОЕ
name_pl TEXT NOT NULL, name_pl TEXT NOT NULL,
name_ru TEXT NOT NULL, name_ru TEXT NOT NULL,
name_uk TEXT NOT NULL, name_uk TEXT NOT NULL,
@@ -361,6 +366,27 @@ async def init_db():
) )
""") """)
# 🔧 НОВОЕ (04.10.2026): track_auto_migration —
# для существующих БД добавляем колонку, если её нет.
col_exists = await conn.fetchval("""
SELECT 1 FROM information_schema.columns
WHERE table_name = 'learning_topics' AND column_name = 'track'
""")
if not col_exists:
await conn.execute("""
ALTER TABLE learning_topics
ADD COLUMN track VARCHAR(10) NOT NULL DEFAULT 'ru_uk'
""")
logger.info("Added track column to learning_topics")
# Backfill: все существующие темы → 'ru_uk' (славянский track)
await conn.execute("""
UPDATE learning_topics
SET track = 'ru_uk'
WHERE track IS NULL OR track = ''
""")
logger.info("Backfilled track='ru_uk' for existing topics")
# ============ learning_lessons ============ # ============ learning_lessons ============
await conn.execute(""" await conn.execute("""
CREATE TABLE IF NOT EXISTS learning_lessons ( CREATE TABLE IF NOT EXISTS learning_lessons (
+145 -24
View File
@@ -57,6 +57,18 @@ Admin Content Router — контент-менеджер для редактир
🔧 НОВОЕ (02.10.2026): POST /lessons/lesson/{lesson_id}/add-question — 🔧 НОВОЕ (02.10.2026): POST /lessons/lesson/{lesson_id}/add-question —
добавление ОДНОГО нового вопроса в существующий урок (edit-режим). добавление ОДНОГО нового вопроса в существующий урок (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 logging
import re import re
@@ -1183,6 +1195,7 @@ async def update_lesson(request: Request, lesson_id: str):
"prompt_pl": "...", "prompt_en": "...", "prompt_ru": "...", "prompt_uk": "...", "prompt_pl": "...", "prompt_en": "...", "prompt_ru": "...", "prompt_uk": "...",
"hint_type": "first_letter" | null, "hint_type": "first_letter" | null,
"hint_value": "j" | null, "hint_value": "j" | null,
"options_language": "pl" | "user",
"options": [ "options": [
{"text_pl": "...", "text_en": "...", "text_ru": "...", "text_uk": "...", {"text_pl": "...", "text_en": "...", "text_ru": "...", "text_uk": "...",
"is_correct": true, "wrong_because": null}, "is_correct": true, "wrong_because": null},
@@ -1312,6 +1325,14 @@ async def update_lesson(request: Request, lesson_id: str):
if hint_value: if hint_value:
hint_value = str(hint_value).strip() or None 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({ questions.append({
"question_id": question_id, "question_id": question_id,
"prompt_pl": prompt_pl, "prompt_pl": prompt_pl,
@@ -1321,6 +1342,7 @@ async def update_lesson(request: Request, lesson_id: str):
"correct_answer": correct_answer, "correct_answer": correct_answer,
"hint_type": hint_type, "hint_type": hint_type,
"hint_value": hint_value, "hint_value": hint_value,
"options_language": options_language, # 🔧 НОВОЕ
"options": options, "options": options,
}) })
@@ -1398,11 +1420,13 @@ async def update_lesson(request: Request, lesson_id: str):
correct_answer = $5, correct_answer = $5,
hint_type = $6, hint_type = $6,
hint_value = $7, hint_value = $7,
options_language = $8,
edited_at = NOW() edited_at = NOW()
WHERE question_id = $8 WHERE question_id = $9
""", """,
q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"], q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"],
q["correct_answer"], q["hint_type"], q["hint_value"], q["correct_answer"], q["hint_type"], q["hint_value"],
q["options_language"],
q["question_id"], q["question_id"],
) )
@@ -1484,6 +1508,9 @@ async def get_lessons_tree(
🔧 НОВОЕ (02.10.2026): lessons_tree — 🔧 НОВОЕ (02.10.2026): lessons_tree —
дерево: уровни → темы → уроки. Один запрос вместо N+1. дерево: уровни → темы → уроки. Один запрос вместо N+1.
🔧 ОБНОВЛЕНО (04.10.2026): track_include —
каждая тема теперь содержит поле track ('pl' / 'ru_uk' / 'en').
Возвращает: Возвращает:
{ {
"levels": [ "levels": [
@@ -1495,23 +1522,14 @@ async def get_lessons_tree(
"lessons_count": 20, "lessons_count": 20,
"topics": [ "topics": [
{ {
"topic_id": "a1_greetings", "topic_id": "a1_ru_uk_greetings",
"name_ru": "Приветствия", "name_ru": "Приветствия",
"name_pl": "Powitania", "name_pl": "Powitania",
"order_number": 1, "order_number": 1,
"track": "ru_uk",
"lessons_count": 10, "lessons_count": 10,
"test_questions_count": 0, "test_questions_count": 0,
"lessons": [ "lessons": [...]
{
"lesson_id": "a1_greetings_l01",
"order_number": 1,
"skill_tag": "podstawowe_powitania",
"title_ru": "...",
"title_pl": "...",
"questions_count": 3,
"is_active": true
}
]
} }
] ]
} }
@@ -1536,9 +1554,10 @@ async def get_lessons_tree(
level_codes = [l["code"] for l in levels] level_codes = [l["code"] for l in levels]
# Темы # 🔧 ОБНОВЛЕНО (04.10.2026): track_include —
# включаем track в дерево, чтобы фронт мог показать бейджи + фильтровать.
topics = await conn.fetch(""" 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 name_pl, name_ru, name_uk, name_en
FROM learning_topics FROM learning_topics
WHERE level_code = ANY($1::text[]) AND is_active = TRUE 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({ topics_by_level.setdefault(t["level_code"], []).append({
"topic_id": t["topic_id"], "topic_id": t["topic_id"],
"order_number": t["order_number"], "order_number": t["order_number"],
"track": t["track"] or "ru_uk", # 🔧 НОВОЕ
"name_pl": t["name_pl"], "name_pl": t["name_pl"],
"name_ru": t["name_ru"], "name_ru": t["name_ru"],
"name_uk": t["name_uk"], "name_uk": t["name_uk"],
@@ -1645,22 +1665,31 @@ async def create_topic(request: Request):
🔧 НОВОЕ (02.10.2026): create_topic — 🔧 НОВОЕ (02.10.2026): create_topic —
создание новой темы. создание новой темы.
🔧 ОБНОВЛЕНО (04.10.2026): track —
аудитория темы (pl / ru_uk / en). Включён в topic_id.
Тело: Тело:
{ {
"level_code": "A1", "level_code": "A1",
"track": "ru_uk", // опционально, по умолчанию 'ru_uk'
"name_pl": "Powitania", "name_pl": "Powitania",
"name_ru": "Приветствия", "name_ru": "Приветствия",
"name_uk": "Привітання", "name_uk": "Привітання",
"name_en": "Greetings" "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) telegram_id, _ = await require_auth(request)
_require_admin(telegram_id) _require_admin(telegram_id)
body = await request.json() body = await request.json()
level_code = (body.get("level_code") or "").strip().upper() 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_pl = (body.get("name_pl") or "").strip()
name_ru = (body.get("name_ru") or "").strip() name_ru = (body.get("name_ru") or "").strip()
name_uk = (body.get("name_uk") 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: if level_code not in LEVELS:
raise HTTPException(400, f"Invalid level_code. Allowed: {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: if not name_pl:
raise HTTPException(400, "name_pl is required") raise HTTPException(400, "name_pl is required")
if not name_ru: if not name_ru:
raise HTTPException(400, "name_ru is required") raise HTTPException(400, "name_ru is required")
# Генерим topic_id: a1_greetings # Генерим topic_id: a1_ru_uk_greetings
import re as _re import re as _re
slug = name_pl.lower() slug = name_pl.lower()
# Транслитерация польских букв # Транслитерация польских букв
@@ -1687,7 +1718,11 @@ async def create_topic(request: Request):
if not slug: if not slug:
raise HTTPException(400, "Cannot generate topic_id from name_pl") 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() pool = await get_pool()
async with pool.acquire() as conn: async with pool.acquire() as conn:
@@ -1706,19 +1741,20 @@ async def create_topic(request: Request):
await conn.execute(""" await conn.execute("""
INSERT INTO learning_topics INSERT INTO learning_topics
(topic_id, level_code, order_number, name_pl, name_ru, name_uk, name_en, is_active, edited_at) (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, TRUE, NOW()) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, TRUE, NOW())
""", topic_id, level_code, next_order, name_pl, name_ru, name_uk, name_en) """, topic_id, level_code, next_order, track, name_pl, name_ru, name_uk, name_en)
logger.info( logger.info(
f"[admin_content] topic created: '{topic_id}' in {level_code} " f"[admin_content] topic created: '{topic_id}' in {level_code} "
f"by admin {telegram_id}" f"(track={track}) by admin {telegram_id}"
) )
return { return {
"status": "ok", "status": "ok",
"topic_id": topic_id, "topic_id": topic_id,
"order_number": next_order, "order_number": next_order,
"track": track,
} }
@@ -1744,6 +1780,7 @@ async def create_lesson(request: Request):
"difficulty": 1, "difficulty": 1,
"hint_type": "first_letter" | null, "hint_type": "first_letter" | null,
"hint_value": "D" | null, "hint_value": "D" | null,
"options_language": "pl" | "user",
"options": [ "options": [
{"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...", {"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...",
"is_correct": true, "wrong_because": null}, "is_correct": true, "wrong_because": null},
@@ -1873,6 +1910,11 @@ async def create_lesson(request: Request):
if hint_value: if hint_value:
hint_value = str(hint_value).strip() or None 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({ questions.append({
"question_type": q_type, "question_type": q_type,
"prompt_pl": prompt_pl, "prompt_pl": prompt_pl,
@@ -1883,6 +1925,7 @@ async def create_lesson(request: Request):
"difficulty": difficulty, "difficulty": difficulty,
"hint_type": hint_type, "hint_type": hint_type,
"hint_value": hint_value, "hint_value": hint_value,
"options_language": options_language, # 🔧 НОВОЕ
"options": options, "options": options,
}) })
@@ -1948,12 +1991,13 @@ async def create_lesson(request: Request):
skill_tag, difficulty, prompt_pl, prompt_ru, prompt_uk, prompt_en, skill_tag, difficulty, prompt_pl, prompt_ru, prompt_uk, prompt_en,
correct_answer, hint_type, hint_value, is_test_question, options_language, edited_at) 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, 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"], question_id, lesson_id, topic_id, q["question_type"],
skill_tag, q["difficulty"], skill_tag, q["difficulty"],
q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"], q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"],
q["correct_answer"], q["hint_type"], q["hint_value"], q["correct_answer"], q["hint_type"], q["hint_value"],
q["options_language"],
) )
for o in q["options"]: for o in q["options"]:
@@ -2340,6 +2384,7 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
"difficulty": 1, "difficulty": 1,
"prompt_pl": "...", "prompt_ru": "...", "prompt_uk": "...", "prompt_en": "...", "prompt_pl": "...", "prompt_ru": "...", "prompt_uk": "...", "prompt_en": "...",
"hint_type": null, "hint_value": null, "hint_type": null, "hint_value": null,
"options_language": "pl" | "user",
"options": [ "options": [
{"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...", {"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "...",
"is_correct": true, "wrong_because": null}, "is_correct": true, "wrong_because": null},
@@ -2389,6 +2434,11 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
if hint_value: if hint_value:
hint_value = str(hint_value).strip() or None 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
options_raw = body.get("options") or [] options_raw = body.get("options") or []
if not isinstance(options_raw, list) or len(options_raw) == 0: 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, correct_answer, hint_type, hint_value,
is_test_question, options_language, edited_at) is_test_question, options_language, edited_at)
VALUES ($1, $2, $3, 'lesson_practice', $4, $5, $6, $7, $8, $9, $10, 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, question_id, lesson_id, topic_id, q_type,
skill_tag, difficulty, 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_uk") or "").strip(),
(body.get("prompt_en") or "").strip(), (body.get("prompt_en") or "").strip(),
correct_answer, hint_type, hint_value, correct_answer, hint_type, hint_value,
options_language,
) )
# INSERT options # INSERT options
@@ -2498,3 +2549,73 @@ async def add_question_to_lesson(request: Request, lesson_id: str):
"question_id": question_id, "question_id": question_id,
"order_number": next_n, "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
View File
@@ -444,12 +444,41 @@ async def get_learning_levels(request: Request):
@router.get("/topics") @router.get("/topics")
async def get_topics(request: Request, level: str = "A1"): 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() pool = await get_pool()
async with pool.acquire() as conn: 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) # Определяем track из app_language юзера
return {"topics": [dict(row) for row in rows]} 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}") @router.get("/topics/{topic_id}")
+45 -11
View File
@@ -6,6 +6,9 @@ Orchestrator — мозг чат-учителя.
3. Иначе → следующий урок по порядку 3. Иначе → следующий урок по порядку
Никакого AI — только детерминированная логика. Никакого AI — только детерминированная логика.
🔧 ОБНОВЛЕНО (04.10.2026): track_filter —
учитель уважает аудиторию юзера (pl / ru_uk / en).
""" """
import logging import logging
from typing import Optional, Dict, Any from typing import Optional, Dict, Any
@@ -24,6 +27,14 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
"reason": str, "reason": str,
"skill_tag": str | None "skill_tag": str | None
} }
🔧 ОБНОВЛЕНО (04.10.2026): track_filter —
учитель уважает аудиторию юзера:
- pl → track='pl'
- ru/uk → track='ru_uk'
- en → track='en'
Все SQL-запросы фильтруют по track, чтобы не подсовывать
RU/UK-уроки польскому или английскому юзеру.
""" """
# Получаем текущий уровень пользователя # Получаем текущий уровень пользователя
@@ -31,6 +42,19 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
SELECT current_level FROM users WHERE telegram_id = $1 SELECT current_level FROM users WHERE telegram_id = $1
""", user_id) or "A1" """, 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 ============ # ============ ШАГ 1: Проверяем retention_status ============
# Если есть навыки, которые давно не повторяли — повторяем их # Если есть навыки, которые давно не повторяли — повторяем их
overdue_skill = await conn.fetchrow(""" overdue_skill = await conn.fetchrow("""
@@ -44,17 +68,21 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
""", user_id) """, user_id)
if overdue_skill: if overdue_skill:
# 🔧 НОВОЕ (04.10.2026): track_filter_lesson — ищем урок по skill_tag
# ТОЛЬКО в темах нужного track.
lesson = await conn.fetchrow(""" 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 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 FROM learning_lessons l
JOIN learning_topics t ON l.topic_id = t.topic_id
WHERE l.skill_tag = $1 WHERE l.skill_tag = $1
AND l.is_active = TRUE AND l.is_active = TRUE
AND t.track = $2
ORDER BY l.order_number ORDER BY l.order_number
LIMIT 1 LIMIT 1
""", overdue_skill["skill_tag"]) """, overdue_skill["skill_tag"], track)
if lesson: 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 { return {
"type": "review", "type": "review",
"lesson": dict(lesson), "lesson": dict(lesson),
@@ -74,17 +102,20 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
""", user_id) """, user_id)
if weak_skill: if weak_skill:
# 🔧 НОВОЕ (04.10.2026): track_filter_lesson
lesson = await conn.fetchrow(""" 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 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 FROM learning_lessons l
JOIN learning_topics t ON l.topic_id = t.topic_id
WHERE l.skill_tag = $1 WHERE l.skill_tag = $1
AND l.is_active = TRUE AND l.is_active = TRUE
AND t.track = $2
ORDER BY l.order_number ORDER BY l.order_number
LIMIT 1 LIMIT 1
""", weak_skill["skill_tag"]) """, weak_skill["skill_tag"], track)
if lesson: 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 { return {
"type": "review", "type": "review",
"lesson": dict(lesson), "lesson": dict(lesson),
@@ -93,20 +124,22 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
} }
# ============ ШАГ 3: Проверяем, нужно ли пройти тест темы ============ # ============ ШАГ 3: Проверяем, нужно ли пройти тест темы ============
# Если пользователь завершил все уроки темы, но не прошёл тест # 🔧 НОВОЕ (04.10.2026): track_filter_test — только темы нужного track.
topic_for_test = await conn.fetchrow(""" topic_for_test = await conn.fetchrow("""
SELECT tp.topic_id, tp.lessons_total, tp.lessons_completed, tp.test_completed SELECT tp.topic_id, tp.lessons_total, tp.lessons_completed, tp.test_completed
FROM user_topic_progress tp FROM user_topic_progress tp
JOIN learning_topics t ON tp.topic_id = t.topic_id
WHERE tp.user_id = $1 WHERE tp.user_id = $1
AND tp.lessons_completed >= tp.lessons_total AND tp.lessons_completed >= tp.lessons_total
AND tp.lessons_total > 0 AND tp.lessons_total > 0
AND tp.test_completed = FALSE AND tp.test_completed = FALSE
AND t.track = $2
ORDER BY tp.topic_id ORDER BY tp.topic_id
LIMIT 1 LIMIT 1
""", user_id) """, user_id, track)
if topic_for_test: 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 { return {
"type": "test", "type": "test",
"lesson": None, "lesson": None,
@@ -115,7 +148,7 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
} }
# ============ ШАГ 4: Следующий урок по порядку ============ # ============ ШАГ 4: Следующий урок по порядку ============
# Находим первый непройденный урок в текущем уровне # 🔧 НОВОЕ (04.10.2026): track_filter_next — только уроки нужного track.
next_lesson = await conn.fetchrow(""" 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, 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 t.topic_id as topic_id, t.order_number as topic_order
@@ -123,16 +156,17 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
JOIN learning_topics t ON l.topic_id = t.topic_id JOIN learning_topics t ON l.topic_id = t.topic_id
WHERE t.level_code = $1 WHERE t.level_code = $1
AND l.is_active = TRUE AND l.is_active = TRUE
AND t.track = $3
AND l.lesson_id NOT IN ( AND l.lesson_id NOT IN (
SELECT lesson_id FROM user_lesson_progress SELECT lesson_id FROM user_lesson_progress
WHERE user_id = $2 AND completed = TRUE WHERE user_id = $2 AND completed = TRUE
) )
ORDER BY t.order_number, l.order_number ORDER BY t.order_number, l.order_number
LIMIT 1 LIMIT 1
""", current_level, user_id) """, current_level, user_id, track)
if next_lesson: 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 { return {
"type": "new", "type": "new",
"lesson": dict(next_lesson), "lesson": dict(next_lesson),
@@ -141,7 +175,7 @@ async def get_next_lesson(conn, user_id: int) -> Dict[str, Any]:
} }
# ============ ШАГ 5: Всё пройдено ============ # ============ ШАГ 5: Всё пройдено ============
logger.info(f"Orchestrator: all completed for user={user_id}") logger.info(f"Orchestrator: all completed for user={user_id}, track={track}")
return { return {
"type": "completed", "type": "completed",
"lesson": None, "lesson": None,