feat: handling SSR on home page

This commit is contained in:
Julien Froidefond
2025-08-21 12:54:48 +02:00
parent e32e3b8bc0
commit 69f23db55d
14 changed files with 828 additions and 342 deletions

View File

@@ -5,7 +5,16 @@ import { useRouter } from "next/navigation";
import { ProfileForm } from "@/components/profile-form";
import { AuthService } from "@/lib/auth-utils";
import { UserProfile, Team } from "@/lib/types";
import { Code2 } from "lucide-react";
import { Code2, LogOut, Edit, X, Home } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import Link from "next/link";
interface LoginPageProps {}
@@ -13,17 +22,16 @@ export default function LoginPage({}: LoginPageProps) {
const [teams, setTeams] = useState<Team[]>([]);
const [loading, setLoading] = useState(true);
const [authenticating, setAuthenticating] = useState(false);
const [currentUser, setCurrentUser] = useState<UserProfile | null>(null);
const [isEditing, setIsEditing] = useState(false);
const router = useRouter();
useEffect(() => {
async function initialize() {
try {
// Vérifier si l'utilisateur est déjà connecté
const currentUser = await AuthService.getCurrentUser();
if (currentUser) {
router.push("/");
return;
}
const user = await AuthService.getCurrentUser();
setCurrentUser(user);
// Charger les équipes
const teamsResponse = await fetch("/api/teams");
@@ -39,13 +47,20 @@ export default function LoginPage({}: LoginPageProps) {
}
initialize();
}, [router]);
}, []);
const handleSubmit = async (profile: UserProfile) => {
setAuthenticating(true);
try {
await AuthService.login(profile);
router.push("/");
if (isEditing) {
// Si on modifie le profil existant, mettre à jour l'état
setCurrentUser(profile);
setIsEditing(false);
} else {
// Si c'est un nouveau login, rediriger
router.push("/");
}
} catch (error) {
console.error("Login failed:", error);
// Vous pouvez ajouter une notification d'erreur ici
@@ -54,6 +69,24 @@ export default function LoginPage({}: LoginPageProps) {
}
};
const handleLogout = async () => {
try {
await AuthService.logout();
setCurrentUser(null);
setIsEditing(false);
} catch (error) {
console.error("Logout failed:", error);
}
};
const handleEdit = () => {
setIsEditing(true);
};
const handleCancelEdit = () => {
setIsEditing(false);
};
if (loading) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
@@ -72,6 +105,100 @@ export default function LoginPage({}: LoginPageProps) {
);
}
// Si l'utilisateur est connecté et qu'on ne modifie pas
if (currentUser && !isEditing) {
const currentTeam = teams.find((t) => t.id === currentUser.teamId);
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
<div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
<div className="relative z-10 container mx-auto py-16 px-6">
<div className="text-center mb-12">
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/5 border border-white/10 backdrop-blur-sm mb-6">
<Code2 className="h-4 w-4 text-blue-400" />
<span className="text-sm font-medium text-slate-200">
PeakSkills
</span>
</div>
<h1 className="text-4xl font-bold mb-4 text-white">
Vous êtes connecté
</h1>
<p className="text-lg text-slate-400 mb-8">
Gérez votre profil ou retournez à l'application
</p>
</div>
<div className="max-w-2xl mx-auto space-y-6">
{/* Informations utilisateur */}
<Card className="bg-white/5 border-white/10 backdrop-blur-sm">
<CardHeader>
<CardTitle className="text-white">Vos informations</CardTitle>
<CardDescription className="text-slate-400">
Profil actuellement connecté
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm font-medium text-slate-300">
Prénom
</label>
<p className="text-white">{currentUser.firstName}</p>
</div>
<div>
<label className="text-sm font-medium text-slate-300">
Nom
</label>
<p className="text-white">{currentUser.lastName}</p>
</div>
</div>
<div>
<label className="text-sm font-medium text-slate-300">
Équipe
</label>
<p className="text-white">
{currentTeam?.name || "Équipe non trouvée"}
</p>
</div>
</CardContent>
</Card>
{/* Actions */}
<div className="flex gap-4 justify-center">
<Button
onClick={() => router.push("/")}
className="bg-blue-500 hover:bg-blue-600 text-white"
>
<Home className="w-4 h-4 mr-2" />
Retour à l'accueil
</Button>
<Button
onClick={handleEdit}
variant="outline"
className="border-white/20 text-white hover:bg-white/10"
>
<Edit className="w-4 h-4 mr-2" />
Modifier le profil
</Button>
<Button
onClick={handleLogout}
variant="outline"
className="border-red-500/50 text-red-400 hover:bg-red-500/10"
>
<LogOut className="w-4 h-4 mr-2" />
Se déconnecter
</Button>
</div>
</div>
</div>
</div>
);
}
// Sinon, afficher le formulaire (nouvel utilisateur ou modification)
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
@@ -87,11 +214,26 @@ export default function LoginPage({}: LoginPageProps) {
</div>
<h1 className="text-4xl font-bold mb-4 text-white">
Bienvenue sur PeakSkills
{isEditing
? "Modifier vos informations"
: "Bienvenue sur PeakSkills"}
</h1>
<p className="text-lg text-slate-400 mb-8">
Évaluez vos compétences techniques et suivez votre progression
{isEditing
? "Mettez à jour vos informations personnelles"
: "Évaluez vos compétences techniques et suivez votre progression"}
</p>
{isEditing && (
<Button
onClick={handleCancelEdit}
variant="outline"
className="mb-8 border-white/20 text-white hover:bg-white/10"
>
<X className="w-4 h-4 mr-2" />
Annuler
</Button>
)}
</div>
<div className="max-w-2xl mx-auto">
@@ -100,11 +242,21 @@ export default function LoginPage({}: LoginPageProps) {
<div className="absolute inset-0 bg-black/20 backdrop-blur-sm z-10 flex items-center justify-center rounded-lg">
<div className="text-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-400 mx-auto mb-2"></div>
<p className="text-white text-sm">Connexion en cours...</p>
<p className="text-white text-sm">
{isEditing
? "Mise à jour en cours..."
: "Connexion en cours..."}
</p>
</div>
</div>
)}
<ProfileForm teams={teams} onSubmit={handleSubmit} />
<ProfileForm
teams={teams}
onSubmit={handleSubmit}
initialProfile={
isEditing && currentUser ? currentUser : undefined
}
/>
</div>
</div>
</div>

View File

@@ -1,352 +1,77 @@
"use client";
import { useEffect, useState } from "react";
import { useEvaluation } from "@/hooks/use-evaluation";
import { SkillsRadarChart } from "@/components/radar-chart";
import { redirect } from "next/navigation";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
isUserAuthenticated,
getServerUserEvaluation,
getServerSkillCategories,
getServerTeams,
} from "@/lib/server-auth";
import { generateRadarData } from "@/lib/evaluation-utils";
import { useUser } from "@/hooks/use-user-context";
import { TechIcon } from "@/components/icons/tech-icon";
import Link from "next/link";
import { Code2, ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
import { getCategoryIcon } from "@/lib/category-icons";
import {
WelcomeHeader,
RadarSection,
CategoryBreakdown,
ActionSection,
ClientWrapper,
WelcomeScreen,
} from "@/components/home";
// Fonction pour déterminer la couleur du badge selon le niveau moyen
function getScoreColors(score: number) {
if (score >= 2.5) {
// Expert/Maîtrise (violet)
return {
bg: "bg-violet-500/20",
border: "border-violet-500/30",
text: "text-violet-400",
gradient: "from-violet-500 to-violet-400",
};
} else if (score >= 1.5) {
// Autonome (vert)
return {
bg: "bg-green-500/20",
border: "border-green-500/30",
text: "text-green-400",
gradient: "from-green-500 to-green-400",
};
} else if (score >= 0.5) {
// Non autonome (orange/amber)
return {
bg: "bg-amber-500/20",
border: "border-amber-500/30",
text: "text-amber-400",
gradient: "from-amber-500 to-amber-400",
};
} else {
// Jamais pratiqué (rouge)
return {
bg: "bg-red-500/20",
border: "border-red-500/30",
text: "text-red-400",
gradient: "from-red-500 to-red-400",
};
}
}
export default async function HomePage() {
// Vérifier l'authentification
const isAuthenticated = await isUserAuthenticated();
export default function HomePage() {
const { userEvaluation, skillCategories, teams, loading } = useEvaluation();
const { setUserInfo } = useUser();
const [expandedCategory, setExpandedCategory] = useState<string | null>(null);
// Update user info in navigation when user evaluation is loaded
useEffect(() => {
if (userEvaluation) {
const teamName =
teams.find((t) => t.id === userEvaluation.profile.teamId)?.name || "";
setUserInfo({
firstName: userEvaluation.profile.firstName,
lastName: userEvaluation.profile.lastName,
teamName,
});
} else {
setUserInfo(null);
}
}, [userEvaluation, teams, setUserInfo]);
if (loading) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
<div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
<div className="relative z-10 container mx-auto py-16 px-6">
<div className="flex items-center justify-center min-h-[400px]">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-400 mx-auto mb-4"></div>
<p className="text-white">Chargement...</p>
</div>
</div>
</div>
</div>
);
// Si pas de cookie d'authentification, rediriger vers login
if (!isAuthenticated) {
redirect("/login");
}
// Charger les données côté serveur
const [userEvaluation, skillCategories, teams] = await Promise.all([
getServerUserEvaluation(),
getServerSkillCategories(),
getServerTeams(),
]);
// Si pas d'évaluation, afficher l'écran d'accueil
if (!userEvaluation) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
<div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
<div className="relative z-10 container mx-auto py-16 px-6">
<div className="flex items-center justify-center min-h-[400px]">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-400 mx-auto mb-4"></div>
<p className="text-white">
Redirection vers la page de connexion...
</p>
</div>
</div>
</div>
</div>
);
return <WelcomeScreen />;
}
// Générer les données radar côté serveur
const radarData = generateRadarData(
userEvaluation.evaluations,
skillCategories
);
// Tout en server-side, seul le ClientWrapper gère setUserInfo
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
{/* Background Effects */}
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
<div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
<div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent" />
<ClientWrapper userEvaluation={userEvaluation} teams={teams}>
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 relative overflow-hidden">
{/* Background Effects */}
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-blue-900/20 via-slate-900 to-slate-950" />
<div className="absolute inset-0 bg-grid-white/5 bg-[size:50px_50px]" />
<div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent" />
<div className="relative z-10 container mx-auto px-6 py-8 max-w-7xl space-y-8">
{/* Header */}
<div className="text-center space-y-4 mb-12">
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/5 border border-white/10 backdrop-blur-sm">
<Code2 className="h-4 w-4 text-blue-400" />
<span className="text-sm font-medium text-slate-200">
Tableau de bord
</span>
<div className="relative z-10 container mx-auto px-6 py-8 max-w-7xl space-y-8">
{/* Header */}
<WelcomeHeader firstName={userEvaluation.profile.firstName} />
{/* Main Content Grid */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Radar Chart */}
<RadarSection radarData={radarData} />
{/* Category Breakdown */}
<CategoryBreakdown
radarData={radarData}
userEvaluation={userEvaluation}
skillCategories={skillCategories}
/>
</div>
<h1 className="text-4xl font-bold text-white">
Bonjour {userEvaluation.profile.firstName} !
</h1>
<p className="text-slate-400 max-w-2xl mx-auto leading-relaxed">
Voici un aperçu de vos compétences techniques
</p>
</div>
{/* Main Content Grid */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Radar Chart */}
<div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
<div className="mb-6">
<h3 className="text-xl font-bold text-white mb-2">
Vue d'ensemble de vos compétences
</h3>
<p className="text-slate-400 text-sm">
Radar chart représentant votre niveau par catégorie
</p>
</div>
<div className="h-80">
<SkillsRadarChart data={radarData} />
</div>
</div>
{/* Category Breakdown */}
<div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6">
<div className="mb-6">
<h3 className="text-xl font-bold text-white mb-2">
Détail par catégorie
</h3>
<p className="text-slate-400 text-sm">
Vue détaillée de votre progression dans chaque domaine
</p>
</div>
<div className="space-y-3">
{radarData.map((category) => {
const categoryEval = userEvaluation.evaluations.find(
(e) => e.category === category.category
);
const skillsCount = categoryEval?.selectedSkillIds?.length || 0;
const evaluatedCount =
categoryEval?.skills.filter((s) => s.level !== null).length ||
0;
const isExpanded = expandedCategory === category.category;
const currentSkillCategory = skillCategories.find(
(sc) => sc.category === category.category
);
const CategoryIcon = currentSkillCategory
? getCategoryIcon(currentSkillCategory.icon)
: null;
return (
<div
key={category.category}
className="bg-white/5 border border-white/10 rounded-lg overflow-hidden transition-colors"
>
<div
className="p-3 hover:bg-white/10 transition-colors cursor-pointer"
onClick={() =>
setExpandedCategory(
isExpanded ? null : category.category
)
}
>
<div className="flex justify-between items-center mb-2">
<div className="flex items-center gap-2">
{isExpanded ? (
<ChevronDown className="h-4 w-4 text-slate-400" />
) : (
<ChevronRight className="h-4 w-4 text-slate-400" />
)}
{CategoryIcon && (
<CategoryIcon className="h-4 w-4 text-blue-400" />
)}
<h4 className="font-medium text-white text-sm">
{category.category}
</h4>
</div>
{skillsCount > 0 ? (
(() => {
const colors = getScoreColors(category.score);
return (
<div
className={`px-2 py-0.5 rounded-full ${colors.bg} border ${colors.border}`}
>
<span
className={`text-xs font-medium ${colors.text}`}
>
{Math.round((category.score / 3) * 100)}%
</span>
</div>
);
})()
) : (
<div className="px-2 py-0.5 rounded-full bg-slate-500/20 border border-slate-500/30">
<span className="text-xs font-medium text-slate-400">
Aucune
</span>
</div>
)}
</div>
<div className="text-xs text-slate-400 mb-2">
{skillsCount > 0
? `${evaluatedCount}/${skillsCount} compétences sélectionnées évaluées`
: "Aucune compétence sélectionnée"}
</div>
{skillsCount > 0 ? (
<div className="w-full bg-white/10 rounded-full h-1.5">
{(() => {
const colors = getScoreColors(category.score);
return (
<div
className={`bg-gradient-to-r ${colors.gradient} h-1.5 rounded-full transition-all`}
style={{
width: `${
(category.score / category.maxScore) * 100
}%`,
}}
></div>
);
})()}
</div>
) : (
<div className="w-full bg-slate-500/10 rounded-full h-1.5"></div>
)}
</div>
{/* Expanded Skills */}
{isExpanded && categoryEval && currentSkillCategory && (
<div className="px-3 pb-3 border-t border-white/10 bg-white/5">
<div className="pt-3 space-y-2 max-h-60 overflow-y-auto">
{categoryEval.selectedSkillIds.map((skillId) => {
const skill = currentSkillCategory.skills.find(
(s) => s.id === skillId
);
if (!skill) return null;
const skillEval = categoryEval.skills.find(
(s) => s.skillId === skillId
);
return (
<div
key={skillId}
className="flex items-center justify-between p-2 bg-white/5 border border-white/10 rounded-lg"
>
<div className="flex items-center gap-2">
<TechIcon
iconName={skill.icon}
className="w-4 h-4 text-blue-400"
fallbackText={skill.name}
/>
<span className="text-sm text-white">
{skill.name}
</span>
</div>
<div className="flex items-center gap-2">
{skillEval?.level && (
<span className="text-xs text-slate-400">
{skillEval.level === "never" &&
"Jamais utilisé"}
{skillEval.level === "not-autonomous" &&
"Non autonome"}
{skillEval.level === "autonomous" &&
"Autonome"}
{skillEval.level === "expert" && "Expert"}
</span>
)}
</div>
</div>
);
})}
</div>
<div className="mt-3 pt-3 border-t border-white/10">
<Button
asChild
className="w-full bg-blue-500 hover:bg-blue-600 text-white"
>
<Link
href={`/evaluation?category=${encodeURIComponent(
category.category
)}`}
>
<ExternalLink className="w-4 h-4 mr-2" />
Évaluer {category.category}
</Link>
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
</div>
</div>
{/* Action Button */}
<div className="flex justify-center mt-12">
<Button
asChild
size="lg"
className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-xl"
>
<Link href="/evaluation">Continuer l'évaluation</Link>
</Button>
{/* Action Button */}
<ActionSection />
</div>
</div>
</div>
</ClientWrapper>
);
}