added advertising
This commit is contained in:
229
src/api/adminAdsApi.js
Normal file
229
src/api/adminAdsApi.js
Normal file
@@ -0,0 +1,229 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(res, "Failed to update campaign"));
|
||||
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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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"));
|
||||
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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(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 new AdminApiError(res.status, await readErrorMessage(res, "Deactivate failed"));
|
||||
return res.json();
|
||||
}
|
||||
Reference in New Issue
Block a user