From 0755533ae1b85f0bfed74debab19e3ab2ae9b1aa Mon Sep 17 00:00:00 2001 From: Drobysh Date: Wed, 30 Sep 2026 16:46:28 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BF=D0=B0=D0=B3=D0=B8=D0=BD=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=B4=D0=BB=D1=8F=20/words/all=20+=20GET?= =?UTF-8?q?=20texts/all=20+=20DELETE=20text=20+=20=D0=B3=D0=BB=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D0=B4=D1=83=D0=B1=D0=BB?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routers/admin_content.py | 133 ++++++++++++++++++++++++++++++++++-- routers/admin_wordsearch.py | 46 ++++++++++--- 2 files changed, 164 insertions(+), 15 deletions(-) diff --git a/routers/admin_content.py b/routers/admin_content.py index 4344da1..7718e71 100644 --- a/routers/admin_content.py +++ b/routers/admin_content.py @@ -15,7 +15,9 @@ Admin Content Router — контент-менеджер для редактир - 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} — тема + уроки + тест @@ -40,6 +42,12 @@ Admin Content Router — контент-менеджер для редактир - 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} — +удаление текста из редактора. """ import logging import re @@ -603,6 +611,24 @@ async def update_text(request: Request, text_id: int): 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): """ @@ -624,15 +650,42 @@ async def create_text(request: Request, level: str): 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: - existing = await conn.fetchval(""" - SELECT id FROM sentences WHERE level = $1 AND LOWER(sentence_pl) = LOWER($2) - """, level, sentence_pl) - if existing: - raise HTTPException(409, f"This sentence already exists in {level}") + 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 @@ -652,6 +705,76 @@ async def create_text(request: Request, level: str): 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, + limit: int = 500, +): + """ + Полный список текстов (с id) для редактора. + Поиск по PL/RU/UK/EN. + """ + telegram_id, _ = await require_auth(request) + _require_admin(telegram_id) + + if limit < 1: + limit = 1 + elif limit > 2000: + limit = 2000 + + pool = await get_pool() + async with pool.acquire() as conn: + conditions = [] + params = [] + 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 "" + params.append(limit) + + 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} + """, *params) + + return { + "total": len(rows), + "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") diff --git a/routers/admin_wordsearch.py b/routers/admin_wordsearch.py index 586e373..ccd3e01 100644 --- a/routers/admin_wordsearch.py +++ b/routers/admin_wordsearch.py @@ -18,6 +18,8 @@ CRUD слов: - POST /admin/wordsearch/words — добавить слово - PUT /admin/wordsearch/words/{word_id} — обновить слово - DELETE /admin/wordsearch/words/{word_id} — удалить слово + +🔧 ОБНОВЛЕНО (30.09.2026): /words/all — пагинация + total. """ import json import logging @@ -632,24 +634,38 @@ async def list_all_csv_words( request: Request, level: Optional[str] = None, q: Optional[str] = None, - limit: int = 500, + page: int = 1, + limit: int = 50, ): """ - Полный список слов (с id) для редактора. - С поиском по PL/RU/UK/EN. + 🔧 ОБНОВЛЕНО (30.09.2026): пагинация + total. + + Возвращает: + { + "total": 2446, # всего под фильтром + "page": 1, # текущая страница + "limit": 50, # размер страницы + "pages": 49, # всего страниц + "words": [...], # слова текущей страницы + } """ telegram_id, _ = await require_auth(request) _require_admin(telegram_id) + if page < 1: + page = 1 if limit < 1: limit = 1 - elif limit > 2000: - limit = 2000 + elif limit > 500: + limit = 500 + + offset = (page - 1) * limit pool = await get_pool() async with pool.acquire() as conn: + # Условия conditions = [] - params = [] + params: list = [] idx = 1 if level and level in LEVELS: @@ -668,18 +684,28 @@ async def list_all_csv_words( idx += 1 where = ("WHERE " + " AND ".join(conditions)) if conditions else "" - params.append(limit) + # Общее количество + total = await conn.fetchval(f""" + SELECT COUNT(*) FROM csv_words {where} + """, *params) or 0 + + # Страница rows = await conn.fetch(f""" SELECT id, level_code, word_pl, translation_ru, translation_uk, translation_en FROM csv_words {where} ORDER BY level_code, word_pl - LIMIT ${idx} - """, *params) + LIMIT ${idx} OFFSET ${idx + 1} + """, *params, limit, offset) + + pages = (total + limit - 1) // limit if limit > 0 else 1 return { - "total": len(rows), + "total": total, + "page": page, + "limit": limit, + "pages": pages, "words": [ { "id": r["id"],