feat: all project setup

This commit is contained in:
ivannoskov
2025-11-10 12:07:24 +03:00
parent fbfd7719bb
commit b0a9934220
99 changed files with 19597 additions and 0 deletions

View File

@@ -0,0 +1,500 @@
"use client";
// ============================================================================
// Purchase Detail Page
// ============================================================================
import React, { useEffect, useState } from "react";
import { use } from "react";
import Link from "next/link";
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { purchasesApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
formatCurrency,
formatDate,
formatPercent,
formatUsername,
} from "@/lib/utils/format";
import {
ShoppingCart,
ArrowLeft,
Loader2,
AlertCircle,
Archive,
Trash2,
BarChart3,
Users,
TrendingUp,
Eye,
Copy,
ExternalLink as ExternalLinkIcon,
Check,
Clock,
CheckCircle,
} from "lucide-react";
import type { PurchaseDetail } from "@/lib/types/api";
interface PageProps {
params: Promise<{ id: string }>;
}
export default function PurchaseDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [purchase, setPurchase] = useState<PurchaseDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
const loadPurchase = async () => {
try {
setLoading(true);
const data = await purchasesApi.get(resolvedParams.id);
setPurchase(data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки закупа");
} finally {
setLoading(false);
}
};
loadPurchase();
}, [resolvedParams.id]);
const handleArchive = async () => {
if (!purchase) return;
try {
await purchasesApi.update(purchase.id, {
is_archived: !purchase.is_archived,
});
setPurchase({ ...purchase, is_archived: !purchase.is_archived });
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления закупа");
}
};
const handleDelete = async () => {
if (!purchase) return;
if (!confirm("Удалить закуп?")) return;
try {
await purchasesApi.delete(purchase.id);
router.push("/purchases");
} catch (err: any) {
alert(err?.error?.message || "Ошибка удаления закупа");
}
};
const handleCopyLink = () => {
if (!purchase) return;
navigator.clipboard.writeText(purchase.invite_link);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
if (loading) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Закупы", href: "/purchases" },
{ label: "Загрузка..." },
]}
/>
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</>
);
}
if (error || !purchase) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Закупы", href: "/purchases" },
{ 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="/purchases">
<ArrowLeft className="mr-2 h-4 w-4" />
Вернуться к закупам
</Link>
</Button>
</div>
</>
);
}
const messageText = purchase.creative.text.replace(
"{link}",
purchase.invite_link
);
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Закупы", href: "/purchases" },
{ label: `Закуп #${purchase.id.slice(0, 8)}` },
]}
/>
<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">
<ShoppingCart className="h-6 w-6" />
<h1 className="text-3xl font-bold tracking-tight">
{purchase.external_channel.title}
</h1>
{purchase.is_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>
<div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
<span>
Целевой канал:{" "}
<Link
href={`/channels/${purchase.target_channel.id}`}
className="hover:underline font-medium"
>
{purchase.target_channel.title}
</Link>
</span>
<span></span>
<span>
Креатив:{" "}
<Link
href={`/creatives/${purchase.creative.id}`}
className="hover:underline font-medium"
>
{purchase.creative.name}
</Link>
</span>
<span></span>
<span>
Дата размещения:{" "}
{formatDate(purchase.actual_date || purchase.scheduled_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 ? "Разархивировать" : "Архивировать"}
</Button>
<Button variant="destructive" onClick={handleDelete}>
<Trash2 className="mr-2 h-4 w-4" />
Удалить
</Button>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Стоимость</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatCurrency(purchase.cost)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Подписчики</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(purchase.subscriptions_count)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Просмотры</CardTitle>
<Eye className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{purchase.views_count
? formatNumber(purchase.views_count)
: "—"}
</div>
</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">
{purchase.cpf ? `${formatMetric(purchase.cpf)}` : "—"}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Конверсия</CardTitle>
<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>
</CardContent>
</Card>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Пригласительная ссылка</CardTitle>
<CardDescription>
Используется для отслеживания подписок
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<code className="flex-1 p-2 bg-muted rounded text-sm break-all">
{purchase.invite_link}
</code>
<Button onClick={handleCopyLink} variant="outline" size="icon">
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
{purchase.post_link && (
<div className="pt-2">
<Label className="text-sm text-muted-foreground">
Ссылка на рекламный пост:
</Label>
<a
href={purchase.post_link}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-sm hover:underline mt-1"
>
{purchase.post_link}
<ExternalLinkIcon className="h-3 w-3" />
</a>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Рекламное сообщение</CardTitle>
<CardDescription>Текст для размещения</CardDescription>
</CardHeader>
<CardContent>
<div className="rounded-lg border bg-muted/50 p-4">
<p className="text-sm whitespace-pre-wrap">{messageText}</p>
</div>
</CardContent>
</Card>
</div>
{purchase.comment && (
<Card>
<CardHeader>
<CardTitle>Комментарий</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
{purchase.comment}
</p>
</CardContent>
</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>
</div>
</>
);
}
function Label({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return <div className={className}>{children}</div>;
}

View File

@@ -0,0 +1,503 @@
"use client";
// ============================================================================
// Create Purchase Page
// ============================================================================
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
purchasesApi,
channelsApi,
externalChannelsApi,
creativesApi,
} from "@/lib/api";
import {
AlertCircle,
Loader2,
ArrowLeft,
Info,
Copy,
Check,
} from "lucide-react";
import type { TargetChannel, ExternalChannel, Creative } from "@/lib/types/api";
export default function CreatePurchasePage() {
const router = useRouter();
const [channels, setChannels] = useState<TargetChannel[]>([]);
const [externalChannels, setExternalChannels] = useState<ExternalChannel[]>(
[]
);
const [creatives, setCreatives] = useState<Creative[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [inviteLink, setInviteLink] = useState<string>("");
const [copied, setCopied] = useState(false);
const [formData, setFormData] = useState({
target_channel_id: "",
external_channel_id: "",
creative_id: "",
scheduled_date: "",
cost: "",
comment: "",
post_link: "",
invite_link_type: "public" as "public" | "private",
});
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
try {
const [channelsRes, externalChannelsRes, creativesRes] =
await Promise.all([
channelsApi.list({ is_active: true }),
externalChannelsApi.list(),
creativesApi.list(),
]);
setChannels(channelsRes.data);
setExternalChannels(externalChannelsRes.data);
setCreatives(creativesRes.data.filter((c) => !c.is_archived));
} catch (err) {
console.error("Error loading data:", err);
}
};
// Фильтр креативов по выбранному целевому каналу
const filteredCreatives = formData.target_channel_id
? creatives.filter(
(c) => c.target_channel_id === formData.target_channel_id
)
: creatives;
const selectedCreative = creatives.find((c) => c.id === formData.creative_id);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validation
if (!formData.target_channel_id) {
setError("Выберите целевой канал");
return;
}
if (!formData.external_channel_id) {
setError("Выберите внешний канал");
return;
}
if (!formData.creative_id) {
setError("Выберите креатив");
return;
}
if (!formData.scheduled_date) {
setError("Укажите дату размещения");
return;
}
if (!formData.cost || parseFloat(formData.cost) <= 0) {
setError("Укажите корректную стоимость");
return;
}
try {
setIsLoading(true);
const result = await purchasesApi.create({
target_channel_id: formData.target_channel_id,
external_channel_id: formData.external_channel_id,
creative_id: formData.creative_id,
scheduled_date: formData.scheduled_date,
cost: parseFloat(formData.cost),
comment: formData.comment || undefined,
post_link: formData.post_link || undefined,
invite_link_type: formData.invite_link_type,
});
// Показываем сгенерированную ссылку
setInviteLink(result.invite_link);
} catch (err: any) {
setError(err?.error?.message || "Ошибка создания закупа");
} finally {
setIsLoading(false);
}
};
const handleCopyLink = () => {
navigator.clipboard.writeText(inviteLink);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const handleCopyMessage = () => {
if (!selectedCreative) return;
const message = selectedCreative.text.replace("{link}", inviteLink);
navigator.clipboard.writeText(message);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
if (inviteLink) {
const messageText = selectedCreative
? selectedCreative.text.replace("{link}", inviteLink)
: "";
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Закупы", href: "/purchases" },
{ label: "Создание" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4 max-w-4xl mx-auto w-full">
<Card className="border-green-500">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-green-600">
<Check className="h-5 w-5" />
Закуп успешно создан!
</CardTitle>
<CardDescription>
Используйте ссылку и готовое сообщение для размещения
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Пригласительная ссылка</Label>
<div className="flex gap-2">
<Input value={inviteLink} readOnly className="font-mono" />
<Button onClick={handleCopyLink} variant="outline">
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
<div className="space-y-2">
<Label>Готовое сообщение для размещения</Label>
<div className="relative">
<Textarea
value={messageText}
readOnly
rows={8}
className="pr-12"
/>
<Button
onClick={handleCopyMessage}
variant="ghost"
size="sm"
className="absolute top-2 right-2"
>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
Скопируйте готовое сообщение и разместите его во внешнем
канале. Все переходы по ссылке будут автоматически
отслеживаться.
</AlertDescription>
</Alert>
<div className="flex gap-2 pt-4">
<Button asChild>
<Link href="/purchases">Перейти к закупам</Link>
</Button>
<Button
variant="outline"
onClick={() => {
setInviteLink("");
setFormData({
target_channel_id: "",
external_channel_id: "",
creative_id: "",
scheduled_date: "",
cost: "",
comment: "",
post_link: "",
invite_link_type: "public",
});
}}
>
Создать еще
</Button>
</div>
</CardContent>
</Card>
</div>
</>
);
}
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Закупы", href: "/purchases" },
{ label: "Создание" },
]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4 max-w-4xl mx-auto w-full">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Создать закуп</h1>
<p className="text-muted-foreground mt-1">
Новое рекламное размещение
</p>
</div>
<Button asChild variant="outline">
<Link href="/purchases">
<ArrowLeft className="mr-2 h-4 w-4" />
Назад
</Link>
</Button>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Основная информация</CardTitle>
<CardDescription>
Выберите каналы и креатив для размещения
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="target_channel_id">Целевой канал *</Label>
<Select
value={formData.target_channel_id}
onValueChange={(value) =>
setFormData({
...formData,
target_channel_id: value,
creative_id: "", // Сбросить креатив при смене канала
})
}
>
<SelectTrigger>
<SelectValue placeholder="Выберите канал" />
</SelectTrigger>
<SelectContent>
{channels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
{channel.title}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="external_channel_id">Внешний канал *</Label>
<Select
value={formData.external_channel_id}
onValueChange={(value) =>
setFormData({ ...formData, external_channel_id: value })
}
>
<SelectTrigger>
<SelectValue placeholder="Выберите канал" />
</SelectTrigger>
<SelectContent>
{externalChannels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
{channel.title}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="creative_id">Креатив *</Label>
<Select
value={formData.creative_id}
onValueChange={(value) =>
setFormData({ ...formData, creative_id: value })
}
disabled={!formData.target_channel_id}
>
<SelectTrigger>
<SelectValue
placeholder={
formData.target_channel_id
? "Выберите креатив"
: "Сначала выберите целевой канал"
}
/>
</SelectTrigger>
<SelectContent>
{filteredCreatives.map((creative) => (
<SelectItem key={creative.id} value={creative.id}>
{creative.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Детали размещения</CardTitle>
<CardDescription>
Стоимость, дата и параметры ссылки
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="scheduled_date">Дата размещения *</Label>
<Input
id="scheduled_date"
type="date"
value={formData.scheduled_date}
onChange={(e) =>
setFormData({
...formData,
scheduled_date: e.target.value,
})
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="cost">Стоимость () *</Label>
<Input
id="cost"
type="number"
step="0.01"
value={formData.cost}
onChange={(e) =>
setFormData({ ...formData, cost: e.target.value })
}
placeholder="1000"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="post_link">Ссылка на рекламное сообщение</Label>
<Input
id="post_link"
type="url"
value={formData.post_link}
onChange={(e) =>
setFormData({ ...formData, post_link: e.target.value })
}
placeholder="https://t.me/channel/123"
/>
<p className="text-xs text-muted-foreground">
Для автоматического отслеживания просмотров
</p>
</div>
<div className="space-y-2">
<Label>Тип пригласительной ссылки *</Label>
<RadioGroup
value={formData.invite_link_type}
onValueChange={(value: "public" | "private") =>
setFormData({ ...formData, invite_link_type: value })
}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="public" id="public" />
<Label htmlFor="public" className="font-normal">
Открытая (пользователь сразу вступает в канал)
</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="private" id="private" />
<Label htmlFor="private" className="font-normal">
С одобрением (запрос на вступление через бота)
</Label>
</div>
</RadioGroup>
</div>
<div className="space-y-2">
<Label htmlFor="comment">Комментарий</Label>
<Textarea
id="comment"
value={formData.comment}
onChange={(e) =>
setFormData({ ...formData, comment: e.target.value })
}
placeholder="Дополнительные заметки о закупе"
rows={3}
/>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => router.push("/purchases")}
>
Отмена
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Создание...
</>
) : (
"Создать закуп"
)}
</Button>
</div>
</form>
</div>
</>
);
}

View File

@@ -0,0 +1,381 @@
"use client";
// ============================================================================
// Purchases List Page
// ============================================================================
import React, { useEffect, useState } from "react";
import Link from "next/link";
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 { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { purchasesApi, channelsApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
formatCurrency,
formatDate,
formatPercent,
} from "@/lib/utils/format";
import {
ShoppingCart,
Loader2,
AlertCircle,
Plus,
Search,
Filter,
Eye,
CheckCircle,
Clock,
Archive,
} from "lucide-react";
import type { Purchase, TargetChannel } from "@/lib/types/api";
import { Alert, AlertDescription } from "@/components/ui/alert";
export default function PurchasesPage() {
const [purchases, setPurchases] = useState<Purchase[]>([]);
const [channels, setChannels] = useState<TargetChannel[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const [filterChannel, setFilterChannel] = useState<string>("all");
const [filterStatus, setFilterStatus] = useState<string>("all");
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
try {
setLoading(true);
const [purchasesRes, channelsRes] = await Promise.all([
purchasesApi.list(),
channelsApi.list({}),
]);
setPurchases(purchasesRes.data);
setChannels(channelsRes.data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки данных");
} finally {
setLoading(false);
}
};
const filteredPurchases = purchases.filter((purchase) => {
// Поиск
const matchesSearch =
purchase.external_channel.title
.toLowerCase()
.includes(searchQuery.toLowerCase()) ||
purchase.target_channel.title
.toLowerCase()
.includes(searchQuery.toLowerCase()) ||
purchase.creative.name.toLowerCase().includes(searchQuery.toLowerCase());
// Фильтр по каналу
const matchesChannel =
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;
}
return matchesSearch && matchesChannel && matchesStatus;
});
// Статистика
const stats = {
total: purchases.length,
completed: purchases.filter((p) => p.actual_date).length,
scheduled: purchases.filter((p) => !p.actual_date).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 (
<>
<DashboardHeader
breadcrumbs={[{ label: "Главная", href: "/" }, { label: "Закупы" }]}
/>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Закупы</h1>
<p className="text-muted-foreground mt-1">
Рекламные размещения во внешних каналах
</p>
</div>
<Button asChild>
<Link href="/purchases/new">
<Plus className="mr-2 h-4 w-4" />
Создать закуп
</Link>
</Button>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Всего закупов
</CardTitle>
<ShoppingCart className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(stats.total)}
</div>
<p className="text-xs text-muted-foreground mt-1">
{stats.completed} завершено, {stats.scheduled} запланировано
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Общие затраты
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatCurrency(stats.totalCost)}
</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>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(stats.totalSubscriptions)}
</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>
</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>
<CardHeader>
<CardTitle>Фильтры</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Поиск по названию..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-8"
/>
</div>
<Select value={filterChannel} onValueChange={setFilterChannel}>
<SelectTrigger>
<SelectValue placeholder="Целевой канал" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Все каналы</SelectItem>
{channels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
{channel.title}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filterStatus} onValueChange={setFilterStatus}>
<SelectTrigger>
<SelectValue placeholder="Статус" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Все статусы</SelectItem>
<SelectItem value="completed">Завершено</SelectItem>
<SelectItem value="scheduled">Запланировано</SelectItem>
<SelectItem value="archived">Архив</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary">
Найдено: {formatNumber(filteredPurchases.length)}
</Badge>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Список закупов</CardTitle>
<CardDescription>Все рекламные размещения</CardDescription>
</CardHeader>
<CardContent>
{loading ? (
<div className="flex items-center justify-center p-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : filteredPurchases.length === 0 ? (
<div className="text-center py-12">
<ShoppingCart className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-lg font-medium text-muted-foreground">
{searchQuery ||
filterChannel !== "all" ||
filterStatus !== "all"
? "Закупы не найдены"
: "Нет закупов"}
</p>
<p className="text-sm text-muted-foreground mt-1">
{searchQuery ||
filterChannel !== "all" ||
filterStatus !== "all"
? "Попробуйте изменить фильтры"
: "Создайте первый закуп"}
</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Статус</TableHead>
<TableHead>Целевой канал</TableHead>
<TableHead>Внешний канал</TableHead>
<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></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredPurchases.map((purchase) => (
<TableRow key={purchase.id}>
<TableCell>
{purchase.is_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}
</TableCell>
<TableCell>{purchase.external_channel.title}</TableCell>
<TableCell className="max-w-[200px] truncate">
{purchase.creative.name}
</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">
{purchase.cpf ? `${formatMetric(purchase.cpf)}` : "—"}
</TableCell>
<TableCell className="text-right">
{purchase.conversion_rate
? formatPercent(purchase.conversion_rate)
: "—"}
</TableCell>
<TableCell className="text-right">
<Button asChild variant="ghost" size="sm">
<Link href={`/purchases/${purchase.id}`}>
<Eye className="h-4 w-4" />
</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
</>
);
}