Files
canina/frontend/admin-panel/src/pages/TasksManagementPage.tsx
T
devops ccbc495900
Deploy Canina / deploy (push) Successful in 39s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 8s
fix(admin): resolve white screen in task management modal and add pagination
2026-10-14 17:03:15 +00:00

508 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useEffect } from 'react';
import {
Search,
RefreshCw,
Bot,
Briefcase,
ChevronDown,
ChevronLeft,
ChevronRight,
Play,
CheckCircle,
Clock,
Filter
} 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: string;
priority: string;
assignee: string;
acceptanceCriteria?: any;
executionLogs?: any;
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);
// Pagination states
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const fetchTasks = async () => {
setLoading(true);
try {
const res = await api.get('/admin/department-tasks?limit=200');
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;
});
// Calculate pagination
const totalPages = Math.ceil(filteredTasks.length / itemsPerPage) || 1;
const paginatedTasks = filteredTasks.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
const getStatusBadge = (status: string) => {
switch (status) {
case 'TODO':
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">
۱. صف اقدام (TODO)
</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 'TEST':
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">
۳. تست استیج و QA (TEST)
</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;
};
const renderAcceptanceCriteria = (criteria: any) => {
if (!criteria) return null;
if (typeof criteria === 'string') return criteria;
if (typeof criteria === 'object') {
if (criteria.rule) return criteria.rule;
try {
return JSON.stringify(criteria, null, 2);
} catch (e) {
return String(criteria);
}
}
return String(criteria);
};
const renderExecutionLogs = (logs: any) => {
if (!logs) return [];
if (Array.isArray(logs)) return logs;
if (typeof logs === 'object') {
return [
{
note: logs.notes || logs.message || JSON.stringify(logs),
timestamp: new Date().toISOString(),
status: logs.status || 'LOG',
},
];
}
return [{ note: String(logs), timestamp: new Date().toISOString(), status: 'LOG' }];
};
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);
setCurrentPage(1);
}}
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);
setCurrentPage(1);
}}
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);
setCurrentPage(1);
}}
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="TODO">۱. صف اقدام (TODO)</option>
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
<option value="TEST">۳. تست و QA (TEST)</option>
<option value="DONE">۴. تکمیل شده (DONE)</option>
</select>
</div>
<div>
<select
value={selectedPriority}
onChange={(e) => {
setSelectedPriority(e.target.value);
setCurrentPage(1);
}}
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>
<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">
{paginatedTasks.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>
{/* Pagination Controls */}
<div className="p-4 border-t border-gray-100 flex items-center justify-between text-xs">
<span className="text-gray-500 font-medium">
نمایش {(currentPage - 1) * itemsPerPage + 1} تا {Math.min(currentPage * itemsPerPage, filteredTasks.length)} از کل {filteredTasks.length} تسک
</span>
<div className="flex items-center gap-2">
<button
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
>
<ChevronRight className="w-4 h-4" />
</button>
<div className="flex items-center gap-1">
{Array.from({ length: totalPages }).map((_, i) => (
<button
key={i}
onClick={() => setCurrentPage(i + 1)}
className={`w-7 h-7 rounded-lg text-xs font-bold transition-colors cursor-pointer ${
currentPage === i + 1
? 'bg-purple-600 text-white shadow-sm'
: 'text-gray-600 hover:bg-gray-100'
}`}
>
{i + 1}
</button>
))}
</div>
<button
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={currentPage === totalPages}
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
</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 whitespace-pre-wrap">
{renderAcceptanceCriteria(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-4 gap-2">
{['TODO', 'IN_PROGRESS', 'TEST', '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 cursor-pointer ${
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 font-medium"
/>
</div>
{/* Execution Logs */}
{activeTaskModal.executionLogs && (
<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">
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
<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 || JSON.stringify(lg)}</span>
<span className="text-gray-400 font-mono">
{lg.timestamp ? 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 cursor-pointer"
>
انصراف
</button>
</div>
</div>
</div>
)}
</div>
);
}