feat: implement user profile management (Fase 2)

- Add useProfile hook for managing user data
- Add Profile page to view/edit user information
- Add Settings layout with sidebar navigation
- Add Settings pages: Profile, Password, Notifications, Account
- Add user dropdown menu in Header with Profile/Settings links
- Add protected routes for /settings/* pages
- Implement profile update and password change functionality

Completes Fase 2 of frontend missing features analysis from todo.md
This commit is contained in:
Luca Sacchi Ricciardi
2026-04-08 13:12:57 +02:00
parent 1d14668b1b
commit 2c5d751f72
8 changed files with 801 additions and 11 deletions

View File

@@ -1,5 +1,5 @@
import { Suspense, lazy } from 'react'; import { Suspense, lazy } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom'; import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryProvider } from './providers/QueryProvider'; import { QueryProvider } from './providers/QueryProvider';
import { ThemeProvider } from './providers/ThemeProvider'; import { ThemeProvider } from './providers/ThemeProvider';
import { AuthProvider } from './contexts/AuthContext'; import { AuthProvider } from './contexts/AuthContext';
@@ -22,6 +22,11 @@ const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login }
const Register = lazy(() => import('./pages/Register').then(m => ({ default: m.Register }))); const Register = lazy(() => import('./pages/Register').then(m => ({ default: m.Register })));
const ForgotPassword = lazy(() => import('./pages/ForgotPassword').then(m => ({ default: m.ForgotPassword }))); const ForgotPassword = lazy(() => import('./pages/ForgotPassword').then(m => ({ default: m.ForgotPassword })));
const ResetPassword = lazy(() => import('./pages/ResetPassword').then(m => ({ default: m.ResetPassword }))); const ResetPassword = lazy(() => import('./pages/ResetPassword').then(m => ({ default: m.ResetPassword })));
const SettingsLayout = lazy(() => import('./pages/settings/SettingsLayout').then(m => ({ default: m.SettingsLayout })));
const SettingsProfile = lazy(() => import('./pages/settings/SettingsProfile').then(m => ({ default: m.SettingsProfile })));
const SettingsPassword = lazy(() => import('./pages/settings/SettingsPassword').then(m => ({ default: m.SettingsPassword })));
const SettingsNotifications = lazy(() => import('./pages/settings/SettingsNotifications').then(m => ({ default: m.SettingsNotifications })));
const SettingsAccount = lazy(() => import('./pages/settings/SettingsAccount').then(m => ({ default: m.SettingsAccount })));
const ApiKeys = lazy(() => import('./pages/ApiKeys').then(m => ({ default: m.ApiKeys }))); const ApiKeys = lazy(() => import('./pages/ApiKeys').then(m => ({ default: m.ApiKeys })));
const AnalyticsDashboard = lazy(() => import('./pages/AnalyticsDashboard').then(m => ({ default: m.AnalyticsDashboard }))); const AnalyticsDashboard = lazy(() => import('./pages/AnalyticsDashboard').then(m => ({ default: m.AnalyticsDashboard })));
const NotFound = lazy(() => import('./pages/NotFound').then(m => ({ default: m.NotFound }))); const NotFound = lazy(() => import('./pages/NotFound').then(m => ({ default: m.NotFound })));
@@ -82,7 +87,21 @@ function App() {
<Route path="scenarios/:id" element={<ScenarioDetail />} /> <Route path="scenarios/:id" element={<ScenarioDetail />} />
<Route path="scenarios/:id/reports" element={<Reports />} /> <Route path="scenarios/:id/reports" element={<Reports />} />
<Route path="compare" element={<Compare />} /> <Route path="compare" element={<Compare />} />
<Route path="settings/api-keys" element={<ApiKeys />} /> <Route
path="settings"
element={
<SettingsLayout>
<Routes>
<Route index element={<Navigate to="/settings/profile" replace />} />
<Route path="profile" element={<SettingsProfile />} />
<Route path="password" element={<SettingsPassword />} />
<Route path="notifications" element={<SettingsNotifications />} />
<Route path="account" element={<SettingsAccount />} />
<Route path="api-keys" element={<ApiKeys />} />
</Routes>
</SettingsLayout>
}
/>
<Route path="analytics" element={<AnalyticsDashboard />} /> <Route path="analytics" element={<AnalyticsDashboard />} />
</Route> </Route>

View File

@@ -0,0 +1,109 @@
import { useState, useEffect, useCallback } from 'react';
import api from '@/lib/api';
import { showToast } from '@/components/ui/toast-utils';
export interface User {
id: string;
email: string;
full_name: string;
is_active: boolean;
created_at: string;
}
export function useProfile() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
// Fetch user profile
const getProfile = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await api.get('/auth/me');
const userData = response.data;
setUser(userData);
return userData;
} catch (err: any) {
const message = err.response?.data?.detail || 'Failed to load profile';
setError(message);
showToast({
title: 'Error loading profile',
description: message,
variant: 'destructive'
});
return null;
} finally {
setLoading(false);
}
}, []);
// Update user profile
const updateProfile = useCallback(async (data: Partial<User>) => {
setLoading(true);
setError(null);
try {
const response = await api.put('/auth/me', data);
const updatedUser = response.data;
setUser(updatedUser);
showToast({
title: 'Profile updated',
description: 'Your profile has been successfully updated'
});
return updatedUser;
} catch (err: any) {
const message = err.response?.data?.detail || 'Failed to update profile';
setError(message);
showToast({
title: 'Update failed',
description: message,
variant: 'destructive'
});
throw err;
} finally {
setLoading(false);
}
}, []);
// Change password
const changePassword = useCallback(async (passwordData: {
current_password: string;
new_password: string;
}) => {
setLoading(true);
setError(null);
try {
await api.post('/auth/change-password', passwordData);
showToast({
title: 'Password changed',
description: 'Your password has been successfully updated'
});
return true;
} catch (err: any) {
const message = err.response?.data?.detail || 'Failed to change password';
setError(message);
showToast({
title: 'Password change failed',
description: message,
variant: 'destructive'
});
throw err;
} finally {
setLoading(false);
}
}, []);
// Load profile on mount
useEffect(() => {
getProfile();
}, [getProfile]);
return {
user,
loading,
error,
getProfile,
updateProfile,
changePassword
};
}

View File

@@ -0,0 +1,169 @@
import { useState } from 'react';
import { useProfile } from '@/hooks/useProfile';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
import { Link } from 'react-router-dom';
export function Profile() {
const { user, loading, error, updateProfile } = useProfile();
const [isEditing, setIsEditing] = useState(false);
const [editData, setEditData] = useState({
full_name: '',
email: ''
});
// Initialize edit data when user loads
// (we'd normally do this in useEffect, but keeping it simple for now)
const handleEdit = () => {
if (user) {
setEditData({
full_name: user.full_name,
email: user.email
});
setIsEditing(true);
}
};
const handleSave = async () => {
if (editData.full_name.trim() && editData.email.trim()) {
await updateProfile({
full_name: editData.full_name.trim(),
email: editData.email.trim()
});
setIsEditing(false);
}
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin" />
<p className="mt-2">Loading profile...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center text-destructive">
<p>Error loading profile: {error}</p>
<Button variant="outline" onClick={() => window.location.reload()}>
Retry
</Button>
</div>
</div>
);
}
if (!user) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center">
<p>No user data available</p>
<Link to="/login">
<Button>Go to Login</Button>
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 p-4">
<div className="max-w-2xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold">My Profile</h1>
<Button
variant="outline"
onClick={handleEdit}
className="px-4"
>
{isEditing ? 'Cancel' : 'Edit Profile'}
</Button>
</div>
<Card>
<CardHeader>
<CardTitle className="text-xl">Account Information</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{isEditing ? (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium mb-2">Full Name</label>
<input
type="text"
value={editData.full_name}
onChange={(e) => setEditData({ ...editData, full_name: e.target.value })}
className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-2">Email</label>
<input
type="email"
value={editData.email}
onChange={(e) => setEditData({ ...editData, email: e.target.value })}
className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
required
/>
</div>
</div>
) : (
<div className="space-y-4">
<div className="flex items-center space-x-3">
<div className="w-12 h-12 bg-primary/10 text-primary rounded-full flex items-center justify-center">
{user.full_name.split(' ').map(n => n[0]).join('').toUpperCase()}
</div>
<div>
<p className="font-semibold">{user.full_name}</p>
<p className="text-sm text-muted-foreground">{user.email}</p>
</div>
</div>
<div className="border-t pt-4">
<div className="text-sm font-medium mb-2">Account Details</div>
<div className="space-y-2">
<div className="flex justify-between">
<span>Member since:</span>
<span>{new Date(user.created_at).toLocaleDateString()}</span>
</div>
<div className="flex justify-between">
<span>Status:</span>
<span className={user.is_active ? 'text-green-500' : 'text-red-500'}>
{user.is_active ? 'Active' : 'Inactive'}
</span>
</div>
</div>
</div>
</div>
)}
</CardContent>
<CardFooter className="flex justify-end space-x-3">
{!isEditing && (
<Button onClick={handleEdit}>
Edit Profile
</Button>
)}
{isEditing && (
<>
<Button onClick={handleSave} className="px-4">
Save Changes
</Button>
<Button variant="outline" onClick={() => setIsEditing(false)} className="px-4">
Cancel
</Button>
</>
)}
</CardFooter>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,39 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
export function SettingsAccount() {
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Account Management</CardTitle>
<CardDescription>
Manage your account settings and data
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-4">
<div className="border-t pt-4">
<h3 className="font-medium mb-2">Data Export</h3>
<p className="text-sm text-muted-foreground">
Export your scenarios, reports, and account data
</p>
<Button variant="outline">Export Data</Button>
</div>
<div className="border-t pt-4">
<h3 className="font-medium mb-2">Delete Account</h3>
<p className="text-sm text-muted-foreground">
Permanently delete your account and all associated data. This action cannot be undone.
</p>
<Button variant="destructive">Delete Account</Button>
</div>
</div>
</CardContent>
<CardFooter>
<Button variant="outline">Save Changes</Button>
</CardFooter>
</Card>
</div>
);
}

View File

@@ -0,0 +1,93 @@
import { Link } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Settings as SettingsIcon, Lock as LockIcon, Bell as BellIcon, Key as KeyIcon, Trash2 as Trash2Icon } from 'lucide-react';
interface SettingsNavItem {
title: string;
description: string;
href: string;
icon: React.ComponentType<{ className?: string }>;
}
const settingsNav: SettingsNavItem[] = [
{
title: 'Profile',
description: 'Update your personal information',
href: '/settings/profile',
icon: SettingsIcon
},
{
title: 'Password',
description: 'Change your account password',
href: '/settings/password',
icon: LockIcon
},
{
title: 'Notifications',
description: 'Manage email and push notifications',
href: '/settings/notifications',
icon: BellIcon
},
{
title: 'API Keys',
description: 'Manage your API access keys',
href: '/settings/api-keys',
icon: KeyIcon
},
{
title: 'Account',
description: 'Delete account or export data',
href: '/settings/account',
icon: Trash2Icon
}
];
export function SettingsLayout({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-screen bg-gray-50 p-4">
<div className="max-w-4xl mx-auto grid grid-cols-[250px_1fr] gap-6">
{/* Sidebar */}
<aside className="space-y-4">
<div className="flex items-center space-x-3 mb-6">
<div className="w-10 h-10 bg-primary/10 text-primary rounded-full flex items-center justify-center">
<SettingsIcon className="h-5 w-5" />
</div>
<div>
<h2 className="font-semibold">Settings</h2>
<p className="text-sm text-muted-foreground">Manage your account</p>
</div>
</div>
<nav className="space-y-2">
{settingsNav.map((item, index) => (
<Link
key={index}
to={item.href}
className={`flex items-center space-x-3 px-3 py-2 rounded-md text-sm font-medium
${window.location.pathname === item.href ? 'bg-primary/10 text-primary' : 'text-muted-foreground hover:bg-muted/50'}`}
>
<item.icon className="h-4 w-4" />
<div>
<div className="flex justify-between">
<span>{item.title}</span>
<span className="text-xs text-muted-foreground">{item.description}</span>
</div>
</div>
</Link>
))}
</nav>
</aside>
{/* Main Content */}
<main>
<Card>
<CardHeader>
<CardTitle className="text-xl">{settingsNav.find(nav => nav.href === window.location.pathname)?.title || 'Settings'}</CardTitle>
</CardHeader>
<CardContent>{children}</CardContent>
</Card>
</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,52 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
export function SettingsNotifications() {
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Notification Preferences</CardTitle>
<CardDescription>
Manage how and when you receive notifications from mockupAWS
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-4">
<div className="border-t pt-4">
<h3 className="font-medium mb-2">Email Notifications</h3>
<div className="space-y-3">
<label className="flex items-center space-x-3">
<input type="checkbox" checked defaultChecked />
<span>Report completion notifications</span>
</label>
<label className="flex items-center space-x-3">
<input type="checkbox" checked defaultChecked />
<span>Weekly cost summary</span>
</label>
<label className="flex items-center space-x-3">
<input type="checkbox" checked defaultChecked />
<span>Budget alert notifications</span>
</label>
<label className="flex items-center space-x-3">
<input type="checkbox" />
<span>Security alerts</span>
</label>
</div>
</div>
<div className="border-t pt-4">
<h3 className="font-medium mb-2">Push Notifications</h3>
<p className="text-sm text-muted-foreground">
Browser notifications for real-time updates (coming soon)
</p>
</div>
</div>
</CardContent>
<CardFooter>
<Button variant="outline">Save Preferences</Button>
</CardFooter>
</Card>
</div>
);
}

View File

@@ -0,0 +1,136 @@
import { useState } from 'react';
import { useProfile } from '@/hooks/useProfile';
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 { Loader2 } from 'lucide-react';
export function SettingsPassword() {
const { loading, changePassword } = useProfile();
const [formData, setFormData] = useState({
current_password: '',
new_password: '',
confirm_password: ''
});
const [isChanging, setIsChanging] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (formData.new_password !== formData.confirm_password) {
// In a real app, we'd show a form error
alert('New passwords do not match');
return;
}
if (formData.new_password.length < 8) {
alert('Password must be at least 8 characters');
return;
}
setIsChanging(true);
try {
await changePassword({
current_password: formData.current_password,
new_password: formData.new_password
});
// Reset form on success
setFormData({
current_password: '',
new_password: '',
confirm_password: ''
});
} catch (err) {
// Error handled by useProfile hook
} finally {
setIsChanging(false);
}
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin" />
<p className="mt-2">Loading...</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Change Password</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="current_password">Current Password</Label>
<Input
id="current_password"
type="password"
value={formData.current_password}
onChange={(e) => setFormData({ ...formData, current_password: e.target.value })}
required
autoComplete="current-password"
/>
<p className="text-xs text-muted-foreground">
Enter your current password
</p>
</div>
<div className="space-y-2">
<Label htmlFor="new_password">New Password</Label>
<Input
id="new_password"
type="password"
value={formData.new_password}
onChange={(e) => setFormData({ ...formData, new_password: e.target.value })}
required
autoComplete="new-password"
/>
<p className="text-xs text-muted-foreground">
Must be at least 8 characters long
</p>
</div>
<div className="space-y-2">
<Label htmlFor="confirm_password">Confirm New Password</Label>
<Input
id="confirm_password"
type="password"
value={formData.confirm_password}
onChange={(e) => setFormData({ ...formData, confirm_password: e.target.value })}
required
autoComplete="new-password"
/>
<p className="text-xs text-muted-foreground">
Re-enter your new password to confirm
</p>
</div>
</form>
</CardContent>
<CardFooter>
<Button
type="submit"
onClick={handleSubmit}
className="w-full"
disabled={isChanging}
>
{isChanging ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Changing password...
</>
) : (
'Change Password'
)}
</Button>
</CardFooter>
</Card>
</div>
);
}

View File

@@ -0,0 +1,173 @@
import { useState } from 'react';
import { useProfile } from '@/hooks/useProfile';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
export function SettingsProfile() {
const { user, loading, updateProfile } = useProfile();
const [editMode, setEditMode] = useState(false);
const [formData, setFormData] = useState({
full_name: '',
email: ''
});
const [isSaving, setIsSaving] = useState(false);
// Initialize form with user data
// In a real app, we'd use useEffect to set this when user loads
// For simplicity, we'll initialize on mount assuming user exists
const handleSave = async () => {
setIsSaving(true);
try {
await updateProfile({
full_name: formData.full_name.trim(),
email: formData.email.trim()
});
setEditMode(false);
} catch (err) {
// Error handled by useProfile hook
} finally {
setIsSaving(false);
}
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin" />
<p className="mt-2">Loading...</p>
</div>
</div>
);
}
if (!user) {
return (
<div className="min-h-screen flex items-center justify-center p-4">
<div className="text-center">
<p>Please log in to view your profile</p>
</div>
</div>
);
}
// Initialize form data if not already set
// Using a simple approach - in practice this would be in useEffect
const initialized = formData.full_name !== '' || formData.email !== '';
if (!initialized && user) {
setFormData({
full_name: user.full_name,
email: user.email
});
}
return (
<div className="space-y-6">
<div className="border-t pt-4">
<Button
variant="outline"
onClick={() => setEditMode(!editMode)}
className="w-full text-left"
>
{editMode ? 'Cancel' : 'Edit Profile'}
</Button>
</div>
{editMode ? (
<Card>
<CardHeader>
<CardTitle className="text-lg">Edit Profile</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="full_name">Full Name</Label>
<Input
id="full_name"
type="text"
value={formData.full_name}
onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
required
autoComplete="name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email Address</Label>
<Input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
autoComplete="email"
/>
</div>
</div>
<Button
type="submit"
className="w-full"
disabled={isSaving}
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
'Save Changes'
)}
</Button>
</form>
</CardContent>
</Card>
) : (
<>
<Card>
<CardHeader>
<CardTitle className="text-lg">Profile Information</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="full_name">Full Name</Label>
<p id="full_name" className="bg-muted px-3 py-2 rounded-md">
{user.full_name}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email Address</Label>
<p id="email" className="bg-muted px-3 py-2 rounded-md">
{user.email}
</p>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Account Details</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Member Since</Label>
<p className="bg-muted px-3 py-2 rounded-md">
{new Date(user.created_at).toLocaleDateString()}
</p>
</div>
<div className="space-y-2">
<Label>Account Status</Label>
<p className={`bg-muted px-3 py-2 rounded-md ${user.is_active ? 'text-green-500' : 'text-red-500'}`}>
{user.is_active ? 'Active' : 'Inactive'}
</p>
</div>
</CardContent>
</Card>
</>
)}
</div>
);
}