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(analytics): make analytics edge cases consistent
spacesdrive208b6c44c9fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 653b8b5..0e6dc4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Fixed+- YouTube analytics counted hidden like and comment counts as zero, which pulled averages and engagement rates down; averages and rates now use only the videos that report each count, and hidden counts sort last (see `docs/architecture/data-flows/ANALYTICS.md`). A channel with no videos now returns the same fields and formats as a full result, a Reddit profile without karma totals reports 0 instead of NaN, and date checks use `getTime()`- Saving the scheduling repository in Settings erased the stored GitHub token and then reported `configured: false` and `patSet: false`. The unused token is no longer stored or reported: `GET /api/settings/github` returns only `repoOwner`, `repoName` and `branch`- 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 configureddiff --git a/backend/services/analyticsMath.ts b/backend/services/analyticsMath.tsindex 089f0c1..3f2ab9e 100644--- a/backend/services/analyticsMath.ts+++ b/backend/services/analyticsMath.ts@@ -7,6 +7,29 @@ export function sumOf<T>(items: T[], pickValue: (item: T) => number): number {return items.reduce((total, item) => total + pickValue(item), 0);}+// a hidden count (null) is left out: not added, and its views are not in the rate's base+export interface ReportedCount {+ total: number;+ items: number;+ views: number;+}++export function reportedCount<T extends { viewCount: number }>(items: T[], pick: (item: T) => number | null | undefined): ReportedCount {+ const counted: ReportedCount = { total: 0, items: 0, views: 0 };+ for (const item of items) {+ const value = pick(item);+ if (value === null || value === undefined) continue;+ counted.total += value;+ counted.items++;+ counted.views += item.viewCount;+ }+ return counted;+}++export function percentOfReportedViews(count: ReportedCount): number {+ return count.views > 0 ? (count.total / count.views) * 100 : 0;+}+export function roundedAverage(total: number, count: number): number {return count > 0 ? Math.round(total / count) : 0;}@@ -50,8 +73,8 @@ export function bestToAverageRatio(best: number, average: number): number {return average > 0 ? parseFloat((best / average).toFixed(1)) : 0;}-// undefined for an empty array-export function pickHighest<T extends Record<K, number>, K extends keyof T>(items: T[], field: K): T {+export function pickHighest<T extends Record<K, number>, K extends keyof T>(items: T[], field: K): T | undefined {+ if (items.length === 0) return undefined;return items.reduce((best, item) => item[field] > best[field] ? item : best, items[0]);}diff --git a/backend/services/instagramAnalytics.ts b/backend/services/instagramAnalytics.tsindex 62bd8ff..f785e23 100644--- a/backend/services/instagramAnalytics.ts+++ b/backend/services/instagramAnalytics.ts@@ -102,7 +102,7 @@ export function computeInstagramAnalytics(profile: AnalyticsProfile, media: Instconst engagement = summarizeEngagement(profile, media);const contentTypeStats = buildContentTypeStats(media);- const dates = media.map(item => new Date(item.timestamp)).filter(date => !isNaN(date as unknown as number));+ const dates = media.map(item => new Date(item.timestamp)).filter(date => !Number.isNaN(date.getTime()));const topPosts = rankTopPosts(media);const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;diff --git a/backend/services/instagramTiming.ts b/backend/services/instagramTiming.tsindex 4c10986..5924413 100644--- a/backend/services/instagramTiming.ts+++ b/backend/services/instagramTiming.ts@@ -56,7 +56,7 @@ function buildMonthlyBreakdown(media: InstagramMedia[]): InstagramMonthStats[] {const months: Record<string, MonthTotals> = {};media.forEach(item => {const date = new Date(item.timestamp);- if (isNaN(date as unknown as number)) return;+ if (Number.isNaN(date.getTime())) return;const key = monthKey(date);if (!months[key]) months[key] = { posts: 0, likes: 0, comments: 0 };months[key].posts++;@@ -82,7 +82,7 @@ export function summarizeTiming(dates: Date[], media: InstagramMedia[]): Instagrconst bestHour = pickHighest(postsByHour, 'avgEngagement');return {postsByDayOfWeek, bestPostingDay: bestDay?.day || '',- postsByHour, bestPostingHour: bestHour?.posts > 0 ? bestHour.label : '',+ postsByHour, bestPostingHour: bestHour && bestHour.posts > 0 ? bestHour.label : '',engagementTimeline: monthlyBreakdown, monthlyBreakdown,};}diff --git a/backend/services/reddit.ts b/backend/services/reddit.tsindex 284635b..8454cdc 100644--- a/backend/services/reddit.ts+++ b/backend/services/reddit.ts@@ -15,8 +15,8 @@ interface RedditApiError {interface RedditApiUser {name: string;total_karma?: number;- link_karma: number;- comment_karma: number;+ link_karma?: number;+ comment_karma?: number;awardee_karma?: number;awarder_karma?: number;icon_img?: string;@@ -82,7 +82,7 @@ export async function fetchRedditProfile(username: string, cookie: RedditCookie)const user = data.data;return {username: user.name,- totalKarma: user.total_karma ?? (user.link_karma + user.comment_karma),+ totalKarma: user.total_karma ?? ((user.link_karma ?? 0) + (user.comment_karma ?? 0)),postKarma: user.link_karma ?? 0,commentKarma: user.comment_karma ?? 0,awardeeKarma: user.awardee_karma ?? 0,diff --git a/backend/services/redditAnalytics.ts b/backend/services/redditAnalytics.tsindex 74e25b2..cb95069 100644--- a/backend/services/redditAnalytics.ts+++ b/backend/services/redditAnalytics.ts@@ -105,7 +105,7 @@ function summarizeTiming(dates: Date[], posts: RedditPost[]): TimingSummary {const bestHour = pickHighest(postsByHour, 'avgScore');return {postsByDayOfWeek, bestPostingDay: bestDay?.day ?? '',- postsByHour, bestPostingHour: bestHour?.posts > 0 ? bestHour.label : '',+ postsByHour, bestPostingHour: bestHour && bestHour.posts > 0 ? bestHour.label : '',};}@@ -120,7 +120,7 @@ function buildMonthlyBreakdown(posts: RedditPost[]): RedditMonthStats[] {posts.forEach(post => {if (!post.createdAt) return;const date = new Date(post.createdAt);- if (isNaN(date as unknown as number)) return;+ if (Number.isNaN(date.getTime())) return;const key = monthKey(date);if (!months[key]) months[key] = { posts: 0, score: 0, comments: 0 };months[key].posts++;diff --git a/backend/services/youtubeAnalytics.ts b/backend/services/youtubeAnalytics.tsindex 83c0484..3a7acda 100644--- a/backend/services/youtubeAnalytics.ts+++ b/backend/services/youtubeAnalytics.ts@@ -1,8 +1,8 @@-import { DAY_MS, sumOf, roundedAverage, medianOf } from './analyticsMath.ts';+import { DAY_MS, sumOf, roundedAverage, medianOf, reportedCount } from './analyticsMath.ts';import { parseDuration, formatDuration, formatVideoSummary } from './youtubeFormat.ts';import {buildPublishTiming, buildCategoryDistribution, buildTagFrequency, countRecentUploads,- buildUploadFrequency, weeklyConsistencyScore, buildViewsDistribution, buildMonthlyTrends,+ buildUploadFrequency, weeklyConsistencyScore, buildViewsDistribution, buildMonthlyTrends, engagementRateOf,} from './youtubeTrends.ts';import type { VideoAnalytics, YouTubeVideo, YouTubeDurationDistribution } from '../../shared/types/youtube.ts';@@ -54,30 +54,32 @@ interface FlagSummary {// shorts are judged by duration alone: any video up to 60 seconds countsconst SHORT_MAX_SECONDS = 60;+// the same fields and formats as a full result, so the client never meets a different typefunction emptyVideoAnalytics(): VideoAnalytics {return {totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,totalEngagement: 0, overallEngagementRate: 0,- avgDurationSeconds: 0, avgDurationFormatted: '0:00',- totalDurationSeconds: 0, totalDurationFormatted: '0:00',+ avgDurationSeconds: 0, avgDurationFormatted: formatDuration(0),+ totalDurationSeconds: 0, totalDurationFormatted: formatDuration(0),+ estimatedTotalWatchTimeHours: 0,bestByViews: null, bestByLikes: null, bestByComments: null,bestByEngagement: null, worstByViews: null,mostRecent: null, oldest: null,top10ByViews: [], top10ByLikes: [], top10ByComments: [], top10ByEngagement: [],shortsCount: 0, regularCount: 0,- avgShortViews: 0, avgRegularViews: 0,- hdCount: 0, sdCount: 0, hdPercentage: 0,- captionCount: 0, captionPercentage: 0,- licensedCount: 0, licensedPercentage: 0,- madeForKidsCount: 0, embeddableCount: 0,+ avgShortViews: 0, avgRegularViews: 0, avgShortLikes: 0, avgRegularLikes: 0,+ hdCount: 0, sdCount: 0, hdPercentage: percentOf(0, 0),+ captionCount: 0, captionPercentage: percentOf(0, 0),+ licensedCount: 0, licensedPercentage: percentOf(0, 0),+ madeForKidsCount: 0, embeddableCount: 0, embeddablePercentage: percentOf(0, 0),publishDayDistribution: {}, publishHourDistribution: {},peakPublishDay: '', peakPublishHour: 0,durationDistribution: { short: 0, medium: 0, long: 0, veryLong: 0 },categoryDistribution: {},tagFrequency: [],videosLast7Days: 0, videosLast30Days: 0, videosLast90Days: 0, videosLast365Days: 0,- uploadFrequencyPerWeek: 0, uploadFrequencyPerMonth: 0,+ uploadFrequencyPerWeek: '0.0', uploadFrequencyPerMonth: '0.0',consistencyScore: 0, viralityScore: 0,viewsDistribution: { ranges: [], counts: [] },engagementTrend: [], viewsTrend: [], likeRateTrend: [],@@ -88,40 +90,53 @@ function rateOfViews(count: number, video: YouTubeVideo): number {return video.viewCount > 0 ? (count / video.viewCount) * 100 : 0;}-// hidden counts are null, which adds, subtracts and divides as zero+// a video's own rates count what it reports; a hidden count adds nothingfunction withEngagementRates(video: YouTubeVideo, now: Date): EnrichedVideo {+ const likes = video.likeCount ?? 0;+ const comments = video.commentCount ?? 0;return {...video,- engagementRate: rateOfViews((video.likeCount as number) + (video.commentCount as number), video),- likeRate: rateOfViews(video.likeCount as number, video),- commentRate: rateOfViews(video.commentCount as number, video),+ engagementRate: rateOfViews(likes + comments, video),+ likeRate: rateOfViews(likes, video),+ commentRate: rateOfViews(comments, video),durationSeconds: parseDuration(video.duration),- daysSinceUpload: Math.max(1, Math.floor(((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) / DAY_MS)),+ daysSinceUpload: Math.max(1, Math.floor((now.getTime() - new Date(video.publishedAt).getTime()) / DAY_MS)),};}+// hidden counts sort after every reported count, zero included+function byReportedCount(pick: (video: YouTubeVideo) => number | null) {+ return (first: YouTubeVideo, second: YouTubeVideo) => (pick(second) ?? -1) - (pick(first) ?? -1);+}+function sortVideos(videos: EnrichedVideo[]): SortedVideos {return {byViews: [...videos].sort((first, second) => second.viewCount - first.viewCount),- byLikes: [...videos].sort((first, second) => (second.likeCount as number) - (first.likeCount as number)),- byComments: [...videos].sort((first, second) => (second.commentCount as number) - (first.commentCount as number)),- byDate: [...videos].sort((first, second) => (new Date(second.publishedAt) as unknown as number) - (new Date(first.publishedAt) as unknown as number)),+ byLikes: [...videos].sort(byReportedCount(video => video.likeCount)),+ byComments: [...videos].sort(byReportedCount(video => video.commentCount)),+ byDate: [...videos].sort((first, second) => new Date(second.publishedAt).getTime() - new Date(first.publishedAt).getTime()),byEngagement: [...videos].sort((first, second) => second.engagementRate - first.engagementRate),};}+function reportedAverage(videos: YouTubeVideo[], pick: (video: YouTubeVideo) => number | null): number {+ const count = reportedCount(videos, pick);+ return roundedAverage(count.total, count.items);+}++// averages and rates use only the videos that report a count, so hidden counts never pull them downfunction summarizeTotals(videos: YouTubeVideo[]): VideoTotals {const totalViews = sumOf(videos, video => video.viewCount);- const totalLikes = sumOf(videos, video => video.likeCount as number);- const totalComments = sumOf(videos, video => video.commentCount as number);+ const totalLikes = sumOf(videos, video => video.likeCount ?? 0);+ const totalComments = sumOf(videos, video => video.commentCount ?? 0);return {totalViews, totalLikes, totalComments,avgViews: Math.round(totalViews / videos.length),- avgLikes: Math.round(totalLikes / videos.length),- avgComments: Math.round(totalComments / videos.length),+ avgLikes: reportedAverage(videos, video => video.likeCount),+ avgComments: reportedAverage(videos, video => video.commentCount),medianViews: medianOf(videos.map(video => video.viewCount)),totalEngagement: totalLikes + totalComments,- overallEngagementRate: totalViews > 0 ? ((totalLikes + totalComments) / totalViews * 100).toFixed(2) : 0,+ overallEngagementRate: engagementRateOf(videos),};}@@ -161,13 +176,13 @@ function summarizeShorts(videos: EnrichedVideo[]): ShortsSummary {regularCount: regular.length,avgShortViews: roundedAverage(sumOf(shorts, video => video.viewCount), shorts.length),avgRegularViews: roundedAverage(sumOf(regular, video => video.viewCount), regular.length),- avgShortLikes: roundedAverage(sumOf(shorts, video => video.likeCount as number), shorts.length),- avgRegularLikes: roundedAverage(sumOf(regular, video => video.likeCount as number), regular.length),+ avgShortLikes: reportedAverage(shorts, video => video.likeCount),+ avgRegularLikes: reportedAverage(regular, video => video.likeCount),};}function percentOf(count: number, total: number): string {- return ((count / total) * 100).toFixed(1);+ return (total > 0 ? (count / total) * 100 : 0).toFixed(1);}function summarizeFlags(videos: YouTubeVideo[]): FlagSummary {diff --git a/backend/services/youtubeTrends.ts b/backend/services/youtubeTrends.tsindex 52476da..b52c3b2 100644--- a/backend/services/youtubeTrends.ts+++ b/backend/services/youtubeTrends.ts@@ -1,4 +1,4 @@-import { DAY_NAMES, DAY_MS, monthKey } from './analyticsMath.ts';+import { DAY_NAMES, DAY_MS, monthKey, reportedCount, percentOfReportedViews } from './analyticsMath.ts';import { formatCompact } from './youtubeFormat.ts';import type {VideoAnalytics, YouTubeVideo, YouTubeTagCount, YouTubeViewsDistribution, YouTubeMonthlyTrends, FormattedRate,@@ -12,13 +12,6 @@ export interface YouTubeUploadFrequency {uploadFrequencyPerMonth: string;}-interface MonthTotals {- views: number;- likes: number;- comments: number;- count: number;-}-const WEEK_MS = 7 * DAY_MS;const HISTOGRAM_BUCKETS = 10;const MAX_TAGS = 30;@@ -72,7 +65,7 @@ export function buildTagFrequency(videos: YouTubeVideo[]): YouTubeTagCount[] {// strict < unlike instagram and reddit (inclusive), to match stored analyticsexport function countRecentUploads(videos: YouTubeVideo[], now: Date): YouTubeRecentUploads {- const uploadedWithin = (days: number) => videos.filter(video => ((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) < days * DAY_MS).length;+ const uploadedWithin = (days: number) => videos.filter(video => (now.getTime() - new Date(video.publishedAt).getTime()) < days * DAY_MS).length;return {videosLast7Days: uploadedWithin(7),videosLast30Days: uploadedWithin(30),@@ -83,7 +76,7 @@ export function countRecentUploads(videos: YouTubeVideo[], now: Date): YouTubeReexport function buildUploadFrequency(videoCount: number, oldestVideo: YouTubeVideo | undefined, now: Date): YouTubeUploadFrequency {const oldestDate = new Date(oldestVideo?.publishedAt || now);- const totalWeeks = Math.max(1, ((now as unknown as number) - (oldestDate as unknown as number)) / WEEK_MS);+ const totalWeeks = Math.max(1, (now.getTime() - oldestDate.getTime()) / WEEK_MS);const totalMonths = Math.max(1, totalWeeks / 4.33);return {uploadFrequencyPerWeek: (videoCount / totalWeeks).toFixed(1),@@ -94,7 +87,7 @@ export function buildUploadFrequency(videoCount: number, oldestVideo: YouTubeVid// scores how evenly uploads spread across the weeks that have anyexport function weeklyConsistencyScore(videos: YouTubeVideo[], now: Date): number {const weeklyUploads = videos.reduce<Record<number, number>>((weeks, video) => {- const weekNumber = Math.floor(((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) / WEEK_MS);+ const weekNumber = Math.floor((now.getTime() - new Date(video.publishedAt).getTime()) / WEEK_MS);weeks[weekNumber] = (weeks[weekNumber] || 0) + 1;return weeks;}, {});@@ -120,29 +113,33 @@ export function buildViewsDistribution(videos: YouTubeVideo[], maxViews: number)return { ranges, counts };}-function percentOfViews(count: number, views: number): FormattedRate {- return views > 0 ? ((count / views) * 100).toFixed(2) : 0;+// hidden counts are left out: each rate's base is the views of the videos that report that count+export function engagementRateOf(videos: YouTubeVideo[]): FormattedRate {+ const likes = reportedCount(videos, video => video.likeCount);+ const comments = reportedCount(videos, video => video.commentCount);+ if (likes.views === 0 && comments.views === 0) return 0;+ return (percentOfReportedViews(likes) + percentOfReportedViews(comments)).toFixed(2);+}++function likeRateOf(videos: YouTubeVideo[]): FormattedRate {+ const likes = reportedCount(videos, video => video.likeCount);+ return likes.views > 0 ? percentOfReportedViews(likes).toFixed(2) : 0;}export function buildMonthlyTrends(videos: YouTubeVideo[]): YouTubeMonthlyTrends {- const months: Record<string, MonthTotals> = {};+ const months: Record<string, YouTubeVideo[]> = {};videos.forEach(video => {const key = monthKey(new Date(video.publishedAt));- if (!months[key]) months[key] = { views: 0, likes: 0, comments: 0, count: 0 };- months[key].views += video.viewCount;- months[key].likes += video.likeCount as number;- months[key].comments += video.commentCount as number;- months[key].count++;+ (months[key] ??= []).push(video);});const sortedMonths = Object.keys(months).sort();return {- viewsTrend: sortedMonths.map(month => ({ month, value: months[month].views, count: months[month].count })),- engagementTrend: sortedMonths.map(month => ({+ viewsTrend: sortedMonths.map(month => ({month,- value: months[month].views > 0- ? ((months[month].likes + months[month].comments) / months[month].views * 100).toFixed(2)- : 0,+ value: months[month].reduce((total, video) => total + video.viewCount, 0),+ count: months[month].length,})),- likeRateTrend: sortedMonths.map(month => ({ month, value: percentOfViews(months[month].likes, months[month].views) })),+ engagementTrend: sortedMonths.map(month => ({ month, value: engagementRateOf(months[month]) })),+ likeRateTrend: sortedMonths.map(month => ({ month, value: likeRateOf(months[month]) })),};}diff --git a/backend/tests/fixtures/reddit.profile.golden.json b/backend/tests/fixtures/reddit.profile.golden.jsonindex 1e32c0b..8c0a22b 100644--- a/backend/tests/fixtures/reddit.profile.golden.json+++ b/backend/tests/fixtures/reddit.profile.golden.json@@ -28,7 +28,7 @@},{"username": "empty",- "totalKarma": "[NaN]",+ "totalKarma": 0,"postKarma": 0,"commentKarma": 0,"awardeeKarma": 0,diff --git a/backend/tests/fixtures/youtubeAnalytics.empty.golden.json b/backend/tests/fixtures/youtubeAnalytics.empty.golden.jsonindex 1ff175c..992ca62 100644--- a/backend/tests/fixtures/youtubeAnalytics.empty.golden.json+++ b/backend/tests/fixtures/youtubeAnalytics.empty.golden.json@@ -11,9 +11,10 @@"totalEngagement": 0,"overallEngagementRate": 0,"avgDurationSeconds": 0,- "avgDurationFormatted": "0:00",+ "avgDurationFormatted": "0m 0s","totalDurationSeconds": 0,- "totalDurationFormatted": "0:00",+ "totalDurationFormatted": "0m 0s",+ "estimatedTotalWatchTimeHours": 0,"bestByViews": null,"bestByLikes": null,"bestByComments": null,@@ -29,15 +30,18 @@"regularCount": 0,"avgShortViews": 0,"avgRegularViews": 0,+ "avgShortLikes": 0,+ "avgRegularLikes": 0,"hdCount": 0,"sdCount": 0,- "hdPercentage": 0,+ "hdPercentage": "0.0","captionCount": 0,- "captionPercentage": 0,+ "captionPercentage": "0.0","licensedCount": 0,- "licensedPercentage": 0,+ "licensedPercentage": "0.0","madeForKidsCount": 0,"embeddableCount": 0,+ "embeddablePercentage": "0.0","publishDayDistribution": {},"publishHourDistribution": {},"peakPublishDay": "",@@ -54,8 +58,8 @@"videosLast30Days": 0,"videosLast90Days": 0,"videosLast365Days": 0,- "uploadFrequencyPerWeek": 0,- "uploadFrequencyPerMonth": 0,+ "uploadFrequencyPerWeek": "0.0",+ "uploadFrequencyPerMonth": "0.0","consistencyScore": 0,"viralityScore": 0,"viewsDistribution": {@@ -78,9 +82,10 @@"totalEngagement": 0,"overallEngagementRate": 0,"avgDurationSeconds": 0,- "avgDurationFormatted": "0:00",+ "avgDurationFormatted": "0m 0s","totalDurationSeconds": 0,- "totalDurationFormatted": "0:00",+ "totalDurationFormatted": "0m 0s",+ "estimatedTotalWatchTimeHours": 0,"bestByViews": null,"bestByLikes": null,"bestByComments": null,@@ -96,15 +101,18 @@"regularCount": 0,"avgShortViews": 0,"avgRegularViews": 0,+ "avgShortLikes": 0,+ "avgRegularLikes": 0,"hdCount": 0,"sdCount": 0,- "hdPercentage": 0,+ "hdPercentage": "0.0","captionCount": 0,- "captionPercentage": 0,+ "captionPercentage": "0.0","licensedCount": 0,- "licensedPercentage": 0,+ "licensedPercentage": "0.0","madeForKidsCount": 0,"embeddableCount": 0,+ "embeddablePercentage": "0.0","publishDayDistribution": {},"publishHourDistribution": {},"peakPublishDay": "",@@ -121,8 +129,8 @@"videosLast30Days": 0,"videosLast90Days": 0,"videosLast365Days": 0,- "uploadFrequencyPerWeek": 0,- "uploadFrequencyPerMonth": 0,+ "uploadFrequencyPerWeek": "0.0",+ "uploadFrequencyPerMonth": "0.0","consistencyScore": 0,"viralityScore": 0,"viewsDistribution": {diff --git a/backend/tests/fixtures/youtubeAnalytics.generated.golden.json b/backend/tests/fixtures/youtubeAnalytics.generated.golden.jsonindex febf302..9c37cb3 100644--- a/backend/tests/fixtures/youtubeAnalytics.generated.golden.json+++ b/backend/tests/fixtures/youtubeAnalytics.generated.golden.json@@ -4,11 +4,11 @@"totalLikes": 11590,"totalComments": 1575,"avgViews": 23305,- "avgLikes": 322,- "avgComments": 44,+ "avgLikes": 414,+ "avgComments": 53,"medianViews": 22745,"totalEngagement": 13165,- "overallEngagementRate": "1.57",+ "overallEngagementRate": "2.05","avgDurationSeconds": 5379,"avgDurationFormatted": "1h 29m","totalDurationSeconds": 193650,@@ -544,7 +544,7 @@"avgShortViews": 0,"avgRegularViews": 23971,"avgShortLikes": 0,- "avgRegularLikes": 331,+ "avgRegularLikes": 414,"hdCount": 36,"sdCount": 0,"hdPercentage": "100.0",@@ -800,23 +800,23 @@"engagementTrend": [{"month": "2025-10",- "value": "1.09"+ "value": "1.96"},{"month": "2025-11",- "value": "1.09"+ "value": "1.52"},{"month": "2025-12",- "value": "6.44"+ "value": "6.87"},{"month": "2026-01",- "value": "1.39"+ "value": "2.20"},{"month": "2026-02",- "value": "2.98"+ "value": "3.68"},{"month": "2026-03",@@ -824,19 +824,19 @@},{"month": "2026-04",- "value": "2.83"+ "value": "6.45"},{"month": "2026-05",- "value": "0.73"+ "value": "0.96"},{"month": "2026-06",- "value": "1.98"+ "value": "2.00"},{"month": "2026-07",- "value": "0.30"+ "value": "0.43"},{"month": "2026-08",@@ -846,11 +846,11 @@"likeRateTrend": [{"month": "2025-10",- "value": "0.60"+ "value": "1.09"},{"month": "2025-11",- "value": "0.85"+ "value": "1.28"},{"month": "2025-12",@@ -858,11 +858,11 @@},{"month": "2026-01",- "value": "1.21"+ "value": "2.02"},{"month": "2026-02",- "value": "2.73"+ "value": "3.29"},{"month": "2026-03",@@ -870,11 +870,11 @@},{"month": "2026-04",- "value": "2.57"+ "value": "6.06"},{"month": "2026-05",- "value": "0.64"+ "value": "0.87"},{"month": "2026-06",@@ -882,7 +882,7 @@},{"month": "2026-07",- "value": "0.26"+ "value": "0.39"},{"month": "2026-08",diff --git a/backend/tests/fixtures/youtubeAnalytics.rich.golden.json b/backend/tests/fixtures/youtubeAnalytics.rich.golden.jsonindex 641c7a6..83ae2b4 100644--- a/backend/tests/fixtures/youtubeAnalytics.rich.golden.json+++ b/backend/tests/fixtures/youtubeAnalytics.rich.golden.json@@ -4,11 +4,11 @@"totalLikes": 67365,"totalComments": 4629,"avgViews": 124948,- "avgLikes": 6124,- "avgComments": 421,+ "avgLikes": 7485,+ "avgComments": 514,"medianViews": 5400,"totalEngagement": 71994,- "overallEngagementRate": "5.24",+ "overallEngagementRate": "5.26","avgDurationSeconds": 1294,"avgDurationFormatted": "21m 34s","totalDurationSeconds": 14239,@@ -292,6 +292,17 @@"engagementRate": "7.79","durationSeconds": 0},+ {+ "videoId": "v11",+ "title": "Video v11",+ "viewCount": 1,+ "likeCount": 0,+ "commentCount": 0,+ "publishedAt": "2024-01-01T00:00:00Z",+ "thumbnail": "https://i/v11/m.jpg",+ "engagementRate": "0.00",+ "durationSeconds": 1800+ },{"videoId": "v02","title": "Video v02",@@ -302,17 +313,6 @@"thumbnail": "https://i/v02/m.jpg","engagementRate": "0.57","durationSeconds": 492- },- {- "videoId": "v05",- "title": "Video v05",- "viewCount": 0,- "likeCount": null,- "commentCount": null,- "publishedAt": "2026-07-14T06:30:00Z",- "thumbnail": "https://i/v05/m.jpg",- "engagementRate": "0.00",- "durationSeconds": 600}],"top10ByComments": [@@ -404,6 +404,17 @@"engagementRate": "7.79","durationSeconds": 0},+ {+ "videoId": "v11",+ "title": "Video v11",+ "viewCount": 1,+ "likeCount": 0,+ "commentCount": 0,+ "publishedAt": "2024-01-01T00:00:00Z",+ "thumbnail": "https://i/v11/m.jpg",+ "engagementRate": "0.00",+ "durationSeconds": 1800+ },{"videoId": "v03","title": "Video v03",@@ -414,17 +425,6 @@"thumbnail": "https://i/v03/m.jpg","engagementRate": "3.89","durationSeconds": 60- },- {- "videoId": "v05",- "title": "Video v05",- "viewCount": 0,- "likeCount": null,- "commentCount": null,- "publishedAt": "2026-07-14T06:30:00Z",- "thumbnail": "https://i/v05/m.jpg",- "engagementRate": "0.00",- "durationSeconds": 600}],"top10ByEngagement": [@@ -544,7 +544,7 @@"avgShortViews": 53585,"avgRegularViews": 184417,"avgShortLikes": 2629,- "avgRegularLikes": 9037,+ "avgRegularLikes": 13555,"hdCount": 9,"sdCount": 2,"hdPercentage": "81.8",@@ -704,7 +704,7 @@},{"month": "2026-08",- "value": "4.90"+ "value": "5.13"}],"likeRateTrend": [@@ -734,7 +734,7 @@},{"month": "2026-08",- "value": "4.31"+ "value": "4.51"}]}diff --git a/backend/tests/fixtures/youtubeAnalytics.small.golden.json b/backend/tests/fixtures/youtubeAnalytics.small.golden.jsonindex a086e55..22d671e 100644--- a/backend/tests/fixtures/youtubeAnalytics.small.golden.json+++ b/backend/tests/fixtures/youtubeAnalytics.small.golden.json@@ -247,11 +247,11 @@"totalLikes": 210,"totalComments": 31,"avgViews": 5400,- "avgLikes": 105,- "avgComments": 16,+ "avgLikes": 210,+ "avgComments": 31,"medianViews": 5400,"totalEngagement": 241,- "overallEngagementRate": "2.23",+ "overallEngagementRate": "4.46","avgDurationSeconds": 276,"avgDurationFormatted": "4m 36s","totalDurationSeconds": 552,@@ -518,13 +518,13 @@"engagementTrend": [{"month": "2026-08",- "value": "2.23"+ "value": "4.46"}],"likeRateTrend": [{"month": "2026-08",- "value": "1.94"+ "value": "3.89"}]},diff --git a/backend/tests/services/analyticsMath.test.ts b/backend/tests/services/analyticsMath.test.tsindex f9f51d6..1e67254 100644--- a/backend/tests/services/analyticsMath.test.ts+++ b/backend/tests/services/analyticsMath.test.ts@@ -55,7 +55,7 @@ describe('analyticsMath', () => {assert.equal(bestToAverageRatio(50, 12), 4.2);assert.equal(bestToAverageRatio(50, 0), 0);const items = [{ id: 'a', value: 1 }, { id: 'b', value: 3 }, { id: 'c', value: 3 }];- assert.equal(pickHighest(items, 'value').id, 'b');+ assert.equal(pickHighest(items, 'value')?.id, 'b');assert.equal(pickHighest([], 'value'), undefined);});diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex 2ef674e..68e0fec 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -63,6 +63,25 @@ Typed as `VideoAnalytics` in `shared/types/youtube.ts`.}```+### Hidden like and comment counts++YouTube hides a video's like count when the owner turns likes off, and its comment count when comments are off. Since cache version 2 these arrive as `null`, and the analytics never count them as zero:++| Metric | Rule |+|---|---|+| `totalLikes`, `totalComments`, `totalEngagement` | Sum of the reported counts; a hidden count adds nothing |+| `avgLikes`, `avgComments`, `avgShortLikes`, `avgRegularLikes` | Divided by the number of videos that report the count, not by every video |+| `overallEngagementRate`, `engagementTrend` | Likes as a percentage of the views of videos that report likes, plus comments as a percentage of the views of videos that report comments. With every count reported this equals (likes + comments) / views |+| `likeRateTrend` | Likes as a percentage of the views of videos that report likes, per month |+| A video's own `engagementRate` | Counts what that video reports |+| `bestByLikes`, `top10ByLikes`, and the comment equivalents | Videos with a hidden count sort after every reported count, including zero |++The same rule applies to Instagram views (`viewCount: null`), which are shown as `-`.++### Empty channels++A channel with no public videos returns the same fields and formats as a full result: zero counts, `null` rankings, `'0m 0s'` durations and `'0.0'` percentages and upload frequencies.+## Instagram Analytics Flow```diff --git a/frontend/src/features/analytics/reddit/redditPostUtils.ts b/frontend/src/features/analytics/reddit/redditPostUtils.tsindex dbc6e6d..7d9a002 100644--- a/frontend/src/features/analytics/reddit/redditPostUtils.ts+++ b/frontend/src/features/analytics/reddit/redditPostUtils.ts@@ -41,8 +41,8 @@ export function filterAndSortRedditPosts<T extends RedditPostRow>(posts: T[], {if (sort === 'score-desc') return b.score - a.score;if (sort === 'score-asc') return a.score - b.score;if (sort === 'comments-desc') return b.numComments - a.numComments;- if (sort === 'date-desc') return (new Date(b.createdAt) as unknown as number) - (new Date(a.createdAt) as unknown as number);- if (sort === 'date-asc') return (new Date(a.createdAt) as unknown as number) - (new Date(b.createdAt) as unknown as number);+ if (sort === 'date-desc') return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();+ if (sort === 'date-asc') return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();return 0;});}diff --git a/frontend/src/features/analytics/tracked/trackedList.ts b/frontend/src/features/analytics/tracked/trackedList.tsindex 3d40698..cf57fdf 100644--- a/frontend/src/features/analytics/tracked/trackedList.ts+++ b/frontend/src/features/analytics/tracked/trackedList.ts@@ -50,7 +50,7 @@ function compareTracked(sort: string, first: TrackedContentItem, second: Trackedif (sort === 'engagement-desc') return trackedEngagement(second) - trackedEngagement(first);if (sort === 'comments-desc') return trackedComments(second) - trackedComments(first);if (sort === 'views-desc') return trackedViews(second) - trackedViews(first);- return (new Date(second.createdAt || 0) as unknown as number) - (new Date(first.createdAt || 0) as unknown as number);+ return new Date(second.createdAt || 0).getTime() - new Date(first.createdAt || 0).getTime();}export function filterAndSortTracked(items: TrackedContentItem[], { typeFilter, categoryFilter, query, sort }: TrackedFilterOptions): TrackedContentItem[] {diff --git a/frontend/src/features/publishing/scheduleHelpers.ts b/frontend/src/features/publishing/scheduleHelpers.tsindex 9e7eca1..4db2221 100644--- a/frontend/src/features/publishing/scheduleHelpers.ts+++ b/frontend/src/features/publishing/scheduleHelpers.ts@@ -36,7 +36,7 @@ export function scheduledStatusChips(posts: readonly ScheduleTiming[]): StatusChexport function filterScheduledPosts<T extends ScheduleTiming>(posts: T[], statusFilter: StatusFilter): T[] {return posts.filter(post => statusFilter === 'all' || post.status === statusFilter)- .sort((first, second) => (new Date(second.scheduledAt) as unknown as number) - (new Date(first.scheduledAt) as unknown as number));+ .sort((first, second) => new Date(second.scheduledAt).getTime() - new Date(first.scheduledAt).getTime());}export function overduePostsOf<T extends ScheduleTiming>(posts: T[], now: number = Date.now()): T[] {diff --git a/frontend/tests/features/analytics/channel/channelChartData.test.ts b/frontend/tests/features/analytics/channel/channelChartData.test.tsindex b08ed0f..3f9f535 100644--- a/frontend/tests/features/analytics/channel/channelChartData.test.ts+++ b/frontend/tests/features/analytics/channel/channelChartData.test.ts@@ -12,11 +12,11 @@ test('watch links point at YouTube', () => {});test('channel meta skips an unknown country and a missing handle', () => {- const meta = channelMeta({ country: 'Unknown', channelAgeYears: 3 as unknown as string, publishedAt: '2023-01-05T12:00:00Z' });+ const meta = channelMeta({ country: 'Unknown', channelAgeYears: '3.0', publishedAt: '2023-01-05T12:00:00Z' });assert.equal(meta.length, 2);- assert.equal(meta[0], '3 years old');+ assert.equal(meta[0], '3.0 years old');assert.ok(meta[1].startsWith('Since '));- assert.equal(channelMeta({ customUrl: '@dusk', country: 'IN', channelAgeYears: 1 as unknown as string })[1], 'IN');+ assert.equal(channelMeta({ customUrl: '@dusk', country: 'IN', channelAgeYears: '1.0' })[1], 'IN');});test('publish distributions become chart rows', () => {@@ -57,7 +57,7 @@ test('view ranges, uploads and comparisons', () => {assert.deepEqual(viewRangeDataOf({ ranges: ['0-1K', '1K+'], counts: [3] }), [{ range: '0-1K', count: 3 }, { range: '1K+', count: 0 }]);assert.deepEqual(viewRangeDataOf(undefined), []);assert.deepEqual(uploadsByMonthOf([{ month: 'Jan', count: 2, value: 9 }]), [{ month: 'Jan', uploads: 2 }]);- assert.equal(shortsComparisonOf({ avgShortViews: 1, avgRegularViews: 2 })[0].Regular, 2);+ assert.deepEqual(shortsComparisonOf({ avgShortViews: 1, avgRegularViews: 2, avgShortLikes: 3, avgRegularLikes: 4 })[1], { metric: 'Average likes', Shorts: 3, Regular: 4 });});test('rates and ratios guard against zero', () => {diff --git a/shared/types/youtube.ts b/shared/types/youtube.tsindex 072f5c4..4c76937 100644--- a/shared/types/youtube.ts+++ b/shared/types/youtube.ts@@ -134,7 +134,7 @@ export interface VideoAnalytics extends YouTubeMonthlyTrends {avgDurationFormatted: string;totalDurationSeconds: number;totalDurationFormatted: string;- estimatedTotalWatchTimeHours?: number;+ estimatedTotalWatchTimeHours: number;bestByViews: YouTubeVideoSummary | null;bestByLikes: YouTubeVideoSummary | null;bestByComments: YouTubeVideoSummary | null;@@ -150,18 +150,18 @@ export interface VideoAnalytics extends YouTubeMonthlyTrends {regularCount: number;avgShortViews: number;avgRegularViews: number;- avgShortLikes?: number;- avgRegularLikes?: number;+ avgShortLikes: number;+ avgRegularLikes: number;hdCount: number;sdCount: number;- hdPercentage: FormattedRate;+ hdPercentage: string;captionCount: number;- captionPercentage: FormattedRate;+ captionPercentage: string;licensedCount: number;- licensedPercentage: FormattedRate;+ licensedPercentage: string;madeForKidsCount: number;embeddableCount: number;- embeddablePercentage?: string;+ embeddablePercentage: string;// keyed by day name and by UTC hourpublishDayDistribution: Record<string, number>;publishHourDistribution: Record<string, number>;@@ -175,8 +175,8 @@ export interface VideoAnalytics extends YouTubeMonthlyTrends {videosLast30Days: number;videosLast90Days: number;videosLast365Days: number;- uploadFrequencyPerWeek: FormattedRate;- uploadFrequencyPerMonth: FormattedRate;+ uploadFrequencyPerWeek: string;+ uploadFrequencyPerMonth: string;consistencyScore: number;viralityScore: number;viewsDistribution: YouTubeViewsDistribution;