improvement for the backend api
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user