feat: platform update

This commit is contained in:
ivannoskov
2026-02-09 13:10:08 +03:00
parent f7597270e5
commit 1826483750
15 changed files with 907 additions and 2796 deletions

View File

@@ -45,7 +45,22 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import type { Channel } from "@/lib/types/api";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useWorkspace } from "@/components/providers/workspace-provider";
import type { Channel, Project } from "@/lib/types/api";
// ============================================================================
// Helpers
@@ -70,6 +85,7 @@ type SortOrder = "asc" | "desc" | null;
export default function ChannelsCatalogPage() {
const params = useParams();
const workspaceId = params?.workspaceId as string;
const { currentProject, projects } = useWorkspace();
const [channels, setChannels] = useState<Channel[]>([]);
const [loading, setLoading] = useState(true);
@@ -78,6 +94,11 @@ export default function ChannelsCatalogPage() {
const [sortField, setSortField] = useState<SortField | null>(null);
const [sortOrder, setSortOrder] = useState<SortOrder>(null);
// Placement dialog
const [selectedChannel, setSelectedChannel] = useState<Channel | null>(null);
const [showPlacementDialog, setShowPlacementDialog] = useState(false);
const [placementProjectId, setPlacementProjectId] = useState<string>("");
useEffect(() => {
const loadChannels = async () => {
try {
@@ -126,6 +147,23 @@ export default function ChannelsCatalogPage() {
return <ArrowUpDown className="h-4 w-4 ml-1" />;
};
const handleOpenPlacement = (channel: Channel) => {
setSelectedChannel(channel);
if (currentProject) {
setPlacementProjectId(currentProject.id);
}
setShowPlacementDialog(true);
};
const handleConfirmPlacement = () => {
if (!placementProjectId || !selectedChannel) return;
window.location.href = `/dashboard/${workspaceId}/purchase-plans/${placementProjectId}?openPlacement=true&channel_id=${selectedChannel.id}`;
};
const activeProjects = useMemo(() => {
return projects.filter(p => p.status === "active");
}, [projects]);
// Filter and sort channels
const filteredChannels = useMemo(() => {
let result = [...channels];
@@ -317,10 +355,8 @@ export default function ChannelsCatalogPage() {
</div>
</TableCell>
<TableCell>
<Button variant="outline" size="sm" asChild>
<a href={`/dashboard/${workspaceId}/placements/new?channel_id=${channel.id}`}>
Разместить
</a>
<Button variant="outline" size="sm" onClick={() => handleOpenPlacement(channel)}>
Разместить
</Button>
</TableCell>
</TableRow>
@@ -361,23 +397,65 @@ export default function ChannelsCatalogPage() {
{channel.description}
</p>
)}
<div className="flex items-center justify-between">
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<Users className="h-4 w-4" />
{formatNumber(channel.subscribers_count)}
</div>
<Button variant="outline" size="sm" asChild>
<a href={`/dashboard/${workspaceId}/placements/new?channel_id=${channel.id}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<Users className="h-4 w-4" />
{formatNumber(channel.subscribers_count)}
</div>
<Button variant="outline" size="sm" onClick={() => handleOpenPlacement(channel)}>
Разместить
</a>
</Button>
</div>
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
<Dialog open={showPlacementDialog} onOpenChange={setShowPlacementDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Создание размещения</DialogTitle>
<DialogDescription>
Выберите проект для размещения на канале {selectedChannel?.title}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<label className="text-sm font-medium">Проект</label>
<Select value={placementProjectId} onValueChange={setPlacementProjectId}>
<SelectTrigger>
<SelectValue placeholder="Выберите проект" />
</SelectTrigger>
<SelectContent>
{activeProjects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.title}
</SelectItem>
))}
</SelectContent>
</Select>
{activeProjects.length === 0 && (
<p className="text-sm text-muted-foreground">
Нет активных проектов. Создайте проект в настройках.
</p>
)}
</div>
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={() => setShowPlacementDialog(false)}>
Отмена
</Button>
<Button
onClick={handleConfirmPlacement}
disabled={!placementProjectId || activeProjects.length === 0}
>
Продолжить
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</TooltipProvider>
);
}

View File

@@ -1,255 +0,0 @@
"use client";
// ============================================================================
// Create Creative Page
// ============================================================================
import { useEffect, useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Loader2, ArrowLeft, Info } from "lucide-react";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { creativesApi } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
// ============================================================================
// Component
// ============================================================================
export default function NewCreativePage() {
const params = useParams();
const router = useRouter();
const searchParams = useSearchParams();
const workspaceId = params?.workspaceId as string;
const { currentProject, setSelectedProjects, projects } = useWorkspace();
const prefilledProjectId = searchParams.get("project_id");
const [name, setName] = useState("");
const [text, setText] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Auto-select project if prefilled from URL
useEffect(() => {
if (prefilledProjectId && projects.length > 0) {
const project = projects.find(p => p.id === prefilledProjectId);
if (project) {
setSelectedProjects([project]);
}
}
}, [prefilledProjectId, projects, setSelectedProjects]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim() || !text.trim()) {
setError("Заполните все обязательные поля");
return;
}
if (!text.includes("{invite_link}")) {
setError("Текст должен содержать {invite_link} для вставки ссылки");
return;
}
if (!currentProject) {
setError("Выберите проект в верхнем меню");
return;
}
try {
setIsSubmitting(true);
setError(null);
const creative = await creativesApi.create(
workspaceId,
currentProject.id,
{
name: name.trim(),
text: text.trim(),
}
);
// Redirect to creatives list with project filter
router.push(`/dashboard/${workspaceId}/creatives?project_id=${currentProject.id}`);
} catch (err: any) {
setError(err?.detail || "Не удалось создать креатив");
} finally {
setIsSubmitting(false);
}
};
const insertInviteLink = () => {
if (!text.includes("{invite_link}")) {
setText((prev) => prev + "{invite_link}");
}
};
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: `/dashboard/${workspaceId}` },
{ label: "Креативы", href: `/dashboard/${workspaceId}/creatives` },
{ label: "Новый креатив" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4 max-w-2xl">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => router.back()}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight">Новый креатив</h1>
<p className="text-muted-foreground">
Создайте рекламный материал для размещений
</p>
</div>
</div>
{!currentProject && (
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
Выберите проект в верхнем меню для создания креатива
</AlertDescription>
</Alert>
)}
<form onSubmit={handleSubmit}>
<Card>
<CardHeader>
<CardTitle>Информация о креативе</CardTitle>
<CardDescription>
Креатив это текст рекламного сообщения с пригласительной ссылкой
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">
Название <span className="text-destructive">*</span>
</Label>
<Input
id="name"
placeholder="Например: Летняя акция 2025"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isSubmitting}
/>
<p className="text-xs text-muted-foreground">
Внутреннее название для удобства поиска
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor="text">
Текст креатива <span className="text-destructive">*</span>
</Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={insertInviteLink}
disabled={text.includes("{invite_link}")}
>
Вставить {"{invite_link}"}
</Button>
</div>
<Textarea
id="text"
placeholder={`Пример:
🔥 Подпишись на наш канал!
Здесь ты найдёшь:
• Полезный контент
• Эксклюзивные материалы
• Актуальные новости
👉 {invite_link}`}
value={text}
onChange={(e) => setText(e.target.value)}
disabled={isSubmitting}
rows={10}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
Используйте <code className="bg-muted px-1 rounded">{"{invite_link}"}</code>{" "}
в том месте, где должна быть пригласительная ссылка
</p>
</div>
{text.includes("{invite_link}") && (
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
<span className="font-medium">Предпросмотр:</span>
<pre className="mt-2 whitespace-pre-wrap text-sm">
{text.replace(
"{invite_link}",
"https://t.me/+AbCdEfGhIjK"
)}
</pre>
</AlertDescription>
</Alert>
)}
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
<div className="flex gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => router.back()}
disabled={isSubmitting}
>
Отмена
</Button>
<Button
type="submit"
disabled={
isSubmitting ||
!name.trim() ||
!text.trim() ||
!currentProject
}
>
{isSubmitting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Создание...
</>
) : (
"Создать креатив"
)}
</Button>
</div>
</CardContent>
</Card>
</form>
</div>
</>
);
}

View File

@@ -26,9 +26,10 @@ import {
Grid,
List,
FileText,
Image,
Image as ImageIcon,
Video,
} from "lucide-react";
import Image from "next/image";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { creativesApi } from "@/lib/api";
@@ -126,7 +127,7 @@ const getCreativeWord = (count: number): string => {
const getMediaIcon = (mediaType: string) => {
switch (mediaType) {
case "photo":
return Image;
return ImageIcon;
case "video":
return Video;
case "animation":
@@ -236,11 +237,7 @@ export default function CreativesPage() {
);
const handleCreateCreativeClick = () => {
if (currentProject) {
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
} else {
setShowCreateDialog(true);
}
setShowCreateDialog(true);
};
const handleOpenBotClick = () => {
@@ -251,12 +248,6 @@ export default function CreativesPage() {
setShowCreateDialog(false);
};
const handleCreateOnPlatformClick = () => {
if (!currentProject) return;
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
setShowCreateDialog(false);
};
const handleCopyText = (text: string) => {
navigator.clipboard.writeText(text);
};
@@ -502,14 +493,14 @@ export default function CreativesPage() {
size="icon"
className="h-8 w-8"
asChild
>
<Link
href={`/dashboard/${workspaceId}/placements/new?creative_id=${creative.id}`}
title="Создать размещение"
>
<Plus className="h-3.5 w-3.5" />
</Link>
</Button>
<Link
href={`/dashboard/${workspaceId}/purchase-plans/${creative.project_id}?openPlacement=true&creative_id=${creative.id}`}
title="Создать размещение"
>
<Plus className="h-3.5 w-3.5" />
</Link>
</Button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -673,47 +664,45 @@ export default function CreativesPage() {
<DialogHeader>
<DialogTitle>Создание креатива</DialogTitle>
<DialogDescription>
Создание креатива через Telegram бота или на платформе
Креативы создаются через Telegram бота
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
Выберите способ создания креатива:
</p>
<div className="space-y-3">
<Button
variant="outline"
className="w-full justify-start"
onClick={handleOpenBotClick}
>
<div className="flex items-center justify-between w-full">
<div className="text-left">
<p className="font-medium">Через Telegram бота</p>
<p className="text-xs text-muted-foreground">
Перешлите сообщение боту
</p>
</div>
</div>
</Button>
{currentProject && (
<Button
variant="outline"
className="w-full justify-start"
onClick={handleCreateOnPlatformClick}
>
<div className="flex items-center justify-between w-full">
<div className="text-left">
<p className="font-medium">На платформе</p>
<p className="text-xs text-muted-foreground">
Для проекта: {currentProject.title}
</p>
</div>
</div>
</Button>
)}
<div className="space-y-3">
<div className="flex items-start gap-3 p-3 bg-muted rounded-lg">
<div>
<p className="text-sm font-medium">Перешлите пост боту</p>
<p className="text-xs text-muted-foreground mt-1">
Перешлите готовый пост с медиа и оформлением. Кнопки можно будет добавить через бота.
</p>
<p className="text-xs text-muted-foreground mt-1">
В тексте должна быть одна invite-ссылка формата: <code className="text-xs">https://t.me/+xxx</code>
</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 bg-muted rounded-lg">
<div>
<p className="text-sm font-medium">Бот создаст креатив</p>
<p className="text-xs text-muted-foreground mt-1">
При создании размещения ссылка автоматически заменится на уникальную для отслеживания
</p>
</div>
</div>
</div>
<Button
variant="default"
className="w-full"
onClick={handleOpenBotClick}
disabled={!currentProject}
>
<Image src="/icons/telegram.svg" alt="Telegram" width={20} height={20} className="w-5 h-5 mr-2" />
Перейти в бота
</Button>
{!currentProject && (
<p className="text-xs text-muted-foreground text-center">
Выберите проект в верхнем меню
</p>
)}
</div>
</DialogContent>
</Dialog>

View File

@@ -1,408 +0,0 @@
"use client";
// ============================================================================
// Placement Detail Page
// ============================================================================
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import {
Loader2,
ArrowLeft,
ExternalLink,
Copy,
Check,
Eye,
Users,
TrendingUp,
} from "lucide-react";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { placementsApi, projectsApi } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import type { Placement } from "@/lib/types/api";
// ============================================================================
// Helpers
// ============================================================================
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
};
const formatDateTime = (dateString: string | null | undefined) => {
if (!dateString) return "—";
return new Date(dateString).toLocaleString("ru-RU", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
const formatCurrency = (value: number | null | undefined) => {
if (value === null || value === undefined) return "—";
return new Intl.NumberFormat("ru-RU", {
style: "currency",
currency: "RUB",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatNumber = (value: number | null | undefined) => {
if (value === null || value === undefined) return "—";
return new Intl.NumberFormat("ru-RU").format(value);
};
// ============================================================================
// Component
// ============================================================================
export default function PlacementDetailPage() {
const params = useParams();
const router = useRouter();
const workspaceId = params?.workspaceId as string;
const placementId = params?.placementId as string;
const { hasPermission } = useWorkspace();
const [placement, setPlacement] = useState<Placement | null>(null);
const [loading, setLoading] = useState(true);
const [copiedLink, setCopiedLink] = useState(false);
const [projectId, setProjectId] = useState<string | null>(null);
const canWrite = hasPermission("placements_write");
useEffect(() => {
loadPlacement();
}, [workspaceId, placementId]);
const loadPlacement = async () => {
try {
setLoading(true);
// First, get all projects to find which project this placement belongs to
const projectsResponse = await projectsApi.list(workspaceId, { size: 100 });
const projects = projectsResponse.items;
// Search for the placement in all projects
let foundProjectId: string | null = null;
let foundPlacement: any = null;
for (const project of projects) {
try {
const placements = await placementsApi.getByProject(workspaceId, project.id);
const placement = placements.find((p) => p.id === placementId);
if (placement) {
foundProjectId = project.id;
foundPlacement = placement;
break;
}
} catch (e) {
// Skip if can't get placements for this project
continue;
}
}
if (foundPlacement) {
setPlacement(foundPlacement);
setProjectId(foundProjectId);
} else {
console.error("Placement not found in any project");
}
} catch (err) {
console.error("Failed to load placement:", err);
} finally {
setLoading(false);
}
};
const handleCopyLink = () => {
if (placement?.invite_link) {
navigator.clipboard.writeText(placement.invite_link);
setCopiedLink(true);
setTimeout(() => setCopiedLink(false), 2000);
}
};
if (loading) {
return (
<>
<DashboardHeader breadcrumbs={[{ label: "Загрузка..." }]} />
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</>
);
}
if (!placement) {
return (
<>
<DashboardHeader breadcrumbs={[{ label: "Ошибка" }]} />
<div className="flex flex-col items-center justify-center py-12">
<h2 className="text-xl font-semibold mb-2">Размещение не найдено</h2>
<Button asChild>
<Link href={`/dashboard/${workspaceId}/placements`}>
Вернуться к списку
</Link>
</Button>
</div>
</>
);
}
// Calculate metrics
const cost = placement.details?.cost?.value;
const subscriptionsCount = placement.placement_post?.subscriptions_count ?? 0;
const viewsCount = placement.placement_post?.views_count ?? 0;
const cps = cost && subscriptionsCount > 0 ? cost / subscriptionsCount : null;
const cpm = cost && viewsCount > 0 ? (cost / viewsCount) * 1000 : null;
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: `/dashboard/${workspaceId}` },
{ label: "Размещения", href: `/dashboard/${workspaceId}/placements` },
{ label: placement.channel.title },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => router.push(`/dashboard/${workspaceId}/placements`)}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold tracking-tight">
{placement.channel.title}
</h1>
<Badge
variant={
placement.status === "Оплачено" ? "default" : "secondary"
}
>
{placement.status === "Оплачено" ? "Активно" : placement.status}
</Badge>
</div>
<p className="text-muted-foreground">
{placement.details?.placement_at ? formatDate(placement.details.placement_at) : "—"}
</p>
</div>
</div>
</div>
{/* Stats Cards */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Стоимость</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatCurrency(cost)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Подписчиков</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(subscriptionsCount)}
</div>
<p className="text-xs text-muted-foreground">
CPS: {cps ? formatCurrency(cps) : "—"}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Просмотров</CardTitle>
<Eye className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(viewsCount)}
</div>
<p className="text-xs text-muted-foreground">
CPM: {cpm ? formatCurrency(cpm) : "—"}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Тип ссылки
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{placement.invite_link_type === "approval"
? "С заявками"
: "Публичная"}
</div>
</CardContent>
</Card>
</div>
<div className="grid gap-4 lg:grid-cols-2">
{/* Invite Link */}
<Card>
<CardHeader>
<CardTitle>Пригласительная ссылка</CardTitle>
<CardDescription>
{placement.invite_link_type === "approval"
? "С одобрением — бот отслеживает подписчиков"
: "Публичная ссылка"}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2">
<code className="flex-1 bg-muted px-3 py-2 rounded text-sm truncate">
{placement.invite_link || "—"}
</code>
<Button
variant="outline"
size="icon"
onClick={handleCopyLink}
disabled={!placement.invite_link}
>
{copiedLink ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
{placement.invite_link && (
<Button variant="outline" size="icon" asChild>
<a
href={placement.invite_link}
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="h-4 w-4" />
</a>
</Button>
)}
</div>
</CardContent>
</Card>
{/* Creative */}
<Card>
<CardHeader>
<CardTitle>Креатив</CardTitle>
<CardDescription>ID: {placement.creative_id}</CardDescription>
</CardHeader>
<CardContent>
{placement.creative_id && (
<Button variant="outline" asChild>
<Link
href={`/dashboard/${workspaceId}/creatives/${placement.creative_id}`}
>
Просмотреть креатив
</Link>
</Button>
)}
</CardContent>
</Card>
</div>
{/* Details */}
<Card>
<CardHeader>
<CardTitle>Детали размещения</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid gap-4 sm:grid-cols-2">
<div>
<dt className="text-sm font-medium text-muted-foreground">
Канал размещения
</dt>
<dd className="text-sm">{placement.channel.title}</dd>
</div>
<div>
<dt className="text-sm font-medium text-muted-foreground">
Дата размещения
</dt>
<dd className="text-sm">{placement.details?.placement_at ? formatDate(placement.details.placement_at) : "—"}</dd>
</div>
<div>
<dt className="text-sm font-medium text-muted-foreground">
Дата оплаты
</dt>
<dd className="text-sm">{placement.details?.payment_at ? formatDate(placement.details.payment_at) : "—"}</dd>
</div>
<div>
<dt className="text-sm font-medium text-muted-foreground">
Формат
</dt>
<dd className="text-sm">{placement.details?.format || "—"}</dd>
</div>
{placement.placement_post?.post?.url && (
<div className="sm:col-span-2">
<dt className="text-sm font-medium text-muted-foreground">
Ссылка на пост
</dt>
<dd className="text-sm">
<a
href={placement.placement_post.post.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-1"
>
{placement.placement_post.post.url}
<ExternalLink className="h-3 w-3" />
</a>
</dd>
</div>
)}
{placement.comment && (
<div className="sm:col-span-2">
<dt className="text-sm font-medium text-muted-foreground">
Комментарий
</dt>
<dd className="text-sm">{placement.comment}</dd>
</div>
)}
</dl>
</CardContent>
</Card>
</div>
</>
);
}

View File

@@ -1,414 +0,0 @@
"use client";
// ============================================================================
// Create Placement Page
// ============================================================================
import { useEffect, useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Loader2, ArrowLeft, Info, Calendar as CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { ru } from "date-fns/locale";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { placementsApi, creativesApi, channelsApi } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import type { Creative, Channel, InviteLinkType } from "@/lib/types/api";
// ============================================================================
// Component
// ============================================================================
export default function NewPlacementPage() {
const params = useParams();
const router = useRouter();
const searchParams = useSearchParams();
const workspaceId = params?.workspaceId as string;
const { currentProject, setSelectedProjects, projects } = useWorkspace();
// Pre-filled from URL params
const prefilledChannelId = searchParams.get("channel_id");
const prefilledCreativeId = searchParams.get("creative_id");
// Form state
const [channelId, setChannelId] = useState(prefilledChannelId || "");
const [creativeId, setCreativeId] = useState(prefilledCreativeId || "");
const [placementDate, setPlacementDate] = useState<Date>(new Date());
const [cost, setCost] = useState("");
const [comment, setComment] = useState("");
const [adPostUrl, setAdPostUrl] = useState("");
const [inviteLinkType, setInviteLinkType] = useState<InviteLinkType>("approval");
// Data
const [channels, setChannels] = useState<Channel[]>([]);
const [creatives, setCreatives] = useState<Creative[]>([]);
const [loadingData, setLoadingData] = useState(true);
// Submit state
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Auto-select project when creative_id is provided
useEffect(() => {
if (!prefilledCreativeId || projects.length === 0) return;
const loadCreativeAndSelectProject = async () => {
try {
const creative = await creativesApi.get(workspaceId, prefilledCreativeId);
const project = projects.find(p => p.id === creative.project_id);
if (project) {
setSelectedProjects([project]);
}
} catch (err) {
console.error("Failed to load creative:", err);
}
};
loadCreativeAndSelectProject();
}, [prefilledCreativeId, projects, workspaceId, setSelectedProjects]);
// Load channels and creatives
const loadData = async () => {
try {
setLoadingData(true);
const [channelsRes, creativesRes] = await Promise.all([
channelsApi.list({ size: 100 }),
currentProject
? creativesApi.list(workspaceId, {
project_id: currentProject.id,
include_archived: false,
size: 100,
})
: Promise.resolve({ items: [] }),
]);
setChannels(channelsRes.items);
setCreatives(creativesRes.items);
} catch (err) {
console.error("Failed to load data:", err);
} finally {
setLoadingData(false);
}
};
useEffect(() => {
loadData();
}, [workspaceId, currentProject?.id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!currentProject) {
setError("Выберите проект в верхнем меню");
return;
}
if (!channelId || !creativeId) {
setError("Выберите канал и креатив");
return;
}
try {
setIsSubmitting(true);
setError(null);
const placement = await placementsApi.create(workspaceId, {
project_id: currentProject.id,
placement_channel_id: channelId,
creative_id: creativeId,
placement_date: placementDate.toISOString(),
cost: cost ? parseFloat(cost) : undefined,
comment: comment || undefined,
ad_post_url: adPostUrl || undefined,
invite_link_type: inviteLinkType,
});
// Redirect to placements list with project filter
router.push(`/dashboard/${workspaceId}/placements?project_id=${currentProject.id}`);
} catch (err: any) {
setError(err?.detail || "Не удалось создать размещение");
} finally {
setIsSubmitting(false);
}
};
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: `/dashboard/${workspaceId}` },
{ label: "Размещения", href: `/dashboard/${workspaceId}/placements` },
{ label: "Новое размещение" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4 max-w-2xl">
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.back()}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight">Новое размещение</h1>
<p className="text-muted-foreground">
Создайте размещение рекламы в Telegram канале
</p>
</div>
</div>
{!currentProject && (
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
Выберите проект в верхнем меню для создания размещения
</AlertDescription>
</Alert>
)}
{loadingData ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : (
<form onSubmit={handleSubmit}>
<Card>
<CardHeader>
<CardTitle>Параметры размещения</CardTitle>
<CardDescription>
Укажите канал, креатив и условия размещения
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Channel */}
<div className="space-y-2">
<Label>
Канал для размещения <span className="text-destructive">*</span>
</Label>
<Select value={channelId} onValueChange={setChannelId}>
<SelectTrigger>
<SelectValue placeholder="Выберите канал" />
</SelectTrigger>
<SelectContent>
{channels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
<div className="flex flex-col">
<span>{channel.title}</span>
{channel.username && (
<span className="text-xs text-muted-foreground">
@{channel.username}
</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Creative */}
<div className="space-y-2">
<Label>
Креатив <span className="text-destructive">*</span>
</Label>
<Select value={creativeId} onValueChange={setCreativeId}>
<SelectTrigger>
<SelectValue placeholder="Выберите креатив" />
</SelectTrigger>
<SelectContent>
{creatives.length === 0 ? (
<div className="p-2 text-sm text-muted-foreground text-center">
Нет доступных креативов
</div>
) : (
creatives.map((creative) => (
<SelectItem key={creative.id} value={creative.id}>
{creative.name}
</SelectItem>
))
)}
</SelectContent>
</Select>
{creatives.length === 0 && currentProject && (
<p className="text-xs text-muted-foreground">
Сначала{" "}
<a
href={`/dashboard/${workspaceId}/creatives/new`}
className="text-primary hover:underline"
>
создайте креатив
</a>
</p>
)}
</div>
{/* Placement Date */}
<div className="space-y-2">
<Label>
Дата размещения <span className="text-destructive">*</span>
</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"w-full justify-start text-left font-normal",
!placementDate && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{placementDate
? format(placementDate, "PPP", { locale: ru })
: "Выберите дату"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={placementDate}
onSelect={(date) => date && setPlacementDate(date)}
locale={ru}
/>
</PopoverContent>
</Popover>
</div>
{/* Cost */}
<div className="space-y-2">
<Label htmlFor="cost">Стоимость ()</Label>
<Input
id="cost"
type="number"
placeholder="0"
value={cost}
onChange={(e) => setCost(e.target.value)}
disabled={isSubmitting}
/>
</div>
{/* Invite Link Type */}
<div className="space-y-2">
<Label>Тип пригласительной ссылки</Label>
<Select
value={inviteLinkType}
onValueChange={(v) => setInviteLinkType(v as InviteLinkType)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="approval">
<div className="flex flex-col">
<span>С одобрением (рекомендуется)</span>
<span className="text-xs text-muted-foreground">
Бот одобряет заявки и отслеживает подписчиков
</span>
</div>
</SelectItem>
<SelectItem value="public">
<div className="flex flex-col">
<span>Публичная ссылка</span>
<span className="text-xs text-muted-foreground">
Без отслеживания подписчиков
</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
{/* Ad Post URL */}
<div className="space-y-2">
<Label htmlFor="adPostUrl">Ссылка на рекламный пост</Label>
<Input
id="adPostUrl"
placeholder="https://t.me/channel/123"
value={adPostUrl}
onChange={(e) => setAdPostUrl(e.target.value)}
disabled={isSubmitting}
/>
<p className="text-xs text-muted-foreground">
Ссылка на пост после публикации (можно добавить позже)
</p>
</div>
{/* Comment */}
<div className="space-y-2">
<Label htmlFor="comment">Комментарий</Label>
<Textarea
id="comment"
placeholder="Дополнительная информация..."
value={comment}
onChange={(e) => setComment(e.target.value)}
disabled={isSubmitting}
rows={3}
/>
</div>
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
<div className="flex gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => router.back()}
disabled={isSubmitting}
>
Отмена
</Button>
<Button
type="submit"
disabled={
isSubmitting ||
!channelId ||
!creativeId ||
!currentProject
}
>
{isSubmitting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Создание...
</>
) : (
"Создать размещение"
)}
</Button>
</div>
</CardContent>
</Card>
</form>
)}
</div>
</>
);
}

View File

@@ -1,784 +0,0 @@
"use client";
// ============================================================================
// Placements List Page - Enhanced with Totals Row and Export
// ============================================================================
import { useEffect, useState, useMemo, useCallback } from "react";
import { useParams, useSearchParams } from "next/navigation";
import Link from "next/link";
import {
Loader2,
Search,
Plus,
ShoppingCart,
MoreHorizontal,
Eye,
ExternalLink,
ArrowUpDown,
ArrowUp,
ArrowDown,
Download,
FileSpreadsheet,
FileText,
Info,
X,
} from "lucide-react";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { demoAwarePlacementsApi } from "@/lib/demo";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
TableFooter,
} from "@/components/ui/table";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
DropdownMenuLabel,
} from "@/components/ui/dropdown-menu";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { ProjectSelector } from "@/components/project-selector";
import type { Placement } from "@/lib/types/api";
// ============================================================================
// Helpers
// ============================================================================
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString("ru-RU", {
day: "numeric",
month: "short",
year: "numeric",
});
};
const formatCurrency = (value: number | null) => {
if (value === null) return "—";
return new Intl.NumberFormat("ru-RU", {
style: "currency",
currency: "RUB",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatNumber = (value: number | null) => {
if (value === null) return "—";
return new Intl.NumberFormat("ru-RU").format(value);
};
const calculateCPS = (cost: number | null, subscriptions: number) => {
if (!cost || subscriptions === 0) return null;
return cost / subscriptions;
};
const calculateCPM = (cost: number | null | undefined, views: number | null | undefined) => {
if (!cost || !views || views === 0) return null;
return (cost / views) * 1000;
};
// ============================================================================
// Sort Types
// ============================================================================
type SortField = "date" | "cost" | "subscriptions" | "views" | "cps" | "cpm" | "status";
type SortOrder = "asc" | "desc" | null;
// ============================================================================
// Aggregation Functions
// ============================================================================
type AggFunc = "sum" | "avg" | "median" | "max" | "min";
const aggregationFunctions: Record<AggFunc, { label: string; fn: (values: number[]) => number | null }> = {
sum: {
label: "Сумма",
fn: (values) => (values.length > 0 ? values.reduce((a, b) => a + b, 0) : null),
},
avg: {
label: "Среднее",
fn: (values) => (values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null),
},
median: {
label: "Медиана",
fn: (values) => {
if (values.length === 0) return null;
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
},
},
max: {
label: "Макс.",
fn: (values) => (values.length > 0 ? Math.max(...values) : null),
},
min: {
label: "Мин.",
fn: (values) => (values.length > 0 ? Math.min(...values) : null),
},
};
// ============================================================================
// Export Functions
// ============================================================================
const exportToCSV = (placements: Placement[], filename: string) => {
const headers = [
"Канал",
"Username",
"Креатив",
"Дата",
"Стоимость",
"Подписки",
"Просмотры",
"CPS",
"CPM",
"Статус",
"Ссылка на пост",
"Пригласительная ссылка",
];
const rows = placements.map((p) => [
p.channel.title,
"",
"—", // creative_name not available in new structure
p.details?.placement_at ? new Date(p.details.placement_at).toISOString().split("T")[0] : "",
p.details?.cost?.value?.toString() || "",
p.placement_post?.subscriptions_count.toString() || "0",
p.placement_post?.views_count?.toString() || "",
calculateCPS(p.details?.cost?.value ?? null, p.placement_post?.subscriptions_count ?? 0)?.toFixed(2) || "",
calculateCPM(p.details?.cost?.value ?? null, p.placement_post?.views_count ?? null)?.toFixed(2) || "",
p.status,
p.placement_post?.post?.url || "",
p.invite_link,
]);
const csv = [headers.join(";"), ...rows.map((r) => r.join(";"))].join("\n");
const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" });
downloadBlob(blob, `${filename}.csv`);
};
const exportToExcel = (placements: Placement[], filename: string) => {
// Simple XLSX-like TSV format (opens in Excel)
const headers = [
"Канал",
"Username",
"Креатив",
"Дата",
"Стоимость",
"Подписки",
"Просмотры",
"CPS",
"CPM",
"Статус",
];
const rows = placements.map((p) => [
p.channel.title,
"",
"—",
p.details?.placement_at ? new Date(p.details.placement_at).toISOString().split("T")[0] : "",
p.details?.cost?.value?.toString() || "",
p.placement_post?.subscriptions_count.toString() || "0",
p.placement_post?.views_count?.toString() || "",
calculateCPS(p.details?.cost?.value ?? null, p.placement_post?.subscriptions_count ?? 0)?.toFixed(2) || "",
calculateCPM(p.details?.cost?.value ?? null, p.placement_post?.views_count ?? null)?.toFixed(2) || "",
p.status,
]);
const tsv = [headers.join("\t"), ...rows.map((r) => r.join("\t"))].join("\n");
const blob = new Blob(["\uFEFF" + tsv], {
type: "application/vnd.ms-excel;charset=utf-8;",
});
downloadBlob(blob, `${filename}.xls`);
};
const exportToTxt = (placements: Placement[], filename: string) => {
const lines = placements.map((p) => {
const cost = p.details?.cost?.value ?? null;
const subscriptions = p.placement_post?.subscriptions_count ?? 0;
const views = p.placement_post?.views_count ?? null;
const cps = calculateCPS(cost, subscriptions);
const cpm = calculateCPM(cost, views);
return [
`Канал: ${p.channel.title}`,
`Креатив: —`,
`Дата: ${p.details?.placement_at ? formatDate(p.details.placement_at) : "—"}`,
`Стоимость: ${formatCurrency(cost)}`,
`Подписки: ${p.placement_post?.subscriptions_count ?? "—"}`,
`Просмотры: ${p.placement_post?.views_count || "—"}`,
`CPS: ${cps ? formatCurrency(cps) : "—"}`,
`CPM: ${cpm ? formatCurrency(cpm) : "—"}`,
`Ссылка: ${p.invite_link || "—"}`,
"---",
].join("\n");
});
const text = lines.join("\n");
const blob = new Blob([text], { type: "text/plain;charset=utf-8;" });
downloadBlob(blob, `${filename}.txt`);
};
const downloadBlob = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
// ============================================================================
// Component
// ============================================================================
export default function PlacementsPage() {
const params = useParams();
const searchParams = useSearchParams();
const workspaceId = params?.workspaceId as string;
const { selectedProjects, getProjectFilterId, allProjectsSelected, hasPermission } = useWorkspace();
const projectFilterId = getProjectFilterId();
const [placements, setPlacements] = useState<Placement[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState("");
const [includeArchived, setIncludeArchived] = useState(false);
const [sortField, setSortField] = useState<SortField | null>(null);
const [sortOrder, setSortOrder] = useState<SortOrder>(null);
const [creativeFilterId, setCreativeFilterId] = useState<string | null>(searchParams.get("creative_id"));
// Aggregation settings
const [aggCost, setAggCost] = useState<AggFunc>("sum");
const [aggSubs, setAggSubs] = useState<AggFunc>("sum");
const [aggViews, setAggViews] = useState<AggFunc>("sum");
const [aggCps, setAggCps] = useState<AggFunc>("avg");
const [aggCpm, setAggCpm] = useState<AggFunc>("avg");
const canWrite = hasPermission("placements_write");
useEffect(() => {
const creativeId = searchParams.get("creative_id");
setCreativeFilterId(creativeId);
}, [searchParams]);
useEffect(() => {
loadPlacements();
}, [workspaceId, projectFilterId, includeArchived]);
const loadPlacements = async () => {
try {
setLoading(true);
const response = await demoAwarePlacementsApi.list(workspaceId, {
project_id: projectFilterId,
include_archived: includeArchived,
size: 100,
});
setPlacements(response.items);
} catch (err) {
console.error("Failed to load placements:", err);
} finally {
setLoading(false);
}
};
// Handle sort
const handleSort = (field: SortField) => {
if (sortField === field) {
if (sortOrder === "asc") {
setSortOrder("desc");
} else if (sortOrder === "desc") {
setSortField(null);
setSortOrder(null);
} else {
setSortOrder("asc");
}
} else {
setSortField(field);
setSortOrder("asc");
}
};
const getSortIcon = (field: SortField) => {
if (sortField !== field) return <ArrowUpDown className="h-4 w-4 ml-1" />;
if (sortOrder === "asc") return <ArrowUp className="h-4 w-4 ml-1" />;
if (sortOrder === "desc") return <ArrowDown className="h-4 w-4 ml-1" />;
return <ArrowUpDown className="h-4 w-4 ml-1" />;
};
// Filter and sort
const filteredPlacements = useMemo(() => {
return placements
.filter((p) => {
const matchesSearch =
p.channel.title.toLowerCase().includes(search.toLowerCase()) ||
(p.creative_id && p.creative_id.toString().toLowerCase().includes(search.toLowerCase()));
const matchesCreative = !creativeFilterId || p.creative_id === creativeFilterId;
return matchesSearch && matchesCreative;
})
.sort((a, b) => {
if (!sortField || !sortOrder) return 0;
let aVal: number | string = 0;
let bVal: number | string = 0;
const aCost = a.details?.cost?.value ?? null;
const bCost = b.details?.cost?.value ?? null;
const aSubs = a.placement_post?.subscriptions_count ?? 0;
const bSubs = b.placement_post?.subscriptions_count ?? 0;
const aViews = a.placement_post?.views_count ?? null;
const bViews = b.placement_post?.views_count ?? null;
switch (sortField) {
case "date":
const aDate = a.details?.placement_at || "";
const bDate = b.details?.placement_at || "";
return sortOrder === "asc"
? aDate.localeCompare(bDate)
: bDate.localeCompare(aDate);
case "cost":
aVal = aCost ?? 0;
bVal = bCost ?? 0;
break;
case "subscriptions":
aVal = aSubs;
bVal = bSubs;
break;
case "views":
aVal = aViews ?? 0;
bVal = bViews ?? 0;
break;
case "cps":
aVal = calculateCPS(aCost, aSubs) ?? 0;
bVal = calculateCPS(bCost, bSubs) ?? 0;
break;
case "cpm":
aVal = calculateCPM(aCost, aViews) ?? 0;
bVal = calculateCPM(bCost, bViews) ?? 0;
break;
case "status":
aVal = a.status;
bVal = b.status;
return sortOrder === "asc"
? aVal.localeCompare(bVal)
: bVal.localeCompare(aVal);
}
return sortOrder === "asc"
? (aVal as number) - (bVal as number)
: (bVal as number) - (aVal as number);
});
}, [placements, search, sortField, sortOrder]);
// Calculate totals with aggregation functions
const totals = useMemo(() => {
const costs = filteredPlacements.map((p) => p.details?.cost?.value).filter((c): c is number => c !== null);
const subs = filteredPlacements.map((p) => p.placement_post?.subscriptions_count ?? 0);
const views = filteredPlacements.map((p) => p.placement_post?.views_count).filter((v): v is number => v !== null);
const cpsValues = filteredPlacements
.map((p) => calculateCPS(p.details?.cost?.value ?? null, p.placement_post?.subscriptions_count ?? 0))
.filter((c): c is number => c !== null);
const cpmValues = filteredPlacements
.map((p) => calculateCPM(p.details?.cost?.value ?? null, p.placement_post?.views_count ?? null))
.filter((c): c is number => c !== null);
return {
cost: aggregationFunctions[aggCost].fn(costs),
subscriptions: aggregationFunctions[aggSubs].fn(subs),
views: aggregationFunctions[aggViews].fn(views),
cps: aggregationFunctions[aggCps].fn(cpsValues),
cpm: aggregationFunctions[aggCpm].fn(cpmValues),
};
}, [filteredPlacements, aggCost, aggSubs, aggViews, aggCps, aggCpm]);
// Export handlers
const handleExport = useCallback(
(format: "csv" | "excel" | "txt") => {
const filename = `placements_${new Date().toISOString().split("T")[0]}`;
switch (format) {
case "csv":
exportToCSV(filteredPlacements, filename);
break;
case "excel":
exportToExcel(filteredPlacements, filename);
break;
case "txt":
exportToTxt(filteredPlacements, filename);
break;
}
},
[filteredPlacements]
);
// Aggregation selector component
const AggSelector = ({
value,
onChange,
}: {
value: AggFunc;
onChange: (v: AggFunc) => void;
}) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-5 w-5 ml-1 opacity-50 hover:opacity-100">
<span className="text-[10px] font-mono">f</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Функция</DropdownMenuLabel>
{(Object.keys(aggregationFunctions) as AggFunc[]).map((key) => (
<DropdownMenuItem
key={key}
onClick={() => onChange(key)}
className={value === key ? "bg-accent" : ""}
>
{aggregationFunctions[key].label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
return (
<TooltipProvider>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: `/dashboard/${workspaceId}` },
{ label: "Размещения" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<div className="flex items-center justify-between">
<div className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight">Размещения</h1>
<div className="flex items-center gap-2">
<p className="text-muted-foreground">
{filteredPlacements.length} размещений
</p>
{creativeFilterId && (
<Badge variant="secondary" className="gap-1">
Креатив
<Link
href={`/dashboard/${workspaceId}/placements`}
className="hover:text-destructive"
>
<X className="h-3 w-3" />
</Link>
</Badge>
)}
</div>
</div>
<div className="flex items-center gap-2">
{/* Export Button */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline">
<Download className="h-4 w-4 mr-2" />
Экспорт
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleExport("excel")}>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Excel (.xls)
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleExport("csv")}>
<FileText className="h-4 w-4 mr-2" />
CSV
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleExport("txt")}>
<FileText className="h-4 w-4 mr-2" />
Текст (.txt)
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{canWrite && (
<Button asChild>
<Link href={`/dashboard/${workspaceId}/placements/new`}>
<Plus className="h-4 w-4 mr-2" />
Создать размещение
</Link>
</Button>
)}
</div>
</div>
<div className="flex items-center gap-4">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Поиск по каналу или креативу..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<ProjectSelector />
<div className="flex items-center gap-2">
<Checkbox
id="include-archived"
checked={includeArchived}
onCheckedChange={(checked) => setIncludeArchived(checked === true)}
/>
<Label htmlFor="include-archived" className="text-sm cursor-pointer">
Показать архивные
</Label>
</div>
</div>
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : filteredPlacements.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12">
<ShoppingCart className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">Нет размещений</h3>
<p className="text-muted-foreground text-center mb-4">
{search ? "Ничего не найдено по вашему запросу" : "Создайте первое размещение"}
</p>
{canWrite && !search && (
<Button asChild>
<Link href={`/dashboard/${workspaceId}/placements/new`}>
<Plus className="h-4 w-4 mr-2" />
Создать размещение
</Link>
</Button>
)}
</CardContent>
</Card>
) : (
<Card>
<Table>
<TableHeader>
<TableRow>
<TableHead>Канал</TableHead>
<TableHead>Креатив</TableHead>
<TableHead>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("date")}
>
Дата
{getSortIcon("date")}
</Button>
</TableHead>
<TableHead>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("cost")}
>
Стоимость
{getSortIcon("cost")}
</Button>
</TableHead>
<TableHead>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("subscriptions")}
>
Подписки
{getSortIcon("subscriptions")}
</Button>
</TableHead>
<TableHead>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("views")}
>
Просмотры
{getSortIcon("views")}
</Button>
</TableHead>
<TableHead>
<div className="flex items-center">
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("cps")}
>
CPS
{getSortIcon("cps")}
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
</TooltipTrigger>
<TooltipContent>Cost Per Subscription</TooltipContent>
</Tooltip>
</div>
</TableHead>
<TableHead>
<div className="flex items-center">
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("cpm")}
>
CPM
{getSortIcon("cpm")}
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
</TooltipTrigger>
<TooltipContent>Cost Per Mille (1000 views)</TooltipContent>
</Tooltip>
</div>
</TableHead>
<TableHead>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8"
onClick={() => handleSort("status")}
>
Статус
{getSortIcon("status")}
</Button>
</TableHead>
<TableHead className="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredPlacements.map((placement) => {
const cost = placement.details?.cost?.value ?? null;
const subscriptions = placement.placement_post?.subscriptions_count ?? 0;
const views = placement.placement_post?.views_count ?? null;
const cps = calculateCPS(cost, subscriptions);
const cpm = calculateCPM(cost, views);
return (
<TableRow key={placement.id}>
<TableCell>
<div className="font-medium">{placement.channel.title}</div>
</TableCell>
<TableCell>
<div className="text-sm"></div>
</TableCell>
<TableCell>{placement.details?.placement_at ? formatDate(placement.details.placement_at) : "—"}</TableCell>
<TableCell>{formatCurrency(cost)}</TableCell>
<TableCell>{formatNumber(subscriptions)}</TableCell>
<TableCell>{formatNumber(views)}</TableCell>
<TableCell>{cps ? formatCurrency(cps) : "—"}</TableCell>
<TableCell>{cpm ? formatCurrency(cpm) : "—"}</TableCell>
<TableCell>
<Badge
variant={placement.status === "Оплачено" ? "default" : "secondary"}
>
{placement.status}
</Badge>
</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`/dashboard/${workspaceId}/placements/${placement.id}`}>
<Eye className="h-4 w-4 mr-2" />
Подробнее
</Link>
</DropdownMenuItem>
{placement.placement_post?.post?.url && (
<DropdownMenuItem asChild>
<a
href={placement.placement_post.post.url}
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="h-4 w-4 mr-2" />
Открыть пост
</a>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
})}
</TableBody>
{/* Totals Row */}
<TableFooter>
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={3}>
<span className="text-muted-foreground">Итого</span>
</TableCell>
<TableCell>
<div className="flex items-center">
{formatCurrency(totals.cost)}
<AggSelector value={aggCost} onChange={setAggCost} />
</div>
</TableCell>
<TableCell>
<div className="flex items-center">
{formatNumber(totals.subscriptions)}
<AggSelector value={aggSubs} onChange={setAggSubs} />
</div>
</TableCell>
<TableCell>
<div className="flex items-center">
{formatNumber(totals.views)}
<AggSelector value={aggViews} onChange={setAggViews} />
</div>
</TableCell>
<TableCell>
<div className="flex items-center">
{totals.cps ? formatCurrency(totals.cps) : "—"}
<AggSelector value={aggCps} onChange={setAggCps} />
</div>
</TableCell>
<TableCell>
<div className="flex items-center">
{totals.cpm ? formatCurrency(totals.cpm) : "—"}
<AggSelector value={aggCpm} onChange={setAggCpm} />
</div>
</TableCell>
<TableCell colSpan={2}></TableCell>
</TableRow>
</TableFooter>
</Table>
</Card>
)}
</div>
</TooltipProvider>
);
}

View File

@@ -6,6 +6,7 @@
import { useEffect, useMemo, useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import {
Loader2,
@@ -36,8 +37,6 @@ import { DashboardHeader } from "@/components/layout/dashboard-header";
import { useWorkspace } from "@/components/providers/workspace-provider";
import { demoAwarePlacementsApi } from "@/lib/demo";
import { placementsApi, creativesApi } from "@/lib/api";
import { AddChannelDialog } from "@/components/dialog-add-channel";
import { CreatePlacementsDialog } from "@/components/dialog-create-placements";
import { FiltersModal, PlacementFilters } from "@/components/filters-modal";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
@@ -82,6 +81,7 @@ import { ColumnSelectorDialog } from "@/components/column-selector-dialog";
import { CreativeSelectDialog } from "@/components/creative-select-dialog";
import { PlacementStatusSelector } from "@/components/placement-status-selector";
import { PlacementPostStatusSelector } from "@/components/placement-post-status-selector";
import { PlacementWizard } from "@/components/placement-wizard";
import { cn } from "@/lib/utils";
import type {
Project,
@@ -933,13 +933,13 @@ function ChannelGroup({
{channel.username && (
<div className="flex items-center gap-1 ml-2">
<a
href={`https://telemetr.me/channel/${channel.username}`}
href={`https://telemetr.me/content/${channel.username}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-center h-6 w-6 hover:opacity-75 transition-opacity"
onClick={(e) => e.stopPropagation()}
>
<img src="/icons/telemetr.jpg" alt="TgStat" className="h-5 w-5 rounded" />
<Image src="/icons/telemetr.jpg" width={20} height={20} alt="TgStat" className="h-5 w-5 rounded" />
</a>
<a
href={`https://tgstat.ru/channel/@${channel.username}`}
@@ -948,7 +948,7 @@ function ChannelGroup({
className="flex items-center justify-center h-6 w-6 hover:opacity-75 transition-opacity"
onClick={(e) => e.stopPropagation()}
>
<img src="/icons/tgstat.jpg" alt="TgStat" className="h-5 w-5 rounded" />
<Image src="/icons/tgstat.jpg" width={20} height={20} alt="TgStat" className="h-5 w-5 rounded" />
</a>
</div>
)}
@@ -1086,10 +1086,9 @@ export default function PurchasePlanDetailPage() {
const [saveError, setSaveError] = useState<string | null>(null);
const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
// Create placements dialog
// Placement wizard state
const prefilledCreativeId = searchParams.get("creative_id");
const [prefilledChannelIds, setPrefilledChannelIds] = useState<string[] | null>(null);
const [showCreateDialog, setShowCreateDialog] = useState(false);
const [showPlacementWizard, setShowPlacementWizard] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
@@ -1109,6 +1108,9 @@ export default function PurchasePlanDetailPage() {
const [selectedPlacementForCreative, setSelectedPlacementForCreative] = useState<PlacementWithStats | null>(null);
const [creatives, setCreatives] = useState<Array<{ id: string; name: string; thumbnail_url?: string | null }>>([]);
// Placement wizard
const [wizardInitialCreative, setWizardInitialCreative] = useState<string | null>(null);
const loadCreatives = async () => {
try {
const response = await creativesApi.list(workspaceId, {
@@ -1169,19 +1171,15 @@ export default function PurchasePlanDetailPage() {
}
}, [projects, projectId]);
// Auto-open create dialog if creative_id is provided
// Handle URL params for placement wizard
useEffect(() => {
if (prefilledCreativeId && project) {
setShowCreateDialog(true);
const openPlacement = searchParams.get("openPlacement");
if (openPlacement === "true") {
const creativeId = searchParams.get("creative_id");
setWizardInitialCreative(creativeId);
setShowPlacementWizard(true);
}
}, [prefilledCreativeId, project]);
// Auto-open create dialog if channel_ids are provided
useEffect(() => {
if (prefilledChannelIds && project) {
setShowCreateDialog(true);
}
}, [prefilledChannelIds, project]);
}, [searchParams]);
useEffect(() => {
loadPlacements();
@@ -1700,32 +1698,10 @@ export default function PurchasePlanDetailPage() {
</div>
</div>
<div className="flex items-center gap-2">
<AddChannelDialog
workspaceId={workspaceId}
projectId={projectId}
existingPlacements={placements}
onSuccess={loadPlacements}
>
<Button variant="outline" disabled={isDemoMode}>
<Plus className="h-4 w-4 mr-2" />
Добавить канал
</Button>
</AddChannelDialog>
<CreatePlacementsDialog
workspaceId={workspaceId}
projectId={projectId}
existingPlacements={placements}
prefilledCreativeId={prefilledCreativeId}
prefilledChannelIds={prefilledChannelIds}
open={showCreateDialog}
onOpenChange={setShowCreateDialog}
onSuccess={loadPlacements}
>
<Button disabled={isDemoMode}>
<Plus className="h-4 w-4 mr-2" />
Создать размещения
</Button>
</CreatePlacementsDialog>
<Button disabled={isDemoMode} onClick={() => setShowPlacementWizard(true)}>
<Plus className="h-4 w-4 mr-2" />
Добавить размещения
</Button>
</div>
</div>
@@ -1950,6 +1926,15 @@ export default function PurchasePlanDetailPage() {
onClear={selectedPlacementForCreative ? () => handleClearCreative(selectedPlacementForCreative.id) : null}
currentCreativeId={selectedPlacementForCreative?.creative_id}
/>
<PlacementWizard
open={showPlacementWizard}
onOpenChange={setShowPlacementWizard}
workspaceId={workspaceId}
projectId={projectId}
initialCreativeId={wizardInitialCreative}
onSuccess={loadPlacements}
/>
</>
);
}