improvement for the backend api

This commit is contained in:
ivannoskov
2025-11-19 12:56:04 +03:00
parent b0a9934220
commit d4672ea32b
40 changed files with 2383 additions and 3313 deletions

View File

@@ -47,7 +47,7 @@ function AuthCompleteContent() {
}, 1500);
} catch (err: any) {
setStatus("error");
setError(err?.error?.message || "Ошибка авторизации");
setError(err?.detail || err?.error?.message || "Ошибка авторизации");
}
};

View File

@@ -59,12 +59,12 @@ export default function AnalyticsCostsPage() {
const [reportData, channelsData] = await Promise.all([
analyticsApi.costs({ period, target_channel_id: targetChannelId }),
channels.length > 0
? Promise.resolve({ data: channels })
: channelsApi.list({}),
? Promise.resolve({ target_channels: channels })
: channelsApi.list(),
]);
setReport(reportData);
if (channels.length === 0) {
setChannels(channelsData.data);
setChannels(channelsData.target_channels);
}
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки аналитики");

View File

@@ -4,357 +4,23 @@
// Target Channel Detail Page
// ============================================================================
import React, { useEffect, useState } from "react";
import { use } from "react";
import Link from "next/link";
import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { channelsApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
formatCurrency,
formatUsername,
formatDate,
} from "@/lib/utils/format";
import {
Target,
Users,
TrendingUp,
ArrowLeft,
Loader2,
AlertCircle,
ExternalLink as ExternalLinkIcon,
BarChart3,
} from "lucide-react";
import type { TargetChannelDetail } from "@/lib/types/api";
import { use } from "react";
interface PageProps {
params: Promise<{ id: string }>;
}
export default function ChannelDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [channel, setChannel] = useState<TargetChannelDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const resolvedParams = use(params);
useEffect(() => {
const loadChannel = async () => {
try {
setLoading(true);
const data = await channelsApi.get(resolvedParams.id);
setChannel(data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки канала");
} finally {
setLoading(false);
}
};
// Redirect back to channels list
// Detail page functionality not yet implemented in backend API
router.push("/channels");
}, [router, resolvedParams.id]);
loadChannel();
}, [resolvedParams.id]);
const handleToggleActive = async () => {
if (!channel) return;
try {
const updated = await channelsApi.update(channel.id, {
is_active: !channel.is_active,
});
setChannel({ ...channel, is_active: updated.is_active });
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления канала");
}
};
const handleDelete = async () => {
if (!channel) return;
if (!confirm("Вы уверены, что хотите отключить этот канал?")) return;
try {
await channelsApi.delete(channel.id);
router.push("/channels");
} catch (err: any) {
alert(err?.error?.message || "Ошибка удаления канала");
}
};
if (loading) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Целевые каналы", href: "/channels" },
{ label: "Загрузка..." },
]}
/>
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</>
);
}
if (error || !channel) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Целевые каналы", href: "/channels" },
{ label: "Ошибка" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error || "Канал не найден"}</AlertDescription>
</Alert>
<Button asChild variant="outline">
<Link href="/channels">
<ArrowLeft className="mr-2 h-4 w-4" />
Вернуться к каналам
</Link>
</Button>
</div>
</>
);
}
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Целевые каналы", href: "/channels" },
{ label: channel.title },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<Target className="h-6 w-6" />
<h1 className="text-3xl font-bold tracking-tight">
{channel.title}
</h1>
<Badge variant={channel.is_active ? "default" : "secondary"}>
{channel.is_active ? "Активен" : "Отключен"}
</Badge>
</div>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
{channel.username ? (
<a
href={`https://t.me/${channel.username.replace("@", "")}`}
target="_blank"
rel="noopener noreferrer"
className="hover:underline flex items-center gap-1"
>
{formatUsername(channel.username)}
<ExternalLinkIcon className="h-3 w-3" />
</a>
) : (
<span>Приватный канал</span>
)}
<span></span>
<span>Добавлен {formatDate(channel.created_at)}</span>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={handleToggleActive}>
{channel.is_active ? "Отключить" : "Включить"}
</Button>
<Button variant="destructive" onClick={handleDelete}>
Удалить
</Button>
</div>
</div>
{channel.description && (
<Card>
<CardHeader>
<CardTitle>Описание</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{channel.description}</p>
</CardContent>
</Card>
)}
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Всего закупов
</CardTitle>
<BarChart3 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(channel.total_purchases)}
</div>
<p className="text-xs text-muted-foreground mt-1">
За весь период
</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>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(channel.total_subscriptions)}
</div>
<p className="text-xs text-muted-foreground mt-1">Всего</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Средний CPF</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatMetric(channel.avg_cpf)}
</div>
<p className="text-xs text-muted-foreground mt-1">
Стоимость подписчика
</p>
</CardContent>
</Card>
</div>
<Tabs defaultValue="stats" className="w-full">
<TabsList>
<TabsTrigger value="stats">Статистика по периодам</TabsTrigger>
<TabsTrigger value="purchases">Последние закупы</TabsTrigger>
</TabsList>
<TabsContent value="stats" className="mt-4">
<Card>
<CardHeader>
<CardTitle>Статистика по периодам</CardTitle>
<CardDescription>
Динамика привлечения подписчиков
</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Период</TableHead>
<TableHead className="text-right">Подписчики</TableHead>
<TableHead className="text-right">Затраты</TableHead>
<TableHead className="text-right">CPF</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{channel.stats_by_period.map((stat, index) => (
<TableRow key={index}>
<TableCell className="font-medium capitalize">
{stat.period}
</TableCell>
<TableCell className="text-right">
{formatNumber(stat.subscriptions)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(stat.cost)}
</TableCell>
<TableCell className="text-right">
{formatMetric(stat.cpf)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="purchases" className="mt-4">
<Card>
<CardHeader>
<CardTitle>Последние закупы</CardTitle>
<CardDescription>
5 последних рекламных размещений
</CardDescription>
</CardHeader>
<CardContent>
{channel.recent_purchases.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
Закупов пока нет
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Внешний канал</TableHead>
<TableHead>Дата</TableHead>
<TableHead className="text-right">Подписчики</TableHead>
<TableHead className="text-right">CPF</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{channel.recent_purchases.map((purchase) => (
<TableRow key={purchase.id}>
<TableCell className="font-medium">
{purchase.external_channel.title}
</TableCell>
<TableCell>
{formatDate(
purchase.actual_date || purchase.scheduled_date
)}
</TableCell>
<TableCell className="text-right">
{formatNumber(purchase.subscriptions_count)}
</TableCell>
<TableCell className="text-right">
{formatMetric(purchase.cpf)}
</TableCell>
<TableCell className="text-right">
<Button asChild variant="ghost" size="sm">
<Link href={`/purchases/${purchase.id}`}>
Открыть
</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
</>
);
return null;
}

View File

@@ -45,9 +45,11 @@ export default function ChannelsPage() {
try {
setLoading(true);
const response = await channelsApi.list();
setChannels(response.data);
setChannels(response.target_channels);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки каналов");
setError(
err?.error?.message || err?.detail || "Ошибка загрузки каналов"
);
} finally {
setLoading(false);
}
@@ -62,14 +64,16 @@ export default function ChannelsPage() {
return true;
});
const handleToggleActive = async (id: string, isActive: boolean) => {
const handleDisconnect = async (id: string, title: string) => {
if (!confirm(`Вы уверены, что хотите отключить канал "${title}"?`)) {
return;
}
try {
await channelsApi.update(id, { is_active: !isActive });
setChannels((prev) =>
prev.map((ch) => (ch.id === id ? { ...ch, is_active: !isActive } : ch))
);
await channelsApi.delete(id);
setChannels((prev) => prev.filter((ch) => ch.id !== id));
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления канала");
alert(err?.error?.message || err?.detail || "Ошибка отключения канала");
}
};
@@ -213,59 +217,23 @@ export default function ChannelsPage() {
</div>
</CardHeader>
<CardContent className="space-y-3">
{channel.description && (
<p className="text-sm text-muted-foreground line-clamp-2">
{channel.description}
</p>
)}
<div className="grid grid-cols-3 gap-2 text-center">
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatNumber(channel.total_purchases)}
</div>
<div className="text-xs text-muted-foreground">
Закупов
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatNumber(channel.total_subscriptions)}
</div>
<div className="text-xs text-muted-foreground">
Подписчиков
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatMetric(channel.avg_cpf)}
</div>
<div className="text-xs text-muted-foreground">
CPF
</div>
</div>
<div className="text-sm text-muted-foreground">
Telegram ID:{" "}
<code className="text-xs bg-muted px-1 rounded">
{channel.telegram_id}
</code>
</div>
<div className="flex gap-2 pt-2">
<Button
asChild
variant="default"
size="sm"
className="flex-1"
>
<Link href={`/channels/${channel.id}`}>
<Eye className="mr-2 h-4 w-4" />
Подробнее
</Link>
</Button>
<Button
variant="outline"
size="sm"
onClick={() =>
handleToggleActive(channel.id, channel.is_active)
handleDisconnect(channel.id, channel.title)
}
className="flex-1"
>
{channel.is_active ? "Отключить" : "Включить"}
Отключить канал
</Button>
</div>
</CardContent>

View File

@@ -45,7 +45,7 @@ import {
Users,
TrendingUp,
} from "lucide-react";
import type { CreativeDetail } from "@/lib/types/api";
import type { Creative } from "@/lib/types/api";
interface PageProps {
params: Promise<{ id: string }>;
@@ -54,7 +54,7 @@ interface PageProps {
export default function CreativeDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [creative, setCreative] = useState<CreativeDetail | null>(null);
const [creative, setCreative] = useState<Creative | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -79,9 +79,12 @@ export default function CreativeDetailPage({ params }: PageProps) {
try {
await creativesApi.update(creative.id, {
is_archived: !creative.is_archived,
status: creative.status === "active" ? "archived" : "active",
});
setCreative({
...creative,
status: creative.status === "active" ? "archived" : "active",
});
setCreative({ ...creative, is_archived: !creative.is_archived });
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления креатива");
}
@@ -162,16 +165,20 @@ export default function CreativeDetailPage({ params }: PageProps) {
<h1 className="text-3xl font-bold tracking-tight">
{creative.name}
</h1>
{creative.is_archived && <Badge variant="secondary">Архив</Badge>}
{creative.status === "archived" && (
<Badge variant="secondary">Архив</Badge>
)}
</div>
<div className="text-sm text-muted-foreground">
Целевой канал: {creative.target_channel.title}
Целевой канал: {creative.target_channel_title}
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={handleArchive}>
<Archive className="mr-2 h-4 w-4" />
{creative.is_archived ? "Разархивировать" : "Архивировать"}
{creative.status === "archived"
? "Разархивировать"
: "Архивировать"}
</Button>
<Button variant="destructive" onClick={handleDelete}>
<Trash2 className="mr-2 h-4 w-4" />
@@ -190,10 +197,10 @@ export default function CreativeDetailPage({ params }: PageProps) {
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(creative.total_purchases)}
{formatNumber(creative.placements_count)}
</div>
<p className="text-xs text-muted-foreground mt-1">
С этим креативом
Всего размещений
</p>
</CardContent>
</Card>
@@ -201,29 +208,16 @@ export default function CreativeDetailPage({ params }: PageProps) {
<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(creative.total_subscriptions)}
</div>
<p className="text-xs text-muted-foreground mt-1">Всего</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Средний CPF</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatMetric(creative.avg_cpf)}
<div className="text-lg font-medium">
{creative.target_channel_title}
</div>
<p className="text-xs text-muted-foreground mt-1">
По всем закупам
Канал для рекламы
</p>
</CardContent>
</Card>
@@ -261,58 +255,29 @@ export default function CreativeDetailPage({ params }: PageProps) {
<Card>
<CardHeader>
<CardTitle>Закупы с этим креативом</CardTitle>
<CardDescription>История использования креатива</CardDescription>
<CardTitle>Информация о размещениях</CardTitle>
<CardDescription>Статистика использования креатива</CardDescription>
</CardHeader>
<CardContent>
{creative.purchases.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
Закупов с этим креативом пока нет
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Внешний канал</TableHead>
<TableHead>Дата</TableHead>
<TableHead className="text-right">Стоимость</TableHead>
<TableHead className="text-right">Подписчики</TableHead>
<TableHead className="text-right">CPF</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{creative.purchases.map((purchase) => (
<TableRow key={purchase.id}>
<TableCell className="font-medium">
{purchase.external_channel.title}
</TableCell>
<TableCell>
{formatDate(
purchase.actual_date || purchase.scheduled_date
)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(purchase.cost)}
</TableCell>
<TableCell className="text-right">
{formatNumber(purchase.subscriptions_count)}
</TableCell>
<TableCell className="text-right">
{formatMetric(purchase.cpf)}
</TableCell>
<TableCell className="text-right">
<Button asChild variant="ghost" size="sm">
<Link href={`/purchases/${purchase.id}`}>
Открыть
</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<div className="space-y-4">
<div>
<h4 className="text-sm font-medium mb-2">Всего размещений:</h4>
<p className="text-2xl font-bold">
{creative.placements_count}
</p>
</div>
<div>
<h4 className="text-sm font-medium mb-2">Создан:</h4>
<p className="text-sm">{formatDate(creative.created_at)}</p>
</div>
<div>
<Button asChild variant="outline" className="w-full">
<Link href={`/purchases?creative_id=${creative.id}`}>
Посмотреть все размещения
</Link>
</Button>
</div>
</div>
</CardContent>
</Card>
</div>

View File

@@ -48,8 +48,8 @@ export default function CreateCreativePage() {
const loadChannels = async () => {
try {
const response = await channelsApi.list({ is_active: true });
setChannels(response.data);
const response = await channelsApi.list();
setChannels(response.target_channels.filter((c) => c.is_active));
} catch (err) {
console.error("Error loading channels:", err);
}

View File

@@ -18,7 +18,12 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { creativesApi } from "@/lib/api";
import { formatNumber, formatMetric, truncate } from "@/lib/utils/format";
import {
formatNumber,
formatMetric,
truncate,
formatDate,
} from "@/lib/utils/format";
import {
Folder,
Loader2,
@@ -48,7 +53,7 @@ export default function CreativesPage() {
try {
setLoading(true);
const response = await creativesApi.list();
setCreatives(response.data);
setCreatives(response.creatives);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки креативов");
} finally {
@@ -56,9 +61,13 @@ export default function CreativesPage() {
}
};
const handleArchive = async (id: string, isArchived: boolean) => {
const handleArchive = async (
id: string,
currentStatus: "active" | "archived"
) => {
try {
await creativesApi.update(id, { is_archived: !isArchived });
const newStatus = currentStatus === "active" ? "archived" : "active";
await creativesApi.update(id, { status: newStatus });
loadCreatives();
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления креатива");
@@ -77,8 +86,8 @@ export default function CreativesPage() {
};
const filteredCreatives = creatives.filter((creative) => {
if (activeTab === "active") return !creative.is_archived;
if (activeTab === "archived") return creative.is_archived;
if (activeTab === "active") return creative.status === "active";
if (activeTab === "archived") return creative.status === "archived";
return true;
});
@@ -117,10 +126,10 @@ export default function CreativesPage() {
>
<TabsList>
<TabsTrigger value="active">
Активные ({creatives.filter((c) => !c.is_archived).length})
Активные ({creatives.filter((c) => c.status === "active").length})
</TabsTrigger>
<TabsTrigger value="archived">
Архив ({creatives.filter((c) => c.is_archived).length})
Архив ({creatives.filter((c) => c.status === "archived").length})
</TabsTrigger>
<TabsTrigger value="all">Все ({creatives.length})</TabsTrigger>
</TabsList>
@@ -166,12 +175,12 @@ export default function CreativesPage() {
<CardTitle className="truncate text-base">
{creative.name}
</CardTitle>
{creative.is_archived && (
{creative.status === "archived" && (
<Badge variant="secondary">Архив</Badge>
)}
</div>
<CardDescription className="text-xs">
{creative.target_channel.title}
{creative.target_channel_title}
</CardDescription>
</div>
<Folder className="h-5 w-5 text-muted-foreground shrink-0" />
@@ -184,29 +193,21 @@ export default function CreativesPage() {
</p>
</div>
<div className="grid grid-cols-3 gap-2 text-center">
<div className="grid grid-cols-2 gap-2 text-center">
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatNumber(creative.total_purchases)}
{formatNumber(creative.placements_count)}
</div>
<div className="text-xs text-muted-foreground">
Закупов
Размещений
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatNumber(creative.total_subscriptions)}
<div className="text-xs font-medium">
{formatDate(creative.created_at)}
</div>
<div className="text-xs text-muted-foreground">
Подписчиков
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatMetric(creative.avg_cpf)}
</div>
<div className="text-xs text-muted-foreground">
CPF
Создан
</div>
</div>
</div>
@@ -227,7 +228,7 @@ export default function CreativesPage() {
variant="ghost"
size="sm"
onClick={() =>
handleArchive(creative.id, creative.is_archived)
handleArchive(creative.id, creative.status)
}
>
<Archive className="h-4 w-4" />

View File

@@ -4,317 +4,23 @@
// External Channel Detail Page
// ============================================================================
import React, { useEffect, useState } from "react";
import { use } from "react";
import Link from "next/link";
import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { externalChannelsApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
formatCurrency,
formatUsername,
formatDate,
formatCompactNumber,
} from "@/lib/utils/format";
import {
ExternalLink as ExternalLinkIcon,
Users,
TrendingUp,
ArrowLeft,
Loader2,
AlertCircle,
BarChart3,
Pencil,
Trash2,
} from "lucide-react";
import type { ExternalChannelDetail } from "@/lib/types/api";
import { use } from "react";
interface PageProps {
params: Promise<{ id: string }>;
}
export default function ExternalChannelDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [channel, setChannel] = useState<ExternalChannelDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const resolvedParams = use(params);
useEffect(() => {
const loadChannel = async () => {
try {
setLoading(true);
const data = await externalChannelsApi.get(resolvedParams.id);
setChannel(data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки канала");
} finally {
setLoading(false);
}
};
// Redirect back to external channels list
// Detail page functionality not yet implemented in backend API
router.push("/external-channels");
}, [router, resolvedParams.id]);
loadChannel();
}, [resolvedParams.id]);
const handleDelete = async () => {
if (!channel) return;
if (!confirm(`Удалить канал "${channel.title}"?`)) return;
try {
await externalChannelsApi.delete(channel.id);
router.push("/external-channels");
} catch (err: any) {
alert(err?.error?.message || "Ошибка удаления канала");
}
};
if (loading) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Внешние каналы", href: "/external-channels" },
{ label: "Загрузка..." },
]}
/>
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</>
);
}
if (error || !channel) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Внешние каналы", href: "/external-channels" },
{ label: "Ошибка" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error || "Канал не найден"}</AlertDescription>
</Alert>
<Button asChild variant="outline">
<Link href="/external-channels">
<ArrowLeft className="mr-2 h-4 w-4" />
Вернуться к каналам
</Link>
</Button>
</div>
</>
);
}
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Внешние каналы", href: "/external-channels" },
{ label: channel.title },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<ExternalLinkIcon className="h-6 w-6" />
<h1 className="text-3xl font-bold tracking-tight">
{channel.title}
</h1>
</div>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
{channel.username ? (
<a
href={channel.link}
target="_blank"
rel="noopener noreferrer"
className="hover:underline flex items-center gap-1"
>
{formatUsername(channel.username)}
<ExternalLinkIcon className="h-3 w-3" />
</a>
) : (
<a
href={channel.link}
target="_blank"
rel="noopener noreferrer"
className="hover:underline flex items-center gap-1"
>
{channel.link}
<ExternalLinkIcon className="h-3 w-3" />
</a>
)}
<span></span>
<span>Добавлен {formatDate(channel.created_at)}</span>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={handleDelete}>
<Trash2 className="mr-2 h-4 w-4" />
Удалить
</Button>
</div>
</div>
{channel.description && (
<Card>
<CardHeader>
<CardTitle>Описание</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{channel.description}</p>
</CardContent>
</Card>
)}
<div className="grid gap-4 md: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>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{channel.subscribers_count
? formatCompactNumber(channel.subscribers_count)
: "—"}
</div>
<p className="text-xs text-muted-foreground mt-1">В канале</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>
<BarChart3 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(channel.total_purchases)}
</div>
<p className="text-xs text-muted-foreground mt-1">
В этом канале
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Средний CPF</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatMetric(channel.avg_cpf)}
</div>
<p className="text-xs text-muted-foreground mt-1">
По всем закупам
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Средний CPM</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatMetric(channel.avg_cpm)}
</div>
<p className="text-xs text-muted-foreground mt-1">
Стоимость 1000 просмотров
</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>История закупов</CardTitle>
<CardDescription>
Все рекламные размещения в этом канале
</CardDescription>
</CardHeader>
<CardContent>
{channel.purchases.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
Закупов в этом канале пока нет
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Целевой канал</TableHead>
<TableHead>Дата</TableHead>
<TableHead className="text-right">Стоимость</TableHead>
<TableHead className="text-right">Подписчики</TableHead>
<TableHead className="text-right">CPF</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{channel.purchases.map((purchase) => (
<TableRow key={purchase.id}>
<TableCell className="font-medium">
{purchase.target_channel.title}
</TableCell>
<TableCell>
{formatDate(
purchase.actual_date || purchase.scheduled_date
)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(purchase.cost)}
</TableCell>
<TableCell className="text-right">
{formatNumber(purchase.subscriptions_count)}
</TableCell>
<TableCell className="text-right">
{formatMetric(purchase.cpf)}
</TableCell>
<TableCell className="text-right">
<Button asChild variant="ghost" size="sm">
<Link href={`/purchases/${purchase.id}`}>
Открыть
</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
</>
);
return null;
}

View File

@@ -4,7 +4,7 @@
// External Channels Import Page
// ============================================================================
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { DashboardHeader } from "@/components/layout/dashboard-header";
@@ -17,8 +17,20 @@ import {
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { externalChannelsApi } from "@/lib/api";
import { Progress } from "@/components/ui/progress";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { externalChannelsApi, channelsApi } from "@/lib/api";
import {
parseChannelsFile,
downloadTemplate,
type ParsedChannel,
} from "@/lib/utils/file-parser";
import {
FileUp,
AlertCircle,
@@ -27,18 +39,46 @@ import {
Download,
ArrowLeft,
X,
FileSpreadsheet,
} from "lucide-react";
import type { ExternalChannelImportResponse } from "@/lib/types/api";
import type { TargetChannel } from "@/lib/types/api";
interface ImportResult {
total: number;
successful: number;
failed: number;
errors: string[];
}
export default function ImportExternalChannelsPage() {
const router = useRouter();
const [file, setFile] = useState<File | null>(null);
const [isDragging, setIsDragging] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const [result, setResult] = useState<ExternalChannelImportResponse | null>(
null
);
const [error, setError] = useState<string | null>(null);
const [parsedChannels, setParsedChannels] = useState<ParsedChannel[]>([]);
const [parseErrors, setParseErrors] = useState<string[]>([]);
const [importResult, setImportResult] = useState<ImportResult | null>(null);
const [progress, setProgress] = useState(0);
const [currentChannel, setCurrentChannel] = useState<string>("");
const [targetChannels, setTargetChannels] = useState<TargetChannel[]>([]);
const [selectedTargetChannel, setSelectedTargetChannel] =
useState<string>("");
useEffect(() => {
loadTargetChannels();
}, []);
const loadTargetChannels = async () => {
try {
const response = await channelsApi.list();
setTargetChannels(response.target_channels);
if (response.target_channels.length > 0) {
setSelectedTargetChannel(response.target_channels[0].id);
}
} catch (err) {
console.error("Error loading target channels:", err);
}
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
@@ -59,25 +99,29 @@ export default function ImportExternalChannelsPage() {
}
};
const handleFileSelect = (selectedFile: File) => {
// Проверка типа файла
const validTypes = [
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"text/csv",
];
if (
!validTypes.includes(selectedFile.type) &&
!selectedFile.name.match(/\.(xlsx|xls|csv)$/i)
) {
setError("Пожалуйста, выберите файл Excel (.xlsx, .xls) или CSV");
const handleFileSelect = async (selectedFile: File) => {
if (!selectedFile.name.match(/\.(xlsx|xls|csv)$/i)) {
setParseErrors(["Пожалуйста, выберите файл Excel (.xlsx, .xls) или CSV"]);
return;
}
setFile(selectedFile);
setError(null);
setResult(null);
setParseErrors([]);
setParsedChannels([]);
setImportResult(null);
// Парсим файл
try {
const result = await parseChannelsFile(selectedFile);
setParsedChannels(result.channels);
setParseErrors(result.errors);
} catch (err) {
setParseErrors([
`Ошибка парсинга файла: ${
err instanceof Error ? err.message : "неизвестная ошибка"
}`,
]);
}
};
const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -87,33 +131,66 @@ export default function ImportExternalChannelsPage() {
}
};
const handleUpload = async () => {
if (!file) return;
const delay = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
try {
setIsUploading(true);
setError(null);
const handleImport = async () => {
if (!selectedTargetChannel || parsedChannels.length === 0) return;
// Для примера используем первый целевой канал (tc1)
// В реальном приложении нужно дать пользователю выбрать
const importResult = await externalChannelsApi.import(file, "tc1");
setResult(importResult);
setFile(null);
} catch (err: any) {
setError(err?.error?.message || "Ошибка импорта файла");
} finally {
setIsUploading(false);
setIsUploading(true);
setImportResult(null);
setProgress(0);
setCurrentChannel("");
const result: ImportResult = {
total: parsedChannels.length,
successful: 0,
failed: 0,
errors: [],
};
for (let i = 0; i < parsedChannels.length; i++) {
const channel = parsedChannels[i];
setCurrentChannel(channel.title);
setProgress(((i + 1) / parsedChannels.length) * 100);
try {
await externalChannelsApi.create({
telegram_id: channel.telegram_id || 0,
title: channel.title,
username: channel.username || null,
description: channel.description || null,
subscribers_count: channel.subscribers_count || null,
target_channel_ids: [selectedTargetChannel],
});
result.successful++;
} catch (err: any) {
result.failed++;
const errorMsg =
err?.detail || err?.error?.message || "Неизвестная ошибка";
result.errors.push(
`Строка ${channel.row} (${channel.title}): ${errorMsg}`
);
}
// Задержка между запросами (300ms)
if (i < parsedChannels.length - 1) {
await delay(300);
}
}
setImportResult(result);
setIsUploading(false);
setCurrentChannel("");
};
const handleReset = () => {
setFile(null);
setResult(null);
setError(null);
};
const handleGoToChannels = () => {
router.push("/external-channels");
setParsedChannels([]);
setParseErrors([]);
setImportResult(null);
setProgress(0);
};
return (
@@ -132,7 +209,7 @@ export default function ImportExternalChannelsPage() {
Импорт внешних каналов
</h1>
<p className="text-muted-foreground mt-1">
Загрузите файл Excel с данными из Tgstat
Загрузите файл Excel или CSV с данными каналов
</p>
</div>
<Button asChild variant="outline">
@@ -143,195 +220,307 @@ export default function ImportExternalChannelsPage() {
</Button>
</div>
{/* Выбор целевого канала */}
<Card>
<CardHeader>
<CardTitle>Формат файла</CardTitle>
<CardTitle>Целевой канал</CardTitle>
<CardDescription>
Требования к структуре Excel файла
Выберите целевой канал для привязки импортируемых каналов
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3 text-sm">
<p>Файл должен содержать следующие колонки:</p>
<ul className="list-disc list-inside space-y-1 text-muted-foreground">
<li>
<strong>Название</strong> - название канала
</li>
<li>
<strong>Username</strong> - username канала (с @ или без)
</li>
<li>
<strong>Ссылка</strong> - ссылка на канал (t.me/...)
</li>
<li>
<strong>Подписчики</strong> - количество подписчиков (число)
</li>
<li>
<strong>Описание</strong> - краткое описание (опционально)
</li>
</ul>
<div className="pt-2">
<Button variant="outline" size="sm">
<Download className="mr-2 h-4 w-4" />
Скачать шаблон
</Button>
</div>
<Select
value={selectedTargetChannel}
onValueChange={setSelectedTargetChannel}
disabled={isUploading || targetChannels.length === 0}
>
<SelectTrigger>
<SelectValue placeholder="Выберите целевой канал" />
</SelectTrigger>
<SelectContent>
{targetChannels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
{channel.title}
{channel.username && ` (@${channel.username})`}
</SelectItem>
))}
</SelectContent>
</Select>
</CardContent>
</Card>
{/* Шаблоны */}
<Card>
<CardHeader>
<CardTitle>Скачать шаблон</CardTitle>
<CardDescription>
Используйте шаблон для правильного заполнения данных
</CardDescription>
</CardHeader>
<CardContent className="flex gap-2">
<Button
variant="outline"
onClick={() => downloadTemplate("xlsx")}
disabled={isUploading}
>
<Download className="mr-2 h-4 w-4" />
Шаблон Excel
</Button>
<Button
variant="outline"
onClick={() => downloadTemplate("csv")}
disabled={isUploading}
>
<Download className="mr-2 h-4 w-4" />
Шаблон CSV
</Button>
</CardContent>
</Card>
{/* Загрузка файла */}
<Card>
<CardHeader>
<CardTitle>Загрузка файла</CardTitle>
<CardDescription>
Перетащите файл или нажмите для выбора
</CardDescription>
</CardHeader>
<CardContent>
<div
className={`relative border-2 border-dashed rounded-lg p-12 text-center transition-colors ${
isDragging
? "border-primary bg-primary/5"
: "border-muted-foreground/25 hover:border-muted-foreground/50"
} ${isUploading ? "opacity-50 pointer-events-none" : ""}`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<input
type="file"
id="file-upload"
className="hidden"
accept=".xlsx,.xls,.csv"
onChange={handleFileInputChange}
disabled={isUploading}
/>
<label
htmlFor="file-upload"
className="cursor-pointer flex flex-col items-center"
>
<FileUp className="h-12 w-12 text-muted-foreground mb-4" />
{file ? (
<div className="space-y-2">
<p className="text-sm font-medium">{file.name}</p>
<p className="text-xs text-muted-foreground">
{(file.size / 1024).toFixed(2)} KB
</p>
{!isUploading && (
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
handleReset();
}}
>
<X className="h-4 w-4 mr-1" />
Удалить
</Button>
)}
</div>
) : (
<>
<p className="text-sm text-muted-foreground">
Перетащите файл сюда или нажмите для выбора
</p>
<p className="text-xs text-muted-foreground mt-1">
Поддерживаются форматы: .xlsx, .xls, .csv
</p>
</>
)}
</label>
</div>
</CardContent>
</Card>
{!result ? (
{/* Результаты парсинга */}
{parsedChannels.length > 0 && !importResult && (
<Card>
<CardHeader>
<CardTitle>Загрузка файла</CardTitle>
<CardTitle>Результаты парсинга</CardTitle>
<CardDescription>
Перетащите файл или выберите его
Найдено каналов: {parsedChannels.length}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={`
border-2 border-dashed rounded-lg p-12 text-center transition-colors
${
isDragging
? "border-primary bg-primary/5"
: "border-muted-foreground/25"
}
${file ? "bg-muted/50" : ""}
`}
>
{file ? (
<div className="space-y-4">
<div className="flex items-center justify-center gap-2">
<FileUp className="h-8 w-8 text-primary" />
</div>
<div>
<p className="font-medium">{file.name}</p>
<p className="text-sm text-muted-foreground">
{(file.size / 1024).toFixed(2)} KB
</p>
</div>
<Button variant="outline" size="sm" onClick={handleReset}>
<X className="mr-2 h-4 w-4" />
Выбрать другой файл
</Button>
</div>
) : (
<div className="space-y-4">
<div className="flex items-center justify-center">
<FileUp className="h-12 w-12 text-muted-foreground" />
</div>
<div>
<p className="text-lg font-medium">
Перетащите файл сюда
</p>
<p className="text-sm text-muted-foreground">
или нажмите кнопку ниже
</p>
</div>
<div>
<label htmlFor="file-upload">
<Button asChild variant="outline">
<span>
<FileUp className="mr-2 h-4 w-4" />
Выбрать файл
</span>
</Button>
</label>
<input
id="file-upload"
type="file"
accept=".xlsx,.xls,.csv"
onChange={handleFileInputChange}
className="hidden"
/>
</div>
</div>
)}
</div>
{error && (
{parseErrors.length > 0 && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
<AlertDescription>
<strong>Ошибки при парсинге:</strong>
<ul className="list-disc list-inside mt-2">
{parseErrors.slice(0, 5).map((error, i) => (
<li key={i} className="text-sm">
{error}
</li>
))}
{parseErrors.length > 5 && (
<li className="text-sm">
...и еще {parseErrors.length - 5}
</li>
)}
</ul>
</AlertDescription>
</Alert>
)}
{file && (
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleReset}>
Отмена
</Button>
<Button onClick={handleUpload} disabled={isUploading}>
{isUploading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Импорт...
</>
) : (
<>
<FileUp className="mr-2 h-4 w-4" />
Импортировать
</>
)}
</Button>
</div>
)}
<div className="flex gap-2">
<Button
onClick={handleImport}
disabled={
isUploading ||
!selectedTargetChannel ||
parsedChannels.length === 0
}
className="flex-1"
>
<FileSpreadsheet className="mr-2 h-4 w-4" />
Импортировать {parsedChannels.length} каналов
</Button>
<Button
variant="outline"
onClick={handleReset}
disabled={isUploading}
>
Отмена
</Button>
</div>
</CardContent>
</Card>
) : (
)}
{/* Прогресс импорта */}
{isUploading && (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<CheckCircle className="h-6 w-6 text-green-500" />
<CardTitle>Импорт завершен</CardTitle>
</div>
<CardDescription>Результаты обработки файла</CardDescription>
<CardTitle>Импорт в процессе</CardTitle>
<CardDescription>
{currentChannel && `Импортируется: ${currentChannel}`}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-2">
<div className="flex items-center justify-between p-3 rounded-lg bg-green-50 dark:bg-green-950/20">
<span className="text-sm font-medium">
Импортировано каналов
</span>
<Badge variant="default">{result.imported}</Badge>
<Progress value={progress} className="w-full" />
<p className="text-sm text-center text-muted-foreground">
{Math.round(progress)}% завершено
</p>
</CardContent>
</Card>
)}
{/* Результаты импорта */}
{importResult && (
<Card>
<CardHeader>
<CardTitle>Результаты импорта</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-3 gap-4 text-center">
<div className="p-4 border rounded-lg">
<div className="text-2xl font-bold">{importResult.total}</div>
<div className="text-xs text-muted-foreground">Всего</div>
</div>
{result.skipped > 0 && (
<div className="flex items-center justify-between p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20">
<span className="text-sm font-medium">Пропущено</span>
<Badge variant="secondary">{result.skipped}</Badge>
<div className="p-4 border rounded-lg border-green-200 bg-green-50 dark:border-green-900 dark:bg-green-950">
<div className="text-2xl font-bold text-green-600 dark:text-green-400">
{importResult.successful}
</div>
)}
<div className="text-xs text-muted-foreground">Успешно</div>
</div>
<div className="p-4 border rounded-lg border-red-200 bg-red-50 dark:border-red-900 dark:bg-red-950">
<div className="text-2xl font-bold text-red-600 dark:text-red-400">
{importResult.failed}
</div>
<div className="text-xs text-muted-foreground">Ошибок</div>
</div>
</div>
{result.errors.length > 0 && (
<Alert>
{importResult.errors.length > 0 && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<p className="font-medium mb-2">
Обнаружены ошибки при импорте:
</p>
<ul className="list-disc list-inside space-y-1 text-sm">
{result.errors.map((error, index) => (
<li key={index}>{error}</li>
<strong>Ошибки импорта:</strong>
<ul className="list-disc list-inside mt-2 max-h-60 overflow-y-auto">
{importResult.errors.map((error, i) => (
<li key={i} className="text-sm">
{error}
</li>
))}
</ul>
</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2 pt-4">
{importResult.successful > 0 && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
Успешно импортировано каналов: {importResult.successful}
</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
<Button
onClick={() => router.push("/external-channels")}
className="flex-1"
>
Перейти к списку каналов
</Button>
<Button variant="outline" onClick={handleReset}>
Импортировать еще
</Button>
<Button onClick={handleGoToChannels}>Перейти к каналам</Button>
</div>
</CardContent>
</Card>
)}
{/* Инструкция */}
<Card>
<CardHeader>
<CardTitle>Формат файла</CardTitle>
<CardDescription>Требования к структуре файла</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 text-sm">
<p>
<strong>Колонки (в порядке):</strong>
</p>
<ol className="list-decimal list-inside space-y-1 ml-2">
<li>
<strong>Название канала*</strong> - обязательное поле
</li>
<li>
<strong>Username</strong> - без символа @ (опционально)
</li>
<li>
<strong>Telegram ID</strong> - числовой ID канала
(опционально)
</li>
<li>
<strong>Подписчиков</strong> - количество подписчиков
(опционально)
</li>
<li>
<strong>Описание</strong> - описание канала (опционально)
</li>
</ol>
<p className="text-muted-foreground mt-4">
* Первая строка файла должна содержать заголовки и будет
пропущена при импорте
</p>
</div>
</CardContent>
</Card>
</div>
</>
);

View File

@@ -17,7 +17,7 @@ import {
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { externalChannelsApi } from "@/lib/api";
import { externalChannelsApi, channelsApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
@@ -74,10 +74,24 @@ export default function ExternalChannelsPage() {
const loadChannels = async () => {
try {
setLoading(true);
const response = await externalChannelsApi.list();
setChannels(response.data);
// Сначала загружаем target channels
const targetChannelsRes = await channelsApi.list();
if (targetChannelsRes.target_channels.length === 0) {
setError("Добавьте сначала целевой канал");
setLoading(false);
return;
}
// Загружаем external channels для первого target channel
const firstTargetChannel = targetChannelsRes.target_channels[0];
const response = await externalChannelsApi.list(firstTargetChannel.id);
setChannels(response.external_channels);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки каналов");
const errorMsg =
typeof err?.detail === "string"
? err.detail
: err?.error?.message || "Ошибка загрузки каналов";
setError(errorMsg);
} finally {
setLoading(false);
}
@@ -86,15 +100,23 @@ export default function ExternalChannelsPage() {
const handleCreate = async () => {
try {
setIsCreating(true);
// Получаем первый доступный target channel
const targetChannelsRes = await channelsApi.list();
if (targetChannelsRes.target_channels.length === 0) {
alert("Добавьте сначала целевой канал");
setIsCreating(false);
return;
}
await externalChannelsApi.create({
telegram_id: 0, // Временно, пока не получим реальный ID
title: formData.title,
username: formData.username || undefined,
link: formData.link,
username: formData.username || null,
subscribers_count: formData.subscribers_count
? parseInt(formData.subscribers_count)
: undefined,
description: formData.description || undefined,
target_channel_ids: [], // По умолчанию не привязываем
: null,
description: formData.description || null,
target_channel_ids: [targetChannelsRes.target_channels[0].id],
});
setIsCreateDialogOpen(false);
setFormData({
@@ -106,7 +128,11 @@ export default function ExternalChannelsPage() {
});
loadChannels();
} catch (err: any) {
alert(err?.error?.message || "Ошибка создания канала");
const errorMsg =
typeof err?.detail === "string"
? err.detail
: err?.error?.message || "Ошибка создания канала";
alert(errorMsg);
} finally {
setIsCreating(false);
}
@@ -317,7 +343,7 @@ export default function ExternalChannelsPage() {
<CardDescription className="truncate mt-1">
{channel.username ? (
<a
href={channel.link}
href={`https://t.me/${channel.username}`}
target="_blank"
rel="noopener noreferrer"
className="hover:underline"
@@ -325,14 +351,9 @@ export default function ExternalChannelsPage() {
{formatUsername(channel.username)}
</a>
) : (
<a
href={channel.link}
target="_blank"
rel="noopener noreferrer"
className="hover:underline text-xs"
>
{channel.link}
</a>
<span className="text-xs">
ID: {channel.telegram_id}
</span>
)}
</CardDescription>
</div>
@@ -345,8 +366,8 @@ export default function ExternalChannelsPage() {
</p>
)}
<div className="grid grid-cols-3 gap-2 text-center">
<div className="rounded-lg border bg-muted/50 p-2">
<div className="flex items-center gap-2">
<div className="flex-1 rounded-lg border bg-muted/50 p-2">
<div className="flex items-center justify-center gap-1">
<Users className="h-3 w-3 text-muted-foreground" />
<div className="text-sm font-medium">
@@ -355,44 +376,29 @@ export default function ExternalChannelsPage() {
: "—"}
</div>
</div>
<div className="text-xs text-muted-foreground">
<div className="text-xs text-muted-foreground text-center">
Подписчики
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="flex-1 rounded-lg border bg-muted/50 p-2 text-center">
<div className="text-sm font-medium">
{formatNumber(channel.total_purchases)}
ID: {channel.telegram_id}
</div>
<div className="text-xs text-muted-foreground">
Закупов
Telegram ID
</div>
</div>
<div className="rounded-lg border bg-muted/50 p-2">
<div className="text-sm font-medium">
{formatMetric(channel.avg_cpf)}
</div>
<div className="text-xs text-muted-foreground">CPF</div>
</div>
</div>
<div className="flex gap-2 pt-2">
<Button
asChild
variant="default"
variant="destructive"
size="sm"
className="flex-1"
>
<Link href={`/external-channels/${channel.id}`}>
<Eye className="mr-2 h-4 w-4" />
Подробнее
</Link>
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(channel.id, channel.title)}
>
<Trash2 className="h-4 w-4" />
<Trash2 className="mr-2 h-4 w-4" />
Удалить
</Button>
</div>
</CardContent>

View File

@@ -19,15 +19,6 @@ import {
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { purchasesApi } from "@/lib/api";
import {
formatNumber,
@@ -54,7 +45,7 @@ import {
Clock,
CheckCircle,
} from "lucide-react";
import type { PurchaseDetail } from "@/lib/types/api";
import type { Placement } from "@/lib/types/api";
interface PageProps {
params: Promise<{ id: string }>;
@@ -63,7 +54,7 @@ interface PageProps {
export default function PurchaseDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [purchase, setPurchase] = useState<PurchaseDetail | null>(null);
const [purchase, setPurchase] = useState<Placement | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
@@ -89,9 +80,12 @@ export default function PurchaseDetailPage({ params }: PageProps) {
try {
await purchasesApi.update(purchase.id, {
is_archived: !purchase.is_archived,
status: purchase.status === "active" ? "archived" : "active",
});
setPurchase({
...purchase,
status: purchase.status === "active" ? "archived" : "active",
});
setPurchase({ ...purchase, is_archived: !purchase.is_archived });
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления закупа");
}
@@ -157,10 +151,8 @@ export default function PurchaseDetailPage({ params }: PageProps) {
);
}
const messageText = purchase.creative.text.replace(
"{link}",
purchase.invite_link
);
// Remove message text generation as we don't have creative.text in Placement
const messageText = `Текст сообщения с ссылкой: ${purchase.invite_link}`;
return (
<>
@@ -177,19 +169,14 @@ export default function PurchaseDetailPage({ params }: PageProps) {
<div className="flex items-center gap-2 mb-2">
<ShoppingCart className="h-6 w-6" />
<h1 className="text-3xl font-bold tracking-tight">
{purchase.external_channel.title}
{purchase.external_channel_title}
</h1>
{purchase.is_archived ? (
{purchase.status === "archived" ? (
<Badge variant="secondary">Архив</Badge>
) : purchase.actual_date ? (
) : (
<Badge variant="default">
<CheckCircle className="h-3 w-3 mr-1" />
Завершено
</Badge>
) : (
<Badge variant="outline">
<Clock className="h-3 w-3 mr-1" />
Запланировано
Активно
</Badge>
)}
</div>
@@ -197,33 +184,34 @@ export default function PurchaseDetailPage({ params }: PageProps) {
<span>
Целевой канал:{" "}
<Link
href={`/channels/${purchase.target_channel.id}`}
href={`/channels`}
className="hover:underline font-medium"
>
{purchase.target_channel.title}
{purchase.target_channel_title}
</Link>
</span>
<span></span>
<span>
Креатив:{" "}
<Link
href={`/creatives/${purchase.creative.id}`}
href={`/creatives`}
className="hover:underline font-medium"
>
{purchase.creative.name}
{purchase.creative_name}
</Link>
</span>
<span></span>
<span>
Дата размещения:{" "}
{formatDate(purchase.actual_date || purchase.scheduled_date)}
Дата размещения: {formatDate(purchase.placement_date)}
</span>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={handleArchive}>
<Archive className="mr-2 h-4 w-4" />
{purchase.is_archived ? "Разархивировать" : "Архивировать"}
{purchase.status === "archived"
? "Разархивировать"
: "Архивировать"}
</Button>
<Button variant="destructive" onClick={handleDelete}>
<Trash2 className="mr-2 h-4 w-4" />
@@ -272,27 +260,45 @@ export default function PurchaseDetailPage({ params }: PageProps) {
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">CPF</CardTitle>
<CardTitle className="text-sm font-medium">
Статус просмотров
</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{purchase.cpf ? `${formatMetric(purchase.cpf)}` : "—"}
<div className="text-lg font-medium">
{purchase.views_availability === "available"
? "Доступны"
: purchase.views_availability === "manual"
? "Вручную"
: purchase.views_availability === "unavailable"
? "Недоступны"
: "Неизвестно"}
</div>
<p className="text-xs text-muted-foreground mt-1">
{purchase.last_views_fetch_at
? `Обновлено: ${formatDate(purchase.last_views_fetch_at)}`
: "Еще не обновлялись"}
</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>
<CardTitle className="text-sm font-medium">Тип ссылки</CardTitle>
<BarChart3 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{purchase.conversion_rate
? formatPercent(purchase.conversion_rate)
: ""}
<div className="text-lg font-medium">
{purchase.invite_link_type === "approval"
? "С одобрением"
: "Публичная"}
</div>
<p className="text-xs text-muted-foreground mt-1">
{purchase.invite_link_type === "approval"
? "Отслеживание подписчиков"
: "Без отслеживания"}
</p>
</CardContent>
</Card>
</div>
@@ -318,18 +324,18 @@ export default function PurchaseDetailPage({ params }: PageProps) {
)}
</Button>
</div>
{purchase.post_link && (
{purchase.ad_post_url && (
<div className="pt-2">
<Label className="text-sm text-muted-foreground">
Ссылка на рекламный пост:
</Label>
<a
href={purchase.post_link}
href={purchase.ad_post_url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-sm hover:underline mt-1"
>
{purchase.post_link}
{purchase.ad_post_url}
<ExternalLinkIcon className="h-3 w-3" />
</a>
</div>
@@ -363,127 +369,21 @@ export default function PurchaseDetailPage({ params }: PageProps) {
</Card>
)}
<Tabs defaultValue="subscriptions" className="w-full">
<TabsList>
<TabsTrigger value="subscriptions">
Подписки ({purchase.subscriptions.length})
</TabsTrigger>
{purchase.views_history && purchase.views_history.length > 0 && (
<TabsTrigger value="views">
История просмотров ({purchase.views_history.length})
</TabsTrigger>
)}
</TabsList>
<TabsContent value="subscriptions" className="mt-4">
<Card>
<CardHeader>
<CardTitle>Подписки</CardTitle>
<CardDescription>
Пользователи, перешедшие по ссылке
</CardDescription>
</CardHeader>
<CardContent>
{purchase.subscriptions.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
Подписок пока нет
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Пользователь</TableHead>
<TableHead>Username</TableHead>
<TableHead>Дата подписки</TableHead>
<TableHead>Статус</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{purchase.subscriptions.map((subscription) => (
<TableRow key={subscription.id}>
<TableCell className="font-medium">
{subscription.user_first_name}{" "}
{subscription.user_last_name}
</TableCell>
<TableCell>
{subscription.user_username
? formatUsername(subscription.user_username)
: "—"}
</TableCell>
<TableCell>
{formatDate(subscription.subscribed_at)}
</TableCell>
<TableCell>
{subscription.is_active ? (
<Badge variant="default">Активен</Badge>
) : (
<Badge variant="secondary">Отписался</Badge>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</TabsContent>
{purchase.views_history && purchase.views_history.length > 0 && (
<TabsContent value="views" className="mt-4">
<Card>
<CardHeader>
<CardTitle>История просмотров</CardTitle>
<CardDescription>
Динамика просмотров рекламного поста
</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Дата</TableHead>
<TableHead className="text-right">Просмотры</TableHead>
<TableHead className="text-right">Прирост</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{purchase.views_history.map((item, index) => {
const prevViews =
index > 0
? purchase.views_history![index - 1].views
: 0;
const growth = item.views - prevViews;
return (
<TableRow key={item.fetched_at}>
<TableCell>{formatDate(item.fetched_at)}</TableCell>
<TableCell className="text-right">
{formatNumber(item.views)}
</TableCell>
<TableCell className="text-right">
{index > 0 && (
<span
className={
growth > 0
? "text-green-600"
: "text-muted-foreground"
}
>
+{formatNumber(growth)}
</span>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
)}
</Tabs>
<Card>
<CardHeader>
<CardTitle>Заметка</CardTitle>
<CardDescription>
Детальная информация о размещении доступна через раздел "Подписки"
в главном меню
</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Для просмотра списка подписчиков и истории просмотров используйте
соответствующие разделы в главном меню.
</p>
</CardContent>
</Card>
</div>
</>
);

View File

@@ -60,11 +60,11 @@ export default function CreatePurchasePage() {
target_channel_id: "",
external_channel_id: "",
creative_id: "",
scheduled_date: "",
placement_date: "",
cost: "",
comment: "",
post_link: "",
invite_link_type: "public" as "public" | "private",
invite_link_type: "public" as "public" | "approval",
});
useEffect(() => {
@@ -73,15 +73,24 @@ export default function CreatePurchasePage() {
const loadData = async () => {
try {
const [channelsRes, externalChannelsRes, creativesRes] =
await Promise.all([
channelsApi.list({ is_active: true }),
externalChannelsApi.list(),
const channelsRes = await channelsApi.list();
setChannels(channelsRes.target_channels.filter((c) => c.is_active));
// Загружаем внешние каналы для первого доступного target channel
if (channelsRes.target_channels.length > 0) {
const firstTargetChannel = channelsRes.target_channels[0];
const [externalChannelsRes, creativesRes] = await Promise.all([
externalChannelsApi.list(firstTargetChannel.id),
creativesApi.list(),
]);
setChannels(channelsRes.data);
setExternalChannels(externalChannelsRes.data);
setCreatives(creativesRes.data.filter((c) => !c.is_archived));
setExternalChannels(externalChannelsRes.external_channels);
setCreatives(
creativesRes.creatives.filter((c) => c.status === "active")
);
} else {
setCreatives([]);
setExternalChannels([]);
}
} catch (err) {
console.error("Error loading data:", err);
}
@@ -116,7 +125,7 @@ export default function CreatePurchasePage() {
return;
}
if (!formData.scheduled_date) {
if (!formData.placement_date) {
setError("Укажите дату размещения");
return;
}
@@ -132,10 +141,10 @@ export default function CreatePurchasePage() {
target_channel_id: formData.target_channel_id,
external_channel_id: formData.external_channel_id,
creative_id: formData.creative_id,
scheduled_date: formData.scheduled_date,
placement_date: formData.placement_date,
cost: parseFloat(formData.cost),
comment: formData.comment || undefined,
post_link: formData.post_link || undefined,
ad_post_url: formData.post_link || undefined,
invite_link_type: formData.invite_link_type,
});
@@ -247,7 +256,7 @@ export default function CreatePurchasePage() {
target_channel_id: "",
external_channel_id: "",
creative_id: "",
scheduled_date: "",
placement_date: "",
cost: "",
comment: "",
post_link: "",
@@ -394,15 +403,15 @@ export default function CreatePurchasePage() {
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="scheduled_date">Дата размещения *</Label>
<Label htmlFor="placement_date">Дата размещения *</Label>
<Input
id="scheduled_date"
type="date"
value={formData.scheduled_date}
id="placement_date"
type="datetime-local"
value={formData.placement_date}
onChange={(e) =>
setFormData({
...formData,
scheduled_date: e.target.value,
placement_date: e.target.value,
})
}
/>
@@ -443,7 +452,7 @@ export default function CreatePurchasePage() {
<Label>Тип пригласительной ссылки *</Label>
<RadioGroup
value={formData.invite_link_type}
onValueChange={(value: "public" | "private") =>
onValueChange={(value: "public" | "approval") =>
setFormData({ ...formData, invite_link_type: value })
}
>
@@ -454,8 +463,8 @@ export default function CreatePurchasePage() {
</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="private" id="private" />
<Label htmlFor="private" className="font-normal">
<RadioGroupItem value="approval" id="approval" />
<Label htmlFor="approval" className="font-normal">
С одобрением (запрос на вступление через бота)
</Label>
</div>

View File

@@ -73,10 +73,10 @@ export default function PurchasesPage() {
setLoading(true);
const [purchasesRes, channelsRes] = await Promise.all([
purchasesApi.list(),
channelsApi.list({}),
channelsApi.list(),
]);
setPurchases(purchasesRes.data);
setChannels(channelsRes.data);
setPurchases(purchasesRes.placements);
setChannels(channelsRes.target_channels);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки данных");
} finally {
@@ -87,26 +87,24 @@ export default function PurchasesPage() {
const filteredPurchases = purchases.filter((purchase) => {
// Поиск
const matchesSearch =
purchase.external_channel.title
purchase.external_channel_title
.toLowerCase()
.includes(searchQuery.toLowerCase()) ||
purchase.target_channel.title
purchase.target_channel_title
.toLowerCase()
.includes(searchQuery.toLowerCase()) ||
purchase.creative.name.toLowerCase().includes(searchQuery.toLowerCase());
purchase.creative_name.toLowerCase().includes(searchQuery.toLowerCase());
// Фильтр по каналу
const matchesChannel =
filterChannel === "all" || purchase.target_channel.id === filterChannel;
filterChannel === "all" || purchase.target_channel_id === filterChannel;
// Фильтр по статусу
let matchesStatus = true;
if (filterStatus === "completed") {
matchesStatus = !!purchase.actual_date;
} else if (filterStatus === "scheduled") {
matchesStatus = !purchase.actual_date;
} else if (filterStatus === "archived") {
matchesStatus = purchase.is_archived;
if (filterStatus === "archived") {
matchesStatus = purchase.status === "archived";
} else if (filterStatus === "active") {
matchesStatus = purchase.status === "active";
}
return matchesSearch && matchesChannel && matchesStatus;
@@ -115,17 +113,13 @@ export default function PurchasesPage() {
// Статистика
const stats = {
total: purchases.length,
completed: purchases.filter((p) => p.actual_date).length,
scheduled: purchases.filter((p) => !p.actual_date).length,
active: purchases.filter((p) => p.status === "active").length,
archived: purchases.filter((p) => p.status === "archived").length,
totalCost: purchases.reduce((sum, p) => sum + (p.cost || 0), 0),
totalSubscriptions: purchases.reduce(
(sum, p) => sum + p.subscriptions_count,
0
),
avgCpf:
purchases.length > 0
? purchases.reduce((sum, p) => sum + (p.cpf || 0), 0) / purchases.length
: 0,
};
return (
@@ -169,7 +163,7 @@ export default function PurchasesPage() {
{formatNumber(stats.total)}
</div>
<p className="text-xs text-muted-foreground mt-1">
{stats.completed} завершено, {stats.scheduled} запланировано
{stats.active} активных, {stats.archived} в архиве
</p>
</CardContent>
</Card>
@@ -203,20 +197,6 @@ export default function PurchasesPage() {
<p className="text-xs text-muted-foreground mt-1">Всего</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Средний CPF</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatMetric(stats.avgCpf)}
</div>
<p className="text-xs text-muted-foreground mt-1">
По всем закупам
</p>
</CardContent>
</Card>
</div>
<Card>
@@ -308,9 +288,8 @@ export default function PurchasesPage() {
<TableHead>Креатив</TableHead>
<TableHead>Дата</TableHead>
<TableHead className="text-right">Стоимость</TableHead>
<TableHead className="text-right">Подписчики</TableHead>
<TableHead className="text-right">CPF</TableHead>
<TableHead className="text-right">Конверсия</TableHead>
<TableHead className="text-right">Подписки</TableHead>
<TableHead className="text-right">Просмотры</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
@@ -318,34 +297,27 @@ export default function PurchasesPage() {
{filteredPurchases.map((purchase) => (
<TableRow key={purchase.id}>
<TableCell>
{purchase.is_archived ? (
{purchase.status === "archived" ? (
<Badge variant="secondary">
<Archive className="h-3 w-3 mr-1" />
Архив
</Badge>
) : purchase.actual_date ? (
) : (
<Badge variant="default">
<CheckCircle className="h-3 w-3 mr-1" />
Завершено
</Badge>
) : (
<Badge variant="outline">
<Clock className="h-3 w-3 mr-1" />
Запланировано
Активно
</Badge>
)}
</TableCell>
<TableCell className="font-medium">
{purchase.target_channel.title}
{purchase.target_channel_title}
</TableCell>
<TableCell>{purchase.external_channel.title}</TableCell>
<TableCell>{purchase.external_channel_title}</TableCell>
<TableCell className="max-w-[200px] truncate">
{purchase.creative.name}
{purchase.creative_name}
</TableCell>
<TableCell>
{formatDate(
purchase.actual_date || purchase.scheduled_date
)}
{formatDate(purchase.placement_date)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(purchase.cost)}
@@ -354,11 +326,8 @@ export default function PurchasesPage() {
{formatNumber(purchase.subscriptions_count)}
</TableCell>
<TableCell className="text-right">
{purchase.cpf ? `${formatMetric(purchase.cpf)}` : "—"}
</TableCell>
<TableCell className="text-right">
{purchase.conversion_rate
? formatPercent(purchase.conversion_rate)
{purchase.views_count
? formatNumber(purchase.views_count)
: "—"}
</TableCell>
<TableCell className="text-right">