feat: Reports & Analytics page, CSV export, notification bell in header

- Reports page with overview stats, client growth chart, email activity chart
- Engagement breakdown (engaged/warm/cooling/cold) with stacked bar
- Industry and tag distribution charts
- At-risk client lists (cold + cooling)
- CSV export button downloads all clients
- Notification bell in top bar: overdue events, upcoming events, stale clients, pending drafts
- Dismissable notifications with priority indicators
- Added Reports to sidebar nav between Network and Settings
This commit is contained in:
2026-01-29 13:04:53 +00:00
parent e7c2e396c0
commit 4c7a8be5b8
5 changed files with 535 additions and 1 deletions

View File

@@ -11,6 +11,7 @@ import EmailsPage from '@/pages/EmailsPage';
import SettingsPage from '@/pages/SettingsPage';
import AdminPage from '@/pages/AdminPage';
import NetworkPage from '@/pages/NetworkPage';
import ReportsPage from '@/pages/ReportsPage';
import InvitePage from '@/pages/InvitePage';
import ForgotPasswordPage from '@/pages/ForgotPasswordPage';
import ResetPasswordPage from '@/pages/ResetPasswordPage';
@@ -50,6 +51,7 @@ export default function App() {
<Route path="events" element={<EventsPage />} />
<Route path="emails" element={<EmailsPage />} />
<Route path="network" element={<NetworkPage />} />
<Route path="reports" element={<ReportsPage />} />
<Route path="settings" element={<SettingsPage />} />
<Route path="admin" element={<AdminPage />} />
</Route>

View File

@@ -4,8 +4,9 @@ import { useAuthStore } from '@/stores/auth';
import { cn } from '@/lib/utils';
import {
LayoutDashboard, Users, Calendar, Mail, Settings, Shield,
LogOut, Menu, X, ChevronLeft, Network,
LogOut, Menu, X, ChevronLeft, Network, BarChart3,
} from 'lucide-react';
import NotificationBell from './NotificationBell';
const baseNavItems = [
{ path: '/', label: 'Dashboard', icon: LayoutDashboard },
@@ -13,6 +14,7 @@ const baseNavItems = [
{ path: '/events', label: 'Events', icon: Calendar },
{ path: '/emails', label: 'Emails', icon: Mail },
{ path: '/network', label: 'Network', icon: Network },
{ path: '/reports', label: 'Reports', icon: BarChart3 },
{ path: '/settings', label: 'Settings', icon: Settings },
];
@@ -124,6 +126,7 @@ export default function Layout() {
{mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
</button>
<div className="flex-1" />
<NotificationBell />
</header>
{/* Content */}

View File

@@ -0,0 +1,173 @@
import { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import { Bell, AlertTriangle, Calendar, Users, Mail, Clock, X } from 'lucide-react';
import { cn } from '@/lib/utils';
interface Notification {
id: string;
type: 'overdue' | 'upcoming' | 'stale' | 'drafts';
title: string;
description: string;
date: string;
link: string;
priority: 'high' | 'medium' | 'low';
}
interface NotifCounts {
total: number;
high: number;
overdue: number;
upcoming: number;
stale: number;
drafts: number;
}
const typeIcons: Record<string, typeof Calendar> = {
overdue: AlertTriangle,
upcoming: Calendar,
stale: Users,
drafts: Mail,
};
const typeColors: Record<string, string> = {
overdue: 'text-red-500 bg-red-50',
upcoming: 'text-blue-500 bg-blue-50',
stale: 'text-amber-500 bg-amber-50',
drafts: 'text-purple-500 bg-purple-50',
};
const priorityDot: Record<string, string> = {
high: 'bg-red-500',
medium: 'bg-amber-400',
low: 'bg-slate-300',
};
export default function NotificationBell() {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [counts, setCounts] = useState<NotifCounts | null>(null);
const [open, setOpen] = useState(false);
const [dismissed, setDismissed] = useState<Set<string>>(new Set());
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
fetchNotifications();
// Refresh every 5 minutes
const interval = setInterval(fetchNotifications, 5 * 60 * 1000);
return () => clearInterval(interval);
}, []);
// Close on outside click
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
};
if (open) document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, [open]);
const fetchNotifications = async () => {
try {
const data = await api.getNotifications();
setNotifications(data.notifications || []);
setCounts(data.counts || null);
} catch {
// Silently fail
}
};
const dismiss = (id: string) => {
setDismissed(prev => new Set(prev).add(id));
};
const visibleNotifs = notifications.filter(n => !dismissed.has(n.id));
const activeCount = visibleNotifs.length;
const highCount = visibleNotifs.filter(n => n.priority === 'high').length;
return (
<div ref={ref} className="relative">
<button
onClick={() => setOpen(!open)}
className={cn(
'relative p-2 rounded-lg transition-colors',
open ? 'bg-slate-100 text-slate-700' : 'text-slate-400 hover:bg-slate-100 hover:text-slate-600'
)}
>
<Bell className="w-5 h-5" />
{activeCount > 0 && (
<span className={cn(
'absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] flex items-center justify-center rounded-full text-[10px] font-bold text-white px-1',
highCount > 0 ? 'bg-red-500' : 'bg-blue-500'
)}>
{activeCount > 99 ? '99+' : activeCount}
</span>
)}
</button>
{open && (
<div className="absolute right-0 top-full mt-2 w-80 sm:w-96 bg-white rounded-xl border border-slate-200 shadow-xl z-50 overflow-hidden">
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-100">
<h3 className="text-sm font-semibold text-slate-800">Notifications</h3>
{counts && (
<div className="flex items-center gap-2 text-xs text-slate-400">
{counts.overdue > 0 && (
<span className="text-red-500 font-medium">{counts.overdue} overdue</span>
)}
{counts.upcoming > 0 && (
<span>{counts.upcoming} upcoming</span>
)}
</div>
)}
</div>
<div className="max-h-[400px] overflow-y-auto">
{visibleNotifs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-slate-400">
<Clock className="w-8 h-8 mb-2" />
<p className="text-sm">All caught up!</p>
</div>
) : (
visibleNotifs.map(n => {
const Icon = typeIcons[n.type] || Calendar;
return (
<div key={n.id} className="flex items-start gap-3 px-4 py-3 hover:bg-slate-50 border-b border-slate-50 last:border-0">
<div className={cn('p-1.5 rounded-lg mt-0.5', typeColors[n.type] || 'bg-slate-50 text-slate-500')}>
<Icon className="w-4 h-4" />
</div>
<Link to={n.link} onClick={() => setOpen(false)} className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<div className={cn('w-1.5 h-1.5 rounded-full flex-shrink-0', priorityDot[n.priority])} />
<p className="text-sm font-medium text-slate-800 truncate">{n.title}</p>
</div>
<p className="text-xs text-slate-400 mt-0.5">{n.description}</p>
</Link>
<button
onClick={() => dismiss(n.id)}
className="p-1 rounded text-slate-300 hover:text-slate-500 hover:bg-slate-100 flex-shrink-0"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
);
})
)}
</div>
{visibleNotifs.length > 0 && (
<div className="border-t border-slate-100 px-4 py-2.5">
<Link
to="/reports"
onClick={() => setOpen(false)}
className="text-xs text-blue-600 hover:text-blue-700 font-medium"
>
View Reports
</Link>
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -404,6 +404,49 @@ class ApiClient {
}
return response.json();
}
// Reports & Analytics
async getReportsOverview(): Promise<any> {
return this.fetch('/reports/overview');
}
async getReportsGrowth(): Promise<any> {
return this.fetch('/reports/growth');
}
async getReportsIndustries(): Promise<any[]> {
return this.fetch('/reports/industries');
}
async getReportsTags(): Promise<any[]> {
return this.fetch('/reports/tags');
}
async getReportsEngagement(): Promise<any> {
return this.fetch('/reports/engagement');
}
async getNotifications(): Promise<any> {
return this.fetch('/reports/notifications');
}
async exportClientsCSV(): Promise<void> {
const token = this.getToken();
const headers: HeadersInit = token ? { Authorization: `Bearer ${token}` } : {};
const response = await fetch(`${API_BASE}/reports/export/clients`, {
headers,
credentials: 'include',
});
if (!response.ok) throw new Error('Export failed');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `clients-export-${new Date().toISOString().split('T')[0]}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
}
export const api = new ApiClient();

313
src/pages/ReportsPage.tsx Normal file
View File

@@ -0,0 +1,313 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import {
BarChart3, Users, Mail, Calendar, TrendingUp, Download,
Activity, Tag, Building2, AlertTriangle, Flame, Snowflake, ThermometerSun,
} from 'lucide-react';
import { PageLoader } from '@/components/LoadingSpinner';
import { cn } from '@/lib/utils';
interface Overview {
clients: { total: number; newThisMonth: number; newThisWeek: number; contactedRecently: number; neverContacted: number };
emails: { total: number; sent: number; draft: number; sentLast30Days: number };
events: { total: number; upcoming30Days: number };
}
interface GrowthData {
clientGrowth: { month: string; count: number }[];
emailActivity: { month: string; count: number }[];
}
interface IndustryData {
industry: string | null;
count: number;
}
interface TagData {
tag: string;
count: number;
}
interface EngagementData {
summary: { engaged: number; warm: number; cooling: number; cold: number };
coldClients: { id: string; name: string; company: string | null; lastContacted: string | null }[];
coolingClients: { id: string; name: string; company: string | null; lastContacted: string | null }[];
}
function StatCard({ icon: Icon, label, value, sub, color }: {
icon: typeof Users; label: string; value: number | string; sub?: string; color: string;
}) {
return (
<div className="bg-white rounded-xl border border-slate-200 p-5 flex items-start gap-4">
<div className={cn('p-2.5 rounded-xl', color)}>
<Icon className="w-5 h-5" />
</div>
<div>
<p className="text-2xl font-bold text-slate-900">{value}</p>
<p className="text-sm text-slate-500">{label}</p>
{sub && <p className="text-xs text-slate-400 mt-0.5">{sub}</p>}
</div>
</div>
);
}
function BarChartSimple({ data, label, color }: {
data: { label: string; value: number }[];
label: string;
color: string;
}) {
const max = Math.max(...data.map(d => d.value), 1);
return (
<div className="bg-white rounded-xl border border-slate-200 p-5">
<h3 className="text-sm font-semibold text-slate-700 mb-4">{label}</h3>
<div className="flex items-end gap-1.5 h-32">
{data.map((d, i) => (
<div key={i} className="flex-1 flex flex-col items-center gap-1">
<span className="text-[10px] text-slate-500 font-medium">{d.value || ''}</span>
<div
className={cn('w-full rounded-t transition-all', color)}
style={{ height: `${Math.max((d.value / max) * 100, 2)}%`, minHeight: d.value > 0 ? 4 : 2 }}
/>
<span className="text-[10px] text-slate-400 truncate w-full text-center">
{d.label}
</span>
</div>
))}
</div>
</div>
);
}
function EngagementRing({ summary }: { summary: EngagementData['summary'] }) {
const total = summary.engaged + summary.warm + summary.cooling + summary.cold;
if (total === 0) return null;
const segments = [
{ label: 'Engaged', count: summary.engaged, color: 'bg-emerald-500', textColor: 'text-emerald-600', icon: Flame },
{ label: 'Warm', count: summary.warm, color: 'bg-amber-400', textColor: 'text-amber-600', icon: ThermometerSun },
{ label: 'Cooling', count: summary.cooling, color: 'bg-blue-400', textColor: 'text-blue-600', icon: Activity },
{ label: 'Cold', count: summary.cold, color: 'bg-slate-300', textColor: 'text-slate-500', icon: Snowflake },
];
return (
<div className="bg-white rounded-xl border border-slate-200 p-5">
<h3 className="text-sm font-semibold text-slate-700 mb-4">Engagement Breakdown</h3>
{/* Stacked bar */}
<div className="flex rounded-full h-4 overflow-hidden mb-4">
{segments.map(s => (
s.count > 0 && (
<div
key={s.label}
className={cn(s.color, 'transition-all')}
style={{ width: `${(s.count / total) * 100}%` }}
title={`${s.label}: ${s.count}`}
/>
)
))}
</div>
<div className="grid grid-cols-2 gap-3">
{segments.map(s => (
<div key={s.label} className="flex items-center gap-2">
<div className={cn('w-3 h-3 rounded-full', s.color)} />
<div>
<span className={cn('text-sm font-semibold', s.textColor)}>{s.count}</span>
<span className="text-xs text-slate-400 ml-1">{s.label}</span>
</div>
</div>
))}
</div>
<p className="text-xs text-slate-400 mt-3">
Engaged = contacted in last 14 days Warm = 15-30 days Cooling = 31-60 days Cold = 60+ days or never
</p>
</div>
);
}
function TopList({ title, items, icon: Icon }: {
title: string;
items: { label: string; value: number }[];
icon: typeof Tag;
}) {
const max = Math.max(...items.map(i => i.value), 1);
return (
<div className="bg-white rounded-xl border border-slate-200 p-5">
<div className="flex items-center gap-2 mb-4">
<Icon className="w-4 h-4 text-slate-400" />
<h3 className="text-sm font-semibold text-slate-700">{title}</h3>
</div>
{items.length === 0 && (
<p className="text-sm text-slate-400">No data yet</p>
)}
<div className="space-y-2.5">
{items.slice(0, 8).map((item, i) => (
<div key={i}>
<div className="flex justify-between text-sm mb-1">
<span className="text-slate-700 truncate">{item.label}</span>
<span className="text-slate-500 font-medium ml-2">{item.value}</span>
</div>
<div className="h-1.5 bg-slate-100 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 rounded-full transition-all"
style={{ width: `${(item.value / max) * 100}%` }}
/>
</div>
</div>
))}
</div>
</div>
);
}
function AtRiskList({ title, clients: clientList }: {
title: string;
clients: { id: string; name: string; company: string | null; lastContacted: string | null }[];
}) {
if (clientList.length === 0) return null;
return (
<div className="bg-white rounded-xl border border-slate-200 p-5">
<div className="flex items-center gap-2 mb-4">
<AlertTriangle className="w-4 h-4 text-amber-500" />
<h3 className="text-sm font-semibold text-slate-700">{title}</h3>
</div>
<div className="space-y-2">
{clientList.map(c => (
<Link
key={c.id}
to={`/clients/${c.id}`}
className="flex items-center justify-between p-2 rounded-lg hover:bg-slate-50 transition-colors"
>
<div>
<p className="text-sm font-medium text-slate-800">{c.name}</p>
{c.company && <p className="text-xs text-slate-400">{c.company}</p>}
</div>
<span className="text-xs text-slate-400">
{c.lastContacted
? `${Math.floor((Date.now() - new Date(c.lastContacted).getTime()) / (1000 * 60 * 60 * 24))}d ago`
: 'Never'}
</span>
</Link>
))}
</div>
</div>
);
}
// Fill in missing months with 0
function fillMonths(data: { month: string; count: number }[]): { label: string; value: number }[] {
const now = new Date();
const months: { label: string; value: number }[] = [];
for (let i = 11; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
const label = d.toLocaleString('default', { month: 'short' });
const match = data.find(m => m.month === key);
months.push({ label, value: match?.count || 0 });
}
return months;
}
export default function ReportsPage() {
const [overview, setOverview] = useState<Overview | null>(null);
const [growth, setGrowth] = useState<GrowthData | null>(null);
const [industries, setIndustries] = useState<IndustryData[]>([]);
const [tags, setTags] = useState<TagData[]>([]);
const [engagement, setEngagement] = useState<EngagementData | null>(null);
const [loading, setLoading] = useState(true);
const [exporting, setExporting] = useState(false);
useEffect(() => {
Promise.all([
api.getReportsOverview().catch(() => null),
api.getReportsGrowth().catch(() => null),
api.getReportsIndustries().catch(() => []),
api.getReportsTags().catch(() => []),
api.getReportsEngagement().catch(() => null),
]).then(([ov, gr, ind, tg, eng]) => {
setOverview(ov as Overview | null);
setGrowth(gr as GrowthData | null);
setIndustries(ind as IndustryData[]);
setTags(tg as TagData[]);
setEngagement(eng as EngagementData | null);
setLoading(false);
});
}, []);
const handleExport = async () => {
setExporting(true);
try {
await api.exportClientsCSV();
} finally {
setExporting(false);
}
};
if (loading) return <PageLoader />;
return (
<div className="max-w-6xl mx-auto space-y-6 animate-fade-in">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h1 className="text-2xl font-bold text-slate-900">Reports & Analytics</h1>
<p className="text-sm text-slate-500">Overview of your CRM performance</p>
</div>
<button
onClick={handleExport}
disabled={exporting}
className="flex items-center gap-2 px-4 py-2 bg-white border border-slate-200 rounded-lg text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors disabled:opacity-50"
>
<Download className="w-4 h-4" />
{exporting ? 'Exporting…' : 'Export Clients CSV'}
</button>
</div>
{/* Overview Stats */}
{overview && (
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard icon={Users} label="Total Clients" value={overview.clients.total}
sub={`+${overview.clients.newThisMonth} this month`}
color="bg-blue-50 text-blue-600" />
<StatCard icon={Mail} label="Emails Sent" value={overview.emails.sent}
sub={`${overview.emails.sentLast30Days} last 30 days`}
color="bg-emerald-50 text-emerald-600" />
<StatCard icon={Calendar} label="Upcoming Events" value={overview.events.upcoming30Days}
sub="Next 30 days"
color="bg-amber-50 text-amber-600" />
<StatCard icon={TrendingUp} label="Contacted Recently" value={overview.clients.contactedRecently}
sub={`${overview.clients.neverContacted} never contacted`}
color="bg-purple-50 text-purple-600" />
</div>
)}
{/* Growth Charts */}
{growth && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<BarChartSimple
data={fillMonths(growth.clientGrowth)}
label="Client Growth (Last 12 Months)"
color="bg-blue-500"
/>
<BarChartSimple
data={fillMonths(growth.emailActivity)}
label="Email Activity (Last 12 Months)"
color="bg-emerald-500"
/>
</div>
)}
{/* Engagement + Distributions */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
{engagement && <EngagementRing summary={engagement.summary} />}
<TopList title="Top Industries" items={industries.map(i => ({ label: i.industry || 'Unknown', value: i.count }))} icon={Building2} />
<TopList title="Top Tags" items={tags.map(t => ({ label: t.tag, value: t.count }))} icon={Tag} />
</div>
{/* At-risk clients */}
{engagement && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<AtRiskList title="Cold Clients (60+ days)" clients={engagement.coldClients} />
<AtRiskList title="Cooling Clients (31-60 days)" clients={engagement.coolingClients} />
</div>
)}
</div>
);
}