Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(reddit): improve analytics detail, add global posts view, fix overview karma
spacesdrive039c7d0e92d1
diff --git a/backend/services/reddit.js b/backend/services/reddit.jsindex f8fd79a..850246a 100644--- a/backend/services/reddit.js+++ b/backend/services/reddit.js@@ -82,6 +82,7 @@ export async function fetchRedditPosts(username, cookie, limit = 100) {isNsfw: p.over_18 ?? false,createdAt: p.created_utc ? new Date(p.created_utc * 1000).toISOString() : '',flair: p.link_flair_text ?? '',+ awardsCount: p.total_awards_received ?? 0,}));}@@ -89,6 +90,7 @@ export function computeRedditAnalytics(profile, posts) {const empty = {fetchedPosts: 0, totalScore: 0, avgScore: 0, medianScore: 0,totalComments: 0, avgComments: 0, avgUpvoteRatio: 0,+ totalAwards: 0, avgAwards: 0,topPosts: [], worstPosts: [], subredditBreakdown: [],mediaTypeDistribution: {}, postsByDayOfWeek: [], postsByHour: [],monthlyBreakdown: [], engagementTimeline: [],@@ -100,10 +102,12 @@ export function computeRedditAnalytics(profile, posts) {if (!posts || posts.length === 0) return empty;- const totalScore = posts.reduce((s, p) => s + p.score, 0);+ const totalScore = posts.reduce((s, p) => s + p.score, 0);const totalComments = posts.reduce((s, p) => s + p.numComments, 0);- const avgScore = Math.round(totalScore / posts.length);+ const totalAwards = posts.reduce((s, p) => s + (p.awardsCount ?? 0), 0);+ const avgScore = Math.round(totalScore / posts.length);const avgComments = Math.round(totalComments / posts.length);+ const avgAwards = parseFloat((totalAwards / posts.length).toFixed(2));const avgUpvoteRatio = parseFloat((posts.reduce((s, p) => s + p.upvoteRatio, 0) / posts.length * 100).toFixed(1));@@ -230,6 +234,7 @@ export function computeRedditAnalytics(profile, posts) {fetchedPosts: posts.length,totalScore, avgScore, medianScore,totalComments, avgComments, avgUpvoteRatio,+ totalAwards, avgAwards,topPosts: byScore.slice(0, 10),worstPosts: byScore.slice(-5).reverse(),subredditBreakdown,diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 4af9a88..f654287 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -20,6 +20,7 @@ const AccountManager = lazy(() => import('./features/accounts/AccountManagerconst Settings = lazy(() => import('./features/settings/Settings'));const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));const RedditPosts = lazy(() => import('./features/analytics/reddit/RedditPosts'));+const RedditPostsAll = lazy(() => import('./features/analytics/reddit/RedditPostsAll'));const router = createBrowserRouter([{@@ -46,6 +47,7 @@ const router = createBrowserRouter([{ path: 'accounts', element: <AccountManager /> },{ path: 'settings', element: <Settings /> },{ path: 'reddit/:id', element: <RedditAnalytics /> },+ { path: 'reddit-posts', element: <RedditPostsAll /> },{ path: 'reddit-posts/:id', element: <RedditPosts /> },{ path: '*', element: <Navigate to="/" replace /> },],diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex 7c3daaa..4b16380 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -15,7 +15,7 @@ import StatCard from '../../../components/ui/StatCard';import MainCard from '../../../components/MainCard';import { useAppContext } from '../../../context/AppContext';import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';-import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera, MessageSquare } from 'lucide-react';+import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera, MessageSquare, Flame } from 'lucide-react';const CHART_COLORS = ['hsl(221.2,83.2%,53.3%)', '#22c55e', '#f97316', '#a855f7', '#06b6d4', '#ec4899', '#6366f1', '#eab308'];@@ -32,7 +32,7 @@ export default function Overview() {return { ...acc, followers: acc.followers + (a.followersCount || 0), posts: acc.posts + (a.mediaCount || 0) };}if (a.platform === 'reddit') {- return { ...acc, karma: acc.karma + (a.totalKarma || 0) };+ return { ...acc, karma: acc.karma + (a.totalKarma || 0), postKarma: acc.postKarma + (a.postKarma || 0), commentKarma: acc.commentKarma + (a.commentKarma || 0) };}return {...acc,@@ -40,13 +40,14 @@ export default function Overview() {views: acc.views + (a.viewCount || 0),videos: acc.videos + (a.videoCount || 0),};- }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0 });+ }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0, postKarma: 0, commentKarma: 0 });- const totalAudience = totals.subscribers + totals.followers + totals.karma;+ // Karma is engagement-based, not audience-based — excluded from totalAudience+ const totalAudience = totals.subscribers + totals.followers;const audienceMetric = (a) => {- if (a.platform === 'reddit') return a.totalKarma || 0;if (a.platform === 'instagram') return a.followersCount || 0;+ if (a.platform === 'reddit') return 0;return a.subscriberCount || 0;};const contentMetric = (a) => {@@ -54,18 +55,22 @@ export default function Overview() {if (a.platform === 'instagram') return a.mediaCount || 0;return a.viewCount || 0;};+ const karmaMetric = (a) => (a.platform === 'reddit' ? a.totalKarma || 0 : 0);++ // Audience charts exclude Reddit - karma is not an audience metric+ const nonRedditAccounts = accounts.filter(a => a.platform !== 'reddit');const sorted = {- byAudience: [...accounts].sort((a, b) => audienceMetric(b) - audienceMetric(a)),- byContent: [...accounts].sort((a, b) => contentMetric(b) - contentMetric(a)),+ byAudience: [...nonRedditAccounts].sort((a, b) => audienceMetric(b) - audienceMetric(a)),+ byContent: [...nonRedditAccounts].sort((a, b) => contentMetric(b) - contentMetric(a)),};- const chartData = accounts.map(a => ({+ const chartData = nonRedditAccounts.map(a => ({name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),audience: audienceMetric(a),}));- const pieData = accounts.map((a, i) => ({+ const pieData = nonRedditAccounts.map((a, i) => ({name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),value: audienceMetric(a),color: CHART_COLORS[i % CHART_COLORS.length],@@ -111,15 +116,54 @@ export default function Overview() {{/* KPI cards */}<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">{[- { icon: <Users />, label: 'Total Audience', value: fmtNum(totalAudience), subtitle: `${fmtNum(totals.subscribers)} subs · ${fmtNum(totals.followers)} followers`, gradient: 'purple' },- { icon: <Eye />, label: 'Total Views', value: fmtNum(totals.views), subtitle: fmtNumFull(totals.views), gradient: 'red' },- { icon: <VideoIcon />, label: 'Total Content', value: fmtNum(totals.videos + totals.posts), subtitle: `${fmtNum(totals.videos)} videos · ${fmtNum(totals.posts)} posts`, gradient: 'blue' },+ { icon: <Users />, label: 'Total Audience', value: fmtNum(totalAudience), subtitle: `${fmtNum(totals.subscribers)} subs · ${fmtNum(totals.followers)} followers`, gradient: 'purple' },+ { icon: <Eye />, label: 'Total Views', value: fmtNum(totals.views), subtitle: fmtNumFull(totals.views), gradient: 'red' },+ { icon: <VideoIcon />, label: 'Total Content', value: fmtNum(totals.videos + totals.posts), subtitle: `${fmtNum(totals.videos)} videos · ${fmtNum(totals.posts)} IG posts`, gradient: 'blue' },{ icon: <BarChart3 />, label: 'Accounts', value: accounts.length, subtitle: [ytAccounts.length ? `${ytAccounts.length} YouTube` : null, igAccounts.length ? `${igAccounts.length} Instagram` : null, redditAccounts.length ? `${redditAccounts.length} Reddit` : null].filter(Boolean).join(' · '), gradient: 'orange' },].map((card, i) => (<StatCard key={i} {...card} loading={loading} />))}</div>+ {/* Reddit karma summary - separate from audience since karma is not an audience metric */}+ {redditAccounts.length > 0 && (+ <MainCard>+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <Flame className="h-4 w-4 text-orange-500" />+ <span className="text-sm font-semibold">Reddit</span>+ <span className="text-xs text-muted-foreground">{redditAccounts.length} account{redditAccounts.length !== 1 ? 's' : ''}</span>+ </div>+ </div>+ <div className="grid grid-cols-3 gap-4">+ {[+ { label: 'Total Karma', value: fmtNum(totals.karma) },+ { label: 'Post Karma', value: fmtNum(totals.postKarma) },+ { label: 'Comment Karma', value: fmtNum(totals.commentKarma) },+ ].map(item => (+ <div key={item.label} className="text-center p-3 rounded-lg bg-muted/40">+ <p className="text-lg font-bold tabular-nums text-orange-500">{item.value}</p>+ <p className="text-xs text-muted-foreground mt-0.5">{item.label}</p>+ </div>+ ))}+ </div>+ {redditAccounts.length > 1 && (+ <div className="mt-3 space-y-1">+ {[...redditAccounts].sort((a, b) => (b.totalKarma || 0) - (a.totalKarma || 0)).map(a => (+ <button+ key={a.id}+ onClick={() => navigate(`/reddit/${a.id}`)}+ className="w-full flex items-center justify-between px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left"+ >+ <span className="text-sm font-medium">u/{a.username}</span>+ <span className="text-sm tabular-nums text-muted-foreground">{fmtNum(a.totalKarma)} karma</span>+ </button>+ ))}+ </div>+ )}+ </MainCard>+ )}+{accounts.length === 0 ? (<MainCard><div className="flex flex-col items-center text-center py-12 gap-4">@@ -129,7 +173,7 @@ export default function Overview() {<div><h3 className="text-lg font-semibold">Welcome to Twiligent</h3><p className="text-sm text-muted-foreground mt-1 max-w-sm">- Add your first YouTube channel or Instagram account to start tracking analytics+ Add your first YouTube channel, Instagram account, or Reddit profile to start tracking analytics</p></div><Button onClick={() => navigate('/accounts')}>Add Account</Button>@@ -137,8 +181,8 @@ export default function Overview() {</MainCard>) : (<>- {/* Charts */}- <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">+ {/* Audience charts - YouTube + Instagram only */}+ {nonRedditAccounts.length > 0 && <div className="grid grid-cols-1 xl:grid-cols-3 gap-4"><MainCard title="Audience Comparison" className="xl:col-span-2"><ResponsiveContainer width="100%" height={260} debounce={200}><AreaChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>@@ -173,38 +217,29 @@ export default function Overview() {</PieChart></ResponsiveContainer></MainCard>- </div>+ </div>}- {/* Leaderboards */}+ {nonRedditAccounts.length > 0 && (<div className="grid grid-cols-1 md:grid-cols-2 gap-4">{[{title: 'Top by Audience',list: sorted.byAudience,- metric: a => {- if (a.platform === 'instagram') return `${fmtNum(a.followersCount)} followers`;- if (a.platform === 'reddit') return `${fmtNum(a.totalKarma)} karma`;- return `${fmtNum(a.subscriberCount)} subs`;- },+ metric: a => a.platform === 'instagram' ? `${fmtNum(a.followersCount)} followers` : `${fmtNum(a.subscriberCount)} subs`,},{title: 'Top by Content',- list: sorted.byContent.filter(a => a.platform !== 'reddit'),+ list: sorted.byContent,metric: a => a.platform === 'instagram' ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views`,},].map(({ title, list, metric }) => (<MainCard key={title} title={title}><div className="space-y-1">{list.map((a, i) => {- const ig = a.platform === 'instagram';- const reddit = a.platform === 'reddit';- const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';- const fallbackBg = ig ? 'bg-pink-500' : reddit ? 'bg-orange-500' : 'bg-red-500';- const badgeCls = ig- ? 'border-pink-200 bg-pink-50 text-pink-700'- ? 'border-orange-200 bg-orange-50 text-orange-700'- : 'border-green-200 bg-green-50 text-green-700';+ const ig = a.platform === 'instagram';+ const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';+ const fallbackBg = ig ? 'bg-pink-500' : 'bg-red-500';+ const badgeCls = ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-green-200 bg-green-50 text-green-700';return (<buttonkey={a.id}@@ -229,8 +264,9 @@ export default function Overview() {</MainCard>))}</div>+ )}- {/* All accounts table */}+ {nonRedditAccounts.length > 0 && (<MainCard title="All Accounts" content={false}><Table><TableHeader>@@ -246,15 +282,10 @@ export default function Overview() {</TableHeader><TableBody>{sorted.byAudience.map((a, i) => {- const ig = a.platform === 'instagram';- const reddit = a.platform === 'reddit';+ const ig = a.platform === 'instagram';const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';- const fallbackBg = ig ? 'bg-pink-500' : reddit ? 'bg-orange-500' : 'bg-red-500';- const platformBadgeCls = ig- ? 'border-pink-200 bg-pink-50 text-pink-700'- ? 'border-orange-200 bg-orange-50 text-orange-700'- : 'border-red-200 bg-red-50 text-red-700';+ const fallbackBg = ig ? 'bg-pink-500' : 'bg-red-500';+ const platformBadgeCls = ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-red-200 bg-red-50 text-red-700';return (<TableRow key={a.id} className="cursor-pointer" onClick={() => handleViewChannel(a)}><TableCell>@@ -271,22 +302,22 @@ export default function Overview() {<div><p className="text-sm font-semibold leading-none">{a.title}</p><p className="text-xs text-muted-foreground mt-0.5">- {ig ? `@${a.username || ''}` : reddit ? `u/${a.username || ''}` : (a.customUrl || a.channelId || '')}+ {ig ? `@${a.username || ''}` : (a.customUrl || a.channelId || '')}</p></div></div></TableCell><TableCell className="text-center"><Badge variant="outline" className={`text-xs ${platformBadgeCls}`}>- {ig ? 'Instagram' : reddit ? 'Reddit' : 'YouTube'}+ {ig ? 'Instagram' : 'YouTube'}</Badge></TableCell><TableCell className="text-right">- <p className="text-sm font-semibold">{fmtNum(ig ? a.followersCount : reddit ? a.totalKarma : a.subscriberCount)}</p>- <p className="text-xs text-muted-foreground">{ig ? 'followers' : reddit ? 'karma' : 'subscribers'}</p>+ <p className="text-sm font-semibold">{fmtNum(ig ? a.followersCount : a.subscriberCount)}</p>+ <p className="text-xs text-muted-foreground">{ig ? 'followers' : 'subscribers'}</p></TableCell><TableCell className="text-right text-sm">- {ig ? `${fmtNum(a.mediaCount)} posts` : reddit ? `${fmtNum(a.postKarma)} post karma` : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`}+ {ig ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`}</TableCell><TableCell className="text-right text-xs text-muted-foreground">{timeAgo(a.lastUpdated)}@@ -305,6 +336,7 @@ export default function Overview() {</TableBody></Table></MainCard>+ )}</>)}</div>diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsxindex c1a4c5b..5bf7660 100644--- a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx@@ -20,7 +20,7 @@ import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters'import {ArrowLeft, RefreshCw, TrendingUp, MessageSquare, Award, BarChart2,Calendar, Clock, Zap, Flame, Trophy, ExternalLink, FileText, Link2,- Image, Video,+ Image, Video, Star,} from 'lucide-react';const REDDIT_COLORS = ['#FF4500', '#FF6534', '#FF8C00', '#FFA500', '#FFB347', '#FFC080'];@@ -124,7 +124,7 @@ export default function RedditAnalytics() {<h1 className="text-xl font-bold">u/{p.username || account.username}</h1>{p.isGold && <Badge className="bg-yellow-500 text-white text-xs">Gold</Badge>}{p.verified && <Badge className="bg-blue-500 text-white text-xs">Verified</Badge>}- {p.isMod && <Badge variant="outline" className="text-xs">Mod</Badge>}+ {p.isMod && <Badge variant="outline" className="text-xs">Moderator</Badge>}</div><p className="text-sm text-muted-foreground mt-0.5">Reddit account@@ -156,19 +156,26 @@ export default function RedditAnalytics() {</Button></div></div>+ </MainCard>- <Separator className="my-4" />-- {/* Karma breakdown */}- <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">+ {/* Karma - separate from profile since it's the key engagement metric on Reddit */}+ <MainCard>+ <div className="flex items-center gap-2 mb-4">+ <Flame className="h-4 w-4 text-orange-500" />+ <span className="text-sm font-semibold">Karma</span>+ <span className="text-xs text-muted-foreground">earned across posts and comments</span>+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">{[- { label: 'Total Karma', value: fmtNum(p.totalKarma) },- { label: 'Post Karma', value: fmtNum(p.postKarma) },- { label: 'Comment Karma', value: fmtNum(p.commentKarma) },+ { label: 'Total Karma', value: fmtNum(p.totalKarma), sub: fmtNumFull(p.totalKarma) },+ { label: 'Post Karma', value: fmtNum(p.postKarma), sub: 'from submitted posts' },+ { label: 'Comment Karma', value: fmtNum(p.commentKarma), sub: 'from comments' },+ { label: 'Awardee Karma', value: fmtNum(p.awardeeKarma ?? 0), sub: 'from received awards' },].map(item => (<div key={item.label} className="text-center p-3 rounded-lg bg-muted/40">- <p className="text-xl font-bold tabular-nums">{item.value}</p>- <p className="text-xs text-muted-foreground mt-0.5">{item.label}</p>+ <p className="text-xl font-bold tabular-nums text-orange-500">{item.value}</p>+ <p className="text-xs font-medium mt-0.5">{item.label}</p>+ <p className="text-[10px] text-muted-foreground mt-0.5">{item.sub}</p></div>))}</div>@@ -176,10 +183,10 @@ export default function RedditAnalytics() {{/* KPI cards */}<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">- <StatCard icon={<TrendingUp />} label="Posts Analyzed" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in last 30 days`} gradient="orange" />- <StatCard icon={<Award />} label="Total Score" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />- <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={`Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" />- <StatCard icon={<BarChart2 />} label="Upvote Rate" value={`${a.avgUpvoteRatio ?? 0}%`} subtitle="average upvote ratio" gradient="purple" />+ <StatCard icon={<TrendingUp />} label="Posts Fetched" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} gradient="orange" />+ <StatCard icon={<Award />} label="Total Score" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />+ <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={`Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" />+ <StatCard icon={<Star />} label="Awards Received" value={fmtNum(a.totalAwards ?? 0)} subtitle={`Avg ${a.avgAwards ?? 0} per post`} gradient="purple" /></div>{/* Score timeline + media type pie */}@@ -219,39 +226,41 @@ export default function RedditAnalytics() {</div>)}- {/* Activity scores */}+ {/* Detailed metrics */}<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">- <MainCard title="Post Activity">+ <MainCard title="Posting Frequency"><div className="space-y-3">{[- { label: 'Last 7 days', value: a.postsLast7Days },- { label: 'Last 30 days', value: a.postsLast30Days },- { label: 'Last 90 days', value: a.postsLast90Days },+ { label: 'Last 7 days', value: `${a.postsLast7Days} posts` },+ { label: 'Last 30 days', value: `${a.postsLast30Days} posts` },+ { label: 'Last 90 days', value: `${a.postsLast90Days} posts` },].map(item => (<div key={item.label} className="flex items-center justify-between"><span className="text-sm text-muted-foreground">{item.label}</span>- <span className="text-sm font-semibold tabular-nums">{item.value} posts</span>+ <span className="text-sm font-semibold tabular-nums">{item.value}</span></div>))}<Separator /><div className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">Per week (avg)</span>- <span className="text-sm font-semibold">{a.postFrequency?.perWeek ?? 0}</span>+ <span className="text-sm text-muted-foreground">Avg per week</span>+ <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perWeek ?? 0}</span></div><div className="flex items-center justify-between">- <span className="text-sm text-muted-foreground">Per month (avg)</span>- <span className="text-sm font-semibold">{a.postFrequency?.perMonth ?? 0}</span>+ <span className="text-sm text-muted-foreground">Avg per month</span>+ <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perMonth ?? 0}</span></div></div></MainCard>- <MainCard title="Score Distribution">+ <MainCard title="Score Breakdown"><div className="space-y-3">{[- { label: 'Avg score', value: fmtNum(a.avgScore) },- { label: 'Median score', value: fmtNum(a.medianScore) },- { label: 'Best score', value: fmtNum(a.topPosts?.[0]?.score) },- { label: 'Avg upvote %', value: `${a.avgUpvoteRatio ?? 0}%` },+ { label: 'Average score', value: fmtNum(a.avgScore) },+ { label: 'Median score', value: fmtNum(a.medianScore) },+ { label: 'Best single post', value: fmtNum(a.topPosts?.[0]?.score) },+ { label: 'Avg upvote ratio', value: `${a.avgUpvoteRatio ?? 0}%` },+ { label: 'Total comments', value: fmtNum(a.totalComments) },+ { label: 'Avg comments', value: fmtNum(a.avgComments) },].map(item => (<div key={item.label} className="flex items-center justify-between"><span className="text-sm text-muted-foreground">{item.label}</span>@@ -261,11 +270,11 @@ export default function RedditAnalytics() {</div></MainCard>- <MainCard title="Performance Scores">+ <MainCard title="Performance Indicators"><div className="space-y-4">{[- { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Peak vs average score ratio' },- { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Score reliability across posts' },+ { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Ratio of peak post score to average - higher means bigger outlier hits' },+ { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Score reliability across posts - 100 means very uniform performance' },].map(item => (<div key={item.label} className="space-y-1.5"><div className="flex items-center justify-between text-sm">diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx b/frontend/src/features/analytics/reddit/RedditPostsAll.jsxnew file mode 100644index 0000000..3cb3fcd--- /dev/null+++ b/frontend/src/features/analytics/reddit/RedditPostsAll.jsx@@ -0,0 +1,327 @@+import React, { useState, useEffect, useMemo } from 'react';+import { useNavigate } from 'react-router-dom';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Badge } from '@/components/ui/badge';+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';+import { Spinner } from '@/components/ui/spinner';+import StatCard from '../../../components/ui/StatCard';+import MainCard from '../../../components/MainCard';+import { useAppContext } from '../../../context/AppContext';+import { api } from '../../../services/api';+import { fmtNum, fmtDate } from '../../../utils/formatters';+import {+ Search, ExternalLink, TrendingUp, MessageSquare, FileText,+ Image, Video, Link2, Award, RefreshCw,+} from 'lucide-react';++const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };+const SORT_OPTIONS = [+ { value: 'score-desc', label: 'Score (high to low)' },+ { value: 'score-asc', label: 'Score (low to high)' },+ { value: 'comments-desc', label: 'Comments (most)' },+ { value: 'date-desc', label: 'Newest first' },+ { value: 'date-asc', label: 'Oldest first' },+];++function MediaTypeIcon({ type }) {+ const props = { className: 'h-3.5 w-3.5' };+ if (type === 'image') return <Image {...props} />;+ if (type === 'video') return <Video {...props} />;+ if (type === 'link') return <Link2 {...props} />;+ return <FileText {...props} />;+}++export default function RedditPostsAll() {+ const { accounts, showToast } = useAppContext();+ const navigate = useNavigate();++ const redditAccounts = accounts.filter(a => a.platform === 'reddit');++ const [posts, setPosts] = useState([]);+ const [loading, setLoading] = useState(false);+ const [refreshing, setRefreshing] = useState(false);+ const [query, setQuery] = useState('');+ const [sort, setSort] = useState('score-desc');+ const [accountFilter, setAccountFilter] = useState('all');+ const [subFilter, setSubFilter] = useState('all');++ const loadPosts = async () => {+ if (redditAccounts.length === 0) return;+ setLoading(true);+ try {+ const results = await Promise.allSettled(+ redditAccounts.map(acc => api.getRedditPosts(acc.id).then(data => ({+ accountId: acc.id,+ username: acc.username,+ iconUrl: acc.iconUrl,+ posts: Array.isArray(data) ? data : [],+ })))+ );+ const combined = [];+ results.forEach(r => {+ if (r.status === 'fulfilled') {+ r.value.posts.forEach(post => combined.push({+ ...post,+ accountId: r.value.accountId,+ accountUsername: r.value.username,+ accountIconUrl: r.value.iconUrl,+ }));+ } else {+ showToast('Failed to load posts for one account: ' + r.reason?.message, 'error');+ }+ });+ setPosts(combined);+ } catch (err) {+ showToast('Failed to load Reddit posts: ' + err.message, 'error');+ } finally {+ setLoading(false);+ }+ };++ useEffect(() => { loadPosts(); }, [redditAccounts.length]);++ const handleRefresh = async () => {+ setRefreshing(true);+ await loadPosts();+ setRefreshing(false);+ };++ const subreddits = useMemo(() => {+ const seen = new Set();+ posts.forEach(p => seen.add(p.subreddit));+ return Array.from(seen).sort();+ }, [posts]);++ const filtered = useMemo(() => {+ let result = posts;+ if (accountFilter !== 'all') result = result.filter(p => p.accountId === accountFilter);+ if (subFilter !== 'all') result = result.filter(p => p.subreddit === subFilter);+ if (query.trim()) {+ const q = query.toLowerCase();+ result = result.filter(p =>+ p.title.toLowerCase().includes(q) ||+ p.subreddit.toLowerCase().includes(q) ||+ (p.flair || '').toLowerCase().includes(q) ||+ p.accountUsername.toLowerCase().includes(q)+ );+ }+ return [...result].sort((a, b) => {+ if (sort === 'score-desc') return b.score - a.score;+ if (sort === 'score-asc') return a.score - b.score;+ if (sort === 'comments-desc') return b.numComments - a.numComments;+ if (sort === 'date-desc') return new Date(b.createdAt) - new Date(a.createdAt);+ if (sort === 'date-asc') return new Date(a.createdAt) - new Date(b.createdAt);+ return 0;+ });+ }, [posts, query, sort, accountFilter, subFilter]);++ const totals = useMemo(() => ({+ posts: filtered.length,+ score: filtered.reduce((s, p) => s + p.score, 0),+ comments: filtered.reduce((s, p) => s + p.numComments, 0),+ }), [filtered]);++ if (redditAccounts.length === 0) {+ return (+ <div className="space-y-6">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">Reddit Posts</h1>+ <p className="text-sm text-muted-foreground mt-0.5">Posts from all connected Reddit accounts</p>+ </div>+ <MainCard>+ <div className="flex flex-col items-center text-center py-12 gap-4">+ <p className="text-sm text-muted-foreground">No Reddit accounts connected.</p>+ <Button onClick={() => navigate('/accounts')}>Add Reddit Account</Button>+ </div>+ </MainCard>+ </div>+ );+ }++ return (+ <div className="space-y-6">+ <div className="flex items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">Reddit Posts</h1>+ <p className="text-sm text-muted-foreground mt-0.5">+ {loading ? 'Loading...' : `${filtered.length} of ${posts.length} posts across ${redditAccounts.length} account${redditAccounts.length !== 1 ? 's' : ''}`}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ className="gap-2 shrink-0"+ onClick={handleRefresh}+ disabled={loading || refreshing}+ >+ <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />+ Refresh+ </Button>+ </div>++ {loading ? (+ <div className="flex items-center justify-center min-h-[40vh]">+ <div className="flex flex-col items-center gap-3">+ <Spinner className="size-10" />+ <p className="text-sm text-muted-foreground">Loading posts from {redditAccounts.length} account{redditAccounts.length !== 1 ? 's' : ''}...</p>+ </div>+ </div>+ ) : (+ <>+ {/* Summary stats */}+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">+ <StatCard icon={<TrendingUp />} label="Posts Shown" value={fmtNum(totals.posts)} subtitle={`${posts.length} total fetched`} gradient="orange" />+ <StatCard icon={<Award />} label="Combined Score" value={fmtNum(totals.score)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.score / filtered.length))} per post` : ''} gradient="red" />+ <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(totals.comments)} subtitle={filtered.length > 0 ? `Avg ${fmtNum(Math.round(totals.comments / filtered.length))} per post` : ''} gradient="blue" />+ </div>++ {/* Filters */}+ <MainCard>+ <div className="flex flex-col sm:flex-row gap-3">+ <div className="relative flex-1">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />+ <Input+ placeholder="Search posts..."+ value={query}+ onChange={e => setQuery(e.target.value)}+ className="pl-9"+ />+ </div>++ {redditAccounts.length > 1 && (+ <Select value={accountFilter} onValueChange={setAccountFilter}>+ <SelectTrigger className="w-full sm:w-48">+ <SelectValue placeholder="All accounts" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All accounts</SelectItem>+ {redditAccounts.map(a => (+ <SelectItem key={a.id} value={a.id}>u/{a.username}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}++ <Select value={subFilter} onValueChange={setSubFilter}>+ <SelectTrigger className="w-full sm:w-48">+ <SelectValue placeholder="All subreddits" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All subreddits</SelectItem>+ {subreddits.map(s => (+ <SelectItem key={s} value={s}>r/{s}</SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Select value={sort} onValueChange={setSort}>+ <SelectTrigger className="w-full sm:w-52">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {SORT_OPTIONS.map(o => (+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </MainCard>++ {/* Posts table */}+ <MainCard content={false}>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-8">#</TableHead>+ <TableHead>Post</TableHead>+ {redditAccounts.length > 1 && <TableHead className="w-36">Account</TableHead>}+ <TableHead className="w-24">Type</TableHead>+ <TableHead className="text-right w-24">Score</TableHead>+ <TableHead className="text-right w-28">Comments</TableHead>+ <TableHead className="text-right w-20">Upvote %</TableHead>+ <TableHead className="text-right w-28">Date</TableHead>+ <TableHead className="w-8" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {filtered.length === 0 ? (+ <TableRow>+ <TableCell colSpan={redditAccounts.length > 1 ? 9 : 8} className="text-center text-muted-foreground py-12">+ No posts match the current filters+ </TableCell>+ </TableRow>+ ) : (+ filtered.map((post, i) => (+ <TableRow key={`${post.accountId}-${post.id}`}>+ <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>+ <TableCell>+ <div className="max-w-md">+ <p className="text-sm font-medium leading-snug line-clamp-2">{post.title}</p>+ <div className="flex items-center gap-2 mt-0.5">+ <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>+ {post.flair && (+ <Badge variant="outline" className="text-[10px] px-1 py-0 h-4">+ {post.flair}+ </Badge>+ )}+ {post.isNsfw && (+ <Badge className="text-[10px] px-1 py-0 h-4 bg-red-100 text-red-700 border-red-200">+ NSFW+ </Badge>+ )}+ </div>+ </div>+ </TableCell>+ {redditAccounts.length > 1 && (+ <TableCell>+ <button+ onClick={() => navigate(`/reddit/${post.accountId}`)}+ className="flex items-center gap-1.5 hover:underline"+ >+ <Avatar className="h-5 w-5 flex-shrink-0">+ <AvatarImage src={post.accountIconUrl} />+ <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">+ {(post.accountUsername || '?').slice(0, 2).toUpperCase()}+ </AvatarFallback>+ </Avatar>+ <span className="text-xs">u/{post.accountUsername}</span>+ </button>+ </TableCell>+ )}+ <TableCell>+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <MediaTypeIcon type={post.mediaType} />+ <span>{MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}</span>+ </div>+ </TableCell>+ <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">+ {fmtNum(post.score)}+ </TableCell>+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>+ <TableCell className="text-right text-sm tabular-nums">+ {Math.round((post.upvoteRatio ?? 0) * 100)}%+ </TableCell>+ <TableCell className="text-right text-xs text-muted-foreground">+ {fmtDate(post.createdAt)}+ </TableCell>+ <TableCell>+ <a href={post.permalink} target="_blank" rel="noopener noreferrer">+ <Button variant="ghost" size="icon" className="size-7">+ <ExternalLink className="h-3.5 w-3.5" />+ </Button>+ </a>+ </TableCell>+ </TableRow>+ ))+ )}+ </TableBody>+ </Table>+ </MainCard>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsxindex 009a5fc..44482b2 100644--- a/frontend/src/layout/Sidebar.jsx+++ b/frontend/src/layout/Sidebar.jsx@@ -8,7 +8,7 @@ import {import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import {LayoutDashboard, PlaySquare, Scissors, Camera,- Upload, Users, Settings,+ Upload, Users, Settings, Flame,} from 'lucide-react';import { useAppContext } from '../context/AppContext';@@ -16,10 +16,11 @@ const NAV_GROUPS = [{label: 'Analytics',items: [- { path: '/', label: 'Overview', icon: LayoutDashboard },- { path: '/videos', label: 'All Videos', icon: PlaySquare },- { path: '/shorts', label: 'Shorts', icon: Scissors },- { path: '/reels', label: 'IG Content', icon: Camera },+ { path: '/', label: 'Overview', icon: LayoutDashboard },+ { path: '/videos', label: 'All Videos', icon: PlaySquare },+ { path: '/shorts', label: 'Shorts', icon: Scissors },+ { path: '/reels', label: 'IG Content', icon: Camera },+ { path: '/reddit-posts', label: 'Reddit Posts', icon: Flame },],},{