feat: complete admin panel major functionalities including responsive layout, recharts, custom modals, inline editing, and loading states

This commit is contained in:
parsa committed 2026-06-12 16:19:57 +03:30
1 parent ee041d4e52
commit a7ebb8d792
33 files changed
+1311 -173

No files matched your search

+5 -2
View File
@@ -2,6 +2,7 @@ import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Layout from './components/Layout';
import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import ProtectedRoute from './components/ProtectedRoute';
import Users from './pages/Users';
import Products from './pages/Products';
import Orders from './pages/Orders';
@@ -11,13 +12,15 @@ function App() {
<BrowserRouter>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route element={<ProtectedRoute />}>
<Route path="/" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="users" element={<Users />} />
<Route path="products" element={<Products />} />
<Route path="orders" element={<Orders />} />
<Route path="coupons" element={<div className="p-4">کدهای تخفیف</div>} />
<Route path="settings" element={<div className="p-4">تنظیمات سیستم</div>} />
</Route>
</Route>
</Routes>
</BrowserRouter>
@@ -1,13 +1,16 @@
import { useState } from 'react';
import { Outlet } from 'react-router-dom';
import Sidebar from './Sidebar';
import Topbar from './Topbar';
export default function Layout() {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
return (
<div className="flex min-h-screen bg-gray-50 text-gray-900 font-vazir" dir="rtl">
<Sidebar />
<div className="flex-1 flex flex-col min-h-screen">
<Topbar />
<div className="flex min-h-screen bg-gray-50 text-gray-900 font-vazir relative overflow-hidden" dir="rtl">
<Sidebar isOpen={isMobileMenuOpen} setIsOpen={setIsMobileMenuOpen} />
<div className="flex-1 flex flex-col min-h-screen w-full lg:w-auto">
<Topbar toggleMenu={() => setIsMobileMenuOpen(!isMobileMenuOpen)} />
<main className="flex-1 p-6 overflow-y-auto">
<Outlet />
</main>
@@ -0,0 +1,11 @@
import { Navigate, Outlet } from 'react-router-dom';
export default function ProtectedRoute() {
const token = localStorage.getItem('adminToken');
if (!token) {
return <Navigate to="/login" replace />;
}
return <Outlet />;
}
@@ -10,11 +10,27 @@ const menuItems = [
{ icon: Settings, label: 'تنظیمات', path: '/settings' },
];
export default function Sidebar() {
interface SidebarProps {
isOpen: boolean;
setIsOpen: (val: boolean) => void;
}
export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
const location = useLocation();
return (
<aside className="w-64 bg-white border-l border-gray-200 h-screen sticky top-0 flex flex-col font-vazir shadow-sm">
<>
{/* Mobile Backdrop */}
{isOpen && (
<div
className="fixed inset-0 bg-black/50 z-40 lg:hidden backdrop-blur-sm"
onClick={() => setIsOpen(false)}
/>
)}
<aside className={`w-64 bg-white border-l border-gray-200 h-screen fixed lg:sticky top-0 flex flex-col font-vazir shadow-sm z-50 transform transition-transform duration-300 ease-in-out ${
isOpen ? 'translate-x-0' : 'translate-x-full lg:translate-x-0'
}`}>
<div className="h-16 flex items-center justify-center border-b border-gray-200">
<h1 className="text-xl font-black text-purple-600">کانی‌نا | ادمین‌پنل</h1>
</div>
@@ -48,5 +64,6 @@ export default function Sidebar() {
</button>
</div>
</aside>
</>
);
}
+15 -5
View File
@@ -1,10 +1,20 @@
import { Bell, Search, UserCircle } from 'lucide-react';
import { Bell, Search, UserCircle, Menu } from 'lucide-react';
export default function Topbar() {
interface TopbarProps {
toggleMenu: () => void;
}
export default function Topbar({ toggleMenu }: TopbarProps) {
return (
<header className="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-6 sticky top-0 z-10 shadow-sm font-vazir">
<div className="flex-1 flex items-center max-w-xl">
<div className="relative w-full">
<header className="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-4 sm:px-6 sticky top-0 z-10 shadow-sm font-vazir">
<div className="flex-1 flex items-center gap-3 max-w-xl">
<button
onClick={toggleMenu}
className="lg:hidden p-2 text-gray-500 hover:bg-gray-100 rounded-lg transition-colors"
>
<Menu className="w-6 h-6" />
</button>
<div className="relative w-full hidden sm:block">
<div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
<Search className="w-5 h-5 text-gray-400" />
</div>
@@ -0,0 +1,61 @@
import React from 'react';
import { X, AlertTriangle } from 'lucide-react';
interface ConfirmModalProps {
isOpen: boolean;
title: string;
message: string;
onConfirm: () => void;
onCancel: () => void;
confirmText?: string;
cancelText?: string;
isDestructive?: boolean;
}
export default function ConfirmModal({
isOpen,
title,
message,
onConfirm,
onCancel,
confirmText = 'تایید',
cancelText = 'لغو',
isDestructive = true
}: ConfirmModalProps) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="flex items-center justify-between p-4 border-b border-gray-100">
<h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
{isDestructive && <AlertTriangle className="w-5 h-5 text-red-500" />}
{title}
</h3>
<button onClick={onCancel} className="text-gray-400 hover:bg-gray-100 p-1.5 rounded-lg transition-colors">
<X className="w-5 h-5" />
</button>
</div>
<div className="p-6">
<p className="text-gray-600 font-medium leading-relaxed">{message}</p>
</div>
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3">
<button
onClick={onCancel}
className="px-4 py-2 font-bold text-gray-700 bg-white border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
>
{cancelText}
</button>
<button
onClick={onConfirm}
className={`px-4 py-2 font-bold text-white rounded-xl transition-colors ${
isDestructive ? 'bg-red-600 hover:bg-red-700 shadow-md shadow-red-200' : 'bg-purple-600 hover:bg-purple-700 shadow-md shadow-purple-200'
}`}
>
{confirmText}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,7 @@
import React from 'react';
export default function Skeleton({ className = '' }: { className?: string }) {
return (
<div className={`animate-pulse bg-gray-200 rounded-md ${className}`}></div>
);
}
@@ -0,0 +1,17 @@
import React from 'react';
export default function Spinner({ size = 'md', className = '' }: { size?: 'sm' | 'md' | 'lg', className?: string }) {
const sizeClasses = {
sm: 'w-4 h-4',
md: 'w-6 h-6',
lg: 'w-8 h-8'
};
return (
<div className={`inline-block animate-spin rounded-full border-2 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite] ${sizeClasses[size]} ${className}`} role="status">
<span className="!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]">
درحال بارگذاری...
</span>
</div>
);
}
+1 -4
View File
@@ -1,10 +1,7 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
<App />
)
+94 -6
View File
@@ -1,11 +1,52 @@
import { useState, useEffect } from 'react';
import { DollarSign, ShoppingCart, Users, Activity } from 'lucide-react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import api from '../services/api';
export default function Dashboard() {
const [data, setData] = useState({
revenue: 0,
newOrders: 0,
users: 0,
todayVisits: 0
});
useEffect(() => {
const fetchStats = async () => {
try {
const response = await api.get('/admin/dashboard/stats');
if (response.data?.success) {
setData(response.data.data);
}
} catch (err) {
console.error('Failed to fetch stats', err);
}
};
fetchStats();
}, []);
const chartData = [
{ name: 'شنبه', بازدید: 400, فروش: 2400 },
{ name: 'یکشنبه', بازدید: 300, فروش: 1398 },
{ name: 'دوشنبه', بازدید: 200, فروش: 9800 },
{ name: 'سه‌شنبه', بازدید: 278, فروش: 3908 },
{ name: 'چهارشنبه', بازدید: 189, فروش: 4800 },
{ name: 'پنجشنبه', بازدید: 239, فروش: 3800 },
{ name: 'جمعه', بازدید: 349, فروش: 4300 },
];
const pieData = [
{ name: 'سگ', value: 400 },
{ name: 'گربه', value: 300 },
{ name: 'پرنده', value: 300 },
];
const COLORS = ['#0088FE', '#00C49F', '#FFBB28'];
const stats = [
{ title: 'درآمد کل', value: '۴۵,۰۰۰,۰۰۰ تومان', icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100' },
{ title: 'سفارشات جدید', value: '۱۲', icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100' },
{ title: 'کاربران فعال', value: '۱,۰۲۴', icon: Users, color: 'text-purple-600', bg: 'bg-purple-100' },
{ title: 'بازدید امروز', value: '۳۴۲', icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100' },
{ title: 'درآمد کل', value: `${data.revenue.toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100' },
{ title: 'سفارشات جدید', value: data.newOrders.toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100' },
{ title: 'کاربران فعال', value: data.users.toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100' },
{ title: 'بازدید امروز', value: data.todayVisits.toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100' },
];
return (
@@ -32,8 +73,55 @@ export default function Dashboard() {
})}
</div>
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 min-h-[400px] flex items-center justify-center">
<p className="text-gray-400 font-bold">بخش نمودارها (در فاز بعدی اضافه می‌شود)</p>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 col-span-1 lg:col-span-2">
<h3 className="text-lg font-bold text-gray-900 mb-6">روند بازدید و فروش (۷ روز گذشته)</h3>
<div className="h-80 w-full" dir="ltr">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="name" axisLine={false} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<Tooltip />
<Line type="monotone" dataKey="فروش" stroke="#8b5cf6" strokeWidth={3} dot={{ r: 4 }} activeDot={{ r: 8 }} />
<Line type="monotone" dataKey="بازدید" stroke="#10b981" strokeWidth={3} dot={{ r: 4 }} />
</LineChart>
</ResponsiveContainer>
</div>
</div>
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 col-span-1">
<h3 className="text-lg font-bold text-gray-900 mb-6">دسته‌بندی محصولات</h3>
<div className="h-80 w-full flex items-center justify-center">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={80}
fill="#8884d8"
paddingAngle={5}
dataKey="value"
>
{pieData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
</div>
<div className="flex justify-center gap-4 mt-4">
{pieData.map((entry, index) => (
<div key={entry.name} className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[index % COLORS.length] }}></div>
<span className="text-sm font-medium text-gray-600">{entry.name}</span>
</div>
))}
</div>
</div>
</div>
</div>
);
+12 -5
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Lock, Mail, ChevronLeft } from 'lucide-react';
import api from '../services/api';
export default function Login() {
const [email, setEmail] = useState('');
@@ -8,15 +9,21 @@ export default function Login() {
const [isLoading, setIsLoading] = useState(false);
const navigate = useNavigate();
const handleLogin = (e: React.FormEvent) => {
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
// Simulate API call
setTimeout(() => {
try {
const response = await api.post('/auth/admin-login', { email, password });
if (response.data?.success) {
localStorage.setItem('adminToken', response.data.data.accessToken);
navigate('/');
}
} catch (error) {
alert('ایمیل یا رمز عبور اشتباه است');
} finally {
setIsLoading(false);
navigate('/');
}, 1000);
}
};
return (
+90 -42
View File
@@ -1,11 +1,8 @@
import { useState, useEffect } from 'react';
import { ShoppingCart, Eye, Truck, Check, X, Search, Filter } from 'lucide-react';
const orders = [
{ id: 'ORD-10045', customer: 'علی رضایی', amount: '۴,۵۰۰,۰۰۰ تومان', date: '۱۴۰۲/۰۸/۱۵', status: 'pending', items: 3 },
{ id: 'ORD-10044', customer: 'کلینیک دامپزشکی مهر', amount: '۱۲,۸۰۰,۰۰۰ تومان', date: '۱۴۰۲/۰۸/۱۴', status: 'shipped', items: 12 },
{ id: 'ORD-10043', customer: 'سارا احمدی', amount: '۸۵۰,۰۰۰ تومان', date: '۱۴۰۲/۰۸/۱۲', status: 'delivered', items: 1 },
{ id: 'ORD-10042', customer: 'محمد کریمی', amount: '۳,۲۰۰,۰۰۰ تومان', date: '۱۴۰۲/۰۸/۱۱', status: 'cancelled', items: 2 },
];
import api from '../services/api';
import Skeleton from '../components/ui/Skeleton';
import Spinner from '../components/ui/Spinner';
const statusStyles: Record<string, { label: string, color: string }> = {
pending: { label: 'در حال بررسی', color: 'bg-orange-100 text-orange-700' },
@@ -15,6 +12,40 @@ const statusStyles: Record<string, { label: string, color: string }> = {
};
export default function Orders() {
const [orders, setOrders] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [processingId, setProcessingId] = useState<string | null>(null);
const fetchOrders = async () => {
try {
setIsLoading(true);
const response = await api.get('/admin/orders');
if (response.data?.success) {
setOrders(response.data.data);
}
} catch (err) {
console.error('Failed to fetch orders', err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchOrders();
}, []);
const handleUpdateStatus = async (id: string, status: string) => {
try {
setProcessingId(id);
await api.put(`/admin/orders/${id}/status`, { status });
fetchOrders();
} catch (err) {
console.error('Failed to update status', err);
} finally {
setProcessingId(null);
}
};
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
@@ -58,42 +89,59 @@ export default function Orders() {
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{orders.map((order) => (
<tr key={order.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-purple-600" dir="ltr">{order.id}</td>
<td className="py-4 px-6 font-bold text-gray-900">{order.customer}</td>
<td className="py-4 px-6 font-bold text-gray-900">{order.amount}</td>
<td className="py-4 px-6 text-gray-500 text-sm font-medium">{order.date}</td>
<td className="py-4 px-6 text-gray-500 font-bold">{order.items} عدد</td>
<td className="py-4 px-6">
<span className={`px-3 py-1 rounded-full text-xs font-bold ${statusStyles[order.status].color}`}>
{statusStyles[order.status].label}
</span>
</td>
<td className="py-4 px-6">
<div className="flex items-center justify-center gap-2">
<button className="text-gray-600 hover:bg-gray-100 p-2 rounded-lg transition-colors" title="مشاهده فاکتور">
<Eye className="w-4 h-4" />
</button>
{order.status === 'pending' && (
<>
<button className="text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors" title="ثبت به عنوان ارسال شده">
<Truck className="w-4 h-4" />
{isLoading ? (
Array.from({ length: 4 }).map((_, i) => (
<tr key={i}>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-32" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-16" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-8 w-24 mx-auto" /></td>
</tr>
))
) : (
orders.map((order) => {
const isProcessing = processingId === order.id;
return (
<tr key={order.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-purple-600" dir="ltr">{order.id.slice(0,8)}</td>
<td className="py-4 px-6 font-bold text-gray-900">{order.user?.firstName} {order.user?.lastName}</td>
<td className="py-4 px-6 font-bold text-gray-900">{Number(order.totalAmount).toLocaleString()} تومان</td>
<td className="py-4 px-6 text-gray-500 text-sm font-medium">{new Date(order.createdAt).toLocaleDateString('fa-IR')}</td>
<td className="py-4 px-6 text-gray-500 font-bold">{order.orderItems?.length || 0} قلم</td>
<td className="py-4 px-6">
<span className={`px-3 py-1 rounded-full text-xs font-bold ${statusStyles[order.status]?.color || 'bg-gray-100 text-gray-700'}`}>
{statusStyles[order.status]?.label || order.status}
</span>
</td>
<td className="py-4 px-6">
<div className="flex items-center justify-center gap-2">
<button className="text-gray-600 hover:bg-gray-100 p-2 rounded-lg transition-colors" title="مشاهده فاکتور" disabled={isProcessing}>
<Eye className="w-4 h-4" />
</button>
<button className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors" title="لغو سفارش">
<X className="w-4 h-4" />
</button>
</>
)}
{order.status === 'shipped' && (
<button className="text-green-600 hover:bg-green-50 p-2 rounded-lg transition-colors" title="ثبت به عنوان تحویل داده شده">
<Check className="w-4 h-4" />
</button>
)}
</div>
</td>
</tr>
))}
{order.status === 'processing' && (
<>
<button onClick={() => handleUpdateStatus(order.id, 'shipped')} className="text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors" title="ثبت به عنوان ارسال شده" disabled={isProcessing}>
{isProcessing ? <Spinner size="sm" /> : <Truck className="w-4 h-4" />}
</button>
<button onClick={() => handleUpdateStatus(order.id, 'cancelled')} className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors" title="لغو سفارش" disabled={isProcessing}>
{isProcessing ? <Spinner size="sm" /> : <X className="w-4 h-4" />}
</button>
</>
)}
{order.status === 'shipped' && (
<button onClick={() => handleUpdateStatus(order.id, 'delivered')} className="text-green-600 hover:bg-green-50 p-2 rounded-lg transition-colors" title="ثبت به عنوان تحویل داده شده" disabled={isProcessing}>
{isProcessing ? <Spinner size="sm" /> : <Check className="w-4 h-4" />}
</button>
)}
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
+160 -44
View File
@@ -1,13 +1,72 @@
import { Package, Plus, Edit3, Trash2, Search } from 'lucide-react';
const products = [
{ id: 1, nameFa: 'کانینا بیوتین فورت', category: 'پوست و مو', price: '۲,۵۰۰,۰۰۰', stock: 45, status: 'موجود' },
{ id: 2, nameFa: 'کانینا پِت‌ویتال', category: 'مفاصل', price: '۳,۲۰۰,۰۰۰', stock: 12, status: 'موجود' },
{ id: 3, nameFa: 'شیر خشک مخصوص سگ', category: 'رشد توله', price: '۱,۸۰۰,۰۰۰', stock: 0, status: 'ناموجود' },
{ id: 4, nameFa: 'قطره تمیزکننده چشم', category: 'بهداشتی', price: '۹۵۰,۰۰۰', stock: 120, status: 'موجود' },
];
import { useState, useEffect } from 'react';
import { Package, Plus, Edit3, Trash2, Search, Check, X } from 'lucide-react';
import api from '../services/api';
import ConfirmModal from '../components/ui/ConfirmModal';
import Skeleton from '../components/ui/Skeleton';
import Spinner from '../components/ui/Spinner';
export default function Products() {
const [products, setProducts] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
// Confirm Modal state
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [productToDelete, setProductToDelete] = useState<string | null>(null);
// Edit Mode state
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState({ packageSize: 0, priceValue: 0 });
const [isSaving, setIsSaving] = useState(false);
const fetchProducts = async () => {
try {
setIsLoading(true);
const response = await api.get('/admin/products');
if (response.data?.success) {
setProducts(response.data.data);
}
} catch (err) {
console.error('Failed to fetch products', err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchProducts();
}, []);
const openDeleteModal = (id: string) => {
setProductToDelete(id);
setIsDeleteModalOpen(true);
};
const confirmDelete = async () => {
if (productToDelete) {
await api.get(`/admin/products/${productToDelete}/delete`);
setIsDeleteModalOpen(false);
setProductToDelete(null);
fetchProducts();
}
};
const handleEditClick = (product: any) => {
setEditingId(product.id);
setEditForm({ packageSize: Number(product.packageSize), priceValue: Number(product.priceValue) });
};
const handleSaveEdit = async (id: string) => {
try {
setIsSaving(true);
await api.put(`/admin/products/${id}`, editForm);
setEditingId(null);
fetchProducts();
} catch (err) {
console.error('Failed to update product', err);
} finally {
setIsSaving(false);
}
};
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
@@ -49,46 +108,103 @@ export default function Products() {
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{products.map((product) => (
<tr key={product.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-gray-900">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
<Package className="w-5 h-5 text-gray-400" />
</div>
{product.nameFa}
</div>
</td>
<td className="py-4 px-6 text-gray-500">{product.category}</td>
<td className="py-4 px-6 font-bold text-gray-900">{product.price}</td>
<td className="py-4 px-6">
<span className={`font-bold ${product.stock < 10 ? 'text-red-500' : 'text-gray-900'}`}>
{product.stock} عدد
</span>
</td>
<td className="py-4 px-6">
<span className={`px-3 py-1 rounded-full text-xs font-bold ${
product.stock > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
}`}>
{product.status}
</span>
</td>
<td className="py-4 px-6">
<div className="flex items-center justify-center gap-2">
<button className="text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors" title="ویرایش">
<Edit3 className="w-4 h-4" />
</button>
<button className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors" title="حذف">
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))}
{isLoading ? (
Array.from({ length: 4 }).map((_, i) => (
<tr key={i}>
<td className="py-4 px-6"><Skeleton className="h-6 w-32" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-16" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-20" /></td>
<td className="py-4 px-6"><Skeleton className="h-8 w-20 mx-auto" /></td>
</tr>
))
) : (
products.map((product) => {
const isEditing = editingId === product.id;
return (
<tr key={product.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-gray-900">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
<Package className="w-5 h-5 text-gray-400" />
</div>
{product.name}
</div>
</td>
<td className="py-4 px-6 text-gray-500">{product.category}</td>
<td className="py-4 px-6 font-bold text-gray-900">
{isEditing ? (
<input
type="number"
className="border border-purple-300 rounded p-1 w-24"
value={editForm.priceValue}
onChange={(e) => setEditForm({...editForm, priceValue: Number(e.target.value)})}
/>
) : (
product.priceValue?.toLocaleString()
)}
</td>
<td className="py-4 px-6">
{isEditing ? (
<input
type="number"
className="border border-purple-300 rounded p-1 w-16"
value={editForm.packageSize}
onChange={(e) => setEditForm({...editForm, packageSize: Number(e.target.value)})}
/>
) : (
<span className={`font-bold ${product.packageSize < 10 ? 'text-red-500' : 'text-gray-900'}`}>
{product.packageSize} عدد
</span>
)}
</td>
<td className="py-4 px-6">
<span className={`px-3 py-1 rounded-full text-xs font-bold ${
product.packageSize > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
}`}>
{product.packageSize > 0 ? 'موجود' : 'ناموجود'}
</span>
</td>
<td className="py-4 px-6">
<div className="flex items-center justify-center gap-2">
{isEditing ? (
<>
<button onClick={() => handleSaveEdit(product.id)} className="text-green-600 hover:bg-green-50 p-2 rounded-lg transition-colors" title="ذخیره" disabled={isSaving}>
{isSaving ? <Spinner size="sm" /> : <Check className="w-4 h-4" />}
</button>
<button onClick={() => setEditingId(null)} className="text-gray-500 hover:bg-gray-50 p-2 rounded-lg transition-colors" title="لغو" disabled={isSaving}>
<X className="w-4 h-4" />
</button>
</>
) : (
<>
<button onClick={() => handleEditClick(product)} className="text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors" title="ویرایش">
<Edit3 className="w-4 h-4" />
</button>
<button onClick={() => openDeleteModal(product.id)} className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors" title="حذف">
<Trash2 className="w-4 h-4" />
</button>
</>
)}
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
<ConfirmModal
isOpen={isDeleteModalOpen}
title="حذف محصول"
message="آیا از حذف این محصول اطمینان دارید؟ این عمل غیرقابل بازگشت است."
onConfirm={confirmDelete}
onCancel={() => setIsDeleteModalOpen(false)}
/>
</div>
);
}
+119 -49
View File
@@ -1,13 +1,53 @@
import { Users as UsersIcon, CheckCircle, XCircle, Search, Filter } from 'lucide-react';
const users = [
{ id: 1, name: 'علی رضایی', email: 'ali@example.com', role: 'B2C', status: 'active', date: '۱۴۰۲/۰۸/۱۵' },
{ id: 2, name: 'کلینیک دامپزشکی مهر', email: 'mehr@clinic.com', role: 'B2B', status: 'pending', date: '۱۴۰۲/۰۸/۱۴' },
{ id: 3, name: 'سارا احمدی', email: 'sara@example.com', role: 'B2C', status: 'active', date: '۱۴۰۲/۰۸/۱۲' },
{ id: 4, name: 'داروخانه پت‌شاپ', email: 'info@petshop.ir', role: 'B2B', status: 'active', date: '۱۴۰۲/۰۸/۱۰' },
];
import { useState, useEffect } from 'react';
import { Users as UsersIcon, CheckCircle, XCircle, Search, Filter, Edit3, Check, X } from 'lucide-react';
import api from '../services/api';
import Skeleton from '../components/ui/Skeleton';
import Spinner from '../components/ui/Spinner';
export default function Users() {
const [users, setUsers] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
// Edit State
const [editingId, setEditingId] = useState<string | null>(null);
const [editRole, setEditRole] = useState<string>('');
const [isSaving, setIsSaving] = useState(false);
const fetchUsers = async () => {
try {
setIsLoading(true);
const response = await api.get('/admin/users');
if (response.data?.success) {
setUsers(response.data.data);
}
} catch (err) {
console.error('Failed to fetch users', err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
const handleEditClick = (user: any) => {
setEditingId(user.id);
setEditRole(user.role || 'User_PetOwner');
};
const handleSaveEdit = async (id: string) => {
try {
setIsSaving(true);
await api.put(`/admin/users/${id}/role`, { role: editRole });
setEditingId(null);
fetchUsers();
} catch (err) {
console.error('Failed to update user role', err);
} finally {
setIsSaving(false);
}
};
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
@@ -49,47 +89,77 @@ export default function Users() {
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{users.map((user) => (
<tr key={user.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-gray-900">{user.name}</td>
<td className="py-4 px-6 text-gray-500" dir="ltr">{user.email}</td>
<td className="py-4 px-6">
<span className={`px-3 py-1 rounded-full text-xs font-bold ${user.role === 'B2B' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}`}>
{user.role === 'B2B' ? 'همکار (B2B)' : 'مشتری عادی'}
</span>
</td>
<td className="py-4 px-6 text-gray-500 text-sm font-medium">{user.date}</td>
<td className="py-4 px-6">
{user.status === 'active' ? (
<span className="flex items-center gap-1.5 text-green-600 font-bold text-sm">
<CheckCircle className="w-4 h-4" />
تایید شده
</span>
) : (
<span className="flex items-center gap-1.5 text-orange-500 font-bold text-sm">
<div className="w-2 h-2 rounded-full bg-orange-500"></div>
در انتظار تایید
</span>
)}
</td>
<td className="py-4 px-6 text-center">
{user.role === 'B2B' && user.status === 'pending' ? (
<div className="flex justify-center gap-2">
<button className="text-green-600 hover:bg-green-50 p-1.5 rounded-lg transition-colors" title="تایید مدارک">
<CheckCircle className="w-5 h-5" />
</button>
<button className="text-red-600 hover:bg-red-50 p-1.5 rounded-lg transition-colors" title="رد درخواست">
<XCircle className="w-5 h-5" />
</button>
</div>
) : (
<button className="text-purple-600 hover:underline text-sm font-bold">
مشاهده پروفایل
</button>
)}
</td>
</tr>
))}
{isLoading ? (
Array.from({ length: 4 }).map((_, i) => (
<tr key={i}>
<td className="py-4 px-6"><Skeleton className="h-6 w-32" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-40" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-20" /></td>
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
<td className="py-4 px-6"><Skeleton className="h-8 w-20 mx-auto" /></td>
</tr>
))
) : (
users.map((user) => {
const isEditing = editingId === user.id;
return (
<tr key={user.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-gray-900">{user.firstName} {user.lastName}</td>
<td className="py-4 px-6 text-gray-500" dir="ltr">{user.email}</td>
<td className="py-4 px-6">
{isEditing ? (
<select
className="border border-purple-300 rounded p-1"
value={editRole}
onChange={(e) => setEditRole(e.target.value)}
>
<option value="User_PetOwner">مشتری عادی</option>
<option value="User_B2B">همکار (B2B)</option>
<option value="ADMIN">ادمین</option>
</select>
) : (
<span className={`px-3 py-1 rounded-full text-xs font-bold ${user.role?.includes('B2B') ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}`}>
{user.role?.includes('B2B') ? 'همکار (B2B)' : (user.role === 'ADMIN' ? 'مدیر سیستم' : 'مشتری عادی')}
</span>
)}
</td>
<td className="py-4 px-6 text-gray-500 text-sm font-medium">{new Date(user.createdAt).toLocaleDateString('fa-IR')}</td>
<td className="py-4 px-6">
{user.status === 'active' ? (
<span className="flex items-center gap-1.5 text-green-600 font-bold text-sm">
<CheckCircle className="w-4 h-4" />
تایید شده
</span>
) : (
<span className="flex items-center gap-1.5 text-orange-500 font-bold text-sm">
<div className="w-2 h-2 rounded-full bg-orange-500"></div>
در انتظار تایید
</span>
)}
</td>
<td className="py-4 px-6 text-center">
{isEditing ? (
<div className="flex justify-center gap-2">
<button onClick={() => handleSaveEdit(user.id)} className="text-green-600 hover:bg-green-50 p-1.5 rounded-lg transition-colors" disabled={isSaving}>
{isSaving ? <Spinner size="sm" /> : <Check className="w-5 h-5" />}
</button>
<button onClick={() => setEditingId(null)} className="text-gray-500 hover:bg-gray-50 p-1.5 rounded-lg transition-colors" disabled={isSaving}>
<X className="w-5 h-5" />
</button>
</div>
) : (
<div className="flex justify-center gap-2">
<button onClick={() => handleEditClick(user)} className="text-blue-600 hover:bg-blue-50 p-1.5 rounded-lg transition-colors" title="ویرایش نقش">
<Edit3 className="w-5 h-5" />
</button>
</div>
)}
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
+29
View File
@@ -0,0 +1,29 @@
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:4001/api', // Backend NestJS API URL
headers: {
'Content-Type': 'application/json',
},
});
api.interceptors.request.use((config) => {
const token = localStorage.getItem('adminToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('adminToken');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default api;