![]() 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/.cursor-server/data/User/History/-3ecb40d5/ |
import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client';
import { getServerSession } from 'next-auth';
import { authOptions } from '../../../lib/auth';
const prisma = new PrismaClient();
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get all public cases
const cases = await prisma.legal_cases.findMany({
where: {
isPublic: true,
status: {
notIn: ['COMPLETED', 'CANCELLED']
}
},
select: {
id: true,
title: true,
status: true,
urgencyLevel: true,
estimatedValue: true,
createdAt: true,
updatedAt: true,
category: true,
jurisdiction: true
}
});
// Get all lawyers
const lawyers = await prisma.users.findMany({
where: {
role: 'LAWYER',
isVerified: true
},
select: {
id: true,
name: true,
averageRating: true,
totalCases: true,
wonCases: true
}
});
// Get all clients
const clients = await prisma.users.findMany({
where: {
role: 'CLIENT'
},
select: {
id: true
}
});
// Calculate statistics
const totalCases = cases.length;
const activeCases = cases.filter(c => c.status === 'ACTIVE').length;
const urgentCases = cases.filter(c => c.urgencyLevel === 'URGENT').length;
const totalValue = cases.reduce((sum, c) => sum + (c.estimatedValue || 0), 0);
const averageCaseValue = totalCases > 0 ? totalValue / totalCases : 0;
const totalLawyers = lawyers.length;
const totalClients = clients.length;
// Calculate success rate (based on completed cases)
const completedCases = await prisma.legal_cases.count({
where: {
status: 'COMPLETED'
}
});
const totalCompletedCases = await prisma.legal_cases.count({
where: {
status: {
in: ['COMPLETED', 'CANCELLED']
}
}
});
const successRate = totalCompletedCases > 0 ? Math.round((completedCases / totalCompletedCases) * 100) : 0;
// Calculate average response time (mock data for now)
const averageResponseTime = 24; // 24 hours average
// Calculate top categories
const categoryCounts = cases.reduce((acc, c) => {
if (c.category) {
acc[c.category] = (acc[c.category] || 0) + 1;
}
return acc;
}, {} as Record<string, number>);
const topCategories = Object.entries(categoryCounts)
.map(([name, count]) => ({
name,
count,
percentage: Math.round((count / totalCases) * 100)
}))
.sort((a, b) => b.count - a.count)
.slice(0, 10);
// Calculate top jurisdictions
const jurisdictionCounts = cases.reduce((acc, c) => {
acc[c.jurisdiction] = (acc[c.jurisdiction] || 0) + 1;
return acc;
}, {} as Record<string, number>);
const topJurisdictions = Object.entries(jurisdictionCounts)
.map(([name, count]) => ({
name,
count,
percentage: Math.round((count / totalCases) * 100)
}))
.sort((a, b) => b.count - a.count)
.slice(0, 10);
// Generate recent activity (simplified - based on recent case updates)
const recentActivity = await prisma.legal_cases.findMany({
where: {
isPublic: true
},
orderBy: {
updatedAt: 'desc'
},
take: 10,
select: {
title: true,
updatedAt: true
}
});
const activityFeed = recentActivity.map(c => {
const timeDiff = Date.now() - new Date(c.updatedAt).getTime();
const hoursAgo = Math.floor(timeDiff / (1000 * 60 * 60));
const daysAgo = Math.floor(hoursAgo / 24);
let timestamp;
if (daysAgo > 0) {
timestamp = `${daysAgo} day${daysAgo > 1 ? 's' : ''} ago`;
} else if (hoursAgo > 0) {
timestamp = `${hoursAgo} hour${hoursAgo > 1 ? 's' : ''} ago`;
} else {
timestamp = 'Just now';
}
return {
type: 'CASE_UPDATE',
description: `Case "${c.title}" was updated`,
timestamp
};
});
// Add some mock activities for demonstration
const mockActivities = [
{
type: 'NEW_CASE',
description: 'New urgent case posted in Civil Litigation',
timestamp: '2 hours ago'
},
{
type: 'LAWYER_JOIN',
description: '5 new lawyers joined the platform',
timestamp: '4 hours ago'
},
{
type: 'CASE_COMPLETED',
description: 'Family law case successfully resolved',
timestamp: '1 day ago'
}
];
const allRecentActivity = [...mockActivities, ...activityFeed].slice(0, 10);
const stats = {
totalCases,
activeCases,
urgentCases,
totalValue,
averageCaseValue: Math.round(averageCaseValue),
totalLawyers,
totalClients,
successRate,
averageResponseTime,
topCategories,
topJurisdictions,
recentActivity: allRecentActivity
};
res.status(200).json(stats);
} catch (error) {
console.error('Error fetching live cases stats:', error);
res.status(500).json({ error: 'Failed to fetch statistics' });
} finally {
await prisma.$disconnect();
}
}