feat: platform update
This commit is contained in:
@@ -45,7 +45,22 @@ import {
|
|||||||
TooltipProvider,
|
TooltipProvider,
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/components/ui/tooltip";
|
} 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
|
// Helpers
|
||||||
@@ -70,6 +85,7 @@ type SortOrder = "asc" | "desc" | null;
|
|||||||
export default function ChannelsCatalogPage() {
|
export default function ChannelsCatalogPage() {
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const workspaceId = params?.workspaceId as string;
|
const workspaceId = params?.workspaceId as string;
|
||||||
|
const { currentProject, projects } = useWorkspace();
|
||||||
|
|
||||||
const [channels, setChannels] = useState<Channel[]>([]);
|
const [channels, setChannels] = useState<Channel[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -78,6 +94,11 @@ export default function ChannelsCatalogPage() {
|
|||||||
const [sortField, setSortField] = useState<SortField | null>(null);
|
const [sortField, setSortField] = useState<SortField | null>(null);
|
||||||
const [sortOrder, setSortOrder] = useState<SortOrder>(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(() => {
|
useEffect(() => {
|
||||||
const loadChannels = async () => {
|
const loadChannels = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -126,6 +147,23 @@ export default function ChannelsCatalogPage() {
|
|||||||
return <ArrowUpDown className="h-4 w-4 ml-1" />;
|
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
|
// Filter and sort channels
|
||||||
const filteredChannels = useMemo(() => {
|
const filteredChannels = useMemo(() => {
|
||||||
let result = [...channels];
|
let result = [...channels];
|
||||||
@@ -317,10 +355,8 @@ export default function ChannelsCatalogPage() {
|
|||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Button variant="outline" size="sm" asChild>
|
<Button variant="outline" size="sm" onClick={() => handleOpenPlacement(channel)}>
|
||||||
<a href={`/dashboard/${workspaceId}/placements/new?channel_id=${channel.id}`}>
|
|
||||||
Разместить
|
Разместить
|
||||||
</a>
|
|
||||||
</Button>
|
</Button>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
@@ -366,10 +402,8 @@ export default function ChannelsCatalogPage() {
|
|||||||
<Users className="h-4 w-4" />
|
<Users className="h-4 w-4" />
|
||||||
{formatNumber(channel.subscribers_count)}
|
{formatNumber(channel.subscribers_count)}
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" size="sm" asChild>
|
<Button variant="outline" size="sm" onClick={() => handleOpenPlacement(channel)}>
|
||||||
<a href={`/dashboard/${workspaceId}/placements/new?channel_id=${channel.id}`}>
|
|
||||||
Разместить
|
Разместить
|
||||||
</a>
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -378,6 +412,50 @@ export default function ChannelsCatalogPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</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>
|
</TooltipProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -26,9 +26,10 @@ import {
|
|||||||
Grid,
|
Grid,
|
||||||
List,
|
List,
|
||||||
FileText,
|
FileText,
|
||||||
Image,
|
Image as ImageIcon,
|
||||||
Video,
|
Video,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import Image from "next/image";
|
||||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||||
import { creativesApi } from "@/lib/api";
|
import { creativesApi } from "@/lib/api";
|
||||||
@@ -126,7 +127,7 @@ const getCreativeWord = (count: number): string => {
|
|||||||
const getMediaIcon = (mediaType: string) => {
|
const getMediaIcon = (mediaType: string) => {
|
||||||
switch (mediaType) {
|
switch (mediaType) {
|
||||||
case "photo":
|
case "photo":
|
||||||
return Image;
|
return ImageIcon;
|
||||||
case "video":
|
case "video":
|
||||||
return Video;
|
return Video;
|
||||||
case "animation":
|
case "animation":
|
||||||
@@ -236,11 +237,7 @@ export default function CreativesPage() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const handleCreateCreativeClick = () => {
|
const handleCreateCreativeClick = () => {
|
||||||
if (currentProject) {
|
|
||||||
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
|
|
||||||
} else {
|
|
||||||
setShowCreateDialog(true);
|
setShowCreateDialog(true);
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleOpenBotClick = () => {
|
const handleOpenBotClick = () => {
|
||||||
@@ -251,12 +248,6 @@ export default function CreativesPage() {
|
|||||||
setShowCreateDialog(false);
|
setShowCreateDialog(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCreateOnPlatformClick = () => {
|
|
||||||
if (!currentProject) return;
|
|
||||||
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
|
|
||||||
setShowCreateDialog(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCopyText = (text: string) => {
|
const handleCopyText = (text: string) => {
|
||||||
navigator.clipboard.writeText(text);
|
navigator.clipboard.writeText(text);
|
||||||
};
|
};
|
||||||
@@ -504,7 +495,7 @@ export default function CreativesPage() {
|
|||||||
asChild
|
asChild
|
||||||
>
|
>
|
||||||
<Link
|
<Link
|
||||||
href={`/dashboard/${workspaceId}/placements/new?creative_id=${creative.id}`}
|
href={`/dashboard/${workspaceId}/purchase-plans/${creative.project_id}?openPlacement=true&creative_id=${creative.id}`}
|
||||||
title="Создать размещение"
|
title="Создать размещение"
|
||||||
>
|
>
|
||||||
<Plus className="h-3.5 w-3.5" />
|
<Plus className="h-3.5 w-3.5" />
|
||||||
@@ -673,48 +664,46 @@ export default function CreativesPage() {
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Создание креатива</DialogTitle>
|
<DialogTitle>Создание креатива</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Создание креатива через Telegram бота или на платформе
|
Креативы создаются через Telegram бота
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="space-y-4 py-4">
|
<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">
|
<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
|
<Button
|
||||||
variant="outline"
|
variant="default"
|
||||||
className="w-full justify-start"
|
className="w-full"
|
||||||
onClick={handleOpenBotClick}
|
onClick={handleOpenBotClick}
|
||||||
|
disabled={!currentProject}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between w-full">
|
<Image src="/icons/telegram.svg" alt="Telegram" width={20} height={20} className="w-5 h-5 mr-2" />
|
||||||
<div className="text-left">
|
Перейти в бота
|
||||||
<p className="font-medium">Через Telegram бота</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Перешлите сообщение боту
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Button>
|
</Button>
|
||||||
{currentProject && (
|
{!currentProject && (
|
||||||
<Button
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
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>
|
</p>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Button>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
|
|||||||
@@ -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>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
Loader2,
|
Loader2,
|
||||||
@@ -36,8 +37,6 @@ import { DashboardHeader } from "@/components/layout/dashboard-header";
|
|||||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||||
import { demoAwarePlacementsApi } from "@/lib/demo";
|
import { demoAwarePlacementsApi } from "@/lib/demo";
|
||||||
import { placementsApi, creativesApi } from "@/lib/api";
|
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 { FiltersModal, PlacementFilters } from "@/components/filters-modal";
|
||||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { Badge } from "@/components/ui/badge";
|
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 { CreativeSelectDialog } from "@/components/creative-select-dialog";
|
||||||
import { PlacementStatusSelector } from "@/components/placement-status-selector";
|
import { PlacementStatusSelector } from "@/components/placement-status-selector";
|
||||||
import { PlacementPostStatusSelector } from "@/components/placement-post-status-selector";
|
import { PlacementPostStatusSelector } from "@/components/placement-post-status-selector";
|
||||||
|
import { PlacementWizard } from "@/components/placement-wizard";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type {
|
import type {
|
||||||
Project,
|
Project,
|
||||||
@@ -933,13 +933,13 @@ function ChannelGroup({
|
|||||||
{channel.username && (
|
{channel.username && (
|
||||||
<div className="flex items-center gap-1 ml-2">
|
<div className="flex items-center gap-1 ml-2">
|
||||||
<a
|
<a
|
||||||
href={`https://telemetr.me/channel/${channel.username}`}
|
href={`https://telemetr.me/content/${channel.username}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="flex items-center justify-center h-6 w-6 hover:opacity-75 transition-opacity"
|
className="flex items-center justify-center h-6 w-6 hover:opacity-75 transition-opacity"
|
||||||
onClick={(e) => e.stopPropagation()}
|
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>
|
||||||
<a
|
<a
|
||||||
href={`https://tgstat.ru/channel/@${channel.username}`}
|
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"
|
className="flex items-center justify-center h-6 w-6 hover:opacity-75 transition-opacity"
|
||||||
onClick={(e) => e.stopPropagation()}
|
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>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -1086,10 +1086,9 @@ export default function PurchasePlanDetailPage() {
|
|||||||
const [saveError, setSaveError] = useState<string | null>(null);
|
const [saveError, setSaveError] = useState<string | null>(null);
|
||||||
const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
|
const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
|
||||||
|
|
||||||
// Create placements dialog
|
// Placement wizard state
|
||||||
const prefilledCreativeId = searchParams.get("creative_id");
|
const prefilledCreativeId = searchParams.get("creative_id");
|
||||||
const [prefilledChannelIds, setPrefilledChannelIds] = useState<string[] | null>(null);
|
const [showPlacementWizard, setShowPlacementWizard] = useState(false);
|
||||||
const [showCreateDialog, setShowCreateDialog] = useState(false);
|
|
||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const [statusFilter, setStatusFilter] = useState("all");
|
const [statusFilter, setStatusFilter] = useState("all");
|
||||||
@@ -1109,6 +1108,9 @@ export default function PurchasePlanDetailPage() {
|
|||||||
const [selectedPlacementForCreative, setSelectedPlacementForCreative] = useState<PlacementWithStats | null>(null);
|
const [selectedPlacementForCreative, setSelectedPlacementForCreative] = useState<PlacementWithStats | null>(null);
|
||||||
const [creatives, setCreatives] = useState<Array<{ id: string; name: string; thumbnail_url?: string | 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 () => {
|
const loadCreatives = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await creativesApi.list(workspaceId, {
|
const response = await creativesApi.list(workspaceId, {
|
||||||
@@ -1169,19 +1171,15 @@ export default function PurchasePlanDetailPage() {
|
|||||||
}
|
}
|
||||||
}, [projects, projectId]);
|
}, [projects, projectId]);
|
||||||
|
|
||||||
// Auto-open create dialog if creative_id is provided
|
// Handle URL params for placement wizard
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (prefilledCreativeId && project) {
|
const openPlacement = searchParams.get("openPlacement");
|
||||||
setShowCreateDialog(true);
|
if (openPlacement === "true") {
|
||||||
|
const creativeId = searchParams.get("creative_id");
|
||||||
|
setWizardInitialCreative(creativeId);
|
||||||
|
setShowPlacementWizard(true);
|
||||||
}
|
}
|
||||||
}, [prefilledCreativeId, project]);
|
}, [searchParams]);
|
||||||
|
|
||||||
// Auto-open create dialog if channel_ids are provided
|
|
||||||
useEffect(() => {
|
|
||||||
if (prefilledChannelIds && project) {
|
|
||||||
setShowCreateDialog(true);
|
|
||||||
}
|
|
||||||
}, [prefilledChannelIds, project]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadPlacements();
|
loadPlacements();
|
||||||
@@ -1700,32 +1698,10 @@ export default function PurchasePlanDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<AddChannelDialog
|
<Button disabled={isDemoMode} onClick={() => setShowPlacementWizard(true)}>
|
||||||
workspaceId={workspaceId}
|
|
||||||
projectId={projectId}
|
|
||||||
existingPlacements={placements}
|
|
||||||
onSuccess={loadPlacements}
|
|
||||||
>
|
|
||||||
<Button variant="outline" disabled={isDemoMode}>
|
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
Добавить канал
|
Добавить размещения
|
||||||
</Button>
|
</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>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1950,6 +1926,15 @@ export default function PurchasePlanDetailPage() {
|
|||||||
onClear={selectedPlacementForCreative ? () => handleClearCreative(selectedPlacementForCreative.id) : null}
|
onClear={selectedPlacementForCreative ? () => handleClearCreative(selectedPlacementForCreative.id) : null}
|
||||||
currentCreativeId={selectedPlacementForCreative?.creative_id}
|
currentCreativeId={selectedPlacementForCreative?.creative_id}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<PlacementWizard
|
||||||
|
open={showPlacementWizard}
|
||||||
|
onOpenChange={setShowPlacementWizard}
|
||||||
|
workspaceId={workspaceId}
|
||||||
|
projectId={projectId}
|
||||||
|
initialCreativeId={wizardInitialCreative}
|
||||||
|
onSuccess={loadPlacements}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
317
components/channel-input.tsx
Normal file
317
components/channel-input.tsx
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useMemo, useEffect } from "react";
|
||||||
|
import { Loader2, Check, X, AlertCircle, ExternalLink, Plus, Trash2 } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { channelsApi } from "@/lib/api";
|
||||||
|
import type { Channel } from "@/lib/types/api";
|
||||||
|
|
||||||
|
export type ParsedChannel = {
|
||||||
|
input: string;
|
||||||
|
type: "invite_link" | "username" | "telemetr" | "tgstat" | "unknown";
|
||||||
|
normalized: string | null;
|
||||||
|
isValid: boolean;
|
||||||
|
channel?: Channel;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface ChannelInputProps {
|
||||||
|
value: ParsedChannel[];
|
||||||
|
onChange: (channels: ParsedChannel[]) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
maxItems?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CHANNEL_PATTERNS = [
|
||||||
|
{ regex: /^https:\/\/t\.me\/(.+)$/i, type: "username", normalize: (m: string) => m.replace(/@/, "").toLowerCase() },
|
||||||
|
{ regex: /^https:\/\/t\.me\/+([a-zA-Z0-9_]+)$/i, type: "invite_link", normalize: (m: string) => m.toUpperCase() },
|
||||||
|
{ regex: /^@([a-zA-Z0-9_]+)$/i, type: "username", normalize: (m: string) => m.replace(/@/, "").toLowerCase() },
|
||||||
|
{ regex: /^([a-zA-Z0-9_]+)$/i, type: "username", normalize: (m: string) => m.toLowerCase() },
|
||||||
|
{ regex: /^https:\/\/telemetr\.me\/content\/([a-zA-Z0-9_]+)$/i, type: "telemetr", normalize: (m: string) => m.toLowerCase() },
|
||||||
|
{ regex: /^https:\/\/tgstat\.ru\/channel\/@?([a-zA-Z0-9_]+)$/i, type: "tgstat", normalize: (m: string) => m.replace(/@/, "").toLowerCase() },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function ChannelInput({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = "Введите каналы (ссылки или @username), каждый с новой строки",
|
||||||
|
maxItems = 50,
|
||||||
|
}: ChannelInputProps) {
|
||||||
|
const [input, setInput] = useState("");
|
||||||
|
const [parsing, setParsing] = useState(false);
|
||||||
|
const [validating, setValidating] = useState(false);
|
||||||
|
|
||||||
|
const parsedResults = useMemo(() => {
|
||||||
|
return value;
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
const handleParse = async () => {
|
||||||
|
if (!input.trim()) return;
|
||||||
|
|
||||||
|
setParsing(true);
|
||||||
|
|
||||||
|
const lines = input
|
||||||
|
.split(/[\n,;]/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const newChannels: ParsedChannel[] = [];
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
let matched = false;
|
||||||
|
|
||||||
|
for (const pattern of CHANNEL_PATTERNS) {
|
||||||
|
const match = line.match(pattern.regex);
|
||||||
|
if (match) {
|
||||||
|
const normalized = pattern.normalize(match[1]);
|
||||||
|
newChannels.push({
|
||||||
|
input: line,
|
||||||
|
type: pattern.type as ParsedChannel["type"],
|
||||||
|
normalized,
|
||||||
|
isValid: false,
|
||||||
|
});
|
||||||
|
matched = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matched) {
|
||||||
|
newChannels.push({
|
||||||
|
input: line,
|
||||||
|
type: "unknown",
|
||||||
|
normalized: null,
|
||||||
|
isValid: false,
|
||||||
|
error: "Неизвестный формат",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setParsing(false);
|
||||||
|
|
||||||
|
// Validate through API
|
||||||
|
await validateChannels(newChannels);
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateChannels = async (channels: ParsedChannel[]) => {
|
||||||
|
setValidating(true);
|
||||||
|
|
||||||
|
const results: ParsedChannel[] = [];
|
||||||
|
|
||||||
|
for (const channel of channels) {
|
||||||
|
if (!channel.normalized) {
|
||||||
|
results.push(channel);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Try to find channel by different identifiers
|
||||||
|
let foundChannel: Channel | undefined;
|
||||||
|
|
||||||
|
if (channel.type === "invite_link") {
|
||||||
|
// Search by invite link pattern
|
||||||
|
const allChannels = await channelsApi.list({ size: 100 });
|
||||||
|
foundChannel = allChannels.items.find(
|
||||||
|
(c) => c.username?.toUpperCase() === channel.normalized?.toUpperCase()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Search by username
|
||||||
|
const allChannels = await channelsApi.list({ size: 100 });
|
||||||
|
foundChannel = allChannels.items.find(
|
||||||
|
(c) => c.username?.toLowerCase() === channel.normalized?.toLowerCase()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foundChannel) {
|
||||||
|
results.push({
|
||||||
|
...channel,
|
||||||
|
isValid: true,
|
||||||
|
channel: foundChannel,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
results.push({
|
||||||
|
...channel,
|
||||||
|
isValid: false,
|
||||||
|
error: "Канал не найден в базе",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
results.push({
|
||||||
|
...channel,
|
||||||
|
isValid: false,
|
||||||
|
error: "Ошибка проверки",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setValidating(false);
|
||||||
|
onChange([...parsedResults, ...results].slice(0, maxItems));
|
||||||
|
setInput("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemove = (index: number) => {
|
||||||
|
const newValue = [...parsedResults];
|
||||||
|
newValue.splice(index, 1);
|
||||||
|
onChange(newValue);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClear = () => {
|
||||||
|
onChange([]);
|
||||||
|
setInput("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTypeIcon = (type: ParsedChannel["type"]) => {
|
||||||
|
switch (type) {
|
||||||
|
case "invite_link":
|
||||||
|
return "🔗";
|
||||||
|
case "username":
|
||||||
|
return "@";
|
||||||
|
case "telemetr":
|
||||||
|
return "📊";
|
||||||
|
case "tgstat":
|
||||||
|
return "📈";
|
||||||
|
default:
|
||||||
|
return "?";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validCount = parsedResults.filter((c) => c.isValid).length;
|
||||||
|
const invalidCount = parsedResults.filter((c) => !c.isValid).length;
|
||||||
|
const existingCount = parsedResults.filter((c) => c.isValid && c.channel).length;
|
||||||
|
const newCount = parsedResults.filter((c) => c.isValid && !c.channel).length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Input area */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Textarea
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => setInput(e.target.value)}
|
||||||
|
placeholder={placeholder}
|
||||||
|
className="min-h-[100px] flex-1"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
handleParse();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Parse button */}
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button
|
||||||
|
onClick={handleParse}
|
||||||
|
disabled={!input.trim() || parsing || validating}
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
{parsing || validating ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Проверка...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Добавить каналы
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Results summary */}
|
||||||
|
{parsedResults.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-2 text-sm">
|
||||||
|
{validCount > 0 && (
|
||||||
|
<Badge variant="secondary" className="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400">
|
||||||
|
{validCount} найдено
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{invalidCount > 0 && (
|
||||||
|
<Badge variant="secondary" className="bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400">
|
||||||
|
{invalidCount} не найдено
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{newCount > 0 && (
|
||||||
|
<Badge variant="secondary" className="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400">
|
||||||
|
{newCount} новых
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{existingCount > 0 && (
|
||||||
|
<Badge variant="secondary">
|
||||||
|
{existingCount} существующих
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Results list */}
|
||||||
|
{parsedResults.length > 0 && (
|
||||||
|
<div className="space-y-2 max-h-64 overflow-y-auto border rounded-lg">
|
||||||
|
{parsedResults.map((item, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-3 p-3 border-b last:border-0",
|
||||||
|
item.isValid
|
||||||
|
? "bg-muted/30"
|
||||||
|
: "bg-destructive/5"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-muted flex items-center justify-center text-sm">
|
||||||
|
{item.isValid ? (
|
||||||
|
item.channel ? (
|
||||||
|
<Check className="h-4 w-4 text-green-600" />
|
||||||
|
) : (
|
||||||
|
<Plus className="h-4 w-4 text-blue-600" />
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<X className="h-4 w-4 text-red-600" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-medium truncate">{getTypeIcon(item.type)} {item.normalized || item.input}</span>
|
||||||
|
{!item.isValid && item.error && (
|
||||||
|
<Badge variant="destructive" className="text-xs">
|
||||||
|
{item.error}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{item.channel && (
|
||||||
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
|
{item.channel.title}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => handleRemove(index)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
{parsedResults.length > 0 && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleClear}>
|
||||||
|
Очистить всё
|
||||||
|
</Button>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
Нажмите Enter для быстрого добавления
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import { Loader2, Plus, AlertCircle, CheckCircle2 } from "lucide-react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { parseChannelInput } from "@/lib/utils/channel-parser";
|
|
||||||
import { channelsApi, placementsApi } from "@/lib/api";
|
|
||||||
import type { Placement } from "@/lib/types/api";
|
|
||||||
|
|
||||||
interface AddChannelDialogProps {
|
|
||||||
workspaceId: string;
|
|
||||||
projectId: string;
|
|
||||||
existingPlacements: Placement[];
|
|
||||||
onSuccess: () => void;
|
|
||||||
children?: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AddChannelDialog({
|
|
||||||
workspaceId,
|
|
||||||
projectId,
|
|
||||||
existingPlacements,
|
|
||||||
onSuccess,
|
|
||||||
children,
|
|
||||||
}: AddChannelDialogProps) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [inputValue, setInputValue] = useState("");
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [success, setSuccess] = useState(false);
|
|
||||||
|
|
||||||
const existingUsernames = new Set(
|
|
||||||
existingPlacements
|
|
||||||
.map((p) => p.channel.username?.toLowerCase())
|
|
||||||
.filter(Boolean)
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
setSuccess(false);
|
|
||||||
|
|
||||||
const username = parseChannelInput(inputValue);
|
|
||||||
|
|
||||||
if (!username) {
|
|
||||||
setError("Не удалось распознать username из ссылки");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existingUsernames.has(username.toLowerCase())) {
|
|
||||||
setError("Этот канал уже добавлен в проект");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
const username = parseChannelInput(inputValue);
|
|
||||||
|
|
||||||
if (!username) {
|
|
||||||
setError("Не удалось распознать username из ссылки");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existingUsernames.has(username.toLowerCase())) {
|
|
||||||
setError("Этот канал уже добавлен в проект");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 1: Create channel via API to get channel_id
|
|
||||||
const createResponse = await channelsApi.create([{ username }]);
|
|
||||||
const channelId = createResponse.results[0]?.channel.id;
|
|
||||||
|
|
||||||
if (!channelId) {
|
|
||||||
setError("Не удалось получить ID канала");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 2: Create empty placement with channel_id
|
|
||||||
await placementsApi.createBulk(workspaceId, projectId, {
|
|
||||||
channels: [
|
|
||||||
{
|
|
||||||
channel_id: channelId,
|
|
||||||
status: "Без статуса",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
setSuccess(true);
|
|
||||||
setInputValue("");
|
|
||||||
|
|
||||||
// Close dialog after short delay
|
|
||||||
setTimeout(() => {
|
|
||||||
setOpen(false);
|
|
||||||
setSuccess(false);
|
|
||||||
onSuccess();
|
|
||||||
}, 1500);
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error("Failed to add channel:", err);
|
|
||||||
setError(err.detail || "Не удалось добавить канал");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleOpenChange = (isOpen: boolean) => {
|
|
||||||
if (!isOpen) {
|
|
||||||
setInputValue("");
|
|
||||||
setError(null);
|
|
||||||
setSuccess(false);
|
|
||||||
}
|
|
||||||
setOpen(isOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
const examples = [
|
|
||||||
"t.me/rian_ru",
|
|
||||||
"@rian_ru",
|
|
||||||
"telemetr.me/content/rian_ru",
|
|
||||||
"tgstat.ru/channel/@rian_ru",
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
|
||||||
<DialogTrigger asChild>{children}</DialogTrigger>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Добавить канал</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Введите ссылку или username канала для проверки и добавления в проект
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="channel-input">Ссылка или username канала</Label>
|
|
||||||
<Input
|
|
||||||
id="channel-input"
|
|
||||||
placeholder="https://t.me/rian_ru или @rian_ru"
|
|
||||||
value={inputValue}
|
|
||||||
onChange={(e) => setInputValue(e.target.value)}
|
|
||||||
disabled={loading}
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Поддерживаются: t.me, telemetr.me, tgstat.ru, а также username с @
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="flex items-center gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm">
|
|
||||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{success && (
|
|
||||||
<div className="flex items-center gap-2 p-3 rounded-md bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 text-sm">
|
|
||||||
<CheckCircle2 className="h-4 w-4 shrink-0" />
|
|
||||||
Канал успешно добавлен!
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-xs text-muted-foreground">Примеры:</p>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{examples.map((example) => (
|
|
||||||
<button
|
|
||||||
key={example}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setInputValue(example)}
|
|
||||||
className="text-xs px-2 py-1 rounded-md bg-muted hover:bg-muted/80 transition-colors"
|
|
||||||
>
|
|
||||||
{example}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<DialogFooter>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => setOpen(false)}
|
|
||||||
disabled={loading}
|
|
||||||
>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button type="submit" disabled={loading || !inputValue.trim()}>
|
|
||||||
{loading ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
||||||
Проверка...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
|
||||||
Проверить и добавить
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,591 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { Loader2, Plus, Check, ChevronRight, X, AlertCircle, BookOpen } from "lucide-react";
|
|
||||||
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 {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { parseChannelInput } from "@/lib/utils/channel-parser";
|
|
||||||
import { placementsApi, creativesApi, channelsApi } from "@/lib/api";
|
|
||||||
import type { Placement, Creative, Channel } from "@/lib/types/api";
|
|
||||||
import { Badge } from "./ui/badge";
|
|
||||||
|
|
||||||
interface ChannelInput {
|
|
||||||
username: string;
|
|
||||||
channelId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CreatePlacementsDialogProps {
|
|
||||||
workspaceId: string;
|
|
||||||
projectId: string;
|
|
||||||
existingPlacements: Placement[];
|
|
||||||
prefilledCreativeId?: string | null;
|
|
||||||
prefilledChannelIds?: string[] | null;
|
|
||||||
open?: boolean;
|
|
||||||
onOpenChange?: (open: boolean) => void;
|
|
||||||
onSuccess: () => void;
|
|
||||||
children?: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_STATUS = "Согласование условий";
|
|
||||||
const DEFAULT_PLACEMENT_TYPE = "standard";
|
|
||||||
|
|
||||||
export function CreatePlacementsDialog({
|
|
||||||
workspaceId,
|
|
||||||
projectId,
|
|
||||||
existingPlacements,
|
|
||||||
prefilledCreativeId = null,
|
|
||||||
prefilledChannelIds = null,
|
|
||||||
open: controlledOpen,
|
|
||||||
onOpenChange,
|
|
||||||
onSuccess,
|
|
||||||
children,
|
|
||||||
}: CreatePlacementsDialogProps) {
|
|
||||||
const [internalOpen, setInternalOpen] = useState(false);
|
|
||||||
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
|
||||||
|
|
||||||
const [step, setStep] = useState(1);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const [newChannelInput, setNewChannelInput] = useState("");
|
|
||||||
const [selectedChannels, setSelectedChannels] = useState<ChannelInput[]>([]);
|
|
||||||
const [existingChannels, setExistingChannels] = useState<string[]>([]);
|
|
||||||
const [projectChannels, setProjectChannels] = useState<Channel[]>([]);
|
|
||||||
const [creativeId, setCreativeId] = useState<string | null>(prefilledCreativeId);
|
|
||||||
const [format, setFormat] = useState("");
|
|
||||||
const [cost, setCost] = useState("");
|
|
||||||
const [placementDate, setPlacementDate] = useState("");
|
|
||||||
const [comment, setComment] = useState("");
|
|
||||||
const [creatives, setCreatives] = useState<Creative[]>([]);
|
|
||||||
const [creating, setCreating] = useState(false);
|
|
||||||
const [createdCount, setCreatedCount] = useState<number | null>(null);
|
|
||||||
|
|
||||||
const handleOpenChange = (isOpen: boolean) => {
|
|
||||||
setInternalOpen(isOpen);
|
|
||||||
onOpenChange?.(isOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleTriggerClick = () => {
|
|
||||||
resetForm();
|
|
||||||
setInternalOpen(true);
|
|
||||||
onOpenChange?.(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setStep(1);
|
|
||||||
setNewChannelInput("");
|
|
||||||
setSelectedChannels([]);
|
|
||||||
setExistingChannels([]);
|
|
||||||
setProjectChannels([]);
|
|
||||||
setCreativeId(prefilledCreativeId);
|
|
||||||
setFormat("");
|
|
||||||
setCost("");
|
|
||||||
setPlacementDate("");
|
|
||||||
setComment("");
|
|
||||||
setError(null);
|
|
||||||
setCreatedCount(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const existingUsernames = new Set(
|
|
||||||
existingPlacements
|
|
||||||
.map((p) => p.channel.username?.toLowerCase())
|
|
||||||
.filter(Boolean)
|
|
||||||
);
|
|
||||||
|
|
||||||
const getExistingChannelIdByUsername = (usernameLower: string): string | null => {
|
|
||||||
const matched = existingPlacements.find(
|
|
||||||
(p) => p.channel.username?.toLowerCase() === usernameLower
|
|
||||||
);
|
|
||||||
return matched?.channel.id ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
loadCreatives();
|
|
||||||
loadProjectChannels();
|
|
||||||
loadPrefilledChannels();
|
|
||||||
}
|
|
||||||
}, [isOpen, workspaceId, projectId, prefilledCreativeId, prefilledChannelIds]);
|
|
||||||
|
|
||||||
const loadCreatives = async () => {
|
|
||||||
try {
|
|
||||||
const response = await creativesApi.list(workspaceId, {
|
|
||||||
project_id: projectId,
|
|
||||||
include_archived: false,
|
|
||||||
size: 100,
|
|
||||||
});
|
|
||||||
setCreatives(response.items);
|
|
||||||
|
|
||||||
if (prefilledCreativeId && response.items.length > 0) {
|
|
||||||
const prefilled = response.items.find((c) => c.id === prefilledCreativeId);
|
|
||||||
if (prefilled) {
|
|
||||||
setCreativeId(prefilled.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to load creatives:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadProjectChannels = async () => {
|
|
||||||
try {
|
|
||||||
const projectPlacements = await placementsApi.getByProject(workspaceId, projectId);
|
|
||||||
const channels = projectPlacements.map((p) => p.channel);
|
|
||||||
setProjectChannels(channels);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to load project channels:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadPrefilledChannels = async () => {
|
|
||||||
if (!prefilledChannelIds || prefilledChannelIds.length === 0) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const projectPlacements = await placementsApi.getByProject(workspaceId, projectId);
|
|
||||||
const prefilledChannels = projectPlacements
|
|
||||||
.filter((p) => prefilledChannelIds.includes(p.channel.id))
|
|
||||||
.map((p) => ({
|
|
||||||
username: p.channel.username || p.channel.title,
|
|
||||||
channelId: p.channel.id,
|
|
||||||
}));
|
|
||||||
|
|
||||||
setSelectedChannels(prefilledChannels);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to load prefilled channels:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const addChannel = async () => {
|
|
||||||
const username = parseChannelInput(newChannelInput);
|
|
||||||
if (!username) {
|
|
||||||
setError("Не удалось распознать username");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lowerUsername = username.toLowerCase();
|
|
||||||
if (selectedChannels.some((c) => c.username.toLowerCase() === lowerUsername)) {
|
|
||||||
setError("Канал уже добавлен в список");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectChannel = projectChannels.find((c) => c.username?.toLowerCase() === lowerUsername);
|
|
||||||
if (projectChannel) {
|
|
||||||
setSelectedChannels([...selectedChannels, { username, channelId: projectChannel.id }]);
|
|
||||||
setNewChannelInput("");
|
|
||||||
setError(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existingUsernames.has(lowerUsername)) {
|
|
||||||
const existingChannelId = getExistingChannelIdByUsername(lowerUsername);
|
|
||||||
if (!existingChannelId) {
|
|
||||||
setError("Не удалось найти ID канала в проекте");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setSelectedChannels([...selectedChannels, { username, channelId: existingChannelId }]);
|
|
||||||
setNewChannelInput("");
|
|
||||||
setError(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const createResponse = await channelsApi.create([{ username }]);
|
|
||||||
const channelId = createResponse.results[0]?.channel.id;
|
|
||||||
|
|
||||||
if (!channelId) {
|
|
||||||
setError("Не удалось получить ID канала");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSelectedChannels([...selectedChannels, { username, channelId }]);
|
|
||||||
setNewChannelInput("");
|
|
||||||
setError(null);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to create channel:", err);
|
|
||||||
setError("Не удалось создать канал");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const removeChannel = (username: string) => {
|
|
||||||
setSelectedChannels(selectedChannels.filter((c) => c.username !== username));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
e.preventDefault();
|
|
||||||
addChannel();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const canProceedStep1 = selectedChannels.length > 0;
|
|
||||||
|
|
||||||
const handleCreate = async () => {
|
|
||||||
try {
|
|
||||||
setCreating(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
const details: any = {};
|
|
||||||
details.placement_type = DEFAULT_PLACEMENT_TYPE;
|
|
||||||
if (format) details.format = format;
|
|
||||||
if (cost) details.cost = { type: "fixed", value: parseFloat(cost) };
|
|
||||||
if (placementDate) details.placement_at = new Date(placementDate).toISOString();
|
|
||||||
if (comment) details.comment = comment;
|
|
||||||
|
|
||||||
await placementsApi.createBulk(workspaceId, projectId, {
|
|
||||||
creative_id: creativeId || undefined,
|
|
||||||
channels: selectedChannels.map((c) => ({
|
|
||||||
channel_id: c.channelId,
|
|
||||||
status: DEFAULT_STATUS,
|
|
||||||
})),
|
|
||||||
details: Object.keys(details).length > 0 ? details : undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
setCreatedCount(selectedChannels.length);
|
|
||||||
onSuccess();
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error("Failed to create placements:", err);
|
|
||||||
setError(err.detail || "Не удалось создать размещения");
|
|
||||||
setCreating(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const selectedCreative = creatives.find((c) => c.id === creativeId);
|
|
||||||
const isControlled = controlledOpen !== undefined;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
|
||||||
<DialogTrigger asChild onClick={isControlled ? undefined : handleTriggerClick}>
|
|
||||||
{children}
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent className="max-w-2xl">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Создать размещения</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Шаг {step} из 3:{" "}
|
|
||||||
{step === 1 && "Выберите каналы"}
|
|
||||||
{step === 2 && "Укажите параметры"}
|
|
||||||
{step === 3 && "Подтвердите создание"}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
{createdCount !== null ? (
|
|
||||||
<div className="py-8 text-center">
|
|
||||||
<div className="inline-flex items-center justify-center h-16 w-16 rounded-full bg-emerald-100 text-emerald-600 mb-4">
|
|
||||||
<Check className="h-8 w-8" />
|
|
||||||
</div>
|
|
||||||
<h3 className="text-lg font-semibold mb-2">
|
|
||||||
Размещения созданы!
|
|
||||||
</h3>
|
|
||||||
<p className="text-muted-foreground">
|
|
||||||
Создано {createdCount} размещений
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="flex items-center justify-center gap-2 mb-6">
|
|
||||||
{[1, 2, 3].map((s) => (
|
|
||||||
<div
|
|
||||||
key={s}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-2",
|
|
||||||
s < 3 && "mr-4"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex items-center justify-center h-8 w-8 rounded-full text-sm font-medium",
|
|
||||||
step === s
|
|
||||||
? "bg-primary text-primary-foreground"
|
|
||||||
: step > s
|
|
||||||
? "bg-emerald-500 text-white"
|
|
||||||
: "bg-muted text-muted-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{step > s ? <Check className="h-4 w-4" /> : s}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="flex items-center gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm mb-4">
|
|
||||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === 1 && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Добавить канал</Label>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Input
|
|
||||||
placeholder="t.me/username или @username"
|
|
||||||
value={newChannelInput}
|
|
||||||
onChange={(e) => setNewChannelInput(e.target.value)}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
disabled={loading}
|
|
||||||
/>
|
|
||||||
<Button type="button" onClick={addChannel} disabled={!newChannelInput.trim()}>
|
|
||||||
<Plus className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Поддерживаются: t.me, telemetr.me, tgstat.ru, username с @
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{selectedChannels.length > 0 && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Выбранные каналы ({selectedChannels.length})</Label>
|
|
||||||
<div className="max-h-48 overflow-y-auto space-y-2">
|
|
||||||
{selectedChannels.map((channel) => (
|
|
||||||
<div
|
|
||||||
key={channel.username}
|
|
||||||
className="flex items-center justify-between p-2 rounded-md bg-muted"
|
|
||||||
>
|
|
||||||
<span className="text-sm">@{channel.username}</span>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={() => removeChannel(channel.username)}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{projectChannels.length > 0 && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Label className="text-base">Существующие каналы проекта</Label>
|
|
||||||
<Badge variant="outline" className="text-xs">
|
|
||||||
{projectChannels.length}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="max-h-48 overflow-y-auto space-y-2">
|
|
||||||
{projectChannels.map((channel) => (
|
|
||||||
<div
|
|
||||||
key={channel.id}
|
|
||||||
className="flex items-center justify-between p-2 rounded-md bg-muted"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm font-medium">{channel.title}</span>
|
|
||||||
{channel.username && (
|
|
||||||
<span className="text-xs text-muted-foreground">@{channel.username}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{selectedChannels.some((c) => c.channelId === channel.id) ? (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={() => removeChannel(channel.username || channel.id)}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
const channelId = channel.id;
|
|
||||||
const username = channel.username || channel.id;
|
|
||||||
setSelectedChannels([...selectedChannels, { username, channelId }]);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Plus className="h-4 w-4 mr-1" />
|
|
||||||
Выбрать
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === 2 && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Креатив</Label>
|
|
||||||
<Select value={creativeId || ""} onValueChange={setCreativeId}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Выберите креатив" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{creatives.map((creative) => (
|
|
||||||
<SelectItem key={creative.id} value={creative.id}>
|
|
||||||
{creative.name}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Формат</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="Стандарт"
|
|
||||||
value={format}
|
|
||||||
onChange={(e) => setFormat(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Стоимость (₽)</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="5000"
|
|
||||||
value={cost}
|
|
||||||
onChange={(e) => setCost(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Дата размещения</Label>
|
|
||||||
<Input
|
|
||||||
type="date"
|
|
||||||
value={placementDate}
|
|
||||||
onChange={(e) => setPlacementDate(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="col-span-2 space-y-2">
|
|
||||||
<Label>Комментарий</Label>
|
|
||||||
<Textarea
|
|
||||||
placeholder="Дополнительные заметки..."
|
|
||||||
value={comment}
|
|
||||||
onChange={(e) => setComment(e.target.value)}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === 3 && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Каналы ({selectedChannels.length})</Label>
|
|
||||||
<div className="max-h-32 overflow-y-auto p-3 rounded-md bg-muted text-sm space-y-1">
|
|
||||||
{selectedChannels.map((c) => (
|
|
||||||
<div key={c.username}>@{c.username}</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Параметры</Label>
|
|
||||||
<div className="grid grid-cols-2 gap-2 text-sm p-3 rounded-md bg-muted">
|
|
||||||
{selectedCreative && (
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground">Креатив:</span>{" "}
|
|
||||||
{selectedCreative.name}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground">Тип:</span>{" "}
|
|
||||||
Стандартный
|
|
||||||
</div>
|
|
||||||
{format && (
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground">Формат:</span>{" "}
|
|
||||||
{format}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cost && (
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground">Стоимость:</span>{" "}
|
|
||||||
{parseFloat(cost).toLocaleString("ru-RU")} ₽
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{placementDate && (
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground">Дата:</span>{" "}
|
|
||||||
{new Date(placementDate).toLocaleDateString("ru-RU")}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{comment && (
|
|
||||||
<div className="col-span-2">
|
|
||||||
<span className="text-muted-foreground">Комментарий:</span>{" "}
|
|
||||||
{comment}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DialogFooter>
|
|
||||||
{step > 1 && (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => setStep(step - 1)}
|
|
||||||
>
|
|
||||||
Назад
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{step < 3 ? (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
if (step === 1 && !prefilledCreativeId) {
|
|
||||||
loadCreatives();
|
|
||||||
}
|
|
||||||
setStep(step + 1);
|
|
||||||
}}
|
|
||||||
disabled={step === 1 && !canProceedStep1}
|
|
||||||
>
|
|
||||||
Далее
|
|
||||||
<ChevronRight className="h-4 w-4 ml-1" />
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Button type="button" onClick={handleCreate} disabled={creating}>
|
|
||||||
{creating ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
||||||
Создание...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
|
||||||
Создать {selectedChannels.length} размещений
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</DialogFooter>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
412
components/placement-wizard.tsx
Normal file
412
components/placement-wizard.tsx
Normal file
@@ -0,0 +1,412 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Loader2, ArrowLeft, ArrowRight, Check, Calendar } from "lucide-react";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { ru } from "date-fns/locale";
|
||||||
|
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 { Badge } from "@/components/ui/badge";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Calendar as CalendarComponent,
|
||||||
|
} from "@/components/ui/calendar";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { placementsApi, creativesApi, channelsApi } from "@/lib/api";
|
||||||
|
import { ChannelInput, type ParsedChannel } from "@/components/channel-input";
|
||||||
|
import type { Creative } from "@/lib/types/api";
|
||||||
|
|
||||||
|
interface PlacementWizardProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
workspaceId: string;
|
||||||
|
projectId: string;
|
||||||
|
initialCreativeId?: string | null;
|
||||||
|
onSuccess?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PlacementWizard({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
workspaceId,
|
||||||
|
projectId,
|
||||||
|
initialCreativeId,
|
||||||
|
onSuccess,
|
||||||
|
}: PlacementWizardProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const [step, setStep] = useState(1);
|
||||||
|
const [creatives, setCreatives] = useState<Creative[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
// Step 1: Creative
|
||||||
|
const [selectedCreative, setSelectedCreative] = useState<Creative | null>(null);
|
||||||
|
|
||||||
|
// Step 2: Channels (parsed from input)
|
||||||
|
const [parsedChannels, setParsedChannels] = useState<ParsedChannel[]>([]);
|
||||||
|
|
||||||
|
// Step 3: Details
|
||||||
|
const [placementDate, setPlacementDate] = useState<Date>(new Date());
|
||||||
|
const [cost, setCost] = useState("");
|
||||||
|
const [comment, setComment] = useState("");
|
||||||
|
const [inviteLinkType, setInviteLinkType] = useState<"approval" | "public">("approval");
|
||||||
|
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
loadData();
|
||||||
|
} else {
|
||||||
|
// Reset on close
|
||||||
|
setStep(1);
|
||||||
|
setParsedChannels([]);
|
||||||
|
setCost("");
|
||||||
|
setComment("");
|
||||||
|
}
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialCreativeId && creatives.length > 0) {
|
||||||
|
const creative = creatives.find(c => c.id === initialCreativeId);
|
||||||
|
if (creative) {
|
||||||
|
setSelectedCreative(creative);
|
||||||
|
setStep(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [initialCreativeId, creatives]);
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const response = await creativesApi.list(workspaceId, { project_id: projectId, size: 100 });
|
||||||
|
setCreatives(response.items);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load data:", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getValidChannelIds = () => {
|
||||||
|
return parsedChannels
|
||||||
|
.filter((c) => c.isValid && c.channel)
|
||||||
|
.map((c) => c.channel!.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!selectedCreative) return;
|
||||||
|
|
||||||
|
const validChannels = parsedChannels.filter((c) => c.isValid);
|
||||||
|
const existingChannelIds = validChannels.filter((c) => c.channel).map((c) => c.channel!.id);
|
||||||
|
const newChannels = validChannels.filter((c) => !c.channel && c.normalized);
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
// Create new channels first
|
||||||
|
const newChannelIds: string[] = [];
|
||||||
|
|
||||||
|
if (newChannels.length > 0) {
|
||||||
|
const channelInputs = newChannels.map((c) => {
|
||||||
|
if (c.type === "invite_link") {
|
||||||
|
return { invite_link: `https://t.me/+${c.normalized}` };
|
||||||
|
}
|
||||||
|
return { username: c.normalized! };
|
||||||
|
});
|
||||||
|
|
||||||
|
const createResult = await channelsApi.create(channelInputs);
|
||||||
|
for (const result of createResult.results) {
|
||||||
|
if ((result.status === "created" || result.status === "updated") && result.channel) {
|
||||||
|
newChannelIds.push(result.channel.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allChannelIds = [...existingChannelIds, ...newChannelIds];
|
||||||
|
|
||||||
|
if (allChannelIds.length === 0) {
|
||||||
|
setError("Не выбрано ни одного канала");
|
||||||
|
setSubmitting(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create placements
|
||||||
|
await placementsApi.createInProject(workspaceId, projectId, {
|
||||||
|
creative_id: selectedCreative.id,
|
||||||
|
channels: allChannelIds.map((channelId) => ({
|
||||||
|
channel_id: channelId,
|
||||||
|
status: "Без статуса",
|
||||||
|
comment: undefined,
|
||||||
|
details: {
|
||||||
|
placement_at: placementDate.toISOString(),
|
||||||
|
cost: cost ? { type: "fixed" as const, value: parseFloat(cost) } : undefined,
|
||||||
|
invite_link_type: inviteLinkType,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
onOpenChange(false);
|
||||||
|
onSuccess?.();
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(err?.detail || "Ошибка создания размещения");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
onOpenChange(false);
|
||||||
|
router.push(`/dashboard/${workspaceId}/purchase-plans/${projectId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const validChannels = parsedChannels.filter((c) => c.isValid);
|
||||||
|
const canProceedStep2 = validChannels.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleClose}>
|
||||||
|
<DialogContent className="max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Создание размещения</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Шаг {step} из 3
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Progress */}
|
||||||
|
<div className="flex items-center gap-2 mb-6">
|
||||||
|
{[1, 2, 3].map((s) => (
|
||||||
|
<div key={s} className="flex items-center gap-2">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",
|
||||||
|
step >= s
|
||||||
|
? "bg-primary text-primary-foreground"
|
||||||
|
: "bg-muted text-muted-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{step > s ? <Check className="h-4 w-4" /> : s}
|
||||||
|
</div>
|
||||||
|
{s < 3 && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"w-12 h-0.5",
|
||||||
|
step > s ? "bg-primary" : "bg-muted"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Step 1: Creative */}
|
||||||
|
{step === 1 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-medium">Выберите креатив</h3>
|
||||||
|
<div className="grid gap-3 max-h-96 overflow-y-auto">
|
||||||
|
{creatives.filter(c => c.status === "active").map((creative) => (
|
||||||
|
<button
|
||||||
|
key={creative.id}
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
"text-left p-4 rounded-lg border transition-colors",
|
||||||
|
selectedCreative?.id === creative.id
|
||||||
|
? "border-primary bg-primary/5"
|
||||||
|
: "hover:bg-muted"
|
||||||
|
)}
|
||||||
|
onClick={() => setSelectedCreative(creative)}
|
||||||
|
>
|
||||||
|
<div className="font-medium">{creative.name}</div>
|
||||||
|
<div className="text-sm text-muted-foreground line-clamp-2 mt-1">
|
||||||
|
{creative.text.replace("{invite_link}", "[ссылка]")}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end pt-4">
|
||||||
|
<Button
|
||||||
|
onClick={() => setStep(2)}
|
||||||
|
disabled={!selectedCreative}
|
||||||
|
>
|
||||||
|
Далее <ArrowRight className="h-4 w-4 ml-2" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Step 2: Channels */}
|
||||||
|
{step === 2 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-medium">Добавьте каналы</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Введите каналы в любом формате, например:
|
||||||
|
</p>
|
||||||
|
<p className="text-xs font-mono">
|
||||||
|
t.me/username, @username, tgstat.ru/channel/@username, telemetr.me/content/username
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ChannelInput
|
||||||
|
value={parsedChannels}
|
||||||
|
onChange={setParsedChannels}
|
||||||
|
maxItems={50}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex justify-between pt-4">
|
||||||
|
<Button variant="outline" onClick={() => setStep(1)}>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-2" /> Назад
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => setStep(3)}
|
||||||
|
disabled={!canProceedStep2}
|
||||||
|
>
|
||||||
|
Далее <ArrowRight className="h-4 w-4 ml-2" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Step 3: Details */}
|
||||||
|
{step === 3 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-medium">Детали размещения</h3>
|
||||||
|
|
||||||
|
{/* Summary of selected channels */}
|
||||||
|
<div className="p-3 bg-muted rounded-lg">
|
||||||
|
<p className="text-sm font-medium mb-2">Выбрано каналов: {validChannels.length}</p>
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{validChannels.slice(0, 5).map((c, i) => (
|
||||||
|
<Badge key={i} variant="secondary">
|
||||||
|
{c.normalized}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
{validChannels.length > 5 && (
|
||||||
|
<Badge variant="secondary">+{validChannels.length - 5} ещё</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Дата публикации</Label>
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className={cn(
|
||||||
|
"w-full justify-start text-left font-normal",
|
||||||
|
!placementDate && "text-muted-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
|
{placementDate
|
||||||
|
? format(placementDate, "PPP", { locale: ru })
|
||||||
|
: "Выберите дату"}
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-auto p-0">
|
||||||
|
<CalendarComponent
|
||||||
|
mode="single"
|
||||||
|
selected={placementDate}
|
||||||
|
onSelect={(date) => date && setPlacementDate(date)}
|
||||||
|
locale={ru}
|
||||||
|
disabled={(date) => date < new Date()}
|
||||||
|
/>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Стоимость (₽)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="0"
|
||||||
|
value={cost}
|
||||||
|
onChange={(e) => setCost(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Тип ссылки</Label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={inviteLinkType === "approval" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setInviteLinkType("approval")}
|
||||||
|
>
|
||||||
|
Согласование
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={inviteLinkType === "public" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setInviteLinkType("public")}
|
||||||
|
>
|
||||||
|
Публичная
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Комментарий</Label>
|
||||||
|
<Textarea
|
||||||
|
placeholder="Дополнительная информация..."
|
||||||
|
value={comment}
|
||||||
|
onChange={(e) => setComment(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="p-3 rounded bg-destructive/10 text-destructive text-sm">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-between pt-4">
|
||||||
|
<Button variant="outline" onClick={() => setStep(2)}>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-2" /> Назад
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleSubmit} disabled={submitting}>
|
||||||
|
{submitting ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Создание...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>Создать размещение ({validChannels.length})</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -15,9 +15,10 @@ interface CreateChannelInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface CreateChannelResult {
|
interface CreateChannelResult {
|
||||||
channel: {
|
index: number;
|
||||||
id: string;
|
status: "created" | "updated" | "failed";
|
||||||
};
|
channel: Channel | null;
|
||||||
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CreateChannelsResponse {
|
interface CreateChannelsResponse {
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ export function parseChannelInput(input: string): string | null {
|
|||||||
|
|
||||||
// Patterns for different URL formats
|
// Patterns for different URL formats
|
||||||
const patterns: RegExp[] = [
|
const patterns: RegExp[] = [
|
||||||
/telemetr\.me\/content\/([a-zA-Z0-9_]+)/, // telemetr.me/content/rian_ru
|
/telemetr\.me\/content\/([a-zA-Z0-9_]+)/, // telemetr.me/content/username
|
||||||
/telemetr\.me\/([a-zA-Z0-9_]+)/, // telemetr.me/rian_ru (alternative)
|
/telemetr\.me\/([a-zA-Z0-9_]+)/, // telemetr.me/username (alternative)
|
||||||
/t\.me\/([a-zA-Z0-9_]+)/, // t.me/rian_ru or https://t.me/rian_ru
|
/t\.me\/([a-zA-Z0-9_]+)/, // t.me/username or https://t.me/username
|
||||||
/tgstat\.ru\/channel\/@?([a-zA-Z0-9_]+)/, // tgstat.ru/channel/@rian_ru or tgstat.ru/channel/rian_ru
|
/tgstat\.ru\/channel\/@?([a-zA-Z0-9_]+)/, // tgstat.ru/channel/@username or tgstat.ru/channel/username
|
||||||
/tg\.me\/([a-zA-Z0-9_]+)/, // tg.me/rian_ru
|
/tg\.me\/([a-zA-Z0-9_]+)/, // tg.me/username
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const pattern of patterns) {
|
for (const pattern of patterns) {
|
||||||
|
|||||||
@@ -56,13 +56,10 @@ export const buildRoute = {
|
|||||||
|
|
||||||
// Creatives
|
// Creatives
|
||||||
creatives: (workspaceId: string) => `/dashboard/${workspaceId}/creatives`,
|
creatives: (workspaceId: string) => `/dashboard/${workspaceId}/creatives`,
|
||||||
creativeNew: (workspaceId: string) => `/dashboard/${workspaceId}/creatives/new`,
|
|
||||||
creativeDetail: (workspaceId: string, creativeId: string) =>
|
creativeDetail: (workspaceId: string, creativeId: string) =>
|
||||||
`/dashboard/${workspaceId}/creatives/${creativeId}`,
|
`/dashboard/${workspaceId}/creatives/${creativeId}`,
|
||||||
|
|
||||||
// Placements
|
// Placements
|
||||||
placements: (workspaceId: string) => `/dashboard/${workspaceId}/placements`,
|
|
||||||
placementNew: (workspaceId: string) => `/dashboard/${workspaceId}/placements/new`,
|
|
||||||
placementDetail: (workspaceId: string, placementId: string) =>
|
placementDetail: (workspaceId: string, placementId: string) =>
|
||||||
`/dashboard/${workspaceId}/placements/${placementId}`,
|
`/dashboard/${workspaceId}/placements/${placementId}`,
|
||||||
|
|
||||||
|
|||||||
1
public/icons/telegram.svg
Normal file
1
public/icons/telegram.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48px" height="48px"><linearGradient id="BiF7D16UlC0RZ_VqXJHnXa" x1="9.858" x2="38.142" y1="9.858" y2="38.142" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#33bef0"/><stop offset="1" stop-color="#0a85d9"/></linearGradient><path fill="url(#BiF7D16UlC0RZ_VqXJHnXa)" d="M44,24c0,11.045-8.955,20-20,20S4,35.045,4,24S12.955,4,24,4S44,12.955,44,24z"/><path d="M10.119,23.466c8.155-3.695,17.733-7.704,19.208-8.284c3.252-1.279,4.67,0.028,4.448,2.113 c-0.273,2.555-1.567,9.99-2.363,15.317c-0.466,3.117-2.154,4.072-4.059,2.863c-1.445-0.917-6.413-4.17-7.72-5.282 c-0.891-0.758-1.512-1.608-0.88-2.474c0.185-0.253,0.658-0.763,0.921-1.017c1.319-1.278,1.141-1.553-0.454-0.412 c-0.19,0.136-1.292,0.935-1.745,1.237c-1.11,0.74-2.131,0.78-3.862,0.192c-1.416-0.481-2.776-0.852-3.634-1.223 C8.794,25.983,8.34,24.272,10.119,23.466z" opacity=".05"/><path d="M10.836,23.591c7.572-3.385,16.884-7.264,18.246-7.813c3.264-1.318,4.465-0.536,4.114,2.011 c-0.326,2.358-1.483,9.654-2.294,14.545c-0.478,2.879-1.874,3.513-3.692,2.337c-1.139-0.734-5.723-3.754-6.835-4.633 c-0.86-0.679-1.751-1.463-0.71-2.598c0.348-0.379,2.27-2.234,3.707-3.614c0.833-0.801,0.536-1.196-0.469-0.508 c-1.843,1.263-4.858,3.262-5.396,3.625c-1.025,0.69-1.988,0.856-3.664,0.329c-1.321-0.416-2.597-0.819-3.262-1.078 C9.095,25.618,9.075,24.378,10.836,23.591z" opacity=".07"/><path fill="#fff" d="M11.553,23.717c6.99-3.075,16.035-6.824,17.284-7.343c3.275-1.358,4.28-1.098,3.779,1.91 c-0.36,2.162-1.398,9.319-2.226,13.774c-0.491,2.642-1.593,2.955-3.325,1.812c-0.833-0.55-5.038-3.331-5.951-3.984 c-0.833-0.595-1.982-1.311-0.541-2.721c0.513-0.502,3.874-3.712,6.493-6.21c0.343-0.328-0.088-0.867-0.484-0.604 c-3.53,2.341-8.424,5.59-9.047,6.013c-0.941,0.639-1.845,0.932-3.467,0.466c-1.226-0.352-2.423-0.772-2.889-0.932 C9.384,25.282,9.81,24.484,11.553,23.717z"/></svg>
|
||||||
|
After Width: | Height: | Size: 1.8 KiB |
Reference in New Issue
Block a user