Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 | 'use client'; /** * ChatDashboard Component * * Agent dashboard for managing live chat conversations. * Displays queue, active chats, and conversation details. */ import { useState, useEffect, useCallback, useRef } from 'react'; import { cn } from '@/lib/core'; import { clientLogger } from '@/lib/logging/clientLogger'; import { Icon } from '@/components/ui/icons'; import { Button } from '@/components/ui/Button'; import { MessageBubble } from '@/components/features/chat/MessageBubble'; import type { ChatStatus, MessageSenderType, MessageContentType } from '@prisma/client'; // ============================================================================ // TYPES // ============================================================================ interface Message { id: string; content: string; senderType: MessageSenderType; contentType: MessageContentType; attachments?: unknown[]; isRead: boolean; createdAt: string; senderId: number | null; } interface Conversation { id: string; userId: number | null; visitorId: string | null; status: ChatStatus; priority: number; tags: string | null; startedAt: string; endedAt: string | null; resolvedAt: string | null; rating: number | null; feedback: string | null; assignedToId: number | null; user: { id: number; name: string | null; email: string; image: string | null; } | null; agent: { id: number; name: string | null; email: string; } | null; messages: Message[]; relatedOrder: { id: number; status: string; total: number; createdAt: string; } | null; userContext?: { recentOrders: Array<{ id: number; status: string; total: number; createdAt: string; }>; openTickets: number; totalOrders: number; }; } interface QueueStats { waiting: number; active: number; onHold: number; myActive: number; } interface Agent { id: number; name: string | null; email: string; } interface ChatDashboardProps { className?: string; } // ============================================================================ // COMPONENT // ============================================================================ export function ChatDashboard({ className }: ChatDashboardProps) { const [activeTab, setActiveTab] = useState<'queue' | 'my-chats'>('queue'); const [queueConversations, setQueueConversations] = useState<Conversation[]>([]); const [myConversations, setMyConversations] = useState<Conversation[]>([]); const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null); const [queueStats, setQueueStats] = useState<QueueStats | null>(null); const [agents, setAgents] = useState<Agent[]>([]); const [isLoading, setIsLoading] = useState(true); const [isSending, setIsSending] = useState(false); const [newMessage, setNewMessage] = useState(''); const [error, setError] = useState<string | null>(null); const messagesEndRef = useRef<HTMLDivElement>(null); // Fetch conversations const fetchConversations = useCallback(async () => { try { const [queueRes, myRes, statsRes, agentsRes] = await Promise.all([ fetch('/api/admin/support/chat/conversations?status=WAITING'), fetch('/api/admin/support/chat/conversations?status=ACTIVE,ON_HOLD&assignedToMe=true'), fetch('/api/admin/support/chat/conversations/stats'), fetch('/api/admin/users?role=ADMIN,SUPPORT'), ]); if (queueRes.ok) { const queueData = await queueRes.json(); setQueueConversations(queueData.data || []); } if (myRes.ok) { const myData = await myRes.json(); setMyConversations(myData.data || []); } if (statsRes.ok) { const statsData = await statsRes.json(); setQueueStats(statsData.data); } if (agentsRes.ok) { const agentsData = await agentsRes.json(); setAgents(agentsData.data || []); } } catch (err) { clientLogger.error('Failed to fetch conversations', err instanceof Error ? err : new Error(String(err))); } finally { setIsLoading(false); } }, []); useEffect(() => { fetchConversations(); // Poll for updates const interval = setInterval(fetchConversations, 10000); return () => clearInterval(interval); }, [fetchConversations]); // Scroll to bottom of messages useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [selectedConversation?.messages]); // Load conversation details const loadConversation = async (conversationId: string) => { try { const res = await fetch(`/api/admin/support/chat/${conversationId}`); if (res.ok) { const data = await res.json(); setSelectedConversation(data.data); } } catch (err) { clientLogger.error('Failed to load conversation', err instanceof Error ? err : new Error(String(err)), { conversationId }); } }; // Pick up a conversation from the queue const pickUpConversation = async (conversationId: string) => { try { const res = await fetch(`/api/admin/support/chat/${conversationId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'assign' }), }); if (res.ok) { await fetchConversations(); await loadConversation(conversationId); setActiveTab('my-chats'); } } catch (err) { clientLogger.error('Failed to pick up conversation', err instanceof Error ? err : new Error(String(err)), { conversationId }); } }; // Send a message const sendMessage = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedConversation || !newMessage.trim() || isSending) return; setIsSending(true); setError(null); try { const res = await fetch(`/api/admin/support/chat/${selectedConversation.id}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: newMessage }), }); if (res.ok) { setNewMessage(''); await loadConversation(selectedConversation.id); } else { const data = await res.json(); setError(data.error?.message || 'Failed to send message'); } } catch (err) { setError('Failed to send message'); clientLogger.error('Failed to send message', err instanceof Error ? err : new Error(String(err)), { conversationId: selectedConversation.id }); } finally { setIsSending(false); } }; // Resolve conversation const resolveConversation = async () => { if (!selectedConversation) return; try { const res = await fetch(`/api/admin/support/chat/${selectedConversation.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'resolve' }), }); if (res.ok) { await fetchConversations(); setSelectedConversation(null); } } catch (err) { clientLogger.error('Failed to resolve conversation', err instanceof Error ? err : new Error(String(err)), { conversationId: selectedConversation.id }); } }; // Close conversation const closeConversation = async () => { if (!selectedConversation) return; try { const res = await fetch(`/api/admin/support/chat/${selectedConversation.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'close' }), }); if (res.ok) { await fetchConversations(); setSelectedConversation(null); } } catch (err) { clientLogger.error('Failed to close conversation', err instanceof Error ? err : new Error(String(err)), { conversationId: selectedConversation.id }); } }; // Transfer conversation const transferConversation = async (toAgentId: number) => { if (!selectedConversation) return; try { const res = await fetch(`/api/admin/support/chat/${selectedConversation.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'transfer', toAgentId }), }); if (res.ok) { await fetchConversations(); setSelectedConversation(null); } } catch (err) { clientLogger.error('Failed to transfer conversation', err instanceof Error ? err : new Error(String(err)), { conversationId: selectedConversation.id, toAgentId }); } }; // Format date const formatTime = (dateString: string) => { const date = new Date(dateString); const now = new Date(); const diff = now.getTime() - date.getTime(); if (diff < 60000) return 'Just now'; if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`; if (diff < 86400000) return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return date.toLocaleDateString(); }; // Get status color const getStatusColor = (status: ChatStatus) => { switch (status) { case 'WAITING': return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'; case 'ACTIVE': return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'; case 'ON_HOLD': return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'; case 'RESOLVED': return 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'; case 'CLOSED': return 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400'; default: return 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400'; } }; // Get priority color const getPriorityColor = (priority: number) => { switch (priority) { case 3: return 'text-red-500'; case 2: return 'text-orange-500'; case 1: return 'text-yellow-500'; default: return 'text-gray-400'; } }; const conversations = activeTab === 'queue' ? queueConversations : myConversations; return ( <div className={cn('flex h-[calc(100vh-200px)] min-h-[500px] overflow-hidden rounded-lg border bg-white dark:border-gray-700 dark:bg-gray-800', className)}> {/* Sidebar - Conversation List */} <div className="flex w-80 flex-col border-r dark:border-gray-700"> {/* Stats Header */} {queueStats && ( <div className="grid grid-cols-4 gap-2 border-b p-3 dark:border-gray-700"> <div className="text-center"> <div className="text-lg font-bold text-yellow-600 dark:text-yellow-400"> {queueStats.waiting} </div> <div className="text-xs text-gray-500">Waiting</div> </div> <div className="text-center"> <div className="text-lg font-bold text-green-600 dark:text-green-400"> {queueStats.active} </div> <div className="text-xs text-gray-500">Active</div> </div> <div className="text-center"> <div className="text-lg font-bold text-blue-600 dark:text-blue-400"> {queueStats.onHold} </div> <div className="text-xs text-gray-500">On Hold</div> </div> <div className="text-center"> <div className="text-lg font-bold text-purple-600 dark:text-purple-400"> {queueStats.myActive} </div> <div className="text-xs text-gray-500">My Chats</div> </div> </div> )} {/* Tabs */} <div className="flex border-b dark:border-gray-700"> <button onClick={() => setActiveTab('queue')} className={cn( 'flex-1 px-4 py-2 text-sm font-medium transition-colors', activeTab === 'queue' ? 'border-b-2 border-primary-600 text-primary-600 dark:border-primary-400 dark:text-primary-400' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300' )} > Queue ({queueConversations.length}) </button> <button onClick={() => setActiveTab('my-chats')} className={cn( 'flex-1 px-4 py-2 text-sm font-medium transition-colors', activeTab === 'my-chats' ? 'border-b-2 border-primary-600 text-primary-600 dark:border-primary-400 dark:text-primary-400' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300' )} > My Chats ({myConversations.length}) </button> </div> {/* Conversation List */} <div className="flex-1 overflow-y-auto"> {isLoading ? ( <div className="flex items-center justify-center py-8"> <Icon name="spinner" className="h-6 w-6 animate-spin text-gray-400" /> </div> ) : conversations.length === 0 ? ( <div className="p-4 text-center text-gray-500 dark:text-gray-400"> {activeTab === 'queue' ? 'No conversations waiting' : 'No active conversations'} </div> ) : ( conversations.map((conversation) => ( <button key={conversation.id} onClick={() => loadConversation(conversation.id)} className={cn( 'w-full border-b p-3 text-left transition-colors dark:border-gray-700', selectedConversation?.id === conversation.id ? 'bg-primary-50 dark:bg-primary-900/20' : 'hover:bg-gray-50 dark:hover:bg-gray-700/50' )} > <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> {conversation.priority > 0 && ( <Icon name="flag" size={14} className={getPriorityColor(conversation.priority)} /> )} <span className="font-medium text-gray-900 dark:text-white"> {conversation.user?.name || conversation.visitorId || 'Anonymous'} </span> </div> <span className="text-xs text-gray-500"> {formatTime(conversation.startedAt)} </span> </div> <div className="mt-1 flex items-center justify-between"> <span className="truncate text-sm text-gray-600 dark:text-gray-400"> {conversation.messages[0]?.content || 'No messages'} </span> <span className={cn('rounded-full px-2 py-0.5 text-xs', getStatusColor(conversation.status))}> {conversation.status} </span> </div> {conversation.user?.email && ( <div className="mt-1 text-xs text-gray-400">{conversation.user.email}</div> )} </button> )) )} </div> </div> {/* Main Content - Chat View */} <div className="flex flex-1 flex-col"> {selectedConversation ? ( <> {/* Chat Header */} <div className="flex items-center justify-between border-b p-4 dark:border-gray-700"> <div> <div className="flex items-center gap-2"> <h3 className="font-medium text-gray-900 dark:text-white"> {selectedConversation.user?.name || selectedConversation.visitorId || 'Anonymous'} </h3> <span className={cn('rounded-full px-2 py-0.5 text-xs', getStatusColor(selectedConversation.status))}> {selectedConversation.status} </span> </div> {selectedConversation.user?.email && ( <p className="text-sm text-gray-500">{selectedConversation.user.email}</p> )} </div> <div className="flex items-center gap-2"> {selectedConversation.status === 'WAITING' && ( <Button size="sm" onClick={() => pickUpConversation(selectedConversation.id)} > <Icon name="user-plus" size={16} className="mr-1" /> Pick Up </Button> )} {selectedConversation.status === 'ACTIVE' && ( <> <Button size="sm" variant="outline" onClick={resolveConversation} > <Icon name="check" size={16} className="mr-1" /> Resolve </Button> <select className="rounded-md border px-2 py-1 text-sm dark:border-gray-600 dark:bg-gray-700" onChange={(e) => { if (e.target.value) { transferConversation(parseInt(e.target.value)); } }} defaultValue="" > <option value="">Transfer to...</option> {agents.map((agent) => ( <option key={agent.id} value={agent.id}> {agent.name || agent.email} </option> ))} </select> </> )} <Button size="sm" variant="ghost" onClick={closeConversation} > <Icon name="x" size={16} /> </Button> </div> </div> {/* Messages */} <div className="flex-1 overflow-y-auto p-4"> <div className="space-y-3"> {selectedConversation.messages.map((message) => ( <MessageBubble key={message.id} message={{ ...message, createdAt: message.createdAt, }} /> ))} <div ref={messagesEndRef} /> </div> </div> {/* Message Input */} {(selectedConversation.status === 'ACTIVE' || selectedConversation.status === 'ON_HOLD') && ( <form onSubmit={sendMessage} className="border-t p-4 dark:border-gray-700"> {error && ( <div className="mb-2 text-sm text-red-500">{error}</div> )} <div className="flex gap-2"> <input type="text" value={newMessage} onChange={(e) => setNewMessage(e.target.value)} placeholder="Type a message..." className="flex-1 rounded-lg border px-4 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white" /> <Button type="submit" disabled={!newMessage.trim() || isSending}> {isSending ? ( <Icon name="spinner" className="h-5 w-5 animate-spin" /> ) : ( <Icon name="send" size={20} /> )} </Button> </div> </form> )} </> ) : ( <div className="flex flex-1 flex-col items-center justify-center text-gray-500 dark:text-gray-400"> <Icon name="message-circle" size={48} className="mb-4 opacity-50" /> <p>Select a conversation to start chatting</p> </div> )} </div> {/* Right Sidebar - Customer Context */} {selectedConversation && ( <div className="w-72 border-l overflow-y-auto dark:border-gray-700"> <div className="p-4"> <h4 className="mb-4 font-medium text-gray-900 dark:text-white"> Customer Info </h4> {/* Customer Details */} <div className="mb-4 space-y-2"> <div className="flex items-center gap-2"> <Icon name="user" size={16} className="text-gray-400" /> <span className="text-sm text-gray-600 dark:text-gray-300"> {selectedConversation.user?.name || 'Guest'} </span> </div> {selectedConversation.user?.email && ( <div className="flex items-center gap-2"> <Icon name="email" size={16} className="text-gray-400" /> <span className="text-sm text-gray-600 dark:text-gray-300"> {selectedConversation.user.email} </span> </div> )} </div> {/* User Context */} {selectedConversation.userContext && ( <> <div className="mb-4 grid grid-cols-2 gap-2"> <div className="rounded-lg bg-gray-100 p-2 text-center dark:bg-gray-700"> <div className="text-lg font-bold text-gray-900 dark:text-white"> {selectedConversation.userContext.totalOrders} </div> <div className="text-xs text-gray-500">Total Orders</div> </div> <div className="rounded-lg bg-gray-100 p-2 text-center dark:bg-gray-700"> <div className="text-lg font-bold text-gray-900 dark:text-white"> {selectedConversation.userContext.openTickets} </div> <div className="text-xs text-gray-500">Open Tickets</div> </div> </div> {/* Recent Orders */} {selectedConversation.userContext.recentOrders.length > 0 && ( <div className="mb-4"> <h5 className="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300"> Recent Orders </h5> <div className="space-y-2"> {selectedConversation.userContext.recentOrders.map((order) => ( <a key={order.id} href={`/admin/orders/${order.id}`} className="block rounded-lg border p-2 transition-colors hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700" > <div className="flex items-center justify-between"> <span className="text-sm font-medium">#{order.id}</span> <span className="text-xs text-gray-500"> ${order.total.toFixed(2)} </span> </div> <div className="text-xs text-gray-400">{order.status}</div> </a> ))} </div> </div> )} </> )} {/* Related Order */} {selectedConversation.relatedOrder && ( <div className="mb-4"> <h5 className="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300"> Related Order </h5> <a href={`/admin/orders/${selectedConversation.relatedOrder.id}`} className="block rounded-lg border p-2 transition-colors hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700" > <div className="flex items-center justify-between"> <span className="font-medium"> #{selectedConversation.relatedOrder.id} </span> <span className="text-primary-600 dark:text-primary-400"> ${selectedConversation.relatedOrder.total.toFixed(2)} </span> </div> <div className="text-sm text-gray-500"> {selectedConversation.relatedOrder.status} </div> </a> </div> )} {/* Tags */} {selectedConversation.tags && ( <div className="mb-4"> <h5 className="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300"> Tags </h5> <div className="flex flex-wrap gap-1"> {selectedConversation.tags.split(',').map((tag, i) => ( <span key={i} className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-300" > {tag} </span> ))} </div> </div> )} </div> </div> )} </div> ); } export default ChatDashboard; |