Compare commits
7 Commits
frontend-i
...
9ed775e04a
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ed775e04a | |||
| a05f99080c | |||
| d285429e25 | |||
| 7b596a9d73 | |||
| f33ef01a6d | |||
| 2ffe3a0197 | |||
| 4e8d64ddc8 |
460
src/App.jsx
460
src/App.jsx
@ -1,11 +1,19 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
|
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 { 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 } 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';
|
||||||
|
|
||||||
const ApartmentDashboard = () => {
|
const ApartmentDashboard = () => {
|
||||||
// Router
|
// Router
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const { user, loading: authLoading, logout } = useAuth();
|
||||||
|
|
||||||
// Basic state
|
// Basic state
|
||||||
const [selectedUnit, setSelectedUnit] = useState(null);
|
const [selectedUnit, setSelectedUnit] = useState(null);
|
||||||
@ -19,8 +27,25 @@ const ApartmentDashboard = () => {
|
|||||||
// Filters
|
// Filters
|
||||||
const [priceFilter, setPriceFilter] = useState({ min: 0, max: 10000 });
|
const [priceFilter, setPriceFilter] = useState({ min: 0, max: 10000 });
|
||||||
const [bedroomFilter, setBedroomFilter] = useState('all');
|
const [bedroomFilter, setBedroomFilter] = useState('all');
|
||||||
const [sortBy, setSortBy] = useState('alphabetical');
|
const [sortBy, setSortBy] = useState('unitCode');
|
||||||
|
const [sortDirection, setSortDirection] = useState('asc');
|
||||||
const [watchedUnits, setWatchedUnits] = useState(new Set());
|
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
|
// API Data state - using your working endpoints
|
||||||
const [dailySummary, setDailySummary] = useState(null);
|
const [dailySummary, setDailySummary] = useState(null);
|
||||||
@ -52,11 +77,11 @@ const ApartmentDashboard = () => {
|
|||||||
|
|
||||||
// Fetch core endpoints that we know work
|
// Fetch core endpoints that we know work
|
||||||
const coreRequests = [
|
const coreRequests = [
|
||||||
fetch(`${API_BASE}/daily-summary`),
|
fetch(`${API_BASE}/daily-summary`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/price-history`),
|
fetch(`${API_BASE}/price-history`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/available-units`),
|
fetch(`${API_BASE}/available-units`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/recent-activity`),
|
fetch(`${API_BASE}/recent-activity`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/plan-stats`)
|
fetch(`${API_BASE}/plan-stats`, { credentials: 'include' })
|
||||||
];
|
];
|
||||||
|
|
||||||
const [
|
const [
|
||||||
@ -94,11 +119,11 @@ const ApartmentDashboard = () => {
|
|||||||
// Try to fetch enhanced endpoints (won't break if they don't exist)
|
// Try to fetch enhanced endpoints (won't break if they don't exist)
|
||||||
try {
|
try {
|
||||||
const enhancedRequests = [
|
const enhancedRequests = [
|
||||||
fetch(`${API_BASE}/best-deals?limit=5`),
|
fetch(`${API_BASE}/best-deals?limit=5`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/price-drops?limit=5`),
|
fetch(`${API_BASE}/price-drops?limit=5`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/stale-inventory?limit=5`),
|
fetch(`${API_BASE}/stale-inventory?limit=5`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/market-insights`),
|
fetch(`${API_BASE}/market-insights`, { credentials: 'include' }),
|
||||||
fetch(`${API_BASE}/last-scrape`)
|
fetch(`${API_BASE}/last-scrape`, { credentials: 'include' })
|
||||||
];
|
];
|
||||||
|
|
||||||
const enhancedResponses = await Promise.all(enhancedRequests);
|
const enhancedResponses = await Promise.all(enhancedRequests);
|
||||||
@ -136,16 +161,19 @@ const ApartmentDashboard = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initial data fetch
|
// Initial data fetch - only when authenticated
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
// Auto-refresh every 5 minutes
|
// Auto-refresh every 5 minutes - only when authenticated
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
const interval = setInterval(fetchData, 5 * 60 * 1000);
|
const interval = setInterval(fetchData, 5 * 60 * 1000);
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, []);
|
}, [user]);
|
||||||
|
|
||||||
// Helper functions
|
// Helper functions
|
||||||
const formatPrice = (price) => `$${(price || 0).toLocaleString()}`;
|
const formatPrice = (price) => `$${(price || 0).toLocaleString()}`;
|
||||||
@ -288,7 +316,7 @@ const ApartmentDashboard = () => {
|
|||||||
const fetchUnitPriceHistory = async (unitCode) => {
|
const fetchUnitPriceHistory = async (unitCode) => {
|
||||||
setLoadingPriceHistory(true);
|
setLoadingPriceHistory(true);
|
||||||
try {
|
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) {
|
if (response.ok) {
|
||||||
const history = await response.json();
|
const history = await response.json();
|
||||||
setUnitPriceHistory(history);
|
setUnitPriceHistory(history);
|
||||||
@ -317,7 +345,7 @@ const ApartmentDashboard = () => {
|
|||||||
if (analyticsData) return; // Already fetched
|
if (analyticsData) return; // Already fetched
|
||||||
setLoadingAnalytics(true);
|
setLoadingAnalytics(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/analytics`);
|
const response = await fetch(`${API_BASE}/analytics`, { credentials: 'include' });
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setAnalyticsData(data);
|
setAnalyticsData(data);
|
||||||
@ -370,19 +398,36 @@ const ApartmentDashboard = () => {
|
|||||||
|
|
||||||
const insights = calculateInsights();
|
const insights = calculateInsights();
|
||||||
|
|
||||||
|
// Sort handler for column headers
|
||||||
|
const handleSort = (field) => {
|
||||||
|
if (sortBy === field) {
|
||||||
|
setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
|
||||||
|
} else {
|
||||||
|
setSortBy(field);
|
||||||
|
setSortDirection('asc');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Filter function for units
|
// Filter function for units
|
||||||
const filteredUnits = availableUnits.filter(unit => {
|
const filteredUnits = availableUnits.filter(unit => {
|
||||||
const matchesPrice = (unit.currentPrice || 0) >= priceFilter.min && (unit.currentPrice || 0) <= priceFilter.max;
|
const price = unit.currentPrice || 0;
|
||||||
|
const matchesPrice = price >= priceFilter.min && (priceFilter.max === 10000 || price <= priceFilter.max);
|
||||||
const matchesBedroom = bedroomFilter === 'all' || (unit.bedCount != null && unit.bedCount.toString() === bedroomFilter);
|
const matchesBedroom = bedroomFilter === 'all' || (unit.bedCount != null && unit.bedCount.toString() === bedroomFilter);
|
||||||
return matchesPrice && matchesBedroom;
|
return matchesPrice && matchesBedroom;
|
||||||
}).sort((a, b) => {
|
}).sort((a, b) => {
|
||||||
|
const dir = sortDirection === 'asc' ? 1 : -1;
|
||||||
switch (sortBy) {
|
switch (sortBy) {
|
||||||
case 'alphabetical': return (a.unitCode || '').localeCompare(b.unitCode || '');
|
case 'unitCode': return dir * (a.unitCode || '').localeCompare(b.unitCode || '');
|
||||||
case 'price': return (a.currentPrice || 0) - (b.currentPrice || 0);
|
case 'planName': return dir * (a.planName || '').localeCompare(b.planName || '');
|
||||||
case 'priceDesc': return (b.currentPrice || 0) - (a.currentPrice || 0);
|
case 'bedCount': return dir * ((a.bedCount || 0) - (b.bedCount || 0));
|
||||||
case 'size': return (b.area || 0) - (a.area || 0);
|
case 'area': return dir * ((a.area || 0) - (b.area || 0));
|
||||||
case 'daysAvailable': return (b.daysAvailable || 0) - (a.daysAvailable || 0);
|
case 'price': return dir * ((a.currentPrice || 0) - (b.currentPrice || 0));
|
||||||
case 'pricePerSqft': return ((a.currentPrice || 0) / (a.area || 1)) - ((b.currentPrice || 0) / (b.area || 1));
|
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;
|
default: return 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -424,6 +469,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
|
// Error state
|
||||||
if (error && !dailySummary) {
|
if (error && !dailySummary) {
|
||||||
return (
|
return (
|
||||||
@ -459,12 +513,34 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
{priceDrops.length > 0 && (
|
{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">
|
<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" />
|
<Bell className="w-4 h-4" />
|
||||||
<span>{priceDrops.length} price drops</span>
|
<span>{priceDrops.length} price drops</span>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<div className="flex items-center space-x-4 mt-4">
|
<div className="flex items-center space-x-4 mt-4">
|
||||||
@ -486,12 +562,40 @@ const ApartmentDashboard = () => {
|
|||||||
>
|
>
|
||||||
Analytics
|
Analytics
|
||||||
</Link>
|
</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/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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Routes>
|
<Routes>
|
||||||
|
<Route path="/login" element={<Login />} />
|
||||||
|
|
||||||
{/* Overview Page */}
|
{/* Overview Page */}
|
||||||
<Route path="/" element={
|
<Route path="/" element={
|
||||||
|
<ProtectedRoute>
|
||||||
<>
|
<>
|
||||||
{/* Key Metrics */}
|
{/* Key Metrics */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||||
@ -643,10 +747,12 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
</ProtectedRoute>
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Units Page */}
|
{/* Units Page */}
|
||||||
<Route path="/units" element={
|
<Route path="/units" element={
|
||||||
|
<ProtectedRoute>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Filters */}
|
{/* Filters */}
|
||||||
<div className="bg-white rounded-lg shadow-md p-6">
|
<div className="bg-white rounded-lg shadow-md p-6">
|
||||||
@ -666,7 +772,7 @@ const ApartmentDashboard = () => {
|
|||||||
onChange={(e) => setPriceFilter({...priceFilter, max: parseInt(e.target.value)})}
|
onChange={(e) => setPriceFilter({...priceFilter, max: parseInt(e.target.value)})}
|
||||||
className="w-32"
|
className="w-32"
|
||||||
/>
|
/>
|
||||||
<span className="text-sm">{formatPrice(priceFilter.max)}</span>
|
<span className="text-sm">{priceFilter.max === 10000 ? 'No limit' : formatPrice(priceFilter.max)}</span>
|
||||||
</div>
|
</div>
|
||||||
<select
|
<select
|
||||||
value={bedroomFilter}
|
value={bedroomFilter}
|
||||||
@ -679,21 +785,91 @@ const ApartmentDashboard = () => {
|
|||||||
<option value="2">2 BR</option>
|
<option value="2">2 BR</option>
|
||||||
</select>
|
</select>
|
||||||
<select
|
<select
|
||||||
value={sortBy}
|
value={`${sortBy}-${sortDirection}`}
|
||||||
onChange={(e) => setSortBy(e.target.value)}
|
onChange={(e) => {
|
||||||
|
const [field, dir] = e.target.value.split('-');
|
||||||
|
setSortBy(field);
|
||||||
|
setSortDirection(dir);
|
||||||
|
}}
|
||||||
className="border rounded-md px-3 py-2"
|
className="border rounded-md px-3 py-2"
|
||||||
>
|
>
|
||||||
<option value="alphabetical">Alphabetical</option>
|
<option value="unitCode-asc">Unit: A to Z</option>
|
||||||
<option value="price">Price: Low to High</option>
|
<option value="unitCode-desc">Unit: Z to A</option>
|
||||||
<option value="priceDesc">Price: High to Low</option>
|
<option value="price-asc">Price: Low to High</option>
|
||||||
<option value="size">Size: Large to Small</option>
|
<option value="price-desc">Price: High to Low</option>
|
||||||
<option value="daysAvailable">Days Available</option>
|
<option value="area-asc">Size: Small to Large</option>
|
||||||
<option value="pricePerSqft">Price per Sqft</option>
|
<option value="area-desc">Size: Large to Small</option>
|
||||||
|
<option value="daysAvailable-asc">Days: Low to High</option>
|
||||||
|
<option value="daysAvailable-desc">Days: High to Low</option>
|
||||||
|
<option value="pricePerSqft-asc">$/sqft: Low to High</option>
|
||||||
|
<option value="pricePerSqft-desc">$/sqft: High to Low</option>
|
||||||
</select>
|
</select>
|
||||||
|
<div className="flex items-center border rounded-md overflow-hidden ml-auto">
|
||||||
|
<button
|
||||||
|
onClick={() => setUnitsViewMode('grid')}
|
||||||
|
className={`p-2 ${unitsViewMode === 'grid' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-100'}`}
|
||||||
|
title="Grid view"
|
||||||
|
>
|
||||||
|
<LayoutGrid className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setUnitsViewMode('list')}
|
||||||
|
className={`p-2 ${unitsViewMode === 'list' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-100'}`}
|
||||||
|
title="List view"
|
||||||
|
>
|
||||||
|
<List className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Unit Cards */}
|
{/* 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 */}
|
||||||
|
{unitsViewMode === 'grid' && (
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
|
||||||
{filteredUnits.map((unit) => (
|
{filteredUnits.map((unit) => (
|
||||||
<div key={unit.unitCode} className={`bg-white rounded-lg shadow-md overflow-hidden ${watchedUnits.has(unit.unitCode) ? 'ring-2 ring-blue-400' : ''}`}>
|
<div key={unit.unitCode} className={`bg-white rounded-lg shadow-md overflow-hidden ${watchedUnits.has(unit.unitCode) ? 'ring-2 ring-blue-400' : ''}`}>
|
||||||
@ -726,28 +902,183 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<button
|
<button
|
||||||
onClick={() => openUnitDetail(unit)}
|
onClick={() => openUnitDetail(unit)}
|
||||||
className="flex-1 bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors"
|
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors"
|
||||||
>
|
>
|
||||||
View Details
|
View Details
|
||||||
</button>
|
</button>
|
||||||
<button
|
|
||||||
onClick={() => toggleWatchUnit(unit.unitCode)}
|
|
||||||
className={`px-4 py-2 rounded-md transition-colors ${
|
|
||||||
watchedUnits.has(unit.unitCode)
|
|
||||||
? 'bg-yellow-500 text-white hover:bg-yellow-600'
|
|
||||||
: 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Eye className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Unit Cards - List View */}
|
||||||
|
{unitsViewMode === 'list' && (
|
||||||
|
<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>
|
||||||
|
{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>
|
||||||
|
{filteredUnits.map((unit, index) => (
|
||||||
|
<tr
|
||||||
|
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`}
|
||||||
|
>
|
||||||
|
{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>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{filteredUnits.length === 0 && (
|
{filteredUnits.length === 0 && (
|
||||||
<div className="text-center py-12">
|
<div className="text-center py-12">
|
||||||
@ -757,10 +1088,12 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</ProtectedRoute>
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Analytics Page */}
|
{/* Analytics Page */}
|
||||||
<Route path="/analytics" element={
|
<Route path="/analytics" element={
|
||||||
|
<ProtectedRoute>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<h2 className="text-xl font-semibold">Market Analytics</h2>
|
<h2 className="text-xl font-semibold">Market Analytics</h2>
|
||||||
@ -964,6 +1297,24 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</ProtectedRoute>
|
||||||
|
} />
|
||||||
|
|
||||||
|
{/* Admin Routes */}
|
||||||
|
<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>
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Catch-all redirect to overview */}
|
{/* Catch-all redirect to overview */}
|
||||||
@ -1107,19 +1458,6 @@ const ApartmentDashboard = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<button
|
|
||||||
onClick={() => toggleWatchUnit(selectedUnit.unitCode)}
|
|
||||||
className={`flex-1 py-2 px-4 rounded-md transition-colors ${
|
|
||||||
watchedUnits.has(selectedUnit.unitCode)
|
|
||||||
? 'bg-yellow-500 text-white hover:bg-yellow-600'
|
|
||||||
: 'bg-blue-600 text-white hover:bg-blue-700'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{watchedUnits.has(selectedUnit.unitCode) ? 'Stop Watching' : 'Watch This Unit'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
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 { StrictMode } from 'react'
|
||||||
import { createRoot } from 'react-dom/client'
|
import { createRoot } from 'react-dom/client'
|
||||||
import { BrowserRouter } from 'react-router-dom'
|
import { BrowserRouter } from 'react-router-dom'
|
||||||
|
import { AuthProvider } from './context/AuthContext'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
import App from './App.jsx'
|
import App from './App.jsx'
|
||||||
|
|
||||||
createRoot(document.getElementById('root')).render(
|
createRoot(document.getElementById('root')).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
|
<AuthProvider>
|
||||||
<App />
|
<App />
|
||||||
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</StrictMode>,
|
</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;
|
||||||
717
src/pages/admin/ActivityStream.jsx
Normal file
717
src/pages/admin/ActivityStream.jsx
Normal file
@ -0,0 +1,717 @@
|
|||||||
|
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 items-center justify-between">
|
||||||
|
<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>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>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 ? (
|
||||||
|
<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 activities...</span>
|
||||||
|
</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
|
||||||
|
? 'Try adjusting your filters to see more results.'
|
||||||
|
: 'No activity has been recorded yet.'}
|
||||||
|
</p>
|
||||||
|
</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 items-center justify-between px-4 py-3 bg-gray-50 border-t">
|
||||||
|
<div className="text-sm text-gray-600">
|
||||||
|
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">Previous</span>
|
||||||
|
</button>
|
||||||
|
<span className="px-3 py-1 text-sm">
|
||||||
|
Page {page} of {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">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;
|
||||||
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;
|
||||||
382
src/pages/admin/UserList.jsx
Normal file
382
src/pages/admin/UserList.jsx
Normal file
@ -0,0 +1,382 @@
|
|||||||
|
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 items-center justify-between">
|
||||||
|
<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 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>
|
||||||
|
|
||||||
|
{/* 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 ? (
|
||||||
|
<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 users...</span>
|
||||||
|
</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'
|
||||||
|
? 'Try adjusting your filters to see more results.'
|
||||||
|
: 'No users have signed up yet.'}
|
||||||
|
</p>
|
||||||
|
</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 items-center justify-between px-4 py-3 bg-gray-50 border-t">
|
||||||
|
<div className="text-sm text-gray-600">
|
||||||
|
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">Previous</span>
|
||||||
|
</button>
|
||||||
|
<span className="px-3 py-1 text-sm">
|
||||||
|
Page {page} of {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">Next</span>
|
||||||
|
<ChevronRight className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UserList;
|
||||||
Reference in New Issue
Block a user