Admin Dashboard Frontend (Phases 1-4) (#3)
Some checks failed
Deploy Apartment Dashboard / deploy (push) Has been cancelled
Some checks failed
Deploy Apartment Dashboard / deploy (push) Has been cancelled
Co-authored-by: Stephen Minakian <stephenminakian@gmail.com> Co-committed-by: Stephen Minakian <stephenminakian@gmail.com>
This commit is contained in:
477
src/App.jsx
477
src/App.jsx
@ -1,11 +1,22 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Area, AreaChart, ScatterChart, Scatter, ComposedChart, ReferenceLine } from 'recharts';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List } from 'lucide-react';
|
||||
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List, LogOut, User, ChevronDown, ChevronUp, Settings, Shield } from 'lucide-react';
|
||||
import useAuth from './hooks/useAuth';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import AdminRoute from './components/AdminRoute';
|
||||
import Login from './pages/Login';
|
||||
import UserList from './pages/admin/UserList';
|
||||
import UserDetail from './pages/admin/UserDetail';
|
||||
import ActivityStream from './pages/admin/ActivityStream';
|
||||
import AdminOverview from './pages/admin/AdminOverview';
|
||||
import UsageStats from './pages/admin/UsageStats';
|
||||
import AdminSettings from './pages/admin/AdminSettings';
|
||||
|
||||
const ApartmentDashboard = () => {
|
||||
// Router
|
||||
const location = useLocation();
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
|
||||
// Basic state
|
||||
const [selectedUnit, setSelectedUnit] = useState(null);
|
||||
@ -23,6 +34,21 @@ const ApartmentDashboard = () => {
|
||||
const [sortDirection, setSortDirection] = useState('asc');
|
||||
const [watchedUnits, setWatchedUnits] = useState(new Set());
|
||||
const [unitsViewMode, setUnitsViewMode] = useState('list');
|
||||
const [columnSettingsOpen, setColumnSettingsOpen] = useState(false);
|
||||
const [visibleColumns, setVisibleColumns] = useState({
|
||||
unit: true,
|
||||
plan: true,
|
||||
bedBath: true,
|
||||
area: true,
|
||||
price: true,
|
||||
pricePerSqft: true,
|
||||
days: true,
|
||||
high: true,
|
||||
low: true,
|
||||
delta: true,
|
||||
soonest: true,
|
||||
actions: true
|
||||
});
|
||||
|
||||
// API Data state - using your working endpoints
|
||||
const [dailySummary, setDailySummary] = useState(null);
|
||||
@ -54,11 +80,11 @@ const ApartmentDashboard = () => {
|
||||
|
||||
// Fetch core endpoints that we know work
|
||||
const coreRequests = [
|
||||
fetch(`${API_BASE}/daily-summary`),
|
||||
fetch(`${API_BASE}/price-history`),
|
||||
fetch(`${API_BASE}/available-units`),
|
||||
fetch(`${API_BASE}/recent-activity`),
|
||||
fetch(`${API_BASE}/plan-stats`)
|
||||
fetch(`${API_BASE}/daily-summary`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-history`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/available-units`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/recent-activity`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/plan-stats`, { credentials: 'include' })
|
||||
];
|
||||
|
||||
const [
|
||||
@ -96,11 +122,11 @@ const ApartmentDashboard = () => {
|
||||
// Try to fetch enhanced endpoints (won't break if they don't exist)
|
||||
try {
|
||||
const enhancedRequests = [
|
||||
fetch(`${API_BASE}/best-deals?limit=5`),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`),
|
||||
fetch(`${API_BASE}/market-insights`),
|
||||
fetch(`${API_BASE}/last-scrape`)
|
||||
fetch(`${API_BASE}/best-deals?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/price-drops?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/stale-inventory?limit=5`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/market-insights`, { credentials: 'include' }),
|
||||
fetch(`${API_BASE}/last-scrape`, { credentials: 'include' })
|
||||
];
|
||||
|
||||
const enhancedResponses = await Promise.all(enhancedRequests);
|
||||
@ -138,16 +164,19 @@ const ApartmentDashboard = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Initial data fetch
|
||||
// Initial data fetch - only when authenticated
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
if (user) {
|
||||
fetchData();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Auto-refresh every 5 minutes
|
||||
// Auto-refresh every 5 minutes - only when authenticated
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const interval = setInterval(fetchData, 5 * 60 * 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
}, [user]);
|
||||
|
||||
// Helper functions
|
||||
const formatPrice = (price) => `$${(price || 0).toLocaleString()}`;
|
||||
@ -290,7 +319,7 @@ const ApartmentDashboard = () => {
|
||||
const fetchUnitPriceHistory = async (unitCode) => {
|
||||
setLoadingPriceHistory(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`);
|
||||
const response = await fetch(`${API_BASE}/unit/${unitCode}/price-history`, { credentials: 'include' });
|
||||
if (response.ok) {
|
||||
const history = await response.json();
|
||||
setUnitPriceHistory(history);
|
||||
@ -319,7 +348,7 @@ const ApartmentDashboard = () => {
|
||||
if (analyticsData) return; // Already fetched
|
||||
setLoadingAnalytics(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/analytics`);
|
||||
const response = await fetch(`${API_BASE}/analytics`, { credentials: 'include' });
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setAnalyticsData(data);
|
||||
@ -398,6 +427,9 @@ const ApartmentDashboard = () => {
|
||||
case 'price': return dir * ((a.currentPrice || 0) - (b.currentPrice || 0));
|
||||
case 'pricePerSqft': return dir * (((a.currentPrice || 0) / (a.area || 1)) - ((b.currentPrice || 0) / (b.area || 1)));
|
||||
case 'daysAvailable': return dir * ((a.daysAvailable || 0) - (b.daysAvailable || 0));
|
||||
case 'maxPrice': return dir * ((a.maxPrice || 0) - (b.maxPrice || 0));
|
||||
case 'minPrice': return dir * ((a.minPrice || 0) - (b.minPrice || 0));
|
||||
case 'delta': return dir * (((a.maxPrice || 0) - (a.minPrice || 0)) - ((b.maxPrice || 0) - (b.minPrice || 0)));
|
||||
case 'soonest': return dir * (a.soonest || '').localeCompare(b.soonest || '');
|
||||
default: return 0;
|
||||
}
|
||||
@ -440,6 +472,15 @@ const ApartmentDashboard = () => {
|
||||
);
|
||||
}
|
||||
|
||||
// Auth loading state
|
||||
if (authLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error && !dailySummary) {
|
||||
return (
|
||||
@ -475,12 +516,34 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{priceDrops.length > 0 && (
|
||||
<div className="flex items-center space-x-2 bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm">
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{priceDrops.length} price drops</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center space-x-4">
|
||||
{priceDrops.length > 0 && (
|
||||
<div className="flex items-center space-x-2 bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm">
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{priceDrops.length} price drops</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
{user.picture ? (
|
||||
<img src={user.picture} alt={user.name} className="w-8 h-8 rounded-full" />
|
||||
) : (
|
||||
<User className="w-8 h-8 text-gray-400" />
|
||||
)}
|
||||
<span className="text-sm text-gray-700">{user.name}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="flex items-center space-x-1 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-4 mt-4">
|
||||
@ -502,12 +565,58 @@ const ApartmentDashboard = () => {
|
||||
>
|
||||
Analytics
|
||||
</Link>
|
||||
{user && user.role === 'admin' && (
|
||||
<div className="relative group">
|
||||
<button
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md ${location.pathname.startsWith('/admin') ? 'bg-violet-600 text-white' : 'bg-violet-100 text-violet-700 border border-violet-300 hover:bg-violet-200'}`}
|
||||
>
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Admin</span>
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</button>
|
||||
<div className="absolute left-0 mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-150 z-50">
|
||||
<Link
|
||||
to="/admin"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Overview
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/users"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/users' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/activity"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/activity' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Activity
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/stats"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/stats' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Statistics
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin/settings"
|
||||
className={`block px-4 py-2 text-sm hover:bg-violet-50 ${location.pathname === '/admin/settings' ? 'bg-violet-100 text-violet-700' : 'text-gray-700'}`}
|
||||
>
|
||||
Settings
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* Overview Page */}
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<>
|
||||
{/* Key Metrics */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
@ -659,10 +768,12 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Units Page */}
|
||||
<Route path="/units" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
@ -731,6 +842,51 @@ const ApartmentDashboard = () => {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Column Settings Toggle */}
|
||||
<div className="mt-4 border-t pt-4">
|
||||
<button
|
||||
onClick={() => setColumnSettingsOpen(!columnSettingsOpen)}
|
||||
className="flex items-center text-sm text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
<span>Column Settings</span>
|
||||
{columnSettingsOpen ? (
|
||||
<ChevronUp className="w-4 h-4 ml-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 ml-1" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{columnSettingsOpen && (
|
||||
<div className="mt-3 flex flex-wrap gap-4">
|
||||
{[
|
||||
{ key: 'unit', label: 'Unit' },
|
||||
{ key: 'plan', label: 'Plan' },
|
||||
{ key: 'bedBath', label: 'Bed/Bath' },
|
||||
{ key: 'area', label: 'Area' },
|
||||
{ key: 'price', label: 'Price' },
|
||||
{ key: 'pricePerSqft', label: '$/sqft' },
|
||||
{ key: 'days', label: 'Days' },
|
||||
{ key: 'high', label: 'High' },
|
||||
{ key: 'low', label: 'Low' },
|
||||
{ key: 'delta', label: 'Delta' },
|
||||
{ key: 'soonest', label: 'Soonest' },
|
||||
{ key: 'actions', label: 'Actions' }
|
||||
].map(({ key, label }) => (
|
||||
<label key={key} className="flex items-center space-x-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={visibleColumns[key]}
|
||||
onChange={(e) => setVisibleColumns({...visibleColumns, [key]: e.target.checked})}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm">{label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unit Cards - Grid View */}
|
||||
@ -781,83 +937,134 @@ const ApartmentDashboard = () => {
|
||||
|
||||
{/* Unit Cards - List View */}
|
||||
{unitsViewMode === 'list' && (
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
<table className="w-full">
|
||||
<div className="bg-white rounded-lg shadow-md overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('unitCode')}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
Unit
|
||||
{sortBy === 'unitCode' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('planName')}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
Plan
|
||||
{sortBy === 'planName' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('bedCount')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Bed/Bath
|
||||
{sortBy === 'bedCount' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('area')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Area
|
||||
{sortBy === 'area' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('price')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Price
|
||||
{sortBy === 'price' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('pricePerSqft')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
$/sqft
|
||||
{sortBy === 'pricePerSqft' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('daysAvailable')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Days
|
||||
{sortBy === 'daysAvailable' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('soonest')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Soonest
|
||||
{sortBy === 'soonest' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Actions</th>
|
||||
{visibleColumns.unit && (
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none sticky left-0 z-10 bg-gray-50 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
onClick={() => handleSort('unitCode')}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
Unit
|
||||
{sortBy === 'unitCode' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.plan && (
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('planName')}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
Plan
|
||||
{sortBy === 'planName' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.bedBath && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('bedCount')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Bed/Bath
|
||||
{sortBy === 'bedCount' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.area && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('area')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Area
|
||||
{sortBy === 'area' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.price && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('price')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Price
|
||||
{sortBy === 'price' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.pricePerSqft && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('pricePerSqft')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
$/sqft
|
||||
{sortBy === 'pricePerSqft' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.days && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('daysAvailable')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Days
|
||||
{sortBy === 'daysAvailable' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.high && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('maxPrice')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
High
|
||||
{sortBy === 'maxPrice' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.low && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('minPrice')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Low
|
||||
{sortBy === 'minPrice' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.delta && (
|
||||
<th
|
||||
className="text-right py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('delta')}
|
||||
>
|
||||
<span className="flex items-center justify-end">
|
||||
Delta
|
||||
{sortBy === 'delta' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.soonest && (
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100 select-none"
|
||||
onClick={() => handleSort('soonest')}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
Soonest
|
||||
{sortBy === 'soonest' && (sortDirection === 'asc' ? <ArrowUp className="w-4 h-4 ml-1" /> : <ArrowDown className="w-4 h-4 ml-1" />)}
|
||||
</span>
|
||||
</th>
|
||||
)}
|
||||
{visibleColumns.actions && (
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Actions</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@ -866,22 +1073,27 @@ const ApartmentDashboard = () => {
|
||||
key={unit.unitCode}
|
||||
className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'} ${watchedUnits.has(unit.unitCode) ? 'ring-2 ring-inset ring-blue-400' : ''} hover:bg-blue-50`}
|
||||
>
|
||||
<td className="py-3 px-4 font-bold">{unit.unitCode}</td>
|
||||
<td className="py-3 px-4 text-gray-600">{unit.planName}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.bedCount}/{unit.bathCount}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.area} sqft</td>
|
||||
<td className="py-3 px-4 text-right font-bold text-green-600">{formatPrice(unit.currentPrice)}</td>
|
||||
<td className="py-3 px-4 text-right text-gray-500">${((unit.currentPrice || 0) / (unit.area || 1)).toFixed(2)}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.daysAvailable || 0}</td>
|
||||
<td className="py-3 px-4 text-center">{unit.soonest ? (new Date(unit.soonest) <= new Date() ? 'Now' : formatDate(unit.soonest)) : '-'}</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<button
|
||||
onClick={() => openUnitDetail(unit)}
|
||||
className="bg-blue-600 text-white py-1 px-3 rounded-md hover:bg-blue-700 transition-colors text-sm"
|
||||
>
|
||||
Details
|
||||
</button>
|
||||
</td>
|
||||
{visibleColumns.unit && <td className={`py-3 px-4 font-bold sticky left-0 z-10 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)] ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>{unit.unitCode}</td>}
|
||||
{visibleColumns.plan && <td className="py-3 px-4 text-gray-600">{unit.planName}</td>}
|
||||
{visibleColumns.bedBath && <td className="py-3 px-4 text-center">{unit.bedCount}/{unit.bathCount}</td>}
|
||||
{visibleColumns.area && <td className="py-3 px-4 text-center">{unit.area} sqft</td>}
|
||||
{visibleColumns.price && <td className="py-3 px-4 text-right font-bold text-green-600">{formatPrice(unit.currentPrice)}</td>}
|
||||
{visibleColumns.pricePerSqft && <td className="py-3 px-4 text-right text-gray-500">${((unit.currentPrice || 0) / (unit.area || 1)).toFixed(2)}</td>}
|
||||
{visibleColumns.days && <td className="py-3 px-4 text-center">{unit.daysAvailable || 0}</td>}
|
||||
{visibleColumns.high && <td className="py-3 px-4 text-right text-gray-600">{formatPrice(unit.maxPrice)}</td>}
|
||||
{visibleColumns.low && <td className="py-3 px-4 text-right text-gray-600">{formatPrice(unit.minPrice)}</td>}
|
||||
{visibleColumns.delta && <td className="py-3 px-4 text-right text-gray-600">{formatPrice((unit.maxPrice || 0) - (unit.minPrice || 0))}</td>}
|
||||
{visibleColumns.soonest && <td className="py-3 px-4 text-center">{unit.soonest ? (new Date(unit.soonest) <= new Date() ? 'Now' : formatDate(unit.soonest)) : '-'}</td>}
|
||||
{visibleColumns.actions && (
|
||||
<td className="py-3 px-4 text-center">
|
||||
<button
|
||||
onClick={() => openUnitDetail(unit)}
|
||||
className="bg-blue-600 text-white py-1 px-3 rounded-md hover:bg-blue-700 transition-colors text-sm"
|
||||
>
|
||||
Details
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@ -897,10 +1109,12 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Analytics Page */}
|
||||
<Route path="/analytics" element={
|
||||
<ProtectedRoute>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-semibold">Market Analytics</h2>
|
||||
@ -1104,6 +1318,39 @@ const ApartmentDashboard = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Admin Routes */}
|
||||
<Route path="/admin" element={
|
||||
<AdminRoute>
|
||||
<AdminOverview />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/users" element={
|
||||
<AdminRoute>
|
||||
<UserList />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/users/:id" element={
|
||||
<AdminRoute>
|
||||
<UserDetail />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/activity" element={
|
||||
<AdminRoute>
|
||||
<ActivityStream />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/stats" element={
|
||||
<AdminRoute>
|
||||
<UsageStats />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/settings" element={
|
||||
<AdminRoute>
|
||||
<AdminSettings />
|
||||
</AdminRoute>
|
||||
} />
|
||||
|
||||
{/* Catch-all redirect to overview */}
|
||||
|
||||
33
src/components/AdminRoute.jsx
Normal file
33
src/components/AdminRoute.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const AdminRoute = ({ children }) => {
|
||||
const { user, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
// Loading state during auth check
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-violet-600"></div>
|
||||
<p className="mt-4 text-gray-600">Checking permissions...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Not authenticated - redirect to login
|
||||
if (!user) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
// Not an admin - redirect to home
|
||||
if (user.role !== 'admin') {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export default AdminRoute;
|
||||
23
src/components/ProtectedRoute.jsx
Normal file
23
src/components/ProtectedRoute.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const ProtectedRoute = ({ children }) => {
|
||||
const { user, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
53
src/context/AuthContext.jsx
Normal file
53
src/context/AuthContext.jsx
Normal file
@ -0,0 +1,53 @@
|
||||
import React, { createContext, useState, useEffect, useCallback } from 'react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
export const AuthContext = createContext(null);
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkAuth = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/me`, { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUser(data.user);
|
||||
} else {
|
||||
setUser(null);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auth check failed:', err);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, [checkAuth]);
|
||||
|
||||
const login = () => {
|
||||
window.location.href = `${API_BASE}/auth/google`;
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err);
|
||||
}
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, checkAuth }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
53
src/hooks/useActivityTracker.js
Normal file
53
src/hooks/useActivityTracker.js
Normal file
@ -0,0 +1,53 @@
|
||||
import { useEffect, useCallback, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import useAuth from './useAuth';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const useActivityTracker = () => {
|
||||
const { user } = useAuth();
|
||||
const location = useLocation();
|
||||
const lastActivity = useRef({ action: null, timestamp: 0 });
|
||||
|
||||
const trackActivity = useCallback(async (action, metadata = {}) => {
|
||||
// Only track if user is authenticated
|
||||
if (!user) return;
|
||||
|
||||
// Debounce: skip if same action within 300ms
|
||||
const now = Date.now();
|
||||
if (lastActivity.current.action === action &&
|
||||
now - lastActivity.current.timestamp < 300) {
|
||||
return;
|
||||
}
|
||||
lastActivity.current = { action, timestamp: now };
|
||||
|
||||
try {
|
||||
await fetch(`${API_BASE}/activity/log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
metadata: {
|
||||
...metadata,
|
||||
page: location.pathname
|
||||
}
|
||||
})
|
||||
});
|
||||
} catch (err) {
|
||||
// Silently fail - activity logging shouldn't break the app
|
||||
console.error('Activity tracking error:', err);
|
||||
}
|
||||
}, [user, location.pathname]);
|
||||
|
||||
// Track page views on route changes
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
trackActivity('page_view', { path: location.pathname });
|
||||
}
|
||||
}, [location.pathname, user, trackActivity]);
|
||||
|
||||
return { trackActivity };
|
||||
};
|
||||
|
||||
export default useActivityTracker;
|
||||
14
src/hooks/useAuth.js
Normal file
14
src/hooks/useAuth.js
Normal file
@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from '../context/AuthContext';
|
||||
|
||||
const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (context === null) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
@ -1,13 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { AuthProvider } from './context/AuthContext'
|
||||
import './index.css'
|
||||
import App from './App.jsx'
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
91
src/pages/Login.jsx
Normal file
91
src/pages/Login.jsx
Normal file
@ -0,0 +1,91 @@
|
||||
import { Navigate, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
|
||||
const Login = () => {
|
||||
const { user, loading, login } = useAuth();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const error = searchParams.get('error');
|
||||
const from = location.state?.from?.pathname || '/';
|
||||
|
||||
// Error messages based on AUTH.md
|
||||
const errorMessages = {
|
||||
cancelled: 'Sign in was cancelled.',
|
||||
unverified: 'Please verify your Google email address first.',
|
||||
invalid_state: 'Session expired. Please try again.',
|
||||
provider_error: 'Google sign in is temporarily unavailable.',
|
||||
auth_failed: 'Authentication failed. Please try again.'
|
||||
};
|
||||
|
||||
// If already authenticated, redirect to intended destination
|
||||
if (!loading && user) {
|
||||
return <Navigate to={from} replace />;
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
<p className="mt-4 text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold text-gray-800">Apartment Dashboard</h1>
|
||||
<p className="text-gray-600 mt-2">Sign in to view rental analytics</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-md text-sm">
|
||||
{errorMessages[error] || 'An error occurred. Please try again.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={login}
|
||||
className="w-full flex items-center justify-center gap-3 px-4 py-3 border border-gray-300 rounded-md shadow-sm bg-white hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 18 18"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g fill="none" fillRule="evenodd">
|
||||
<path
|
||||
d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 01-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
<span className="text-gray-700 font-medium">Sign in with Google</span>
|
||||
</button>
|
||||
|
||||
<div className="mt-6 text-center text-xs text-gray-500">
|
||||
<p>By signing in, you agree to access apartment rental analytics</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
744
src/pages/admin/ActivityStream.jsx
Normal file
744
src/pages/admin/ActivityStream.jsx
Normal file
@ -0,0 +1,744 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
RefreshCw,
|
||||
Activity,
|
||||
Download,
|
||||
Filter,
|
||||
X,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Bell,
|
||||
Calendar,
|
||||
User,
|
||||
LogIn,
|
||||
LogOut,
|
||||
Eye,
|
||||
Navigation
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Action type icons and labels
|
||||
const ACTION_CONFIG = {
|
||||
LOGIN: { icon: LogIn, label: 'Logged in', color: 'text-green-600' },
|
||||
LOGOUT: { icon: LogOut, label: 'Logged out', color: 'text-gray-600' },
|
||||
PAGE_VIEW: { icon: Eye, label: 'Viewed', color: 'text-blue-600' },
|
||||
NAVIGATION: { icon: Navigation, label: 'Navigated', color: 'text-violet-600' },
|
||||
API_CALL: { icon: Activity, label: 'API call', color: 'text-orange-600' },
|
||||
ADMIN_ENABLE_USER: { icon: User, label: 'Enabled user', color: 'text-green-600' },
|
||||
ADMIN_DISABLE_USER: { icon: User, label: 'Disabled user', color: 'text-red-600' },
|
||||
ADMIN_PROMOTE_USER: { icon: User, label: 'Promoted user', color: 'text-violet-600' },
|
||||
ADMIN_DEMOTE_USER: { icon: User, label: 'Demoted user', color: 'text-orange-600' }
|
||||
};
|
||||
|
||||
// Available action types for filter
|
||||
const ACTION_TYPES = [
|
||||
{ value: '', label: 'All Actions' },
|
||||
{ value: 'LOGIN', label: 'Login' },
|
||||
{ value: 'LOGOUT', label: 'Logout' },
|
||||
{ value: 'PAGE_VIEW', label: 'Page View' },
|
||||
{ value: 'NAVIGATION', label: 'Navigation' }
|
||||
];
|
||||
|
||||
const ActivityStream = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [activities, setActivities] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Pagination
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalActivities, setTotalActivities] = useState(0);
|
||||
const limit = 50;
|
||||
|
||||
// Filters
|
||||
const [userFilter, setUserFilter] = useState('');
|
||||
const [actionFilter, setActionFilter] = useState('');
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [endDate, setEndDate] = useState('');
|
||||
|
||||
// Users for filter dropdown
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loadingUsers, setLoadingUsers] = useState(false);
|
||||
|
||||
// Auto-refresh state
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
const [newActivityCount, setNewActivityCount] = useState(0);
|
||||
const [lastActivityId, setLastActivityId] = useState(null);
|
||||
const autoRefreshInterval = useRef(null);
|
||||
|
||||
// Export modal state
|
||||
const [showExportModal, setShowExportModal] = useState(false);
|
||||
const [exportStartDate, setExportStartDate] = useState('');
|
||||
const [exportEndDate, setExportEndDate] = useState('');
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
// Check if filters are active
|
||||
const hasActiveFilters = userFilter || actionFilter || startDate || endDate;
|
||||
|
||||
// Fetch users for filter dropdown
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoadingUsers(true);
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users?limit=100`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setUsers(data.data.users || []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching users:', err);
|
||||
} finally {
|
||||
setLoadingUsers(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch activities
|
||||
const fetchActivities = useCallback(async (isBackgroundRefresh = false) => {
|
||||
if (!isBackgroundRefresh) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString()
|
||||
});
|
||||
|
||||
if (userFilter) {
|
||||
params.append('userId', userFilter);
|
||||
}
|
||||
if (actionFilter) {
|
||||
params.append('action', actionFilter);
|
||||
}
|
||||
if (startDate) {
|
||||
params.append('startDate', new Date(startDate).toISOString());
|
||||
}
|
||||
if (endDate) {
|
||||
// Set end date to end of day
|
||||
const end = new Date(endDate);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
params.append('endDate', end.toISOString());
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/activity?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch activity data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const newActivities = data.activities || [];
|
||||
|
||||
// Check for new activities (for indicator)
|
||||
if (isBackgroundRefresh && newActivities.length > 0 && lastActivityId) {
|
||||
const newCount = newActivities.findIndex(a => a._id === lastActivityId);
|
||||
if (newCount > 0) {
|
||||
setNewActivityCount(newCount);
|
||||
} else if (newCount === -1 && newActivities[0]._id !== lastActivityId) {
|
||||
// All activities are new (or first activity changed)
|
||||
setNewActivityCount(newActivities.length);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isBackgroundRefresh) {
|
||||
setActivities(newActivities);
|
||||
setNewActivityCount(0);
|
||||
if (newActivities.length > 0) {
|
||||
setLastActivityId(newActivities[0]._id);
|
||||
}
|
||||
}
|
||||
|
||||
setTotalPages(data.pagination?.pages || 1);
|
||||
setTotalActivities(data.pagination?.total || 0);
|
||||
} catch (err) {
|
||||
console.error('Error fetching activities:', err);
|
||||
if (!isBackgroundRefresh) {
|
||||
setError(err.message);
|
||||
}
|
||||
} finally {
|
||||
if (!isBackgroundRefresh) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [page, userFilter, actionFilter, startDate, endDate, lastActivityId]);
|
||||
|
||||
// Load new activities when indicator is clicked
|
||||
const loadNewActivities = () => {
|
||||
setNewActivityCount(0);
|
||||
fetchActivities(false);
|
||||
};
|
||||
|
||||
// Fetch on mount and when dependencies change
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [fetchUsers]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchActivities();
|
||||
}, [fetchActivities]);
|
||||
|
||||
// Auto-refresh every 30 seconds (when tab is active and no filters)
|
||||
useEffect(() => {
|
||||
// Clear existing interval
|
||||
if (autoRefreshInterval.current) {
|
||||
clearInterval(autoRefreshInterval.current);
|
||||
autoRefreshInterval.current = null;
|
||||
}
|
||||
|
||||
// Only auto-refresh if enabled and no filters active
|
||||
if (autoRefresh && !hasActiveFilters) {
|
||||
autoRefreshInterval.current = setInterval(() => {
|
||||
// Only refresh if document is visible
|
||||
if (!document.hidden) {
|
||||
fetchActivities(true);
|
||||
}
|
||||
}, 30000); // 30 seconds
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (autoRefreshInterval.current) {
|
||||
clearInterval(autoRefreshInterval.current);
|
||||
}
|
||||
};
|
||||
}, [autoRefresh, hasActiveFilters, fetchActivities]);
|
||||
|
||||
// Pause auto-refresh when tab is hidden
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.hidden) {
|
||||
// Tab is hidden, pause is handled by the interval check
|
||||
} else {
|
||||
// Tab is visible again, do an immediate check
|
||||
if (autoRefresh && !hasActiveFilters) {
|
||||
fetchActivities(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, [autoRefresh, hasActiveFilters, fetchActivities]);
|
||||
|
||||
// Handle export
|
||||
const handleExport = async () => {
|
||||
if (!exportStartDate || !exportEndDate) {
|
||||
alert('Please select both start and end dates');
|
||||
return;
|
||||
}
|
||||
|
||||
setExporting(true);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
startDate: new Date(exportStartDate).toISOString(),
|
||||
endDate: new Date(exportEndDate + 'T23:59:59.999').toISOString()
|
||||
});
|
||||
|
||||
if (userFilter) {
|
||||
params.append('userId', userFilter);
|
||||
}
|
||||
if (actionFilter) {
|
||||
params.append('action', actionFilter);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/activity/export?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to export activity data');
|
||||
}
|
||||
|
||||
// Get filename from content-disposition header or generate one
|
||||
const contentDisposition = response.headers.get('content-disposition');
|
||||
let filename = `activity-export-${exportStartDate}-to-${exportEndDate}.csv`;
|
||||
if (contentDisposition) {
|
||||
const match = contentDisposition.match(/filename="?([^"]+)"?/);
|
||||
if (match) {
|
||||
filename = match[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Download the file
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
|
||||
setShowExportModal(false);
|
||||
setExportStartDate('');
|
||||
setExportEndDate('');
|
||||
} catch (err) {
|
||||
console.error('Error exporting activity:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Clear all filters
|
||||
const clearFilters = () => {
|
||||
setUserFilter('');
|
||||
setActionFilter('');
|
||||
setStartDate('');
|
||||
setEndDate('');
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Format relative time
|
||||
const formatRelativeTime = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now - date;
|
||||
const diffSeconds = Math.floor(diffMs / 1000);
|
||||
const diffMinutes = Math.floor(diffSeconds / 60);
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'Just now';
|
||||
} else if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minute${diffMinutes !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Get action description
|
||||
const getActionDescription = (activity) => {
|
||||
const config = ACTION_CONFIG[activity.action] || { label: activity.action };
|
||||
|
||||
switch (activity.action) {
|
||||
case 'PAGE_VIEW':
|
||||
return `viewed ${activity.metadata?.path || 'a page'}`;
|
||||
case 'NAVIGATION':
|
||||
return `navigated from ${activity.metadata?.from || 'unknown'} to ${activity.metadata?.to || 'unknown'}`;
|
||||
case 'LOGIN':
|
||||
return 'logged in';
|
||||
case 'LOGOUT':
|
||||
return 'logged out';
|
||||
case 'ADMIN_ENABLE_USER':
|
||||
return 'enabled a user account';
|
||||
case 'ADMIN_DISABLE_USER':
|
||||
return 'disabled a user account';
|
||||
case 'ADMIN_PROMOTE_USER':
|
||||
return 'promoted a user to admin';
|
||||
case 'ADMIN_DEMOTE_USER':
|
||||
return 'demoted a user from admin';
|
||||
default:
|
||||
return config.label.toLowerCase();
|
||||
}
|
||||
};
|
||||
|
||||
// Get action icon
|
||||
const getActionIcon = (action) => {
|
||||
const config = ACTION_CONFIG[action] || { icon: Activity, color: 'text-gray-600' };
|
||||
const Icon = config.icon;
|
||||
return <Icon className={`w-4 h-4 ${config.color}`} />;
|
||||
};
|
||||
|
||||
// Navigate to user detail
|
||||
const handleUserClick = (userId, e) => {
|
||||
e.stopPropagation();
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={() => fetchActivities()}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Activity Stream</h1>
|
||||
<p className="text-gray-600">
|
||||
{totalActivities} total activit{totalActivities !== 1 ? 'ies' : 'y'}
|
||||
{hasActiveFilters && ' (filtered)'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center space-x-3">
|
||||
{/* Export Button */}
|
||||
<button
|
||||
onClick={() => setShowExportModal(true)}
|
||||
className="flex items-center space-x-2 px-4 py-2 border border-gray-300 rounded-md bg-white hover:bg-gray-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Export</span>
|
||||
</button>
|
||||
|
||||
{/* Refresh Button */}
|
||||
<button
|
||||
onClick={() => fetchActivities()}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* New Activity Indicator */}
|
||||
{newActivityCount > 0 && (
|
||||
<button
|
||||
onClick={loadNewActivities}
|
||||
className="w-full flex items-center justify-center space-x-2 py-3 bg-violet-100 text-violet-700 rounded-lg hover:bg-violet-200 transition-colors"
|
||||
>
|
||||
<Bell className="w-4 h-4" />
|
||||
<span>{newActivityCount} new activit{newActivityCount !== 1 ? 'ies' : 'y'} available</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Filter className="w-5 h-5 text-gray-500" />
|
||||
<span className="font-medium text-gray-700">Filters:</span>
|
||||
</div>
|
||||
|
||||
{/* User Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">User:</label>
|
||||
<select
|
||||
value={userFilter}
|
||||
onChange={(e) => { setUserFilter(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
disabled={loadingUsers}
|
||||
>
|
||||
<option value="">All Users</option>
|
||||
{users.map((user) => (
|
||||
<option key={user._id} value={user._id}>
|
||||
{user.name} ({user.email})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Action Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">Action:</label>
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => { setActionFilter(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
>
|
||||
{ACTION_TYPES.map((type) => (
|
||||
<option key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Date Range */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => { setStartDate(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
placeholder="Start Date"
|
||||
/>
|
||||
<span className="text-gray-500">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => { setEndDate(e.target.value); setPage(1); }}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
placeholder="End Date"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Clear Filters */}
|
||||
{hasActiveFilters && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="flex items-center space-x-1 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<span>Clear</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Auto-refresh toggle */}
|
||||
<div className="ml-auto flex items-center space-x-2">
|
||||
<label className="text-sm text-gray-600">Auto-refresh:</label>
|
||||
<button
|
||||
onClick={() => setAutoRefresh(!autoRefresh)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
autoRefresh && !hasActiveFilters ? 'bg-violet-600' : 'bg-gray-300'
|
||||
}`}
|
||||
disabled={hasActiveFilters}
|
||||
title={hasActiveFilters ? 'Auto-refresh is paused while filters are active' : ''}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
autoRefresh && !hasActiveFilters ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
{hasActiveFilters && (
|
||||
<span className="text-xs text-gray-500">(paused)</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Activity List */}
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{loading && activities.length === 0 ? (
|
||||
/* Skeleton Loader */
|
||||
<div className="divide-y divide-gray-100">
|
||||
{[...Array(8)].map((_, index) => (
|
||||
<div key={index} className="p-4">
|
||||
<div className="flex items-start space-x-4 animate-pulse">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-10 h-10 rounded-full bg-gray-200"></div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="h-4 bg-gray-200 rounded w-24"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-32"></div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="h-3 bg-gray-200 rounded w-4"></div>
|
||||
<div className="h-3 bg-gray-200 rounded w-40"></div>
|
||||
<div className="h-3 bg-gray-200 rounded w-20"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : activities.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Activity className="w-16 h-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">No Activity Found</h3>
|
||||
<p className="text-gray-600">
|
||||
{hasActiveFilters
|
||||
? 'No activity recorded in this period. Try adjusting your filters.'
|
||||
: 'No activity has been recorded yet. User activity will appear here once users start interacting with the application.'}
|
||||
</p>
|
||||
{hasActiveFilters && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="mt-4 px-4 py-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50 rounded-md"
|
||||
>
|
||||
Clear all filters
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{activities.map((activity) => (
|
||||
<div
|
||||
key={activity._id}
|
||||
className="p-4 hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<div className="flex items-start space-x-4">
|
||||
{/* Avatar */}
|
||||
<div
|
||||
className="flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
>
|
||||
{activity.userPicture ? (
|
||||
<img
|
||||
src={activity.userPicture}
|
||||
alt={activity.userName}
|
||||
className="w-10 h-10 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-gray-600">
|
||||
{activity.userName?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="font-medium text-gray-900 hover:text-violet-600 hover:underline"
|
||||
>
|
||||
{activity.userName || 'Unknown User'}
|
||||
</button>
|
||||
<span className="text-gray-600">
|
||||
{getActionDescription(activity)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 mt-1 text-sm text-gray-500">
|
||||
{getActionIcon(activity.action)}
|
||||
<span>{activity.userEmail}</span>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span>{formatRelativeTime(activity.timestamp)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-between gap-3 px-4 py-3 bg-gray-50 border-t">
|
||||
<div className="text-sm text-gray-600 text-center sm:text-left">
|
||||
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalActivities)} of {totalActivities} activities
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => setPage(Math.max(1, page - 1))}
|
||||
disabled={page === 1 || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span className="ml-1 hidden sm:inline">Previous</span>
|
||||
</button>
|
||||
<span className="px-3 py-1 text-sm">
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setPage(Math.min(totalPages, page + 1))}
|
||||
disabled={page === totalPages || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="mr-1 hidden sm:inline">Next</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Export Modal */}
|
||||
{showExportModal && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-semibold">Export Activity Data</h3>
|
||||
<button
|
||||
onClick={() => setShowExportModal(false)}
|
||||
className="text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 mb-4">
|
||||
Select a date range to export activity data as CSV. Export is limited to 10,000 records.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Start Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={exportStartDate}
|
||||
onChange={(e) => setExportStartDate(e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
End Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={exportEndDate}
|
||||
onChange={(e) => setExportEndDate(e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{userFilter && (
|
||||
<p className="text-sm text-gray-500">
|
||||
Note: Current user filter will be applied to export.
|
||||
</p>
|
||||
)}
|
||||
{actionFilter && (
|
||||
<p className="text-sm text-gray-500">
|
||||
Note: Current action filter will be applied to export.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3 mt-6">
|
||||
<button
|
||||
onClick={() => setShowExportModal(false)}
|
||||
disabled={exporting}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleExport}
|
||||
disabled={exporting || !exportStartDate || !exportEndDate}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
{exporting ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Exporting...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Export CSV</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ActivityStream;
|
||||
518
src/pages/admin/AdminOverview.jsx
Normal file
518
src/pages/admin/AdminOverview.jsx
Normal file
@ -0,0 +1,518 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
import {
|
||||
Users,
|
||||
UserPlus,
|
||||
Activity,
|
||||
TrendingUp,
|
||||
RefreshCw,
|
||||
Calendar,
|
||||
LogIn,
|
||||
Eye,
|
||||
ChevronRight
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Stats card component
|
||||
const StatsCard = ({ title, value, subtitle, icon: Icon, color = 'violet', loading = false }) => {
|
||||
const colorClasses = {
|
||||
violet: 'bg-violet-100 text-violet-600',
|
||||
green: 'bg-green-100 text-green-600',
|
||||
blue: 'bg-blue-100 text-blue-600',
|
||||
orange: 'bg-orange-100 text-orange-600',
|
||||
red: 'bg-red-100 text-red-600'
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-600">{title}</p>
|
||||
{loading ? (
|
||||
<div className="h-8 w-16 bg-gray-200 animate-pulse rounded mt-1" />
|
||||
) : (
|
||||
<p className="text-2xl font-bold text-gray-900">{value}</p>
|
||||
)}
|
||||
{subtitle && <p className="text-sm text-gray-500 mt-1">{subtitle}</p>}
|
||||
</div>
|
||||
<div className={`p-3 rounded-full ${colorClasses[color]}`}>
|
||||
<Icon className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Action type icons and labels for recent activity
|
||||
const ACTION_CONFIG = {
|
||||
LOGIN: { icon: LogIn, label: 'logged in', color: 'text-green-600' },
|
||||
LOGOUT: { icon: LogIn, label: 'logged out', color: 'text-gray-600' },
|
||||
PAGE_VIEW: { icon: Eye, label: 'viewed', color: 'text-blue-600' },
|
||||
NAVIGATION: { icon: Activity, label: 'navigated', color: 'text-violet-600' }
|
||||
};
|
||||
|
||||
const AdminOverview = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [overview, setOverview] = useState(null);
|
||||
const [activeUsersData, setActiveUsersData] = useState([]);
|
||||
const [recentActivity, setRecentActivity] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Fetch overview stats
|
||||
const fetchOverview = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/overview`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch overview stats');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setOverview(data.data);
|
||||
} catch (err) {
|
||||
console.error('Error fetching overview:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch 7-day active users
|
||||
const fetchActiveUsers = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/active-users?period=daily&days=7`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch active users data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// Sort by date ascending for chart display
|
||||
const sortedData = (data.data || []).sort((a, b) =>
|
||||
new Date(a.date) - new Date(b.date)
|
||||
);
|
||||
setActiveUsersData(sortedData);
|
||||
} catch (err) {
|
||||
console.error('Error fetching active users:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch recent activity (last 10)
|
||||
const fetchRecentActivity = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/activity?limit=10`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch recent activity');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setRecentActivity(data.activities || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching recent activity:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch all data
|
||||
const fetchAllData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchOverview(),
|
||||
fetchActiveUsers(),
|
||||
fetchRecentActivity()
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchOverview, fetchActiveUsers, fetchRecentActivity]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchAllData();
|
||||
}, [fetchAllData]);
|
||||
|
||||
// Format relative time
|
||||
const formatRelativeTime = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now - date;
|
||||
const diffSeconds = Math.floor(diffMs / 1000);
|
||||
const diffMinutes = Math.floor(diffSeconds / 60);
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'Just now';
|
||||
} else if (diffMinutes < 60) {
|
||||
return `${diffMinutes}m ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours}h ago`;
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays}d ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Format date for chart
|
||||
const formatChartDate = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Get action description
|
||||
const getActionDescription = (activity) => {
|
||||
switch (activity.action) {
|
||||
case 'PAGE_VIEW':
|
||||
return `viewed ${activity.metadata?.path || 'a page'}`;
|
||||
case 'NAVIGATION':
|
||||
return `navigated to ${activity.metadata?.to || 'unknown'}`;
|
||||
case 'LOGIN':
|
||||
return 'logged in';
|
||||
case 'LOGOUT':
|
||||
return 'logged out';
|
||||
default:
|
||||
return activity.action.toLowerCase().replace(/_/g, ' ');
|
||||
}
|
||||
};
|
||||
|
||||
// Navigate to user detail
|
||||
const handleUserClick = (userId, e) => {
|
||||
e.stopPropagation();
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Admin Dashboard</h1>
|
||||
<p className="text-gray-600">Overview of user activity and statistics</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<StatsCard
|
||||
title="Total Users"
|
||||
value={overview?.totalUsers || 0}
|
||||
subtitle={`${overview?.activeUsers || 0} active`}
|
||||
icon={Users}
|
||||
color="violet"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active Today (DAU)"
|
||||
value={overview?.dau || 0}
|
||||
icon={Activity}
|
||||
color="green"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active This Week (WAU)"
|
||||
value={overview?.wau || 0}
|
||||
icon={TrendingUp}
|
||||
color="blue"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="New This Week"
|
||||
value={overview?.newUsersThisWeek || 0}
|
||||
subtitle={`${overview?.newUsersToday || 0} today`}
|
||||
icon={UserPlus}
|
||||
color="orange"
|
||||
loading={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Second Row Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<StatsCard
|
||||
title="Monthly Active (MAU)"
|
||||
value={overview?.mau || 0}
|
||||
icon={Calendar}
|
||||
color="violet"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Total Logins"
|
||||
value={overview?.totalLogins?.toLocaleString() || 0}
|
||||
subtitle={`Avg ${overview?.avgLoginsPerUser?.toFixed(1) || 0} per user`}
|
||||
icon={LogIn}
|
||||
color="green"
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="DAU/MAU Ratio"
|
||||
value={overview?.mau > 0 ? `${((overview?.dau / overview?.mau) * 100).toFixed(1)}%` : '0%'}
|
||||
subtitle="Engagement indicator"
|
||||
icon={TrendingUp}
|
||||
color="blue"
|
||||
loading={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Charts and Activity Row */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* 7-Day Active Users Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Active Users (7 Days)</h2>
|
||||
<button
|
||||
onClick={() => navigate('/admin/stats')}
|
||||
className="text-sm text-violet-600 hover:text-violet-700 flex items-center"
|
||||
>
|
||||
View More
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Chart Skeleton */
|
||||
<div className="h-64 animate-pulse">
|
||||
<div className="flex items-end h-52 space-x-2 px-4">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 bg-gray-200 rounded-t"
|
||||
style={{ height: `${Math.random() * 60 + 20}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-between mt-3 px-4">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div key={i} className="h-3 bg-gray-200 rounded w-8" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : activeUsersData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={activeUsersData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatChartDate}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<YAxis
|
||||
allowDecimals={false}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value, 'Active Users']}
|
||||
labelFormatter={formatChartDate}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="count"
|
||||
stroke="#7c3aed"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#7c3aed', strokeWidth: 2 }}
|
||||
activeDot={{ r: 6 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
No activity data available
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Activity Widget */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Recent Activity</h2>
|
||||
<button
|
||||
onClick={() => navigate('/admin/activity')}
|
||||
className="text-sm text-violet-600 hover:text-violet-700 flex items-center"
|
||||
>
|
||||
View All
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-3">
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<div key={i} className="flex items-center space-x-3">
|
||||
<div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse" />
|
||||
<div className="flex-1">
|
||||
<div className="h-4 bg-gray-200 rounded animate-pulse w-3/4" />
|
||||
<div className="h-3 bg-gray-200 rounded animate-pulse w-1/2 mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : recentActivity.length > 0 ? (
|
||||
<div className="space-y-3 max-h-[280px] overflow-y-auto">
|
||||
{recentActivity.map((activity) => {
|
||||
const config = ACTION_CONFIG[activity.action] || {
|
||||
icon: Activity,
|
||||
color: 'text-gray-600'
|
||||
};
|
||||
const Icon = config.icon;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={activity._id}
|
||||
className="flex items-start space-x-3 p-2 hover:bg-gray-50 rounded-lg transition-colors"
|
||||
>
|
||||
{/* Avatar */}
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
{activity.userPicture ? (
|
||||
<img
|
||||
src={activity.userPicture}
|
||||
alt={activity.userName}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-xs font-medium text-gray-600">
|
||||
{activity.userName?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-gray-900 truncate">
|
||||
<button
|
||||
onClick={(e) => handleUserClick(activity.userId, e)}
|
||||
className="font-medium hover:text-violet-600"
|
||||
>
|
||||
{activity.userName || 'Unknown'}
|
||||
</button>
|
||||
{' '}
|
||||
<span className="text-gray-600">
|
||||
{getActionDescription(activity)}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 flex items-center mt-0.5">
|
||||
<Icon className={`w-3 h-3 mr-1 ${config.color}`} />
|
||||
{formatRelativeTime(activity.timestamp)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No recent activity</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Links */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-violet-100 rounded-lg">
|
||||
<Users className="w-5 h-5 text-violet-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Manage Users</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate('/admin/activity')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-blue-100 rounded-lg">
|
||||
<Activity className="w-5 h-5 text-blue-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Activity Stream</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate('/admin/stats')}
|
||||
className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-green-100 rounded-lg">
|
||||
<TrendingUp className="w-5 h-5 text-green-600" />
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">Full Statistics</span>
|
||||
</div>
|
||||
<ChevronRight className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminOverview;
|
||||
347
src/pages/admin/AdminSettings.jsx
Normal file
347
src/pages/admin/AdminSettings.jsx
Normal file
@ -0,0 +1,347 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Settings, AlertTriangle, RefreshCw, Save, Clock } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const AdminSettings = () => {
|
||||
// State
|
||||
const [settings, setSettings] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [saveError, setSaveError] = useState(null);
|
||||
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||
|
||||
// Form state
|
||||
const [retentionDays, setRetentionDays] = useState(90);
|
||||
const [originalRetentionDays, setOriginalRetentionDays] = useState(90);
|
||||
|
||||
// Warning dialog state
|
||||
const [showWarningDialog, setShowWarningDialog] = useState(false);
|
||||
|
||||
// Validation
|
||||
const MIN_RETENTION = 30;
|
||||
const MAX_RETENTION = 365;
|
||||
|
||||
const isValidRetention = retentionDays >= MIN_RETENTION && retentionDays <= MAX_RETENTION;
|
||||
const hasChanges = retentionDays !== originalRetentionDays;
|
||||
const isReducingRetention = retentionDays < originalRetentionDays;
|
||||
|
||||
// Fetch settings
|
||||
const fetchSettings = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/settings`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch settings');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setSettings(data);
|
||||
setRetentionDays(data.activityRetentionDays || 90);
|
||||
setOriginalRetentionDays(data.activityRetentionDays || 90);
|
||||
} catch (err) {
|
||||
console.error('Error fetching settings:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, [fetchSettings]);
|
||||
|
||||
// Clear success message after 3 seconds
|
||||
useEffect(() => {
|
||||
if (saveSuccess) {
|
||||
const timer = setTimeout(() => setSaveSuccess(false), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [saveSuccess]);
|
||||
|
||||
// Handle save
|
||||
const handleSave = async () => {
|
||||
// If reducing retention, show warning first
|
||||
if (isReducingRetention && !showWarningDialog) {
|
||||
setShowWarningDialog(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/settings`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
activityRetentionDays: retentionDays
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to save settings');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setSettings(data.settings);
|
||||
setOriginalRetentionDays(retentionDays);
|
||||
setSaveSuccess(true);
|
||||
setShowWarningDialog(false);
|
||||
} catch (err) {
|
||||
console.error('Error saving settings:', err);
|
||||
setSaveError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle confirm from warning dialog
|
||||
const handleConfirmChange = () => {
|
||||
handleSave();
|
||||
};
|
||||
|
||||
// Handle cancel from warning dialog
|
||||
const handleCancelChange = () => {
|
||||
setShowWarningDialog(false);
|
||||
};
|
||||
|
||||
// Reset to original value
|
||||
const handleReset = () => {
|
||||
setRetentionDays(originalRetentionDays);
|
||||
setSaveError(null);
|
||||
};
|
||||
|
||||
// Skeleton loader
|
||||
const SettingsSkeleton = () => (
|
||||
<div className="space-y-6 animate-pulse">
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="h-6 bg-gray-200 rounded w-48 mb-4"></div>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-32 mb-2"></div>
|
||||
<div className="h-10 bg-gray-200 rounded w-24"></div>
|
||||
</div>
|
||||
<div className="h-4 bg-gray-200 rounded w-full max-w-md"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-3/4 max-w-md"></div>
|
||||
<div className="h-10 bg-gray-200 rounded w-32 mt-4"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchSettings}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Admin Settings</h1>
|
||||
<p className="text-gray-600">
|
||||
Configure application settings and data retention policies
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchSettings}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Settings Content */}
|
||||
{loading ? (
|
||||
<SettingsSkeleton />
|
||||
) : (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-6">
|
||||
<Clock className="w-5 h-5 text-violet-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Activity Log Retention</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 max-w-lg">
|
||||
{/* Retention Period Input */}
|
||||
<div>
|
||||
<label htmlFor="retention-days" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Retention Period (days)
|
||||
</label>
|
||||
<div className="flex items-center space-x-3">
|
||||
<input
|
||||
id="retention-days"
|
||||
type="number"
|
||||
min={MIN_RETENTION}
|
||||
max={MAX_RETENTION}
|
||||
value={retentionDays}
|
||||
onChange={(e) => {
|
||||
const value = parseInt(e.target.value, 10);
|
||||
if (!isNaN(value)) {
|
||||
setRetentionDays(value);
|
||||
}
|
||||
}}
|
||||
className={`w-24 px-3 py-2 border rounded-md focus:ring-2 focus:ring-violet-500 focus:border-violet-500 ${
|
||||
!isValidRetention ? 'border-red-500' : 'border-gray-300'
|
||||
}`}
|
||||
/>
|
||||
<span className="text-sm text-gray-500">
|
||||
({MIN_RETENTION}-{MAX_RETENTION} days)
|
||||
</span>
|
||||
</div>
|
||||
{!isValidRetention && (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
Retention period must be between {MIN_RETENTION} and {MAX_RETENTION} days
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-sm text-gray-600">
|
||||
Activity logs older than this will be automatically deleted. This helps manage database size while maintaining an audit trail for recent activity.
|
||||
</p>
|
||||
|
||||
{/* Current Setting Info */}
|
||||
{settings && (
|
||||
<div className="bg-gray-50 rounded-md p-3">
|
||||
<p className="text-sm text-gray-600">
|
||||
<span className="font-medium">Current setting:</span> {originalRetentionDays} days
|
||||
</p>
|
||||
{settings.activityLogLevel && (
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
<span className="font-medium">Log level:</span> {settings.activityLogLevel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Save Error */}
|
||||
{saveError && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-md p-3">
|
||||
<p className="text-sm text-red-700">Error: {saveError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success Message */}
|
||||
{saveSuccess && (
|
||||
<div className="bg-green-50 border border-green-200 rounded-md p-3">
|
||||
<p className="text-sm text-green-700">Settings saved successfully</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center space-x-3 pt-2">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || !isValidRetention || saving}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Saving...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="w-4 h-4" />
|
||||
<span>Save Changes</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{hasChanges && (
|
||||
<button
|
||||
onClick={handleReset}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Warning Dialog */}
|
||||
{showWarningDialog && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<div className="flex items-start space-x-3 mb-4">
|
||||
<div className="flex-shrink-0">
|
||||
<AlertTriangle className="w-6 h-6 text-amber-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-gray-900">
|
||||
Warning: Reducing Retention Period
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 mb-6">
|
||||
<p className="text-gray-600">
|
||||
Reducing the retention period from{' '}
|
||||
<span className="font-semibold">{originalRetentionDays} days</span> to{' '}
|
||||
<span className="font-semibold">{retentionDays} days</span> will permanently delete
|
||||
activity logs older than {retentionDays} days.
|
||||
</p>
|
||||
<p className="text-red-600 font-medium">
|
||||
This action cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={handleCancelChange}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirmChange}
|
||||
disabled={saving}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span>Saving...</span>
|
||||
</>
|
||||
) : (
|
||||
<span>Confirm Change</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminSettings;
|
||||
671
src/pages/admin/UsageStats.jsx
Normal file
671
src/pages/admin/UsageStats.jsx
Normal file
@ -0,0 +1,671 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
BarChart,
|
||||
Bar,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Legend
|
||||
} from 'recharts';
|
||||
import {
|
||||
TrendingUp,
|
||||
RefreshCw,
|
||||
ArrowLeft,
|
||||
Calendar,
|
||||
Activity,
|
||||
Clock,
|
||||
Users
|
||||
} from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
// Colors for charts
|
||||
const CHART_COLORS = ['#7c3aed', '#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#6366f1', '#ec4899'];
|
||||
|
||||
// Heatmap color scale (light to dark violet)
|
||||
const HEATMAP_COLORS = [
|
||||
'#f5f3ff', // 0 - lightest
|
||||
'#ede9fe', // 1
|
||||
'#ddd6fe', // 2
|
||||
'#c4b5fd', // 3
|
||||
'#a78bfa', // 4
|
||||
'#8b5cf6', // 5
|
||||
'#7c3aed', // 6
|
||||
'#6d28d9', // 7
|
||||
'#5b21b6', // 8
|
||||
'#4c1d95' // 9 - darkest
|
||||
];
|
||||
|
||||
// Day names for heatmap
|
||||
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
|
||||
const UsageStats = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [activeUsersData, setActiveUsersData] = useState([]);
|
||||
const [actionsData, setActionsData] = useState([]);
|
||||
const [peakTimesData, setPeakTimesData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Period toggle for active users chart
|
||||
const [period, setPeriod] = useState('daily');
|
||||
const [days, setDays] = useState(30);
|
||||
|
||||
// Date range for actions
|
||||
const [actionStartDate, setActionStartDate] = useState(() => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 30);
|
||||
return date.toISOString().split('T')[0];
|
||||
});
|
||||
const [actionEndDate, setActionEndDate] = useState(() => {
|
||||
return new Date().toISOString().split('T')[0];
|
||||
});
|
||||
|
||||
// Fetch active users data
|
||||
const fetchActiveUsers = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${API_BASE}/admin/stats/active-users?period=${period}&days=${days}`,
|
||||
{ credentials: 'include' }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch active users data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// Sort by date ascending for chart display
|
||||
const sortedData = (data.data || []).sort((a, b) =>
|
||||
new Date(a.date) - new Date(b.date)
|
||||
);
|
||||
setActiveUsersData(sortedData);
|
||||
} catch (err) {
|
||||
console.error('Error fetching active users:', err);
|
||||
throw err;
|
||||
}
|
||||
}, [period, days]);
|
||||
|
||||
// Fetch actions breakdown
|
||||
const fetchActions = useCallback(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (actionStartDate) {
|
||||
params.append('startDate', new Date(actionStartDate).toISOString());
|
||||
}
|
||||
if (actionEndDate) {
|
||||
const end = new Date(actionEndDate);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
params.append('endDate', end.toISOString());
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE}/admin/stats/actions?${params}`,
|
||||
{ credentials: 'include' }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch actions data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setActionsData(data.data?.actions || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching actions:', err);
|
||||
throw err;
|
||||
}
|
||||
}, [actionStartDate, actionEndDate]);
|
||||
|
||||
// Fetch peak times
|
||||
const fetchPeakTimes = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/stats/peak-times`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch peak times data');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setPeakTimesData(data.data);
|
||||
} catch (err) {
|
||||
console.error('Error fetching peak times:', err);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch all data
|
||||
const fetchAllData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchActiveUsers(),
|
||||
fetchActions(),
|
||||
fetchPeakTimes()
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchActiveUsers, fetchActions, fetchPeakTimes]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchAllData();
|
||||
}, [fetchAllData]);
|
||||
|
||||
// Re-fetch active users when period changes
|
||||
useEffect(() => {
|
||||
fetchActiveUsers();
|
||||
}, [fetchActiveUsers]);
|
||||
|
||||
// Re-fetch actions when date range changes
|
||||
useEffect(() => {
|
||||
fetchActions();
|
||||
}, [fetchActions]);
|
||||
|
||||
// Format date for chart
|
||||
const formatChartDate = (dateStr) => {
|
||||
if (!dateStr) return '';
|
||||
const date = new Date(dateStr);
|
||||
|
||||
if (period === 'monthly') {
|
||||
return date.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
|
||||
} else if (period === 'weekly') {
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
};
|
||||
|
||||
// Format hour for display
|
||||
const formatHour = (hour) => {
|
||||
if (hour === 0) return '12am';
|
||||
if (hour === 12) return '12pm';
|
||||
return hour < 12 ? `${hour}am` : `${hour - 12}pm`;
|
||||
};
|
||||
|
||||
// Get color for heatmap cell based on value
|
||||
const getHeatmapColor = (value, maxValue) => {
|
||||
if (!value || maxValue === 0) return HEATMAP_COLORS[0];
|
||||
const intensity = Math.min(Math.floor((value / maxValue) * 10), 9);
|
||||
return HEATMAP_COLORS[intensity];
|
||||
};
|
||||
|
||||
// Build heatmap data (24 hours x 7 days)
|
||||
const buildHeatmapData = () => {
|
||||
if (!peakTimesData?.hourly || !peakTimesData?.daily) return null;
|
||||
|
||||
// Find max value for color scaling
|
||||
const hourlyMax = Math.max(...peakTimesData.hourly.map(h => h.avgActivity || 0));
|
||||
const dailyMax = Math.max(...peakTimesData.daily.map(d => d.avgActivity || 0));
|
||||
const maxValue = Math.max(hourlyMax, dailyMax);
|
||||
|
||||
// Create a simple heatmap structure
|
||||
// For now, we'll show hourly distribution across the week
|
||||
// The backend returns separate hourly and daily averages
|
||||
return {
|
||||
hourly: peakTimesData.hourly,
|
||||
daily: peakTimesData.daily,
|
||||
maxValue
|
||||
};
|
||||
};
|
||||
|
||||
const heatmapData = buildHeatmapData();
|
||||
|
||||
// Custom tooltip for pie chart
|
||||
const CustomPieTooltip = ({ active, payload }) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0];
|
||||
const total = actionsData.reduce((sum, d) => sum + (d.count || 0), 0);
|
||||
const percentage = total > 0 ? ((data.value / total) * 100).toFixed(1) : 0;
|
||||
return (
|
||||
<div className="bg-white p-3 border rounded-lg shadow-lg">
|
||||
<p className="font-medium">{data.payload.action}</p>
|
||||
<p className="text-sm text-gray-600">{data.value.toLocaleString()} ({percentage}%)</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<button
|
||||
onClick={() => navigate('/admin')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Dashboard
|
||||
</button>
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<button
|
||||
onClick={() => navigate('/admin')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700 mb-2"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Dashboard
|
||||
</button>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usage Statistics</h1>
|
||||
<p className="text-gray-600">Detailed analytics and usage patterns</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchAllData}
|
||||
disabled={loading}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Active Users Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 mb-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<TrendingUp className="w-5 h-5 text-violet-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Active Users Over Time</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
{/* Period Toggle */}
|
||||
<div className="flex items-center space-x-1 bg-gray-100 rounded-lg p-1">
|
||||
{['daily', 'weekly', 'monthly'].map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => {
|
||||
setPeriod(p);
|
||||
// Adjust days based on period
|
||||
if (p === 'daily') setDays(30);
|
||||
else if (p === 'weekly') setDays(12);
|
||||
else setDays(12);
|
||||
}}
|
||||
className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
|
||||
period === p
|
||||
? 'bg-white text-violet-600 shadow-sm'
|
||||
: 'text-gray-600 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
{p.charAt(0).toUpperCase() + p.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Days selector */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="w-4 h-4 text-gray-500" />
|
||||
<select
|
||||
value={days}
|
||||
onChange={(e) => setDays(parseInt(e.target.value))}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 text-sm focus:ring-2 focus:ring-violet-500"
|
||||
>
|
||||
<option value={7}>Last 7 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={14}>Last 14 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={30}>Last 30 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
<option value={90}>Last 90 {period === 'daily' ? 'days' : period === 'weekly' ? 'weeks' : 'months'}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Chart Skeleton */
|
||||
<div className="h-80 animate-pulse">
|
||||
<div className="flex items-end h-64 space-x-2 px-8">
|
||||
{[...Array(12)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 bg-gray-200 rounded-t"
|
||||
style={{ height: `${Math.random() * 60 + 20}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-between mt-4 px-8">
|
||||
{[...Array(6)].map((_, i) => (
|
||||
<div key={i} className="h-3 bg-gray-200 rounded w-12" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : activeUsersData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={320}>
|
||||
<LineChart data={activeUsersData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatChartDate}
|
||||
tick={{ fontSize: 12 }}
|
||||
interval="preserveStartEnd"
|
||||
/>
|
||||
<YAxis
|
||||
allowDecimals={false}
|
||||
tick={{ fontSize: 12 }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value, 'Active Users']}
|
||||
labelFormatter={formatChartDate}
|
||||
/>
|
||||
<Legend />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="count"
|
||||
name="Active Users"
|
||||
stroke="#7c3aed"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#7c3aed', strokeWidth: 2, r: 3 }}
|
||||
activeDot={{ r: 6 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-80 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Users className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No active user data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Breakdown Section */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Pie Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 mb-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Activity className="w-5 h-5 text-blue-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Action Breakdown</h2>
|
||||
</div>
|
||||
|
||||
{/* Date Range */}
|
||||
<div className="flex items-center space-x-2 text-sm">
|
||||
<input
|
||||
type="date"
|
||||
value={actionStartDate}
|
||||
onChange={(e) => setActionStartDate(e.target.value)}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
<span className="text-gray-500">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={actionEndDate}
|
||||
onChange={(e) => setActionEndDate(e.target.value)}
|
||||
className="border border-gray-300 rounded-md px-2 py-1 focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Pie Chart Skeleton */
|
||||
<div className="h-64 flex items-center justify-center animate-pulse">
|
||||
<div className="w-48 h-48 rounded-full bg-gray-200 relative">
|
||||
<div className="absolute inset-4 rounded-full bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
) : actionsData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={actionsData}
|
||||
dataKey="count"
|
||||
nameKey="action"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={100}
|
||||
label={({ action, percent }) =>
|
||||
`${action} (${(percent * 100).toFixed(0)}%)`
|
||||
}
|
||||
labelLine={{ stroke: '#64748b', strokeWidth: 1 }}
|
||||
>
|
||||
{actionsData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={CHART_COLORS[index % CHART_COLORS.length]}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip content={<CustomPieTooltip />} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No action data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bar Chart */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-4">
|
||||
<Activity className="w-5 h-5 text-green-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Actions by Type</h2>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Bar Chart Skeleton */
|
||||
<div className="h-64 space-y-3 py-4 animate-pulse">
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<div key={i} className="flex items-center space-x-3">
|
||||
<div className="h-4 bg-gray-200 rounded w-20" />
|
||||
<div
|
||||
className="h-6 bg-gray-200 rounded"
|
||||
style={{ width: `${Math.random() * 50 + 20}%` }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : actionsData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<BarChart data={actionsData} layout="vertical">
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis type="number" tick={{ fontSize: 12 }} />
|
||||
<YAxis
|
||||
type="category"
|
||||
dataKey="action"
|
||||
tick={{ fontSize: 12 }}
|
||||
width={100}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => [value.toLocaleString(), 'Count']}
|
||||
/>
|
||||
<Bar dataKey="count" radius={[0, 4, 4, 0]}>
|
||||
{actionsData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={CHART_COLORS[index % CHART_COLORS.length]}
|
||||
/>
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Activity className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No action data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Peak Times Heatmap */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center space-x-2 mb-4">
|
||||
<Clock className="w-5 h-5 text-orange-600" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Peak Usage Times</h2>
|
||||
<span className="text-sm text-gray-500">(Based on last 30 days)</span>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
/* Heatmap Skeleton */
|
||||
<div className="space-y-6 animate-pulse">
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-40 mb-3" />
|
||||
<div className="flex space-x-1">
|
||||
{[...Array(24)].map((_, i) => (
|
||||
<div key={i} className="w-6 h-16 bg-gray-200 rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="h-4 bg-gray-200 rounded w-40 mb-3" />
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div key={i} className="h-16 bg-gray-200 rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : heatmapData ? (
|
||||
<div className="space-y-6">
|
||||
{/* Hourly Distribution */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-700 mb-3">Hourly Activity Distribution</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="inline-flex items-end space-x-1 min-w-full">
|
||||
{heatmapData.hourly.map((hourData, index) => {
|
||||
const height = heatmapData.maxValue > 0
|
||||
? Math.max(20, (hourData.avgActivity / heatmapData.maxValue) * 100)
|
||||
: 20;
|
||||
return (
|
||||
<div key={index} className="flex flex-col items-center">
|
||||
<div
|
||||
className="w-6 rounded-t transition-all duration-200 hover:opacity-80"
|
||||
style={{
|
||||
height: `${height}px`,
|
||||
backgroundColor: getHeatmapColor(hourData.avgActivity, heatmapData.maxValue)
|
||||
}}
|
||||
title={`${formatHour(hourData.hour)}: ${hourData.avgActivity?.toFixed(1) || 0} avg activities`}
|
||||
/>
|
||||
<span className="text-xs text-gray-500 mt-1">
|
||||
{index % 3 === 0 ? formatHour(hourData.hour) : ''}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Daily Distribution */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-700 mb-3">Daily Activity Distribution</h3>
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{heatmapData.daily.map((dayData, index) => {
|
||||
const dayIndex = DAY_NAMES.indexOf(dayData.day);
|
||||
const displayDay = dayIndex !== -1 ? DAY_NAMES[dayIndex] : dayData.day;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="p-4 rounded-lg text-center transition-all duration-200 hover:opacity-80"
|
||||
style={{
|
||||
backgroundColor: getHeatmapColor(dayData.avgActivity, heatmapData.maxValue)
|
||||
}}
|
||||
title={`${displayDay}: ${dayData.avgActivity?.toFixed(1) || 0} avg activities`}
|
||||
>
|
||||
<p className="text-xs font-medium text-gray-700">{displayDay}</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{dayData.avgActivity?.toFixed(0) || 0}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Color Legend */}
|
||||
<div className="flex items-center justify-end space-x-2">
|
||||
<span className="text-xs text-gray-500">Less</span>
|
||||
<div className="flex space-x-0.5">
|
||||
{HEATMAP_COLORS.map((color, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-4 h-4 rounded-sm"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">More</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
<div className="text-center">
|
||||
<Clock className="w-12 h-12 text-gray-300 mx-auto mb-2" />
|
||||
<p>No peak times data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Summary Stats */}
|
||||
{actionsData.length > 0 && (
|
||||
<div className="bg-gray-100 rounded-lg p-4">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Total Actions</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionsData.reduce((sum, a) => sum + (a.count || 0), 0).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Most Common</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionsData.length > 0
|
||||
? actionsData.reduce((max, a) => a.count > max.count ? a : max, actionsData[0]).action
|
||||
: 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Action Types</p>
|
||||
<p className="text-lg font-bold text-gray-900">{actionsData.length}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Date Range</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{actionStartDate && actionEndDate
|
||||
? `${new Date(actionStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} - ${new Date(actionEndDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`
|
||||
: 'All time'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UsageStats;
|
||||
480
src/pages/admin/UserDetail.jsx
Normal file
480
src/pages/admin/UserDetail.jsx
Normal file
@ -0,0 +1,480 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { ArrowLeft, Shield, ShieldOff, UserCheck, UserX, RefreshCw, AlertCircle, Clock, Activity } from 'lucide-react';
|
||||
import useAuth from '../../hooks/useAuth';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const UserDetail = () => {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
// State
|
||||
const [user, setUser] = useState(null);
|
||||
const [recentActivity, setRecentActivity] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
|
||||
// Confirmation dialogs
|
||||
const [showStatusConfirm, setShowStatusConfirm] = useState(false);
|
||||
const [showRoleConfirm, setShowRoleConfirm] = useState(false);
|
||||
|
||||
// Check if viewing own profile
|
||||
const isOwnProfile = currentUser?._id === id;
|
||||
|
||||
// Fetch user details
|
||||
const fetchUser = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
throw new Error('Failed to fetch user details');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setRecentActivity(data.data.recentActivity || []);
|
||||
} catch (err) {
|
||||
console.error('Error fetching user:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
// Fetch on mount
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, [fetchUser]);
|
||||
|
||||
// Toggle user status (enable/disable)
|
||||
const handleToggleStatus = async () => {
|
||||
setActionLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ isActive: !user.isActive })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to update user status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setShowStatusConfirm(false);
|
||||
} catch (err) {
|
||||
console.error('Error toggling status:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle user role (promote/demote)
|
||||
const handleToggleRole = async () => {
|
||||
setActionLoading(true);
|
||||
|
||||
try {
|
||||
const newRole = user.role === 'admin' ? 'user' : 'admin';
|
||||
const response = await fetch(`${API_BASE}/admin/users/${id}/role`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ role: newRole })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to update user role');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUser(data.data.user);
|
||||
setShowRoleConfirm(false);
|
||||
} catch (err) {
|
||||
console.error('Error toggling role:', err);
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Format date helper
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Format datetime helper
|
||||
const formatDateTime = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
// Get activity action description
|
||||
const getActivityDescription = (activity) => {
|
||||
const actions = {
|
||||
'LOGIN': 'Logged in',
|
||||
'LOGOUT': 'Logged out',
|
||||
'PAGE_VIEW': `Viewed ${activity.metadata?.path || 'a page'}`,
|
||||
'API_CALL': `API call to ${activity.metadata?.endpoint || 'unknown'}`,
|
||||
'ADMIN_ENABLE_USER': 'Enabled a user',
|
||||
'ADMIN_DISABLE_USER': 'Disabled a user',
|
||||
'ADMIN_PROMOTE_USER': 'Promoted a user to admin',
|
||||
'ADMIN_DEMOTE_USER': 'Demoted a user from admin'
|
||||
};
|
||||
return actions[activity.action] || activity.action;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-6">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<RefreshCw className="w-8 h-8 animate-spin text-violet-600" />
|
||||
<span className="ml-3 text-gray-600">Loading user details...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Users
|
||||
</button>
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-red-700 mb-4">{error}</p>
|
||||
<button
|
||||
onClick={fetchUser}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Back Button */}
|
||||
<button
|
||||
onClick={() => navigate('/admin/users')}
|
||||
className="flex items-center text-violet-600 hover:text-violet-700"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Users
|
||||
</button>
|
||||
|
||||
{/* User Profile Card */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
{user.picture ? (
|
||||
<img
|
||||
src={user.picture}
|
||||
alt={user.name}
|
||||
className="w-20 h-20 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-20 h-20 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-2xl font-medium text-gray-600">
|
||||
{user.name?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{user.name}</h1>
|
||||
<p className="text-gray-600">{user.email}</p>
|
||||
<div className="flex items-center space-x-2 mt-2">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.role === 'admin'
|
||||
? 'bg-violet-100 text-violet-800'
|
||||
: 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.isActive
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{user.isActive ? 'Active' : 'Disabled'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={fetchUser}
|
||||
className="p-2 text-gray-400 hover:text-gray-600"
|
||||
title="Refresh"
|
||||
>
|
||||
<RefreshCw className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* User Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6 pt-6 border-t">
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Login Count</p>
|
||||
<p className="text-xl font-semibold">{user.loginCount || 0}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Created</p>
|
||||
<p className="text-lg font-medium">{formatDate(user.createdAt)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Last Login</p>
|
||||
<p className="text-lg font-medium">{formatDateTime(user.lastLoginAt)}</p>
|
||||
</div>
|
||||
{user.disabledAt && (
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Disabled At</p>
|
||||
<p className="text-lg font-medium text-red-600">{formatDateTime(user.disabledAt)}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Google ID (for debugging) */}
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<p className="text-sm text-gray-500">
|
||||
<span className="font-medium">Google ID:</span> {user.googleId}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions Card */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">Actions</h2>
|
||||
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{/* Enable/Disable Button */}
|
||||
<div className="relative group">
|
||||
<button
|
||||
onClick={() => setShowStatusConfirm(true)}
|
||||
disabled={isOwnProfile || actionLoading}
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
|
||||
user.isActive
|
||||
? 'bg-red-100 text-red-700 hover:bg-red-200'
|
||||
: 'bg-green-100 text-green-700 hover:bg-green-200'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{user.isActive ? (
|
||||
<>
|
||||
<UserX className="w-4 h-4" />
|
||||
<span>Disable User</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserCheck className="w-4 h-4" />
|
||||
<span>Enable User</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{isOwnProfile && (
|
||||
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
|
||||
You cannot disable your own account
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Promote/Demote Button */}
|
||||
<div className="relative group">
|
||||
<button
|
||||
onClick={() => setShowRoleConfirm(true)}
|
||||
disabled={isOwnProfile || actionLoading}
|
||||
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
|
||||
user.role === 'admin'
|
||||
? 'bg-orange-100 text-orange-700 hover:bg-orange-200'
|
||||
: 'bg-violet-100 text-violet-700 hover:bg-violet-200'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{user.role === 'admin' ? (
|
||||
<>
|
||||
<ShieldOff className="w-4 h-4" />
|
||||
<span>Demote to User</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Promote to Admin</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{isOwnProfile && (
|
||||
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
|
||||
You cannot demote yourself
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-lg font-semibold mb-4 flex items-center">
|
||||
<Activity className="w-5 h-5 mr-2" />
|
||||
Recent Activity
|
||||
</h2>
|
||||
|
||||
{recentActivity.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
<Clock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
|
||||
<p>No recent activity recorded</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{recentActivity.map((activity, index) => (
|
||||
<div
|
||||
key={activity._id || index}
|
||||
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">
|
||||
{getActivityDescription(activity)}
|
||||
</p>
|
||||
{activity.metadata?.ip && (
|
||||
<p className="text-sm text-gray-500">
|
||||
IP: {activity.metadata.ip}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">
|
||||
{formatDateTime(activity.timestamp)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Confirmation Dialog */}
|
||||
{showStatusConfirm && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
{user.isActive ? 'Disable User' : 'Enable User'}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{user.isActive
|
||||
? `Are you sure you want to disable ${user.name}? They will no longer be able to access the application.`
|
||||
: `Are you sure you want to enable ${user.name}? They will be able to access the application again.`}
|
||||
</p>
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={() => setShowStatusConfirm(false)}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleToggleStatus}
|
||||
disabled={actionLoading}
|
||||
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
|
||||
user.isActive
|
||||
? 'bg-red-600 hover:bg-red-700'
|
||||
: 'bg-green-600 hover:bg-green-700'
|
||||
}`}
|
||||
>
|
||||
{actionLoading ? (
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
) : user.isActive ? (
|
||||
'Disable'
|
||||
) : (
|
||||
'Enable'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Role Confirmation Dialog */}
|
||||
{showRoleConfirm && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
{user.role === 'admin' ? 'Demote User' : 'Promote User'}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{user.role === 'admin'
|
||||
? `Are you sure you want to demote ${user.name} from admin? They will lose access to admin features.`
|
||||
: `Are you sure you want to promote ${user.name} to admin? They will have full administrative access.`}
|
||||
</p>
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={() => setShowRoleConfirm(false)}
|
||||
disabled={actionLoading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleToggleRole}
|
||||
disabled={actionLoading}
|
||||
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
|
||||
user.role === 'admin'
|
||||
? 'bg-orange-600 hover:bg-orange-700'
|
||||
: 'bg-violet-600 hover:bg-violet-700'
|
||||
}`}
|
||||
>
|
||||
{actionLoading ? (
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
) : user.role === 'admin' ? (
|
||||
'Demote'
|
||||
) : (
|
||||
'Promote'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserDetail;
|
||||
436
src/pages/admin/UserList.jsx
Normal file
436
src/pages/admin/UserList.jsx
Normal file
@ -0,0 +1,436 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Search, ChevronLeft, ChevronRight, Users, RefreshCw } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'https://apartments.maverickapplications.com/api';
|
||||
|
||||
const UserList = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// State
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Pagination
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalUsers, setTotalUsers] = useState(0);
|
||||
const limit = 20;
|
||||
|
||||
// Filters
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('all');
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortOrder, setSortOrder] = useState('desc');
|
||||
|
||||
// Debounce search input (300ms)
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedSearch(searchQuery);
|
||||
setPage(1); // Reset to first page on search
|
||||
}, 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchQuery]);
|
||||
|
||||
// Fetch users
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString(),
|
||||
sortBy,
|
||||
sortOrder
|
||||
});
|
||||
|
||||
if (debouncedSearch) {
|
||||
params.append('search', debouncedSearch);
|
||||
}
|
||||
|
||||
if (statusFilter !== 'all') {
|
||||
params.append('status', statusFilter);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/users?${params}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch users');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setUsers(data.data.users);
|
||||
setTotalPages(data.data.pagination.totalPages);
|
||||
setTotalUsers(data.data.pagination.total);
|
||||
} catch (err) {
|
||||
console.error('Error fetching users:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, debouncedSearch, statusFilter, sortBy, sortOrder]);
|
||||
|
||||
// Fetch on mount and when dependencies change
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [fetchUsers]);
|
||||
|
||||
// Handle row click
|
||||
const handleRowClick = (userId) => {
|
||||
navigate(`/admin/users/${userId}`);
|
||||
};
|
||||
|
||||
// Handle status filter change
|
||||
const handleStatusChange = (e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Handle sort change
|
||||
const handleSortChange = (field) => {
|
||||
if (sortBy === field) {
|
||||
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
setSortBy(field);
|
||||
setSortOrder('desc');
|
||||
}
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// Format date helper
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// Format datetime helper
|
||||
const formatDateTime = (dateStr) => {
|
||||
if (!dateStr) return 'Never';
|
||||
return new Date(dateStr).toLocaleString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
// Sort indicator
|
||||
const SortIndicator = ({ field }) => {
|
||||
if (sortBy !== field) return null;
|
||||
return (
|
||||
<span className="ml-1">
|
||||
{sortOrder === 'asc' ? '\u2191' : '\u2193'}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-6">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
|
||||
<p className="text-red-700 mb-4">Error: {error}</p>
|
||||
<button
|
||||
onClick={fetchUsers}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">User Management</h1>
|
||||
<p className="text-gray-600">
|
||||
{totalUsers} total user{totalUsers !== 1 ? 's' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={fetchUsers}
|
||||
disabled={loading}
|
||||
className="flex items-center justify-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50 w-full sm:w-auto"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white rounded-lg shadow-md p-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
{/* Search */}
|
||||
<div className="flex-1 min-w-[250px]">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or email..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Filter */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm font-medium text-gray-700">Status:</label>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={handleStatusChange}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
|
||||
>
|
||||
<option value="all">All</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="disabled">Disabled</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Users Table */}
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{loading && users.length === 0 ? (
|
||||
/* Skeleton Loader */
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">User</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Role</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Status</th>
|
||||
<th className="text-center py-3 px-4 font-semibold text-gray-700">Logins</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Last Login</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...Array(5)].map((_, index) => (
|
||||
<tr key={index} className={`border-b ${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}`}>
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center space-x-3 animate-pulse">
|
||||
<div className="w-8 h-8 rounded-full bg-gray-200"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-24"></div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-40 animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-5 bg-gray-200 rounded-full w-12 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-5 bg-gray-200 rounded-full w-16 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-center">
|
||||
<div className="h-4 bg-gray-200 rounded w-8 mx-auto animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-32 animate-pulse"></div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-24 animate-pulse"></div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">No Users Found</h3>
|
||||
<p className="text-gray-600">
|
||||
{debouncedSearch || statusFilter !== 'all'
|
||||
? 'No users found matching your search. Try adjusting your filters.'
|
||||
: 'No users have signed up yet.'}
|
||||
</p>
|
||||
{(debouncedSearch || statusFilter !== 'all') && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSearchQuery('');
|
||||
setStatusFilter('all');
|
||||
setPage(1);
|
||||
}}
|
||||
className="mt-4 px-4 py-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50 rounded-md"
|
||||
>
|
||||
Clear all filters
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max">
|
||||
<thead className="bg-gray-50 border-b">
|
||||
<tr>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">User</th>
|
||||
<th className="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('role')}
|
||||
>
|
||||
Role
|
||||
<SortIndicator field="role" />
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('isActive')}
|
||||
>
|
||||
Status
|
||||
<SortIndicator field="isActive" />
|
||||
</th>
|
||||
<th
|
||||
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('loginCount')}
|
||||
>
|
||||
Logins
|
||||
<SortIndicator field="loginCount" />
|
||||
</th>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('lastLoginAt')}
|
||||
>
|
||||
Last Login
|
||||
<SortIndicator field="lastLoginAt" />
|
||||
</th>
|
||||
<th
|
||||
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
|
||||
onClick={() => handleSortChange('createdAt')}
|
||||
>
|
||||
Created
|
||||
<SortIndicator field="createdAt" />
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user, index) => (
|
||||
<tr
|
||||
key={user._id}
|
||||
onClick={() => handleRowClick(user._id)}
|
||||
className={`border-b cursor-pointer transition-colors ${
|
||||
index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
|
||||
} hover:bg-violet-50`}
|
||||
>
|
||||
{/* Avatar + Name */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
{user.picture ? (
|
||||
<img
|
||||
src={user.picture}
|
||||
alt={user.name}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-gray-600">
|
||||
{user.name?.charAt(0)?.toUpperCase() || '?'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<span className="font-medium text-gray-900">{user.name}</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Email */}
|
||||
<td className="py-3 px-4 text-gray-600">{user.email}</td>
|
||||
|
||||
{/* Role */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.role === 'admin'
|
||||
? 'bg-violet-100 text-violet-800'
|
||||
: 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
user.isActive
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{user.isActive ? 'Active' : 'Disabled'}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Login Count */}
|
||||
<td className="py-3 px-4 text-center text-gray-600">
|
||||
{user.loginCount || 0}
|
||||
</td>
|
||||
|
||||
{/* Last Login */}
|
||||
<td className="py-3 px-4 text-gray-600">
|
||||
{formatDateTime(user.lastLoginAt)}
|
||||
</td>
|
||||
|
||||
{/* Created */}
|
||||
<td className="py-3 px-4 text-gray-600">
|
||||
{formatDate(user.createdAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-between gap-3 px-4 py-3 bg-gray-50 border-t">
|
||||
<div className="text-sm text-gray-600 text-center sm:text-left">
|
||||
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalUsers)} of {totalUsers} users
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => setPage(Math.max(1, page - 1))}
|
||||
disabled={page === 1 || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span className="ml-1 hidden sm:inline">Previous</span>
|
||||
</button>
|
||||
<span className="px-3 py-1 text-sm">
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setPage(Math.min(totalPages, page + 1))}
|
||||
disabled={page === totalPages || loading}
|
||||
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="mr-1 hidden sm:inline">Next</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserList;
|
||||
Reference in New Issue
Block a user