- 11 файлов, 16 unused imports удалено - pip 24.0 → 26.2.1, urllib3 2.7.0 → 2.8.0 (CVE fix) - pip-audit: 0 vulnerabilities - Логика не затронута, только imports - Проверено: systemctl restart OK, /health 200
2620 lines
102 KiB
Python
2620 lines
102 KiB
Python
"""
|
||
Admin Content Router — контент-менеджер для редактирования уроков, слов и текстов.
|
||
|
||
Доступ: только для ADMIN_IDS.
|
||
Логика: препод (ты) правит контент через дашборд, без захода в код.
|
||
|
||
Разделы:
|
||
- GET /admin/content/summary — сводка по уровням
|
||
- GET /admin/content/words/levels — уровни слов (счётчики)
|
||
- GET /admin/content/words/level/{level} — список слов уровня
|
||
- GET /admin/content/words/word/{word_id} — одно слово
|
||
- PUT /admin/content/words/word/{word_id} — обновить слово
|
||
- POST /admin/content/words/level/{level} — добавить слово
|
||
- GET /admin/content/texts/levels — уровни текстов
|
||
- GET /admin/content/texts/level/{level} — список текстов
|
||
- GET /admin/content/texts/text/{text_id} — один текст
|
||
- PUT /admin/content/texts/text/{text_id} — обновить текст
|
||
- DELETE /admin/content/texts/text/{text_id} — удалить текст
|
||
- POST /admin/content/texts/level/{level} — добавить текст
|
||
- GET /admin/content/texts/all — все тексты (для редактора)
|
||
- GET /admin/content/lessons/levels — уровни уроков (счётчики тем)
|
||
- GET /admin/content/lessons/level/{level}/topics — темы уровня
|
||
- GET /admin/content/lessons/topic/{topic_id} — тема + уроки + тест
|
||
- GET /admin/content/lessons/lesson/{lesson_id} — урок целиком (WYSIWYG)
|
||
- PUT /admin/content/lessons/lesson/{lesson_id} — сохранить урок (Вариант B)
|
||
- GET /admin/content/wrong-because — справочник wrong_because
|
||
|
||
🔧 ФИКС (19.09.2026): в words-эндпоинтах фильтруем только строки с level_id IS NULL.
|
||
Причина: в level_words хранятся ДВЕ категории строк:
|
||
1. Слова уровня для Word Quiz / Bubble Words → level_id IS NULL.
|
||
2. Привязки слов к игровым уровням Филвордов → level_id != NULL.
|
||
В дашборде преподу нужны только "чистые" слова уровня (level_id IS NULL).
|
||
Строки с level_id != NULL используются игрой и остаются нетронутыми.
|
||
При обновлении слова (PUT) — обновляем ВСЕ строки с этим (level, word_pl),
|
||
чтобы Филворды получили актуальный перевод.
|
||
|
||
🔧 НОВОЕ (19.09.2026, вечер): раздел «Уроки» — 6 эндпоинтов для LessonsEditor.
|
||
- Уровни → Темы → Уроки (иерархия как в словах/текстах).
|
||
- WYSIWYG-модалка редактирует: title, objective, explanation, examples, questions, options.
|
||
- Сохранение урока целиком (Вариант B) — одна транзакция.
|
||
- option_key генерируется бэкендом: A, B, C, D... по порядку массива.
|
||
- correct_answer в learning_questions = option_key того варианта, где is_correct=true.
|
||
- test_order пересчитывается 1..N по порядку для теста темы (is_test_question=TRUE).
|
||
- level_code НЕ трогаем — он вычисляется через topic_id → learning_topics.level_code.
|
||
|
||
🔧 ФИКС (30.09.2026): global_duplicate_warning в create_text —
|
||
проверяем все уровни на дубликат sentence_pl. force=true пропускает проверку.
|
||
|
||
🔧 НОВОЕ (30.09.2026): DELETE /admin/content/texts/text/{text_id} —
|
||
удаление текста из редактора.
|
||
|
||
🔧 ОБНОВЛЕНО (30.09.2026): /texts/all — пагинация + total.
|
||
|
||
🔧 НОВОЕ (02.10.2026): 6 эндпоинтов для LessonsEditor v2 —
|
||
дерево, создание темы, создание урока, удаление урока,
|
||
вопросы темы для генератора, генератор теста.
|
||
|
||
🔧 НОВОЕ (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
|
||
from typing import Optional
|
||
|
||
from fastapi import APIRouter, Request, HTTPException
|
||
from auth import require_auth
|
||
from database import get_pool
|
||
from config import ADMIN_IDS
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
router = APIRouter(prefix="/admin/content", tags=["admin-content"])
|
||
|
||
LEVELS = ["A1", "A2", "B1", "B2", "C1", "C2"]
|
||
|
||
|
||
def _require_admin(telegram_id: int) -> None:
|
||
if telegram_id not in ADMIN_IDS:
|
||
raise HTTPException(403, "Access denied")
|
||
|
||
|
||
# ============ SUMMARY ============
|
||
|
||
@router.get("/summary")
|
||
async def get_content_summary(request: Request):
|
||
"""
|
||
Сводка по всем уровням: темы, уроки, слова, тексты, последняя правка.
|
||
Слова считаются только level_id IS NULL (чистые слова уровня).
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
level_rows = await conn.fetch("""
|
||
SELECT code, name_ru, sort_order
|
||
FROM learning_levels
|
||
WHERE is_active = TRUE
|
||
ORDER BY sort_order
|
||
""")
|
||
|
||
# 🔧 ФИКС (24.09.2026): admin_content_summary_n_plus_1 —
|
||
# раньше 6 уровней × 5 запросов = 30 round-trip. Теперь 5 GROUP BY.
|
||
level_codes = [lvl["code"] for lvl in level_rows]
|
||
|
||
# 1. Темы — GROUP BY level_code
|
||
topics_rows = await conn.fetch("""
|
||
SELECT level_code, COUNT(*) as cnt
|
||
FROM learning_topics
|
||
WHERE level_code = ANY($1::text[])
|
||
GROUP BY level_code
|
||
""", level_codes)
|
||
topics_map = {r["level_code"]: r["cnt"] for r in topics_rows}
|
||
|
||
# 2. Уроки — GROUP BY level_code (через JOIN)
|
||
lessons_rows = await conn.fetch("""
|
||
SELECT t.level_code, COUNT(*) as cnt
|
||
FROM learning_lessons l
|
||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||
WHERE t.level_code = ANY($1::text[])
|
||
GROUP BY t.level_code
|
||
""", level_codes)
|
||
lessons_map = {r["level_code"]: r["cnt"] for r in lessons_rows}
|
||
|
||
# 3. Слова — GROUP BY level (level_id IS NULL)
|
||
words_rows = await conn.fetch("""
|
||
SELECT level, COUNT(*) as cnt
|
||
FROM level_words
|
||
WHERE level = ANY($1::text[]) AND level_id IS NULL
|
||
GROUP BY level
|
||
""", level_codes)
|
||
words_map = {r["level"]: r["cnt"] for r in words_rows}
|
||
|
||
# 4. Тексты — GROUP BY level
|
||
texts_rows = await conn.fetch("""
|
||
SELECT level, COUNT(*) as cnt
|
||
FROM sentences
|
||
WHERE level = ANY($1::text[])
|
||
GROUP BY level
|
||
""", level_codes)
|
||
texts_map = {r["level"]: r["cnt"] for r in texts_rows}
|
||
|
||
# 5. Последняя правка — один запрос с UNION ALL + GROUP BY
|
||
last_edited_rows = await conn.fetch("""
|
||
SELECT level_code, MAX(edited_at) as last_edited
|
||
FROM (
|
||
SELECT level_code, edited_at FROM learning_topics
|
||
WHERE level_code = ANY($1::text[])
|
||
UNION ALL
|
||
SELECT t.level_code, l.edited_at
|
||
FROM learning_lessons l
|
||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||
WHERE t.level_code = ANY($1::text[])
|
||
UNION ALL
|
||
SELECT level, edited_at FROM level_words
|
||
WHERE level = ANY($1::text[]) AND level_id IS NULL
|
||
UNION ALL
|
||
SELECT level, edited_at FROM sentences
|
||
WHERE level = ANY($1::text[])
|
||
) sub
|
||
GROUP BY level_code
|
||
""", level_codes)
|
||
last_edited_map = {r["level_code"]: r["last_edited"] for r in last_edited_rows}
|
||
|
||
# Собираем result
|
||
result = []
|
||
for lvl in level_rows:
|
||
code = lvl["code"]
|
||
last_edited = last_edited_map.get(code)
|
||
|
||
result.append({
|
||
"code": code,
|
||
"name_ru": lvl["name_ru"],
|
||
"topics_total": topics_map.get(code, 0),
|
||
"lessons_total": lessons_map.get(code, 0),
|
||
"words_total": words_map.get(code, 0),
|
||
"texts_total": texts_map.get(code, 0),
|
||
"last_edited": last_edited.isoformat() if last_edited else None,
|
||
})
|
||
|
||
return {"levels": result}
|
||
|
||
|
||
# ============ WORDS ============
|
||
|
||
@router.get("/words/levels")
|
||
async def get_word_levels(request: Request):
|
||
"""Уровни A1–C2 с количеством слов (только level_id IS NULL)."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
level_rows = await conn.fetch("""
|
||
SELECT code, name_ru, sort_order
|
||
FROM learning_levels
|
||
WHERE is_active = TRUE
|
||
ORDER BY sort_order
|
||
""")
|
||
|
||
if not level_rows:
|
||
return {"levels": []}
|
||
|
||
level_codes = [lvl["code"] for lvl in level_rows]
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_get_word_levels_n_plus_1 —
|
||
# раньше 6 уровней × 2 запроса = 12 round-trip. Теперь 1 GROUP BY.
|
||
rows = await conn.fetch("""
|
||
SELECT level,
|
||
COUNT(*) as cnt,
|
||
MAX(edited_at) as last_edited
|
||
FROM level_words
|
||
WHERE level = ANY($1::text[]) AND level_id IS NULL
|
||
GROUP BY level
|
||
""", level_codes)
|
||
stats_map = {r["level"]: r for r in rows}
|
||
|
||
result = []
|
||
for lvl in level_rows:
|
||
code = lvl["code"]
|
||
stat = stats_map.get(code)
|
||
last_edited = stat["last_edited"] if stat else None
|
||
result.append({
|
||
"code": code,
|
||
"name_ru": lvl["name_ru"],
|
||
"words_count": stat["cnt"] if stat else 0,
|
||
"last_edited": last_edited.isoformat() if last_edited else None,
|
||
})
|
||
|
||
return {"levels": result}
|
||
|
||
|
||
@router.get("/words/level/{level}")
|
||
async def get_level_words(
|
||
request: Request,
|
||
level: str,
|
||
q: Optional[str] = None,
|
||
limit: int = 1000,
|
||
):
|
||
"""
|
||
Список слов уровня — только строки с level_id IS NULL.
|
||
Поиск по word_pl / translation_ru / translation_uk / translation_en.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if level not in LEVELS:
|
||
raise HTTPException(400, f"Invalid level: {level}")
|
||
|
||
if limit < 1:
|
||
limit = 1
|
||
elif limit > 2000:
|
||
limit = 2000
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
if q and q.strip():
|
||
pattern = f"%{q.strip()}%"
|
||
rows = await conn.fetch("""
|
||
SELECT id, word_pl, translation_ru, translation_uk, translation_en,
|
||
edited_at
|
||
FROM level_words
|
||
WHERE level = $1
|
||
AND level_id IS NULL
|
||
AND (
|
||
word_pl ILIKE $2
|
||
OR translation_ru ILIKE $2
|
||
OR translation_uk ILIKE $2
|
||
OR translation_en ILIKE $2
|
||
)
|
||
ORDER BY word_pl ASC
|
||
LIMIT $3
|
||
""", level, pattern, limit)
|
||
else:
|
||
rows = await conn.fetch("""
|
||
SELECT id, word_pl, translation_ru, translation_uk, translation_en,
|
||
edited_at
|
||
FROM level_words
|
||
WHERE level = $1
|
||
AND level_id IS NULL
|
||
ORDER BY word_pl ASC
|
||
LIMIT $2
|
||
""", level, limit)
|
||
|
||
return {
|
||
"level": level,
|
||
"count": len(rows),
|
||
"words": [
|
||
{
|
||
"id": r["id"],
|
||
"word_pl": r["word_pl"],
|
||
"translation_ru": r["translation_ru"] or "",
|
||
"translation_uk": r["translation_uk"] or "",
|
||
"translation_en": r["translation_en"] or "",
|
||
"edited_at": r["edited_at"].isoformat() if r["edited_at"] else None,
|
||
}
|
||
for r in rows
|
||
],
|
||
}
|
||
|
||
|
||
@router.get("/words/word/{word_id}")
|
||
async def get_word(request: Request, word_id: int):
|
||
"""Одно слово по id."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
row = await conn.fetchrow("""
|
||
SELECT id, word_pl, translation_ru, translation_uk, translation_en, level, edited_at
|
||
FROM level_words WHERE id = $1
|
||
""", word_id)
|
||
|
||
if not row:
|
||
raise HTTPException(404, "Word not found")
|
||
|
||
return {
|
||
"id": row["id"],
|
||
"word_pl": row["word_pl"],
|
||
"translation_ru": row["translation_ru"] or "",
|
||
"translation_uk": row["translation_uk"] or "",
|
||
"translation_en": row["translation_en"] or "",
|
||
"level": row["level"],
|
||
"edited_at": row["edited_at"].isoformat() if row["edited_at"] else None,
|
||
}
|
||
|
||
|
||
@router.put("/words/word/{word_id}")
|
||
async def update_word(request: Request, word_id: int):
|
||
"""
|
||
Обновить слово.
|
||
Обновляем ВСЕ строки с этим (level, word_pl) — включая привязки к игровым
|
||
уровням Филвордов (level_id != NULL), чтобы игра получила новый перевод.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
word_pl = (body.get("word_pl") or "").strip()
|
||
translation_ru = (body.get("translation_ru") or "").strip()
|
||
translation_uk = (body.get("translation_uk") or "").strip()
|
||
translation_en = (body.get("translation_en") or "").strip()
|
||
|
||
if not word_pl:
|
||
raise HTTPException(400, "word_pl is required")
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
existing = await conn.fetchrow("""
|
||
SELECT level, word_pl FROM level_words WHERE id = $1
|
||
""", word_id)
|
||
|
||
if not existing:
|
||
raise HTTPException(404, "Word not found")
|
||
|
||
old_word_pl = existing["word_pl"]
|
||
level = existing["level"]
|
||
|
||
# 🔧 ФИКС: обновляем все строки с этим (level, old_word_pl)
|
||
result = await conn.execute("""
|
||
UPDATE level_words
|
||
SET word_pl = $1,
|
||
translation_ru = $2,
|
||
translation_uk = $3,
|
||
translation_en = $4,
|
||
edited_at = NOW()
|
||
WHERE level = $5 AND word_pl = $6
|
||
""", word_pl, translation_ru, translation_uk, translation_en, level, old_word_pl)
|
||
|
||
affected = int(result.split()[-1])
|
||
|
||
logger.info(
|
||
f"[admin_content] word '{old_word_pl}' -> '{word_pl}' in {level}: "
|
||
f"{affected} rows updated by admin {telegram_id}"
|
||
)
|
||
|
||
return {"status": "ok", "word_id": word_id, "rows_updated": affected}
|
||
|
||
|
||
@router.post("/words/level/{level}")
|
||
async def create_word(request: Request, level: str):
|
||
"""Добавить слово в уровень (level_id = NULL)."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if level not in LEVELS:
|
||
raise HTTPException(400, f"Invalid level: {level}")
|
||
|
||
body = await request.json()
|
||
word_pl = (body.get("word_pl") or "").strip()
|
||
translation_ru = (body.get("translation_ru") or "").strip()
|
||
translation_uk = (body.get("translation_uk") or "").strip()
|
||
translation_en = (body.get("translation_en") or "").strip()
|
||
|
||
if not word_pl:
|
||
raise HTTPException(400, "word_pl is required")
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
existing = await conn.fetchval("""
|
||
SELECT id FROM level_words
|
||
WHERE level = $1 AND level_id IS NULL AND LOWER(word_pl) = LOWER($2)
|
||
""", level, word_pl)
|
||
if existing:
|
||
raise HTTPException(409, f"Word '{word_pl}' already exists in {level}")
|
||
|
||
row = await conn.fetchrow("""
|
||
INSERT INTO level_words
|
||
(level_id, word_pl, translation_ru, translation_uk, translation_en, level, edited_at)
|
||
VALUES (NULL, $1, $2, $3, $4, $5, NOW())
|
||
RETURNING id
|
||
""", word_pl, translation_ru, translation_uk, translation_en, level)
|
||
|
||
logger.info(
|
||
f"[admin_content] word created: #{row['id']} '{word_pl}' in {level} "
|
||
f"by admin {telegram_id}"
|
||
)
|
||
|
||
return {"status": "ok", "word_id": row["id"]}
|
||
|
||
|
||
# ============ TEXTS (sentences) ============
|
||
|
||
@router.get("/texts/levels")
|
||
async def get_text_levels(request: Request):
|
||
"""Уровни A1–C2 с количеством текстов и последней правкой."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
level_rows = await conn.fetch("""
|
||
SELECT code, name_ru, sort_order
|
||
FROM learning_levels
|
||
WHERE is_active = TRUE
|
||
ORDER BY sort_order
|
||
""")
|
||
|
||
if not level_rows:
|
||
return {"levels": []}
|
||
|
||
level_codes = [lvl["code"] for lvl in level_rows]
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_text_levels_n_plus_1 —
|
||
# 1 GROUP BY вместо 6×2 запросов.
|
||
rows = await conn.fetch("""
|
||
SELECT level,
|
||
COUNT(*) as cnt,
|
||
MAX(edited_at) as last_edited
|
||
FROM sentences
|
||
WHERE level = ANY($1::text[])
|
||
GROUP BY level
|
||
""", level_codes)
|
||
stats_map = {r["level"]: r for r in rows}
|
||
|
||
result = []
|
||
for lvl in level_rows:
|
||
code = lvl["code"]
|
||
stat = stats_map.get(code)
|
||
last_edited = stat["last_edited"] if stat else None
|
||
result.append({
|
||
"code": code,
|
||
"name_ru": lvl["name_ru"],
|
||
"texts_count": stat["cnt"] if stat else 0,
|
||
"last_edited": last_edited.isoformat() if last_edited else None,
|
||
})
|
||
|
||
return {"levels": result}
|
||
|
||
|
||
@router.get("/texts/level/{level}")
|
||
async def get_level_texts(
|
||
request: Request,
|
||
level: str,
|
||
q: Optional[str] = None,
|
||
limit: int = 1000,
|
||
):
|
||
"""Список текстов уровня с опциональным поиском."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if level not in LEVELS:
|
||
raise HTTPException(400, f"Invalid level: {level}")
|
||
|
||
if limit < 1:
|
||
limit = 1
|
||
elif limit > 2000:
|
||
limit = 2000
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
if q and q.strip():
|
||
pattern = f"%{q.strip()}%"
|
||
rows = await conn.fetch("""
|
||
SELECT id, sentence_number, sentence_pl,
|
||
translation_ru, translation_uk, translation_en,
|
||
difficulty, edited_at
|
||
FROM sentences
|
||
WHERE level = $1
|
||
AND (
|
||
sentence_pl ILIKE $2
|
||
OR translation_ru ILIKE $2
|
||
OR translation_uk ILIKE $2
|
||
OR translation_en ILIKE $2
|
||
)
|
||
ORDER BY sentence_number ASC
|
||
LIMIT $3
|
||
""", level, pattern, limit)
|
||
else:
|
||
rows = await conn.fetch("""
|
||
SELECT id, sentence_number, sentence_pl,
|
||
translation_ru, translation_uk, translation_en,
|
||
difficulty, edited_at
|
||
FROM sentences
|
||
WHERE level = $1
|
||
ORDER BY sentence_number ASC
|
||
LIMIT $2
|
||
""", level, limit)
|
||
|
||
return {
|
||
"level": level,
|
||
"count": len(rows),
|
||
"texts": [
|
||
{
|
||
"id": r["id"],
|
||
"sentence_number": r["sentence_number"],
|
||
"sentence_pl": r["sentence_pl"],
|
||
"translation_ru": r["translation_ru"] or "",
|
||
"translation_uk": r["translation_uk"] or "",
|
||
"translation_en": r["translation_en"] or "",
|
||
"difficulty": r["difficulty"],
|
||
"edited_at": r["edited_at"].isoformat() if r["edited_at"] else None,
|
||
}
|
||
for r in rows
|
||
],
|
||
}
|
||
|
||
|
||
@router.get("/texts/text/{text_id}")
|
||
async def get_text(request: Request, text_id: int):
|
||
"""Один текст по id."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
row = await conn.fetchrow("""
|
||
SELECT id, sentence_number, sentence_pl,
|
||
translation_ru, translation_uk, translation_en,
|
||
difficulty, level, edited_at
|
||
FROM sentences WHERE id = $1
|
||
""", text_id)
|
||
|
||
if not row:
|
||
raise HTTPException(404, "Text not found")
|
||
|
||
return {
|
||
"id": row["id"],
|
||
"sentence_number": row["sentence_number"],
|
||
"sentence_pl": row["sentence_pl"],
|
||
"translation_ru": row["translation_ru"] or "",
|
||
"translation_uk": row["translation_uk"] or "",
|
||
"translation_en": row["translation_en"] or "",
|
||
"difficulty": row["difficulty"],
|
||
"level": row["level"],
|
||
"edited_at": row["edited_at"].isoformat() if row["edited_at"] else None,
|
||
}
|
||
|
||
|
||
def _compute_difficulty(sentence_pl: str) -> int:
|
||
"""Пересчитывает difficulty по количеству слов (как в load_sentences.py)."""
|
||
words_count = len(sentence_pl.split())
|
||
if words_count <= 4:
|
||
return 1
|
||
elif words_count <= 6:
|
||
return 2
|
||
return 3
|
||
|
||
|
||
@router.put("/texts/text/{text_id}")
|
||
async def update_text(request: Request, text_id: int):
|
||
"""
|
||
Обновить текст.
|
||
Difficulty пересчитывается автоматически по количеству слов в sentence_pl.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
sentence_pl = (body.get("sentence_pl") or "").strip()
|
||
translation_ru = (body.get("translation_ru") or "").strip()
|
||
translation_uk = (body.get("translation_uk") or "").strip()
|
||
translation_en = (body.get("translation_en") or "").strip()
|
||
|
||
if not sentence_pl:
|
||
raise HTTPException(400, "sentence_pl is required")
|
||
|
||
difficulty = _compute_difficulty(sentence_pl)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
exists = await conn.fetchval("SELECT 1 FROM sentences WHERE id = $1", text_id)
|
||
if not exists:
|
||
raise HTTPException(404, "Text not found")
|
||
|
||
await conn.execute("""
|
||
UPDATE sentences
|
||
SET sentence_pl = $1,
|
||
translation_ru = $2,
|
||
translation_uk = $3,
|
||
translation_en = $4,
|
||
difficulty = $5,
|
||
edited_at = NOW()
|
||
WHERE id = $6
|
||
""", sentence_pl, translation_ru, translation_uk, translation_en, difficulty, text_id)
|
||
|
||
logger.info(f"[admin_content] text #{text_id} updated by admin {telegram_id}")
|
||
|
||
return {"status": "ok", "text_id": text_id, "difficulty": difficulty}
|
||
|
||
|
||
@router.delete("/texts/text/{text_id}")
|
||
async def delete_text(request: Request, text_id: int):
|
||
"""Удалить текст."""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
exists = await conn.fetchval("SELECT 1 FROM sentences WHERE id = $1", text_id)
|
||
if not exists:
|
||
raise HTTPException(404, "Text not found")
|
||
|
||
await conn.execute("DELETE FROM sentences WHERE id = $1", text_id)
|
||
|
||
logger.info(f"[admin_content] text #{text_id} deleted by admin {telegram_id}")
|
||
return {"status": "ok", "text_id": text_id}
|
||
|
||
|
||
@router.post("/texts/level/{level}")
|
||
async def create_text(request: Request, level: str):
|
||
"""
|
||
Добавить текст в уровень.
|
||
Нумерация: max(sentence_number) + 1 для этого уровня.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if level not in LEVELS:
|
||
raise HTTPException(400, f"Invalid level: {level}")
|
||
|
||
body = await request.json()
|
||
sentence_pl = (body.get("sentence_pl") or "").strip()
|
||
translation_ru = (body.get("translation_ru") or "").strip()
|
||
translation_uk = (body.get("translation_uk") or "").strip()
|
||
translation_en = (body.get("translation_en") or "").strip()
|
||
|
||
if not sentence_pl:
|
||
raise HTTPException(400, "sentence_pl is required")
|
||
|
||
# 🔧 ФИКС (30.09.2026): global_duplicate_warning —
|
||
# проверяем все уровни. force=true пропускает проверку.
|
||
force = bool(body.get("force", False))
|
||
|
||
difficulty = _compute_difficulty(sentence_pl)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
if not force:
|
||
existing = await conn.fetchrow("""
|
||
SELECT id, level FROM sentences
|
||
WHERE LOWER(sentence_pl) = LOWER($1)
|
||
ORDER BY
|
||
CASE level
|
||
WHEN 'A1' THEN 1 WHEN 'A2' THEN 2
|
||
WHEN 'B1' THEN 3 WHEN 'B2' THEN 4
|
||
WHEN 'C1' THEN 5 WHEN 'C2' THEN 6
|
||
ELSE 7
|
||
END
|
||
LIMIT 1
|
||
""", sentence_pl)
|
||
|
||
if existing:
|
||
existing_level = existing["level"]
|
||
# Короткий текст для сообщения (не режем посреди слова)
|
||
short_text = sentence_pl[:50] + ("…" if len(sentence_pl) > 50 else "")
|
||
if existing_level == level:
|
||
raise HTTPException(
|
||
409,
|
||
f"DUPLICATE_SAME_LEVEL|{short_text}|{existing_level}"
|
||
)
|
||
else:
|
||
raise HTTPException(
|
||
409,
|
||
f"DUPLICATE_OTHER_LEVEL|{short_text}|{existing_level}"
|
||
)
|
||
|
||
next_num = await conn.fetchval("""
|
||
SELECT COALESCE(MAX(sentence_number), 0) + 1 FROM sentences WHERE level = $1
|
||
""", level) or 1
|
||
|
||
row = await conn.fetchrow("""
|
||
INSERT INTO sentences
|
||
(sentence_number, sentence_pl, translation_ru, translation_uk, translation_en, difficulty, level, edited_at)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
|
||
RETURNING id
|
||
""", next_num, sentence_pl, translation_ru, translation_uk, translation_en, difficulty, level)
|
||
|
||
logger.info(
|
||
f"[admin_content] text created: #{row['id']} in {level} by admin {telegram_id}"
|
||
)
|
||
|
||
return {"status": "ok", "text_id": row["id"], "sentence_number": next_num}
|
||
|
||
|
||
@router.get("/texts/all")
|
||
async def list_all_texts(
|
||
request: Request,
|
||
level: Optional[str] = None,
|
||
q: Optional[str] = None,
|
||
page: int = 1,
|
||
limit: int = 50,
|
||
):
|
||
"""
|
||
🔧 ОБНОВЛЕНО (30.09.2026): пагинация + total.
|
||
|
||
Возвращает:
|
||
{
|
||
"total": 400, # всего под фильтром
|
||
"page": 1, # текущая страница
|
||
"limit": 50, # размер страницы
|
||
"pages": 8, # всего страниц
|
||
"texts": [...], # тексты текущей страницы
|
||
}
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if page < 1:
|
||
page = 1
|
||
if limit < 1:
|
||
limit = 1
|
||
elif limit > 500:
|
||
limit = 500
|
||
|
||
offset = (page - 1) * limit
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
conditions = []
|
||
params: list = []
|
||
idx = 1
|
||
|
||
if level and level in LEVELS:
|
||
conditions.append(f"level = ${idx}")
|
||
params.append(level)
|
||
idx += 1
|
||
|
||
if q and q.strip():
|
||
conditions.append(f"""(
|
||
sentence_pl ILIKE ${idx} OR
|
||
translation_ru ILIKE ${idx} OR
|
||
translation_uk ILIKE ${idx} OR
|
||
translation_en ILIKE ${idx}
|
||
)""")
|
||
params.append(f"%{q.strip()}%")
|
||
idx += 1
|
||
|
||
where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
|
||
|
||
# Total
|
||
total = await conn.fetchval(f"""
|
||
SELECT COUNT(*) FROM sentences {where}
|
||
""", *params) or 0
|
||
|
||
# Page
|
||
rows = await conn.fetch(f"""
|
||
SELECT id, level, sentence_number, sentence_pl,
|
||
translation_ru, translation_uk, translation_en, difficulty
|
||
FROM sentences
|
||
{where}
|
||
ORDER BY level, sentence_number
|
||
LIMIT ${idx} OFFSET ${idx + 1}
|
||
""", *params, limit, offset)
|
||
|
||
pages = (total + limit - 1) // limit if limit > 0 else 1
|
||
|
||
return {
|
||
"total": total,
|
||
"page": page,
|
||
"limit": limit,
|
||
"pages": pages,
|
||
"texts": [
|
||
{
|
||
"id": r["id"],
|
||
"level": r["level"],
|
||
"sentence_number": r["sentence_number"],
|
||
"sentence_pl": r["sentence_pl"],
|
||
"translation_ru": r["translation_ru"] or "",
|
||
"translation_uk": r["translation_uk"] or "",
|
||
"translation_en": r["translation_en"] or "",
|
||
"difficulty": r["difficulty"],
|
||
}
|
||
for r in rows
|
||
],
|
||
}
|
||
|
||
|
||
# ============ LESSONS ============
|
||
|
||
@router.get("/lessons/levels")
|
||
async def get_lesson_levels(request: Request):
|
||
"""
|
||
Уровни A1–C2 с количеством тем и последней правкой.
|
||
Считаем только активные темы.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
level_rows = await conn.fetch("""
|
||
SELECT code, name_ru, sort_order
|
||
FROM learning_levels
|
||
WHERE is_active = TRUE
|
||
ORDER BY sort_order
|
||
""")
|
||
|
||
if not level_rows:
|
||
return {"levels": []}
|
||
|
||
level_codes = [lvl["code"] for lvl in level_rows]
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_lesson_levels_n_plus_1 —
|
||
# 3 GROUP BY запроса вместо 3×N.
|
||
topics_rows = await conn.fetch("""
|
||
SELECT level_code, COUNT(*) as cnt
|
||
FROM learning_topics
|
||
WHERE level_code = ANY($1::text[]) AND is_active = TRUE
|
||
GROUP BY level_code
|
||
""", level_codes)
|
||
topics_map = {r["level_code"]: r["cnt"] for r in topics_rows}
|
||
|
||
lessons_rows = await conn.fetch("""
|
||
SELECT t.level_code, COUNT(*) as cnt
|
||
FROM learning_lessons l
|
||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||
WHERE t.level_code = ANY($1::text[]) AND l.is_active = TRUE
|
||
GROUP BY t.level_code
|
||
""", level_codes)
|
||
lessons_map = {r["level_code"]: r["cnt"] for r in lessons_rows}
|
||
|
||
last_edited_rows = await conn.fetch("""
|
||
SELECT level_code, MAX(edited_at) as last_edited
|
||
FROM (
|
||
SELECT t.level_code, t.edited_at FROM learning_topics t
|
||
WHERE t.level_code = ANY($1::text[])
|
||
UNION ALL
|
||
SELECT t.level_code, l.edited_at FROM learning_lessons l
|
||
JOIN learning_topics t ON l.topic_id = t.topic_id
|
||
WHERE t.level_code = ANY($1::text[])
|
||
) sub
|
||
GROUP BY level_code
|
||
""", level_codes)
|
||
last_edited_map = {r["level_code"]: r["last_edited"] for r in last_edited_rows}
|
||
|
||
result = []
|
||
for lvl in level_rows:
|
||
code = lvl["code"]
|
||
last_edited = last_edited_map.get(code)
|
||
result.append({
|
||
"code": code,
|
||
"name_ru": lvl["name_ru"],
|
||
"topics_count": topics_map.get(code, 0),
|
||
"lessons_count": lessons_map.get(code, 0),
|
||
"last_edited": last_edited.isoformat() if last_edited else None,
|
||
})
|
||
|
||
return {"levels": result}
|
||
|
||
|
||
@router.get("/lessons/level/{level}/topics")
|
||
async def get_lesson_topics(request: Request, level: str):
|
||
"""
|
||
Темы уровня с количеством уроков и вопросов в тесте.
|
||
Сортировка: order_number ASC.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
if level not in LEVELS:
|
||
raise HTTPException(400, f"Invalid level: {level}")
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
rows = await conn.fetch("""
|
||
SELECT
|
||
topic_id,
|
||
order_number,
|
||
name_pl, name_ru, name_uk, name_en,
|
||
is_active
|
||
FROM learning_topics
|
||
WHERE level_code = $1 AND is_active = TRUE
|
||
ORDER BY order_number ASC
|
||
""", level)
|
||
|
||
if not rows:
|
||
return {"level": level, "topics": []}
|
||
|
||
topic_ids = [r["topic_id"] for r in rows]
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_lesson_topics_n_plus_1 —
|
||
# 2 GROUP BY запроса вместо 2×N.
|
||
lessons_rows = await conn.fetch("""
|
||
SELECT topic_id, COUNT(*) as cnt
|
||
FROM learning_lessons
|
||
WHERE topic_id = ANY($1::text[]) AND is_active = TRUE
|
||
GROUP BY topic_id
|
||
""", topic_ids)
|
||
lessons_map = {r["topic_id"]: r["cnt"] for r in lessons_rows}
|
||
|
||
test_rows = await conn.fetch("""
|
||
SELECT topic_id, COUNT(*) as cnt
|
||
FROM learning_questions
|
||
WHERE topic_id = ANY($1::text[]) AND is_test_question = TRUE
|
||
GROUP BY topic_id
|
||
""", topic_ids)
|
||
test_map = {r["topic_id"]: r["cnt"] for r in test_rows}
|
||
|
||
result = []
|
||
for r in rows:
|
||
topic_id = r["topic_id"]
|
||
result.append({
|
||
"topic_id": topic_id,
|
||
"order_number": r["order_number"],
|
||
"name_pl": r["name_pl"],
|
||
"name_ru": r["name_ru"],
|
||
"name_uk": r["name_uk"],
|
||
"name_en": r["name_en"],
|
||
"lessons_count": lessons_map.get(topic_id, 0),
|
||
"test_questions_count": test_map.get(topic_id, 0),
|
||
})
|
||
|
||
return {"level": level, "topics": result}
|
||
|
||
|
||
@router.get("/lessons/topic/{topic_id}")
|
||
async def get_lesson_topic(request: Request, topic_id: str):
|
||
"""
|
||
Тема целиком: инфо о теме + список уроков + информация о тесте темы.
|
||
Уроки сортируются по order_number ASC.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
topic = await conn.fetchrow("""
|
||
SELECT topic_id, level_code, order_number,
|
||
name_pl, name_ru, name_uk, name_en,
|
||
description_pl, description_ru, description_uk, description_en
|
||
FROM learning_topics
|
||
WHERE topic_id = $1
|
||
""", topic_id)
|
||
|
||
if not topic:
|
||
raise HTTPException(404, "Topic not found")
|
||
|
||
lessons_rows = await conn.fetch("""
|
||
SELECT lesson_id, order_number, skill_tag,
|
||
title_pl, title_ru, title_uk, title_en,
|
||
is_active
|
||
FROM learning_lessons
|
||
WHERE topic_id = $1 AND is_active = TRUE
|
||
ORDER BY order_number ASC
|
||
""", topic_id)
|
||
|
||
lessons = []
|
||
for l in lessons_rows:
|
||
lessons.append({
|
||
"lesson_id": l["lesson_id"],
|
||
"order_number": l["order_number"],
|
||
"skill_tag": l["skill_tag"],
|
||
"title_pl": l["title_pl"],
|
||
"title_ru": l["title_ru"],
|
||
"title_uk": l["title_uk"],
|
||
"title_en": l["title_en"],
|
||
})
|
||
|
||
# Считаем вопросы теста темы
|
||
test_questions_count = await conn.fetchval("""
|
||
SELECT COUNT(*) FROM learning_questions
|
||
WHERE topic_id = $1 AND is_test_question = TRUE
|
||
""", topic_id) or 0
|
||
|
||
# Проверяем, есть ли вообще тест-вопросы
|
||
has_test = test_questions_count > 0
|
||
|
||
return {
|
||
"topic": {
|
||
"topic_id": topic["topic_id"],
|
||
"level_code": topic["level_code"],
|
||
"order_number": topic["order_number"],
|
||
"name_pl": topic["name_pl"],
|
||
"name_ru": topic["name_ru"],
|
||
"name_uk": topic["name_uk"],
|
||
"name_en": topic["name_en"],
|
||
"description_pl": topic["description_pl"],
|
||
"description_ru": topic["description_ru"],
|
||
"description_uk": topic["description_uk"],
|
||
"description_en": topic["description_en"],
|
||
},
|
||
"lessons": lessons,
|
||
"has_test": has_test,
|
||
"test_questions_count": test_questions_count,
|
||
}
|
||
|
||
|
||
@router.get("/lessons/lesson/{lesson_id}")
|
||
async def get_lesson(request: Request, lesson_id: str):
|
||
"""
|
||
Урок целиком для WYSIWYG-редактора:
|
||
- lesson: title, objective, explanation (4 языка) + метаданные
|
||
- examples: список примеров (order_number ASC)
|
||
- questions: список вопросов урока (is_test_question = FALSE)
|
||
- options: список вариантов
|
||
- wrong_because_text: человекочитаемый текст для неправильных вариантов
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
lesson = await conn.fetchrow("""
|
||
SELECT lesson_id, topic_id, order_number, skill_tag,
|
||
title_pl, title_ru, title_uk, title_en,
|
||
objective_pl, objective_ru, objective_uk, objective_en,
|
||
explanation_pl, explanation_ru, explanation_uk, explanation_en,
|
||
is_active
|
||
FROM learning_lessons
|
||
WHERE lesson_id = $1
|
||
""", lesson_id)
|
||
|
||
if not lesson:
|
||
raise HTTPException(404, "Lesson not found")
|
||
|
||
# Примеры
|
||
examples_rows = await conn.fetch("""
|
||
SELECT id, order_number, text_pl, text_ru, text_uk, text_en, audio_url
|
||
FROM lesson_examples
|
||
WHERE lesson_id = $1
|
||
ORDER BY order_number ASC
|
||
""", lesson_id)
|
||
|
||
examples = [
|
||
{
|
||
"id": e["id"],
|
||
"order_number": e["order_number"],
|
||
"text_pl": e["text_pl"] or "",
|
||
"text_ru": e["text_ru"] or "",
|
||
"text_uk": e["text_uk"] or "",
|
||
"text_en": e["text_en"] or "",
|
||
"audio_url": e["audio_url"],
|
||
}
|
||
for e in examples_rows
|
||
]
|
||
|
||
# Вопросы урока (не тест темы)
|
||
questions_rows = await conn.fetch("""
|
||
SELECT question_id, context_type, question_type, skill_tag, difficulty,
|
||
prompt_pl, prompt_ru, prompt_uk, prompt_en,
|
||
correct_answer, hint_type, hint_value, options_language,
|
||
is_test_question, test_order
|
||
FROM learning_questions
|
||
WHERE lesson_id = $1 AND is_test_question = FALSE
|
||
ORDER BY id ASC
|
||
""", lesson_id)
|
||
|
||
# Справочник wrong_because → человекочитаемый текст (RU)
|
||
wb_rows = await conn.fetch("""
|
||
SELECT wrong_because, explanation_ru
|
||
FROM wrong_because_explanations
|
||
""")
|
||
wb_map = {w["wrong_because"]: w["explanation_ru"] for w in wb_rows}
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_get_lesson_n_plus_1 —
|
||
# один запрос ANY + группировка.
|
||
question_ids = [q["question_id"] for q in questions_rows]
|
||
all_options = []
|
||
if question_ids:
|
||
all_options = await conn.fetch("""
|
||
SELECT question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because
|
||
FROM question_options
|
||
WHERE question_id = ANY($1::text[])
|
||
ORDER BY question_id, option_key ASC
|
||
""", question_ids)
|
||
|
||
options_by_q: dict = {}
|
||
for o in all_options:
|
||
options_by_q.setdefault(o["question_id"], []).append(o)
|
||
|
||
questions = []
|
||
for q in questions_rows:
|
||
options_rows = options_by_q.get(q["question_id"], [])
|
||
|
||
options = []
|
||
for o in options_rows:
|
||
wb_code = o["wrong_because"]
|
||
options.append({
|
||
"option_key": o["option_key"],
|
||
"text_pl": o["text_pl"] or "",
|
||
"text_ru": o["text_ru"] or "",
|
||
"text_uk": o["text_uk"] or "",
|
||
"text_en": o["text_en"] or "",
|
||
"is_correct": o["is_correct"],
|
||
"wrong_because": wb_code,
|
||
"wrong_because_text": wb_map.get(wb_code, "") if wb_code else "",
|
||
})
|
||
|
||
questions.append({
|
||
"question_id": q["question_id"],
|
||
"context_type": q["context_type"],
|
||
"question_type": q["question_type"],
|
||
"skill_tag": q["skill_tag"],
|
||
"difficulty": q["difficulty"],
|
||
"prompt_pl": q["prompt_pl"] or "",
|
||
"prompt_ru": q["prompt_ru"] or "",
|
||
"prompt_uk": q["prompt_uk"] or "",
|
||
"prompt_en": q["prompt_en"] or "",
|
||
"correct_answer": q["correct_answer"] or "",
|
||
"hint_type": q["hint_type"],
|
||
"hint_value": q["hint_value"],
|
||
"options_language": q["options_language"] or "pl",
|
||
"options": options,
|
||
})
|
||
|
||
return {
|
||
"lesson": {
|
||
"lesson_id": lesson["lesson_id"],
|
||
"topic_id": lesson["topic_id"],
|
||
"order_number": lesson["order_number"],
|
||
"skill_tag": lesson["skill_tag"],
|
||
"title_pl": lesson["title_pl"] or "",
|
||
"title_ru": lesson["title_ru"] or "",
|
||
"title_uk": lesson["title_uk"] or "",
|
||
"title_en": lesson["title_en"] or "",
|
||
"objective_pl": lesson["objective_pl"] or "",
|
||
"objective_ru": lesson["objective_ru"] or "",
|
||
"objective_uk": lesson["objective_uk"] or "",
|
||
"objective_en": lesson["objective_en"] or "",
|
||
"explanation_pl": lesson["explanation_pl"] or "",
|
||
"explanation_ru": lesson["explanation_ru"] or "",
|
||
"explanation_uk": lesson["explanation_uk"] or "",
|
||
"explanation_en": lesson["explanation_en"] or "",
|
||
},
|
||
"examples": examples,
|
||
"questions": questions,
|
||
}
|
||
|
||
|
||
@router.put("/lessons/lesson/{lesson_id}")
|
||
async def update_lesson(request: Request, lesson_id: str):
|
||
"""
|
||
Сохранить урок целиком (Вариант B) — одна транзакция:
|
||
1. UPDATE learning_lessons (title, objective, explanation, edited_at).
|
||
2. DELETE + INSERT lesson_examples.
|
||
3. UPDATE learning_questions (prompt, correct_answer, hint_type, hint_value, edited_at).
|
||
4. DELETE + INSERT question_options (option_key генерируется A/B/C/D/...).
|
||
|
||
Тело запроса:
|
||
{
|
||
"title_pl": "...", "title_en": "...", "title_ru": "...", "title_uk": "...",
|
||
"objective_pl": "...", "objective_en": "...", "objective_ru": "...", "objective_uk": "...",
|
||
"explanation_pl": "...", "explanation_en": "...", "explanation_ru": "...", "explanation_uk": "...",
|
||
"examples": [
|
||
{"text_pl": "...", "text_en": "...", "text_ru": "...", "text_uk": "..."}
|
||
],
|
||
"questions": [
|
||
{
|
||
"question_id": "a1_greetings_l01_q1",
|
||
"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},
|
||
{"text_pl": "...", "text_en": "...", "text_ru": "...", "text_uk": "...",
|
||
"is_correct": false, "wrong_because": "wrong_case"}
|
||
]
|
||
}
|
||
]
|
||
}
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
|
||
# ============ 1. Валидация ============
|
||
|
||
title_pl = (body.get("title_pl") or "").strip()
|
||
title_ru = (body.get("title_ru") or "").strip()
|
||
title_uk = (body.get("title_uk") or "").strip()
|
||
title_en = (body.get("title_en") or "").strip()
|
||
|
||
if not title_pl:
|
||
raise HTTPException(400, "title_pl is required")
|
||
|
||
objective_pl = (body.get("objective_pl") or "").strip()
|
||
objective_ru = (body.get("objective_ru") or "").strip()
|
||
objective_uk = (body.get("objective_uk") or "").strip()
|
||
objective_en = (body.get("objective_en") or "").strip()
|
||
|
||
explanation_pl = (body.get("explanation_pl") or "").strip()
|
||
explanation_ru = (body.get("explanation_ru") or "").strip()
|
||
explanation_uk = (body.get("explanation_uk") or "").strip()
|
||
explanation_en = (body.get("explanation_en") or "").strip()
|
||
|
||
examples_raw = body.get("examples") or []
|
||
if not isinstance(examples_raw, list):
|
||
raise HTTPException(400, "examples must be a list")
|
||
|
||
examples = []
|
||
for ex in examples_raw:
|
||
text_pl = (ex.get("text_pl") or "").strip()
|
||
if not text_pl:
|
||
continue # пропускаем пустые примеры
|
||
examples.append({
|
||
"text_pl": text_pl,
|
||
"text_ru": (ex.get("text_ru") or "").strip(),
|
||
"text_uk": (ex.get("text_uk") or "").strip(),
|
||
"text_en": (ex.get("text_en") or "").strip(),
|
||
})
|
||
|
||
questions_raw = body.get("questions") or []
|
||
if not isinstance(questions_raw, list):
|
||
raise HTTPException(400, "questions must be a list")
|
||
|
||
# Валидация вопросов
|
||
questions = []
|
||
for q in questions_raw:
|
||
question_id = (q.get("question_id") or "").strip()
|
||
if not question_id:
|
||
raise HTTPException(400, "question_id is required for every question")
|
||
|
||
prompt_pl = (q.get("prompt_pl") or "").strip()
|
||
if not prompt_pl:
|
||
raise HTTPException(400, f"prompt_pl is required for question {question_id}")
|
||
|
||
options_raw = q.get("options") or []
|
||
if not isinstance(options_raw, list) or len(options_raw) == 0:
|
||
raise HTTPException(400, f"At least one option required for question {question_id}")
|
||
|
||
# 🔧 ФИКС (25.09.2026): admin_content_option_key_overflow —
|
||
# если >26 вариантов, chr(ord('A') + idx) даст '[' '\' ']' —
|
||
# фронт не сопоставит correct_answer. Ограничиваем 26 (A-Z).
|
||
if len(options_raw) > 26:
|
||
raise HTTPException(
|
||
400,
|
||
f"Question {question_id}: too many options (max 26, got {len(options_raw)})"
|
||
)
|
||
|
||
# Проверка: ровно один правильный вариант
|
||
correct_count = sum(1 for o in options_raw if o.get("is_correct") is True)
|
||
if correct_count != 1:
|
||
raise HTTPException(
|
||
400,
|
||
f"Question {question_id}: exactly one option must be is_correct=true "
|
||
f"(got {correct_count})"
|
||
)
|
||
|
||
# Генерируем option_key A, B, C, D...
|
||
options = []
|
||
correct_answer = None
|
||
for idx, o in enumerate(options_raw):
|
||
option_key = chr(ord('A') + idx) # A, B, C, D...
|
||
|
||
text_pl_opt = (o.get("text_pl") or "").strip()
|
||
if not text_pl_opt:
|
||
raise HTTPException(
|
||
400,
|
||
f"Option {option_key} of question {question_id}: text_pl is required"
|
||
)
|
||
|
||
is_correct = bool(o.get("is_correct"))
|
||
if is_correct:
|
||
correct_answer = option_key
|
||
|
||
wrong_because = o.get("wrong_because")
|
||
if is_correct:
|
||
wrong_because = None # у правильного wrong_because нет
|
||
elif not wrong_because:
|
||
wrong_because = None # оставляем None если пусто
|
||
|
||
options.append({
|
||
"option_key": option_key,
|
||
"text_pl": text_pl_opt,
|
||
"text_ru": (o.get("text_ru") or "").strip(),
|
||
"text_uk": (o.get("text_uk") or "").strip(),
|
||
"text_en": (o.get("text_en") or "").strip(),
|
||
"is_correct": is_correct,
|
||
"wrong_because": wrong_because,
|
||
})
|
||
|
||
hint_type = q.get("hint_type")
|
||
if hint_type:
|
||
hint_type = str(hint_type).strip() or None
|
||
|
||
hint_value = q.get("hint_value")
|
||
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,
|
||
"prompt_ru": (q.get("prompt_ru") or "").strip(),
|
||
"prompt_uk": (q.get("prompt_uk") or "").strip(),
|
||
"prompt_en": (q.get("prompt_en") or "").strip(),
|
||
"correct_answer": correct_answer,
|
||
"hint_type": hint_type,
|
||
"hint_value": hint_value,
|
||
"options_language": options_language, # 🔧 НОВОЕ
|
||
"options": options,
|
||
})
|
||
|
||
# ============ 2. Транзакция ============
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
async with conn.transaction():
|
||
# Проверяем, что урок существует
|
||
exists = await conn.fetchval(
|
||
"SELECT 1 FROM learning_lessons WHERE lesson_id = $1", lesson_id
|
||
)
|
||
if not exists:
|
||
raise HTTPException(404, "Lesson not found")
|
||
|
||
# --- 2.1. UPDATE learning_lessons ---
|
||
await conn.execute("""
|
||
UPDATE learning_lessons
|
||
SET title_pl = $1,
|
||
title_ru = $2,
|
||
title_uk = $3,
|
||
title_en = $4,
|
||
objective_pl = $5,
|
||
objective_ru = $6,
|
||
objective_uk = $7,
|
||
objective_en = $8,
|
||
explanation_pl = $9,
|
||
explanation_ru = $10,
|
||
explanation_uk = $11,
|
||
explanation_en = $12,
|
||
edited_at = NOW()
|
||
WHERE lesson_id = $13
|
||
""",
|
||
title_pl, title_ru, title_uk, title_en,
|
||
objective_pl, objective_ru, objective_uk, objective_en,
|
||
explanation_pl, explanation_ru, explanation_uk, explanation_en,
|
||
lesson_id,
|
||
)
|
||
|
||
# --- 2.2. DELETE + INSERT lesson_examples ---
|
||
await conn.execute(
|
||
"DELETE FROM lesson_examples WHERE lesson_id = $1", lesson_id
|
||
)
|
||
|
||
for idx, ex in enumerate(examples, start=1):
|
||
await conn.execute("""
|
||
INSERT INTO lesson_examples
|
||
(lesson_id, order_number, text_pl, text_ru, text_uk, text_en)
|
||
VALUES ($1, $2, $3, $4, $5, $6)
|
||
""",
|
||
lesson_id, idx,
|
||
ex["text_pl"], ex["text_ru"], ex["text_uk"], ex["text_en"],
|
||
)
|
||
|
||
# --- 2.3. UPDATE learning_questions + DELETE + INSERT question_options ---
|
||
for q in questions:
|
||
# Проверяем, что вопрос принадлежит этому уроку
|
||
q_exists = await conn.fetchval("""
|
||
SELECT 1 FROM learning_questions
|
||
WHERE question_id = $1 AND lesson_id = $2
|
||
""", q["question_id"], lesson_id)
|
||
|
||
if not q_exists:
|
||
raise HTTPException(
|
||
400,
|
||
f"Question {q['question_id']} does not belong to lesson {lesson_id}"
|
||
)
|
||
|
||
await conn.execute("""
|
||
UPDATE learning_questions
|
||
SET prompt_pl = $1,
|
||
prompt_ru = $2,
|
||
prompt_uk = $3,
|
||
prompt_en = $4,
|
||
correct_answer = $5,
|
||
hint_type = $6,
|
||
hint_value = $7,
|
||
options_language = $8,
|
||
edited_at = NOW()
|
||
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"],
|
||
)
|
||
|
||
# Удаляем старые опции
|
||
await conn.execute(
|
||
"DELETE FROM question_options WHERE question_id = $1",
|
||
q["question_id"],
|
||
)
|
||
|
||
# Вставляем новые
|
||
for o in q["options"]:
|
||
await conn.execute("""
|
||
INSERT INTO question_options
|
||
(question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||
""",
|
||
q["question_id"], o["option_key"],
|
||
o["text_pl"], o["text_ru"], o["text_uk"], o["text_en"],
|
||
o["is_correct"], o["wrong_because"],
|
||
)
|
||
|
||
logger.info(
|
||
f"[admin_content] lesson '{lesson_id}' updated by admin {telegram_id}: "
|
||
f"{len(examples)} examples, {len(questions)} questions"
|
||
)
|
||
|
||
return {
|
||
"status": "ok",
|
||
"lesson_id": lesson_id,
|
||
"examples_count": len(examples),
|
||
"questions_count": len(questions),
|
||
}
|
||
|
||
|
||
# ============ WRONG BECAUSE (справочник) ============
|
||
|
||
@router.get("/wrong-because")
|
||
async def get_wrong_because(request: Request):
|
||
"""
|
||
Справочник wrong_because — 7 записей.
|
||
Отдаём код + 4 языка, чтобы фронт мог показать человекочитаемый текст
|
||
на языке интерфейса препода.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
rows = await conn.fetch("""
|
||
SELECT wrong_because, explanation_pl, explanation_ru,
|
||
explanation_uk, explanation_en
|
||
FROM wrong_because_explanations
|
||
ORDER BY wrong_because ASC
|
||
""")
|
||
|
||
return {
|
||
"items": [
|
||
{
|
||
"wrong_because": r["wrong_because"],
|
||
"explanation_pl": r["explanation_pl"] or "",
|
||
"explanation_ru": r["explanation_ru"] or "",
|
||
"explanation_uk": r["explanation_uk"] or "",
|
||
"explanation_en": r["explanation_en"] or "",
|
||
}
|
||
for r in rows
|
||
]
|
||
}
|
||
|
||
|
||
# ============ LESSONS: TREE, CREATE, DELETE, TOPIC, TEST-GENERATE ============
|
||
|
||
@router.get("/lessons/tree")
|
||
async def get_lessons_tree(
|
||
request: Request,
|
||
include_test_counts: bool = True,
|
||
):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): lessons_tree —
|
||
дерево: уровни → темы → уроки. Один запрос вместо N+1.
|
||
|
||
🔧 ОБНОВЛЕНО (04.10.2026): track_include —
|
||
каждая тема теперь содержит поле track ('pl' / 'ru_uk' / 'en').
|
||
|
||
Возвращает:
|
||
{
|
||
"levels": [
|
||
{
|
||
"code": "A1",
|
||
"name_ru": "...",
|
||
"name_pl": "...",
|
||
"topics_count": 2,
|
||
"lessons_count": 20,
|
||
"topics": [
|
||
{
|
||
"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": [...]
|
||
}
|
||
]
|
||
}
|
||
]
|
||
}
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
# Уровни
|
||
levels = await conn.fetch("""
|
||
SELECT code, name_pl, name_ru, name_uk, name_en, sort_order
|
||
FROM learning_levels
|
||
WHERE is_active = TRUE
|
||
ORDER BY sort_order
|
||
""")
|
||
|
||
if not levels:
|
||
return {"levels": []}
|
||
|
||
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, track,
|
||
name_pl, name_ru, name_uk, name_en
|
||
FROM learning_topics
|
||
WHERE level_code = ANY($1::text[]) AND is_active = TRUE
|
||
ORDER BY level_code, order_number
|
||
""", level_codes)
|
||
|
||
if not topics:
|
||
result = []
|
||
for lvl in levels:
|
||
result.append({
|
||
"code": lvl["code"],
|
||
"name_pl": lvl["name_pl"],
|
||
"name_ru": lvl["name_ru"],
|
||
"name_uk": lvl["name_uk"],
|
||
"name_en": lvl["name_en"],
|
||
"topics_count": 0,
|
||
"lessons_count": 0,
|
||
"topics": [],
|
||
})
|
||
return {"levels": result}
|
||
|
||
topic_ids = [t["topic_id"] for t in topics]
|
||
|
||
# Уроки (одним запросом)
|
||
lessons = await conn.fetch("""
|
||
SELECT lesson_id, topic_id, order_number, skill_tag,
|
||
title_pl, title_ru, title_uk, title_en,
|
||
is_active
|
||
FROM learning_lessons
|
||
WHERE topic_id = ANY($1::text[]) AND is_active = TRUE
|
||
ORDER BY topic_id, order_number
|
||
""", topic_ids)
|
||
|
||
# Кол-во вопросов на урок (GROUP BY)
|
||
q_counts = await conn.fetch("""
|
||
SELECT lesson_id, COUNT(*) as cnt
|
||
FROM learning_questions
|
||
WHERE lesson_id = ANY($1::text[]) AND is_test_question = FALSE
|
||
GROUP BY lesson_id
|
||
""", [les["lesson_id"] for les in lessons])
|
||
q_count_map = {r["lesson_id"]: r["cnt"] for r in q_counts}
|
||
|
||
# Кол-во тестовых вопросов на тему
|
||
test_counts = await conn.fetch("""
|
||
SELECT topic_id, COUNT(*) as cnt
|
||
FROM learning_questions
|
||
WHERE topic_id = ANY($1::text[]) AND is_test_question = TRUE
|
||
GROUP BY topic_id
|
||
""", topic_ids)
|
||
test_count_map = {r["topic_id"]: r["cnt"] for r in test_counts}
|
||
|
||
# Группируем уроки по topic_id
|
||
lessons_by_topic: dict = {}
|
||
for les in lessons:
|
||
lessons_by_topic.setdefault(les["topic_id"], []).append({
|
||
"lesson_id": les["lesson_id"],
|
||
"order_number": les["order_number"],
|
||
"skill_tag": les["skill_tag"],
|
||
"title_pl": les["title_pl"] or "",
|
||
"title_ru": les["title_ru"] or "",
|
||
"title_uk": les["title_uk"] or "",
|
||
"title_en": les["title_en"] or "",
|
||
"questions_count": q_count_map.get(les["lesson_id"], 0),
|
||
"is_active": les["is_active"],
|
||
})
|
||
|
||
# Группируем темы по level_code
|
||
topics_by_level: dict = {}
|
||
for t in topics:
|
||
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"],
|
||
"name_en": t["name_en"],
|
||
"lessons_count": len(lessons_by_topic.get(t["topic_id"], [])),
|
||
"test_questions_count": test_count_map.get(t["topic_id"], 0),
|
||
"lessons": lessons_by_topic.get(t["topic_id"], []),
|
||
})
|
||
|
||
# Финальный результат
|
||
result = []
|
||
for lvl in levels:
|
||
lvl_topics = topics_by_level.get(lvl["code"], [])
|
||
total_lessons = sum(t["lessons_count"] for t in lvl_topics)
|
||
result.append({
|
||
"code": lvl["code"],
|
||
"name_pl": lvl["name_pl"],
|
||
"name_ru": lvl["name_ru"],
|
||
"name_uk": lvl["name_uk"],
|
||
"name_en": lvl["name_en"],
|
||
"topics_count": len(lvl_topics),
|
||
"lessons_count": total_lessons,
|
||
"topics": lvl_topics,
|
||
})
|
||
|
||
return {"levels": result}
|
||
|
||
|
||
@router.post("/lessons/topic")
|
||
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}_{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()
|
||
name_en = (body.get("name_en") or "").strip()
|
||
|
||
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_ru_uk_greetings
|
||
import re as _re
|
||
slug = name_pl.lower()
|
||
# Транслитерация польских букв
|
||
translit = {
|
||
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n',
|
||
'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
|
||
}
|
||
for pl, lat in translit.items():
|
||
slug = slug.replace(pl, lat)
|
||
slug = _re.sub(r'[^a-z0-9]+', '_', slug).strip('_')
|
||
if not slug:
|
||
raise HTTPException(400, "Cannot generate topic_id from name_pl")
|
||
|
||
# 🔧 НОВОЕ (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:
|
||
# Проверка на дубликат
|
||
existing = await conn.fetchval(
|
||
"SELECT 1 FROM learning_topics WHERE topic_id = $1", topic_id
|
||
)
|
||
if existing:
|
||
raise HTTPException(409, f"Topic '{topic_id}' already exists")
|
||
|
||
# Следующий order_number для этого уровня
|
||
next_order = await conn.fetchval("""
|
||
SELECT COALESCE(MAX(order_number), 0) + 1
|
||
FROM learning_topics WHERE level_code = $1
|
||
""", level_code) or 1
|
||
|
||
await conn.execute("""
|
||
INSERT INTO learning_topics
|
||
(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"(track={track}) by admin {telegram_id}"
|
||
)
|
||
|
||
return {
|
||
"status": "ok",
|
||
"topic_id": topic_id,
|
||
"order_number": next_order,
|
||
"track": track,
|
||
}
|
||
|
||
|
||
@router.post("/lessons/lesson")
|
||
async def create_lesson(request: Request):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): create_lesson —
|
||
создание урока с вопросами и опциями одной транзакцией.
|
||
|
||
Тело:
|
||
{
|
||
"topic_id": "a1_greetings",
|
||
"skill_tag": "podstawowe_powitania",
|
||
"title_pl": "...", "title_ru": "...", "title_uk": "...", "title_en": "...",
|
||
"explanation_pl": "...", "explanation_ru": "...", "explanation_uk": "...", "explanation_en": "...",
|
||
"examples": [
|
||
{"text_pl": "...", "text_ru": "...", "text_uk": "...", "text_en": "..."}
|
||
],
|
||
"questions": [
|
||
{
|
||
"question_type": "recognition" | "production",
|
||
"prompt_pl": "...", "prompt_ru": "...", "prompt_uk": "...", "prompt_en": "...",
|
||
"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},
|
||
...
|
||
]
|
||
}
|
||
]
|
||
}
|
||
|
||
lesson_id генерируется: {topic_id}_l{order:02d}.
|
||
question_id: {lesson_id}_q{n}.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
topic_id = (body.get("topic_id") or "").strip()
|
||
skill_tag = (body.get("skill_tag") or "").strip()
|
||
|
||
if not topic_id:
|
||
raise HTTPException(400, "topic_id is required")
|
||
if not skill_tag:
|
||
raise HTTPException(400, "skill_tag is required")
|
||
|
||
# Валидация skill_tag
|
||
import re as _re
|
||
if not _re.match(r'^[a-z][a-z0-9_]*$', skill_tag):
|
||
raise HTTPException(400, "skill_tag must match ^[a-z][a-z0-9_]*$")
|
||
|
||
title_pl = (body.get("title_pl") or "").strip()
|
||
title_ru = (body.get("title_ru") or "").strip()
|
||
title_uk = (body.get("title_uk") or "").strip()
|
||
title_en = (body.get("title_en") or "").strip()
|
||
|
||
if not title_pl:
|
||
raise HTTPException(400, "title_pl is required")
|
||
if not title_ru:
|
||
raise HTTPException(400, "title_ru is required")
|
||
|
||
explanation_pl = (body.get("explanation_pl") or "").strip()
|
||
explanation_ru = (body.get("explanation_ru") or "").strip()
|
||
explanation_uk = (body.get("explanation_uk") or "").strip()
|
||
explanation_en = (body.get("explanation_en") or "").strip()
|
||
|
||
examples_raw = body.get("examples") or []
|
||
examples = []
|
||
for ex in examples_raw:
|
||
text_pl = (ex.get("text_pl") or "").strip()
|
||
if not text_pl:
|
||
continue
|
||
examples.append({
|
||
"text_pl": text_pl,
|
||
"text_ru": (ex.get("text_ru") or "").strip(),
|
||
"text_uk": (ex.get("text_uk") or "").strip(),
|
||
"text_en": (ex.get("text_en") or "").strip(),
|
||
})
|
||
|
||
questions_raw = body.get("questions") or []
|
||
if not isinstance(questions_raw, list):
|
||
raise HTTPException(400, "questions must be a list")
|
||
|
||
# Валидация вопросов
|
||
questions = []
|
||
for q in questions_raw:
|
||
prompt_pl = (q.get("prompt_pl") or "").strip()
|
||
if not prompt_pl:
|
||
raise HTTPException(400, "prompt_pl is required for every question")
|
||
|
||
q_type = (q.get("question_type") or "recognition").strip()
|
||
if q_type not in ("recognition", "production"):
|
||
raise HTTPException(400, f"Invalid question_type: {q_type}")
|
||
|
||
options_raw = q.get("options") or []
|
||
if q_type == "recognition":
|
||
if len(options_raw) < 2:
|
||
raise HTTPException(400, "Recognition needs at least 2 options")
|
||
correct_count = sum(1 for o in options_raw if o.get("is_correct") is True)
|
||
if correct_count != 1:
|
||
raise HTTPException(
|
||
400,
|
||
f"Exactly one option must be is_correct=true (got {correct_count})"
|
||
)
|
||
else: # production
|
||
if not options_raw or not options_raw[0].get("text_pl"):
|
||
raise HTTPException(400, "Production needs at least 1 correct answer")
|
||
|
||
options = []
|
||
correct_answer = None
|
||
for idx, o in enumerate(options_raw):
|
||
option_key = chr(ord('A') + idx)
|
||
text_pl_opt = (o.get("text_pl") or "").strip()
|
||
if not text_pl_opt:
|
||
raise HTTPException(400, f"Option {option_key}: text_pl is required")
|
||
|
||
is_correct = bool(o.get("is_correct"))
|
||
if is_correct:
|
||
correct_answer = option_key
|
||
|
||
wrong_because = o.get("wrong_because")
|
||
if is_correct:
|
||
wrong_because = None
|
||
elif not wrong_because:
|
||
# 🔧 wrong_because обязателен для неправильных
|
||
raise HTTPException(
|
||
400,
|
||
f"Option {option_key}: wrong_because is required for wrong options"
|
||
)
|
||
|
||
options.append({
|
||
"option_key": option_key,
|
||
"text_pl": text_pl_opt,
|
||
"text_ru": (o.get("text_ru") or "").strip(),
|
||
"text_uk": (o.get("text_uk") or "").strip(),
|
||
"text_en": (o.get("text_en") or "").strip(),
|
||
"is_correct": is_correct,
|
||
"wrong_because": wrong_because,
|
||
})
|
||
|
||
difficulty = int(q.get("difficulty") or 1)
|
||
if difficulty < 1 or difficulty > 3:
|
||
difficulty = 1
|
||
|
||
hint_type = q.get("hint_type") or None
|
||
hint_value = q.get("hint_value") or None
|
||
if hint_type:
|
||
hint_type = str(hint_type).strip() or None
|
||
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,
|
||
"prompt_ru": (q.get("prompt_ru") or "").strip(),
|
||
"prompt_uk": (q.get("prompt_uk") or "").strip(),
|
||
"prompt_en": (q.get("prompt_en") or "").strip(),
|
||
"correct_answer": correct_answer,
|
||
"difficulty": difficulty,
|
||
"hint_type": hint_type,
|
||
"hint_value": hint_value,
|
||
"options_language": options_language, # 🔧 НОВОЕ
|
||
"options": options,
|
||
})
|
||
|
||
# ============ Транзакция ============
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
async with conn.transaction():
|
||
# Проверка темы
|
||
topic = await conn.fetchrow("""
|
||
SELECT topic_id, level_code FROM learning_topics WHERE topic_id = $1
|
||
""", topic_id)
|
||
if not topic:
|
||
raise HTTPException(404, f"Topic '{topic_id}' not found")
|
||
|
||
# Следующий order_number
|
||
next_order = await conn.fetchval("""
|
||
SELECT COALESCE(MAX(order_number), 0) + 1
|
||
FROM learning_lessons WHERE topic_id = $1
|
||
""", topic_id) or 1
|
||
|
||
# lesson_id: {topic_id}_l{order:02d}
|
||
lesson_id = f"{topic_id}_l{next_order:02d}"
|
||
|
||
# Проверка на дубликат
|
||
exists = await conn.fetchval(
|
||
"SELECT 1 FROM learning_lessons WHERE lesson_id = $1", lesson_id
|
||
)
|
||
if exists:
|
||
raise HTTPException(409, f"Lesson '{lesson_id}' already exists")
|
||
|
||
# 1. INSERT learning_lessons
|
||
await conn.execute("""
|
||
INSERT INTO learning_lessons
|
||
(lesson_id, topic_id, order_number, skill_tag,
|
||
title_pl, title_ru, title_uk, title_en,
|
||
explanation_pl, explanation_ru, explanation_uk, explanation_en,
|
||
is_active, edited_at)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, TRUE, NOW())
|
||
""",
|
||
lesson_id, topic_id, next_order, skill_tag,
|
||
title_pl, title_ru, title_uk, title_en,
|
||
explanation_pl, explanation_ru, explanation_uk, explanation_en,
|
||
)
|
||
|
||
# 2. INSERT lesson_examples
|
||
for idx, ex in enumerate(examples, start=1):
|
||
await conn.execute("""
|
||
INSERT INTO lesson_examples
|
||
(lesson_id, order_number, text_pl, text_ru, text_uk, text_en)
|
||
VALUES ($1, $2, $3, $4, $5, $6)
|
||
""",
|
||
lesson_id, idx,
|
||
ex["text_pl"], ex["text_ru"], ex["text_uk"], ex["text_en"],
|
||
)
|
||
|
||
# 3. INSERT learning_questions + question_options
|
||
for idx, q in enumerate(questions, start=1):
|
||
question_id = f"{lesson_id}_q{idx}"
|
||
|
||
await conn.execute("""
|
||
INSERT INTO learning_questions
|
||
(question_id, lesson_id, topic_id, context_type, question_type,
|
||
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, $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"]:
|
||
await conn.execute("""
|
||
INSERT INTO question_options
|
||
(question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||
""",
|
||
question_id, o["option_key"],
|
||
o["text_pl"], o["text_ru"], o["text_uk"], o["text_en"],
|
||
o["is_correct"], o["wrong_because"],
|
||
)
|
||
|
||
logger.info(
|
||
f"[admin_content] lesson created: '{lesson_id}' in topic '{topic_id}' "
|
||
f"({len(questions)} questions) by admin {telegram_id}"
|
||
)
|
||
|
||
return {
|
||
"status": "ok",
|
||
"lesson_id": lesson_id,
|
||
"order_number": next_order,
|
||
"questions_count": len(questions),
|
||
}
|
||
|
||
|
||
@router.delete("/lessons/lesson/{lesson_id}")
|
||
async def delete_lesson(request: Request, lesson_id: str):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): delete_lesson —
|
||
удаление урока с каскадом (примеры, вопросы, опции).
|
||
|
||
⚠️ CASCADE должен быть в схеме БД:
|
||
learning_questions.lesson_id REFERENCES learning_lessons(lesson_id)
|
||
lesson_examples.lesson_id REFERENCES learning_lessons(lesson_id)
|
||
Если CASCADE нет — удаляем вручную.
|
||
"""
|
||
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_lessons WHERE lesson_id = $1", lesson_id
|
||
)
|
||
if not exists:
|
||
raise HTTPException(404, "Lesson not found")
|
||
|
||
# Удаляем опции вопросов
|
||
await conn.execute("""
|
||
DELETE FROM question_options
|
||
WHERE question_id IN (
|
||
SELECT question_id FROM learning_questions WHERE lesson_id = $1
|
||
)
|
||
""", lesson_id)
|
||
|
||
# Удаляем вопросы
|
||
await conn.execute(
|
||
"DELETE FROM learning_questions WHERE lesson_id = $1", lesson_id
|
||
)
|
||
|
||
# Удаляем примеры
|
||
await conn.execute(
|
||
"DELETE FROM lesson_examples WHERE lesson_id = $1", lesson_id
|
||
)
|
||
|
||
# Удаляем сам урок
|
||
await conn.execute(
|
||
"DELETE FROM learning_lessons WHERE lesson_id = $1", lesson_id
|
||
)
|
||
|
||
logger.info(f"[admin_content] lesson deleted: '{lesson_id}' by admin {telegram_id}")
|
||
return {"status": "ok", "lesson_id": lesson_id}
|
||
|
||
|
||
@router.get("/lessons/topic/{topic_id}/questions")
|
||
async def get_topic_questions_for_test(request: Request, topic_id: str):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): get_topic_questions_for_test —
|
||
все вопросы уроков темы для генератора теста.
|
||
|
||
Возвращает список вопросов с опциями, сгруппированных по урокам.
|
||
Используется в TestGeneratorModal для мультивыбора.
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
# Вопросы уроков этой темы (is_test_question=FALSE)
|
||
questions = await conn.fetch("""
|
||
SELECT q.question_id, q.lesson_id, q.question_type, q.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,
|
||
l.title_ru AS lesson_title_ru,
|
||
l.title_pl AS lesson_title_pl,
|
||
l.order_number AS lesson_order
|
||
FROM learning_questions q
|
||
JOIN learning_lessons l ON l.lesson_id = q.lesson_id
|
||
WHERE q.topic_id = $1 AND q.is_test_question = FALSE
|
||
ORDER BY l.order_number, q.question_id
|
||
""", topic_id)
|
||
|
||
if not questions:
|
||
return {
|
||
"topic_id": topic_id,
|
||
"total": 0,
|
||
"lessons": [],
|
||
}
|
||
|
||
question_ids = [q["question_id"] for q in questions]
|
||
|
||
# Опции одним запросом
|
||
options_rows = await conn.fetch("""
|
||
SELECT question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because
|
||
FROM question_options
|
||
WHERE question_id = ANY($1::text[])
|
||
ORDER BY question_id, option_key
|
||
""", question_ids)
|
||
|
||
options_by_q: dict = {}
|
||
for o in options_rows:
|
||
options_by_q.setdefault(o["question_id"], []).append({
|
||
"option_key": o["option_key"],
|
||
"text_pl": o["text_pl"] or "",
|
||
"text_ru": o["text_ru"] or "",
|
||
"text_uk": o["text_uk"] or "",
|
||
"text_en": o["text_en"] or "",
|
||
"is_correct": o["is_correct"],
|
||
"wrong_because": o["wrong_because"],
|
||
})
|
||
|
||
# Группируем вопросы по урокам
|
||
lessons_map: dict = {}
|
||
for q in questions:
|
||
lid = q["lesson_id"]
|
||
if lid not in lessons_map:
|
||
lessons_map[lid] = {
|
||
"lesson_id": lid,
|
||
"lesson_order": q["lesson_order"],
|
||
"title_pl": q["lesson_title_pl"] or "",
|
||
"title_ru": q["lesson_title_ru"] or "",
|
||
"questions": [],
|
||
}
|
||
lessons_map[lid]["questions"].append({
|
||
"question_id": q["question_id"],
|
||
"question_type": q["question_type"],
|
||
"skill_tag": q["skill_tag"],
|
||
"difficulty": q["difficulty"],
|
||
"prompt_pl": q["prompt_pl"] or "",
|
||
"prompt_ru": q["prompt_ru"] or "",
|
||
"prompt_uk": q["prompt_uk"] or "",
|
||
"prompt_en": q["prompt_en"] or "",
|
||
"correct_answer": q["correct_answer"] or "",
|
||
"hint_type": q["hint_type"],
|
||
"hint_value": q["hint_value"],
|
||
"options": options_by_q.get(q["question_id"], []),
|
||
})
|
||
|
||
lessons_list = sorted(lessons_map.values(), key=lambda x: x["lesson_order"])
|
||
|
||
return {
|
||
"topic_id": topic_id,
|
||
"total": len(questions),
|
||
"lessons": lessons_list,
|
||
}
|
||
|
||
|
||
@router.post("/lessons/test/generate")
|
||
async def generate_topic_test(request: Request):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): generate_topic_test —
|
||
генерирует тест темы из выбранных вопросов уроков.
|
||
|
||
Тело:
|
||
{
|
||
"topic_id": "a1_greetings",
|
||
"question_ids": ["a1_greetings_l01_q1", "a1_greetings_l01_q2", ...],
|
||
"replace_existing": true — удалить старые тестовые вопросы темы
|
||
}
|
||
|
||
Логика:
|
||
1. Если replace_existing=true → удалить все существующие
|
||
тестовые вопросы темы (is_test_question=TRUE).
|
||
2. Для каждого выбранного question_id — создать КОПИЮ:
|
||
- новый question_id: {topic_id}_t{N}
|
||
- is_test_question=TRUE, test_order=N
|
||
- context_type='topic_test'
|
||
- prompt и correct_answer скопированы
|
||
- опции скопированы с ПЕРЕМЕШАННЫМИ option_key
|
||
3. Вернуть: {test_id_prefix, total_created}
|
||
"""
|
||
import random as _random
|
||
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
topic_id = (body.get("topic_id") or "").strip()
|
||
question_ids = body.get("question_ids") or []
|
||
replace_existing = bool(body.get("replace_existing", True))
|
||
|
||
if not topic_id:
|
||
raise HTTPException(400, "topic_id is required")
|
||
if not isinstance(question_ids, list) or len(question_ids) == 0:
|
||
raise HTTPException(400, "question_ids must be a non-empty list")
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
async with conn.transaction():
|
||
# Проверка темы
|
||
topic = await conn.fetchrow("""
|
||
SELECT topic_id, level_code FROM learning_topics WHERE topic_id = $1
|
||
""", topic_id)
|
||
if not topic:
|
||
raise HTTPException(404, f"Topic '{topic_id}' not found")
|
||
|
||
# Удаляем старые тестовые вопросы темы (если replace)
|
||
if replace_existing:
|
||
old_ids_rows = await conn.fetch("""
|
||
SELECT question_id FROM learning_questions
|
||
WHERE topic_id = $1 AND is_test_question = TRUE
|
||
""", topic_id)
|
||
old_ids = [r["question_id"] for r in old_ids_rows]
|
||
|
||
if old_ids:
|
||
await conn.execute("""
|
||
DELETE FROM question_options WHERE question_id = ANY($1::text[])
|
||
""", old_ids)
|
||
await conn.execute("""
|
||
DELETE FROM learning_questions WHERE question_id = ANY($1::text[])
|
||
""", old_ids)
|
||
logger.info(f"[test_generate] deleted {len(old_ids)} old test questions")
|
||
|
||
# Загружаем выбранные вопросы + опции
|
||
questions = await conn.fetch("""
|
||
SELECT question_id, lesson_id, question_type, skill_tag, difficulty,
|
||
prompt_pl, prompt_ru, prompt_uk, prompt_en,
|
||
correct_answer, hint_type, hint_value, options_language
|
||
FROM learning_questions
|
||
WHERE question_id = ANY($1::text[]) AND topic_id = $2
|
||
""", question_ids, topic_id)
|
||
|
||
if not questions:
|
||
raise HTTPException(404, "No questions found for the given IDs")
|
||
|
||
# Проверка: все запрошенные вопросы существуют
|
||
found_ids = {q["question_id"] for q in questions}
|
||
missing = set(question_ids) - found_ids
|
||
if missing:
|
||
raise HTTPException(
|
||
400,
|
||
f"Questions not found in topic: {sorted(missing)[:5]}"
|
||
)
|
||
|
||
# Опции для выбранных вопросов
|
||
options_rows = await conn.fetch("""
|
||
SELECT question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because
|
||
FROM question_options
|
||
WHERE question_id = ANY($1::text[])
|
||
""", list(found_ids))
|
||
|
||
options_by_q: dict = {}
|
||
for o in options_rows:
|
||
options_by_q.setdefault(o["question_id"], []).append(dict(o))
|
||
|
||
# Создаём тестовые копии
|
||
created = 0
|
||
for idx, q in enumerate(questions, start=1):
|
||
test_question_id = f"{topic_id}_t{idx:02d}"
|
||
|
||
# Проверка на дубликат
|
||
dup = await conn.fetchval(
|
||
"SELECT 1 FROM learning_questions WHERE question_id = $1",
|
||
test_question_id,
|
||
)
|
||
if dup:
|
||
raise HTTPException(
|
||
409,
|
||
f"Test question '{test_question_id}' already exists"
|
||
)
|
||
|
||
# Новый correct_answer = option_key правильного варианта ПОСЛЕ перемешивания
|
||
orig_options = options_by_q.get(q["question_id"], [])
|
||
if not orig_options:
|
||
continue
|
||
|
||
# Находим правильную опцию
|
||
orig_correct_key = None
|
||
for o in orig_options:
|
||
if o["is_correct"]:
|
||
orig_correct_key = o["option_key"]
|
||
break
|
||
|
||
if not orig_correct_key:
|
||
logger.warning(
|
||
f"[test_generate] question {q['question_id']} has no correct option, skipped"
|
||
)
|
||
continue
|
||
|
||
# Перемешиваем порядок опций
|
||
shuffled = list(orig_options)
|
||
_random.shuffle(shuffled)
|
||
|
||
# Переназначаем option_key A, B, C, D...
|
||
new_options = []
|
||
new_correct_key = None
|
||
for opt_idx, o in enumerate(shuffled):
|
||
new_key = chr(ord('A') + opt_idx)
|
||
if o["option_key"] == orig_correct_key:
|
||
new_correct_key = new_key
|
||
new_options.append({
|
||
"option_key": new_key,
|
||
"text_pl": o["text_pl"] or "",
|
||
"text_ru": o["text_ru"] or "",
|
||
"text_uk": o["text_uk"] or "",
|
||
"text_en": o["text_en"] or "",
|
||
"is_correct": o["is_correct"],
|
||
"wrong_because": o["wrong_because"] if not o["is_correct"] else None,
|
||
})
|
||
|
||
# INSERT тестового вопроса
|
||
await conn.execute("""
|
||
INSERT INTO learning_questions
|
||
(question_id, lesson_id, topic_id, context_type, question_type,
|
||
skill_tag, difficulty, prompt_pl, prompt_ru, prompt_uk, prompt_en,
|
||
correct_answer, hint_type, hint_value,
|
||
is_test_question, test_order, options_language, edited_at)
|
||
VALUES ($1, NULL, $2, 'topic_test', $3, $4, $5, $6, $7, $8, $9,
|
||
$10, $11, $12, TRUE, $13, $14, NOW())
|
||
""",
|
||
test_question_id, topic_id, q["question_type"],
|
||
q["skill_tag"], q["difficulty"],
|
||
q["prompt_pl"], q["prompt_ru"], q["prompt_uk"], q["prompt_en"],
|
||
new_correct_key, q["hint_type"], q["hint_value"],
|
||
idx, q["options_language"] or "pl",
|
||
)
|
||
|
||
for o in new_options:
|
||
await conn.execute("""
|
||
INSERT INTO question_options
|
||
(question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||
""",
|
||
test_question_id, o["option_key"],
|
||
o["text_pl"], o["text_ru"], o["text_uk"], o["text_en"],
|
||
o["is_correct"], o["wrong_because"],
|
||
)
|
||
|
||
created += 1
|
||
|
||
logger.info(
|
||
f"[admin_content] test generated for topic '{topic_id}': "
|
||
f"{created} questions by admin {telegram_id}"
|
||
)
|
||
|
||
return {
|
||
"status": "ok",
|
||
"topic_id": topic_id,
|
||
"total_created": created,
|
||
}
|
||
|
||
|
||
# ============ LESSONS: ADD QUESTION (edit-режим) ============
|
||
|
||
@router.post("/lessons/lesson/{lesson_id}/add-question")
|
||
async def add_question_to_lesson(request: Request, lesson_id: str):
|
||
"""
|
||
🔧 НОВОЕ (02.10.2026): add_question_to_lesson —
|
||
добавляет ОДИН новый вопрос в существующий урок (edit-режим).
|
||
|
||
Используется, когда админ в редакторе урока добавляет новое задание
|
||
через «+ Добавить задание». Старые вопросы обновляются через
|
||
PUT /lessons/lesson/{lesson_id}.
|
||
|
||
Тело:
|
||
{
|
||
"question_type": "recognition" | "production",
|
||
"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},
|
||
...
|
||
]
|
||
}
|
||
|
||
Возвращает: {status, question_id, order_number}
|
||
"""
|
||
telegram_id, _ = await require_auth(request)
|
||
_require_admin(telegram_id)
|
||
|
||
body = await request.json()
|
||
|
||
pool = await get_pool()
|
||
async with pool.acquire() as conn:
|
||
async with conn.transaction():
|
||
# Проверка урока
|
||
lesson = await conn.fetchrow("""
|
||
SELECT lesson_id, topic_id, skill_tag
|
||
FROM learning_lessons
|
||
WHERE lesson_id = $1
|
||
""", lesson_id)
|
||
if not lesson:
|
||
raise HTTPException(404, "Lesson not found")
|
||
|
||
topic_id = lesson["topic_id"]
|
||
skill_tag = lesson["skill_tag"]
|
||
|
||
# Валидация question_type
|
||
q_type = (body.get("question_type") or "recognition").strip()
|
||
if q_type not in ("recognition", "production"):
|
||
raise HTTPException(400, f"Invalid question_type: {q_type}")
|
||
|
||
prompt_pl = (body.get("prompt_pl") or "").strip()
|
||
if not prompt_pl:
|
||
raise HTTPException(400, "prompt_pl is required")
|
||
|
||
difficulty = int(body.get("difficulty") or 1)
|
||
if difficulty < 1 or difficulty > 3:
|
||
difficulty = 1
|
||
|
||
hint_type = body.get("hint_type")
|
||
if hint_type:
|
||
hint_type = str(hint_type).strip() or None
|
||
hint_value = body.get("hint_value")
|
||
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:
|
||
raise HTTPException(400, "At least one option is required")
|
||
|
||
correct_count = sum(1 for o in options_raw if o.get("is_correct") is True)
|
||
if correct_count != 1:
|
||
raise HTTPException(
|
||
400,
|
||
f"Exactly one option must be is_correct=true (got {correct_count})"
|
||
)
|
||
|
||
# Следующий номер вопроса
|
||
# Формат: {lesson_id}_q{N}, где N — последний + 1.
|
||
# Ищем существующие вопросы урока и парсим числовой суффикс.
|
||
existing_q = await conn.fetch("""
|
||
SELECT question_id FROM learning_questions WHERE lesson_id = $1
|
||
""", lesson_id)
|
||
|
||
max_n = 0
|
||
for r in existing_q:
|
||
qid = r["question_id"]
|
||
# qid = "a1_greetings_l01_q3"
|
||
parts = qid.rsplit("_q", 1)
|
||
if len(parts) == 2:
|
||
try:
|
||
n = int(parts[1])
|
||
if n > max_n:
|
||
max_n = n
|
||
except ValueError:
|
||
pass
|
||
|
||
next_n = max_n + 1
|
||
question_id = f"{lesson_id}_q{next_n}"
|
||
|
||
# Генерируем options (A, B, C, D...)
|
||
new_options = []
|
||
correct_answer = None
|
||
for idx, o in enumerate(options_raw):
|
||
option_key = chr(ord('A') + idx)
|
||
text_pl_opt = (o.get("text_pl") or "").strip()
|
||
if not text_pl_opt:
|
||
raise HTTPException(400, f"Option {option_key}: text_pl is required")
|
||
|
||
is_correct = bool(o.get("is_correct"))
|
||
if is_correct:
|
||
correct_answer = option_key
|
||
|
||
wrong_because = o.get("wrong_because")
|
||
if is_correct:
|
||
wrong_because = None
|
||
elif not wrong_because:
|
||
raise HTTPException(
|
||
400,
|
||
f"Option {option_key}: wrong_because is required for wrong options"
|
||
)
|
||
|
||
new_options.append({
|
||
"option_key": option_key,
|
||
"text_pl": text_pl_opt,
|
||
"text_ru": (o.get("text_ru") or "").strip(),
|
||
"text_uk": (o.get("text_uk") or "").strip(),
|
||
"text_en": (o.get("text_en") or "").strip(),
|
||
"is_correct": is_correct,
|
||
"wrong_because": wrong_because,
|
||
})
|
||
|
||
# INSERT question
|
||
await conn.execute("""
|
||
INSERT INTO learning_questions
|
||
(question_id, lesson_id, topic_id, context_type, question_type,
|
||
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, $14, NOW())
|
||
""",
|
||
question_id, lesson_id, topic_id, q_type,
|
||
skill_tag, difficulty,
|
||
prompt_pl,
|
||
(body.get("prompt_ru") or "").strip(),
|
||
(body.get("prompt_uk") or "").strip(),
|
||
(body.get("prompt_en") or "").strip(),
|
||
correct_answer, hint_type, hint_value,
|
||
options_language,
|
||
)
|
||
|
||
# INSERT options
|
||
for o in new_options:
|
||
await conn.execute("""
|
||
INSERT INTO question_options
|
||
(question_id, option_key, text_pl, text_ru, text_uk, text_en,
|
||
is_correct, wrong_because)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||
""",
|
||
question_id, o["option_key"],
|
||
o["text_pl"], o["text_ru"], o["text_uk"], o["text_en"],
|
||
o["is_correct"], o["wrong_because"],
|
||
)
|
||
|
||
logger.info(
|
||
f"[admin_content] question added: '{question_id}' to lesson '{lesson_id}' "
|
||
f"by admin {telegram_id}"
|
||
)
|
||
|
||
return {
|
||
"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} |