feat(admin): implement live audit history and department tasks management system
Deploy Canina / deploy (push) Failing after 2m14s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 8s

This commit is contained in:
devops committed 2026-10-14 13:42:26 +00:00
1 parent 5590281bd4
commit d13ce5cbc2
10 files changed
+1272 -66

No files matched your search

+45 -54
View File
@@ -1,44 +1,46 @@
import {
Activity,
Activity,
CheckSquare,
BookOpen,
Building2,
ChevronDown,
CreditCard,
DollarSign,
FileText,
FlaskConical,
FolderTree,
Globe,
Heart,
HelpCircle,
Image,
Key,
Languages,
Layers,
LayoutDashboard,
Menu,
MessageSquare,
MessageSquareQuote,
Package,
PhoneCall,
Receipt,
RotateCcw,
Settings,
ShieldCheck,
ShoppingCart,
Sliders,
Sparkles,
Star,
Tag,
TrendingUp,
Truck,
UserCheck,
Users,
Video,
BookOpen,
Building2,
ChevronDown,
CreditCard,
DollarSign,
FileText,
FlaskConical,
FolderTree,
Globe,
Heart,
HelpCircle,
Image,
Key,
Languages,
Layers,
LayoutDashboard,
Menu,
MessageSquare,
MessageSquareQuote,
Package,
PhoneCall,
Receipt,
RotateCcw,
Settings,
ShieldCheck,
ShoppingCart,
Sliders,
Sparkles,
Star,
Tag,
TrendingUp,
Truck,
UserCheck,
Users,
Video,
History,
Briefcase
} from 'lucide-react';
import { useEffect,useRef,useState } from 'react';
import { Link,useLocation } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import api from '../services/api';
interface SubMenuItem {
@@ -66,7 +68,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
const [newOrdersCount, setNewOrdersCount] = useState(0);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Auto-close sidebar on mobile navigation and manage body overflow
useEffect(() => {
setIsOpen(false);
}, [location.pathname, setIsOpen]);
@@ -112,20 +113,20 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
},
{
id: 'governance',
title: 'حاکمیت و تاییدات مدیریت',
title: 'حاکمیت، تاییدات و وظایف',
icon: CheckSquare,
items: [
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
{ icon: Briefcase, label: 'وظایف دپارتمان‌ها و ایجنت‌ها', path: '/tasks' },
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
],
},
{
id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت',
icon: Activity,
CheckSquare,
items: [
{ icon: Activity,
CheckSquare, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' },
{ icon: Activity, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' },
{ icon: RotateCcw, label: 'پرتال مالی و استرداد زیبال', path: '/zibal-portal' },
],
},
@@ -208,7 +209,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
},
];
// Store only the active group ID so only one group stays expanded at a time
const [activeGroupId, setActiveGroupId] = useState<string | null>(() => {
for (const g of menuGroups) {
const hasActive = g.items.some(
@@ -221,7 +221,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
return 'main';
});
// Keep active group synchronized with URL navigation
useEffect(() => {
for (const g of menuGroups) {
const hasActive = g.items.some(
@@ -242,7 +241,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
return (
<>
{/* Mobile Backdrop */}
{isOpen && (
<div
className="fixed inset-0 bg-black/50 z-40 lg:hidden backdrop-blur-sm transition-opacity"
@@ -257,7 +255,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
isOpen ? 'translate-x-0' : 'translate-x-full lg:translate-x-0'
}`}
>
{/* Header */}
<div className={`h-16 flex items-center ${isCollapsed ? 'justify-center lg:px-2 px-5' : 'justify-between px-5'} border-b border-gray-200 shrink-0 bg-white`}>
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-xl bg-purple-600 flex items-center justify-center text-white font-black text-sm italic shadow-md shrink-0">
@@ -269,12 +266,11 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
</div>
{!isCollapsed && (
<span className="text-[10px] bg-purple-50 text-purple-700 font-bold px-2 py-0.5 rounded-md border border-purple-200 shrink-0">
v2.4
v2.5
</span>
)}
</div>
{/* Menu Navigation - touch friendly & full scrolling */}
<nav className="flex-1 overflow-y-auto overscroll-contain py-3 px-2 space-y-2 pb-16 lg:pb-6 custom-scrollbar">
{menuGroups.map((group) => {
const GroupIcon = group.icon;
@@ -286,7 +282,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
);
if (isCollapsed) {
// In collapsed mode, render compact group buttons with first active item link or dropdown
const firstItem = group.items[0];
return (
<div key={group.id} className="relative group/collapsed flex flex-col items-center">
@@ -303,7 +298,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
<GroupIcon className="w-5 h-5 shrink-0" />
</Link>
{/* Flyout Submenu on Hover in Collapsed Mode */}
<div className="hidden lg:group-hover/collapsed:block absolute right-full top-0 mr-2 w-56 bg-white rounded-2xl shadow-xl border border-gray-100 p-2 z-50">
<div className="text-[11px] font-black text-purple-700 px-3 py-1.5 border-b border-gray-100 mb-1">
{group.title}
@@ -344,7 +338,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
return (
<div key={group.id} className="rounded-2xl overflow-hidden bg-gray-50/50 border border-gray-100 transition-colors">
{/* Group Accordion Header */}
<button
type="button"
onClick={() => toggleGroup(group.id)}
@@ -363,7 +356,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
/>
</button>
{/* Submenu Items */}
{isExpanded && (
<div className="p-1 space-y-0.5 bg-white border-t border-gray-100 animate-in slide-in-from-top-1 duration-150">
{group.items.map((item) => {
@@ -412,4 +404,3 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
</>
);
}
@@ -0,0 +1,323 @@
import React, { useState, useEffect } from 'react';
import {
History,
Search,
Filter,
RefreshCw,
Clock,
User,
Database,
ArrowRight,
Shield,
Layers,
ChevronDown,
Calendar,
AlertCircle,
Eye,
CheckCircle2
} from 'lucide-react';
import api from '../services/api';
interface AuditLogItem {
id: string;
entity: string;
entityId: string;
action: 'CREATE' | 'UPDATE' | 'DELETE' | 'EXECUTE' | 'BULK_UPDATE';
department: string;
actor: string;
summary: string;
oldValues?: any;
newValues?: any;
metadata?: any;
createdAt: string;
}
export default function AuditHistoryPage() {
const [logs, setLogs] = useState<AuditLogItem[]>([]);
const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [selectedEntity, setSelectedEntity] = useState('ALL');
const [selectedDept, setSelectedDept] = useState('ALL');
const [selectedAction, setSelectedAction] = useState('ALL');
const [activeLogModal, setActiveLogModal] = useState<AuditLogItem | null>(null);
const fetchLogs = async () => {
setLoading(true);
try {
const res = await api.get('/admin/audit-logs?limit=100');
if (res.data?.success) {
setLogs(res.data.data);
}
} catch (err) {
console.error('Error fetching audit logs:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchLogs();
}, []);
const filteredLogs = logs.filter((log) => {
const matchesSearch =
!searchTerm ||
log.summary.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.actor.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.entity.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.entityId.toLowerCase().includes(searchTerm.toLowerCase());
const matchesEntity = selectedEntity === 'ALL' || log.entity === selectedEntity;
const matchesDept = selectedDept === 'ALL' || log.department === selectedDept;
const matchesAction = selectedAction === 'ALL' || log.action === selectedAction;
return matchesSearch && matchesEntity && matchesDept && matchesAction;
});
const getActionBadge = (action: string) => {
switch (action) {
case 'CREATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">افزودن (Create)</span>;
case 'UPDATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200">ویرایش (Update)</span>;
case 'DELETE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">حذف (Delete)</span>;
case 'EXECUTE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-purple-100 text-purple-800 border border-purple-200">اجرا (Execute)</span>;
case 'BULK_UPDATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">دسته‌جمعی (Bulk)</span>;
default:
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-800">{action}</span>;
}
};
const getDeptBadge = (dept: string) => {
const map: Record<string, string> = {
COMMERCE: 'بازرگانی و مالی',
PRODUCT: 'محصولات',
CONTENT: 'محتوا و وبلاگ',
SEO: 'سئو و مارکتینگ',
DEV: 'فنی و زیرساخت',
ORDER: 'سفارشات',
APPROVAL: 'تاییدات مدیریت',
};
return (
<span className="text-[11px] font-bold text-gray-600 bg-gray-100 px-2 py-0.5 rounded-md border border-gray-200">
{map[dept] || dept}
</span>
);
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-3 mb-1">
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
<History className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900">تاریخچه تغییرات زنده دیتابیس (Audit Logs)</h1>
<p className="text-xs text-gray-500 font-medium">ردیابی تمامی عملیات‌های اصلاح قیمت، استوک، پست‌ها و کاتالوگ</p>
</div>
</div>
</div>
<button
onClick={fetchLogs}
disabled={loading}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی لحظه‌ای</span>
</button>
</div>
{/* Filter and Search Bar */}
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
<div className="relative">
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
<input
type="text"
placeholder="جستجو در خلاصه تغییرات، شناسه، اپراتور..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
/>
</div>
<div>
<select
value={selectedEntity}
onChange={(e) => setSelectedEntity(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه موجودیت‌ها (Entities)</option>
<option value="product">محصولات (Product)</option>
<option value="blog">وبلاگ و مقالات (Blog)</option>
<option value="category">دسته‌بندی‌ها (Category)</option>
<option value="order">سفارشات (Order)</option>
<option value="approval">تاییدیه مدیریت (Approval)</option>
<option value="task">تسک‌ها (Task)</option>
</select>
</div>
<div>
<select
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه دپارتمان‌ها</option>
<option value="COMMERCE">بازرگانی و مالی</option>
<option value="PRODUCT">کاتالوگ و انبار</option>
<option value="CONTENT">محتوا و وبلاگ</option>
<option value="SEO">سئو و مارکتینگ</option>
<option value="DEV">فنی و زیرساخت</option>
<option value="APPROVAL">تاییدات هیئت مدیره</option>
</select>
</div>
<div>
<select
value={selectedAction}
onChange={(e) => setSelectedAction(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه نوع عملیات</option>
<option value="CREATE">افزودن (Create)</option>
<option value="UPDATE">ویرایش (Update)</option>
<option value="DELETE">حذف (Delete)</option>
<option value="EXECUTE">اجرای تغییر (Execute)</option>
<option value="BULK_UPDATE">به‌روزرسانی انبوه (Bulk)</option>
</select>
</div>
</div>
</div>
{/* Audit Logs Table */}
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
{loading ? (
<div className="p-12 text-center text-gray-500 font-bold text-sm">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
در حال بارگذاری لاگ‌های تغییرات دیتابیس...
</div>
) : filteredLogs.length === 0 ? (
<div className="p-12 text-center text-gray-400 font-bold text-sm">
هیچ رکورد تغییری با فیلترهای انتخابی یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
<tr>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">موجودیت / شناسه</th>
<th className="py-3 px-4">نوع اقدام</th>
<th className="py-3 px-4">دپارتمان</th>
<th className="py-3 px-4">اقدام‌کننده</th>
<th className="py-3 px-4">شرح تغییرات</th>
<th className="py-3 px-4 text-center">جزییات فنی</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
{filteredLogs.map((log) => (
<tr key={log.id} className="hover:bg-purple-50/20 transition-colors">
<td className="py-3.5 px-4 whitespace-nowrap text-gray-500">
<div className="flex items-center gap-1.5 font-sans font-bold text-[11px]">
<Clock className="w-3.5 h-3.5 text-gray-400" />
<span>{new Date(log.createdAt).toLocaleString('fa-IR')}</span>
</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<div className="font-bold text-gray-900">{log.entity}</div>
<div className="text-[10px] font-mono text-gray-400 truncate max-w-[120px]">{log.entityId}</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getActionBadge(log.action)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getDeptBadge(log.department)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap font-bold text-purple-900">
<div className="flex items-center gap-1">
<User className="w-3.5 h-3.5 text-purple-600" />
<span>{log.actor}</span>
</div>
</td>
<td className="py-3.5 px-4">
<div className="font-bold text-gray-800 line-clamp-2 max-w-md">{log.summary}</div>
</td>
<td className="py-3.5 px-4 text-center whitespace-nowrap">
<button
onClick={() => setActiveLogModal(log)}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-gray-100 hover:bg-purple-100 hover:text-purple-700 text-gray-600 font-bold text-[11px] transition-colors cursor-pointer"
>
<Eye className="w-3.5 h-3.5" />
<span>مشاهده Diff</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Modal View Diff */}
{activeLogModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
<div className="bg-white rounded-2xl max-w-2xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[85vh] overflow-y-auto">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<div className="flex items-center gap-2">
<Database className="w-5 h-5 text-purple-600" />
<h3 className="font-black text-sm text-gray-900">جزییات تغییر داده‌ها ({activeLogModal.entity})</h3>
</div>
<button
onClick={() => setActiveLogModal(null)}
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
>
✕
</button>
</div>
<div className="text-xs space-y-2">
<div className="p-3 bg-gray-50 rounded-xl">
<span className="font-bold text-gray-500">خلاصه عملیات: </span>
<span className="font-black text-gray-800">{activeLogModal.summary}</span>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<h4 className="font-bold text-rose-700 mb-1">مقادیر قبلی (Old Values):</h4>
<pre className="bg-rose-50 text-rose-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
{JSON.stringify(activeLogModal.oldValues || { info: 'مقداری ثبت نشده بود' }, null, 2)}
</pre>
</div>
<div>
<h4 className="font-bold text-emerald-700 mb-1">مقادیر جدید (New Values):</h4>
<pre className="bg-emerald-50 text-emerald-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
{JSON.stringify(activeLogModal.newValues || { info: 'تغییری ثبت نشده' }, null, 2)}
</pre>
</div>
</div>
</div>
<div className="pt-2 text-left">
<button
onClick={() => setActiveLogModal(null)}
className="px-4 py-2 bg-purple-600 text-white rounded-xl text-xs font-bold hover:bg-purple-700 transition-colors"
>
بستن
</button>
</div>
</div>
</div>
)}
</div>
);
}
+145 -6
View File
@@ -1,4 +1,4 @@
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft } from "lucide-react";
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Clock, Database } from "lucide-react";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
@@ -17,8 +17,25 @@ interface DashboardData {
categoriesDistribution?: CategoryDist[];
}
interface AuditLogSummary {
id: string;
entity: string;
action: string;
department: string;
actor: string;
summary: string;
createdAt: string;
}
export default function Dashboard() {
const [pendingApprovalsCount, setPendingApprovalsCount] = useState<number>(0);
const [recentLogs, setRecentLogs] = useState<AuditLogSummary[]>([]);
const [taskStats, setTaskStats] = useState<{ total: number; done: number; inProgress: number }>({
total: 0,
done: 0,
inProgress: 0,
});
const [data, setData] = useState<DashboardData>({
revenue: 0,
newOrders: 0,
@@ -50,6 +67,36 @@ export default function Dashboard() {
}
};
fetchStats();
// Fetch recent audit logs for live widget
const fetchRecentLogs = async () => {
try {
const res = await api.get('/admin/audit-logs?limit=5');
if (res.data?.success) {
setRecentLogs(res.data.data);
}
} catch (e) {
console.error('Failed to fetch audit logs widget', e);
}
};
fetchRecentLogs();
// Fetch tasks summary
const fetchTaskStats = async () => {
try {
const res = await api.get('/admin/department-tasks/stats');
if (res.data?.success) {
setTaskStats({
total: res.data.data.total || 0,
done: res.data.data.byStatus?.DONE || 0,
inProgress: res.data.data.byStatus?.IN_PROGRESS || 0,
});
}
} catch (e) {
console.error('Failed to fetch task stats widget', e);
}
};
fetchTaskStats();
}, []);
const chartData = [
@@ -77,10 +124,30 @@ export default function Dashboard() {
];
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-black text-gray-900">داشبورد</h2>
<p className="text-gray-500 font-medium mt-1">خلاصه‌ای از وضعیت فروشگاه کنینا</p>
<div className="space-y-6 font-vazir" dir="rtl">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900">داشبورد فرماندهی کنینا</h2>
<p className="text-gray-500 font-medium mt-1">خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان</p>
</div>
<div className="flex items-center gap-2">
<Link
to="/history"
className="flex items-center gap-1.5 px-3 py-2 bg-white border border-gray-200 hover:border-purple-300 text-gray-700 rounded-xl text-xs font-bold transition-all shadow-sm"
>
<History className="w-4 h-4 text-purple-600" />
<span>تاریخچه تغییرات دیتابیس</span>
</Link>
<Link
to="/tasks"
className="flex items-center gap-1.5 px-3 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all shadow-sm"
>
<Briefcase className="w-4 h-4" />
<span>کارتابل تسک‌ها ({taskStats.total})</span>
</Link>
</div>
</div>
{/* Approval Gate Alert Banner */}
@@ -112,6 +179,7 @@ export default function Dashboard() {
</div>
)}
{/* Quick Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{stats.map((stat, i) => {
const Icon = stat.icon;
@@ -129,6 +197,77 @@ export default function Dashboard() {
})}
</div>
{/* Live History Widget & Department Tasks Widget */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Recent Audit Logs Widget */}
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Database className="w-5 h-5 text-purple-600" />
<h3 className="text-sm font-black text-gray-900">آخرین تغییرات زنده دیتابیس (Audit History)</h3>
</div>
<Link to="/history" className="text-xs font-bold text-purple-600 hover:underline">
مشاهده تمام لاگ‌ها
</Link>
</div>
<div className="space-y-3">
{recentLogs.length === 0 ? (
<div className="text-center py-6 text-gray-400 text-xs font-medium">
رکوردی در تاریخچه ثبت نشده است.
</div>
) : (
recentLogs.map((log) => (
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
<div className="flex items-center gap-2.5 overflow-hidden">
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
<div className="truncate">
<p className="font-bold text-gray-800 truncate">{log.summary}</p>
<span className="text-[10px] text-gray-400">{log.entity} • توسط {log.actor}</span>
</div>
</div>
<span className="text-[10px] text-gray-400 shrink-0 font-mono">
{new Date(log.createdAt).toLocaleTimeString('fa-IR')}
</span>
</div>
))
)}
</div>
</div>
{/* Department Tasks Live Pipeline Widget */}
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Briefcase className="w-5 h-5 text-indigo-600" />
<h3 className="text-sm font-black text-gray-900">پایپ‌لاین وظایف دپارتمان‌ها و ایجنت‌ها</h3>
</div>
<Link to="/tasks" className="text-xs font-bold text-indigo-600 hover:underline">
ورود به تسک منیجر
</Link>
</div>
<div className="grid grid-cols-3 gap-3 mb-4">
<div className="p-3 bg-gray-50 rounded-xl text-center">
<div className="text-lg font-black text-gray-800">{taskStats.total}</div>
<div className="text-[11px] font-bold text-gray-500">کل تسک‌ها</div>
</div>
<div className="p-3 bg-blue-50 rounded-xl text-center">
<div className="text-lg font-black text-blue-700">{taskStats.inProgress}</div>
<div className="text-[11px] font-bold text-blue-600">در حال انجام</div>
</div>
<div className="p-3 bg-emerald-50 rounded-xl text-center">
<div className="text-lg font-black text-emerald-700">{taskStats.done}</div>
<div className="text-[11px] font-bold text-emerald-600">تکمیل‌شده</div>
</div>
</div>
<p className="text-xs text-gray-500 leading-relaxed font-medium">
تمام تسک‌های تاییدشده به صورت خودکار به پایپ‌لاین اجرایی منتقل شده و لاگ تغییرات آنها در جدول دیتابیس و تاریخچه به ثبت می‌رسد.
</p>
</div>
</div>
<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>
@@ -181,4 +320,4 @@ export default function Dashboard() {
</div>
</div>
);
}
}
@@ -0,0 +1,401 @@
import React, { useState, useEffect } from 'react';
import {
CheckSquare,
Search,
Filter,
RefreshCw,
Clock,
User,
Plus,
PlayCircle,
CheckCircle2,
AlertTriangle,
ChevronDown,
ArrowRight,
ExternalLink,
Bot,
Briefcase
} from 'lucide-react';
import api from '../services/api';
import toast from 'react-hot-toast';
interface DepartmentTask {
id: string;
code: string;
department: string;
title: string;
description?: string;
status: 'BACKLOG' | 'IN_PROGRESS' | 'IN_REVIEW' | 'APPROVED' | 'DEPLOYING' | 'DONE';
priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
assignee: string;
acceptanceCriteria?: string;
executionLogs?: Array<{ timestamp: string; status: string; note: string }>;
deliverableUrl?: string;
startedAt?: string;
completedAt?: string;
createdAt: string;
}
export default function TasksManagementPage() {
const [tasks, setTasks] = useState<DepartmentTask[]>([]);
const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [selectedDept, setSelectedDept] = useState('ALL');
const [selectedStatus, setSelectedStatus] = useState('ALL');
const [selectedPriority, setSelectedPriority] = useState('ALL');
const [activeTaskModal, setActiveTaskModal] = useState<DepartmentTask | null>(null);
const [logNote, setLogNote] = useState('');
const [updating, setUpdating] = useState(false);
const fetchTasks = async () => {
setLoading(true);
try {
const res = await api.get('/admin/department-tasks?limit=100');
if (res.data?.success) {
setTasks(res.data.data);
}
} catch (err) {
console.error('Error fetching tasks:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchTasks();
}, []);
const handleStatusChange = async (taskId: string, newStatus: string) => {
setUpdating(true);
try {
const res = await api.put(`/admin/department-tasks/${taskId}/status`, {
status: newStatus,
logNote: logNote || `تغییر وضعیت به ${newStatus}`,
});
if (res.data?.success) {
toast.success(`وضعیت تسک به ${newStatus} به‌روزرسانی شد`);
setLogNote('');
setActiveTaskModal(null);
fetchTasks();
}
} catch (err) {
toast.error('خطا در به‌روزرسانی وضعیت تسک');
} finally {
setUpdating(false);
}
};
const filteredTasks = tasks.filter((t) => {
const matchesSearch =
!searchTerm ||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
t.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
(t.description && t.description.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesDept = selectedDept === 'ALL' || t.department === selectedDept;
const matchesStatus = selectedStatus === 'ALL' || t.status === selectedStatus;
const matchesPriority = selectedPriority === 'ALL' || t.priority === selectedPriority;
return matchesSearch && matchesDept && matchesStatus && matchesPriority;
});
const getStatusBadge = (status: string) => {
switch (status) {
case 'BACKLOG':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-700 border border-gray-200">بک‌لاگ (Backlog)</span>;
case 'IN_PROGRESS':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200 animate-pulse">در حال انجام (In Progress)</span>;
case 'IN_REVIEW':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">در انتظار بررسی (Review)</span>;
case 'APPROVED':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-indigo-100 text-indigo-800 border border-indigo-200">تایید شده (Approved)</span>;
case 'DEPLOYING':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-purple-100 text-purple-800 border border-purple-200">درحال استقرار (Deploying)</span>;
case 'DONE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">تکمیل شده (Done)</span>;
default:
return <span>{status}</span>;
}
};
const getPriorityBadge = (priority: string) => {
switch (priority) {
case 'CRITICAL':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-600 text-white rounded">فوری / بحرانی</span>;
case 'HIGH':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-100 text-rose-700 rounded border border-rose-200">بالا</span>;
case 'MEDIUM':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-amber-100 text-amber-700 rounded border border-amber-200">متوسط</span>;
default:
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-gray-100 text-gray-600 rounded">عادی</span>;
}
};
const getDeptName = (dept: string) => {
const map: Record<string, string> = {
DEV: 'مهندسی و توسعه',
COMMERCE: 'بازرگانی و مالی',
PRODUCT: 'کاتالوگ و انبار',
CONTENT: 'تولید محتوا و سئو',
SEO: 'رشد و مارکتینگ',
CRM: 'ارتباط با مشتریان',
PMO: 'مدیریت و استراتژی',
};
return map[dept] || dept;
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-3 mb-1">
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
<Briefcase className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900">مدیریت تسک‌های دپارتمان‌ها و ایجنت‌ها (Task Manager)</h1>
<p className="text-xs text-gray-500 font-medium">پایش لحظه‌ای فعالیت‌های خودکار، استیت تسک‌ها و تضمین کیفیت تحویل</p>
</div>
</div>
</div>
<button
onClick={fetchTasks}
disabled={loading}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی وظایف</span>
</button>
</div>
{/* Filter and Search Bar */}
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
<div className="relative">
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
<input
type="text"
placeholder="جستجو بر اساس عنوان تسک، کد..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
/>
</div>
<div>
<select
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه دپارتمان‌ها</option>
<option value="DEV">مهندسی و توسعه (DEV)</option>
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</option>
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
<option value="SEO">سئو و مارکت‌پلیس (SEO)</option>
<option value="PMO">مدیریت محصول و تضمین کیفیت (PMO)</option>
</select>
</div>
<div>
<select
value={selectedStatus}
onChange={(e) => setSelectedStatus(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه وضعیت‌ها</option>
<option value="BACKLOG">بک‌لاگ (Backlog)</option>
<option value="IN_PROGRESS">در حال انجام (In Progress)</option>
<option value="IN_REVIEW">در انتظار بررسی (Review)</option>
<option value="APPROVED">تایید شده (Approved)</option>
<option value="DEPLOYING">در حال دپلوی (Deploying)</option>
<option value="DONE">تکمیل شده (Done)</option>
</select>
</div>
<div>
<select
value={selectedPriority}
onChange={(e) => setSelectedPriority(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه اولویت‌ها</option>
<option value="CRITICAL">بحرانی / فوری</option>
<option value="HIGH">بالا</option>
<option value="MEDIUM">متوسط</option>
<option value="LOW">عادی</option>
</select>
</div>
</div>
</div>
{/* Task List Table */}
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
{loading ? (
<div className="p-12 text-center text-gray-500 font-bold text-sm">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
در حال بارگذاری لیست تسک‌ها...
</div>
) : filteredTasks.length === 0 ? (
<div className="p-12 text-center text-gray-400 font-bold text-sm">
هیچ تسکی با این مشخصات یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
<tr>
<th className="py-3 px-4">کد تسک</th>
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
<th className="py-3 px-4">دپارتمان</th>
<th className="py-3 px-4">اولویت</th>
<th className="py-3 px-4">مسئول اجرا (Agent)</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4 text-center">اقدام و تغییر استیت</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
{filteredTasks.map((task) => (
<tr key={task.id} className="hover:bg-purple-50/20 transition-colors">
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="font-mono font-bold text-gray-500 bg-gray-100 px-2 py-1 rounded">
{task.code}
</span>
</td>
<td className="py-3.5 px-4">
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
{task.description && (
<div className="text-[11px] text-gray-500 line-clamp-1 max-w-sm">{task.description}</div>
)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="text-[11px] font-bold text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-md border border-purple-100">
{getDeptName(task.department)}
</span>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getPriorityBadge(task.priority)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<div className="flex items-center gap-1.5 font-bold text-gray-800">
<Bot className="w-4 h-4 text-indigo-600" />
<span>{task.assignee}</span>
</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getStatusBadge(task.status)}
</td>
<td className="py-3.5 px-4 text-center whitespace-nowrap">
<button
onClick={() => setActiveTaskModal(task)}
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl bg-purple-600 text-white font-bold text-[11px] hover:bg-purple-700 transition-colors shadow-sm cursor-pointer"
>
<span>مدیریت و استیت</span>
<ChevronDown className="w-3.5 h-3.5" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Task Modal for Status Updates */}
{activeTaskModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
<div className="bg-white rounded-2xl max-w-xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<div>
<span className="text-[11px] font-mono text-purple-600 font-bold">{activeTaskModal.code}</span>
<h3 className="font-black text-sm text-gray-900">{activeTaskModal.title}</h3>
</div>
<button
onClick={() => setActiveTaskModal(null)}
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
>
✕
</button>
</div>
<div className="text-xs space-y-3">
<div className="p-3 bg-gray-50 rounded-xl space-y-1">
<div className="font-bold text-gray-500">شرح کامل وظیفه:</div>
<div className="text-gray-800 font-medium leading-relaxed">{activeTaskModal.description || 'توضیحی ثبت نشده است.'}</div>
</div>
{activeTaskModal.acceptanceCriteria && (
<div className="p-3 bg-indigo-50/50 rounded-xl space-y-1 border border-indigo-100">
<div className="font-bold text-indigo-900">معیارهای پذیرش (Acceptance Criteria):</div>
<div className="text-indigo-800 font-medium">{activeTaskModal.acceptanceCriteria}</div>
</div>
)}
{/* Status Update Options */}
<div className="pt-2">
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
<div className="grid grid-cols-3 gap-2">
{['BACKLOG', 'IN_PROGRESS', 'IN_REVIEW', 'APPROVED', 'DEPLOYING', 'DONE'].map((st) => (
<button
key={st}
type="button"
onClick={() => handleStatusChange(activeTaskModal.id, st)}
disabled={updating || activeTaskModal.status === st}
className={`py-2 px-2 text-[11px] font-bold rounded-xl border text-center transition-all ${
activeTaskModal.status === st
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
: 'bg-white hover:bg-gray-50 text-gray-700 border-gray-200'
}`}
>
{st}
</button>
))}
</div>
</div>
<div className="pt-2">
<label className="block text-xs font-bold text-gray-700 mb-1">یادداشت برای تاریخچه لاگ (اختیاری):</label>
<input
type="text"
placeholder="مثال: تست‌ها پاس شد و کاتالوگ به‌روز گردید..."
value={logNote}
onChange={(e) => setLogNote(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500"
/>
</div>
{/* Execution Logs */}
{activeTaskModal.executionLogs && activeTaskModal.executionLogs.length > 0 && (
<div className="pt-2 space-y-1">
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجام‌شده روی این تسک:</div>
<div className="space-y-1 max-h-36 overflow-y-auto">
{activeTaskModal.executionLogs.map((lg, i) => (
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
<span className="font-bold text-gray-800">{lg.note}</span>
<span className="text-gray-400 font-mono">{new Date(lg.timestamp).toLocaleTimeString('fa-IR')}</span>
</div>
))}
</div>
</div>
)}
</div>
<div className="pt-3 border-t border-gray-100 flex justify-end">
<button
type="button"
onClick={() => setActiveTaskModal(null)}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold transition-colors"
>
انصراف
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -1,5 +1,5 @@
import type { ComponentType } from 'react';
import { createBrowserRouter,Navigate } from 'react-router-dom';
import { createBrowserRouter, Navigate } from 'react-router-dom';
import Layout from '../components/Layout';
import ProtectedRoute from '../components/ProtectedRoute';
import { RouteErrorBoundary } from '../components/RouteErrorBoundary';
@@ -47,8 +47,8 @@ const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
export interface AdminRouteConfig {
path: string;
@@ -111,10 +111,10 @@ export const router = createBrowserRouter([
{ path: 'menu/*', element: <MenuManager /> },
{ path: 'monitoring/*', element: <MonitoringPage /> },
{ path: 'approvals/*', element: <ApprovalsPage /> },
{ path: 'history/*', element: <AuditHistoryPage /> },
{ path: 'tasks/*', element: <TasksManagementPage /> },
],
},
],
},
{