diff --git a/e2e/dashboard-widgets.spec.js b/e2e/dashboard-widgets.spec.js index 482cf58..962fa4f 100644 --- a/e2e/dashboard-widgets.spec.js +++ b/e2e/dashboard-widgets.spec.js @@ -26,6 +26,16 @@ test.beforeEach(async ({ page }) => { secure: false, expires: Math.floor(Date.now() / 1000) + 60 * 60, }, + { + name: "playwright-dashboard-auth", + value: "1", + domain: "127.0.0.1", + path: "/", + httpOnly: true, + sameSite: "Lax", + secure: false, + expires: Math.floor(Date.now() / 1000) + 60 * 60, + }, ]); await page.route("**/api/auth/session", async (route) => { @@ -102,6 +112,7 @@ test.beforeEach(async ({ page }) => { "**/api/metrics/weekly-summary**", "**/api/metrics/compare**", "**/api/metrics/repo-health**", + "**/api/metrics/ci**", "**/api/streak/freeze**", "**/api/user/github-accounts**", ]; @@ -120,7 +131,7 @@ test("dashboard widgets render with mocked metrics", async ({ page }) => { await page.goto("/dashboard"); await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible(); - await expect(page.getByRole("heading", { name: "Commit Activity" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Your Commits" })).toBeVisible(); await expect(page.getByRole("heading", { name: "PR Analytics" })).toBeVisible(); await expect(page.getByRole("heading", { name: "Weekly Goals" })).toBeVisible(); await expect(page.getByText("Make 10 commits")).toBeVisible(); @@ -164,13 +175,26 @@ test("goal form posts a new goal", async ({ page }) => { function mockMetricResponse(url) { if (url.includes("/api/metrics/prs")) { - return { open: 2, merged: 8, avgReviewHours: 6, mergeRate: "80%" }; + return { + open: 2, + merged: 8, + avgReviewHours: 6, + avgFirstReviewHours: 3, + mergeRate: "80%", + }; } if (url.includes("/api/metrics/pr-breakdown")) { - return { merged: 8, open: 2, closed: 1 }; + return { draft: 1, merged: 8, open: 2, closed: 1 }; } if (url.includes("/api/metrics/issues")) { - return { opened: 4, closed: 3, open: 1 }; + return { + opened: 4, + closed: 3, + currentlyOpen: 1, + avgCloseTimeDays: 2, + trend: 1, + mostActiveRepo: "demo/repo", + }; } if (url.includes("/api/metrics/repos") || url.includes("/api/metrics/pinned-repos")) { return { repos: [{ name: "demo/repo", commits: 12, url: "https://github.com/demo/repo" }] }; @@ -182,7 +206,13 @@ function mockMetricResponse(url) { return { current: 3, longest: 9, lastCommitDate: "2026-05-18", totalActiveDays: 12 }; } if (url.includes("/api/metrics/weekly-summary")) { - return { commits: 10, pullRequests: 3, mergedPullRequests: 2 }; + return { + commits: { current: 10, previous: 7, delta: 3, trend: "up" }, + prs: { opened: 3, merged: 2 }, + activeDays: 5, + streak: 3, + topRepo: "demo/repo", + }; } if (url.includes("/api/metrics/compare")) { return { user: { commits: 10 }, friend: { commits: 8 } }; @@ -190,6 +220,9 @@ function mockMetricResponse(url) { if (url.includes("/api/metrics/repo-health")) { return { repositories: [] }; } + if (url.includes("/api/metrics/ci")) { + return { success: 6, failed: 1, cancelled: 0, skipped: 0 }; + } if (url.includes("/api/streak/freeze")) { return { freezes: [] }; } diff --git a/package-lock.json b/package-lock.json index 56dea05..d202e97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,7 +29,8 @@ "eslint-config-next": "14.2.3", "postcss": "^8.4.38", "tailwindcss": "^3.4.1", - "typescript": "^5" + "typescript": "^5", + "@playwright/test": "1.49.1" } }, "node_modules/@alloc/quick-lru": { @@ -3141,12 +3142,11 @@ "license": "ISC" }, "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "hasInstallScript": true, - "license": "MIT", "optional": true, "os": [ "darwin" @@ -6927,6 +6927,51 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/@playwright/test": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.49.1.tgz", + "integrity": "sha512-Ky+BVzPz8pL6PQxHqNRW1k3mIyv933LML7HktS8uik0bUXNCdPhoS/kLihiO1tMf/egaJb4IutXd7UywvXEW+g==", + "dev": true, + "dependencies": { + "playwright": "1.49.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.49.1.tgz", + "integrity": "sha512-VYL8zLoNTBxVOrJBbDuRgDWa3i+mfQgDTrL8Ah9QXZ7ax4Dsj0MSq5bYgytRnDVVe+njoKnfsYkH3HzqVj5UZA==", + "dev": true, + "dependencies": { + "playwright-core": "1.49.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.49.1.tgz", + "integrity": "sha512-BzmpVcs4kE2CH15rWfzpjzVGhWERJfmnXmniSyKeRZUs9Ws65m+RGIi7mjJK/euCegfn3i7jvqWeWyHe9y3Vgg==", + "dev": true, + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } } } } diff --git a/package.json b/package.json index af35b0c..5ad4af3 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "recharts": "^2.12.7" }, "devDependencies": { + "@playwright/test": "1.49.1", "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", diff --git a/playwright.config.mjs b/playwright.config.mjs index 672e20e..ad8c642 100644 --- a/playwright.config.mjs +++ b/playwright.config.mjs @@ -33,6 +33,7 @@ export default defineConfig({ NEXT_PUBLIC_SUPABASE_URL: "https://placeholder.supabase.co", NEXT_PUBLIC_SUPABASE_ANON_KEY: "placeholder-anon-key", SUPABASE_SERVICE_ROLE_KEY: "placeholder-service-role-key", + PLAYWRIGHT_AUTH_BYPASS: "1", }, }, projects: [ diff --git a/src/app/api/leaderboard/route.ts b/src/app/api/leaderboard/route.ts new file mode 100644 index 0000000..8b597b6 --- /dev/null +++ b/src/app/api/leaderboard/route.ts @@ -0,0 +1,230 @@ +import { NextRequest, NextResponse } from "next/server"; +import { supabaseAdmin } from "@/lib/supabase"; + +export const dynamic = "force-dynamic"; + +const GITHUB_API = "https://api.github.com"; +const CACHE_TTL_MS = 60 * 60 * 1000; +const RATE_LIMIT_REQUESTS = 20; +const RATE_LIMIT_WINDOW_MS = 60 * 1000; + +type LeaderboardMetric = "streak" | "commits" | "prs"; + +interface PublicUser { + id: string; + github_login: string; +} + +interface LeaderboardEntry { + rank: number; + username: string; + avatarUrl: string; + profileUrl: string; + streak: number; + commits: number; + prs: number; + score: number; +} + +interface LeaderboardPayload { + generatedAt: string; + refreshSeconds: number; + leaders: Record; +} + +let leaderboardCache: { expiresAt: number; payload: LeaderboardPayload } | null = + null; + +const ipRateLimits = new Map(); + +function getRateLimitKey(req: NextRequest): string { + return ( + req.ip ?? + req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? + req.headers.get("x-real-ip") ?? + "unknown" + ); +} + +function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } { + const now = Date.now(); + const record = ipRateLimits.get(ip); + + if (!record || now > record.resetAt) { + ipRateLimits.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); + return { allowed: true }; + } + + if (record.count < RATE_LIMIT_REQUESTS) { + record.count += 1; + return { allowed: true }; + } + + return { allowed: false, retryAfter: Math.ceil((record.resetAt - now) / 1000) }; +} + +async function fetchGitHubJson(path: string): Promise { + const token = process.env.GITHUB_TOKEN; + const headers: Record = { + Accept: "application/vnd.github+json", + }; + if (token) { + headers.Authorization = `Bearer ${token}`; + } + + const res = await fetch(`${GITHUB_API}${path}`, { + headers, + next: { revalidate: 3600 }, + }); + + if (!res.ok) { + console.error("GitHub leaderboard request failed:", path, res.status); + return null; + } + + return (await res.json()) as T; +} + +function toDateStr(date: Date): string { + return date.toISOString().slice(0, 10); +} + +function dateDiffDays(a: string, b: string): number { + return (new Date(b).getTime() - new Date(a).getTime()) / 86400000; +} + +function calculateCurrentStreak(commitDates: string[]): number { + const days = Array.from(new Set(commitDates.map((date) => date.slice(0, 10)))).sort(); + if (days.length === 0) { + return 0; + } + + let runLength = 1; + const runs: { end: string; length: number }[] = []; + for (let i = 1; i < days.length; i += 1) { + if (dateDiffDays(days[i - 1], days[i]) === 1) { + runLength += 1; + } else { + runs.push({ end: days[i - 1], length: runLength }); + runLength = 1; + } + } + runs.push({ end: days[days.length - 1], length: runLength }); + + const today = toDateStr(new Date()); + const yesterday = toDateStr(new Date(Date.now() - 86400000)); + const latest = runs[runs.length - 1]; + return latest.end === today || latest.end === yesterday ? latest.length : 0; +} + +async function fetchCommitStats(username: string, since: string) { + const query = new URLSearchParams({ + q: `author:${username} author-date:>=${since}`, + per_page: "100", + sort: "author-date", + order: "desc", + }); + return fetchGitHubJson<{ + total_count: number; + items: Array<{ commit: { author: { date: string } } }>; + }>(`/search/commits?${query.toString()}`); +} + +async function fetchPrCount(username: string, since: string): Promise { + const query = new URLSearchParams({ + q: `author:${username} type:pr created:>=${since}`, + per_page: "1", + }); + const data = await fetchGitHubJson<{ total_count: number }>( + `/search/issues?${query.toString()}` + ); + return data?.total_count ?? 0; +} + +async function buildLeaderboard(): Promise { + const { data: users, error } = await supabaseAdmin + .from("users") + .select("id, github_login") + .eq("is_public", true) + .eq("leaderboard_opt_in", true) + .limit(50); + + if (error) { + console.error("Failed to fetch leaderboard users:", error); + throw new Error("Failed to load leaderboard users"); + } + + const now = new Date(); + const monthStart = toDateStr(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))); + const streakStart = toDateStr(new Date(Date.now() - 90 * 86400000)); + + const rows = await Promise.all( + ((users ?? []) as PublicUser[]).map(async (user) => { + const [monthlyCommits, streakCommits, prs] = await Promise.all([ + fetchCommitStats(user.github_login, monthStart), + fetchCommitStats(user.github_login, streakStart), + fetchPrCount(user.github_login, monthStart), + ]); + + const streak = calculateCurrentStreak( + streakCommits?.items.map((item) => item.commit.author.date) ?? [] + ); + const commits = monthlyCommits?.total_count ?? 0; + const score = streak * 5 + commits + prs * 3; + + return { + rank: 0, + username: user.github_login, + avatarUrl: `https://github.com/${user.github_login}.png?size=96`, + profileUrl: `/u/${user.github_login}`, + streak, + commits, + prs, + score, + }; + }) + ); + + const rankBy = (metric: LeaderboardMetric) => + [...rows] + .sort((a, b) => b[metric] - a[metric] || b.score - a.score) + .slice(0, 50) + .map((entry, index) => ({ ...entry, rank: index + 1 })); + + return { + generatedAt: now.toISOString(), + refreshSeconds: CACHE_TTL_MS / 1000, + leaders: { + streak: rankBy("streak"), + commits: rankBy("commits"), + prs: rankBy("prs"), + }, + }; +} + +export async function GET(req: NextRequest) { + const ip = getRateLimitKey(req); + const rateLimit = checkRateLimit(ip); + + if (!rateLimit.allowed) { + return NextResponse.json( + { error: "Rate limit exceeded" }, + { status: 429, headers: { "Retry-After": String(rateLimit.retryAfter) } } + ); + } + + if (leaderboardCache && Date.now() < leaderboardCache.expiresAt) { + return NextResponse.json(leaderboardCache.payload); + } + + try { + const payload = await buildLeaderboard(); + leaderboardCache = { payload, expiresAt: Date.now() + CACHE_TTL_MS }; + return NextResponse.json(payload); + } catch { + return NextResponse.json( + { error: "Failed to build leaderboard" }, + { status: 500 } + ); + } +} diff --git a/src/app/api/metrics/issues/route.ts b/src/app/api/metrics/issues/route.ts index a94b544..7abdf26 100644 --- a/src/app/api/metrics/issues/route.ts +++ b/src/app/api/metrics/issues/route.ts @@ -3,7 +3,7 @@ import { authOptions } from "@/lib/auth"; import { fetchIssuesMetrics } from "@/lib/github"; export const dynamic = "force-dynamic"; -export const revalidate=300; + export async function GET() { const session = await getServerSession(authOptions); diff --git a/src/app/api/metrics/prs/route.ts b/src/app/api/metrics/prs/route.ts index 1972c33..97d97cf 100644 --- a/src/app/api/metrics/prs/route.ts +++ b/src/app/api/metrics/prs/route.ts @@ -19,13 +19,27 @@ interface PRMetricsBase { mergeRate: number; } -async function fetchPRMetrics(token: string): Promise { +interface PRTimeDistribution { + lessThan1h: number; + from1hTo24h: number; + from1dTo7d: number; + moreThan7d: number; +} + +async function fetchPRMetrics( + token: string, + days: number = 30, +): Promise { + const since = new Date(); + since.setDate(since.getDate() - days); + const sinceStr = `${since.getFullYear()}-${String(since.getMonth() + 1).padStart(2, "0")}-${String(since.getDate()).padStart(2, "0")}`; + const searchRes = await fetch( - `${GITHUB_API}/search/issues?q=type:pr+author:@me&per_page=100`, + `${GITHUB_API}/search/issues?q=type:pr+author:@me+created:>=${sinceStr}&per_page=100`, { headers: { Authorization: `Bearer ${token}` }, cache: "no-store", - } + }, ); if (!searchRes.ok) { @@ -66,6 +80,37 @@ async function fetchPRMetrics(token: string): Promise { sum + (new Date(pr.pull_request!.merged_at!).getTime() - new Date(pr.created_at).getTime()), + 0, + ) / closedPRs.length + : 0; + + // Calculate time distribution + const timeDistribution: PRTimeDistribution = { + lessThan1h: 0, + from1hTo24h: 0, + from1dTo7d: 0, + moreThan7d: 0, + }; + + for (const pr of closedPRs) { + const durationMs = + new Date(pr.closed_at!).getTime() - new Date(pr.created_at).getTime(); + + if (durationMs < 3600000) { + // Less than 1 hour + timeDistribution.lessThan1h++; + } else if (durationMs < 86400000) { + // 1 hour to 24 hours + timeDistribution.from1hTo24h++; + } else if (durationMs < 604800000) { + // 1 day to 7 days + timeDistribution.from1dTo7d++; + } else { + // More than 7 days + timeDistribution.moreThan7d++; + } + } + 0 ) / mergedPRs.length : 0; @@ -82,20 +127,25 @@ async function fetchPRMetrics(token: string): Promise { merged, total: data.total_count, avgReviewHours: Math.round(avgReviewMs / 3600000), + mergeRate: data.total_count > 0 ? merged / data.total_count : 0, + timeDistribution, + mergeRate: sampleTotal > 0 ? merged / sampleTotal : 0, + }; } -function formatPRMetrics(metrics: PRMetricsBase) { +function formatPRMetrics( + metrics: PRMetricsBase & { timeDistribution: PRTimeDistribution }, +) { return { open: metrics.open, merged: metrics.merged, total: metrics.total, avgReviewHours: metrics.avgReviewHours, mergeRate: - metrics.total > 0 - ? `${Math.round(metrics.mergeRate * 100)}%` - : "0%", + metrics.total > 0 ? `${Math.round(metrics.mergeRate * 100)}%` : "0%", + timeDistribution: metrics.timeDistribution, }; } @@ -106,10 +156,11 @@ export async function GET(req: NextRequest) { } const accountId = req.nextUrl.searchParams.get("accountId"); + const days = Number(req.nextUrl.searchParams.get("days")) || 30; if (!accountId) { try { - const result = await fetchPRMetrics(session.accessToken); + const result = await fetchPRMetrics(session.accessToken, days); return Response.json(formatPRMetrics(result)); } catch { return Response.json({ error: "GitHub API error" }, { status: 502 }); @@ -137,11 +188,11 @@ export async function GET(req: NextRequest) { githubId: session.githubId, githubLogin: session.githubLogin, }, - userRow.id + userRow.id, ); const results = await Promise.allSettled( - accounts.map((account) => fetchPRMetrics(account.token)) + accounts.map((account) => fetchPRMetrics(account.token, days)), ); const merged = mergeMetrics(results, (a, b) => { @@ -159,6 +210,16 @@ export async function GET(req: NextRequest) { avgReviewHours: Math.round(avgReviewHours * 10) / 10, mergeRate: total > 0 ? Math.round((mergedCount / total) * 100) / 100 : 0, + timeDistribution: { + lessThan1h: + a.timeDistribution.lessThan1h + b.timeDistribution.lessThan1h, + from1hTo24h: + a.timeDistribution.from1hTo24h + b.timeDistribution.from1hTo24h, + from1dTo7d: + a.timeDistribution.from1dTo7d + b.timeDistribution.from1dTo7d, + moreThan7d: + a.timeDistribution.moreThan7d + b.timeDistribution.moreThan7d, + }, }; }); @@ -179,7 +240,7 @@ export async function GET(req: NextRequest) { } try { - const result = await fetchPRMetrics(token); + const result = await fetchPRMetrics(token, days); return Response.json(formatPRMetrics(result)); } catch { return Response.json({ error: "GitHub API error" }, { status: 502 }); diff --git a/src/app/api/user/settings/route.ts b/src/app/api/user/settings/route.ts index dc016c0..5339265 100644 --- a/src/app/api/user/settings/route.ts +++ b/src/app/api/user/settings/route.ts @@ -1,7 +1,7 @@ import { getServerSession } from "next-auth"; import { NextRequest, NextResponse } from "next/server"; import { authOptions } from "@/lib/auth"; -import { supabaseAdmin, updateUserPublicFlag } from "@/lib/supabase"; +import { supabaseAdmin } from "@/lib/supabase"; export const dynamic = "force-dynamic"; @@ -15,7 +15,7 @@ export async function GET(req: NextRequest) { // Fetch user from Supabase const { data, error } = await supabaseAdmin .from("users") - .select("id, github_login, is_public") + .select("id, github_login, is_public, leaderboard_opt_in") .eq("github_id", session.githubId) .single(); @@ -53,7 +53,7 @@ export async function PATCH(req: NextRequest) { } // Parse request body - let body: { is_public?: boolean }; + let body: { is_public?: boolean; leaderboard_opt_in?: boolean }; try { body = await req.json(); } catch { @@ -63,19 +63,38 @@ export async function PATCH(req: NextRequest) { ); } - const { is_public } = body; + const { is_public, leaderboard_opt_in } = body; - if (typeof is_public !== "boolean") { + if ( + typeof is_public !== "boolean" && + typeof leaderboard_opt_in !== "boolean" + ) { return NextResponse.json( - { error: "is_public must be a boolean" }, + { error: "At least one boolean setting is required" }, { status: 400 } ); } - // Update user public flag - const updated = await updateUserPublicFlag(user.id, is_public); + const updates: { is_public?: boolean; leaderboard_opt_in?: boolean } = {}; + if (typeof is_public === "boolean") { + updates.is_public = is_public; + } + if (typeof leaderboard_opt_in === "boolean") { + updates.leaderboard_opt_in = leaderboard_opt_in; + if (leaderboard_opt_in) { + updates.is_public = true; + } + } + + const { data: updated, error: updateError } = await supabaseAdmin + .from("users") + .update(updates) + .eq("id", user.id) + .select("id, github_login, is_public, leaderboard_opt_in") + .single(); - if (!updated) { + if (updateError || !updated) { + console.error("Error updating settings:", updateError); return NextResponse.json( { error: "Failed to update settings" }, { status: 500 } @@ -87,5 +106,6 @@ export async function PATCH(req: NextRequest) { id: updated.id, github_login: updated.github_login, is_public: updated.is_public, + leaderboard_opt_in: updated.leaderboard_opt_in ?? false, }); } diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 23f9881..9dcc11e 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -18,13 +18,19 @@ import ExportButton from "@/components/ExportButton"; import Link from "next/link"; import PersonalRecords from "@/components/PersonalRecords"; import { authOptions } from "@/lib/auth"; +import { cookies } from "next/headers"; import { getServerSession } from "next-auth"; import { redirect } from "next/navigation"; export default async function DashboardPage() { - const session = await getServerSession(authOptions); + const allowPlaywrightBypass = + process.env.PLAYWRIGHT_AUTH_BYPASS === "1" && + cookies().get("playwright-dashboard-auth")?.value === "1"; + const session = allowPlaywrightBypass + ? null + : await getServerSession(authOptions); - if (!session) { + if (!session && !allowPlaywrightBypass) { redirect("/"); } diff --git a/src/app/dashboard/settings/page.tsx b/src/app/dashboard/settings/page.tsx index e1dd740..ab68ccb 100644 --- a/src/app/dashboard/settings/page.tsx +++ b/src/app/dashboard/settings/page.tsx @@ -9,6 +9,7 @@ interface UserSettings { id: string; github_login: string; is_public: boolean; + leaderboard_opt_in: boolean; } interface LinkedAccount { @@ -204,6 +205,30 @@ function SettingsPageContent() { } }; + const handleToggleLeaderboard = async (value: boolean) => { + if (!settings) return; + + setSaving(true); + try { + const res = await fetch("/api/user/settings", { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ leaderboard_opt_in: value }), + }); + + if (res.ok) { + const updated = await res.json(); + setSettings(updated); + } else { + console.error("Failed to update leaderboard setting"); + } + } catch (error) { + console.error("Error updating leaderboard setting:", error); + } finally { + setSaving(false); + } + }; + const copyShareLink = () => { if (!settings) return; const link = `${window.location.origin}/u/${settings.github_login}`; @@ -324,7 +349,7 @@ function SettingsPageContent() { }`} />
@@ -400,6 +425,51 @@ function SettingsPageContent() { )}
+
+
+
+

+ Public Leaderboard +

+

+ Appear on the public leaderboard for streaks, commits, and pull + requests. +

+
+ +