feat(feed): /admin/feed/stats — счётчики для бейджа черновиков

- total / drafts / published / pinned одним запросом
- COUNT(*) FILTER — быстро, без N+1
- Нужно для бейджа в сайдбаре админки
This commit is contained in:
2026-10-01 17:37:40 +00:00
parent 75b10c536b
commit 8c46a78aed
+176 -1
View File
@@ -11,6 +11,8 @@ Feed Router — посты для карусели (новости / партн
- POST /admin/feed/post/{id}/delete — удалить (вложения удалит CASCADE) - POST /admin/feed/post/{id}/delete — удалить (вложения удалит CASCADE)
- POST /admin/feed/upload-image — загрузить картинку (multipart, до 3 на пост) - POST /admin/feed/upload-image — загрузить картинку (multipart, до 3 на пост)
- POST /admin/feed/translate — перевести title+body вручную (без сохранения) - POST /admin/feed/translate — перевести title+body вручную (без сохранения)
- GET /admin/feed/list — список постов для админки (пагинация, все 4 языка)
- GET /admin/feed/stats — быстрая статистика (total/drafts/published/pinned)
Логика локализации: Логика локализации:
- В БД хранятся 4 версии поста (title_pl/ru/uk/en, body_pl/ru/uk/en). - В БД хранятся 4 версии поста (title_pl/ru/uk/en, body_pl/ru/uk/en).
@@ -788,4 +790,177 @@ async def admin_translate_feed(request: Request):
if not translations: if not translations:
raise HTTPException(500, "Translation failed (AI unavailable or invalid response)") raise HTTPException(500, "Translation failed (AI unavailable or invalid response)")
return translations return translations
# ============ ADMIN: СПИСОК ПОСТОВ (с пагинацией) ============
@router.get("/admin/feed/list")
async def admin_list_feed_posts(
request: Request,
section: Optional[str] = None,
page: int = 1,
limit: int = 50,
include_drafts: bool = True,
q: Optional[str] = None,
):
"""
🔧 НОВОЕ (01.10.2026): admin_feed_list —
список постов для админки со ВСЕМИ 4 языками + пагинация.
Query:
section — news|partners|contacts|apps (опционально)
page — страница (с 1)
limit — размер страницы (по умолчанию 50, макс 100)
include_drafts — включать is_published=FALSE (по умолчанию True)
q — поиск по title_pl / body_pl (ILIKE)
Ответ:
{ total, page, limit, pages, posts: [...] }
"""
telegram_id, _ = await require_auth(request)
_require_admin(telegram_id)
# Валидация
if section and section not in FEED_SECTIONS:
raise HTTPException(400, f"Invalid section: {section}")
# Защита от дурака
page = max(1, page)
limit = max(1, min(100, limit))
pool = await get_pool()
async with pool.acquire() as conn:
where = []
params = []
idx = 1
if section:
where.append(f"section = ${idx}")
params.append(section)
idx += 1
if not include_drafts:
where.append("is_published = TRUE")
if q:
where.append(f"(title_pl ILIKE ${idx} OR body_pl ILIKE ${idx} OR title_ru ILIKE ${idx} OR body_ru ILIKE ${idx})")
params.append(f"%{q}%")
idx += 1
where_sql = "WHERE " + " AND ".join(where) if where else ""
# Общее количество
total = await conn.fetchval(
f"SELECT COUNT(*) FROM feed_posts {where_sql}",
*params,
) or 0
# Страница
offset = (page - 1) * limit
rows = await conn.fetch(f"""
SELECT * FROM feed_posts
{where_sql}
ORDER BY section, is_pinned DESC, created_at DESC
LIMIT ${idx} OFFSET ${idx + 1}
""", *params, limit, offset)
if not rows:
return {
"total": total,
"page": page,
"limit": limit,
"pages": (total + limit - 1) // limit,
"posts": [],
}
# Вложения одним запросом (без N+1)
post_ids = [r["id"] for r in rows]
att_rows = await conn.fetch("""
SELECT post_id, file_path, order_number
FROM feed_attachments
WHERE post_id = ANY($1::bigint[])
ORDER BY post_id, order_number ASC
""", post_ids)
att_by_post: dict[int, list] = {}
for a in att_rows:
att_by_post.setdefault(a["post_id"], []).append(dict(a))
# Собираем результат
posts = []
for r in rows:
row = dict(r)
attachments = att_by_post.get(r["id"], [])
images = [
f"{API_PUBLIC_URL}{a['file_path']}" if a["file_path"].startswith("/") else a["file_path"]
for a in attachments
]
posts.append({
"id": row["id"],
"section": row["section"],
"source_language": row.get("source_language"),
"is_pinned": bool(row.get("is_pinned")),
"is_published": bool(row.get("is_published")),
"link_url": row.get("link_url"),
"telegram_url": row.get("telegram_url"),
"created_at": row["created_at"].isoformat() if row.get("created_at") else None,
"updated_at": row["updated_at"].isoformat() if row.get("updated_at") else None,
"expires_at": row["expires_at"].isoformat() if row.get("expires_at") else None,
"images": images,
# все 4 языка
"title_pl": row.get("title_pl") or "",
"title_ru": row.get("title_ru") or "",
"title_uk": row.get("title_uk") or "",
"title_en": row.get("title_en") or "",
"body_pl": row.get("body_pl") or "",
"body_ru": row.get("body_ru") or "",
"body_uk": row.get("body_uk") or "",
"body_en": row.get("body_en") or "",
})
return {
"total": total,
"page": page,
"limit": limit,
"pages": (total + limit - 1) // limit,
"posts": posts,
}
# ============ ADMIN: СТАТИСТИКА ДЛЯ БЕЙДЖА ============
@router.get("/admin/feed/stats")
async def admin_feed_stats(request: Request):
"""
🔧 НОВОЕ (01.10.2026): admin_feed_stats —
быстрая статистика для бейджа в сайдбаре.
Ответ:
{
"total": 42, — всего постов
"drafts": 2, — черновиков (is_published=FALSE)
"published": 40, — опубликованных
"pinned": 3 — закреплённых
}
"""
telegram_id, _ = await require_auth(request)
_require_admin(telegram_id)
pool = await get_pool()
async with pool.acquire() as conn:
row = await conn.fetchrow("""
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE is_published = FALSE) AS drafts,
COUNT(*) FILTER (WHERE is_published = TRUE) AS published,
COUNT(*) FILTER (WHERE is_pinned = TRUE) AS pinned
FROM feed_posts
""")
return {
"total": int(row["total"] or 0),
"drafts": int(row["drafts"] or 0),
"published": int(row["published"] or 0),
"pinned": int(row["pinned"] or 0),
}