- 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>
254 lines
9.8 KiB
JavaScript
254 lines
9.8 KiB
JavaScript
// src/api/adminAdsApi.js
|
||
import { API_URL } from "../config/authConstants";
|
||
import { apiFetch } from "./apiClient";
|
||
|
||
const ADMIN_BASE = `${API_URL}/api/v1/admin`;
|
||
|
||
/**
|
||
* Ошибка API админ-панели. Несёт HTTP-статус, чтобы UI мог отличить
|
||
* 400 (невалидные данные) от 422 (недопустимый переход статуса) и т.п.
|
||
*/
|
||
export class AdminApiError extends Error {
|
||
constructor(status, message) {
|
||
super(message || `Admin API error ${status}`);
|
||
this.name = "AdminApiError";
|
||
this.status = status;
|
||
}
|
||
}
|
||
|
||
/** Ошибка с текстом сервера в 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();
|
||
if (body && typeof body.message === "string") return body.message;
|
||
if (body && typeof body.error === "string") return body.error;
|
||
} catch {
|
||
// тело не JSON — используем fallback
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
// ── Кампании ──
|
||
|
||
/**
|
||
* GET /api/v1/admin/campaigns — список кампаний с вложенными объявлениями.
|
||
*/
|
||
export async function getCampaigns() {
|
||
const res = await apiFetch(`${ADMIN_BASE}/campaigns`);
|
||
if (!res.ok) throw await adminError(res, "Failed to load campaigns");
|
||
return res.json();
|
||
}
|
||
|
||
export async function createCampaign({ name, startDate, endDate, dailyImpressionCap }) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/campaigns`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to create campaign");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* Ответ 200: CampaignResponseDto. 422 — недопустимый переход статуса.
|
||
*/
|
||
export async function updateCampaignStatus(campaignId, status) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/campaigns/${campaignId}/status`, {
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ status }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to update status");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* PUT /api/v1/admin/campaigns/{campaignId} — обновление полей кампании
|
||
* (без статуса; статус меняется отдельным PATCH-запросом).
|
||
* Ответ 200: обновлённый CampaignResponseDto. 400 — невалидные данные.
|
||
*/
|
||
export async function updateCampaign(campaignId, { name, startDate, endDate, dailyImpressionCap }) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/campaigns/${campaignId}`, {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
|
||
});
|
||
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();
|
||
}
|
||
|
||
// ── Объявления (креативы) ──
|
||
|
||
/**
|
||
* GET /api/v1/admin/ads?campaignId={campaignId} — список объявлений кампании.
|
||
* (Lazy-загрузка объявлений при раскрытии карточки кампании.)
|
||
*/
|
||
export async function getAdvertisingsByCampaign(campaignId) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads?campaignId=${encodeURIComponent(campaignId)}`);
|
||
if (!res.ok) throw await adminError(res, "Failed to load advertisings");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* POST /api/v1/admin/ads — создаёт объявление.
|
||
* IMAGE → transcodingStatus сразу "READY"; VIDEO → "PENDING".
|
||
*/
|
||
export async function createAdvertising({ campaignId, type, mediaKey, targetUrl, weight }) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ campaignId, type, mediaKey, targetUrl, weight }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to create advertising");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* PUT /api/v1/admin/ads/{advertisingId} — обновляет объявление
|
||
* (targetUrl, weight). Тип/медиа/статус транскодинга не меняются.
|
||
*/
|
||
export async function updateAdvertising(advertisingId, { targetUrl, weight }) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads/${advertisingId}`, {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ targetUrl, weight }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to update advertising");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* POST /api/v1/admin/ads/image — загрузка изображения креатива.
|
||
* multipart/form-data (поле "file"), Content-Type НЕ задаём вручную —
|
||
* браузер сам проставит boundary. Ответ 200: { mediaKey }.
|
||
*/
|
||
export async function uploadAdImage(file) {
|
||
const formData = new FormData();
|
||
formData.append("file", file);
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads/image`, {
|
||
method: "POST",
|
||
body: formData,
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to upload image");
|
||
return res.json(); // { mediaKey }
|
||
}
|
||
|
||
export async function presignVideoUpload(advertisingId, contentType) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads/${advertisingId}/video/presign-upload`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ contentType }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Presign failed");
|
||
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
|
||
}
|
||
|
||
/**
|
||
* Ответ 202 — транскодинг запущен на бэкенде.
|
||
*/
|
||
export async function confirmVideoUpload(advertisingId, sourceKey) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/ads/${advertisingId}/video/confirm-upload`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ sourceKey }),
|
||
});
|
||
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 await adminError(res, "Status check failed");
|
||
return res.json(); // { advertisingId, transcodingStatus }
|
||
}
|
||
|
||
// ── Полноэкранная реклама ──
|
||
|
||
/**
|
||
* GET /api/v1/admin/fullscreen-ads — список всех роликов (DRAFT/ACTIVE/INACTIVE).
|
||
*/
|
||
export async function getFullscreenAds() {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads`);
|
||
if (!res.ok) throw await adminError(res, "Failed to load fullscreen ads");
|
||
return res.json();
|
||
}
|
||
|
||
/**
|
||
* POST /api/v1/admin/fullscreen-ads — создаёт ролик (targetUrl необязателен).
|
||
*/
|
||
export async function createFullscreenAd({ targetUrl }) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ targetUrl: targetUrl || null }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Failed to create fullscreen ad");
|
||
return res.json();
|
||
}
|
||
|
||
export async function presignFullscreenVideoUpload(fullscreenAdId, contentType) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/video/presign-upload`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ contentType }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Presign failed");
|
||
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
|
||
}
|
||
|
||
/**
|
||
* Ответ 202 — транскодинг запущен на бэкенде.
|
||
*/
|
||
export async function confirmFullscreenVideoUpload(fullscreenAdId, sourceKey) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/video/confirm-upload`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ sourceKey }),
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Confirm upload failed");
|
||
return res;
|
||
}
|
||
|
||
/**
|
||
* PATCH /api/v1/admin/fullscreen-ads/{id}/activate — перевод ролика в ACTIVE
|
||
* (предыдущий активный автоматически становится INACTIVE).
|
||
*/
|
||
export async function activateFullscreenAd(fullscreenAdId) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/activate`, {
|
||
method: "PATCH",
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Activate failed");
|
||
return res.json();
|
||
}
|
||
|
||
export async function deactivateFullscreenAd(fullscreenAdId) {
|
||
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/deactivate`, {
|
||
method: "PATCH",
|
||
});
|
||
if (!res.ok) throw await adminError(res, "Deactivate failed");
|
||
return res.json();
|
||
} |