feat: пагинация для /words/all + GET texts/all + DELETE text + глобальные дубликаты

This commit is contained in:
2026-09-30 16:46:28 +00:00
parent 7bbce67cc4
commit 0755533ae1
2 changed files with 164 additions and 15 deletions
+127 -4
View File
@@ -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 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:
raise HTTPException(409, f"This sentence already exists in {level}")
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")
+36 -10
View File
@@ -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"],