i want the recent issies to be pushed to the notification… · The Chat Archive
Explore / Programming i want the recent issies to be pushed to the notification instead of shoing it in the… Save Share Download ▾ Reporti want the recent issies to be pushed to the notification instead of shoing it in the table make it good and solid and beaitifull
"""
"""
"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";
// Dynamically import heavy components with loading fallbacks
const AdvancedAnalyticsDashboard = dynamic(
() => import('@/components/AdvancedAnalyticsDashboard'),
{
loading: () => (
),
ssr: false
}
);
const SettingsComponent = dynamic(
() => import('@/components/SettingsComponent'),
{
loading: () =>
Loading settings...
,
ssr: false
}
);
// Error fallback component
function ErrorFallback({ error, resetErrorBoundary }: any) {
return (
Something went wrong
{error.message}
Try again
);
}
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, setNotifications] = useState([
{ id: 1, text: "System update scheduled", time: "5m ago" },
{ id: 2, text: "New alert detected", time: "10m ago" },
{ id: 3, text: "Backup completed", time: "1h ago" }
]);
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' },
];
Show full message · 543 lines Assistant2024-11-15 06:25 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 15, 2024
Added to archive Nov 16, 2026
ID 01m7h4294ga7xaq719w8y9bf9sSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: fd023e9df27e5ba256758cdb3dabd1ed
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
if (isLoading) {
return (
Setting up your dashboard
);
}
if (!isAuthenticated) {
return (
Please log in to continue
<Button onClick={() => router.push('/login')}>Go to Login
{isSidebarOpen && Not1fy}
code Copy code
<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>
code Copy code
<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">
{notifications.length}
</Badge>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80">
<DropdownMenuLabel>Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start">
<p>{notif.text}</p>
<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>
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';
import RecentIssuesTable from './Tables/RecentIssuesTable';
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";
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('day');
const [isLoading, setIsLoading] = useState(true);
const [isRealtime, setIsRealtime] = useState(false);
const [urlFilter, setUrlFilter] = useState('');
const [statusCodeFilter, setStatusCodeFilter] = useState('');
const [responseTimeRange, setResponseTimeRange] = useState<number[]>([0, 5000]);
const { toast } = useToast();
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);
} 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]);
// 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 ;
}
Advanced Analytics Dashboard
{/* Statistics Cards */}
{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 */}
code Copy code
{/* 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>
{/* Recent Issues */}
<Card>
<CardHeader>
<CardTitle>Recent Issues</CardTitle>
</CardHeader>
<CardContent>
{analytics && <RecentIssuesTable data={analytics.recentIssues} />}
</CardContent>
</Card>
export default AdvancedAnalyticsDashboard;
"""
"""
// components/Tables/RecentIssuesTable.tsx
import React from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { RecentIssue } from '../../app/types/api.types';
interface RecentIssuesTableProps {
data: RecentIssue[];
}
const RecentIssuesTable: React.FC = ({ data }) => (
URL
Status Code
Checked At
Response Time
{data.map((issue, index) => (
= 500 ? "destructive" : "secondary"}>
{issue.statusCode}
{new Date(issue.checkedAt).toLocaleString()}
{issue.responseTime}
);
export default React.memo(RecentIssuesTable);
"""
make it good and nice remoe the recent isisue tabel and push the recent issues to the notifcation and porpely functioning wiht number s and stuff
i am using nextjs ts tailwind app routing
To enhance your Next.js dashboard by removing the RecentIssuesTable and integrating recent issues into the notification system, follow these steps:
Lift Notifications State to Global Context (Optional but Recommended)
Modify the Home Component
Update the AdvancedAnalyticsDashboard Component
Enhance the Notification UI
Below is a step-by-step guide with code snippets to achieve a beautiful and functional notification system that incorporates recent issues.
1. Lift Notifications State to Global Context (Optional but Recommended)
To make notifications accessible across different components without prop drilling, it's advisable to use React Context. This provides a centralized state management solution for your notifications.
Create a Notification Context
Create a new directory contexts in your src folder.
Add a new file NotificationContext.tsx with the following content:
tsx Copy code
// src/contexts/NotificationContext.tsx
'use client';
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface Notification {
id: number;
text: string;
time: string;
type?: 'info' | 'warning' | 'error' | 'success'; // Optional: For different notification types
}
interface NotificationContextProps {
notifications: Notification[];
addNotification: (notification: Notification) => void;
removeNotification: (id: number) => void;
}
const NotificationContext = createContext<NotificationContextProps | undefined>(undefined);
export const NotificationProvider = ({ children }: { children: ReactNode }) => {
const [notifications, setNotifications] = useState<Notification[]>([]);
const addNotification = (notification: Notification) => {
setNotifications((prev) => [notification, ...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 the NotificationProvider. Modify your layout.tsx or the top-level component accordingly:
tsx Copy code
// src/app/layout.tsx
import './globals.css';
import { NotificationProvider } from '@/contexts/NotificationContext';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<NotificationProvider>
{children}
</NotificationProvider>
</body>
</html>
);
}
2. Modify the Home Component
Now, update your Home component to use the global notification context.
Updated Home Component
Explanation of Changes:
Using NotificationProvider and useNotifications Hook:
The Home component now uses useNotifications to access and manipulate the notification state globally.
Updated Notification Dropdown:
Enhanced the notification dropdown with better styling using Tailwind CSS.
Added a scroll area to handle multiple notifications gracefully.
Included a "View All" button for future expansion.
Badge Styling:
Improved the badge showing the number of notifications for better visibility.
3. Update the AdvancedAnalyticsDashboard Component
Now, update the AdvancedAnalyticsDashboard component to push recent issues to the global notifications instead of displaying them in a table.
Modified AdvancedAnalyticsDashboard.tsx
Explanation of Changes:
Removed RecentIssuesTable:
The import and usage of RecentIssuesTable have been removed since recent issues will now be part of the notifications.
Integrated Notifications:
Imported and used the useNotifications hook to access the addNotification function.
After fetching analytics data, iterated through data.recentIssues to push each issue as a notification.
Each notification includes an id, text, time, and an optional type for styling purposes.
Enhanced Handling of Recent Issues:
Notifications are conditionally added only if there are recent issues.
The type field categorizes notifications based on the statusCode to allow different styling.
4. Enhance the Notification UI
Finally, improve the visual appearance of notifications for a better user experience.
Update Notification Dropdown in Home Component
Ensure your notification dropdown is visually appealing by customizing it with Tailwind CSS and conditional styling based on the notification type.
tsx Copy code
// Inside the Home component's return statement, update the DropdownMenuContent
<DropdownMenuContent align="end" className="w-80 p-4">
<DropdownMenuLabel className="font-semibold">Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
<ScrollArea className="max-h-60">
{notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start gap-1">
<div className="flex items-center w-full justify-between">
<span className={`font-medium ${notif.type === 'error' ? 'text-red-600' : notif.type === 'warning' ? 'text-yellow-500' : 'text-gray-800'}`}>
{notif.text}
</span>
<button onClick={() => removeNotification(notif.id)} className="text-gray-400 hover:text-gray-600">
×
</button>
</div>
<span className="text-xs text-muted-foreground">{notif.time}</span>
</DropdownMenuItem>
))}
</ScrollArea>
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
<DropdownMenuSeparator />
<Button variant="ghost" className="w-full text-left">
View All
</Button>
</DropdownMenuContent>
Explanation of Enhancements:
Conditional Styling:
Notifications are styled based on their type (e.g., errors in red, warnings in yellow) to quickly convey the nature of each notification.
Dismiss Button:
Added a dismiss (×) button to allow users to remove individual notifications.
Scroll Area:
Incorporated a scrollable area to handle a large number of notifications without overflowing the UI.
"View All" Button:
Positioned a "View All" button at the bottom for potential navigation to a full notifications page.
Optional: Add Animations for Notifications
For a more dynamic feel, you can add entry and exit animations to notifications using libraries like Framer Motion or integrate Tailwind CSS animations.
bash Copy code
# Install Framer Motion
npm install framer-motion
tsx Copy code
// src/components/NotificationItem.tsx
import React from 'react';
import { motion } from 'framer-motion';
interface NotificationItemProps {
id: number;
text: string;
time: string;
type?: 'info' | 'warning' | 'error' | 'success';
onDismiss: (id: number) => void;
}
const NotificationItem: React.FC<NotificationItemProps> = ({ id, text, time, type, onDismiss }) => {
return (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
className="mb-2 w-full"
>
<div className={`flex justify-between items-center p-2 rounded ${type === 'error' ? 'bg-red-100' : type === 'warning' ? 'bg-yellow-100' : 'bg-gray-100'}`}>
<div>
<p className={`font-medium ${type === 'error' ? 'text-red-700' : type === 'warning' ? 'text-yellow-700' : 'text-gray-700'}`}>{text}</p>
<p className="text-xs text-gray-500">{time}</p>
</div>
<button onClick={() => onDismiss(id)} className="text-gray-400 hover:text-gray-600">
×
</button>
</div>
</motion.div>
);
};
export default NotificationItem;
tsx Copy code
// Update the DropdownMenuContent in Home component to use NotificationItem
import { AnimatePresence } from 'framer-motion';
import NotificationItem from '@/components/NotificationItem';
// Inside the DropdownMenuContent
{notifications.length > 0 ? (
<ScrollArea className="max-h-60">
<AnimatePresence>
{notifications.map((notif) => (
<NotificationItem
key={notif.id}
id={notif.id}
text={notif.text}
time={notif.time}
type={notif.type}
onDismiss={removeNotification}
/>
))}
</AnimatePresence>
</ScrollArea>
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
Explanation of Animations:
5. Final Touches
Testing:
Ensure that when new issues are detected, they appear in the notifications dropdown.
Verify that the notification count updates accordingly.
Test the dismiss functionality and ensure notifications can be removed seamlessly.
Styling Consistency:
Make sure that the styles across different components are consistent.
Adjust Tailwind CSS classes as needed to match your design system.
Accessibility:
Ensure that the notification system is accessible.
Add appropriate aria attributes and keyboard navigation support.
By following these steps, you've successfully removed the RecentIssuesTable from your dashboard and integrated recent issues into a robust and visually appealing notification system. This not only declutters your dashboard but also provides users with real-time alerts in an elegant manner.
Feel free to further customize the notification styles and behaviors to best fit your application's needs!
Show full message · 797 lines Copy first response
Not yet included in a published release.
// src/app/page.tsx or whichever file is your Home component
"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,
ChevronDown, 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 '@/contexts/NotificationContext';
// Dynamically import heavy components with loading fallbacks
const AdvancedAnalyticsDashboard = dynamic(
() => import('@/components/AdvancedAnalyticsDashboard'),
{
loading: () => <div className="p-4">Loading Dashboard...</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 role="alert" className="p-4">
<p className="text-red-500">Something went wrong:</p>
<pre className="mb-4">{error.message}</pre>
<button onClick={resetErrorBoundary} className="btn btn-primary">
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 router = useRouter();
const { notifications, addNotification } = useNotifications();
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: Settings, label: 'Settings', id: 'settings' },
// Add more menu items as needed
];
if (isLoading) {
return (
<div className="flex items-center justify-center h-screen">
<div className="text-center">
<p className="text-xl">Loading...</p>
<p className="text-muted-foreground">Setting up your dashboard</p>
</div>
</div>
);
}
if (!isAuthenticated) {
return (
<div className="flex items-center justify-center h-screen">
<div className="text-center">
<h1 className="text-2xl font-semibold">Access Denied</h1>
<p className="text-muted-foreground">Please log in to continue</p>
<Button onClick={() => router.push('/login')} className="mt-4">
Go to Login
</Button>
</div>
</div>
);
}
return (
<div className="flex h-screen">
{/* Sidebar */}
<aside className={`${isSidebarOpen ? 'w-64' : 'w-20'} bg-background border-r transition-all duration-300 flex flex-col`}>
<div className="flex items-center justify-center h-16 border-b">
{isSidebarOpen ? <span className="text-xl font-bold">Not1fy</span> : <span className="text-xl font-bold">N</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">
{/* Notification Dropdown */}
<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 rounded-full bg-red-500 text-white text-xs">
{notifications.length}
</Badge>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-4">
<DropdownMenuLabel className="font-semibold">Notifications</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length > 0 ? (
<ScrollArea className="max-h-60">
{notifications.map((notif) => (
<DropdownMenuItem key={notif.id} className="flex flex-col items-start gap-1">
<div className="flex items-center w-full justify-between">
<span className={`font-medium ${notif.type === 'error' ? 'text-red-600' : 'text-gray-800'}`}>
{notif.text}
</span>
<button onClick={() => addNotification(notif)} className="text-gray-400 hover:text-gray-600">
×
</button>
</div>
<span className="text-xs text-muted-foreground">{notif.time}</span>
</DropdownMenuItem>
))}
</ScrollArea>
) : (
<div className="p-4 text-center text-muted-foreground">
No new notifications
</div>
)}
<DropdownMenuSeparator />
<Button variant="ghost" className="w-full text-left">
View All
</Button>
</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 p-4">
<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>
);
}
// src/components/AdvancedAnalyticsDashboard.tsx
'use client';
import React, { useState, useEffect, 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 '@/contexts/NotificationContext';
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('day');
const [isLoading, setIsLoading] = useState(true);
const [isRealtime, setIsRealtime] = useState(false);
const [urlFilter, setUrlFilter] = useState('');
const [statusCodeFilter, setStatusCodeFilter] = useState('');
const [responseTimeRange, setResponseTimeRange] = useState<number[]>([0, 5000]);
const { toast } = useToast();
const { addNotification } = useNotifications();
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({
id: issue.id,
text: `Issue detected on ${issue.url} with status ${issue.statusCode}`,
time: new Date(issue.checkedAt).toLocaleString(),
type: 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="space-y-8">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Advanced Analytics Dashboard</h1>
<div className="flex items-center gap-2">
<Label className="flex items-center space-x-2">
<span>Realtime Updates</span>
<Switch checked={isRealtime} onCheckedChange={setIsRealtime} />
</Label>
<Button variant="ghost" onClick={loadAnalytics}>
<RefreshCw className="mr-2" />
Refresh
</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 RecentIssuesTable */}
</div>
</div>
);
};
export default AdvancedAnalyticsDashboard;