diff --git a/src/api/adminAdsApi.js b/src/api/adminAdsApi.js index ecd2bcb..f29b71b 100644 --- a/src/api/adminAdsApi.js +++ b/src/api/adminAdsApi.js @@ -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(); } \ No newline at end of file diff --git a/src/components/UploadAdModal.jsx b/src/components/UploadAdModal.jsx index 4722c16..bac0118 100644 --- a/src/components/UploadAdModal.jsx +++ b/src/components/UploadAdModal.jsx @@ -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(""); diff --git a/src/components/admin/AdvertisingCreateModal.jsx b/src/components/admin/AdvertisingCreateModal.jsx index 425f514..ffc419c 100644 --- a/src/components/admin/AdvertisingCreateModal.jsx +++ b/src/components/admin/AdvertisingCreateModal.jsx @@ -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; } // Контекст не теряем: по шагу показываем понятную ошибку diff --git a/src/components/admin/CampaignStatsPanel.jsx b/src/components/admin/CampaignStatsPanel.jsx new file mode 100644 index 0000000..ff276f7 --- /dev/null +++ b/src/components/admin/CampaignStatsPanel.jsx @@ -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 ( +
| {t("adminPanel.statsAd")} | +{t("adminPanel.statsImpressions")} | +{t("adminPanel.statsClicks")} | +CTR | +
|---|---|---|---|
| + #{row.advertisingId} + {ad && · {ad.type} · {ad.targetUrl}} + | +{number(row.impressions)} | +{number(row.clicks)} | +{formatCtr(row.ctr)} | +