feat: Enable agents to initiate conversations with connected users and refactor the conversation start flow to be role-aware.

This commit is contained in:
pradeepkumar
2026-03-15 00:29:25 +05:30
parent 9acb0063fa
commit 50640a5828
6 changed files with 289 additions and 23 deletions

View File

@@ -6,6 +6,7 @@ import { useSession } from 'next-auth/react';
import { ChatHeader } from './ChatHeader'; import { ChatHeader } from './ChatHeader';
import { MessageInput } from './MessageInput'; import { MessageInput } from './MessageInput';
import { ChatDropdownMenu, type DropdownMenuItem } from './ChatDropdownMenu'; import { ChatDropdownMenu, type DropdownMenuItem } from './ChatDropdownMenu';
import { NewConversationModal, type ConnectedContact } from './NewConversationModal';
import { useMessaging } from '@/hooks/useMessaging'; import { useMessaging } from '@/hooks/useMessaging';
import { connectionRequestsService, type ConnectionRequest } from '@/services/connection-requests.service'; import { connectionRequestsService, type ConnectionRequest } from '@/services/connection-requests.service';
import { uploadService } from '@/services/upload.service'; import { uploadService } from '@/services/upload.service';
@@ -112,13 +113,15 @@ function AvatarWithPlaceholder({ src, alt, size }: { src: string; alt: string; s
); );
} }
// Connected agent with avatar URL // Connected contact with avatar URL (used for both user-side agents and agent-side users)
interface ConnectedAgent { interface ConnectedAgent {
agentProfileId: string; agentProfileId: string;
userId?: string; // The user's ID (for agent-side contacts)
name: string; name: string;
avatar: string | null; avatar: string | null;
avatarUrl: string | null; avatarUrl: string | null;
headline: string | null; headline: string | null;
email: string | null;
city: string | null; city: string | null;
state: string | null; state: string | null;
} }
@@ -154,6 +157,7 @@ export function MessagingPage() {
const [connectedAgents, setConnectedAgents] = useState<ConnectedAgent[]>([]); const [connectedAgents, setConnectedAgents] = useState<ConnectedAgent[]>([]);
const [isLoadingAgents, setIsLoadingAgents] = useState(false); const [isLoadingAgents, setIsLoadingAgents] = useState(false);
const [isStartingConversation, setIsStartingConversation] = useState<string | null>(null); const [isStartingConversation, setIsStartingConversation] = useState<string | null>(null);
const [isComposeOpen, setIsComposeOpen] = useState(false);
// Store converted avatar URLs by conversation ID // Store converted avatar URLs by conversation ID
const [conversationAvatarUrls, setConversationAvatarUrls] = useState<Record<string, string>>({}); const [conversationAvatarUrls, setConversationAvatarUrls] = useState<Record<string, string>>({});
// Store converted file URLs by message ID (for S3-stored images/files) // Store converted file URLs by message ID (for S3-stored images/files)
@@ -196,6 +200,7 @@ export function MessagingPage() {
avatar: agent?.avatar || null, avatar: agent?.avatar || null,
avatarUrl, avatarUrl,
headline: agent?.headline || null, headline: agent?.headline || null,
email: null,
city: agent?.city || null, city: agent?.city || null,
state: agent?.state || null, state: agent?.state || null,
}; };
@@ -204,9 +209,43 @@ export function MessagingPage() {
setConnectedAgents(agents); setConnectedAgents(agents);
} else { } else {
// For AGENT role - they don't start conversations, they receive them // AGENT role — fetch accepted connections (users who connected with this agent)
// So we don't need to show a list to start conversations const requests = await connectionRequestsService.getReceivedRequests('ACCEPTED');
setConnectedAgents([]);
const users: ConnectedAgent[] = await Promise.all(
requests.map(async (req) => {
const user = req.user;
const profile = user?.userProfile;
let avatarUrl: string | null = null;
const avatarKey = profile?.avatar || user?.avatar;
if (avatarKey) {
try {
avatarUrl = await uploadService.getPresignedDownloadUrl(avatarKey);
} catch {
avatarUrl = null;
}
}
const fullName = profile
? `${profile.firstName || ''} ${profile.lastName || ''}`.trim()
: '';
return {
agentProfileId: req.agentProfileId,
userId: req.userId,
name: fullName || user?.email || 'User',
avatar: avatarKey || null,
avatarUrl,
headline: null,
email: user?.email || null,
city: null,
state: null,
};
})
);
setConnectedAgents(users);
} }
} catch (error) { } catch (error) {
console.error('Failed to fetch connected contacts:', error); console.error('Failed to fetch connected contacts:', error);
@@ -321,18 +360,21 @@ export function MessagingPage() {
setMessageFileUrls({}); setMessageFileUrls({});
}, [currentConversation?.id]); }, [currentConversation?.id]);
// Handle starting a new conversation with an agent // Handle starting a new conversation — role-aware
const handleStartConversation = useCallback(async (agentProfileId: string) => { const handleStartConversation = useCallback(async (contactId: string) => {
setIsStartingConversation(agentProfileId); setIsStartingConversation(contactId);
try { try {
const conversation = await startConversation(agentProfileId); const body = userRole === 'AGENT'
? { userId: contactId }
: { agentProfileId: contactId };
const conversation = await startConversation(body);
await selectConversation(conversation.id); await selectConversation(conversation.id);
} catch (error) { } catch (error) {
console.error('Failed to start conversation:', error); console.error('Failed to start conversation:', error);
} finally { } finally {
setIsStartingConversation(null); setIsStartingConversation(null);
} }
}, [startConversation, selectConversation]); }, [startConversation, selectConversation, userRole]);
// Handle sending a message // Handle sending a message
const handleSendMessage = useCallback(async (content: string) => { const handleSendMessage = useCallback(async (content: string) => {
@@ -518,6 +560,26 @@ export function MessagingPage() {
</div> </div>
)} )}
{/* New conversation modal */}
<NewConversationModal
isOpen={isComposeOpen}
onClose={() => setIsComposeOpen(false)}
contacts={connectedAgents.map((agent) => ({
id: userRole === 'AGENT' ? agent.userId! : agent.agentProfileId,
name: agent.name,
avatar: agent.avatar,
avatarUrl: agent.avatarUrl,
headline: agent.headline,
email: agent.email,
city: agent.city,
state: agent.state,
}))}
isLoading={isLoadingAgents}
onStartConversation={async (contactId) => {
await handleStartConversation(contactId);
}}
/>
<div className="border border-[#00293d]/10 rounded-[20px] bg-white overflow-hidden"> <div className="border border-[#00293d]/10 rounded-[20px] bg-white overflow-hidden">
{/* Header */} {/* Header */}
<div className="flex items-center gap-4 p-4 border-b border-[#00293d]/10"> <div className="flex items-center gap-4 p-4 border-b border-[#00293d]/10">
@@ -572,7 +634,10 @@ export function MessagingPage() {
onClose={() => setIsPageMenuOpen(false)} onClose={() => setIsPageMenuOpen(false)}
/> />
</div> </div>
<button className="p-2 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"> <button
onClick={() => setIsComposeOpen(true)}
className="p-2 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
>
<Image <Image
src="/assets/icons/compose-icon.svg" src="/assets/icons/compose-icon.svg"
alt="Compose" alt="Compose"
@@ -597,7 +662,7 @@ export function MessagingPage() {
{/* Header for connected agents */} {/* Header for connected agents */}
<div className="p-4 border-b border-[#00293d]/10"> <div className="p-4 border-b border-[#00293d]/10">
<p className="font-serif font-normal text-[14px] text-[#00293D]/50 text-center"> <p className="font-serif font-normal text-[14px] text-[#00293D]/50 text-center">
{searchQuery ? 'No conversations found' : 'No conversations yet. Start a conversation with an agent!'} {searchQuery ? 'No conversations found' : `No conversations yet. Start a conversation with ${userRole === 'AGENT' ? 'a user' : 'an agent'}!`}
</p> </p>
</div> </div>
@@ -605,7 +670,7 @@ export function MessagingPage() {
{connectedAgents.length > 0 ? ( {connectedAgents.length > 0 ? (
<div className="flex-1 overflow-y-auto p-2 space-y-2 custom-scrollbar"> <div className="flex-1 overflow-y-auto p-2 space-y-2 custom-scrollbar">
<p className="px-2 py-1 font-fractul font-medium text-[12px] text-[#00293D]/70 uppercase tracking-wide"> <p className="px-2 py-1 font-fractul font-medium text-[12px] text-[#00293D]/70 uppercase tracking-wide">
Your Connected Agents {userRole === 'AGENT' ? 'Your Connected Users' : 'Your Connected Agents'}
</p> </p>
{connectedAgents {connectedAgents
.filter((agent) => .filter((agent) =>
@@ -614,7 +679,7 @@ export function MessagingPage() {
.map((agent) => ( .map((agent) => (
<button <button
key={agent.agentProfileId} key={agent.agentProfileId}
onClick={() => handleStartConversation(agent.agentProfileId)} onClick={() => handleStartConversation(userRole === 'AGENT' ? agent.userId! : agent.agentProfileId)}
disabled={isStartingConversation === agent.agentProfileId} disabled={isStartingConversation === agent.agentProfileId}
className="w-full flex items-center gap-3 p-4 rounded-[15px] cursor-pointer transition-colors hover:bg-[#00293d]/5 disabled:opacity-50" className="w-full flex items-center gap-3 p-4 rounded-[15px] cursor-pointer transition-colors hover:bg-[#00293d]/5 disabled:opacity-50"
style={{ border: '1px solid rgba(0, 41, 61, 0.1)' }} style={{ border: '1px solid rgba(0, 41, 61, 0.1)' }}
@@ -668,7 +733,7 @@ export function MessagingPage() {
</div> </div>
) : ( ) : (
<div className="flex-1 flex items-center justify-center text-[#00293D]/50 font-serif p-4 text-center"> <div className="flex-1 flex items-center justify-center text-[#00293D]/50 font-serif p-4 text-center">
<p>No connected agents yet. Connect with agents to start messaging!</p> <p>{userRole === 'AGENT' ? 'No connected users yet.' : 'No connected agents yet. Connect with agents to start messaging!'}</p>
</div> </div>
)} )}
</div> </div>

View File

@@ -0,0 +1,197 @@
'use client';
import { useState } from 'react';
import Image from 'next/image';
// Helper to get a valid avatar URL
function getValidAvatarUrl(avatar: string | null | undefined): string {
const placeholder = '/assets/icons/user-placeholder-icon.svg';
if (!avatar) return placeholder;
if (avatar.startsWith('http://') || avatar.startsWith('https://') || avatar.startsWith('/')) {
return avatar;
}
return placeholder;
}
export interface ConnectedContact {
id: string; // agentProfileId (for users) or userId (for agents)
name: string;
avatar: string | null;
avatarUrl: string | null;
headline: string | null;
email: string | null;
city: string | null;
state: string | null;
}
interface NewConversationModalProps {
isOpen: boolean;
onClose: () => void;
contacts: ConnectedContact[];
isLoading: boolean;
onStartConversation: (contactId: string) => Promise<void>;
}
export function NewConversationModal({
isOpen,
onClose,
contacts,
isLoading,
onStartConversation,
}: NewConversationModalProps) {
const [searchQuery, setSearchQuery] = useState('');
const [startingId, setStartingId] = useState<string | null>(null);
if (!isOpen) return null;
const filteredContacts = contacts.filter((contact) =>
contact.name.toLowerCase().includes(searchQuery.toLowerCase())
);
const handleStart = async (contactId: string) => {
setStartingId(contactId);
try {
await onStartConversation(contactId);
onClose();
} catch (error) {
console.error('Failed to start conversation:', error);
} finally {
setStartingId(null);
}
};
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="bg-white rounded-[20px] w-full max-w-[480px] mx-4 shadow-xl overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-[#00293d]/10">
<h2 className="font-fractul font-bold text-[16px] text-[#00293D]">
New Conversation
</h2>
<button
onClick={onClose}
className="p-1 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
>
<Image
src="/assets/icons/close-icon.svg"
alt="Close"
width={20}
height={20}
/>
</button>
</div>
{/* Search */}
<div className="p-4 border-b border-[#00293d]/10">
<div className="flex items-center gap-2 border border-[#00293d]/10 rounded-[15px] px-4 py-2">
<Image
src="/assets/icons/search-icon.svg"
alt="Search"
width={18}
height={18}
/>
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search connections..."
className="flex-1 font-serif font-normal text-[14px] text-[#00293D] placeholder-[#00293D]/50 focus:outline-none"
autoFocus
/>
</div>
</div>
{/* Contact list */}
<div className="max-h-[400px] overflow-y-auto">
{isLoading ? (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00293d]" />
</div>
) : filteredContacts.length === 0 ? (
<div className="flex items-center justify-center py-12 px-4">
<p className="font-serif font-normal text-[14px] text-[#00293D]/50 text-center">
{searchQuery
? 'No connections match your search'
: 'No connections yet'}
</p>
</div>
) : (
<div className="p-2 space-y-1">
{filteredContacts.map((contact) => (
<button
key={contact.id}
onClick={() => handleStart(contact.id)}
disabled={startingId === contact.id}
className="w-full flex items-center gap-3 p-3 rounded-[12px] cursor-pointer transition-colors hover:bg-[#00293d]/5 disabled:opacity-50"
>
{/* Avatar */}
<div className="w-[44px] h-[44px] rounded-full overflow-hidden border border-[#00293D]/20 flex-shrink-0">
{contact.avatarUrl && !contact.avatarUrl.endsWith('user-placeholder-icon.svg') ? (
<img
src={getValidAvatarUrl(contact.avatarUrl)}
alt={contact.name}
className="w-full h-full object-cover"
/>
) : (
<Image
src="/assets/icons/user-placeholder-icon.svg"
alt={contact.name}
width={44}
height={44}
className="w-full h-full object-cover"
/>
)}
</div>
{/* Info */}
<div className="flex-1 min-w-0 text-left">
<p className="font-fractul font-medium text-[14px] leading-[17px] text-[#00293D]">
{contact.name}
</p>
{contact.headline && (
<p className="font-serif font-normal text-[12px] leading-[16px] text-[#00293D]/70 truncate">
{contact.headline}
</p>
)}
{contact.email && !contact.headline && (
<p className="font-serif font-normal text-[12px] leading-[16px] text-[#00293D]/70 truncate">
{contact.email}
</p>
)}
{(contact.city || contact.state) && (
<p className="font-serif font-normal text-[11px] leading-[14px] text-[#00293D]/50">
{[contact.city, contact.state].filter(Boolean).join(', ')}
</p>
)}
</div>
{/* Loading or arrow */}
<div className="flex-shrink-0">
{startingId === contact.id ? (
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#e58625]" />
) : (
<div className="w-8 h-8 rounded-full bg-[#e58625]/10 flex items-center justify-center">
<Image
src="/assets/icons/message-icon.svg"
alt="Start chat"
width={16}
height={16}
className="opacity-70"
/>
</div>
)}
</div>
</button>
))}
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -2,3 +2,4 @@
export { ChatHeader } from './ChatHeader'; export { ChatHeader } from './ChatHeader';
export { MessageInput } from './MessageInput'; export { MessageInput } from './MessageInput';
export { MessagingPage } from './MessagingPage'; export { MessagingPage } from './MessagingPage';
export { NewConversationModal } from './NewConversationModal';

View File

@@ -34,7 +34,7 @@ interface UseMessagingReturn {
disconnect: () => void; disconnect: () => void;
loadConversations: () => Promise<void>; loadConversations: () => Promise<void>;
selectConversation: (conversationId: string) => Promise<void>; selectConversation: (conversationId: string) => Promise<void>;
startConversation: (agentProfileId: string) => Promise<Conversation>; startConversation: (body: { agentProfileId?: string; userId?: string }) => Promise<Conversation>;
sendMessage: (content: string, messageType?: MessageType, fileFields?: { fileUrl?: string; mimeType?: string; fileName?: string; fileSize?: number }) => Promise<void>; sendMessage: (content: string, messageType?: MessageType, fileFields?: { fileUrl?: string; mimeType?: string; fileName?: string; fileSize?: number }) => Promise<void>;
loadMoreMessages: () => Promise<void>; loadMoreMessages: () => Promise<void>;
startTyping: () => void; startTyping: () => void;
@@ -163,10 +163,10 @@ export function useMessaging(options: UseMessagingOptions = {}): UseMessagingRet
[isConnected] [isConnected]
); );
// Start a new conversation with an agent // Start a new conversation with an agent (for users) or a user (for agents)
const startConversation = useCallback( const startConversation = useCallback(
async (agentProfileId: string): Promise<Conversation> => { async (body: { agentProfileId?: string; userId?: string }): Promise<Conversation> => {
const conversation = await messagesService.startConversation(agentProfileId); const conversation = await messagesService.startConversation(body);
// Add to conversations list if not exists // Add to conversations list if not exists
setConversations((prev) => { setConversations((prev) => {

View File

@@ -16,6 +16,11 @@ export interface ConnectionRequest {
id: string; id: string;
email: string; email: string;
avatar: string | null; avatar: string | null;
userProfile?: {
firstName: string | null;
lastName: string | null;
avatar: string | null;
} | null;
}; };
agentProfile?: { agentProfile?: {
id: string; id: string;

View File

@@ -22,12 +22,10 @@ class MessagesService {
} }
/** /**
* Start or get existing conversation with an agent * Start or get existing conversation with an agent (for users) or a user (for agents)
*/ */
async startConversation(agentProfileId: string): Promise<Conversation> { async startConversation(body: { agentProfileId?: string; userId?: string }): Promise<Conversation> {
const response = await api.post<ApiResponse<Conversation>>('/messages/conversations', { const response = await api.post<ApiResponse<Conversation>>('/messages/conversations', body);
agentProfileId,
});
return response.data.data; return response.data.data;
} }