feat: пагинация для /words/all + GET texts/all + DELETE text + глобальные дубликаты
This commit is contained in:
+128
-5
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user