diff --git a/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx new file mode 100644 index 00000000..51b37102 --- /dev/null +++ b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx @@ -0,0 +1,267 @@ +'use client'; + +import { use } from 'react'; +import { FaGithub, FaCodeBranch, FaCircleNotch, FaExclamationCircle, FaExternalLinkAlt, FaSyncAlt } from 'react-icons/fa'; +import { useAuth } from '@/lib/hooks/useAuth'; +import { useGitHubData } from '@/lib/hooks/useGitHubData'; +import { useGitHubIntegration } from '@/lib/hooks/useGitHubIntegration'; + +export default function GitHubPage({ params }: { params: Promise<{ projectId: string }> }) { + const { projectId } = use(params); + const { userId, isLoading: authLoading, error: authError } = useAuth(); + const { patStatus, isLoading: patLoading } = useGitHubIntegration(projectId); + const { pullRequests, issues, isLoading: dataLoading, error, refetch } = useGitHubData(projectId, { state: 'open' }); + + const isLoading = authLoading || patLoading || dataLoading; + + if (authLoading || patLoading) { + return ( +
Loading...
+Please sign in to view this page
+View pull requests and issues from your repository
++ Connect your GitHub repository in settings to view pull requests and issues here. +
+ + Go to Settings + +View pull requests and issues from your repository
+{error}
+Loading pull requests...
+No open pull requests
+Loading issues...
+No open issues
+Loading...
@@ -134,7 +203,7 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: Upload image {logoPreview && logoPreview !== (project?.logoUrl ?? null) && ( -New logo selected — save to apply
+New logo selected - save to apply
)}PNG, JPG, SVG up to 5 MB
Loading GitHub status...
+ ) : patStatus?.hasPAT ? ( ++ Connected to:{' '} + + {patStatus.githubUrl} + +
+ )} + + {patStatus.updatedAt && ( ++ Token last updated: {new Date(patStatus.updatedAt).toLocaleDateString()} +
+ )} + + {isProjectLead && ( ++ Connect your GitHub repository to view pull requests and issues in your project dashboard. +
+ + {isProjectLead ? ( + <> + {!patStatus?.githubUrl && ( ++ Only project leads can configure the GitHub integration. +
+ )} +
+ Create a token with repo scope at{' '}
+
+ GitHub Settings
+
+
{patError}
} + +{patSuccess}
} +Changes saved!
diff --git a/src/app/api/projects/[projectId]/github/issues/route.ts b/src/app/api/projects/[projectId]/github/issues/route.ts new file mode 100644 index 00000000..a950935c --- /dev/null +++ b/src/app/api/projects/[projectId]/github/issues/route.ts @@ -0,0 +1,72 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { isProjectMember } from '@/lib/utils/authorization'; +import { fetchIssues, parseGitHubUrl } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + if (!project) { + return NextResponse.json({ error: 'Project not found' }, { status: 404 }); + } + + if (!project.github_pat_encrypted) { + return NextResponse.json({ error: 'GitHub not connected' }, { status: 400 }); + } + + if (!project.githubUrl) { + return NextResponse.json({ error: 'No GitHub URL configured' }, { status: 400 }); + } + + const parsed = parseGitHubUrl(project.githubUrl); + if (!parsed) { + return NextResponse.json({ error: 'Invalid GitHub URL' }, { status: 400 }); + } + + const { owner, repo } = parsed; + + const { searchParams } = new URL(request.url); + const state = (searchParams.get('state') as 'open' | 'closed' | 'all') ?? 'open'; + const perPage = parseInt(searchParams.get('per_page') ?? '30', 10); + + const { data, error } = await fetchIssues(owner, repo, project.github_pat_encrypted, { + state, + per_page: Math.min(perPage, 100), + }); + + if (error) { + return NextResponse.json({ error: error.message }, { status: error.status ?? 500 }); + } + + return NextResponse.json({ data }); + } catch (error) { + console.error('Error fetching issues:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/app/api/projects/[projectId]/github/pat/route.ts b/src/app/api/projects/[projectId]/github/pat/route.ts new file mode 100644 index 00000000..d23c6267 --- /dev/null +++ b/src/app/api/projects/[projectId]/github/pat/route.ts @@ -0,0 +1,138 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { encryptPAT } from '@/lib/utils/encryption'; +import { isProjectLead, isProjectMember } from '@/lib/utils/authorization'; +import { validateGitHubPAT } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +/** + * GET - Check if PAT is configured (returns only status, not the token) + */ +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, github_pat_updated_at, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + return NextResponse.json({ + hasPAT: !!project?.github_pat_encrypted, + updatedAt: project?.github_pat_updated_at ?? null, + githubUrl: project?.githubUrl ?? null, + }); + } catch (error) { + console.error('Error checking PAT status:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} + +/** + * POST - Save or update the PAT + */ +export async function POST(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const leadCheck = await isProjectLead(user.id, projectId); + if (!leadCheck) { + return NextResponse.json({ error: 'Only project leads can configure GitHub integration' }, { status: 403 }); + } + + const body = await request.json(); + const { pat } = body; + + if (!pat || typeof pat !== 'string') { + return NextResponse.json({ error: 'PAT is required' }, { status: 400 }); + } + + const validation = await validateGitHubPAT(pat); + if (!validation.valid) { + return NextResponse.json({ error: validation.error ?? 'Invalid PAT' }, { status: 400 }); + } + + const encryptedPAT = encryptPAT(pat); + + const { error: updateError } = await supabase + .from('projects') + .update({ + github_pat_encrypted: encryptedPAT, + github_pat_updated_at: new Date().toISOString(), + }) + .eq('id', projectId); + + if (updateError) { + console.error('Error saving PAT:', updateError); + return NextResponse.json({ error: 'Failed to save PAT' }, { status: 500 }); + } + + return NextResponse.json({ success: true, message: 'GitHub token saved successfully' }); + } catch (error) { + console.error('Error saving PAT:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} + +/** + * DELETE - Remove the PAT + */ +export async function DELETE(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const leadCheck = await isProjectLead(user.id, projectId); + if (!leadCheck) { + return NextResponse.json({ error: 'Only project leads can remove GitHub integration' }, { status: 403 }); + } + + const { error: updateError } = await supabase + .from('projects') + .update({ + github_pat_encrypted: null, + github_pat_updated_at: null, + }) + .eq('id', projectId); + + if (updateError) { + console.error('Error removing PAT:', updateError); + return NextResponse.json({ error: 'Failed to remove PAT' }, { status: 500 }); + } + + return NextResponse.json({ success: true, message: 'GitHub token removed' }); + } catch (error) { + console.error('Error removing PAT:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/app/api/projects/[projectId]/github/pulls/route.ts b/src/app/api/projects/[projectId]/github/pulls/route.ts new file mode 100644 index 00000000..6678cd94 --- /dev/null +++ b/src/app/api/projects/[projectId]/github/pulls/route.ts @@ -0,0 +1,72 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { isProjectMember } from '@/lib/utils/authorization'; +import { fetchPullRequests, parseGitHubUrl } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + if (!project) { + return NextResponse.json({ error: 'Project not found' }, { status: 404 }); + } + + if (!project.github_pat_encrypted) { + return NextResponse.json({ error: 'GitHub not connected' }, { status: 400 }); + } + + if (!project.githubUrl) { + return NextResponse.json({ error: 'No GitHub URL configured' }, { status: 400 }); + } + + const parsed = parseGitHubUrl(project.githubUrl); + if (!parsed) { + return NextResponse.json({ error: 'Invalid GitHub URL' }, { status: 400 }); + } + + const { owner, repo } = parsed; + + const { searchParams } = new URL(request.url); + const state = (searchParams.get('state') as 'open' | 'closed' | 'all') ?? 'open'; + const perPage = parseInt(searchParams.get('per_page') ?? '30', 10); + + const { data, error } = await fetchPullRequests(owner, repo, project.github_pat_encrypted, { + state, + per_page: Math.min(perPage, 100), + }); + + if (error) { + return NextResponse.json({ error: error.message }, { status: error.status ?? 500 }); + } + + return NextResponse.json({ data }); + } catch (error) { + console.error('Error fetching PRs:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/components/portal/project/MembershipPortalSidebar.tsx b/src/components/portal/project/MembershipPortalSidebar.tsx index 4727f359..112159e7 100644 --- a/src/components/portal/project/MembershipPortalSidebar.tsx +++ b/src/components/portal/project/MembershipPortalSidebar.tsx @@ -10,6 +10,7 @@ import { RxFileText, RxGear, } from "react-icons/rx"; +import { FaGithub } from "react-icons/fa"; export type MembershipPortalSidebarItem = { id: string; @@ -35,6 +36,7 @@ const BASE_ITEMS = [ { id: "overview", label: "Overview", path: "overview", icon: RxHome }, { id: "board", label: "Board", path: "board", icon: RxDashboard }, { id: "list", label: "List", path: "list", icon: RxRows }, + { id: "github", label: "GitHub", path: "github", icon: FaGithub }, { id: "members", label: "Members", path: "members", icon: RxPerson }, { id: "docs", label: "Docs", path: "docs", icon: RxFileText }, { id: "settings", label: "Settings", path: "settings", icon: RxGear }, diff --git a/src/lib/hooks/useGitHubData.ts b/src/lib/hooks/useGitHubData.ts new file mode 100644 index 00000000..280fb141 --- /dev/null +++ b/src/lib/hooks/useGitHubData.ts @@ -0,0 +1,105 @@ +import { useState, useEffect, useCallback } from 'react'; + +interface GitHubPullRequest { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + merged_at: string | null; + user: { login: string; avatar_url: string }; + labels: Array<{ name: string; color: string }>; + draft: boolean; +} + +interface GitHubIssue { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + user: { login: string; avatar_url: string }; + labels: Array<{ name: string; color: string }>; + assignees: Array<{ login: string; avatar_url: string }>; +} + +interface UseGitHubDataReturn { + pullRequests: GitHubPullRequest[]; + issues: GitHubIssue[]; + isLoading: boolean; + error: string | null; + refetch: () => void; +} + +export function useGitHubData( + projectId: string | null, + options?: { state?: 'open' | 'closed' | 'all' } +): UseGitHubDataReturn { + const [pullRequests, setPullRequests] = useState