import { beforeEach,afterEach,expect,it,vi } from 'vitest' import { mount,flushPromises } from '@vue/test-utils' import ElementPlus, { ElMessageBox } from 'element-plus' import Detail from '@/views/kpi/assessment/index.vue' import Workspace from '@/components/Kpi/KpiWorkspace.vue' const testState=vi.hoisted(()=>({route:{name:'KpiAssessment',path:'/kpi/assessment/10',params:{id:'10'},query:{from:'mine'}},push:vi.fn(),leave:null,manager:false,form:null,periods:[],people:[]})) const api=vi.hoisted(()=>Object.fromEntries(['kpiCapabilities','listKpiPeriods','createKpiPeriod','setKpiPeriodState','kpiUserOptions','assignKpiUsers','listKpiAssessments','exportKpi','getKpiAssessment','saveKpiAssessment','reopenKpiAssessment','confirmKpiAssessment'].map(key=>[key,vi.fn()]))) vi.mock('@/api/kpi',()=>api) vi.mock('@/store/modules/user',()=>({default:()=>({id:42})})) vi.mock('vue-router',()=>({useRoute:()=>testState.route,useRouter:()=>({push:testState.push,replace:vi.fn(async route=>{testState.route.query=route.query||{}})}),onBeforeRouteLeave:fn=>{testState.leave=fn},onBeforeRouteUpdate:()=>{}})) vi.mock('file-saver',()=>({saveAs:vi.fn()})) vi.mock('element-plus',async original=>({...await original(),ElMessage:{warning:vi.fn(),error:vi.fn(),success:vi.fn()},ElMessageBox:{confirm:vi.fn(()=>Promise.resolve('confirm'))}})) const mounted=[] function render(component,props={}){const wrapper=mount(component,{props,attachTo:document.body,global:{plugins:[ElementPlus],stubs:{KpiProjectSelect:{template:'
'}},directives:{loading:()=>{}}}});mounted.push(wrapper);return wrapper} function button(wrapper,name){return wrapper.findAll('button').find(button=>button.text()===name)} beforeEach(()=>{ vi.clearAllMocks();localStorage.clear();testState.manager=false;testState.route={name:'KpiAssessment',path:'/kpi/assessment/10',params:{id:'10'},query:{from:'mine'}} testState.form={id:10,userId:42,periodId:7,periodName:'2026年第4季度KPI',employeeName:'测试员工',account:'test-user',deptName:'研发',email:'test@example.com',status:'DRAFT',phase:'PLANNING',workflowState:'PLANNING',closed:0,version:1,items:[{category:'重点专项工作',name:'研发工作',description:'原描述',weight:15,target:'完成目标',metrics:'完成标准',standardGroup:'',score:null,sources:[]}]} testState.periods=[{id:7,name:'2026年第4季度KPI',year:2026,quarter:4,phase:'PLANNING',workflowState:'PLANNING',version:1,closed:0,assessmentId:10,status:'DRAFT',assignedCount:2,submittedCount:0}] testState.people=[{id:10,userId:42,employeeName:'测试员工',account:'test-user',deptName:'研发',status:'DRAFT',version:1}] api.kpiCapabilities.mockImplementation(async()=>({data:{manage:testState.manager,categories:['重点专项工作','扣分项指标']}})) api.getKpiAssessment.mockImplementation(async()=>({data:structuredClone(testState.form)})) api.listKpiPeriods.mockImplementation(async()=>({data:structuredClone(testState.periods)})) api.listKpiAssessments.mockImplementation(async()=>({data:structuredClone(testState.people)})) api.saveKpiAssessment.mockImplementation(async(id,data)=>({data:{...structuredClone(testState.form),...JSON.parse(JSON.stringify(data)),version:2}})) api.confirmKpiAssessment.mockImplementation(async(id,version,phase)=>({data:{...structuredClone(testState.form),status:'SUBMITTED',version:version+1,phase}})) api.kpiUserOptions.mockResolvedValue({data:[]});api.assignKpiUsers.mockResolvedValue({data:{created:1,existing:0}}) api.reopenKpiAssessment.mockResolvedValue({code:200});api.setKpiPeriodState.mockResolvedValue({code:200}) }) afterEach(()=>{mounted.splice(0).forEach(wrapper=>wrapper.unmount());localStorage.clear()}) it('personal editors expose only their own form, never administrator export or scoring controls',async()=>{ const wrapper=render(Detail);await flushPromises() expect(wrapper.text()).toContain('测试员工 · 2026年第4季度KPI');expect(wrapper.find('[aria-label="关键业绩指标名称"]').exists()).toBe(true) expect(button(wrapper,'导出Excel')).toBeUndefined();expect(wrapper.find('input[aria-label="考核项得分"]').exists()).toBe(false) await wrapper.find('[aria-label="关键业绩指标名称"]').setValue('修改后的目标') await button(wrapper,'保存草稿').trigger('click');await flushPromises() expect(api.saveKpiAssessment).toHaveBeenCalledWith(10,expect.objectContaining({version:1,submit:false,items:[expect.objectContaining({name:'修改后的目标',score:null})]})) expect(api.saveKpiAssessment.mock.calls[0][1].items[0]._key).toBeUndefined() }) it('submitted and scored forms are read-only to the employee and a zero score stays visible',async()=>{ testState.form.status='SCORED';testState.form.phase='REVIEW';testState.form.workflowState='REVIEW';testState.form.items[0].score=0 const wrapper=render(Detail);await flushPromises() expect(wrapper.text()).toContain('已评分');expect(wrapper.find('[aria-label="关键业绩指标名称"]').attributes('disabled')).toBeDefined() expect(button(wrapper,'保存草稿')).toBeUndefined();expect(button(wrapper,'退回填写')).toBeUndefined();expect(wrapper.text()).toContain('管理员评分合计 0') }) it('save failure preserves the typed content and the leaving guard retains a user-scoped local draft',async()=>{ const wrapper=render(Detail);await flushPromises() await wrapper.find('[aria-label="关键业绩指标名称"]').setValue('不能丢失的目标') api.saveKpiAssessment.mockRejectedValueOnce(new Error('version conflict')) await button(wrapper,'保存草稿').trigger('click');await flushPromises() expect(wrapper.find('[aria-label="关键业绩指标名称"]').element.value).toBe('不能丢失的目标') expect(await testState.leave()).toBe(true) const draft=JSON.parse(localStorage.getItem('kpi-draft:42:10:PLANNING'));expect(draft.items[0].name).toBe('不能丢失的目标');expect(draft.version).toBe(1) }) it('a KPI administrator can score and explicitly return a scored form for employee revision',async()=>{ testState.manager=true;testState.form.status='SCORED';testState.form.phase='REVIEW';testState.form.workflowState='REVIEW';testState.form.items[0].score=10 const wrapper=render(Detail);await flushPromises() expect(wrapper.find('input[aria-label="考核项得分"]').exists()).toBe(true) await button(wrapper,'退回填写').trigger('click');await flushPromises() expect(api.reopenKpiAssessment).toHaveBeenCalledWith(10,1,'REVIEW') }) it('ordinary users opening the management URL cannot load other employees or create periods',async()=>{ testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{}} const wrapper=render(Workspace,{manage:true});await flushPromises() expect(wrapper.text()).toContain('由KPI管理员协助办理');expect(api.listKpiPeriods).not.toHaveBeenCalled();expect(button(wrapper,'创建KPI')).toBeUndefined() }) it('my KPI cards navigate directly to the assigned assessment instead of an unrestricted personnel list',async()=>{ testState.route={name:'KpiMine',path:'/kpi/mine',params:{},query:{}} const wrapper=render(Workspace);await flushPromises() await wrapper.find('.kpi-period').trigger('click');await flushPromises() expect(api.listKpiPeriods).toHaveBeenCalledWith(false);expect(testState.push).toHaveBeenCalledWith({path:'/kpi/assessment/10',query:{from:'mine'}}) expect(api.listKpiAssessments).not.toHaveBeenCalled() }) it('management retains the chosen period on return from a personal form and does not expose account secrets',async()=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} const wrapper=render(Workspace,{manage:true});await flushPromises() expect(wrapper.text()).toContain('测试员工');expect(api.listKpiAssessments).toHaveBeenCalledWith(7) await button(wrapper,'分配人员').trigger('click');await flushPromises() expect(api.kpiUserOptions).toHaveBeenCalledWith('');expect(wrapper.text()).toContain('不会重复创建或覆盖内容') }) it('planning hides all three evaluation columns even for administrators',async()=>{ testState.manager=true const wrapper=render(Detail);await flushPromises() expect(wrapper.find('[aria-label="完成情况"]').exists()).toBe(false) expect(wrapper.find('[aria-label="个人自评得分"]').exists()).toBe(false) expect(wrapper.find('[aria-label="考核项得分"]').exists()).toBe(false) expect(button(wrapper,'确认期初')).toBeDefined() }) it('review locks goals and lets employees complete and self-score without editing the administrator score',async()=>{ testState.form.phase='REVIEW';testState.form.workflowState='REVIEW' const wrapper=render(Detail);await flushPromises() expect(wrapper.find('[aria-label="关键业绩指标名称"]').attributes('disabled')).toBeDefined() expect(wrapper.find('[aria-label="完成情况"]').attributes('disabled')).toBeUndefined() expect(wrapper.find('[aria-label="考核项得分"]').exists()).toBe(false) await wrapper.find('[aria-label="完成情况"]').setValue('已完成目标') await wrapper.find('[aria-label="个人自评得分"]').setValue('0') await button(wrapper,'确认期末').trigger('click');await flushPromises() expect(api.saveKpiAssessment).toHaveBeenCalledWith(10,expect.objectContaining({phase:'REVIEW',submit:false,items:[expect.objectContaining({completion:'已完成目标',selfScore:'0',name:'研发工作',score:null})]})) expect(api.confirmKpiAssessment).toHaveBeenCalledExactlyOnceWith(10,2,'REVIEW') }) it('only managers can switch the cycle into review, preserving the optimistic period version',async()=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} testState.periods[0].workflowState='PLANNING_CONFIRMED' const wrapper=render(Workspace,{manage:true});await flushPromises() await button(wrapper,'开始期末').trigger('click');await flushPromises() expect(api.setKpiPeriodState).toHaveBeenCalledWith(7,{version:1,state:'REVIEW'}) }) it.each([ ['CREATED','开始期初',true], ['PLANNING','确认期初',true], ['PLANNING_CONFIRMED','开始期末',false], ['REVIEW','确认期末',false], ['REVIEW_CONFIRMED','结束考核',false], ['ENDED',null,false] ])('the %s cycle shows only its valid next action',async(state,label,assignable)=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} testState.periods[0].workflowState=state;testState.periods[0].closed=state==='ENDED'?1:0;testState.people[0].status='SUBMITTED' const wrapper=render(Workspace,{manage:true});await flushPromises() for(const action of ['开始期初','确认期初','开始期末','确认期末','结束考核'])expect(!!button(wrapper,action)).toBe(action===label) expect(!!button(wrapper,'分配人员')).toBe(assignable) expect(button(wrapper,'返回目标填报')).toBeUndefined();expect(button(wrapper,'重新开放')).toBeUndefined() }) it('personal progress never blocks manager transitions, even for an empty period',async()=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} const wrapper=render(Workspace,{manage:true});await flushPromises() expect(button(wrapper,'确认期初').attributes('disabled')).toBeUndefined() await button(wrapper,'确认期初').trigger('click');await flushPromises() expect(api.setKpiPeriodState).toHaveBeenCalledWith(7,{version:1,state:'PLANNING_CONFIRMED'}) wrapper.unmount();mounted.splice(mounted.indexOf(wrapper),1) testState.periods[0].workflowState='CREATED';testState.people=[] const empty=render(Workspace,{manage:true});await flushPromises() expect(empty.text()).toContain('还没有参与人员');expect(button(empty,'开始期初').attributes('disabled')).toBeUndefined() expect(empty.find('.kpi-empty').exists()).toBe(true) }) it('after review confirmation only administrators can maintain content, and ending makes everyone read-only',async()=>{ testState.form.phase='REVIEW';testState.form.workflowState='REVIEW_CONFIRMED';testState.form.status='SUBMITTED';testState.manager=true const admin=render(Detail);await flushPromises() expect(admin.find('[aria-label="完成情况"]').attributes('disabled')).toBeUndefined() expect(admin.find('[aria-label="关键业绩指标名称"]').attributes('disabled')).toBeDefined() expect(button(admin,'退回填写')).toBeUndefined() admin.unmount();mounted.splice(mounted.indexOf(admin),1) testState.manager=false const own=render(Detail);await flushPromises() expect(own.find('[aria-label="完成情况"]').attributes('disabled')).toBeDefined();expect(button(own,'保存修改')).toBeUndefined() own.unmount();mounted.splice(mounted.indexOf(own),1) testState.manager=true;testState.form.workflowState='ENDED';testState.form.closed=1 const ended=render(Detail);await flushPromises() expect(ended.find('[aria-label="完成情况"]').attributes('disabled')).toBeDefined();expect(button(ended,'保存修改')).toBeUndefined() }) it('before starting a new period an empty personal KPI is deliberately read-only with a helpful waiting state',async()=>{ testState.manager=true;testState.form.workflowState='CREATED';testState.form.items=[] const wrapper=render(Detail);await flushPromises() expect(wrapper.text()).toContain('等待开始期初');expect(button(wrapper,'新增考核项')).toBeUndefined();expect(button(wrapper,'确认期初')).toBeUndefined() expect(wrapper.find('.kpi-empty').exists()).toBe(true) }) it('the assignment view shows distinct untouched, partial and confirmed progress and allows inspecting everyone',async()=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} testState.people=[ {...testState.people[0],progress:'NOT_STARTED',itemCount:0,filledCount:0}, {id:11,userId:43,employeeName:'填写中的员工',account:'partial',status:'DRAFT',progress:'IN_PROGRESS',itemCount:2,filledCount:1}, {id:12,userId:44,employeeName:'已确认员工',account:'confirmed',status:'SUBMITTED',progress:'CONFIRMED',itemCount:2,filledCount:2} ] api.kpiUserOptions.mockResolvedValue({data:[{id:42,name:'测试员工',account:'test-user'}]}) const wrapper=render(Workspace,{manage:true});await flushPromises() expect(wrapper.text()).toContain('已填 1 项目标') await wrapper.findAll('.kpi-list-tabs button').find(b=>b.text().startsWith('未填写')).trigger('click');await flushPromises() expect(wrapper.find('.kpi-people-table').text()).toContain('测试员工');expect(wrapper.find('.kpi-people-table').text()).not.toContain('填写中的员工') await button(wrapper,'分配人员').trigger('click');await flushPromises() expect(document.body.textContent).toContain('已分配 · 未填写') }) it.each(['CREATED','PLANNING','PLANNING_CONFIRMED','REVIEW','REVIEW_CONFIRMED','ENDED'])('the %s page never exposes ad hoc notification buttons',async state=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} testState.periods[0].workflowState=state const wrapper=render(Workspace,{manage:true});await flushPromises() expect(wrapper.text()).not.toContain('提醒待确认人员');expect(button(wrapper,'提醒')).toBeUndefined() expect(api.setKpiPeriodState).not.toHaveBeenCalled() }) it.each([['CREATED','开始期初','PLANNING'],['PLANNING_CONFIRMED','开始期末','REVIEW']])('starting from %s announces automatic notifications and advances once',async(state,label,target)=>{ testState.manager=true;testState.route={name:'KpiManage',path:'/kpi/manage',params:{},query:{periodId:'7'}} testState.periods[0].workflowState=state const wrapper=render(Workspace,{manage:true});await flushPromises() await button(wrapper,label).trigger('click');await flushPromises() expect(ElMessageBox.confirm).toHaveBeenCalledWith(expect.stringContaining('站内消息'),label,expect.anything()) expect(api.setKpiPeriodState).toHaveBeenCalledExactlyOnceWith(7,{version:1,state:target}) }) it.each(['PLANNING','REVIEW'])('saving complete %s content remains editable and never confirms automatically',async phase=>{ testState.form.phase=phase;testState.form.workflowState=phase testState.form.items[0].completion=phase==='REVIEW'?'全部完成':'';testState.form.items[0].selfScore=phase==='REVIEW'?0:null const wrapper=render(Detail);await flushPromises() const field=phase==='REVIEW'?'完成情况':'关键业绩指标名称' await wrapper.find('[aria-label="'+field+'"]').setValue('完整填写的内容') await button(wrapper,'保存草稿').trigger('click');await flushPromises() expect(api.saveKpiAssessment).toHaveBeenCalledWith(10,expect.objectContaining({submit:false})) expect(api.confirmKpiAssessment).not.toHaveBeenCalled() expect(button(wrapper,phase==='REVIEW'?'确认期末':'确认期初')).toBeDefined() expect(wrapper.find('[aria-label="'+field+'"]').attributes('disabled')).toBeUndefined() }) it('confirming an already saved draft uses the separate confirmation action without saving it again',async()=>{ const wrapper=render(Detail);await flushPromises() expect(api.confirmKpiAssessment).not.toHaveBeenCalled() await button(wrapper,'确认期初').trigger('click');await flushPromises() expect(api.saveKpiAssessment).not.toHaveBeenCalled();expect(api.confirmKpiAssessment).toHaveBeenCalledExactlyOnceWith(10,1,'PLANNING') expect(button(wrapper,'保存草稿')).toBeUndefined() }) it('cancelling personal confirmation leaves the draft and backend unchanged',async()=>{ const wrapper=render(Detail);await flushPromises() ElMessageBox.confirm.mockRejectedValueOnce('cancel') await button(wrapper,'确认期初').trigger('click');await flushPromises() expect(api.saveKpiAssessment).not.toHaveBeenCalled();expect(api.confirmKpiAssessment).not.toHaveBeenCalled() expect(button(wrapper,'确认期初')).toBeDefined() }) it('a manager maintaining someone else can save but cannot confirm on their behalf',async()=>{ testState.manager=true;testState.form.userId=43 const wrapper=render(Detail);await flushPromises() await wrapper.find('[aria-label="关键业绩指标名称"]').setValue('管理员协助维护') await button(wrapper,'保存草稿').trigger('click');await flushPromises() expect(api.saveKpiAssessment).toHaveBeenCalledWith(10,expect.objectContaining({submit:false})) expect(button(wrapper,'确认期初')).toBeUndefined();expect(api.confirmKpiAssessment).not.toHaveBeenCalled() }) it('a failed confirmation keeps the successfully saved draft unconfirmed and editable',async()=>{ const wrapper=render(Detail);await flushPromises() await wrapper.find('[aria-label="关键业绩指标名称"]').setValue('确认失败也不丢失的目标') api.confirmKpiAssessment.mockRejectedValueOnce(new Error('confirmation interrupted')) await button(wrapper,'确认期初').trigger('click');await flushPromises() expect(api.saveKpiAssessment).toHaveBeenCalledTimes(1);expect(api.confirmKpiAssessment).toHaveBeenCalledWith(10,2,'PLANNING') expect(wrapper.find('[aria-label="关键业绩指标名称"]').element.value).toBe('确认失败也不丢失的目标') expect(wrapper.find('[aria-label="关键业绩指标名称"]').attributes('disabled')).toBeUndefined() expect(button(wrapper,'确认期初')).toBeDefined() })