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";
// Force rebuild - v3
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import {
Card,
CardContent,
@@ -13,8 +13,6 @@ import { Button } from "@/components/ui/button";
import { Plus, Sparkles, Loader2, MoreVertical, Trash2 } from "lucide-react";
import Link from "next/link";
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 {
DropdownMenu,
@@ -42,17 +40,33 @@ interface ProjectWithStats {
productVision?: string;
workspacePath?: string;
status?: string;
createdAt: { toDate?: () => Date } | Date | string | number | null;
updatedAt: { toDate?: () => Date } | Date | string | number | null;
createdAt: string | null;
updatedAt: string | null;
stats: {
sessions: 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() {
const params = useParams();
const workspace = params.workspace as string;
const { data: session, status } = useSession();
const [projects, setProjects] = useState<ProjectWithStats[]>([]);
const [loading, setLoading] = useState(true);
@@ -61,175 +75,90 @@ export default function ProjectsPage() {
const [projectToDelete, setProjectToDelete] = useState<ProjectWithStats | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const fetchProjects = async (user: { uid: string }) => {
const fetchProjects = async () => {
try {
// Fetch projects for this user
const projectsRef = collection(db, 'projects');
const projectsQuery = query(
projectsRef,
where('userId', '==', user.uid),
orderBy('createdAt', 'desc')
);
const projectsSnapshot = await getDocs(projectsQuery);
// 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);
setLoading(true);
const res = await fetch("/api/projects");
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Failed to fetch projects");
}
const data = await res.json();
setProjects(data.projects || []);
setError(null);
} catch (err: unknown) {
console.error('Error fetching projects:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
console.error("Error fetching projects:", err);
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
}
};
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
if (!user) {
setError('Not authenticated');
setLoading(false);
return;
}
fetchProjects(user);
});
return () => unsubscribe();
}, []);
if (status === "authenticated") {
fetchProjects();
} else if (status === "unauthenticated") {
setLoading(false);
}
}, [status]);
const handleDeleteProject = async () => {
if (!projectToDelete) return;
setIsDeleting(true);
try {
const user = auth.currentUser;
if (!user) {
toast.error('You must be signed in');
return;
}
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,
}),
const res = await fetch("/api/projects/delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ projectId: projectToDelete.id }),
});
if (response.ok) {
const data = await response.json();
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));
if (res.ok) {
toast.success("Project deleted");
setProjectToDelete(null);
fetchProjects();
} else {
const error = await response.json();
toast.error(error.error || 'Failed to delete project');
const err = await res.json();
toast.error(err.error || "Failed to delete project");
}
} catch (error) {
console.error('Error deleting project:', error);
toast.error('An error occurred while deleting');
} catch (err) {
console.error("Delete error:", err);
toast.error("An error occurred");
} finally {
setIsDeleting(false);
}
};
const getTimeAgo = (timestamp: { toDate?: () => Date } | Date | string | number | null | undefined) => {
if (!timestamp) return 'Recently';
let date: Date;
if (typeof timestamp === 'object' && timestamp !== null && 'toDate' in timestamp && timestamp.toDate) {
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();
};
if (status === "loading") {
return (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<>
{/* Header */}
<div className="flex h-14 items-center justify-between border-b px-6">
<div>
<h1 className="text-lg font-semibold">Projects</h1>
<p className="text-sm text-muted-foreground">
Manage your product development projects
</p>
<div className="container mx-auto py-8 px-4 max-w-6xl">
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold">Projects</h1>
<p className="text-muted-foreground text-sm mt-1">
{session?.user?.email}
</p>
</div>
<Button onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
New Project
</Button>
</div>
<Button onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
New Project
</Button>
</div>
{/* Content */}
<div className="flex-1 overflow-auto p-6">
<div className="mx-auto max-w-7xl space-y-8">
{/* Loading State */}
<div className="space-y-6">
{loading && (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)}
{/* Error State */}
{error && (
<Card className="border-red-500/50 bg-red-500/5">
<CardContent className="py-6">
@@ -238,91 +167,85 @@ export default function ProjectsPage() {
</Card>
)}
{/* Projects Grid */}
{!loading && !error && projects.length > 0 && (
<section>
<h2 className="text-base font-semibold mb-4">Your Projects</h2>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{projects.map((project) => {
const projectHref = `/${workspace}/project/${project.id}/overview`;
return (
<div key={project.id} className="relative">
<Link href={projectHref}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="text-3xl">📦</div>
<div>
<CardTitle className="text-base">{project.productName}</CardTitle>
<CardDescription className="text-xs mt-0.5">
{getTimeAgo(project.updatedAt)}
</CardDescription>
</div>
</div>
<div className="flex items-center gap-2">
<div
className={`px-2 py-0.5 rounded-full text-xs font-medium ${
project.status === "active"
? "bg-green-500/10 text-green-600"
: "bg-gray-500/10 text-gray-600"
}`}
>
{project.status}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-red-600 focus:text-red-600"
onClick={(e: React.MouseEvent) => {
e.preventDefault();
setProjectToDelete(project);
}}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Project
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4 line-clamp-2">
{project.productVision || 'No description'}
</p>
{project.workspacePath && (
<p className="text-xs text-muted-foreground font-mono mb-4 truncate" title={project.workspacePath}>
📁 {project.workspacePath.split('/').pop()}
</p>
)}
<div className="flex items-center justify-between text-xs">
<div>
<span className="text-muted-foreground">Sessions:</span>{" "}
<span className="font-medium">{project.stats.sessions}</span>
</div>
<div>
<span className="text-muted-foreground">Costs:</span>{" "}
<span className="font-medium">${project.stats.costs.toFixed(2)}</span>
</div>
</div>
</CardContent>
</Card>
</Link>
</div>
);
})}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{projects.map((project) => {
const projectHref = `/${workspace}/project/${project.id}/overview`;
return (
<div key={project.id} className="relative">
<Link href={projectHref}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="text-3xl">📦</div>
<div>
<CardTitle className="text-base">{project.productName}</CardTitle>
<CardDescription className="text-xs mt-0.5">
{getTimeAgo(project.updatedAt)}
</CardDescription>
</div>
</div>
<div className="flex items-center gap-2">
<div
className={`px-2 py-0.5 rounded-full text-xs font-medium ${
project.status === "active"
? "bg-green-500/10 text-green-600"
: "bg-gray-500/10 text-gray-600"
}`}
>
{project.status}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-red-600 focus:text-red-600"
onClick={(e: React.MouseEvent) => {
e.preventDefault();
setProjectToDelete(project);
}}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Project
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4 line-clamp-2">
{project.productVision || "No description"}
</p>
{project.workspacePath && (
<p className="text-xs text-muted-foreground font-mono mb-4 truncate" title={project.workspacePath}>
📁 {project.workspacePath.split("/").pop()}
</p>
)}
<div className="flex items-center justify-between text-xs">
<div>
<span className="text-muted-foreground">Sessions:</span>{" "}
<span className="font-medium">{project.stats.sessions}</span>
</div>
<div>
<span className="text-muted-foreground">Costs:</span>{" "}
<span className="font-medium">${project.stats.costs.toFixed(2)}</span>
</div>
</div>
</CardContent>
</Card>
</Link>
</div>
);
})}
{/* New Project Card */}
<Card
className="hover:border-primary transition-all cursor-pointer border-dashed h-full"
onClick={() => setShowCreationModal(true)}
@@ -341,7 +264,6 @@ export default function ProjectsPage() {
</section>
)}
{/* Empty State (show when no projects) */}
{!loading && !error && projects.length === 0 && (
<Card className="border-dashed">
<CardContent className="flex flex-col items-center justify-center py-16">
@@ -350,8 +272,7 @@ export default function ProjectsPage() {
</div>
<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">
Create your first project to start tracking your AI-powered development
workflow, manage costs, and maintain living documentation.
Create your first project to start tracking your AI-powered development workflow.
</p>
<Button size="lg" onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
@@ -363,39 +284,27 @@ export default function ProjectsPage() {
</div>
</div>
{/* Project Creation Modal */}
<ProjectCreationModal
open={showCreationModal}
onOpenChange={(open) => {
setShowCreationModal(open);
if (!open) {
// Refresh projects list when modal closes
const user = auth.currentUser;
if (user) fetchProjects(user);
}
if (!open) fetchProjects();
}}
workspace={workspace}
/>
{/* Delete Project Confirmation Dialog */}
<AlertDialog open={!!projectToDelete} onOpenChange={(open) => !open && setProjectToDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action will delete the project &quot;{projectToDelete?.productName}&quot;.
All associated sessions and data will be preserved but unlinked from this project.
You can reassign them to another project later.
This will delete &quot;{projectToDelete?.productName}&quot;. Sessions will be preserved but unlinked.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteProject} disabled={isDeleting} className="bg-red-600 hover:bg-red-700">
{isDeleting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Trash2 className="mr-2 h-4 w-4" />
)}
{isDeleting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Trash2 className="mr-2 h-4 w-4" />}
Delete Project
</AlertDialogAction>
</AlertDialogFooter>
@@ -404,4 +313,3 @@ export default function ProjectsPage() {
</>
);
}