feat: some fixes
This commit is contained in:
@@ -12,10 +12,15 @@ import {
|
||||
ArrowLeft,
|
||||
Pencil,
|
||||
Archive,
|
||||
Trash2,
|
||||
Copy,
|
||||
Check,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
LayoutList,
|
||||
Plus,
|
||||
BarChart3,
|
||||
FileText,
|
||||
Image,
|
||||
Video,
|
||||
} from "lucide-react";
|
||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||
@@ -43,6 +48,19 @@ import {
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs";
|
||||
import { TelegramPostPreview } from "@/components/telegram-post-preview";
|
||||
import type { Creative } from "@/lib/types/api";
|
||||
|
||||
// ============================================================================
|
||||
@@ -62,8 +80,8 @@ export default function CreativeDetailPage() {
|
||||
const [isEditing, setIsEditing] = useState(searchParams.get("edit") === "true");
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [viewMode, setViewMode] = useState<"preview" | "data">("preview");
|
||||
|
||||
// Edit form state
|
||||
const [name, setName] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -72,6 +90,7 @@ export default function CreativeDetailPage() {
|
||||
|
||||
useEffect(() => {
|
||||
loadCreative();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [workspaceId, creativeId]);
|
||||
|
||||
const loadCreative = async () => {
|
||||
@@ -110,8 +129,9 @@ export default function CreativeDetailPage() {
|
||||
|
||||
setCreative(updated);
|
||||
setIsEditing(false);
|
||||
} catch (err: any) {
|
||||
setError(err?.detail || "Не удалось сохранить");
|
||||
} catch (err) {
|
||||
const errorMessage = err && typeof err === 'object' && 'detail' in err ? (err as { detail?: string }).detail ?? "Не удалось сохранить" : "Не удалось сохранить";
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
@@ -121,8 +141,7 @@ export default function CreativeDetailPage() {
|
||||
if (!creative) return;
|
||||
|
||||
try {
|
||||
// Toggle archive status by updating via delete endpoint (soft delete)
|
||||
await creativesApi.delete(workspaceId, creativeId);
|
||||
await creativesApi.update(workspaceId, creativeId, { status: "archived" });
|
||||
router.push(`/dashboard/${workspaceId}/creatives`);
|
||||
} catch (err) {
|
||||
console.error("Failed to archive:", err);
|
||||
@@ -173,6 +192,8 @@ export default function CreativeDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const isActive = creative.status === "active";
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader
|
||||
@@ -183,7 +204,7 @@ export default function CreativeDetailPage() {
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4 max-w-3xl">
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
@@ -198,12 +219,8 @@ export default function CreativeDetailPage() {
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{creative.name}
|
||||
</h1>
|
||||
<Badge
|
||||
variant={
|
||||
creative.status === "active" ? "default" : "secondary"
|
||||
}
|
||||
>
|
||||
{creative.status === "active" ? "Активен" : "Архив"}
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{isActive ? "Активен" : "Архив"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
@@ -214,6 +231,38 @@ export default function CreativeDetailPage() {
|
||||
|
||||
{canWrite && !isEditing && (
|
||||
<div className="flex gap-2">
|
||||
{isActive && (
|
||||
<Button
|
||||
asChild
|
||||
variant="outline"
|
||||
>
|
||||
<Link href={`/dashboard/${workspaceId}/purchase-plans/${creative.project_id}?creative_id=${creative.id}`}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Создать размещение
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline">
|
||||
Дополнительно
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/dashboard/${workspaceId}/purchase-plans/${creative.project_id}`}>
|
||||
<LayoutList className="h-4 w-4 mr-2" />
|
||||
Все размещения
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/dashboard/${workspaceId}/analytics/placements?creative_id=${creative.id}`}>
|
||||
<BarChart3 className="h-4 w-4 mr-2" />
|
||||
Аналитика
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" onClick={() => setIsEditing(true)}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Редактировать
|
||||
@@ -245,120 +294,209 @@ export default function CreativeDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isEditing ? (
|
||||
<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={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="text">Текст креатива</Label>
|
||||
<Textarea
|
||||
id="text"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
disabled={isSaving}
|
||||
rows={10}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Не забудьте <code className="bg-muted px-1 rounded">{"{invite_link}"}</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
<div className="max-w-3xl mx-auto space-y-4">
|
||||
{isEditing ? (
|
||||
<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={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Сохранение...
|
||||
</>
|
||||
) : (
|
||||
"Сохранить"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Текст креатива</CardTitle>
|
||||
<Button variant="outline" size="sm" onClick={handleCopy}>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
Скопировано
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Копировать
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<pre className="whitespace-pre-wrap text-sm bg-muted p-4 rounded-lg">
|
||||
{creative.text.replace(
|
||||
"{invite_link}",
|
||||
"https://t.me/+AbCdEfGhIjK"
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="text">Текст креатива</Label>
|
||||
<Textarea
|
||||
id="text"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
disabled={isSaving}
|
||||
rows={10}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Не забудьте <code className="bg-muted px-1 rounded">{"{invite_link}"}</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</pre>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
<code className="bg-muted px-1 rounded">{"{invite_link}"}</code>{" "}
|
||||
заменяется уникальной ссылкой при создании размещения
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Quick Actions */}
|
||||
{canWrite && creative.status === "active" && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Действия</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/placements/new?creative_id=${creative.id}`}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Создать размещение с этим креативом
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Сохранение...
|
||||
</>
|
||||
) : (
|
||||
"Сохранить"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as "preview" | "data")}>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="preview" className="gap-2">
|
||||
<Eye className="h-4 w-4" />
|
||||
Preview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="data" className="gap-2">
|
||||
<LayoutList className="h-4 w-4" />
|
||||
Данные
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="preview" className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Предпросмотр</h3>
|
||||
<Button variant="outline" size="sm" onClick={handleCopy}>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
Скопировано
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Копировать
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<TelegramPostPreview
|
||||
text={creative.text}
|
||||
mediaItems={creative.media_items}
|
||||
buttons={creative.buttons}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="data" className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Данные креатива</h3>
|
||||
<Button variant="outline" size="sm" onClick={handleCopy}>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
Скопировано
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Копировать
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm">Название</Label>
|
||||
<p className="font-medium">{creative.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm">Статус</Label>
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{isActive ? "Активен" : "Архив"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm">Размещений</Label>
|
||||
<p className="font-medium">{creative.placements_count}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm">Проект</Label>
|
||||
<p className="font-medium">{creative.project_channel_title}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm">Создан</Label>
|
||||
<p className="font-medium">
|
||||
{new Date(creative.created_at).toLocaleDateString("ru-RU", {
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{creative.media_items && creative.media_items.length > 0 && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm mb-3 block">Медиа ({creative.media_items.length})</Label>
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{creative.media_items.map((media, index) => (
|
||||
<div key={index} className="border rounded-lg p-3 space-y-2">
|
||||
<div className="w-8 h-8 bg-muted rounded-md flex items-center justify-center">
|
||||
{/* eslint-disable-next-line jsx-a11y/alt-text */}
|
||||
{media.media_type === "photo" && <Image className="h-4 w-4 text-muted-foreground" />}
|
||||
{media.media_type === "video" && <Video className="h-4 w-4 text-muted-foreground" />}
|
||||
{media.media_type === "animation" && <FileText className="h-4 w-4 text-muted-foreground" />}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium capitalize">{media.media_type}</p>
|
||||
<p className="text-[10px] text-muted-foreground font-mono">
|
||||
{media.media_file_id.slice(0, 10)}...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{creative.buttons && creative.buttons.length > 0 && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm mb-3 block">Кнопки ({creative.buttons.length})</Label>
|
||||
<div className="space-y-2">
|
||||
{creative.buttons.map((button, index) => (
|
||||
<div key={index} className="border rounded-lg p-3 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{button.text}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{button.url}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label className="text-muted-foreground text-sm mb-3 block">Текст</Label>
|
||||
<div className="border rounded-lg p-4 bg-muted">
|
||||
<pre className="text-sm whitespace-pre-wrap font-mono">
|
||||
{creative.text}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
// Create Creative Page
|
||||
// ============================================================================
|
||||
|
||||
import { useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import { Loader2, ArrowLeft, Info } from "lucide-react";
|
||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||
@@ -30,14 +30,27 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
export default function NewCreativePage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const workspaceId = params?.workspaceId as string;
|
||||
const { currentProject } = useWorkspace();
|
||||
const { currentProject, setSelectedProjects, projects } = useWorkspace();
|
||||
|
||||
const prefilledProjectId = searchParams.get("project_id");
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Auto-select project if prefilled from URL
|
||||
useEffect(() => {
|
||||
if (prefilledProjectId && projects.length > 0) {
|
||||
const project = projects.find(p => p.id === prefilledProjectId);
|
||||
if (project) {
|
||||
setSelectedProjects([project]);
|
||||
}
|
||||
}
|
||||
}, [prefilledProjectId, projects, setSelectedProjects]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -69,7 +82,8 @@ export default function NewCreativePage() {
|
||||
}
|
||||
);
|
||||
|
||||
router.push(`/dashboard/${workspaceId}/creatives/${creative.id}`);
|
||||
// Redirect to creatives list with project filter
|
||||
router.push(`/dashboard/${workspaceId}/creatives?project_id=${currentProject.id}`);
|
||||
} catch (err: any) {
|
||||
setError(err?.detail || "Не удалось создать креатив");
|
||||
} finally {
|
||||
@@ -239,4 +253,3 @@ export default function NewCreativePage() {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// ============================================================================
|
||||
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Loader2,
|
||||
@@ -25,6 +25,9 @@ import {
|
||||
Info,
|
||||
Grid,
|
||||
List,
|
||||
FileText,
|
||||
Image,
|
||||
Video,
|
||||
} from "lucide-react";
|
||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||
@@ -120,12 +123,26 @@ const getCreativeWord = (count: number): string => {
|
||||
return "креативов";
|
||||
};
|
||||
|
||||
const getMediaIcon = (mediaType: string) => {
|
||||
switch (mediaType) {
|
||||
case "photo":
|
||||
return Image;
|
||||
case "video":
|
||||
return Video;
|
||||
case "animation":
|
||||
return FileText;
|
||||
default:
|
||||
return FileText;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Component
|
||||
// ============================================================================
|
||||
|
||||
export default function CreativesPage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const workspaceId = params?.workspaceId as string;
|
||||
const { selectedProjects, getProjectFilterId, allProjectsSelected, hasPermission, currentProject } = useWorkspace();
|
||||
const projectFilterId = getProjectFilterId();
|
||||
@@ -192,7 +209,8 @@ export default function CreativesPage() {
|
||||
|
||||
const handleArchive = async (creative: Creative) => {
|
||||
try {
|
||||
await creativesApi.update(workspaceId, creative.id, {});
|
||||
const newStatus = creative.status === "active" ? "archived" : "active";
|
||||
await creativesApi.update(workspaceId, creative.id, { status: newStatus });
|
||||
loadCreatives();
|
||||
} catch (err) {
|
||||
console.error("Failed to archive creative:", err);
|
||||
@@ -210,17 +228,39 @@ export default function CreativesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopyText = (text: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
};
|
||||
|
||||
// Filter by search
|
||||
const filteredCreatives = creativesWithStats.filter(
|
||||
(c) =>
|
||||
c.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.text.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
const handleCreateCreativeClick = () => {
|
||||
if (currentProject) {
|
||||
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
|
||||
} else {
|
||||
setShowCreateDialog(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenBotClick = () => {
|
||||
const botUrl = currentProject
|
||||
? `https://t.me/${BOT_USERNAME}?start=project_${currentProject.id}_createcreative`
|
||||
: `https://t.me/${BOT_USERNAME}`;
|
||||
window.open(botUrl, "_blank");
|
||||
setShowCreateDialog(false);
|
||||
};
|
||||
|
||||
const handleCreateOnPlatformClick = () => {
|
||||
if (!currentProject) return;
|
||||
router.push(`/dashboard/${workspaceId}/creatives/new?project_id=${currentProject.id}`);
|
||||
setShowCreateDialog(false);
|
||||
};
|
||||
|
||||
const handleCopyText = (text: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
};
|
||||
|
||||
// Totals
|
||||
const totals = useMemo(() => {
|
||||
const data = filteredCreatives.filter((c) => c.analytics);
|
||||
@@ -233,11 +273,11 @@ export default function CreativesPage() {
|
||||
}, [filteredCreatives]);
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipProvider>
|
||||
<DashboardHeader
|
||||
breadcrumbs={[
|
||||
{ label: "Главная", href: `/dashboard/${workspaceId}` },
|
||||
{ label: "Креативы" },
|
||||
{ label: "Креативы", href: `/dashboard/${workspaceId}/creatives` },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -270,7 +310,7 @@ export default function CreativesPage() {
|
||||
</Button>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<Button onClick={() => setShowCreateDialog(true)}>
|
||||
<Button onClick={handleCreateCreativeClick}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Создать креатив
|
||||
</Button>
|
||||
@@ -390,16 +430,35 @@ export default function CreativesPage() {
|
||||
{filteredCreatives.map((creative) => (
|
||||
<TableRow key={creative.id}>
|
||||
<TableCell>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{creative.name}
|
||||
</Link>
|
||||
<div className="flex items-start gap-3">
|
||||
{creative.media_items && creative.media_items.length > 0 && (
|
||||
<div className="flex gap-0.5 mt-0.5">
|
||||
{creative.media_items.slice(0, 2).map((media: { media_type: string }, idx: number) => {
|
||||
const MediaIcon = getMediaIcon(media.media_type);
|
||||
return (
|
||||
<MediaIcon key={idx} className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
);
|
||||
})}
|
||||
{creative.media_items.length > 2 && (
|
||||
<span className="text-xs text-muted-foreground">+{creative.media_items.length - 2}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}`}
|
||||
className="font-medium hover:underline block"
|
||||
>
|
||||
{creative.name}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="max-w-[300px] truncate text-sm text-muted-foreground">
|
||||
{creative.text.replace("{invite_link}", "[ссылка]")}
|
||||
<div className="max-w-[350px] text-sm text-muted-foreground">
|
||||
<div className="line-clamp-2">
|
||||
{creative.text.replace("{invite_link}", "[ссылка]")}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
@@ -436,61 +495,78 @@ export default function CreativesPage() {
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<div className="flex items-center gap-1">
|
||||
{canWrite && creative.status === "active" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
asChild
|
||||
>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/placements/new?creative_id=${creative.id}`}
|
||||
title="Создать размещение"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}`}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
Просмотр
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/analytics/creatives?creative_id=${creative.id}`}
|
||||
>
|
||||
<BarChart3 className="h-4 w-4 mr-2" />
|
||||
Аналитика
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleCopyText(creative.text)}>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Копировать текст
|
||||
</DropdownMenuItem>
|
||||
{canWrite && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}?edit=true`}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Редактировать
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleArchive(creative)}>
|
||||
<Archive className="h-4 w-4 mr-2" />
|
||||
{creative.status === "active" ? "В архив" : "Восстановить"}
|
||||
</DropdownMenuItem>
|
||||
{creative.placements_count === 0 && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDelete(creative.id)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Удалить
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}`}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
Просмотр
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/analytics/placements?creative_id=${creative.id}`}
|
||||
>
|
||||
<BarChart3 className="h-4 w-4 mr-2" />
|
||||
Аналитика
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleCopyText(creative.text)}>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Копировать текст
|
||||
</DropdownMenuItem>
|
||||
{canWrite && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/creatives/${creative.id}?edit=true`}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Редактировать
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<DropdownMenuItem onClick={() => handleArchive(creative)}>
|
||||
<Archive className="h-4 w-4 mr-2" />
|
||||
{creative.status === "active" ? "В архив" : "Восстановить"}
|
||||
</DropdownMenuItem>
|
||||
{creative.placements_count === 0 && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDelete(creative.id)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Удалить
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -597,41 +673,47 @@ export default function CreativesPage() {
|
||||
<DialogHeader>
|
||||
<DialogTitle>Создание креатива</DialogTitle>
|
||||
<DialogDescription>
|
||||
Создание креатива работает через Telegram бота
|
||||
Создание креатива через Telegram бота или на платформе
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Чтобы создать креатив:
|
||||
Выберите способ создания креатива:
|
||||
</p>
|
||||
<ol className="list-decimal list-inside space-y-2 text-sm">
|
||||
<li>Перейдите в Telegram бота <strong>@{BOT_USERNAME}</strong></li>
|
||||
<li>Откройте раздел <strong>Креативы</strong></li>
|
||||
<li>Нажмите <strong>Создание</strong></li>
|
||||
<li>Перешлите созданный креатив боту</li>
|
||||
<li>Креатив автоматически отобразится на платформе</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowCreateDialog(false)}
|
||||
className="w-full justify-start"
|
||||
onClick={handleOpenBotClick}
|
||||
>
|
||||
Понятно
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
const botUrl = currentProject
|
||||
? `https://t.me/${BOT_USERNAME}?start=project_${currentProject.id}_createcreative`
|
||||
: `https://t.me/${BOT_USERNAME}`;
|
||||
window.open(botUrl, "_blank");
|
||||
setShowCreateDialog(false);
|
||||
}}
|
||||
>
|
||||
Открыть бота
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Через Telegram бота</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Перешлите сообщение боту
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
{currentProject && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start"
|
||||
onClick={handleCreateOnPlatformClick}
|
||||
>
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="text-left">
|
||||
<p className="font-medium">На платформе</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Для проекта: {currentProject.title}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -49,11 +49,11 @@ export default function NewPlacementPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const workspaceId = params?.workspaceId as string;
|
||||
const { currentProject } = useWorkspace();
|
||||
const { currentProject, setSelectedProjects, projects } = useWorkspace();
|
||||
|
||||
// Pre-filled from URL params
|
||||
const prefilledCreativeId = searchParams.get("creative_id");
|
||||
const prefilledChannelId = searchParams.get("channel_id");
|
||||
const prefilledCreativeId = searchParams.get("creative_id");
|
||||
|
||||
// Form state
|
||||
const [channelId, setChannelId] = useState(prefilledChannelId || "");
|
||||
@@ -73,10 +73,26 @@ export default function NewPlacementPage() {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Auto-select project when creative_id is provided
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [workspaceId, currentProject?.id]);
|
||||
if (!prefilledCreativeId || projects.length === 0) return;
|
||||
|
||||
const loadCreativeAndSelectProject = async () => {
|
||||
try {
|
||||
const creative = await creativesApi.get(workspaceId, prefilledCreativeId);
|
||||
const project = projects.find(p => p.id === creative.project_id);
|
||||
if (project) {
|
||||
setSelectedProjects([project]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load creative:", err);
|
||||
}
|
||||
};
|
||||
|
||||
loadCreativeAndSelectProject();
|
||||
}, [prefilledCreativeId, projects, workspaceId, setSelectedProjects]);
|
||||
|
||||
// Load channels and creatives
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoadingData(true);
|
||||
@@ -101,6 +117,10 @@ export default function NewPlacementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [workspaceId, currentProject?.id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -129,7 +149,8 @@ export default function NewPlacementPage() {
|
||||
invite_link_type: inviteLinkType,
|
||||
});
|
||||
|
||||
router.push(`/dashboard/${workspaceId}/placements/${placement.id}`);
|
||||
// Redirect to placements list with project filter
|
||||
router.push(`/dashboard/${workspaceId}/placements?project_id=${currentProject.id}`);
|
||||
} catch (err: any) {
|
||||
setError(err?.detail || "Не удалось создать размещение");
|
||||
} finally {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// ============================================================================
|
||||
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useParams, useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Loader2,
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
FileSpreadsheet,
|
||||
FileText,
|
||||
Info,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { DashboardHeader } from "@/components/layout/dashboard-header";
|
||||
import { useWorkspace } from "@/components/providers/workspace-provider";
|
||||
@@ -254,6 +255,7 @@ const downloadBlob = (blob: Blob, filename: string) => {
|
||||
|
||||
export default function PlacementsPage() {
|
||||
const params = useParams();
|
||||
const searchParams = useSearchParams();
|
||||
const workspaceId = params?.workspaceId as string;
|
||||
const { selectedProjects, getProjectFilterId, allProjectsSelected, hasPermission } = useWorkspace();
|
||||
const projectFilterId = getProjectFilterId();
|
||||
@@ -264,6 +266,7 @@ export default function PlacementsPage() {
|
||||
const [includeArchived, setIncludeArchived] = useState(false);
|
||||
const [sortField, setSortField] = useState<SortField | null>(null);
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>(null);
|
||||
const [creativeFilterId, setCreativeFilterId] = useState<string | null>(searchParams.get("creative_id"));
|
||||
|
||||
// Aggregation settings
|
||||
const [aggCost, setAggCost] = useState<AggFunc>("sum");
|
||||
@@ -274,6 +277,11 @@ export default function PlacementsPage() {
|
||||
|
||||
const canWrite = hasPermission("placements_write");
|
||||
|
||||
useEffect(() => {
|
||||
const creativeId = searchParams.get("creative_id");
|
||||
setCreativeFilterId(creativeId);
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
loadPlacements();
|
||||
}, [workspaceId, projectFilterId, includeArchived]);
|
||||
@@ -321,11 +329,15 @@ export default function PlacementsPage() {
|
||||
// Filter and sort
|
||||
const filteredPlacements = useMemo(() => {
|
||||
return placements
|
||||
.filter(
|
||||
(p) =>
|
||||
.filter((p) => {
|
||||
const matchesSearch =
|
||||
p.channel.title.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(p.creative_id && p.creative_id.toString().toLowerCase().includes(search.toLowerCase()))
|
||||
)
|
||||
(p.creative_id && p.creative_id.toString().toLowerCase().includes(search.toLowerCase()));
|
||||
|
||||
const matchesCreative = !creativeFilterId || p.creative_id === creativeFilterId;
|
||||
|
||||
return matchesSearch && matchesCreative;
|
||||
})
|
||||
.sort((a, b) => {
|
||||
if (!sortField || !sortOrder) return 0;
|
||||
|
||||
@@ -460,11 +472,24 @@ export default function PlacementsPage() {
|
||||
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Размещения</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{filteredPlacements.length} размещений
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-muted-foreground">
|
||||
{filteredPlacements.length} размещений
|
||||
</p>
|
||||
{creativeFilterId && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
Креатив
|
||||
<Link
|
||||
href={`/dashboard/${workspaceId}/placements`}
|
||||
className="hover:text-destructive"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Link>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Export Button */}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// ============================================================================
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Loader2,
|
||||
@@ -531,6 +531,7 @@ function ChannelGroup({
|
||||
export default function PurchasePlanDetailPage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const workspaceId = params?.workspaceId as string;
|
||||
const projectId = params?.projectId as string;
|
||||
const { projects, hasPermission } = useWorkspace();
|
||||
@@ -543,6 +544,10 @@ export default function PurchasePlanDetailPage() {
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
|
||||
|
||||
// Create placements dialog
|
||||
const prefilledCreativeId = searchParams.get("creative_id");
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false);
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState("all");
|
||||
const [expandedAll, setExpandedAll] = useState(true);
|
||||
@@ -574,6 +579,13 @@ export default function PurchasePlanDetailPage() {
|
||||
}
|
||||
}, [projects, projectId]);
|
||||
|
||||
// Auto-open create dialog if creative_id is provided
|
||||
useEffect(() => {
|
||||
if (prefilledCreativeId && project) {
|
||||
setShowCreateDialog(true);
|
||||
}
|
||||
}, [prefilledCreativeId, project]);
|
||||
|
||||
useEffect(() => {
|
||||
loadPlacements();
|
||||
}, [workspaceId, projectId]);
|
||||
@@ -913,6 +925,9 @@ export default function PurchasePlanDetailPage() {
|
||||
workspaceId={workspaceId}
|
||||
projectId={projectId}
|
||||
existingPlacements={placements}
|
||||
prefilledCreativeId={prefilledCreativeId}
|
||||
open={showCreateDialog}
|
||||
onOpenChange={setShowCreateDialog}
|
||||
onSuccess={loadPlacements}
|
||||
>
|
||||
<Button disabled={isDemoMode}>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Loader2, Plus, Check, ChevronRight, X, AlertCircle } from "lucide-react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Loader2, Plus, Check, ChevronRight, X, AlertCircle, BookOpen } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -36,6 +37,9 @@ interface CreatePlacementsDialogProps {
|
||||
workspaceId: string;
|
||||
projectId: string;
|
||||
existingPlacements: Placement[];
|
||||
prefilledCreativeId?: string | null;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onSuccess: () => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
@@ -47,10 +51,15 @@ export function CreatePlacementsDialog({
|
||||
workspaceId,
|
||||
projectId,
|
||||
existingPlacements,
|
||||
prefilledCreativeId = null,
|
||||
open: controlledOpen,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
children,
|
||||
}: CreatePlacementsDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
||||
|
||||
const [step, setStep] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -59,9 +68,10 @@ export function CreatePlacementsDialog({
|
||||
const [newChannelInput, setNewChannelInput] = useState("");
|
||||
const [selectedChannels, setSelectedChannels] = useState<ChannelInput[]>([]);
|
||||
const [existingChannels, setExistingChannels] = useState<string[]>([]);
|
||||
const [projectChannels, setProjectChannels] = useState<Channel[]>([]);
|
||||
|
||||
// Step 2: Details
|
||||
const [creativeId, setCreativeId] = useState<string | null>(null);
|
||||
const [creativeId, setCreativeId] = useState<string | null>(prefilledCreativeId);
|
||||
const [format, setFormat] = useState("");
|
||||
const [cost, setCost] = useState("");
|
||||
const [placementDate, setPlacementDate] = useState("");
|
||||
@@ -89,7 +99,14 @@ export function CreatePlacementsDialog({
|
||||
if (!isOpen) {
|
||||
resetForm();
|
||||
}
|
||||
setOpen(isOpen);
|
||||
setInternalOpen(isOpen);
|
||||
onOpenChange?.(isOpen);
|
||||
};
|
||||
|
||||
const handleTriggerClick = () => {
|
||||
resetForm();
|
||||
setInternalOpen(true);
|
||||
onOpenChange?.(true);
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
@@ -97,7 +114,8 @@ export function CreatePlacementsDialog({
|
||||
setNewChannelInput("");
|
||||
setSelectedChannels([]);
|
||||
setExistingChannels([]);
|
||||
setCreativeId(null);
|
||||
setProjectChannels([]);
|
||||
setCreativeId(prefilledCreativeId);
|
||||
setFormat("");
|
||||
setCost("");
|
||||
setPlacementDate("");
|
||||
@@ -106,15 +124,47 @@ export function CreatePlacementsDialog({
|
||||
setCreatedCount(null);
|
||||
};
|
||||
|
||||
// Load creatives when dialog opens or when moving to step 2
|
||||
const loadCreatives = async () => {
|
||||
try {
|
||||
const response = await creativesApi.listByProject(workspaceId, projectId);
|
||||
const response = await creativesApi.list(workspaceId, {
|
||||
project_id: projectId,
|
||||
include_archived: false,
|
||||
size: 100,
|
||||
});
|
||||
setCreatives(response.items);
|
||||
|
||||
// Auto-select prefilled creative if set
|
||||
if (prefilledCreativeId && response.items.length > 0) {
|
||||
const prefilled = response.items.find((c) => c.id === prefilledCreativeId);
|
||||
if (prefilled) {
|
||||
setCreativeId(prefilled.id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load creatives:", err);
|
||||
}
|
||||
};
|
||||
|
||||
// Load project channels when opening dialog
|
||||
const loadProjectChannels = async () => {
|
||||
try {
|
||||
const projectPlacements = await placementsApi.getByProject(workspaceId, projectId);
|
||||
const channels = projectPlacements.map((p) => p.channel);
|
||||
setProjectChannels(channels);
|
||||
} catch (err) {
|
||||
console.error("Failed to load project channels:", err);
|
||||
}
|
||||
};
|
||||
|
||||
// Load creatives and project channels when dialog opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadCreatives();
|
||||
loadProjectChannels();
|
||||
}
|
||||
}, [isOpen, workspaceId, projectId, prefilledCreativeId]);
|
||||
|
||||
const addChannel = async () => {
|
||||
const username = parseChannelInput(newChannelInput);
|
||||
if (!username) {
|
||||
@@ -128,9 +178,16 @@ export function CreatePlacementsDialog({
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if channel exists in project channels
|
||||
const projectChannel = projectChannels.find((c) => c.username?.toLowerCase() === lowerUsername);
|
||||
if (projectChannel) {
|
||||
setSelectedChannels([...selectedChannels, { username, channelId: projectChannel.id }]);
|
||||
setNewChannelInput("");
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// If channel already has placements in this project, reuse its channel_id.
|
||||
// Channels are global, so we don't need to create them again - we just need
|
||||
// the channel_id to create a new placement for this channel.
|
||||
if (existingUsernames.has(lowerUsername)) {
|
||||
const existingChannelId = getExistingChannelIdByUsername(lowerUsername);
|
||||
if (!existingChannelId) {
|
||||
@@ -144,7 +201,6 @@ export function CreatePlacementsDialog({
|
||||
}
|
||||
|
||||
// Channel doesn't exist in project yet. Create it globally via API to get channel_id.
|
||||
// If channel already exists globally, API will return existing channel.
|
||||
try {
|
||||
const createResponse = await channelsApi.create([{ username }]);
|
||||
const channelId = createResponse.results[0]?.channel.id;
|
||||
@@ -206,16 +262,16 @@ export function CreatePlacementsDialog({
|
||||
}
|
||||
};
|
||||
|
||||
const handleTriggerClick = () => {
|
||||
resetForm();
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const selectedCreative = creatives.find((c) => c.id === creativeId);
|
||||
|
||||
// If open is controlled, don't render DialogTrigger
|
||||
const isControlled = controlledOpen !== undefined;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild onClick={handleTriggerClick}>{children}</DialogTrigger>
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild onClick={handleTriggerClick}>{children}</DialogTrigger>
|
||||
)}
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Создать размещения</DialogTitle>
|
||||
@@ -278,8 +334,9 @@ export function CreatePlacementsDialog({
|
||||
{/* Step 1: Channels */}
|
||||
{step === 1 && (
|
||||
<div className="space-y-4">
|
||||
{/* Add new channel */}
|
||||
<div className="space-y-2">
|
||||
<Label>Добавить каналы</Label>
|
||||
<Label>Добавить канал</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="t.me/username или @username"
|
||||
@@ -297,6 +354,7 @@ export function CreatePlacementsDialog({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Selected channels */}
|
||||
{selectedChannels.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label>Выбранные каналы ({selectedChannels.length})</Label>
|
||||
@@ -320,6 +378,57 @@ export function CreatePlacementsDialog({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Existing project channels */}
|
||||
{projectChannels.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="text-base">Существующие каналы проекта</Label>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{projectChannels.length}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="max-h-48 overflow-y-auto space-y-2">
|
||||
{projectChannels.map((channel) => (
|
||||
<div
|
||||
key={channel.id}
|
||||
className="flex items-center justify-between p-2 rounded-md bg-muted"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{channel.title}</span>
|
||||
{channel.username && (
|
||||
<span className="text-xs text-muted-foreground">@{channel.username}</span>
|
||||
)}
|
||||
</div>
|
||||
{selectedChannels.some((c) => c.channelId === channel.id) ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeChannel(channel.username || channel.id)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const channelId = channel.id;
|
||||
const username = channel.username || channel.id;
|
||||
setSelectedChannels([...selectedChannels, { username, channelId }]);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Выбрать
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -453,7 +562,7 @@ export function CreatePlacementsDialog({
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (step === 1) {
|
||||
if (step === 1 && !prefilledCreativeId) {
|
||||
loadCreatives();
|
||||
}
|
||||
setStep(step + 1);
|
||||
|
||||
226
components/telegram-post-preview.tsx
Normal file
226
components/telegram-post-preview.tsx
Normal file
@@ -0,0 +1,226 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
|
||||
interface TelegramPostPreviewProps {
|
||||
text: string;
|
||||
mediaItems?: Array<{ media_type: string; media_file_id: string }>;
|
||||
buttons?: Array<{ text: string; url: string }>;
|
||||
inviteLinkPreview?: string;
|
||||
}
|
||||
|
||||
export function TelegramPostPreview({
|
||||
text,
|
||||
mediaItems,
|
||||
buttons,
|
||||
inviteLinkPreview = "https://t.me/+AbCdEfGhIjK",
|
||||
}: TelegramPostPreviewProps) {
|
||||
const [hoveredLink, setHoveredLink] = useState<string | null>(null);
|
||||
|
||||
const renderTextWithLinks = () => {
|
||||
const result: React.ReactNode[] = [];
|
||||
let lastIndex = 0;
|
||||
const patterns = [
|
||||
{ regex: /<a\s+class=["']tg-link["']>([^<]*)<\/a>/gi, type: 'tg-link' },
|
||||
{ regex: /\{invite_link\}/gi, type: 'single' },
|
||||
];
|
||||
|
||||
const matches: { start: number; end: number; type: string; text?: string }[] = [];
|
||||
|
||||
patterns.forEach(({ regex, type }) => {
|
||||
let match;
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
start: match.index!,
|
||||
end: match.index! + match[0].length,
|
||||
type,
|
||||
text: match[1],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
matches.sort((a, b) => a.start - b.start);
|
||||
|
||||
matches.forEach((match) => {
|
||||
if (lastIndex < match.start) {
|
||||
result.push(<span key={`text-${lastIndex}`}>{text.slice(lastIndex, match.start)}</span>);
|
||||
}
|
||||
|
||||
const linkContent = match.type === 'tg-link' && match.text ? match.text : '[ссылка]';
|
||||
|
||||
result.push(
|
||||
<TooltipProvider key={`link-${match.start}`}>
|
||||
<Tooltip open={hoveredLink === `${match.start}-${match.end}`} onOpenChange={(open) => setHoveredLink(open ? `${match.start}-${match.end}` : null)}>
|
||||
<TooltipTrigger asChild>
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => e.preventDefault()}
|
||||
className="text-primary font-medium underline hover:opacity-80 transition-opacity"
|
||||
onMouseEnter={() => setHoveredLink(`${match.start}-${match.end}`)}
|
||||
onMouseLeave={() => setHoveredLink(null)}
|
||||
>
|
||||
{linkContent}
|
||||
</a>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Сюда будет подставлена ссылка на канал:</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
<span className="font-mono text-xs">{inviteLinkPreview}</span>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
lastIndex = match.end;
|
||||
});
|
||||
|
||||
if (lastIndex < text.length) {
|
||||
result.push(<span key={`text-end-${lastIndex}`}>{text.slice(lastIndex)}</span>);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const renderButton = (button: { text: string; url: string }, index: number) => {
|
||||
const hasInviteLink = button.url === '{{invite_link}}';
|
||||
|
||||
return (
|
||||
<TooltipProvider key={index}>
|
||||
<Tooltip open={hoveredLink === `button-${index}`} onOpenChange={(open) => setHoveredLink(open ? `button-${index}` : null)}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
className={`w-full py-2 text-sm font-medium transition-colors ${
|
||||
buttons && buttons.length === 1 ? 'text-primary hover:bg-primary/10 rounded-full' : 'text-primary hover:bg-primary/10 rounded-md'
|
||||
}`}
|
||||
>
|
||||
{button.text}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
{hasInviteLink && (
|
||||
<TooltipContent>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Сюда будет подставлена ссылка на канал:</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
<span className="font-mono text-xs">{inviteLinkPreview}</span>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const getMediaGrid = () => {
|
||||
if (!mediaItems || mediaItems.length === 0) return null;
|
||||
const count = mediaItems.length;
|
||||
|
||||
if (count === 1) {
|
||||
return (
|
||||
<div className="rounded-lg overflow-hidden bg-muted h-64 flex items-center justify-center">
|
||||
<MediaPreview media={mediaItems[0]} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (count === 2) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-0.5 rounded-lg overflow-hidden">
|
||||
{mediaItems.map((media, index) => (
|
||||
<div key={index} className="aspect-square bg-muted flex items-center justify-center">
|
||||
<MediaPreview media={media} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (count === 3) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 grid-rows-2 gap-0.5 rounded-lg overflow-hidden">
|
||||
<div className="row-span-2 bg-muted flex items-center justify-center">
|
||||
<MediaPreview media={mediaItems[0]} />
|
||||
</div>
|
||||
<div className="bg-muted flex items-center justify-center">
|
||||
<MediaPreview media={mediaItems[1]} />
|
||||
</div>
|
||||
<div className="bg-muted flex items-center justify-center">
|
||||
<MediaPreview media={mediaItems[2]} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (count >= 4) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 grid-rows-2 gap-0.5 rounded-lg overflow-hidden">
|
||||
{mediaItems.slice(0, 4).map((media, index) => (
|
||||
<div key={index} className="aspect-square bg-muted flex items-center justify-center">
|
||||
<MediaPreview media={media} />
|
||||
</div>
|
||||
))}
|
||||
{mediaItems.length > 4 && (
|
||||
<div className="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
|
||||
+{mediaItems.length - 4}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-[384px] mx-auto bg-background rounded-xl overflow-hidden border shadow-sm">
|
||||
<div className="p-3 space-y-2">
|
||||
{mediaItems && mediaItems.length > 0 && (
|
||||
<div className="relative">
|
||||
{getMediaGrid()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="whitespace-pre-wrap text-sm leading-relaxed px-1">
|
||||
{renderTextWithLinks()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{buttons && buttons.length > 0 && (
|
||||
<div className="border-t px-3 pb-3 pt-2">
|
||||
{buttons.map((button, index) => renderButton(button, index))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MediaPreview({ media }: { media: { media_type: string; media_file_id: string } }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
{media.media_type === "photo" && (
|
||||
<span className="text-4xl">📷</span>
|
||||
)}
|
||||
{media.media_type === "video" && (
|
||||
<span className="text-4xl">🎬</span>
|
||||
)}
|
||||
{media.media_type === "animation" && (
|
||||
<span className="text-4xl">🎞️</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
{media.media_file_id.slice(0, 12)}...
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -140,6 +140,14 @@ export const demoCreatives: Creative[] = [
|
||||
id: "crea-0001-0000-0000-000000000001",
|
||||
name: "Крипто - Основной",
|
||||
text: "🚀 Присоединяйтесь к лучшему крипто-каналу!\n\n💰 Ежедневные сигналы\n📊 Аналитика рынка\n🎯 Точные прогнозы\n\n{invite_link}",
|
||||
media_items: [
|
||||
{
|
||||
media_type: "photo",
|
||||
media_file_id: "photo123",
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
buttons: [],
|
||||
status: "active",
|
||||
placements_count: 12,
|
||||
project_id: "proj-0001-0000-0000-000000000001",
|
||||
@@ -149,7 +157,20 @@ export const demoCreatives: Creative[] = [
|
||||
{
|
||||
id: "crea-0002-0000-0000-000000000002",
|
||||
name: "Крипто - Агрессивный",
|
||||
text: "⚡️ СРОЧНО! Секретный канал для избранных!\n\n🔥 Закрытая информация\n💎 Альткоины x100\n🚀 Успей до памп!\n\n{invite_link}",
|
||||
text: "⚡️ СРОЧНО! Секретный канал для избранных!\n\n🔥 Закрытая информация\n💎 Альткоины x100\n🚀 Успей до памп!\n\n<a class=\"tg-link\">Подпишись сейчас</a>",
|
||||
media_items: [
|
||||
{
|
||||
media_type: "video",
|
||||
media_file_id: "video123",
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
buttons: [
|
||||
{
|
||||
text: "Перейти в канал",
|
||||
url: "{{invite_link}}",
|
||||
},
|
||||
],
|
||||
status: "active",
|
||||
placements_count: 5,
|
||||
project_id: "proj-0001-0000-0000-000000000001",
|
||||
@@ -160,6 +181,8 @@ export const demoCreatives: Creative[] = [
|
||||
id: "crea-0003-0000-0000-000000000003",
|
||||
name: "IT Jobs - Основной",
|
||||
text: "👨💻 Ищешь работу в IT?\n\n✅ Вакансии от топ-компаний\n✅ Удаленка и офис\n✅ Junior - Senior\n\nПодписывайся: {invite_link}",
|
||||
media_items: [],
|
||||
buttons: [],
|
||||
status: "active",
|
||||
placements_count: 8,
|
||||
project_id: "proj-0002-0000-0000-000000000002",
|
||||
@@ -170,6 +193,19 @@ export const demoCreatives: Creative[] = [
|
||||
id: "crea-0004-0000-0000-000000000004",
|
||||
name: "Startups - Нетворкинг",
|
||||
text: "🤝 Нетворкинг для стартаперов\n\n🎯 Найди кофаундера\n💡 Обменяйся идеями\n🚀 Развивай проект\n\n{invite_link}",
|
||||
media_items: [
|
||||
{
|
||||
media_type: "photo",
|
||||
media_file_id: "photo456",
|
||||
position: 0,
|
||||
},
|
||||
{
|
||||
media_type: "photo",
|
||||
media_file_id: "photo789",
|
||||
position: 1,
|
||||
},
|
||||
],
|
||||
buttons: [],
|
||||
status: "active",
|
||||
placements_count: 6,
|
||||
project_id: "proj-0003-0000-0000-000000000003",
|
||||
@@ -180,6 +216,8 @@ export const demoCreatives: Creative[] = [
|
||||
id: "crea-0005-0000-0000-000000000005",
|
||||
name: "IT Jobs - Тестовый",
|
||||
text: "🔥 Тестовый креатив для IT вакансий\n\n{invite_link}",
|
||||
media_items: [],
|
||||
buttons: [],
|
||||
status: "archived",
|
||||
placements_count: 2,
|
||||
project_id: "proj-0002-0000-0000-000000000002",
|
||||
|
||||
@@ -187,10 +187,23 @@ export interface PurchasePlanChannelUpdateRequest {
|
||||
|
||||
export type CreativeStatus = "active" | "archived";
|
||||
|
||||
export interface CreativeMediaItem {
|
||||
media_type: string;
|
||||
media_file_id: string;
|
||||
position: number;
|
||||
}
|
||||
|
||||
export interface CreativeButton {
|
||||
text: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface Creative {
|
||||
id: string; // UUID
|
||||
name: string;
|
||||
text: string; // Contains {invite_link} placeholder
|
||||
media_items: CreativeMediaItem[];
|
||||
buttons: CreativeButton[];
|
||||
project_id: string;
|
||||
project_channel_title: string;
|
||||
created_at: string;
|
||||
@@ -206,6 +219,9 @@ export interface CreativeCreateRequest {
|
||||
export interface CreativeUpdateRequest {
|
||||
name?: string;
|
||||
text?: string;
|
||||
status?: CreativeStatus;
|
||||
media_items?: CreativeMediaItem[];
|
||||
buttons?: CreativeButton[];
|
||||
}
|
||||
|
||||
export interface CreativesQueryParams extends PaginationParams {
|
||||
|
||||
Reference in New Issue
Block a user