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,321 @@
"use client";
// ============================================================================
// Creative 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 { creativesApi } from "@/lib/api";
import {
formatNumber,
formatMetric,
formatCurrency,
formatDate,
} from "@/lib/utils/format";
import {
Folder,
ArrowLeft,
Loader2,
AlertCircle,
Archive,
Trash2,
BarChart3,
Users,
TrendingUp,
} from "lucide-react";
import type { CreativeDetail } from "@/lib/types/api";
interface PageProps {
params: Promise<{ id: string }>;
}
export default function CreativeDetailPage({ params }: PageProps) {
const resolvedParams = use(params);
const router = useRouter();
const [creative, setCreative] = useState<CreativeDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadCreative = async () => {
try {
setLoading(true);
const data = await creativesApi.get(resolvedParams.id);
setCreative(data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки креатива");
} finally {
setLoading(false);
}
};
loadCreative();
}, [resolvedParams.id]);
const handleArchive = async () => {
if (!creative) return;
try {
await creativesApi.update(creative.id, {
is_archived: !creative.is_archived,
});
setCreative({ ...creative, is_archived: !creative.is_archived });
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления креатива");
}
};
const handleDelete = async () => {
if (!creative) return;
if (!confirm(`Удалить креатив "${creative.name}"?`)) return;
try {
await creativesApi.delete(creative.id);
router.push("/creatives");
} catch (err: any) {
alert(err?.error?.message || "Ошибка удаления креатива");
}
};
if (loading) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Креативы", href: "/creatives" },
{ label: "Загрузка..." },
]}
/>
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</>
);
}
if (error || !creative) {
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Креативы", href: "/creatives" },
{ 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="/creatives">
<ArrowLeft className="mr-2 h-4 w-4" />
Вернуться к креативам
</Link>
</Button>
</div>
</>
);
}
const previewText = creative.text.replace(
"{link}",
"https://t.me/+InviteLinkExample"
);
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Креативы", href: "/creatives" },
{ label: creative.name },
]}
/>
<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">
<Folder className="h-6 w-6" />
<h1 className="text-3xl font-bold tracking-tight">
{creative.name}
</h1>
{creative.is_archived && <Badge variant="secondary">Архив</Badge>}
</div>
<div className="text-sm text-muted-foreground">
Целевой канал: {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 ? "Разархивировать" : "Архивировать"}
</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-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(creative.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(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>
<p className="text-xs text-muted-foreground mt-1">
По всем закупам
</p>
</CardContent>
</Card>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Текст креатива</CardTitle>
<CardDescription>Шаблон с переменной {"{link}"}</CardDescription>
</CardHeader>
<CardContent>
<div className="rounded-lg border bg-muted/50 p-4">
<pre className="text-sm whitespace-pre-wrap font-sans">
{creative.text}
</pre>
</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">{previewText}</p>
</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<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>
)}
</CardContent>
</Card>
</div>
</>
);
}

View File

@@ -0,0 +1,249 @@
"use client";
// ============================================================================
// Create Creative Page
// ============================================================================
import React, { useEffect, useState } 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 { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { creativesApi, channelsApi } from "@/lib/api";
import { AlertCircle, Loader2, ArrowLeft, Info } from "lucide-react";
import type { TargetChannel } from "@/lib/types/api";
export default function CreateCreativePage() {
const router = useRouter();
const [channels, setChannels] = useState<TargetChannel[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [formData, setFormData] = useState({
name: "",
text: "",
target_channel_id: "",
});
useEffect(() => {
loadChannels();
}, []);
const loadChannels = async () => {
try {
const response = await channelsApi.list({ is_active: true });
setChannels(response.data);
} catch (err) {
console.error("Error loading channels:", err);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validation
if (!formData.name.trim()) {
setError("Введите название креатива");
return;
}
if (!formData.text.trim()) {
setError("Введите текст креатива");
return;
}
if (!formData.text.includes("{link}")) {
setError("Текст должен содержать переменную {link} для вставки ссылки");
return;
}
if (!formData.target_channel_id) {
setError("Выберите целевой канал");
return;
}
try {
setIsLoading(true);
await creativesApi.create(formData);
router.push("/creatives");
} catch (err: any) {
setError(err?.error?.message || "Ошибка создания креатива");
} finally {
setIsLoading(false);
}
};
const previewText = formData.text.replace(
"{link}",
"https://t.me/+InviteLinkExample"
);
return (
<>
<DashboardHeader
breadcrumbs={[
{ label: "Главная", href: "/" },
{ label: "Креативы", href: "/creatives" },
{ 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">
<a href="/creatives">
<ArrowLeft className="mr-2 h-4 w-4" />
Назад
</a>
</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="space-y-2">
<Label htmlFor="name">Название креатива *</Label>
<Input
id="name"
value={formData.name}
onChange={(e) =>
setFormData({ ...formData, name: e.target.value })
}
placeholder='Например: Креатив "Присоединяйся"'
/>
</div>
<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 })
}
>
<SelectTrigger>
<SelectValue placeholder="Выберите канал" />
</SelectTrigger>
<SelectContent>
{channels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
{channel.title}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Текст сообщения</CardTitle>
<CardDescription>
Используйте переменную {"{link}"} для вставки ссылки
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="text">Текст креатива *</Label>
<Textarea
id="text"
value={formData.text}
onChange={(e) =>
setFormData({ ...formData, text: e.target.value })
}
placeholder="🔥 Присоединяйся к нашему сообществу!&#10;&#10;Узнавай первым о новых возможностях.&#10;&#10;👉 {link}"
rows={8}
className="font-mono text-sm"
/>
</div>
<Alert>
<Info className="h-4 w-4" />
<AlertDescription className="text-sm">
<strong>Обязательно</strong> включите переменную {"{link}"} в
текст. На её место будет подставлена пригласительная ссылка в
целевой канал.
</AlertDescription>
</Alert>
</CardContent>
</Card>
{formData.text && (
<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">{previewText}</p>
</div>
</CardContent>
</Card>
)}
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => router.push("/creatives")}
>
Отмена
</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,255 @@
"use client";
// ============================================================================
// Creatives 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { creativesApi } from "@/lib/api";
import { formatNumber, formatMetric, truncate } from "@/lib/utils/format";
import {
Folder,
Loader2,
AlertCircle,
Plus,
Eye,
Pencil,
Archive,
Trash2,
} from "lucide-react";
import type { Creative } from "@/lib/types/api";
import { Alert, AlertDescription } from "@/components/ui/alert";
export default function CreativesPage() {
const [creatives, setCreatives] = useState<Creative[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<"all" | "active" | "archived">(
"active"
);
useEffect(() => {
loadCreatives();
}, []);
const loadCreatives = async () => {
try {
setLoading(true);
const response = await creativesApi.list();
setCreatives(response.data);
} catch (err: any) {
setError(err?.error?.message || "Ошибка загрузки креативов");
} finally {
setLoading(false);
}
};
const handleArchive = async (id: string, isArchived: boolean) => {
try {
await creativesApi.update(id, { is_archived: !isArchived });
loadCreatives();
} catch (err: any) {
alert(err?.error?.message || "Ошибка обновления креатива");
}
};
const handleDelete = async (id: string, name: string) => {
if (!confirm(`Удалить креатив "${name}"?`)) return;
try {
await creativesApi.delete(id);
loadCreatives();
} catch (err: any) {
alert(err?.error?.message || "Ошибка удаления креатива");
}
};
const filteredCreatives = creatives.filter((creative) => {
if (activeTab === "active") return !creative.is_archived;
if (activeTab === "archived") return creative.is_archived;
return true;
});
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="/creatives/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>
)}
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as any)}
className="w-full"
>
<TabsList>
<TabsTrigger value="active">
Активные ({creatives.filter((c) => !c.is_archived).length})
</TabsTrigger>
<TabsTrigger value="archived">
Архив ({creatives.filter((c) => c.is_archived).length})
</TabsTrigger>
<TabsTrigger value="all">Все ({creatives.length})</TabsTrigger>
</TabsList>
<TabsContent value={activeTab} className="mt-4">
{loading ? (
<div className="flex items-center justify-center p-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : filteredCreatives.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center justify-center p-12">
<Folder className="h-12 w-12 text-muted-foreground mb-4" />
<p className="text-lg font-medium text-muted-foreground">
{activeTab === "all" && "Нет креативов"}
{activeTab === "active" && "Нет активных креативов"}
{activeTab === "archived" && "Нет архивных креативов"}
</p>
<p className="text-sm text-muted-foreground mt-1">
Создайте первый креатив для рекламных сообщений
</p>
{activeTab === "active" && (
<Button asChild className="mt-4">
<Link href="/creatives/new">
<Plus className="mr-2 h-4 w-4" />
Создать креатив
</Link>
</Button>
)}
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredCreatives.map((creative) => (
<Card
key={creative.id}
className="hover:shadow-md transition-shadow"
>
<CardHeader>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<CardTitle className="truncate text-base">
{creative.name}
</CardTitle>
{creative.is_archived && (
<Badge variant="secondary">Архив</Badge>
)}
</div>
<CardDescription className="text-xs">
{creative.target_channel.title}
</CardDescription>
</div>
<Folder className="h-5 w-5 text-muted-foreground shrink-0" />
</div>
</CardHeader>
<CardContent className="space-y-3">
<div className="rounded-lg border bg-muted/50 p-3">
<p className="text-sm whitespace-pre-wrap line-clamp-4">
{creative.text}
</p>
</div>
<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(creative.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(creative.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(creative.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"
size="sm"
className="flex-1"
>
<Link href={`/creatives/${creative.id}`}>
<Eye className="mr-2 h-4 w-4" />
Открыть
</Link>
</Button>
<Button
variant="ghost"
size="sm"
onClick={() =>
handleArchive(creative.id, creative.is_archived)
}
>
<Archive className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() =>
handleDelete(creative.id, creative.name)
}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
</TabsContent>
</Tabs>
</div>
</>
);
}