Absolutely! Below are the updated and improved versions for those files, following best practices, flow correctness, async handling, and typing.
6. src/components/onboarding/founder/FounderProfileForm.tsx
import React, { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { getUserProfile, updateUserProfile } from "@/utils/profile/profileUtils";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
interface FounderProfileFormProps {
onClose?: () => void;
onBack?: () => void;
}
const PREFERRED_ROLES = ["founder", "cto", "ceo", "product"];
const FounderProfileForm: React.FC<FounderProfileFormProps> = ({ onClose, onBack }) => {
const { user } = useAuth();
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
fullName: "",
headline: "",
skills: [] as string[],
preferredRole: "",
githubUsername: "",
portfolioUrl: "",
weeklyAvailability: "",
remoteOnly: true,
newSkill: ""
});
useEffect(() => {
if (!user?.id) return;
(async () => {
try {
const profile = await getUserProfile(user.id);
if (profile) {
setFormData((prev) => ({
...prev,
fullName: profile.full_name || user.user_metadata?.full_name || "",
headline: profile.headline || "",
skills: profile.founderInfo?.skills || [],
preferredRole: profile.founderInfo?.preferredRole || "",
githubUsername: profile.founderInfo?.githubUsername || "",
portfolioUrl: profile.founderInfo?.portfolioUrl || profile.website || "",
weeklyAvailability: profile.founderInfo?.weeklyAvailability || "",
remoteOnly: profile.founderInfo?.remoteOnly !== false
}));
}
} catch (error) {
console.error("Error loading profile:", error);
toast.error("Failed to load profile data.");
}
})();
}, [user]);
const handleChange = (field: keyof typeof formData, value: any) => {
setFormData((prev) => ({
...prev,
[field]: value
}));
};
const handleAddSkill = () => {
const trimmed = formData.newSkill.trim();
if (trimmed && !formData.skills.includes(trimmed)) {
const newSkills = [...formData.skills, trimmed];
setFormData((prev) => ({ ...prev, skills: newSkills, newSkill: "" }));
}
};
const handleRemoveSkill = (skill: string) => {
const newSkills = formData.skills.filter((s) => s !== skill);
setFormData((prev) => ({ ...prev, skills: newSkills }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!user?.id) return;
if (!formData.fullName.trim()) {
toast.error("Full name is required");
return;
}
setLoading(true);
try {
await updateUserProfile({
id: user.id,
full_name: formData.fullName,
headline: formData.headline,
founderInfo: {
skills: formData.skills,
preferredRole: formData.preferredRole,
githubUsername: formData.githubUsername,
portfolioUrl: formData.portfolioUrl,
weeklyAvailability: formData.weeklyAvailability,
remoteOnly: formData.remoteOnly
},
user_roles: ['founder'],
founder_profile_complete: true,
onboarding_completed: true
});
toast.success("Profile saved successfully");
onClose?.();
} catch (error) {
console.error("Error saving profile:", error);
toast.error("Failed to save profile");
} finally {
setLoading(false);
}
};
if (!user) return null;
return (
<div className="max-w-2xl mx-auto">
<Card>
<CardHeader className="text-center pb-8">
<div className="flex justify-center mb-6">
<Avatar className="w-24 h-24">
<AvatarImage src={user.user_metadata?.avatar_url} />
<AvatarFallback className="text-2xl bg-primary/10 text-primary">
{formData.fullName.split(" ").map(n => n[0]).join("").toUpperCase() || "U"}
</AvatarFallback>
</Avatar>
</div>
<CardTitle className="text-2xl">Edit Profile</CardTitle>
</CardHeader>
<form className="space-y-6" onSubmit={handleSubmit}>
<CardContent className="space-y-4 pt-6">
<div>
<Label htmlFor="fullName">Full Name *</Label>
<Input
id="fullName"
minLength={2}
value={formData.fullName}
onChange={(e) => handleChange("fullName", e.target.value)}
required
placeholder="John Doe"
/>
</div>
<div>
<Label htmlFor="headline">Professional Headline</Label>
<Input
id="headline"
value={formData.headline}
onChange={(e) => handleChange("headline", e.target.value)}
placeholder="Full Stack Developer"
/>
</div>
<div>
<Label>Skills</Label>
<div className="flex flex-wrap gap-2 mb-2">
{formData.skills.map((skill) => (
<Badge key={skill} variant="secondary" className="px-3 py-1 cursor-pointer" onClick={() => handleRemoveSkill(skill)}>
{skill} ×
</Badge>
))}
</div>
<div className="flex gap-2">
<Input
placeholder="Add a skill..."
value={formData.newSkill}
onChange={(e) => handleChange("newSkill", e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleAddSkill();
}
}}
/>
<Button type="button" onClick={handleAddSkill} disabled={!formData.newSkill.trim()}>
Add
</Button>
</div>
</div>
<div>
<Label htmlFor="preferredRole">Preferred Role</Label>
<Select value={formData.preferredRole} onValueChange={(val) => handleChange("preferredRole", val)} >
<SelectTrigger aria-label="Preferred role">
<SelectValue placeholder="Select your primary role" />
</SelectTrigger>
<SelectContent>
{PREFERRED_ROLES.map((role) => (
<SelectItem key={role} value={role}>{role.toUpperCase()}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="githubUsername">GitHub Username</Label>
<Input
id="githubUsername"
value={formData.githubUsername}
onChange={(e) => handleChange("githubUsername", e.target.value)}
placeholder="johndoe"
/>
</div>
<div>
<Label htmlFor="portfolioUrl">Portfolio URL</Label>
<Input
id="portfolioUrl"
type="url"
value={formData.portfolioUrl}
onChange={(e) => handleChange("portfolioUrl", e.target.value)}
placeholder="https://portfolio.example.com"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<Label htmlFor="weeklyAvailability">Weekly Availability (hours)</Label>
<Input
id="weeklyAvailability"
type="number"
min={0}
max={80}
value={formData.weeklyAvailability}
onChange={(e) => handleChange("weeklyAvailability", e.target.value)}
placeholder="20"
/>
</div>
<div>
<Label htmlFor="remoteOnly" className="mb-1">Remote Work Only</Label>
<Switch
id="remoteOnly"
checked={formData.remoteOnly}
onCheckedChange={(val) => handleChange("remoteOnly", val)}
/>
</div>
</div>
</CardContent>
<CardFooter className="flex justify-between pt-6">
<Button type="button" variant="outline" onClick={onBack}>Back</Button>
<Button type="submit" disabled={loading}>
{loading ? 'Saving...' : 'Complete'}
</Button>
</CardFooter>
</form>
</Card>
</div>
);
};
export default FounderProfileForm;
7. src/hooks/founder/useFounderDashboardData.ts
import { useState, useEffect } from "react";
import { useAuth } from "@/context/AuthContext";
import { supabase } from "@/integrations/supabase/client";
export interface DashboardStats {
activeProjects: number;
teamMembers: number;
investorInterests: number;
fundingGoal: number;
fundingProgress: number;
}
export const useFounderDashboardData = () => {
const { user } = useAuth();
const userId = user?.id ?? null;
const [stats, setStats] = useState<DashboardStats>({
activeProjects: 0,
teamMembers: 0,
investorInterests: 0,
fundingGoal: 250000, // keep initial/fallback values reasonable
fundingProgress: 35,
});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (!userId) {
setLoading(false);
return;
}
const fetchStats = async () => {
setLoading(true);
try {
const { data: projectsData, error: projectsError } = await supabase
.from("projects")
.select("id, is_active")
.eq("user_id", userId);
if (projectsError) throw projectsError;
const projectIds = projectsData?.map((p) => p.id) || [];
const activeProjects = projectsData?.filter((p) => p.is_active).length || 0;
if (projectIds.length === 0) {
setStats((prev) => ({
...prev,
activeProjects: 0,
teamMembers: 0,
investorInterests: 0,
}));
return;
}
const [teamRes, investorRes] = await Promise.all([
supabase
.from("project_members")
.select("*", { count: "exact", head: true })
.eq("status", "approved")
.in("project_id", projectIds),
supabase
.from("project_interests")
.select("*", { count: "exact", head: true })
.eq("type", "investor")
.in("project_id", projectIds),
]);
if (teamRes.error) throw teamRes.error;
if (investorRes.error) throw investorRes.error;
setStats({
activeProjects,
teamMembers: teamRes.count || 0,
investorInterests: investorRes.count || 0,
fundingGoal: stats.fundingGoal,
fundingProgress: stats.fundingProgress,
});
} catch (error) {
setError(error instanceof Error ? error : new Error("Unknown error"));
} finally {
setLoading(false);
}
};
fetchStats();
}, [userId]);
return { stats, loading, error };
};
8. src/pages/founder/FounderTasks.tsx
import React, { useEffect } from "react";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import FounderTasksWidget from "@/components/features/founder/tasks/FounderTasksWidget";
import { useAuth } from "@/context/AuthContext";
import { useRoleDetection } from "@/hooks/useRoleDetection";
const FounderTasks = () => {
const { user } = useAuth();
const navigate = useNavigate();
const { isFounder } = useRoleDetection();
useEffect(() => {
if (!user) {
toast.error("Please log in to access founder tasks");
navigate("/login");
return;
}
if (!isFounder) {
toast.error("Access denied. Founders only.");
navigate('/dashboard');
return;
}
}, [user, isFounder, navigate]);
if (!user) return null;
return (
<div className="min-h-screen flex flex-col bg-white">
<Navbar />
<main className="flex-grow container mx-auto px-4 py-8">
<Card>
<CardHeader>
<CardTitle>Founder Tasks</CardTitle>
</CardHeader>
<CardContent>
<Tabs defaultValue="all">
<TabsList className="grid grid-cols-4">
<TabsTrigger value="all">All Tasks</TabsTrigger>
<TabsTrigger value="active">Active</TabsTrigger>
<TabsTrigger value="pending">Pending</TabsTrigger>
<TabsTrigger value="completed">Completed</TabsTrigger>
</TabsList>
<TabsContent value="all">
<FounderTasksWidget />
</TabsContent>
<TabsContent value="active">
<FounderTasksWidget filter="active" />
</TabsContent>
<TabsContent value="pending">
<FounderTasksWidget filter="pending" />
</TabsContent>
<TabsContent value="completed">
<FounderTasksWidget filter="completed" />
</TabsContent>
</Tabs>
</CardContent>
</Card>
</main>
<Footer />
</div>
);
};
export default FounderTasks;
9. src/components/features/founder/tasks/FounderTasksWidget.tsx
import React, { useEffect, useState, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Calendar, Users, MessageCircle, CheckCircle2, Clock } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { toast } from 'sonner';
import { Task } from '@/types/task';
interface FounderTasksWidgetProps {
filter?: 'all' | 'active' | 'pending' | 'completed';
onTaskAction?: (action: string, taskId?: string) => void;
}
const TASK_STATUS_COLORS: Record<string, string> = {
completed: 'bg-green-100 text-green-700',
active: 'bg-blue-100 text-blue-700',
pending: 'bg-amber-100 text-amber-700',
'in-review': 'bg-purple-100 text-purple-700',
};
const taskTypeIcon = (type?: string) => {
switch (type) {
case 'team': return <Users className="h-4 w-4 text-purple-600" />;
case 'planning': return <Clock className="h-4 w-4 text-blue-600" />;
case 'investor': return <MessageCircle className="h-4 w-4 text-green-600" />;
case 'review': return <CheckCircle2 className="h-4 w-4 text-amber-600" />;
default: return <Clock className="h-4 w-4" />;
}
}
const FounderTasksWidget: React.FC<FounderTasksWidgetProps> = ({ filter = 'all', onTaskAction }) => {
const { user } = useAuth();
const navigate = useNavigate();
const [tasks, setTasks] = useState<Task[]>([]);
const [loading, setLoading] = useState(true);
// For demo - replace with backend fetching
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Replace with API fetching logic here
(async () => {
setLoading(true);
try {
// supabase fetch here
// Simulating fetch delay
await new Promise(res => setTimeout(res, 1000));
setTasks([]); // set fetched tasks
setError(null);
} catch (e) {
setError("Failed to fetch tasks");
} finally {
setLoading(false);
}
})();
}, []);
// Filter tasks per prop
const filteredTasks = useMemo(() => {
if (filter === 'all') return tasks;
return tasks.filter((t) => t.status === filter);
}, [tasks, filter]);
const handleViewProject = (projectId: string) => {
navigate(`/projects/${projectId}`);
};
if (loading) {
return (
<Card>
<CardHeader>
<CardTitle>Loading...</CardTitle>
</CardHeader>
<CardContent>
{/* Skeleton loaders or spinner here */}
<p>Loading tasks...</p>
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardHeader>
<CardTitle>Error</CardTitle>
</CardHeader>
<CardContent>
<p className="text-red-600">{error}</p>
</CardContent>
</Card>
);
}
if (filteredTasks.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle>No tasks</CardTitle>
</CardHeader>
<CardContent>
<p>No {filter !== 'all' ? filter : ''} tasks found.</p>
</CardContent>
</Card>
);
}
return (
<div className="space-y-4">
{filteredTasks.map((task) => (
<Card key={task.id} className="hover:shadow-md">
<CardContent className="pt-6">
<div className="flex justify-between items-start">
<div className="flex items-start gap-3">
{taskTypeIcon(task.type)}
<div>
<h3 className="font-medium">{task.title}</h3>
<p className="text-sm text-muted-foreground mt-1">{task.description}</p>
<div className="text-xs mt-2 text-muted-foreground">Project: {task.project_title || "Untitled Project"}</div>
</div>
</div>
<Badge className={TASK_STATUS_COLORS[task.status]}>{task.status.charAt(0).toUpperCase() + task.status.slice(1)}</Badge>
</div>
<div className="flex justify-between mt-4 items-center text-sm text-muted-foreground">
<div className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
<span>{task.due_date ? new Date(task.due_date).toLocaleDateString() : 'No deadline'}</span>
</div>
<Button variant="ghost" size="sm" onClick={() => handleViewProject(task.project_id)}>
View Project
</Button>
</div>
</CardContent>
</Card>
))}
</div>
);
};
export default FounderTasksWidget;
10. Role Managers & Utils (Async pattern)
Put in src/utils/roles/roleManager.ts
import { getUserProfile } from '@/utils/profile/profileUtils';
import { ProfileData } from '@/utils/profile/profileUtils';
export interface RolePermissions {
canCreateProject: boolean;
canViewProjects: boolean;
canEditProjects: boolean;
canInviteUsers: boolean;
canManageSettings: boolean;
}
export abstract class BaseRoleManager {
protected userId: string;
protected profileData?: ProfileData;
protected permissions: RolePermissions;
constructor(userId: string, permissions: RolePermissions) {
this.userId = userId;
this.permissions = permissions;
}
async init(): Promise<void> {
this.profileData = await getUserProfile(this.userId);
}
async hasRole(role: string): Promise<boolean> {
return this.profileData?.user_roles?.includes(role) ?? false;
}
async isProfileComplete(): Promise<boolean> {
// Override in subclass
return false;
}
async canCreateProject(): Promise<boolean> {
return this.permissions.canCreateProject;
}
}
// Example FounderManager
export class FounderManager extends BaseRoleManager {
constructor(userId: string) {
super(userId, {
canCreateProject: true,
canViewProjects: true,
canEditProjects: true,
canInviteUsers: true,
canManageSettings: true,
});
}
async hasRole(): Promise<boolean> {
return this.profileData?.user_roles?.includes('founder') || this.profileData?.user_roles?.includes('entrepreneur') || false;
}
async isProfileComplete(): Promise<boolean> {
if (!this.profileData) return false;
const finfo = this.profileData.founderInfo || {};
return !!(finfo.companyName && finfo.industry);
}
// Other founder-specific methods...
}
// Similar for ContributorManager, InvestorManager
export async function getRoleManager(userId: string) {
const profile = await getUserProfile(userId);
if (!profile) throw new Error("User profile not found");
const roles = profile.user_roles || [];
if (roles.includes("founder") || roles.includes("entrepreneur")) {
const manager = new FounderManager(userId);
await manager.init();
return manager;
} else if (roles.includes("investor")) {
// ...
// return InvestorManager instance ...
} else {
// ContributorManager...
}
}
Summary of Next Steps
- Remember to handle loading/login state in pages before rendering.
- Inject role managers with
await getRoleManager(user.id) pattern.
- Use responsive components & error boundaries.
- Add tests for role permissions & profile completions.
If you want me to help write tests, or components for team management or analytics next, just ask!