![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/lavocat.ca/private_html/src/pages/lawyer/ |
import React, { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
import LayoutWithSidebar from '@/components/LayoutWithSidebar';
import { toast } from 'react-hot-toast';
import {
TrendingUp,
TrendingDown,
DollarSign,
Users,
Calendar,
CheckCircle,
Clock,
AlertCircle,
BarChart3,
PieChart,
Download,
Filter,
RefreshCw
} from 'lucide-react';
interface AnalyticsData {
overview: {
totalCases: number;
activeCases: number;
completedCases: number;
totalRevenue: number;
monthlyRevenue: number;
totalConsultations: number;
completedConsultations: number;
teamMembers: number;
averageCaseDuration: number;
};
performance: {
winRate: number;
clientSatisfaction: number;
averageResponseTime: number;
taskCompletionRate: number;
};
revenue: {
monthly: Array<{ month: string; revenue: number }>;
byCaseType: Array<{ type: string; revenue: number }>;
byLawyer: Array<{ name: string; revenue: number }>;
};
cases: {
byStatus: Array<{ status: string; count: number }>;
byType: Array<{ type: string; count: number }>;
timeline: Array<{ date: string; cases: number }>;
};
consultations: {
byStatus: Array<{ status: string; count: number }>;
byType: Array<{ type: string; count: number }>;
completionRate: number;
};
}
const LawyerAnalytics: React.FC = () => {
const { data: session, status } = useSession();
const router = useRouter();
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
const [loading, setLoading] = useState(true);
const [timeRange, setTimeRange] = useState('30d');
const [refreshing, setRefreshing] = useState(false);
useEffect(() => {
if (status === 'loading') return;
if (!session || !['LAWYER', 'ADMIN', 'SUPERADMIN'].includes(session.user.role)) {
router.push('/');
return;
}
fetchAnalytics();
}, [session, status, router, timeRange]);
const fetchAnalytics = async () => {
try {
setLoading(true);
const params = new URLSearchParams({
range: timeRange,
lawyerId: session?.user?.id || ''
});
const response = await fetch(`/api/lawyer/analytics?${params}`);
if (response.ok) {
const data = await response.json();
setAnalytics(data);
} else {
const errorData = await response.json();
console.error('Failed to load analytics:', errorData.error);
toast.error('Failed to load analytics. Please try again.');
}
} catch (error) {
console.error('Error fetching analytics:', error);
toast.error('Network error. Please check your connection.');
} finally {
setLoading(false);
}
};
const refreshData = async () => {
setRefreshing(true);
await fetchAnalytics();
setRefreshing(false);
toast.success('Analytics refreshed');
};
// Auto-refresh every 5 minutes
useEffect(() => {
const interval = setInterval(() => {
if (!loading && !refreshing) {
fetchAnalytics();
}
}, 5 * 60 * 1000); // 5 minutes
return () => clearInterval(interval);
}, [loading, refreshing]);
const exportReport = async (format: 'pdf' | 'excel') => {
try {
const response = await fetch(`/api/lawyer/analytics/export?format=${format}&range=${timeRange}`);
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `analytics-report-${timeRange}.${format === 'pdf' ? 'pdf' : 'xlsx'}`;
a.click();
window.URL.revokeObjectURL(url);
toast.success(`Report exported as ${format.toUpperCase()}`);
} else {
toast.error('Failed to export report');
}
} catch (error) {
toast.error('Failed to export report');
}
};
const getPercentageChange = (current: number, previous: number) => {
if (previous === 0) return current > 0 ? 100 : 0;
return ((current - previous) / previous) * 100;
};
const getTrendIcon = (change: number) => {
if (change > 0) return <TrendingUp className="h-4 w-4 text-green-500" />;
if (change < 0) return <TrendingDown className="h-4 w-4 text-red-500" />;
return <TrendingUp className="h-4 w-4 text-gray-400" />;
};
if (status === 'loading' || loading) {
return (
<LayoutWithSidebar>
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
</div>
</LayoutWithSidebar>
);
}
return (
<LayoutWithSidebar>
<div className="max-w-7xl mx-auto px-4 py-8">
{/* Header */}
<div className="mb-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-gray-900">Analytics Dashboard</h1>
<p className="text-gray-600 mt-1">Comprehensive insights into your legal practice performance</p>
</div>
<div className="flex items-center gap-3">
<select
value={timeRange}
onChange={(e) => setTimeRange(e.target.value)}
className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
>
<option value="7d">Last 7 days</option>
<option value="30d">Last 30 days</option>
<option value="90d">Last 90 days</option>
<option value="1y">Last year</option>
</select>
<button
onClick={refreshData}
disabled={refreshing}
className="p-2 text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors"
title="Refresh Data"
>
<RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
</button>
<div className="flex items-center gap-2 text-sm text-gray-500">
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
<span>Auto-refresh every 5 minutes</span>
</div>
<div className="flex gap-2">
<button
onClick={() => exportReport('pdf')}
className="inline-flex items-center px-3 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm"
>
<Download className="h-4 w-4 mr-2" />
PDF
</button>
<button
onClick={() => exportReport('excel')}
className="inline-flex items-center px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm"
>
<Download className="h-4 w-4 mr-2" />
Excel
</button>
</div>
</div>
</div>
</div>
{analytics ? (
<>
{/* Overview Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Total Revenue</p>
<p className="text-2xl font-bold text-gray-900">
${analytics.overview.totalRevenue.toLocaleString()}
</p>
<div className="flex items-center gap-1 mt-1">
{getTrendIcon(getPercentageChange(analytics.overview.monthlyRevenue, analytics.overview.totalRevenue / 12))}
<span className="text-sm text-gray-600">
{getPercentageChange(analytics.overview.monthlyRevenue, analytics.overview.totalRevenue / 12).toFixed(1)}%
</span>
</div>
</div>
<DollarSign className="h-8 w-8 text-green-600" />
</div>
</div>
<div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Active Cases</p>
<p className="text-2xl font-bold text-gray-900">{analytics.overview.activeCases}</p>
<p className="text-sm text-gray-600 mt-1">
{((analytics.overview.activeCases / analytics.overview.totalCases) * 100).toFixed(1)}% of total
</p>
</div>
<BarChart3 className="h-8 w-8 text-blue-600" />
</div>
</div>
<div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Win Rate</p>
<p className="text-2xl font-bold text-gray-900">{analytics.performance.winRate}%</p>
<p className="text-sm text-gray-600 mt-1">
{analytics.overview.completedCases} completed cases
</p>
</div>
<CheckCircle className="h-8 w-8 text-green-600" />
</div>
</div>
<div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Consultations</p>
<p className="text-2xl font-bold text-gray-900">{analytics.overview.totalConsultations}</p>
<p className="text-sm text-gray-600 mt-1">
{analytics.consultations.completionRate}% completion rate
</p>
</div>
<Users className="h-8 w-8 text-purple-600" />
</div>
</div>
</div>
{/* Performance Metrics */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Performance Metrics</h3>
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600">Client Satisfaction</span>
<span className="text-sm font-medium text-gray-900">{analytics.performance.clientSatisfaction}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-green-600 h-2 rounded-full"
style={{ width: `${analytics.performance.clientSatisfaction}%` }}
></div>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600">Average Response Time</span>
<span className="text-sm font-medium text-gray-900">{analytics.performance.averageResponseTime}h</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full"
style={{ width: `${Math.max(0, 100 - analytics.performance.averageResponseTime * 10)}%` }}
></div>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600">Task Completion Rate</span>
<span className="text-sm font-medium text-gray-900">{analytics.performance.taskCompletionRate}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-purple-600 h-2 rounded-full"
style={{ width: `${analytics.performance.taskCompletionRate}%` }}
></div>
</div>
</div>
</div>
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Case Distribution</h3>
<div className="space-y-3">
{analytics.cases.byType.map((caseType, index) => (
<div key={caseType.type} className="flex items-center justify-between">
<span className="text-sm text-gray-600">{caseType.type}</span>
<div className="flex items-center gap-2">
<div className="w-16 bg-gray-200 rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full"
style={{ width: `${(caseType.count / analytics.overview.totalCases) * 100}%` }}
></div>
</div>
<span className="text-sm font-medium text-gray-900 w-8">{caseType.count}</span>
</div>
</div>
))}
</div>
</div>
</div>
{/* Revenue Analytics */}
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Revenue by Case Type</h3>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{analytics.revenue.byCaseType.map((item) => (
<div key={item.type} className="bg-gray-50 rounded-lg p-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-900">{item.type}</span>
<span className="text-sm text-gray-600">${item.revenue.toLocaleString()}</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2 mt-2">
<div
className="bg-green-600 h-2 rounded-full"
style={{ width: `${(item.revenue / analytics.overview.totalRevenue) * 100}%` }}
></div>
</div>
</div>
))}
</div>
</div>
{/* Team Performance */}
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Team Performance</h3>
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Team Member
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Revenue
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Cases
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Win Rate
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{analytics.revenue.byLawyer.map((lawyer, index) => (
<tr key={index}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{lawyer.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
${lawyer.revenue.toLocaleString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{/* Placeholder - would need case count per lawyer */}
-
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{/* Placeholder - would need win rate per lawyer */}
-
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</>
) : (
<div className="text-center py-12">
<BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">No analytics data available</h3>
<p className="text-gray-500">Start using the platform to see your performance metrics</p>
</div>
)}
</div>
</LayoutWithSidebar>
);
};
export default LawyerAnalytics;