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:
@@ -13,8 +13,8 @@ export async function generateMetadata({ params }: { params: Promise<{ locale: s
|
||||
const { locale } = await params
|
||||
const t = await getTranslations({ locale, namespace: 'seo' })
|
||||
|
||||
const currentUrl = locale === 'ro' ? 'https://ghidulbiblic.ro/ro/' : 'https://ghidulbiblic.ro/en/'
|
||||
const alternateUrl = locale === 'ro' ? 'https://ghidulbiblic.ro/en/' : 'https://ghidulbiblic.ro/ro/'
|
||||
const currentUrl = locale === 'ro' ? 'https://biblical-guide.com/ro/' : 'https://biblical-guide.com/en/'
|
||||
const alternateUrl = locale === 'ro' ? 'https://biblical-guide.com/en/' : 'https://biblical-guide.com/ro/'
|
||||
|
||||
return {
|
||||
title: t('title'),
|
||||
@@ -23,9 +23,9 @@ export async function generateMetadata({ params }: { params: Promise<{ locale: s
|
||||
alternates: {
|
||||
canonical: currentUrl,
|
||||
languages: {
|
||||
'ro': 'https://ghidulbiblic.ro/ro/',
|
||||
'en': 'https://ghidulbiblic.ro/en/',
|
||||
'x-default': 'https://ghidulbiblic.ro/'
|
||||
'ro': 'https://biblical-guide.com/ro/',
|
||||
'en': 'https://biblical-guide.com/en/',
|
||||
'x-default': 'https://biblical-guide.com/'
|
||||
}
|
||||
},
|
||||
openGraph: {
|
||||
|
||||
415
app/admin/analytics/page.tsx
Normal file
415
app/admin/analytics/page.tsx
Normal file
@@ -0,0 +1,415 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Typography,
|
||||
Box,
|
||||
Breadcrumbs,
|
||||
Link,
|
||||
Card,
|
||||
CardContent,
|
||||
Grid,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
Chip,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper
|
||||
} from '@mui/material';
|
||||
import {
|
||||
Home,
|
||||
Analytics,
|
||||
TrendingUp,
|
||||
People,
|
||||
Chat,
|
||||
FavoriteBorder,
|
||||
Bookmarks
|
||||
} from '@mui/icons-material';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
AreaChart,
|
||||
Area,
|
||||
BarChart,
|
||||
Bar,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
|
||||
interface AnalyticsData {
|
||||
period: number;
|
||||
overview: {
|
||||
users: { total: number; new: number; active: number };
|
||||
prayerRequests: { total: number; active: number; new: number };
|
||||
prayers: { total: number; new: number };
|
||||
conversations: { total: number; active: number; new: number };
|
||||
messages: { total: number; new: number };
|
||||
bookmarks: { total: number; new: number };
|
||||
};
|
||||
distributions: {
|
||||
usersByRole: Array<{ role: string; _count: { role: number } }>;
|
||||
prayersByCategory: Array<{ category: string; _count: { category: number } }>;
|
||||
};
|
||||
topContent: {
|
||||
prayerRequests: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
category: string;
|
||||
prayerCount: number;
|
||||
author: string;
|
||||
}>;
|
||||
};
|
||||
activity: {
|
||||
daily: Array<{
|
||||
date: string;
|
||||
newUsers: number;
|
||||
newPrayers: number;
|
||||
newConversations: number;
|
||||
newBookmarks: number;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
interface MetricCardProps {
|
||||
title: string;
|
||||
value: number;
|
||||
change: number;
|
||||
icon: React.ReactNode;
|
||||
color: string;
|
||||
}
|
||||
|
||||
function MetricCard({ title, value, change, icon, color }: MetricCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<Box>
|
||||
<Typography color="textSecondary" gutterBottom variant="body2">
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant="h4">
|
||||
{value.toLocaleString()}
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
|
||||
<TrendingUp sx={{ fontSize: 16, mr: 0.5, color: change >= 0 ? 'success.main' : 'error.main' }} />
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ color: change >= 0 ? 'success.main' : 'error.main' }}
|
||||
>
|
||||
{change >= 0 ? '+' : ''}{change}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="textSecondary" sx={{ ml: 0.5 }}>
|
||||
this period
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ color, fontSize: 40 }}>
|
||||
{icon}
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const COLORS = ['#8884d8', '#82ca9d', '#ffc658', '#ff7300', '#0088fe', '#00c49f'];
|
||||
|
||||
export default function AdminAnalyticsPage() {
|
||||
const [data, setData] = useState<AnalyticsData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [period, setPeriod] = useState('30');
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAnalytics = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/admin/analytics/overview?period=${period}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const analyticsData = await response.json();
|
||||
setData(analyticsData);
|
||||
} else {
|
||||
setError('Failed to load analytics data');
|
||||
}
|
||||
} catch (error) {
|
||||
setError('Network error loading analytics');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchAnalytics();
|
||||
}, [period]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Alert severity="error" sx={{ mb: 3 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Analytics sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Analytics
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
|
||||
<Box>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
Analytics Dashboard
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Comprehensive insights into user behavior and content engagement
|
||||
</Typography>
|
||||
</Box>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Time Period</InputLabel>
|
||||
<Select
|
||||
value={period}
|
||||
label="Time Period"
|
||||
onChange={(e) => setPeriod(e.target.value)}
|
||||
>
|
||||
<MenuItem value="7">Last 7 days</MenuItem>
|
||||
<MenuItem value="30">Last 30 days</MenuItem>
|
||||
<MenuItem value="90">Last 90 days</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
{/* Metric Cards */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
|
||||
gap: 3,
|
||||
mb: 4
|
||||
}}
|
||||
>
|
||||
<Box sx={{ cursor: 'pointer' }} onClick={() => window.location.href = '/admin/analytics/users'}>
|
||||
<MetricCard
|
||||
title="Total Users"
|
||||
value={data.overview.users.total}
|
||||
change={data.overview.users.new}
|
||||
icon={<People />}
|
||||
color="#1976d2"
|
||||
/>
|
||||
</Box>
|
||||
<MetricCard
|
||||
title="Prayer Requests"
|
||||
value={data.overview.prayerRequests.total}
|
||||
change={data.overview.prayerRequests.new}
|
||||
icon={<FavoriteBorder />}
|
||||
color="#d32f2f"
|
||||
/>
|
||||
<MetricCard
|
||||
title="Total Prayers"
|
||||
value={data.overview.prayers.total}
|
||||
change={data.overview.prayers.new}
|
||||
icon={<FavoriteBorder />}
|
||||
color="#ed6c02"
|
||||
/>
|
||||
<MetricCard
|
||||
title="Conversations"
|
||||
value={data.overview.conversations.total}
|
||||
change={data.overview.conversations.new}
|
||||
icon={<Chat />}
|
||||
color="#2e7d32"
|
||||
/>
|
||||
<MetricCard
|
||||
title="Messages"
|
||||
value={data.overview.messages.total}
|
||||
change={data.overview.messages.new}
|
||||
icon={<Chat />}
|
||||
color="#9c27b0"
|
||||
/>
|
||||
<MetricCard
|
||||
title="Bookmarks"
|
||||
value={data.overview.bookmarks.total}
|
||||
change={data.overview.bookmarks.new}
|
||||
icon={<Bookmarks />}
|
||||
color="#0288d1"
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: { xs: '1fr', lg: '2fr 1fr' },
|
||||
gap: 3,
|
||||
mb: 3
|
||||
}}
|
||||
>
|
||||
{/* Daily Activity Chart */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Daily Activity Trends
|
||||
</Typography>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<LineChart data={data.activity.daily}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="date" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="newUsers" stroke="#8884d8" name="New Users" />
|
||||
<Line type="monotone" dataKey="newPrayers" stroke="#82ca9d" name="New Prayers" />
|
||||
<Line type="monotone" dataKey="newConversations" stroke="#ffc658" name="New Conversations" />
|
||||
<Line type="monotone" dataKey="newBookmarks" stroke="#ff7300" name="New Bookmarks" />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* User Roles Distribution */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
User Roles Distribution
|
||||
</Typography>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={data.distributions.usersByRole.map(item => ({
|
||||
name: item.role,
|
||||
value: item._count.role
|
||||
}))}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={80}
|
||||
fill="#8884d8"
|
||||
dataKey="value"
|
||||
label
|
||||
>
|
||||
{data.distributions.usersByRole.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: { xs: '1fr', lg: '1fr 1fr' },
|
||||
gap: 3
|
||||
}}
|
||||
>
|
||||
{/* Prayer Categories Chart */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Prayer Requests by Category
|
||||
</Typography>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={data.distributions.prayersByCategory.map(item => ({
|
||||
category: item.category,
|
||||
count: item._count.category
|
||||
}))}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="category" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Bar dataKey="count" fill="#8884d8" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Top Prayer Requests */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Most Prayed For Requests
|
||||
</Typography>
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Title</TableCell>
|
||||
<TableCell>Category</TableCell>
|
||||
<TableCell align="right">Prayers</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.topContent.prayerRequests.map((request) => (
|
||||
<TableRow key={request.id}>
|
||||
<TableCell>
|
||||
<Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
|
||||
{request.title}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
by {request.author}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={request.category}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Typography variant="body2" fontWeight="medium">
|
||||
{request.prayerCount}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
468
app/admin/analytics/users/page.tsx
Normal file
468
app/admin/analytics/users/page.tsx
Normal file
@@ -0,0 +1,468 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Typography,
|
||||
Box,
|
||||
Breadcrumbs,
|
||||
Link,
|
||||
Card,
|
||||
CardContent,
|
||||
Grid,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
Chip,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper,
|
||||
Avatar
|
||||
} from '@mui/material';
|
||||
import {
|
||||
Home,
|
||||
Analytics,
|
||||
People,
|
||||
TrendingUp,
|
||||
Schedule,
|
||||
Assignment
|
||||
} from '@mui/icons-material';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
AreaChart,
|
||||
Area,
|
||||
BarChart,
|
||||
Bar,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
|
||||
interface UserAnalyticsData {
|
||||
period: number;
|
||||
timeline: {
|
||||
registrations: Array<{ date: string; registrations: number }>;
|
||||
};
|
||||
activity: {
|
||||
patterns: Array<{
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: string;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
_count: {
|
||||
chatConversations: number;
|
||||
prayerRequests: number;
|
||||
bookmarks: number;
|
||||
notes: number;
|
||||
};
|
||||
}>;
|
||||
mostActive: Array<{
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: string;
|
||||
totalActivity: number;
|
||||
_count: {
|
||||
chatConversations: number;
|
||||
prayerRequests: number;
|
||||
bookmarks: number;
|
||||
notes: number;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
retention: {
|
||||
rate: number;
|
||||
newUsers: number;
|
||||
activeUsers: number;
|
||||
};
|
||||
engagement: {
|
||||
featureUsage: {
|
||||
chat: number;
|
||||
prayers: number;
|
||||
bookmarks: number;
|
||||
notes: number;
|
||||
};
|
||||
avgSessionLength: number;
|
||||
avgMessagesPerSession: number;
|
||||
};
|
||||
demographics: Array<{
|
||||
role: string;
|
||||
_count: { role: number };
|
||||
_min: { createdAt: string };
|
||||
_max: { createdAt: string };
|
||||
}>;
|
||||
}
|
||||
|
||||
const COLORS = ['#8884d8', '#82ca9d', '#ffc658', '#ff7300', '#0088fe', '#00c49f'];
|
||||
|
||||
export default function UserAnalyticsPage() {
|
||||
const [data, setData] = useState<UserAnalyticsData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [period, setPeriod] = useState('30');
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserAnalytics = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/admin/analytics/users?period=${period}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const analyticsData = await response.json();
|
||||
setData(analyticsData);
|
||||
} else {
|
||||
setError('Failed to load user analytics data');
|
||||
}
|
||||
} catch (error) {
|
||||
setError('Network error loading user analytics');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserAnalytics();
|
||||
}, [period]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Alert severity="error" sx={{ mb: 3 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
const featureUsageData = Object.entries(data.engagement.featureUsage).map(([key, value]) => ({
|
||||
name: key.charAt(0).toUpperCase() + key.slice(1),
|
||||
value
|
||||
}));
|
||||
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin/analytics"
|
||||
>
|
||||
<Analytics sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Analytics
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<People sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
User Analytics
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
|
||||
<Box>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
User Analytics
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Detailed insights into user behavior, engagement, and retention
|
||||
</Typography>
|
||||
</Box>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Time Period</InputLabel>
|
||||
<Select
|
||||
value={period}
|
||||
label="Time Period"
|
||||
onChange={(e) => setPeriod(e.target.value)}
|
||||
>
|
||||
<MenuItem value="7">Last 7 days</MenuItem>
|
||||
<MenuItem value="30">Last 30 days</MenuItem>
|
||||
<MenuItem value="90">Last 90 days</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
|
||||
gap: 3,
|
||||
mb: 3
|
||||
}}
|
||||
>
|
||||
{/* Key Metrics */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<TrendingUp sx={{ fontSize: 40, color: 'primary.main', mr: 2 }} />
|
||||
<Box>
|
||||
<Typography color="textSecondary" variant="body2">
|
||||
Retention Rate
|
||||
</Typography>
|
||||
<Typography variant="h5">
|
||||
{data.retention.rate}%
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Schedule sx={{ fontSize: 40, color: 'warning.main', mr: 2 }} />
|
||||
<Box>
|
||||
<Typography color="textSecondary" variant="body2">
|
||||
Avg Session (min)
|
||||
</Typography>
|
||||
<Typography variant="h5">
|
||||
{data.engagement.avgSessionLength}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Assignment sx={{ fontSize: 40, color: 'success.main', mr: 2 }} />
|
||||
<Box>
|
||||
<Typography color="textSecondary" variant="body2">
|
||||
Avg Messages/Session
|
||||
</Typography>
|
||||
<Typography variant="h5">
|
||||
{data.engagement.avgMessagesPerSession}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<People sx={{ fontSize: 40, color: 'info.main', mr: 2 }} />
|
||||
<Box>
|
||||
<Typography color="textSecondary" variant="body2">
|
||||
Active/New Users
|
||||
</Typography>
|
||||
<Typography variant="h5">
|
||||
{data.retention.activeUsers}/{data.retention.newUsers}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: { xs: '1fr', lg: '2fr 1fr' },
|
||||
gap: 3,
|
||||
mb: 3
|
||||
}}
|
||||
>
|
||||
{/* User Registration Timeline */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
User Registration Timeline
|
||||
</Typography>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<AreaChart data={data.timeline.registrations}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="date" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="registrations"
|
||||
stroke="#8884d8"
|
||||
fill="#8884d8"
|
||||
fillOpacity={0.6}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Feature Usage Distribution */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Feature Usage Distribution
|
||||
</Typography>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={featureUsageData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={80}
|
||||
fill="#8884d8"
|
||||
dataKey="value"
|
||||
label={({ name, percent }: any) => `${name} ${(percent * 100).toFixed(0)}%`}
|
||||
>
|
||||
{featureUsageData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: { xs: '1fr', lg: '1fr 1fr' },
|
||||
gap: 3
|
||||
}}
|
||||
>
|
||||
{/* Most Active Users */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Most Active Users
|
||||
</Typography>
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>User</TableCell>
|
||||
<TableCell>Role</TableCell>
|
||||
<TableCell align="right">Total Activity</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.activity.mostActive.slice(0, 10).map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Avatar sx={{ width: 24, height: 24, fontSize: 12 }}>
|
||||
{(user.name || user.email)[0].toUpperCase()}
|
||||
</Avatar>
|
||||
<Box>
|
||||
<Typography variant="body2">
|
||||
{user.name || 'Unknown User'}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{user.email}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={user.role}
|
||||
size="small"
|
||||
color={user.role === 'admin' ? 'error' : user.role === 'moderator' ? 'warning' : 'primary'}
|
||||
variant="outlined"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Typography variant="body2" fontWeight="medium">
|
||||
{user.totalActivity}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{user._count.chatConversations}c {user._count.prayerRequests}p {user._count.bookmarks}b
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* User Demographics */}
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
User Demographics by Role
|
||||
</Typography>
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Role</TableCell>
|
||||
<TableCell align="right">Count</TableCell>
|
||||
<TableCell>First User</TableCell>
|
||||
<TableCell>Latest User</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.demographics.map((demo) => (
|
||||
<TableRow key={demo.role}>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={demo.role}
|
||||
size="small"
|
||||
color={demo.role === 'admin' ? 'error' : demo.role === 'moderator' ? 'warning' : 'primary'}
|
||||
variant="outlined"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Typography variant="body2" fontWeight="medium">
|
||||
{demo._count.role}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="caption">
|
||||
{new Date(demo._min.createdAt).toLocaleDateString()}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="caption">
|
||||
{new Date(demo._max.createdAt).toLocaleDateString()}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
41
app/admin/chat/page.tsx
Normal file
41
app/admin/chat/page.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { Typography, Box, Breadcrumbs, Link } from '@mui/material';
|
||||
import { Home, Chat } from '@mui/icons-material';
|
||||
import { ConversationMonitoring } from '@/components/admin/chat/conversation-monitoring';
|
||||
|
||||
export default function AdminChatPage() {
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Chat sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Chat Monitoring
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
Chat Monitoring
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Monitor and manage chat conversations, detect inappropriate content, and ensure platform safety
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Conversation Monitoring */}
|
||||
<ConversationMonitoring />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
41
app/admin/content/page.tsx
Normal file
41
app/admin/content/page.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { Typography, Box, Breadcrumbs, Link } from '@mui/material';
|
||||
import { Home, Gavel } from '@mui/icons-material';
|
||||
import { PrayerRequestDataGrid } from '@/components/admin/content/prayer-request-data-grid';
|
||||
|
||||
export default function AdminContentPage() {
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Gavel sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Content Moderation
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
Content Moderation
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Review and moderate prayer requests and user-generated content
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Prayer Request Data Grid */}
|
||||
<PrayerRequestDataGrid />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
98
app/admin/layout.tsx
Normal file
98
app/admin/layout.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { ThemeProvider } from '@mui/material/styles';
|
||||
import { CssBaseline, Box, CircularProgress } from '@mui/material';
|
||||
import '@fontsource/roboto/300.css';
|
||||
import '@fontsource/roboto/400.css';
|
||||
import '@fontsource/roboto/500.css';
|
||||
import '@fontsource/roboto/700.css';
|
||||
|
||||
import { AdminLayout } from '@/components/admin/layout/admin-layout';
|
||||
import { adminTheme } from '@/lib/admin-theme';
|
||||
|
||||
interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export default function AdminLayoutPage({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const [admin, setAdmin] = useState<AdminUser | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
// Skip auth check if already on login page
|
||||
if (pathname === '/admin/login') {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/auth/me', {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setAdmin(data.user);
|
||||
} else {
|
||||
// 401 is expected when not logged in - don't log as error
|
||||
setAdmin(null);
|
||||
router.push('/admin/login');
|
||||
}
|
||||
} catch (error) {
|
||||
// Only log actual network errors, not auth failures
|
||||
if (error instanceof TypeError) {
|
||||
console.error('Network error during auth check:', error);
|
||||
}
|
||||
setAdmin(null);
|
||||
router.push('/admin/login');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, [pathname, router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<ThemeProvider theme={adminTheme}>
|
||||
<CssBaseline />
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '100vh',
|
||||
}}
|
||||
>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={adminTheme}>
|
||||
<CssBaseline />
|
||||
{admin && pathname !== '/admin/login' ? (
|
||||
<AdminLayout user={admin}>
|
||||
{children}
|
||||
</AdminLayout>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
20
app/admin/login/page.tsx
Normal file
20
app/admin/login/page.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { ThemeProvider } from '@mui/material/styles';
|
||||
import { CssBaseline } from '@mui/material';
|
||||
import '@fontsource/roboto/300.css';
|
||||
import '@fontsource/roboto/400.css';
|
||||
import '@fontsource/roboto/500.css';
|
||||
import '@fontsource/roboto/700.css';
|
||||
|
||||
import { AdminLoginForm } from '@/components/admin/auth/admin-login-form';
|
||||
import { adminTheme } from '@/lib/admin-theme';
|
||||
|
||||
export default function AdminLoginPage() {
|
||||
return (
|
||||
<ThemeProvider theme={adminTheme}>
|
||||
<CssBaseline />
|
||||
<AdminLoginForm />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
46
app/admin/page.tsx
Normal file
46
app/admin/page.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Typography, Box, Breadcrumbs, Link } from '@mui/material';
|
||||
import { Home } from '@mui/icons-material';
|
||||
import { OverviewCards } from '@/components/admin/dashboard/overview-cards';
|
||||
|
||||
export default function AdminDashboard() {
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary">Dashboard</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
Dashboard Overview
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Monitor key metrics and system performance for Biblical Guide
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Overview Cards */}
|
||||
<OverviewCards />
|
||||
|
||||
{/* Recent Activity Section - Placeholder for future implementation */}
|
||||
<Box sx={{ mt: 4 }}>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Recent Activity
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Activity feed will be implemented in Phase 2
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
41
app/admin/settings/page.tsx
Normal file
41
app/admin/settings/page.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { Typography, Box, Breadcrumbs, Link } from '@mui/material';
|
||||
import { Home, Settings } from '@mui/icons-material';
|
||||
import { SystemDashboard } from '@/components/admin/system/system-dashboard';
|
||||
|
||||
export default function AdminSettingsPage() {
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Settings sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
System Administration
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
System Administration
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Monitor system health, manage backups, and configure platform settings
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* System Dashboard */}
|
||||
<SystemDashboard />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
41
app/admin/users/page.tsx
Normal file
41
app/admin/users/page.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { Typography, Box, Breadcrumbs, Link } from '@mui/material';
|
||||
import { Home, People } from '@mui/icons-material';
|
||||
import { UserDataGrid } from '@/components/admin/users/user-data-grid';
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
return (
|
||||
<Box>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
|
||||
<Link
|
||||
underline="hover"
|
||||
sx={{ display: 'flex', alignItems: 'center' }}
|
||||
color="inherit"
|
||||
href="/admin"
|
||||
>
|
||||
<Home sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Admin
|
||||
</Link>
|
||||
<Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<People sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||
Users
|
||||
</Typography>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Page Header */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
User Management
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
Manage user accounts, roles, and permissions
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* User Data Grid */}
|
||||
<UserDataGrid />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
272
app/api/admin/analytics/content/route.ts
Normal file
272
app/api/admin/analytics/content/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
239
app/api/admin/analytics/overview/route.ts
Normal file
239
app/api/admin/analytics/overview/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
228
app/api/admin/analytics/realtime/route.ts
Normal file
228
app/api/admin/analytics/realtime/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
224
app/api/admin/analytics/users/route.ts
Normal file
224
app/api/admin/analytics/users/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
104
app/api/admin/auth/login/route.ts
Normal file
104
app/api/admin/auth/login/route.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { validateUser } from '@/lib/auth';
|
||||
import { generateAdminToken } from '@/lib/admin-auth';
|
||||
import { createUserLoginSchema } from '@/lib/validation';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function getErrorMessages() {
|
||||
return {
|
||||
fieldsRequired: 'Email and password are required',
|
||||
invalidCredentials: 'Invalid admin credentials',
|
||||
serverError: 'Server error',
|
||||
invalidInput: 'Invalid input data',
|
||||
accessDenied: 'Access denied - admin privileges required'
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const messages = getErrorMessages();
|
||||
const body = await request.json();
|
||||
|
||||
// Validate input
|
||||
const validation = createUserLoginSchema().safeParse(body);
|
||||
if (!validation.success) {
|
||||
return NextResponse.json(
|
||||
{ error: messages.invalidInput },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { email, password } = validation.data;
|
||||
|
||||
// Find user by email
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: email.toLowerCase() }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: messages.invalidCredentials },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if user has admin/moderator role
|
||||
if (!['admin', 'moderator'].includes(user.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: messages.accessDenied },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate password
|
||||
const isValidPassword = await validateUser(email, password);
|
||||
if (!isValidPassword) {
|
||||
return NextResponse.json(
|
||||
{ error: messages.invalidCredentials },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Generate admin token
|
||||
const adminToken = generateAdminToken(user);
|
||||
console.log('Generated admin token for user:', user.email);
|
||||
|
||||
// Update last login
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { lastLoginAt: new Date() }
|
||||
});
|
||||
|
||||
// Set admin cookie
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set('adminToken', adminToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
maxAge: 60 * 60 * 8, // 8 hours
|
||||
path: '/'
|
||||
});
|
||||
|
||||
console.log('Admin cookie set successfully');
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin login error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessages().serverError },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
21
app/api/admin/auth/logout/route.ts
Normal file
21
app/api/admin/auth/logout/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
// Clear admin token cookie
|
||||
cookieStore.delete('adminToken');
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Admin logout error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
43
app/api/admin/auth/me/route.ts
Normal file
43
app/api/admin/auth/me/route.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { cookies } from 'next/headers';
|
||||
import { getCurrentAdmin } from '@/lib/admin-auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
console.log('Admin auth check - starting...');
|
||||
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('adminToken')?.value;
|
||||
|
||||
console.log('Admin token found:', !!token);
|
||||
|
||||
if (!token) {
|
||||
console.log('No admin token found in cookies');
|
||||
return NextResponse.json(
|
||||
{ error: 'Not authenticated - no token' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const admin = await getCurrentAdmin();
|
||||
console.log('Admin user found:', !!admin);
|
||||
|
||||
if (!admin) {
|
||||
console.log('Admin token invalid or user not found');
|
||||
return NextResponse.json(
|
||||
{ error: 'Not authenticated - invalid token' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ user: admin });
|
||||
} catch (error) {
|
||||
console.error('Get admin user error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
209
app/api/admin/chat/conversations/[id]/route.ts
Normal file
209
app/api/admin/chat/conversations/[id]/route.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
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,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const conversation = await prisma.chatConversation.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
lastLoginAt: true
|
||||
}
|
||||
},
|
||||
messages: {
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
content: true,
|
||||
timestamp: true,
|
||||
metadata: true
|
||||
},
|
||||
orderBy: {
|
||||
timestamp: 'asc'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!conversation) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Conversation not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Analyze conversation for potential issues
|
||||
const analysis = {
|
||||
messageCount: conversation.messages.length,
|
||||
userMessages: conversation.messages.filter(m => m.role === 'USER').length,
|
||||
assistantMessages: conversation.messages.filter(m => m.role === 'ASSISTANT').length,
|
||||
averageMessageLength: conversation.messages.reduce((acc, msg) => acc + msg.content.length, 0) / conversation.messages.length || 0,
|
||||
lastActivity: conversation.lastMessageAt,
|
||||
duration: conversation.lastMessageAt
|
||||
? new Date(conversation.lastMessageAt).getTime() - new Date(conversation.createdAt).getTime()
|
||||
: 0,
|
||||
potentialIssues: [] as string[]
|
||||
};
|
||||
|
||||
// Check for potential content issues
|
||||
const suspiciousKeywords = ['inappropriate', 'harmful', 'illegal', 'violence', 'hate'];
|
||||
const hasContentIssues = conversation.messages.some(msg =>
|
||||
suspiciousKeywords.some(keyword =>
|
||||
msg.content.toLowerCase().includes(keyword)
|
||||
)
|
||||
);
|
||||
|
||||
if (hasContentIssues) {
|
||||
analysis.potentialIssues.push('Potentially inappropriate content detected');
|
||||
}
|
||||
|
||||
if (analysis.messageCount > 100) {
|
||||
analysis.potentialIssues.push('Unusually long conversation');
|
||||
}
|
||||
|
||||
if (analysis.userMessages > 50) {
|
||||
analysis.potentialIssues.push('High user message count');
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
conversation,
|
||||
analysis
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin conversation detail error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const { action, reason } = body;
|
||||
|
||||
let updateData: any = {};
|
||||
|
||||
switch (action) {
|
||||
case 'deactivate':
|
||||
updateData = { isActive: false };
|
||||
break;
|
||||
case 'activate':
|
||||
updateData = { isActive: true };
|
||||
break;
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid action' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const conversation = await prisma.chatConversation.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
user: {
|
||||
select: {
|
||||
email: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: Add audit log entry here in the future
|
||||
console.log(`Admin ${admin.email} performed action '${action}' on conversation ${conversation.title}${reason ? ` with reason: ${reason}` : ''}`);
|
||||
|
||||
return NextResponse.json({ conversation });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin conversation update error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const conversation = await prisma.chatConversation.findUnique({
|
||||
where: { id },
|
||||
select: { title: true, user: { select: { email: true } } }
|
||||
});
|
||||
|
||||
if (!conversation) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Conversation not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Delete conversation and all related messages (CASCADE)
|
||||
await prisma.chatConversation.delete({
|
||||
where: { id }
|
||||
});
|
||||
|
||||
console.log(`Admin ${admin.email} deleted conversation "${conversation.title}"`);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin conversation delete error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
140
app/api/admin/chat/conversations/route.ts
Normal file
140
app/api/admin/chat/conversations/route.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
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.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const page = parseInt(url.searchParams.get('page') || '0');
|
||||
const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
|
||||
const search = url.searchParams.get('search') || '';
|
||||
const status = url.searchParams.get('status') || 'all';
|
||||
const language = url.searchParams.get('language') || 'all';
|
||||
const sortBy = url.searchParams.get('sortBy') || 'lastMessage';
|
||||
|
||||
// Build where clause for filtering
|
||||
const where: any = {};
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ title: { contains: search, mode: 'insensitive' } },
|
||||
{ user: { email: { contains: search, mode: 'insensitive' } } },
|
||||
{ user: { name: { contains: search, mode: 'insensitive' } } }
|
||||
];
|
||||
}
|
||||
if (status !== 'all') {
|
||||
where.isActive = status === 'active';
|
||||
}
|
||||
if (language !== 'all') {
|
||||
where.language = language;
|
||||
}
|
||||
|
||||
// Build order by clause
|
||||
let orderBy: any = { lastMessageAt: 'desc' };
|
||||
switch (sortBy) {
|
||||
case 'created':
|
||||
orderBy = { createdAt: 'desc' };
|
||||
break;
|
||||
case 'messageCount':
|
||||
orderBy = { messages: { _count: 'desc' } };
|
||||
break;
|
||||
case 'lastMessage':
|
||||
default:
|
||||
orderBy = { lastMessageAt: 'desc' };
|
||||
break;
|
||||
}
|
||||
|
||||
// Get total count for pagination
|
||||
const total = await prisma.chatConversation.count({ where });
|
||||
|
||||
// Get conversations with pagination
|
||||
const conversations = await prisma.chatConversation.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
language: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
lastMessageAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true
|
||||
}
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
messages: true
|
||||
}
|
||||
},
|
||||
messages: {
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
content: true,
|
||||
timestamp: true
|
||||
},
|
||||
orderBy: {
|
||||
timestamp: 'desc'
|
||||
},
|
||||
take: 1
|
||||
}
|
||||
},
|
||||
orderBy,
|
||||
skip: page * pageSize,
|
||||
take: pageSize
|
||||
});
|
||||
|
||||
// Add conversation statistics
|
||||
const stats = {
|
||||
total: await prisma.chatConversation.count(),
|
||||
active: await prisma.chatConversation.count({ where: { isActive: true } }),
|
||||
inactive: await prisma.chatConversation.count({ where: { isActive: false } }),
|
||||
today: await prisma.chatConversation.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: new Date(new Date().setHours(0, 0, 0, 0))
|
||||
}
|
||||
}
|
||||
}),
|
||||
thisWeek: await prisma.chatConversation.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
return NextResponse.json({
|
||||
conversations,
|
||||
stats,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize)
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin chat conversations list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
183
app/api/admin/content/prayer-requests/[id]/route.ts
Normal file
183
app/api/admin/content/prayer-requests/[id]/route.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
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,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const prayerRequest = await prisma.prayerRequest.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true
|
||||
}
|
||||
},
|
||||
prayers: {
|
||||
select: {
|
||||
id: true,
|
||||
ipAddress: true,
|
||||
createdAt: true
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10
|
||||
},
|
||||
userPrayers: {
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!prayerRequest) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Prayer request not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ prayerRequest });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin prayer request detail error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const { action, reason } = body;
|
||||
|
||||
let updateData: any = {};
|
||||
|
||||
switch (action) {
|
||||
case 'approve':
|
||||
updateData = { isActive: true };
|
||||
break;
|
||||
case 'reject':
|
||||
updateData = { isActive: false };
|
||||
break;
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid action' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const prayerRequest = await prisma.prayerRequest.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
isActive: true,
|
||||
user: {
|
||||
select: {
|
||||
email: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: Add audit log entry here in the future
|
||||
console.log(`Admin ${admin.email} performed action '${action}' on prayer request ${prayerRequest.title}${reason ? ` with reason: ${reason}` : ''}`);
|
||||
|
||||
return NextResponse.json({ prayerRequest });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin prayer request update error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const prayerRequest = await prisma.prayerRequest.findUnique({
|
||||
where: { id },
|
||||
select: { title: true, user: { select: { email: true } } }
|
||||
});
|
||||
|
||||
if (!prayerRequest) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Prayer request not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Delete prayer request and all related data (CASCADE)
|
||||
await prisma.prayerRequest.delete({
|
||||
where: { id }
|
||||
});
|
||||
|
||||
console.log(`Admin ${admin.email} deleted prayer request "${prayerRequest.title}"`);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin prayer request delete error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
87
app/api/admin/content/prayer-requests/route.ts
Normal file
87
app/api/admin/content/prayer-requests/route.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
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.MODERATE_CONTENT)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const page = parseInt(url.searchParams.get('page') || '0');
|
||||
const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
|
||||
const search = url.searchParams.get('search') || '';
|
||||
const category = url.searchParams.get('category') || '';
|
||||
const status = url.searchParams.get('status') || 'all';
|
||||
|
||||
// Build where clause for filtering
|
||||
const where: any = {};
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ title: { contains: search, mode: 'insensitive' } },
|
||||
{ description: { contains: search, mode: 'insensitive' } },
|
||||
{ author: { contains: search, mode: 'insensitive' } }
|
||||
];
|
||||
}
|
||||
if (category && category !== 'all') {
|
||||
where.category = category;
|
||||
}
|
||||
if (status !== 'all') {
|
||||
where.isActive = status === 'active';
|
||||
}
|
||||
|
||||
// Get total count for pagination
|
||||
const total = await prisma.prayerRequest.count({ where });
|
||||
|
||||
// Get prayer requests with pagination
|
||||
const prayerRequests = await prisma.prayerRequest.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
category: true,
|
||||
author: true,
|
||||
isAnonymous: true,
|
||||
prayerCount: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: page * pageSize,
|
||||
take: pageSize
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
prayerRequests,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize)
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin prayer requests list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
143
app/api/admin/stats/overview/route.ts
Normal file
143
app/api/admin/stats/overview/route.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { getCurrentAdmin } from '@/lib/admin-auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get date ranges
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
|
||||
const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Parallel queries for better performance
|
||||
const [
|
||||
totalUsers,
|
||||
usersToday,
|
||||
usersYesterday,
|
||||
dailyActiveUsers,
|
||||
conversationsToday,
|
||||
conversationsYesterday,
|
||||
prayerRequestsToday,
|
||||
prayerRequestsYesterday,
|
||||
totalConversations,
|
||||
totalPrayerRequests
|
||||
] = await Promise.all([
|
||||
// Total users
|
||||
prisma.user.count(),
|
||||
|
||||
// Users created today
|
||||
prisma.user.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// Users created yesterday
|
||||
prisma.user.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: yesterday,
|
||||
lt: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// Daily active users (logged in today)
|
||||
prisma.user.count({
|
||||
where: {
|
||||
lastLoginAt: {
|
||||
gte: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// AI conversations today
|
||||
prisma.chatConversation.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// AI conversations yesterday
|
||||
prisma.chatConversation.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: yesterday,
|
||||
lt: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// Prayer requests today
|
||||
prisma.prayerRequest.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// Prayer requests yesterday
|
||||
prisma.prayerRequest.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: yesterday,
|
||||
lt: today
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
// Total conversations
|
||||
prisma.chatConversation.count(),
|
||||
|
||||
// Total prayer requests
|
||||
prisma.prayerRequest.count()
|
||||
]);
|
||||
|
||||
// Calculate percentage changes
|
||||
const calculateChange = (today: number, yesterday: number) => {
|
||||
if (yesterday === 0) return today > 0 ? 100 : 0;
|
||||
return Math.round(((today - yesterday) / yesterday) * 100);
|
||||
};
|
||||
|
||||
const userGrowthChange = calculateChange(usersToday, usersYesterday);
|
||||
const conversationChange = calculateChange(conversationsToday, conversationsYesterday);
|
||||
const prayerChange = calculateChange(prayerRequestsToday, prayerRequestsYesterday);
|
||||
|
||||
return NextResponse.json({
|
||||
totalUsers,
|
||||
dailyActiveUsers,
|
||||
conversationsToday,
|
||||
prayerRequestsToday,
|
||||
userGrowthChange,
|
||||
conversationChange,
|
||||
prayerChange,
|
||||
totalConversations,
|
||||
totalPrayerRequests,
|
||||
usersToday,
|
||||
usersYesterday
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin overview stats error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
151
app/api/admin/system/backup/route.ts
Normal file
151
app/api/admin/system/backup/route.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getCurrentAdmin, AdminPermission, hasPermission } from '@/lib/admin-auth';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MANAGE_SYSTEM)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { type } = body; // 'database' or 'full'
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const backupDir = '/tmp/biblical-guide-backups';
|
||||
|
||||
try {
|
||||
// Create backup directory
|
||||
await execAsync(`mkdir -p ${backupDir}`);
|
||||
|
||||
let backupPath = '';
|
||||
let command = '';
|
||||
|
||||
if (type === 'database') {
|
||||
// Database backup using pg_dump
|
||||
backupPath = `${backupDir}/db-backup-${timestamp}.sql`;
|
||||
const dbUrl = process.env.DATABASE_URL;
|
||||
|
||||
if (!dbUrl) {
|
||||
throw new Error('Database URL not configured');
|
||||
}
|
||||
|
||||
command = `pg_dump "${dbUrl}" > "${backupPath}"`;
|
||||
} else if (type === 'full') {
|
||||
// Full system backup (excluding node_modules and .next)
|
||||
backupPath = `${backupDir}/full-backup-${timestamp}.tar.gz`;
|
||||
command = `tar -czf "${backupPath}" --exclude=node_modules --exclude=.next --exclude=.git /root/biblical-guide`;
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid backup type' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`Starting ${type} backup...`);
|
||||
const { stdout, stderr } = await execAsync(command);
|
||||
|
||||
if (stderr && !stderr.includes('Warning')) {
|
||||
throw new Error(`Backup failed: ${stderr}`);
|
||||
}
|
||||
|
||||
// Get backup file size
|
||||
const { stdout: sizeOutput } = await execAsync(`ls -lh "${backupPath}" | awk '{print $5}'`);
|
||||
const fileSize = sizeOutput.trim();
|
||||
|
||||
console.log(`Admin ${admin.email} created ${type} backup: ${backupPath}`);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
backup: {
|
||||
type,
|
||||
path: backupPath,
|
||||
size: fileSize,
|
||||
timestamp: new Date().toISOString(),
|
||||
createdBy: admin.email
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Backup creation failed:', error);
|
||||
return NextResponse.json(
|
||||
{ error: `Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}` },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin backup error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MANAGE_SYSTEM)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const backupDir = '/tmp/biblical-guide-backups';
|
||||
|
||||
try {
|
||||
// List existing backups
|
||||
const { stdout } = await execAsync(`ls -la ${backupDir} 2>/dev/null || echo ""`);
|
||||
|
||||
if (!stdout.trim()) {
|
||||
return NextResponse.json({
|
||||
backups: []
|
||||
});
|
||||
}
|
||||
|
||||
const lines = stdout.trim().split('\n').slice(1); // Skip the first line (total)
|
||||
const backups = lines
|
||||
.filter(line => !line.startsWith('d') && line.includes('backup'))
|
||||
.map(line => {
|
||||
const parts = line.split(/\s+/);
|
||||
const filename = parts[parts.length - 1];
|
||||
const size = parts[4];
|
||||
const date = `${parts[5]} ${parts[6]} ${parts[7]}`;
|
||||
|
||||
return {
|
||||
filename,
|
||||
size,
|
||||
date,
|
||||
type: filename.includes('db-backup') ? 'database' : 'full'
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
backups: backups.reverse() // Most recent first
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
backups: []
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin backup list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
132
app/api/admin/system/health/route.ts
Normal file
132
app/api/admin/system/health/route.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
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.MANAGE_SYSTEM)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
// Database health check
|
||||
let dbHealth = 'healthy';
|
||||
let dbResponseTime = 0;
|
||||
try {
|
||||
const dbStart = Date.now();
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
dbResponseTime = Date.now() - dbStart;
|
||||
} catch (error) {
|
||||
dbHealth = 'unhealthy';
|
||||
console.error('Database health check failed:', error);
|
||||
}
|
||||
|
||||
// System metrics
|
||||
const systemMetrics = {
|
||||
database: {
|
||||
status: dbHealth,
|
||||
responseTime: dbResponseTime,
|
||||
connections: {
|
||||
// This would require additional monitoring setup in production
|
||||
active: 'N/A',
|
||||
max: 'N/A'
|
||||
}
|
||||
},
|
||||
application: {
|
||||
status: 'healthy',
|
||||
uptime: process.uptime(),
|
||||
memory: {
|
||||
used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
|
||||
total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024),
|
||||
rss: Math.round(process.memoryUsage().rss / 1024 / 1024)
|
||||
},
|
||||
nodeVersion: process.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch
|
||||
}
|
||||
};
|
||||
|
||||
// Database statistics
|
||||
const dbStats = {
|
||||
tables: {
|
||||
users: await prisma.user.count(),
|
||||
conversations: await prisma.chatConversation.count(),
|
||||
messages: await prisma.chatMessage.count(),
|
||||
prayerRequests: await prisma.prayerRequest.count(),
|
||||
prayers: await prisma.prayer.count(),
|
||||
bookmarks: await prisma.bookmark.count(),
|
||||
notes: await prisma.note.count()
|
||||
},
|
||||
recentActivity: {
|
||||
last24h: {
|
||||
newUsers: await prisma.user.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
|
||||
}
|
||||
}
|
||||
}),
|
||||
newConversations: await prisma.chatConversation.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
|
||||
}
|
||||
}
|
||||
}),
|
||||
newPrayers: await prisma.prayer.count({
|
||||
where: {
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Security status
|
||||
const securityStatus = {
|
||||
adminUsers: await prisma.user.count({
|
||||
where: { role: 'admin' }
|
||||
}),
|
||||
suspendedUsers: await prisma.user.count({
|
||||
where: { role: 'suspended' }
|
||||
}),
|
||||
inactivePrayerRequests: await prisma.prayerRequest.count({
|
||||
where: { isActive: false }
|
||||
}),
|
||||
inactiveConversations: await prisma.chatConversation.count({
|
||||
where: { isActive: false }
|
||||
})
|
||||
};
|
||||
|
||||
const totalResponseTime = Date.now() - startTime;
|
||||
|
||||
return NextResponse.json({
|
||||
timestamp: new Date().toISOString(),
|
||||
status: dbHealth === 'healthy' ? 'healthy' : 'degraded',
|
||||
responseTime: totalResponseTime,
|
||||
metrics: systemMetrics,
|
||||
database: dbStats,
|
||||
security: securityStatus
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('System health check error:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'System health check failed',
|
||||
status: 'unhealthy',
|
||||
timestamp: new Date().toISOString()
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
214
app/api/admin/users/[id]/route.ts
Normal file
214
app/api/admin/users/[id]/route.ts
Normal file
@@ -0,0 +1,214 @@
|
||||
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,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.VIEW_USERS)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
chatConversations: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
createdAt: true,
|
||||
_count: {
|
||||
select: { messages: true }
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10
|
||||
},
|
||||
prayerRequests: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
category: true,
|
||||
createdAt: true,
|
||||
prayerCount: true
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10
|
||||
},
|
||||
bookmarks: {
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
verse: {
|
||||
select: {
|
||||
verseNum: true,
|
||||
chapter: {
|
||||
select: {
|
||||
chapterNum: true,
|
||||
book: {
|
||||
select: {
|
||||
name: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
take: 10
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
chatConversations: true,
|
||||
prayerRequests: true,
|
||||
bookmarks: true,
|
||||
notes: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'User not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ user });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin user detail error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MANAGE_USERS)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const { action, reason } = body;
|
||||
|
||||
let updateData: any = {};
|
||||
|
||||
switch (action) {
|
||||
case 'suspend':
|
||||
updateData = { role: 'suspended' };
|
||||
break;
|
||||
case 'activate':
|
||||
updateData = { role: 'user' };
|
||||
break;
|
||||
case 'make_admin':
|
||||
updateData = { role: 'admin' };
|
||||
break;
|
||||
case 'make_moderator':
|
||||
updateData = { role: 'moderator' };
|
||||
break;
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid action' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const user = await prisma.user.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: Add audit log entry here in the future
|
||||
console.log(`Admin ${admin.email} performed action '${action}' on user ${user.email}${reason ? ` with reason: ${reason}` : ''}`);
|
||||
|
||||
return NextResponse.json({ user });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin user update error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !hasPermission(admin, AdminPermission.MANAGE_USERS)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Prevent admin from deleting themselves
|
||||
if (id === admin.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cannot delete your own account' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { email: true, role: true }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'User not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Delete user and all related data (CASCADE)
|
||||
await prisma.user.delete({
|
||||
where: { id }
|
||||
});
|
||||
|
||||
console.log(`Admin ${admin.email} deleted user ${user.email}`);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin user delete error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
78
app/api/admin/users/route.ts
Normal file
78
app/api/admin/users/route.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
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_USERS)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const page = parseInt(url.searchParams.get('page') || '0');
|
||||
const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
|
||||
const search = url.searchParams.get('search') || '';
|
||||
const role = url.searchParams.get('role') || '';
|
||||
|
||||
// Build where clause for filtering
|
||||
const where: any = {};
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ email: { contains: search, mode: 'insensitive' } },
|
||||
{ name: { contains: search, mode: 'insensitive' } }
|
||||
];
|
||||
}
|
||||
if (role && role !== 'all') {
|
||||
where.role = role;
|
||||
}
|
||||
|
||||
// Get total count for pagination
|
||||
const total = await prisma.user.count({ where });
|
||||
|
||||
// Get users with pagination
|
||||
const users = await prisma.user.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
lastLoginAt: true,
|
||||
_count: {
|
||||
select: {
|
||||
chatConversations: true,
|
||||
prayerRequests: true,
|
||||
bookmarks: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: page * pageSize,
|
||||
take: pageSize
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
users,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize)
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Admin users list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user