add dashboard Channel Stats page#153
Open
GauravOP-03 wants to merge 13 commits intoscriptaiapp:mainfrom
Open
Conversation
…ema to resue on frontend as well as backend
…FileSize, formatTime)
…tarting AI training
Contributor
|
@GauravOP-03 is attempting to deploy a commit to the afrin127329's projects Team on Vercel. A member of the Team first needs to authorize it. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📝 Description
Add the dashboard Channel Stats page and all related modified/added files. The page delivers a seamless, cost-conscious UX by showing cached channel data from the database by default; the YouTube Data API is only called when the user explicitly clicks Sync Latest Data, which is rate-limited per plan (e.g. 5 syncs/day for free, with a 60‑minute cooldown between syncs). This relies on the Supabase functions introduced in the plans_v2 migration (
use_feature,get_feature_usage) to enforce limits and cooldowns in the database, keeping API costs down and responses fast. This PR includes only the stats page and its related front-end files; the migration and API usage of the functions are from a previous PR.🎯 Type of Change
🧪 Testing
Describe: Open
/dashboard/stats; confirm cached data loads quickly. Click "Sync Latest Data" when allowed; confirm fresh data and quota bar update. When at daily limit or in cooldown, confirm button state and messaging. Confirm error state and "Try Again" when the API fails.📋 Checklist
📸 Screenshots (if applicable)
🔧 Technical Details
How the stats page uses the Supabase functions (from
plans_v2migration)Initial load (no sync)
The page calls
fetchStats()with no argument → API requests/api/v1/youtube/channel-stats?forceSync=false. The backend:youtube_channels(top_videos,recent_videos,channel_name, counts, etc.).get_feature_usage(p_user_id)to get read-only quota state:plan,usage_count,remaining,daily_limit,cooldown_minutes,cooldown_remaining,can_use_now.User clicks “Sync Latest Data”
The page calls
fetchStats(true)→ API requests?forceSync=true. The backend:use_feature(p_user_id)first. The function (frompackages/supabase/migrations/20260224185424_plans_v2.sql):plans.daily_limit,plans.cooldown_minutes; fallback tostarter).youtube_channels.usage_count,last_used_at,usage_reset_dateand resets count when the date has rolled over.allowed: false,reason: 'cooldown',minutes_remaining, etc.allowed: false,reason: 'daily_limit', etc.usage_count, setslast_used_at = NOW(),usage_reset_date = CURRENT_DATE, and returnsallowed: trueplus updated counts.use_featurereturnsallowed: false, the API responds with the function’s message (e.g. daily limit or cooldown); no YouTube API call.allowed: true, the API then calls the YouTube Data API, updatesyoutube_channelswith newtop_videos,recent_videos,last_synced_at, etc., and returns the fresh stats plus updated quota info.So: first fetch is always from DB (fast, no cost); refresh is optional, limited per day and by cooldown, and gated by the same Supabase functions used in the previous PR.
Why use Supabase functions instead of “normal” DB reads/writes in the app?
Atomicity and no race conditions
Incrementing usage and checking limits in a single DB function avoids races when multiple requests or tabs hit “Sync” at once. The app does not do “read count → check → increment” in separate steps.
Single source of truth
Plan resolution (subscription → plan →
daily_limit,cooldown_minutes) and daily reset logic live in one place in the DB. Any client (web, future mobile or workers) that callsuse_feature/get_feature_usagegets the same behavior without duplicating business rules.Plan-aware limits without app config
Limits and cooldowns come from
plans(e.g. 5/day, 60 min). Changing a plan or adding a new tier is a data change, not a code deploy.Security and consistency
Functions run as
SECURITY DEFINERand operate on the givenuser_id; the app cannot bypass or mis-implement limit checks. All enforcement is server-side in Postgres.Better UX
get_feature_usagegivescan_use_now,remaining,cooldown_remainingso the UI can show accurate state (e.g. “3/5 syncs left”, “Available in 42 mins”) without mutating state on simple page loads.Files in this PR (unchanged list)
app/dashboard/stats/page.tsxhooks/useChannelStats.ts/api/v1/youtube/channel-stats?forceSync=${forceSync}; returnsstats,loading,error,fetchStats(forceSync?).utils/toolsUtil.tsformatCount,parseDuration,timeAgo, etc., used by stats page and components.stats/StatCard.tsxstats/EngagementChart.tsxformatCount,ChannelStatsVideo.stats/TopVideosTable.tsxparseDuration,formatCount.stats/RecentVideosGrid.tsxtimeAgo.stats/StatsPageSkeleton.tsxDependencies: Backend must use the Supabase RPCs
use_featureandget_feature_usagefrompackages/supabase/migrations/20260224185424_plans_v2.sql(previous PR).@repo/validation(ChannelStats,ChannelStatsVideo),api-client, UI components, Recharts.🚀 Deployment Notes
use_featureandget_feature_usageand theyoutube_channels/planscolumns being applied./api/v1/youtube/channel-statsmust be deployed and must call these Supabase functions as described above.📚 Documentation Updates
🔍 Review Notes
can_use_now,remaining, andcooldown_remainingfrom the API.📊 Performance Impact
Details: Default path uses cached data from the DB and read-only
get_feature_usage, so the stats page loads quickly and does not call the YouTube API. Sync is optional and rate-limited, reducing API cost and improving perceived performance.🔒 Security Considerations
Details: Stats endpoint is authenticated; quota and cooldown are enforced in the DB via
use_feature(SECURITY DEFINER).🎉 Additional Notes
(1) Lower API cost — YouTube is only called on explicit sync, within daily and cooldown limits.
(2) Fast UX — Cached data and
get_feature_usagemake the first load instant.(3) Clear limits — e.g. 5 syncs/day for free users, 60‑min cooldown; configurable per plan in
plans.(4) Consistent enforcement — Same logic for web and any future clients; no drift between app and DB.
(5) Scalable — Atomic updates and plan-based limits in Postgres scale with traffic without app-level race conditions.