feat(admin): remove governance, orchestration, approvals, tasks, and audit logs modules
Deploy Canina / deploy (push) Successful in 4m14s

This commit is contained in:
parsa aghaei committed 2026-10-26 10:15:06 +03:30
1 parent 99f0c0d626
commit effe30ee58
128 files changed
+5 -14449

No files matched your search

@@ -1,162 +0,0 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import api from "../services/api";
import ApprovalsPage from "./ApprovalsPage";
vi.mock("../services/api", () => {
return {
default: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
},
};
});
vi.mock("react-hot-toast", () => ({
default: {
success: vi.fn(),
error: vi.fn(),
},
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
describe("ApprovalsPage Component", () => {
const mockApprovals = [
{
id: "app-1",
department: "CONTENT",
category: "CAMPAIGN",
title: "کمپین تخصصی مفاصل: برتری بالینی صدف لب‌سبز کنینا نسبت به وت‌اکسپرت",
status: "PENDING",
createdAt: "2026-10-19T10:00:00Z",
payload: {
"1_مسئله_و_شکاف_بازار": "قیمت گزاف قرص مفاصل وت‌اکسپرت لهستان باعث شکست دوره‌های درمانی شده است.",
"2_راه‌حل_و_مزیت_کنینا": "معرفی مکمل بی‌رقیب Velox Gelenkenergie ۱۰۰٪ عصاره صدف لب‌سبز با نصف قیمت رقیب.",
"3_طرح_اقدام_عملیاتی": "تولید لندینگ‌پیج جامع و سئومحور و اتصال مستقیم به ترب.",
"4_دپارتمان‌های_مسئول": "CONTENT, SEO, CLINICAL_RD",
"5_معیار_پذیرش_و_تکمیل": "رندر شدن لندینگ بدون خطای SSR و افزایش ایمپرشن ارگانیک."
}
},
{
id: "app-2",
department: "PRICING",
category: "PRICE_CHANGE",
title: "پیشنهاد اصلاح قیمت و همگام‌سازی با ترب: Canina Flexan 150g",
status: "PENDING",
createdAt: "2026-10-19T11:00:00Z",
payload: {
product_name: "Canina Flexan 150g",
current_price: 34800000,
suggested_price: 36500000,
margin_percent: 20.5,
competitor_min_torob: 37200000,
reason: "افزایش قیمت تامین‌کننده و میانگین قیمت ترب روی ۳۷.۲ میلیون ریال است."
}
},
{
id: "app-3",
department: "MARKETING",
category: "SMS_CAMPAIGN",
title: "کمپین یادآوری تمدید دوره مکمل‌های مفاصل و GAG",
status: "APPROVED",
createdAt: "2026-10-18T09:00:00Z",
executedAt: "2026-10-18T10:00:00Z",
ceoNotes: "تایید شد و پیامک‌ها ارسال شدند.",
payload: {
campaign_name: "Refill GAG 60-Day Reminder",
sms_pattern: "سلام {name} عزیز، دوره مکمل مفاصل کنینا رو به اتمام است.",
target_count: 86,
estimated_cost_irr: 860000,
expected_revenue_irr: 54000000,
expected_conversion_rate: "18%"
}
}
];
beforeEach(() => {
vi.clearAllMocks();
(api.get as any).mockResolvedValue({
data: {
success: true,
data: mockApprovals,
meta: {
total: 3,
pendingCount: 2,
},
},
});
});
it("renders header, KPI cards, and maps strategic 5-part proposal nicely", async () => {
render(<ApprovalsPage />);
expect(await screen.findByText(/کارتابل حاکمیت سازمانی و تاییدات مدیرعامل/i)).toBeInTheDocument();
expect(screen.getByText(/2 پیشنهاد منتظر تصمیم شما/i)).toBeInTheDocument();
// Verify 5-part structured fields are cleanly mapped
expect(screen.getByText(/مسئله و شکاف شناسایی‌شده در بازار:/i)).toBeInTheDocument();
expect(screen.getByText(/قیمت گزاف قرص مفاصل وت‌اکسپرت لهستان/i)).toBeInTheDocument();
expect(screen.getByText(/راه‌حل، محصول و مزیت رقابتی کنینا:/i)).toBeInTheDocument();
expect(screen.getByText(/Velox Gelenkenergie/i)).toBeInTheDocument();
});
it("renders pricing payload with current price, suggested price, and margin", async () => {
render(<ApprovalsPage />);
expect(await screen.findByText(/پیشنهاد اصلاح قیمت و همگام‌سازی با ترب/i)).toBeInTheDocument();
expect(screen.getByText(/محاسبه قیمت‌گذاری و سود ناخالص:/i)).toBeInTheDocument();
expect(screen.getByText(/20.5٪/i)).toBeInTheDocument();
});
it("approves a pending request with CEO directive note", async () => {
(api.put as any).mockResolvedValue({
data: { success: true },
});
render(<ApprovalsPage />);
expect(await screen.findByText(/کمپین تخصصی مفاصل/i)).toBeInTheDocument();
const approveButtons = screen.getAllByRole("button", { name: /تایید و صدور مجوز اجرا/i });
expect(approveButtons.length).toBeGreaterThan(0);
fireEvent.click(approveButtons[0]);
await waitFor(() => {
expect(api.put).toHaveBeenCalledWith(
"/admin/approvals/app-2/decide",
expect.objectContaining({ decision: "APPROVED" })
);
});
});
it("runs simulation test when clicking play button", async () => {
(api.post as any).mockResolvedValue({
data: {
success: true,
testResult: {
status: "SIMULATION_SUCCESS",
executionSafe: true,
},
},
});
render(<ApprovalsPage />);
const runTestButtons = await screen.findAllByRole("button", { name: /اجرای تست و شبیه‌سازی/i });
expect(runTestButtons.length).toBeGreaterThan(0);
fireEvent.click(runTestButtons[0]);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith("/admin/approvals/app-2/test");
});
expect(await screen.findByText(/نتیجه تست سلامت و شبیه‌سازی:/i)).toBeInTheDocument();
});
});
File diff suppressed because it is too large. Load diff
@@ -1,315 +0,0 @@
import { useState, useEffect } from 'react';
import {
History,
Search,
RefreshCw,
Clock,
User,
Database,
Eye,
} 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>
);
}
@@ -1,348 +0,0 @@
import { useEffect, useState } from 'react';
import {
Building2,
ArrowUpRight,
RefreshCw,
ShieldCheck,
Briefcase,
FileText,
Stethoscope,
Search,
Headphones,
Cpu,
Terminal,
Activity,
XCircle,
} from 'lucide-react';
import { Link } from 'react-router-dom';
import api from '../services/api';
interface DepartmentCard {
id: string;
name: string;
role: string;
agentName: string;
avatarColor: string;
icon: any;
status: 'ACTIVE' | 'PROCESSING' | 'STANDBY';
currentFocus: string;
pendingApprovals: number;
completedTasks: number;
recentReasoningSnippet: string;
}
const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'completedTasks' | 'recentReasoningSnippet' | 'currentFocus'>[] = [
{
id: 'CONTENT',
name: 'واحد محتوا و وبلاگ تخصصی',
role: 'تحقیق عمیق، مقالات بالینی، تولید تصویر و سئوی محتوایی',
agentName: 'Canina-Content-Agent',
avatarColor: 'from-blue-600 to-indigo-700',
icon: FileText,
},
{
id: 'CLINICAL_RD',
name: 'واحد تحقیق و توسعه بالینی (R&D)',
role: 'فکت‌چکینگ پزشکی، اعتبارسنجی دوزها و مراجع داروسازی آلمان',
agentName: 'Canina-Medical-Agent',
avatarColor: 'from-emerald-600 to-teal-700',
icon: Stethoscope,
},
{
id: 'SEO',
name: 'واحد سئو و هوش بازار',
role: 'پایش سرچ کنسول، شناسایی کلمات کلیدی، بهینه‌سازی اسکیما و فید ترب',
agentName: 'Canina-SEO-Agent',
avatarColor: 'from-amber-500 to-orange-600',
icon: Search,
},
{
id: 'B2B',
name: 'واحد توسعه سازمانی و B2B',
role: 'پایپ‌لاین کلینیک‌ها، بیمارستان‌های دامپزشکی و بسته‌های نمایندگی',
agentName: 'Canina-B2B-Agent',
avatarColor: 'from-purple-600 to-violet-800',
icon: Building2,
},
{
id: 'DEVOPS',
name: 'واحد مهندسی، زیرساخت و امنیت',
role: 'پایش سلامت کانتینرها، مصرف دیسک، SSL و پایپ‌لاین آزمون‌محور TDD',
agentName: 'Canina-DevOps-Agent',
avatarColor: 'from-rose-600 to-red-700',
icon: Cpu,
},
{
id: 'SUPPORT',
name: 'واحد پشتیبانی و مشاوره هوشمند',
role: 'پاسخ‌گویی به مشتریان، تریاژ پرسش‌های پت و ثبت تیکت‌های پیگیری',
agentName: 'Canina-Support-Agent',
avatarColor: 'from-cyan-600 to-blue-700',
icon: Headphones,
}
];
export default function CompanyOrchestrationHQ() {
const [departments, setDepartments] = useState<DepartmentCard[]>([]);
const [totalPendingApprovals, setTotalPendingApprovals] = useState<number>(0);
const [totalTasksCount, setTotalTasksCount] = useState<number>(0);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [hasError, setHasError] = useState<boolean>(false);
const fetchLiveStatus = async () => {
setIsLoading(true);
setHasError(false);
try {
const [_statsRes, tasksRes, approvalsRes] = await Promise.all([
api.get('/admin/department-tasks/stats'),
api.get('/admin/department-tasks?limit=100'),
api.get('/admin/approvals?limit=100')
]);
const tasks = tasksRes.data?.data || [];
const approvals = approvalsRes.data?.data || [];
// Calculate operational pending approvals (excluding non-authorization items)
const pendingApprovalsList = approvals.filter((a: any) =>
a.status === 'PENDING' && a.category !== 'B2B_SUPPLIER_STRATEGY'
);
setTotalPendingApprovals(pendingApprovalsList.length);
setTotalTasksCount(tasks.length);
const mapped: DepartmentCard[] = BASE_DEPARTMENTS.map(base => {
const deptTasks = tasks.filter((t: any) =>
t.department === base.id || (base.id === 'DEVOPS' && t.department === 'DEV')
);
const inProgress = deptTasks.find((t: any) => t.status === 'IN_PROGRESS');
const latestTask = deptTasks[0];
const completedCount = deptTasks.filter((t: any) => t.status === 'DONE').length;
let status: 'ACTIVE' | 'PROCESSING' | 'STANDBY' = 'STANDBY';
if (inProgress) status = 'ACTIVE';
else if (deptTasks.some((t: any) => t.status === 'TEST' || t.status === 'WAITING_DEPENDENCIES')) {
status = 'PROCESSING';
}
let currentFocus = 'آماده‌باش / بدون وظیفه فعال در حال حاضر';
if (inProgress) currentFocus = inProgress.title;
else if (latestTask) currentFocus = latestTask.title;
let snippet = 'بدون ثبت لاگ اجرایی در وظایف اخیر.';
if (latestTask?.executionLogs?.length) {
const lastLog = latestTask.executionLogs[latestTask.executionLogs.length - 1];
snippet = lastLog?.summary || lastLog?.note || (lastLog?.deliverable?.type ? `تحویل خروجی: ${lastLog.deliverable.type}` : snippet);
}
// Real department-specific pending approvals (strictly from live data, no synthetic telemetry)
const deptPendingCount = pendingApprovalsList.filter((a: any) =>
a.department === base.id || (base.id === 'DEVOPS' && a.department === 'DEV')
).length;
return {
...base,
status,
currentFocus,
pendingApprovals: deptPendingCount,
completedTasks: completedCount,
recentReasoningSnippet: snippet
};
});
setDepartments(mapped);
} catch (err) {
console.error('Error fetching live orchestration telemetry:', err);
setHasError(true);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchLiveStatus();
}, []);
return (
<div className="space-y-6 font-vazir" dir="rtl">
{/* Honest Executive Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
<div>
<div className="flex items-center gap-3">
<div className="p-3 bg-purple-100 text-purple-700 rounded-2xl border border-purple-200">
<Building2 className="w-8 h-8" />
</div>
<div>
<h1 className="text-xl md:text-2xl font-black text-gray-900 flex items-center gap-3">
وضعیت و ارکستراسیون دپارتمان‌ها (Department Governance Status)
{hasError ? (
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-rose-100 text-rose-800 border border-rose-300">
خطا در همگام‌سازی وضعیت
</span>
) : isLoading ? (
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-blue-100 text-blue-800 border border-blue-300">
در حال دریافت داده‌ها...
</span>
) : (
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-emerald-100 text-emerald-800 border border-emerald-300">
داده‌های زنده سیستم
</span>
)}
</h1>
<p className="text-xs text-gray-500 mt-1 font-medium">
پایش وظایف، وضعیت و خروجی عملیاتی دپارتمان‌ها و ایجنت‌ها بر اساس داده‌های واقعی سرویس
</p>
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-2.5">
<Link
to="/manager-actions"
className="flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold transition-all"
>
<Briefcase className="w-4 h-4 text-indigo-600" />
<span>اقدامات مدیریتی و همکاری‌ها</span>
</Link>
<Link
to="/approvals"
className="flex items-center gap-1.5 px-3.5 py-2 bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-300 rounded-xl text-xs font-bold transition-all"
>
<ShieldCheck className="w-4 h-4 text-amber-600" />
<span>مجوزهای عملیاتی ({totalPendingApprovals} مورد)</span>
</Link>
<button
type="button"
onClick={fetchLiveStatus}
disabled={isLoading}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
<span>تازه‌سازی</span>
</button>
</div>
</div>
{/* Honest Error State */}
{hasError ? (
<div className="bg-white p-8 rounded-3xl border border-rose-200 shadow-sm text-center space-y-3">
<XCircle className="w-12 h-12 text-rose-500 mx-auto" />
<h3 className="text-base font-black text-gray-900">داده‌های وضعیت در دسترس نیست</h3>
<p className="text-xs text-gray-500 max-w-md mx-auto">
امکان ارتباط با سرویس ارکستراسیون یا دریافت آمار وظایف دپارتمان‌ها وجود ندارد. به منظور حفظ صداقت عملیاتی، هیچ وضعیت شبیه‌سازی‌شده‌ای رندر نمی‌شود.
</p>
<button
type="button"
onClick={fetchLiveStatus}
className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all"
>
تلاش مجدد جهت اتصال
</button>
</div>
) : isLoading ? (
<div className="py-24 flex flex-col justify-center items-center gap-3">
<RefreshCw className="w-8 h-8 text-purple-600 animate-spin" />
<span className="text-xs font-bold text-gray-500">در حال واکشی وضعیت واقعی دپارتمان‌ها...</span>
</div>
) : (
<>
{/* Honest Metrics Summary */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
<span className="text-[11px] font-bold text-gray-500">کل دپارتمان‌های سازمانی</span>
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{departments.length}</p>
</div>
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
<span className="text-[11px] font-bold text-gray-500">کل وظایف ثبت‌شده</span>
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{totalTasksCount}</p>
</div>
<div className="bg-white p-4 rounded-2xl border border-amber-200 shadow-xs">
<span className="text-[11px] font-bold text-amber-700">مجوزهای عملیاتی معلق</span>
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{totalPendingApprovals}</p>
</div>
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs">
<span className="text-[11px] font-bold text-emerald-700">دپارتمان‌های در حال کار</span>
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">
{departments.filter(d => d.status === 'ACTIVE').length}
</p>
</div>
</div>
{/* Department Cards Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
{departments.map((dept) => (
<div
key={dept.id}
className="bg-white border border-gray-200 rounded-3xl p-5 hover:border-purple-300 hover:shadow-md transition-all flex flex-col justify-between shadow-xs"
>
<div>
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-3">
<div className={`p-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-xs`}>
<dept.icon className="w-5 h-5" />
</div>
<div>
<h3 className="text-sm font-black text-gray-900">{dept.name}</h3>
<p className="text-[11px] text-purple-700 font-bold">{dept.agentName}</p>
</div>
</div>
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
dept.status === 'ACTIVE'
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
: dept.status === 'PROCESSING'
? 'bg-amber-50 text-amber-800 border-amber-200'
: 'bg-gray-100 text-gray-600 border-gray-200'
}`}>
{dept.status === 'ACTIVE' ? 'در حال کار' : dept.status === 'PROCESSING' ? 'در حال تست' : 'آماده‌باش'}
</span>
</div>
<p className="text-xs text-gray-600 mt-3 font-medium leading-relaxed">
{dept.role}
</p>
<div className="mt-4 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
<Activity className="w-3.5 h-3.5 text-purple-600" />
<span>تمرکز فعلی دپارتمان:</span>
</div>
<p className="text-xs text-gray-800 font-medium line-clamp-1">
{dept.currentFocus}
</p>
</div>
<div className="mt-2 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
<Terminal className="w-3.5 h-3.5 text-purple-600" />
<span>آخرین لاگ و استدلال واقعی:</span>
</div>
<p className="text-[11px] text-gray-700 font-mono leading-relaxed line-clamp-2">
{dept.recentReasoningSnippet}
</p>
</div>
</div>
<div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between text-xs">
<div className="space-x-2 space-x-reverse text-gray-600">
<span>وظایف انجام‌شده: <strong className="text-gray-900 font-bold">{dept.completedTasks}</strong></span>
{dept.pendingApprovals > 0 && (
<span className="text-amber-700 font-bold">({dept.pendingApprovals} مجوز معلق)</span>
)}
</div>
<Link
to="/tasks"
className="flex items-center gap-1 text-purple-700 hover:text-purple-800 font-bold text-xs"
>
<span>مشاهده وظایف</span>
<ArrowUpRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
))}
</div>
</>
)}
</div>
);
}
@@ -43,13 +43,7 @@ describe('Dashboard Page Component', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/audit-logs')) {
return Promise.resolve({ data: { success: true, data: [] } } as any);
}
if (url.includes('/admin/approvals')) {
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
}
vi.mocked(api.get).mockImplementation((_url: string) => {
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
});
});
@@ -66,7 +60,7 @@ describe('Dashboard Page Component', () => {
renderDashboard();
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument();
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument();
expect(screen.getByText('خلاصه عملیات و آمار فروشگاه')).toBeInTheDocument();
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
+2 -180
View File
@@ -1,4 +1,4 @@
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Database } from "lucide-react";
import { Activity, DollarSign, ShoppingCart, Users } 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,25 +17,7 @@ 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,
@@ -44,18 +26,6 @@ export default function Dashboard() {
});
useEffect(() => {
const fetchPendingApprovals = async () => {
try {
const res = await api.get('/admin/approvals?limit=1');
if (res.data?.success && res.data?.meta) {
setPendingApprovalsCount(res.data.meta.pendingCount || 0);
}
} catch (e) {
console.error('Failed to fetch approvals count', e);
}
};
fetchPendingApprovals();
const fetchStats = async () => {
try {
const response = await api.get('/admin/dashboard/stats');
@@ -67,36 +37,6 @@ 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(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : []));
}
} 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 = [
@@ -128,57 +68,10 @@ export default function Dashboard() {
<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>
<p className="text-gray-500 font-medium mt-1">خلاصه عملیات و آمار فروشگاه</p>
</div>
</div>
{/* Approval Gate Alert Banner */}
{pendingApprovalsCount > 0 && (
<div className="bg-gradient-to-r from-amber-500/10 via-amber-500/5 to-transparent border border-amber-500/30 rounded-2xl p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-xl bg-amber-500 text-white flex items-center justify-center shadow-lg shadow-amber-500/20 shrink-0">
<ShieldAlert className="w-6 h-6" />
</div>
<div>
<h3 className="font-bold text-gray-900 text-base flex items-center gap-2">
میز کار تاییدات و حاکمیت سازمانی
<span className="bg-amber-100 text-amber-800 text-xs px-2.5 py-0.5 rounded-full font-black">
{pendingApprovalsCount} مورد در انتظار تصمیم شما
</span>
</h3>
<p className="text-xs text-gray-500 mt-1 font-medium">
پیشنهادات کارشناسی دپارتمان‌ها (مالی، تامین، محتوا، بازاریابی و DevOps) معلق به تایید نهایی شما هستند.
</p>
</div>
</div>
<Link
to="/approvals"
className="flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs px-4 py-2.5 rounded-xl transition-all shadow-sm shrink-0"
>
ورود به کارتابل و بررسی
<ArrowLeft className="w-4 h-4" />
</Link>
</div>
)}
{/* Quick Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{stats.map((stat, i) => {
@@ -197,77 +90,6 @@ 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>
) : (
(Array.isArray(recentLogs) ? 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>
@@ -1,15 +0,0 @@
import {render,screen,within} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
it('shows expired queued work in owner decisions as blocked, not ready to execute',async()=>{
const t={id:'t',key:'t',title:'Expired queued research',state:'READY',displayState:'GATE1_RENEWAL_REQUIRED',version:4,operationMode:'PREPARE',budgetLimitCents:20,availableActions:['APPROVE_GATE1'],metadata:{scope:'Same immutable scope',acceptanceCriteria:['Evidence']}};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));
render(<OrchestrationCommandCenter/>);
const queue=screen.getByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(queue).findByRole('button',{name:t.title})).toBeInTheDocument();
expect(within(queue).getByText(/نیازمند تأیید مجدد مالک/)).toBeInTheDocument();
expect(screen.queryByText('آماده اجرا')).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();
});
@@ -1,18 +0,0 @@
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from '../services/api';
import CompanyOrchestrationHQ from './CompanyOrchestrationHQ';
vi.mock('../services/api', () => ({ default: { get: vi.fn() } }));
describe('governance source integrity', () => {
beforeEach(() => { vi.clearAllMocks(); });
it('shows unavailable instead of a synthetic active department when APIs fail', async () => {
vi.mocked(api.get).mockRejectedValue(new Error('offline'));
render(<MemoryRouter><CompanyOrchestrationHQ /></MemoryRouter>);
expect(await screen.findByText(/داده‌های وضعیت در دسترس نیست/)).toBeInTheDocument();
expect(screen.queryByText(/سیستم زنده و فعال/)).not.toBeInTheDocument();
expect(screen.queryByText(/نمای سه‌بعدی و بصری/)).not.toBeInTheDocument();
});
});
@@ -1,150 +0,0 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from '../services/api';
import ManagerActionsPage from './ManagerActionsPage';
vi.mock('../services/api', () => ({
default: {
get: vi.fn(),
put: vi.fn(),
post: vi.fn(),
},
}));
vi.mock('react-hot-toast', () => ({
default: {
success: vi.fn(),
error: vi.fn(),
},
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
const mockItems = [
{
id: 'act-supplier-1',
category: 'B2B_SUPPLIER_STRATEGY',
department: 'B2B',
title: 'توسعه استراتژی تامین‌کننده صدف لب‌سبز آلمان',
status: 'IN_PROGRESS',
createdAt: '2026-10-19T08:00:00Z',
payload: {
'1_مسئله_و_شکاف_بازار': 'کمبود ماده موثره پودر صدف در خطوط تولید داخلی',
'2_راه‌حل_و_مزیت_کنینا': 'عقد تفاهم‌نامه مستقیم با تامین‌کننده لوکزامبورگ/آلمان',
'3_طرح_اقدام_عملیاتی': 'مذاکره بازرگانی جهت دریافت نمونه آزمایشگاهی و بچ آزمایشی',
'4_دپارتمان‌های_مسئول': 'B2B, CLINICAL_RD',
},
// No outcome or evidence yet
outcome: null,
evidence: null,
},
{
id: 'act-supplier-2',
category: 'B2B_SUPPLIER_STRATEGY',
department: 'B2B',
title: 'قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی',
status: 'COMPLETED',
createdAt: '2026-10-18T10:00:00Z',
payload: {
partner_name: 'بیمارستان دامپزشکی مرکزی',
scope: 'توزیع انحصاری مکمل‌های مفاصل و آرامبخش',
},
outcome: 'انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته',
evidence: 'قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی',
},
{
id: 'auth-seo-1',
category: 'SEO',
department: 'SEO',
title: 'تغییر عنوان متاتگ و ریدایرکت‌های مقالات مفاصل',
status: 'PENDING',
createdAt: '2026-10-19T09:00:00Z',
payload: {
target_url: '/blog/joint-supplements-guide',
},
},
];
describe('ManagerActionsPage Component', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({
data: {
success: true,
data: mockItems,
},
});
});
it('renders B2B_SUPPLIER_STRATEGY items and excludes operational SEO authorizations', async () => {
render(
<MemoryRouter>
<ManagerActionsPage />
</MemoryRouter>
);
expect(await screen.findByText('توسعه استراتژی تامین‌کننده صدف لب‌سبز آلمان')).toBeInTheDocument();
expect(screen.getByText('قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی')).toBeInTheDocument();
// SEO item belongs strictly in operational authorization queue, not here!
expect(screen.queryByText('تغییر عنوان متاتگ و ریدایرکت‌های مقالات مفاصل')).not.toBeInTheDocument();
});
it('never displays an approval button; requires explicit outcome and evidence for completion', async () => {
render(
<MemoryRouter>
<ManagerActionsPage />
</MemoryRouter>
);
await screen.findByText('توسعه استراتژی تامین‌کننده صدف لب‌سبز آلمان');
// Rule: Manager actions are NOT operational authorizations. No "approval" button allowed!
expect(screen.queryByRole('button', { name: /تایید و صدور مجوز اجرا/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /تایید درخواست/i })).not.toBeInTheDocument();
// Incomplete manager action shows explicit requirement indicator
expect(screen.getByText(/نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل/i)).toBeInTheDocument();
// Completed action displays its explicit outcome and evidence
expect(screen.getByText(/انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته/i)).toBeInTheDocument();
expect(screen.getByText(/قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی/i)).toBeInTheDocument();
expect(screen.getByText(/تکمیل‌شده و احراز شده با مستندات/i)).toBeInTheDocument();
});
it('allows recording explicit outcome and evidence for an action', async () => {
vi.mocked(api.put).mockResolvedValue({
data: { success: true },
});
render(
<MemoryRouter>
<ManagerActionsPage />
</MemoryRouter>
);
expect(await screen.findByText('توسعه استراتژی تامین‌کننده صدف لب‌سبز آلمان')).toBeInTheDocument();
const outcomeInput = screen.getByPlaceholderText(/نتیجه حاصله از این اقدام مدیریتی.../i);
const evidenceInput = screen.getByPlaceholderText(/مستندات، شماره سند، لینک گزارش یا فایل.../i);
fireEvent.change(outcomeInput, { target: { value: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد' } });
fireEvent.change(evidenceInput, { target: { value: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921' } });
const submitBtn = screen.getByRole('button', { name: /ثبت نتیجه و مستندات اقدام/i });
fireEvent.click(submitBtn);
await waitFor(() => {
expect(api.put).toHaveBeenCalledWith(
'/admin/approvals/act-supplier-1/decide',
expect.objectContaining({
outcome: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد',
evidence: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921',
})
);
});
});
});
@@ -1,477 +0,0 @@
import { useState, useEffect, useMemo } from 'react';
import {
Building2,
Briefcase,
CheckCircle2,
AlertTriangle,
Clock,
RefreshCw,
Search,
FileText,
ShieldCheck,
Send,
AlertCircle,
Layers,
} from 'lucide-react';
import { Link } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../services/api';
interface ManagerActionItem {
id: string;
department: string;
category: string;
title: string;
payload: any;
status: string;
ceoNotes?: string;
outcome?: string | null;
evidence?: string | null;
createdAt: string;
executedAt?: string;
}
export default function ManagerActionsPage() {
const [items, setItems] = useState<ManagerActionItem[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<boolean>(false);
const [searchQuery, setSearchQuery] = useState<string>('');
const [statusFilter, setStatusFilter] = useState<'ALL' | 'VERIFIED' | 'PENDING_EVIDENCE'>('ALL');
// Input states for outcome and evidence editing
const [actionForm, setActionForm] = useState<Record<string, { outcome: string; evidence: string }>>({});
const [submittingId, setSubmittingId] = useState<string | null>(null);
const fetchActions = async () => {
setLoading(true);
setError(false);
try {
const res = await api.get('/admin/approvals?limit=100');
if (res.data?.success && Array.isArray(res.data.data)) {
// Manager actions are strategic categories like B2B_SUPPLIER_STRATEGY or PARTNERSHIP
// Operational authorizations (SEO, PRICING, SMS, etc.) are strictly excluded!
const managerActions = res.data.data.filter((item: any) =>
item.category === 'B2B_SUPPLIER_STRATEGY' ||
item.category === 'PARTNERSHIP' ||
(item.department === 'B2B' && item.category?.includes('STRATEGY'))
);
const initialForms: Record<string, { outcome: string; evidence: string }> = {};
managerActions.forEach((item: ManagerActionItem) => {
initialForms[item.id] = {
outcome: item.outcome || item.payload?.outcome || item.payload?.['نتیجه_اقدام'] || '',
evidence: item.evidence || item.payload?.evidence || item.payload?.['مستندات_و_مدرک'] || '',
};
});
setItems(managerActions);
setActionForm(initialForms);
} else {
setError(true);
}
} catch (err) {
console.error('Failed to fetch manager actions:', err);
setError(true);
toast.error('خطا در دریافت لیست اقدامات مدیریتی');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchActions();
}, []);
const handleSaveEvidence = async (id: string) => {
const form = actionForm[id] || { outcome: '', evidence: '' };
if (!form.outcome.trim() || !form.evidence.trim()) {
toast.error('برای ثبت اقدام، درج هر دو مورد نتیجه و مدرک/مستندات الزامی است.');
return;
}
setSubmittingId(id);
try {
const res = await api.put(`/admin/approvals/${id}/decide`, {
decision: 'APPROVED',
outcome: form.outcome.trim(),
evidence: form.evidence.trim(),
ceoNotes: `اقدام تکمیل شد با نتیجه: ${form.outcome.trim()}`,
});
if (res.data?.success) {
toast.success('نتیجه و مستندات اقدام مدیریتی با موفقیت ثبت شد');
// Update local item with verified outcome and evidence
setItems((prev) =>
prev.map((item) =>
item.id === id
? {
...item,
status: 'COMPLETED',
outcome: form.outcome.trim(),
evidence: form.evidence.trim(),
}
: item
)
);
}
} catch (err) {
console.error('Failed to update manager action evidence:', err);
toast.error('خطا در ثبت نتیجه و مستندات اقدام');
} finally {
setSubmittingId(null);
}
};
const filteredItems = useMemo(() => {
return items.filter((item) => {
const isVerified = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
if (statusFilter === 'VERIFIED' && !isVerified) return false;
if (statusFilter === 'PENDING_EVIDENCE' && isVerified) return false;
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase().trim();
const form = actionForm[item.id] || { outcome: '', evidence: '' };
const matchTitle = item.title?.toLowerCase().includes(q);
const matchDept = item.department?.toLowerCase().includes(q);
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
const matchOutcome = (item.outcome || form.outcome)?.toLowerCase().includes(q);
if (!matchTitle && !matchDept && !matchPayload && !matchOutcome) return false;
}
return true;
});
}, [items, actionForm, statusFilter, searchQuery]);
const verifiedCount = items.filter(
(item) => Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim())
).length;
const pendingEvidenceCount = items.length - verifiedCount;
return (
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6 font-vazir text-gray-900 bg-gray-50 min-h-screen" dir="rtl">
{/* Header */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200/80 shadow-xs">
<div>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-2xl bg-indigo-100 flex items-center justify-center text-indigo-700 shadow-xs">
<Briefcase className="w-6 h-6" />
</div>
<div>
<h1 className="text-xl md:text-2xl font-black text-gray-900 tracking-tight">
اقدامات مدیریتی و همکاری‌ها (Manager Strategic Actions & Partnerships)
</h1>
<p className="text-xs text-gray-500 font-medium mt-1 leading-relaxed">
طرح‌های راهبردی، پروژه‌های B2B و تامین‌کنندگان. این موارد مجوز سیستمی نیستند؛ تکمیل اقدام صرفاً با احراز نتیجه و مستندات معتبر صورت می‌گیرد.
</p>
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-2.5">
<Link
to="/approvals"
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-amber-50 hover:bg-amber-100 text-amber-800 text-xs font-bold transition-all border border-amber-300"
>
<ShieldCheck className="w-4 h-4 text-amber-600" />
<span>رفتن به مجوزهای عملیاتی</span>
</Link>
<Link
to="/tasks"
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-purple-50 hover:bg-purple-100 text-purple-700 text-xs font-bold transition-all border border-purple-200"
>
<Layers className="w-4 h-4 text-purple-600" />
<span>مشاهده وظایف دپارتمان‌ها</span>
</Link>
<button
type="button"
onClick={fetchActions}
disabled={loading}
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">تازه‌سازی</span>
</button>
</div>
</div>
{/* Governance Directive Banner */}
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex items-start gap-3">
<AlertCircle className="w-5 h-5 text-indigo-700 shrink-0 mt-0.5" />
<div className="text-xs text-indigo-950 space-y-1">
<p className="font-bold">قانون تفکیک حاکمیتی اقدامات مدیریتی از مجوزهای عملیاتی:</p>
<p className="leading-relaxed text-indigo-900">
طرح‌های استراتژیک تامین‌کنندگان (B2B_SUPPLIER_STRATEGY) و همکاری‌های تجاری، وظایف انسانی و راهبردی هستند که دکمه تایید فوری ندارند. تکمیل این موارد صرفاً با درج صریح نتیجه واقعی (Outcome) و مستندات قابل اعتبارسنجی (Evidence) محقق می‌شود.
</p>
</div>
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-gray-500">کل اقدامات مدیریتی</p>
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{items.length}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-700 flex items-center justify-center font-bold">
<Building2 className="w-5 h-5" />
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-amber-300 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-amber-700">نیازمند ثبت نتیجه و مدرک</p>
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{pendingEvidenceCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center font-bold">
<Clock className="w-5 h-5" />
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-emerald-700">تکمیل و احراز شده با مستندات</p>
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{verifiedCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
<CheckCircle2 className="w-5 h-5" />
</div>
</div>
</div>
{/* Filters Bar */}
<div className="bg-white p-4 rounded-3xl border border-gray-200/80 shadow-xs flex flex-col md:flex-row gap-3 items-center justify-between">
<div className="relative w-full md:w-96">
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو در عنوان اقدام، تامین‌کننده، دپارتمان..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pr-10 pl-4 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-indigo-500 font-medium text-gray-900"
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<button
type="button"
onClick={() => setStatusFilter('ALL')}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
statusFilter === 'ALL'
? 'bg-indigo-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
همه موارد ({items.length})
</button>
<button
type="button"
onClick={() => setStatusFilter('PENDING_EVIDENCE')}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
statusFilter === 'PENDING_EVIDENCE'
? 'bg-amber-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
نیازمند نتیجه ({pendingEvidenceCount})
</button>
<button
type="button"
onClick={() => setStatusFilter('VERIFIED')}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
statusFilter === 'VERIFIED'
? 'bg-emerald-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
احراز شده ({verifiedCount})
</button>
</div>
</div>
{/* Main List */}
{error ? (
<div className="bg-white p-8 rounded-3xl border border-rose-200 text-center space-y-3">
<AlertTriangle className="w-12 h-12 text-rose-500 mx-auto" />
<h3 className="text-base font-black text-gray-900">دریافت اقدامات ناموفق بود</h3>
<p className="text-xs text-gray-500">امکان برقراری ارتباط با سرور و واکشی اقدامات مدیریتی وجود ندارد.</p>
<button
type="button"
onClick={fetchActions}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all"
>
تلاش مجدد
</button>
</div>
) : loading ? (
<div className="py-24 flex flex-col justify-center items-center gap-3">
<RefreshCw className="w-8 h-8 text-indigo-600 animate-spin" />
<span className="text-xs font-bold text-gray-500">در حال دریافت اقدامات مدیریتی...</span>
</div>
) : filteredItems.length === 0 ? (
<div className="bg-white p-12 text-center rounded-3xl border border-gray-200/80 shadow-xs space-y-2">
<CheckCircle2 className="w-12 h-12 text-indigo-500 mx-auto mb-2" />
<h3 className="text-base font-black text-gray-900">اقدامی در این فهرست یافت نشد</h3>
<p className="text-xs text-gray-500">موردی با شرایط فیلتر انتخاب‌شده مطابقت ندارد.</p>
</div>
) : (
<div className="grid gap-5">
{filteredItems.map((item) => {
const form = actionForm[item.id] || { outcome: item.outcome || '', evidence: item.evidence || '' };
const isCompleted = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
return (
<div
key={item.id}
className={`bg-white rounded-3xl border transition-all overflow-hidden ${
isCompleted ? 'border-emerald-200 shadow-xs' : 'border-amber-300 shadow-md ring-1 ring-amber-300/40'
}`}
>
{/* Header */}
<div className="p-5 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-gray-50/60">
<div className="flex items-center gap-3">
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl text-[11px] font-black border bg-indigo-50 text-indigo-800 border-indigo-200">
<Building2 className="w-3.5 h-3.5 shrink-0" />
<span>{item.category === 'B2B_SUPPLIER_STRATEGY' ? 'طرح استراتژیک تامین‌کننده' : item.category}</span>
</span>
<div>
<h3 className="font-black text-gray-900 text-sm md:text-base leading-snug">
{item.title}
</h3>
<div className="flex items-center gap-2 mt-1 text-[11px] text-gray-500 font-medium">
<span>دپارتمان: <strong className="text-gray-800">{item.department}</strong></span>
<span>•</span>
<span>
ثبت: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.createdAt))}
</span>
</div>
</div>
</div>
<div>
{isCompleted ? (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
<span>تکمیل‌شده و احراز شده با مستندات</span>
</span>
) : (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-amber-50 text-amber-800 border border-amber-300">
<Clock className="w-3.5 h-3.5 text-amber-600" />
<span>نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل</span>
</span>
)}
</div>
</div>
{/* Body */}
<div className="p-5 space-y-4">
{/* Strategic 5-Part Proposal Mapping */}
{item.payload && (
<div className="space-y-2.5">
{item.payload['1_مسئله_و_شکاف_بازار'] && (
<div className="p-3 bg-rose-50/60 border border-rose-200/80 rounded-xl text-xs">
<span className="font-black text-rose-800 block mb-1">مسئله و شکاف بازار:</span>
<span className="text-gray-800">{item.payload['1_مسئله_و_شکاف_بازار']}</span>
</div>
)}
{item.payload['2_راه‌حل_و_مزیت_کنینا'] && (
<div className="p-3 bg-emerald-50/60 border border-emerald-200/80 rounded-xl text-xs">
<span className="font-black text-emerald-800 block mb-1">راه‌حل و مزیت کنینا:</span>
<span className="text-gray-800">{item.payload['2_راه‌حل_و_مزیت_کنینا']}</span>
</div>
)}
{item.payload['3_طرح_اقدام_عملیاتی'] && (
<div className="p-3 bg-blue-50/60 border border-blue-200/80 rounded-xl text-xs">
<span className="font-black text-blue-800 block mb-1">طرح اقدام عملیاتی:</span>
<span className="text-gray-800">{item.payload['3_طرح_اقدام_عملیاتی']}</span>
</div>
)}
</div>
)}
{/* Explicit Outcome & Evidence Section */}
<div className="bg-gray-50/90 rounded-2xl p-4 border border-gray-200 space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-black text-gray-800 flex items-center gap-1.5">
<FileText className="w-4 h-4 text-indigo-600" />
<span>نتیجه و مدرک تحقق اقدام (Outcome & Evidence)</span>
</span>
<span className="text-[11px] text-gray-500 font-medium">
تکمیل صرفاً با مستندات معتبر احراز می‌شود
</span>
</div>
{isCompleted ? (
<div className="space-y-2 text-xs">
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
<span className="text-emerald-800 font-bold block">نتیجه حاصله (Outcome):</span>
<p className="text-gray-800 font-medium">{item.outcome}</p>
</div>
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
<span className="text-emerald-800 font-bold block">مستندات و مدرک تحقق (Evidence):</span>
<p className="text-gray-800 font-medium">{item.evidence}</p>
</div>
</div>
) : (
<div className="space-y-3">
<div className="space-y-1">
<label className="text-[11px] font-bold text-gray-700 block">
نتیجه حاصله از این اقدام مدیریتی (Outcome):
</label>
<textarea
rows={2}
placeholder="نتیجه حاصله از این اقدام مدیریتی..."
value={form.outcome}
onChange={(e) =>
setActionForm((prev) => ({
...prev,
[item.id]: { ...form, outcome: e.target.value },
}))
}
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
/>
</div>
<div className="space-y-1">
<label className="text-[11px] font-bold text-gray-700 block">
مستندات و مدرک تحقق (Evidence):
</label>
<input
type="text"
placeholder="مستندات، شماره سند، لینک گزارش یا فایل..."
value={form.evidence}
onChange={(e) =>
setActionForm((prev) => ({
...prev,
[item.id]: { ...form, evidence: e.target.value },
}))
}
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
/>
</div>
<div className="flex justify-end pt-1">
<button
type="button"
onClick={() => handleSaveEvidence(item.id)}
disabled={submittingId === item.id || !form.outcome.trim() || !form.evidence.trim()}
className="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-black shadow-xs transition-all disabled:opacity-50 cursor-pointer"
>
<Send className="w-3.5 h-3.5" />
<span>{submittingId === item.id ? 'در حال ثبت...' : 'ثبت نتیجه و مستندات اقدام'}</span>
</button>
</div>
</div>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
);
}
@@ -1,198 +0,0 @@
import { render, screen, fireEvent, within, waitFor, act } from '@testing-library/react';
import { beforeEach, describe, it, expect, vi } from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api', () => ({ default: {get:vi.fn(),post:vi.fn(),put:vi.fn()} }));
const task={id:'t1',key:'bounded-1',title:'Bounded SEO audit',department:'SEO',state:'GATE1_PENDING',version:4,operationMode:'PREPARE',budgetLimitCents:500,availableActions:[{id:'g1',label:'Approve bounded work',gate:1,decision:'APPROVED'}],runs:[],metadata:{scope:'Only staging',acceptanceCriteria:['Audit schema']}};
describe('command center', () => {
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => {
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,killSwitch:true,chat:true,runtime:false}}};
if(url.endsWith('/tasks')) return {data:[task]};
if(url.endsWith('/tasks/t1')) return {data:task};
throw new Error('Unavailable: '+url);
}); });
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
expect(within(detail).getByText(/Only staging/)).toBeInTheDocument();
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'عامل‌ها و دپارتمان‌ها'}));
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
expect(vi.mocked(api.get).mock.calls.some(([url])=>url.endsWith('/agents'))).toBe(false);
});
it('labels deliberately omitted scope metadata unavailable, not immutable scope',async()=>{
const {metadata:_metadata,...safeTask}=task;
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[safeTask]:safeTask}));
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText('محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.')).toBeInTheDocument();
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
});
it('approves immediately without date or reason after explicit confirmation',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{...task,state:'READY'}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toHaveValue('');
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await waitFor(()=>expect(api.post).toHaveBeenCalledTimes(1));
const payload=vi.mocked(api.post).mock.calls[0][1] as Record<string,unknown>;
expect(payload.decision).toBe('APPROVED');
expect(payload.expiresAt).toBeUndefined();expect(payload.notBefore).toBeUndefined();
});
it('requires explicit confirmation; retains idempotency across failed retry', async () => {
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده'),{target:{value:new Date(Date.now()+3600000).toISOString().slice(0,16)}});
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'محدوده checked'}});
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
expect(within(dialog).getByLabelText('دلیل')).toBeDisabled();
expect(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toBeDisabled();
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await within(dialog).findByRole('alert');
expect(api.post).toHaveBeenCalledTimes(2);
const first=vi.mocked(api.post).mock.calls[0][1];
expect(first).toEqual(expect.objectContaining({expectedVersion:4,decision:'APPROVED'}));
expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(first);
});
it('keeps legacy Gate2 release decisions disabled without sending a command',async()=>{
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[release]:release}));
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByRole('button',{name:'تأیید در Gate2'})).toBeDisabled();
expect(api.post).not.toHaveBeenCalled();
});
it('requires global impact confirmation for each kill level and reports backend rejection',async()=>{
vi.mocked(api.put).mockRejectedValue(new Error('Forbidden: role'));
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
expect(screen.getAllByRole('option')).toHaveLength(4);
expect(screen.getByRole('button',{name:'اعمال توقف سراسری'})).toBeDisabled();
fireEvent.change(screen.getByLabelText('سطح توقف'),{target:{value:'EMERGENCY_HALT'}});
fireEvent.change(screen.getByLabelText('دلیل توقف'),{target:{value:'Incident'}});
fireEvent.click(screen.getByLabelText('پیامد عملیاتی سراسری را تأیید می‌کنم'));
fireEvent.click(screen.getByRole('button',{name:'اعمال توقف سراسری'}));
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden: role');
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'EMERGENCY_HALT',reason:'Incident'});
});
it('sends advisory chat via typed bridge and renders text, not HTML',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'<script>unsafe</script>'}});
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'گفت‌وگو'}));
fireEvent.change(screen.getByLabelText('شناسه نشست'),{target:{value:'session-1'}});
fireEvent.change(screen.getByLabelText('پیام'),{target:{value:'Explain bounded work'}});
fireEvent.click(screen.getByRole('button',{name:'ارسال پیام مشورتی'}));
expect(await screen.findByText('assistant: <script>unsafe</script>')).toBeInTheDocument();
expect(document.querySelector('script')).toBeNull();
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',expect.objectContaining({sessionId:'session-1',message:'Explain bounded work'}));
});
it('fails closed for creation, kill and chat when overview cannot authorize capabilities',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/tasks'))return {data:[task]};throw new Error('Unavailable');});
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'وظیفه‌ها و تأییدها'}));
expect(screen.queryByText('ایجاد کار محدود')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'گفت‌وگو'}));
expect(screen.queryByRole('button',{name:'ارسال پیام مشورتی'})).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
});
});
it('requires explicit kill capability rather than generic mutations',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
});
it.each([{}, {scope:'STAGE_PREPARE'}, {scope:'Human scope',acceptanceCriteria:[]}])('does not claim incomplete or legacy metadata is scope evidence: %j',async metadata=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[{...task,metadata}]:{...task,metadata}}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText(/محدوده و معیارهای پذیرش در دسترس نیست/)).toBeInTheDocument();
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
});
it('separates human evidence from server workflow scope without inventing a marker',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:task}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText('محدوده و معیارهای پذیرش گزارش‌شده از سرور')).toBeInTheDocument();
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
});
it('shows advertised decisions directly on pending card and labels reservation not measured cost',async()=>{
const ownerTask={...task,budgetLimitCents:20,availableActions:['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[ownerTask]:ownerTask}));
render(<OrchestrationCommandCenter/>);
const card=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(card).findByRole('button',{name:'تأیید کار محدود در Gate1'})).toBeEnabled();
expect(within(card).getByRole('button',{name:'رد کار در Gate1'})).toBeEnabled();
expect(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'})).toBeEnabled();
expect(within(card).getByText('رزرو آزمایشی؛ هزینه واقعی نامشخص')).toBeInTheDocument();
fireEvent.click(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'}));
const dialog=await screen.findByRole('dialog');
expect(within(dialog).getByRole('heading',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled(); expect(api.put).not.toHaveBeenCalled();
});
const cardActions=['APPROVE_GATE1','HOLD_GATE1','REJECT_GATE1'];
const cardLabels=['تأیید کار محدود در Gate1','تعویق تصمیم Gate1','رد کار در Gate1'];
it.each(cardActions)('opens fresh matching %s from the card without a preconfirm mutation',async action=>{
vi.resetAllMocks();
const fresh={...task,version:9,budgetLimitCents:73,availableActions:[action]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[{...task,availableActions:cardActions}]:fresh}));
render(<OrchestrationCommandCenter/>);
const queue=screen.getByRole('region',{name:'منتظر تصمیم شما'});
const label=cardLabels[cardActions.indexOf(action)];
fireEvent.click(await within(queue).findByRole('button',{name:label}));
const dialog=await screen.findByRole('dialog');
expect(within(dialog).getByRole('heading',{name:label})).toBeInTheDocument();
expect(within(dialog).getByText('9')).toBeInTheDocument();
expect(within(dialog).getByText('73')).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks/t1');
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button',{name:'انصراف'}));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
});
it.each(['missing','disabled','wrong-task','error'])('reports fresh card action failure: %s',async failure=>{
vi.resetAllMocks();
vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'now',capabilities:{mutations:true}}};
if(url.endsWith('/tasks'))return {data:[{...task,availableActions:cardActions}]};
if(failure==='error')throw new Error('offline detail');
return {data:{...task,id:failure==='wrong-task'?'other':task.id,availableActions:failure==='missing'?['HOLD_GATE1']:[{id:'APPROVE_GATE1',disabledReason:'policy'}]}};
});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await within(screen.getByRole('region',{name:'منتظر تصمیم شما'})).findByRole('button',{name:cardLabels[0]}));
expect(await screen.findByRole('alert')).toBeInTheDocument();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
});
it('invalidates a delayed card decision on refresh',async()=>{
vi.resetAllMocks();let resolve!:(value:{data:unknown})=>void;
vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'now',capabilities:{mutations:true}}};
if(url.endsWith('/tasks'))return {data:[{...task,availableActions:cardActions}]};
return await new Promise<{data:unknown}>(r=>{resolve=r});
});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await within(screen.getByRole('region',{name:'منتظر تصمیم شما'})).findByRole('button',{name:cardLabels[0]}));
expect(screen.getByRole('status')).toHaveTextContent('در حال');
fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));
await act(async()=>resolve({data:{...task,availableActions:cardActions}}));
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
});
@@ -1,128 +0,0 @@
import { useEffect, useState, useRef } from 'react';
import Button from '../components/ui/Button';
import EditorialRecoveryDialog from '../components/EditorialRecoveryDialog';
import {editorialRecoveryRun} from '../services/orchestration';
import RouterUsagePanel from '../components/RouterUsagePanel';
import RuntimeReadPanel from '../components/RuntimeReadPanel';
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
import { orchestration, killLevels, actionBlockReason, commandFailure } from '../services/orchestration';
import {label,actionLabel,Records} from '../components/OrchestrationPresentation';
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
const sections = ['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها','عامل‌ها و دپارتمان‌ها','مدل‌ها و بودجه‌ها','زمان‌بندی‌ها','ممیزی و انتشارها','توقف اضطراری','مصرف و سهمیه 9router','اطلاعات اجرا و نشست‌ها','گفت‌وگو'] as const;
type Section = typeof sections[number];
const resources:Partial<Record<Section,Resource>> = {'ممیزی و انتشارها':'releases'};
const unavailable:Partial<Record<Section,string>> = {'عامل‌ها و دپارتمان‌ها':'فهرست عامل‌ها به هویت و اتصال مورد اعتماد اجرا نیاز دارد. اطلاعات نمای ثبت‌شده را از بخش اطلاعات اجرا و نشست‌ها ببینید؛ این اطلاعات سلامت زنده نیست.','مدل‌ها و بودجه‌ها':'قرارداد خواندن سیاست مدل در سرور پیاده‌سازی نشده است. سقف بودجه هر وظیفه در فهرست وظیفه‌ها قابل مشاهده است.','زمان‌بندی‌ها':'مسیر مدیریت زمان‌بندی در این نسخه پشتیبانی نمی‌شود؛ زمان‌بندی ساختگی نمایش داده نمی‌شود.'};
const errorText=(e:unknown)=> {const status=(e as {response?:{status?:number}})?.response?.status;return status?`خطای سرور (HTTP ${status})`:e instanceof Error?e.message:'پاسخ سرور در دسترس نیست'};
function Json({value}:{value:unknown}) {return <Records value={value}/>;}
export default function OrchestrationCommandCenter() {
const detailEpoch=useRef(0);
const [recovery,setRecovery]=useState<Task|null>(null);
const [section,setSection]=useState<Section>('نمای کلی');
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false});
const [tasks,setTasks]=useState<Task[]>([]);
const [selected,setSelected]=useState<Task|null>(null);
const [decisionLoading,setDecisionLoading]=useState(false);
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
const [error,setError]=useState(''); const [loading,setLoading]=useState(false);
const [search,setSearch]=useState('');
const [decisionFilter,setDecisionFilter]=useState('ALL');
const [pending,setPending]=useState<{task:Task;action:ServerAction;key:string}|null>(null);
const [expires,setExpires]=useState(''); const [reason,setReason]=useState('');
const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false);
const [attempted,setAttempted]=useState(false); const [busy,setBusy]=useState(false); const [commandError,setCommandError]=useState('');
const [success,setSuccess]=useState('');
const [blocked,setBlocked]=useState(false);
const [now,setNow]=useState(()=>Date.now());
useEffect(()=>{const timer=setInterval(()=>setNow(Date.now()),1000);return ()=>clearInterval(timer)},[]);
const [kill,setKill]=useState<KillLevel>('FREEZE_NEW_WORK');
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
const [messages,setMessages]=useState<ChatMessage[]>([]);
const [chatKey,setChatKey]=useState(()=>crypto.randomUUID());
const loadTasks=async()=> {setLoading(true);setError(''); try {setTasks(await orchestration.tasks())} catch(e){setTasks([]);setSelected(null);setError(errorText(e))} finally {setLoading(false)}};
useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true,killSwitch:s.capabilities?.killSwitch===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false,killSwitch:false}));},[]);
useEffect(()=> {
const resource=resources[section]; setSnapshot(null);
if(!resource)return;
let active=true;setLoading(true);
orchestration.resource(resource).then(data=>{if(active)setSnapshot(data)}).catch(e=>{if(active)setError(errorText(e))}).finally(()=>{if(active)setLoading(false)});
return ()=>{active=false};
},[section]);
const select=async(task:Task)=>{const epoch=++detailEpoch.current;setDecisionLoading(false);setSelected(null);setError('');try {const detail=await orchestration.task(task.id);if(epoch===detailEpoch.current)setSelected(detail)}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}};
const open=(task:Task,action:ServerAction)=>{if(!capabilities.mutations||actionBlockReason(task,action))return;setBlocked(false);setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
const decide=async(task:Task,requested:ServerAction)=>{
const epoch=++detailEpoch.current;
setSelected(null);setPending(null);setError('');setSuccess('');setDecisionLoading(true);
try {
const detail=await orchestration.task(task.id);
if(epoch!==detailEpoch.current)return;
if(detail.id!==task.id)throw new Error('پاسخ جزئیات با وظیفه انتخاب‌شده مطابقت ندارد');
const action=detail.availableActions.find(a=>a.id===requested.id);
if(!action)throw new Error('این اقدام دیگر توسط سرور مجاز نیست؛ وضعیت را بازخوانی کنید');
const blockedReason=actionBlockReason(detail,action);
if(blockedReason)throw new Error(blockedReason);
if(!capabilities.mutations)throw new Error('تغییرات از طرف سرور مجاز نیست');
setSelected(detail);open(detail,action);
} catch(e) {if(epoch===detailEpoch.current)setError(errorText(e))}
finally {if(epoch===detailEpoch.current)setDecisionLoading(false)}
};
const execute=async()=> {
if(!pending||busy||!confirmed||blocked||!capabilities.mutations)return;
setAttempted(true);setBusy(true);setCommandError('');
try { const [runId,artifactHash]=binding.split('|');
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,notBefore:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
};
const openRecovery=async(task:Task)=>{
if(!capabilities.mutations||pending||recovery)return;
const epoch=++detailEpoch.current;setDecisionLoading(true);setSelected(null);setError('');
try{const detail=await orchestration.task(task.id);if(epoch!==detailEpoch.current)return;
if(detail.id!==task.id||!editorialRecoveryRun(detail))throw new Error('بازیابی دیگر مجاز نیست؛ وضعیت را بازخوانی کنید');
setRecovery(detail);
}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}finally{if(epoch===detailEpoch.current)setDecisionLoading(false)}
};
const refresh=()=>{detailEpoch.current++;setDecisionLoading(false);setSelected(null);setPending(null);setRecovery(null);void loadTasks()};
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
return <><div inert={!!recovery} dir="rtl" lang="fa" className="space-y-5 font-vazir pb-12">
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">مرکز فرماندهی ارکستراسیون</h1><p className="text-sm text-gray-600">مرجع عملیات سرور است · Gate1 برای کار محدود · Gate2 و انتشار غیرفعال هستند</p></div><Button onClick={refresh} disabled={busy||loading}>بازخوانی وضعیت از سرور</Button></header>
<nav aria-label="بخش‌های ارکستراسیون" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{detailEpoch.current++;setDecisionLoading(false);setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
{unavailable[section]&&<section className="bg-amber-50 border border-amber-200 rounded-2xl p-5 space-y-3"><h2 className="font-bold">این بخش در نسخه فعلی در دسترس نیست</h2><p>{unavailable[section]}</p><p>برای این بخش درخواست ناموفق تکراری به سرور ارسال نمی‌شود.</p></section>}
{(loading||decisionLoading)&&<p role="status">در حال دریافت وضعیت از سرور…</p>}
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">دریافت اطلاعات از سرور ناموفق بود: {error}. داده جایگزین نمایش داده نمی‌شود. <button onClick={refresh}>بازخوانی وظیفه‌ها</button></p>}
{success&&<p role="status">{success}</p>}
{section==='وظیفه‌ها و تأییدها'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
{section==='نمای کلی'&&<section aria-label="منتظر تصمیم شما" className="border-2 border-purple-300 bg-purple-50 rounded-2xl p-5 space-y-4">
<h2 className="text-xl font-black">منتظر تصمیم شما</h2><p>تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. دکمه‌ها فقط اقدام‌های مجاز اعلام‌شده توسط سرور هستند؛ برای بررسی و تصمیم، جزئیات را باز کنید.</p>
<label>فیلتر تصمیم‌ها<select aria-label="فیلتر تصمیم‌ها" value={decisionFilter} onChange={e=>setDecisionFilter(e.target.value)} className="border rounded p-2 m-2"><option value="ALL">در انتظار، به‌تعویق‌افتاده و نیازمند تمدید</option><option value="GATE1_PENDING">در انتظار تصمیم</option><option value="GATE1_HELD">به‌تعویق‌افتاده</option></select></label>
{!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=><article key={t.id} className="bg-white border rounded-xl p-4 space-y-3"><button disabled={!!pending||busy} className="font-bold text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button><p>{label(t.department)} · {label(t.displayState??t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p><p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><div className="flex flex-wrap gap-2">{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=><Button key={a.id} disabled={!capabilities.mutations||!!pending||busy||!!actionBlockReason(t,a)} onClick={()=>void decide(t,a)}>{actionLabel(a)}</Button>)}</div>{selected?.id!==t.id&&<><p>محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}</p><h3>معیارهای پذیرش</h3>{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?<ul className="list-disc list-inside">{(t.metadata.acceptanceCriteria as string[]).map((c,i)=><li key={i}>{c}</li>)}</ul>:<p>گزارش نشده؛ جزئیات را بررسی کنید</p>}</>}</article>)}
</section>}
{section==='نمای کلی'&&!loading&&!error&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">فهرست وظیفه‌های ثبت‌شده</h2><p>{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.</p><div className="flex flex-wrap gap-3">{[...new Set(tasks.map(t=>t.displayState??t.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>(t.displayState??t.state)===state).length}</span>)}</div></section>}
{(['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>جست‌وجوی وظیفه‌ها<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
{!loading&&!error&&!tasks.length&&<p>وظیفه‌ای از سرور دریافت نشد.</p>}
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.filter(t=>section!=='نمای کلی'||!['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)).map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{label(t.department)}</td><td>{label(t.displayState??t.state)}</td><td>{label(t.operationMode)}</td><td>{t.budgetLimitCents??'نامشخص'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
</section>}
{selected&&<section aria-label="جزئیات وظیفه" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?<h3 className="font-bold">محدوده و معیارهای پذیرش گزارش‌شده از سرور</h3>:<p>محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.</p>}<p>محدوده گردش کار سرور: در نمای امن در دسترس نیست.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
{selected.displayState==='GATE1_RENEWAL_REQUIRED'&&<p role="status">مسدود — تأیید Gate1 منقضی شده؛ برای همان وظیفه و محدوده، تأیید مجدد مستقل لازم است. برنامه زمانی و سقف بودجه تغییر نمی‌کند.</p>}<h3 className="font-bold">اقدام‌های مجاز اعلام‌شده توسط سرور</h3>{!selected.availableActions.length&&<p>اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'تغییرات از طرف سرور مجاز نیست':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{actionLabel(a)}</Button>)}</div>
{editorialRecoveryRun(selected)&&<Button disabled={!capabilities.mutations||!!pending||busy||decisionLoading} onClick={()=>void openRecovery(selected)}>ثبت شکست اجرای متوقف‌شده</Button>}
<h3 className="font-bold">تصمیم‌های تأیید تغییرناپذیر</h3><Json value={selected.decisions??[]}/>
<h3 className="font-bold">اجراها و خروجی‌های ثبت‌شده</h3>{!selected.runs?.length&&<p>اجرای ثبت‌شده‌ای وجود ندارد.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {label(r.status)}</h4><p>کامیت: {r.commitSha} · محیط: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
<p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><h3 className="font-bold">دفتر بودجه (سنت؛ رزرو با هزینه واقعی متفاوت است)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی به‌ترتیب</h3><Json value={selected.events??[]}/>
</section>}
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>زمان دریافت از سرور: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>رکوردی از سرور دریافت نشد.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3 className="font-bold">{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{label(k)}</dt><dd>{String(v??'نامشخص')}</dd></div>)}</dl></article>)}</div><p>تغییر تنظیمات فقط با فرمان مجاز سرور ممکن است؛ مرورگر فرمانی ایجاد نمی‌کند.</p></section>}
{section==='توقف اضطراری'&&!capabilities.killSwitch&&<p>کنترل توقف اضطراری در این نسخه در دسترس نیست؛ مسیر سرور اجازه تغییر نمی‌دهد.</p>}
{section==='توقف اضطراری'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>توقف سراسری — چهار سطح افزایشی</h2><p>این اقدام سراسری است و فقط به Task انتخاب‌شده محدود نیست. ازسرگیری خودکار ندارد. سطح فعال تا دریافت وضعیت سرور نامشخص است.</p><label>سطح<select aria-label="سطح توقف" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l} value={l}>{label(l)}</option>)}</select></label><p>توقف کار جدید ← توقف عامل‌ها ← منع تغییرات ← توقف اضطراری</p><label>دلیل<input aria-label="دلیل توقف" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>پیامد عملیاتی سراسری را تأیید می‌کنم</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('سرور فرمان توقف را دریافت کرد: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>اعمال توقف سراسری</Button></section>}
{section==='مصرف و سهمیه 9router'&&<RouterUsagePanel/>}
{section==='اطلاعات اجرا و نشست‌ها'&&<RuntimeReadPanel/>}
{section==='گفت‌وگو'&&!capabilities.chat&&<p>گفت‌وگو در دسترس نیست؛ پل مورد اعتماد اجرا فعال نیست.</p>}
{section==='گفت‌وگو'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>گفت‌وگوی متنی از مسیر امن سرور</h2><p>فقط متن مشورتی؛ بدون ترمینال، PTY، توکن اجرا یا اتصال مستقیم به Hermes. تصمیم‌ها از کنترل تأیید مستقل عبور می‌کنند.</p><label>شناسه نشست<input value={session} onChange={e=>{setSession(e.target.value);setMessages([])}} className="border p-2"/></label><div role="log">{messages.map(m=><p key={m.id}>{m.role}: {m.content}</p>)}</div><label>پیام<textarea value={message} onChange={e=>{setMessage(e.target.value);setChatKey(crypto.randomUUID())}} className="border p-2 block w-full"/></label><Button disabled={busy||!session.trim()||!message.trim()} onClick={async()=>{setBusy(true);setError('');try{const reply=await orchestration.chat(session,message,chatKey);setMessages(prev=>[...prev,{id:chatKey,role:'user',content:message},reply]);setMessage('');setChatKey(crypto.randomUUID())}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>ارسال پیام مشورتی</Button></section>}
{pending&&<div role="dialog" aria-modal="true" aria-label="تأیید فرمان تغییرناپذیر" className="fixed inset-0 z-50 bg-black/50 overflow-y-auto p-8"><div className="bg-white rounded-2xl p-6 max-w-2xl mx-auto space-y-4"><h2>{actionLabel(pending.action)}</h2><Json value={{taskId:pending.task.id,expectedVersion:pending.task.version,idempotencyKey:pending.key,scope:pending.task.metadata,budgetLimitCents:pending.task.budgetLimitCents,operationMode:pending.task.operationMode}}/>
{pending.action.gate===1&&pending.action.decision==='APPROVED'&&pending.task.displayState!=='GATE1_RENEWAL_REQUIRED'&&<label className="block">زمان اجرای برنامه‌ریزی‌شده (اختیاری؛ پیش‌فرض فوری)<input aria-label="زمان اجرای برنامه‌ریزی‌شده" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>اتصال اجرای ثبت‌شده به خروجی<select aria-label="اتصال اجرای ثبت‌شده به خروجی" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">انتخاب شواهد تغییرناپذیر</option>{pending.task.runs?.filter(r=>r.status==='SUCCEEDED').flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
<p>تأیید، وظیفه را در اولویت صف آماده قرار می‌دهد؛ زمان اختیاری فقط زودترین زمان شروع است و اجرای دقیق در آن لحظه تضمین نمی‌شود. حداکثر زمان‌بندی ۳۰ روز است؛ اعتبار تأیید را سرور مدیریت می‌کند.</p>
<label className="block">دلیل (برای تأیید اختیاری)<input aria-label="دلیل" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>محدوده و اتصال تغییرناپذیر را بررسی کردم</label>
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||(pending.action.toState==='GATE1_HELD'&&!reason.trim())|| (!!expires&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+30*86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
</div></div>}
</div>{recovery&&<EditorialRecoveryDialog task={recovery} onClose={refresh} onSuccess={async()=>{detailEpoch.current++;setRecovery(null);setSelected(null);setSuccess('شکست ثبت شد؛ رزرو با هزینه نامشخص حفظ شد.');await loadTasks()}}/>}</>;
}
@@ -1,39 +0,0 @@
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
const proposal={id:'pending',key:'p',title:'بررسی منابع محتوا',department:'Content',state:'GATE1_PENDING',version:3,operationMode:'PREPARE',budgetLimitCents:240,metadata:{scope:'فقط تحقیق منابع عمومی',acceptanceCriteria:['سه منبع معتبر']},availableActions:['APPROVE_GATE1','HOLD_GATE1','REJECT_GATE1']};
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[proposal,{...proposal,id:'held',title:'کار نگه‌داشته',state:'GATE1_HELD'}, {...proposal,id:'done',title:'کار پایان‌یافته',state:'CLOSED'}]:proposal}));});
it('opens with obvious pending and held owner queue, scope, criteria and budget; filters without invented actions',async()=>{
render(<OrchestrationCommandCenter/>);
const queue=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(queue).findByRole('button',{name:proposal.title})).toBeInTheDocument();
const card=within(queue).getByRole('button',{name:proposal.title}).closest('article')!;
expect(within(card).getByText(/فقط تحقیق منابع عمومی/)).toBeInTheDocument();
expect(within(card).getByText('سه منبع معتبر')).toBeInTheDocument();
expect(within(card).getByText(/240/)).toBeInTheDocument();
expect(within(queue).queryByText('کار پایان‌یافته')).not.toBeInTheDocument();
fireEvent.change(within(queue).getByLabelText('فیلتر تصمیم‌ها'),{target:{value:'GATE1_HELD'}});
expect(within(queue).queryByRole('button',{name:proposal.title})).not.toBeInTheDocument();
fireEvent.click(within(queue).getByRole('button',{name:'کار نگه‌داشته'}));
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
expect(within(detail).getByRole('button',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
expect(api.put).not.toHaveBeenCalled();expect(api.post).not.toHaveBeenCalled();
});
it('holds through authenticated server transition and reloads instead of fabricating a local decision',async()=>{
vi.mocked(api.put).mockResolvedValue({data:{}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:proposal.title}));
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
fireEvent.click(within(detail).getByRole('button',{name:'تعویق تصمیم Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'بررسی بودجه'}});
fireEvent.click(within(dialog).getByRole('checkbox'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await waitFor(()=>expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/pending/transition',{toState:'GATE1_HELD',expectedVersion:3,idempotencyKey:expect.any(String),reason:'بررسی بودجه'}));
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(await screen.findByRole('button',{name:proposal.title})).toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();
});
@@ -1,30 +0,0 @@
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),put:vi.fn(),post:vi.fn()}}));
it('offers Persian RTL navigation and honest unavailable tabs without calling unsupported routes',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/tasks'))return {data:[]};
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:false}}};
throw new Error('Unexpected request '+url);
});
const {container}=render(<OrchestrationCommandCenter/>);
expect(await screen.findByRole('heading',{name:'مرکز فرماندهی ارکستراسیون'})).toBeInTheDocument();
expect(container.firstElementChild).toHaveAttribute('dir','rtl');
for(const tab of ['عامل‌ها و دپارتمان‌ها','مدل‌ها و بودجه‌ها','زمان‌بندی‌ها']){
fireEvent.click(screen.getByRole('button',{name:tab}));
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
}
await waitFor(()=>expect(api.get).toHaveBeenCalledTimes(2));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('retains available-read failures in Persian instead of claiming a healthy empty inventory',async()=>{
vi.mocked(api.get).mockRejectedValue({response:{status:503}});
render(<OrchestrationCommandCenter/>);
expect(await screen.findByRole('alert')).toHaveTextContent('دریافت اطلاعات از سرور ناموفق بود');
expect(screen.queryByText(/وظیفه‌ای از سرور دریافت نشد/)).not.toBeInTheDocument();
});
import {actionBlockReason} from '../services/orchestration';
it('keeps Gate2 disabled even if a legacy server action advertises it',()=>{expect(actionBlockReason({operationMode:'PREPARE',state:'GATE2_PENDING'} as never,{id:'g2',label:'release',gate:2,decision:'APPROVED'})).toMatch(/Gate2.*غیرفعال/)});
@@ -1,602 +0,0 @@
import { useState, useEffect } from 'react';
import {
Search,
RefreshCw,
Bot,
Briefcase,
ChevronDown,
ChevronLeft,
ChevronRight,
} 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 [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
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 sortedTasks = [...tasks].sort((a, b) => {
const tA = new Date(a.createdAt || 0).getTime();
const tB = new Date(b.createdAt || 0).getTime();
return sortOrder === 'desc' ? tB - tA : tA - tB;
});
const filteredTasks = sortedTasks.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 'WAITING_DEPENDENCIES':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-violet-100 text-violet-800 border border-violet-200">
۳. منتظر تکمیل اقدامات وابسته
</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>
);
case 'REJECTED':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">
رد شده (REJECTED)
</span>
);
default:
return <span>{status}</span>;
}
};
const getStatusTransitionsSummary = (logsRaw: any) => {
const list = Array.isArray(logsRaw) ? logsRaw : (typeof logsRaw === 'object' && logsRaw ? [logsRaw] : []);
let inProgressCount = 0;
let testCount = 0;
let qaRejectedCount = 0;
let qaPassedCount = 0;
list.forEach((entry: any) => {
const st = String(entry?.status || '');
if (st.includes('STARTED') || st === 'IN_PROGRESS') inProgressCount += 1;
if (st.includes('COMPLETED') || st === 'TEST') testCount += 1;
if (st === 'QA_FAILED') qaRejectedCount += 1;
if (st === 'QA_PASSED') qaPassedCount += 1;
});
return { inProgressCount, testCount, qaRejectedCount, qaPassedCount, totalEvents: list.length };
};
const getPriorityBadge = (priority: string) => {
switch (priority) {
case 'CEO_EXPEDITE':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-purple-700 text-white rounded animate-pulse shadow-sm shadow-purple-300">⚡ فوری مدیرعامل</span>;
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="DEVOPS">زیرساخت و سرور (DEVOPS)</option>
<option value="SEO">سئو و مارکت‌پلیس (SEO)</option>
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
<option value="CLINICAL_RD">تحقیق و توسعه بالینی (CLINICAL_RD)</option>
<option value="B2B">بازرگانی و توسعه کلینیک‌ها (B2B)</option>
<option value="SUPPORT">پشتیبانی مشتریان و CRM (SUPPORT)</option>
<option value="QA">تضمین کیفیت و تست (QA)</option>
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</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="WAITING_DEPENDENCIES">۴. منتظر اقدامات وابسته (WAITING_DEPENDENCIES)</option>
<option value="DONE">۵. تکمیل و راستی‌آزمایی‌شده (DONE)</option>
<option value="REJECTED">۶. رد شده (REJECTED)</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="CEO_EXPEDITE">⚡ فوری مدیرعامل (CEO_EXPEDITE)</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 cursor-pointer select-none hover:text-purple-700" onClick={() => setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc')}>
<div className="flex items-center gap-1">
<span>تاریخ و ساعت (تهران)</span>
<span className="text-[10px] text-purple-600">({sortOrder === 'desc' ? '▼ جدیدترین' : '▲ قدیمی‌ترین'})</span>
</div>
</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 whitespace-nowrap text-xs text-gray-600 font-medium" dir="ltr">
{task.createdAt ? new Intl.DateTimeFormat('fa-IR', {
timeZone: 'Asia/Tehran',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}).format(new Date(task.createdAt)) : '-'}
</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-3 sm:grid-cols-6 gap-2">
{['TODO', 'IN_PROGRESS', 'TEST', 'WAITING_DEPENDENCIES', 'DONE', 'REJECTED'].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>
{/* Status History & Transitions Summary */}
{activeTaskModal.executionLogs && (() => {
const summary = getStatusTransitionsSummary(activeTaskModal.executionLogs);
return (
<div className="p-3 bg-purple-50/50 rounded-2xl border border-purple-100 space-y-2">
<div className="font-bold text-purple-900 text-[11px] flex items-center justify-between">
<span>آمار چرخه‌ها و وضعیت‌های طی‌شده تسک:</span>
<span className="font-mono text-[10px] text-purple-700 bg-white px-2 py-0.5 rounded-full border border-purple-200">
{summary.totalEvents} رکورد ثبتی
</span>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
<div className="bg-white p-2 rounded-xl border border-blue-100 text-center shadow-xs">
<span className="block text-[10px] text-gray-500 font-bold">دفعات ارجاع به اجرا</span>
<span className="text-xs font-black text-blue-700 font-mono">{summary.inProgressCount} بار</span>
</div>
<div className="bg-white p-2 rounded-xl border border-amber-100 text-center shadow-xs">
<span className="block text-[10px] text-gray-500 font-bold">بررسی تست و QA</span>
<span className="text-xs font-black text-amber-700 font-mono">{summary.testCount} بار</span>
</div>
<div className="bg-white p-2 rounded-xl border border-rose-100 text-center shadow-xs">
<span className="block text-[10px] text-gray-500 font-bold">عدم تایید QA</span>
<span className="text-xs font-black text-rose-700 font-mono">{summary.qaRejectedCount} بار</span>
</div>
<div className="bg-white p-2 rounded-xl border border-emerald-100 text-center shadow-xs">
<span className="block text-[10px] text-gray-500 font-bold">تاییدیه کیفی</span>
<span className="text-xs font-black text-emerald-700">{summary.qaPassedCount > 0 ? 'دارد (تایید)' : 'در جریان'}</span>
</div>
</div>
</div>
);
})()}
{/* Execution Logs Timeline */}
{activeTaskModal.executionLogs && (
<div className="pt-2 space-y-1.5">
<div className="font-bold text-gray-600 text-[11px] flex items-center justify-between">
<span>تایم‌لاین رویدادها و تغییر وضعیت‌ها:</span>
<span className="text-[10px] text-gray-400">(به وقت تهران)</span>
</div>
<div className="space-y-1.5 max-h-48 overflow-y-auto p-1">
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
<div key={i} className="text-[10px] p-2.5 bg-gray-50 hover:bg-gray-100/70 rounded-xl flex items-start justify-between gap-3 border border-gray-100 transition-colors">
<span className="font-bold text-gray-800 leading-relaxed text-right flex-1">{lg.note || JSON.stringify(lg)}</span>
<span className="text-gray-400 font-mono text-[9px] whitespace-nowrap dir-ltr pt-0.5">
{lg.timestamp ? new Date(lg.timestamp).toLocaleString('fa-IR', { hour: '2-digit', minute: '2-digit', second: '2-digit', day: '2-digit', month: '2-digit' }) : '-'}
</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>
);
}
@@ -1,63 +0,0 @@
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import {orchestration} from '../services/orchestration';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
const run={id:'r-expired',status:'RUNNING',environment:'staging',commitSha:'a'.repeat(40),artifacts:[]};
const task={id:'editorial',key:'editorial-v1:'+ 'a'.repeat(64),title:'Editorial research: Test',department:'CONTENT',operationMode:'PREPARE',state:'RUNNING',version:6,budgetLimitCents:20,metadata:{commitSha:run.commitSha},availableActions:[],runs:[run],editorialRecovery:{runId:run.id}};
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));});
it('posts only the exact expired recovery payload through authenticated API',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{}});
await orchestration.editorialFailure(task,{runId:run.id,expectedVersion:6,idempotencyKey:'stable',reason:'Process ended'});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks/editorial/editorial-failure',{runId:run.id,expectedVersion:6,idempotencyKey:'stable',reason:'Process ended'});
});
it.each([{...task,editorialRecovery:undefined},{...task,runs:[]},{...task,runs:[{...run,status:'SUCCEEDED'}]},{...task,runs:[{...run,commitSha:'b'.repeat(40)}]}])('rejects missing or mismatched server recovery binding',async invalid=>{
await expect(orchestration.editorialFailure(invalid,{runId:run.id,expectedVersion:6,idempotencyKey:'k',reason:'Process ended'})).rejects.toThrow();expect(api.post).not.toHaveBeenCalled();
});
it.each(['',' ','x'.repeat(501)])('bounds required recovery reason',async reason=>{
await expect(orchestration.editorialFailure(task,{runId:run.id,expectedVersion:6,idempotencyKey:'k',reason})).rejects.toThrow();expect(api.post).not.toHaveBeenCalled();
});
it('uses fresh detail before modal; freezes retry bytes; blocks concurrency rejection until refresh',async()=>{
let details=0;
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:{...task,version:++details===1?6:7}}));
vi.mocked(api.post).mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce({response:{status:409}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:task.title}));
fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقف‌شده'}));
const dialog=await screen.findByRole('dialog',{name:'ثبت شکست اجرای متوقف‌شده'});
expect(details).toBe(2);expect(api.post).not.toHaveBeenCalled();
expect(within(dialog).getByText(/۲۰ سنت.*نامشخص/)).toBeInTheDocument();
expect(within(dialog).getByText(/QA.*تأیید خودکار/)).toBeInTheDocument();
const submit=within(dialog).getByRole('button',{name:'ثبت شکست'});
expect(submit).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('دلیل شکست'),{target:{value:'Process ended'}});
fireEvent.click(within(dialog).getByLabelText('ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید می‌کنم'));
fireEvent.click(submit);await within(dialog).findByRole('alert');
expect(within(dialog).getByLabelText('دلیل شکست')).toBeDisabled();
fireEvent.click(submit);await waitFor(()=>expect(submit).toBeDisabled());
expect(api.post).toHaveBeenCalledTimes(2);
const payload=vi.mocked(api.post).mock.calls[0][1];expect(payload).toEqual(expect.objectContaining({runId:run.id,expectedVersion:7,reason:'Process ended'}));expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(payload);
fireEvent.click(within(dialog).getByRole('button',{name:'بازخوانی و بستن'}));await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
});
it('refreshes authoritative tasks after success without approval or budget commands',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{state:'FAILED'}});
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقف‌شده'}));
const dialog=await screen.findByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('دلیل شکست'),{target:{value:'Process ended'}});
fireEvent.click(within(dialog).getByLabelText('ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید می‌کنم'));
fireEvent.click(within(dialog).getByRole('button',{name:'ثبت شکست'}));
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(api.post).toHaveBeenCalledTimes(1);expect(api.put).not.toHaveBeenCalled();
expect(vi.mocked(api.get).mock.calls.filter(([url])=>url.endsWith('/tasks'))).toHaveLength(2);
});
it('does not infer eligibility from RUNNING or guessed age',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:{...task,editorialRecovery:undefined}}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));await screen.findByRole('region',{name:'جزئیات وظیفه'});
expect(screen.queryByRole('button',{name:'ثبت شکست اجرای متوقف‌شده'})).not.toBeInTheDocument();
});
it('rejects eligibility removed during fresh open without a mutation',async()=>{
let details=0;vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:{...task,editorialRecovery:++details===1?task.editorialRecovery:undefined}}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقف‌شده'}));
expect(await screen.findByRole('alert')).toHaveTextContent(/بازخوانی/);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();expect(api.post).not.toHaveBeenCalled();
});
@@ -1,24 +0,0 @@
import {render,screen,fireEvent,within,waitFor,act} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
it('does not restore stale detail after authoritative refresh while detail request is pending',async()=>{
const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[]};
let resolve!:(v:unknown)=>void;
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}};if(url.endsWith('/tasks'))return {data:[t]};return await new Promise<unknown>(r=>{resolve=r}) as never});
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
expect(screen.queryByRole('region',{name:'جزئیات وظیفه'})).not.toBeInTheDocument();
});
it('keeps payload immutable when navigating after an ambiguous network failure',async()=>{
vi.resetAllMocks();const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[{id:'g1',label:'Approve safe work',gate:1,decision:'APPROVED'}]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));vi.mocked(api.post).mockRejectedValue(new Error('network'));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));expect(d.queryByLabelText('زمان انقضا')).not.toBeInTheDocument();expect(d.getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toHaveValue('');fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));await d.findByRole('alert');
const sentPayload=structuredClone(vi.mocked(api.post).mock.calls[0][1]);
expect(sentPayload).toMatchObject({expectedVersion:2,decision:'APPROVED',notes:'Reviewed'});
expect(sentPayload).not.toHaveProperty('expiresAt');expect(sentPayload).not.toHaveProperty('notBefore');
fireEvent.click(screen.getByRole('button',{name:'وظیفه‌ها و تأییدها'}));expect(d.getByLabelText('دلیل')).toHaveValue('Reviewed');expect(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم')).toBeChecked();
expect(vi.mocked(api.post).mock.calls[0][1]).toEqual(sentPayload);
expect(d.getByLabelText('دلیل')).toBeDisabled();expect(d.getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toBeDisabled();
});
@@ -1,49 +0,0 @@
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import {orchestration} from '../services/orchestration';
import type {CreateTaskInput} from '../services/orchestration';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
const action={id:'g1',label:'تأیید در Gate1',gate:1 as const,decision:'APPROVED' as const};
const task={id:'t',key:'t',title:'Safe proposal',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[action],runs:[]};
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[task]:task}));});
it('refuses Production creation even when called outside form',async()=>{
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|اعلام نشده/);
expect(api.post).not.toHaveBeenCalled();
});
it('rejects ambiguous advertised action rather than selecting a mutation path',async()=>{
const ambiguous={...action,toState:'READY'};
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/اعلام نشده/);
expect(api.post).not.toHaveBeenCalled();
});
it('blocks release transitions even when advertised by server',async()=>{
const release={id:'release',label:'Release',toState:'RELEASING'};
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|اعلام نشده/);
expect(api.put).not.toHaveBeenCalled();
});
it('rejects Gate2 evidence from failed runs',async()=>{
const g2={...action,gate:2 as const};
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
expect(api.post).not.toHaveBeenCalled();
});
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));expect(d.queryByLabelText('زمان انقضا')).not.toBeInTheDocument();expect(d.getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toHaveValue('');fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));return d;}
it('locks stale 409 command until authoritative refresh instead of retrying stale payload',async()=>{
vi.mocked(api.post).mockRejectedValue({response:{status:409,data:{message:'Version conflict'}}});
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));
await waitFor(()=>expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled());
expect(await d.findByRole('alert')).toHaveTextContent(/نسخه قدیمی/);
fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));expect(api.post).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
});
it('does not expose authorized task mutations when capabilities are unavailable',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))throw new Error('offline');return {data:url.endsWith('/tasks')?[task]:task};});
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'جزئیات وظیفه'});
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeDisabled();
});
it('prevents confirming a scheduled start in the past without sending a command',async()=>{
const d=await dialog();fireEvent.change(d.getByLabelText('زمان اجرای برنامه‌ریزی‌شده'),{target:{value:'2020-01-01T12:00'}});
expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));
expect(api.post).not.toHaveBeenCalled();
});