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(tracked-content): add manual view counts for Reddit posts
spacesdriveb542a35e4b7e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a9eeaa..2b5c52c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,31 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [Unreleased]+### Added++**Manual view counts for tracked Reddit posts**+- Reddit removed `view_count` from its API in December 2018, so views for a tracked Reddit post can now be entered by hand+- `PUT /api/tracked-content/:id` accepts `manualViews`: a whole number of 0 or more, `null` to clear, rejected with a 400 for YouTube items which report a real view count+- `patchTrackedPostData()` added to `backend/lib/db.js` - merges keys into the `data` jsonb instead of replacing it+- `POST /api/tracked-content/:id/refresh` now patches rather than replaces `data`, so a manually entered view count survives a live refresh+- `frontend/src/utils/trackedContent.js` added with `trackedViews()` and `hasTrackedViews()`; every view total in the UI reads through them so YouTube and Reddit items resolve the right field+- Tracked Content table: Views column now shows the manual figure for Reddit posts, with a "Set" button on posts that have none; the Views sort covers both platforms+- Tracked Content edit dialog: Views field for Reddit posts, with an explanation of why it is manual+### Changed+**Views now include tracked content everywhere**+- Overview Total Views tab: channel views plus tracked YouTube views plus manual Reddit views; tab subtitle breaks the two apart+- Views tab gained Total Views, Channel Views, and Tracked Views stat cards, plus a "Views by Category" area chart+- Tracked Category page: "YouTube Views" replaced with a combined "Total Views" card showing the YouTube and Reddit split+- Tracked Category Reddit section: "Post Views" stat card added showing how many posts have a figure recorded; "Avg Karma per Post" folded into the Post Karma subtitle to keep the grid at four cards+- Tracked Category Reddit table: Views column added+- Overview Tracked Categories card: view figure is now the YouTube plus Reddit total rather than YouTube alone++**Audience Comparison plots category karma only**+- Categories previously plotted karma plus views, which mixed an audience metric with a reach metric an order of magnitude larger and pushed categories far above the accounts beside them+- Tooltip now reads "Karma", the legend reads "Category (karma)", and the caption reads "Categories = karma"+**Reddit score renamed to karma across the UI**- Every user-facing "score" label for a Reddit post now reads "karma", matching the vocabulary Reddit shows its own users- `RedditAnalytics.jsx`: "Total Score" to "Total Karma", "Score Over Time" to "Karma Over Time", "Score Breakdown" to "Karma Breakdown", "Top Posts by Score" to "Top Posts by Karma", table headers and tooltips updateddiff --git a/backend/lib/db.js b/backend/lib/db.jsindex 7d63360..84a8289 100644--- a/backend/lib/db.js+++ b/backend/lib/db.js@@ -241,6 +241,26 @@ export async function updateTrackedPost(supabase, id, updates, userId) {if (error) throw error;}+// Merges keys into the data jsonb instead of replacing it, so manually entered+// fields survive a live refresh and vice versa+export async function patchTrackedPostData(supabase, id, patch, userId) {+ const { data: row, error: readError } = await supabase+ .from('tracked_posts')+ .select('data')+ .eq('id', id)+ .eq('user_id', userId)+ .single();+ if (readError || !row) throw readError || new Error('Tracked content not found');++ const merged = { ...(row.data || {}), ...patch };+ const { error } = await supabase+ .from('tracked_posts')+ .update({ data: merged, updated_at: new Date().toISOString() })+ .eq('id', id)+ .eq('user_id', userId);+ if (error) throw error;+}+export async function deleteTrackedPost(supabase, id, userId) {const { error } = await supabase.from('tracked_posts')diff --git a/backend/routes/trackedContent.js b/backend/routes/trackedContent.jsindex 9484afb..833c493 100644--- a/backend/routes/trackedContent.js+++ b/backend/routes/trackedContent.js@@ -4,6 +4,7 @@ import {getTrackedPostById,createTrackedPost,updateTrackedPost,+ patchTrackedPostData,deleteTrackedPost,getAccountById,} from '../lib/db.js';@@ -80,23 +81,42 @@ router.post('/tracked-content', async (c) => {}});-// Update label, category, or account on a tracked content item+// Update label, category, account, or manually entered view countrouter.put('/tracked-content/:id', async (c) => {const id = c.req.param('id');const userId = c.get('userId');const supabase = c.get('supabase');const body = await c.req.json();- const { label, category, accountId } = body;+ const { label, category, accountId, manualViews } = body;try {const existing = await getTrackedPostById(supabase, id, userId);if (!existing) return c.json({ error: 'Tracked content not found' }, 404);+ // Reddit removed view_count from their API in 2018, so views can only be entered by hand.+ // YouTube returns a real view count, so accepting a manual one would silently override it.+ if (manualViews !== undefined) {+ if ((existing.contentType || 'reddit') === 'youtube') {+ return c.json({ error: 'YouTube view counts are fetched automatically and cannot be set by hand' }, 400);+ }+ if (manualViews === null || manualViews === '') {+ await patchTrackedPostData(supabase, id, { manualViews: null }, userId);+ } else {+ const views = Number(manualViews);+ if (!Number.isInteger(views) || views < 0) {+ return c.json({ error: 'Views must be a whole number of 0 or more' }, 400);+ }+ await patchTrackedPostData(supabase, id, { manualViews: views }, userId);+ }+ }+const updates = {};if (label !== undefined) updates.label = label;if (category !== undefined) updates.category = category;if (accountId !== undefined) updates.accountId = accountId;- await updateTrackedPost(supabase, id, updates, userId);+ if (Object.keys(updates).length > 0) {+ await updateTrackedPost(supabase, id, updates, userId);+ }const updated = await getTrackedPostById(supabase, id, userId);return c.json(updated);@@ -147,7 +167,8 @@ router.post('/tracked-content/:id/refresh', async (c) => {fetchedData = await fetchTrackedPostData(existing.url, cookie);}- await updateTrackedPost(supabase, id, { data: fetchedData }, userId);+ // Patch rather than replace so a manually entered view count survives the refresh+ await patchTrackedPostData(supabase, id, fetchedData, userId);const updated = await getTrackedPostById(supabase, id, userId);return c.json(updated);} catch (err) {diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex ecb3d0c..5b11338 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -78,7 +78,7 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup|---|---|---|---|| GET | `/api/tracked-content` | `routes/trackedContent.js` | List all tracked items for the current user (Reddit posts and YouTube videos) || POST | `/api/tracked-content` | `routes/trackedContent.js` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |-| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update label, category, or accountId for a tracked item |+| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update `label`, `category`, `accountId`, or `manualViews` for a tracked item. `manualViews` is Reddit-only (400 for YouTube), must be a whole number of 0 or more, and `null` clears it || DELETE | `/api/tracked-content/:id` | `routes/trackedContent.js` | Remove a tracked item || POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.js` | Re-fetch live data from Reddit or YouTube API for one tracked item |diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex 518d41c..06ceac2 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -225,7 +225,7 @@ and the page re-fetches once after 6 seconds.| Metric | Formula ||---|---|| Total Audience | YouTube subscribers + Instagram followers + Reddit account karma |-| Total Views | YouTube channel view counts |+| Total Views | YouTube channel views + tracked YouTube video views + manually entered Reddit post views || Total Content | YouTube videos + Instagram posts + Reddit account posts (cache) + tracked items || Total Comments | cache comments (YouTube + Instagram + Reddit) + tracked item comments || Total Likes | Reddit karma (account + tracked) + YouTube likes (cache + tracked) + Instagram likes |@@ -238,6 +238,24 @@ Tracked Reddit post karma counts toward Total Likes, not Total Audience - a monicontent, not an audience the user owns. Connected-account karma does count toward TotalAudience as that account's reputation.+### Tracked content views++Reddit removed `view_count` from its API in December 2018, so a tracked Reddit post's views are+whatever the user typed into the edit dialog, stored as `data.manualViews`. `trackedViews()` in+`frontend/src/utils/trackedContent.js` is the single place that decides which field to read:+`viewCount` for YouTube items, `manualViews` for Reddit items. Every view total in the UI goes+through it, so a post with no manual figure contributes 0 rather than breaking the sum.++`hasTrackedViews()` distinguishes "no figure recorded" from a real zero, so tables can render a+dash and a "Set" action instead of a misleading `0`.++### Audience Comparison chart++Categories plot **karma only**, never karma plus views. Views are a reach metric an order of+magnitude larger than karma; adding them would push a category far above the accounts it sits+beside on the same axis and misrepresent its audience. Category view totals belong in the Views+tab, where they are compared against other view figures.+### NamingReddit's API returns a post's net upvotes as `score`. Every aggregate the frontend derives fromdiff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 3ac40ec..228c029 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -172,10 +172,22 @@ Populated by `fetchTrackedPostData()` in `backend/services/reddit.js`:"upvoteRatio": 0.97,"numComments": 56,"permalink": "https://reddit.com/r/programming/comments/abc123/...",- "lastFetchedAt": "2026-08-04T10:00:00Z"+ "lastFetchedAt": "2026-08-04T10:00:00Z",+ "manualViews": 12500}```+`manualViews` is the one key in `data` that is not fetched from Reddit. Reddit removed+`view_count` from its API in December 2018, so view counts can only be entered by hand+through `PUT /api/tracked-content/:id`. It is `null` or absent until the user sets one.++Because of this, the refresh route calls `patchTrackedPostData()` rather than+`updateTrackedPost({ data })` - the former merges freshly fetched keys into the existing+blob so a manually entered view count survives a refresh. Anything writing to `data` for a+Reddit item must merge, never replace.++`manualViews` is rejected for YouTube items; YouTube returns a real `viewCount`.+### `data` jsonb shape for YouTube itemsPopulated by `fetchTrackedYouTubeData()` in `backend/services/youtube.js`:diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex e792f4d..0c46e70 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -111,6 +111,10 @@ refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { metho`accountId` may be `null`. For YouTube items, `accountId` is always `null` (fetched via the server's `YOUTUBE_API_KEY`). For Reddit items, `accountId` is optional and refers to a Reddit account whose cookie improves datacenter IP access.+`updateTrackedContent` takes a partial object, so only the keys present are changed. Accepted+keys are `label`, `category`, `accountId`, and `manualViews`. `manualViews` is Reddit-only and+sending it for a YouTube item returns a 400; pass `null` to clear a previously entered figure.+## AuthenticationThe `request()` function automatically attaches the JWT. Components do not need to handle auth tokens - the API layer manages this transparently. If the user is not logged in, the token will be absent and the backend will return 401, which `request()` will throw as an error.diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsxindex 6502206..68dcf3d 100644--- a/frontend/src/features/analytics/overview/Overview.jsx+++ b/frontend/src/features/analytics/overview/Overview.jsx@@ -20,8 +20,9 @@ import MetricAreaChart from '../../../components/MetricAreaChart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtPercent, timeAgo } from '../../../utils/formatters';+import { trackedViews } from '../../../utils/trackedContent';import {- RefreshCw, Users, VideoIcon, ExternalLink, Camera, BarChart2,+ RefreshCw, Users, VideoIcon, ExternalLink, Camera, BarChart2, Eye,Tag, ThumbsUp, MessageSquare, CirclePlay, Flame, BookmarkCheck,} from 'lucide-react';@@ -139,8 +140,10 @@ export default function Overview() {total: trackedContent.length,ytItems,rdItems,+ ytViews: ytItems.reduce((s, p) => s + trackedViews(p), 0),ytLikes: ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0),ytComments: ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0),+ rdViews: rdItems.reduce((s, p) => s + trackedViews(p), 0),rdKarma: rdItems.reduce((s, p) => s + (p.score ?? 0), 0),rdComments: rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0),};@@ -154,6 +157,10 @@ export default function Overview() {// Total Content = YT videos + IG posts + Reddit account posts (from cache) + tracked itemsconst totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;+ // Total Views = YouTube channel views + tracked video views + manually entered Reddit post views+ const trackedViewTotal = trackedStats.ytViews + trackedStats.rdViews;+ const totalViews = totals.views + trackedViewTotal;+// 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.const ytComments = cacheTotals.ytComments + trackedStats.ytComments;@@ -188,25 +195,26 @@ export default function Overview() {category: p.category,count: 0, ytCount: 0, rdCount: 0,ytViews: 0, ytLikes: 0, ytComments: 0,- rdKarma: 0, rdComments: 0,+ rdViews: 0, rdKarma: 0, rdComments: 0,};}const c = map[p.category];c.count++;if (p.contentType === 'youtube') {c.ytCount++;- c.ytViews += p.viewCount ?? 0;+ c.ytViews += trackedViews(p);c.ytLikes += p.likeCount ?? 0;c.ytComments += p.commentCount ?? 0;} else {c.rdCount++;+ c.rdViews += trackedViews(p);c.rdKarma += p.score ?? 0;c.rdComments += p.numComments ?? 0;}});- return Object.values(map).sort((a, b) =>- (b.rdKarma + b.ytViews) - (a.rdKarma + a.ytViews)- );+ return Object.values(map)+ .map(c => ({ ...c, views: c.ytViews + c.rdViews }))+ .sort((a, b) => (b.views + b.rdKarma) - (a.views + a.rdKarma));}, [trackedContent]);// ── Audience metric per account ────────────────────────────────────────────────@@ -242,9 +250,11 @@ export default function Overview() {value: a.totalKarma || 0,type: 'reddit',})),+ // Karma only. Adding views would mix an audience metric with a reach metric and+ // inflate the category far above the accounts it sits beside....categoryStats.map(c => ({name: c.category.slice(0, 12) + (c.category.length > 12 ? '…' : ''),- value: c.rdKarma + c.ytViews,+ value: c.rdKarma,type: 'category',})),], [ytAccounts, igAccounts, redditAccounts, categoryStats]);@@ -261,6 +271,13 @@ export default function Overview() {[trackedContent]);+ const categoryViewData = useMemo(() =>+ categoryStats+ .map(c => ({ name: c.category.slice(0, 16), views: c.views }))+ .sort((a, b) => b.views - a.views),+ [categoryStats]+ );+const commentByCategoryData = useMemo(() =>categoryStats.map(c => ({ name: c.category.slice(0, 16), comments: c.ytComments + c.rdComments }))@@ -367,9 +384,12 @@ export default function Overview() {<TabsTrigger value="views" className={tabTriggerCls}><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-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">- {ytAccounts.length > 0 ? `${ytAccounts.length} YouTube channel${ytAccounts.length !== 1 ? 's' : ''}` : 'no YouTube accounts'}+ {[+ totals.views ? `${fmtNum(totals.views)} channels` : null,+ trackedViewTotal ? `${fmtNum(trackedViewTotal)} tracked` : null,+ ].filter(Boolean).join(' · ') || 'no views recorded yet'}</span></TabsTrigger>@@ -421,7 +441,7 @@ export default function Overview() {<TabsContent value="audience" className="space-y-4"><MainCard title="Audience Comparison"><p className="text-xs text-muted-foreground mb-3">- YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = views + karma+ YouTube = subscribers · Instagram = followers · Reddit = karma · Categories = karma</p>{audienceChartData.length === 0 ? (<p className="text-sm text-muted-foreground py-8 text-center">No data to display</p>@@ -439,7 +459,7 @@ export default function Overview() {<YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} /><ReTooltipcontentStyle={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}- formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Views + Karma' : 'Audience']}+ formatter={(v, name, props) => [fmtNumFull(v), props.payload.type === 'category' ? 'Karma' : 'Audience']}/><Areatype="monotone"@@ -471,7 +491,7 @@ export default function Overview() {ytAccounts.length ? { color: PLATFORM_COLORS.youtube, label: 'YouTube (subs)' } : null,igAccounts.length ? { color: PLATFORM_COLORS.instagram, label: 'Instagram (followers)' } : null,redditAccounts.length ? { color: PLATFORM_COLORS.reddit, label: 'Reddit (karma)' } : null,- categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Category (views + karma)' } : null,+ categoryStats.length ? { color: PLATFORM_COLORS.category, label: 'Category (karma)' } : null,].filter(Boolean).map(({ color, label }) => (<div key={label} className="flex items-center gap-1.5 text-xs text-muted-foreground"><span className="h-2.5 w-2.5 rounded-full flex-shrink-0" style={{ background: color }} />@@ -529,11 +549,28 @@ export default function Overview() {{/* ── VIEWS TAB ──────────────────────────────────────────────────── */}<TabsContent value="views" className="space-y-4">- {ytAccounts.length === 0 ? (- <MainCard>- <p className="text-sm text-muted-foreground text-center py-8">No YouTube accounts connected</p>+ <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>++ {categoryStats.length > 0 && (+ <MainCard+ title="Views by Category"+ subheader="YouTube video views plus manually entered Reddit post views"+ >+ <MetricAreaChart+ data={categoryViewData}+ dataKey="views"+ label="Views"+ color="#06b6d4"+ emptyMessage="No views recorded for these categories yet"+ /></MainCard>- ) : (+ )}++ {ytAccounts.length === 0 ? null : (<MainCard title="YouTube Views by Channel" content={false}><Table><TableHeader>@@ -657,9 +694,9 @@ export default function Overview() {</p></div><div className="text-right">- {stat.ytCount > 0 && (- <p className="text-xs font-semibold tabular-nums text-red-500 leading-none">- {fmtNum(stat.ytViews)} views+ {stat.views > 0 && (+ <p className="text-xs font-semibold tabular-nums text-cyan-500 leading-none">+ {fmtNum(stat.views)} views</p>)}{stat.rdCount > 0 && (diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.jsx b/frontend/src/features/analytics/tracked/TrackedCategory.jsxindex dae1e8d..4581d2e 100644--- a/frontend/src/features/analytics/tracked/TrackedCategory.jsx+++ b/frontend/src/features/analytics/tracked/TrackedCategory.jsx@@ -14,9 +14,10 @@ import MetricAreaChart from '../../../components/MetricAreaChart';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate } from '../../../utils/formatters';+import { trackedViews, hasTrackedViews } from '../../../utils/trackedContent';import {ArrowLeft, CirclePlay, Flame, ExternalLink, Eye,- ThumbsUp, MessageSquare, Tag, TrendingUp, BarChart2,+ ThumbsUp, MessageSquare, Tag, TrendingUp,} from 'lucide-react';// fmtNum abbreviates only at 1000 and above, so the full value is redundant below that@@ -49,7 +50,7 @@ export default function TrackedCategory() {const ytStats = useMemo(() => {const count = ytItems.length;- const views = ytItems.reduce((s, p) => s + (p.viewCount ?? 0), 0);+ const views = ytItems.reduce((s, p) => s + trackedViews(p), 0);const likes = ytItems.reduce((s, p) => s + (p.likeCount ?? 0), 0);const comments = ytItems.reduce((s, p) => s + (p.commentCount ?? 0), 0);return {@@ -70,16 +71,22 @@ export default function TrackedCategory() {const karma = rdItems.reduce((s, p) => s + (p.score ?? 0), 0);const comments = rdItems.reduce((s, p) => s + (p.numComments ?? 0), 0);const ratioSum = rdItems.reduce((s, p) => s + (p.upvoteRatio ?? 0), 0);+ const views = rdItems.reduce((s, p) => s + trackedViews(p), 0);+ const withViews = rdItems.filter(hasTrackedViews).length;return {count,karma,comments,+ views,+ withViews,avgKarma: count ? Math.round(karma / count) : 0,avgComments: count ? Math.round(comments / count) : 0,avgRatio: count ? ratioSum / count : 0,};}, [rdItems]);+ const totalViews = ytStats.views + rdStats.views;+const ytChartData = useMemo(() =>[...ytItems].sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0))@@ -196,9 +203,16 @@ export default function TrackedCategory() {/><StatCardicon={<Eye />}- label="YouTube Views"- value={ytItems.length > 0 ? fmtNum(ytStats.views) : '-'}- subtitle={ytItems.length > 0 ? `avg ${fmtNum(ytStats.avgViews)} per video` : 'no YouTube videos in this category'}+ label="Total Views"+ value={totalViews > 0 ? fmtNum(totalViews) : '-'}+ subtitle={+ totalViews > 0+ ? [+ ytItems.length > 0 ? `${fmtNum(ytStats.views)} YouTube` : null,+ rdItems.length > 0 ? `${fmtNum(rdStats.views)} Reddit` : null,+ ].filter(Boolean).join(' · ')+ : 'no views recorded yet'+ }gradient="red"/><StatCard@@ -377,9 +391,20 @@ export default function TrackedCategory() {icon={<Flame />}label="Post Karma"value={fmtNum(rdStats.karma)}- subtitle="upvotes minus downvotes"+ subtitle={`avg ${fmtNum(rdStats.avgKarma)} per post`}gradient="orange"/>+ <StatCard+ icon={<Eye />}+ label="Post Views"+ value={rdStats.withViews > 0 ? fmtNum(rdStats.views) : '-'}+ subtitle={+ rdStats.withViews > 0+ ? `entered by hand on ${rdStats.withViews} of ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`+ : 'Reddit does not report views - add them per post'+ }+ gradient="teal"+ /><StatCardicon={<MessageSquare />}label="Post Comments"@@ -394,13 +419,6 @@ export default function TrackedCategory() {subtitle="upvotes as share of total votes"gradient="green"/>- <StatCard- icon={<BarChart2 />}- label="Avg Karma per Post"- value={fmtNum(rdStats.avgKarma)}- subtitle={`across ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`}- gradient="purple"- /></div>{rdChartData.length > 1 && (@@ -425,6 +443,7 @@ export default function TrackedCategory() {<TableHead className="w-8">#</TableHead><TableHead>Post</TableHead><TableHead className="text-right w-28">Karma</TableHead>+ <TableHead className="text-right w-24">Views</TableHead><TableHead className="text-right w-20">Upvote %</TableHead><TableHead className="text-right w-24">Comments</TableHead><TableHead className="text-right w-28">Fetched</TableHead>@@ -462,6 +481,11 @@ export default function TrackedCategory() {<p className="text-xs text-muted-foreground tabular-nums">{fmtNumFull(item.score)}</p>)}</TableCell>+ <TableCell className="text-right text-sm tabular-nums">+ {hasTrackedViews(item)+ ? fmtNum(trackedViews(item))+ : <span className="text-muted-foreground">-</span>}+ </TableCell><TableCell className="text-right text-sm tabular-nums text-muted-foreground">{(item.upvoteRatio != null && (item.score ?? 0) >= 10)? Math.round(item.upvoteRatio * 100) + '%'diff --git a/frontend/src/features/analytics/tracked/TrackedContent.jsx b/frontend/src/features/analytics/tracked/TrackedContent.jsxindex aad502f..352d23e 100644--- a/frontend/src/features/analytics/tracked/TrackedContent.jsx+++ b/frontend/src/features/analytics/tracked/TrackedContent.jsx@@ -3,7 +3,6 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Badge } from '@/components/ui/badge';import { Checkbox } from '@/components/ui/checkbox';-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 { Skeleton } from '@/components/ui/skeleton';@@ -13,9 +12,10 @@ import MainCard from '../../../components/MainCard';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtDate } from '../../../utils/formatters';+import { trackedViews, hasTrackedViews } from '../../../utils/trackedContent';import {Plus, RefreshCw, Trash2, Pencil, ExternalLink,- Tag, Bookmark, TrendingUp, BookmarkCheck, CirclePlay, Flame,+ Tag, Bookmark, BookmarkCheck, CirclePlay, Flame, Eye,} from 'lucide-react';function detectContentType(url) {@@ -35,6 +35,10 @@ function getComments(item) {return item.numComments ?? 0;}+function isRedditItem(item) {+ return (item?.contentType || 'reddit') === 'reddit';+}+function ContentTypeBadge({ type }) {if (type === 'youtube') {return (@@ -79,6 +83,7 @@ export default function TrackedContent() {// Edit dialog stateconst [editLabel, setEditLabel] = useState('');const [editCategory, setEditCategory] = useState('');+ const [editViews, setEditViews] = useState('');const [saving, setSaving] = useState(false);const load = useCallback(async () => {@@ -121,7 +126,7 @@ export default function TrackedContent() {return [...result].sort((a, b) => {if (sort === 'engagement-desc') return getEngagement(b) - getEngagement(a);if (sort === 'comments-desc') return getComments(b) - getComments(a);- if (sort === 'views-desc') return (b.viewCount ?? 0) - (a.viewCount ?? 0);+ if (sort === 'views-desc') return trackedViews(b) - trackedViews(a);return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);});}, [items, query, typeFilter, categoryFilter, sort]);@@ -175,13 +180,31 @@ export default function TrackedContent() {setEditItem(item);setEditLabel(item.label || '');setEditCategory(item.category || '');+ setEditViews(item.manualViews != null ? String(item.manualViews) : '');}async function handleSaveEdit() {if (!editItem) return;++ const updates = { label: editLabel, category: editCategory };++ if (isRedditItem(editItem)) {+ const raw = editViews.trim();+ if (raw === '') {+ updates.manualViews = null;+ } else {+ const views = Number(raw);+ if (!Number.isInteger(views) || views < 0) {+ showToast('Views must be a whole number of 0 or more', 'error');+ return;+ }+ updates.manualViews = views;+ }+ }+setSaving(true);try {- const updated = await api.updateTrackedContent(editItem.id, { label: editLabel, category: editCategory });+ const updated = await api.updateTrackedContent(editItem.id, updates);setItems(prev => prev.map(p => p.id === editItem.id ? updated : p));setEditItem(null);showToast('Updated');@@ -406,7 +429,6 @@ export default function TrackedContent() {) : (filtered.map(item => {const isYT = item.contentType === 'youtube';- const acc = !isYT ? accounts.find(a => a.id === item.accountId) : null;const isRefreshing = refreshingIds.has(item.id);return (<TableRow key={item.id} className={selected.has(item.id) ? 'bg-muted/30' : ''}>@@ -455,7 +477,22 @@ export default function TrackedContent() {)}</TableCell><TableCell className="text-right text-sm tabular-nums text-muted-foreground">- {isYT && item.viewCount !== undefined ? fmtNum(item.viewCount) : '-'}+ {hasTrackedViews(item) ? (+ <span className={isYT ? '' : 'text-foreground'}>{fmtNum(trackedViews(item))}</span>+ ) : isYT ? (+ '-'+ ) : (+ <Button+ variant="ghost"+ size="sm"+ className="h-6 px-1.5 text-xs font-normal text-muted-foreground gap-1"+ onClick={() => openEdit(item)}+ title="Reddit does not report views - enter them manually"+ >+ <Eye className="h-3 w-3" />+ Set+ </Button>+ )}</TableCell><TableCell className="text-right text-sm font-semibold tabular-nums">{isYT@@ -644,6 +681,26 @@ export default function TrackedContent() {</div>)}</div>+ {editItem && isRedditItem(editItem) && (+ <div className="space-y-1.5">+ <label className="text-sm font-medium">+ Views <span className="text-muted-foreground font-normal">(optional)</span>+ </label>+ <Input+ type="number"+ min="0"+ step="1"+ inputMode="numeric"+ value={editViews}+ onChange={e => setEditViews(e.target.value)}+ placeholder="e.g. 12500"+ />+ <p className="text-xs text-muted-foreground">+ Reddit does not report view counts through its API. Copy the number from the post+ insights page to include it in your totals. Leave empty to remove it.+ </p>+ </div>+ )}</div><DialogFooter><Button variant="outline" onClick={() => setEditItem(null)} disabled={saving}>Cancel</Button>diff --git a/frontend/src/utils/trackedContent.js b/frontend/src/utils/trackedContent.jsnew file mode 100644index 0000000..3705706--- /dev/null+++ b/frontend/src/utils/trackedContent.js@@ -0,0 +1,15 @@+// Views for a tracked item. YouTube reports a real view count; Reddit removed view_count+// from their API in 2018, so Reddit views are whatever the user entered by hand.+export function trackedViews(item) {+ if (!item) return 0;+ if (item.contentType === 'youtube') return item.viewCount ?? 0;+ return item.manualViews ?? 0;+}++// True when the item is a Reddit post whose views have not been entered yet, so the UI can+// distinguish "no views recorded" from a genuine zero+export function hasTrackedViews(item) {+ if (!item) return false;+ if (item.contentType === 'youtube') return item.viewCount !== undefined && item.viewCount !== null;+ return item.manualViews !== undefined && item.manualViews !== null;+}