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>
This commit is contained in:
2025-09-23 12:01:34 +00:00
parent ee99e93ec2
commit 39b6899315
48 changed files with 8525 additions and 5198 deletions

View File

@@ -0,0 +1,272 @@
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);
// Prayer request engagement
const prayerRequestEngagement = await prisma.prayerRequest.findMany({
select: {
id: true,
title: true,
category: true,
author: true,
prayerCount: true,
createdAt: true,
isActive: true,
_count: {
select: {
prayers: true,
userPrayers: true
}
}
},
where: {
createdAt: {
gte: startDate
}
},
orderBy: {
prayerCount: 'desc'
},
take: 50
});
// Prayer request engagement timeline
const prayerEngagementTimeline = await Promise.all(
Array.from({ length: periodDays }, (_, i) => {
const date = new Date();
date.setDate(date.getDate() - i);
return date.toISOString().split('T')[0];
}).reverse().map(async (date) => {
const startOfDay = new Date(date + 'T00:00:00.000Z');
const endOfDay = new Date(date + 'T23:59:59.999Z');
const [newRequests, newPrayers] = await Promise.all([
prisma.prayerRequest.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
}),
prisma.prayer.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
})
]);
return {
date,
newRequests,
newPrayers
};
})
);
// Chat conversation engagement
const chatEngagement = await prisma.chatConversation.findMany({
select: {
id: true,
title: true,
language: true,
createdAt: true,
lastMessageAt: true,
isActive: true,
_count: {
select: {
messages: true
}
}
},
where: {
createdAt: {
gte: startDate
}
},
orderBy: {
lastMessageAt: 'desc'
},
take: 50
});
// Most bookmarked verses
const mostBookmarkedVerses = await prisma.bookmark.groupBy({
by: ['verseId'],
_count: {
verseId: true
},
where: {
createdAt: {
gte: startDate
}
},
orderBy: {
_count: {
verseId: 'desc'
}
},
take: 20
});
// Get verse details for bookmarked verses
const verseDetails = await Promise.all(
mostBookmarkedVerses.map(async (bookmark) => {
const verse = await prisma.bibleVerse.findUnique({
where: { id: bookmark.verseId },
select: {
id: true,
verseNum: true,
text: true,
chapter: {
select: {
chapterNum: true,
book: {
select: {
name: true
}
}
}
}
}
});
return {
...bookmark,
verse
};
})
);
// Content categories performance
const categoryPerformance = await prisma.prayerRequest.groupBy({
by: ['category'],
_sum: {
prayerCount: true
},
_count: {
category: true
},
_avg: {
prayerCount: true
},
where: {
createdAt: {
gte: startDate
},
isActive: true
}
});
// Language distribution for conversations
const languageDistribution = await prisma.chatConversation.groupBy({
by: ['language'],
_count: {
language: true
},
where: {
createdAt: {
gte: startDate
}
}
});
// Content creation vs engagement ratio
const contentMetrics = {
totalPrayerRequests: await prisma.prayerRequest.count({
where: {
createdAt: { gte: startDate }
}
}),
totalPrayers: await prisma.prayer.count({
where: {
createdAt: { gte: startDate }
}
}),
totalConversations: await prisma.chatConversation.count({
where: {
createdAt: { gte: startDate }
}
}),
totalMessages: await prisma.chatMessage.count({
where: {
timestamp: { gte: startDate }
}
}),
totalBookmarks: await prisma.bookmark.count({
where: {
createdAt: { gte: startDate }
}
})
};
// Average engagement rates
const avgPrayersPerRequest = contentMetrics.totalPrayerRequests > 0
? contentMetrics.totalPrayers / contentMetrics.totalPrayerRequests
: 0;
const avgMessagesPerConversation = contentMetrics.totalConversations > 0
? contentMetrics.totalMessages / contentMetrics.totalConversations
: 0;
// Content quality metrics (based on engagement)
const highEngagementRequests = prayerRequestEngagement.filter(req => req.prayerCount >= 5).length;
const lowEngagementRequests = prayerRequestEngagement.filter(req => req.prayerCount <= 1).length;
const engagementDistribution = {
high: highEngagementRequests,
medium: prayerRequestEngagement.length - highEngagementRequests - lowEngagementRequests,
low: lowEngagementRequests
};
return NextResponse.json({
period: periodDays,
engagement: {
prayerRequests: prayerRequestEngagement.slice(0, 20),
conversations: chatEngagement.slice(0, 20),
bookmarkedVerses: verseDetails.slice(0, 15)
},
timeline: {
prayers: prayerEngagementTimeline
},
metrics: {
...contentMetrics,
avgPrayersPerRequest: Math.round(avgPrayersPerRequest * 100) / 100,
avgMessagesPerConversation: Math.round(avgMessagesPerConversation * 100) / 100
},
distributions: {
categories: categoryPerformance,
languages: languageDistribution,
engagement: engagementDistribution
}
});
} catch (error) {
console.error('Admin content analytics error:', error);
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,239 @@
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 }
);
}
}

View File

@@ -0,0 +1,228 @@
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 now = new Date();
const last24Hours = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const lastHour = new Date(now.getTime() - 60 * 60 * 1000);
const last15Minutes = new Date(now.getTime() - 15 * 60 * 1000);
// Real-time activity counters
const realTimeStats = {
last15Minutes: {
newUsers: await prisma.user.count({
where: { createdAt: { gte: last15Minutes } }
}),
newPrayers: await prisma.prayer.count({
where: { createdAt: { gte: last15Minutes } }
}),
newMessages: await prisma.chatMessage.count({
where: { timestamp: { gte: last15Minutes } }
}),
newBookmarks: await prisma.bookmark.count({
where: { createdAt: { gte: last15Minutes } }
})
},
lastHour: {
newUsers: await prisma.user.count({
where: { createdAt: { gte: lastHour } }
}),
newPrayers: await prisma.prayer.count({
where: { createdAt: { gte: lastHour } }
}),
newMessages: await prisma.chatMessage.count({
where: { timestamp: { gte: lastHour } }
}),
newBookmarks: await prisma.bookmark.count({
where: { createdAt: { gte: lastHour } }
}),
activeConversations: await prisma.chatConversation.count({
where: {
lastMessageAt: { gte: lastHour },
isActive: true
}
})
},
last24Hours: {
newUsers: await prisma.user.count({
where: { createdAt: { gte: last24Hours } }
}),
newPrayers: await prisma.prayer.count({
where: { createdAt: { gte: last24Hours } }
}),
newPrayerRequests: await prisma.prayerRequest.count({
where: { createdAt: { gte: last24Hours } }
}),
newMessages: await prisma.chatMessage.count({
where: { timestamp: { gte: last24Hours } }
}),
newConversations: await prisma.chatConversation.count({
where: { createdAt: { gte: last24Hours } }
}),
newBookmarks: await prisma.bookmark.count({
where: { createdAt: { gte: last24Hours } }
})
}
};
// Current online activity indicators
const recentActivity = {
activeUsers: await prisma.user.count({
where: {
lastLoginAt: { gte: lastHour }
}
}),
recentConversations: await prisma.chatConversation.findMany({
select: {
id: true,
title: true,
lastMessageAt: true,
user: {
select: {
name: true,
email: true
}
}
},
where: {
lastMessageAt: { gte: lastHour },
isActive: true
},
orderBy: {
lastMessageAt: 'desc'
},
take: 10
}),
recentPrayerRequests: await prisma.prayerRequest.findMany({
select: {
id: true,
title: true,
category: true,
author: true,
createdAt: true
},
where: {
createdAt: { gte: last24Hours },
isActive: true
},
orderBy: {
createdAt: 'desc'
},
take: 10
}),
recentPrayers: await prisma.prayer.findMany({
select: {
id: true,
createdAt: true,
request: {
select: {
title: true,
category: true
}
}
},
where: {
createdAt: { gte: lastHour }
},
orderBy: {
createdAt: 'desc'
},
take: 10
})
};
// System health indicators
const systemHealth = {
totalUsers: await prisma.user.count(),
totalPrayerRequests: await prisma.prayerRequest.count({ where: { isActive: true } }),
totalActiveConversations: await prisma.chatConversation.count({ where: { isActive: true } }),
pendingModerationRequests: await prisma.prayerRequest.count({ where: { isActive: false } }),
timestamp: now.toISOString()
};
// Hourly breakdown for the last 24 hours
const hourlyBreakdown = await Promise.all(
Array.from({ length: 24 }, (_, i) => {
const hour = new Date(now.getTime() - i * 60 * 60 * 1000);
const hourStart = new Date(hour.getFullYear(), hour.getMonth(), hour.getDate(), hour.getHours(), 0, 0);
const hourEnd = new Date(hour.getFullYear(), hour.getMonth(), hour.getDate(), hour.getHours(), 59, 59);
return hourStart.toISOString().split('T')[1].substring(0, 5);
}).reverse().map(async (time, index) => {
const hourStart = new Date(now.getTime() - (23 - index) * 60 * 60 * 1000);
hourStart.setMinutes(0, 0, 0);
const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000 - 1);
const [users, prayers, messages, conversations] = await Promise.all([
prisma.user.count({
where: {
createdAt: {
gte: hourStart,
lte: hourEnd
}
}
}),
prisma.prayer.count({
where: {
createdAt: {
gte: hourStart,
lte: hourEnd
}
}
}),
prisma.chatMessage.count({
where: {
timestamp: {
gte: hourStart,
lte: hourEnd
}
}
}),
prisma.chatConversation.count({
where: {
createdAt: {
gte: hourStart,
lte: hourEnd
}
}
})
]);
return {
time,
users,
prayers,
messages,
conversations
};
})
);
return NextResponse.json({
timestamp: now.toISOString(),
stats: realTimeStats,
activity: recentActivity,
health: systemHealth,
hourlyBreakdown
});
} catch (error) {
console.error('Admin real-time analytics error:', error);
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,224 @@
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 registration timeline (last 30 days)
const registrationTimeline = await Promise.all(
Array.from({ length: periodDays }, (_, i) => {
const date = new Date();
date.setDate(date.getDate() - i);
return date.toISOString().split('T')[0];
}).reverse().map(async (date) => {
const startOfDay = new Date(date + 'T00:00:00.000Z');
const endOfDay = new Date(date + 'T23:59:59.999Z');
const registrations = await prisma.user.count({
where: {
createdAt: {
gte: startOfDay,
lte: endOfDay
}
}
});
return {
date,
registrations
};
})
);
// User activity patterns (login frequency)
const userActivityPatterns = await prisma.user.findMany({
select: {
id: true,
email: true,
name: true,
role: true,
createdAt: true,
lastLoginAt: true,
_count: {
select: {
chatConversations: true,
prayerRequests: true,
bookmarks: true,
notes: true
}
}
},
orderBy: {
lastLoginAt: 'desc'
},
take: 100
});
// Most active users (by total activity)
const mostActiveUsers = userActivityPatterns
.map(user => ({
...user,
totalActivity:
user._count.chatConversations +
user._count.prayerRequests +
user._count.bookmarks +
user._count.notes
}))
.sort((a, b) => b.totalActivity - a.totalActivity)
.slice(0, 20);
// User retention analysis
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
const newUsersLast30Days = await prisma.user.count({
where: {
createdAt: {
gte: thirtyDaysAgo
}
}
});
const activeUsersLast30Days = await prisma.user.count({
where: {
createdAt: {
gte: thirtyDaysAgo
},
lastLoginAt: {
gte: sevenDaysAgo
}
}
});
const retentionRate = newUsersLast30Days > 0 ? (activeUsersLast30Days / newUsersLast30Days) * 100 : 0;
// User engagement by feature
const featureUsage = {
chat: await prisma.chatConversation.count({
where: {
createdAt: {
gte: startDate
}
}
}),
prayers: await prisma.prayerRequest.count({
where: {
createdAt: {
gte: startDate
}
}
}),
bookmarks: await prisma.bookmark.count({
where: {
createdAt: {
gte: startDate
}
}
}),
notes: await prisma.note.count({
where: {
createdAt: {
gte: startDate
}
}
})
};
// User demographics (by role and creation time)
const userDemographics = await prisma.user.groupBy({
by: ['role'],
_count: {
role: true
},
_min: {
createdAt: true
},
_max: {
createdAt: true
}
});
// Session length analysis (approximate based on conversation activity)
const sessionAnalysis = await prisma.chatConversation.findMany({
select: {
userId: true,
createdAt: true,
lastMessageAt: true,
_count: {
select: {
messages: true
}
}
},
where: {
createdAt: {
gte: startDate
},
userId: {
not: null
}
},
orderBy: {
lastMessageAt: 'desc'
},
take: 1000
});
const avgSessionLength = sessionAnalysis.reduce((acc, session) => {
const duration = new Date(session.lastMessageAt).getTime() - new Date(session.createdAt).getTime();
return acc + (duration / 1000 / 60); // minutes
}, 0) / sessionAnalysis.length || 0;
const avgMessagesPerSession = sessionAnalysis.reduce((acc, session) => {
return acc + session._count.messages;
}, 0) / sessionAnalysis.length || 0;
return NextResponse.json({
period: periodDays,
timeline: {
registrations: registrationTimeline
},
activity: {
patterns: userActivityPatterns.slice(0, 50), // Limit for performance
mostActive: mostActiveUsers
},
retention: {
rate: Math.round(retentionRate * 100) / 100,
newUsers: newUsersLast30Days,
activeUsers: activeUsersLast30Days
},
engagement: {
featureUsage,
avgSessionLength: Math.round(avgSessionLength * 100) / 100,
avgMessagesPerSession: Math.round(avgMessagesPerSession * 100) / 100
},
demographics: userDemographics
});
} catch (error) {
console.error('Admin user analytics error:', error);
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}