feat: rewrite projects page to use NextAuth session + Postgres API (remove Firebase)

This commit is contained in:
2026-02-18 01:26:25 +00:00
parent 065f0f6b33
commit 5831d19207

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
// Force rebuild - v3
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { import {
Card, Card,
CardContent, CardContent,
@@ -13,8 +13,6 @@ import { Button } from "@/components/ui/button";
import { Plus, Sparkles, Loader2, MoreVertical, Trash2 } from "lucide-react"; import { Plus, Sparkles, Loader2, MoreVertical, Trash2 } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { db, auth } from "@/lib/firebase/config";
import { collection, query, where, orderBy, getDocs } from "firebase/firestore";
import { ProjectCreationModal } from "@/components/project-creation-modal"; import { ProjectCreationModal } from "@/components/project-creation-modal";
import { import {
DropdownMenu, DropdownMenu,
@@ -42,17 +40,33 @@ interface ProjectWithStats {
productVision?: string; productVision?: string;
workspacePath?: string; workspacePath?: string;
status?: string; status?: string;
createdAt: { toDate?: () => Date } | Date | string | number | null; createdAt: string | null;
updatedAt: { toDate?: () => Date } | Date | string | number | null; updatedAt: string | null;
stats: { stats: {
sessions: number; sessions: number;
costs: number; costs: number;
}; };
} }
function getTimeAgo(dateStr: string | null | undefined): string {
if (!dateStr) return "Unknown";
const date = new Date(dateStr);
if (isNaN(date.getTime())) return "Unknown";
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return "Today";
if (days === 1) return "Yesterday";
if (days < 7) return `${days} days ago`;
if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
if (days < 365) return `${Math.floor(days / 30)} months ago`;
return `${Math.floor(days / 365)} years ago`;
}
export default function ProjectsPage() { export default function ProjectsPage() {
const params = useParams(); const params = useParams();
const workspace = params.workspace as string; const workspace = params.workspace as string;
const { data: session, status } = useSession();
const [projects, setProjects] = useState<ProjectWithStats[]>([]); const [projects, setProjects] = useState<ProjectWithStats[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -61,156 +75,75 @@ export default function ProjectsPage() {
const [projectToDelete, setProjectToDelete] = useState<ProjectWithStats | null>(null); const [projectToDelete, setProjectToDelete] = useState<ProjectWithStats | null>(null);
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
const fetchProjects = async (user: { uid: string }) => { const fetchProjects = async () => {
try { try {
// Fetch projects for this user setLoading(true);
const projectsRef = collection(db, 'projects'); const res = await fetch("/api/projects");
const projectsQuery = query( if (!res.ok) {
projectsRef, const err = await res.json();
where('userId', '==', user.uid), throw new Error(err.error || "Failed to fetch projects");
orderBy('createdAt', 'desc') }
); const data = await res.json();
const projectsSnapshot = await getDocs(projectsQuery); setProjects(data.projects || []);
setError(null);
// Fetch sessions to calculate stats
const sessionsRef = collection(db, 'sessions');
const sessionsQuery = query(
sessionsRef,
where('userId', '==', user.uid)
);
const sessionsSnapshot = await getDocs(sessionsQuery);
// Group sessions by project
const sessionsByProject = new Map<string, { count: number; totalCost: number }>();
sessionsSnapshot.docs.forEach(doc => {
const session = doc.data();
const projectId = session.projectId || 'unassigned';
const existing = sessionsByProject.get(projectId) || { count: 0, totalCost: 0 };
sessionsByProject.set(projectId, {
count: existing.count + 1,
totalCost: existing.totalCost + (session.cost || 0),
});
});
// Map projects with stats
const projectsWithStats: ProjectWithStats[] = projectsSnapshot.docs.map(doc => {
const project = doc.data();
const stats = sessionsByProject.get(doc.id) || { count: 0, totalCost: 0 };
return {
id: doc.id,
name: project.name,
slug: project.slug,
productName: project.productName,
productVision: project.productVision,
workspacePath: project.workspacePath,
status: project.status || 'active',
createdAt: project.createdAt,
updatedAt: project.updatedAt,
stats: {
sessions: stats.count,
costs: stats.totalCost,
},
};
});
setProjects(projectsWithStats);
} catch (err: unknown) { } catch (err: unknown) {
console.error('Error fetching projects:', err); console.error("Error fetching projects:", err);
setError(err instanceof Error ? err.message : 'Unknown error'); setError(err instanceof Error ? err.message : "Unknown error");
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
useEffect(() => { useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => { if (status === "authenticated") {
if (!user) { fetchProjects();
setError('Not authenticated'); } else if (status === "unauthenticated") {
setLoading(false); setLoading(false);
return;
} }
}, [status]);
fetchProjects(user);
});
return () => unsubscribe();
}, []);
const handleDeleteProject = async () => { const handleDeleteProject = async () => {
if (!projectToDelete) return; if (!projectToDelete) return;
setIsDeleting(true); setIsDeleting(true);
try { try {
const user = auth.currentUser; const res = await fetch("/api/projects/delete", {
if (!user) { method: "POST",
toast.error('You must be signed in'); headers: { "Content-Type": "application/json" },
return; body: JSON.stringify({ projectId: projectToDelete.id }),
}
const token = await user.getIdToken();
const response = await fetch('/api/projects/delete', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
projectId: projectToDelete.id,
}),
}); });
if (response.ok) { if (res.ok) {
const data = await response.json(); toast.success("Project deleted");
toast.success('Project deleted successfully', {
description: data.sessionsPreserved > 0
? `${data.sessionsPreserved} sessions preserved and can be reassigned`
: undefined
});
// Remove from local state
setProjects(projects.filter(p => p.id !== projectToDelete.id));
setProjectToDelete(null); setProjectToDelete(null);
fetchProjects();
} else { } else {
const error = await response.json(); const err = await res.json();
toast.error(error.error || 'Failed to delete project'); toast.error(err.error || "Failed to delete project");
} }
} catch (error) { } catch (err) {
console.error('Error deleting project:', error); console.error("Delete error:", err);
toast.error('An error occurred while deleting'); toast.error("An error occurred");
} finally { } finally {
setIsDeleting(false); setIsDeleting(false);
} }
}; };
const getTimeAgo = (timestamp: { toDate?: () => Date } | Date | string | number | null | undefined) => { if (status === "loading") {
if (!timestamp) return 'Recently'; return (
<div className="flex items-center justify-center py-16">
let date: Date; <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
if (typeof timestamp === 'object' && timestamp !== null && 'toDate' in timestamp && timestamp.toDate) { </div>
date = timestamp.toDate(); );
} else {
date = new Date(timestamp as string | number | Date);
} }
const seconds = Math.floor((new Date().getTime() - date.getTime()) / 1000);
if (seconds < 60) return 'Just now';
if (seconds < 3600) return `${Math.floor(seconds / 60)} minutes ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)} hours ago`;
if (seconds < 2592000) return `${Math.floor(seconds / 86400)} days ago`;
return date.toLocaleDateString();
};
return ( return (
<> <>
{/* Header */} <div className="container mx-auto py-8 px-4 max-w-6xl">
<div className="flex h-14 items-center justify-between border-b px-6"> <div className="flex items-center justify-between mb-8">
<div> <div>
<h1 className="text-lg font-semibold">Projects</h1> <h1 className="text-2xl font-bold">Projects</h1>
<p className="text-sm text-muted-foreground"> <p className="text-muted-foreground text-sm mt-1">
Manage your product development projects {session?.user?.email}
</p> </p>
</div> </div>
<Button onClick={() => setShowCreationModal(true)}> <Button onClick={() => setShowCreationModal(true)}>
@@ -219,17 +152,13 @@ export default function ProjectsPage() {
</Button> </Button>
</div> </div>
{/* Content */} <div className="space-y-6">
<div className="flex-1 overflow-auto p-6">
<div className="mx-auto max-w-7xl space-y-8">
{/* Loading State */}
{loading && ( {loading && (
<div className="flex items-center justify-center py-16"> <div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div> </div>
)} )}
{/* Error State */}
{error && ( {error && (
<Card className="border-red-500/50 bg-red-500/5"> <Card className="border-red-500/50 bg-red-500/5">
<CardContent className="py-6"> <CardContent className="py-6">
@@ -238,7 +167,6 @@ export default function ProjectsPage() {
</Card> </Card>
)} )}
{/* Projects Grid */}
{!loading && !error && projects.length > 0 && ( {!loading && !error && projects.length > 0 && (
<section> <section>
<h2 className="text-base font-semibold mb-4">Your Projects</h2> <h2 className="text-base font-semibold mb-4">Your Projects</h2>
@@ -272,11 +200,7 @@ export default function ProjectsPage() {
</div> </div>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}> <DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}>
<Button <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<MoreVertical className="h-4 w-4" /> <MoreVertical className="h-4 w-4" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
@@ -298,11 +222,11 @@ export default function ProjectsPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<p className="text-sm text-muted-foreground mb-4 line-clamp-2"> <p className="text-sm text-muted-foreground mb-4 line-clamp-2">
{project.productVision || 'No description'} {project.productVision || "No description"}
</p> </p>
{project.workspacePath && ( {project.workspacePath && (
<p className="text-xs text-muted-foreground font-mono mb-4 truncate" title={project.workspacePath}> <p className="text-xs text-muted-foreground font-mono mb-4 truncate" title={project.workspacePath}>
📁 {project.workspacePath.split('/').pop()} 📁 {project.workspacePath.split("/").pop()}
</p> </p>
)} )}
<div className="flex items-center justify-between text-xs"> <div className="flex items-center justify-between text-xs">
@@ -322,7 +246,6 @@ export default function ProjectsPage() {
); );
})} })}
{/* New Project Card */}
<Card <Card
className="hover:border-primary transition-all cursor-pointer border-dashed h-full" className="hover:border-primary transition-all cursor-pointer border-dashed h-full"
onClick={() => setShowCreationModal(true)} onClick={() => setShowCreationModal(true)}
@@ -341,7 +264,6 @@ export default function ProjectsPage() {
</section> </section>
)} )}
{/* Empty State (show when no projects) */}
{!loading && !error && projects.length === 0 && ( {!loading && !error && projects.length === 0 && (
<Card className="border-dashed"> <Card className="border-dashed">
<CardContent className="flex flex-col items-center justify-center py-16"> <CardContent className="flex flex-col items-center justify-center py-16">
@@ -350,8 +272,7 @@ export default function ProjectsPage() {
</div> </div>
<h3 className="text-lg font-semibold mb-2">No projects yet</h3> <h3 className="text-lg font-semibold mb-2">No projects yet</h3>
<p className="text-sm text-muted-foreground text-center max-w-md mb-6"> <p className="text-sm text-muted-foreground text-center max-w-md mb-6">
Create your first project to start tracking your AI-powered development Create your first project to start tracking your AI-powered development workflow.
workflow, manage costs, and maintain living documentation.
</p> </p>
<Button size="lg" onClick={() => setShowCreationModal(true)}> <Button size="lg" onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" /> <Plus className="mr-2 h-4 w-4" />
@@ -363,39 +284,27 @@ export default function ProjectsPage() {
</div> </div>
</div> </div>
{/* Project Creation Modal */}
<ProjectCreationModal <ProjectCreationModal
open={showCreationModal} open={showCreationModal}
onOpenChange={(open) => { onOpenChange={(open) => {
setShowCreationModal(open); setShowCreationModal(open);
if (!open) { if (!open) fetchProjects();
// Refresh projects list when modal closes
const user = auth.currentUser;
if (user) fetchProjects(user);
}
}} }}
workspace={workspace} workspace={workspace}
/> />
{/* Delete Project Confirmation Dialog */}
<AlertDialog open={!!projectToDelete} onOpenChange={(open) => !open && setProjectToDelete(null)}> <AlertDialog open={!!projectToDelete} onOpenChange={(open) => !open && setProjectToDelete(null)}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle> <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
This action will delete the project &quot;{projectToDelete?.productName}&quot;. This will delete &quot;{projectToDelete?.productName}&quot;. Sessions will be preserved but unlinked.
All associated sessions and data will be preserved but unlinked from this project.
You can reassign them to another project later.
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel> <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteProject} disabled={isDeleting} className="bg-red-600 hover:bg-red-700"> <AlertDialogAction onClick={handleDeleteProject} disabled={isDeleting} className="bg-red-600 hover:bg-red-700">
{isDeleting ? ( {isDeleting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Trash2 className="mr-2 h-4 w-4" />}
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Trash2 className="mr-2 h-4 w-4" />
)}
Delete Project Delete Project
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
@@ -404,4 +313,3 @@ export default function ProjectsPage() {
</> </>
); );
} }