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,16 +0,0 @@
import {fireEvent,render,screen} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import CreateOrchestrationTask from './CreateOrchestrationTask';
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
it('submits exact bounded PREPARE contract only after valid commit and budget',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();
for(const [label,value] of Object.entries({'کلید یکتای وظیفه':'audit-1','عنوان':'Audit schema','دپارتمان':'SEO','شناسه کامیت (۴۰ نویسه هگز کوچک)':'a'.repeat(40),'سقف بودجه به سنت':'500','محدوده':'Audit staging only','معیارهای پذیرش (هر معیار در یک خط)':'Schema checked\nEvidence attached'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value}});expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();}
fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value:'500'}});
fireEvent.click(screen.getByRole('button',{name:'ایجاد وظیفه محدود'}));
await screen.findByText('وظیفه توسط سرور ایجاد شد.');
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'audit-1',title:'Audit schema',department:'SEO',operationMode:'PREPARE',budgetLimitCents:500,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked','Evidence attached']}});
expect(done).toHaveBeenCalledOnce();
});
@@ -1,15 +0,0 @@
import {useState} from 'react';
import Button from './ui/Button';
import {orchestration,proposalError} from '../services/orchestration';
import type {CreateTaskInput} from '../services/orchestration';
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
const [fields,setFields]=useState({key:'',title:'',department:'',commitSha:'',budget:'',scope:'',criteria:''});
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
const input:CreateTaskInput={key:fields.key,title:fields.title,department:fields.department,operationMode:'PREPARE',budgetLimitCents:Number(fields.budget),metadata:{commitSha:fields.commitSha,scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n')}};
const valid=Object.values(fields).every(value=>value.trim())&&!proposalError(input);
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">ایجاد کار محدود</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('وظیفه توسط سرور ایجاد شد.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — پیش از ارسال مجدد، کلید وظیفه را با وضعیت سرور تطبیق دهید.':'ایجاد ناموفق بود؛ پیش از تلاش مجدد کلید وظیفه را تطبیق دهید.')}finally{setBusy(false)}}}>
{([['key','کلید یکتای وظیفه'],['title','عنوان'],['department','دپارتمان'],['commitSha','شناسه کامیت (۴۰ نویسه هگز کوچک)'],['budget','سقف بودجه به سنت'],['scope','محدوده'],['criteria','معیارهای پذیرش (هر معیار در یک خط)']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
<p>حالت عملیات: PREPARE · محیط: staging. بودجه: ۲۰ تا ۱۰۰۰۰ سنت. محدوده: غیرخالی، حداکثر ۲۰۰۰ نویسه. معیار پذیرش: ۱ تا ۲۰ خط غیرخالی، هر خط حداکثر ۵۰۰ نویسه. محدوده و معیارهای انسانی بدون تغییر ذخیره می‌شوند؛ محدودیت گردش کار متعلق به سرور است.</p><p>ایجاد وظیفه مجوز اجرا نیست. Gate1 تصمیمی مستقل و تغییرناپذیر است. پیشنهاد Production غیرفعال است. پس از خطای مبهم، پیش از ارسال مجدد کلید یکتا را با وضعیت سرور تطبیق دهید.</p>
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>ایجاد وظیفه محدود</Button>
</form></details>;
}
@@ -1,26 +0,0 @@
import {useRef,useState} from 'react';
import Button from './ui/Button';
import {commandFailure,orchestration} from '../services/orchestration';
import type {Task,EditorialFailureInput} from '../services/orchestration';
export default function EditorialRecoveryDialog({task,onClose,onSuccess}:{task:Task;onClose:()=>void;onSuccess:()=>Promise<void>}) {
const [reason,setReason]=useState('');const [confirmed,setConfirmed]=useState(false);
const [busy,setBusy]=useState(false);const [attempted,setAttempted]=useState(false);const [blocked,setBlocked]=useState(false);const [error,setError]=useState('');
const payload=useRef<EditorialFailureInput|null>(null);const inFlight=useRef(false);
const execute=async()=>{
if(inFlight.current||blocked||!confirmed||!reason.trim()||reason.length>500)return;
if(!payload.current)payload.current={runId:task.editorialRecovery!.runId,expectedVersion:task.version,idempotencyKey:crypto.randomUUID(),reason};
inFlight.current=true;setBusy(true);setAttempted(true);setError('');
try {await orchestration.editorialFailure(task,payload.current);await onSuccess();}
catch(e){const failure=commandFailure(e);setBlocked(!failure.retryable);setError(failure.message)}
finally{inFlight.current=false;setBusy(false)}
};
return <div dir="rtl" lang="fa" 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>ثبت شکست اجرای متوقف‌شده</h2><p>وظیفه: {task.title} · نسخه: {task.version}</p><p>شناسه اجرا: {task.editorialRecovery!.runId}</p>
<p>فقط اجرای منقضی‌شده به شکست ثبت می‌شود. رزرو ۲۰ سنت حفظ می‌شود؛ هزینه واقعی نامشخص است، نه هزینه صفر.</p>
<p>این اقدام QA یا تأیید خودکار ایجاد نمی‌کند؛ انتشار، اجرای دوباره، افزایش بودجه یا آزادسازی رزرو انجام نمی‌شود. مجوز بازبین مستقل و اتصال اجرای منقضی را سرور دوباره بررسی می‌کند.</p>
<label className="block">دلیل شکست<textarea aria-label="دلیل شکست" maxLength={500} value={reason} disabled={busy||attempted} onChange={e=>{setReason(e.target.value);setConfirmed(false)}} className="border p-2 w-full"/></label><p>{reason.length}/500</p>
<label className="block"><input type="checkbox" checked={confirmed} disabled={busy||attempted} onChange={e=>setConfirmed(e.target.checked)}/>ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید می‌کنم</label>
{error&&<p role="alert">{error}</p>}
<div className="flex gap-3"><Button disabled={busy||blocked||!confirmed||!reason.trim()||reason.length>500} onClick={()=>void execute()}>ثبت شکست</Button><Button disabled={busy} variant="outline" onClick={onClose}>بازخوانی و بستن</Button></div>
</div></div>;
}
@@ -1,9 +0,0 @@
import { render,screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { it,expect,vi } from 'vitest';
import Sidebar from './Sidebar';
vi.mock('../services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:{success:true,data:{}}})}}));
it('exposes command center inside existing authenticated navigation',async()=>{
render(<MemoryRouter initialEntries={['/orchestration']}><Sidebar isOpen setIsOpen={vi.fn()}/></MemoryRouter>);
expect(await screen.findByRole('link',{name:'Orchestration command center'})).toHaveAttribute('href','/orchestration');
});
@@ -1,10 +0,0 @@
import {render,screen} from '@testing-library/react';
import {expect,it} from 'vitest';
import {Records} from './OrchestrationPresentation';
it('preserves human scope, criteria and immutable identifiers while translating protocol enums',()=>{
render(<Records value={{metadata:{scope:'READY',acceptanceCriteria:['SUCCEEDED'],commitSha:'READY'},operationMode:'PREPARE',status:'SUCCEEDED'}}/>);
expect(screen.getAllByText('READY')).toHaveLength(2);
expect(screen.getByText('SUCCEEDED')).toBeInTheDocument();
expect(screen.getByText('آماده‌سازی')).toBeInTheDocument();
expect(screen.getByText('موفق')).toBeInTheDocument();
});
@@ -1,11 +0,0 @@
import type {ServerAction} from '../services/orchestration';
const labels:Record<string,string>={GATE1_RENEWAL_REQUIRED:'مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک',DRAFT:'پیش‌نویس',GATE1_HELD:'تصمیم به تعویق افتاده',GATE1_PENDING:'در انتظار تأیید Gate1',GATE1_APPROVED:'تأییدشده در Gate1',READY:'آماده اجرا',RUNNING:'در حال اجرا',SUCCEEDED:'موفق',FAILED:'ناموفق',BLOCKED:'مسدود',EXPIRED:'منقضی',REJECTED:'ردشده',APPROVED:'تأییدشده',GATE2_PENDING:'در انتظار Gate2 (غیرفعال)',PREPARE:'آماده‌سازی',MUTATE_PRODUCTION:'تغییر Production (غیرفعال)',SEO:'بهینه‌سازی جست‌وجو (SEO)',Content:'محتوا',Tech:'فنی',operationMode:'حالت عملیات',budgetLimitCents:'سقف بودجه (سنت)',metadata:'اطلاعات ثبت‌شده',scope:'محدوده',acceptanceCriteria:'معیارهای پذیرش',commitSha:'شناسه کامیت',id:'شناسه',taskId:'شناسه وظیفه',expectedVersion:'نسخه مورد انتظار',idempotencyKey:'کلید جلوگیری از اجرای تکراری',gate:'دروازه تأیید',decision:'تصمیم',expiresAt:'زمان انقضا',createdAt:'زمان ثبت',runId:'شناسه اجرا',artifactHash:'هش خروجی',environment:'محیط',sha256:'هش SHA-256',kind:'نوع',eventType:'نوع رویداد',fromState:'وضعیت پیشین',toState:'وضعیت بعدی',sequence:'ترتیب',amountCents:'مبلغ (سنت)',status:'وضعیت',reason:'دلیل',department:'دپارتمان',staging:'آزمایشی (staging)',FREEZE_NEW_WORK:'توقف کار جدید',STOP_AGENTS:'توقف عامل‌ها',DISABLE_MUTATIONS:'منع تغییرات',EMERGENCY_HALT:'توقف اضطراری',RESERVE:'رزرو بودجه',RECONCILE:'تطبیق بودجه'};
export const label=(value:string)=>labels[value]??value;
export const actionLabel=(action:ServerAction)=>({HOLD_GATE1:'تعویق تصمیم Gate1',SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صف‌بندی آماده‌سازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور'));
export function Records({value,field}:{value:unknown;field?:string}){
if(value===null||value===undefined)return <span>نامشخص — گزارش نشده</span>;
if(Array.isArray(value))return value.length?<div className="space-y-3">{value.map((item,index)=><article className="border rounded-lg p-3" key={index}><Records value={item} field={field}/></article>)}</div>:<p>رکوردی ثبت نشده است.</p>;
if(typeof value==='object')return <dl className="grid gap-3 sm:grid-cols-2">{Object.entries(value).map(([key,item])=><div key={key} className="min-w-0"><dt className="text-sm text-gray-500">{label(key)}</dt><dd className="break-words"><Records value={item} field={key}/></dd></div>)}</dl>;
if(typeof value==='boolean')return <span>{value?'بله':'خیر'}</span>;
return <bdi className="break-all">{typeof value==='string'&&['state','status','fromState','toState','operationMode','department','decision','environment','kind'].includes(field??'')?label(value):String(value)}</bdi>;
}
@@ -1,20 +0,0 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {routerUsage,usagePeriods} from '../services/routerUsage';
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
const shown=(value:unknown)=>value===null||value===undefined?'نامشخص — گزارش نشده':String(value);
const labels:Record<string,string>={requests:'درخواست‌ها',inputTokens:'توکن ورودی',outputTokens:'توکن خروجی',cacheReadTokens:'توکن خواندن حافظه نهان',cacheWriteTokens:'توکن نوشتن حافظه نهان',reasoningTokens:'توکن استدلال',errors:'خطاها',providers:'تأمین‌کننده‌ها',models:'مدل‌ها',accounts:'حساب‌ها'};
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{labels[key]}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
export default function RouterUsagePanel(){
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'مصرف در دسترس نیست')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">مصرف 9router و سهمیه گزارش‌شده تأمین‌کننده</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>بازخوانی مصرف</Button></header>
<label>بازه مصرف<select aria-label="بازه مصرف" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
<p>مجموع درگاه شامل همه مشتری‌هاست. تفکیک تأمین‌کننده، مدل و حساب هم‌پوشانی دارد؛ آن‌ها را جمع نکنید. شمارنده حافظه نهان و استدلال ممکن است با توکن‌ها هم‌پوشان باشد. مجموع یا سهمیه تخمینی محاسبه نمی‌شود.</p>
<p>سهم مصرف Hermes: نامشخص و گزارش‌نشده؛ با مجموع درگاه جمع نکنید.</p>
{loading&&<p role="status">در حال دریافت مصرف درگاه…</p>}{error&&<p role="alert">دریافت مصرف ناموفق بود: {error}</p>}
{data&&<><dl><dt>منبع</dt><dd>{data.source}</dd><dt>زمان دریافت (نه زمان تازگی منبع)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>زمان به‌روزرسانی منبع</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>قدیمی بودن داده</dt><dd>{shown(data.freshness.stale)}</dd><dt>بازه گزارش‌شده</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>مجموع درگاه (شامل Hermes)</h3><Counters data={data.data.totals}/></article>
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{labels[group]}</h3>{!data.data[group].length&&<p>داده‌ای برای {labels[group]} گزارش نشده است.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>سهمیه باقی‌مانده گزارش‌شده تأمین‌کننده</dt><dd>{shown(row.quota?.remaining)}</dd><dt>زمان بازنشانی سهمیه گزارش‌شده</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>دلیل وضعیت سهمیه</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
<p>سهمیه نامشخص است: درخواست سهمیه به منبع، اطلاعات احراز هویت را تغییر می‌دهد؛ بنابراین این رابط فقط‌خواندنی آن را فراخوانی نمی‌کند.</p></>}
</section>;
}
@@ -1,44 +0,0 @@
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import RuntimeReadPanel from './RuntimeReadPanel';
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:5000,freshness:'stale',liveProcess:'unknown'};
it('labels snapshot inventory without presenting متوقف gateway, zero agents or فعال sessions as live',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'v1',gateway_running:false,overall:'نامشخص',active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:1,sessions:[{id:'session-1',profile:'dev',source:'cli',is_active:true}],provenance}:{period_days:30,totals:{total_input:1,total_output:2,total_sessions:1,total_estimated_cost:0},provenance}}));
render(<RuntimeReadPanel/>);
expect(await screen.findByText('سرویس فهرست ثبت‌شده: پاسخ‌گو (نه سلامت زنده Hermes)')).toBeInTheDocument();
screen.getAllByText(/زمان ثبت: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('قدیمی'));
fireEvent.change(screen.getByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
expect(await screen.findByText(/عامل‌های فعال: نامشخص/)).toBeInTheDocument();
expect(await screen.findByText(/پرچم تاریخی نمای ثبت‌شده: فعال; فعالیت زنده نامشخص است/)).toBeInTheDocument();
expect(screen.queryByText(/درگاه.*متوقف/)).not.toBeInTheDocument();
expect(screen.queryByText(/عامل‌های فعال: 0/)).not.toBeInTheDocument();
expect(screen.queryByText(/runtime health: healthy/)).not.toBeInTheDocument();
});
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/health'))return {data:{ok:true,version:'v1',commit:'abc',auth_required:true}};
if(url.endsWith('/profiles'))return {data:[{name:'dev',is_default:false,gateway_running:false}]};
if(url.endsWith('/status'))return {data:{version:'v1',gateway_running:false,overall:'degraded',active_agents:0,gateway_state:null}};
if(url.endsWith('/sessions'))return {data:{total:0,sessions:[]}};
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
throw new Error('Runtime unavailable');
});});
it('shows actual health identity, explicit متوقف gateway, zero usage and profile-bound reads',async()=>{
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).toBeInTheDocument();
fireEvent.change(await screen.findByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('نشستی دریافت نشد.')).toBeInTheDocument();
expect(screen.getByText('توکن ورودی: 0')).toBeInTheDocument();expect(screen.getByText(/هزینه تخمینی منبع: 0/)).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/runtime/sessions',{params:{profile:'dev',limit:20,offset:0}});
});
it('shows unavailable rather than healthy when runtime cannot be authenticated',async()=>{
vi.mocked(api.get).mockRejectedValue(new Error('Runtime unavailable'));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText('اجرای احرازهویت‌شده health: healthy')).not.toBeInTheDocument();
});
it('rejects malformed health and never renders نامشخص secret fields',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:false,password:'secret-value'}:[]}));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
});
it('refreshes the authenticated runtime reads without a browser runtime connection',async()=>{
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'بازخوانی اطلاعات اجرا'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
});
@@ -1,35 +0,0 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {runtime} from '../services/runtime';
import type {RuntimeProvenance,RuntimeHealth,RuntimeProfile,RuntimeStatus,RuntimeSessions,RuntimeUsage} from '../services/runtime';
function Snapshot({value}:{value?:RuntimeProvenance}){return value?<p>فهرست ثبت‌شده · زمان ثبت: {value.capturedAt} · قدمت: {value.ageSeconds} ثانیه · {value.freshness==='fresh'?'تازه':'قدیمی'} · فرایند زنده: نامشخص. حتی نمای تازه، آمادگی زنده را اثبات نمی‌کند.</p>:null}
export default function RuntimeReadPanel(){
const [revision,setRevision]=useState(0);const [profile,setProfile]=useState('');const [offset,setOffset]=useState(0);
const [health,setHealth]=useState<RuntimeHealth|null>(null);const [profiles,setProfiles]=useState<RuntimeProfile[]>([]);const [errors,setErrors]=useState<Record<string,string>>({});
const [status,setStatus]=useState<RuntimeStatus|null>(null);const [sessions,setSessions]=useState<RuntimeSessions|null>(null);const [usage,setUsage]=useState<RuntimeUsage|null>(null);
const [observed,setObserved]=useState('');
useEffect(()=>{let active=true;setHealth(null);setProfiles([]);setErrors({});
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'وضعیت اجرا در دسترس نیست؛ خواندن احرازهویت‌شده از سرور ناموفق بود.'}))});
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'پروفایل‌ها در دسترس نیستند؛ فهرست هویت‌های مجاز دریافت نشد.'}))}});
return ()=>{active=false};
},[revision]);
useEffect(()=>{let active=true;setStatus(null);setSessions(null);setUsage(null);setErrors(e=>({health:e.health,profiles:e.profiles}));if(!profile)return;
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:(({Status:'وضعیت',Sessions:'نشست‌ها',Usage:'مصرف'} as Record<string,string>)[name]??name)+' در دسترس نیست؛ مقدار جایگزین وجود ندارد.'}))};
runtime.status(profile).then(v=>{if(active)setStatus(v)}).catch(()=>fail('Status'));
runtime.sessions(profile,offset).then(v=>{if(active)setSessions(v)}).catch(()=>fail('Sessions'));
runtime.usage(profile).then(v=>{if(active)setUsage(v)}).catch(()=>fail('Usage'));
return ()=>{active=false};
},[profile,offset,revision]);
return <section aria-label="اجرای احرازهویت‌شده" className="bg-white border rounded-2xl p-5 space-y-4">
<div className="flex justify-between"><h2 className="font-bold">اطلاعات اجرای Hermes — خواندن احرازهویت‌شده از سرور</h2><Button onClick={()=>setRevision(r=>r+1)}>بازخوانی اطلاعات اجرا</Button></div>
<p>اطلاعات محرمانه اجرا وارد مرورگر نمی‌شود و اتصال مستقیم به Hermes وجود ندارد. زمان دریافت پاسخ، زمان ضربان حیات نیست.</p>
{Object.entries(errors).filter(([,message])=>message).map(([name,message])=><p key={name} role="alert">{message}</p>)}
{health&&<div><p>سرویس فهرست ثبت‌شده: {health.ok?'پاسخ‌گو':'بدون پاسخ'} (نه سلامت زنده Hermes)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>زمان دریافت توسط مرورگر: {observed}. فقط زمان دریافت پاسخ است؛ نه زمان ثبت منبع یا ضربان زنده.</p></div>}
<label>پروفایل اجرای مجاز<select aria-label="پروفایل اجرای مجاز" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">انتخاب پروفایل مجاز</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
{!profiles.length&&!errors.profiles&&<p>پروفایل مجازی دریافت نشد.</p>}
{profiles.map(p=><div key={p.name}>{p.name} · درگاه {p.provenance?'نامشخص (نمای ثبت‌شده؛ نه آمادگی فرایند)':p.gateway_running?'در حال اجرا':'متوقف'} · {p.is_default?'پروفایل پیش‌فرض':'پروفایل غیرپیش‌فرض'}<Snapshot value={p.provenance}/></div>)}
{status&&<div><h3>وضعیت پروفایل</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>درگاه: {status.provenance?'نامشخص':status.gateway_running?'در حال اجرا':'متوقف'} · وضعیت: {status.provenance?'نامشخص':status.gateway_state??'نامشخص'} · عامل‌های فعال: {status.provenance?'نامشخص':status.active_agents}</p></div>}
{usage&&<div><h3>مصرف اجرا — {usage.period_days} روز؛ فقط پروفایل انتخاب‌شده</h3><Snapshot value={usage.provenance}/><p>توکن ورودی: {usage.totals.total_input}</p><p>توکن خروجی: {usage.totals.total_output}</p><p>نشست‌ها: {usage.totals.total_sessions}</p><p>هزینه تخمینی منبع: {usage.totals.total_estimated_cost} (ارز توسط منبع مشخص نشده؛ صورت‌حساب قطعی نیست)</p><p>این مقدار را با مجموع 9router جمع نکنید؛ انتساب مصرف هم‌پوشانی دارد و تطبیق داده نشده است.</p></div>}
{sessions&&<div><h3>نشست‌ها — {sessions.total} مجموع گزارش‌شده</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>نشستی دریافت نشد.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`پرچم تاریخی نمای ثبت‌شده: ${s.is_active?'فعال':'غیرفعال'}; فعالیت زنده نامشخص است`:s.is_active?'فعال':'غیرفعال'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>نشست‌های قبلی</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>نشست‌های بعدی</Button></div>}
</section>;
}
@@ -112,19 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
],
},
{
id: 'governance',
title: 'حاکمیت، تاییدات و وظایف',
icon: CheckSquare,
items: [
{ icon: Building2, label: 'Orchestration command center', path: '/orchestration' },
{ icon: Building2, label: 'نمای وضعیت دپارتمان‌ها', path: '/governance/hq' },
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاری‌ها', path: '/manager-actions' },
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },
{ icon: Briefcase, label: 'وظایف دپارتمان‌ها و ایجنت‌ها', path: '/tasks' },
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
],
},
{
id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت',
@@ -12,9 +12,6 @@ interface TopbarProps {
}
const SEARCHABLE_PAGES = [
{ label: "اقدامات مدیریتی و همکاری‌ها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
{ label: "وضعیت دپارتمان‌ها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
{ label: 'مرکز مانیتورینگ و سلامت سرویس‌ها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
{ label: 'مدیریت نسخه‌های پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخه‌ها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },
@@ -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();
});
@@ -50,12 +50,6 @@ const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
const ManagerActionsPage = lazyWithRetry(() => import('../pages/ManagerActionsPage'));
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
const OrchestrationCommandCenter = lazyWithRetry(() => import('../pages/OrchestrationCommandCenter'));
const CompanyOrchestrationHQ = lazyWithRetry(() => import('../pages/CompanyOrchestrationHQ'));
export interface AdminRouteConfig {
path: string;
@@ -121,12 +115,6 @@ export const router = createBrowserRouter([
{ path: 'faq/*', element: <FAQManager /> },
{ path: 'menu/*', element: <MenuManager /> },
{ path: 'monitoring/*', element: <MonitoringPage /> },
{ path: 'approvals/*', element: <ApprovalsPage /> },
{ path: 'manager-actions/*', element: <ManagerActionsPage /> },
{ path: 'history/*', element: <AuditHistoryPage /> },
{ path: 'tasks/*', element: <TasksManagementPage /> },
{ path: 'orchestration/*', element: <OrchestrationCommandCenter /> },
{ path: 'governance/hq/*', element: <CompanyOrchestrationHQ /> },
],
},
],
@@ -1,126 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from './api';
import { orchestration } from './orchestration';
import type { Task } from './orchestration';
vi.mock('./api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
const task = {id:'t/1',version:7,state:'GATE2_PENDING',availableActions:[{id:'approve',label:'Approve',gate:2,decision:'APPROVED'}]} as Task;
describe('orchestration adapter', () => {
beforeEach(() => vi.resetAllMocks());
it('loads bare task lists through existing authenticated client and fails closed without actions', async () => {
vi.mocked(api.get).mockResolvedValue({data:[{id:'t1',title:'Bounded work',version:2,state:'READY'}]});
const tasks = await orchestration.tasks();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks');
expect(tasks[0].availableActions).toEqual([]);
});
it('rejects unadvertised transitions and incomplete Gate2 binding without a request', async () => {
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/اعلام نشده/);
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Gate2.*غیرفعال/);
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
});
it('rejects even fully registered Gate2 evidence because release decisions are disabled', async () => {
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],{idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
expect(api.post).not.toHaveBeenCalled();
});
it('refuses expired approvals and unknown artifacts', async () => {
await expect(orchestration.command({...task,availableActions:[{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'}]},{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'},{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/انقضا/);
const bad={...task,runs:[{id:'r',commitSha:'abc',environment:'staging',status:'DONE',artifacts:[]}]};
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/Gate2.*غیرفعال/);
});
it('loads immutable detail and rejects malformed optional resources', async () => {
vi.mocked(api.get).mockResolvedValueOnce({data:{success:true,data:{...task,runs:[]}}}).mockResolvedValueOnce({data:{nonsense:true}});
expect((await orchestration.task('t/1')).version).toBe(7);
await expect(orchestration.resource('agents')).rejects.toThrow(/نامعتبر/);
});
it('requires kill reason and uses only typed message bridge', async () => {
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/دلیل/);
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/پیام/);
vi.mocked(api.put).mockResolvedValue({data:{active:true}});
await orchestration.kill('STOP_AGENTS','Incident review');
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'STOP_AGENTS',reason:'Incident review'});
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'Review complete'}});
expect(await orchestration.chat('session','Review task','key')).toEqual({id:'reply',role:'assistant',content:'Review complete'});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',{sessionId:'session',message:'Review task',idempotencyKey:'key'});
});
it('creates bounded work without permitting invalid caps or client-supplied state',async()=>{
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/budget/);
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
});
});
describe('actual PREPARE backend contract',()=>{
beforeEach(()=>vi.resetAllMocks());
it('normalizes strings by fixed mapping, drops unknown and tampered objects, never infers from state',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE','RELEASE_AUTHORIZE',{id:'SUBMIT_GATE1',label:'bad',toState:'RELEASING'},null]}});
const detail=await orchestration.task('t/1');
expect(detail.availableActions.map(a=>a.id)).toEqual(['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE']);
vi.mocked(api.put).mockResolvedValue({data:{}});
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'submit'});
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1/transition',{toState:'GATE1_PENDING',expectedVersion:7,idempotencyKey:'submit',reason:undefined});
vi.mocked(api.get).mockResolvedValue({data:[{...task,state:'DRAFT',availableActions:[]}]});
expect((await orchestration.tasks())[0].availableActions).toEqual([]);
});
it('rejects arbitrary object transitions and conflicting known mappings',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:[{id:'evil',label:'go',toState:'RUNNING'},{id:'SUBMIT_GATE1',label:'go',toState:'READY'}]}});
expect((await orchestration.task('t/1')).availableActions).toEqual([]);
});
it.each([0,19,10001,20.5])('rejects invalid budget %s',async budget=>{
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/budget/i);
expect(api.post).not.toHaveBeenCalled();
});
it.each(['abc','A'.repeat(40),'a'.repeat(64),''])('rejects invalid commit %s',async commitSha=>{
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha,scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/commit/i);
});
it.each([20,10000])('posts exact DTO at boundary %s',async budget=>{
vi.mocked(api.post).mockResolvedValue({data:{}});
const dto={key:'k',title:'t',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}};
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
});
});
it.each([
['APPROVE_GATE1','post','/gates/1/decide',{decision:'APPROVED'}],
['REJECT_GATE1','post','/gates/1/decide',{decision:'REJECTED'}],
['QUEUE_PREPARE','put','/transition',{toState:'READY'}],
])('routes actual advertised %s regardless of state',async(id,method,path,payload)=>{
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:[id]}});
vi.mocked(api.post).mockResolvedValue({data:{}});vi.mocked(api.put).mockResolvedValue({data:{}});
const detail=await orchestration.task('t/1');
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:new Date(Date.now()+3600000).toISOString()});
expect(method==='post'?api.post:api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1'+path,expect.objectContaining({...payload,expectedVersion:7,idempotencyKey:'k'}));
});
it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:['APPROVE_GATE1']}});
const detail=await orchestration.task('t/1');
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/۲۴ ساعت/);
expect(api.post).not.toHaveBeenCalled();
});
const validProposal={key:'scope-1',title:'Review staging',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:' Human scope ',acceptanceCriteria:[' Evidence reviewed ']}};
it('preserves immutable human metadata exactly and strips server-owned fields from exact DTO',async()=>{
vi.resetAllMocks();
const projected={id:'new',...validProposal,state:'DRAFT',version:1,metadata:{...validProposal.metadata,environment:'staging'},availableActions:['SUBMIT_GATE1']};
vi.mocked(api.post).mockResolvedValue({data:projected});
await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,workflowScope:'PRODUCTION',createdBy:'forged'}} as unknown as import('./orchestration').CreateTaskInput)).resolves.toEqual(projected);
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',validProposal);
vi.mocked(api.get).mockResolvedValue({data:projected});
expect((await orchestration.task('new')).metadata).toEqual(projected.metadata);
vi.mocked(api.get).mockResolvedValue({data:[projected]});
expect((await orchestration.tasks())[0].metadata).toEqual(projected.metadata);
});
it.each(['', ' ', 'x'.repeat(2001),undefined,42])('rejects invalid human scope %s before HTTP',async scope=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,scope}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/scope/i);expect(api.post).not.toHaveBeenCalled();
});
it.each([[],Array(21).fill('x'),[''],[' '],['x'.repeat(501)],undefined,'criterion',[42]])('rejects invalid acceptance criteria %s before HTTP',async acceptanceCriteria=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,acceptanceCriteria}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/criteria/i);expect(api.post).not.toHaveBeenCalled();
});
it('rejects array-coerced commit hashes',async()=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,commitSha:['a'.repeat(40)]}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/commit/i);expect(api.post).not.toHaveBeenCalled();
});
it('accepts scope and criteria at exact backend limits',async()=>{
vi.resetAllMocks();vi.mocked(api.post).mockResolvedValue({data:{}});
const dto={...validProposal,metadata:{...validProposal.metadata,scope:'x'.repeat(2000),acceptanceCriteria:Array(20).fill('x'.repeat(500))}};
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
});
@@ -1,137 +0,0 @@
import api from './api';
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
// Only advertised IDs select commands; task state never manufactures authorization.
const actionCommands: Record<string, ServerAction> = {
HOLD_GATE1:{id:'HOLD_GATE1',label:'تعویق تصمیم Gate1',toState:'GATE1_HELD'},
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'ارسال برای Gate1',toState:'GATE1_PENDING'},
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'تأیید کار محدود در Gate1',gate:1,decision:'APPROVED'},
REJECT_GATE1:{id:'REJECT_GATE1',label:'رد کار در Gate1',gate:1,decision:'REJECTED'},
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'صف‌بندی آماده‌سازی',toState:'READY'},
};
export function normalizeActions(value:unknown):ServerAction[] {
if(!Array.isArray(value))return [];
const result:ServerAction[]=[];
for(const raw of value){
let action:ServerAction|undefined;
if(typeof raw==='string')action=Object.hasOwn(actionCommands,raw)?actionCommands[raw]:undefined;
else if(raw&&typeof raw==='object'&&typeof raw.id==='string'){
const fixed=Object.hasOwn(actionCommands,raw.id)?actionCommands[raw.id]:undefined;
if(fixed){
if(['toState','gate','decision'].some(k=>raw[k]!==undefined&&raw[k]!==fixed[k as keyof ServerAction]))continue;
action={...fixed};
}else if(!raw.toState&&[1,2].includes(raw.gate)&&['APPROVED','REJECTED'].includes(raw.decision)){
// Legacy object format may describe only dedicated gate decisions, never arbitrary transitions.
action={id:raw.id,label:raw.id,gate:raw.gate,decision:raw.decision};
}
if(action){
if(typeof raw.label==='string'&&raw.label.trim())action={...action,label:raw.label};
if(typeof raw.disabledReason==='string')action={...action,disabledReason:raw.disabledReason};
}
}
if(action&&!result.some(a=>a.id===action.id))result.push({...action});
}
return result;
}
export interface Artifact { id: string; sha256: string; kind?: string; uri?: string }
export interface Run { id: string; commitSha: string; environment: string; status: string; artifacts: Artifact[] }
export interface Task { id: string; key: string; title: string; department: string; state: string; displayState?: string; editorialRecovery?: {runId:string}; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; notBefore?: string; runId?: string; artifactHash?: string }
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt?:string;notBefore?:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
if(action.gate===2)return 'Gate2 و انتشار در این پنل غیرفعال هستند';
if(action.disabledReason)return 'اقدام توسط سرور غیرفعال شده است: '+action.disabledReason;
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'عملیات Production در این پنل در دسترس نیست';
if(task.state==='EXPIRED')return 'پیشنهاد منقضی شده است؛ پیشنهاد جدید ایجاد کنید';
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'اقدام سرور پشتیبانی نمی‌شود';
return undefined;
}
export function commandFailure(error:unknown):{message:string;retryable:boolean} {
const status=(error as {response?:{status?:number}})?.response?.status;
if(status===409)return {message:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',retryable:false};
if(status===410)return {message:'پیشنهاد یا تأیید منقضی شده است. وضعیت را بازخوانی کنید؛ پیشنهاد منقضی به پیشنهاد جدید نیاز دارد.',retryable:false};
if(status===401||status===403)return {message:'سرور این اقدام را رد کرد. پیش از ادامه مجوزها را بازخوانی کنید.',retryable:false};
if(status&&status>=400&&status<500)return {message:'سرور این اقدام را رد کرد (HTTP '+status+'). وضعیت را بازخوانی و پیشنهاد را بررسی کنید.',retryable:false};
return {message:(error instanceof Error?error.message:'درخواست سرور در دسترس نیست')+' — نتیجه نامشخص است. فقط همان داده و کلید را تکرار کنید یا وضعیت را برای تطبیق بازخوانی کنید.',retryable:true};
}
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean;killSwitch?:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const;
export type KillLevel = typeof killLevels[number];
export interface ChatMessage {id:string;role:'assistant'|'user';content:string}
function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof data === 'object' && 'success' in data) {if (!data.success) throw new Error('Orchestration request failed'); return data.data;} return data as T; }
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string;scope:string;acceptanceCriteria:string[]}}
export function proposalError(input:CreateTaskInput):string|undefined {
if(input.operationMode!=='PREPARE')return 'Only bounded Stage PREPARE proposals are available';
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<20||input.budgetLimitCents>10000)return 'PREPARE budget must be an integer 20..10000 cents';
if(typeof input.metadata?.commitSha!=='string'||!/^[a-f0-9]{40}$/.test(input.metadata.commitSha))return 'Immutable commit must be 40 lowercase hex characters';
if(typeof input.metadata?.scope!=='string'||!input.metadata.scope.trim()||input.metadata.scope.length>2000)return 'Scope must be nonblank and at most 2000 characters';
if(!Array.isArray(input.metadata?.acceptanceCriteria)||input.metadata.acceptanceCriteria.length<1||input.metadata.acceptanceCriteria.length>20||input.metadata.acceptanceCriteria.some(value=>typeof value!=='string'||!value.trim()||value.length>500))return 'Acceptance criteria must contain 1..20 nonblank strings of at most 500 characters';
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است';
}
export interface EditorialFailureInput {runId:string;expectedVersion:number;idempotencyKey:string;reason:string}
// Eligibility is a safe server hint, never inferred from elapsed browser time.
export function editorialRecoveryRun(task:Task):Run|undefined {
if(task.state!=='RUNNING'||task.operationMode!=='PREPARE'||task.department!=='CONTENT'||task.budgetLimitCents!==20||!/^editorial-v1:[a-f0-9]{64}$/.test(task.key))return;
const matches=task.runs?.filter(r=>r.id===task.editorialRecovery?.runId&&r.status==='RUNNING'&&r.environment==='staging'&&r.commitSha===task.metadata?.commitSha&&Array.isArray(r.artifacts)&&!r.artifacts.length);
return matches?.length===1?matches[0]:undefined;
}
export const orchestration = {
async editorialFailure(task:Task,input:EditorialFailureInput):Promise<unknown> {
if(!editorialRecoveryRun(task)||input.runId!==task.editorialRecovery?.runId||input.expectedVersion!==task.version||!Number.isInteger(input.expectedVersion)||!input.idempotencyKey||typeof input.reason!=='string'||!input.reason.trim()||input.reason.length>500)throw new Error('اتصال بازیابی معتبر نیست؛ وضعیت را بازخوانی کنید');
return (await api.post('/admin/orchestration/tasks/'+encodeURIComponent(task.id)+'/editorial-failure',{runId:input.runId,expectedVersion:input.expectedVersion,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
},
async create(input:CreateTaskInput):Promise<unknown> {
const error=proposalError(input);if(error)throw new Error(error);
// Preserve human evidence exactly; workflowScope/environment/identity remain server-owned.
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:'PREPARE',budgetLimitCents:input.budgetLimitCents,metadata:{commitSha:input.metadata.commitSha,scope:input.metadata.scope,acceptanceCriteria:[...input.metadata.acceptanceCriteria]}})).data;
},
async task(id:string):Promise<Task> {
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);
if (!data?.id || !Number.isInteger(data.version)) throw new Error('پاسخ جزئیات وظیفه نامعتبر است');
return {...data,availableActions:normalizeActions(data.availableActions)};
},
async resource(name:Resource):Promise<ResourceSnapshot> {
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('پاسخ نمای ثبت‌شده نامعتبر است');
return data;
},
async kill(level:KillLevel,reason:string):Promise<unknown> {
if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است');
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
},
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('نشست و پیام الزامی است');
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('پاسخ گفت‌وگو نامعتبر است');
return data;
},
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
if (!action || action.disabledReason) throw new Error('اقدام اعلام نشده یا غیرفعال است');
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است');
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
if (action.gate && action.decision) {
if (input.notBefore && (action.decision!=='APPROVED' || !(Date.parse(input.notBefore)>Date.now()) || Date.parse(input.notBefore)>Date.now()+30*86400000)) throw new Error('زمان اجرا باید در آینده و حداکثر ۳۰ روز باشد');
if (input.expiresAt && !(Date.parse(input.expiresAt)>Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
if(input.expiresAt && Date.parse(input.expiresAt)>(input.notBefore?Date.parse(input.notBefore):Date.now())+86400000) throw new Error('انقضای Gate1 باید در ۲۴ ساعت پس از زمان اجرا باشد');
let binding = {};
if (action.gate === 2 && action.decision === 'APPROVED') {
const run = task.runs?.find(r => r.id === input.runId);
if(run?.status!=='SUCCEEDED')throw new Error('Registered successful run binding required for Gate2 evidence');
if (!run?.commitSha || !run.environment || !run.artifacts.some(a => a.sha256 === input.artifactHash)) throw new Error('Registered immutable Gate2 binding required');
binding = {runId:run.id, artifactHash:input.artifactHash, commitSha:run.commitSha, environment:run.environment};
}
return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,...(input.expiresAt?{expiresAt:input.expiresAt}:{}),...(input.notBefore?{notBefore:input.notBefore}:{}),notes:input.reason,...binding})).data;
}
if (!action.toState) throw new Error('اقدام سرور پشتیبانی نمی‌شود');
return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
},
async tasks(): Promise<Task[]> {
const { data } = await api.get('/admin/orchestration/tasks');
const rows = Array.isArray(data) ? data : data.data;
if (!Array.isArray(rows)) throw new Error('پاسخ فهرست وظیفه‌ها نامعتبر است');
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
},
};
@@ -1,31 +0,0 @@
import {render,screen,fireEvent} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from './api';
import {routerUsage} from './routerUsage';
import RouterUsagePanel from '../components/RouterUsagePanel';
vi.mock('./api',()=>({default:{get:vi.fn()}}));
const metrics={requests:20,inputTokens:100,outputTokens:50,cacheReadTokens:0,cacheWriteTokens:null,reasoningTokens:null,errors:null};
const snapshot={source:'9router',period:'7d',status:'available',reason:null,attribution:{scope:'9router_total',hermes:null,additive:false},freshness:{retrievedAt:'2026-10-22T12:00:00Z',sourceUpdatedAt:null,stale:null},data:{totals:metrics,providers:[{provider:'provider-a',...metrics}],models:[{model:'model-b',provider:'provider-a',...metrics}],accounts:[{accountId:'opaque-1',provider:'provider-a',model:'model-b',...metrics,quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}}]}};
it('renders concrete backend contract, unknown quota and source freshness; period selects backend filter',async()=>{
vi.mocked(api.get).mockResolvedValue({data:snapshot});render(<RouterUsagePanel/>);
expect(await screen.findByText('opaque-1')).toBeInTheDocument();
expect(screen.getByText('مجموع درگاه (شامل Hermes)')).toBeInTheDocument();
expect(screen.getByText('سهم مصرف Hermes: نامشخص و گزارش‌نشده؛ با مجموع درگاه جمع نکنید.')).toBeInTheDocument();
expect(screen.getByText('9router')).toBeInTheDocument();
expect(screen.getAllByText('نامشخص — گزارش نشده').length).toBeGreaterThan(0);
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
expect(api.get).toHaveBeenCalledWith('/admin/router-usage',{params:{period:'7d'}});
fireEvent.change(screen.getByLabelText('بازه مصرف'),{target:{value:'today'}});
await screen.findByText('opaque-1');
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
});
it('rejects missing provenance instead of inventing freshness',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{accounts:[]}});
await expect(routerUsage.snapshot()).rejects.toThrow(/Invalid/);
});
it('shows unavailable configuration honestly and discards arbitrary credential properties',async()=>{
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,status:'unavailable',reason:'not_configured',data:null}});
await expect(routerUsage.snapshot()).rejects.toThrow('not_configured');
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,token:'secret',data:{...snapshot.data,credentials:'secret'}}});
expect(JSON.stringify(await routerUsage.snapshot())).not.toContain('secret');
});
@@ -1,20 +0,0 @@
import api from './api';
export const usagePeriods=['today','24h','7d','30d','60d','all'] as const;
export type UsagePeriod=typeof usagePeriods[number];
export interface UsageCounters {requests:number|null;inputTokens:number|null;outputTokens:number|null;cacheReadTokens:number|null;cacheWriteTokens:number|null;reasoningTokens:number|null;errors:number|null}
export interface UsageRow extends UsageCounters {provider:string|null;model?:string|null;accountId?:string|null;quota?:{status:string;remaining:number|null;resetAt:string|null;reason:string|null}}
export interface RouterUsageSnapshot {source:string;period:UsagePeriod;freshness:{retrievedAt:string|null;sourceUpdatedAt:string|null;stale:boolean|null};attribution:{scope:'9router_total';hermes:null;additive:false};data:{totals:UsageCounters;providers:UsageRow[];models:UsageRow[];accounts:UsageRow[]}}
const count=(v:unknown):number|null=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=0?v:null;
const text=(v:unknown):string|null=>typeof v==='string'?v:null;
function counters(raw:UsageCounters):UsageCounters {
return {requests:count(raw?.requests),inputTokens:count(raw?.inputTokens),outputTokens:count(raw?.outputTokens),cacheReadTokens:count(raw?.cacheReadTokens),cacheWriteTokens:count(raw?.cacheWriteTokens),reasoningTokens:count(raw?.reasoningTokens),errors:count(raw?.errors)};
}
function rows(list:UsageRow[]):UsageRow[]{return list.map(a=>({provider:text(a.provider),model:text(a.model),accountId:text(a.accountId),...counters(a),...(a.quota?{quota:{status:a.quota.status,remaining:count(a.quota.remaining),resetAt:text(a.quota.resetAt),reason:text(a.quota.reason)}}:{})}))}
export const routerUsage={async snapshot(period:UsagePeriod='7d'):Promise<RouterUsageSnapshot>{
const {data:raw}=await api.get('/admin/router-usage',{params:{period}});
const data=raw?.success===true?raw.data:raw;
if(data?.status==='unavailable')throw new Error('Usage unavailable: '+(data.reason??'unknown'));
if(data?.status!=='available'||data.source!=='9router'||!usagePeriods.includes(data.period)||!data.freshness||!data.data||!Array.isArray(data.data.providers)||!Array.isArray(data.data.models)||!Array.isArray(data.data.accounts))throw new Error('Invalid usage snapshot contract');
// Explicit allowlist; never forward raw gateway configuration or arbitrary response properties.
return {source:data.source,period:data.period,freshness:{retrievedAt:text(data.freshness.retrievedAt),sourceUpdatedAt:text(data.freshness.sourceUpdatedAt),stale:typeof data.freshness.stale==='boolean'?data.freshness.stale:null},attribution:{scope:'9router_total',hermes:null,additive:false},data:{totals:counters(data.data.totals),providers:rows(data.data.providers),models:rows(data.data.models),accounts:rows(data.data.accounts)}};
}};
@@ -1,21 +0,0 @@
import {it,expect,vi} from 'vitest';
import api from './api';
import {runtime} from './runtime';
vi.mock('./api',()=>({default:{get:vi.fn()}}));
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:100,freshness:'stale',liveProcess:'unknown'};
it.each([{source:'live'},{capturedAt:'not-a-date'},{capturedAt:'2999-01-01T00:00:00Z'},{ageSeconds:-1},{ageSeconds:0.5},{freshness:'live'},{liveProcess:'running'}])('rejects invalid provenance %j',async invalid=>{
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,...invalid}}});
await expect(runtime.health()).rejects.toThrow('Invalid snapshot provenance');
});
it('retains fresh snapshots as inventory with unknown process state',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,freshness:'fresh'}}});
expect(await runtime.health()).toMatchObject({provenance:{freshness:'fresh',liveProcess:'unknown'}});
});
it('retains validated snapshot provenance and unknown live telemetry across inventory reads',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'1',commit:'x',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'1',overall:'unknown',gateway_running:false,active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:0,sessions:[],provenance}:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0},provenance}}));
expect(await runtime.health()).toMatchObject({provenance});
expect(await runtime.profiles()).toMatchObject([{provenance,liveGatewayState:'unknown'}]);
expect(await runtime.status('dev')).toMatchObject({provenance,liveGatewayState:'unknown',liveActiveAgents:null});
expect(await runtime.sessions('dev')).toMatchObject({provenance});
expect(await runtime.usage('dev')).toMatchObject({provenance});
});
@@ -1,28 +0,0 @@
import api from './api';
export interface RuntimeProvenance {source:'snapshot';capturedAt:string;ageSeconds:number;freshness:'fresh'|'stale';liveProcess:'unknown'}
interface Inventory {provenance?:RuntimeProvenance}
export interface RuntimeHealth extends Inventory {ok:boolean;version:string;commit:string;auth_required:true}
export interface RuntimeProfile extends Inventory {name:string;is_default:boolean;gateway_running:boolean;liveGatewayState?:'unknown'}
export interface RuntimeStatus extends Inventory {version:string;gateway_running:boolean;overall:string;active_agents:number;gateway_state:string|null;liveGatewayState?:'unknown';liveActiveAgents?:null}
export interface RuntimeSession {id:string;profile:string;source:string;is_active:boolean}
export interface RuntimeSessions extends Inventory {total:number;sessions:RuntimeSession[]}
export interface RuntimeUsage extends Inventory {period_days:number;totals:{total_input:number;total_output:number;total_sessions:number;total_estimated_cost:number}}
function object(value:unknown):Record<string,unknown>{if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Invalid runtime contract');return value as Record<string,unknown>}
function text(value:unknown):string{if(typeof value!=='string')throw new Error('Invalid runtime text');return value}
function bool(value:unknown):boolean{if(typeof value!=='boolean')throw new Error('Invalid runtime flag');return value}
function count(value:unknown):number{if(typeof value!=='number'||!Number.isFinite(value)||value<0)throw new Error('Invalid runtime count');return value}
function list(value:unknown):unknown[]{if(!Array.isArray(value)||value.length>1000)throw new Error('Invalid runtime list');return value}
async function read(path:string,params?:Record<string,string|number>):Promise<unknown>{const {data}=await api.get('/admin/orchestration/runtime/'+path,...(params?[{params}]:[]));const row=data&&typeof data==='object'&&!Array.isArray(data)?data:null;if(row&&'success' in row){if(row.success!==true)throw new Error('Runtime unavailable');return row.data}return data}
function provenance(r:Record<string,unknown>):Inventory {
if(r.provenance===undefined)return {};
const p=object(r.provenance);
if(p.source!=='snapshot'||p.liveProcess!=='unknown'||typeof p.capturedAt!=='string'||!p.capturedAt.endsWith('Z')||!Number.isFinite(Date.parse(p.capturedAt))||Date.parse(p.capturedAt)>Date.now()||typeof p.ageSeconds!=='number'||!Number.isInteger(p.ageSeconds)||p.ageSeconds<0||!['fresh','stale'].includes(String(p.freshness)))throw new Error('Invalid snapshot provenance');
return {provenance:{source:'snapshot',capturedAt:p.capturedAt,ageSeconds:p.ageSeconds,freshness:p.freshness as 'fresh'|'stale',liveProcess:'unknown'}};
}
export const runtime={
async health():Promise<RuntimeHealth>{const r=object(await read('health'));if(r.auth_required!==true)throw new Error('Authenticated runtime required');return {...provenance(r),ok:bool(r.ok),version:text(r.version),commit:text(r.commit),auth_required:true}},
async profiles():Promise<RuntimeProfile[]>{return list(await read('profiles')).map(value=>{const r=object(value);return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const}:{}),name:text(r.name),is_default:bool(r.is_default),gateway_running:bool(r.gateway_running)}})},
async status(profile:string):Promise<RuntimeStatus>{const r=object(await read('status',{profile}));return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const,liveActiveAgents:null}:{}),version:text(r.version),gateway_running:bool(r.gateway_running),overall:text(r.overall),active_agents:count(r.active_agents),gateway_state:r.gateway_state===null?null:text(r.gateway_state)}},
async sessions(profile:string,offset=0):Promise<RuntimeSessions>{const r=object(await read('sessions',{profile,limit:20,offset}));return {...provenance(r),total:count(r.total),sessions:list(r.sessions).map(value=>{const s=object(value);if(s.profile!==profile)throw new Error('Runtime profile mismatch');return {id:text(s.id),profile:text(s.profile),source:text(s.source),is_active:bool(s.is_active)}})}},
async usage(profile:string):Promise<RuntimeUsage>{const r=object(await read('usage',{profile,days:30}));const t=object(r.totals);return {...provenance(r),period_days:count(r.period_days),totals:{total_input:count(t.total_input),total_output:count(t.total_output),total_sessions:count(t.total_sessions),total_estimated_cost:count(t.total_estimated_cost)}}},
};