Spaces:
Paused

dushyantsingh0
fix: allow staff cross-workspace live events via WebSockets
bc1617c
Raw History Blame Contribute Delete
9.32 kB
import React, { useState, useEffect } from 'react';
import { useAuth, api, getWsUrl, getStorageKey } from '@nexus/shared';
import styles from './TopBar.module.css';
interface TopBarProps {
title: string;
subtitle?: string;
onTicketSelect?: (ticket: any) => void;
}
export const TopBar: React.FC<TopBarProps> = ({ title, subtitle, onTicketSelect }) => {
const [time, setTime] = useState(new Date());
const [searchQuery, setSearchQuery] = useState('');
const [results, setResults] = useState<any[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
const [showNotifications, setShowNotifications] = useState(false);
const searchRef = React.useRef<HTMLFormElement>(null);
const { logout, user } = useAuth();
const [notifications, setNotifications] = useState<any[]>([]);
const [hasUnread, setHasUnread] = useState(false);
const fetchNotifications = async () => {
try {
const res = await api.get('notifications/');
setNotifications(res.data);
setHasUnread(res.data.some((n: any) => !n.is_read));
} catch (err) {
console.error("Failed to fetch notifications:", err);
}
};
const markAllAsRead = async () => {
try {
await api.patch('notifications/mark-read/');
setHasUnread(false);
fetchNotifications();
} catch (err) {
console.error("Failed to mark notifications read:", err);
}
};
useEffect(() => {
fetchNotifications();
const token = localStorage.getItem(getStorageKey('token'));
if (token && user?.workspace_id) {
try {
const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'notification' || data.event === 'ticket_updated') {
setHasUnread(true);
fetchNotifications();
}
};
ws.onerror = () => console.warn('[WS] Connection error โ€” notifications may be delayed');
ws.onclose = () => console.info('[WS] Connection closed');
return () => ws.close();
} catch (e) {
console.warn('[WS] Failed to initialize:', e);
}
}
}, [user?.workspace_id]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
setResults([]);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
useEffect(() => {
const t = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(t);
}, []);
const handleSearch = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
if (!searchQuery.trim()) {
setResults([]);
setHasSearched(false);
return;
}
setIsSearching(true);
try {
const resp = await api.get(`tickets/search/?q=${encodeURIComponent(searchQuery)}`);
setResults(resp.data.results || []);
setHasSearched(true);
} catch (err) {
console.error('Ticket search failed:', err);
} finally {
setIsSearching(false);
}
};
const handleNotifClick = async (n: any) => {
setShowNotifications(false);
if (!n.link) return;
// Parse deep links (e.g., /dashboard?ticket=UUID)
try {
const url = new URL(n.link, window.location.origin);
const ticketId = url.searchParams.get('ticket');
if (ticketId) {
const res = await api.get(`tickets/${ticketId}/`);
onTicketSelect?.(res.data);
}
} catch (err) {
console.error("Failed to parse or fetch notification link:", err);
}
};
// Handle Deep Linking on Load
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const ticketId = params.get('ticket');
if (ticketId) {
api.get(`tickets/${ticketId}/`)
.then(res => onTicketSelect?.(res.data))
.catch(err => console.error("URL-based ticket load failed:", err));
}
}, []);
// We only search on Enter now, so we remove the useEffect watcher
return (
<div className={styles.topbar}>
<div className={styles.left}>
<div className={styles.title}>{title}</div>
{subtitle && <div className={styles.subtitle}>{subtitle}</div>}
</div>
<div className={styles.right}>
<form className={styles.searchWrapper} ref={searchRef} onSubmit={handleSearch}>
<span className={styles.searchIcon}>โŒ•</span>
<input
type="text"
placeholder="Press Enter to search tickets..."
className={styles.searchInput}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
{hasSearched && (
<div className={styles.resultsDropdown}>
{results.length > 0 ? (
results.map(r => (
<div
key={r.id}
className={styles.resultItem}
onClick={() => {
onTicketSelect?.(r);
setResults([]);
setSearchQuery('');
setHasSearched(false);
}}
>
<div className={styles.resultMeta}>
<div className={styles.resultMetaLeft}>
<span className={styles.resultScore}>{r.score}% Match</span>
<span className={styles.resultId}>#{r.id?.slice(0, 8).toUpperCase()}</span>
</div>
<span className={styles.resultStatus} data-status={r.status?.toUpperCase()}>{r.status}</span>
</div>
<div className={styles.resultTitle}>{r.title}</div>
<div className={styles.resultFooter}>
Created {new Date(r.created_at).toLocaleDateString()}
</div>
</div>
))
) : (
<div className={styles.noResults}>No tickets found matching your query.</div>
)}
</div>
)}
{isSearching && (
<div className={styles.searchLoader}>Scanning network...</div>
)}
{results.length === 0 && searchQuery && !isSearching && !hasSearched && (
<div className={styles.searchHint}>Press Enter to search</div>
)}
</form>
<div className={styles.statusIndicator}>
<span className={styles.dot} />
<span className={styles.statusText}>LIVE</span>
<span className={styles.timeText}>{time.toLocaleTimeString('en-GB')}</span>
</div>
<div className={styles.notificationWrapper}>
<button className={styles.iconButton} onClick={() => {
setShowNotifications(!showNotifications);
if (!showNotifications) markAllAsRead();
}}>๐Ÿ””</button>
{hasUnread && <span className={styles.notificationBadge} />}
{showNotifications && (
<div className={styles.notifDropdown}>
<div className={styles.notifHeader}>
Notifications
{notifications.length > 0 && (
<span style={{ fontSize: '10px', marginLeft: '8px', opacity: 0.6 }}>{notifications.length} total</span>
)}
</div>
<div className={styles.notifList}>
{notifications.length === 0 ? (
<div className={styles.notifEmpty}>No new system alerts</div>
) : (
notifications.map(n => (
<div
key={n.id}
className={styles.notifItem}
data-read={n.is_read}
onClick={() => handleNotifClick(n)}
style={{ cursor: n.link ? 'pointer' : 'default' }}
>
<div className={styles.notifTitle}>{n.title}</div>
<div className={styles.notifMsg}>{n.message}</div>
<div className={styles.notifTime}>{new Date(n.created_at).toLocaleString()}</div>
</div>
))
)}
</div>
</div>
)}
</div>
<div className={styles.logoutWrapper}>
<button onClick={() => setShowLogoutConfirm(true)} className={styles.logoutBtn}>
Logout
</button>
{showLogoutConfirm && (
<div className={styles.logoutConfirm}>
<div className={styles.logoutText}>Do you want to quit?</div>
<div className={styles.logoutActions}>
<button onClick={() => setShowLogoutConfirm(false)} className={styles.cancelBtn}>Cancel</button>
<button onClick={logout} className={styles.confirmBtn}>Yes, Logout</button>
</div>
</div>
)}
</div>
</div>
</div>
);
};