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
+146 -25
View File
@@ -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}