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:
@@ -16,6 +16,14 @@ export class AdminApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Ошибка с текстом сервера в serverMessage (пусто, если сервер его не прислал). */
|
||||
async function adminError(res, fallback) {
|
||||
const message = await readErrorMessage(res, null);
|
||||
const err = new AdminApiError(res.status, message || fallback);
|
||||
err.serverMessage = message || "";
|
||||
return err;
|
||||
}
|
||||
|
||||
async function readErrorMessage(res, fallback) {
|
||||
try {
|
||||
const body = await res.json();
|
||||
@@ -34,7 +42,7 @@ async function readErrorMessage(res, fallback) {
|
||||
*/
|
||||
export async function getCampaigns() {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/campaigns`);
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load campaigns"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to load campaigns");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -44,7 +52,7 @@ export async function createCampaign({ name, startDate, endDate, dailyImpression
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create campaign"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to create campaign");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -57,7 +65,7 @@ export async function updateCampaignStatus(campaignId, status) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update status"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to update status");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -72,7 +80,24 @@ export async function updateCampaign(campaignId, { name, startDate, endDate, dai
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update campaign"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to update campaign");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/v1/admin/campaigns/{id}/stats?from=YYYY-MM-DD&to=YYYY-MM-DD —
|
||||
* показы, клики и CTR (%) кампании и каждого её объявления за дни from..to
|
||||
* включительно (по умолчанию бэкенд берёт последние 30 дней, максимум 366).
|
||||
* Ответ: {campaignId, from, to, impressions, clicks, ctr, advertisings: [...]}.
|
||||
* Старый бэкенд маршрута не знает — 404.
|
||||
*/
|
||||
export async function getCampaignStats(campaignId, { from, to } = {}) {
|
||||
const params = new URLSearchParams();
|
||||
if (from) params.set("from", from);
|
||||
if (to) params.set("to", to);
|
||||
const query = params.toString();
|
||||
const res = await apiFetch(`${ADMIN_BASE}/campaigns/${encodeURIComponent(campaignId)}/stats${query ? `?${query}` : ""}`);
|
||||
if (!res.ok) throw await adminError(res, "Failed to load stats");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -84,7 +109,7 @@ export async function updateCampaign(campaignId, { name, startDate, endDate, dai
|
||||
*/
|
||||
export async function getAdvertisingsByCampaign(campaignId) {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/ads?campaignId=${encodeURIComponent(campaignId)}`);
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load advertisings"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to load advertisings");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -98,7 +123,7 @@ export async function createAdvertising({ campaignId, type, mediaKey, targetUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ campaignId, type, mediaKey, targetUrl, weight }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create advertising"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to create advertising");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -112,7 +137,7 @@ export async function updateAdvertising(advertisingId, { targetUrl, weight }) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ targetUrl, weight }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update advertising"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to update advertising");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -128,7 +153,7 @@ export async function uploadAdImage(file) {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to upload image"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to upload image");
|
||||
return res.json(); // { mediaKey }
|
||||
}
|
||||
|
||||
@@ -138,7 +163,7 @@ export async function presignVideoUpload(advertisingId, contentType) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ contentType }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Presign failed"));
|
||||
if (!res.ok) throw await adminError(res, "Presign failed");
|
||||
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
|
||||
}
|
||||
|
||||
@@ -151,13 +176,13 @@ export async function confirmVideoUpload(advertisingId, sourceKey) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sourceKey }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Confirm upload failed"));
|
||||
if (!res.ok) throw await adminError(res, "Confirm upload failed");
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function getAdvertisingStatus(advertisingId) {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/ads/${advertisingId}/status`);
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Status check failed"));
|
||||
if (!res.ok) throw await adminError(res, "Status check failed");
|
||||
return res.json(); // { advertisingId, transcodingStatus }
|
||||
}
|
||||
|
||||
@@ -168,7 +193,7 @@ export async function getAdvertisingStatus(advertisingId) {
|
||||
*/
|
||||
export async function getFullscreenAds() {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads`);
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load fullscreen ads"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to load fullscreen ads");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -181,7 +206,7 @@ export async function createFullscreenAd({ targetUrl }) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ targetUrl: targetUrl || null }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create fullscreen ad"));
|
||||
if (!res.ok) throw await adminError(res, "Failed to create fullscreen ad");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -191,7 +216,7 @@ export async function presignFullscreenVideoUpload(fullscreenAdId, contentType)
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ contentType }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Presign failed"));
|
||||
if (!res.ok) throw await adminError(res, "Presign failed");
|
||||
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
|
||||
}
|
||||
|
||||
@@ -204,7 +229,7 @@ export async function confirmFullscreenVideoUpload(fullscreenAdId, sourceKey) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sourceKey }),
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Confirm upload failed"));
|
||||
if (!res.ok) throw await adminError(res, "Confirm upload failed");
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -216,7 +241,7 @@ export async function activateFullscreenAd(fullscreenAdId) {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/activate`, {
|
||||
method: "PATCH",
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Activate failed"));
|
||||
if (!res.ok) throw await adminError(res, "Activate failed");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -224,6 +249,6 @@ export async function deactivateFullscreenAd(fullscreenAdId) {
|
||||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/deactivate`, {
|
||||
method: "PATCH",
|
||||
});
|
||||
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Deactivate failed"));
|
||||
if (!res.ok) throw await adminError(res, "Deactivate failed");
|
||||
return res.json();
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { toSafeHttpUrl } from "../utils/safeUrl";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import {
|
||||
@@ -106,14 +107,15 @@ export default function UploadAdModal({ onClose }) {
|
||||
if (creating) return;
|
||||
let targetUrl = newTargetUrl.trim();
|
||||
if (targetUrl) {
|
||||
if (!/^https?:\/\//i.test(targetUrl)) targetUrl = `https://${targetUrl}`;
|
||||
try {
|
||||
// eslint-disable-next-line no-new
|
||||
new URL(targetUrl);
|
||||
} catch {
|
||||
if (!/^[a-z][a-z0-9+.-]*:/i.test(targetUrl)) targetUrl = `https://${targetUrl}`;
|
||||
// Бэкенд принимает только абсолютный http(s) — проверяем так же,
|
||||
// иначе "javascript:..." дошёл бы до сервера и вернулся бы 400
|
||||
const safe = toSafeHttpUrl(targetUrl);
|
||||
if (!safe) {
|
||||
setCreateError(t("adminPanel.urlInvalid"));
|
||||
return;
|
||||
}
|
||||
targetUrl = safe;
|
||||
}
|
||||
setCreating(true);
|
||||
setCreateError("");
|
||||
|
||||
@@ -38,6 +38,9 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
|
||||
const [progress, setProgress] = useState(null); // 0..100 во время PUT в MinIO
|
||||
const [stepError, setStepError] = useState(""); // ошибка конкретного шага
|
||||
const [submitError, setSubmitError] = useState(""); // общая ошибка
|
||||
// Объявление, уже созданное на бэкенде, если упала загрузка видео: повторная
|
||||
// отправка продолжает с presign, а не создаёт второе объявление-сироту
|
||||
const createdAdRef = useRef(null);
|
||||
|
||||
// IMAGE-загрузка: файл, превью (object URL) и mediaKey, полученный с бэкенда.
|
||||
const [mediaKey, setMediaKey] = useState("");
|
||||
@@ -172,14 +175,18 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
|
||||
}
|
||||
|
||||
try {
|
||||
// Шаг 1 (общий): создание объявления
|
||||
const ad = await createAdvertising({
|
||||
// Шаг 1 (общий): создание объявления. Для VIDEO после сбоя загрузки
|
||||
// берём уже созданное (тип и кампания те же, правки URL/веса — через
|
||||
// редактирование в списке).
|
||||
const reuse = adType === "VIDEO" && createdAdRef.current?.type === "VIDEO";
|
||||
const ad = reuse ? createdAdRef.current : await createAdvertising({
|
||||
campaignId,
|
||||
type: adType,
|
||||
mediaKey: adType === "IMAGE" ? mediaKey : null,
|
||||
targetUrl,
|
||||
weight: Number(weight),
|
||||
});
|
||||
if (adType === "VIDEO") createdAdRef.current = ad;
|
||||
|
||||
if (adType === "IMAGE") {
|
||||
// IMAGE → transcodingStatus сразу "READY", загрузки нет.
|
||||
@@ -198,12 +205,15 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
|
||||
);
|
||||
|
||||
// Модалку закрываем сразу после confirm; транскодинг поллится страницей.
|
||||
createdAdRef.current = null;
|
||||
onCreated({ ...ad, transcodingStatus: "PENDING" });
|
||||
} catch (err) {
|
||||
setSubmitting(false);
|
||||
setProgress(null);
|
||||
if (err?.status === 400) {
|
||||
setSubmitError(t("adminPanel.adCreateFailed"));
|
||||
// Текст бэкенда объясняет причину (ссылка не http(s), вес, ключ
|
||||
// confirm-upload не из presign этого объявления)
|
||||
setSubmitError(err.serverMessage || t("adminPanel.adCreateFailed"));
|
||||
return;
|
||||
}
|
||||
// Контекст не теряем: по шагу показываем понятную ошибку
|
||||
|
||||
152
src/components/admin/CampaignStatsPanel.jsx
Normal file
152
src/components/admin/CampaignStatsPanel.jsx
Normal file
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getCampaignStats } from "../../api/adminAdsApi";
|
||||
|
||||
const DEFAULT_DAYS = 30;
|
||||
const MAX_DAYS = 366;
|
||||
|
||||
/** Дата в формате YYYY-MM-DD по локальному календарю (не UTC). */
|
||||
export function toIsoDate(date) {
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(date.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
/** Последние 30 дней включая сегодня — тот же период, что бэкенд берёт по умолчанию. */
|
||||
export function defaultStatsRange(now = new Date()) {
|
||||
const from = new Date(now);
|
||||
from.setDate(from.getDate() - (DEFAULT_DAYS - 1));
|
||||
return { from: toIsoDate(from), to: toIsoDate(now) };
|
||||
}
|
||||
|
||||
/** Число дней from..to включительно, или null для некорректного диапазона. */
|
||||
export function rangeDays(from, to) {
|
||||
const start = Date.parse(`${from}T00:00:00Z`);
|
||||
const end = Date.parse(`${to}T00:00:00Z`);
|
||||
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return null;
|
||||
return Math.round((end - start) / 86400000) + 1;
|
||||
}
|
||||
|
||||
function formatCtr(value) {
|
||||
return typeof value === "number" ? `${value.toFixed(2)}%` : "—";
|
||||
}
|
||||
|
||||
/**
|
||||
* Статистика кампании: показы, клики и CTR — итог и по каждому объявлению
|
||||
* (GET /api/v1/admin/campaigns/{id}/stats). Показ засчитывается по факту
|
||||
* видимости баннера (см. useAdViewability), а не по выдаче.
|
||||
*
|
||||
* @param {{ campaignId: number, ads?: Array<{id, type, targetUrl}> }} props
|
||||
*/
|
||||
export default function CampaignStatsPanel({ campaignId, ads = [] }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [range, setRange] = useState(() => defaultStatsRange());
|
||||
const [stats, setStats] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const days = rangeDays(range.from, range.to);
|
||||
const rangeError = days === null
|
||||
? t("adminPanel.statsRangeInvalid")
|
||||
: days > MAX_DAYS ? t("adminPanel.statsRangeTooLong", { max: MAX_DAYS }) : "";
|
||||
|
||||
const load = useCallback(async (signal) => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const data = await getCampaignStats(campaignId, range);
|
||||
if (signal.cancelled) return;
|
||||
setStats(data);
|
||||
} catch (err) {
|
||||
if (signal.cancelled) return;
|
||||
setStats(null);
|
||||
// 404 — бэкенд ещё без эндпоинта статистики
|
||||
setError(err?.status === 404 ? t("adminPanel.statsUnavailable") : t("adminPanel.statsLoadError"));
|
||||
} finally {
|
||||
if (!signal.cancelled) setLoading(false);
|
||||
}
|
||||
}, [campaignId, range, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (rangeError) return undefined;
|
||||
const signal = { cancelled: false };
|
||||
load(signal);
|
||||
return () => { signal.cancelled = true; };
|
||||
}, [load, rangeError]);
|
||||
|
||||
const number = (value) => (typeof value === "number" ? value.toLocaleString(i18n.language) : "—");
|
||||
const adById = new Map(ads.map((ad) => [ad.id, ad]));
|
||||
|
||||
return (
|
||||
<div className="admp-stats">
|
||||
<div className="admp-stats-range">
|
||||
<label>
|
||||
{t("adminPanel.statsFrom")}
|
||||
<input
|
||||
type="date"
|
||||
className="f-m-field"
|
||||
value={range.from}
|
||||
max={range.to}
|
||||
onChange={(e) => setRange((r) => ({ ...r, from: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t("adminPanel.statsTo")}
|
||||
<input
|
||||
type="date"
|
||||
className="f-m-field"
|
||||
value={range.to}
|
||||
min={range.from}
|
||||
onChange={(e) => setRange((r) => ({ ...r, to: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{rangeError && <div className="f-err-msg">{rangeError}</div>}
|
||||
{!rangeError && loading && <div className="admp-no-ads">{t("adminPanel.statsLoading")}</div>}
|
||||
{!rangeError && !loading && error && <div className="f-err-msg admp-load-error">{error}</div>}
|
||||
|
||||
{!rangeError && !loading && !error && stats && (
|
||||
<>
|
||||
<div className="admp-stats-totals">
|
||||
<div><span>{t("adminPanel.statsImpressions")}</span><strong>{number(stats.impressions)}</strong></div>
|
||||
<div><span>{t("adminPanel.statsClicks")}</span><strong>{number(stats.clicks)}</strong></div>
|
||||
<div><span>CTR</span><strong>{formatCtr(stats.ctr)}</strong></div>
|
||||
</div>
|
||||
|
||||
{Array.isArray(stats.advertisings) && stats.advertisings.length > 0 ? (
|
||||
<table className="admp-stats-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{t("adminPanel.statsAd")}</th>
|
||||
<th scope="col">{t("adminPanel.statsImpressions")}</th>
|
||||
<th scope="col">{t("adminPanel.statsClicks")}</th>
|
||||
<th scope="col">CTR</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stats.advertisings.map((row) => {
|
||||
const ad = adById.get(row.advertisingId);
|
||||
return (
|
||||
<tr key={row.advertisingId}>
|
||||
<td className="admp-stats-ad" title={ad?.targetUrl}>
|
||||
#{row.advertisingId}
|
||||
{ad && <span> · {ad.type} · {ad.targetUrl}</span>}
|
||||
</td>
|
||||
<td>{number(row.impressions)}</td>
|
||||
<td>{number(row.clicks)}</td>
|
||||
<td>{formatCtr(row.ctr)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="admp-no-ads">{t("adminPanel.statsEmpty")}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,7 +391,21 @@
|
||||
"fullscreenStatusActive": "Active",
|
||||
"fullscreenStatusInactive": "Inactive",
|
||||
"fullscreenNoUrl": "No target URL",
|
||||
"fullscreenCanActivate": "Ready to activate"
|
||||
"fullscreenCanActivate": "Ready to activate",
|
||||
"showStats": "Stats",
|
||||
"hideStats": "Hide stats",
|
||||
"stats": "Stats",
|
||||
"statsFrom": "From",
|
||||
"statsTo": "To",
|
||||
"statsImpressions": "Impressions",
|
||||
"statsClicks": "Clicks",
|
||||
"statsAd": "Ad",
|
||||
"statsLoading": "Loading stats…",
|
||||
"statsLoadError": "Failed to load stats",
|
||||
"statsUnavailable": "Stats are unavailable: the backend is not updated yet",
|
||||
"statsEmpty": "No impressions or clicks for this period",
|
||||
"statsRangeInvalid": "“To” date is before “From” date",
|
||||
"statsRangeTooLong": "The period cannot be longer than {{max}} days"
|
||||
},
|
||||
"landing": {
|
||||
"eyebrow": "Service for finding lost pets and items",
|
||||
|
||||
@@ -391,7 +391,21 @@
|
||||
"fullscreenStatusActive": "Активен",
|
||||
"fullscreenStatusInactive": "Неактивен",
|
||||
"fullscreenNoUrl": "Переход не задан",
|
||||
"fullscreenCanActivate": "Доступен для активации"
|
||||
"fullscreenCanActivate": "Доступен для активации",
|
||||
"showStats": "Статистика",
|
||||
"hideStats": "Скрыть статистику",
|
||||
"stats": "Статистика",
|
||||
"statsFrom": "С",
|
||||
"statsTo": "По",
|
||||
"statsImpressions": "Показы",
|
||||
"statsClicks": "Клики",
|
||||
"statsAd": "Объявление",
|
||||
"statsLoading": "Загружаем статистику…",
|
||||
"statsLoadError": "Не удалось загрузить статистику",
|
||||
"statsUnavailable": "Статистика недоступна: бэкенд ещё не обновлён",
|
||||
"statsEmpty": "За выбранный период показов и кликов нет",
|
||||
"statsRangeInvalid": "Дата «по» раньше даты «с»",
|
||||
"statsRangeTooLong": "Период не может быть длиннее {{max}} дней"
|
||||
},
|
||||
"landing": {
|
||||
"eyebrow": "Сервис поиска пропавших питомцев и вещей",
|
||||
|
||||
@@ -18,6 +18,7 @@ import AdvertisingCreateModal from "../components/admin/AdvertisingCreateModal";
|
||||
import AdvertisingEditModal from "../components/admin/AdvertisingEditModal";
|
||||
import CampaignStatusUpdateModal from "../components/admin/CampaignStatusUpdateModal";
|
||||
import PostsTab from "../components/admin/PostsTab";
|
||||
import CampaignStatsPanel from "../components/admin/CampaignStatsPanel";
|
||||
import { getAdvertisingStatus, getCampaigns, getAdvertisingsByCampaign } from "../api/adminAdsApi";
|
||||
import { getNextCampaignStatuses, isProcessingTranscoding } from "../utils/campaignStatus";
|
||||
import "../styles/admin.css";
|
||||
@@ -80,6 +81,16 @@ export default function AdminAdsPage() {
|
||||
const [campaignsLoading, setCampaignsLoading] = useState(true);
|
||||
const [campaignsLoadError, setCampaignsLoadError] = useState("");
|
||||
const [expandedCampaignIds, setExpandedCampaignIds] = useState(() => new Set());
|
||||
const [statsCampaignIds, setStatsCampaignIds] = useState(() => new Set());
|
||||
|
||||
const toggleStats = useCallback((campaignId) => {
|
||||
setStatsCampaignIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(campaignId)) next.delete(campaignId);
|
||||
else next.add(campaignId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const [toast, setToast] = useState(null);
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
const profileFetchedFor = useRef(null);
|
||||
@@ -404,6 +415,16 @@ export default function AdminAdsPage() {
|
||||
? t('adminPanel.hideAds')
|
||||
: t('adminPanel.showAds')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admp-btn admp-btn--ghost"
|
||||
aria-expanded={statsCampaignIds.has(campaign.id)}
|
||||
onClick={() => toggleStats(campaign.id)}
|
||||
>
|
||||
{statsCampaignIds.has(campaign.id)
|
||||
? t('adminPanel.hideStats')
|
||||
: t('adminPanel.showStats')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admp-btn admp-btn--ghost"
|
||||
@@ -440,6 +461,13 @@ export default function AdminAdsPage() {
|
||||
<span>{t('adminPanel.dailyCap')}: <strong>{campaign.dailyImpressionCap}</strong></span>
|
||||
</div>
|
||||
|
||||
{statsCampaignIds.has(campaign.id) && (
|
||||
<>
|
||||
<div className="admp-section-title">{t('adminPanel.stats')}</div>
|
||||
<CampaignStatsPanel campaignId={campaign.id} ads={campaign.ads} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{expandedCampaignIds.has(campaign.id) && (
|
||||
<>
|
||||
<div className="admp-section-title">{t('adminPanel.ads')}</div>
|
||||
|
||||
@@ -315,4 +315,66 @@
|
||||
}
|
||||
.fs-ad-row .f-upload-progress-text {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
/* ── Статистика кампании ── */
|
||||
.admp-stats {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.admp-stats-range {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.admp-stats-range label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: .75rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.admp-stats-totals {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.admp-stats-totals div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: .75rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.admp-stats-totals strong {
|
||||
font-size: 1.2rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.admp-stats-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: .82rem;
|
||||
}
|
||||
.admp-stats-table th,
|
||||
.admp-stats-table td {
|
||||
text-align: right;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.admp-stats-table th:first-child,
|
||||
.admp-stats-table td:first-child {
|
||||
text-align: left;
|
||||
}
|
||||
.admp-stats-table th {
|
||||
color: var(--muted);
|
||||
font-weight: 700;
|
||||
}
|
||||
.admp-stats-ad {
|
||||
max-width: 420px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.admp-stats-ad span {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user