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(reddit): add tracked posts feature

spacesdrive0a89405b646a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78be03f..b1ff304 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,24 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
+**Tracked Reddit Posts feature**
+- New `tracked_posts` Supabase table: stores post URLs, an optional account cookie reference, label, category, and cached Reddit data as jsonb
+- `backend/routes/trackedPosts.js` - 5 routes under `/api/reddit/tracked-posts`: GET (list), POST (add + fetch), PUT (update label/category/account), DELETE, and POST `:id/refresh`
+- `fetchTrackedPostData(postUrl, cookie)` added to `backend/services/reddit.js` - uses the `.json` trick to retrieve score, upvote ratio, comment count, and metadata for any public Reddit post
+- `backend/lib/db.js` - 5 new functions: `getTrackedPosts`, `getTrackedPostById`, `createTrackedPost`, `updateTrackedPost`, `deleteTrackedPost`
+- `frontend/src/features/analytics/reddit/RedditTracked.jsx` - new page at `/reddit-tracked`:
+ - StatCards: Tracked Posts, Categories, Avg Score
+ - "Track Post" dialog: URL input, account cookie selector (nullable), label, category
+ - Table with score, comment count, upvote%, last fetched, per-row refresh/edit/delete/open
+ - Checkbox selection with bulk category assignment bar
+ - "Edit" dialog with category quick-select from existing categories
+ - Filters: text search, category filter, sort by date/score/comments
+ - Empty state with CTA
+- Route `/reddit-tracked` added to `App.jsx`
+- "Tracked Posts" nav item with `BookmarkCheck` icon added to Analytics group in `Sidebar.jsx`
+- `api.js` - 5 new methods: `getTrackedPosts`, `addTrackedPost`, `updateTrackedPost`, `deleteTrackedPost`, `refreshTrackedPost`
+- `Overview.jsx` - category stats section below Reddit karma card; lazily fetches tracked posts and groups by category showing total score, avg score, upvote%; hidden when no categories assigned
+
**Reddit Analytics improvements**
- Karma separated into its own dedicated card in `RedditAnalytics.jsx` (total, post, comment, awardee karma); previously karma was mixed into the profile header
- KPI cards: Posts Fetched, Total Score, Total Comments, Awards Received - replacing the previous generic set
diff --git a/DECISIONS.md b/DECISIONS.md
index fdbcac5..cf6b40c 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -419,3 +419,25 @@ Records every significant architectural decision, the alternatives considered, a
- The maintenance overhead exceeded the value delivered relative to the project's primary focus (YouTube and Instagram)
**Supersedes:** ADR-017
+
+---
+
+## ADR-019: Tracked posts fetch data on create and manual refresh only
+
+**Date:** 2026-08-04
+**Status:** Accepted
+
+**Decision:** When a user adds a tracked Reddit post URL, the backend fetches live data once (score, upvote ratio, comment count, title, subreddit) and stores it in `tracked_posts.data` as a jsonb cache. Subsequent GET requests return only the cached data. Live data is re-fetched only when the user explicitly triggers a refresh on a specific post.
+
+**Alternatives considered:**
+- Fetch live data on every GET: would fire N Reddit API requests on each page load, hitting rate limits immediately for users with many tracked posts
+- Background cron refresh: would require a new cron trigger and add Worker scheduling complexity for a feature where staleness is acceptable
+
+**Reasoning:**
+- Reddit's public JSON API is rate-limited to ~60 requests per 10 minutes unauthenticated. Fetching 20 posts on page load would consume the rate limit in one request cycle.
+- Score and comment count are not real-time metrics for typical use (monitoring campaign performance, not live event tracking). Manual refresh on demand is sufficient.
+- Storing data in jsonb keeps the fetch result queryable without an extra API call round-trip.
+- `account_id` is nullable with `ON DELETE SET NULL` so tracked posts survive account deletion and fall back to public (cookieless) access on refresh.
+
+**Trade-offs:**
+- Data shown on the page may be hours or days stale if the user does not refresh manually. The `lastFetchedAt` timestamp is displayed in the table so staleness is visible.
diff --git a/backend/lib/db.js b/backend/lib/db.js
index 5d90cd8..fa6835f 100644
--- a/backend/lib/db.js
+++ b/backend/lib/db.js
@@ -175,3 +175,75 @@ export async function deleteAllPosts(supabase, userId) {
if (error) throw error;
return { deleted: (total || 0) - (keeping || 0), kept: keeping || 0 };
}
+
+// ── Tracked Posts ─────────────────────────────────────────────────────────────
+
+function rowToTrackedPost(row) {
+ return {
+ id: row.id,
+ accountId: row.account_id,
+ url: row.url,
+ label: row.label || '',
+ category: row.category || '',
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ ...(row.data || {}),
+ };
+}
+
+export async function getTrackedPosts(supabase, userId) {
+ const { data, error } = await supabase
+ .from('tracked_posts')
+ .select('id, account_id, url, label, category, created_at, updated_at, data')
+ .eq('user_id', userId)
+ .order('created_at', { ascending: false });
+ if (error) throw error;
+ return (data || []).map(rowToTrackedPost);
+}
+
+export async function getTrackedPostById(supabase, id, userId) {
+ const { data, error } = await supabase
+ .from('tracked_posts')
+ .select('id, account_id, url, label, category, created_at, updated_at, data')
+ .eq('id', id)
+ .eq('user_id', userId)
+ .single();
+ if (error || !data) return null;
+ return rowToTrackedPost(data);
+}
+
+export async function createTrackedPost(supabase, post, userId) {
+ const { id, accountId, url, label, category } = post;
+ const { error } = await supabase.from('tracked_posts').insert({
+ id,
+ user_id: userId,
+ account_id: accountId || null,
+ url,
+ label: label || '',
+ category: category || '',
+ });
+ if (error) throw error;
+}
+
+export async function updateTrackedPost(supabase, id, updates, userId) {
+ const colUpdates = { updated_at: new Date().toISOString() };
+ if (updates.label !== undefined) colUpdates.label = updates.label;
+ if (updates.category !== undefined) colUpdates.category = updates.category;
+ if (updates.accountId !== undefined) colUpdates.account_id = updates.accountId || null;
+ if (updates.data !== undefined) colUpdates.data = updates.data;
+ const { error } = await supabase
+ .from('tracked_posts')
+ .update(colUpdates)
+ .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')
+ .delete()
+ .eq('id', id)
+ .eq('user_id', userId);
+ if (error) throw error;
+}
diff --git a/backend/routes/trackedPosts.js b/backend/routes/trackedPosts.js
new file mode 100644
index 0000000..62930aa
--- /dev/null
+++ b/backend/routes/trackedPosts.js
@@ -0,0 +1,126 @@
+import { Hono } from 'hono';
+import {
+ getTrackedPosts,
+ getTrackedPostById,
+ createTrackedPost,
+ updateTrackedPost,
+ deleteTrackedPost,
+ getAccountById,
+} from '../lib/db.js';
+import { fetchTrackedPostData } from '../services/reddit.js';
+
+const router = new Hono();
+
+// List all tracked posts for the current user
+router.get('/reddit/tracked-posts', async (c) => {
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const posts = await getTrackedPosts(supabase, userId);
+ return c.json(posts);
+ } catch (err) {
+ console.error('GET /reddit/tracked-posts:', err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Add a new tracked post - fetches live data immediately using the account's cookie
+router.post('/reddit/tracked-posts', async (c) => {
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ const body = await c.req.json();
+ const { url, accountId, label, category } = body;
+
+ if (!url) return c.json({ error: 'url is required' }, 400);
+
+ try {
+ let cookie = null;
+ if (accountId) {
+ const account = await getAccountById(supabase, accountId, userId);
+ if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+ cookie = account.cookie || null;
+ }
+
+ const postData = await fetchTrackedPostData(url, cookie);
+
+ const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
+ await createTrackedPost(supabase, { id, accountId, url, label, category }, userId);
+ await updateTrackedPost(supabase, id, { data: postData }, userId);
+
+ const created = await getTrackedPostById(supabase, id, userId);
+ return c.json(created, 201);
+ } catch (err) {
+ console.error('POST /reddit/tracked-posts:', err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Update label or category on a tracked post
+router.put('/reddit/tracked-posts/: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;
+
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked post not found' }, 404);
+
+ 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);
+
+ const updated = await getTrackedPostById(supabase, id, userId);
+ return c.json(updated);
+ } catch (err) {
+ console.error(`PUT /reddit/tracked-posts/${id}:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Delete a tracked post
+router.delete('/reddit/tracked-posts/:id', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked post not found' }, 404);
+ await deleteTrackedPost(supabase, id, userId);
+ return c.json({ success: true });
+ } catch (err) {
+ console.error(`DELETE /reddit/tracked-posts/${id}:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Refresh live data for a single tracked post
+router.post('/reddit/tracked-posts/:id/refresh', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ try {
+ const existing = await getTrackedPostById(supabase, id, userId);
+ if (!existing) return c.json({ error: 'Tracked post not found' }, 404);
+
+ let cookie = null;
+ if (existing.accountId) {
+ const account = await getAccountById(supabase, existing.accountId, userId);
+ cookie = account?.cookie || null;
+ }
+
+ const postData = await fetchTrackedPostData(existing.url, cookie);
+ await updateTrackedPost(supabase, id, { data: postData }, userId);
+
+ const updated = await getTrackedPostById(supabase, id, userId);
+ return c.json(updated);
+ } catch (err) {
+ console.error(`POST /reddit/tracked-posts/${id}/refresh:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+export default router;
diff --git a/backend/server.js b/backend/server.js
index bce511e..a50ec98 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -10,6 +10,7 @@ import publishingRouter from './routes/publishing.js';
import scheduledPostsRouter from './routes/scheduledPosts.js';
import settingsRouter from './routes/settings.js';
import redditRouter from './routes/reddit.js';
+import trackedPostsRouter from './routes/trackedPosts.js';
import { urlHandler, callbackHandler } from './routes/instagramAuth.js';
import { processScheduledPosts } from './utils/scheduler.js';
import { autoRefreshInstagramTokens } from './services/instagram.js';
@@ -54,6 +55,7 @@ api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
api.route('/', redditRouter);
+api.route('/', trackedPostsRouter);
// Instagram OAuth URL generator - protected (needs userId to create state token)
api.get('/auth/instagram/url', urlHandler);
diff --git a/backend/services/reddit.js b/backend/services/reddit.js
index 15a1d8b..e909900 100644
--- a/backend/services/reddit.js
+++ b/backend/services/reddit.js
@@ -7,13 +7,9 @@ const REDDIT_BASE = 'https://www.reddit.com';
const USER_AGENT = 'script:twiligent:v1.0 (by /u/spacesdrive)';
async function redditFetch(path, cookie) {
- const res = await fetch(`${REDDIT_BASE}${path}`, {
- headers: {
- 'User-Agent': USER_AGENT,
- 'Accept': 'application/json',
- 'Cookie': `reddit_session=${cookie}`,
- },
- });
+ const headers = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };
+ if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
+ const res = await fetch(`${REDDIT_BASE}${path}`, { headers });
if (res.status === 404) throw new Error('Reddit user not found - check the username');
if (res.status === 403) throw new Error('Session cookie is invalid or expired - open reddit.com in your browser, copy a fresh reddit_session value from DevTools (Application > Cookies > reddit.com), delete this account, and re-add it');
@@ -262,3 +258,34 @@ export function safeRedditAccount(account) {
// No-op: kept for compatibility with server.js cron handler.
export async function autoRefreshRedditSessions() {}
+
+function parseRedditPostUrl(rawUrl) {
+ let u;
+ try { u = new URL(rawUrl); } catch { throw new Error('Invalid URL - paste the full post link from reddit.com'); }
+ if (!u.hostname.includes('reddit.com')) throw new Error('Not a Reddit URL - paste a link from reddit.com');
+ const match = u.pathname.match(/^(\/r\/[^/]+\/comments\/[^/]+(?:\/[^/]+)?)\/?$/);
+ if (!match) throw new Error('Not a Reddit post URL - paste the full post link including /r/.../comments/...');
+ return match[1];
+}
+
+export async function fetchTrackedPostData(postUrl, cookie) {
+ const path = parseRedditPostUrl(postUrl);
+ const data = await redditFetch(`${path}.json`, cookie);
+ if (!Array.isArray(data) || !data[0]) throw new Error('Unexpected Reddit response - post may be deleted or private');
+ const post = data[0]?.data?.children?.[0]?.data;
+ if (!post) throw new Error('Post not found or has been deleted');
+ return {
+ postId: post.id,
+ title: post.title,
+ subreddit: post.subreddit,
+ subredditPrefixed: post.subreddit_name_prefixed ?? `r/${post.subreddit}`,
+ author: post.author ?? '[deleted]',
+ score: post.score ?? 0,
+ upvoteRatio: post.upvote_ratio ?? 0,
+ numComments: post.num_comments ?? 0,
+ permalink: `https://reddit.com${post.permalink}`,
+ isNsfw: post.over_18 ?? false,
+ createdAt: post.created_utc ? new Date(post.created_utc * 1000).toISOString() : '',
+ lastFetchedAt: new Date().toISOString(),
+ };
+}
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 6b4fbe4..3ba48d6 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -68,6 +68,15 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.js` | Fetch profile + posts + computed analytics; cached in Redis |
| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.js` | Returns cached post list or live-fetched posts |
+### Tracked Reddit Posts
+| Method | Path | File | Purpose |
+|---|---|---|---|
+| GET | `/api/reddit/tracked-posts` | `routes/trackedPosts.js` | List all tracked posts for the current user (returns cached data from `data` column) |
+| POST | `/api/reddit/tracked-posts` | `routes/trackedPosts.js` | Add a post URL to track; fetches live data immediately using the selected account's cookie |
+| PUT | `/api/reddit/tracked-posts/:id` | `routes/trackedPosts.js` | Update label, category, or accountId for a tracked post |
+| DELETE | `/api/reddit/tracked-posts/:id` | `routes/trackedPosts.js` | Remove a tracked post |
+| POST | `/api/reddit/tracked-posts/:id/refresh` | `routes/trackedPosts.js` | Re-fetch live score/comment data from Reddit for one tracked post |
+
### Settings
| Method | Path | File | Purpose |
|---|---|---|---|
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index b0a77f8..a1517c9 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -111,6 +111,7 @@ All Reddit public JSON API calls go through `redditFetch(path, cookie)`. Request
| `fetchRedditPosts(username, cookie, limit)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |
| `computeRedditAnalytics(profile, posts)` | Computes score stats, subreddit breakdown, posting time patterns, monthly breakdown, virality/consistency scores |
| `safeRedditAccount(account)` | Strips the `cookie` field before any API response |
+| `fetchTrackedPostData(postUrl, cookie)` | Fetches score, comments, and metadata for any public Reddit post URL using the `.json` trick; optionally uses a session cookie |
### `safeRedditAccount(account)`
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index a97b21c..e14b975 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -141,6 +141,74 @@ The `publishing` status is a mutex - it prevents double-publishing when both the
---
+## Table: `tracked_posts`
+
+Stores Reddit post URLs the user wants to monitor for score and comment count changes.
+
+| Column | Type | Nullable | Description |
+|---|---|---|---|
+| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |
+| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE |
+| `account_id` | text | NULL | FK -> `accounts.id` ON DELETE SET NULL. Which account's cookie to use when fetching |
+| `url` | text | NOT NULL | Full Reddit post URL (e.g. `https://www.reddit.com/r/.../comments/...`) |
+| `label` | text | NOT NULL DEFAULT '' | User-defined name for the post |
+| `category` | text | NOT NULL DEFAULT '' | User-defined grouping label (used for category stats on Overview) |
+| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the user added the tracked post |
+| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Last time any field or the cached data was changed |
+| `data` | jsonb | NULL | Cached post data fetched from Reddit (see below) |
+
+### `data` jsonb shape
+
+Populated by `fetchTrackedPostData()` in `backend/services/reddit.js`:
+
+```json
+{
+ "postId": "abc123",
+ "title": "Post title from Reddit",
+ "subreddit": "programming",
+ "subredditPrefixed": "r/programming",
+ "author": "username",
+ "score": 1234,
+ "upvoteRatio": 0.97,
+ "numComments": 56,
+ "permalink": "https://reddit.com/r/programming/comments/abc123/...",
+ "isNsfw": false,
+ "createdAt": "2026-01-01T00:00:00Z",
+ "lastFetchedAt": "2026-08-04T10:00:00Z"
+}
+```
+
+Data is fetched on create and on manual refresh. It is not re-fetched on every GET to avoid Reddit rate limits.
+
+### `account_id` nullable logic
+
+`account_id` is nullable with `ON DELETE SET NULL`. If the user deletes the Reddit account whose cookie was used, the tracked post is kept but `account_id` becomes `null`. Subsequent refreshes access the post as public (no cookie).
+
+### Indexes
+
+```sql
+CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);
+```
+
+### Migration SQL
+
+```sql
+CREATE TABLE tracked_posts (
+ id text PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
+ account_id text REFERENCES accounts(id) ON DELETE SET NULL,
+ url text NOT NULL,
+ label text NOT NULL DEFAULT '',
+ category text NOT NULL DEFAULT '',
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ data jsonb
+);
+CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);
+```
+
+---
+
## `lib/db.js` - Query Layer
All SQL operations are centralized in `backend/lib/db.js`. Route handlers and cron handlers import named functions from this file - they never call `supabase.from()` directly.
@@ -167,6 +235,13 @@ createPost(supabase, post, userId)
updatePost(supabase, id, updates, userId?)
deletePost(supabase, id, userId?)
deleteAllPosts(supabase, userId) // skips 'publishing' status posts
+
+// Tracked Reddit Posts
+getTrackedPosts(supabase, userId)
+getTrackedPostById(supabase, id, userId)
+createTrackedPost(supabase, post, userId)
+updateTrackedPost(supabase, id, updates, userId)
+deleteTrackedPost(supabase, id, userId)
```
## Adding a New Table
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index d76ef89..ae6e9b5 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -87,6 +87,20 @@ async function handleAction() {
}
```
+## Tracked Reddit Post Methods
+
+Added to the `api` object in `api.js`:
+
+```js
+getTrackedPosts: () => request('/reddit/tracked-posts'),
+addTrackedPost: (url, accountId, label, category) => request('/reddit/tracked-posts', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+updateTrackedPost: (id, updates) => request(`/reddit/tracked-posts/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+deleteTrackedPost: (id) => request(`/reddit/tracked-posts/${id}`, { method: 'DELETE' }),
+refreshTrackedPost: (id) => request(`/reddit/tracked-posts/${id}/refresh`, { method: 'POST' }),
+```
+
+`accountId` may be `null` (public access without a session cookie).
+
## Authentication
The `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/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 8f16b3d..09abb9c 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -15,7 +15,8 @@ frontend/src/
│ │ └── reddit/
│ │ ├── RedditAnalytics.jsx <- Reddit account analytics (karma, scores, subreddits)
│ │ ├── RedditPosts.jsx <- Per-account post explorer
-│ │ └── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)
+│ │ ├── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)
+│ │ └── RedditTracked.jsx <- Tracked post monitor (URL-based, live score/comments)
│ ├── accounts/
│ │ └── AccountManager.jsx <- Add/remove connected accounts
│ ├── publishing/
@@ -78,6 +79,7 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
| Reddit Analytics | `/reddit/:id` | Reddit analytics for one account - karma breakdown, score timeline, post type distribution, day/hour analysis, subreddit breakdown, top posts |
| Reddit Posts (global) | `/reddit-posts` | Combined post explorer across all Reddit accounts with account and subreddit filters |
| Reddit Posts (per account) | `/reddit-posts/:id` | Searchable and sortable post list for a single Reddit account |
+| Tracked Posts | `/reddit-tracked` | Monitor specific Reddit post URLs for score and comment changes; bulk category assignment; category stats shown on Overview |
| Video Explorer | `/videos/:id` | YouTube video library with search and sort |
| Publish | `/publish/:id` | Publish a post to Instagram immediately |
| Schedule | `/schedule/:id` | View and manage the scheduled post queue |
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index 2454e39..06ca3a2 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -17,6 +17,7 @@ The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `Browser
| `/reddit/:id` | `RedditAnalytics.jsx` | `:id` = account.id for Reddit accounts |
| `/reddit-posts` | `RedditPostsAll.jsx` | Combined post explorer across all connected Reddit accounts |
| `/reddit-posts/:id` | `RedditPosts.jsx` | `:id` = account.id; filterable/sortable post explorer for one account |
+| `/reddit-tracked` | `RedditTracked.jsx` | Tracked post URL monitor - paste any Reddit URL, watch score and comment count |
| `/videos/:id` | `VideoExplorer.jsx` | `:id` = account.id for YouTube accounts |
| `/publish/:id` | `Publish.jsx` | `:id` = account.id for Instagram accounts |
| `/schedule/:id` | `Schedule.jsx` | `:id` = account.id for Instagram accounts |
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index f654287..7065128 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -21,6 +21,7 @@ const 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 RedditTracked = lazy(() => import('./features/analytics/reddit/RedditTracked'));
const router = createBrowserRouter([
{
@@ -47,8 +48,9 @@ const router = createBrowserRouter([
{ path: 'accounts', element: <AccountManager /> },
{ path: 'settings', element: <Settings /> },
{ path: 'reddit/:id', element: <RedditAnalytics /> },
- { path: 'reddit-posts', element: <RedditPostsAll /> },
+ { path: 'reddit-posts', element: <RedditPostsAll /> },
{ path: 'reddit-posts/:id', element: <RedditPosts /> },
+ { path: 'reddit-tracked', element: <RedditTracked /> },
{ path: '*', element: <Navigate to="/" replace /> },
],
},
diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsx
index 4b16380..63c3907 100644
--- a/frontend/src/features/analytics/overview/Overview.jsx
+++ b/frontend/src/features/analytics/overview/Overview.jsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -14,8 +14,9 @@ import {
import StatCard from '../../../components/ui/StatCard';
import MainCard from '../../../components/MainCard';
import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
-import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera, MessageSquare, Flame } from 'lucide-react';
+import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera, MessageSquare, Flame, Tag, TrendingUp } from 'lucide-react';
const CHART_COLORS = ['hsl(221.2,83.2%,53.3%)', '#22c55e', '#f97316', '#a855f7', '#06b6d4', '#ec4899', '#6366f1', '#eab308'];
@@ -23,6 +24,32 @@ export default function Overview() {
const { accounts, loading, refreshAll } = useAppContext();
const navigate = useNavigate();
+ const [trackedPosts, setTrackedPosts] = useState([]);
+ useEffect(() => {
+ api.getTrackedPosts().then(data => {
+ if (Array.isArray(data)) setTrackedPosts(data);
+ }).catch(() => {});
+ }, []);
+
+ const categoryStats = useMemo(() => {
+ const withCategory = trackedPosts.filter(p => p.category);
+ if (withCategory.length === 0) return [];
+ const map = {};
+ withCategory.forEach(p => {
+ if (!map[p.category]) map[p.category] = { category: p.category, count: 0, totalScore: 0, totalComments: 0, upvoteRatios: [] };
+ map[p.category].count++;
+ map[p.category].totalScore += p.score ?? 0;
+ map[p.category].totalComments += p.numComments ?? 0;
+ if (p.upvoteRatio != null) map[p.category].upvoteRatios.push(p.upvoteRatio);
+ });
+ return Object.values(map).map(s => ({
+ ...s,
+ avgScore: Math.round(s.totalScore / s.count),
+ avgComments: Math.round(s.totalComments / s.count),
+ avgUpvoteRatio: s.upvoteRatios.length > 0 ? Math.round(s.upvoteRatios.reduce((a, b) => a + b, 0) / s.upvoteRatios.length * 100) : 0,
+ })).sort((a, b) => b.totalScore - a.totalScore);
+ }, [trackedPosts]);
+
const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');
const igAccounts = accounts.filter(a => a.platform === 'instagram');
const redditAccounts = accounts.filter(a => a.platform === 'reddit');
@@ -164,6 +191,50 @@ export default function Overview() {
</MainCard>
)}
+ {/* Tracked post category stats */}
+ {categoryStats.length > 0 && (
+ <MainCard
+ title="Tracked Post Categories"
+ secondary={
+ <button
+ onClick={() => navigate('/reddit-tracked')}
+ className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
+ >
+ <Tag className="h-3 w-3" />
+ Manage
+ </button>
+ }
+ >
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
+ {categoryStats.map(stat => (
+ <div
+ key={stat.category}
+ className="rounded-lg border border-border p-3 space-y-2"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-semibold truncate">{stat.category}</span>
+ <span className="text-xs text-muted-foreground shrink-0">{stat.count} post{stat.count !== 1 ? 's' : ''}</span>
+ </div>
+ <div className="grid grid-cols-3 gap-1 text-center">
+ <div>
+ <p className="text-sm font-bold tabular-nums text-orange-500">{fmtNum(stat.totalScore)}</p>
+ <p className="text-[10px] text-muted-foreground">total score</p>
+ </div>
+ <div>
+ <p className="text-sm font-bold tabular-nums">{fmtNum(stat.avgScore)}</p>
+ <p className="text-[10px] text-muted-foreground">avg score</p>
+ </div>
+ <div>
+ <p className="text-sm font-bold tabular-nums">{stat.avgUpvoteRatio}%</p>
+ <p className="text-[10px] text-muted-foreground">upvote %</p>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </MainCard>
+ )}
+
{accounts.length === 0 ? (
<MainCard>
<div className="flex flex-col items-center text-center py-12 gap-4">
diff --git a/frontend/src/features/analytics/reddit/RedditTracked.jsx b/frontend/src/features/analytics/reddit/RedditTracked.jsx
new file mode 100644
index 0000000..3977fc6
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditTracked.jsx
@@ -0,0 +1,556 @@
+import React, { useState, useEffect, useMemo, useCallback } from 'react';
+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';
+import {
+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
+} from '@/components/ui/dialog';
+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 {
+ Plus, RefreshCw, Trash2, Pencil, ExternalLink,
+ Tag, Bookmark, TrendingUp, BookmarkCheck,
+} from 'lucide-react';
+
+export default function RedditTracked() {
+ const { accounts, showToast } = useAppContext();
+ const redditAccounts = accounts.filter(a => a.platform === 'reddit');
+
+ const [posts, setPosts] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [addOpen, setAddOpen] = useState(false);
+ const [editPost, setEditPost] = useState(null);
+ const [selected, setSelected] = useState(new Set());
+ const [bulkCategory, setBulkCategory] = useState('');
+ const [query, setQuery] = useState('');
+ const [categoryFilter, setCategoryFilter] = useState('all');
+ const [sort, setSort] = useState('date-desc');
+ const [refreshingIds, setRefreshingIds] = useState(new Set());
+
+ // Add dialog state
+ const [addUrl, setAddUrl] = useState('');
+ const [addAccountId, setAddAccountId] = useState(redditAccounts[0]?.id ?? 'none');
+ const [addLabel, setAddLabel] = useState('');
+ const [addCategory, setAddCategory] = useState('');
+ const [adding, setAdding] = useState(false);
+
+ // Edit dialog state
+ const [editLabel, setEditLabel] = useState('');
+ const [editCategory, setEditCategory] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ const load = useCallback(async () => {
+ try {
+ const data = await api.getTrackedPosts();
+ setPosts(Array.isArray(data) ? data : []);
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [showToast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const categories = useMemo(() => {
+ const seen = new Set(posts.map(p => p.category).filter(Boolean));
+ return Array.from(seen).sort();
+ }, [posts]);
+
+ const filtered = useMemo(() => {
+ let result = posts;
+ if (categoryFilter !== 'all') result = result.filter(p => p.category === categoryFilter);
+ if (query.trim()) {
+ const q = query.toLowerCase();
+ result = result.filter(p =>
+ (p.title || '').toLowerCase().includes(q) ||
+ (p.subreddit || '').toLowerCase().includes(q) ||
+ (p.label || '').toLowerCase().includes(q) ||
+ (p.category || '').toLowerCase().includes(q)
+ );
+ }
+ return [...result].sort((a, b) => {
+ if (sort === 'score-desc') return (b.score ?? 0) - (a.score ?? 0);
+ if (sort === 'comments-desc') return (b.numComments ?? 0) - (a.numComments ?? 0);
+ return new Date(b.createdAt || 0) - new Date(a.createdAt || 0);
+ });
+ }, [posts, query, categoryFilter, sort]);
+
+ const totals = useMemo(() => ({
+ tracked: posts.length,
+ categories: categories.length,
+ avgScore: posts.length > 0 ? Math.round(posts.reduce((s, p) => s + (p.score ?? 0), 0) / posts.length) : 0,
+ }), [posts, categories]);
+
+ const allSelected = filtered.length > 0 && filtered.every(p => selected.has(p.id));
+ const someSelected = selected.size > 0;
+
+ function toggleAll() {
+ if (allSelected) {
+ setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.delete(p.id)); return n; });
+ } else {
+ setSelected(prev => { const n = new Set(prev); filtered.forEach(p => n.add(p.id)); return n; });
+ }
+ }
+
+ function toggleOne(id) {
+ setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
+ }
+
+ async function handleAdd() {
+ if (!addUrl.trim()) { showToast('Paste a Reddit post URL', 'error'); return; }
+ setAdding(true);
+ try {
+ const accountId = addAccountId === 'none' ? null : addAccountId;
+ const post = await api.addTrackedPost(addUrl.trim(), accountId, addLabel.trim(), addCategory.trim());
+ setPosts(prev => [post, ...prev]);
+ setAddOpen(false);
+ setAddUrl(''); setAddLabel(''); setAddCategory('');
+ showToast('Post is now tracked');
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setAdding(false);
+ }
+ }
+
+ function openEdit(post) {
+ setEditPost(post);
+ setEditLabel(post.label || '');
+ setEditCategory(post.category || '');
+ }
+
+ async function handleSaveEdit() {
+ if (!editPost) return;
+ setSaving(true);
+ try {
+ const updated = await api.updateTrackedPost(editPost.id, { label: editLabel, category: editCategory });
+ setPosts(prev => prev.map(p => p.id === editPost.id ? updated : p));
+ setEditPost(null);
+ showToast('Post updated');
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function handleDelete(id) {
+ try {
+ await api.deleteTrackedPost(id);
+ setPosts(prev => prev.filter(p => p.id !== id));
+ setSelected(prev => { const n = new Set(prev); n.delete(id); return n; });
+ } catch (err) {
+ showToast(err.message, 'error');
+ }
+ }
+
+ async function handleRefresh(id) {
+ setRefreshingIds(prev => new Set(prev).add(id));
+ try {
+ const updated = await api.refreshTrackedPost(id);
+ setPosts(prev => prev.map(p => p.id === id ? updated : p));
+ } catch (err) {
+ showToast(err.message, 'error');
+ } finally {
+ setRefreshingIds(prev => { const n = new Set(prev); n.delete(id); return n; });
+ }
+ }
+
+ async function handleBulkCategory() {
+ if (!bulkCategory.trim() || selected.size === 0) return;
+ try {
+ const updates = await Promise.allSettled(
+ [...selected].map(id => api.updateTrackedPost(id, { category: bulkCategory.trim() }))
+ );
+ const succeeded = updates
+ .map((r, i) => r.status === 'fulfilled' ? { id: [...selected][i], data: r.value } : null)
+ .filter(Boolean);
+ setPosts(prev => prev.map(p => {
+ const hit = succeeded.find(s => s.id === p.id);
+ return hit ? hit.data : p;
+ }));
+ setSelected(new Set());
+ setBulkCategory('');
+ showToast(`Category assigned to ${succeeded.length} post${succeeded.length !== 1 ? 's' : ''}`);
+ } catch (err) {
+ showToast(err.message, 'error');
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="space-y-6">
+ <Skeleton className="h-8 w-48" />
+ <div className="grid grid-cols-3 gap-4">
+ <Skeleton className="h-28" />
+ <Skeleton className="h-28" />
+ <Skeleton className="h-28" />
+ </div>
+ <Skeleton className="h-64" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">Tracked Posts</h1>
+ <p className="text-sm text-muted-foreground mt-0.5">
+ Monitor score and comments on specific Reddit posts using your account cookies
+ </p>
+ </div>
+ <Button size="sm" className="gap-2 shrink-0" onClick={() => setAddOpen(true)}>
+ <Plus className="h-3.5 w-3.5" />
+ Track Post
+ </Button>
+ </div>
+
+ {/* Stat cards */}
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <StatCard icon={<BookmarkCheck />} label="Tracked Posts" value={totals.tracked} subtitle="across all categories" gradient="orange" />
+ <StatCard icon={<Tag />} label="Categories" value={totals.categories} subtitle={totals.categories === 0 ? 'none assigned yet' : `${totals.categories} group${totals.categories !== 1 ? 's' : ''}`} gradient="blue" />
+ <StatCard icon={<TrendingUp />} label="Avg Score" value={fmtNum(totals.avgScore)} subtitle="across all tracked posts" gradient="red" />
+ </div>
+
+ {/* Bulk category bar */}
+ {someSelected && (
+ <MainCard>
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-medium text-muted-foreground">{selected.size} selected</span>
+ <div className="flex-1 flex items-center gap-2">
+ <Tag className="h-4 w-4 text-muted-foreground shrink-0" />
+ <Input
+ placeholder="Category name"
+ value={bulkCategory}
+ onChange={e => setBulkCategory(e.target.value)}
+ className="h-8 max-w-xs"
+ onKeyDown={e => e.key === 'Enter' && handleBulkCategory()}
+ />
+ <Button size="sm" onClick={handleBulkCategory} disabled={!bulkCategory.trim()}>
+ Assign
+ </Button>
+ </div>
+ <Button size="sm" variant="ghost" onClick={() => setSelected(new Set())}>
+ Clear
+ </Button>
+ </div>
+ </MainCard>
+ )}
+
+ {/* Filters */}
+ <MainCard>
+ <div className="flex flex-col sm:flex-row gap-3">
+ <Input
+ placeholder="Search posts..."
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ className="flex-1"
+ />
+ {categories.length > 0 && (
+ <Select
+ value={categoryFilter}
+ onValueChange={setCategoryFilter}
+ items={[{ value: 'all', label: 'All categories' }, ...categories.map(c => ({ value: c, label: c }))]}
+ >
+ <SelectTrigger className="w-full sm:w-48">
+ <SelectValue placeholder="All categories" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All categories</SelectItem>
+ {categories.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ )}
+ <Select
+ value={sort}
+ onValueChange={setSort}
+ items={[
+ { value: 'date-desc', label: 'Newest first' },
+ { value: 'score-desc', label: 'Score (high to low)' },
+ { value: 'comments-desc', label: 'Comments (most)' },
+ ]}
+ >
+ <SelectTrigger className="w-full sm:w-52">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="date-desc">Newest first</SelectItem>
+ <SelectItem value="score-desc">Score (high to low)</SelectItem>
+ <SelectItem value="comments-desc">Comments (most)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </MainCard>
+
+ {/* Table */}
+ <MainCard content={false}>
+ {posts.length === 0 ? (
+ <div className="flex flex-col items-center text-center py-16 gap-4">
+ <div className="h-14 w-14 rounded-full bg-orange-500/10 flex items-center justify-center">
+ <Bookmark className="h-7 w-7 text-orange-500" />
+ </div>
+ <div>
+ <p className="text-sm font-semibold">No posts tracked yet</p>
+ <p className="text-xs text-muted-foreground mt-1">
+ Paste a Reddit post URL and pick which account cookie to use for fetching
+ </p>
+ </div>
+ <Button size="sm" onClick={() => setAddOpen(true)}>
+ <Plus className="h-3.5 w-3.5 mr-1.5" />
+ Track your first post
+ </Button>
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10">
+ <Checkbox
+ checked={allSelected}
+ onCheckedChange={toggleAll}
+ aria-label="Select all"
+ />
+ </TableHead>
+ <TableHead>Post</TableHead>
+ <TableHead className="w-32">Account</TableHead>
+ <TableHead className="w-28">Category</TableHead>
+ <TableHead className="text-right w-20">Score</TableHead>
+ <TableHead className="text-right w-24">Comments</TableHead>
+ <TableHead className="text-right w-20">Upvote %</TableHead>
+ <TableHead className="text-right w-28">Fetched</TableHead>
+ <TableHead className="w-24" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={9} className="text-center text-muted-foreground py-10">
+ No posts match the current filters
+ </TableCell>
+ </TableRow>
+ ) : (
+ filtered.map(post => {
+ const acc = accounts.find(a => a.id === post.accountId);
+ const isRefreshing = refreshingIds.has(post.id);
+ return (
+ <TableRow key={post.id} className={selected.has(post.id) ? 'bg-muted/30' : ''}>
+ <TableCell>
+ <Checkbox
+ checked={selected.has(post.id)}
+ onCheckedChange={() => toggleOne(post.id)}
+ aria-label={`Select ${post.title}`}
+ />
+ </TableCell>
+ <TableCell>
+ <div className="max-w-sm">
+ <p className="text-sm font-medium leading-snug line-clamp-2">
+ {post.title || post.label || post.url}
+ </p>
+ <div className="flex items-center gap-2 mt-0.5">
+ {post.subredditPrefixed && (
+ <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>
+ )}
+ {post.label && (
+ <span className="text-xs text-muted-foreground italic">{post.label}</span>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ {acc ? (
+ <div className="flex items-center gap-1.5">
+ <Avatar className="h-5 w-5 flex-shrink-0">
+ <AvatarImage src={acc.iconUrl} />
+ <AvatarFallback className="bg-orange-500 text-white text-[0.5rem] font-bold">
+ {(acc.username || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <span className="text-xs text-muted-foreground">u/{acc.username}</span>
+ </div>
+ ) : (
+ <span className="text-xs text-muted-foreground">Public</span>
+ )}
+ </TableCell>
+ <TableCell>
+ {post.category ? (
+ <Badge variant="outline" className="text-xs font-medium">
+ {post.category}
+ </Badge>
+ ) : (
+ <span className="text-xs text-muted-foreground">-</span>
+ )}
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">
+ {post.score !== undefined ? fmtNum(post.score) : '-'}
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums">
+ {post.numComments !== undefined ? fmtNum(post.numComments) : '-'}
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums">
+ {post.upvoteRatio !== undefined ? `${Math.round(post.upvoteRatio * 100)}%` : '-'}
+ </TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">
+ {post.lastFetchedAt ? fmtDate(post.lastFetchedAt) : '-'}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-0.5 justify-end">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ onClick={() => handleRefresh(post.id)}
+ disabled={isRefreshing}
+ title="Refresh live data"
+ >
+ <RefreshCw className={`h-3.5 w-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ onClick={() => openEdit(post)}
+ title="Edit label or category"
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ </Button>
+ <a href={post.permalink} target="_blank" rel="noopener noreferrer">
+ <Button variant="ghost" size="icon" className="size-7" title="Open on Reddit">
+ <ExternalLink className="h-3.5 w-3.5" />
+ </Button>
+ </a>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-destructive hover:text-destructive"
+ onClick={() => handleDelete(post.id)}
+ title="Stop tracking"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
+ )}
+ </MainCard>
+
+ {/* Add post dialog */}
+ <Dialog open={addOpen} onOpenChange={setAddOpen}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>Track a Reddit post</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4 py-2">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Post URL</label>
+ <Input
+ placeholder="https://www.reddit.com/r/.../comments/..."
+ value={addUrl}
+ onChange={e => setAddUrl(e.target.value)}
+ autoFocus
+ />
+ <p className="text-xs text-muted-foreground">
+ Paste the full URL of the Reddit post you want to track
+ </p>
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Account cookie</label>
+ <Select
+ value={addAccountId}
+ onValueChange={setAddAccountId}
+ items={[
+ { value: 'none', label: 'No cookie (public posts only)' },
+ ...redditAccounts.map(a => ({ value: a.id, label: `u/${a.username}` })),
+ ]}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">No cookie (public posts only)</SelectItem>
+ {redditAccounts.map(a => (
+ <SelectItem key={a.id} value={a.id} textValue={`u/${a.username}`}>
+ u/{a.username}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ Using a session cookie improves access from datacenter IPs
+ </p>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Label <span className="text-muted-foreground font-normal">(optional)</span></label>
+ <Input placeholder="My post" value={addLabel} onChange={e => setAddLabel(e.target.value)} />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Category <span className="text-muted-foreground font-normal">(optional)</span></label>
+ <Input placeholder="Campaign A" value={addCategory} onChange={e => setAddCategory(e.target.value)} />
+ </div>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setAddOpen(false)} disabled={adding}>Cancel</Button>
+ <Button onClick={handleAdd} disabled={adding || !addUrl.trim()}>
+ {adding ? 'Fetching...' : 'Track Post'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Edit dialog */}
+ <Dialog open={!!editPost} onOpenChange={v => !v && setEditPost(null)}>
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Edit tracked post</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4 py-2">
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Label</label>
+ <Input value={editLabel} onChange={e => setEditLabel(e.target.value)} placeholder="My post" />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-sm font-medium">Category</label>
+ <Input value={editCategory} onChange={e => setEditCategory(e.target.value)} placeholder="Campaign A" />
+ {categories.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 pt-1">
+ {categories.map(c => (
+ <button
+ key={c}
+ onClick={() => setEditCategory(c)}
+ className="text-xs px-2 py-0.5 rounded-full border border-border hover:bg-muted transition-colors"
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setEditPost(null)} disabled={saving}>Cancel</Button>
+ <Button onClick={handleSaveEdit} disabled={saving}>
+ {saving ? 'Saving...' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsx
index b4a8650..5d524b2 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, Flame,
+ Upload, Users, Settings, Flame, BookmarkCheck,
} from 'lucide-react';
import { useAppContext } from '../context/AppContext';
@@ -21,7 +21,8 @@ const NAV_GROUPS = [
{ 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 },
+ { path: '/reddit-posts', label: 'Reddit Posts', icon: Flame },
+ { path: '/reddit-tracked', label: 'Tracked Posts', icon: BookmarkCheck },
],
},
{
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 99199ae..5bbe377 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -65,6 +65,13 @@ export const api = {
getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
+ // Tracked Reddit posts
+ getTrackedPosts: () => request('/reddit/tracked-posts'),
+ addTrackedPost: (url, accountId, label, category) => request('/reddit/tracked-posts', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+ updateTrackedPost: (id, updates) => request(`/reddit/tracked-posts/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+ deleteTrackedPost: (id) => request(`/reddit/tracked-posts/${id}`, { method: 'DELETE' }),
+ refreshTrackedPost: (id) => request(`/reddit/tracked-posts/${id}/refresh`, { method: 'POST' }),
+
// GitHub settings
getGithubSettings: () => request('/settings/github'),
saveGithubSettings: (data) => request('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),