diff --git a/backend/src/orchestration/orchestration.domain.ts b/backend/src/orchestration/orchestration.domain.ts index e395060b..95d0146b 100644 --- a/backend/src/orchestration/orchestration.domain.ts +++ b/backend/src/orchestration/orchestration.domain.ts @@ -3,6 +3,7 @@ import { BadRequestException } from '@nestjs/common'; export enum WorkflowState { DRAFT = 'DRAFT', GATE1_PENDING = 'GATE1_PENDING', + GATE1_HELD = 'GATE1_HELD', GATE1_APPROVED = 'GATE1_APPROVED', READY = 'READY', CLAIMED = 'CLAIMED', @@ -43,7 +44,9 @@ export enum KillSwitchLevel { const transitions: Record = { DRAFT: [WorkflowState.GATE1_PENDING, WorkflowState.CANCELLED], + GATE1_HELD: [WorkflowState.GATE1_APPROVED, WorkflowState.REJECTED], GATE1_PENDING: [ + WorkflowState.GATE1_HELD, WorkflowState.GATE1_APPROVED, WorkflowState.REJECTED, WorkflowState.EXPIRED, diff --git a/backend/src/orchestration/owner-decisions.spec.ts b/backend/src/orchestration/owner-decisions.spec.ts new file mode 100644 index 00000000..7e65c914 --- /dev/null +++ b/backend/src/orchestration/owner-decisions.spec.ts @@ -0,0 +1,48 @@ +import { PrepareWorkflowService } from './prepare-workflow.service'; + +describe('owner Gate1 hold operation', () => { + const reviewer={id:'reviewer',role:'SUPER_ADMIN'}; + let task:any, tx:any, service:PrepareWorkflowService; + beforeEach(()=>{ + task={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'proposer'}}; + tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>task),update:jest.fn(async({data}:any)=>(task={...task,state:data.state,version:task.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{create:jest.fn()}}; + service=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)}, {workerIds:[],stageCiIds:[]}); + }); + const hold={toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold-t',reason:'Need revised budget'}; + it('advertises hold only to independent owner reviewer',()=>{ + expect(service.project(task,reviewer).availableActions).toContain('HOLD_GATE1'); + expect(service.project(task,{id:'proposer',role:'SUPER_ADMIN'}).availableActions).not.toContain('HOLD_GATE1'); + }); + it('persists hold with actor, immutable reason and version without approval or queueing',async()=>{ + await expect(service.transition('t',hold,reviewer)).resolves.toMatchObject({state:'GATE1_HELD',version:3}); + expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:'reviewer',fromState:'GATE1_PENDING',toState:'GATE1_HELD',eventType:'PREPARE_GATE1_HELD',idempotencyKey:'hold-t',payload:expect.objectContaining({fingerprint:expect.stringContaining('Need revised budget')})})}); + expect(tx.orchestrationApprovalDecision.create).not.toHaveBeenCalled(); + expect(service.project(task,reviewer).availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1']); + }); + it.each([{id:'proposer',role:'SUPER_ADMIN'},{id:'other',role:'Admin'}])('denies unauthorized hold %j',async actor=>{ + await expect(service.transition('t',hold,actor)).rejects.toMatchObject({status:403}); + expect(tx.orchestrationTask.update).not.toHaveBeenCalled(); + }); + it.each(['DRAFT','READY','GATE1_APPROVED','GATE2_PENDING'])('denies hold from %s',async state=>{ + task.state=state; + await expect(service.transition('t',hold,reviewer)).rejects.toMatchObject({status:403}); + expect(tx.orchestrationTask.update).not.toHaveBeenCalled(); + }); + it('rejects missing reason and stale version without writes',async()=>{ + await expect(service.transition('t',{...hold,reason:' '},reviewer)).rejects.toMatchObject({status:400}); + await expect(service.transition('t',{...hold,expectedVersion:1},reviewer)).rejects.toMatchObject({status:409}); + expect(tx.orchestrationTask.update).not.toHaveBeenCalled(); + }); + it('replays identical hold, rejects changed payload',async()=>{ + await service.transition('t',hold,reviewer); + const event=tx.orchestrationEvent.create.mock.calls[0][0].data; + tx.orchestrationEvent.findUnique.mockResolvedValue(event); + await service.transition('t',hold,reviewer); + expect(tx.orchestrationTask.update).toHaveBeenCalledTimes(1); + await expect(service.transition('t',{...hold,reason:'changed'},reviewer)).rejects.toMatchObject({status:409}); + }); + it.each(['APPROVED','REJECTED'])('decides held proposal via existing Gate1 command: %s',async decision=>{ + task.state='GATE1_HELD'; + await expect(service.decide('t',1,{decision,expectedVersion:2,idempotencyKey:'decision',expiresAt:new Date(Date.now()+60000).toISOString()},reviewer)).resolves.toMatchObject({state:decision==='APPROVED'?'GATE1_APPROVED':'REJECTED'}); + }); +}); diff --git a/backend/src/orchestration/prepare-workflow.http.spec.ts b/backend/src/orchestration/prepare-workflow.http.spec.ts index 9e29998c..5fa16b40 100644 --- a/backend/src/orchestration/prepare-workflow.http.spec.ts +++ b/backend/src/orchestration/prepare-workflow.http.spec.ts @@ -108,6 +108,12 @@ describe('bounded workflow HTTP contracts', () => { idempotencyKey: 'submit', }) .expect(200); + await request(app.getHttpServer()) + .put('/admin/orchestration/tasks/t/transition') + .set('Authorization', 'SUPER_ADMIN') + .send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'}) + .expect(200); + expect(workflow.transition).toHaveBeenCalledWith('t', expect.objectContaining({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'}), {id:'verified-subject',role:'SUPER_ADMIN'}); await request(app.getHttpServer()) .post('/admin/orchestration/tasks/t/gates/1/decide') .set('Authorization', 'SUPER_ADMIN') diff --git a/backend/src/orchestration/prepare-workflow.service.ts b/backend/src/orchestration/prepare-workflow.service.ts index 046d8f76..7c25d7e8 100644 --- a/backend/src/orchestration/prepare-workflow.service.ts +++ b/backend/src/orchestration/prepare-workflow.service.ts @@ -198,6 +198,13 @@ export class PrepareWorkflowService { const fingerprint = JSON.stringify({ id, dto, a }); if (await this.replay(tx, dto.idempotencyKey, fingerprint)) return t; this.version(t, dto); + if (dto.toState === 'GATE1_HELD') { + if (a.role !== 'SUPER_ADMIN' || t.metadata.createdBy === a.id || t.state !== 'GATE1_PENDING') + throw new ForbiddenException('Independent Gate1 reviewer and pending proposal required'); + if (typeof dto.reason !== 'string' || !dto.reason.trim() || dto.reason.length > 2000) + throw new BadRequestException('Hold requires reason of 1..2000 characters'); + return this.event(tx, t, 'GATE1_HELD', a, dto.idempotencyKey, 'PREPARE_GATE1_HELD', fingerprint); + } if (t.metadata.createdBy !== a.id && a.role !== 'SUPER_ADMIN') throw new ForbiddenException('Proposal owner required'); if ( @@ -252,7 +259,7 @@ export class PrepareWorkflowService { this.version(t, dto); if (t.metadata.createdBy === a.id) throw new ForbiddenException('Independent reviewer required'); - if (t.state !== 'GATE1_PENDING') + if (!['GATE1_PENDING', 'GATE1_HELD'].includes(t.state)) throw new ConflictException('Gate1 pending required'); await tx.orchestrationApprovalDecision.create({ data: { @@ -538,9 +545,11 @@ export class PrepareWorkflowService { safe && a?.role === 'SUPER_ADMIN' && t.metadata?.createdBy !== a.id && - t.state === 'GATE1_PENDING' - ) + ['GATE1_PENDING', 'GATE1_HELD'].includes(t.state) + ) { actions.push('APPROVE_GATE1', 'REJECT_GATE1'); + if (t.state === 'GATE1_PENDING') actions.push('HOLD_GATE1'); + } return { ...t, metadata: safe diff --git a/backend/src/orchestration/workflow-db.spec.ts b/backend/src/orchestration/workflow-db.spec.ts index b5a04c52..33f5096f 100644 --- a/backend/src/orchestration/workflow-db.spec.ts +++ b/backend/src/orchestration/workflow-db.spec.ts @@ -69,6 +69,28 @@ const enabled = process.env.WORKFLOW_DB === '1'; afterAll(async () => { await db.$disconnect(); }); + it('serializes competing owner holds and preserves audited reason, then decides held task', async () => { + let t = await service.create(dto(), admin); + t = await service.transition(t.id, {toState:'GATE1_PENDING',expectedVersion:t.version,idempotencyKey:`submit-hold-${t.id}`}, admin); + const command = {toState:'GATE1_HELD',expectedVersion:t.version,idempotencyKey:`hold-${t.id}`,reason:'Need source review'}; + const results = await Promise.allSettled([ + service.transition(t.id, command, reviewer), + service.transition(t.id, {...command,idempotencyKey:`competing-${t.id}`}, reviewer), + ]); + expect(results.filter(r=>r.status==='fulfilled')).toHaveLength(1); + const held = await db.orchestrationTask.findUniqueOrThrow({where:{id:t.id}}); + expect(held.state).toBe('GATE1_HELD'); + expect(held.version).toBe(t.version+1); + const events = await db.orchestrationEvent.findMany({where:{taskId:t.id,eventType:'PREPARE_GATE1_HELD'}}); + expect(events).toHaveLength(1); + expect(events[0].actorId).toBe(reviewer.id); + expect(JSON.stringify(events[0].payload)).toContain('Need source review'); + expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(0); + expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(0); + await expect(service.transition(t.id, {...command,expectedVersion:held.version,reason:'changed'},reviewer)).rejects.toMatchObject({status:409}); + const decision = await service.decide(t.id,1,{decision:'REJECTED',expectedVersion:held.version,idempotencyKey:`decline-held-${t.id}`,expiresAt:new Date(Date.now()+60000).toISOString()},reviewer); + expect(decision.state).toBe('REJECTED'); + }); it('persists and projects immutable bounded proposal scope without arbitrary metadata', async () => { const input = dto(); const t = await service.create(input, admin); diff --git a/frontend/admin-panel/src/components/OrchestrationPresentation.tsx b/frontend/admin-panel/src/components/OrchestrationPresentation.tsx index 3d22c5ed..0b84f8fc 100644 --- a/frontend/admin-panel/src/components/OrchestrationPresentation.tsx +++ b/frontend/admin-panel/src/components/OrchestrationPresentation.tsx @@ -1,7 +1,7 @@ import type {ServerAction} from '../services/orchestration'; -const labels:Record={DRAFT:'پیش‌نویس',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:'تطبیق بودجه'}; +const labels:Record={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)=>({SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صف‌بندی آماده‌سازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور')); +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 نامشخص — گزارش نشده; if(Array.isArray(value))return value.length?
{value.map((item,index)=>
)}
:

رکوردی ثبت نشده است.

; diff --git a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx index 68193d0c..1c96e25d 100644 --- a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx +++ b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx @@ -14,7 +14,8 @@ describe('command center', () => { it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => { render(); fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'})); - expect(await screen.findByText(/Only staging/)).toBeInTheDocument(); + 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:'عامل‌ها و دپارتمان‌ها'})); diff --git a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx index 0c0eb30a..0a8fef67 100644 --- a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx +++ b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx @@ -21,6 +21,7 @@ export default function OrchestrationCommandCenter() { const [snapshot,setSnapshot]=useState(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); @@ -62,10 +63,16 @@ export default function OrchestrationCommandCenter() { {error&&

دریافت اطلاعات از سرور ناموفق بود: {error}. داده جایگزین نمایش داده نمی‌شود.

} {success&&

{success}

} {section==='وظیفه‌ها و تأییدها'&&capabilities.mutations&&void loadTasks()}/>} + {section==='نمای کلی'&&
+

منتظر تصمیم شما

تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. اقدام‌ها پس از دریافت جزئیات از سرور نمایش داده می‌شوند.

+ + {!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&

تصمیمی در این فیلتر منتظر نیست.

} + {!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=>

{label(t.department)} · {label(t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت

{selected?.id!==t.id&&<>

محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}

معیارهای پذیرش

{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?
    {(t.metadata.acceptanceCriteria as string[]).map((c,i)=>
  • {c}
  • )}
:

گزارش نشده؛ جزئیات را بررسی کنید

}}
)} +
} {section==='نمای کلی'&&!loading&&!error&&

فهرست وظیفه‌های ثبت‌شده

{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.

{[...new Set(tasks.map(t=>t.state))].map(state=>{label(state)}: {tasks.filter(t=>t.state===state).length})}
} {(['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها'] as Section[]).includes(section)&&
{!loading&&!error&&!tasks.length&&

وظیفه‌ای از سرور دریافت نشد.

} -
{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=>)}{filtered.map(t=>)}
{h}
{label(t.department)}{label(t.state)}{label(t.operationMode)}{t.budgetLimitCents??'نامشخص'}{t.version}
+
{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=>)}{filtered.filter(t=>section!=='نمای کلی'||!['GATE1_PENDING','GATE1_HELD'].includes(t.state)).map(t=>)}
{h}
{label(t.department)}{label(t.state)}{label(t.operationMode)}{t.budgetLimitCents??'نامشخص'}{t.version}
} {selected&&

{selected.title} · v{selected.version}

{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())?

محدوده و معیارهای پذیرش گزارش‌شده از سرور

:

محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.

}

محدوده گردش کار سرور: در نمای امن در دسترس نیست.

اقدام‌های مجاز اعلام‌شده توسط سرور

{!selected.availableActions.length&&

اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.

}
{selected.availableActions.map(a=>)}
diff --git a/frontend/admin-panel/src/pages/OwnerDecisions.test.tsx b/frontend/admin-panel/src/pages/OwnerDecisions.test.tsx new file mode 100644 index 00000000..8f6e1b47 --- /dev/null +++ b/frontend/admin-panel/src/pages/OwnerDecisions.test.tsx @@ -0,0 +1,37 @@ +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(); + 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:'کار نگه‌داشته'})); + expect(await screen.findByRole('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(); + fireEvent.click(await screen.findByRole('button',{name:proposal.title})); + fireEvent.click(await screen.findByRole('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(); +}); diff --git a/frontend/admin-panel/src/services/orchestration.ts b/frontend/admin-panel/src/services/orchestration.ts index 02f92512..e7b4f4f2 100644 --- a/frontend/admin-panel/src/services/orchestration.ts +++ b/frontend/admin-panel/src/services/orchestration.ts @@ -2,6 +2,7 @@ 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 = { + 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'},