Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(overview): fix UI overlap, add analytics cache warming for YouTube and Instagram
spacesdrive838f15e76b9a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 019c0d5..b06d1f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- Reddit section card removed; Reddit data fully integrated into the tab views- Accounts tab now shows all accounts including Reddit in a unified table+**Overview metrics fixed**+- New `/api/overview` backend endpoint reads per-account analytics from Redis cache (YouTube video likes/comments, Instagram media likes/comments, Reddit account posts/score/comments)+- Total Comments and Total Likes now include YouTube channel video data and Instagram media data, not just tracked content+- Total Content now includes Reddit account posts from analytics cache+- Audience Comparison changed from BarChart to AreaChart with gradient fill and platform-colored custom dots per account+- Top by Audience list simplified: shows rank, avatar, account name, and platform badge only (no metric value)+- Tab trigger subtitles now truncated cleanly; no visual overflow between adjacent triggers+- When any account's analytics cache is cold, backend fires a background warm-up task (YouTube fetchAllVideos, Instagram fetchInstagramMedia); frontend shows "Syncing analytics..." and auto-refreshes after 6 seconds+### Removed**X (Twitter) integration removed**diff --git a/backend/routes/overview.js b/backend/routes/overview.jsindex 7f7edcf..c5e7be3 100644--- a/backend/routes/overview.js+++ b/backend/routes/overview.js@@ -1,6 +1,8 @@import { Hono } from 'hono';-import { getTrackedPosts } from '../lib/db.js';-import { getVideosCache, getIGCache, getRedditCache } from '../lib/cache.js';+import { getAccounts, getTrackedPosts } from '../lib/db.js';+import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache } from '../lib/cache.js';+import { fetchAllVideos } from '../services/youtube.js';+import { fetchInstagramMedia } from '../services/instagram.js';const router = new Hono();@@ -8,49 +10,84 @@ router.get('/overview', async (c) => {const userId = c.get('userId');const supabase = c.get('supabase');const redis = c.get('redis');+ const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();try {- const [accounts, tracked] = await Promise.all([- supabase.from('accounts').select('id, platform, data').eq('user_id', userId),+ const [rawAccounts, tracked] = await Promise.all([+ getAccounts(supabase, userId),getTrackedPosts(supabase, userId),]);- if (accounts.error) throw accounts.error;- const rawAccounts = (accounts.data || []).map(row => ({ id: row.id, platform: row.platform, ...row.data }));+ const warmTasks = [];const cacheResults = await Promise.allSettled(rawAccounts.map(async (a) => {if (a.platform === 'reddit') {const cached = await getRedditCache(redis, userId, a.id);- if (!cached?.analytics) return { id: a.id };+ if (!cached?.analytics) return { id: a.id, cacheWarmed: false };return {id: a.id,+ cacheWarmed: true,fetchedPosts: cached.analytics.fetchedPosts ?? 0,- totalScore: cached.analytics.totalScore ?? 0,+ totalScore: cached.analytics.totalScore ?? 0,totalComments: cached.analytics.totalComments ?? 0,};}+if (a.platform === 'instagram') {const cached = await getIGCache(redis, userId, a.id);const media = cached?.media ?? [];- if (!media.length) return { id: a.id };+ if (!media.length) {+ if (redis && a.igUserId && a.accessToken) {+ warmTasks.push(+ fetchInstagramMedia(a.igUserId, a.accessToken, 500)+ .then(m => setIGCache(redis, userId, a.id, { media: m, fetchedAt: new Date().toISOString() }))+ .catch(() => {})+ );+ }+ return { id: a.id, cacheWarmed: false };+ }return {id: a.id,- totalLikes: media.reduce((s, m) => s + (m.likeCount ?? 0), 0),+ cacheWarmed: true,+ totalLikes: media.reduce((s, m) => s + (m.likeCount ?? 0), 0),totalComments: media.reduce((s, m) => s + (m.commentsCount ?? 0), 0),};}++ // YouTubeconst cached = await getVideosCache(redis, userId, a.id);const videos = cached?.videos ?? [];- if (!videos.length) return { id: a.id };+ if (!videos.length) {+ if (redis && apiKey && a.uploadsPlaylistId) {+ warmTasks.push(+ fetchAllVideos(a.uploadsPlaylistId, apiKey, 10)+ .then(v => setVideosCache(redis, userId, a.id, { videos: v, fetchedAt: new Date().toISOString() }))+ .catch(() => {})+ );+ }+ return { id: a.id, cacheWarmed: false };+ }return {id: a.id,- totalLikes: videos.reduce((s, v) => s + (v.likeCount ?? 0), 0),+ cacheWarmed: true,+ totalLikes: videos.reduce((s, v) => s + (v.likeCount ?? 0), 0),totalComments: videos.reduce((s, v) => s + (v.commentCount ?? 0), 0),};}));+ // Fire warming tasks without blocking the response.+ // The client will auto-refresh after a short delay when cacheWarmed: false is detected.+ if (warmTasks.length > 0) {+ const ctx = c.executionCtx;+ if (ctx?.waitUntil) {+ ctx.waitUntil(Promise.allSettled(warmTasks));+ } else {+ Promise.allSettled(warmTasks).catch(() => {});+ }+ }+const analyticsCache = {};cacheResults.forEach(r => {if (r.status === 'fulfilled' && r.value?.id) {diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex 86d6411..0354213 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -64,6 +64,23 @@ export default function Overview() {.finally(() => setOverviewLoading(false));}, []);+ // When the backend returns cacheWarmed: false for any account, it has fired a background+ // analytics fetch. Auto-refresh once after 6 seconds to pick up the newly warmed data.+ const isSyncing = !overviewLoading && accounts.some(a => {+ const entry = overviewData.analyticsCache[a.id];+ return entry?.cacheWarmed === false;+ });++ useEffect(() => {+ if (!isSyncing) return;+ const timer = setTimeout(() => {+ api.getOverview()+ .then(data => { if (data && !data.error) setOverviewData(data); })+ .catch(() => {});+ }, 6000);+ return () => clearTimeout(timer);+ }, [isSyncing]);+const loading = accountsLoading || overviewLoading;const trackedContent = overviewData.tracked ?? [];const analyticsCache = overviewData.analyticsCache ?? {};@@ -221,7 +238,7 @@ export default function Overview() {else navigate(`/channel/${acc.id}`);}- const tabTriggerCls = 'flex flex-col items-start gap-0 h-auto py-3 px-4 text-left min-w-[140px]';+ const tabTriggerCls = 'flex flex-col items-start gap-0 h-auto py-3 px-4 text-left w-[175px] overflow-hidden';return (<div className="space-y-6">@@ -240,15 +257,23 @@ export default function Overview() {].filter(Boolean).join(' · ')}</p></div>- <Button- onClick={refreshAll}- disabled={loading || accounts.length === 0}- size="sm"- className="gap-2 shrink-0"- >- <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />- {loading ? 'Refreshing...' : 'Refresh All'}- </Button>+ <div className="flex items-center gap-2 shrink-0">+ {isSyncing && (+ <span className="text-xs text-muted-foreground flex items-center gap-1.5">+ <RefreshCw className="h-3 w-3 animate-spin" />+ Syncing analytics...+ </span>+ )}+ <Button+ onClick={refreshAll}+ disabled={loading || accounts.length === 0}+ size="sm"+ className="gap-2"+ >+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />+ {loading ? 'Refreshing...' : 'Refresh All'}+ </Button>+ </div></div>{loading && <Progress className="h-1" value={undefined} />}@@ -275,43 +300,42 @@ export default function Overview() {<TabsList className="w-max flex gap-1 bg-muted/50 p-1 rounded-xl" style={{ height: 'auto' }}><TabsTrigger value="audience" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Audience</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Audience</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalAudience)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">{[- totals.subscribers ? `${fmtNum(totals.subscribers)} subs` : null,- totals.followers ? `${fmtNum(totals.followers)} followers` : null,- totals.karma ? `${fmtNum(totals.karma)} karma` : null,- trackedStats.rdScore ? `${fmtNum(trackedStats.rdScore)} tracked` : null,+ totals.subscribers ? `${fmtNum(totals.subscribers)} subs` : null,+ totals.followers ? `${fmtNum(totals.followers)} followers` : null,+ totals.karma ? `${fmtNum(totals.karma)} karma` : null,].filter(Boolean).join(' · ') || 'no data yet'}</span></TabsTrigger><TabsTrigger value="views" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Views</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Views</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totals.views)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">{ytAccounts.length > 0 ? `${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}` : 'no YouTube accounts'}</span></TabsTrigger><TabsTrigger value="content" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Content</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Content</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalContent)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">{[- totals.videos ? `${fmtNum(totals.videos)} videos` : null,- totals.posts ? `${fmtNum(totals.posts)} IG posts` : null,- cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,- trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,+ totals.videos ? `${fmtNum(totals.videos)} videos` : null,+ totals.posts ? `${fmtNum(totals.posts)} IG posts` : null,+ cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,+ trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,].filter(Boolean).join(' · ') || 'no content yet'}</span></TabsTrigger><TabsTrigger value="accounts" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Accounts</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Accounts</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{accounts.length}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">{[ytAccounts.length ? `${ytAccounts.length} YouTube` : null,igAccounts.length ? `${igAccounts.length} Instagram` : null,@@ -321,18 +345,18 @@ export default function Overview() {</TabsTrigger><TabsTrigger value="comments" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Comments</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Comments</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalComments)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">- {totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'}+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">+ {isSyncing ? 'syncing analytics...' : totalComments > 0 ? 'across all platforms' : 'visit analytics pages to load'}</span></TabsTrigger><TabsTrigger value="likes" className={tabTriggerCls}>- <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">Total Likes</span>+ <span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide truncate w-full">Total Likes</span><span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalLikes)}</span>- <span className="text-[11px] text-muted-foreground mt-0.5">- {totalLikes > 0 ? 'across all platforms' : 'visit analytics pages to load'}+ <span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">+ {isSyncing ? 'syncing analytics...' : totalLikes > 0 ? 'across all platforms' : 'visit analytics pages to load'}</span></TabsTrigger>