From 98ac40367572d0c1451a2245d29832000ddcd913 Mon Sep 17 00:00:00 2001 From: Drobysh Date: Fri, 2 Oct 2026 12:47:56 +0000 Subject: [PATCH] =?UTF-8?q?feat(admin):=20=D1=83=D1=80=D0=BE=D0=BA=D0=B8?= =?UTF-8?q?=20+=20AI-=D0=BF=D0=BE=D0=BC=D0=BE=D1=89=D0=BD=D0=B8=D0=BA=20+?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8B=20+=20=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D1=91=D1=82=20=D0=BF=D0=BE=20=D1=82=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backend: - admin_ai.py: POST /admin/ai/chat + /admin/ai/translate (DeepSeek V4 Pro 0813) * rate limit 60/час, reasoning отключён, context support * перевод на 4 языка через JSON mode - admin_content.py: CRUD уроков/тем + генератор теста * GET /lessons/tree — дерево уровней/тем/уроков * POST /lessons/topic — создание темы * POST /lessons/lesson — создание урока (транзакция) * DELETE /lessons/lesson/{id} — каскадное удаление * GET /lessons/topic/{id}/questions — вопросы для генератора * POST /lessons/test/generate — генерация теста с перемешиванием * POST /lessons/lesson/{id}/add-question — добавление вопроса в edit-режиме - learning.py: attempt_number + revised + revision_of_id * show_correct_answer с 3-й попытки * session/complete возвращает report (percent, message, weak_skills, next_topic) - learning_data/__init__.py: seed только при пустой БД * SEED_LEARNING_DATA=true для принудительной перезаливки - main.py: подключение admin_ai router - database.py: миграция revised + revision_of_id --- database.py | 38 ++ main.py | 2 + routers/admin_ai.py | 322 +++++++++ routers/admin_content.py | 1036 ++++++++++++++++++++++++++++- routers/learning.py | 359 ++++++++-- routers/learning_data/__init__.py | 49 +- 6 files changed, 1755 insertions(+), 51 deletions(-) create mode 100644 routers/admin_ai.py diff --git a/database.py b/database.py index 69b47fe..b9e24f7 100644 --- a/database.py +++ b/database.py @@ -467,6 +467,8 @@ async def init_db(): """) # ============ user_learning_answers ============ + # 🔧 ОБНОВЛЕНО (02.10.2026): добавлены revised и revision_of_id + # прямо в определение — на свежих БД создаются сразу. await conn.execute(""" CREATE TABLE IF NOT EXISTS user_learning_answers ( id BIGSERIAL PRIMARY KEY, @@ -487,10 +489,46 @@ async def init_db(): hint_used BOOLEAN DEFAULT FALSE, wrong_because VARCHAR(100), is_final_answer BOOLEAN DEFAULT TRUE, + revised BOOLEAN DEFAULT FALSE, -- 🔧 НОВОЕ + revision_of_id BIGINT, -- 🔧 НОВОЕ created_at TIMESTAMP DEFAULT NOW() ) """) + # 🔧 НОВОЕ (02.10.2026): revised — фиксируем, что ученик + # поменял ответ после «Повторить урок». + col_exists = await conn.fetchval(""" + SELECT 1 FROM information_schema.columns + WHERE table_name = 'user_learning_answers' AND column_name = 'revised' + """) + if not col_exists: + await conn.execute(""" + ALTER TABLE user_learning_answers + ADD COLUMN revised BOOLEAN DEFAULT FALSE + """) + logger.info("Added revised column to user_learning_answers") + + # 🔧 НОВОЕ (02.10.2026): revision_of_id — ссылка на предыдущий + # ответ этого же вопроса в этой же сессии. Позволяет строить + # цепочку: первый ответ → второй (после повтора) → третий. + col_exists = await conn.fetchval(""" + SELECT 1 FROM information_schema.columns + WHERE table_name = 'user_learning_answers' AND column_name = 'revision_of_id' + """) + if not col_exists: + await conn.execute(""" + ALTER TABLE user_learning_answers + ADD COLUMN revision_of_id BIGINT + """) + logger.info("Added revision_of_id column to user_learning_answers") + + # Индекс для быстрого поиска цепочек повторов + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_learning_answers_revision + ON user_learning_answers(revision_of_id) + WHERE revision_of_id IS NOT NULL + """) + # ============ user_lesson_progress ============ await conn.execute(""" CREATE TABLE IF NOT EXISTS user_lesson_progress ( diff --git a/main.py b/main.py index 55bff5e..48cf082 100644 --- a/main.py +++ b/main.py @@ -15,6 +15,7 @@ from config import FRONTEND_ORIGINS, UPLOADS_DIR, CF_IPS from database import init_db from routers import users, game, hints, leaderboard, sentences, achievements, wordquiz, bubblewords, pronunciation, assistant, learning, tts, typing, teacher, support, admin, feed, admin_content from routers import lectures, admin_auth, admin_wordsearch, admin_users +from routers import admin_ai # 🔧 НОВОЕ from routers.sentences import init_sentences from routers.achievements import init_achievements from routers.learning_data import init_learning_data @@ -370,6 +371,7 @@ app.include_router(lectures.router) app.include_router(admin_auth.router) app.include_router(admin_wordsearch.router) app.include_router(admin_users.router) +app.include_router(admin_ai.router) # 🔧 НОВОЕ # ============ Базовые эндпоинты ============ diff --git a/routers/admin_ai.py b/routers/admin_ai.py new file mode 100644 index 0000000..5dfc9b2 --- /dev/null +++ b/routers/admin_ai.py @@ -0,0 +1,322 @@ +""" +Admin AI Router — универсальный AI-помощник в админке. + +🔧 НОВОЕ (02.10.2026): floating AI widget в admin frontend. + +Использует DeepSeek V4 Pro 0813 через Together AI: +- Модель: deepseek-ai/DeepSeek-V4-Pro-0813 +- Reasoning: отключён для скорости (можно включить через body) +- Rate limit: 60 запросов/час на админа +""" +import logging +import time +from collections import defaultdict +from typing import Optional + +import httpx +from fastapi import APIRouter, Request, HTTPException +from auth import require_auth +from config import TOGETHER_API_KEY, ADMIN_IDS + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/admin/ai", tags=["admin-ai"]) + +TOGETHER_API_URL = "https://api.together.xyz/v1/chat/completions" + +# 🔧 НОВОЕ (02.10.2026): DeepSeek V4 Pro — flagship, 1M контекст, 30+ языков +DEFAULT_MODEL = "deepseek-ai/DeepSeek-V4-Pro-0813" + +# In-memory rate limit (60/час на юзера) +_admin_ai_usage: dict[int, list[float]] = defaultdict(list) +_ADMIN_AI_RATE_LIMIT = 60 +_ADMIN_AI_RATE_WINDOW = 3600 # 1 час + + +DEFAULT_SYSTEM_PROMPT = """Ты — помощник преподавателя польского языка в приложении Filwords PL (Telegram Mini App для изучения польского). + +Помогаешь создавать учебный контент: +- Задания для уроков (recognition — выбор варианта A/B/C/D) +- Дистракторы (неправильные, но похожие по смыслу варианты) +- Переводы на польский, русский, украинский, английский +- Грамматические пояснения + +ПРАВИЛА: +1. Отвечай на языке пользователя (по умолчанию — русский). +2. Не используй markdown. Просто текст. +3. Для заданий-recognition: дай РОВНО 4 варианта (A, B, C, D). +4. Один вариант — правильный (отметь явно). +5. Три других — похожие по смыслу (та же часть речи, тот же контекст). +6. Указывай wrong_because для неправильных: wrong_word, wrong_case, wrong_context, wrong_gender, wrong_sentence_type, wrong_translation. +7. Если просят перевод — дай на все 4 языка (PL, RU, UK, EN). +8. Если просят контекст из БД — используй его, не выдумывай.""" + + +def _check_rate_limit(user_id: int) -> bool: + """Проверка: не превысил ли админ лимит.""" + now = time.time() + # Чистим старые записи + _admin_ai_usage[user_id] = [ + t for t in _admin_ai_usage[user_id] + if now - t < _ADMIN_AI_RATE_WINDOW + ] + return len(_admin_ai_usage[user_id]) < _ADMIN_AI_RATE_LIMIT + + +def _increment_usage(user_id: int) -> None: + _admin_ai_usage[user_id].append(time.time()) + + +@router.post("/chat") +async def admin_ai_chat(request: Request): + """ + 🔧 НОВОЕ (02.10.2026): admin_ai_chat — + универсальный AI-помощник в админке. + + Тело: + { + "message": "Придумай 4 варианта к заданию: ...", + "system_prompt": "опционально, переопределить дефолт", + "model": "deepseek-ai/DeepSeek-V4-Pro-0813", // опционально + "reasoning": false, // опционально, по умолчанию false + "context": "опционально, длинный контекст" // например, вся тема целиком + } + + Возвращает: + { + "response": "...", + "model_used": "deepseek-ai/DeepSeek-V4-Pro-0813", + "tokens_used": 123 + } + """ + telegram_id, _ = await require_auth(request) + + if telegram_id not in ADMIN_IDS: + raise HTTPException(403, "Access denied") + + if not _check_rate_limit(telegram_id): + raise HTTPException(429, f"Rate limit exceeded ({_ADMIN_AI_RATE_LIMIT}/hour)") + + if not TOGETHER_API_KEY: + raise HTTPException(500, "TOGETHER_API_KEY not configured") + + body = await request.json() + message = (body.get("message") or "").strip() + system_prompt = (body.get("system_prompt") or "").strip() or DEFAULT_SYSTEM_PROMPT + model = (body.get("model") or "").strip() or DEFAULT_MODEL + reasoning_enabled = bool(body.get("reasoning", False)) + context = (body.get("context") or "").strip() + + if not message: + raise HTTPException(400, "message is required") + + if len(message) > 4000: + raise HTTPException(400, "message too long (max 4000)") + + # Собираем user content: context + message + user_content = message + if context: + user_content = f"Контекст из БД:\n{context}\n\nЗадача:\n{message}" + + # Отправляем в Together + try: + async with httpx.AsyncClient(timeout=120.0) as client: + response = await client.post( + TOGETHER_API_URL, + headers={ + "Authorization": f"Bearer {TOGETHER_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": model, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_content}, + ], + "max_tokens": 2000, + "temperature": 1.0, # 🔧 DeepSeek рекомендует 1.0 + "reasoning": {"enabled": reasoning_enabled}, + }, + ) + except httpx.TimeoutException: + raise HTTPException(504, "AI timeout (120s)") + + if response.status_code != 200: + logger.error(f"[admin_ai] Together error: {response.status_code} {response.text[:300]}") + raise HTTPException(500, f"AI error: {response.status_code}") + + data = response.json() + + # Извлекаем ответ + try: + message_obj = data["choices"][0]["message"] + ai_response = message_obj.get("content") or message_obj.get("reasoning_content") or "" + except (KeyError, IndexError, TypeError) as e: + logger.error(f"[admin_ai] parse error: {e}") + raise HTTPException(500, "AI returned invalid response") + + if not ai_response: + raise HTTPException(500, "AI returned empty response") + + # Считаем токены + usage = data.get("usage", {}) + tokens_used = usage.get("total_tokens", 0) + + _increment_usage(telegram_id) + + logger.info( + f"[admin_ai] user={telegram_id} model={model} tokens={tokens_used}" + ) + + return { + "response": ai_response.strip(), + "model_used": model, + "tokens_used": tokens_used, + } + + +@router.post("/translate") +async def admin_ai_translate(request: Request): + """ + 🔧 НОВОЕ (02.10.2026): admin_ai_translate — + перевод текста на 4 языка (PL, RU, UK, EN). + + Тело: + { + "text": "Podstawowe powitania", + "source_lang": "pl", + "target_langs": ["ru", "uk", "en"] // опционально, по умолчанию все кроме source + } + + Возвращает: + { + "translations": {"ru": "...", "uk": "...", "en": "..."}, + "source_lang": "pl" + } + """ + telegram_id, _ = await require_auth(request) + + if telegram_id not in ADMIN_IDS: + raise HTTPException(403, "Access denied") + + if not _check_rate_limit(telegram_id): + raise HTTPException(429, f"Rate limit exceeded ({_ADMIN_AI_RATE_LIMIT}/hour)") + + if not TOGETHER_API_KEY: + raise HTTPException(500, "TOGETHER_API_KEY not configured") + + body = await request.json() + text = (body.get("text") or "").strip() + source_lang = (body.get("source_lang") or "pl").strip().lower() + target_langs = body.get("target_langs") or ["ru", "uk", "en"] + + if not text: + raise HTTPException(400, "text is required") + + if len(text) > 3000: + raise HTTPException(400, "text too long (max 3000)") + + if source_lang not in ("pl", "ru", "uk", "en"): + raise HTTPException(400, f"Invalid source_lang: {source_lang}") + + # Валидация target_langs + valid_langs = {"pl", "ru", "uk", "en"} + target_langs = [l for l in target_langs if l in valid_langs and l != source_lang] + + if not target_langs: + raise HTTPException(400, "No valid target_langs") + + lang_names = { + "pl": "Polish", "ru": "Russian", "uk": "Ukrainian", "en": "English", + } + + source_name = lang_names[source_lang] + targets_str = ", ".join([f'"{l}": "{lang_names[l]}"' for l in target_langs]) + + system_prompt = f"""Ты — переводчик. Переведи текст с {source_name} на указанные языки. + +Верни СТРОГО JSON (без markdown, без пояснений) в формате: +{{ + {targets_str} +}} + +ПРАВИЛА: +- Переводи ТОЧНО, сохраняя смысл и стиль. +- Для терминов и названий — используй общепринятые варианты. +- Если текст — название урока/темы, переводи как название (с заглавной буквы). +- Если текст — объяснение, сохраняй переносы строк и форматирование. +- Не добавляй ничего кроме JSON.""" + + user_prompt = f"Текст для перевода:\n{text}" + + try: + async with httpx.AsyncClient(timeout=60.0) as client: + response = await client.post( + TOGETHER_API_URL, + headers={ + "Authorization": f"Bearer {TOGETHER_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": DEFAULT_MODEL, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + "max_tokens": 1500, + "temperature": 0.3, # Для перевода — низкая + "reasoning": {"enabled": False}, + }, + ) + except httpx.TimeoutException: + raise HTTPException(504, "AI timeout") + + if response.status_code != 200: + logger.error(f"[admin_ai] translate error: {response.status_code} {response.text[:300]}") + raise HTTPException(500, f"AI error: {response.status_code}") + + data = response.json() + + try: + message_obj = data["choices"][0]["message"] + raw = (message_obj.get("content") or "").strip() + except (KeyError, IndexError, TypeError): + raise HTTPException(500, "AI returned invalid response") + + # Парсим JSON (снимаем ```json ... ``` если AI обернул) + import re as _re + import json as _json + + if raw.startswith("```"): + raw = _re.sub(r'^```(?:json)?\s*', '', raw) + raw = _re.sub(r'\s*```$', '', raw) + + json_match = _re.search(r'\{.*\}', raw, _re.DOTALL) + if not json_match: + logger.error(f"[admin_ai] no JSON in response: {raw[:200]}") + raise HTTPException(500, "AI returned no JSON") + + try: + parsed = _json.loads(json_match.group(0)) + except _json.JSONDecodeError as e: + logger.error(f"[admin_ai] JSON parse error: {e}, raw={raw[:300]}") + raise HTTPException(500, "AI returned invalid JSON") + + translations = {} + for lang in target_langs: + value = parsed.get(lang, "") + translations[lang] = str(value).strip() if value else "" + + tokens_used = data.get("usage", {}).get("total_tokens", 0) + _increment_usage(telegram_id) + + logger.info( + f"[admin_ai] translate user={telegram_id} " + f"{source_lang} → {target_langs} tokens={tokens_used}" + ) + + return { + "translations": translations, + "source_lang": source_lang, + "tokens_used": tokens_used, + } \ No newline at end of file diff --git a/routers/admin_content.py b/routers/admin_content.py index 3b015f1..5ea8411 100644 --- a/routers/admin_content.py +++ b/routers/admin_content.py @@ -50,6 +50,13 @@ Admin Content Router — контент-менеджер для редактир удаление текста из редактора. 🔧 ОБНОВЛЕНО (30.09.2026): /texts/all — пагинация + total. + +🔧 НОВОЕ (02.10.2026): 6 эндпоинтов для LessonsEditor v2 — +дерево, создание темы, создание урока, удаление урока, +вопросы темы для генератора, генератор теста. + +🔧 НОВОЕ (02.10.2026): POST /lessons/lesson/{lesson_id}/add-question — +добавление ОДНОГО нового вопроса в существующий урок (edit-режим). """ import logging import re @@ -1463,4 +1470,1031 @@ async def get_wrong_because(request: Request): } for r in rows ] - } \ No newline at end of file + } + + +# ============ 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. + + Возвращает: + { + "levels": [ + { + "code": "A1", + "name_ru": "...", + "name_pl": "...", + "topics_count": 2, + "lessons_count": 20, + "topics": [ + { + "topic_id": "a1_greetings", + "name_ru": "Приветствия", + "name_pl": "Powitania", + "order_number": 1, + "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 + } + ] + } + ] + } + ] + } + """ + 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] + + # Темы + topics = await conn.fetch(""" + SELECT topic_id, level_code, order_number, + 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"], + "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 — + создание новой темы. + + Тело: + { + "level_code": "A1", + "name_pl": "Powitania", + "name_ru": "Приветствия", + "name_uk": "Привітання", + "name_en": "Greetings" + } + + topic_id генерируется автоматически: {level}_{slug(name_pl)}. + """ + telegram_id, _ = await require_auth(request) + _require_admin(telegram_id) + + body = await request.json() + level_code = (body.get("level_code") or "").strip().upper() + 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 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 + 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") + + topic_id = f"{level_code.lower()}_{slug[:50]}" + + 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, 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) + + logger.info( + f"[admin_content] topic created: '{topic_id}' in {level_code} " + f"by admin {telegram_id}" + ) + + return { + "status": "ok", + "topic_id": topic_id, + "order_number": next_order, + } + + +@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": [ + {"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 + + 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": 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, 'pl', 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"], + ) + + 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": [ + {"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 + + # Валидация 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, 'pl', 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, + ) + + # 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, + } \ No newline at end of file diff --git a/routers/learning.py b/routers/learning.py index 051a0b6..7f6339e 100644 --- a/routers/learning.py +++ b/routers/learning.py @@ -594,9 +594,29 @@ async def start_session(request: Request): return {"session_id": row["id"]} +# 🔧 ОБНОВЛЕНО (02.10.2026): attempt_number + revised — +# если ученик отвечает на вопрос повторно (после «Повторить урок»), +# создаётся НОВАЯ запись с attempt_number+1, revised=TRUE, +# revision_of_id=предыдущий ответ. История сохраняется полностью. @router.post("/answer") async def save_answer(request: Request): - """Сохранить ответ пользователя""" + """ + Сохранить ответ пользователя. + + 🔧 ОБНОВЛЕНО (02.10.2026): attempt_number + revised — + если ученик отвечает на вопрос повторно (после «Повторить урок»), + создаётся НОВАЯ запись с attempt_number+1, revised=TRUE, + revision_of_id=предыдущий ответ. История сохраняется полностью. + + Возвращает: + { + "correct": bool, + "wrong_because": str | None, + "attempt_number": int, # какая это попытка + "show_correct_answer": bool, # TRUE только если attempt >= 3 + "correct_answer": str | None # только при show_correct_answer + } + """ telegram_id, _ = await require_auth(request) body = await request.json() session_id = body.get("session_id") @@ -604,20 +624,39 @@ async def save_answer(request: Request): selected_answer = body.get("answer", "") time_taken_ms = body.get("time_taken_ms", 0) is_final = body.get("is_final_answer", True) - # 🔧 ФИКС (22.09.2026): раньше hint_used был захардкожен False, - # поэтому подсказки не попадали в аналитику (hint_dependency всегда 0). hint_used = body.get("hint_used", False) + # 🔧 НОВОЕ: клиент сообщает, что это повторная попытка + is_retry = body.get("is_retry", False) if not session_id or not question_id: raise HTTPException(400, "session_id and question_id required") pool = await get_pool() async with pool.acquire() as conn: - question = await conn.fetchrow("SELECT * FROM learning_questions WHERE question_id = $1", question_id) + question = await conn.fetchrow( + "SELECT * FROM learning_questions WHERE question_id = $1", question_id + ) if not question: raise HTTPException(404, "Question not found") - correct = selected_answer.strip().lower() == (question["correct_answer"] or "").strip().lower() + # 🔧 НОВОЕ: считаем текущее количество попыток по этому вопросу в сессии + prev_attempts = await conn.fetch( + """ + SELECT id, attempt_number, correct + FROM user_learning_answers + WHERE session_id = $1 AND question_id = $2 + ORDER BY attempt_number ASC + """, + session_id, question_id, + ) + + next_attempt = (prev_attempts[-1]["attempt_number"] + 1) if prev_attempts else 1 + prev_id = prev_attempts[-1]["id"] if prev_attempts else None + + correct = ( + selected_answer.strip().lower() + == (question["correct_answer"] or "").strip().lower() + ) wrong_because = None if not correct: @@ -628,58 +667,212 @@ async def save_answer(request: Request): if option: wrong_because = option["wrong_because"] - session = await conn.fetchrow("SELECT * FROM learning_sessions WHERE id = $1", session_id) - - # 🔧 ФИКС (23.09.2026): learning_save_answer_missing_session_check — - # раньше при несуществующем session_id падало с TypeError → 500. - # Теперь честная 404 + проверка владельца сессии. + session = await conn.fetchrow( + "SELECT * FROM learning_sessions WHERE id = $1", session_id + ) if not session: raise HTTPException(404, "Session not found") if session["user_id"] != telegram_id: raise HTTPException(403, "Session belongs to another user") - await conn.execute(""" - INSERT INTO user_learning_answers (user_id, session_id, level_code, topic_id, lesson_id, question_id, selected_answer, correct, skill_tag, question_type, context_type, difficulty, time_taken_ms, hint_used, wrong_because, is_final_answer) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) - """, telegram_id, session_id, session["level_code"], session["topic_id"], question["lesson_id"], question_id, selected_answer, correct, question["skill_tag"], question["question_type"], question["context_type"], question["difficulty"], time_taken_ms, hint_used, wrong_because, is_final) + # 🔧 Логика revised: если это повторная попытка — фиксируем + revised = is_retry or next_attempt > 1 - return {"correct": correct, "wrong_because": wrong_because} + # 🔧 is_final_answer: только ПОСЛЕДНЯЯ попытка считается финальной + # (для статистики). Промежуточные — revision-записи, не идут в total. + # Если клиент сказал is_final=False (подсказка) — уважаем. + if is_retry: + # Сначала снимаем флаг is_final_answer у предыдущей записи + await conn.execute( + """ + UPDATE user_learning_answers + SET is_final_answer = FALSE + WHERE session_id = $1 AND question_id = $2 + """, + session_id, question_id, + ) + + await conn.execute( + """ + INSERT INTO user_learning_answers ( + user_id, session_id, level_code, topic_id, lesson_id, + question_id, selected_answer, correct, skill_tag, + question_type, context_type, difficulty, time_taken_ms, + attempt_number, hint_used, wrong_because, is_final_answer, + revised, revision_of_id + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, + $14, $15, $16, $17, $18, $19) + """, + telegram_id, session_id, session["level_code"], session["topic_id"], + question["lesson_id"], question_id, selected_answer, correct, + question["skill_tag"], question["question_type"], question["context_type"], + question["difficulty"], time_taken_ms, next_attempt, hint_used, + wrong_because, is_final, revised, prev_id, + ) + + # 🔧 Решаем, показывать ли правильный ответ + # Первая попытка — НЕ показываем + # Вторая — НЕ показываем + # Третья и выше — показываем + show_correct_answer = next_attempt >= 3 + + # Правильный ответ — текст варианта (для recognition) + correct_answer_text = None + if show_correct_answer: + correct_option = await conn.fetchrow( + """ + SELECT option_key, text_pl, text_ru, text_uk, text_en + FROM question_options + WHERE question_id = $1 AND is_correct = TRUE + LIMIT 1 + """, + question_id, + ) + if correct_option: + correct_answer_text = ( + f"{correct_option['option_key']} — {correct_option['text_pl']}" + ) + else: + # Для production — просто correct_answer из вопроса + correct_answer_text = question["correct_answer"] + + return { + "correct": correct, + "wrong_because": wrong_because, + "attempt_number": next_attempt, + "show_correct_answer": show_correct_answer, + "correct_answer": correct_answer_text, + } +# 🔧 ОБНОВЛЕНО (02.10.2026): session_report — +# без AI формируем человеческий отчёт для экрана «Тема пройдена»: +# - total / correct / percent +# - message («Отлично!» / «Стоит повторить») +# - weak_skills этой темы (с понятными названиями) +# - next_topic @router.post("/session/complete") async def complete_session(request: Request): - """Завершить сессию: обновляет прогресс урока/теста, мастерство навыков, прогресс темы и AI-контекст""" + """ + Завершить сессию: обновляет прогресс, мастерство, AI-контекст + и возвращает отчёт для экрана «Тема пройдена». + + 🔧 ОБНОВЛЕНО (02.10.2026): session_report — + без AI формируем человеческий отчёт: + - total / correct / percent + - message («Отлично!» / «Стоит повторить») + - weak_skills этой темы (с понятными названиями) + - next_topic + """ telegram_id, _ = await require_auth(request) body = await request.json() session_id = body.get("session_id") + # 🔧 НОВОЕ: язык для формирования отчёта + lang = body.get("lang", "ru") pool = await get_pool() async with pool.acquire() as conn: - session = await conn.fetchrow("SELECT * FROM learning_sessions WHERE id = $1 AND user_id = $2", session_id, telegram_id) + session = await conn.fetchrow( + "SELECT * FROM learning_sessions WHERE id = $1 AND user_id = $2", + session_id, telegram_id, + ) if not session: raise HTTPException(404, "Session not found") - await conn.execute("UPDATE learning_sessions SET is_completed = TRUE, completed_at = NOW() WHERE id = $1", session_id) + await conn.execute( + "UPDATE learning_sessions SET is_completed = TRUE, completed_at = NOW() WHERE id = $1", + session_id, + ) - stats = await conn.fetchrow(""" - SELECT COUNT(*) as total, COALESCE(SUM(CASE WHEN correct THEN 1 ELSE 0 END), 0) as correct_count - FROM user_learning_answers WHERE session_id = $1 AND is_final_answer = TRUE - """, session_id) + # 🔧 Считаем только ПОСЛЕДНИЕ (is_final_answer=TRUE) ответы на каждый вопрос + stats = await conn.fetchrow( + """ + WITH last_answers AS ( + SELECT DISTINCT ON (question_id) question_id, correct, wrong_because, skill_tag + FROM user_learning_answers + WHERE session_id = $1 + ORDER BY question_id, attempt_number DESC + ) + SELECT + COUNT(*) AS total, + COALESCE(SUM(CASE WHEN correct THEN 1 ELSE 0 END), 0) AS correct_count + FROM last_answers + """, + session_id, + ) + # Слабые навыки этой темы (те, где были ошибки) + weak_rows = await conn.fetch( + """ + WITH last_answers AS ( + SELECT DISTINCT ON (question_id) question_id, correct, skill_tag + FROM user_learning_answers + WHERE session_id = $1 + ORDER BY question_id, attempt_number DESC + ) + SELECT + la.skill_tag, + COUNT(*) FILTER (WHERE NOT la.correct) AS errors, + COALESCE(ll.title_ru, la.skill_tag) AS name_ru, + COALESCE(ll.title_pl, la.skill_tag) AS name_pl, + COALESCE(ll.title_uk, la.skill_tag) AS name_uk, + COALESCE(ll.title_en, la.skill_tag) AS name_en + FROM last_answers la + LEFT JOIN learning_lessons ll ON ll.skill_tag = la.skill_tag + WHERE NOT la.correct + GROUP BY la.skill_tag, ll.title_ru, ll.title_pl, ll.title_uk, ll.title_en + HAVING COUNT(*) FILTER (WHERE NOT la.correct) > 0 + ORDER BY errors DESC + LIMIT 5 + """, + session_id, + ) + + # Информация о теме topic_id = session["topic_id"] + topic_row = await conn.fetchrow( + "SELECT * FROM learning_topics WHERE topic_id = $1", topic_id + ) + + # Следующая тема того же уровня + next_topic = None + if topic_row: + next_topic = await conn.fetchrow( + """ + SELECT topic_id, name_ru, name_pl, name_uk, name_en + FROM learning_topics + WHERE level_code = $1 + AND order_number > $2 + AND is_active = TRUE + ORDER BY order_number + LIMIT 1 + """, + topic_row["level_code"], topic_row["order_number"], + ) + + # ============ Обновляем прогресс ============ + # (всё что было — оставляем) - # Обновляем прогресс урока if session["session_type"] == "lesson": - lesson_row = await conn.fetchrow(""" - SELECT DISTINCT lesson_id FROM user_learning_answers WHERE session_id = $1 AND lesson_id IS NOT NULL - """, session_id) - + lesson_row = await conn.fetchrow( + """ + SELECT DISTINCT lesson_id FROM user_learning_answers + WHERE session_id = $1 AND lesson_id IS NOT NULL + """, + session_id, + ) if lesson_row and lesson_row["lesson_id"]: lesson_id = lesson_row["lesson_id"] - score = (stats["correct_count"] / stats["total"] * 100) if stats["total"] > 0 else 0 - - await conn.execute(""" - INSERT INTO user_lesson_progress (user_id, lesson_id, started_at, completed_at, attempts_count, correct_count, best_score, completed) + score = ( + stats["correct_count"] / stats["total"] * 100 + ) if stats["total"] > 0 else 0 + await conn.execute( + """ + INSERT INTO user_lesson_progress ( + user_id, lesson_id, started_at, completed_at, + attempts_count, correct_count, best_score, completed + ) VALUES ($1, $2, NOW(), NOW(), 1, $3, $4, TRUE) ON CONFLICT (user_id, lesson_id) DO UPDATE SET completed_at = NOW(), @@ -687,37 +880,111 @@ async def complete_session(request: Request): correct_count = user_lesson_progress.correct_count + $3, best_score = GREATEST(user_lesson_progress.best_score, $4), completed = TRUE - """, telegram_id, lesson_id, stats["correct_count"], score) + """, + telegram_id, lesson_id, stats["correct_count"], score, + ) - # Обновляем прогресс темы если это тест if session["session_type"] == "topic_test": - test_score = (stats["correct_count"] / stats["total"] * 100) if stats["total"] > 0 else 0 - - await conn.execute(""" - INSERT INTO user_topic_progress (user_id, topic_id, test_started, test_completed, test_score, completed_at) + test_score = ( + stats["correct_count"] / stats["total"] * 100 + ) if stats["total"] > 0 else 0 + await conn.execute( + """ + INSERT INTO user_topic_progress ( + user_id, topic_id, test_started, test_completed, test_score, completed_at + ) VALUES ($1, $2, TRUE, TRUE, $3, NOW()) ON CONFLICT (user_id, topic_id) DO UPDATE SET test_completed = TRUE, test_score = $3, completed_at = NOW() - """, telegram_id, topic_id, test_score) + """, + telegram_id, topic_id, test_score, + ) - # Обновляем мастерство по всем навыкам из этой сессии - skill_tags = await conn.fetch(""" - SELECT DISTINCT skill_tag FROM user_learning_answers WHERE session_id = $1 - """, session_id) - + skill_tags = await conn.fetch( + "SELECT DISTINCT skill_tag FROM user_learning_answers WHERE session_id = $1", + session_id, + ) for st in skill_tags: await update_skill_mastery(conn, telegram_id, st["skill_tag"]) - # Обновляем прогресс темы ТОЛЬКО для lesson и topic_test if session["session_type"] in ("lesson", "topic_test") and topic_id: await update_topic_progress(conn, telegram_id, topic_id) - # Обновляем AI-контекст (всегда) await update_ai_context(conn, telegram_id) - return {"status": "ok", "total": stats["total"], "correct_count": stats["correct_count"]} + # ============ Формируем отчёт ============ + total = stats["total"] or 0 + correct_count = stats["correct_count"] or 0 + percent = round(correct_count / total * 100) if total > 0 else 0 + + # Человеческое сообщение (без AI, чистая математика) + if percent >= 90: + message = { + "ru": "Отлично! Ты прекрасно усвоил тему! 🎉", + "pl": "Świetnie! Doskonale opanowałeś temat! 🎉", + "uk": "Чудово! Ти чудово засвоїв тему! 🎉", + "en": "Excellent! You've mastered this topic! 🎉", + }.get(lang, "Отлично! 🎉") + elif percent >= 75: + message = { + "ru": "Хороший результат! Так держать! 💪", + "pl": "Dobry wynik! Tak trzymaj! 💪", + "uk": "Гарний результат! Так тримати! 💪", + "en": "Good result! Keep it up! 💪", + }.get(lang, "Хороший результат! 💪") + elif percent >= 60: + message = { + "ru": "Неплохо! Но есть над чем поработать.", + "pl": "Nieźle! Ale jest nad czym popracować.", + "uk": "Непогано! Але є над чим попрацювати.", + "en": "Not bad! But there's room to improve.", + }.get(lang, "Неплохо!") + else: + message = { + "ru": "Стоит пройти тему ещё раз — много ошибок.", + "pl": "Warto powtórzyć temat — dużo błędów.", + "uk": "Варто пройти тему ще раз — багато помилок.", + "en": "Worth repeating this topic — many mistakes.", + }.get(lang, "Стоит повторить.") + + # Слабые навыки на нужном языке + name_field = f"name_{lang}" + weak_skills_out = [] + for w in weak_rows: + weak_skills_out.append({ + "skill_tag": w["skill_tag"], + "name": w.get(name_field) or w["name_ru"], + "errors": w["errors"], + }) + + # Информация о следующей теме + next_out = None + if next_topic: + next_out = { + "topic_id": next_topic["topic_id"], + "name": next_topic.get(name_field) or next_topic["name_ru"], + } + + # Название текущей темы + topic_name = None + if topic_row: + topic_name = topic_row.get(name_field) or topic_row["name_ru"] + + return { + "status": "ok", + "total": total, + "correct_count": correct_count, + "report": { + "topic_id": topic_id, + "topic_name": topic_name, + "percent": percent, + "message": message, + "weak_skills": weak_skills_out, + "next_topic": next_out, + }, + } @router.get("/progress") diff --git a/routers/learning_data/__init__.py b/routers/learning_data/__init__.py index ddbb9c5..19770e2 100644 --- a/routers/learning_data/__init__.py +++ b/routers/learning_data/__init__.py @@ -1,8 +1,27 @@ """ Learning Data Package — данные всех уровней. Каждый уровень в отдельном файле. + +🔧 ОБНОВЛЕНО (02.10.2026): seed_data_only_if_empty — +файлы level_*.py остаются в репозитории как АРХИВ, +но при старте бэкенда контент НЕ перезаписывается, если +в БД уже есть данные. + +Причины: +- Контент правится через админку → правки в БД. +- Если seed запускать всегда — правки затираются. +- Уровни (learning_levels) гарантированно создаются — они статичны. + +Управление: +- Переменная окружения SEED_LEARNING_DATA=true в .env → заливаем файлы. +- По умолчанию false → пропускаем seed, если данные уже есть. + +Для fresh install (пустая БД): seed запустится автоматически, +т.к. проверка «learning_topics пуст» проходит. """ import logging +import os + from database import get_pool from . import level_a1, level_a2, level_b1, level_b2, level_c1, level_c2 @@ -10,10 +29,10 @@ logger = logging.getLogger(__name__) async def init_learning_data(): - """Инициализирует уровни и все темы""" + """Инициализирует уровни и (опционально) контент из файлов.""" pool = await get_pool() async with pool.acquire() as conn: - # ============ УРОВНИ ============ + # ============ УРОВНИ (всегда, они статичны) ============ levels = [ ("A1", "Poziom A1", "Уровень A1", "Рівень A1", "Level A1", 1), ("A2", "Poziom A2", "Уровень A2", "Рівень A2", "Level A2", 2), @@ -29,7 +48,29 @@ async def init_learning_data(): ON CONFLICT (code) DO NOTHING """, code, pl, ru, uk, en, sort) - # Загружаем данные каждого уровня + logger.info("[seed] learning_levels ensured (A1-C2)") + + # ============ ПРОВЕРКА: нужен ли seed контента? ============ + force_seed = os.getenv("SEED_LEARNING_DATA", "false").lower() == "true" + + topics_count = await conn.fetchval(""" + SELECT COUNT(*) FROM learning_topics + """) or 0 + + if topics_count > 0 and not force_seed: + logger.info( + f"[seed] learning_topics not empty ({topics_count} topics) — " + f"skipping content seed. Установи SEED_LEARNING_DATA=true в .env " + f"для принудительной перезаливки." + ) + return + + # ============ SEED КОНТЕНТА (fresh install ИЛИ force) ============ + if force_seed: + logger.warning("[seed] SEED_LEARNING_DATA=true — принудительная перезаливка контента") + else: + logger.info("[seed] Empty DB detected — seeding content from level_*.py files") + await level_a1.init_level_a1(conn) await level_a2.init_level_a2(conn) await level_b1.init_level_b1(conn) @@ -37,4 +78,4 @@ async def init_learning_data(): await level_c1.init_level_c1(conn) await level_c2.init_level_c2(conn) - logger.info("Learning data fully initialized") \ No newline at end of file + logger.info("[seed] Learning content initialized from files") \ No newline at end of file