Campaign stats in admin, user posts via new route, safer ad creation

- Admin: campaign stats panel (impressions, clicks, CTR per campaign and ad) with date range
- My posts: GET /api/v1/users/{id}/posts with paging, fallback to the legacy route
- Ad creation: retry after a failed video upload reuses the created ad; show backend 400 text
- Fullscreen ad form: only absolute http(s) target URLs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 11:53:08 +03:00
parent db37befb8d
commit 804018d2ce
9 changed files with 389 additions and 44 deletions

View File

@@ -1,41 +1,79 @@
import { useState, useCallback } from "react";
import { useState, useCallback, useRef } from "react";
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
// Максимальный size страницы у бэкенда (spring.data.web.pageable.max-page-size)
const PAGE_SIZE = 50;
// Защита от бесконечного цикла, если бэкенд вдруг не отдаст признак last
const MAX_PAGES = 20;
/**
* Объявления пользователя: новый маршрут GET /api/v1/users/{userId}/posts
* (Page<PostResponse>). Подгружаем все страницы — «Мои объявления» показываются
* целиком, а своих объявлений у пользователя немного.
*
* @returns {Promise<object[]|null>} null — маршрута нет (старый бэкенд)
*/
async function fetchUserPostsPaged(userId) {
const all = [];
for (let page = 0; page < MAX_PAGES; page++) {
const params = new URLSearchParams({ page, size: PAGE_SIZE, sort: "createdAt,desc" });
const res = await apiFetch(`${API_URL}/api/v1/users/${userId}/posts?${params}`);
// Старый бэкенд: маршрута нет (404) либо /users/** закрыт без токена и
// неизвестный путь падает в 500 — откатываемся на прежний эндпоинт
if (page === 0 && (res.status === 404 || res.status === 405 || res.status >= 500)) return null;
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
const items = Array.isArray(data) ? data : (data.content ?? data.items ?? []);
all.push(...items);
const last = Array.isArray(data) || typeof data.last !== "boolean" ? items.length < PAGE_SIZE : data.last;
if (last) break;
}
return all;
}
/** Прежний маршрут: GET /api/v1/posts/{userId} — список без пагинации. */
async function fetchUserPostsLegacy(userId) {
const res = await apiFetch(`${API_URL}/api/v1/posts/${userId}`);
if (res.status === 404) return [];
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}
/**
* Загружает объявления текущего пользователя по userId.
*
* Запросы — через apiFetch: своему автору бэкенд отдаёт и неопубликованные
* объявления (MODERATION/REJECTED), но только авторизованному запросу.
*/
export function useMyPosts(userId) {
const [myAds, setMyAds] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
// Ответ для прошлого пользователя (вышли и вошли под другим) не должен
// перетереть список нового
const requestIdRef = useRef(0);
const loadMyPosts = useCallback(async () => {
if (!userId) return;
const requestId = ++requestIdRef.current;
setLoading(true);
setError("");
try {
// apiFetch, а не fetch: своему автору бэкенд отдаёт и неопубликованные
// объявления (MODERATION/REJECTED), но только авторизованному запросу.
const res = await apiFetch(`${API_URL}/api/v1/posts/${userId}`);
if (res.status === 404) {
setMyAds([]);
return;
}
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
const posts = Array.isArray(data) ? data : (data.items ?? []);
const normalizedPosts = posts.map(ad => ({
const posts = (await fetchUserPostsPaged(userId)) ?? (await fetchUserPostsLegacy(userId));
if (requestId !== requestIdRef.current) return;
setMyAds(posts.map(ad => ({
...ad,
type: ad.type ? ad.type.toLowerCase() : "loss",
}));
setMyAds(normalizedPosts);
})));
} catch (err) {
if (requestId !== requestIdRef.current) return;
setError(err.message || "Failed to load your ads");
} finally {
setLoading(false);
if (requestId === requestIdRef.current) setLoading(false);
}
}, [userId]);
return { myAds, loading, error, loadMyPosts };
}
}