Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(accounts): check required account fields before platform API calls
spacesdrive2f75a91fa922
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bf0afb8..7c59c57 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Fixed+- Refreshing or loading an account without the field its platform needs (a YouTube channel id or uploads playlist, a Reddit username) called the platform with `undefined`; it now answers with a message that says to re-add the account. Channel analytics also refuse accounts on other platforms, and the analytics response no longer carries `bannerUrl` and `isLinked`, which are not account fields- Publishing and scheduling checked too little before calling Instagram: a missing Instagram app secret made the OAuth callback fail with a server error, posts for an account without a token or on another platform called `/undefined/media`, and a Reel still processing after the last status check was published anyway. Each case now fails with a message that says what to fix, and `GET /api/cloudinary-config` answers 503 instead of 200 when Cloudinary is not configured- The Instagram sign-in state is now checked in constant time- When Redis was unreachable, every cached request waited about 4 seconds for the cache client's retries; the cache now gives up after one quick retry and skips Redis for 30 seconds after a failurediff --git a/backend/routes/analytics.ts b/backend/routes/analytics.tsindex 0d0b1b7..43d81e5 100644--- a/backend/routes/analytics.ts+++ b/backend/routes/analytics.ts@@ -25,6 +25,8 @@ interface SnapshotScope {// no stored account has a channelTitle field, so that fallback is always undefinedtype LegacyChannelAccount = Account & { channelTitle?: string };+const NO_PLAYLIST_MESSAGE = 'No uploads playlist stored - delete this channel and add it again';+const app = new Hono<AppEnv>();// api errors can echo request urls that carry the api key or access token@@ -55,9 +57,10 @@ app.get('/accounts/:id/analytics', async (c) => {if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);const account = await getAccountById(supabase, c.req.param('id'), userId);- if (!account) return c.json({ success: false, message: 'Account not found' }, 404);+ if (!account || account.platform !== 'youtube') return c.json({ success: false, message: 'YouTube channel not found' }, 404);+ if (!account.uploadsPlaylistId) return c.json({ success: false, message: NO_PLAYLIST_MESSAGE }, 400);- const videos = await fetchAllVideos(account.uploadsPlaylistId!, apiKey, 10);+ const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);await setVideosCache(c.get('redis'), userId, c.req.param('id'), { videos, fetchedAt: new Date().toISOString() });const analytics = computeVideoAnalytics(videos);@@ -90,9 +93,10 @@ app.get('/accounts/:id/videos', async (c) => {if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);const account = await getAccountById(supabase, id, userId);- if (!account) return c.json({ success: false, message: 'Account not found' }, 404);+ if (!account || account.platform !== 'youtube') return c.json({ success: false, message: 'YouTube channel not found' }, 404);+ if (!account.uploadsPlaylistId) return c.json({ success: false, message: NO_PLAYLIST_MESSAGE }, 400);- const videos = await fetchAllVideos(account.uploadsPlaylistId!, apiKey, 10);+ const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);const fetchedAt = new Date().toISOString();await setVideosCache(redis, userId, id, { videos, fetchedAt });@@ -124,13 +128,13 @@ app.get('/accounts/:id/ig-analytics', async (c) => {if (!account || account.platform !== 'instagram') {return c.json({ success: false, message: 'Instagram account not found' }, 404);}- if (!account.accessToken) {+ if (!account.accessToken || !account.igUserId) {return c.json({ success: false, message: 'No access token stored' }, 400);}const [profile, media] = await Promise.all([fetchInstagramProfile(account.igUserId, account.accessToken),- fetchInstagramMedia(account.igUserId!, account.accessToken, 500),+ fetchInstagramMedia(account.igUserId, account.accessToken, 500),]);await storeInstagramSnapshot({ supabase, redis: c.get('redis'), userId, id }, account, profile, media);@@ -165,11 +169,11 @@ app.get('/accounts/:id/ig-media', async (c) => {if (!account || account.platform !== 'instagram') {return c.json({ success: false, message: 'Not found' }, 404);}- if (!account.accessToken) {+ if (!account.accessToken || !account.igUserId) {return c.json({ success: false, message: 'No access token' }, 400);}- const media = await fetchInstagramMedia(account.igUserId!, account.accessToken, 500);+ const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);const fetchedAt = new Date().toISOString();await setIGCache(redis, userId, id, { media, fetchedAt });diff --git a/backend/routes/reddit.ts b/backend/routes/reddit.tsindex d69d830..8b546a7 100644--- a/backend/routes/reddit.ts+++ b/backend/routes/reddit.ts@@ -17,13 +17,14 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {const account = await getAccountById(supabase, id, userId);if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);+ if (!account.username) return c.json({ error: 'No Reddit username stored - delete this account and add it again' }, 400);const cached = await getRedditCache(redis, userId, id);if (cached) return c.json(cached);const [profile, posts] = await Promise.all([- fetchRedditProfile(account.username!, account.cookie),- fetchRedditPosts(account.username!, account.cookie, 100),+ fetchRedditProfile(account.username, account.cookie),+ fetchRedditPosts(account.username, account.cookie, 100),]);const analytics = computeRedditAnalytics(profile, posts);const result: RedditCacheData = { profile, analytics, posts };@@ -46,11 +47,12 @@ router.get('/accounts/:id/reddit-posts', async (c) => {const account = await getAccountById(supabase, id, userId);if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);+ if (!account.username) return c.json({ error: 'No Reddit username stored - delete this account and add it again' }, 400);const cached = await getRedditCache(redis, userId, id);if (cached?.posts) return c.json(cached.posts);- const posts = await fetchRedditPosts(account.username!, account.cookie, 100);+ const posts = await fetchRedditPosts(account.username, account.cookie, 100);return c.json(posts);} catch (err) {console.error(`GET /accounts/${id}/reddit-posts:`, (err as Error).message);diff --git a/backend/services/accountRefresh.ts b/backend/services/accountRefresh.tsindex 8c3029f..2222666 100644--- a/backend/services/accountRefresh.ts+++ b/backend/services/accountRefresh.ts@@ -9,7 +9,7 @@ import type { YouTubeChannelData } from '../../shared/types/youtube.ts';import type { RedditProfile } from '../../shared/types/reddit.ts';import type { InstagramProfile } from '../../shared/types/instagram.ts';-type Credential = 'accessToken' | 'cookie' | 'apiKey';+type Credential = 'accessToken' | 'cookie' | 'username' | 'channelId' | 'apiKey';export type AccountRefreshOutcome = { failure: ServiceFailure; account?: undefined } | { account: Account; failure?: undefined };@@ -21,12 +21,20 @@ export interface RefreshAllOutcome {const NO_COOKIE_MESSAGE = 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools';// known issue: the two refresh paths word a missing YouTube key differently-const SINGLE_REFRESH_MESSAGES: Record<Credential, string> = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No API key' };-const REFRESH_ALL_MESSAGES: Record<Credential, string> = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No YouTube API key' };+const NO_USERNAME_MESSAGE = 'No Reddit username stored - delete this account and add it again';+const NO_CHANNEL_MESSAGE = 'No YouTube channel ID stored - delete this channel and add it again';+const SINGLE_REFRESH_MESSAGES: Record<Credential, string> = {+ accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, username: NO_USERNAME_MESSAGE, channelId: NO_CHANNEL_MESSAGE, apiKey: 'No API key',+};+const REFRESH_ALL_MESSAGES: Record<Credential, string> = { ...SINGLE_REFRESH_MESSAGES, apiKey: 'No YouTube API key' };function findMissingCredential(account: Account, apiKey: string | undefined): Credential | null {if (account.platform === 'instagram') return account.accessToken ? null : 'accessToken';- if (account.platform === 'reddit') return account.cookie ? null : 'cookie';+ if (account.platform === 'reddit') {+ if (!account.username) return 'username';+ return account.cookie ? null : 'cookie';+ }+ if (!account.channelId) return 'channelId';return apiKey ? null : 'apiKey';}@@ -69,9 +77,10 @@ function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial// fills creation dates on older accounts once; a failure only skips the extrasexport async function backfillChannelData(supabase: SupabaseClient, account: Account, apiKey: string, userId: string): Promise<void> {+ if (!account.channelId) return;try {- const channelData = await fetchChannelData(account.channelId!, apiKey);- await updateAccount(supabase, account.id, {+ const channelData = await fetchChannelData(account.channelId, apiKey);+ const updates: Partial<Account> = {publishedAt: channelData.publishedAt,subscriberCount: channelData.subscriberCount,viewCount: channelData.viewCount,@@ -81,8 +90,9 @@ export async function backfillChannelData(supabase: SupabaseClient, account: AcccustomUrl: channelData.customUrl,country: channelData.country,lastUpdated: new Date().toISOString(),- }, userId);- Object.assign(account, channelData);+ };+ await updateAccount(supabase, account.id, updates, userId);+ Object.assign(account, updates);} catch (err) {console.error('Failed to backfill channel data:', (err as Error).message);}@@ -90,14 +100,18 @@ export async function backfillChannelData(supabase: SupabaseClient, account: Accexport async function fetchAccountUpdates(account: Account, apiKey: string | undefined, full: boolean): Promise<Partial<Account>> {if (account.platform === 'instagram') {- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken!);+ if (!account.accessToken) throw new Error(SINGLE_REFRESH_MESSAGES.accessToken);+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);return instagramUpdates(profile, full);}if (account.platform === 'reddit') {- const profile = await fetchRedditProfile(account.username!, account.cookie);+ if (!account.username) throw new Error(NO_USERNAME_MESSAGE);+ const profile = await fetchRedditProfile(account.username, account.cookie);return redditUpdates(profile);}- const channelData = await fetchChannelData(account.channelId!, apiKey!);+ if (!account.channelId) throw new Error(NO_CHANNEL_MESSAGE);+ if (!apiKey) throw new Error(SINGLE_REFRESH_MESSAGES.apiKey);+ const channelData = await fetchChannelData(account.channelId, apiKey);return youtubeUpdates(channelData, full);}diff --git a/backend/services/instagramTokens.ts b/backend/services/instagramTokens.tsindex 7930d28..07912b1 100644--- a/backend/services/instagramTokens.ts+++ b/backend/services/instagramTokens.ts@@ -48,13 +48,15 @@ export async function refreshLongLivedToken(longToken: string): Promise<Instagrareturn toTokenResult(data as IssuedToken);}-function isInstagramWithToken(account: Account): string | false | null | undefined {- return account.platform === 'instagram' && account.accessToken && account.tokenExpiresAt;+type ExpiringInstagramAccount = Account & { accessToken: string; tokenExpiresAt: string };++function isInstagramWithToken(account: Account): account is ExpiringInstagramAccount {+ return account.platform === 'instagram' && !!account.accessToken && !!account.tokenExpiresAt;}-async function refreshStoredToken(supabase: SupabaseClient, account: Account): Promise<void> {+async function refreshStoredToken(supabase: SupabaseClient, account: ExpiringInstagramAccount): Promise<void> {try {- const refreshed = await refreshLongLivedToken(account.accessToken!);+ const refreshed = await refreshLongLivedToken(account.accessToken);const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });console.log(`Token refreshed for @${account.username} - expires ${tokenExpiresAt}`);diff --git a/backend/services/overviewSummary.ts b/backend/services/overviewSummary.tsindex b39f1aa..fb98eb0 100644--- a/backend/services/overviewSummary.ts+++ b/backend/services/overviewSummary.ts@@ -38,28 +38,32 @@ function startWarm(context: SummaryContext, accountId: string, task: WarmTask |}function redditWarmTask(context: SummaryContext, account: Account): WarmTask | null {- if (!account.username || !account.cookie) return null;+ const { username, cookie } = account;+ if (!username || !cookie) return null;return async () => {const [profile, posts] = await Promise.all([- fetchRedditProfile(account.username!, account.cookie),- fetchRedditPosts(account.username!, account.cookie, 100),+ fetchRedditProfile(username, cookie),+ fetchRedditPosts(username, cookie, 100),]);await setRedditCache(context.redis, context.userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });};}function instagramWarmTask(context: SummaryContext, account: Account): WarmTask | null {- if (!account.igUserId || !account.accessToken) return null;+ const { igUserId, accessToken } = account;+ if (!igUserId || !accessToken) return null;return async () => {- const media = await fetchInstagramMedia(account.igUserId!, account.accessToken!, 500);+ const media = await fetchInstagramMedia(igUserId, accessToken, 500);await setIGCache(context.redis, context.userId, account.id, { media, fetchedAt: new Date().toISOString() });};}function youtubeWarmTask(context: SummaryContext, account: Account): WarmTask | null {- if (!context.apiKey || !account.uploadsPlaylistId) return null;+ const { apiKey } = context;+ const { uploadsPlaylistId } = account;+ if (!apiKey || !uploadsPlaylistId) return null;return async () => {- const videos = await fetchAllVideos(account.uploadsPlaylistId!, context.apiKey!, 10);+ const videos = await fetchAllVideos(uploadsPlaylistId, apiKey, 10);await setVideosCache(context.redis, context.userId, account.id, { videos, fetchedAt: new Date().toISOString() });};}diff --git a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json b/backend/tests/fixtures/analyticsRoutes.youtube.golden.jsonindex bf61cb0..ca1e1e1 100644--- a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json+++ b/backend/tests/fixtures/analyticsRoutes.youtube.golden.json@@ -38,13 +38,13 @@},{"call": "GET /accounts/yt3/analytics",- "status": 200,- "body": "{\"success\":true,\"channel\":{\"id\":\"yt3\",\"platform\":\"youtube\",\"channelId\":\"UC3\",\"title\":\"Gamma\",\"customUrl\":\"@gamma\",\"publishedAt\":\"2025-09-01T00:00:00Z\",\"country\":\"Unknown\",\"thumbnails\":{\"default\":\"\",\"medium\":\"\",\"high\":\"\"},\"subscriberCount\":20,\"viewCount\":400,\"videoCount\":2,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UU3\",\"keywords\":\"\",\"bannerUrl\":\"\",\"madeForKids\":false,\"topicCategories\":[],\"isLinked\":false,\"channelAge\":365,\"channelAgeYears\":\"1.0\",\"viewsPerSubscriber\":20,\"subscriberToViewRatio\":5,\"avgViewsPerVideo\":200,\"avgSubGainPerDay\":0,\"avgViewsPerDay\":1,\"estimatedMonthlyViews\":30,\"estimatedMonthlySubGain\":0,\"estimatedYearlyViews\":365,\"estimatedYearlySubGain\":0},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"+ "status": 400,+ "body": "{\"success\":false,\"message\":\"No uploads playlist stored - delete this channel and add it again\"}"},{"call": "GET /accounts/missing/analytics","status": 404,- "body": "{\"success\":false,\"message\":\"Account not found\"}"+ "body": "{\"success\":false,\"message\":\"YouTube channel not found\"}"}],"queries": [@@ -148,54 +148,6 @@]]},- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "yt3"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",- "values": {- "platform": "youtube",- "data": {- "channelId": "UC3",- "title": "Gamma",- "publishedAt": "2025-09-01T00:00:00Z",- "subscriberCount": 20,- "viewCount": 400,- "videoCount": 2,- "thumbnails": {- "default": "",- "medium": "",- "high": ""- },- "customUrl": "@gamma",- "country": "Unknown",- "lastUpdated": "2026-09-01T12:00:00.000Z"- }- },- "filters": [- [- "id",- "yt3"- ],- [- "user_id",- "user-1"- ]- ]- },{"type": "select","table": "accounts",@@ -232,18 +184,6 @@{"url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC2&key=YTKEY","method": "GET"- },- {- "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=undefined&maxResults=50&key=YTKEY",- "method": "GET"- },- {- "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=v1&key=YTKEY",- "method": "GET"- },- {- "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC3&key=YTKEY",- "method": "GET"}],"logLines": [@@ -267,13 +207,6 @@"ex": 21600},"version": 2- },- {- "key": "videos:user-1:yt3",- "options": {- "ex": 21600- },- "version": 2}]},diff --git a/backend/tests/routes/accounts.test.ts b/backend/tests/routes/accounts.test.tsindex e531f27..d99b7f9 100644--- a/backend/tests/routes/accounts.test.ts+++ b/backend/tests/routes/accounts.test.ts@@ -2,6 +2,7 @@process.removeAllListeners('warning');import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';+import assert from 'node:assert/strict';import accountsRouter from '../../routes/accounts.ts';import { assertGolden } from '../fixtures/golden.ts';import { installFetch, reply } from '../fixtures/fakeFetch.ts';@@ -200,4 +201,22 @@ describe('accounts routes golden output', () => {['DELETE', '/accounts/ig1'],], { supabase: brokenSupabase }), 'accountsRoutes.dbFailure');});++ test('refreshing an account without a channel id or username fails before calling the platform', async () => {+ const supabase = fakeSupabase([+ accountRow({ id: 'ytOld', platform: 'youtube', title: 'No id' }),+ accountRow({ id: 'rdOld', platform: 'reddit', cookie: 'COOKIE' }),+ ]);+ const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis: fakeRedis(), userId: 'user-1' });+ const single = async (id: string) => JSON.parse((await callRoute(app, 'POST', `/accounts/${id}/refresh`, { env: ENV })).body) as unknown;+ assert.deepEqual(await single('ytOld'), { success: false, message: 'No YouTube channel ID stored - delete this channel and add it again' });+ assert.deepEqual(await single('rdOld'), { success: false, message: 'No Reddit username stored - delete this account and add it again' });++ const all = JSON.parse((await callRoute(app, 'POST', '/accounts/refresh-all', { env: ENV })).body) as { results: unknown[] };+ assert.deepEqual(all.results, [+ { id: 'ytOld', success: false, error: 'No YouTube channel ID stored - delete this channel and add it again' },+ { id: 'rdOld', success: false, error: 'No Reddit username stored - delete this account and add it again' },+ ]);+ assert.deepEqual(fetchMock!.requests, []);+ });});diff --git a/backend/tests/routes/analytics.test.ts b/backend/tests/routes/analytics.test.tsindex 4565d30..545a394 100644--- a/backend/tests/routes/analytics.test.ts+++ b/backend/tests/routes/analytics.test.ts@@ -14,7 +14,7 @@ import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';import type { RouteStep } from '../fixtures/routeHarness.ts';import type { AppEnv } from '../../types/app.ts';import type { Env } from '../../types/env.ts';-import type { YouTubeComparisonResponse } from '../../../shared/types/youtube.ts';+import type { YouTubeAnalyticsPayload, YouTubeComparisonResponse } from '../../../shared/types/youtube.ts';import assert from 'node:assert/strict';interface StoreWrite {@@ -124,6 +124,35 @@ describe('analytics and overview routes golden output', () => {assertGolden({ result, withoutKey }, 'analyticsRoutes.youtube');});+ test('channel analytics and videos refuse other platforms and channels without an uploads playlist', async () => {+ const supabase = fakeSupabase([+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1' }),+ accountRow({ id: 'ytOld', platform: 'youtube', channelId: 'UC9' }),+ ]);+ const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });+ fetchMock = installFetch(youtubeReply);+ const notChannel = { status: 404, body: JSON.stringify({ success: false, message: 'YouTube channel not found' }) };+ const noPlaylist = { status: 400, body: JSON.stringify({ success: false, message: 'No uploads playlist stored - delete this channel and add it again' }) };+ assert.deepEqual(await callRoute(app, 'GET', '/accounts/ig1/analytics', { env: ENV }), notChannel);+ assert.deepEqual(await callRoute(app, 'GET', '/accounts/ig1/videos', { env: ENV }), notChannel);+ assert.deepEqual(await callRoute(app, 'GET', '/accounts/ytOld/analytics', { env: ENV }), noPlaylist);+ assert.deepEqual(await callRoute(app, 'GET', '/accounts/ytOld/videos', { env: ENV }), noPlaylist);+ assert.deepEqual(fetchMock.requests, []);+ });++ test('backfilling an older channel adds only stored account fields to the response', async () => {+ const supabase = fakeSupabase([accountRow({ id: 'ytNew', platform: 'youtube', channelId: 'UC3', uploadsPlaylistId: 'UU3', title: 'Gamma' })]);+ const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });+ fetchMock = installFetch(youtubeReply);+ const response = await callRoute(app, 'GET', '/accounts/ytNew/analytics', { env: ENV });+ const { channel } = JSON.parse(response.body) as YouTubeAnalyticsPayload;+ assert.equal(response.status, 200);+ assert.equal(channel.publishedAt, '2025-09-01T00:00:00Z');+ assert.equal(channel.customUrl, '@gamma');+ assert.equal('bannerUrl' in channel, false);+ assert.equal('isLinked' in channel, false);+ });+test('the comparison ranks YouTube channels only and never returns stored secrets', async () => {const supabase = fakeSupabase(ACCOUNT_ROWS);const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 2f46acd..f5881e3 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -38,8 +38,8 @@ Channel metrics, the comparison and the all videos filter live in `services/yout| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/accounts/:id/analytics` | `routes/analytics.ts` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |-| GET | `/api/accounts/:id/videos` | `routes/analytics.ts` | Returns cached video list (from Redis if available) |+| GET | `/api/accounts/:id/analytics` | `routes/analytics.ts` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics; 404 for an account that is not a YouTube channel, 400 when no uploads playlist is stored |+| GET | `/api/accounts/:id/videos` | `routes/analytics.ts` | Returns cached video list (from Redis if available); the same 404 and 400 checks before a live fetch || GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.ts` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` || GET | `/api/accounts/:id/ig-media` | `routes/analytics.ts` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss || GET | `/api/comparison` | `routes/analytics.ts` | Cross-account comparison data for the Overview dashboard |@@ -73,7 +73,7 @@ Channel metrics, the comparison and the all videos filter live in `services/yout| Method | Path | File | Purpose ||---|---|---|---|| POST | `/api/accounts/reddit` | `routes/accounts.ts` | Add Reddit account by username + optional session cookie |-| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.ts` | Fetch profile + posts + computed analytics; cached in Redis |+| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.ts` | Fetch profile + posts + computed analytics; cached in Redis; 400 when the cookie or username is missing || GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.ts` | Returns cached post list or live-fetched posts |### Overviewdiff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 961d167..253b757 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -154,7 +154,7 @@ The account routes in `routes/accounts.ts` only parse the request, check require|---|---|| `accountFactory.ts` | Pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount` || `accountConnect.ts` | `addYouTubeAccount`, `addRedditAccount`, `addInstagramAccount` (tries the long-lived exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails), `refreshInstagramToken` |-| `accountRefresh.ts` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (`Promise.allSettled`, results aligned with the account list by index), `backfillChannelData` (fills channel fields for a YouTube account without `publishedAt` when its analytics load; a failure is logged and skipped) |+| `accountRefresh.ts` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (both check the fields the platform call needs first: an Instagram token, a Reddit username and cookie, a YouTube channel id and API key) (`Promise.allSettled`, results aligned with the account list by index), `backfillChannelData` (fills channel fields for a YouTube account without `publishedAt` when its analytics load; a failure is logged and skipped) |Duplicate accounts throw an `Error` whose message the route returns with status 400, the same shape as any other failure. Failures that need another status (404 for a missing account, 400 for a missing credential) come back as `{ failure: { status, message } }`.diff --git a/frontend/src/hooks/use-account-analytics.ts b/frontend/src/hooks/use-account-analytics.tsindex 0d6b4eb..05dfad4 100644--- a/frontend/src/hooks/use-account-analytics.ts+++ b/frontend/src/hooks/use-account-analytics.ts@@ -38,9 +38,10 @@ export function useAccountAnalytics<P, A>(useEffect(() => { loadAnalytics(); }, [loadAnalytics]);const handleRefresh = async () => {+ if (!accountId) return;setRefreshing(true);try {- await api.refreshAccount(accountId!);+ await api.refreshAccount(accountId);await loadAnalytics();showToast(`${label} account refreshed`);} catch (err) {