feat: enhance user preferences management with userId integration

- Added `userId` field to `UserPreferences` model in Prisma schema for user-specific preferences.
- Implemented migration to populate existing preferences with the first user.
- Updated user preferences service methods to handle user-specific data retrieval and updates.
- Modified API routes and components to ensure user authentication and fetch preferences based on the authenticated user.
- Enhanced session management in various components to load user preferences accordingly.
This commit is contained in:
Julien Froidefond
2025-09-30 22:15:44 +02:00
parent 17b86b6087
commit 30aaca4877
23 changed files with 381 additions and 124 deletions

View File

@@ -12,6 +12,7 @@ import {
toggleColumnVisibility as toggleColumnVisibilityAction
} from '@/actions/preferences';
import { useTheme } from './ThemeContext';
import { useSession } from 'next-auth/react';
interface UserPreferencesContextType {
preferences: UserPreferences;
@@ -77,6 +78,38 @@ export function UserPreferencesProvider({ children, initialPreferences }: UserPr
const [preferences, setPreferences] = useState<UserPreferences>(initialPreferences || defaultPreferences);
const [isPending, startTransition] = useTransition();
const { theme, toggleTheme: themeToggleTheme, setTheme: themeSetTheme } = useTheme();
const { data: session, status } = useSession();
// Fonction pour charger les préférences côté client
const loadUserPreferences = useCallback(async () => {
if (status === 'loading') return; // Attendre que la session soit chargée
try {
const response = await fetch('/api/user-preferences');
if (response.ok) {
const result = await response.json();
if (result.success) {
setPreferences(result.data);
// Synchroniser le thème avec le ThemeContext
if (result.data.viewPreferences.theme !== theme) {
themeSetTheme(result.data.viewPreferences.theme);
}
}
}
} catch (error) {
console.error('Erreur lors du chargement des préférences:', error);
}
}, [status, theme, themeSetTheme]);
// Recharger les préférences quand la session change (login/logout)
useEffect(() => {
if (status === 'authenticated') {
loadUserPreferences();
} else if (status === 'unauthenticated') {
// Reset aux préférences par défaut quand l'utilisateur se déconnecte
setPreferences(defaultPreferences);
}
}, [status, loadUserPreferences]);
// Synchroniser les préférences avec le thème actuel du ThemeContext
useEffect(() => {