feat(words): единый источник csv_words — wordquiz, bubblewords, pronunciation + CRUD

This commit is contained in:
2026-09-30 12:17:15 +00:00
parent 2d82d615c7
commit 6d0d1b5001
4 changed files with 202 additions and 34 deletions
+172 -1
View File
@@ -12,6 +12,12 @@ Admin Wordsearch Router — конструктор уровней филворд
- PUT /admin/wordsearch/level/{id} — обновить
- DELETE /admin/wordsearch/level/{id} — удалить
- POST /admin/wordsearch/validate — проверить корректность уровня
CRUD слов:
- GET /admin/wordsearch/words/all — полный список слов (с id)
- POST /admin/wordsearch/words — добавить слово
- PUT /admin/wordsearch/words/{word_id} — обновить слово
- DELETE /admin/wordsearch/words/{word_id} — удалить слово
"""
import json
import logging
@@ -494,4 +500,169 @@ async def delete_level(request: Request, level_id: int):
f"({row['level']} #{row['level_number']}) by admin {telegram_id}"
)
return {"status": "ok", "level_id": level_id}
return {"status": "ok", "level_id": level_id}
# ============ CRUD СЛОВ (csv_words) ============
@router.post("/words")
async def create_csv_word(request: Request):
"""Добавить слово в csv_words."""
telegram_id, _ = await require_auth(request)
_require_admin(telegram_id)
body = await request.json()
level_code = (body.get("level_code") or "").strip()
word_pl = (body.get("word_pl") or "").strip().lower()
translation_ru = (body.get("translation_ru") or "").strip()
translation_uk = (body.get("translation_uk") or "").strip()
translation_en = (body.get("translation_en") or "").strip()
if level_code not in LEVELS:
raise HTTPException(400, f"Invalid level: {level_code}")
if not word_pl:
raise HTTPException(400, "word_pl is required")
pool = await get_pool()
async with pool.acquire() as conn:
existing = await conn.fetchval("""
SELECT id FROM csv_words
WHERE level_code = $1 AND LOWER(word_pl) = LOWER($2)
""", level_code, word_pl)
if existing:
raise HTTPException(409, f"Word '{word_pl}' already exists in {level_code}")
row = await conn.fetchrow("""
INSERT INTO csv_words (level_code, word_pl, translation_ru, translation_uk, translation_en)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
""", level_code, word_pl, translation_ru, translation_uk, translation_en)
logger.info(f"[admin_wordsearch] csv_word created: #{row['id']} '{word_pl}' in {level_code} by admin {telegram_id}")
return {"status": "ok", "word_id": row["id"]}
@router.put("/words/{word_id}")
async def update_csv_word(request: Request, word_id: int):
"""Обновить слово в csv_words."""
telegram_id, _ = await require_auth(request)
_require_admin(telegram_id)
body = await request.json()
word_pl = (body.get("word_pl") or "").strip().lower()
translation_ru = (body.get("translation_ru") or "").strip()
translation_uk = (body.get("translation_uk") or "").strip()
translation_en = (body.get("translation_en") or "").strip()
if not word_pl:
raise HTTPException(400, "word_pl is required")
pool = await get_pool()
async with pool.acquire() as conn:
existing = await conn.fetchrow("SELECT level_code, word_pl FROM csv_words WHERE id = $1", word_id)
if not existing:
raise HTTPException(404, "Word not found")
await conn.execute("""
UPDATE csv_words
SET word_pl = $1,
translation_ru = $2,
translation_uk = $3,
translation_en = $4
WHERE id = $5
""", word_pl, translation_ru, translation_uk, translation_en, word_id)
# 🔧 Синхронизируем с level_words (для филвордов)
await conn.execute("""
UPDATE level_words
SET word_pl = $1, translation_ru = $2, translation_uk = $3, translation_en = $4
WHERE word_pl = $5
""", word_pl, translation_ru, translation_uk, translation_en, existing["word_pl"])
logger.info(f"[admin_wordsearch] csv_word updated: #{word_id} '{existing['word_pl']}' -> '{word_pl}' by admin {telegram_id}")
return {"status": "ok", "word_id": word_id}
@router.delete("/words/{word_id}")
async def delete_csv_word(request: Request, word_id: int):
"""Удалить слово из csv_words."""
telegram_id, _ = await require_auth(request)
_require_admin(telegram_id)
pool = await get_pool()
async with pool.acquire() as conn:
existing = await conn.fetchrow("SELECT level_code, word_pl FROM csv_words WHERE id = $1", word_id)
if not existing:
raise HTTPException(404, "Word not found")
await conn.execute("DELETE FROM csv_words WHERE id = $1", word_id)
logger.info(f"[admin_wordsearch] csv_word deleted: #{word_id} '{existing['word_pl']}' by admin {telegram_id}")
return {"status": "ok", "word_id": word_id}
@router.get("/words/all")
async def list_all_csv_words(
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_code = ${idx}")
params.append(level)
idx += 1
if q and q.strip():
conditions.append(f"""(
word_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_code, word_pl, translation_ru, translation_uk, translation_en
FROM csv_words
{where}
ORDER BY level_code, word_pl
LIMIT ${idx}
""", *params)
return {
"total": len(rows),
"words": [
{
"id": r["id"],
"level_code": r["level_code"],
"word_pl": r["word_pl"],
"translation_ru": r["translation_ru"] or "",
"translation_uk": r["translation_uk"] or "",
"translation_en": r["translation_en"] or "",
}
for r in rows
],
}