feat: журнальная главная, страница Зеро, TG-баннер, stats, auto-publish UI
- Журнальная главная: hero, CategoryRow, PopularBlock, RecentBlock (Сегодня/Вчера/Неделя) - ArticleCard: 3 размера (hero/regular/compact), цветной badge без дублей тегов - ArticleCoverSVG: 6 брендовых палитр, аватар Зеро в углу вместо #ZEROPOST - /about/zero: страница персонажа с галереей 8 поз - Footer: TG-баннер с аватаром Зеро на каждой странице - Конец статьи: блок «Понравилась? → Подписаться на канал» - ChannelEditor: 4 вкладки (Настройки/Расписание/Авто-публикация/Ручная) - AutoPublishTab: toggle, категории, delay, template, live preview - ArticlePicker: typeahead с was_sent_to_channel / next_scheduled_at флагами - /admin/channels/[id]/stats: график роста подписчиков (recharts) - Dashboard: блок TG-статистики (подписчики, delta 24h/7d, постов) - Header: упрощён до 2 пунктов desktop + расширенное мобильное меню - AutogenPanel: корректные time-picker'ы, calcNextRun с учётом last_run_at
This commit is contained in:
@@ -3,15 +3,66 @@ import { formatDate } from '@/lib/markdown';
|
||||
import { Clock } from 'lucide-react';
|
||||
import ArticleCoverSVG from './ArticleCoverSVG';
|
||||
|
||||
const CATEGORY_META = {
|
||||
'ai-tools': { label: 'AI Tools', cls: 'bg-emerald-50 dark:bg-emerald-950/60 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-900' },
|
||||
'cybersec': { label: 'Cybersec', cls: 'bg-red-50 dark:bg-red-950/60 text-red-700 dark:text-red-300 border-red-200 dark:border-red-900' },
|
||||
'automation': { label: 'Automation', cls: 'bg-amber-50 dark:bg-amber-950/60 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-900' },
|
||||
'ai-dev': { label: 'AI Dev', cls: 'bg-blue-50 dark:bg-blue-950/60 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-900' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Отдать список «человеческих» тегов без дублей и без category-slug.
|
||||
*/
|
||||
function cleanTags(tags, category) {
|
||||
if (!Array.isArray(tags)) return [];
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
const catLower = (category || '').toLowerCase();
|
||||
for (const raw of tags) {
|
||||
if (typeof raw !== 'string') continue;
|
||||
const t = raw.trim();
|
||||
if (!t) continue;
|
||||
const lower = t.toLowerCase();
|
||||
if (lower === catLower) continue;
|
||||
if (seen.has(lower)) continue;
|
||||
seen.add(lower);
|
||||
out.push(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function CategoryBadge({ category }) {
|
||||
if (!category) return null;
|
||||
const meta = CATEGORY_META[category] || { label: category, cls: 'bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 border-neutral-200 dark:border-neutral-700' };
|
||||
// Просто бейдж без вложенной ссылки — карточка целиком кликабельна.
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center text-[11px] font-medium px-2 py-0.5 rounded-full border ${meta.cls}`}
|
||||
>
|
||||
{meta.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function imageUrl(article) {
|
||||
if (!article.cover_url) return null;
|
||||
return article.cover_url;
|
||||
}
|
||||
|
||||
export default function ArticleCard({ article, featured = false }) {
|
||||
/**
|
||||
* ArticleCard — карточка статьи в трёх размерах.
|
||||
* - size="hero": большая, 5/3 grid (для главной)
|
||||
* - size="regular": обычная карточка (для сеток 3-в-ряд)
|
||||
* - size="compact": плотная (для вертикальных лент / sidebar)
|
||||
*
|
||||
* featured prop оставлен для обратной совместимости (= size="hero").
|
||||
*/
|
||||
export default function ArticleCard({ article, featured = false, size = 'regular' }) {
|
||||
const effectiveSize = featured ? 'hero' : size;
|
||||
const img = imageUrl(article);
|
||||
const tags = cleanTags(article.tags, article.category);
|
||||
|
||||
if (featured) {
|
||||
if (effectiveSize === 'hero') {
|
||||
return (
|
||||
<Link href={`/blog/${article.slug}`} className="article-card block group overflow-hidden p-0">
|
||||
<div className="flex flex-col sm:grid sm:grid-cols-5 sm:gap-0">
|
||||
@@ -29,7 +80,8 @@ export default function ArticleCard({ article, featured = false }) {
|
||||
</div>
|
||||
<div className="p-5 sm:p-8 sm:col-span-3 flex flex-col justify-center">
|
||||
<div className="flex flex-wrap items-center gap-2 mb-3">
|
||||
{(article.tags || []).slice(0, 3).map(t => (
|
||||
<CategoryBadge category={article.category} />
|
||||
{tags.slice(0, 3).map(t => (
|
||||
<span key={t} className="tag">#{t}</span>
|
||||
))}
|
||||
</div>
|
||||
@@ -55,6 +107,35 @@ export default function ArticleCard({ article, featured = false }) {
|
||||
);
|
||||
}
|
||||
|
||||
if (effectiveSize === 'compact') {
|
||||
return (
|
||||
<Link href={`/blog/${article.slug}`} className="article-card group flex gap-3 items-start p-3">
|
||||
<div className="shrink-0 w-20 h-20 rounded-lg overflow-hidden bg-neutral-100 dark:bg-neutral-800">
|
||||
{img ? (
|
||||
<img src={img} alt={article.title} className="w-full h-full object-cover" loading="lazy" />
|
||||
) : (
|
||||
<ArticleCoverSVG article={article} aspect="1/1" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="mb-1.5"><CategoryBadge category={article.category} /></div>
|
||||
<h3 className="text-sm font-semibold mb-1 ink group-hover:accent transition-colors leading-snug line-clamp-2">
|
||||
{article.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 text-[11px] mute">
|
||||
<span>{formatDate(article.published_at)}</span>
|
||||
{article.reading_time && (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" /> {article.reading_time} мин
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
// regular
|
||||
return (
|
||||
<Link href={`/blog/${article.slug}`} className="article-card block group overflow-hidden p-0">
|
||||
<div className="p-3">
|
||||
@@ -66,7 +147,8 @@ export default function ArticleCard({ article, featured = false }) {
|
||||
</div>
|
||||
<div className="p-4 sm:p-5 pt-2">
|
||||
<div className="flex flex-wrap items-center gap-2 mb-2">
|
||||
{(article.tags || []).slice(0, 2).map(t => (
|
||||
<CategoryBadge category={article.category} />
|
||||
{tags.slice(0, 2).map(t => (
|
||||
<span key={t} className="tag">#{t}</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
/**
|
||||
* Процедурно-сгенерированная SVG-обложка в стиле сайта.
|
||||
* Не требует AI — рендерится сразу, выглядит достойно вместо плоского градиента.
|
||||
*
|
||||
* Идея: используем seed (id статьи) для воспроизводимой композиции.
|
||||
* Каждая статья получает свой уникальный, но узнаваемый узор.
|
||||
* Процедурно-сгенерированная SVG-обложка в стиле ZeroPost.
|
||||
* Используется когда настоящая обложка ещё не сгенерирована.
|
||||
* Каждая статья получает уникальный, воспроизводимый узор.
|
||||
*/
|
||||
|
||||
// псевдо-рандом по seed (mulberry32)
|
||||
function rng(seed) {
|
||||
let t = seed + 0x6D2B79F5;
|
||||
return () => {
|
||||
@@ -16,38 +13,37 @@ function rng(seed) {
|
||||
};
|
||||
}
|
||||
|
||||
// Палитры — приглушённые, чтобы не спорить с UI
|
||||
// Только наши бренд-палитры — никакого произвольного фиолетового
|
||||
const PALETTES = [
|
||||
{ bg: '#ecfdf5', accent: '#10b981', soft: '#a7f3d0', dark: '#065f46' }, // emerald
|
||||
{ bg: '#ecfdf5', accent: '#10b981', soft: '#a7f3d0', dark: '#065f46' }, // emerald (основной)
|
||||
{ bg: '#f0fdfa', accent: '#14b8a6', soft: '#99f6e4', dark: '#115e59' }, // teal
|
||||
{ bg: '#fefce8', accent: '#eab308', soft: '#fef08a', dark: '#854d0e' }, // yellow
|
||||
{ bg: '#f8fafc', accent: '#10b981', soft: '#d1fae5', dark: '#1e293b' }, // emerald+neutral
|
||||
{ bg: '#fefce8', accent: '#d97706', soft: '#fde68a', dark: '#92400e' }, // amber
|
||||
{ bg: '#eff6ff', accent: '#3b82f6', soft: '#bfdbfe', dark: '#1e40af' }, // blue
|
||||
{ bg: '#fdf4ff', accent: '#a855f7', soft: '#e9d5ff', dark: '#6b21a8' }, // purple
|
||||
{ bg: '#fff7ed', accent: '#f97316', soft: '#fed7aa', dark: '#9a3412' }, // orange
|
||||
];
|
||||
|
||||
export default function ArticleCoverSVG({ article, className = '', aspect = '16/9', priority = false }) {
|
||||
export default function ArticleCoverSVG({ article, className = '', aspect = '16/9' }) {
|
||||
const seed = (article?.id || 1) * 9301 + 49297;
|
||||
const rand = rng(seed);
|
||||
const palette = PALETTES[Math.floor(rand() * PALETTES.length)];
|
||||
|
||||
// Композиция: 3-5 «слоёв» геометрии
|
||||
// Выбор палитры по id — не случайный, а детерминированный
|
||||
const palette = PALETTES[(article?.id || 0) % PALETTES.length];
|
||||
|
||||
const layers = 3 + Math.floor(rand() * 3);
|
||||
const shapes = [];
|
||||
|
||||
for (let i = 0; i < layers; i++) {
|
||||
const kind = ['curve', 'circle', 'arc', 'rect'][Math.floor(rand() * 4)];
|
||||
const opacity = 0.35 + rand() * 0.5;
|
||||
const kind = ['circle', 'circle', 'arc', 'rect'][Math.floor(rand() * 4)]; // circle чаще
|
||||
const opacity = 0.25 + rand() * 0.45;
|
||||
const colors = [palette.accent, palette.soft, palette.dark];
|
||||
const fill = colors[Math.floor(rand() * colors.length)];
|
||||
shapes.push({ kind, opacity, fill, r: rand });
|
||||
}
|
||||
|
||||
// тег (первый) — мелкая метка в углу
|
||||
const tag = (article?.tags?.[0] || 'zeropost').toString().slice(0, 18);
|
||||
|
||||
return (
|
||||
<div className={`relative overflow-hidden rounded-xl ${className}`} style={{ aspectRatio: aspect, background: palette.bg }}>
|
||||
<div
|
||||
className={`relative overflow-hidden rounded-xl ${className}`}
|
||||
style={{ aspectRatio: aspect, background: palette.bg }}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 400 225"
|
||||
preserveAspectRatio="xMidYMid slice"
|
||||
@@ -55,7 +51,6 @@ export default function ArticleCoverSVG({ article, className = '', aspect = '16/
|
||||
aria-hidden="true"
|
||||
>
|
||||
{shapes.map((s, idx) => {
|
||||
// координаты, тоже псевдо-случайно
|
||||
const cx = 60 + s.r() * 320;
|
||||
const cy = 30 + s.r() * 165;
|
||||
const size = 60 + s.r() * 180;
|
||||
@@ -68,67 +63,55 @@ export default function ArticleCoverSVG({ article, className = '', aspect = '16/
|
||||
return (
|
||||
<rect
|
||||
key={idx}
|
||||
x={cx - size / 2}
|
||||
y={cy - size / 2}
|
||||
width={size}
|
||||
height={size * (0.5 + s.r() * 1)}
|
||||
fill={s.fill}
|
||||
opacity={s.opacity}
|
||||
x={cx - size / 2} y={cy - size / 2}
|
||||
width={size} height={size * (0.5 + s.r() * 1)}
|
||||
fill={s.fill} opacity={s.opacity}
|
||||
rx={s.r() > 0.5 ? size / 8 : 0}
|
||||
transform={`rotate(${rot} ${cx} ${cy})`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (s.kind === 'arc') {
|
||||
// Полукруг
|
||||
const r = size / 2;
|
||||
return (
|
||||
<path
|
||||
key={idx}
|
||||
d={`M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${cx + r} ${cy} Z`}
|
||||
fill={s.fill}
|
||||
opacity={s.opacity}
|
||||
fill={s.fill} opacity={s.opacity}
|
||||
transform={`rotate(${rot} ${cx} ${cy})`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
// curve — плавная волна
|
||||
const w = size;
|
||||
const h = size * 0.4;
|
||||
const w = size, h = size * 0.4;
|
||||
return (
|
||||
<path
|
||||
key={idx}
|
||||
d={`M ${cx - w / 2} ${cy} Q ${cx} ${cy - h}, ${cx + w / 2} ${cy} T ${cx + w * 1.5} ${cy}`}
|
||||
stroke={s.fill}
|
||||
strokeWidth={6 + s.r() * 16}
|
||||
strokeLinecap="round"
|
||||
fill="none"
|
||||
opacity={s.opacity}
|
||||
d={`M ${cx - w/2} ${cy} Q ${cx} ${cy - h}, ${cx + w/2} ${cy} T ${cx + w*1.5} ${cy}`}
|
||||
stroke={s.fill} strokeWidth={6 + s.r() * 16}
|
||||
strokeLinecap="round" fill="none" opacity={s.opacity}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Мелкие точки-частицы — добавляют детализации */}
|
||||
{Array.from({ length: 14 }).map((_, i) => (
|
||||
{/* Точки-частицы */}
|
||||
{Array.from({ length: 12 }).map((_, i) => (
|
||||
<circle
|
||||
key={`d-${i}`}
|
||||
cx={rand() * 400}
|
||||
cy={rand() * 225}
|
||||
r={1 + rand() * 2}
|
||||
fill={palette.dark}
|
||||
opacity={0.18 + rand() * 0.18}
|
||||
cx={rand() * 400} cy={rand() * 225}
|
||||
r={1 + rand() * 2.5}
|
||||
fill={palette.dark} opacity={0.12 + rand() * 0.15}
|
||||
/>
|
||||
))}
|
||||
</svg>
|
||||
|
||||
{/* тэг в углу */}
|
||||
<div className="absolute inset-0 flex items-end p-3 sm:p-4 pointer-events-none">
|
||||
<div
|
||||
className="text-[10px] sm:text-xs font-mono tracking-wider uppercase px-2 py-0.5 rounded-md"
|
||||
style={{ background: 'rgba(255,255,255,0.65)', color: palette.dark, backdropFilter: 'blur(4px)' }}
|
||||
>
|
||||
#{tag}
|
||||
</div>
|
||||
{/* Аватар Зеро в правом нижнем углу вместо текстового тега */}
|
||||
<div className="absolute bottom-3 right-3 pointer-events-none">
|
||||
<img
|
||||
src="/uploads/zero-avatar.webp"
|
||||
alt=""
|
||||
className="w-8 h-8 rounded-lg opacity-70"
|
||||
style={{ boxShadow: '0 1px 4px rgba(0,0,0,0.15)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import Link from 'next/link';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import ArticleCard from './ArticleCard';
|
||||
|
||||
const CATEGORY_INFO = {
|
||||
'ai-tools': { label: 'AI Tools', icon: '🤖', accent: 'text-emerald-600 dark:text-emerald-400', border: 'border-emerald-200 dark:border-emerald-900' },
|
||||
'cybersec': { label: 'Cybersec', icon: '🔒', accent: 'text-red-600 dark:text-red-400', border: 'border-red-200 dark:border-red-900' },
|
||||
'automation': { label: 'Automation', icon: '⚡', accent: 'text-amber-600 dark:text-amber-400', border: 'border-amber-200 dark:border-amber-900' },
|
||||
'ai-dev': { label: 'AI Dev', icon: '💻', accent: 'text-blue-600 dark:text-blue-400', border: 'border-blue-200 dark:border-blue-900' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Категорийный ряд: заголовок + 3 карточки + «все →».
|
||||
* Показываем только если в категории есть хотя бы 1 статья.
|
||||
*/
|
||||
export default function CategoryRow({ category, articles }) {
|
||||
if (!articles || articles.length === 0) return null;
|
||||
const info = CATEGORY_INFO[category] || { label: category, icon: '📝', accent: 'text-neutral-700', border: 'border-neutral-200' };
|
||||
|
||||
return (
|
||||
<section className={`container-wide pb-10`}>
|
||||
<div className={`flex items-end justify-between mb-5 pb-3 border-b ${info.border}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-2xl">{info.icon}</span>
|
||||
<h2 className={`text-xl sm:text-2xl font-bold ${info.accent}`}>{info.label}</h2>
|
||||
</div>
|
||||
<Link href={`/category/${category}`} className={`text-sm font-medium inline-flex items-center gap-1 ${info.accent} hover:opacity-80 transition-opacity`}>
|
||||
Все материалы <ArrowRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{articles.map(a => <ArticleCard key={a.id} article={a} />)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+31
-2
@@ -1,13 +1,42 @@
|
||||
import Link from 'next/link';
|
||||
import { Send } from 'lucide-react';
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<footer className="border-t-soft mt-20">
|
||||
<div className="container-wide py-10 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm mute">
|
||||
<div>
|
||||
{/* TG-банер */}
|
||||
<div className="border-b-soft">
|
||||
<div className="container-wide py-6 flex flex-col sm:flex-row items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl overflow-hidden shrink-0">
|
||||
<img src="/uploads/zero-avatar.webp" alt="Зеро" className="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm font-semibold ink">ZeroPost в Telegram</div>
|
||||
<div className="text-xs mute">Каждый день — анонс новой заметки от Зеро</div>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href="https://t.me/zeropostru"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white transition-colors shrink-0"
|
||||
style={{ background: 'rgb(var(--accent))' }}
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
Подписаться
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Обычный footer */}
|
||||
<div className="container-wide py-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm mute">
|
||||
<div className="flex items-center gap-2">
|
||||
<img src="/uploads/zero-avatar.webp" alt="" className="w-5 h-5 rounded opacity-60" />
|
||||
© {new Date().getFullYear()} ZeroPost — генерируется ИИ, читается людьми
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/about/zero" className="hover:ink transition-colors">Кто такой Зеро?</Link>
|
||||
<Link href="/archive" className="hover:ink transition-colors">Архив</Link>
|
||||
<Link href="/notes" className="hover:ink transition-colors">Заметки</Link>
|
||||
<Link href="/about" className="hover:ink transition-colors">О проекте</Link>
|
||||
|
||||
+30
-30
@@ -5,6 +5,12 @@ import { Sparkles, Menu, X } from 'lucide-react';
|
||||
import ThemeToggle from './ThemeToggle';
|
||||
import SearchBox from './SearchBox';
|
||||
|
||||
// Минимум: главная + о проекте. Серии и заметки доступны через карточки на главной и футер.
|
||||
const NAV_LINKS = [
|
||||
{ href: '/', label: 'Главная' },
|
||||
{ href: '/about', label: 'О проекте' },
|
||||
];
|
||||
|
||||
export default function Header() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [hidden, setHidden] = useState(false);
|
||||
@@ -55,20 +61,18 @@ export default function Header() {
|
||||
|
||||
{/* Desktop nav */}
|
||||
<nav className="hidden sm:flex items-center gap-1 text-sm">
|
||||
<Link href="/" className="btn btn-ghost text-sm py-1.5">Статьи</Link>
|
||||
<Link href="/category/cybersec" className="btn btn-ghost text-sm py-1.5">🔒 Безопасность</Link>
|
||||
<Link href="/category/automation" className="btn btn-ghost text-sm py-1.5">⚡ Автоматизация</Link>
|
||||
<Link href="/category/ai-dev" className="btn btn-ghost text-sm py-1.5">💻 Dev + AI</Link>
|
||||
<Link href="/archive" className="btn btn-ghost text-sm py-1.5">Архив</Link>
|
||||
<Link href="/notes" className="btn btn-ghost text-sm py-1.5">Заметки</Link>
|
||||
<Link href="/about" className="btn btn-ghost text-sm py-1.5">О проекте</Link>
|
||||
<div className="ml-1 flex items-center gap-1">
|
||||
{NAV_LINKS.map(link => (
|
||||
<Link key={link.href} href={link.href} className="btn btn-ghost text-sm py-1.5">
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
<div className="ml-2 flex items-center gap-1 pl-2 border-l border-soft">
|
||||
<SearchBox />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Mobile */}
|
||||
{/* Mobile controls */}
|
||||
<div className="sm:hidden flex items-center gap-1">
|
||||
<SearchBox />
|
||||
<ThemeToggle />
|
||||
@@ -90,27 +94,23 @@ export default function Header() {
|
||||
style={{ background: 'rgb(var(--bg) / 0.98)', paddingTop: 'calc(64px + env(safe-area-inset-top))' }}
|
||||
>
|
||||
<nav className="container-wide pt-6 pb-8 flex flex-col gap-1">
|
||||
<Link
|
||||
href="/"
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-2xl font-semibold ink py-3 border-b-soft"
|
||||
>Статьи</Link>
|
||||
<Link
|
||||
href="/archive"
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-2xl font-semibold ink py-3 border-b-soft"
|
||||
>Архив</Link>
|
||||
<Link
|
||||
href="/notes"
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-2xl font-semibold ink py-3 border-b-soft"
|
||||
>Заметки</Link>
|
||||
<Link
|
||||
href="/about"
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-2xl font-semibold ink py-3 border-b-soft"
|
||||
>О проекте</Link>
|
||||
<div className="mt-6 mute text-sm">
|
||||
<Link href="/" onClick={() => setOpen(false)} className="text-2xl font-semibold ink py-3 border-b-soft">
|
||||
Главная
|
||||
</Link>
|
||||
<div className="py-3 border-b-soft">
|
||||
<div className="text-xs uppercase tracking-widest mute mb-2">Темы</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Link onClick={() => setOpen(false)} href="/category/ai-tools" className="text-base font-medium py-2">🤖 AI Tools</Link>
|
||||
<Link onClick={() => setOpen(false)} href="/category/ai-dev" className="text-base font-medium py-2">💻 AI Dev</Link>
|
||||
<Link onClick={() => setOpen(false)} href="/category/automation" className="text-base font-medium py-2">⚡ Automation</Link>
|
||||
<Link onClick={() => setOpen(false)} href="/category/cybersec" className="text-base font-medium py-2">🔒 Cybersec</Link>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/series" onClick={() => setOpen(false)} className="text-base font-medium ink py-3 border-b-soft">Серии</Link>
|
||||
<Link href="/notes" onClick={() => setOpen(false)} className="text-base font-medium ink py-3 border-b-soft">Заметки</Link>
|
||||
<Link href="/archive" onClick={() => setOpen(false)} className="text-base font-medium ink py-3 border-b-soft">Архив</Link>
|
||||
<Link href="/about" onClick={() => setOpen(false)} className="text-base font-medium ink py-3 border-b-soft">О проекте</Link>
|
||||
<div className="mt-8 mute text-sm leading-relaxed">
|
||||
Блог, который ведёт ИИ — а человек только следит за курсом.
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import ArticleCard from './ArticleCard';
|
||||
import { Flame } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Блок «Популярное за неделю/месяц».
|
||||
* Не рендерится если пусто.
|
||||
*/
|
||||
export default function PopularBlock({ articles }) {
|
||||
if (!articles || articles.length === 0) return null;
|
||||
return (
|
||||
<section className="container-wide pb-10">
|
||||
<div className="flex items-center gap-2 mb-5 pb-3 border-b border-orange-200 dark:border-orange-900">
|
||||
<Flame className="w-5 h-5 text-orange-500" />
|
||||
<h2 className="text-xl sm:text-2xl font-bold text-orange-600 dark:text-orange-400">
|
||||
Популярное за месяц
|
||||
</h2>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{articles.map(a => <ArticleCard key={a.id} article={a} />)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import Link from 'next/link';
|
||||
import ArticleCard from './ArticleCard';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Группировка свежих материалов по дням: «Сегодня», «Вчера», «Эта неделя», «Ранее».
|
||||
* Не рендерится, если пусто.
|
||||
*/
|
||||
function groupByPeriod(articles) {
|
||||
const now = new Date();
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||||
const startOfYesterday = startOfToday - 24 * 3600 * 1000;
|
||||
const startOfWeek = startOfToday - 7 * 24 * 3600 * 1000;
|
||||
|
||||
const groups = { today: [], yesterday: [], week: [], earlier: [] };
|
||||
for (const a of articles) {
|
||||
const t = new Date(a.published_at).getTime();
|
||||
if (t >= startOfToday) groups.today.push(a);
|
||||
else if (t >= startOfYesterday) groups.yesterday.push(a);
|
||||
else if (t >= startOfWeek) groups.week.push(a);
|
||||
else groups.earlier.push(a);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
const LABELS = {
|
||||
today: 'Сегодня',
|
||||
yesterday: 'Вчера',
|
||||
week: 'На этой неделе',
|
||||
earlier: 'Ранее',
|
||||
};
|
||||
|
||||
export default function RecentBlock({ articles }) {
|
||||
if (!articles || articles.length === 0) return null;
|
||||
const groups = groupByPeriod(articles);
|
||||
const nonEmpty = Object.entries(groups).filter(([, arr]) => arr.length > 0);
|
||||
if (nonEmpty.length === 0) return null;
|
||||
|
||||
return (
|
||||
<section className="container-wide pb-12">
|
||||
<div className="flex items-end justify-between mb-5">
|
||||
<h2 className="text-xl sm:text-2xl font-bold ink">Свежие материалы</h2>
|
||||
<Link href="/archive" className="text-sm font-medium inline-flex items-center gap-1 accent hover:opacity-80 transition-opacity">
|
||||
Архив <ArrowRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="space-y-8">
|
||||
{nonEmpty.map(([key, arr]) => (
|
||||
<div key={key}>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-widest mute mb-3">
|
||||
{LABELS[key]} <span className="opacity-50">· {arr.length}</span>
|
||||
</h3>
|
||||
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{arr.map(a => <ArticleCard key={a.id} article={a} />)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
'use client';
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { LayoutDashboard, FileText, Radio, Zap, LogOut, ExternalLink } from 'lucide-react';
|
||||
import { LayoutDashboard, FileText, Radio, Zap, Settings, LogOut, ExternalLink } from 'lucide-react';
|
||||
|
||||
const NAV = [
|
||||
{ href: '/admin', label: 'Дашборд', icon: LayoutDashboard, exact: true },
|
||||
{ href: '/admin/articles', label: 'Статьи', icon: FileText },
|
||||
{ href: '/admin/channels', label: 'Каналы', icon: Radio },
|
||||
{ href: '/admin/autogen', label: 'Автогенерация', icon: Zap },
|
||||
{ href: '/admin/settings', label: 'Настройки', icon: Settings },
|
||||
];
|
||||
|
||||
export default function AdminNav() {
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
'use client';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Search, Loader2, X, Check, AlertTriangle, Clock, Image as ImageIcon } from 'lucide-react';
|
||||
|
||||
const CATEGORY_LABELS = {
|
||||
'ai-tools': 'AI Tools',
|
||||
'cybersec': 'Cybersec',
|
||||
'automation': 'Automation',
|
||||
'ai-dev': 'AI Dev',
|
||||
};
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
}
|
||||
function fmtTime(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleString('ru-RU', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
/**
|
||||
* ArticlePicker — typeahead-выбор статьи для публикации в канал.
|
||||
* - Серверный поиск через /admin/api/articles/search
|
||||
* - Показывает обложку, категорию, дату публикации, состояние (отправлено уже/в очереди)
|
||||
* - Поддерживает channelId для сигнализации «уже было / в очереди»
|
||||
*/
|
||||
export default function ArticlePicker({ value, onChange, channelId, placeholder = 'Найти статью…' }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [items, setItems] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selected, setSelected] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const debounceRef = useRef(null);
|
||||
const rootRef = useRef(null);
|
||||
|
||||
// Загружаем выбранную статью по id (если уже выбрана и items не содержит её)
|
||||
useEffect(() => {
|
||||
if (!value) { setSelected(null); return; }
|
||||
if (selected?.id === Number(value)) return;
|
||||
// Дозагрузка
|
||||
fetch(`/admin/api/articles/search?q=&channel_id=${channelId || ''}&limit=200`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
const it = (d.items || []).find(a => a.id === Number(value));
|
||||
if (it) setSelected(it);
|
||||
})
|
||||
.catch(() => {});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value, channelId]);
|
||||
|
||||
// Debounced поиск
|
||||
const search = useCallback((q) => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set('q', q);
|
||||
if (channelId) params.set('channel_id', String(channelId));
|
||||
params.set('limit', '20');
|
||||
fetch(`/admin/api/articles/search?${params.toString()}`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
if (d.error) throw new Error(d.error);
|
||||
setItems(d.items || []);
|
||||
})
|
||||
.catch(e => { setError(e.message); setItems([]); })
|
||||
.finally(() => setLoading(false));
|
||||
}, [channelId]);
|
||||
|
||||
function onInput(v) {
|
||||
setQuery(v);
|
||||
setOpen(true);
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => search(v.trim()), 200);
|
||||
}
|
||||
|
||||
function openDropdown() {
|
||||
setOpen(true);
|
||||
if (items.length === 0 && !loading) search(query.trim());
|
||||
}
|
||||
|
||||
function pick(article) {
|
||||
setSelected(article);
|
||||
onChange?.(article);
|
||||
setOpen(false);
|
||||
setQuery('');
|
||||
}
|
||||
|
||||
function clear() {
|
||||
setSelected(null);
|
||||
onChange?.(null);
|
||||
setQuery('');
|
||||
}
|
||||
|
||||
// Закрытие по клику снаружи
|
||||
useEffect(() => {
|
||||
function onDocClick(e) {
|
||||
if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false);
|
||||
}
|
||||
document.addEventListener('mousedown', onDocClick);
|
||||
return () => document.removeEventListener('mousedown', onDocClick);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative" ref={rootRef}>
|
||||
{/* Selected chip */}
|
||||
{selected && (
|
||||
<div className="mb-2 flex items-start gap-3 p-3 rounded-lg border border-emerald-200 dark:border-emerald-900 bg-emerald-50 dark:bg-emerald-950">
|
||||
{selected.cover_url ? (
|
||||
<img
|
||||
src={selected.cover_url.startsWith('http') ? selected.cover_url : `https://zeropost.ru${selected.cover_url}`}
|
||||
alt=""
|
||||
className="w-14 h-14 rounded object-cover shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-14 h-14 rounded bg-neutral-200 dark:bg-neutral-800 flex items-center justify-center shrink-0">
|
||||
<ImageIcon className="w-5 h-5 text-neutral-400" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100 truncate">{selected.title}</div>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-neutral-500 flex-wrap">
|
||||
<span className="px-1.5 py-0.5 rounded bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-700">
|
||||
{CATEGORY_LABELS[selected.category] || selected.category}
|
||||
</span>
|
||||
<span>{fmtDate(selected.published_at)}</span>
|
||||
{selected.was_sent_to_channel && (
|
||||
<span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-400" title="Уже отправлено в этот канал">
|
||||
<AlertTriangle className="w-3 h-3" /> уже было {fmtTime(selected.was_sent_to_channel)}
|
||||
</span>
|
||||
)}
|
||||
{selected.next_scheduled_at && (
|
||||
<span className="inline-flex items-center gap-1 text-blue-600 dark:text-blue-400" title="Уже в очереди">
|
||||
<Clock className="w-3 h-3" /> в очереди на {fmtTime(selected.next_scheduled_at)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={clear} className="text-neutral-400 hover:text-red-500 p-1" title="Очистить">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search input */}
|
||||
<div className="relative">
|
||||
<Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={e => onInput(e.target.value)}
|
||||
onFocus={openDropdown}
|
||||
placeholder={selected ? 'Заменить статью…' : placeholder}
|
||||
className="w-full pl-9 pr-9 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
/>
|
||||
{loading && (
|
||||
<Loader2 className="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Dropdown */}
|
||||
{open && (
|
||||
<div className="absolute z-30 mt-1 w-full bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-lg shadow-xl max-h-96 overflow-y-auto">
|
||||
{error && (
|
||||
<div className="p-3 text-sm text-red-500">{error}</div>
|
||||
)}
|
||||
{!error && !loading && items.length === 0 && (
|
||||
<div className="p-4 text-sm text-neutral-500 text-center">
|
||||
{query ? `Ничего не найдено по «${query}»` : 'Нет статей'}
|
||||
</div>
|
||||
)}
|
||||
{items.map(a => (
|
||||
<button
|
||||
key={a.id}
|
||||
onClick={() => pick(a)}
|
||||
className="w-full flex items-start gap-3 p-3 text-left hover:bg-neutral-50 dark:hover:bg-neutral-800 border-b border-neutral-100 dark:border-neutral-800 last:border-b-0 transition-colors"
|
||||
>
|
||||
{a.cover_url ? (
|
||||
<img
|
||||
src={a.cover_url.startsWith('http') ? a.cover_url : `https://zeropost.ru${a.cover_url}`}
|
||||
alt=""
|
||||
className="w-12 h-12 rounded object-cover shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded bg-neutral-200 dark:bg-neutral-800 flex items-center justify-center shrink-0">
|
||||
<ImageIcon className="w-4 h-4 text-neutral-400" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100 truncate">{a.title}</div>
|
||||
<div className="flex items-center gap-2 mt-0.5 text-xs text-neutral-500 flex-wrap">
|
||||
<span className="px-1.5 py-0.5 rounded bg-neutral-100 dark:bg-neutral-800">
|
||||
{CATEGORY_LABELS[a.category] || a.category}
|
||||
</span>
|
||||
<span>{fmtDate(a.published_at)}</span>
|
||||
{a.was_sent_to_channel && (
|
||||
<span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-400">
|
||||
<AlertTriangle className="w-3 h-3" /> уже было
|
||||
</span>
|
||||
)}
|
||||
{a.next_scheduled_at && (
|
||||
<span className="inline-flex items-center gap-1 text-blue-600 dark:text-blue-400">
|
||||
<Clock className="w-3 h-3" /> в очереди
|
||||
</span>
|
||||
)}
|
||||
{selected?.id === a.id && (
|
||||
<Check className="w-3.5 h-3.5 text-emerald-500" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Save, Loader2, Eye, AlertCircle, Sparkles, Clock, RefreshCw } from 'lucide-react';
|
||||
|
||||
const CATEGORIES = [
|
||||
{ slug: 'ai-tools', label: 'AI Tools' },
|
||||
{ slug: 'cybersec', label: 'Cybersec' },
|
||||
{ slug: 'automation', label: 'Automation' },
|
||||
{ slug: 'ai-dev', label: 'AI Dev' },
|
||||
];
|
||||
|
||||
const PLACEHOLDERS = [
|
||||
{ key: '{title}', desc: 'Заголовок статьи' },
|
||||
{ key: '{excerpt}', desc: 'Краткое описание (excerpt)' },
|
||||
{ key: '{url}', desc: 'https://zeropost.ru/blog/{slug}' },
|
||||
{ key: '{category}', desc: 'Категория (ai-tools, cybersec, …)' },
|
||||
];
|
||||
|
||||
const DEFAULT_TEMPLATE = '*{title}*\n\n{excerpt}\n\n{url}';
|
||||
|
||||
export default function AutoPublishTab({ channel, onSaved }) {
|
||||
const [enabled, setEnabled] = useState(channel?.auto_publish_enabled ?? false);
|
||||
const [categories, setCategories] = useState(channel?.auto_publish_categories || []);
|
||||
const [delayMin, setDelayMin] = useState(channel?.auto_publish_delay_min ?? 0);
|
||||
const [template, setTemplate] = useState(channel?.auto_publish_template || '');
|
||||
const [withCover, setWithCover] = useState(channel?.auto_publish_with_cover ?? true);
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [savedToast, setSavedToast] = useState(false);
|
||||
const [err, setErr] = useState('');
|
||||
|
||||
// Превью
|
||||
const [previewArticleId, setPreviewArticleId] = useState(null);
|
||||
const [previewArticleTitle, setPreviewArticleTitle] = useState('');
|
||||
const [preview, setPreview] = useState(null);
|
||||
const [loadingPreview, setLoadingPreview] = useState(false);
|
||||
|
||||
// Подгружаем первую статью для авто-превью
|
||||
useEffect(() => {
|
||||
const cat = categories[0] || '';
|
||||
const url = `/admin/api/articles/search?status=published&limit=1${cat ? `&category=${cat}` : ''}`;
|
||||
fetch(url).then(r => r.json()).then(d => {
|
||||
const it = d.items?.[0];
|
||||
if (it) {
|
||||
setPreviewArticleId(it.id);
|
||||
setPreviewArticleTitle(it.title);
|
||||
}
|
||||
}).catch(() => {});
|
||||
}, [categories.join(',')]); // переоценим если категория меняется
|
||||
|
||||
// Авто-превью при изменении template или статьи
|
||||
useEffect(() => {
|
||||
if (!previewArticleId) return;
|
||||
setLoadingPreview(true);
|
||||
fetch('/admin/api/scheduled/preview', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ article_id: previewArticleId, template: template || DEFAULT_TEMPLATE }),
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(d => setPreview(d))
|
||||
.catch(e => setPreview({ error: e.message }))
|
||||
.finally(() => setLoadingPreview(false));
|
||||
}, [previewArticleId, template]);
|
||||
|
||||
function toggleCategory(slug) {
|
||||
setCategories(cs => cs.includes(slug) ? cs.filter(c => c !== slug) : [...cs, slug]);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
setErr('');
|
||||
try {
|
||||
const res = await fetch(`/admin/api/channels/${channel.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
auto_publish_enabled: enabled,
|
||||
auto_publish_categories: categories,
|
||||
auto_publish_delay_min: parseInt(delayMin) || 0,
|
||||
auto_publish_template: template || null,
|
||||
auto_publish_with_cover: withCover,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
setSavedToast(true);
|
||||
setTimeout(() => setSavedToast(false), 2000);
|
||||
onSaved?.();
|
||||
} catch (e) {
|
||||
setErr(e.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function insertPlaceholder(p) {
|
||||
const el = document.getElementById('auto-publish-template');
|
||||
if (!el) return;
|
||||
const start = el.selectionStart || template.length;
|
||||
const end = el.selectionEnd || template.length;
|
||||
setTemplate(t => t.slice(0, start) + p + t.slice(end));
|
||||
setTimeout(() => {
|
||||
el.focus();
|
||||
el.selectionStart = el.selectionEnd = start + p.length;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
const effectiveTemplate = template || DEFAULT_TEMPLATE;
|
||||
const captionWarning = preview?.length > 1024 && withCover;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Toggle */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<div className="flex items-start justify-between gap-3 mb-3">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4 text-emerald-500" />
|
||||
Автоматическая публикация статей
|
||||
</h2>
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
Как только статья получает статус <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">published</code>,
|
||||
она автоматически попадает в очередь публикации в этот канал.
|
||||
</p>
|
||||
</div>
|
||||
<label className="inline-flex items-center gap-2 cursor-pointer shrink-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enabled}
|
||||
onChange={e => setEnabled(e.target.checked)}
|
||||
className="w-4 h-4 rounded accent-emerald-500"
|
||||
/>
|
||||
<span className="text-sm font-medium">{enabled ? 'Включено' : 'Выключено'}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Категории */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<h3 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 mb-1">Категории статей</h3>
|
||||
<p className="text-xs text-neutral-500 mb-4">
|
||||
Если ничего не выбрано — публикуется всё. Иначе только статьи из выбранных категорий.
|
||||
</p>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
{CATEGORIES.map(c => {
|
||||
const on = categories.includes(c.slug);
|
||||
return (
|
||||
<button
|
||||
key={c.slug}
|
||||
onClick={() => toggleCategory(c.slug)}
|
||||
className={`px-3 py-2 rounded-lg border text-sm transition-all ${
|
||||
on
|
||||
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-300'
|
||||
: 'border-neutral-200 dark:border-neutral-700 text-neutral-600 dark:text-neutral-400 hover:border-neutral-300'
|
||||
}`}
|
||||
>
|
||||
{c.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Задержка + cover */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5 grid sm:grid-cols-2 gap-5">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">
|
||||
<Clock className="w-3.5 h-3.5 inline mr-1" /> Задержка (мин)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={10080}
|
||||
value={delayMin}
|
||||
onChange={e => setDelayMin(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
/>
|
||||
<p className="text-xs text-neutral-400 mt-1">
|
||||
<code>0</code> = ближайший слот канала. <code>30</code> = через полчаса.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Картинка к посту</label>
|
||||
<label className="inline-flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={withCover}
|
||||
onChange={e => setWithCover(e.target.checked)}
|
||||
className="w-4 h-4 rounded accent-emerald-500"
|
||||
/>
|
||||
<span className="text-sm">Прикреплять обложку статьи</span>
|
||||
</label>
|
||||
<p className="text-xs text-neutral-400 mt-1">
|
||||
TG: ограничение caption — 1024 символа.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Шаблон */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<h3 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 mb-1">Шаблон поста</h3>
|
||||
<p className="text-xs text-neutral-500 mb-3">
|
||||
Markdown для Telegram. Если пусто — используется дефолт:
|
||||
<code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded ml-1 text-[11px]">{DEFAULT_TEMPLATE.replaceAll('\n', '↵')}</code>
|
||||
</p>
|
||||
<textarea
|
||||
id="auto-publish-template"
|
||||
value={template}
|
||||
onChange={e => setTemplate(e.target.value)}
|
||||
rows={5}
|
||||
placeholder={DEFAULT_TEMPLATE}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500 resize-y"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2">
|
||||
{PLACEHOLDERS.map(p => (
|
||||
<button
|
||||
key={p.key}
|
||||
onClick={() => insertPlaceholder(p.key)}
|
||||
title={p.desc}
|
||||
className="text-[11px] px-2 py-0.5 rounded bg-neutral-100 dark:bg-neutral-800 hover:bg-emerald-100 dark:hover:bg-emerald-900 text-neutral-700 dark:text-neutral-300 font-mono"
|
||||
>
|
||||
{p.key}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preview */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<h3 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 mb-1 flex items-center gap-2">
|
||||
<Eye className="w-4 h-4 text-blue-500" />
|
||||
Превью на свежей статье
|
||||
</h3>
|
||||
{previewArticleTitle && (
|
||||
<p className="text-xs text-neutral-500 mb-3">
|
||||
Пример: <span className="font-medium">{previewArticleTitle}</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loadingPreview ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-neutral-400" />
|
||||
</div>
|
||||
) : preview?.error ? (
|
||||
<p className="text-sm text-red-500">{preview.error}</p>
|
||||
) : preview ? (
|
||||
<div>
|
||||
{withCover && preview.cover_url && (
|
||||
<img
|
||||
src={preview.cover_url.startsWith('http') ? preview.cover_url : `https://zeropost.ru${preview.cover_url}`}
|
||||
alt=""
|
||||
className="w-full max-h-64 object-cover rounded mb-3"
|
||||
/>
|
||||
)}
|
||||
<pre className="whitespace-pre-wrap text-sm bg-neutral-50 dark:bg-neutral-800 p-3 rounded border border-neutral-200 dark:border-neutral-700 font-mono">
|
||||
{preview.text}
|
||||
</pre>
|
||||
<div className="flex items-center justify-between mt-2 text-xs">
|
||||
<span className={preview.length > 1024 && withCover ? 'text-amber-500' : 'text-neutral-400'}>
|
||||
{preview.length} символов{preview.length > 1024 && withCover && ' (caption обрежется до 1024)'}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => fetch(`/admin/api/articles/search?limit=20`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
const arr = d.items || [];
|
||||
if (arr.length < 2) return;
|
||||
const cur = arr.findIndex(a => a.id === previewArticleId);
|
||||
const next = arr[(cur + 1) % arr.length];
|
||||
setPreviewArticleId(next.id);
|
||||
setPreviewArticleTitle(next.title);
|
||||
})}
|
||||
className="text-blue-600 dark:text-blue-400 hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
<RefreshCw className="w-3 h-3" /> Другая статья
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-neutral-400">Нет статей для превью</p>
|
||||
)}
|
||||
|
||||
{captionWarning && (
|
||||
<div className="mt-3 flex items-start gap-2 text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950 rounded p-2">
|
||||
<AlertCircle className="w-3.5 h-3.5 mt-0.5 shrink-0" />
|
||||
<span>Текст длиннее 1024 — Telegram обрежет caption у фото. Уменьши шаблон или сними «Прикреплять обложку».</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Save */}
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={save}
|
||||
disabled={saving}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-emerald-500 hover:bg-emerald-600 disabled:opacity-50 text-white text-sm font-medium transition-colors"
|
||||
>
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{saving ? 'Сохранение…' : 'Сохранить настройки автопубликации'}
|
||||
</button>
|
||||
{savedToast && <span className="text-sm text-emerald-600 dark:text-emerald-400">✓ Сохранено</span>}
|
||||
{err && <span className="text-sm text-red-500">{err}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,52 @@ const COLOR = {
|
||||
blue: 'bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800 text-blue-700 dark:text-blue-300',
|
||||
};
|
||||
|
||||
/**
|
||||
* Рассчитать реальное время следующего запуска автогенерации.
|
||||
*
|
||||
* Логика автогена (см. src/services/autogen.js):
|
||||
* - cron бьёт каждые 10 минут
|
||||
* - срабатывает если: run_hour=ТЕКУЩИЙ_ЧАС_MSK + run_minute в окне ±5
|
||||
* - + защита: last_run_at < NOW() - INTERVAL '6 hours'
|
||||
*
|
||||
* Это даёт: следующий запуск — ближайший момент {run_hour:run_minute} MSK
|
||||
* после max(now, last_run_at + 6h).
|
||||
*/
|
||||
function calcNextRun({ run_hour = 8, run_minute = 0, last_run_at, enabled }) {
|
||||
if (!enabled) return null;
|
||||
const now = Date.now();
|
||||
|
||||
// Сегодняшняя дата в MSK
|
||||
const mskNow = new Date(now + 3 * 3600 * 1000);
|
||||
const y = mskNow.getUTCFullYear();
|
||||
const m = mskNow.getUTCMonth();
|
||||
const d = mskNow.getUTCDate();
|
||||
|
||||
// Целевое UTC время для сегодняшнего run_hour:run_minute в MSK
|
||||
// (MSK = UTC+3, поэтому UTC = MSK - 3h)
|
||||
let target = Date.UTC(y, m, d, run_hour, run_minute) - 3 * 3600 * 1000;
|
||||
|
||||
// Если уже прошло (с окном +5 мин) — переносим на завтра
|
||||
if (target + 5 * 60 * 1000 < now) {
|
||||
target += 24 * 3600 * 1000;
|
||||
}
|
||||
|
||||
// Защита «не чаще раза в 6 часов»
|
||||
if (last_run_at) {
|
||||
const guard = new Date(last_run_at).getTime() + 6 * 3600 * 1000;
|
||||
while (target < guard) target += 24 * 3600 * 1000;
|
||||
}
|
||||
return new Date(target);
|
||||
}
|
||||
|
||||
function fmtNextRun(date) {
|
||||
if (!date) return '—';
|
||||
return date.toLocaleString('ru-RU', {
|
||||
timeZone: 'Europe/Moscow',
|
||||
day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
export default function AutogenPanel({ status, queue, topics }) {
|
||||
const router = useRouter();
|
||||
const [running, setRunning] = useState({});
|
||||
@@ -122,11 +168,9 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
}
|
||||
|
||||
const pendingQueue = queue.filter(q => q.status === 'pending');
|
||||
const doneQueue = queue.filter(q => q.status === 'done').slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Toast */}
|
||||
{toast && (
|
||||
<div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-xl text-sm font-medium shadow-lg max-w-sm ${
|
||||
toast.type === 'error' ? 'bg-red-500 text-white' : 'bg-emerald-500 text-white'
|
||||
@@ -135,11 +179,10 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Шапка */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-neutral-900 dark:text-neutral-100">Автогенерация</h1>
|
||||
<p className="text-sm text-neutral-500 mt-0.5">Автоматическое создание статей по расписанию</p>
|
||||
<p className="text-sm text-neutral-500 mt-0.5">Автоматическое создание статей по расписанию (MSK)</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={runAll}
|
||||
@@ -151,12 +194,12 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Категории */}
|
||||
<div className="grid sm:grid-cols-2 gap-4">
|
||||
{status.map(s => {
|
||||
const cat = CAT_LABELS[s.category] || { name: s.category, icon: '📝', color: 'emerald' };
|
||||
const colorCls = COLOR[cat.color] || COLOR.emerald;
|
||||
const isRunning = running[s.category] || running.all;
|
||||
const nextRun = calcNextRun(s);
|
||||
return (
|
||||
<div key={s.category} className={`rounded-xl border p-5 ${colorCls}`}>
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
@@ -167,7 +210,6 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
<div className="text-xs opacity-70">{s.article_count || 0} статей · {s.queue_count || 0} в очереди</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* Вкл/выкл */}
|
||||
<button
|
||||
onClick={() => toggleCategory(s.category, !s.enabled)}
|
||||
className={`text-xs px-2 py-1 rounded-full font-medium border transition-colors ${
|
||||
@@ -188,36 +230,41 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
{[1,2,3,4].map(n => <option key={n} value={n}>{n}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<Clock className="w-3.5 h-3.5 opacity-60 shrink-0" />
|
||||
<span className="text-xs opacity-70">Время запуска:</span>
|
||||
<select
|
||||
value={s.run_hour ?? 8}
|
||||
onChange={e => updateTime(s.category, e.target.value, s.run_minute ?? 0)}
|
||||
className="text-xs bg-white/50 dark:bg-black/20 border border-current/20 rounded px-2 py-0.5"
|
||||
>
|
||||
{Array.from({length: 24}, (_,i) => (
|
||||
<option key={i} value={i}>{String(i).padStart(2,'0')}:__</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
value={s.run_minute ?? 0}
|
||||
onChange={e => updateTime(s.category, s.run_hour ?? 8, e.target.value)}
|
||||
className="text-xs bg-white/50 dark:bg-black/20 border border-current/20 rounded px-2 py-0.5"
|
||||
>
|
||||
{[0,5,10,15,20,25,30,35,40,45,50,55].map(m => (
|
||||
<option key={m} value={m}>__:{String(m).padStart(2,'0')}</option>
|
||||
))}
|
||||
</select>
|
||||
{s.next_run_at && (
|
||||
<span className="text-xs opacity-60 ml-auto">
|
||||
след.: {new Date(s.next_run_at).toLocaleString('ru-RU', {day:'numeric',month:'short',hour:'2-digit',minute:'2-digit'})}
|
||||
</span>
|
||||
<span className="text-xs opacity-70">Время (MSK):</span>
|
||||
<div className="inline-flex items-center gap-1 bg-white/50 dark:bg-black/20 border border-current/20 rounded px-1.5 py-0.5">
|
||||
<select
|
||||
value={s.run_hour ?? 8}
|
||||
onChange={e => updateTime(s.category, e.target.value, s.run_minute ?? 0)}
|
||||
className="text-xs bg-transparent font-mono focus:outline-none"
|
||||
>
|
||||
{Array.from({length: 24}, (_,i) => (
|
||||
<option key={i} value={i}>{String(i).padStart(2,'0')}</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="text-xs opacity-70 font-mono">:</span>
|
||||
<select
|
||||
value={s.run_minute ?? 0}
|
||||
onChange={e => updateTime(s.category, s.run_hour ?? 8, e.target.value)}
|
||||
className="text-xs bg-transparent font-mono focus:outline-none"
|
||||
>
|
||||
{[0,5,10,15,20,25,30,35,40,45,50,55].map(m => (
|
||||
<option key={m} value={m}>{String(m).padStart(2,'0')}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-xs opacity-60 pl-6">
|
||||
Следующий запуск: <span className="font-medium">{fmtNextRun(nextRun)}</span>
|
||||
{s.last_run_at && (
|
||||
<> · последний: {new Date(s.last_run_at).toLocaleString('ru-RU', { timeZone: 'Europe/Moscow', day:'numeric', month:'short', hour:'2-digit', minute:'2-digit' })}</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Кнопка запуска */}
|
||||
<button
|
||||
onClick={() => runCategory(s.category)}
|
||||
disabled={isRunning || !s.enabled}
|
||||
@@ -245,7 +292,6 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Форма добавления */}
|
||||
{showAddForm && (
|
||||
<div className="px-5 py-4 border-b border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-800/50">
|
||||
<div className="flex gap-3">
|
||||
@@ -278,7 +324,6 @@ export default function AutogenPanel({ status, queue, topics }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Список очереди */}
|
||||
<div className="divide-y divide-neutral-100 dark:divide-neutral-800">
|
||||
{pendingQueue.length === 0 && !showAddForm && (
|
||||
<div className="px-5 py-8 text-center text-sm text-neutral-400">
|
||||
|
||||
+273
-159
@@ -2,7 +2,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { ArrowLeft, Save, Trash2, Send, Plus, Clock, X } from 'lucide-react';
|
||||
import { ArrowLeft, Save, Trash2, Send, Plus, Clock, X, Sparkles, RefreshCw, BarChart2 } from 'lucide-react';
|
||||
import ArticlePicker from './ArticlePicker';
|
||||
import AutoPublishTab from './AutoPublishTab';
|
||||
|
||||
const PLATFORMS = [
|
||||
{ value: 'telegram', label: 'Telegram', desc: 'Публикация через Bot API' },
|
||||
@@ -11,12 +13,13 @@ const PLATFORMS = [
|
||||
];
|
||||
|
||||
const TABS = [
|
||||
{ id: 'settings', label: 'Настройки' },
|
||||
{ id: 'schedule', label: 'Расписание' },
|
||||
{ id: 'publish', label: 'Публикация' },
|
||||
{ id: 'settings', label: 'Настройки' },
|
||||
{ id: 'schedule', label: 'Расписание' },
|
||||
{ id: 'autopublish', label: 'Авто-публикация' },
|
||||
{ id: 'publish', label: 'Ручная публикация' },
|
||||
];
|
||||
|
||||
export default function ChannelEditor({ channel, articles = [] }) {
|
||||
export default function ChannelEditor({ channel }) {
|
||||
const router = useRouter();
|
||||
const isNew = !channel;
|
||||
|
||||
@@ -31,9 +34,11 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
const [maxToken, setMaxToken] = useState(channel?.max_access_token || '');
|
||||
const [isActive, setIsActive] = useState(channel?.is_active ?? true);
|
||||
|
||||
// Публикация
|
||||
const [selectedArticle, setSelectedArticle] = useState('');
|
||||
// Ручная публикация: либо статья, либо custom_text. Опционально — на конкретное время (или сейчас).
|
||||
const [pickedArticle, setPickedArticle] = useState(null);
|
||||
const [customText, setCustomText] = useState('');
|
||||
const [publishMode, setPublishMode] = useState('now'); // 'now' | 'schedule'
|
||||
const [scheduleAt, setScheduleAt] = useState('');
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [publishResult, setPublishResult] = useState(null);
|
||||
|
||||
@@ -42,19 +47,33 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
const [toast, setToast] = useState(null);
|
||||
const [activeTab, setActiveTab] = useState('settings');
|
||||
|
||||
// Слоты расписания
|
||||
// Слоты
|
||||
const [slots, setSlots] = useState([]);
|
||||
const [newSlotH, setNewSlotH] = useState(8);
|
||||
const [newSlotM, setNewSlotM] = useState(0);
|
||||
const [addingSlot, setAddingSlot] = useState(false);
|
||||
|
||||
// Загружаем слоты
|
||||
// Очередь канала
|
||||
const [queue, setQueue] = useState([]);
|
||||
const [loadingQueue, setLoadingQueue] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!channel?.id) return;
|
||||
fetch(`/admin/api/channels/${channel.id}/slots`)
|
||||
.then(r => r.json()).then(setSlots).catch(() => {});
|
||||
fetch(`/admin/api/channels/${channel.id}/slots`).then(r => r.json()).then(setSlots).catch(() => {});
|
||||
loadQueue();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [channel?.id]);
|
||||
|
||||
async function loadQueue() {
|
||||
if (!channel?.id) return;
|
||||
setLoadingQueue(true);
|
||||
try {
|
||||
const r = await fetch(`/admin/api/channels/${channel.id}/scheduled`);
|
||||
const d = await r.json();
|
||||
if (Array.isArray(d)) setQueue(d);
|
||||
} catch {} finally { setLoadingQueue(false); }
|
||||
}
|
||||
|
||||
function showToast(msg, type = 'success') {
|
||||
setToast({ msg, type });
|
||||
setTimeout(() => setToast(null), 4000);
|
||||
@@ -105,27 +124,43 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function publish() {
|
||||
if (!selectedArticle && !customText.trim()) {
|
||||
async function doPublish() {
|
||||
if (!pickedArticle && !customText.trim()) {
|
||||
return showToast('Выберите статью или введите текст', 'error');
|
||||
}
|
||||
setPublishing(true);
|
||||
setPublishResult(null);
|
||||
try {
|
||||
const res = await fetch(`/admin/api/channels/${channel.id}/publish`, {
|
||||
const isSchedule = publishMode === 'schedule';
|
||||
if (isSchedule && !scheduleAt) {
|
||||
throw new Error('Укажите время публикации');
|
||||
}
|
||||
const url = isSchedule
|
||||
? `/admin/api/channels/${channel.id}/scheduled`
|
||||
: `/admin/api/channels/${channel.id}/publish`;
|
||||
const body = isSchedule
|
||||
? {
|
||||
article_id: pickedArticle?.id,
|
||||
custom_text: customText.trim() || undefined,
|
||||
scheduled_at: new Date(scheduleAt).toISOString(),
|
||||
}
|
||||
: {
|
||||
article_id: pickedArticle?.id,
|
||||
custom_text: customText.trim() || undefined,
|
||||
};
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
article_id: selectedArticle ? parseInt(selectedArticle) : undefined,
|
||||
custom_text: customText.trim() || undefined,
|
||||
}),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Ошибка публикации');
|
||||
setPublishResult({ ok: true, data });
|
||||
showToast('Опубликовано!');
|
||||
setSelectedArticle('');
|
||||
setPublishResult({ ok: true, data, scheduled: isSchedule });
|
||||
showToast(isSchedule ? `Запланировано на ${new Date(scheduleAt).toLocaleString('ru-RU')}` : 'Опубликовано!');
|
||||
setPickedArticle(null);
|
||||
setCustomText('');
|
||||
setScheduleAt('');
|
||||
loadQueue();
|
||||
} catch (e) {
|
||||
setPublishResult({ ok: false, error: e.message });
|
||||
showToast(e.message.slice(0, 120), 'error');
|
||||
@@ -134,13 +169,14 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Автозаполнение текста при выборе статьи
|
||||
function onArticleSelect(artId) {
|
||||
setSelectedArticle(artId);
|
||||
if (!artId) { setCustomText(''); return; }
|
||||
const art = articles.find(a => String(a.id) === artId);
|
||||
if (art) {
|
||||
setCustomText(`${art.title}\n\n${art.excerpt || ''}\n\nhttps://zeropost.ru/blog/${art.slug}`);
|
||||
async function cancelScheduled(id) {
|
||||
if (!confirm('Отменить эту запланированную публикацию?')) return;
|
||||
try {
|
||||
await fetch(`/admin/api/scheduled/${id}`, { method: 'DELETE' });
|
||||
loadQueue();
|
||||
showToast('Отменено');
|
||||
} catch (e) {
|
||||
showToast(e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,9 +202,14 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
setSlots(s => s.filter(sl => sl.id !== slotId));
|
||||
}
|
||||
|
||||
const STATUS_LABELS = {
|
||||
pending: { text: 'В очереди', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-950 dark:text-blue-300' },
|
||||
sent: { text: 'Отправлено', cls: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300' },
|
||||
failed: { text: 'Ошибка', cls: 'bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300' },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
{/* Toast */}
|
||||
{toast && (
|
||||
<div className={`fixed top-4 right-4 z-50 px-4 py-2.5 rounded-xl text-sm font-medium shadow-lg ${
|
||||
toast.type === 'error' ? 'bg-red-500 text-white' : 'bg-emerald-500 text-white'
|
||||
@@ -186,8 +227,21 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
<h1 className="text-xl font-bold text-neutral-900 dark:text-neutral-100">
|
||||
{isNew ? 'Новый канал' : channel.name}
|
||||
</h1>
|
||||
{!isNew && channel.auto_publish_enabled && (
|
||||
<span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-emerald-100 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-300">
|
||||
<Sparkles className="w-3 h-3" />
|
||||
auto
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{!isNew && (
|
||||
<Link href={`/admin/channels/${channel.id}/stats`}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 text-sm text-neutral-600 dark:text-neutral-400 hover:bg-neutral-50 dark:hover:bg-neutral-800 transition-colors">
|
||||
<BarChart2 className="w-4 h-4" />
|
||||
Статистика
|
||||
</Link>
|
||||
)}
|
||||
{!isNew && (
|
||||
<button onClick={deleteChannel} disabled={deleting}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-red-200 dark:border-red-900 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950 transition-colors disabled:opacity-50">
|
||||
@@ -195,20 +249,21 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
{deleting ? 'Удаление...' : 'Удалить'}
|
||||
</button>
|
||||
)}
|
||||
<button onClick={save} disabled={saving}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-emerald-500 hover:bg-emerald-600 disabled:opacity-50 text-white text-sm font-medium transition-colors">
|
||||
<Save className="w-4 h-4" />
|
||||
{saving ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
{(isNew || activeTab === 'settings') && (
|
||||
<button onClick={save} disabled={saving}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-emerald-500 hover:bg-emerald-600 disabled:opacity-50 text-white text-sm font-medium transition-colors">
|
||||
<Save className="w-4 h-4" />
|
||||
{saving ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Вкладки — только для существующего канала */}
|
||||
{!isNew && (
|
||||
<div className="flex gap-1 border-b border-neutral-200 dark:border-neutral-800">
|
||||
<div className="flex gap-1 border-b border-neutral-200 dark:border-neutral-800 overflow-x-auto">
|
||||
{TABS.map(tab => (
|
||||
<button key={tab.id} onClick={() => setActiveTab(tab.id)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
|
||||
activeTab === tab.id
|
||||
? 'border-emerald-500 text-emerald-600 dark:text-emerald-400'
|
||||
: 'border-transparent text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
|
||||
@@ -222,115 +277,104 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
{/* Вкладка: Настройки */}
|
||||
{(isNew || activeTab === 'settings') && (
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5 space-y-4">
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">Основное</h2>
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">Основное</h2>
|
||||
|
||||
{/* Платформа */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-2">Платформа</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{PLATFORMS.map(p => (
|
||||
<button
|
||||
key={p.value}
|
||||
onClick={() => setPlatform(p.value)}
|
||||
className={`p-3 rounded-lg border text-left transition-all ${
|
||||
platform === p.value
|
||||
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950'
|
||||
: 'border-neutral-200 dark:border-neutral-700 hover:border-neutral-300'
|
||||
}`}
|
||||
>
|
||||
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100">{p.label}</div>
|
||||
<div className="text-xs text-neutral-400 mt-0.5">{p.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Название */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Название канала</label>
|
||||
<input type="text" value={name} onChange={e => setName(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="ZeroPost TG" />
|
||||
</div>
|
||||
|
||||
{/* Поля Telegram */}
|
||||
{platform === 'telegram' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">
|
||||
Создайте бота через <a href="https://t.me/BotFather" target="_blank" className="text-blue-500 hover:underline">@BotFather</a>, добавьте его в канал как администратора.
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Bot Token</label>
|
||||
<input type="password" value={botToken} onChange={e => setBotToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="123456789:AABBccdd..." />
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-2">Платформа</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{PLATFORMS.map(p => (
|
||||
<button key={p.value} onClick={() => setPlatform(p.value)}
|
||||
className={`p-3 rounded-lg border text-left transition-all ${
|
||||
platform === p.value
|
||||
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950'
|
||||
: 'border-neutral-200 dark:border-neutral-700 hover:border-neutral-300'
|
||||
}`}>
|
||||
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100">{p.label}</div>
|
||||
<div className="text-xs text-neutral-400 mt-0.5">{p.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Название канала</label>
|
||||
<input type="text" value={name} onChange={e => setName(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="ZeroPost TG" />
|
||||
</div>
|
||||
|
||||
{platform === 'telegram' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">
|
||||
Создайте бота через <a href="https://t.me/BotFather" target="_blank" className="text-blue-500 hover:underline">@BotFather</a>, добавьте его в канал как администратора.
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Bot Token</label>
|
||||
<input type="password" value={botToken} onChange={e => setBotToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="123456789:AABBccdd..." />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Channel ID</label>
|
||||
<input type="text" value={tgChannelId} onChange={e => setTgChannelId(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="-100123456789" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Username (опц.)</label>
|
||||
<input type="text" value={tgUsername} onChange={e => setTgUsername(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="@zeropost_ru" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{platform === 'vk' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">
|
||||
Получите токен через <a href="https://vk.com/dev/implicit_flow_user" target="_blank" className="text-blue-500 hover:underline">VK API</a> с правами wall, photos.
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">ID группы</label>
|
||||
<input type="text" value={vkGroupId} onChange={e => setVkGroupId(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="123456789" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Access Token</label>
|
||||
<input type="password" value={vkToken} onChange={e => setVkToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="vk1.a.xxx..." />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{platform === 'max' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">Max — публикация через Bot API.</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Channel ID</label>
|
||||
<input type="text" value={tgChannelId} onChange={e => setTgChannelId(e.target.value)}
|
||||
<input type="text" value={maxChannelId} onChange={e => setMaxChannelId(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="-100123456789" />
|
||||
placeholder="channel_id" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Username (опц.)</label>
|
||||
<input type="text" value={tgUsername} onChange={e => setTgUsername(e.target.value)}
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Access Token</label>
|
||||
<input type="password" value={maxToken} onChange={e => setMaxToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="@zeropost_ru" />
|
||||
placeholder="token..." />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{/* Поля ВКонтакте */}
|
||||
{platform === 'vk' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">
|
||||
Получите токен через <a href="https://vk.com/dev/implicit_flow_user" target="_blank" className="text-blue-500 hover:underline">VK API</a> с правами wall, photos.
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">ID группы</label>
|
||||
<input type="text" value={vkGroupId} onChange={e => setVkGroupId(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="123456789" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Access Token</label>
|
||||
<input type="password" value={vkToken} onChange={e => setVkToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="vk1.a.xxx..." />
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<input type="checkbox" id="isActive" checked={isActive} onChange={e => setIsActive(e.target.checked)}
|
||||
className="w-4 h-4 rounded accent-emerald-500" />
|
||||
<label htmlFor="isActive" className="text-sm text-neutral-700 dark:text-neutral-300">Канал активен</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Поля Max */}
|
||||
{platform === 'max' && (
|
||||
<div className="space-y-3 pt-2 border-t border-neutral-100 dark:border-neutral-800">
|
||||
<p className="text-xs text-neutral-400">
|
||||
Max (бывший ОК) — публикация через Bot API.
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Channel ID</label>
|
||||
<input type="text" value={maxChannelId} onChange={e => setMaxChannelId(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="channel_id" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Access Token</label>
|
||||
<input type="password" value={maxToken} onChange={e => setMaxToken(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="token..." />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Активность */}
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<input type="checkbox" id="isActive" checked={isActive} onChange={e => setIsActive(e.target.checked)}
|
||||
className="w-4 h-4 rounded accent-emerald-500" />
|
||||
<label htmlFor="isActive" className="text-sm text-neutral-700 dark:text-neutral-300">Канал активен</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Вкладка: Расписание */}
|
||||
@@ -338,9 +382,8 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 mb-1">Слоты публикации</h2>
|
||||
<p className="text-xs text-neutral-400 mb-5">Время когда будут отправляться запланированные посты. Добавьте несколько слотов — посты распределятся по ним автоматически.</p>
|
||||
<p className="text-xs text-neutral-400 mb-5">Время когда выходят запланированные посты. При автопубликации новая статья ставится на ближайший свободный слот.</p>
|
||||
|
||||
{/* Список слотов */}
|
||||
<div className="space-y-2 mb-5">
|
||||
{slots.length === 0 && (
|
||||
<p className="text-sm text-neutral-400 text-center py-4">Слотов пока нет — добавьте время публикации</p>
|
||||
@@ -360,7 +403,6 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Добавить слот */}
|
||||
<div className="border-t border-neutral-100 dark:border-neutral-800 pt-4">
|
||||
<p className="text-xs font-medium text-neutral-500 mb-3">Добавить слот</p>
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -385,47 +427,116 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
Добавить
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-neutral-400 mt-2">
|
||||
Совет: используй не круглые числа (8:06, 11:23) — так посты выглядят органичнее в ленте
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Подсказка */}
|
||||
<div className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-xl p-4 text-sm text-blue-700 dark:text-blue-300">
|
||||
<p className="font-medium mb-1">Как работает расписание</p>
|
||||
<p className="text-xs opacity-80">Когда ты ставишь пост в очередь на вкладке "Публикация" — он автоматически назначается на ближайший свободный слот. Если добавить 4 слота, посты будут выходить 4 раза в день.</p>
|
||||
{/* Очередь канала */}
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">Очередь канала</h2>
|
||||
<button onClick={loadQueue} className="text-xs text-neutral-500 hover:text-emerald-600 inline-flex items-center gap-1">
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${loadingQueue ? 'animate-spin' : ''}`} /> Обновить
|
||||
</button>
|
||||
</div>
|
||||
{queue.length === 0 ? (
|
||||
<p className="text-sm text-neutral-400 text-center py-4">Очередь пуста</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{queue.map(q => {
|
||||
const label = STATUS_LABELS[q.status] || STATUS_LABELS.pending;
|
||||
return (
|
||||
<div key={q.id} className="flex items-start gap-3 p-3 rounded-lg bg-neutral-50 dark:bg-neutral-800">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100 truncate">
|
||||
{q.article_title || (q.custom_text?.slice(0, 60) + '...') || `Пост #${q.id}`}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-neutral-500 flex-wrap">
|
||||
<span className={`px-1.5 py-0.5 rounded font-medium ${label.cls}`}>{label.text}</span>
|
||||
<span>{new Date(q.scheduled_at).toLocaleString('ru-RU', { day:'numeric', month:'short', hour:'2-digit', minute:'2-digit' })}</span>
|
||||
{q.article_category && <span className="text-neutral-400">[{q.article_category}]</span>}
|
||||
{q.error && <span className="text-red-500 truncate">{q.error}</span>}
|
||||
</div>
|
||||
</div>
|
||||
{q.status === 'pending' && (
|
||||
<button onClick={() => cancelScheduled(q.id)}
|
||||
className="text-xs text-neutral-400 hover:text-red-500 px-2 py-1">
|
||||
отменить
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Вкладка: Публикация */}
|
||||
{/* Вкладка: Авто-публикация */}
|
||||
{!isNew && activeTab === 'autopublish' && (
|
||||
<AutoPublishTab channel={channel} onSaved={() => router.refresh()} />
|
||||
)}
|
||||
|
||||
{/* Вкладка: Ручная публикация */}
|
||||
{!isNew && activeTab === 'publish' && (
|
||||
<div className="bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800 p-5 space-y-4">
|
||||
<h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">Опубликовать</h2>
|
||||
|
||||
{/* Выбор статьи */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Выбрать статью</label>
|
||||
<select value={selectedArticle} onChange={e => onArticleSelect(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500">
|
||||
<option value="">— выбрать статью —</option>
|
||||
{articles.map(a => (
|
||||
<option key={a.id} value={a.id}>{a.title}</option>
|
||||
))}
|
||||
</select>
|
||||
<ArticlePicker
|
||||
value={pickedArticle?.id}
|
||||
onChange={a => {
|
||||
setPickedArticle(a);
|
||||
if (a) setCustomText(''); // когда выбрана статья — текст рендерит шаблон канала
|
||||
}}
|
||||
channelId={channel.id}
|
||||
placeholder="Найти статью (поиск по названию)…"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Текст поста */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Текст поста</label>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">
|
||||
Или произвольный текст {pickedArticle && <span className="text-neutral-400">(если задан — перебивает шаблон статьи)</span>}
|
||||
</label>
|
||||
<textarea value={customText} onChange={e => setCustomText(e.target.value)} rows={6}
|
||||
className="w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 resize-y font-mono"
|
||||
placeholder="Текст поста (Markdown для Telegram)..." />
|
||||
placeholder="Markdown для Telegram. Если пусто и выбрана статья — текст возьмётся из шаблона авто-публикации канала." />
|
||||
<div className="text-xs text-neutral-300 text-right mt-0.5">{customText.length} символов</div>
|
||||
</div>
|
||||
|
||||
{/* Результат */}
|
||||
{/* Режим */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-neutral-500 mb-1.5">Когда</label>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => setPublishMode('now')}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm border transition-all ${
|
||||
publishMode === 'now'
|
||||
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-300'
|
||||
: 'border-neutral-200 dark:border-neutral-700 text-neutral-600'
|
||||
}`}>
|
||||
<Send className="w-3.5 h-3.5 inline mr-1" /> Сейчас
|
||||
</button>
|
||||
<button onClick={() => setPublishMode('schedule')}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm border transition-all ${
|
||||
publishMode === 'schedule'
|
||||
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-300'
|
||||
: 'border-neutral-200 dark:border-neutral-700 text-neutral-600'
|
||||
}`}>
|
||||
<Clock className="w-3.5 h-3.5 inline mr-1" /> Запланировать
|
||||
</button>
|
||||
</div>
|
||||
{publishMode === 'schedule' && (
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={scheduleAt}
|
||||
onChange={e => setScheduleAt(e.target.value)}
|
||||
min={new Date(Date.now() + 60000).toISOString().slice(0, 16)}
|
||||
className="mt-2 w-full px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-stone-50 dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{publishResult && (
|
||||
<div className={`rounded-lg px-4 py-3 text-sm ${
|
||||
publishResult.ok
|
||||
@@ -433,17 +544,20 @@ export default function ChannelEditor({ channel, articles = [] }) {
|
||||
: 'bg-red-50 dark:bg-red-950 text-red-700 dark:text-red-300'
|
||||
}`}>
|
||||
{publishResult.ok ? (
|
||||
<span>✓ Опубликовано{publishResult.data?.tg_message_id ? ` (message_id: ${publishResult.data.tg_message_id})` : ''}</span>
|
||||
<span>
|
||||
✓ {publishResult.scheduled ? 'Запланировано' : 'Опубликовано'}
|
||||
{publishResult.data?.tg_message_id ? ` (message_id: ${publishResult.data.tg_message_id})` : ''}
|
||||
</span>
|
||||
) : (
|
||||
<span>✗ {publishResult.error}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button onClick={publish} disabled={publishing || (!selectedArticle && !customText.trim())}
|
||||
<button onClick={doPublish} disabled={publishing || (!pickedArticle && !customText.trim()) || (publishMode === 'schedule' && !scheduleAt)}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-blue-500 hover:bg-blue-600 disabled:opacity-50 text-white text-sm font-medium transition-colors">
|
||||
<Send className="w-4 h-4" />
|
||||
{publishing ? 'Публикация...' : `Опубликовать в ${PLATFORMS.find(p=>p.value===channel.platform)?.label || 'канал'}`}
|
||||
{publishing ? '…' : (publishMode === 'schedule' ? 'Поставить в очередь' : `Опубликовать в ${PLATFORMS.find(p=>p.value===channel.platform)?.label || 'канал'}`)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user