From 2843a1aa933ef7d74a15bf336b9f97e1e78955c5 Mon Sep 17 00:00:00 2001 From: thainapires Date: Sat, 19 Sep 2026 23:08:51 -0300 Subject: [PATCH 1/3] feat(WIP): improving landing page and dashboard --- src/app/dashboard/page.tsx | 349 ++++++++- src/app/globals.css | 27 +- .../dashboard/components/activity-list.tsx | 25 +- .../components/contribution-chart.tsx | 12 +- .../dashboard/components/metric-card.tsx | 65 +- .../dashboard/components/repository-table.tsx | 68 +- .../components/account-connection-card.tsx | 58 +- .../components/integration-accounts-panel.tsx | 18 +- .../landing/components/hero-illustration.tsx | 352 +++++---- .../landing/components/landing-navbar.tsx | 61 +- .../landing/components/landing-page.tsx | 296 +++++++- src/lib/dashboard/overview.test.ts | 56 ++ src/lib/dashboard/overview.ts | 55 +- src/shared/app-shell/authenticated-layout.tsx | 717 +++++++++++------- 14 files changed, 1514 insertions(+), 645 deletions(-) create mode 100644 src/lib/dashboard/overview.test.ts diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 08b0dc4..83ced43 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -1,7 +1,9 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; -import { FiRefreshCw } from "react-icons/fi"; +import Image from "next/image"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { FaFire } from "react-icons/fa"; +import { FiActivity, FiFolder, FiGitPullRequest, FiRefreshCw } from "react-icons/fi"; import { IntegrationAccountsPanel } from "@/features/integrations/components/integration-accounts-panel"; import { AuthenticatedLayout } from "@/shared/app-shell/authenticated-layout"; import { ActivityList } from "@/features/dashboard/components/activity-list"; @@ -15,7 +17,7 @@ import { DashboardOverview, DashboardSyncStatus, } from "@/types/dashboard"; -import { KeepGoingCard } from "@/features/dashboard/components/keep-going-card"; +import { DailyContribution, RepositorySummary } from "@/types/mock-app"; export default function DashboardPage() { const [overview, setOverview] = useState(null); @@ -110,6 +112,7 @@ export default function DashboardPage() { const activeDays = overview?.dailyContributions.filter((day) => day.total > 0).length ?? 0; const currentStreak = overview ? getCurrentStreak(overview.dailyContributions) : 0; + const dashboardMetrics = useMemo(() => overview ? buildDashboardMetrics(overview, currentStreak) : [], [overview, currentStreak]); return ( loadOverview({ refresh: true })} disabled={isRefreshing} - className="inline-flex min-h-[52px] items-center justify-center gap-2 px-3 text-sm font-bold text-muted-foreground transition hover:bg-gray-50 hover:text-primary disabled:cursor-not-allowed cursor-pointer disabled:opacity-60 dark:hover:bg-gray-900/70 min-[420px]:px-4" + className="inline-flex h-10 items-center justify-center gap-2 px-3 text-sm font-bold text-muted-foreground transition hover:bg-muted hover:text-primary disabled:cursor-not-allowed disabled:opacity-60" aria-label="Refresh dashboard data" > } {!isLoading && overview?.hasConnections && ( - <> -
- -
+
+ -
-
-
- {overview.metrics.map((metric) => ( - - ))} -
+ {syncStatus?.status === "failed" && ( + loadOverview({ refresh: true })} isRefreshing={isRefreshing} /> + )} + +
+ {dashboardMetrics.map((metric) => ( + + ))} +
+ +
+
- +
+ + +
+
+ + +
-
+ +
+ +
- +
)} ); } +function DashboardHero({ viewerName, activeDays, currentStreak }: { viewerName: string; activeDays: number; currentStreak: number }) { + return ( +
+
+
+ + +
+
+

Dashboard

+

+ Good to see you again, {viewerName}! 👋 +

+

+ Here's your connected GitHub and GitLab activity overview. +

+
+ +
+
+ + 🔥 + +
+

Current streak

+

+ {currentStreak} {currentStreak === 1 ? "day" : "days"} +

+
+
+

+ {currentStreak > 0 ? "Nice momentum. Keep it going." : "No current streak yet."} +

+
+ {Array.from({ length: 8 }).map((_, index) => ( + + ))} +
+
+
+
+ ); +} + +function InlineSyncAlert({ syncStatus, onRetry, isRefreshing }: { syncStatus: DashboardSyncStatus; onRetry: () => void; isRefreshing: boolean }) { + return ( +
+
+ ! +

+ Provider data unavailable {syncStatus.errorMessage || "Unable to load dashboard data."} +

+
+ +
+ ); +} + +function ActivityOverview({ data }: { data: DailyContribution[] }) { + const months = getMonthlyActivity(data).slice(-7); + const maxValue = Math.max(...months.flatMap((month) => [month.github, month.gitlab]), 1); + const points = months.map((month, index) => ({ + x: months.length === 1 ? 0 : (index / (months.length - 1)) * 100, + githubY: 100 - (month.github / maxValue) * 82, + gitlabY: 100 - (month.gitlab / maxValue) * 82, + })); + const githubPoints = points.map((point) => `${point.x},${point.githubY}`).join(" "); + const gitlabPoints = points.map((point) => `${point.x},${point.gitlabY}`).join(" "); + + return ( +
+
+
+

Activity overview

+

Monthly contributions by provider.

+
+
+ GitHub + GitLab +
+
+ +
+ + {[20, 45, 70, 95].map((y) => ( + + ))} + + + {points.map((point, index) => ( + + + + + ))} + +
+
+ {months.map((month) => {month.label})} +
+
+ ); +} + +function LanguagesBreakdown({ repositories, totalContributions }: { repositories: RepositorySummary[]; totalContributions: number }) { + const languages = getLanguageBreakdown(repositories); + const gradient = languages.length + ? `conic-gradient(${languages.map((language) => `${language.color} ${language.start}% ${language.end}%`).join(", ")})` + : "conic-gradient(var(--muted) 0% 100%)"; + + return ( +
+

Languages

+
+
+
+

{totalContributions.toLocaleString("en-US")}

+

total contributions

+
+
+
+ {!languages.length &&

No repository language data was returned yet.

} + {languages.map((language) => ( +
+ + {language.name} + {language.percent}% +
+ ))} +
+
+
+ ); +} + +function KeepBuildingCard() { + return ( +
+
+

Keep building

+

Small commits drive big results.

+
+
+ {[34, 50, 68, 86].map((height, index) => ( + + ))} +
+
+ ); +} + +function buildDashboardMetrics(overview: DashboardOverview, currentStreak: number) { + const total = getTotalContributions(overview.dailyContributions); + const githubTotal = overview.dailyContributions.reduce((sum, day) => sum + day.platforms.github, 0); + const gitlabTotal = overview.dailyContributions.reduce((sum, day) => sum + day.platforms.gitlab, 0); + const pullOrMergeRequests = overview.metrics.find((metric) => metric.label === "Pull / merge requests")?.value || "0"; + + return [ + { + label: "Total contributions", + value: total.toLocaleString("en-US"), + helper: `GitHub ${githubTotal.toLocaleString("en-US")} · GitLab ${gitlabTotal.toLocaleString("en-US")}`, + trend: `${overview.activeDays.toLocaleString("en-US")} active days`, + icon: FiActivity, + visual: "sparkline" as const, + }, + { + label: "Repositories", + value: overview.topRepositories.length.toLocaleString("en-US"), + helper: `Across ${overview.connectedProviders.length || 0} ${overview.connectedProviders.length === 1 ? "provider" : "providers"}`, + trend: "Loaded from providers", + icon: FiFolder, + visual: "bars" as const, + }, + { + label: "Pull / merge requests", + value: pullOrMergeRequests, + helper: "Detected from provider APIs", + trend: "Last year window", + icon: FiGitPullRequest, + visual: "bars" as const, + }, + { + label: "Current streak", + value: `${currentStreak.toLocaleString("en-US")} ${currentStreak === 1 ? "day" : "days"}`, + helper: currentStreak > 0 ? "Nice momentum." : "No current streak yet.", + trend: `${overview.activeDays.toLocaleString("en-US")} active days`, + icon: FaFire, + visual: "progress" as const, + }, + ]; +} + +function getMonthlyActivity(data: DailyContribution[]) { + const monthFormatter = new Intl.DateTimeFormat("en-US", { month: "short" }); + const grouped = new Map(); + + data.forEach((day) => { + const date = parseLocalDate(day.date); + const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`; + const current = grouped.get(key) ?? { label: monthFormatter.format(date), github: 0, gitlab: 0 }; + current.github += day.platforms.github; + current.gitlab += day.platforms.gitlab; + grouped.set(key, current); + }); + + return Array.from(grouped.values()); +} + +function getLanguageBreakdown(repositories: RepositorySummary[]) { + const totals = new Map(); + + repositories.forEach((repo) => { + const language = repo.language && repo.language !== "Unknown" ? repo.language : "Other"; + totals.set(language, (totals.get(language) || 0) + Math.max(repo.contributions, 1)); + }); + + const entries = Array.from(totals.entries()).sort((a, b) => b[1] - a[1]).slice(0, 5); + const total = entries.reduce((sum, [, value]) => sum + value, 0); + let cursor = 0; + const colors = ["#8b5cf6", "#a855f7", "#c084fc", "#7c3aed", "#818cf8"]; + + return entries.map(([name, value], index) => { + const percent = total ? Math.round((value / total) * 100) : 0; + const start = cursor; + cursor += total ? (value / total) * 100 : 0; + + return { + name, + percent, + start, + end: cursor, + color: colors[index % colors.length], + }; + }); +} + +function getTotalContributions(data: DailyContribution[]) { + return data.reduce((sum, day) => sum + day.total, 0); +} + function getFirstName(value: string) { const firstName = value.trim().split(/\s+/).filter(Boolean)[0]; @@ -188,24 +467,36 @@ function getCurrentStreak(days: DashboardOverview["dailyContributions"]) { return firstInactiveIndex === -1 ? activeDays.length : firstInactiveIndex; } +function parseLocalDate(date: string) { + const [year, month, day] = date.split("-").map(Number); + return new Date(year, month - 1, day); +} + function DashboardLoading() { return ( -
- {Array.from({ length: 4 }).map((_, index) => ( -
- ))} +
+
+
+ {Array.from({ length: 4 }).map((_, index) => ( +
+ ))} +
+
+
+
+
); } function EmptyConnectionsState() { return ( -
-
+
+

No providers connected

Connect GitHub or GitLab to build your dashboard.

- Once at least one provider is connected, Git Fusion will load repositories, daily activity, recent events, and overview metrics from that account. + Once at least one provider is connected, GitFusion will load repositories, daily activity, recent events, and overview metrics from that account.

diff --git a/src/app/globals.css b/src/app/globals.css index 4c6acdc..b795d4d 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -26,19 +26,19 @@ } .dark { - --background: #080a17; - --foreground: #f4f4f5; + --background: #070a16; + --foreground: #f4f6fb; - --surface: #101421; - --card: #151927; - --card-hover: #1a1f2f; + --surface: #0d1222; + --card: #0d1324; + --card-hover: #131a2d; - --border: #252a3b; + --border: #27315a; - --muted: #1b2030; - --muted-foreground: #9299aa; + --muted: #171d34; + --muted-foreground: #97a0b8; - --heatmap-empty: #1b2030; + --heatmap-empty: #151b34; } @theme { @@ -62,7 +62,10 @@ } body { - background: var(--background); + background: + radial-gradient(circle at 70% -12%, rgba(139, 92, 246, 0.16), transparent 30rem), + radial-gradient(circle at 4% 8%, rgba(76, 29, 149, 0.16), transparent 24rem), + var(--background); color: var(--foreground); } @@ -128,8 +131,8 @@ body { } .gf-contribution-calendar .react-calendar-heatmap rect { - rx: 2px; - ry: 2px; + rx: 2.5px; + ry: 2.5px; } /* Empty days */ diff --git a/src/features/dashboard/components/activity-list.tsx b/src/features/dashboard/components/activity-list.tsx index 60a396b..967f1f0 100644 --- a/src/features/dashboard/components/activity-list.tsx +++ b/src/features/dashboard/components/activity-list.tsx @@ -3,27 +3,30 @@ import { ActivityItem } from "@/types/mock-app"; export function ActivityList({ activities }: { activities: ActivityItem[] }) { return ( -
-

Recent activity

-
+
+
+

Recent activity

+ Latest +
+
{!activities.length && ( -
+
No recent provider activity was returned yet.
)} - {activities.map((activity) => { + {activities.slice(0, 6).map((activity) => { const Icon = activity.platform === "github" ? FaGithub : FaGitlab; return ( -
- +
+
-
-

{activity.title}

- +
+

{activity.title}

+
-

{activity.description}

+

{activity.description}

); diff --git a/src/features/dashboard/components/contribution-chart.tsx b/src/features/dashboard/components/contribution-chart.tsx index cbb6476..b138dce 100644 --- a/src/features/dashboard/components/contribution-chart.tsx +++ b/src/features/dashboard/components/contribution-chart.tsx @@ -32,20 +32,20 @@ export function ContributionChart({ data }: { data: DailyContribution[] }) { }; return ( -
+
-

Contribution graph

+

Contribution activity

Daily activity across connected platforms.

- GitHub + GitHub GitLab
-
-
+
+
-

Each square represents one day. Tooltip values are already split by platform.

+

Each square represents one day.

Less {[0, 1, 2, 3, 4].map((level) => ( diff --git a/src/features/dashboard/components/metric-card.tsx b/src/features/dashboard/components/metric-card.tsx index 6e3bc78..67e2351 100644 --- a/src/features/dashboard/components/metric-card.tsx +++ b/src/features/dashboard/components/metric-card.tsx @@ -1,12 +1,65 @@ +import { IconType } from "react-icons"; import { DashboardMetric } from "@/types/mock-app"; -export function MetricCard({ metric }: { metric: DashboardMetric }) { +type EnhancedMetric = DashboardMetric & { + icon?: IconType; + visual?: "sparkline" | "bars" | "progress"; +}; + +export function MetricCard({ metric }: { metric: EnhancedMetric }) { + const Icon = metric.icon; + return ( -
-

{metric.label}

-
{metric.value}
-

{metric.helper}

-

{metric.trend}

+
+
+
+ {Icon && ( + + + + )} +
+

{metric.label}

+
{metric.value}
+

{metric.helper}

+
+
+ ↗ +
+ +
+

{metric.trend}

+ +
); } + +function MetricVisual({ type }: { type?: EnhancedMetric["visual"] }) { + if (type === "bars") { + return ( +
+ {[18, 24, 30, 25, 34, 39, 46].map((height, index) => ( + + ))} +
+ ); + } + + if (type === "progress") { + return ( +
+ {[0, 1, 2, 3, 4, 5, 6].map((index) => ( + + ))} +
+ ); + } + + return ( + + + + + ); +} diff --git a/src/features/dashboard/components/repository-table.tsx b/src/features/dashboard/components/repository-table.tsx index c2666bb..01580f9 100644 --- a/src/features/dashboard/components/repository-table.tsx +++ b/src/features/dashboard/components/repository-table.tsx @@ -2,47 +2,45 @@ import { FaGithub, FaGitlab } from "react-icons/fa"; import { RepositorySummary } from "@/types/mock-app"; export function RepositoryTable({ repositories }: { repositories: RepositorySummary[] }) { + const maxContributions = Math.max(...repositories.map((repo) => repo.contributions), 1); + return ( -
-

Top repositories

+
+
+

Top repositories

+ Top {Math.min(repositories.length, 5)} +
{!repositories.length ? ( -
+
No repositories were returned by the connected providers yet.
) : ( -
- - - - - - - - - - - {repositories.map((repo) => { - const Icon = repo.platform === "github" ? FaGithub : FaGitlab; - return ( - - - - - - - ); - })} - -
RepositoryPlatformLanguageContributions
-
{repo.name}
-
{repo.visibility}
-
- - - {repo.platform} +
+ {repositories.slice(0, 5).map((repo, index) => { + const Icon = repo.platform === "github" ? FaGithub : FaGitlab; + const width = `${Math.max((repo.contributions / maxContributions) * 100, 8)}%`; + + return ( +
+ {index + 1} +
+
+ +

{repo.name}

+ {repo.visibility} +
+
+ {repo.language} + + -
{repo.language}{repo.contributions}
-
+
+
+ {repo.contributions.toLocaleString("en-US")} +
+ ); + })} +
)}
); diff --git a/src/features/integrations/components/account-connection-card.tsx b/src/features/integrations/components/account-connection-card.tsx index 92368fe..b95c285 100644 --- a/src/features/integrations/components/account-connection-card.tsx +++ b/src/features/integrations/components/account-connection-card.tsx @@ -1,6 +1,7 @@ "use client"; import { FaGithub, FaGitlab } from "react-icons/fa"; +import { FiChevronRight, FiLink2, FiLogOut } from "react-icons/fi"; import { ConnectedAccount } from "@/types/mock-app"; type AccountConnectionCardProps = { @@ -16,42 +17,51 @@ export function AccountConnectionCard({ account, onConnect, onDisconnect, compac const Icon = account.provider === "github" ? FaGithub : FaGitlab; return ( -
-
-
- +
+
+
+
-

{account.name}

-

- {isConnected ? `@${account.username}` : `Connect your account`} +

{account.name}

+

+ {isConnected ? `@${account.username}` : "Connect your account"}

- + {isConnected ? ( + <> + Connected + + + + ) : ( + + )}
{isConnected && !compact && ( -
+
diff --git a/src/features/integrations/components/integration-accounts-panel.tsx b/src/features/integrations/components/integration-accounts-panel.tsx index 821a6e8..03dbb0e 100644 --- a/src/features/integrations/components/integration-accounts-panel.tsx +++ b/src/features/integrations/components/integration-accounts-panel.tsx @@ -7,7 +7,6 @@ import { notify } from "@/lib/notifications/toast"; import { createSupabaseBrowserClient, isSupabaseConfigured } from "@/lib/supabase/client"; import { AccountProvider, ConnectedAccount } from "@/types/mock-app"; import { AccountConnectionCard } from "./account-connection-card"; -import { TbLayoutDashboard } from "react-icons/tb"; type ConnectedAccountResponse = { provider: AccountProvider; @@ -172,15 +171,12 @@ export function IntegrationAccountsPanel({ compact = false, showContinue = false return (
-
-
-
- -

Connected Accounts

-
-

- {connectedCount}/{accounts.length} connected -

+
+
+

Connected accounts

+

+ {connectedCount}/{accounts.length} connected +

{accounts.map((account) => ( @@ -188,7 +184,7 @@ export function IntegrationAccountsPanel({ compact = false, showContinue = false
{showContinue && ( -
+

{connectedCount} of {accounts.length} accounts connected

index); - -function levelFor(index: number) { - const pattern = [0, 1, 2, 3, 1, 0, 4, 2, 3, 1, 0, 2, 4, 3, 1, 2, 0, 3, 4, 1, 2]; - return pattern[index % pattern.length]; -} - -function PlatformIcon({ platform }: { platform: "github" | "gitlab" }) { - return platform === "github" ? ( - - ) : ( - - ); -} +const repositories = [ + ["gitfusion", "TypeScript", 92, "1,234"], + ["portfolio", "TypeScript", 72, "892"], + ["jobflow", "PHP", 55, "654"], + ["dotfiles", "Shell", 30, "321"], + ["study-notes", "Markdown", 24, "287"], +] as const; + +const activities = [ + ["Pushed commits", "to gitfusion", "2h ago", FaGithub], + ["Opened a pull request", "in portfolio", "5h ago", FiGitPullRequest], + ["Merged pull request", "dotfiles", "1d ago", FaGithub], +] as const; + +const heatmap = Array.from({ length: 52 }, (_, week) => + Array.from({ length: 7 }, (_, day) => (week * 3 + day * 5 + (week % 5)) % 5), +); + +const chartPoints = "0,108 70,92 140,120 210,38 280,105 350,102 420,72 490,112 560,60 630,92"; +const gitlabPoints = "0,112 70,88 140,72 210,96 280,66 350,94 420,86 490,82 560,78 630,58"; export function HeroIllustration() { return ( -
-
-
- -
-
-
- +
+ +
@@ -184,36 +146,92 @@ export function HeroIllustration() { ); } -function ProviderCard({ provider, name, username, stats }: { provider: "github" | "gitlab"; name: string; username: string; stats: string }) { +function TopRepositories() { return ( -
-
-
- - - -
-

{name}

-

@{username}

+
+

Top repositories

+
+ {repositories.map(([name, language, width, count]) => ( +
+
+ +
+

{name}

+

{language}

+
+
+ + {count}
-
- Connected + ))} +
+
+ ); +} + +function ActivityOverview() { + return ( +
+
+

Activity overview

+
GitHubGitLab
-

{stats}

+ + + + + {[30, 70, 110].map((y) => )} + + + +
); } -function Activity({ provider, title, repo }: { provider: "github" | "gitlab"; title: string; repo: string }) { +function ConnectedAccounts() { return ( -
- - - -
-

{title}

-

{repo}

+
+

Connected accounts

+
+ +
+
+ ); +} + +function Provider({ provider, name, username }: { provider: "github" | "gitlab"; name: string; username: string }) { + const Icon = provider === "github" ? FaGithub : FaGitlab; + return ( +
+

{name}

{username}

+ Connected
); } + +function RecentActivity() { + return ( +
+

Recent activity

+
+ {activities.map(([title, description, time, Icon]) => ( +
+ +

{title}

{description}

+ +
+ ))} +
+
+ ); +} + +function heatColor(level: number) { + if (level === 0) return "bg-[#1b2030]"; + if (level === 1) return "bg-[#3b256f]"; + if (level === 2) return "bg-[#6d28d9]"; + if (level === 3) return "bg-[#8b5cf6]"; + return "bg-[#c084fc]"; +} diff --git a/src/features/landing/components/landing-navbar.tsx b/src/features/landing/components/landing-navbar.tsx index b49e281..e20a67f 100644 --- a/src/features/landing/components/landing-navbar.tsx +++ b/src/features/landing/components/landing-navbar.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import { FiLogOut } from "react-icons/fi"; +import { FiArrowRight, FiLogOut } from "react-icons/fi"; import type { LandingSessionUser } from "./landing-page"; import { AppLogo } from "@/shared/components/app-logo"; @@ -9,60 +9,59 @@ type LandingNavbarProps = { onSignOut: () => void; }; +const navItems = [ + { label: "Product", href: "#product" }, + { label: "Features", href: "#features" }, + { label: "About", href: "#about" }, + { label: "Resources", href: "#resources" }, +]; + export function LandingNavbar({ user, isCheckingSession, onSignOut }: LandingNavbarProps) { return (
- - - - Git Fusion - + + GitFusion - {user && ( -
+
- )} + ))} + - +
); } diff --git a/src/features/landing/components/landing-page.tsx b/src/features/landing/components/landing-page.tsx index c865bb5..cc84bc2 100644 --- a/src/features/landing/components/landing-page.tsx +++ b/src/features/landing/components/landing-page.tsx @@ -1,11 +1,14 @@ "use client"; +import Link from "next/link"; import { useEffect, useState } from "react"; -import { HeroContent } from "./hero-content"; -import { HeroHighlights } from "./hero-highlights"; +import { FaGithub, FaGitlab, FaLinkedin, FaXTwitter } from "react-icons/fa6"; +import { SiNextdotjs, SiSupabase, SiVercel } from "react-icons/si"; +import { FiArrowRight, FiBarChart2, FiMail, FiPlayCircle, FiTarget, FiUsers, FiZap } from "react-icons/fi"; import { HeroIllustration } from "./hero-illustration"; import { LandingNavbar } from "./landing-navbar"; import { createSupabaseBrowserClient, isSupabaseConfigured } from "@/lib/supabase/client"; +import { AppLogo } from "@/shared/components/app-logo"; export type LandingSessionUser = { name: string; @@ -13,6 +16,9 @@ export type LandingSessionUser = { avatarUrl: string | null; }; +const repositoryUrl = "https://github.com/thainapires/gitfusion"; +const navItems = ["Product", "Features", "About", "Resources"]; + export function LandingPage() { const [user, setUser] = useState(null); const [isCheckingSession, setIsCheckingSession] = useState(isSupabaseConfigured()); @@ -71,19 +77,291 @@ export function LandingPage() { }; return ( -
-
+
+
+
+ +
-
-
- - +
+ +
+

+ ✨ + Your dev journey, unified. +

+ +

+ All-in-One Developer Productivity Platform +

+ +

+ Connect your GitHub and GitLab, track your progress, analyze your activity and see the bigger picture of your coding journey. +

+ +
- +
+ + + + + + +
); } + +function LandingActions({ isAuthenticated, isCheckingSession, className = "" }: { isAuthenticated: boolean; isCheckingSession: boolean; className?: string }) { + const primaryHref = isAuthenticated ? "/dashboard" : "/sign-up"; + + return ( +
+ + {isAuthenticated ? "Go to dashboard" : "Get Started Free"} + + +
+ ); +} + +function HeroLines() { + return ( +
+
+
+
+
+
+ ); +} + +function FeatureStrip() { + const features = [ + { title: "GitHub & GitLab", description: "Connect in seconds", icon: FaGithub }, + { title: "Beautiful Insights", description: "Understand your habits", icon: FiBarChart2 }, + { title: "Track Your Growth", description: "See your evolution", icon: FiZap }, + { title: "Set Goals", description: "Stay motivated", icon: FiTarget }, + { title: "Built for Developers", description: "100% free and open source", icon: FiUsers }, + ]; + + return ( +
+ {features.map((feature) => { + const Icon = feature.icon; + return ( +
+ + + +

{feature.title}

+

{feature.description}

+
+ ); + })} +
+ ); +} + +function PlatformStrip() { + const platforms = [ + { name: "GitHub", icon: FaGithub }, + { name: "GitLab", icon: FaGitlab }, + { name: "Vercel", icon: SiVercel }, + { name: "Supabase", icon: SiSupabase }, + { name: "Next.js", icon: SiNextdotjs }, + ]; + + return ( +
+
+
+

Built with & connected to

+
+
+
+ {platforms.map((platform) => { + const Icon = platform.icon; + return ( +
+ + {platform.name} +
+ ); + })} +
+
+ ); +} + +function InsightsSection() { + return ( +
+
+

Turn activity into insights

+

+ Understand more. Build what's next. +

+

+ Go beyond raw contribution counts. GitFusion helps developers understand activity, languages, repositories, and trends across the platforms where real work happens. +

+ + Explore all features + + +
+ +
+ + +
+
+ ); +} + +function LanguagesCard() { + const languages = [ + ["TypeScript", "42%", "#8b5cf6"], + ["JavaScript", "28%", "#a855f7"], + ["PHP", "12%", "#6d5dfc"], + ["Python", "8%", "#c4b5fd"], + ["Other", "10%", "#94a3b8"], + ]; + + return ( +
+

Languages

+
+
+
+
+
+ {languages.map(([name, value, color]) => ( +
+
{name}
+
{value}
+
+ ))} +
+
+
+ ); +} + +function ContributionsCard() { + const months = [ + ["Jan", 34], + ["Feb", 78], + ["Mar", 52], + ["Apr", 82], + ["May", 60], + ["Jun", 92], + ]; + + return ( +
+
+

Contributions

+ +12% +
+
+ {months.map(([month, value]) => ( +
+ + {month} +
+ ))} +
+
+ ); +} + +function OpenSourceSection() { + return ( +
+
+
+

Open source forever

+

Built by a developer, for developers.

+

+ GitFusion is 100% free and open source. No hidden fees, no tracking, no lock-in. Just a tool made to help you understand your journey and build what's next. +

+
+ + + View on GitHub + + + Our story + +
+
+
+ ); +} + +function FinalCta({ isAuthenticated, isCheckingSession }: { isAuthenticated: boolean; isCheckingSession: boolean }) { + return ( +
+
+
+
+

+ Ready to see your dev journey in a new way? +

+

+ Connect your GitHub and GitLab, track your progress and join a growing community of developers. +

+ +
+
+ ); +} + +function LandingFooter() { + return ( +
+
+
+ + + GitFusion + +

Open source developer analytics. Made with ♥ by Thainá Pires.

+
+ + + +
+ + + + +
+
+
+ ); +} + +function navHref(label: string) { + if (label === "Product") return "#product"; + if (label === "Features") return "#features"; + if (label === "Pricing") return "#pricing"; + if (label === "About") return "#about"; + return "#resources"; +} diff --git a/src/lib/dashboard/overview.test.ts b/src/lib/dashboard/overview.test.ts new file mode 100644 index 0000000..d3a43d1 --- /dev/null +++ b/src/lib/dashboard/overview.test.ts @@ -0,0 +1,56 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { buildDashboardOverview } from "./overview"; + +describe("buildDashboardOverview", () => { + beforeEach(() => { + vi.stubGlobal("fetch", vi.fn()); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("surfaces GitHub REST error messages from the GraphQL endpoint", async () => { + const fetchMock = vi.mocked(fetch); + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ message: "Bad credentials" }), { + status: 401, + statusText: "Unauthorized", + headers: { "Content-Type": "application/json" }, + }), + ); + + await expect( + buildDashboardOverview([ + { + provider: "github", + username: "octocat", + provider_user_id: "1", + access_token: "invalid-token", + }, + ]), + ).rejects.toThrow("Bad credentials"); + }); + + it("includes the GitHub response status when the error body is empty", async () => { + const fetchMock = vi.mocked(fetch); + fetchMock.mockResolvedValue( + new Response("", { + status: 403, + statusText: "Forbidden", + }), + ); + + await expect( + buildDashboardOverview([ + { + provider: "github", + username: "octocat", + provider_user_id: "1", + access_token: "limited-token", + }, + ]), + ).rejects.toThrow("Unable to load GitHub dashboard data (403 Forbidden)."); + }); +}); diff --git a/src/lib/dashboard/overview.ts b/src/lib/dashboard/overview.ts index 1e140b7..807bbca 100644 --- a/src/lib/dashboard/overview.ts +++ b/src/lib/dashboard/overview.ts @@ -16,6 +16,19 @@ type ProviderDashboardData = { pullOrMergeRequests: number; }; +type GitHubDashboardGraphResponse = { + data?: { + viewer?: { + contributionsCollection?: { + contributionCalendar?: { weeks?: { contributionDays?: { date: string; contributionCount: number }[] }[] }; + pullRequestContributions?: { totalCount: number }; + }; + }; + }; + errors?: { message?: string }[]; + message?: string; +}; + export type StoredDailyTotal = { date: string; github_count: number; @@ -157,20 +170,12 @@ async function fetchGitHubDashboardData(account: ConnectedAccountRow, since: str variables: { from, to }, }), }); - const graphJson = await graphResponse.json() as { - data?: { - viewer?: { - contributionsCollection?: { - contributionCalendar?: { weeks?: { contributionDays?: { date: string; contributionCount: number }[] }[] }; - pullRequestContributions?: { totalCount: number }; - }; - }; - }; - errors?: { message: string }[]; - }; + const graphJson = await readJsonResponse(graphResponse); if (!graphResponse.ok || graphJson.errors?.length) { - throw new Error(graphJson.errors?.[0]?.message || "Unable to load GitHub dashboard data."); + console.log(graphResponse); + console.log(graphJson); + throw new Error(getGitHubDashboardErrorMessage(graphResponse, graphJson)); } const daily = new Map(); @@ -247,6 +252,32 @@ async function fetchGitHubEvents(account: ConnectedAccountRow) { return { activities, pullRequests }; } +async function readJsonResponse(response: Response): Promise { + try { + return await response.json() as T; + } catch { + return {} as T; + } +} + +function getGitHubDashboardErrorMessage( + response: Response, + payload: GitHubDashboardGraphResponse, +) { + const graphQLError = payload.errors?.find((error) => error.message)?.message; + + if (graphQLError) { + return graphQLError; + } + + if (payload.message) { + return payload.message; + } + + const statusText = response.statusText || "GitHub API error"; + return `Unable to load GitHub dashboard data (${response.status} ${statusText}).`; +} + async function fetchGitLabDashboardData(account: ConnectedAccountRow, since: string): Promise { const [calendarDaily, projects, events] = await Promise.all([ fetchGitLabCalendarContributions(account, since), diff --git a/src/shared/app-shell/authenticated-layout.tsx b/src/shared/app-shell/authenticated-layout.tsx index 4ae3824..7c7de09 100644 --- a/src/shared/app-shell/authenticated-layout.tsx +++ b/src/shared/app-shell/authenticated-layout.tsx @@ -4,21 +4,38 @@ import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; import { ReactNode, useEffect, useRef, useState } from "react"; import { FaGithub, FaGitlab } from "react-icons/fa"; -import { FiAlertCircle, FiAward, FiBarChart2, FiCalendar, FiCheckCircle, FiChevronDown, FiChevronLeft, FiChevronRight, FiClock, FiGitPullRequest, FiGrid, FiLogOut, FiMenu, FiSettings, FiX } from "react-icons/fi"; -import { createSupabaseBrowserClient, isSupabaseConfigured } from "@/lib/supabase/client"; -import { AccountProvider, SidebarItem } from "@/types/mock-app"; -// import { ThemeToggle } from "@/shared/components/theme-toggle"; +import { + FiAlertCircle, + FiAward, + FiBarChart2, + FiBell, + FiCalendar, + FiCheckCircle, + FiChevronDown, + FiClock, + FiCompass, + FiGitPullRequest, + FiGrid, + FiLogOut, + FiMenu, + FiMoon, + FiSearch, + FiSettings, + FiX, +} from "react-icons/fi"; import { Avatar } from "@heroui/react"; +import { createSupabaseBrowserClient, isSupabaseConfigured } from "@/lib/supabase/client"; import { AppLogo } from "@/shared/components/app-logo"; +import { AccountProvider, SidebarItem } from "@/types/mock-app"; import { DashboardSyncStatus } from "@/types/dashboard"; -const sidebarItems: SidebarItem[] = [ +const navItems: SidebarItem[] = [ { label: "Dashboard", href: "/dashboard", icon: FiGrid }, { label: "Repositories", disabled: true, icon: FiGitPullRequest }, { label: "Analytics", disabled: true, icon: FiBarChart2 }, { label: "Compare", disabled: true, icon: FiBarChart2 }, { label: "Achievements", disabled: true, icon: FiAward }, - { label: "Settings", href: "/settings", icon: FiSettings }, + { label: "Explore", disabled: true, icon: FiCompass }, ]; type AuthenticatedLayoutProps = { @@ -31,10 +48,21 @@ type AuthenticatedLayoutProps = { syncProviders?: AccountProvider[]; }; -export function AuthenticatedLayout({ title, description, children, actions, syncActions, syncStatus, syncProviders }: AuthenticatedLayoutProps) { +type UserDisplay = { + name: string; + username: string; + avatarUrl: string | null; +}; + +export function AuthenticatedLayout({ + children, + actions, + syncActions, + syncStatus, + syncProviders, +}: AuthenticatedLayoutProps) { const router = useRouter(); const [isOpen, setIsOpen] = useState(false); - const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false); const [isCheckingSession, setIsCheckingSession] = useState(isSupabaseConfigured()); useEffect(() => { @@ -46,6 +74,7 @@ export function AuthenticatedLayout({ title, description, children, actions, syn supabase.auth.getSession().then(({ data }) => { if (!data.session) { + setIsCheckingSession(false); router.replace("/sign-in"); return; } @@ -64,48 +93,322 @@ export function AuthenticatedLayout({ title, description, children, actions, syn return (
-
- setIsOpen(true)} /> - {isOpen && ( -
-
+ )} + +
+
+ {children} +
+
+
+ ); +} + +function AuthenticatedHeader({ + onOpenMobileMenu, + syncActions, + syncStatus, + syncProviders, + actions, +}: { + onOpenMobileMenu: () => void; + syncActions?: ReactNode; + syncStatus?: DashboardSyncStatus | null; + syncProviders?: AccountProvider[]; + actions?: ReactNode; +}) { + return ( +
+
+ + + + + GitFusion + + + + +
+ + +
+ +
+
+
- )} +
{actions}
+ + + + + + + + +
+
+ ); +} + +function NavItem({ item }: { item: SidebarItem }) { + const pathname = usePathname(); + const Icon = item.icon; + const isActive = item.href === pathname; + const classes = `inline-flex h-9 items-center gap-2 rounded-full px-3 text-sm font-bold transition ${ + isActive + ? "bg-primary/18 text-primary ring-1 ring-primary/25" + : item.disabled + ? "cursor-not-allowed text-muted-foreground/60" + : "text-muted-foreground hover:bg-card hover:text-foreground" + }`; + + if (!item.href || item.disabled) { + return ( + + ); + } + + return ( + + + {item.label} + + ); +} + +function SearchControl() { + return ( +
+ + + + Ctrl K + +
+ ); +} + +function IconButton({ label, children }: { label: string; children: ReactNode }) { + return ( + + ); +} + +function UserMenu() { + const router = useRouter(); + const [isOpen, setIsOpen] = useState(false); + const menuRef = useRef(null); + const user = useUserDisplay(); + + useEffect(() => { + if (!isOpen) { + return; + } + + const handlePointerDown = (event: PointerEvent) => { + if (!menuRef.current?.contains(event.target as Node)) { + setIsOpen(false); + } + }; + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + setIsOpen(false); + } + }; + + document.addEventListener("pointerdown", handlePointerDown); + document.addEventListener("keydown", handleKeyDown); + + return () => { + document.removeEventListener("pointerdown", handlePointerDown); + document.removeEventListener("keydown", handleKeyDown); + }; + }, [isOpen]); + + const handleSignOut = async () => { + if (isSupabaseConfigured()) { + const supabase = createSupabaseBrowserClient(); + await supabase.auth.signOut(); + } + + setIsOpen(false); + router.push("/sign-in"); + router.refresh(); + }; + + return ( +
+ -
- -
-
-
-
-

Dashboard

-

{title}

-

{description}

-
-
- -
- {actions} - {/* */} -
-
-
- {children} +
+ +
+

{user.name}

+

{user.username}

+
-
-
+ + setIsOpen(false)} + className="flex items-center gap-3 px-4 py-3 text-sm font-bold text-muted-foreground transition hover:bg-muted hover:text-foreground" + > + + Settings + + + +
+ )}
); } +function MobileMenu({ onNavigate }: { onNavigate: () => void }) { + const user = useUserDisplay(); + + return ( + <> +
+ + + GitFusion + + +
+ + + +
+
+ +
+
{user.name}
+
{user.username}
+
+
+
+ + ); +} + +function MobileNavItem({ item, onNavigate }: { item: SidebarItem; onNavigate: () => void }) { + const pathname = usePathname(); + const Icon = item.icon; + const isActive = item.href === pathname; + const classes = `flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-bold transition ${ + isActive + ? "bg-primary/18 text-primary ring-1 ring-primary/25" + : item.disabled + ? "cursor-not-allowed text-muted-foreground/55" + : "text-muted-foreground hover:bg-muted hover:text-foreground" + }`; + + if (!item.href || item.disabled) { + return ( + + ); + } + + return ( + + + {item.label} + + ); +} + function SyncStatusPanel({ sync, providers, actions }: { sync: DashboardSyncStatus | null; providers: AccountProvider[]; actions?: ReactNode }) { const [isOpen, setIsOpen] = useState(false); const panelRef = useRef(null); @@ -138,7 +441,7 @@ function SyncStatusPanel({ sync, providers, actions }: { sync: DashboardSyncStat if (!sync || sync.status === "idle") { return actions ? ( -
+
{actions}
) : null; @@ -148,32 +451,26 @@ function SyncStatusPanel({ sync, providers, actions }: { sync: DashboardSyncStat const shownProviders = providers.length ? providers : (["github", "gitlab"] satisfies AccountProvider[]); return ( -
-
+
+
{actions && ( -
+
{actions}
)} @@ -183,14 +480,14 @@ function SyncStatusPanel({ sync, providers, actions }: { sync: DashboardSyncStat

Last sync

-
+
{summary.finishedDetail}
@@ -220,7 +517,7 @@ function ProviderSyncRow({ provider, sync }: { provider: AccountProvider; sync: return (
- + {formatProviderName(provider)} @@ -233,6 +530,63 @@ function ProviderSyncRow({ provider, sync }: { provider: AccountProvider; sync: ); } +function UserAvatar({ user }: { user: UserDisplay }) { + return ( + + + + {getInitials(user.name)} + + + ); +} + +function useUserDisplay() { + const [display, setDisplay] = useState({ + name: "GitFusion user", + username: "", + avatarUrl: null, + }); + + useEffect(() => { + if (!isSupabaseConfigured()) { + return; + } + + const loadUser = async () => { + const supabase = createSupabaseBrowserClient(); + const { data } = await supabase.auth.getUser(); + const user = data.user; + + if (!user) { + return; + } + + const { data: profile } = await supabase + .from("profiles") + .select("full_name,avatar_url") + .eq("id", user.id) + .maybeSingle<{ full_name: string | null; avatar_url: string | null }>(); + + const metadataName = typeof user.user_metadata.full_name === "string" ? user.user_metadata.full_name : ""; + const metadataAvatarUrl = typeof user.user_metadata.avatar_url === "string" ? user.user_metadata.avatar_url : ""; + const fullName = profile?.full_name || metadataName || user.email || "GitFusion user"; + + setDisplay({ + name: fullName, + username: user.email || "", + avatarUrl: profile?.avatar_url || metadataAvatarUrl || null, + }); + }; + + loadUser(); + window.addEventListener("gitfusion:profile-updated", loadUser); + return () => window.removeEventListener("gitfusion:profile-updated", loadUser); + }, []); + + return display; +} + function getSyncSummary(sync: DashboardSyncStatus) { const isSyncing = sync.status === "syncing"; const isSynced = sync.status === "synced"; @@ -259,15 +613,15 @@ function getSyncSummary(sync: DashboardSyncStatus) { detail, finishedDetail, iconClassName: isSyncing - ? "bg-blue-500/10 text-blue-500" + ? "bg-blue-500/10 text-blue-400" : isSynced - ? "bg-emerald-500/10 text-emerald-500" - : "bg-rose-500/10 text-rose-500", + ? "bg-emerald-500/10 text-emerald-400" + : "bg-rose-500/10 text-rose-400", statusClassName: isSyncing - ? "text-blue-500" + ? "text-blue-400" : isSynced - ? "text-emerald-500" - : "text-rose-500", + ? "text-emerald-400" + : "text-rose-400", }; } @@ -282,229 +636,6 @@ function formatSyncDate(value: string) { }).format(new Date(value)); } -function MobileTopbar({ onOpen }: { onOpen: () => void }) { - const [displayAvatarUrl, setDisplayAvatarUrl] = useState(null); - const [displayName, setDisplayName] = useState("Git Fusion user"); - - useEffect(() => { - if (!isSupabaseConfigured()) { - return; - } - - const loadUser = async () => { - const supabase = createSupabaseBrowserClient(); - const { data } = await supabase.auth.getUser(); - const user = data.user; - - if (!user) { - return; - } - - const { data: profile } = await supabase - .from("profiles") - .select("full_name,avatar_url") - .eq("id", user.id) - .maybeSingle<{ full_name: string | null; avatar_url: string | null }>(); - - const metadataName = typeof user.user_metadata.full_name === "string" ? user.user_metadata.full_name : ""; - const metadataAvatarUrl = typeof user.user_metadata.avatar_url === "string" ? user.user_metadata.avatar_url : ""; - const fullName = profile?.full_name || metadataName || user.email; - - setDisplayName(fullName || "Git Fusion user"); - setDisplayAvatarUrl(profile?.avatar_url || metadataAvatarUrl || null); - }; - - loadUser(); - window.addEventListener("gitfusion:profile-updated", loadUser); - return () => window.removeEventListener("gitfusion:profile-updated", loadUser); - }, []); - - return ( -
- - - Git Fusion - - - - - - - {getInitials(displayName)} - - -
- ); -} - -function Sidebar({ onNavigate, collapsed = false, onToggleCollapse }: { onNavigate?: () => void; collapsed?: boolean; onToggleCollapse?: () => void }) { - const pathname = usePathname(); - const router = useRouter(); - const [displayName, setDisplayName] = useState("Git Fusion user"); - const [displayUsername, setDisplayUsername] = useState(""); - const [displayAvatarUrl, setDisplayAvatarUrl] = useState(null); - - useEffect(() => { - if (!isSupabaseConfigured()) { - return; - } - - const loadUser = async () => { - const supabase = createSupabaseBrowserClient(); - const { data } = await supabase.auth.getUser(); - const user = data.user; - - if (!user) { - return; - } - - const { data: profile } = await supabase - .from("profiles") - .select("full_name,avatar_url") - .eq("id", user.id) - .maybeSingle<{ full_name: string | null; avatar_url: string | null }>(); - - const metadataName = typeof user.user_metadata.full_name === "string" ? user.user_metadata.full_name : ""; - const metadataAvatarUrl = typeof user.user_metadata.avatar_url === "string" ? user.user_metadata.avatar_url : ""; - const fullName = profile?.full_name || metadataName || user.email; - - setDisplayName(fullName || "Git Fusion user"); - setDisplayUsername(user.email || ""); - setDisplayAvatarUrl(profile?.avatar_url || metadataAvatarUrl || null); - }; - - loadUser(); - window.addEventListener("gitfusion:profile-updated", loadUser); - return () => window.removeEventListener("gitfusion:profile-updated", loadUser); - }, []); - - const handleSignOut = async () => { - if (isSupabaseConfigured()) { - const supabase = createSupabaseBrowserClient(); - await supabase.auth.signOut(); - } - - onNavigate?.(); - router.push("/sign-in"); - router.refresh(); - }; - - return ( -
-
- - - {!collapsed && "Git Fusion"} - - {onNavigate ? ( - - ) : onToggleCollapse ? ( - - ) : null} -
- - - -
-
- - - - - {getInitials(displayName)} - - - - {!collapsed && ( -
-
- {displayName} -
- -
- {displayUsername} -
-
- )} -
- - -
-
- ); -} - - function getInitials(value: string) { const parts = value.trim().split(/\s+/).filter(Boolean); From 874eeab8c91529e5acf11cdfa2959e3b9dc435b0 Mon Sep 17 00:00:00 2001 From: thainapires Date: Sun, 20 Sep 2026 12:39:49 -0300 Subject: [PATCH 2/3] feat: refresh OAuth tokens and improve dashboard layout --- src/app/api/dashboard/overview/route.test.ts | 2 + src/app/api/dashboard/overview/route.ts | 1 + src/app/dashboard/page.tsx | 119 ++++++------ .../dashboard/components/activity-list.tsx | 28 ++- .../components/contribution-chart.tsx | 16 +- .../dashboard/components/metric-card.tsx | 12 +- .../dashboard/components/metrics-carousel.tsx | 170 ++++++++++++++++++ .../components/account-connection-card.tsx | 10 +- .../components/integration-accounts-panel.tsx | 13 +- src/lib/dashboard/overview.ts | 42 ++++- src/lib/integrations/providers.test.ts | 91 ++++++++++ src/lib/integrations/providers.ts | 87 ++++++++- .../modules/dashboard/dashboard.service.ts | 89 ++++++--- .../modules/dashboard/dashboard.types.ts | 3 + .../integrations/integration.repository.ts | 49 +++++ .../integrations/integration.service.ts | 1 + .../provider-token.service.test.ts | 133 ++++++++++++++ .../integrations/provider-token.service.ts | 108 +++++++++++ src/shared/app-shell/authenticated-layout.tsx | 14 +- ...0260920013000_store_oauth_redirect_uri.sql | 4 + 20 files changed, 856 insertions(+), 136 deletions(-) create mode 100644 src/features/dashboard/components/metrics-carousel.tsx create mode 100644 src/lib/integrations/providers.test.ts create mode 100644 src/server/modules/integrations/provider-token.service.test.ts create mode 100644 src/server/modules/integrations/provider-token.service.ts create mode 100644 supabase/migrations/20260920013000_store_oauth_redirect_uri.sql diff --git a/src/app/api/dashboard/overview/route.test.ts b/src/app/api/dashboard/overview/route.test.ts index 2e67633..cb27e86 100644 --- a/src/app/api/dashboard/overview/route.test.ts +++ b/src/app/api/dashboard/overview/route.test.ts @@ -92,6 +92,7 @@ describe("/api/dashboard/overview", () => { expect(getDashboardOverviewMock).toHaveBeenCalledWith({ accessToken: "supabase-token", forceRefresh: false, + requestOrigin: "https://gitfusion.test", }); }); @@ -128,6 +129,7 @@ describe("/api/dashboard/overview", () => { expect(getDashboardOverviewMock).toHaveBeenCalledWith({ accessToken: "supabase-token", forceRefresh: true, + requestOrigin: "https://gitfusion.test", }); }); diff --git a/src/app/api/dashboard/overview/route.ts b/src/app/api/dashboard/overview/route.ts index 78c9af3..3c7abfb 100644 --- a/src/app/api/dashboard/overview/route.ts +++ b/src/app/api/dashboard/overview/route.ts @@ -24,6 +24,7 @@ export async function GET(request: NextRequest) { const result = await getDashboardOverview({ accessToken, forceRefresh, + requestOrigin: request.nextUrl.origin, }); return NextResponse.json(result); diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 83ced43..02724ba 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -2,13 +2,14 @@ import Image from "next/image"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { FaFire } from "react-icons/fa"; import { FiActivity, FiFolder, FiGitPullRequest, FiRefreshCw } from "react-icons/fi"; +import { Tooltip } from "react-tooltip"; import { IntegrationAccountsPanel } from "@/features/integrations/components/integration-accounts-panel"; import { AuthenticatedLayout } from "@/shared/app-shell/authenticated-layout"; import { ActivityList } from "@/features/dashboard/components/activity-list"; import { ContributionChart } from "@/features/dashboard/components/contribution-chart"; import { MetricCard } from "@/features/dashboard/components/metric-card"; +import { MetricsCarousel } from "@/features/dashboard/components/metrics-carousel"; import { RepositoryTable } from "@/features/dashboard/components/repository-table"; import { readApiJson } from "@/lib/api/response"; import { notify } from "@/lib/notifications/toast"; @@ -112,7 +113,7 @@ export default function DashboardPage() { const activeDays = overview?.dailyContributions.filter((day) => day.total > 0).length ?? 0; const currentStreak = overview ? getCurrentStreak(overview.dailyContributions) : 0; - const dashboardMetrics = useMemo(() => overview ? buildDashboardMetrics(overview, currentStreak) : [], [overview, currentStreak]); + const dashboardMetrics = useMemo(() => overview ? buildDashboardMetrics(overview) : [], [overview]); return ( } {!isLoading && overview?.hasConnections && ( -
+
{syncStatus?.status === "failed" && ( - loadOverview({ refresh: true })} isRefreshing={isRefreshing} /> +
+ loadOverview({ refresh: true })} isRefreshing={isRefreshing} /> +
)} -
- {dashboardMetrics.map((metric) => ( - - ))} -
- -
-
- -
- - -
-
- - -
-
+ + {dashboardMetrics.map((metric) => ( + + ))} + - +
+ +
+ + +
+ +
)} ); } -function DashboardHero({ viewerName, activeDays, currentStreak }: { viewerName: string; activeDays: number; currentStreak: number }) { +function DashboardHero({ viewerName, activeDays, currentStreak, className = "" }: { viewerName: string; activeDays: number; currentStreak: number; className?: string }) { return ( -
+
-
+

Dashboard

Good to see you again, {viewerName}! 👋

+ +
+ 🔥 +

+ {currentStreak} {currentStreak === 1 ? "day" : "days"} streak +

+
+

Here's your connected GitHub and GitLab activity overview.

-
+
🔥 @@ -291,9 +296,17 @@ function ActivityOverview({ data }: { data: DailyContribution[] }) { {points.map((point, index) => ( - + + 96 ? 4 : 8} height="112" fill="transparent" /> ))} @@ -301,11 +314,12 @@ function ActivityOverview({ data }: { data: DailyContribution[] }) {
{months.map((month) => {month.label})}
+
); } -function LanguagesBreakdown({ repositories, totalContributions }: { repositories: RepositorySummary[]; totalContributions: number }) { +function LanguagesBreakdown({ repositories }: { repositories: RepositorySummary[] }) { const languages = getLanguageBreakdown(repositories); const gradient = languages.length ? `conic-gradient(${languages.map((language) => `${language.color} ${language.start}% ${language.end}%`).join(", ")})` @@ -314,12 +328,9 @@ function LanguagesBreakdown({ repositories, totalContributions }: { repositories return (

Languages

-
-
-
-

{totalContributions.toLocaleString("en-US")}

-

total contributions

-
+
+
+
{!languages.length &&

No repository language data was returned yet.

} @@ -336,27 +347,7 @@ function LanguagesBreakdown({ repositories, totalContributions }: { repositories ); } -function KeepBuildingCard() { - return ( -
-
-

Keep building

-

Small commits drive big results.

-
-
- {[34, 50, 68, 86].map((height, index) => ( - - ))} -
-
- ); -} - -function buildDashboardMetrics(overview: DashboardOverview, currentStreak: number) { +function buildDashboardMetrics(overview: DashboardOverview) { const total = getTotalContributions(overview.dailyContributions); const githubTotal = overview.dailyContributions.reduce((sum, day) => sum + day.platforms.github, 0); const gitlabTotal = overview.dailyContributions.reduce((sum, day) => sum + day.platforms.gitlab, 0); @@ -387,14 +378,6 @@ function buildDashboardMetrics(overview: DashboardOverview, currentStreak: numbe icon: FiGitPullRequest, visual: "bars" as const, }, - { - label: "Current streak", - value: `${currentStreak.toLocaleString("en-US")} ${currentStreak === 1 ? "day" : "days"}`, - helper: currentStreak > 0 ? "Nice momentum." : "No current streak yet.", - trend: `${overview.activeDays.toLocaleString("en-US")} active days`, - icon: FaFire, - visual: "progress" as const, - }, ]; } diff --git a/src/features/dashboard/components/activity-list.tsx b/src/features/dashboard/components/activity-list.tsx index 967f1f0..43f7def 100644 --- a/src/features/dashboard/components/activity-list.tsx +++ b/src/features/dashboard/components/activity-list.tsx @@ -1,23 +1,32 @@ +import { useState } from "react"; import { FaGithub, FaGitlab } from "react-icons/fa"; import { ActivityItem } from "@/types/mock-app"; -export function ActivityList({ activities }: { activities: ActivityItem[] }) { +export function ActivityList({ activities, className = "" }: { activities: ActivityItem[]; className?: string }) { + const [showAllOnMobile, setShowAllOnMobile] = useState(false); + const visibleActivities = activities.slice(0, 6); + return ( -
+

Recent activity

Latest
-
+
{!activities.length && (
No recent provider activity was returned yet.
)} - {activities.slice(0, 6).map((activity) => { + {visibleActivities.map((activity, index) => { const Icon = activity.platform === "github" ? FaGithub : FaGitlab; + const isExtraOnMobile = index >= 4 && !showAllOnMobile; + return ( -
+
@@ -32,6 +41,15 @@ export function ActivityList({ activities }: { activities: ActivityItem[] }) { ); })}
+ {visibleActivities.length > 4 && ( + + )}
); } diff --git a/src/features/dashboard/components/contribution-chart.tsx b/src/features/dashboard/components/contribution-chart.tsx index b138dce..db91f04 100644 --- a/src/features/dashboard/components/contribution-chart.tsx +++ b/src/features/dashboard/components/contribution-chart.tsx @@ -1,6 +1,6 @@ "use client"; -import { SVGAttributes } from "react"; +import { SVGAttributes, useEffect, useRef } from "react"; import CalendarHeatmap, { ReactCalendarHeatmapValue } from "react-calendar-heatmap"; import "react-calendar-heatmap/dist/styles.css"; import { Tooltip } from "react-tooltip"; @@ -9,6 +9,8 @@ import { DailyContribution } from "@/types/mock-app"; type CalendarContribution = ReactCalendarHeatmapValue & Omit; export function ContributionChart({ data }: { data: DailyContribution[] }) { + const scrollRef = useRef(null); + const values: CalendarContribution[] = data.map((contribution) => ({ ...contribution, date: parseLocalDate(contribution.date), @@ -18,6 +20,14 @@ export function ContributionChart({ data }: { data: DailyContribution[] }) { const startDate = values[0]?.date ?? new Date(); const endDate = values[values.length - 1]?.date ?? new Date(); + useEffect(() => { + const node = scrollRef.current; + + if (node) { + node.scrollLeft = node.scrollWidth; + } + }, [data]); + const tooltipDataAttrs = (value?: ReactCalendarHeatmapValue): SVGAttributes => { const contribution = value as CalendarContribution | undefined; @@ -44,8 +54,8 @@ export function ContributionChart({ data }: { data: DailyContribution[] }) {
-
-
+
+
+
{Icon && ( @@ -24,7 +24,7 @@ export function MetricCard({ metric }: { metric: EnhancedMetric }) {

{metric.helper}

- ↗ + ↗
@@ -38,7 +38,7 @@ export function MetricCard({ metric }: { metric: EnhancedMetric }) { function MetricVisual({ type }: { type?: EnhancedMetric["visual"] }) { if (type === "bars") { return ( -
+
{[18, 24, 30, 25, 34, 39, 46].map((height, index) => ( ))} @@ -48,7 +48,7 @@ function MetricVisual({ type }: { type?: EnhancedMetric["visual"] }) { if (type === "progress") { return ( -
+
{[0, 1, 2, 3, 4, 5, 6].map((index) => ( ))} @@ -57,7 +57,7 @@ function MetricVisual({ type }: { type?: EnhancedMetric["visual"] }) { } return ( - + diff --git a/src/features/dashboard/components/metrics-carousel.tsx b/src/features/dashboard/components/metrics-carousel.tsx new file mode 100644 index 0000000..855fb6a --- /dev/null +++ b/src/features/dashboard/components/metrics-carousel.tsx @@ -0,0 +1,170 @@ +"use client"; + +import type { IconType } from "react-icons"; +import { FiCalendar, FiChevronLeft, FiChevronRight } from "react-icons/fi"; +import { TouchEvent, useEffect, useRef, useState } from "react"; +import { DashboardMetric } from "@/types/mock-app"; + +type EnhancedMetric = DashboardMetric & { + icon?: IconType; + visual?: "sparkline" | "bars" | "progress"; +}; + +const AUTO_ADVANCE_MS = 5000; +const SWIPE_THRESHOLD_PX = 40; + +export function MetricsCarousel({ metrics }: { metrics: EnhancedMetric[] }) { + const count = metrics.length; + const [activeIndex, setActiveIndex] = useState(0); + const touchStartX = useRef(null); + + useEffect(() => { + if (activeIndex >= count) { + setActiveIndex(0); + } + }, [count, activeIndex]); + + useEffect(() => { + if (count <= 1) { + return; + } + + const intervalId = window.setInterval(() => { + setActiveIndex((current) => (current + 1) % count); + }, AUTO_ADVANCE_MS); + + return () => window.clearInterval(intervalId); + }, [count, activeIndex]); + + if (!count) { + return null; + } + + const goTo = (index: number) => { + setActiveIndex(((index % count) + count) % count); + }; + + const handleTouchStart = (event: TouchEvent) => { + touchStartX.current = event.touches[0]?.clientX ?? null; + }; + + const handleTouchEnd = (event: TouchEvent) => { + if (touchStartX.current === null) { + return; + } + + const deltaX = (event.changedTouches[0]?.clientX ?? touchStartX.current) - touchStartX.current; + touchStartX.current = null; + + if (Math.abs(deltaX) < SWIPE_THRESHOLD_PX) { + return; + } + + goTo(activeIndex + (deltaX < 0 ? 1 : -1)); + }; + + return ( +
+
+
+ {metrics.map((metric, index) => ( + + ))} +
+ + {count > 1 && ( + <> + + + + )} +
+ + {count > 1 && ( +
+ {metrics.map((metric, index) => ( +
+ )} +
+ ); +} + +function MobileMetricCard({ + metric, + isActive, + position, + count, +}: { + metric: EnhancedMetric; + isActive: boolean; + position: number; + count: number; +}) { + const Icon = metric.icon; + + return ( +
+
+ {Icon && ( + + + + )} +

{metric.label}

+
+ +

{metric.value}

+

{metric.helper}

+ +
+ + {metric.trend} +
+
+ ); +} diff --git a/src/features/integrations/components/account-connection-card.tsx b/src/features/integrations/components/account-connection-card.tsx index b95c285..e940339 100644 --- a/src/features/integrations/components/account-connection-card.tsx +++ b/src/features/integrations/components/account-connection-card.tsx @@ -23,7 +23,7 @@ export function AccountConnectionCard({ account, onConnect, onDisconnect, compac -
+

{account.name}

{isConnected ? `@${account.username}` : "Connect your account"} @@ -34,17 +34,17 @@ export function AccountConnectionCard({ account, onConnect, onDisconnect, compac

{isConnected ? ( <> - Connected + Connected - + ) : ( )}
diff --git a/src/features/integrations/components/integration-accounts-panel.tsx b/src/features/integrations/components/integration-accounts-panel.tsx index 03dbb0e..946f556 100644 --- a/src/features/integrations/components/integration-accounts-panel.tsx +++ b/src/features/integrations/components/integration-accounts-panel.tsx @@ -21,6 +21,7 @@ type IntegrationAccountsPanelProps = { compact?: boolean; showContinue?: boolean; redirectTo?: string; + className?: string; }; const providerAccounts: ConnectedAccount[] = [ @@ -46,7 +47,7 @@ const providerAccounts: ConnectedAccount[] = [ }, ]; -export function IntegrationAccountsPanel({ compact = false, showContinue = false, redirectTo = "/connect-accounts" }: IntegrationAccountsPanelProps) { +export function IntegrationAccountsPanel({ compact = false, showContinue = false, redirectTo = "/connect-accounts", className = "" }: IntegrationAccountsPanelProps) { const [accounts, setAccounts] = useState(() => buildAccounts([])); const loadAccounts = useCallback(async () => { @@ -170,7 +171,7 @@ export function IntegrationAccountsPanel({ compact = false, showContinue = false const connectedCount = accounts.filter((account) => account.status === "connected").length; return ( -
+

Connected accounts

@@ -178,9 +179,11 @@ export function IntegrationAccountsPanel({ compact = false, showContinue = false {connectedCount}/{accounts.length} connected
- {accounts.map((account) => ( - - ))} +
+ {accounts.map((account) => ( + + ))} +
{showContinue && ( diff --git a/src/lib/dashboard/overview.ts b/src/lib/dashboard/overview.ts index 807bbca..95b21ef 100644 --- a/src/lib/dashboard/overview.ts +++ b/src/lib/dashboard/overview.ts @@ -35,6 +35,17 @@ export type StoredDailyTotal = { gitlab_count: number; }; +export class ProviderApiError extends Error { + constructor( + public readonly provider: AccountProvider, + public readonly status: number, + message: string, + ) { + super(message); + this.name = "ProviderApiError"; + } +} + const dashboardDays = 365; const gitlabApiBaseUrl = "https://gitlab.com/api/v4"; @@ -172,9 +183,15 @@ async function fetchGitHubDashboardData(account: ConnectedAccountRow, since: str }); const graphJson = await readJsonResponse(graphResponse); + if (graphResponse.status === 401) { + throw new ProviderApiError( + "github", + 401, + getGitHubDashboardErrorMessage(graphResponse, graphJson), + ); + } + if (!graphResponse.ok || graphJson.errors?.length) { - console.log(graphResponse); - console.log(graphJson); throw new Error(getGitHubDashboardErrorMessage(graphResponse, graphJson)); } @@ -205,6 +222,8 @@ async function fetchGitHubRepos(account: ConnectedAccountRow): Promise(); } @@ -386,6 +409,8 @@ async function fetchAllGitLabPages(path: string, accessToken: string) { headers: { Authorization: `Bearer ${accessToken}` }, }); + throwIfUnauthorized(response, "gitlab"); + if (!response.ok) { break; } @@ -398,6 +423,19 @@ async function fetchAllGitLabPages(path: string, accessToken: string) { return items; } +function throwIfUnauthorized( + response: Response, + provider: AccountProvider, +): void { + if (response.status === 401) { + throw new ProviderApiError( + provider, + 401, + `${provider} credentials are invalid or expired.`, + ); + } +} + function withGitLabPage(path: string, page: string) { const [pathname, query = ""] = path.split("?"); const params = new URLSearchParams(query); diff --git a/src/lib/integrations/providers.test.ts b/src/lib/integrations/providers.test.ts new file mode 100644 index 0000000..82af970 --- /dev/null +++ b/src/lib/integrations/providers.test.ts @@ -0,0 +1,91 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + ProviderTokenRefreshError, + refreshProviderToken, +} from "./providers"; + +describe("refreshProviderToken", () => { + beforeEach(() => { + process.env.GITHUB_OAUTH_CLIENT_ID = "github-client"; + process.env.GITHUB_OAUTH_CLIENT_SECRET = "github-secret"; + process.env.GITLAB_OAUTH_CLIENT_ID = "gitlab-client"; + process.env.GITLAB_OAUTH_CLIENT_SECRET = "gitlab-secret"; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("exchanges a GitLab refresh token for a new token pair", async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + access_token: "new-access", + refresh_token: "new-refresh", + expires_in: 7200, + token_type: "Bearer", + }), + { + status: 200, + headers: { "Content-Type": "application/json" }, + }, + ), + ); + vi.stubGlobal("fetch", fetchMock); + + await expect( + refreshProviderToken({ + provider: "gitlab", + refreshToken: "old-refresh", + }), + ).resolves.toMatchObject({ + access_token: "new-access", + refresh_token: "new-refresh", + expires_in: 7200, + }); + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe("https://gitlab.com/oauth/token"); + expect(init.method).toBe("POST"); + expect(String(init.body)).toContain("grant_type=refresh_token"); + expect(String(init.body)).toContain("refresh_token=old-refresh"); + }); + + it("distinguishes rejected refresh credentials from temporary failures", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response( + JSON.stringify({ error: "invalid_grant" }), + { status: 400 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ message: "temporarily unavailable" }), + { status: 503 }, + ), + ); + vi.stubGlobal("fetch", fetchMock); + + const rejected = refreshProviderToken({ + provider: "github", + refreshToken: "rejected-refresh", + }); + await expect(rejected).rejects.toMatchObject({ + name: "ProviderTokenRefreshError", + requiresReconnect: true, + } satisfies Partial); + + const temporary = refreshProviderToken({ + provider: "github", + refreshToken: "valid-refresh", + }); + await expect(temporary).rejects.toMatchObject({ + name: "ProviderTokenRefreshError", + requiresReconnect: false, + } satisfies Partial); + }); +}); diff --git a/src/lib/integrations/providers.ts b/src/lib/integrations/providers.ts index c2d4337..1dd2342 100644 --- a/src/lib/integrations/providers.ts +++ b/src/lib/integrations/providers.ts @@ -7,6 +7,15 @@ export type ProviderProfile = { avatarUrl: string | null; }; +export type ProviderTokenData = { + access_token: string; + refresh_token?: string; + expires_in?: number; + refresh_token_expires_in?: number; + scope?: string; + token_type?: string; +}; + export function isIntegrationProvider(provider: string): provider is IntegrationProvider { return provider === "github" || provider === "gitlab"; } @@ -72,12 +81,7 @@ export async function exchangeCodeForToken({ provider, code, redirectUri }: { pr body, }); - const tokenData = await response.json() as { - access_token?: string; - refresh_token?: string; - expires_in?: number; - scope?: string; - token_type?: string; + const tokenData = await response.json() as Partial & { error?: string; error_description?: string; }; @@ -86,7 +90,76 @@ export async function exchangeCodeForToken({ provider, code, redirectUri }: { pr throw new Error(tokenData.error_description || tokenData.error || `Unable to connect ${provider}.`); } - return tokenData; + return tokenData as ProviderTokenData; +} + +export async function refreshProviderToken({ + provider, + refreshToken, + redirectUri, +}: { + provider: IntegrationProvider; + refreshToken: string; + redirectUri?: string | null; +}): Promise { + const config = getProviderConfig(provider); + + if (!config.clientId || !config.clientSecret) { + throw new Error(`${provider} OAuth credentials are not configured.`); + } + + const body = new URLSearchParams({ + client_id: config.clientId, + client_secret: config.clientSecret, + grant_type: "refresh_token", + refresh_token: refreshToken, + }); + + if (redirectUri) { + body.set("redirect_uri", redirectUri); + } + + const response = await fetch(config.tokenUrl, { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/x-www-form-urlencoded", + }, + body, + }); + + const tokenData = await response.json().catch(() => ({})) as Partial & { + error?: string; + error_description?: string; + message?: string; + }; + + if (!response.ok || !tokenData.access_token) { + const message = tokenData.error_description || tokenData.error || tokenData.message; + const requiresReconnect = + tokenData.error === "bad_refresh_token" || + tokenData.error === "invalid_grant"; + throw new ProviderTokenRefreshError( + provider, + message || `Unable to refresh ${provider} access token.`, + response.status, + requiresReconnect, + ); + } + + return tokenData as ProviderTokenData; +} + +export class ProviderTokenRefreshError extends Error { + constructor( + public readonly provider: IntegrationProvider, + message: string, + public readonly status: number, + public readonly requiresReconnect: boolean, + ) { + super(message); + this.name = "ProviderTokenRefreshError"; + } } export async function fetchProviderProfile(provider: IntegrationProvider, accessToken: string): Promise { diff --git a/src/server/modules/dashboard/dashboard.service.ts b/src/server/modules/dashboard/dashboard.service.ts index 6e3310e..2084275 100644 --- a/src/server/modules/dashboard/dashboard.service.ts +++ b/src/server/modules/dashboard/dashboard.service.ts @@ -5,11 +5,12 @@ import { DashboardSyncStatus } from "@/types/dashboard"; import { buildDashboardOverview, buildDashboardOverviewFromStoredDailyTotals, + ProviderApiError, } from "@/lib/dashboard/overview"; -import { decryptProviderToken } from "@/lib/security/tokens"; import { createSupabaseAdminClient, } from "@/lib/supabase/server"; +import { getValidProviderAccessToken } from "@/server/modules/integrations/provider-token.service"; import { buildDashboardCacheKey, @@ -28,13 +29,13 @@ import { } from "./dashboard.repository"; import { ConnectedAccountRow } from "./dashboard.types"; import { getAuthenticatedUser } from "@/server/auth/auth.service"; -import { AppError } from "@/server/errors/app-error"; const STALE_RUNNING_SYNC_MS = 15 * 60 * 1000; type GetDashboardOverviewParams = { accessToken: string; forceRefresh?: boolean; + requestOrigin: string; }; type FetchAccount = { @@ -51,9 +52,15 @@ type SyncRunRow = { export async function getDashboardOverview({ accessToken, forceRefresh = false, + requestOrigin, }: GetDashboardOverviewParams) { const { id: userId } = await getAuthenticatedUser(accessToken); - const accounts = await getConnectedAccounts(userId); + const accounts = (await getConnectedAccounts(userId)).map((account) => ({ + ...account, + oauth_redirect_uri: + account.oauth_redirect_uri || + `${requestOrigin}/api/integrations/${account.provider}/callback`, + })); const cacheKey = buildDashboardCacheKey(accounts); if (!forceRefresh) { @@ -127,7 +134,7 @@ async function getConnectedAccounts( const { data, error } = await supabase .from("connected_accounts") .select( - "provider,username,provider_user_id,access_token_encrypted,updated_at,last_sync_at", + "provider,username,provider_user_id,access_token_encrypted,refresh_token_encrypted,expires_at,oauth_redirect_uri,updated_at,last_sync_at", ) .eq("user_id", userId); @@ -259,19 +266,8 @@ async function syncDashboardOverview({ syncRunId: string; }) { try { - const fetchAccounts = getFetchAccounts(accounts); - - if ( - accounts.length && - fetchAccounts.length !== accounts.length - ) { - throw new AppError( - "One or more connected provider tokens are unavailable. Reconnect the affected account.", - 409, - ); - } - - const overview = await buildDashboardOverview(fetchAccounts); + const { overview, fetchAccounts } = + await buildDashboardOverviewWithValidTokens(userId, accounts); await persistDailyTotals(userId, overview); @@ -305,22 +301,59 @@ async function syncDashboardOverview({ } } -function getFetchAccounts( +async function buildDashboardOverviewWithValidTokens( + userId: string, accounts: ConnectedAccountRow[], -): FetchAccount[] { - return accounts - .map((account) => ({ +): Promise<{ + overview: Awaited>; + fetchAccounts: FetchAccount[]; +}> { + const fetchAccounts = await Promise.all( + accounts.map(async (account) => ({ provider: account.provider, username: account.username, provider_user_id: account.provider_user_id, - access_token: decryptProviderToken( - account.access_token_encrypted, - ), - })) - .filter( - (account): account is FetchAccount => - Boolean(account.access_token), + access_token: await getValidProviderAccessToken({ + userId, + account, + }), + })), + ); + + try { + return { + overview: await buildDashboardOverview(fetchAccounts), + fetchAccounts, + }; + } catch (error) { + if (!(error instanceof ProviderApiError) || error.status !== 401) { + throw error; + } + + const connectedAccount = accounts.find( + (account) => account.provider === error.provider, ); + + if (!connectedAccount) { + throw error; + } + + const refreshedAccessToken = await getValidProviderAccessToken({ + userId, + account: connectedAccount, + forceRefresh: true, + }); + const retryAccounts = fetchAccounts.map((account) => + account.provider === error.provider + ? { ...account, access_token: refreshedAccessToken } + : account, + ); + + return { + overview: await buildDashboardOverview(retryAccounts), + fetchAccounts: retryAccounts, + }; + } } async function getDashboardSyncStatus( diff --git a/src/server/modules/dashboard/dashboard.types.ts b/src/server/modules/dashboard/dashboard.types.ts index 1290571..babd7e1 100644 --- a/src/server/modules/dashboard/dashboard.types.ts +++ b/src/server/modules/dashboard/dashboard.types.ts @@ -5,6 +5,9 @@ export type ConnectedAccountRow = { username: string; provider_user_id: string; access_token_encrypted: string; + refresh_token_encrypted: string | null; + expires_at: string | null; + oauth_redirect_uri: string | null; updated_at?: string; last_sync_at?: string | null; }; diff --git a/src/server/modules/integrations/integration.repository.ts b/src/server/modules/integrations/integration.repository.ts index 85b815d..9d16ded 100644 --- a/src/server/modules/integrations/integration.repository.ts +++ b/src/server/modules/integrations/integration.repository.ts @@ -13,6 +13,18 @@ type SaveConnectedAccountParams = { tokenType: string | null; scopes: string[]; expiresAt: string | null; + oauthRedirectUri: string; +}; + +type UpdateConnectedAccountTokensParams = { + userId: string; + provider: AccountProvider; + accessTokenEncrypted: string; + refreshTokenEncrypted: string | null; + tokenType: string | null; + scopes: string[] | null; + expiresAt: string | null; + oauthRedirectUri: string | null; }; export async function getConnectedAccounts(userId: string) { @@ -47,6 +59,7 @@ export async function saveConnectedAccount({ tokenType, scopes, expiresAt, + oauthRedirectUri, }: SaveConnectedAccountParams) { const supabase = createSupabaseAdminClient(); const now = new Date().toISOString(); @@ -66,6 +79,7 @@ export async function saveConnectedAccount({ token_type: tokenType, scopes, expires_at: expiresAt, + oauth_redirect_uri: oauthRedirectUri, connected_at: now, updated_at: now, }, @@ -96,6 +110,41 @@ export async function deleteConnectedAccount( } } +export async function updateConnectedAccountTokens({ + userId, + provider, + accessTokenEncrypted, + refreshTokenEncrypted, + tokenType, + scopes, + expiresAt, + oauthRedirectUri, +}: UpdateConnectedAccountTokensParams) { + const supabase = createSupabaseAdminClient(); + const values: Record = { + access_token_encrypted: accessTokenEncrypted, + refresh_token_encrypted: refreshTokenEncrypted, + token_type: tokenType, + expires_at: expiresAt, + oauth_redirect_uri: oauthRedirectUri, + updated_at: new Date().toISOString(), + }; + + if (scopes) { + values.scopes = scopes; + } + + const { error } = await supabase + .from("connected_accounts") + .update(values) + .eq("user_id", userId) + .eq("provider", provider); + + if (error) { + throw new Error(error.message); + } +} + //TODO: move this to dashboard module, because technically it belongs there, not the integration export async function invalidateDashboardCache(userId: string) { const supabase = createSupabaseAdminClient(); diff --git a/src/server/modules/integrations/integration.service.ts b/src/server/modules/integrations/integration.service.ts index 085d6a9..3896744 100644 --- a/src/server/modules/integrations/integration.service.ts +++ b/src/server/modules/integrations/integration.service.ts @@ -128,6 +128,7 @@ export async function completeIntegration({ tokenType: tokenData.token_type ?? null, scopes, expiresAt, + oauthRedirectUri: redirectUri, }); await invalidateDashboardCache(stateRow.user_id); diff --git a/src/server/modules/integrations/provider-token.service.test.ts b/src/server/modules/integrations/provider-token.service.test.ts new file mode 100644 index 0000000..ce05bf6 --- /dev/null +++ b/src/server/modules/integrations/provider-token.service.test.ts @@ -0,0 +1,133 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + ProviderTokenRefreshError, + refreshProviderToken, +} from "@/lib/integrations/providers"; +import { decryptProviderToken, encryptProviderToken } from "@/lib/security/tokens"; + +import { updateConnectedAccountTokens } from "./integration.repository"; +import { + getValidProviderAccessToken, + shouldRefreshProviderToken, +} from "./provider-token.service"; + +vi.mock("@/lib/integrations/providers", async (importOriginal) => { + const original = await importOriginal(); + + return { + ...original, + refreshProviderToken: vi.fn(), + }; +}); + +vi.mock("./integration.repository", () => ({ + updateConnectedAccountTokens: vi.fn(), +})); + +const refreshProviderTokenMock = vi.mocked(refreshProviderToken); +const updateConnectedAccountTokensMock = vi.mocked(updateConnectedAccountTokens); + +function createAccount(overrides: Partial<{ + provider: "github" | "gitlab"; + access_token_encrypted: string; + refresh_token_encrypted: string | null; + expires_at: string | null; + oauth_redirect_uri: string | null; +}> = {}) { + return { + provider: "github" as const, + access_token_encrypted: encryptProviderToken("current-access-token"), + refresh_token_encrypted: encryptProviderToken("current-refresh-token"), + expires_at: "2099-01-01T00:00:00.000Z", + oauth_redirect_uri: "https://gitfusion.test/api/integrations/github/callback", + ...overrides, + }; +} + +describe("provider token service", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.GITFUSION_TOKEN_ENCRYPTION_KEY = "provider-token-service-test-key"; + }); + + it("uses an access token that is valid for more than five minutes", async () => { + const token = await getValidProviderAccessToken({ + userId: "user-1", + account: createAccount(), + }); + + expect(token).toBe("current-access-token"); + expect(refreshProviderTokenMock).not.toHaveBeenCalled(); + expect(updateConnectedAccountTokensMock).not.toHaveBeenCalled(); + }); + + it("refreshes and persists rotated credentials before expiration", async () => { + refreshProviderTokenMock.mockResolvedValue({ + access_token: "next-access-token", + refresh_token: "next-refresh-token", + expires_in: 7200, + token_type: "bearer", + scope: "read_user read_api", + }); + const account = createAccount({ + provider: "gitlab", + expires_at: "2020-01-01T00:00:00.000Z", + oauth_redirect_uri: "https://gitfusion.test/api/integrations/gitlab/callback", + }); + + const token = await getValidProviderAccessToken({ + userId: "user-1", + account, + }); + + expect(token).toBe("next-access-token"); + expect(refreshProviderTokenMock).toHaveBeenCalledWith({ + provider: "gitlab", + refreshToken: "current-refresh-token", + redirectUri: "https://gitfusion.test/api/integrations/gitlab/callback", + }); + expect(updateConnectedAccountTokensMock).toHaveBeenCalledOnce(); + + const update = updateConnectedAccountTokensMock.mock.calls[0][0]; + expect(update).toMatchObject({ + userId: "user-1", + provider: "gitlab", + tokenType: "bearer", + scopes: ["read_user", "read_api"], + }); + expect(decryptProviderToken(update.accessTokenEncrypted)).toBe("next-access-token"); + expect(decryptProviderToken(update.refreshTokenEncrypted)).toBe("next-refresh-token"); + }); + + it("requires reconnection only when the refresh credential is rejected", async () => { + refreshProviderTokenMock.mockRejectedValue( + new ProviderTokenRefreshError("github", "bad_refresh_token", 400, true), + ); + + await expect( + getValidProviderAccessToken({ + userId: "user-1", + account: createAccount({ + expires_at: "2020-01-01T00:00:00.000Z", + }), + }), + ).rejects.toThrow( + "GitHub authorization could not be renewed. Reconnect the account and try again.", + ); + }); +}); + +describe("shouldRefreshProviderToken", () => { + it("refreshes tokens inside the five minute safety window", () => { + const now = Date.parse("2026-09-19T12:00:00.000Z"); + + expect( + shouldRefreshProviderToken("2026-09-19T12:04:59.000Z", now), + ).toBe(true); + expect( + shouldRefreshProviderToken("2026-09-19T12:05:01.000Z", now), + ).toBe(false); + expect(shouldRefreshProviderToken(null, now)).toBe(false); + }); +}); diff --git a/src/server/modules/integrations/provider-token.service.ts b/src/server/modules/integrations/provider-token.service.ts new file mode 100644 index 0000000..50868aa --- /dev/null +++ b/src/server/modules/integrations/provider-token.service.ts @@ -0,0 +1,108 @@ +import { + ProviderTokenRefreshError, + refreshProviderToken, +} from "@/lib/integrations/providers"; +import { + decryptProviderToken, + encryptProviderToken, +} from "@/lib/security/tokens"; +import { AppError } from "@/server/errors/app-error"; +import { AccountProvider } from "@/types/mock-app"; + +import { updateConnectedAccountTokens } from "./integration.repository"; + +const TOKEN_REFRESH_WINDOW_MS = 5 * 60 * 1000; + +export type ProviderCredentialAccount = { + provider: AccountProvider; + access_token_encrypted: string; + refresh_token_encrypted: string | null; + expires_at: string | null; + oauth_redirect_uri: string | null; +}; + +export function shouldRefreshProviderToken( + expiresAt: string | null, + now = Date.now(), +): boolean { + if (!expiresAt) { + return false; + } + + const expiration = new Date(expiresAt).getTime(); + return !Number.isFinite(expiration) || expiration <= now + TOKEN_REFRESH_WINDOW_MS; +} + +export async function getValidProviderAccessToken({ + userId, + account, + forceRefresh = false, +}: { + userId: string; + account: ProviderCredentialAccount; + forceRefresh?: boolean; +}): Promise { + const accessToken = decryptProviderToken(account.access_token_encrypted); + + if (!accessToken) { + throw reconnectRequiredError(account.provider); + } + + if (!forceRefresh && !shouldRefreshProviderToken(account.expires_at)) { + return accessToken; + } + + const refreshToken = decryptProviderToken(account.refresh_token_encrypted); + + if (!refreshToken) { + throw reconnectRequiredError(account.provider); + } + + try { + const tokenData = await refreshProviderToken({ + provider: account.provider, + refreshToken, + redirectUri: account.oauth_redirect_uri, + }); + const nextRefreshToken = tokenData.refresh_token || refreshToken; + const expiresAt = tokenData.expires_in + ? new Date(Date.now() + tokenData.expires_in * 1000).toISOString() + : null; + const scopes = tokenData.scope + ? tokenData.scope.split(/[ ,]+/).filter(Boolean) + : null; + const accessTokenEncrypted = encryptProviderToken(tokenData.access_token); + const refreshTokenEncrypted = encryptProviderToken(nextRefreshToken); + + await updateConnectedAccountTokens({ + userId, + provider: account.provider, + accessTokenEncrypted, + refreshTokenEncrypted, + tokenType: tokenData.token_type ?? null, + scopes, + expiresAt, + oauthRedirectUri: account.oauth_redirect_uri, + }); + + account.access_token_encrypted = accessTokenEncrypted; + account.refresh_token_encrypted = refreshTokenEncrypted; + account.expires_at = expiresAt; + + return tokenData.access_token; + } catch (error) { + if (error instanceof ProviderTokenRefreshError && error.requiresReconnect) { + throw reconnectRequiredError(account.provider); + } + + throw error; + } +} + +function reconnectRequiredError(provider: AccountProvider): AppError { + const label = provider === "github" ? "GitHub" : "GitLab"; + return new AppError( + `${label} authorization could not be renewed. Reconnect the account and try again.`, + 409, + ); +} diff --git a/src/shared/app-shell/authenticated-layout.tsx b/src/shared/app-shell/authenticated-layout.tsx index 7c7de09..fb60262 100644 --- a/src/shared/app-shell/authenticated-layout.tsx +++ b/src/shared/app-shell/authenticated-layout.tsx @@ -115,7 +115,7 @@ export function AuthenticatedLayout({ )}
-
+
{children}
@@ -138,7 +138,7 @@ function AuthenticatedHeader({ }) { return (
-
+
@@ -176,13 +176,13 @@ function AuthenticatedHeader({
{actions}
- + {/* - + */}
@@ -333,7 +333,7 @@ function UserMenu() { type="button" role="menuitem" onClick={handleSignOut} - className="flex w-full items-center gap-3 px-4 py-3 text-left text-sm font-bold text-muted-foreground transition hover:bg-muted hover:text-foreground" + className="flex w-full items-center gap-3 px-4 py-3 text-left text-sm font-bold text-muted-foreground transition hover:bg-muted hover:text-foreground cursor-pointer" > Sign out diff --git a/supabase/migrations/20260920013000_store_oauth_redirect_uri.sql b/supabase/migrations/20260920013000_store_oauth_redirect_uri.sql new file mode 100644 index 0000000..bb2105c --- /dev/null +++ b/supabase/migrations/20260920013000_store_oauth_redirect_uri.sql @@ -0,0 +1,4 @@ +alter table public.connected_accounts + add column if not exists oauth_redirect_uri text; + +notify pgrst, 'reload schema'; From 38ecc2ab6ab661f8005d28656f6f02c190364bbf Mon Sep 17 00:00:00 2001 From: thainapires Date: Sun, 20 Sep 2026 14:41:41 -0300 Subject: [PATCH 3/3] chore: improve landing page and update loading --- src/app/dashboard/page.tsx | 46 ++++++++++--- .../landing/components/hero-illustration.tsx | 4 +- .../landing/components/landing-navbar.tsx | 2 +- .../landing/components/landing-page.tsx | 64 +++++++++---------- 4 files changed, 70 insertions(+), 46 deletions(-) diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 02724ba..683c8fa 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -408,7 +408,7 @@ function getLanguageBreakdown(repositories: RepositorySummary[]) { const entries = Array.from(totals.entries()).sort((a, b) => b[1] - a[1]).slice(0, 5); const total = entries.reduce((sum, [, value]) => sum + value, 0); let cursor = 0; - const colors = ["#8b5cf6", "#a855f7", "#c084fc", "#7c3aed", "#818cf8"]; + const colors = ["#67E8F9", "#A78BFA", "#F9A8D4", "#FBBF24", "#6EE7B7"]; return entries.map(([name, value], index) => { const percent = total ? Math.round((value / total) * 100) : 0; @@ -457,16 +457,42 @@ function parseLocalDate(date: string) { function DashboardLoading() { return ( -
-
-
- {Array.from({ length: 4 }).map((_, index) => ( -
- ))} +
+
+ +
+ + {Array.from({ length: 3 }).map((_, index) => ( +
+ ))} + +
+
+
+
+
+
+
+ +
+
+
+
+
+
-
-
-
+ +
+
+
); diff --git a/src/features/landing/components/hero-illustration.tsx b/src/features/landing/components/hero-illustration.tsx index e333d8a..f27db1f 100644 --- a/src/features/landing/components/hero-illustration.tsx +++ b/src/features/landing/components/hero-illustration.tsx @@ -44,8 +44,8 @@ export function HeroIllustration() { return (
-
-
+
+