Spaces:
Paused

miracle / frontend /apps /customer /src /components /ThreadView.tsx
dushyantsingh0
backend sprint
4c985e0
Raw History Blame Contribute Delete
46.3 kB
import React, { useState, useEffect, useRef, useCallback } from 'react'; import { StatusBadge } from './Badges'; import { api, NexusMarkdown, getFileIcon, getStorageKey, useMentions, MentionOverlay, RichEditor, useTheme, useNotification } from '@nexus/shared'; import type { Ticket, Message } from '@nexus/shared'; import styles from './ThreadView.module.css'; import { ArrowLeft, Send, Paperclip, Sparkles, Maximize2, RefreshCcw, Loader2, Trash2, BookOpen, Download } from 'lucide-react'; interface ThreadViewProps { ticket: Ticket; onBack: () => void; onNavigate?: (ticket: { id: string }) => void; onNavigateArticle?: (articleId: string) => void; } export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, onBack, onNavigate, onNavigateArticle }) => { const { theme } = useTheme(); const { alert, confirm } = useNotification(); const [ticket, setTicket] = useState<Ticket>(initialTicket); const [messages, setMessages] = useState<Message[]>([]); const [newMessage, setNewMessage] = useState(""); const [sending, setSending] = useState(false); const [currentUser, setCurrentUser] = useState<{ id: string, full_name: string } | null>(null); // Description Edit State const [isEditingDesc, setIsEditingDesc] = useState(false); const [descDraft, setDescDraft] = useState(initialTicket.description); const [savingDesc, setSavingDesc] = useState(false); const [isUploading, setIsUploading] = useState(false); // Feedback States const [ratingDraft, setRatingDraft] = useState<number | null>(ticket.rating || null); const [hoverRating, setHoverRating] = useState<number | null>(null); const [commentDraft, setCommentDraft] = useState(""); const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false); const [showReopenModal, setShowReopenModal] = useState(false); const [reopenReason, setReopenReason] = useState(""); const [isReopening, setIsReopening] = useState(false); // AI Intensity States const [isRegeneratingSummary, setIsRegeneratingSummary] = useState(false); const [isEscalating, setIsEscalating] = useState(false); const [historyEvents, setHistoryEvents] = useState<any[]>([]); const [showConfirmEscalate, setShowConfirmEscalate] = useState(false); // Sidebar States const [isSidebarOpen, setIsSidebarOpen] = useState(false); const [isLeftSidebarOpen, setIsLeftSidebarOpen] = useState(false); const [forbidden, setForbidden] = useState(false); const [sidebarWidth, setSidebarWidth] = useState(400); const [isResizing, setIsResizing] = useState(false); const [sidebarTab, setSidebarTab] = useState<'messages' | 'files' | 'history'>('messages'); const { filteredUsers, showMentionList, selectedMentionIndex, setSelectedMentionIndex, cursorPos, handleInputChange, getMentionText, closeMentions } = useMentions({ workspaceId: ticket?.workspace_id }); const bottomRef = useRef<HTMLDivElement>(null); const fileInputRef = useRef<HTMLInputElement>(null); const isRefreshing = useRef(false); const [isLoading, setIsLoading] = useState(false); const refreshData = useCallback(async (bypassCache = false) => { if (isRefreshing.current) return; isRefreshing.current = true; setIsLoading(true); const watchdog = setTimeout(() => { // Release the refresh lock so users can retry after a hung request. // Without this, isRefreshing stays true indefinitely if the request never // resolves, silently blocking every subsequent manual refresh. setIsLoading(false); isRefreshing.current = false; }, 30000); try { const ticketId = initialTicket.id; const ticketUrl = `tickets/${ticketId}/${bypassCache ? '?bypass_cache=true' : ''}`; const [ticketResp, messagesResp, auditResp] = await Promise.all([ api.get(ticketUrl), api.get(`tickets/${ticketId}/messages/`), api.get(`tickets/${ticketId}/audit/`) ]); setTicket(ticketResp.data); setDescDraft(ticketResp.data.description); setMessages(messagesResp.data); // Transform raw audit logs into UI-friendly history events const rawLogs = auditResp.data; const auditEvents = rawLogs.map((log: any) => { let label = log.action.toUpperCase(); let icon = '📝'; let detail = `Action performed by ${log.actor_name}`; if (log.action === 'create') { icon = '🎫'; label = 'INCIDENT LOGGED'; detail = 'Incident initialized via portal.'; } else if (log.action === 'escalation') { icon = '🚨'; label = 'CRITICAL ESCALATION'; detail = 'Priority elevated to P0 for lead intervention.'; } else if (log.action === 'update' && log.new_value?.status === 'RESOLVED') { icon = '✅'; label = 'RESOLVED'; detail = 'Agent has finalized the resolution.'; } else if (log.action === 'update' && log.new_value?.status === 'ACKNOWLEDGED') { icon = '🛡️'; label = 'ACKNOWLEDGED'; detail = 'Technical specialist has claimed this ticket.'; } else if (log.action === 'update' && log.new_value?.status === 'IN_PROGRESS') { icon = '⚙️'; label = 'IN PROGRESS'; detail = 'Active investigation is underway.'; } else if (log.action === 'update' && log.new_value?.priority) { icon = '⚡'; label = 'PRIORITY CHANGE'; detail = `Priority adjusted to ${log.new_value.priority}.`; } else if (log.action === 'update' && log.new_value?.assigned_to) { icon = '👥'; label = 'ASSIGNMENT'; detail = `Assigned to ${log.new_value.assigned_to_name || 'Technical Specialist'}.`; } else if (log.action === 'update' && log.new_value?.title) { icon = '✏️'; label = 'TITLE UPDATED'; detail = 'Subject was refined for clarity.'; } else if (log.action === 'reopen') { icon = '🔄'; label = 'REOPENED'; detail = log.new_value?.reason || 'Resumed for further review.'; } return { id: log.id, time: log.created_at, label, detail, icon }; }); const messageEvents = (messagesResp.data || []).map((m: any) => { const isCustomer = m.sender_role?.toLowerCase().includes('customer'); return { id: m.id, time: m.created_at, label: isCustomer ? 'CLIENT MESSAGE' : 'AGENT RESPONSE', detail: m.content.length > 100 ? m.content.substring(0, 100) + '...' : m.content, icon: isCustomer ? '💬' : '🎧' }; }); const combinedEvents = [...auditEvents, ...messageEvents].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime() ); setHistoryEvents(combinedEvents); setForbidden(false); } catch (err: any) { console.error("Failed to refresh data", err); if (err.response?.status === 403) { setForbidden(true); } } finally { clearTimeout(watchdog); setIsLoading(false); isRefreshing.current = false; } }, [initialTicket.id]); useEffect(() => { // Standard data fetch on mount, NO force-refresh (bypassCache=false) refreshData(false); const userString = localStorage.getItem(getStorageKey('user')); if (userString) setCurrentUser(JSON.parse(userString)); }, [initialTicket.id]); // ONLY trigger on ID change, ignore refreshData ref to avoid loops // Real-time Event Listener useEffect(() => { const handleLiveEvent = (event: Event) => { const customEvent = event as CustomEvent; const data = customEvent.detail; if (data.event === 'summary_updated' && data.ticket_id === ticket.id) { refreshData(); setIsRegeneratingSummary(false); } else if ((data.event === 'ticket_updated' || data.event === 'new_message') && data.ticket_id === ticket.id) { if (data.event === 'new_message') { setMessages(prev => { if (prev.some(m => m.id === data.message.id)) return prev; return [...prev, data.message]; }); setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 50); } else { refreshData(); } } }; window.addEventListener('nexus-live-event', handleLiveEvent); return () => window.removeEventListener('nexus-live-event', handleLiveEvent); }, [ticket?.id]); // Removed refreshData from dependencies to prevent listener churn loops // Reset state only when navigating to a DIFFERENT ticket ID useEffect(() => { setTicket(initialTicket); setMessages([]); setDescDraft(initialTicket.description); setNewMessage(""); setRatingDraft(initialTicket.rating || null); setIsEditingDesc(false); setShowConfirmEscalate(false); setIsRegeneratingSummary(false); closeMentions(); }, [initialTicket.id]); // ONLY trigger on ID change useEffect(() => { if (isSidebarOpen) { setTimeout(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, 100); } }, [messages, isSidebarOpen, sidebarTab]); // Sidebar Resize Logic const handleMouseDown = useCallback((e: React.MouseEvent) => { e.preventDefault(); setIsResizing(true); }, []); useEffect(() => { const handleMouseMove = (e: MouseEvent) => { if (!isResizing) return; const newWidth = window.innerWidth - e.clientX - 32; if (newWidth > 320 && newWidth < window.innerWidth * 0.5) { setSidebarWidth(newWidth); } }; const handleMouseUp = () => setIsResizing(false); if (isResizing) { document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); document.body.style.cursor = 'col-resize'; } else { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); document.body.style.cursor = 'default'; } return () => { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; }, [isResizing]); // --- MENTION LOGIC --- const handleMentionInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => { const val = e.target.value; const position = e.target.selectionStart; setNewMessage(val); handleInputChange(val, position); }; const handleInsertMention = (user: any) => { const textBeforeMention = newMessage.slice(0, cursorPos).replace(/@(\w*)$/, ""); const textAfterMention = newMessage.slice(cursorPos); const mentionText = getMentionText(user); const newValue = textBeforeMention + mentionText + textAfterMention; setNewMessage(newValue); closeMentions(); }; const handleSend = async () => { if (!newMessage.trim() || sending) return; const content = newMessage; const tempId = `temp-${Date.now()}`; const optimisticMsg: any = { id: tempId, content: content, sender_id: currentUser?.id || 'unknown', sender_name: currentUser?.full_name || "You", sender_role: "customer", is_internal: false, created_at: new Date().toISOString(), attachments: [], is_sending: true }; setMessages(prev => [...prev, optimisticMsg]); setNewMessage(""); setSending(true); try { const resp = await api.post(`tickets/${ticket.id}/messages/`, { content, is_internal: false }); setMessages(prev => prev.map(m => m.id === tempId ? resp.data : m)); } catch { setMessages(prev => prev.filter(m => m.id !== tempId)); setNewMessage(content); } finally { setSending(false); } }; const handleSaveDescription = async () => { setSavingDesc(true); try { const resp = await api.patch(`tickets/${ticket.id}/`, { description: descDraft }); setTicket(resp.data); setIsEditingDesc(false); } catch { console.error("Failed to update description"); } finally { setSavingDesc(false); } }; const handleRegenerateSummary = async () => { setIsRegeneratingSummary(true); try { await api.post(`tickets/${ticket.id}/summarize/`); } catch { setIsRegeneratingSummary(false); } }; const handleReopen = async () => { if (!reopenReason.trim()) return; setIsReopening(true); try { await api.post(`tickets/${ticket.id}/reopen/`, { reason: reopenReason }); setReopenReason(""); setShowReopenModal(false); refreshData(); } catch (err) { console.error("Reopen failed", err); } finally { setIsReopening(false); } }; const handleEscalate = async () => { setIsEscalating(true); try { const resp = await api.post(`tickets/${ticket.id}/escalate/`); setTicket(resp.data); setShowConfirmEscalate(false); const messagesResp = await api.get(`tickets/${ticket.id}/messages/`); setMessages(messagesResp.data); } catch { console.error("Escalation failed"); } finally { setIsEscalating(false); } }; const handleSubmitFeedback = async () => { if (!ratingDraft) return; setIsSubmittingFeedback(true); try { const resp = await api.post(`tickets/${ticket.id}/feedback/`, { rating: ratingDraft, comment: commentDraft }); setTicket({ ...ticket, rating: resp.data.rating, feedback_comment: resp.data.comment }); } catch { console.error("Feedback submission failed"); } finally { setIsSubmittingFeedback(false); } }; const handlePaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>, isMainDesc: boolean) => { const items = e.clipboardData.items; let fileItem = null; for (let i = 0; i < items.length; i++) { if (items[i].kind === "file") { fileItem = items[i]; break; } } if (fileItem) { e.preventDefault(); const file = fileItem.getAsFile(); if (!file) return; await handleUpload(file, isMainDesc); } }; const handleUpload = async (file: File, isMainDesc: boolean) => { if (file.size > 10 * 1024 * 1024) { alert("File is too large (max 10MB).", { type: 'error', title: 'Upload Restriction' }); return; } setIsUploading(true); const formData = new FormData(); formData.append("file", file); const isImage = file.type.startsWith("image/"); const uploadId = Date.now() % 10000; const placeholder = isImage ? `\n![Uploading ${file.name} (#${uploadId})...]()\n` : `\n[Uploading ${file.name} (#${uploadId})...]()\n`; if (isMainDesc) setDescDraft((curr: string) => curr + placeholder); else setNewMessage((curr: string) => curr + placeholder); try { const resp = await api.post(`tickets/${ticket.id}/attachments/`, formData); const baseUrl = api.defaults.baseURL || ""; const backendBase = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'; const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`; const finalMarkdown = isImage ? `\n![Screenshot](${downloadUrl})\n` : `\n${getFileIcon(file.name)} [${file.name}](${downloadUrl})\n`; if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, finalMarkdown)); else setNewMessage((curr: string) => curr.replace(placeholder, finalMarkdown)); setTicket(curr => ({ ...curr, attachments: [...(curr.attachments || []), resp.data] })); } catch { if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, "")); else setNewMessage((curr: string) => curr.replace(placeholder, "")); } finally { setIsUploading(false); } }; const formatETA = (dateStr: string) => { if (!dateStr) return "PENDING"; const date = new Date(dateStr); return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).toUpperCase(); }; const handleDeleteMessage = async (messageId: string) => { const confirmed = await confirm("Purge this message from your history?", { title: "Purge Message", confirmLabel: "Purge", type: "error", danger: true }); if (!confirmed) return; api.delete(`tickets/${ticket.id}/messages/${messageId}/`).then(() => { setMessages(prev => prev.filter(m => m.id !== messageId)); }).catch(() => { alert("Deletion failed.", { type: 'error', title: 'System Error' }); }); }; const handleDeleteAttachment = async (attachmentId: string) => { const confirmed = await confirm("Permanently remove this asset?", { title: "Remove Asset", confirmLabel: "Remove", type: "error", danger: true }); if (!confirmed) return; try { // Correct endpoint path matches main.py prefix + attachments.py route await api.delete(`tickets/attachments/${attachmentId}/`); setTicket(curr => ({ ...curr, attachments: (curr.attachments || []).filter(a => a.id !== attachmentId) })); setMessages(prev => prev.map(m => ({ ...m, attachments: (m.attachments || []).filter(a => a.id !== attachmentId) }))); } catch (err) { console.error("Asset deletion failed", err); alert("Failed to delete attachment. Please verify permissions.", { type: 'error', title: 'Access Denied' }); } }; const handleFileDownload = async (attId: string, fileName: string) => { try { const response = await api.get(`tickets/attachments/${attId}/download/`, { responseType: 'blob' }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', fileName || 'attachment'); document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); } catch (error) { console.error("Download failed:", error); alert("Authenticated asset download failed. Session may have expired.", { type: 'error', title: 'Download Error' }); } }; if (forbidden) { return ( <div className={styles.container} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', textAlign: 'center', padding: 40 }}> <div className="mesh-bg" /> <div style={{ fontSize: 64, marginBottom: 24 }}>🛡️</div> <h1 style={{ fontWeight: 900, letterSpacing: '-0.02em', marginBottom: 12 }}>ACCESS RESTRICTED</h1> <p style={{ opacity: 0.6, maxWidth: 400, margin: '0 auto 32px', lineHeight: 1.6 }}>Your current neural credentials do not permit access to this specific operational thread.</p> <button onClick={onBack} className={styles.btnPrimary} style={{ padding: '12px 32px' }}>RETURN TO DASHBOARD</button> </div> ); } if (!ticket) return null; return ( <div className={styles.container}> <div className="mesh-bg" /> <header className={styles.header}> <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}> <button className={styles.headerBtn} onClick={onBack} title="Go Back"> <ArrowLeft size={20} /> </button> <div className={styles.headerTitleArea}> <div className={styles.ticketIdBadge}>#{ticket.id.slice(0, 8).toUpperCase()}</div> {ticket.is_escalated && ( <div className={styles.escalatedBadge}>ESCALATED</div> )} <h1 className={styles.mainTitle} style={{ color: theme === 'light' ? '#000000' : 'var(--primary)' }}>{ticket.title}</h1> </div> </div> <div className={styles.headerActions}> <div style={{ display: 'flex', gap: 6, marginRight: 12 }}> <button className={styles.toggleBtn} onClick={() => setIsLeftSidebarOpen(!isLeftSidebarOpen)} title="Toggle Analysis"> <Maximize2 size={16} style={{ transform: 'rotate(90deg)' }} color={isLeftSidebarOpen ? 'var(--primary)' : 'var(--text-muted)'} /> </button> <button className={styles.toggleBtn} onClick={() => setIsSidebarOpen(!isSidebarOpen)} title="Toggle Feed"> <Maximize2 size={16} color={isSidebarOpen ? 'var(--primary)' : 'var(--text-muted)'} /> </button> </div> <button className={styles.headerBtn} onClick={() => refreshData(true)} disabled={isLoading} title="Refresh Intelligence" style={{ opacity: isLoading ? 0.5 : 1, cursor: isLoading ? 'not-allowed' : 'pointer', marginRight: 12 }} > <RefreshCcw size={18} className={isLoading ? styles.spin : ''} /> </button> {['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && ( <button onClick={() => setShowReopenModal(true)} disabled={isReopening} className={`${styles.btn} ${styles.btnSecondary}`} style={{ padding: '8px 16px' }}> {isReopening ? 'REOPENING...' : 'REOPEN TICKET'} </button> )} {!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !ticket.is_escalated && ( <button onClick={() => setShowConfirmEscalate(true)} disabled={isEscalating} className={`${styles.btn} ${styles.btnEscalate}`} style={{ padding: '8px 16px' }}> {isEscalating ? 'ESCALATING...' : 'ESCALATE'} </button> )} </div> </header> <div className={styles.propertyStrip}> <div className={styles.propertySlot}> <div className={styles.slotLabel}>TICKET PRIORITY</div> <div className={styles.slotValueArea}> <div className={styles.priorityDot} style={{ background: ticket.priority === 'P0' ? 'var(--error)' : 'var(--primary)' }} /> <span className={styles.slotValue}>{ticket.priority?.toUpperCase() || "STANDARD"}</span> </div> </div> <div className={styles.propertySlot}> <div className={styles.slotLabel}>ASSIGNED AGENT</div> <div className={styles.slotValueArea}> <div className={styles.assigneeAvatar}>{ticket.assigned_name ? ticket.assigned_name[0] : "N"}</div> <span className={styles.slotValue}>{ticket.assigned_name || "Nexus AI Agent"}</span> </div> </div> <div className={styles.propertySlot}> <div className={styles.slotLabel}>OPERATIONAL STATUS</div> <div className={styles.slotValueArea}> <StatusBadge status={ticket.status} /> </div> </div> <div className={styles.propertySlot}> <div className={styles.slotLabel}>ESTIMATED RESOLUTION</div> <div className={styles.slotValueArea}> <span className={styles.slotValue}>{formatETA(ticket.expected_resolution_at || "")}</span> </div> </div> </div> <div className={styles.horizontalWorkspace}> {/* Left Sidebar: Analysis & Context */} <aside className={`${styles.leftSidebar} ${!isLeftSidebarOpen ? styles.leftSidebarCollapsed : ''}`}> {/* Relevant Knowledge Section */} <div className={styles.sidebarSection}> <div className={styles.sidebarSectionTitle}>Relevant Knowledge</div> {ticket.similar_articles && ticket.similar_articles.length > 0 ? ( <div style={{ display: "flex", flexDirection: "column", gap: 8 }}> {ticket.similar_articles?.map((art) => ( <div key={art.id} className={styles.knowledgeItem} onClick={() => onNavigateArticle?.(art.id)} > <BookOpen size={16} color="var(--primary)" /> <span className={styles.knowledgeTitle}>{art.title}</span> </div> ))} </div> ) : ( <div style={{ fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', padding: '20px 0' }}>No relevant articles found.</div> )} </div> {/* Similar Tickets Section */} <div className={styles.sidebarSection}> <div className={styles.sidebarSectionTitle}>Historical Parallels</div> {ticket.similar_tickets && ticket.similar_tickets.length > 0 ? ( <div style={{ display: "flex", flexDirection: "column", gap: 8 }}> {ticket.similar_tickets?.map((sim) => ( <div key={sim.id} className={styles.parallelItem} onClick={() => onNavigate?.({ id: sim.id })} > <div className={styles.parallelHeader}> <span className={styles.matchBadge}>{(sim.similarity * 100).toFixed(0)}% MATCH</span> <StatusBadge status={sim.status} /> </div> <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sim.title}</div> </div> ))} </div> ) : ( <div style={{ fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', padding: '20px 0' }}>No historical overlaps detected.</div> )} </div> </aside> <main className={styles.mainContent}> {/* AI Intelligence Summary */} {ticket.status?.toUpperCase() !== 'OPEN' && ( <div className={styles.aiIntelligenceCard}> <div className={styles.aiHeader}> <div className={styles.aiBadge}> <Sparkles size={16} /> AI Intelligence Summary </div> <button className={styles.btnSecondary} style={{ padding: '6px 12px', fontSize: 10, height: 'auto' }} onClick={handleRegenerateSummary} disabled={isRegeneratingSummary} > <RefreshCcw size={12} className={isRegeneratingSummary ? styles.spin : ''} /> {isRegeneratingSummary ? 'Regenerating...' : 'Regenerate'} </button> </div> <div className={styles.intelligenceSurface}> {isRegeneratingSummary ? ( <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--primary)', fontWeight: 700 }}> <Loader2 size={18} className={styles.spin} /> <span>Synthesizing neural insights...</span> </div> ) : ticket.summary ? ( <NexusMarkdown content={ticket.summary} /> ) : ( <div style={{ opacity: 0.5, fontStyle: "italic" }}> Neural core is synthesizing high-fidelity resolution steps... </div> )} </div> </div> )} {/* Duplicate Alert HUD */} {ticket.status === 'CLOSED' && ticket.duplicate_of_id && ( <div className={styles.duplicateAlert}> <div className={styles.duplicateIcon}><Maximize2 size={20} /></div> <div className={styles.duplicateContent}> <div className={styles.duplicateTitle}>Duplicate Signal Detected</div> <div className={styles.duplicateSub}> This incident has been linked to <span className={styles.duplicateLink} onClick={() => onNavigate?.({ id: ticket.duplicate_of_id! })}>#{ticket.duplicate_of_id.slice(0, 8).toUpperCase()}</span>. </div> </div> </div> )} {/* Ticket Description Card */} <section className={styles.descriptionCard}> <div className={styles.sectionHeader}> <div className={styles.sectionLabel}>Ticket details</div> {!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !isEditingDesc && ( <button className={styles.btnSecondary} style={{ padding: '6px 12px', fontSize: 10 }} onClick={() => setIsEditingDesc(true)} > Edit Description </button> )} </div> {isEditingDesc ? ( <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <RichEditor value={descDraft} onChange={setDescDraft} ticketId={ticket.id} placeholder="Provide context, logs, or steps to reproduce..." /> <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}> <button onClick={() => setIsEditingDesc(false)} className={styles.btnSecondary} style={{ padding: '8px 20px' }}>CANCEL</button> <button className={styles.btnPrimary} onClick={handleSaveDescription} disabled={savingDesc} style={{ padding: '8px 24px' }} > {savingDesc ? <Loader2 size={16} className={styles.spin} /> : 'Save Description'} </button> </div> </div> ) : ( <div className={styles.descriptionContent}> <NexusMarkdown content={ticket.description || "No description provided."} /> </div> )} </section> {/* Resolution Overview (Visible when resolved/closed) */} {(ticket.status === 'RESOLVED' || ticket.status === 'CLOSED' || ticket.resolution_text) && ( <section className={styles.descriptionCard} style={{ background: 'rgba(16, 185, 129, 0.05)', borderColor: 'var(--success)', marginTop: 24 }}> <div className={styles.sectionHeader}> <div className={styles.sectionLabel} style={{ color: 'var(--success)' }}>Resolution</div> </div> <div className={styles.descriptionContent}> <NexusMarkdown content={ticket.resolution_text || "_Final documentation of the resolution is being synchronized to the portal..._"} /> </div> </section> )} {/* Feedback Section (Conditional) */} {ticket.status === 'RESOLVED' && !ticket.rating && ( <div className={styles.feedbackSurface}> <div style={{ fontSize: 24, fontWeight: 900, marginBottom: 12 }}>How was the resolution?</div> <p style={{ color: 'var(--text-muted)', marginBottom: 32 }}>Your feedback helps us optimize the Nexus neural core.</p> <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginBottom: 40 }}> {[1, 2, 3, 4, 5].map(star => ( <div key={star} onMouseEnter={() => setHoverRating(star)} onMouseLeave={() => setHoverRating(null)} onClick={() => setRatingDraft(star)} style={{ cursor: 'pointer', fontSize: 32, transition: 'all 0.2s', transform: (hoverRating || ratingDraft || 0) >= star ? 'scale(1.2)' : 'scale(1)' }} > {(hoverRating || ratingDraft || 0) >= star ? '⭐' : '☆'} </div> ))} </div> <textarea className={styles.feedbackTextarea} placeholder="Additional testimony (optional)..." value={commentDraft} onChange={(e) => setCommentDraft(e.target.value)} /> <button className={styles.btnPrimary} style={{ width: '100%', padding: '16px' }} onClick={handleSubmitFeedback} disabled={isSubmittingFeedback || !ratingDraft} > {isSubmittingFeedback ? 'Syncing...' : 'Submit Satisfaction Signal'} </button> </div> )} {ticket.rating && ( <div className={styles.feedbackSurface} style={{ textAlign: 'left', background: 'rgba(16, 185, 129, 0.05)', borderColor: 'var(--success)' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}> <div style={{ fontSize: 10, fontWeight: 900, color: 'var(--success)', textTransform: 'uppercase' }}>User Testimony Logged</div> <div style={{ fontSize: 20 }}>{'⭐'.repeat(ticket.rating)}</div> </div> <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text-main)', fontStyle: 'italic' }}> "{ticket.feedback_comment || "No written testimony provided."}" </div> </div> )} </main> {/* Right Sidebar: Feed */} {isSidebarOpen && ( <div onMouseDown={handleMouseDown} style={{ width: 12, cursor: 'col-resize', zIndex: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: "0 -6px", opacity: isResizing ? 1 : 0 }} className="sidebar-resizer"> <div style={{ width: 2, height: 60, background: 'var(--primary)', borderRadius: 2, opacity: 0.4 }} /> </div> )} {isSidebarOpen && ( <div style={{ width: sidebarWidth, minWidth: 320, height: '100%', flexShrink: 0, borderLeft: '1px solid var(--border-subtle)' }}> <div className={styles.sidebarContainer}> <div className={styles.sidebarTabs}> {(['messages', 'files', 'history'] as const).map((tab) => ( <button key={tab} onClick={() => setSidebarTab(tab)} className={`${styles.tabButton} ${sidebarTab === tab ? styles.activeTab : ''}`} > {tab} </button> ))} </div> <div style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}> {sidebarTab === 'messages' && ( <> <div className={styles.messageThread}> {messages.map((m, i) => { const isMe = m.sender_id === currentUser?.id || m.sender_role?.toLowerCase() === 'customer'; return ( <div key={i} className={`${styles.message} ${isMe ? styles.messageMe : styles.messageThem}`}> <div className={styles.messageMeta}> <span>{m.sender_name || 'Agent'}</span> <span>{new Date(m.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span> {isMe && ( <button onClick={() => handleDeleteMessage(m.id)} style={{ background: 'transparent', border: 'none', color: 'var(--error)', cursor: 'pointer', padding: 0, opacity: 0.5 }} title="Delete Message" > <Trash2 size={11} /> </button> )} </div> <div className={`${styles.messageBubble} ${isMe ? styles.messageBubbleMe : styles.messageBubbleThem}`}> <div style={{ position: 'relative' }}> <NexusMarkdown content={m.content} isMe={isMe} /> {m.is_sending && ( <div className={styles.syncStatus}> <Loader2 size={10} className={styles.spin} /> <span>SENDING...</span> </div> )} </div> </div> </div> ); })} <div ref={bottomRef} /> </div> <div className={styles.replyConsole} style={{ position: 'relative' }}> <div className={styles.replyArea}> {showMentionList && ( <MentionOverlay users={filteredUsers} selectedIndex={selectedMentionIndex} onSelect={handleInsertMention} onClose={closeMentions} /> )} <textarea value={newMessage} onChange={handleMentionInput} onPaste={(e) => handlePaste(e, false)} onKeyDown={(e) => { if (showMentionList && filteredUsers.length > 0) { if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedMentionIndex(idx => (idx + 1) % filteredUsers.length); } else if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedMentionIndex(idx => (idx - 1 + filteredUsers.length) % filteredUsers.length); } else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); handleInsertMention(filteredUsers[selectedMentionIndex]); } else if (e.key === 'Escape') { closeMentions(); } } }} placeholder="Reply to thread..." className={styles.replyTextarea} /> <button onClick={handleSend} disabled={sending || !newMessage.trim() || isUploading} className={styles.sendBtnSmall} title="Send Message" > {sending ? <Loader2 size={14} className={styles.spin} /> : <Send size={14} />} </button> </div> <div className={styles.consoleFooter}> <div className={styles.toolGroup}> <button onClick={() => fileInputRef.current?.click()} disabled={isUploading} className={styles.toolBtn}> <Paperclip size={14} /> </button> <input type="file" ref={fileInputRef} onChange={e => e.target.files?.[0] && handleUpload(e.target.files[0], false)} style={{ display: 'none' }} /> </div> </div> </div> </> )} {sidebarTab === 'files' && ( <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--bg-dark)', flex: 1, overflowY: 'auto' }}> {(ticket.attachments || []).map((att) => ( <div key={att.id} style={{ padding: '16px 20px', borderRadius: 12, background: '#fff', border: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 16, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}> <div style={{ color: 'var(--primary)', background: 'var(--primary-glow)', width: 32, height: 32, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}> {getFileIcon(att.filename)} </div> <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={() => handleFileDownload(att.id, att.filename)}> <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{att.filename}</div> <div style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 600 }}>{(att.file_size / 1024).toFixed(1)} KB</div> </div> <div style={{ display: 'flex', gap: 4 }}> <button onClick={() => handleFileDownload(att.id, att.filename)} className={styles.downloadBtn} title="Download Asset" > <Download size={14} /> </button> <button onClick={() => handleDeleteAttachment(att.id)} className={styles.deleteBtn} title="Delete Asset" > <Trash2 size={14} /> </button> </div> </div> ))} {(ticket.attachments || []).length === 0 && ( <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)', fontSize: 12, fontWeight: 600 }}>No digital assets captured in this thread.</div> )} </div> )} {sidebarTab === 'history' && ( <div className={styles.historyTimeline}> {historyEvents.map((event) => ( <div key={event.id} className={styles.historyItem}> <div className={styles.historyLine} /> <div className={styles.historyIcon}>{event.icon}</div> <div className={styles.historyContent}> <div className={styles.historyMeta}> <span className={styles.historyLabel}>{event.label}</span> <span className={styles.historyTime}>{new Date(event.time).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span> </div> <div className={styles.historyDetail}>{event.detail}</div> </div> </div> ))} {historyEvents.length === 0 && ( <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)', fontSize: 12, fontWeight: 600 }}>No operational events recorded.</div> )} </div> )} </div> </div> </div> )} </div> {showReopenModal && ( <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}> <div className="organic-surface" style={{ width: '100%', maxWidth: 440, padding: 32, borderRadius: 12, boxShadow: '0 30px 60px rgba(0,0,0,0.4)', border: '1px solid var(--border-subtle)' }}> <h3 style={{ fontSize: 20, fontWeight: 900, marginBottom: 8, color: 'var(--text-main)', fontFamily: 'var(--font-heading)', letterSpacing: '-0.02em' }}>Reopen Ticket</h3> <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.5, marginBottom: 24, opacity: 0.8 }}>Please provide a brief justification to resume this resolution.</p> <textarea autoFocus value={reopenReason} onChange={e => setReopenReason(e.target.value)} placeholder="Reason for reopening..." style={{ width: "100%", padding: 16, borderRadius: 8, background: 'var(--bg-dark)', border: '1.5px solid var(--border-subtle)', fontSize: 14, color: 'var(--text-main)', marginBottom: 24, minHeight: 120, resize: 'none', outline: 'none', fontFamily: 'inherit' }} /> <div style={{ display: 'flex', gap: 12 }}> <button onClick={() => setShowReopenModal(false)} className={styles.btnSecondary} style={{ flex: 1, height: 48 }}>CANCEL</button> <button onClick={handleReopen} disabled={!reopenReason.trim() || isReopening} className={styles.btnPrimary} style={{ flex: 1, height: 48 }}> {isReopening ? 'REOPENING...' : 'RESUME TICKET'} </button> </div> </div> </div> )} {showConfirmEscalate && ( <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(12px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}> <div className="organic-surface" style={{ maxWidth: 400, width: '100%', padding: 48, textAlign: 'center', borderRadius: 24, border: '1px solid var(--border-subtle)', boxShadow: 'var(--shadow-xl)' }}> <div style={{ fontSize: 64, marginBottom: 24, display: 'flex', justifyContent: 'center' }}>🚨</div> <h2 style={{ fontSize: 24, fontWeight: 900, marginBottom: 12, color: 'var(--text-main)', letterSpacing: '-0.02em' }}>CONFIRM ESCALATION</h2> <p style={{ fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.6, marginBottom: 40, opacity: 0.9 }}>This will immediately notify lead specialists for priority intervention.</p> <div style={{ display: 'flex', gap: 16 }}> <button onClick={() => setShowConfirmEscalate(false)} className={styles.btnSecondary} style={{ flex: 1, height: 52 }}>CANCEL</button> <button onClick={handleEscalate} disabled={isEscalating} className={styles.btnPrimary} style={{ flex: 1, height: 52, background: 'var(--error)', boxShadow: '0 8px 20px rgba(239, 68, 68, 0.25)' }}> {isEscalating ? 'ESCALATING...' : 'CONFIRM'} </button> </div> </div> </div> )} </div> ); };
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StatusBadge } from './Badges';
import {
api,
NexusMarkdown,
getFileIcon,
getStorageKey,
useMentions,
MentionOverlay,
RichEditor,
useTheme,
useNotification
} from '@nexus/shared';
import type { Ticket, Message } from '@nexus/shared';
import styles from './ThreadView.module.css';
import {
ArrowLeft,
Send,
Paperclip,
Sparkles,
Maximize2,
RefreshCcw,
Loader2,
Trash2,
BookOpen,
Download
} from 'lucide-react';
interface ThreadViewProps {
ticket: Ticket;
onBack: () => void;
onNavigate?: (ticket: { id: string }) => void;
onNavigateArticle?: (articleId: string) => void;
}
export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, onBack, onNavigate, onNavigateArticle }) => {
const { theme } = useTheme();
const { alert, confirm } = useNotification();
const [ticket, setTicket] = useState<Ticket>(initialTicket);
const [messages, setMessages] = useState<Message[]>([]);
const [newMessage, setNewMessage] = useState("");
const [sending, setSending] = useState(false);
const [currentUser, setCurrentUser] = useState<{ id: string, full_name: string } | null>(null);
// Description Edit State
const [isEditingDesc, setIsEditingDesc] = useState(false);
const [descDraft, setDescDraft] = useState(initialTicket.description);
const [savingDesc, setSavingDesc] = useState(false);
const [isUploading, setIsUploading] = useState(false);
// Feedback States
const [ratingDraft, setRatingDraft] = useState<number | null>(ticket.rating || null);
const [hoverRating, setHoverRating] = useState<number | null>(null);
const [commentDraft, setCommentDraft] = useState("");
const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
const [showReopenModal, setShowReopenModal] = useState(false);
const [reopenReason, setReopenReason] = useState("");
const [isReopening, setIsReopening] = useState(false);
// AI Intensity States
const [isRegeneratingSummary, setIsRegeneratingSummary] = useState(false);
const [isEscalating, setIsEscalating] = useState(false);
const [historyEvents, setHistoryEvents] = useState<any[]>([]);
const [showConfirmEscalate, setShowConfirmEscalate] = useState(false);
// Sidebar States
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [isLeftSidebarOpen, setIsLeftSidebarOpen] = useState(false);
const [forbidden, setForbidden] = useState(false);
const [sidebarWidth, setSidebarWidth] = useState(400);
const [isResizing, setIsResizing] = useState(false);
const [sidebarTab, setSidebarTab] = useState<'messages' | 'files' | 'history'>('messages');
const {
filteredUsers,
showMentionList,
selectedMentionIndex,
setSelectedMentionIndex,
cursorPos,
handleInputChange,
getMentionText,
closeMentions
} = useMentions({ workspaceId: ticket?.workspace_id });
const bottomRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const isRefreshing = useRef(false);
const [isLoading, setIsLoading] = useState(false);
const refreshData = useCallback(async (bypassCache = false) => {
if (isRefreshing.current) return;
isRefreshing.current = true;
setIsLoading(true);
const watchdog = setTimeout(() => {
// Release the refresh lock so users can retry after a hung request.
// Without this, isRefreshing stays true indefinitely if the request never