feat: Introduce user profile service and enable role-based profile management for users and agents, including avatar uploads and a dismissible error message in the hero section.

This commit is contained in:
pradeepkumar
2026-02-01 00:50:09 +05:30
parent 1ec1696db7
commit c4afc421cf
6 changed files with 270 additions and 79 deletions

View File

@@ -70,6 +70,10 @@ export function HeroSection() {
setValidationError(null); // Clear error when user starts typing setValidationError(null); // Clear error when user starts typing
}; };
const handleClearError = () => {
setValidationError(null);
};
return ( return (
<section className="relative min-h-[600px] overflow-hidden"> <section className="relative min-h-[600px] overflow-hidden">
{/* Background Image */} {/* Background Image */}
@@ -169,9 +173,18 @@ export function HeroSection() {
{/* Validation Error Message */} {/* Validation Error Message */}
{validationError && ( {validationError && (
<div className="mt-3 text-center"> <div className="mt-3 text-center">
<p className="text-white font-serif text-sm bg-red-500/90 rounded-[7px] py-2 px-4 inline-block"> <div className="text-white font-serif text-sm bg-red-500/90 rounded-[7px] py-2 px-4 inline-flex items-center gap-3">
{validationError} <span>{validationError}</span>
</p> <button
onClick={handleClearError}
className="hover:bg-white/20 rounded-full p-0.5 transition-colors"
title="Dismiss"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
</div>
</div> </div>
)} )}

View File

@@ -5,6 +5,7 @@ import Link from 'next/link';
import Image from 'next/image'; import Image from 'next/image';
import { useSession, signOut } from 'next-auth/react'; import { useSession, signOut } from 'next-auth/react';
import { agentsService } from '@/services/agents.service'; import { agentsService } from '@/services/agents.service';
import { usersService } from '@/services/users.service';
import { uploadService } from '@/services/upload.service'; import { uploadService } from '@/services/upload.service';
const navLinks = [ const navLinks = [
@@ -36,17 +37,27 @@ export function CommonHeader() {
}; };
}, [showProfileMenu]); }, [showProfileMenu]);
// Fetch profile image from backend // Fetch profile image from backend based on user role
useEffect(() => { useEffect(() => {
const fetchProfileImage = async () => { const fetchProfileImage = async () => {
try { try {
const profile = await agentsService.getMyProfile(); const role = (session?.user as any)?.role;
if (profile.avatar) { let avatar: string | null = null;
if (role === 'AGENT') {
const profile = await agentsService.getMyProfile();
avatar = profile.avatar;
} else if (role === 'USER') {
const profile = await usersService.getMyProfile();
avatar = profile.avatar;
}
if (avatar) {
try { try {
const avatarUrl = await uploadService.getPresignedDownloadUrl(profile.avatar); const avatarUrl = await uploadService.getPresignedDownloadUrl(avatar);
setProfileImage(avatarUrl); setProfileImage(avatarUrl);
} catch { } catch {
setProfileImage(profile.avatar); setProfileImage(avatar);
} }
} }
} catch (err) { } catch (err) {

View File

@@ -5,6 +5,7 @@ import Image from 'next/image';
import { useSession, signIn } from 'next-auth/react'; import { useSession, signIn } from 'next-auth/react';
import { uploadService } from '@/services/upload.service'; import { uploadService } from '@/services/upload.service';
import { agentsService } from '@/services/agents.service'; import { agentsService } from '@/services/agents.service';
import { usersService } from '@/services/users.service';
interface ProfileSettingsFormProps { interface ProfileSettingsFormProps {
initialData?: { initialData?: {
@@ -49,29 +50,48 @@ export function ProfileSettingsForm({
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Fetch profile data on mount // Fetch profile data on mount based on user role
useEffect(() => { useEffect(() => {
const fetchProfile = async () => { const fetchProfile = async () => {
try { try {
setIsLoading(true); setIsLoading(true);
const profile = await agentsService.getMyProfile(); const role = (session?.user as any)?.role;
setFormData({ if (role === 'AGENT') {
fullName: `${profile.firstName || ''} ${profile.lastName || ''}`.trim(), const profile = await agentsService.getMyProfile();
career: profile.agentType?.name || 'Real Estate Agent', setFormData({
email: profile.email || session?.user?.email || '', fullName: `${profile.firstName || ''} ${profile.lastName || ''}`.trim(),
phone: profile.phone || '', career: profile.agentType?.name || 'Real Estate Agent',
location: profile.serviceAreas?.[0] || '', email: profile.email || session?.user?.email || '',
}); phone: profile.phone || '',
location: profile.serviceAreas?.[0] || '',
});
// Handle avatar URL - if it's an S3 key, get presigned URL if (profile.avatar) {
if (profile.avatar) { try {
try { const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar); setAvatarUrl(presignedUrl);
setAvatarUrl(presignedUrl); } catch {
} catch { setAvatarUrl(profile.avatar);
// If getting presigned URL fails, the avatar might be a full URL }
setAvatarUrl(profile.avatar); }
} else if (role === 'USER') {
const profile = await usersService.getMyProfile();
setFormData({
fullName: `${profile.firstName || ''} ${profile.lastName || ''}`.trim(),
career: '', // Users don't have career/agent type
email: profile.email || session?.user?.email || '',
phone: profile.phone || '',
location: [profile.city, profile.state, profile.country].filter(Boolean).join(', '),
});
if (profile.avatar) {
try {
const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
setAvatarUrl(presignedUrl);
} catch {
setAvatarUrl(profile.avatar);
}
} }
} }
} catch (err) { } catch (err) {
@@ -130,26 +150,50 @@ export function ProfileSettingsForm({
setError(null); setError(null);
setUploadProgress(0); setUploadProgress(0);
// Upload the avatar // Show local preview immediately for instant feedback
const uploadedFile = await uploadService.uploadAvatar(file, (progress) => { const localPreviewUrl = URL.createObjectURL(file);
setUploadProgress(progress.percentage); setAvatarUrl(localPreviewUrl);
});
// Update the profile with the new avatar key const role = (session?.user as any)?.role;
await agentsService.updateProfile({ avatar: uploadedFile.url });
// Upload the avatar based on role
let uploadedFile;
if (role === 'AGENT') {
uploadedFile = await uploadService.uploadAvatar(file, (progress) => {
setUploadProgress(progress.percentage);
});
// Update the agent profile with the new avatar key
await agentsService.updateProfile({ avatar: uploadedFile.url });
} else {
uploadedFile = await uploadService.uploadUserAvatar(file, (progress) => {
setUploadProgress(progress.percentage);
});
// Update the user profile with the new avatar key
await usersService.updateProfile({ avatar: uploadedFile.url });
}
// Small delay to ensure S3 has processed the upload
await new Promise(resolve => setTimeout(resolve, 500));
// Get the presigned URL for display // Get the presigned URL for display
const presignedUrl = await uploadService.getPresignedDownloadUrl(uploadedFile.url); try {
setAvatarUrl(presignedUrl); const presignedUrl = await uploadService.getPresignedDownloadUrl(uploadedFile.url);
setAvatarUrl(presignedUrl);
// Clean up local preview URL only after successful presigned URL
URL.revokeObjectURL(localPreviewUrl);
// Update the session to reflect the new avatar // Update the session to reflect the new avatar
await updateSession({ await updateSession({
...session, ...session,
user: { user: {
...session?.user, ...session?.user,
image: presignedUrl, image: presignedUrl,
}, },
}); });
} catch {
// If presigned URL fails, keep the local preview (don't revoke it)
console.warn('Could not get presigned URL, using local preview');
}
setSuccessMessage('Profile picture updated successfully!'); setSuccessMessage('Profile picture updated successfully!');
} catch (err) { } catch (err) {
@@ -170,8 +214,14 @@ export function ProfileSettingsForm({
setIsUploading(true); setIsUploading(true);
setError(null); setError(null);
// Update profile to remove avatar const role = (session?.user as any)?.role;
await agentsService.updateProfile({ avatar: null });
// Update profile to remove avatar based on role
if (role === 'AGENT') {
await agentsService.updateProfile({ avatar: null });
} else {
await usersService.updateProfile({ avatar: null });
}
setAvatarUrl(null); setAvatarUrl(null);
// Update session // Update session
@@ -197,19 +247,33 @@ export function ProfileSettingsForm({
setIsSaving(true); setIsSaving(true);
setError(null); setError(null);
const role = (session?.user as any)?.role;
// Split full name into first and last name // Split full name into first and last name
const nameParts = formData.fullName.trim().split(' '); const nameParts = formData.fullName.trim().split(' ');
const firstName = nameParts[0] || ''; const firstName = nameParts[0] || '';
const lastName = nameParts.slice(1).join(' ') || ''; const lastName = nameParts.slice(1).join(' ') || '';
// Update profile // Update profile based on role (email is not editable - tied to auth)
await agentsService.updateProfile({ if (role === 'AGENT') {
firstName, await agentsService.updateProfile({
lastName, firstName,
email: formData.email, lastName,
phone: formData.phone, phone: formData.phone,
serviceAreas: formData.location ? [formData.location] : [], serviceAreas: formData.location ? [formData.location] : [],
}); });
} else {
// Parse location into city, state, country for users
const locationParts = formData.location.split(',').map(s => s.trim());
await usersService.updateProfile({
firstName,
lastName,
phone: formData.phone,
city: locationParts[0] || undefined,
state: locationParts[1] || undefined,
country: locationParts[2] || undefined,
});
}
// Update session with new name // Update session with new name
await updateSession({ await updateSession({
@@ -334,8 +398,8 @@ export function ProfileSettingsForm({
{/* Form Fields */} {/* Form Fields */}
<div className="space-y-5"> <div className="space-y-5">
{/* Row 1: Full Name & Career */} {/* Row 1: Full Name & Career (Career only for agents) */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-5"> <div className={`grid grid-cols-1 ${(session?.user as any)?.role === 'AGENT' ? 'sm:grid-cols-2' : ''} gap-5`}>
<div> <div>
<label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2"> <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
Full Name Full Name
@@ -347,17 +411,19 @@ export function ProfileSettingsForm({
className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]" className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
/> />
</div> </div>
<div> {(session?.user as any)?.role === 'AGENT' && (
<label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2"> <div>
Career <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
</label> Career
<input </label>
type="text" <input
value={formData.career} type="text"
onChange={(e) => handleChange('career', e.target.value)} value={formData.career}
className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]" onChange={(e) => handleChange('career', e.target.value)}
/> className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
</div> />
</div>
)}
</div> </div>
{/* Row 2: Email & Phone */} {/* Row 2: Email & Phone */}
@@ -369,8 +435,8 @@ export function ProfileSettingsForm({
<input <input
type="email" type="email"
value={formData.email} value={formData.email}
onChange={(e) => handleChange('email', e.target.value)} disabled
className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]" className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D]/60 bg-gray-50 cursor-not-allowed"
/> />
</div> </div>
<div> <div>

View File

@@ -6,6 +6,7 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { useSession } from 'next-auth/react'; import { useSession } from 'next-auth/react';
import { agentsService } from '@/services/agents.service'; import { agentsService } from '@/services/agents.service';
import { usersService } from '@/services/users.service';
import { uploadService } from '@/services/upload.service'; import { uploadService } from '@/services/upload.service';
interface NavItem { interface NavItem {
@@ -33,22 +34,38 @@ export function SettingsSidebar({
useEffect(() => { useEffect(() => {
const fetchProfile = async () => { const fetchProfile = async () => {
try { try {
const profile = await agentsService.getMyProfile(); const role = (session?.user as any)?.role;
let avatarUrl = session?.user?.image || null; let avatarUrl = session?.user?.image || null;
if (profile.avatar) { let name = session?.user?.name || 'User';
try { let title = 'User';
avatarUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
} catch { if (role === 'AGENT') {
avatarUrl = profile.avatar; const profile = await agentsService.getMyProfile();
name = `${profile.firstName || ''} ${profile.lastName || ''}`.trim() || name;
title = profile.agentType?.name || 'Real Estate Agent';
if (profile.avatar) {
try {
avatarUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
} catch {
avatarUrl = profile.avatar;
}
}
} else if (role === 'USER') {
const profile = await usersService.getMyProfile();
name = `${profile.firstName || ''} ${profile.lastName || ''}`.trim() || name;
title = 'Member';
if (profile.avatar) {
try {
avatarUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
} catch {
avatarUrl = profile.avatar;
}
} }
} }
setProfileData({ setProfileData({ name, title, avatarUrl });
name: `${profile.firstName || ''} ${profile.lastName || ''}`.trim() || session?.user?.name || 'User',
title: profile.agentType?.name || 'Real Estate Agent',
avatarUrl,
});
} catch (err) { } catch (err) {
console.error('Failed to fetch profile for sidebar:', err); console.error('Failed to fetch profile for sidebar:', err);
// Keep session data as fallback // Keep session data as fallback

View File

@@ -148,7 +148,8 @@ class UploadService {
} }
/** /**
* Upload avatar image (uses agent profile ID as filename for auto-replacement) * Upload avatar image for AGENTS (uses agent profile ID as filename for auto-replacement)
* S3 path: {env}/agents/{agentId}/avatar.{ext}
* Returns the S3 key (not full URL) for storage in database * Returns the S3 key (not full URL) for storage in database
*/ */
async uploadAvatar( async uploadAvatar(
@@ -179,6 +180,39 @@ class UploadService {
}; };
} }
/**
* Upload avatar image for regular USERS (uses user ID as folder)
* S3 path: {env}/users/{userId}/avatar.{ext}
* Returns the S3 key (not full URL) for storage in database
*/
async uploadUserAvatar(
file: File,
onProgress?: (progress: UploadProgress) => void
): Promise<UploadedFile> {
// Step 1: Get presigned URL from backend (uses user ID as folder)
const response = await api.post<{ data: PresignedUrlResponse }>(
`${this.basePath}/user-avatar-presigned-url`,
{
filename: file.name,
contentType: file.type,
}
);
const { uploadUrl, key } = response.data.data;
// Step 2: Upload directly to S3
await this.uploadToS3(uploadUrl, file, onProgress);
// Step 3: Return uploaded file info with KEY (not full URL) for database storage
return {
id: key,
name: file.name,
size: file.size,
type: file.type,
url: key, // Store the S3 key, not the full URL
uploadedAt: new Date().toISOString(),
};
}
/** /**
* Get a presigned download URL for an S3 key * Get a presigned download URL for an S3 key
*/ */

View File

@@ -0,0 +1,50 @@
import api from './api';
export interface UserProfile {
id: string;
userId: string;
email: string;
firstName: string | null;
lastName: string | null;
phone: string | null;
avatar: string | null;
city: string | null;
state: string | null;
country: string | null;
createdAt: string;
updatedAt: string;
}
export interface UpdateUserProfileData {
firstName?: string;
lastName?: string;
phone?: string;
avatar?: string | null;
city?: string;
state?: string;
country?: string;
}
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
export const usersService = {
/**
* Get current user's profile
*/
async getMyProfile(): Promise<UserProfile> {
const response = await api.get<ApiResponse<UserProfile>>('/users/profile/me');
return response.data.data;
},
/**
* Update current user's profile
*/
async updateProfile(data: UpdateUserProfileData): Promise<UserProfile> {
const response = await api.patch<ApiResponse<UserProfile>>('/users/profile/me', data);
return response.data.data;
},
};