Files
biblical-guide.com/app/api/admin/analytics/overview/route.ts
Andrei 2074ee3bda Complete admin dashboard implementation with comprehensive features
🚀 Major Update: v2.0.0 - Complete Administrative Dashboard

## Phase 1: Dashboard Overview & Authentication 
- Secure admin authentication with JWT tokens
- Beautiful overview dashboard with key metrics
- Role-based access control (admin, moderator permissions)
- Professional MUI design with responsive layout

## Phase 2: User Management & Content Moderation 
- Complete user management with advanced data grid
- Prayer request content moderation system
- User actions: view, suspend, activate, promote, delete
- Content approval/rejection workflows

## Phase 3: Analytics Dashboard 
- Comprehensive analytics with interactive charts (Recharts)
- User activity analytics with retention tracking
- Content engagement metrics and trends
- Real-time statistics and performance monitoring

## Phase 4: Chat Monitoring & System Administration 
- Advanced conversation monitoring with content analysis
- System health monitoring and backup management
- Security oversight and automated alerts
- Complete administrative control panel

## Key Features Added:
 **32 new API endpoints** for complete admin functionality
 **Material-UI DataGrid** with advanced filtering and pagination
 **Interactive Charts** using Recharts library
 **Real-time Monitoring** with auto-refresh capabilities
 **System Health Dashboard** with performance metrics
 **Database Backup System** with automated scheduling
 **Content Filtering** with automated moderation alerts
 **Role-based Permissions** with granular access control
 **Professional UI/UX** with consistent MUI design
 **Visit Website Button** in admin header for easy navigation

## Technical Implementation:
- **Frontend**: Material-UI components with responsive design
- **Backend**: 32 new API routes with proper authentication
- **Database**: Optimized queries with proper indexing
- **Security**: Admin-specific JWT authentication
- **Performance**: Efficient data loading with pagination
- **Charts**: Interactive visualizations with Recharts

The Biblical Guide application now provides world-class administrative capabilities for complete platform management!

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-23 12:01:34 +00:00

239 lines
5.7 KiB
TypeScript

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getCurrentAdmin, AdminPermission, hasPermission } from '@/lib/admin-auth';
export const runtime = 'nodejs';
export async function GET(request: Request) {
try {
const admin = await getCurrentAdmin();
if (!admin || !hasPermission(admin, AdminPermission.VIEW_ANALYTICS)) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const url = new URL(request.url);
const period = url.searchParams.get('period') || '30'; // days
const periodDays = parseInt(period);
const startDate = new Date();
startDate.setDate(startDate.getDate() - periodDays);
// User statistics
const totalUsers = await prisma.user.count();
const newUsers = await prisma.user.count({
where: {
createdAt: {
gte: startDate
}
}
});
const activeUsers = await prisma.user.count({
where: {
lastLoginAt: {
gte: startDate
}
}
});
// Content statistics
const totalPrayerRequests = await prisma.prayerRequest.count();
const activePrayerRequests = await prisma.prayerRequest.count({
where: { isActive: true }
});
const newPrayerRequests = await prisma.prayerRequest.count({
where: {
createdAt: {
gte: startDate
}
}
});
// Prayer statistics
const totalPrayers = await prisma.prayer.count();
const newPrayers = await prisma.prayer.count({
where: {
createdAt: {
gte: startDate
}
}
});
// Chat statistics
const totalConversations = await prisma.chatConversation.count();
const activeConversations = await prisma.chatConversation.count({
where: { isActive: true }
});
const newConversations = await prisma.chatConversation.count({
where: {
createdAt: {
gte: startDate
}
}
});
const totalMessages = await prisma.chatMessage.count();
const newMessages = await prisma.chatMessage.count({
where: {
timestamp: {
gte: startDate
}
}
});
// Bookmark statistics
const totalBookmarks = await prisma.bookmark.count();
const newBookmarks = await prisma.bookmark.count({
where: {
createdAt: {
gte: startDate
}
}
});
// User role distribution
const usersByRole = await prisma.user.groupBy({
by: ['role'],
_count: {
role: true
}
});
// Prayer request categories
const prayersByCategory = await prisma.prayerRequest.groupBy({
by: ['category'],
_count: {
category: true
},
where: {
isActive: true
}
});
// Top prayer requests by prayer count
const topPrayerRequests = await prisma.prayerRequest.findMany({
select: {
id: true,
title: true,
category: true,
prayerCount: true,
author: true
},
where: {
isActive: true
},
orderBy: {
prayerCount: 'desc'
},
take: 10
});
// Recent activity (last 7 days daily breakdown)
const last7Days = Array.from({ length: 7 }, (_, i) => {
const date = new Date();
date.setDate(date.getDate() - i);
return date.toISOString().split('T')[0];
}).reverse();
const dailyActivity = await Promise.all(
last7Days.map(async (date) => {
const startOfDay = new Date(date + 'T00:00:00.000Z');
const endOfDay = new Date(date + 'T23:59:59.999Z');
const [newUsers, newPrayers, newConversations, newBookmarks] = await Promise.all([
prisma.user.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
}),
prisma.prayer.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
}),
prisma.chatConversation.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
}),
prisma.bookmark.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
})
]);
return {
date,
newUsers,
newPrayers,
newConversations,
newBookmarks
};
})
);
return NextResponse.json({
period: periodDays,
overview: {
users: {
total: totalUsers,
new: newUsers,
active: activeUsers
},
prayerRequests: {
total: totalPrayerRequests,
active: activePrayerRequests,
new: newPrayerRequests
},
prayers: {
total: totalPrayers,
new: newPrayers
},
conversations: {
total: totalConversations,
active: activeConversations,
new: newConversations
},
messages: {
total: totalMessages,
new: newMessages
},
bookmarks: {
total: totalBookmarks,
new: newBookmarks
}
},
distributions: {
usersByRole,
prayersByCategory
},
topContent: {
prayerRequests: topPrayerRequests
},
activity: {
daily: dailyActivity
}
});
} catch (error) {
console.error('Admin analytics overview error:', error);
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}