To enhance your application by moving the Recent Issues from a table to the Notifications dropdown, we'll follow a structured approach:
- Remove the
RecentIssuesTable from the Dashboard.
- Implement a global
NotificationContext to manage notifications.
- Update the
Home component to handle notifications dynamically.
- Modify
AdvancedAnalyticsDashboard to push recent issues to notifications.
- Ensure the Notifications dropdown is aesthetically pleasing and functional.
This approach ensures a clean separation of concerns, making your application scalable and maintainable.
1. Remove the RecentIssuesTable from AdvancedAnalyticsDashboard
First, eliminate the RecentIssuesTable from your dashboard to prevent displaying recent issues in a table.
Before (AdvancedAnalyticsDashboard.tsx):
/* ... existing imports ... */
import RecentIssuesTable from './Tables/RecentIssuesTable';
/* ... inside the component's return ... */
<Card>
<CardHeader>
<CardTitle>Recent Issues</CardTitle>
</CardHeader>
<CardContent>
{analytics && <RecentIssuesTable data={analytics.recentIssues} />}
</CardContent>
</Card>
After (AdvancedAnalyticsDashboard.tsx):
/* ... existing imports ... */
// Removed RecentIssuesTable import
/* ... inside the component's return ... */
/* Removed the Recent Issues card */
2. Implement a Global NotificationContext
To allow different components to access and modify notifications, we'll create a NotificationContext.
Create NotificationContext.tsx:
// src/context/NotificationContext.tsx
'use client';
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface Notification {
id: number;
text: string;
time: string;
status?: 'info' | 'warning' | 'error'; // Optional: For categorizing notifications
}
interface NotificationContextProps {
notifications: Notification[];
addNotification: (notification: Omit<Notification, 'id' | 'time'>) => void;
removeNotification: (id: number) => void;
}
const NotificationContext = createContext<NotificationContextProps | undefined>(undefined);
let notificationId = 0;
export const NotificationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [notifications, setNotifications] = useState<Notification[]>([]);
const addNotification = (notification: Omit<Notification, 'id' | 'time'>) => {
const newNotification: Notification = {
id: ++notificationId,
time: new Date().toLocaleTimeString(),
...notification,
};
setNotifications((prev) => [newNotification, ...prev]);
};
const removeNotification = (id: number) => {
setNotifications((prev) => prev.filter((notif) => notif.id !== id));
};
return (
<NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>
{children}
</NotificationContext.Provider>
);
};
export const useNotifications = (): NotificationContextProps => {
const context = useContext(NotificationContext);
if (!context) {
throw new Error('useNotifications must be used within a NotificationProvider');
}
return context;
};
Wrap Your Application with NotificationProvider:
Assuming you're using _app.tsx or a similar entry point, wrap your application with the NotificationProvider.
// src/app/layout.tsx or src/pages/_app.tsx (depending on your project structure)
import { NotificationProvider } from '@/context/NotificationContext';
/* ... existing imports ... */
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<NotificationProvider>
{children}
</NotificationProvider>
</body>
</html>
);
}
3. Update the Home Component to Handle Notifications
Now, modify the Home component to consume the NotificationContext and display notifications dynamically.
Modify Home.tsx:
"use client";
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { ErrorBoundary } from 'react-error-boundary';
import {
LayoutDashboard, Settings, LogOut, Bell, Search, Menu,
Command, ChevronDown, ActivitySquare, Database, Shield
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { useNotifications } from '@/context/NotificationContext'; // Import the custom hook
// Dynamically import heavy components with loading fallbacks
const AdvancedAnalyticsDashboard = dynamic(
() => import('@/components/AdvancedAnalyticsDashboard'),
{
loading: () => (
<div className="flex items-center justify-center h-full">
<ActivitySquare className="w-8 h-8 text-primary animate-spin" />
</div>
),
ssr: false
}
);
const SettingsComponent = dynamic(
() => import('@/components/SettingsComponent'),
{
loading: () => <div className="p-4">Loading settings...</div>,
ssr: false
}
);
// Error fallback component
function ErrorFallback({ error, resetErrorBoundary }: any) {
return (
<div className="flex flex-col items-center justify-center h-full p-4">
<Shield className="w-12 h-12 text-destructive mb-4" />
<h2 className="text-xl font-semibold mb-2">Something went wrong</h2>
<p className="text-muted-foreground mb-4">{error.message}</p>
<Button onClick={resetErrorBoundary}>Try again</Button>
</div>
);
}
export default function Home() {
const [activeView, setActiveView] = useState('dashboard');
const [username, setUsername] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const { notifications, addNotification, removeNotification } = useNotifications(); // Destructure from context
const router = useRouter();
useEffect(() => {
try {
const token = localStorage.getItem('token');
if (!token) {
router.push('/login');
return;
}
setUsername("Durgesh Kumar");
setIsAuthenticated(true);
} catch (error) {
console.error('Authentication error:', error);
router.push('/login');
} finally {
setIsLoading(false);
}
}, [router]);
const handleLogout = () => {
try {
localStorage.removeItem('token');
setIsAuthenticated(false);
router.push('/login');
} catch (error) {
console.error('Logout error:', error);
}
};
const menuItems = [
{ icon: LayoutDashboard, label: 'Dashboard', id: 'dashboard' },
{ icon: Database, label: 'Analytics', id: 'analytics' },
{ icon: ActivitySquare, label: 'Monitoring', id: 'monitoring' },
{ icon: Shield, label: 'Security', id: 'security' },
{ icon: Settings, label: 'Settings', id: 'settings' },
];
if (isLoading) {
return (
<div className="flex items-center justify-center h-screen bg-gradient-to-r from-blue-500/10 to-purple-500/10">
<div className="p-8 rounded-lg bg-background shadow-xl">
<ActivitySquare className="w-12 h-12 text-primary mb-4 animate-spin" />
<h1 className="text-2xl font-bold mb-2">Loading...</h1>
<p className="text-muted-foreground">Setting up your dashboard</p>
</div>
</div>
);
}
if (!isAuthenticated) {
return (
<div className="flex items-center justify-center h-screen bg-gradient-to-r from-blue-500/10 to-purple-500/10">
<div className="p-8 rounded-lg bg-background shadow-xl">
<Shield className="w-12 h-12 text-destructive mb-4" />
<h1 className="text-2xl font-bold mb-2">Access Denied</h1>
<p className="text-muted-foreground mb-4">Please log in to continue</p>
<Button onClick={() => router.push('/login')}>Go to Login</Button>
</div>
</div>
);
}
return (
<div className="flex h-screen bg-background">
{/* Sidebar */}
<aside className={`${isSidebarOpen ? 'w-64' : 'w-20'} bg-background border-r transition-all duration-300 flex flex-col`}>
<div className="p-6 flex items-center gap-3">
<Command className="h-6 w-6 text-primary" />
{isSidebarOpen && <span className="font-bold text-xl">Not1fy</span>}
</div>
<ScrollArea className="flex-1 py-4">
{menuItems.map((item) => (
<button
key={item.id}
onClick={() => setActiveView(item.id)}
className={`w-full flex items-center gap-3 px-6 py-3 transition-colors
${activeView === item.id ? 'bg-primary/10 text-primary' : 'hover:bg-muted'}
${!isSidebarOpen && 'justify-center'}`}
>
<item.icon className="h-5 w-5" />
{isSidebarOpen && <span>{item.label}</span>}
</button>
))}
</ScrollArea>
<div className="p-4 border-t">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full flex items-center gap-2">
<Avatar className="h-8 w-8">
<AvatarImage src="/avatar.png" alt={username} />
<AvatarFallback>
{username.split(' ').map(n => n[0]).join('')}
</AvatarFallback>
</Avatar>
{isSidebarOpen && (
<>
<div className="flex-1 text-left">
<p className="text-sm font-medium">{username}</p>
<p className="text-xs text-muted-foreground">Admin</p>
</div>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel>My Account</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Profile</DropdownMenuItem>
<DropdownMenuItem>Settings</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-destructive">
<LogOut className="mr-2 h-4 w-4" /> Logout
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</aside>
{/* Main Content */}
<div className="flex-1 flex flex-col overflow-hidden">
<header className="h-16 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="h-full flex items-center justify-between px-6">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsSidebarOpen(!isSidebarOpen)}
>
<Menu className="h-5 w-5" />
</Button>
<div className="w-64">
<Input
placeholder="Search..."
className="w-full"
prefix={<Search className="h-4 w-4 text-muted-foreground" />}
/>
</div>
</div>
<div className="flex items-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative">
<Bell className="h-5 w-5" />
{notifications.length > 0 && (
<Badge className="absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center bg-red-500 text-white rounded-full">
{notifications.length}
</Badge>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 max-h-96 overflow-auto">
<DropdownMenuLabel>Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start">
<div className="flex justify-between w-full">
<p className="text-sm">{notif.text}</p>
<span className="text-xs text-muted-foreground cursor-pointer" onClick={() => removeNotification(notif.id)}>×</span>
</div>
<span className="text-xs text-muted-foreground">{notif.time}</span>
</DropdownMenuItem>
))
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
</DropdownMenuContent>
</DropdownMenu>
<Separator orientation="vertical" className="h-8" />
<Button variant="default" className="gap-2">
<Shield className="h-4 w-4" />
Upgrade Pro
</Button>
</div>
</div>
</header>
<main className="flex-1 overflow-auto bg-muted/20">
<ErrorBoundary FallbackComponent={ErrorFallback}>
{activeView === 'dashboard' && <AdvancedAnalyticsDashboard />}
{activeView === 'settings' && <SettingsComponent />}
{!['dashboard', 'settings'].includes(activeView) && (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<h2 className="text-xl font-semibold mb-2">Coming Soon</h2>
<p className="text-muted-foreground">This feature is under development</p>
</div>
</div>
)}
</ErrorBoundary>
</main>
</div>
</div>
);
}
Key Changes:
- Consume
NotificationContext: Imported and destructured notifications, addNotification, and removeNotification.
- Notifications Dropdown:
- Enhanced the appearance with better badges and remove buttons (×) for individual notifications.
- Limited the dropdown height with
max-h-96 and made it scrollable with overflow-auto.
- Removed Static
notifications State: The previous static notifications array is now managed globally.
4. Modify AdvancedAnalyticsDashboard to Push Recent Issues to Notifications
Now, update the dashboard to push any new recent issues directly to the notifications instead of displaying them in a table.
Modify AdvancedAnalyticsDashboard.tsx:
'use client';
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import StatisticsCards from './StatisticsCards';
import Filters from './Filters';
import ChecksOverTimeChart from './Charts/ChecksOverTimeChart';
import StatusCodeDistributionChart from './Charts/StatusCodeDistributionChart';
import UptimePerUrlChart from './Charts/UptimePerUrlChart';
import ResponseTimeDistributionChart from './Charts/ResponseTimeDistributionChart';
import TopSlowestUrlsTable from './Tables/TopSlowestUrlsTable';
// Removed RecentIssuesTable import
import LoadingIndicator from './LoadingIndicator';
import { useToast } from "../hooks/use-toast";
import { Button } from "@/components/ui/button";
import { RefreshCw, Loader2 } from 'lucide-react';
import { DateRange } from 'react-day-picker';
import { analyticsService } from '../app/services/analytics.service';
import { AnalyticsData } from '../app/types/api.types';
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useNotifications } from '@/context/NotificationContext'; // Import the custom hook
const AdvancedAnalyticsDashboard: React.FC = () => {
// State
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
const [dateRange, setDateRange] = useState<DateRange | undefined>({
from: new Date(new Date().setDate(new Date().getDate() - 30)),
to: new Date(),
});
const [groupBy, setGroupBy] = useState<string>('day');
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isRealtime, setIsRealtime] = useState<boolean>(false);
const [urlFilter, setUrlFilter] = useState<string>('');
const [statusCodeFilter, setStatusCodeFilter] = useState<string>('');
const [responseTimeRange, setResponseTimeRange] = useState<number[]>([0, 5000]);
const { toast } = useToast();
const { addNotification } = useNotifications(); // Destructure addNotification
const mapDateRange = (
range: DateRange | undefined
): import('../app/types/api.types').DateRange | undefined => {
if (!range) return undefined;
return {
from: range.from || new Date(), // Default date if undefined
to: range.to || new Date(),
};
};
// Fetch Analytics Data
const loadAnalytics = useCallback(async () => {
setIsLoading(true);
try {
const params: Record<string, any> = {};
if (dateRange) {
if (dateRange.from) params.startDate = dateRange.from.toISOString();
if (dateRange.to) params.endDate = dateRange.to.toISOString();
}
if (urlFilter) params.urls = urlFilter;
if (statusCodeFilter) params.statusCodes = statusCodeFilter;
if (responseTimeRange) {
params.minResponseTime = responseTimeRange[0];
params.maxResponseTime = responseTimeRange[1];
}
params.groupBy = groupBy;
const data = await analyticsService.getAnalytics(params);
setAnalytics(data);
// Push recent issues to notifications
if (data.recentIssues && data.recentIssues.length > 0) {
data.recentIssues.forEach(issue => {
addNotification({
text: `Issue on ${issue.url} - Status: ${issue.statusCode}`,
status: issue.statusCode >= 500 ? 'error' : 'warning',
});
});
}
} catch (error: any) {
console.error('Failed to fetch analytics:', error);
// Display a toast notification for errors other than unauthorized access
if (error.response && error.response.status !== 401 && error.response.status !== 403) {
toast({
title: "Error",
description: "Failed to fetch analytics data. Please try again.",
variant: "destructive",
});
}
// Unauthorized access is handled within the service by redirecting to login
} finally {
setIsLoading(false);
}
}, [toast, dateRange, urlFilter, statusCodeFilter, responseTimeRange, groupBy, addNotification]);
// Initial Load
useEffect(() => {
loadAnalytics();
}, [loadAnalytics]);
// Realtime Updates
useEffect(() => {
if (isRealtime) {
const interval = setInterval(() => {
loadAnalytics();
}, 5000); // Refresh every 5 seconds in realtime mode
return () => clearInterval(interval);
}
}, [isRealtime, loadAnalytics]);
if (isLoading && !analytics) {
return <LoadingIndicator />;
}
return (
<div className="container mx-auto p-4 space-y-8">
{/* Header */}
<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
<h1 className="text-4xl font-bold">Advanced Analytics Dashboard</h1>
<div className="flex items-center space-x-4">
<Switch
checked={isRealtime}
onCheckedChange={setIsRealtime}
id="realtime-mode"
/>
<Label htmlFor="realtime-mode">Realtime Updates</Label>
<Button onClick={loadAnalytics} disabled={isLoading} variant="secondary">
{isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
Refresh Data
</Button>
</div>
</div>
{/* Statistics Cards */}
{analytics && <StatisticsCards analytics={analytics} />}
{/* Filters */}
<Filters
dateRange={mapDateRange(dateRange)} // Apply mapping here
setDateRange={(range) => setDateRange(range)}
groupBy={groupBy}
setGroupBy={setGroupBy}
urlFilter={urlFilter}
setUrlFilter={setUrlFilter}
statusCodeFilter={statusCodeFilter}
setStatusCodeFilter={setStatusCodeFilter}
responseTimeRange={responseTimeRange}
setResponseTimeRange={setResponseTimeRange}
/>
{/* Charts and Tables */}
<div className="space-y-8">
{/* Checks Over Time */}
<Card>
<CardHeader>
<CardTitle>Checks Over Time</CardTitle>
</CardHeader>
<CardContent className="h-[400px]">
{analytics && <ChecksOverTimeChart data={analytics.checksOverTime} />}
</CardContent>
</Card>
{/* Status Code Distribution and Uptime Per URL */}
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Status Code Distribution</CardTitle>
</CardHeader>
<CardContent className="h-[300px]">
{analytics && <StatusCodeDistributionChart data={analytics.statusCodeDistribution} />}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Uptime Per URL</CardTitle>
</CardHeader>
<CardContent className="h-[300px]">
{analytics && <UptimePerUrlChart data={analytics.uptimePerUrl} />}
</CardContent>
</Card>
</div>
{/* Response Time Distribution */}
<Card>
<CardHeader>
<CardTitle>Response Time Distribution</CardTitle>
</CardHeader>
<CardContent className="h-[400px]">
{analytics && <ResponseTimeDistributionChart data={analytics.responseTimeDistribution} />}
</CardContent>
</Card>
{/* Top Slowest URLs */}
<Card>
<CardHeader>
<CardTitle>Top Slowest URLs</CardTitle>
</CardHeader>
<CardContent>
{analytics && <TopSlowestUrlsTable data={analytics.topSlowestUrls} />}
</CardContent>
</Card>
{/* Removed Recent Issues Table */}
</div>
</div>
);
};
export default AdvancedAnalyticsDashboard;
Key Changes:
- Consume
NotificationContext: Imported and destructured addNotification.
- Push Recent Issues to Notifications:
- After fetching analytics data, iterate over
data.recentIssues and push each issue as a notification.
- Categorize notifications based on
statusCode ('error' for status codes >= 500, 'warning' otherwise).
5. Ensure the Notifications Dropdown is Aesthetically Pleasing and Functional
Finally, enhance the Notifications dropdown to handle different notification types and provide a better user experience.
Enhance Notification Display in Home.tsx:
/* ... existing code ... */
<DropdownMenuContent align="end" className="w-80 max-h-96 overflow-auto">
<DropdownMenuLabel>Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start">
<div className="flex justify-between w-full">
<div className="flex items-center gap-2">
{notif.status === 'error' && <Badge className="bg-red-500 text-white">Error</Badge>}
{notif.status === 'warning' && <Badge className="bg-yellow-500 text-white">Warning</Badge>}
<p className="text-sm">{notif.text}</p>
</div>
<span
className="text-xs text-muted-foreground cursor-pointer"
onClick={() => removeNotification(notif.id)}
title="Dismiss"
>
×
</span>
</div>
<span className="text-xs text-muted-foreground">{notif.time}</span>
</DropdownMenuItem>
))
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
</DropdownMenuContent>
Enhancements:
- Categorize Notifications: Display badges indicating the type of notification (
Error, Warning).
- Dismiss Button: Added a clickable
× to allow users to dismiss individual notifications.
- Responsive Design: Ensured the dropdown handles overflow with
max-h-96 and overflow-auto.
- Tooltips: Added
title="Dismiss" to the × for better accessibility.
Full Updated Code Snippets
NotificationContext.tsx:
// src/context/NotificationContext.tsx
'use client';
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface Notification {
id: number;
text: string;
time: string;
status?: 'info' | 'warning' | 'error'; // Optional: For categorizing notifications
}
interface NotificationContextProps {
notifications: Notification[];
addNotification: (notification: Omit<Notification, 'id' | 'time'>) => void;
removeNotification: (id: number) => void;
}
const NotificationContext = createContext<NotificationContextProps | undefined>(undefined);
let notificationId = 0;
export const NotificationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [notifications, setNotifications] = useState<Notification[]>([]);
const addNotification = (notification: Omit<Notification, 'id' | 'time'>) => {
const newNotification: Notification = {
id: ++notificationId,
time: new Date().toLocaleTimeString(),
...notification,
};
setNotifications((prev) => [newNotification, ...prev]);
};
const removeNotification = (id: number) => {
setNotifications((prev) => prev.filter((notif) => notif.id !== id));
};
return (
<NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>
{children}
</NotificationContext.Provider>
);
};
export const useNotifications = (): NotificationContextProps => {
const context = useContext(NotificationContext);
if (!context) {
throw new Error('useNotifications must be used within a NotificationProvider');
}
return context;
};
Home.tsx:
"use client";
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { ErrorBoundary } from 'react-error-boundary';
import {
LayoutDashboard, Settings, LogOut, Bell, Search, Menu,
Command, ChevronDown, ActivitySquare, Database, Shield
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { useNotifications } from '@/context/NotificationContext'; // Import the custom hook
// Dynamically import heavy components with loading fallbacks
const AdvancedAnalyticsDashboard = dynamic(
() => import('@/components/AdvancedAnalyticsDashboard'),
{
loading: () => (
<div className="flex items-center justify-center h-full">
<ActivitySquare className="w-8 h-8 text-primary animate-spin" />
</div>
),
ssr: false
}
);
const SettingsComponent = dynamic(
() => import('@/components/SettingsComponent'),
{
loading: () => <div className="p-4">Loading settings...</div>,
ssr: false
}
);
// Error fallback component
function ErrorFallback({ error, resetErrorBoundary }: any) {
return (
<div className="flex flex-col items-center justify-center h-full p-4">
<Shield className="w-12 h-12 text-destructive mb-4" />
<h2 className="text-xl font-semibold mb-2">Something went wrong</h2>
<p className="text-muted-foreground mb-4">{error.message}</p>
<Button onClick={resetErrorBoundary}>Try again</Button>
</div>
);
}
export default function Home() {
const [activeView, setActiveView] = useState('dashboard');
const [username, setUsername] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const { notifications, addNotification, removeNotification } = useNotifications(); // Destructure from context
const router = useRouter();
useEffect(() => {
try {
const token = localStorage.getItem('token');
if (!token) {
router.push('/login');
return;
}
setUsername("Durgesh Kumar");
setIsAuthenticated(true);
} catch (error) {
console.error('Authentication error:', error);
router.push('/login');
} finally {
setIsLoading(false);
}
}, [router]);
const handleLogout = () => {
try {
localStorage.removeItem('token');
setIsAuthenticated(false);
router.push('/login');
} catch (error) {
console.error('Logout error:', error);
}
};
const menuItems = [
{ icon: LayoutDashboard, label: 'Dashboard', id: 'dashboard' },
{ icon: Database, label: 'Analytics', id: 'analytics' },
{ icon: ActivitySquare, label: 'Monitoring', id: 'monitoring' },
{ icon: Shield, label: 'Security', id: 'security' },
{ icon: Settings, label: 'Settings', id: 'settings' },
];
if (isLoading) {
return (
<div className="flex items-center justify-center h-screen bg-gradient-to-r from-blue-500/10 to-purple-500/10">
<div className="p-8 rounded-lg bg-background shadow-xl">
<ActivitySquare className="w-12 h-12 text-primary mb-4 animate-spin" />
<h1 className="text-2xl font-bold mb-2">Loading...</h1>
<p className="text-muted-foreground">Setting up your dashboard</p>
</div>
</div>
);
}
if (!isAuthenticated) {
return (
<div className="flex items-center justify-center h-screen bg-gradient-to-r from-blue-500/10 to-purple-500/10">
<div className="p-8 rounded-lg bg-background shadow-xl">
<Shield className="w-12 h-12 text-destructive mb-4" />
<h1 className="text-2xl font-bold mb-2">Access Denied</h1>
<p className="text-muted-foreground mb-4">Please log in to continue</p>
<Button onClick={() => router.push('/login')}>Go to Login</Button>
</div>
</div>
);
}
return (
<div className="flex h-screen bg-background">
{/* Sidebar */}
<aside className={`${isSidebarOpen ? 'w-64' : 'w-20'} bg-background border-r transition-all duration-300 flex flex-col`}>
<div className="p-6 flex items-center gap-3">
<Command className="h-6 w-6 text-primary" />
{isSidebarOpen && <span className="font-bold text-xl">Not1fy</span>}
</div>
<ScrollArea className="flex-1 py-4">
{menuItems.map((item) => (
<button
key={item.id}
onClick={() => setActiveView(item.id)}
className={`w-full flex items-center gap-3 px-6 py-3 transition-colors
${activeView === item.id ? 'bg-primary/10 text-primary' : 'hover:bg-muted'}
${!isSidebarOpen && 'justify-center'}`}
>
<item.icon className="h-5 w-5" />
{isSidebarOpen && <span>{item.label}</span>}
</button>
))}
</ScrollArea>
<div className="p-4 border-t">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full flex items-center gap-2">
<Avatar className="h-8 w-8">
<AvatarImage src="/avatar.png" alt={username} />
<AvatarFallback>
{username.split(' ').map(n => n[0]).join('')}
</AvatarFallback>
</Avatar>
{isSidebarOpen && (
<>
<div className="flex-1 text-left">
<p className="text-sm font-medium">{username}</p>
<p className="text-xs text-muted-foreground">Admin</p>
</div>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel>My Account</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Profile</DropdownMenuItem>
<DropdownMenuItem>Settings</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-destructive">
<LogOut className="mr-2 h-4 w-4" /> Logout
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</aside>
{/* Main Content */}
<div className="flex-1 flex flex-col overflow-hidden">
<header className="h-16 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="h-full flex items-center justify-between px-6">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsSidebarOpen(!isSidebarOpen)}
>
<Menu className="h-5 w-5" />
</Button>
<div className="w-64">
<Input
placeholder="Search..."
className="w-full"
prefix={<Search className="h-4 w-4 text-muted-foreground" />}
/>
</div>
</div>
<div className="flex items-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative">
<Bell className="h-5 w-5" />
{notifications.length > 0 && (
<Badge className="absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center bg-red-500 text-white rounded-full">
{notifications.length}
</Badge>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 max-h-96 overflow-auto">
<DropdownMenuLabel>Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start">
<div className="flex justify-between w-full">
<div className="flex items-center gap-2">
{notif.status === 'error' && <Badge className="bg-red-500 text-white">Error</Badge>}
{notif.status === 'warning' && <Badge className="bg-yellow-500 text-white">Warning</Badge>}
<p className="text-sm">{notif.text}</p>
</div>
<span
className="text-xs text-muted-foreground cursor-pointer"
onClick={() => removeNotification(notif.id)}
title="Dismiss"
>
×
</span>
</div>
<span className="text-xs text-muted-foreground">{notif.time}</span>
</DropdownMenuItem>
))
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
</DropdownMenuContent>
</DropdownMenu>
<Separator orientation="vertical" className="h-8" />
<Button variant="default" className="gap-2">
<Shield className="h-4 w-4" />
Upgrade Pro
</Button>
</div>
</div>
</header>
<main className="flex-1 overflow-auto bg-muted/20">
<ErrorBoundary FallbackComponent={ErrorFallback}>
{activeView === 'dashboard' && <AdvancedAnalyticsDashboard />}
{activeView === 'settings' && <SettingsComponent />}
{!['dashboard', 'settings'].includes(activeView) && (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<h2 className="text-xl font-semibold mb-2">Coming Soon</h2>
<p className="text-muted-foreground">This feature is under development</p>
</div>
</div>
)}
</ErrorBoundary>
</main>
</div>
</div>
);
}
AdvancedAnalyticsDashboard.tsx:
'use client';
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import StatisticsCards from './StatisticsCards';
import Filters from './Filters';
import ChecksOverTimeChart from './Charts/ChecksOverTimeChart';
import StatusCodeDistributionChart from './Charts/StatusCodeDistributionChart';
import UptimePerUrlChart from './Charts/UptimePerUrlChart';
import ResponseTimeDistributionChart from './Charts/ResponseTimeDistributionChart';
import TopSlowestUrlsTable from './Tables/TopSlowestUrlsTable';
// Removed RecentIssuesTable import
import LoadingIndicator from './LoadingIndicator';
import { useToast } from "../hooks/use-toast";
import { Button } from "@/components/ui/button";
import { RefreshCw, Loader2 } from 'lucide-react';
import { DateRange } from 'react-day-picker';
import { analyticsService } from '../app/services/analytics.service';
import { AnalyticsData } from '../app/types/api.types';
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useNotifications } from '@/context/NotificationContext'; // Import the custom hook
const AdvancedAnalyticsDashboard: React.FC = () => {
// State
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
const [dateRange, setDateRange] = useState<DateRange | undefined>({
from: new Date(new Date().setDate(new Date().getDate() - 30)),
to: new Date(),
});
const [groupBy, setGroupBy] = useState<string>('day');
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isRealtime, setIsRealtime] = useState<boolean>(false);
const [urlFilter, setUrlFilter] = useState<string>('');
const [statusCodeFilter, setStatusCodeFilter] = useState<string>('');
const [responseTimeRange, setResponseTimeRange] = useState<number[]>([0, 5000]);
const { toast } = useToast();
const { addNotification } = useNotifications(); // Destructure addNotification
const mapDateRange = (
range: DateRange | undefined
): import('../app/types/api.types').DateRange | undefined => {
if (!range) return undefined;
return {
from: range.from || new Date(), // Default date if undefined
to: range.to || new Date(),
};
};
// Fetch Analytics Data
const loadAnalytics = useCallback(async () => {
setIsLoading(true);
try {
const params: Record<string, any> = {};
if (dateRange) {
if (dateRange.from) params.startDate = dateRange.from.toISOString();
if (dateRange.to) params.endDate = dateRange.to.toISOString();
}
if (urlFilter) params.urls = urlFilter;
if (statusCodeFilter) params.statusCodes = statusCodeFilter;
if (responseTimeRange) {
params.minResponseTime = responseTimeRange[0];
params.maxResponseTime = responseTimeRange[1];
}
params.groupBy = groupBy;
const data = await analyticsService.getAnalytics(params);
setAnalytics(data);
// Push recent issues to notifications
if (data.recentIssues && data.recentIssues.length > 0) {
data.recentIssues.forEach(issue => {
addNotification({
text: `Issue on ${issue.url} - Status: ${issue.statusCode}`,
status: issue.statusCode >= 500 ? 'error' : 'warning',
});
});
}
} catch (error: any) {
console.error('Failed to fetch analytics:', error);
// Display a toast notification for errors other than unauthorized access
if (error.response && error.response.status !== 401 && error.response.status !== 403) {
toast({
title: "Error",
description: "Failed to fetch analytics data. Please try again.",
variant: "destructive",
});
}
// Unauthorized access is handled within the service by redirecting to login
} finally {
setIsLoading(false);
}
}, [toast, dateRange, urlFilter, statusCodeFilter, responseTimeRange, groupBy, addNotification]);
// Initial Load
useEffect(() => {
loadAnalytics();
}, [loadAnalytics]);
// Realtime Updates
useEffect(() => {
if (isRealtime) {
const interval = setInterval(() => {
loadAnalytics();
}, 5000); // Refresh every 5 seconds in realtime mode
return () => clearInterval(interval);
}
}, [isRealtime, loadAnalytics]);
if (isLoading && !analytics) {
return <LoadingIndicator />;
}
return (
<div className="container mx-auto p-4 space-y-8">
{/* Header */}
<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
<h1 className="text-4xl font-bold">Advanced Analytics Dashboard</h1>
<div className="flex items-center space-x-4">
<Switch
checked={isRealtime}
onCheckedChange={setIsRealtime}
id="realtime-mode"
/>
<Label htmlFor="realtime-mode">Realtime Updates</Label>
<Button onClick={loadAnalytics} disabled={isLoading} variant="secondary">
{isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
Refresh Data
</Button>
</div>
</div>
{/* Statistics Cards */}
{analytics && <StatisticsCards analytics={analytics} />}
{/* Filters */}
<Filters
dateRange={mapDateRange(dateRange)} // Apply mapping here
setDateRange={(range) => setDateRange(range)}
groupBy={groupBy}
setGroupBy={setGroupBy}
urlFilter={urlFilter}
setUrlFilter={setUrlFilter}
statusCodeFilter={statusCodeFilter}
setStatusCodeFilter={setStatusCodeFilter}
responseTimeRange={responseTimeRange}
setResponseTimeRange={setResponseTimeRange}
/>
{/* Charts and Tables */}
<div className="space-y-8">
{/* Checks Over Time */}
<Card>
<CardHeader>
<CardTitle>Checks Over Time</CardTitle>
</CardHeader>
<CardContent className="h-[400px]">
{analytics && <ChecksOverTimeChart data={analytics.checksOverTime} />}
</CardContent>
</Card>
{/* Status Code Distribution and Uptime Per URL */}
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Status Code Distribution</CardTitle>
</CardHeader>
<CardContent className="h-[300px]">
{analytics && <StatusCodeDistributionChart data={analytics.statusCodeDistribution} />}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Uptime Per URL</CardTitle>
</CardHeader>
<CardContent className="h-[300px]">
{analytics && <UptimePerUrlChart data={analytics.uptimePerUrl} />}
</CardContent>
</Card>
</div>
{/* Response Time Distribution */}
<Card>
<CardHeader>
<CardTitle>Response Time Distribution</CardTitle>
</CardHeader>
<CardContent className="h-[400px]">
{analytics && <ResponseTimeDistributionChart data={analytics.responseTimeDistribution} />}
</CardContent>
</Card>
{/* Top Slowest URLs */}
<Card>
<CardHeader>
<CardTitle>Top Slowest URLs</CardTitle>
</CardHeader>
<CardContent>
{analytics && <TopSlowestUrlsTable data={analytics.topSlowestUrls} />}
</CardContent>
</Card>
{/* Removed Recent Issues Table */}
</div>
</div>
);
};
export default AdvancedAnalyticsDashboard;
Additional Recommendations
-
Persist Notifications:
- Consider persisting notifications in
localStorage or a backend to retain them across sessions.
-
Notification Badges:
- Enhance badges with different colors or icons based on notification type for better visual differentiation.
-
Bulk Dismissal:
- Add a "Clear All" option in the notifications dropdown to allow users to dismiss all notifications at once.
-
Real-time Notifications:
- Integrate WebSockets or similar technologies to push notifications in real-time as they occur.
-
Accessibility:
- Ensure that notifications are accessible via keyboard navigation and screen readers.
-
Animations:
- Add subtle animations when new notifications appear to draw user attention without being intrusive.
By following this approach, you've successfully transformed the Recent Issues from a static table into dynamic, user-friendly notifications. This not only declutters your dashboard but also ensures that users are promptly informed about critical issues in an elegant manner.
If you encounter any challenges or need further customization, feel free to ask!