fix(admin): open fresh card decisions in confirmation dialog

This commit is contained in:
devops committed 2026-10-24 05:24:13 +00:00
1 parent 3321bac22d
commit 173e8ce6b1
3 files changed
+79 -9

No files matched your search

@@ -1,4 +1,4 @@
import { render, screen, fireEvent, within } from '@testing-library/react';
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';
@@ -127,6 +127,57 @@ it('shows advertised decisions directly on pending card and labels reservation n
expect(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'})).toBeEnabled();
expect(within(card).getByText('رزرو آزمایشی؛ هزینه واقعی نامشخص')).toBeInTheDocument();
fireEvent.click(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'}));
expect(await screen.findByRole('region',{name:'جزئیات وظیفه'})).toBeInTheDocument();
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();
});
@@ -18,6 +18,7 @@ export default function OrchestrationCommandCenter() {
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('');
@@ -43,8 +44,24 @@ export default function OrchestrationCommandCenter() {
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;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 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('');
@@ -53,13 +70,13 @@ export default function OrchestrationCommandCenter() {
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
};
const refresh=()=>{detailEpoch.current++;setSelected(null);setPending(null);void loadTasks()};
const refresh=()=>{detailEpoch.current++;setDecisionLoading(false);setSelected(null);setPending(null);void loadTasks()};
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
return <div 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={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
<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&&<p role="status">در حال دریافت وضعیت از سرور…</p>}
{(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()}/>}
@@ -67,7 +84,7 @@ export default function OrchestrationCommandCenter() {
<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'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(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.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 select(t)}>{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>)}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(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.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.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>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>
@@ -17,14 +17,16 @@ it('opens with obvious pending and held owner queue, scope, criteria and budget;
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:'کار نگه‌داشته'}));
expect(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
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}));
fireEvent.click(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'}));
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:'بررسی بودجه'}});