feat: global platform v2 update
This commit is contained in:
431
app/dashboard/[workspaceId]/placements/[placementId]/page.tsx
Normal file
431
app/dashboard/[workspaceId]/placements/[placementId]/page.tsx
Normal file
@@ -0,0 +1,431 @@
|
||||
"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,
|
||||
Archive,
|
||||
Eye,
|
||||
Users,
|
||||
TrendingUp,
|
||||
} from "lucide-react";
|
||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||
import { placementsApi } 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 {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
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 canWrite = hasPermission("placements_write");
|
||||
|
||||
useEffect(() => {
|
||||
loadPlacement();
|
||||
}, [workspaceId, placementId]);
|
||||
|
||||
const loadPlacement = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await placementsApi.get(workspaceId, placementId);
|
||||
setPlacement(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load placement:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleArchive = async () => {
|
||||
try {
|
||||
await placementsApi.delete(workspaceId, placementId);
|
||||
router.push(`/dashboard/${workspaceId}/placements`);
|
||||
} catch (err) {
|
||||
console.error("Failed to archive:", err);
|
||||
}
|
||||
};
|
||||
|
||||
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 cps =
|
||||
placement.cost && placement.subscriptions_count > 0
|
||||
? placement.cost / placement.subscriptions_count
|
||||
: null;
|
||||
const cpm =
|
||||
placement.cost && placement.views_count
|
||||
? (placement.cost / placement.views_count) * 1000
|
||||
: null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader
|
||||
breadcrumbs={[
|
||||
{ label: "Главная", href: `/dashboard/${workspaceId}` },
|
||||
{ label: "Размещения", href: `/dashboard/${workspaceId}/placements` },
|
||||
{ label: placement.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.placement_channel_title}
|
||||
</h1>
|
||||
<Badge
|
||||
variant={
|
||||
placement.status === "active" ? "default" : "secondary"
|
||||
}
|
||||
>
|
||||
{placement.status === "active" ? "Активно" : "Архив"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
{formatDate(placement.placement_date)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canWrite && placement.status === "active" && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<Archive className="h-4 w-4 mr-2" />
|
||||
В архив
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Архивировать размещение?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Размещение будет перемещено в архив. Статистика сохранится.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleArchive}>
|
||||
Архивировать
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</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(placement.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(placement.subscriptions_count)}
|
||||
</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(placement.views_count)}
|
||||
</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}>
|
||||
{copiedLink ? (
|
||||
<Check className="h-4 w-4" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<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>{placement.creative_name}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<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.project_channel_title}</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">
|
||||
Дата размещения
|
||||
</dt>
|
||||
<dd className="text-sm">{formatDate(placement.placement_date)}</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">
|
||||
Статус просмотров
|
||||
</dt>
|
||||
<dd className="text-sm">
|
||||
<Badge variant="outline">
|
||||
{placement.views_availability === "available"
|
||||
? "Автообновление"
|
||||
: placement.views_availability === "manual"
|
||||
? "Ручной ввод"
|
||||
: placement.views_availability === "unavailable"
|
||||
? "Недоступно"
|
||||
: "Не проверено"}
|
||||
</Badge>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">
|
||||
Последнее обновление просмотров
|
||||
</dt>
|
||||
<dd className="text-sm">
|
||||
{formatDateTime(placement.last_views_fetch_at)}
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
{placement.ad_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.ad_post_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
{placement.ad_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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
393
app/dashboard/[workspaceId]/placements/new/page.tsx
Normal file
393
app/dashboard/[workspaceId]/placements/new/page.tsx
Normal file
@@ -0,0 +1,393 @@
|
||||
"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 } = useWorkspace();
|
||||
|
||||
// Pre-filled from URL params
|
||||
const prefilledCreativeId = searchParams.get("creative_id");
|
||||
const prefilledChannelId = searchParams.get("channel_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);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [workspaceId, currentProject?.id]);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
router.push(`/dashboard/${workspaceId}/placements/${placement.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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
742
app/dashboard/[workspaceId]/placements/page.tsx
Normal file
742
app/dashboard/[workspaceId]/placements/page.tsx
Normal file
@@ -0,0 +1,742 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================================
|
||||
// Placements List Page - Enhanced with Totals Row and Export
|
||||
// ============================================================================
|
||||
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Loader2,
|
||||
Search,
|
||||
Plus,
|
||||
ShoppingCart,
|
||||
MoreHorizontal,
|
||||
Eye,
|
||||
ExternalLink,
|
||||
ArrowUpDown,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
Download,
|
||||
FileSpreadsheet,
|
||||
FileText,
|
||||
Info,
|
||||
} 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 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.placement_channel_title,
|
||||
"",
|
||||
p.creative_name,
|
||||
new Date(p.placement_date).toISOString().split("T")[0],
|
||||
p.cost?.toString() || "",
|
||||
p.subscriptions_count.toString(),
|
||||
p.views_count?.toString() || "",
|
||||
calculateCPS(p.cost, p.subscriptions_count)?.toFixed(2) || "",
|
||||
calculateCPM(p.cost, p.views_count)?.toFixed(2) || "",
|
||||
p.status,
|
||||
p.ad_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.placement_channel_title,
|
||||
"",
|
||||
p.creative_name,
|
||||
new Date(p.placement_date).toISOString().split("T")[0],
|
||||
p.cost?.toString() || "",
|
||||
p.subscriptions_count.toString(),
|
||||
p.views_count?.toString() || "",
|
||||
calculateCPS(p.cost, p.subscriptions_count)?.toFixed(2) || "",
|
||||
calculateCPM(p.cost, p.views_count)?.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 cps = calculateCPS(p.cost, p.subscriptions_count);
|
||||
const cpm = calculateCPM(p.cost, p.views_count);
|
||||
return [
|
||||
`Канал: ${p.placement_channel_title}`,
|
||||
`Креатив: ${p.creative_name}`,
|
||||
`Дата: ${formatDate(p.placement_date)}`,
|
||||
`Стоимость: ${formatCurrency(p.cost)}`,
|
||||
`Подписки: ${p.subscriptions_count}`,
|
||||
`Просмотры: ${p.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 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);
|
||||
|
||||
// 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(() => {
|
||||
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) =>
|
||||
p.placement_channel_title.toLowerCase().includes(search.toLowerCase()) ||
|
||||
p.creative_name.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
.sort((a, b) => {
|
||||
if (!sortField || !sortOrder) return 0;
|
||||
|
||||
let aVal: number | string = 0;
|
||||
let bVal: number | string = 0;
|
||||
|
||||
switch (sortField) {
|
||||
case "date":
|
||||
return sortOrder === "asc"
|
||||
? new Date(a.placement_date).getTime() - new Date(b.placement_date).getTime()
|
||||
: new Date(b.placement_date).getTime() - new Date(a.placement_date).getTime();
|
||||
case "cost":
|
||||
aVal = a.cost ?? 0;
|
||||
bVal = b.cost ?? 0;
|
||||
break;
|
||||
case "subscriptions":
|
||||
aVal = a.subscriptions_count;
|
||||
bVal = b.subscriptions_count;
|
||||
break;
|
||||
case "views":
|
||||
aVal = a.views_count ?? 0;
|
||||
bVal = b.views_count ?? 0;
|
||||
break;
|
||||
case "cps":
|
||||
aVal = calculateCPS(a.cost, a.subscriptions_count) ?? 0;
|
||||
bVal = calculateCPS(b.cost, b.subscriptions_count) ?? 0;
|
||||
break;
|
||||
case "cpm":
|
||||
aVal = calculateCPM(a.cost, a.views_count) ?? 0;
|
||||
bVal = calculateCPM(b.cost, b.views_count) ?? 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.cost).filter((c): c is number => c !== null);
|
||||
const subs = filteredPlacements.map((p) => p.subscriptions_count);
|
||||
const views = filteredPlacements.map((p) => p.views_count).filter((v): v is number => v !== null);
|
||||
const cpsValues = filteredPlacements
|
||||
.map((p) => calculateCPS(p.cost, p.subscriptions_count))
|
||||
.filter((c): c is number => c !== null);
|
||||
const cpmValues = filteredPlacements
|
||||
.map((p) => calculateCPM(p.cost, p.views_count))
|
||||
.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>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Размещения</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{filteredPlacements.length} размещений
|
||||
</p>
|
||||
</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>
|
||||
<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 cps = calculateCPS(placement.cost, placement.subscriptions_count);
|
||||
const cpm = calculateCPM(placement.cost, placement.views_count);
|
||||
|
||||
return (
|
||||
<TableRow key={placement.id}>
|
||||
<TableCell>
|
||||
<div className="font-medium">{placement.placement_channel_title}</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="text-sm">{placement.creative_name}</div>
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(placement.placement_date)}</TableCell>
|
||||
<TableCell>{formatCurrency(placement.cost)}</TableCell>
|
||||
<TableCell>{formatNumber(placement.subscriptions_count)}</TableCell>
|
||||
<TableCell>{formatNumber(placement.views_count ?? null)}</TableCell>
|
||||
<TableCell>{cps ? formatCurrency(cps) : "—"}</TableCell>
|
||||
<TableCell>{cpm ? formatCurrency(cpm) : "—"}</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={placement.status === "active" ? "default" : "secondary"}
|
||||
>
|
||||
{placement.status === "active" ? "Активен" : "Архив"}
|
||||
</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.ad_post_url && (
|
||||
<DropdownMenuItem asChild>
|
||||
<a
|
||||
href={placement.ad_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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user