Skip to content

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(analytics): show Instagram reels, posts, videos and views by type

spacesdrive5dfd8e0a3778
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 333012f..2366ba0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,8 +7,24 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]
+### Fixed
+
+**Instagram Reels counted as Videos**
+- Reels were labelled Videos everywhere because the backend only requested `media_type`, which Instagram reports as `VIDEO` for reels, and checked for a `REEL` value the API never returns
+- Media is now classified from `media_product_type` into exactly one of Reels, Posts (photos and carousels), or Videos (in-feed videos), with a `/reel/` permalink fallback and case-insensitive matching
+- IG Content Explorer: Newest First sorting works, Best Engagement is (likes + comments) / views, and filter dropdowns show their labels instead of raw values
+- Cached Instagram media from older versions is refetched automatically
+
### Added
+**Instagram views by content type**
+- Views are fetched from the Instagram `views` insight alongside media, with no extra requests per item; items without insights show `-` instead of 0
+- Instagram analytics page: Total Views plus Reels, Posts, and Videos cards; views columns in the top posts and content type tables
+- IG Content Explorer: views on every card, per-type count and view totals, and a Most Viewed sort
+- Overview: Total Views now includes Instagram views; the Views tab adds an Instagram Views card and a per-account Reels / Posts / Videos views table; the Content tab breaks Instagram content down by type
+- Backend unit tests for classification, views parsing, pagination fallback, and per-type totals (`cd backend && npm test`)
+
+
**Images on tracked Reddit posts**
- Reddit's public JSON API carries no usable thumbnail, so a screenshot can now be uploaded per tracked Reddit post
- The browser posts the file directly to Cloudinary with the unsigned preset and sends only the returned `secure_url`, keeping the Worker free of binary uploads as the architecture requires
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 16622da..c2c0dcb 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -2,7 +2,13 @@
## Current State
-This project has no automated test suite. Testing is currently manual. This is a known gap - see ROADMAP.md.
+Most testing is manual. The backend has unit tests for pure service logic using Node's built-in test runner (no dependencies). Broader coverage is a known gap - see ROADMAP.md.
+
+```bash
+cd backend && npm test
+```
+
+Test files sit next to the module they cover as `*.test.js` (for example `services/instagram.test.js`). Wrangler only bundles files reachable from `server.js`, so test files never ship in the Worker.
The testing workflow documented here describes what should run before shipping any change.
@@ -67,6 +73,9 @@ Open the app in a browser. For each changed area, test:
- [ ] Overview page loads with correct totals
- [ ] Channel analytics page loads for a YouTube account
- [ ] Instagram analytics page loads for an Instagram account
+- [ ] Reels show as Reels (not Videos) on the Instagram analytics page and IG Content Explorer; Reels, Posts, and Videos counts add up to the items analyzed
+- [ ] Views appear per content type; items without insights show `-`
+- [ ] Overview Total Views includes Instagram views, and the Views tab shows the per-account content type table
- [ ] Video explorer shows all videos, filtering works
**Publishing (if changed):**
diff --git a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
index e82053c..8ed04cd 100644
--- a/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
+++ b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
@@ -18,15 +18,16 @@ import MainCard from '../../../components/MainCard';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';
import {
ArrowLeft, RefreshCw, Heart, MessageCircle, Users, UserPlus, Image,
TrendingUp, Calendar, Clock, Zap, Flame, Trophy, Star, Camera,
- ExternalLink, BarChart2, Hash,
+ ExternalLink, BarChart2, Hash, Eye, Clapperboard, Film,
} from 'lucide-react';
const IG_COLORS = ['#F58529', '#DD2A7B', '#8134AF', '#515BD4', '#FEDA77', '#405DE6'];
-const MEDIA_TYPE_NAMES = { IMAGE: 'Photos', VIDEO: 'Videos', CAROUSEL_ALBUM: 'Carousels', REEL: 'Reels' };
-const MEDIA_TYPE_COLORS = { IMAGE: '#F58529', VIDEO: '#DD2A7B', CAROUSEL_ALBUM: '#8134AF', REEL: '#515BD4' };
+const CONTENT_TYPE_ICONS = { reel: <Clapperboard />, post: <Image />, video: <Film /> };
+const CONTENT_TYPE_GRADIENTS = { reel: 'pink', post: 'orange', video: 'purple' };
const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };
@@ -95,13 +96,12 @@ export default function InstagramAnalytics() {
const p = profile || account;
const a = analytics || {};
- const mediaTypeData = a.mediaTypeDistribution
- ? Object.entries(a.mediaTypeDistribution).map(([key, value], i) => ({ name: MEDIA_TYPE_NAMES[key] || key, value, color: MEDIA_TYPE_COLORS[key] || IG_COLORS[i % IG_COLORS.length] }))
- : [];
+ const typeStats = a.contentTypeStats || {};
+ const typeRows = IG_CONTENT_TYPES
+ .filter(type => typeStats[type]?.count > 0)
+ .map(type => ({ type, ...typeStats[type], name: IG_CONTENT_TYPE_META[type].plural, color: IG_CONTENT_TYPE_META[type].color }));
+ const contentMixData = typeRows.map(row => ({ name: row.name, value: row.count, color: row.color }));
const topPostsData = (a.topPosts || []).slice(0, 8).map((post, i) => ({ name: `#${i + 1}`, likes: post.likeCount, comments: post.commentsCount }));
- const perfByTypeData = a.performanceByType
- ? Object.entries(a.performanceByType).map(([type, s]) => ({ name: MEDIA_TYPE_NAMES[type] || type, avgLikes: s.avgLikes, avgComments: s.avgComments, count: s.count, color: MEDIA_TYPE_COLORS[type] || '#999' }))
- : [];
const dayOfWeekData = (a.postsByDayOfWeek || []).map(d => ({ name: d.shortDay, posts: d.posts, avgEngagement: d.avgEngagement, avgLikes: d.avgLikes }));
const timelineData = (a.engagementTimeline || []).map(m => ({ name: m.month, posts: m.posts, likes: m.likes, comments: m.comments, avgLikes: m.avgLikes }));
const captionData = a.captionLengthCorrelation || [];
@@ -146,6 +146,23 @@ export default function InstagramAnalytics() {
<StatCard icon={<MessageCircle />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={fmtNumFull(a.totalComments)} gradient="teal" small />
<StatCard icon={<TrendingUp />} label="Engagement Rate" value={`${a.engagementRate || 0}%`} subtitle={`Avg ${fmtNum(a.avgLikes)} likes/post`} gradient="green" small />
</div>
+ <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
+ <StatCard icon={<Eye />} label="Total Views" value={fmtNum(a.totalViews)} subtitle={`${a.mediaWithViews || 0} of ${a.fetchedPosts || 0} items report views`} gradient="blue" small />
+ {IG_CONTENT_TYPES.map(type => {
+ const stats = typeStats[type] || {};
+ return (
+ <StatCard
+ key={type}
+ icon={CONTENT_TYPE_ICONS[type]}
+ label={IG_CONTENT_TYPE_META[type].plural}
+ value={fmtNum(stats.count)}
+ subtitle={stats.viewsReported > 0 ? `${fmtNum(stats.totalViews)} views, ${fmtNum(stats.avgViews)} avg` : 'no views reported'}
+ gradient={CONTENT_TYPE_GRADIENTS[type]}
+ small
+ />
+ );
+ })}
+ </div>
<div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">
<StatCard icon={<Zap />} label="Avg Likes/Post" value={fmtNum(a.avgLikes)} gradient="cyan" small />
<StatCard icon={<MessageCircle />} label="Avg Comments" value={fmtNum(a.avgComments)} gradient="indigo" small />
@@ -202,11 +219,11 @@ export default function InstagramAnalytics() {
) : <p className="text-sm text-muted-foreground text-center py-10">Not enough data for timeline</p>}
</MainCard>
<MainCard title="Content Type Mix" contentClassName="p-3">
- {mediaTypeData.length > 0 ? (
+ {contentMixData.length > 0 ? (
<ResponsiveContainer width="100%" height={280} debounce={200}>
<PieChart>
- <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={42} paddingAngle={3} strokeWidth={0}>
- {mediaTypeData.map((entry, i) => <Cell key={i} fill={entry.color} />)}
+ <Pie data={contentMixData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={42} paddingAngle={3} strokeWidth={0}>
+ {contentMixData.map((entry, i) => <Cell key={i} fill={entry.color} />)}
</Pie>
<ReTooltip contentStyle={TS} formatter={(v, n) => [`${v} posts`, n]} />
<Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
@@ -219,9 +236,9 @@ export default function InstagramAnalytics() {
{/* Performance by type + Day of week */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<MainCard title="Performance by Content Type" contentClassName="p-3">
- {perfByTypeData.length > 0 ? (
+ {typeRows.length > 0 ? (
<ResponsiveContainer width="100%" height={260} debounce={200}>
- <BarChart data={perfByTypeData}>
+ <BarChart data={typeRows}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
<XAxis dataKey="name" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
<YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} width={44} />
@@ -329,14 +346,15 @@ export default function InstagramAnalytics() {
className="relative aspect-square rounded-lg overflow-hidden border border-border cursor-pointer group hover:shadow-md transition-shadow"
onClick={() => post.permalink && window.open(post.permalink, '_blank')}
>
- <img src={post.thumbnailUrl || post.mediaUrl} className="w-full h-full object-cover" alt=""
+ <img src={post.contentType === 'post' ? (post.thumbnailUrl || post.mediaUrl) : post.thumbnailUrl} className="w-full h-full object-cover" alt=""
onError={e => { e.target.style.display = 'none'; }} />
- {post.mediaType !== 'IMAGE' && (
+ {post.contentType !== 'post' && (
<span className="absolute top-1 right-1 bg-black/65 text-white text-[9px] font-semibold px-1 rounded">
- {MEDIA_TYPE_NAMES[post.mediaType]?.[0] || 'V'}
+ {igContentTypeMeta(post.contentType).label}
</span>
)}
<div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-1 gap-2">
+ <span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><Eye className="h-2.5 w-2.5" />{fmtIGViews(post.viewCount)}</span>
<span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><Heart className="h-2.5 w-2.5" />{fmtNum(post.likeCount)}</span>
<span className="flex items-center gap-0.5 text-white text-[10px] font-semibold"><MessageCircle className="h-2.5 w-2.5" />{fmtNum(post.commentsCount)}</span>
</div>
@@ -355,6 +373,7 @@ export default function InstagramAnalytics() {
<TableHead className="w-8">#</TableHead>
<TableHead>Caption</TableHead>
<TableHead>Type</TableHead>
+ <TableHead className="text-right">Views</TableHead>
<TableHead className="text-right">Likes</TableHead>
<TableHead className="text-right">Comments</TableHead>
<TableHead className="text-right">Engagement</TableHead>
@@ -363,58 +382,66 @@ export default function InstagramAnalytics() {
</TableRow>
</TableHeader>
<TableBody>
- {a.topPosts.slice(0, 10).map((post, i) => (
- <TableRow key={post.id}>
- <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>
- <TableCell className="max-w-[200px]"><p className="text-sm truncate">{post.caption || '(no caption)'}</p></TableCell>
- <TableCell>
- <Badge variant="outline" className="text-[10px] h-5" style={{ borderColor: `${MEDIA_TYPE_COLORS[post.mediaType] || '#999'}50`, color: MEDIA_TYPE_COLORS[post.mediaType] || '#999', background: `${MEDIA_TYPE_COLORS[post.mediaType] || '#999'}10` }}>
- {MEDIA_TYPE_NAMES[post.mediaType] || post.mediaType}
- </Badge>
- </TableCell>
- <TableCell className="text-right text-sm">{fmtNum(post.likeCount)}</TableCell>
- <TableCell className="text-right text-sm">{fmtNum(post.commentsCount)}</TableCell>
- <TableCell className="text-right text-sm">{fmtNum(post.engagement)}</TableCell>
- <TableCell className="text-xs text-muted-foreground">{fmtDate(post.timestamp)}</TableCell>
- <TableCell>
- {post.permalink && (
- <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => window.open(post.permalink, '_blank')}>
- <ExternalLink className="h-3 w-3" />
- </Button>
- )}
- </TableCell>
- </TableRow>
- ))}
+ {a.topPosts.slice(0, 10).map((post, i) => {
+ const meta = igContentTypeMeta(post.contentType);
+ return (
+ <TableRow key={post.id}>
+ <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>
+ <TableCell className="max-w-[200px]"><p className="text-sm truncate">{post.caption || '(no caption)'}</p></TableCell>
+ <TableCell>
+ <Badge variant="outline" className="text-[10px] h-5" style={{ borderColor: `${meta.color}50`, color: meta.color, background: `${meta.color}10` }}>
+ {meta.label}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-right text-sm">{fmtIGViews(post.viewCount)}</TableCell>
+ <TableCell className="text-right text-sm">{fmtNum(post.likeCount)}</TableCell>
+ <TableCell className="text-right text-sm">{fmtNum(post.commentsCount)}</TableCell>
+ <TableCell className="text-right text-sm">{fmtNum(post.engagement)}</TableCell>
+ <TableCell className="text-xs text-muted-foreground">{fmtDate(post.timestamp)}</TableCell>
+ <TableCell>
+ {post.permalink && (
+ <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => window.open(post.permalink, '_blank')}>
+ <ExternalLink className="h-3 w-3" />
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
</TableBody>
</Table>
</MainCard>
)}
{/* Performance by type table */}
- {perfByTypeData.length > 0 && (
+ {typeRows.length > 0 && (
<MainCard title="Performance Summary by Content Type" content={false}>
<Table>
<TableHeader>
<TableRow>
<TableHead>Type</TableHead>
<TableHead className="text-right">Count</TableHead>
+ <TableHead className="text-right">Total Views</TableHead>
+ <TableHead className="text-right">Avg Views</TableHead>
<TableHead className="text-right">Avg Likes</TableHead>
<TableHead className="text-right">Avg Comments</TableHead>
<TableHead className="text-right">Avg Engagement</TableHead>
</TableRow>
</TableHeader>
<TableBody>
- {perfByTypeData.map(row => (
- <TableRow key={row.name}>
+ {typeRows.map(row => (
+ <TableRow key={row.type}>
<TableCell>
<Badge variant="outline" className="text-xs" style={{ borderColor: `${row.color}50`, color: row.color, background: `${row.color}10` }}>
{row.name}
</Badge>
</TableCell>
<TableCell className="text-right">{row.count}</TableCell>
+ <TableCell className="text-right">{row.viewsReported > 0 ? fmtNum(row.totalViews) : '-'}</TableCell>
+ <TableCell className="text-right">{row.viewsReported > 0 ? fmtNum(row.avgViews) : '-'}</TableCell>
<TableCell className="text-right">{fmtNum(row.avgLikes)}</TableCell>
<TableCell className="text-right">{fmtNum(row.avgComments)}</TableCell>
- <TableCell className="text-right">{fmtNum(row.avgLikes + row.avgComments)}</TableCell>
+ <TableCell className="text-right">{fmtNum(row.avgEngagement)}</TableCell>
</TableRow>
))}
</TableBody>
diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsx
index 68dcf3d..1b8f545 100644
--- a/frontend/src/features/analytics/overview/Overview.jsx
+++ b/frontend/src/features/analytics/overview/Overview.jsx
@@ -21,6 +21,7 @@ import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { fmtNum, fmtNumFull, fmtPercent, timeAgo } from '../../../utils/formatters';
import { trackedViews } from '../../../utils/trackedContent';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
import {
RefreshCw, Users, VideoIcon, ExternalLink, Camera, BarChart2, Eye,
Tag, ThumbsUp, MessageSquare, CirclePlay, Flame, BookmarkCheck,
@@ -113,7 +114,10 @@ export default function Overview() {
// Per-account analytics from Redis cache (populated when user visits individual analytics pages)
const cacheTotals = useMemo(() => {
- const result = { ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, rdPosts: 0, rdKarma: 0, rdComments: 0 };
+ const result = {
+ ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, igViews: 0, rdPosts: 0, rdKarma: 0, rdComments: 0,
+ igTypes: Object.fromEntries(IG_CONTENT_TYPES.map(t => [t, { count: 0, views: 0 }])),
+ };
accounts.forEach(a => {
const c = analyticsCache[a.id];
if (!c) return;
@@ -123,6 +127,11 @@ export default function Overview() {
} else if (a.platform === 'instagram') {
result.igLikes += c.totalLikes ?? 0;
result.igComments += c.totalComments ?? 0;
+ result.igViews += c.totalViews ?? 0;
+ IG_CONTENT_TYPES.forEach(t => {
+ result.igTypes[t].count += c.contentTypes?.[t]?.count ?? 0;
+ result.igTypes[t].views += c.contentTypes?.[t]?.views ?? 0;
+ });
} else if (a.platform === 'reddit') {
result.rdPosts += c.fetchedPosts ?? 0;
result.rdKarma += c.totalScore ?? 0;
@@ -157,9 +166,15 @@ export default function Overview() {
// Total Content = YT videos + IG posts + Reddit account posts (from cache) + tracked items
const totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;
- // Total Views = YouTube channel views + tracked video views + manually entered Reddit post views
+ // Total Views = YouTube channel views + Instagram reel, post, and video views + tracked views
const trackedViewTotal = trackedStats.ytViews + trackedStats.rdViews;
- const totalViews = totals.views + trackedViewTotal;
+ const totalViews = totals.views + cacheTotals.igViews + trackedViewTotal;
+ const igTypeSummary = (field) => IG_CONTENT_TYPES
+ .map(t => `${fmtNum(cacheTotals.igTypes[t][field])} ${IG_CONTENT_TYPE_META[t].plural.toLowerCase()}`)
+ .join(' · ');
+ const igAccountRows = igAccounts
+ .map(a => ({ account: a, cache: analyticsCache[a.id] }))
+ .sort((x, y) => (y.cache?.totalViews ?? 0) - (x.cache?.totalViews ?? 0));
// Tracked items are third-party URLs the user monitors, never their own account content,
// so cache totals and tracked totals are disjoint and sum without double-counting.
@@ -387,8 +402,9 @@ export default function Overview() {
<span className="text-2xl font-bold tabular-nums leading-tight mt-0.5">{fmtNum(totalViews)}</span>
<span className="text-[11px] text-muted-foreground mt-0.5 truncate w-full">
{[
- totals.views ? `${fmtNum(totals.views)} channels` : null,
- trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,
+ totals.views ? `${fmtNum(totals.views)} YouTube` : null,
+ cacheTotals.igViews ? `${fmtNum(cacheTotals.igViews)} Instagram` : null,
+ trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,
].filter(Boolean).join(' · ') || 'no views recorded yet'}
</span>
</TabsTrigger>
@@ -399,7 +415,7 @@ export default function Overview() {
<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,
+ totals.posts ? `${fmtNum(totals.posts)} Instagram` : null,
cacheTotals.rdPosts ? `${fmtNum(cacheTotals.rdPosts)} Reddit` : null,
trackedStats.total ? `${fmtNum(trackedStats.total)} tracked` : null,
].filter(Boolean).join(' · ') || 'no content yet'}
@@ -549,12 +565,71 @@ export default function Overview() {
{/* ── VIEWS TAB ──────────────────────────────────────────────────── */}
<TabsContent value="views" className="space-y-4">
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
- <StatCard icon={<Eye />} label="Total Views" value={fmtNum(totalViews)} subtitle="channels and tracked content combined" gradient="blue" />
- <StatCard icon={<CirclePlay />} label="Channel Views" value={fmtNum(totals.views)} subtitle={`${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />
- <StatCard icon={<BookmarkCheck />} label="Tracked Views" value={fmtNum(trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube · ${fmtNum(trackedStats.rdViews)} Reddit`} gradient="purple" />
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
+ <StatCard icon={<Eye />} label="Total Views" value={fmtNum(totalViews)} subtitle="YouTube, Instagram, and tracked content combined" gradient="blue" />
+ <StatCard icon={<CirclePlay />} label="Channel Views" value={fmtNum(totals.views)} subtitle={`${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />
+ <StatCard icon={<Camera />} label="Instagram Views" value={fmtNum(cacheTotals.igViews)} subtitle={igAccounts.length > 0 ? igTypeSummary('views') : 'no Instagram accounts'} gradient="pink" />
+ <StatCard icon={<BookmarkCheck />} label="Tracked Views" value={fmtNum(trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube · ${fmtNum(trackedStats.rdViews)} Reddit`} gradient="purple" />
</div>
+ {igAccounts.length > 0 && (
+ <MainCard title="Instagram Views by Content Type" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Account</TableHead>
+ {IG_CONTENT_TYPES.map(t => (
+ <TableHead key={t} className="text-right">{IG_CONTENT_TYPE_META[t].plural}</TableHead>
+ ))}
+ <TableHead className="text-right">Total Views</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {igAccountRows.map(({ account: a, cache }) => (
+ <TableRow key={a.id} className="cursor-pointer" onClick={() => navigate(`/instagram/${a.id}`)}>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <Avatar className="h-8 w-8">
+ <AvatarImage src={a.profilePictureUrl} />
+ <AvatarFallback className="bg-pink-500 text-xs font-bold text-white">
+ {(a.title || a.username || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <p className="text-sm font-semibold leading-none">{a.title || a.username}</p>
+ <p className="text-xs text-muted-foreground mt-0.5">@{a.username || ''}</p>
+ </div>
+ </div>
+ </TableCell>
+ {IG_CONTENT_TYPES.map(t => (
+ <TableCell key={t} className="text-right">
+ {cache?.cacheWarmed ? (
+ <>
+ <p className="text-sm font-semibold">{fmtNum(cache.contentTypes?.[t]?.views)}</p>
+ <p className="text-xs text-muted-foreground">{fmtNum(cache.contentTypes?.[t]?.count)} {IG_CONTENT_TYPE_META[t].plural.toLowerCase()}</p>
+ </>
+ ) : <span className="text-sm text-muted-foreground">-</span>}
+ </TableCell>
+ ))}
+ <TableCell className="text-right text-sm font-bold">
+ {cache?.cacheWarmed ? fmtNum(cache.totalViews) : <span className="font-normal text-muted-foreground">{isSyncing ? 'syncing...' : '-'}</span>}
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon" className="size-7" onClick={(e) => { e.stopPropagation(); navigate(`/instagram/${a.id}`); }} />}>
+ <ExternalLink />
+ </TooltipTrigger>
+ <TooltipContent>View Analytics</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </MainCard>
+ )}
+
{categoryStats.length > 0 && (
<MainCard
title="Views by Category"
@@ -631,7 +706,7 @@ export default function Overview() {
<TabsContent value="content" className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard icon={<CirclePlay />} label="YouTube Videos" value={fmtNum(totals.videos)} subtitle={`${ytAccounts.length} channel${ytAccounts.length !== 1 ? 's' : ''}`} gradient="red" />
- <StatCard icon={<VideoIcon />} label="Instagram Posts" value={fmtNum(totals.posts)} subtitle={`${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} gradient="blue" />
+ <StatCard icon={<VideoIcon />} label="Instagram Content" value={fmtNum(totals.posts)} subtitle={IG_CONTENT_TYPES.some(t => cacheTotals.igTypes[t].count > 0) ? igTypeSummary('count') : `${igAccounts.length} account${igAccounts.length !== 1 ? 's' : ''}`} gradient="blue" />
<StatCard icon={<Flame />} label="Reddit Posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'from analytics cache' : 'visit Reddit analytics to load'} gradient="orange" />
<StatCard icon={<BookmarkCheck />} label="Tracked Content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube · ${trackedStats.rdItems.length} Reddit`} gradient="purple" />
</div>
@@ -641,7 +716,7 @@ export default function Overview() {
<div className="space-y-1">
{allSortedByContent.map((a, i) => {
const metric = a.platform === 'instagram'
- ? `${fmtNum(a.mediaCount)} posts`
+ ? `${fmtNum(a.mediaCount)} items`
: a.platform === 'reddit'
? `${fmtNum(a.totalKarma)} karma`
: `${fmtNum(a.viewCount)} views`;
@@ -736,7 +811,7 @@ export default function Overview() {
? `${fmtNum(a.totalKarma)} karma`
: `${fmtNum(a.subscriberCount)} subs`;
const content = a.platform === 'instagram'
- ? `${fmtNum(a.mediaCount)} posts`
+ ? `${fmtNum(a.mediaCount)} items`
: a.platform === 'reddit'
? `${fmtNum(a.postKarma)} post karma`
: `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`;
diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.jsx b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
index f2a6958..1553a77 100644
--- a/frontend/src/features/analytics/reels/ReelsExplorer.jsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
@@ -1,67 +1,66 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
-import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Progress } from '@/components/ui/progress';
import {
Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
-import { Search, RefreshCw, Heart, MessageCircle, Play, Image, Film, LayoutGrid, Camera } from 'lucide-react';
-import { Empty, EmptyMedia, EmptyHeader, EmptyTitle, EmptyDescription } from '@/components/ui/empty';
+import { Search, RefreshCw, Heart, MessageCircle, Camera, Eye, Clapperboard, Image, Film } from 'lucide-react';
+import { Empty, EmptyMedia, EmptyHeader, EmptyDescription } from '@/components/ui/empty';
+import StatCard from '../../../components/ui/StatCard';
import MainCard from '../../../components/MainCard';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { fmtNum, timeAgo } from '../../../utils/formatters';
-import { cn } from '@/lib/utils';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';
const ITEMS_PER_PAGE = 24;
-const MEDIA_TYPE_FILTER = [
- { label: 'All Types', value: 'all' },
- { label: 'Reels', value: 'REEL' },
- { label: 'Videos', value: 'VIDEO' },
- { label: 'Photos', value: 'IMAGE' },
- { label: 'Carousels', value: 'CAROUSEL_ALBUM' },
+const CONTENT_TYPE_FILTER = [
+ { label: 'All Types', value: 'all' },
+ ...IG_CONTENT_TYPES.map(type => ({ label: IG_CONTENT_TYPE_META[type].plural, value: type })),
];
-const MEDIA_TYPE_META = {
- REEL: { label: 'Reel', className: 'bg-pink-600' },
- VIDEO: { label: 'Video', className: 'bg-purple-600' },
- IMAGE: { label: 'Photo', className: 'bg-orange-500' },
- CAROUSEL_ALBUM: { label: 'Carousel', className: 'bg-blue-600' },
-};
+const CONTENT_TYPE_ICONS = { reel: <Clapperboard />, post: <Image />, video: <Film /> };
+const CONTENT_TYPE_GRADIENTS = { reel: 'pink', post: 'orange', video: 'purple' };
const PERFORMANCE_TIERS = [
- { label: 'All', value: 'all' },
+ { label: 'All Likes', value: 'all' },
{ label: 'Viral (>100K)', value: 'viral', min: 100000 },
- { label: 'High (10K-100K)', value: 'high', min: 10000, max: 100000 },
- { label: 'Medium (1K-10K)', value: 'medium', min: 1000, max: 10000 },
+ { label: 'High (10K-100K)', value: 'high', min: 10000, max: 100000 },
+ { label: 'Medium (1K-10K)', value: 'medium', min: 1000, max: 10000 },
{ label: 'Low (<1K)', value: 'low', max: 1000 },
];
const SORT_OPTIONS = [
- { label: 'Most Liked', field: 'likeCount' },
- { label: 'Most Comments', field: 'commentsCount' },
- { label: 'Best Engagement', field: 'engagementRate' },
- { label: 'Newest First', field: 'timestamp' },
+ { label: 'Most Viewed', value: 'viewCount' },
+ { label: 'Most Liked', value: 'likeCount' },
+ { label: 'Most Comments', value: 'commentsCount' },
+ { label: 'Best Engagement', value: 'engagementRate' },
+ { label: 'Newest First', value: 'timestamp' },
];
+function sortValue(item, field) {
+ if (field === 'timestamp') return new Date(item.timestamp).getTime() || 0;
+ return item[field] ?? -1;
+}
+
export default function ReelsExplorer() {
const { accounts, showToast } = useAppContext();
- const [media, setMedia] = useState([]);
- const [loading, setLoading] = useState(true);
- const [search, setSearch] = useState('');
- const [accountFilter, setAccountFilter] = useState('all');
- const [mediaTypeFilter, setMediaTypeFilter] = useState('all');
- const [performanceTier, setPerformanceTier] = useState('all');
- const [sortField, setSortField] = useState('likeCount');
- const [page, setPage] = useState(1);
- const [igAccounts, setIgAccounts] = useState([]);
-
- useEffect(() => { loadAllReels(); }, [accounts]);
-
- const loadAllReels = async () => {
+ const [media, setMedia] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [search, setSearch] = useState('');
+ const [accountFilter, setAccountFilter] = useState('all');
+ const [contentTypeFilter, setContentTypeFilter] = useState('all');
+ const [performanceTier, setPerformanceTier] = useState('all');
+ const [sortField, setSortField] = useState('viewCount');
+ const [page, setPage] = useState(1);
+ const [igAccounts, setIgAccounts] = useState([]);
+
+ useEffect(() => { loadAllMedia(); }, [accounts]);
+
+ const loadAllMedia = async () => {
setLoading(true);
try {
const all = [];
@@ -70,13 +69,13 @@ export default function ReelsExplorer() {
if (acct.platform !== 'instagram') continue;
try {
const res = await api.getIGMedia(acct.id);
- const items = res.media || res.data || [];
- accList.push({ id: acct.id, title: acct.title || acct.username || 'Unknown', thumbnail: acct.profilePictureUrl || '' });
+ const items = res.media || [];
+ accList.push({ value: acct.id, label: acct.title || acct.username || 'Unknown' });
all.push(...items.map(m => ({
...m,
accountTitle: acct.title || acct.username || 'Unknown',
accountId: acct.id,
- engagementRate: (m.likeCount || 0) > 0 ? (((m.likeCount || 0) + (m.commentsCount || 0)) / (m.likeCount || 1) * 100).toFixed(2) : '0.00',
+ engagementRate: m.viewCount > 0 ? ((m.likeCount || 0) + (m.commentsCount || 0)) / m.viewCount * 100 : null,
})));
} catch (e) { console.warn('Failed to load media for', acct.id, e.message); }
}
@@ -89,10 +88,30 @@ export default function ReelsExplorer() {
}
};
+ const accountMedia = useMemo(
+ () => accountFilter === 'all' ? media : media.filter(m => m.accountId === accountFilter),
+ [media, accountFilter],
+ );
+
+ const typeTotals = useMemo(() => {
+ const totals = Object.fromEntries(IG_CONTENT_TYPES.map(t => [t, { count: 0, views: 0, viewsReported: 0 }]));
+ accountMedia.forEach(m => {
+ const t = totals[m.contentType] ?? totals.post;
+ t.count++;
+ if (typeof m.viewCount === 'number') {
+ t.views += m.viewCount;
+ t.viewsReported++;
+ }
+ });
+ return totals;
+ }, [accountMedia]);
+
+ const totalViews = IG_CONTENT_TYPES.reduce((s, t) => s + typeTotals[t].views, 0);
+ const viewsReported = IG_CONTENT_TYPES.reduce((s, t) => s + typeTotals[t].viewsReported, 0);
+
const filtered = useMemo(() => {
- let result = [...media];
- if (accountFilter !== 'all') result = result.filter(m => m.accountId === accountFilter);
- if (mediaTypeFilter !== 'all') result = result.filter(m => m.mediaType === mediaTypeFilter);
+ let result = [...accountMedia];
+ if (contentTypeFilter !== 'all') result = result.filter(m => m.contentType === contentTypeFilter);
if (search.trim()) {
const q = search.toLowerCase();
result = result.filter(m => m.caption?.toLowerCase().includes(q));
@@ -102,9 +121,9 @@ export default function ReelsExplorer() {
if (tier?.min != null) result = result.filter(m => (m.likeCount || 0) >= tier.min);
if (tier?.max != null) result = result.filter(m => (m.likeCount || 0) < tier.max);
}
- result.sort((a, b) => (b[sortField] ?? 0) - (a[sortField] ?? 0));
+ result.sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));
return result;
- }, [media, accountFilter, mediaTypeFilter, search, performanceTier, sortField]);
+ }, [accountMedia, contentTypeFilter, search, performanceTier, sortField]);
const pageCount = Math.ceil(filtered.length / ITEMS_PER_PAGE);
const paged = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
@@ -127,54 +146,73 @@ export default function ReelsExplorer() {
<div>
<h1 className="text-2xl font-bold tracking-tight">IG Content Explorer</h1>
<p className="text-sm text-muted-foreground mt-0.5">
- {media.length} posts across {igAccounts.length} account{igAccounts.length !== 1 ? 's' : ''}
+ {media.length} item{media.length !== 1 ? 's' : ''} across {igAccounts.length} account{igAccounts.length !== 1 ? 's' : ''}
</p>
</div>
- <Button variant="outline" size="sm" onClick={loadAllReels} className="gap-2">
- <RefreshCw className="h-3.5 w-3.5" /> Refresh
+ <Button variant="outline" size="sm" onClick={loadAllMedia} className="gap-2">
+ <RefreshCw data-icon="inline-start" /> Refresh
</Button>
</div>
- {/* Filters */}
+ <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
+ <StatCard
+ icon={<Eye />}
+ label="Total Views"
+ value={fmtNum(totalViews)}
+ subtitle={`${viewsReported} of ${accountMedia.length} items report views`}
+ gradient="blue"
+ small
+ />
+ {IG_CONTENT_TYPES.map(type => (
+ <StatCard
+ key={type}
+ icon={CONTENT_TYPE_ICONS[type]}
+ label={IG_CONTENT_TYPE_META[type].plural}
+ value={fmtNum(typeTotals[type].count)}
+ subtitle={typeTotals[type].viewsReported > 0 ? `${fmtNum(typeTotals[type].views)} views` : 'no views reported'}
+ gradient={CONTENT_TYPE_GRADIENTS[type]}
+ small
+ />
+ ))}
+ </div>
+
<MainCard>
<div className="flex flex-wrap gap-3 items-center">
<div className="relative flex-1 min-w-48">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input className="pl-9" placeholder="Search captions…" value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
+ <Input className="pl-9" placeholder="Search captions..." value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
</div>
{igAccounts.length > 1 && (
- <Select value={accountFilter} onValueChange={v => { setAccountFilter(v); setPage(1); }}>
- <SelectTrigger className="w-40"><SelectValue placeholder="All Accounts" /></SelectTrigger>
+ <Select value={accountFilter} onValueChange={v => { setAccountFilter(v); setPage(1); }} items={[{ value: 'all', label: 'All Accounts' }, ...igAccounts]}>
+ <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All Accounts</SelectItem>
- {igAccounts.map(a => <SelectItem key={a.id} value={a.id}>{a.title}</SelectItem>)}
+ {igAccounts.map(a => <SelectItem key={a.value} value={a.value}>{a.label}</SelectItem>)}
</SelectGroup>
</SelectContent>
</Select>
)}
- <Select value={mediaTypeFilter} onValueChange={v => { setMediaTypeFilter(v); setPage(1); }}>
+ <Select value={contentTypeFilter} onValueChange={v => { setContentTypeFilter(v); setPage(1); }} items={CONTENT_TYPE_FILTER}>
<SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
- <SelectContent><SelectGroup>{MEDIA_TYPE_FILTER.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>
+ <SelectContent><SelectGroup>{CONTENT_TYPE_FILTER.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>
</Select>
- <Select value={performanceTier} onValueChange={v => { setPerformanceTier(v); setPage(1); }}>
+ <Select value={performanceTier} onValueChange={v => { setPerformanceTier(v); setPage(1); }} items={PERFORMANCE_TIERS}>
<SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
<SelectContent><SelectGroup>{PERFORMANCE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectGroup></SelectContent>
</Select>
- <Select value={sortField} onValueChange={setSortField}>
+ <Select value={sortField} onValueChange={setSortField} items={SORT_OPTIONS}>
<SelectTrigger className="w-44"><SelectValue /></SelectTrigger>
- <SelectContent><SelectGroup>{SORT_OPTIONS.map(o => <SelectItem key={o.field} value={o.field}>{o.label}</SelectItem>)}</SelectGroup></SelectContent>
+ <SelectContent><SelectGroup>{SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}</SelectGroup></SelectContent>
</Select>
</div>
- <p className="text-xs text-muted-foreground mt-2">Showing {paged.length} of {filtered.length} posts</p>
+ <p className="text-xs text-muted-foreground mt-2">Showing {paged.length} of {filtered.length} items</p>
</MainCard>
- {/* Grid */}
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-3">
{paged.map((m, i) => {
- const meta = MEDIA_TYPE_META[m.mediaType] || MEDIA_TYPE_META.IMAGE;
- const isVideo = m.mediaType === 'REEL' || m.mediaType === 'VIDEO';
- const thumb = isVideo ? m.thumbnailUrl : (m.thumbnailUrl || m.mediaUrl);
+ const meta = igContentTypeMeta(m.contentType);
+ const thumb = m.contentType === 'post' ? (m.thumbnailUrl || m.mediaUrl) : m.thumbnailUrl;
return (
<div
key={`${m.id}-${i}`}
@@ -185,7 +223,7 @@ export default function ReelsExplorer() {
{thumb
? <img src={thumb} className="w-full h-full object-cover" alt="" />
: <div className="w-full h-full bg-gradient-to-br from-pink-500 to-purple-600 flex items-center justify-center"><Camera className="h-8 w-8 text-white" /></div>}
- <span className={cn('absolute top-1.5 left-1.5 text-white text-[9px] font-bold px-1.5 py-0.5 rounded', meta.className)}>
+ <span className="absolute top-1.5 left-1.5 text-white text-[9px] font-bold px-1.5 py-0.5 rounded" style={{ background: meta.color }}>
{meta.label}
</span>
</div>
@@ -194,6 +232,7 @@ export default function ReelsExplorer() {
<p className="text-[11px] leading-snug line-clamp-2 text-foreground/80">{m.caption}</p>
)}
<div className="flex items-center gap-3 text-[11px] text-muted-foreground">
+ <span className="flex items-center gap-0.5"><Eye className="h-3 w-3" />{fmtIGViews(m.viewCount)}</span>
<span className="flex items-center gap-0.5"><Heart className="h-3 w-3 text-pink-500" />{fmtNum(m.likeCount)}</span>
<span className="flex items-center gap-0.5"><MessageCircle className="h-3 w-3" />{fmtNum(m.commentsCount)}</span>
<span className="ml-auto">{timeAgo(m.timestamp)}</span>
@@ -212,7 +251,7 @@ export default function ReelsExplorer() {
<EmptyDescription>
{accounts?.filter(a => a.platform === 'instagram').length === 0
? 'Add an Instagram account to explore content'
- : 'No posts match your filters'}
+ : 'No content matches your filters'}
</EmptyDescription>
</EmptyHeader>
</Empty>
diff --git a/frontend/src/utils/instagramContent.js b/frontend/src/utils/instagramContent.js
new file mode 100644
index 0000000..c74b24e
--- /dev/null
+++ b/frontend/src/utils/instagramContent.js
@@ -0,0 +1,18 @@
+import { fmtNum } from './formatters';
+
+export const IG_CONTENT_TYPES = ['reel', 'post', 'video'];
+
+export const IG_CONTENT_TYPE_META = {
+ reel: { label: 'Reel', plural: 'Reels', color: '#DD2A7B' },
+ post: { label: 'Post', plural: 'Posts', color: '#F58529' },
+ video: { label: 'Video', plural: 'Videos', color: '#8134AF' },
+};
+
+export function igContentTypeMeta(type) {
+ return IG_CONTENT_TYPE_META[type] ?? IG_CONTENT_TYPE_META.post;
+}
+
+// Instagram omits views when insights are unavailable, so null means "not reported", not zero
+export function fmtIGViews(views) {
+ return typeof views === 'number' ? fmtNum(views) : '-';
+}