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/level/{level} — список текстов
|
||||||
- GET /admin/content/texts/text/{text_id} — один текст
|
- GET /admin/content/texts/text/{text_id} — один текст
|
||||||
- PUT /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} — добавить текст
|
- POST /admin/content/texts/level/{level} — добавить текст
|
||||||
|
- GET /admin/content/texts/all — все тексты (для редактора)
|
||||||
- GET /admin/content/lessons/levels — уровни уроков (счётчики тем)
|
- GET /admin/content/lessons/levels — уровни уроков (счётчики тем)
|
||||||
- GET /admin/content/lessons/level/{level}/topics — темы уровня
|
- GET /admin/content/lessons/level/{level}/topics — темы уровня
|
||||||
- GET /admin/content/lessons/topic/{topic_id} — тема + уроки + тест
|
- GET /admin/content/lessons/topic/{topic_id} — тема + уроки + тест
|
||||||
@@ -40,6 +42,12 @@ Admin Content Router — контент-менеджер для редактир
|
|||||||
- correct_answer в learning_questions = option_key того варианта, где is_correct=true.
|
- correct_answer в learning_questions = option_key того варианта, где is_correct=true.
|
||||||
- test_order пересчитывается 1..N по порядку для теста темы (is_test_question=TRUE).
|
- test_order пересчитывается 1..N по порядку для теста темы (is_test_question=TRUE).
|
||||||
- level_code НЕ трогаем — он вычисляется через topic_id → learning_topics.level_code.
|
- 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 logging
|
||||||
import re
|
import re
|
||||||
@@ -603,6 +611,24 @@ async def update_text(request: Request, text_id: int):
|
|||||||
return {"status": "ok", "text_id": text_id, "difficulty": difficulty}
|
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}")
|
@router.post("/texts/level/{level}")
|
||||||
async def create_text(request: Request, level: str):
|
async def create_text(request: Request, level: str):
|
||||||
"""
|
"""
|
||||||
@@ -624,15 +650,42 @@ async def create_text(request: Request, level: str):
|
|||||||
if not sentence_pl:
|
if not sentence_pl:
|
||||||
raise HTTPException(400, "sentence_pl is required")
|
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)
|
difficulty = _compute_difficulty(sentence_pl)
|
||||||
|
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
existing = await conn.fetchval("""
|
if not force:
|
||||||
SELECT id FROM sentences WHERE level = $1 AND LOWER(sentence_pl) = LOWER($2)
|
existing = await conn.fetchrow("""
|
||||||
""", level, sentence_pl)
|
SELECT id, level FROM sentences
|
||||||
if existing:
|
WHERE LOWER(sentence_pl) = LOWER($1)
|
||||||
raise HTTPException(409, f"This sentence already exists in {level}")
|
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("""
|
next_num = await conn.fetchval("""
|
||||||
SELECT COALESCE(MAX(sentence_number), 0) + 1 FROM sentences WHERE level = $1
|
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}
|
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 ============
|
# ============ LESSONS ============
|
||||||
|
|
||||||
@router.get("/lessons/levels")
|
@router.get("/lessons/levels")
|
||||||
|
|||||||
+36
-10
@@ -18,6 +18,8 @@ CRUD слов:
|
|||||||
- POST /admin/wordsearch/words — добавить слово
|
- POST /admin/wordsearch/words — добавить слово
|
||||||
- PUT /admin/wordsearch/words/{word_id} — обновить слово
|
- PUT /admin/wordsearch/words/{word_id} — обновить слово
|
||||||
- DELETE /admin/wordsearch/words/{word_id} — удалить слово
|
- DELETE /admin/wordsearch/words/{word_id} — удалить слово
|
||||||
|
|
||||||
|
🔧 ОБНОВЛЕНО (30.09.2026): /words/all — пагинация + total.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -632,24 +634,38 @@ async def list_all_csv_words(
|
|||||||
request: Request,
|
request: Request,
|
||||||
level: Optional[str] = None,
|
level: Optional[str] = None,
|
||||||
q: Optional[str] = None,
|
q: Optional[str] = None,
|
||||||
limit: int = 500,
|
page: int = 1,
|
||||||
|
limit: int = 50,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Полный список слов (с id) для редактора.
|
🔧 ОБНОВЛЕНО (30.09.2026): пагинация + total.
|
||||||
С поиском по PL/RU/UK/EN.
|
|
||||||
|
Возвращает:
|
||||||
|
{
|
||||||
|
"total": 2446, # всего под фильтром
|
||||||
|
"page": 1, # текущая страница
|
||||||
|
"limit": 50, # размер страницы
|
||||||
|
"pages": 49, # всего страниц
|
||||||
|
"words": [...], # слова текущей страницы
|
||||||
|
}
|
||||||
"""
|
"""
|
||||||
telegram_id, _ = await require_auth(request)
|
telegram_id, _ = await require_auth(request)
|
||||||
_require_admin(telegram_id)
|
_require_admin(telegram_id)
|
||||||
|
|
||||||
|
if page < 1:
|
||||||
|
page = 1
|
||||||
if limit < 1:
|
if limit < 1:
|
||||||
limit = 1
|
limit = 1
|
||||||
elif limit > 2000:
|
elif limit > 500:
|
||||||
limit = 2000
|
limit = 500
|
||||||
|
|
||||||
|
offset = (page - 1) * limit
|
||||||
|
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
|
# Условия
|
||||||
conditions = []
|
conditions = []
|
||||||
params = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
if level and level in LEVELS:
|
if level and level in LEVELS:
|
||||||
@@ -668,18 +684,28 @@ async def list_all_csv_words(
|
|||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
|
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"""
|
rows = await conn.fetch(f"""
|
||||||
SELECT id, level_code, word_pl, translation_ru, translation_uk, translation_en
|
SELECT id, level_code, word_pl, translation_ru, translation_uk, translation_en
|
||||||
FROM csv_words
|
FROM csv_words
|
||||||
{where}
|
{where}
|
||||||
ORDER BY level_code, word_pl
|
ORDER BY level_code, word_pl
|
||||||
LIMIT ${idx}
|
LIMIT ${idx} OFFSET ${idx + 1}
|
||||||
""", *params)
|
""", *params, limit, offset)
|
||||||
|
|
||||||
|
pages = (total + limit - 1) // limit if limit > 0 else 1
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"total": len(rows),
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"limit": limit,
|
||||||
|
"pages": pages,
|
||||||
"words": [
|
"words": [
|
||||||
{
|
{
|
||||||
"id": r["id"],
|
"id": r["id"],
|
||||||
|
|||||||
Reference in New Issue
Block a user