forked from admin/zeropost-tool
256 lines
11 KiB
JavaScript
256 lines
11 KiB
JavaScript
'use client';
|
|
|
|
/**
|
|
* ChannelAnalytics — вкладка аналитики в ChannelView.
|
|
* Props: channelId, channelName
|
|
*/
|
|
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
import { BarChart2, TrendingUp, Clock, RefreshCw,
|
|
Heart, Share2, Eye, AlertCircle, Calendar } from 'lucide-react';
|
|
|
|
const DOW_SHORT = ['Пн','Вт','Ср','Чт','Пт','Сб','Вс'];
|
|
const BAR_HEIGHT = 80;
|
|
|
|
// ── Мини-бар для гистограммы ──────────────────────────────────────────────────
|
|
function Bar({ value, max, label, highlight }) {
|
|
const pct = max > 0 ? (value / max) : 0;
|
|
return (
|
|
<div className="flex flex-col items-center gap-1 flex-1">
|
|
<span className="text-[10px] text-text-mute">{value > 0 ? value : ''}</span>
|
|
<div className="w-full rounded-t-sm" style={{
|
|
height: BAR_HEIGHT,
|
|
display: 'flex',
|
|
alignItems: 'flex-end',
|
|
}}>
|
|
<div
|
|
className={`w-full rounded-t-sm transition-all ${highlight ? 'bg-accent' : 'bg-accent/30'}`}
|
|
style={{ height: `${Math.max(pct * BAR_HEIGHT, value > 0 ? 4 : 0)}px` }}
|
|
/>
|
|
</div>
|
|
<span className="text-[10px] text-text-mute">{label}</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ── Карточка метрики ──────────────────────────────────────────────────────────
|
|
function MetricCard({ Icon, label, value, sub, color = 'text-accent' }) {
|
|
return (
|
|
<div className="card p-4 flex items-center gap-3">
|
|
<div className={`p-2 rounded-lg bg-surface2 ${color}`}>
|
|
<Icon className="w-5 h-5" />
|
|
</div>
|
|
<div>
|
|
<div className="text-xl font-bold">{value ?? '—'}</div>
|
|
<div className="text-xs text-text-mute">{label}</div>
|
|
{sub && <div className="text-xs text-text-mute mt-0.5">{sub}</div>}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ── Строка реакций ────────────────────────────────────────────────────────────
|
|
function ReactionBar({ reactions }) {
|
|
if (!reactions || !Object.keys(reactions).length) return null;
|
|
const total = Object.values(reactions).reduce((s, v) => s + v, 0);
|
|
return (
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
{Object.entries(reactions)
|
|
.sort((a, b) => b[1] - a[1])
|
|
.map(([emoji, count]) => (
|
|
<span key={emoji} className="flex items-center gap-1 text-sm bg-surface2 px-2 py-0.5 rounded-full border border-border">
|
|
{emoji} <span className="text-xs text-text-mute">{count}</span>
|
|
</span>
|
|
))}
|
|
<span className="text-xs text-text-mute ml-auto">всего {total}</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ── Главный компонент ─────────────────────────────────────────────────────────
|
|
export default function ChannelAnalytics({ channelId, channelName }) {
|
|
const [metrics, setMetrics] = useState(null);
|
|
const [bestTime, setBestTime] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const [days, setDays] = useState(30);
|
|
|
|
const load = useCallback(async () => {
|
|
setLoading(true);
|
|
setError('');
|
|
try {
|
|
const [m, b] = await Promise.all([
|
|
fetch(`/api/metrics/channel/${channelId}?days=${days}`).then(r => r.json()),
|
|
fetch(`/api/metrics/best-time/${channelId}?days=90`).then(r => r.json()),
|
|
]);
|
|
if (m.error) throw new Error(m.error);
|
|
setMetrics(m);
|
|
setBestTime(b);
|
|
} catch (e) {
|
|
setError(e.message);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [channelId, days]);
|
|
|
|
useEffect(() => { load(); }, [load]);
|
|
|
|
const totals = metrics?.totals || {};
|
|
const topPosts = metrics?.top_posts || [];
|
|
const reactionTotals = metrics?.reaction_totals || [];
|
|
const totalReactions = reactionTotals.reduce((s, r) => s + parseInt(r.total), 0);
|
|
|
|
// Лучший день недели по кол-ву публикаций
|
|
const dowData = Array.from({ length: 7 }, (_, i) => {
|
|
const d = bestTime?.by_dow?.find(r => parseInt(r.dow) === i + 1);
|
|
return { label: DOW_SHORT[i], value: d?.count || 0 };
|
|
});
|
|
const maxDow = Math.max(...dowData.map(d => d.value), 1);
|
|
const bestDow = dowData.reduce((best, d, i) => d.value > best.value ? { ...d, i } : best, { value: 0, i: -1 });
|
|
|
|
// Лучший час
|
|
const hourData = Array.from({ length: 24 }, (_, h) => {
|
|
const d = bestTime?.by_hour?.find(r => parseInt(r.hour) === h);
|
|
return { label: `${h}`, value: d?.count || 0 };
|
|
});
|
|
const maxHour = Math.max(...hourData.map(d => d.value), 1);
|
|
const bestHour = hourData.reduce((best, d, i) => d.value > best.value ? { ...d, i } : best, { value: 0, i: -1 });
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5">
|
|
|
|
{/* Тулбар */}
|
|
<div className="flex items-center justify-between flex-wrap gap-2">
|
|
<h3 className="font-semibold flex items-center gap-2">
|
|
<BarChart2 className="w-4 h-4 text-accent" />
|
|
Аналитика
|
|
</h3>
|
|
<div className="flex items-center gap-2">
|
|
<select
|
|
className="input py-1 text-sm w-32"
|
|
value={days}
|
|
onChange={e => setDays(parseInt(e.target.value))}
|
|
>
|
|
<option value={7}>7 дней</option>
|
|
<option value={30}>30 дней</option>
|
|
<option value={90}>90 дней</option>
|
|
</select>
|
|
<button onClick={load} className="btn-ghost p-1.5 rounded-lg" title="Обновить">
|
|
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{error && (
|
|
<div className="card p-3 text-sm text-red-400 flex items-center gap-2">
|
|
<AlertCircle className="w-4 h-4 shrink-0" /> {error}
|
|
</div>
|
|
)}
|
|
|
|
{/* Карточки-цифры */}
|
|
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
|
<MetricCard Icon={Calendar} label={`Постов за ${days} дн.`} value={totals.total_posts || 0} />
|
|
<MetricCard Icon={Eye} label="Опубликовано в TG" value={totals.published_to_tg || 0} />
|
|
<MetricCard Icon={Heart} label="Реакций за период" value={totalReactions || 0} color="text-pink-400" />
|
|
<MetricCard Icon={Share2} label="Пересылок" value={totals.total_forwards || 0} color="text-blue-400" />
|
|
</div>
|
|
|
|
{/* Топ реакций */}
|
|
{reactionTotals.length > 0 && (
|
|
<div className="card p-4">
|
|
<div className="text-sm font-semibold mb-3 flex items-center gap-2">
|
|
<Heart className="w-4 h-4 text-pink-400" /> Реакции за {days} дней
|
|
</div>
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
{reactionTotals.map(r => (
|
|
<span key={r.emoji} className="flex items-center gap-1.5 text-sm bg-surface2 px-3 py-1 rounded-full border border-border">
|
|
{r.emoji}
|
|
<span className="font-semibold">{r.total}</span>
|
|
</span>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Лучший день недели */}
|
|
<div className="card p-4">
|
|
<div className="text-sm font-semibold mb-1 flex items-center gap-2">
|
|
<TrendingUp className="w-4 h-4 text-accent" /> Активность по дням недели
|
|
</div>
|
|
{bestDow.value > 0 && (
|
|
<p className="text-xs text-text-mute mb-3">
|
|
Чаще всего публикуешь в <span className="text-accent font-medium">{DOW_SHORT[bestDow.i]}</span>
|
|
</p>
|
|
)}
|
|
<div className="flex gap-1 items-end" style={{ height: BAR_HEIGHT + 32 }}>
|
|
{dowData.map((d, i) => (
|
|
<Bar key={i} value={d.value} max={maxDow} label={d.label} highlight={i === bestDow.i} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Лучший час */}
|
|
<div className="card p-4">
|
|
<div className="text-sm font-semibold mb-1 flex items-center gap-2">
|
|
<Clock className="w-4 h-4 text-accent" /> Активность по часам (МСК, 90 дн.)
|
|
</div>
|
|
{bestHour.value > 0 && (
|
|
<p className="text-xs text-text-mute mb-3">
|
|
Пик публикаций в <span className="text-accent font-medium">{bestHour.i}:00</span>
|
|
</p>
|
|
)}
|
|
<div className="flex gap-px items-end overflow-x-auto" style={{ height: BAR_HEIGHT + 32 }}>
|
|
{hourData.map((d, i) => (
|
|
<Bar key={i} value={d.value} max={maxHour} label={i % 4 === 0 ? String(i) : ''} highlight={i === bestHour.i} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Топ постов по реакциям */}
|
|
{topPosts.length > 0 && (
|
|
<div className="card p-4">
|
|
<div className="text-sm font-semibold mb-3 flex items-center gap-2">
|
|
<Heart className="w-4 h-4 text-pink-400" /> Топ постов по реакциям
|
|
</div>
|
|
<div className="flex flex-col gap-3">
|
|
{topPosts.map(p => (
|
|
<div key={p.id} className="p-3 rounded-lg bg-surface2 border border-border">
|
|
<div className="text-xs text-text-soft line-clamp-2 mb-2">{p.preview}</div>
|
|
<div className="flex items-center gap-3 flex-wrap">
|
|
<ReactionBar reactions={p.reactions} />
|
|
{p.forwards > 0 && (
|
|
<span className="text-xs text-text-mute flex items-center gap-1">
|
|
<Share2 className="w-3 h-3" /> {p.forwards}
|
|
</span>
|
|
)}
|
|
<span className="text-xs text-text-mute ml-auto">
|
|
{p.published_at ? new Date(p.published_at).toLocaleDateString('ru', { day:'numeric', month:'short' }) : ''}
|
|
</span>
|
|
{p.tg_message_id && (
|
|
<a
|
|
href={`https://t.me/${channelName?.replace('@','')}/${p.tg_message_id}`}
|
|
target="_blank" rel="noopener noreferrer"
|
|
className="text-xs text-accent hover:underline"
|
|
>
|
|
Открыть
|
|
</a>
|
|
)}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Нет данных */}
|
|
{!loading && metrics && topPosts.length === 0 && reactionTotals.length === 0 && (
|
|
<div className="card p-8 text-center text-text-mute">
|
|
<BarChart2 className="w-8 h-8 mx-auto mb-3 opacity-30" />
|
|
<p>Пока нет данных для отображения</p>
|
|
<p className="text-xs mt-1">Реакции появятся после первых публикаций через этот канал</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|