import {beforeEach,expect,test,vi} from 'vitest'
import {shallowMount,flushPromises,mount as realMount} from '@vue/test-utils'
import {defineComponent,provide,inject,computed,h,onBeforeUnmount} from 'vue'
import ElementPlus,{ElMessageBox} from 'element-plus'
import Archive from '@/views/archive/index.vue'
import Cost from '@/views/archive/ArchiveCost.vue'
import Files from '@/views/archive/ArchiveFiles.vue'
import ItemStatus from '@/views/archive/ArchiveItemStatus.vue'
import LaborRates from '@/views/archive/ArchiveLaborRates.vue'
import {countDocuments,summary,archiveSubmitIssues,MAX_ARCHIVE_FILE,transferPercent,normalizeCost,costCategories,costSignerFields} from '@/views/archive/archive-model'
import {archiveReference,comparisonRows,comparisonSpan} from '@/views/archive/archive-reference'
const api=vi.hoisted(()=>Object.fromEntries(['archiveMetadata','archiveProjects','archiveDetail','archivePeople','archiveManagers','archiveSave','archiveItem','archiveConfirmItems','archiveCost','archiveCostPeople','archiveLaborRates','archiveLaborRate','archiveState','archiveCatalog','archiveAssign','archiveExport','archiveCostExport','archiveDocument','archiveUpload','archiveRead','archiveRemove','archiveFinal'].map(k=>[k,vi.fn()])))
vi.mock('@/api/archive',()=>api)
const catalog={version:0,items:[{key:'technical',category:'前期',title:'技术方案',required:true}],customerTypes:['高校'],businessCategories:['智能座舱']}
const project={id:21,name:'隔离资料项目',code:'DOC-21',version:3,manager_id:2,manager_name:'经理',archive_state:'EDITING',canEdit:true,canAssign:false,cost:{},items:[],history:[]}
const tableStub=defineComponent({methods:{clearSelection(){}},template:'
'})
const widgetStubs=Object.fromEntries('ElButton ElInput ElFormItem ElForm ElSelect ElOption ElIcon ElCheckbox ElRadioGroup ElRadioButton ElDropdown ElDropdownMenu ElDropdownItem ElPagination ElResult ElDialog ElTag ElProgress ElEmpty ElTabs ElTabPane ElTimeline ElTimelineItem ElSwitch ElInputNumber ElDatePicker'.split(' ').map(k=>[k,true]))
function mount(component,props={}){return shallowMount(component,{props,global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElTable:tableStub,ElTableColumn:true}}})}
beforeEach(()=>{vi.clearAllMocks();api.archiveMetadata.mockResolvedValue({data:{actorId:2,all:false,canCreate:true,canAssign:false,canBeManager:true,catalog}});api.archiveProjects.mockResolvedValue({data:{rows:[],total:0}});api.archiveDetail.mockResolvedValue({data:project});api.archivePeople.mockResolvedValue({data:[]});api.archiveManagers.mockResolvedValue({data:[]});api.archiveCostPeople.mockResolvedValue({data:[{id:2,name:'经理甲',account:'manager',rate:1000}]})})
test('new project defaults its start date, keeps expected end optional and hides actual end until editing',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.editProject();await flushPromises();expect(state.projectForm.startTime).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);expect(state.projectForm.expectedEndTime).toBeNull();const form=w.findAllComponents({name:'ElForm'}).find(f=>f.classes().includes('project-form'));expect(form.findAllComponents({name:'ElFormItem'}).map(f=>f.attributes('label'))).toContain('预计结束时间');expect(form.findAllComponents({name:'ElFormItem'}).map(f=>f.attributes('label'))).not.toContain('结束时间');state.editProject({...project,start_time:'2026-01-01 09:00:00',expected_end_time:null,end_time:'2026-10-01 18:00:00'});await flushPromises();expect(state.projectForm.endTime).toBe('2026-10-01 18:00:00');expect(form.findAllComponents({name:'ElFormItem'}).map(f=>f.attributes('label'))).toContain('结束时间');w.unmount()
})
test('Excel comparison keeps all original labels and merges only the six category ranges',()=>{
expect(archiveReference).toHaveLength(30);expect(new Set(archiveReference.map(i=>i.key)).size).toBe(30)
const spans=archiveReference.map((_,index)=>comparisonSpan(archiveReference,index,1)[0])
expect(spans.filter(Boolean)).toEqual([2,2,6,5,3,12]);expect(spans.reduce((a,b)=>a+b,0)).toBe(30)
for(let row=0;row<30;row++){expect(comparisonSpan(archiveReference,row,0)).toEqual([1,1]);expect(comparisonSpan(archiveReference,row,2)).toEqual([1,1]);expect(comparisonSpan(archiveReference,row,3)).toEqual([1,1])}
expect(archiveReference[2].title).toBe('招标文件/或采购需求SOR')
expect(archiveReference[3].title).toBe('投标文件(签章扫描版)/如无,则提供投标文件最终word版')
expect(archiveReference[4].title).toBe('项目机械设计图/软件架构图/控制逻辑图')
expect(archiveReference[13].title).toBe('发票(跟上游客户)');expect(archiveReference[17].title).toBe('发票(跟下游供应商)等款项支付资料')
expect(archiveReference[18]).toMatchObject({key:'costAnalysis',title:'项目成本分析表'})
const original=[{key:'tender',title:'招标文件或采购需求 SOR',category:'招投标/采购',required:true},{key:'custom',title:'自定义资料',category:'自定义'}]
expect(comparisonRows(original)[0]).toMatchObject({title:'招标文件/或采购需求SOR',category:'② 招投标/采购资料',required:true})
expect(comparisonRows(original)[1]).toEqual(original[1]);expect(original[0].title).toBe('招标文件或采购需求 SOR')
expect(comparisonRows(original,true)).toEqual(original)
expect(comparisonSpan([{category:'A'},{category:'B'},{category:'A'}],2,1)).toEqual([1,1])
})
test('comparison column order is sequence, merged category, original material name, then projects',async()=>{
const table=defineComponent({props:['data','spanMethod'],setup(props,{slots,expose}){provide('archiveTestRows',computed(()=>props.data||[]));expose({clearSelection(){}});return()=>h('div',slots.default?.())}})
const column=defineComponent({props:['label','fixed','align','headerAlign'],setup(props){return()=>h('section',{'data-column':props.label,'data-fixed':props.fixed,'data-align':props.align,'data-header-align':props.headerAlign})}})
api.archiveMetadata.mockResolvedValue({data:{actorId:2,catalog:{...catalog,items:archiveReference}}})
api.archiveProjects.mockResolvedValue({data:{rows:[project],total:1}})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElTable:table,ElTableColumn:column}}});await flushPromises()
w.vm.$.setupState.view='matrix';await flushPromises()
const columns=w.find('.matrix-view').findAll('[data-column]')
expect(columns.map(c=>c.attributes('data-column'))).toEqual(['序号','归档大项','具体资料(小项)','隔离资料项目'])
expect(columns.every(c=>!c.attributes('data-fixed'))).toBe(true)
expect(columns.at(-1).attributes('data-align')).toBe('center');expect(columns.at(-1).attributes('data-header-align')).toBe('center')
const comparison=w.find('.matrix-view').findComponent(table)
expect(comparison.props('spanMethod')({rowIndex:0,columnIndex:1})).toEqual([2,1])
expect(comparison.props('spanMethod')({rowIndex:1,columnIndex:1})).toEqual([0,0])
expect(api.archiveSave).not.toHaveBeenCalled();expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
})
test('independent page loads without importing business projects or collaboration membership',async()=>{
const w=mount(Archive);await flushPromises();expect(api.archiveProjects).toHaveBeenCalledOnce();expect(w.find('.page-heading').exists()).toBe(false);expect(w.find('.list-toolbar .toolbar-actions').text()).toContain('新建资料项目');expect(api.archiveDetail).not.toHaveBeenCalled();w.unmount()
})
test('archived visibility is opt-in, shared by both views, and disabling it resets the archive-only filter and page',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({includeArchived:false,comparison:false,page:1}),expect.any(AbortSignal))
const checkbox=w.get('.include-archived');expect(checkbox.text()).toBe('显示归档项目')
expect(checkbox.findComponent({name:'ElCheckbox'}).exists()||checkbox.element.tagName==='EL-CHECKBOX-STUB').toBe(true)
state.query.customer='高校';state.query.page=4;state.query.includeArchived=true;state.changeArchivedVisibility();await flushPromises()
expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({includeArchived:true,customer:'高校',page:1}),expect.any(AbortSignal))
state.view='matrix';await flushPromises();expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({includeArchived:true,comparison:true}),expect.any(AbortSignal))
state.query.state='ARCHIVED';state.query.page=7;state.query.includeArchived=false;state.changeArchivedVisibility();await flushPromises()
expect(state.query).toMatchObject({includeArchived:false,state:'',page:1,customer:'高校'})
state.query.state='ARCHIVED';state.changeArchiveState();await flushPromises();expect(state.query.includeArchived).toBe(true)
state.reset();await flushPromises();expect(state.query.includeArchived).toBe(false)
state.filterOverview('archived');await flushPromises();expect(state.query).toMatchObject({includeArchived:true,state:'ARCHIVED',page:1})
expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('paged comparisons show total and current-page counts and accept the server-clamped page',async()=>{
api.archiveProjects.mockResolvedValue({data:{rows:[project],total:1001,page:51,size:20,matrix:{[project.id]:[]}}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
expect(state.query.page).toBe(51);expect(w.get('.project-total').text()).toContain('1001 个项目');expect(w.get('.project-total').text()).toContain('本页 1 个')
expect(api.archiveDetail).not.toHaveBeenCalled();expect(api.archiveProjects).toHaveBeenCalledOnce();w.unmount()
})
test('overview shortcuts preserve customer filters and clear only the previous state choice',async()=>{
api.archiveProjects.mockResolvedValue({data:{rows:[],total:0,overview:{total:42,editing:20,review:12,archived:10,missing:18}}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
expect(w.findAll('.overview-card')).toHaveLength(5);expect(w.find('.overview-card.total').text()).toContain('42')
state.query.customer='高校';state.query.page=3;await w.get('.overview-card.review').trigger('click');await flushPromises()
expect(state.query.customer).toBe('高校')
expect(state.query).toMatchObject({customer:'高校',page:1,state:'REVIEW',missing:false});expect(state.activeOverview).toBe('review')
await w.get('.overview-card.missing').trigger('click');await flushPromises();expect(state.query).toMatchObject({customer:'高校',state:'',missing:true});expect(state.activeOverview).toBe('missing')
expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('all five project filters are always visible without a collapse or incomplete-only checkbox',async()=>{
const w=mount(Archive);await flushPromises()
const form=w.get('.project-filters')
expect(form.findAll('el-form-item-stub').map(item=>item.attributes('label')).filter(Boolean)).toEqual(['项目','归档状态','客户类别','业务类别','内外项目'])
expect(form.text()).not.toContain('收起筛选');expect(form.text()).not.toContain('更多筛选');expect(form.text()).not.toContain('仅看必需资料未齐全')
expect(form.findAll('el-checkbox-stub')).toHaveLength(0);expect(form.find('[style*="display: none"]').exists()).toBe(false)
const state=w.vm.$.setupState;state.query.customer='高校';state.query.business='智能座舱';state.query.scope='INTERNAL';state.search();await flushPromises()
expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({customer:'高校',business:'智能座舱',scope:'INTERNAL',page:1}),expect.any(AbortSignal))
state.reset();await flushPromises();expect(state.query).toMatchObject({customer:'',business:'',scope:'',missing:false});w.unmount()
})
test('empty and filtered empty lists have distinct guidance without inventing statistics',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
expect(state.hasFilters).toBe(false);expect(w.get('.overview-card.total').text()).toContain('—')
state.query.keyword='找不到';await flushPromises();expect(state.hasFilters).toBe(true);state.reset();await flushPromises();expect(state.hasFilters).toBe(false);w.unmount()
})
test('project fields have independent columns and the visible cost action opens in one click',async()=>{
const table=defineComponent({props:['data'],setup(props,{slots,expose}){provide('archiveTestRows',computed(()=>props.data||[]));expose({clearSelection(){}});return()=>h('div',slots.default?.())}})
const column=defineComponent({props:['label'],setup(props,{slots}){const rows=inject('archiveTestRows');return()=>h('section',{'data-column':props.label},rows.value.map(row=>slots.default?.({row})))}})
api.archiveProjects.mockResolvedValue({data:{rows:[{...project,item_total:30,item_resolved:0,required_total:21,required_done:0,optional_total:9,optional_done:0}],total:1}})
api.archiveDetail.mockResolvedValue({data:{...project,items:[{id:1,item_key:'costAnalysis',state:'MISSING',applicable:1,category:'交付',documents:[]}]}})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElTable:table,ElTableColumn:column}}});await flushPromises()
const labels=w.findAll('[data-column]').map(e=>e.attributes('data-column'))
expect(labels).toEqual(expect.arrayContaining(['项目名称','项目编号','客户类别','业务类别','内外项目','项目阶段','附件份数','创建时间','最近维护时间','操作','资料齐全进度']))
expect(w.get('[data-column="资料齐全进度"]').text()).toContain('必需 0 / 21');expect(w.get('[data-column="资料齐全进度"]').text()).toContain('选填 0 / 9')
expect(labels.some(label=>label.includes(' / '))).toBe(false)
const costButton=w.get('[data-column="操作"]').findAll('el-button-stub').find(e=>e.text()==='成本分析')
expect(costButton).toBeTruthy();await costButton.trigger('click');await flushPromises()
expect(api.archiveDetail).toHaveBeenCalledOnce();expect(w.vm.$.setupState.tab).toBe('cost');expect(w.vm.$.setupState.drawer).toBe(true)
expect(api.archiveCost).not.toHaveBeenCalled();expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('compact maintenance keeps status, quantity, files and check actions on separate horizontal cells',async()=>{
const item={id:1,item_key:'technical',title:'技术方案',category:'前期',state:'PARTIAL',required:1,applicable:1,documents:[{current_file_id:'f1'}]}
api.archiveDetail.mockResolvedValue({data:{...project,items:[item]}})
const w=mount(Archive);await flushPromises();await w.vm.$.setupState.open(21);await flushPromises()
const row=w.get('.attachment-item')
expect(row.find('.requirement .requirement-state').exists()).toBe(false)
expect(row.find('.requirement-state').exists()).toBe(true);expect(row.get('.requirement-count').text()).toBe('1')
expect(row.find('.requirement-actions').text()).toBe('上传附件');expect(row.findComponent(ItemStatus).props('editable')).toBe(true);expect(w.findComponent(Files).props('compact')).toBe(true);expect(w.findComponent(Files).props('hideUpload')).toBe(true);w.unmount()
})
test('the right-hand upload button targets its own file editor and batch confirmation never silently includes ineligible rows',async()=>{
const upload=vi.fn(),files=defineComponent({props:{item:Object,hideUpload:Boolean},setup(_,{expose}){expose({openNew:upload});return()=>h('div')}})
const items=[{id:1,item_key:'technical',title:'技术方案',category:'前期',required:1,applicable:1,state:'PARTIAL',documents:[{current_file_id:'f1'}]},{id:2,item_key:'bid',title:'投标文件',category:'前期',required:1,applicable:1,state:'MISSING',documents:[]}]
api.archiveDetail.mockResolvedValue({data:{...project,items}});api.archiveConfirmItems.mockResolvedValue({data:{confirmed:1}})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElTable:tableStub,ElTableColumn:true,ArchiveFiles:files}}});await flushPromises();const state=w.vm.$.setupState;await state.open(21);await flushPromises()
const first=w.get('[data-item-key="technical"]');await first.findAll('el-button-stub').find(button=>button.text()==='上传附件').trigger('click');expect(upload).toHaveBeenCalledOnce()
expect(first.findComponent(files).props('hideUpload')).toBe(true);state.toggleEligible(true);expect(state.selectedItemIds).toEqual([1]);state.showBatchConfirm();expect(state.batchDialog).toBe(true);expect(api.archiveConfirmItems).not.toHaveBeenCalled()
await state.confirmBatch();expect(api.archiveConfirmItems).toHaveBeenCalledWith(21,{version:3,itemIds:[1]});expect(state.selectedItemIds).toEqual([])
api.archiveConfirmItems.mockClear();state.selectedItemIds=[1,2];await state.confirmBatch();expect(api.archiveConfirmItems).not.toHaveBeenCalled();state.detail.canEdit=false;state.uploadItem(items[0]);expect(upload).toHaveBeenCalledOnce();w.unmount()
})
test('reviewers open the checklist by default and can still return specific items after entering requirements',async()=>{
const items=[{id:1,item_key:'technical',title:'技术方案',category:'前期',required:1,applicable:1,state:'DONE',documents:[{current_file_id:'f1',final_file_id:'f1'}]}]
api.archiveMetadata.mockResolvedValue({data:{actorId:3,all:true,canReview:true,catalog}});api.archiveDetail.mockResolvedValue({data:{...project,archive_state:'REVIEW',canEdit:false,canReview:true,items,review:{baselineAvailable:true,documents:[],costChanges:[],itemChanges:[]}}});api.archiveState.mockResolvedValue({code:200})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21);await flushPromises();expect(state.tab).toBe('items');expect(w.findComponent({name:'ArchiveReview'}).exists()).toBe(false);expect(state.overviewCards.find(card=>card.key==='review').label).toBe('待我核对')
state.openReturn('technical');expect(state.returnDialog).toBe(true);expect(state.returnItems).toEqual([1]);await state.confirmReturn();expect(api.archiveState).not.toHaveBeenCalled()
state.returnReason='请补充盖章扫描件';await state.confirmReturn();expect(api.archiveState).toHaveBeenCalledWith(21,{version:3,action:'RETURN',reason:'请补充盖章扫描件',itemIds:[1]})
api.archiveState.mockClear();state.detail.canReview=false;state.openReturn();await state.confirmReturn();expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('readonly file views default to the selected archive version rather than a newly uploaded unselected version',async()=>{
const doc={id:7,title:'图纸',current_file_id:'v2',final_file_id:'v1',files:[{id:'v2',name:'新图.pdf',revision:2},{id:'v1',name:'核对图.pdf',revision:1}]}
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[doc]},editable:false});expect(w.get('.file-name').text()).toBe('核对图.pdf');expect(w.text()).toContain('选定归档版')
await w.setProps({editable:true});expect(w.get('.file-name').text()).toBe('新图.pdf');expect(api.archiveRead).not.toHaveBeenCalled();w.unmount()
})
test('compact file rows retain direct preview and upload while avoiding a duplicate preview button',async()=>{
const doc={id:8,title:'说明.txt',current_file_id:'f1',files:[{id:'f1',name:'说明.txt',byte_size:80,content_type:'application/octet-stream',revision:1}]}
const blob=new Blob(['safe']);blob.text=async()=>'隔离测试文本';api.archiveRead.mockResolvedValue(blob)
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[doc]},editable:true,compact:true})
expect(w.get('.archive-files').classes()).toContain('compact');expect(w.text()).not.toContain('已上传')
expect(w.find('[aria-label="上传技术方案附件"]').exists()).toBe(true);expect(w.find('[aria-label="预览附件说明.txt"]').exists()).toBe(false)
await w.get('.file-name').trigger('click');await flushPromises();expect(api.archiveRead).toHaveBeenCalledWith(8,'f1',true,expect.any(AbortSignal));expect(w.vm.$.setupState.previewOpen).toBe(true);w.unmount()
})
test('missing/cost/history shortcuts and project switching are read only and protect dirty edits',async()=>{
const items=[{id:1,item_key:'technical',category:'前期',title:'技术方案',state:'MISSING',applicable:1,documents:[]},{id:2,item_key:'costAnalysis',category:'交付',title:'成本分析',state:'PARTIAL',applicable:1}]
api.archiveProjects.mockResolvedValue({data:{rows:[project,{...project,id:22}],total:2}})
api.archiveDetail.mockImplementation(id=>Promise.resolve({data:{...project,id,items}}))
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21,'missing')
expect(state.onlyMissing).toBe(true);expect(state.costIncomplete).toBe(true);expect(state.canPrevious).toBe(false);expect(state.canNext).toBe(true)
state.costDirty=true;await state.navigateProject(1);expect(state.detail.id).toBe(21)
state.costDirty=false;await state.navigateProject(1);expect(state.detail.id).toBe(22);expect(state.onlyMissing).toBe(true)
await state.open(21,'costAnalysis');expect(state.tab).toBe('cost');await state.navigateProject(1);expect(state.tab).toBe('cost')
await state.open(21,'history');expect(state.tab).toBe('history')
expect(api.archiveItem).not.toHaveBeenCalled();expect(api.archiveCost).not.toHaveBeenCalled();expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('create project opens its fresh detail instead of being blocked by its own saving flag',async()=>{
api.archiveSave.mockResolvedValue({data:{id:21}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
state.projectForm={name:'隔离资料项目',code:'DOC-21',managerId:2,scopeType:'INTERNAL',phase:'INITIATION'}
await state.saveProject();await flushPromises();expect(api.archiveDetail).toHaveBeenCalledWith(21,expect.any(AbortSignal));expect(state.drawer).toBe(true);w.unmount()
})
test('a late list response after unmount cannot replace the visible project state',async()=>{
let resolve;api.archiveProjects.mockReturnValue(new Promise(r=>{resolve=r}))
const w=mount(Archive);await flushPromises();w.unmount();resolve({data:{rows:[project],total:1}});await flushPromises();expect(w.vm.$.setupState.rows).toEqual([])
})
test('unsaved cost entries survive an unrelated parent metadata refresh',async()=>{
const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{data:{formatVersion:2,income:100}}});await flushPromises()
const state=w.vm.$.setupState;state.form.income=200;await flushPromises()
await w.setProps({version:4,cost:{data:{formatVersion:2,income:100}}});expect(state.form.income).toBe(200);expect(state.dirty).toBe(true);w.unmount()
})
test('cost save uses the archive API and never turns saving into completion confirmation',async()=>{
api.archiveCost.mockResolvedValue({code:200});const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{}});await flushPromises();const state=w.vm.$.setupState;state.form.income=100;await state.save()
expect(api.archiveCost).toHaveBeenCalledWith(21,expect.objectContaining({version:3,data:expect.objectContaining({income:100,formatVersion:3})}));expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
})
test('new projects default external and the rates entry is restricted by administrator metadata',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.editProject();expect(state.projectForm.scopeType).toBe('EXTERNAL');expect(w.text()).not.toContain('管理设置');state.manageProjectData('rates');expect(state.ratesDialog).toBe(false);state.metadata.canMaintainCosts=true;await flushPromises();expect(w.text()).toContain('管理设置');state.manageProjectData('rates');expect(state.ratesDialog).toBe(true);state.manageProjectData('catalog');expect(state.catalogDialog).toBe(false);w.unmount()
})
test('person selectors keep selected users during search and use their current centrally managed rates',async()=>{
api.archiveCostPeople.mockResolvedValue({data:[{id:5,name:'普通成员',account:'member',rate:1200}]});const source={data:{formatVersion:3,income:10000,labor:[{userId:5,name:'旧姓名',duty:'研发',days:2,rate:900}]}}
const w=mount(Cost,{projectId:21,version:3,editable:true,cost:source});await flushPromises();const state=w.vm.$.setupState;expect(api.archiveCostPeople).toHaveBeenCalledWith(21,{keyword:'',ids:'5'},expect.any(AbortSignal));expect(state.form.labor[0].rate).toBe(1200);expect(source.data.labor[0].rate).toBe(900);expect(state.dirty).toBe(true)
await state.loadPeople('普通');expect(api.archiveCostPeople).toHaveBeenLastCalledWith(21,{keyword:'普通',ids:undefined},expect.any(AbortSignal));state.selectPerson(state.form.labor[0],null,'labor');expect(state.form.labor[0].rate).toBeNull();expect(state.form.labor[0].name).toBe('');w.unmount()
const readonly=mount(Cost,{projectId:21,version:3,editable:false,cost:source});await flushPromises();expect(readonly.vm.$.setupState.form.labor[0].rate).toBe(900);readonly.unmount()
})
test('failed people loading and legacy free text block writes rather than silently saving arbitrary names',async()=>{
api.archiveCostPeople.mockRejectedValue(new Error('offline'));const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{}});await flushPromises();const state=w.vm.$.setupState;state.form.income=100;await state.save();expect(api.archiveCost).not.toHaveBeenCalled();expect(state.peopleError).toBe(true)
api.archiveCostPeople.mockResolvedValue({data:[]});await state.loadPeople();state.form.labor=[{name:'未关联姓名',userId:null,duty:'研发',days:1,rate:1000}];await state.save();expect(api.archiveCost).not.toHaveBeenCalled();w.unmount()
})
test('rate maintenance preserves other unsaved rows and submits the current configuration version',async()=>{
api.archiveLaborRates.mockResolvedValue({data:{rows:[{id:2,name:'经理甲',account:'manager',rate:1000},{id:5,name:'普通成员',account:'member',rate:1000}],total:2,page:1,version:4}});api.archiveLaborRate.mockResolvedValue({code:200});const w=mount(LaborRates);await flushPromises();const state=w.vm.$.setupState;state.rows[0].rate=1200;state.rows[1].rate=1300;await state.save(state.rows[0]);expect(api.archiveLaborRate).toHaveBeenCalledWith({version:4,userId:2,rate:1200});expect(state.rows[1].rate).toBe(1300);expect(state.rows[1].savedRate).toBe(1000);await state.save(state.rows[1]);expect(api.archiveLaborRate).toHaveBeenLastCalledWith({version:5,userId:5,rate:1300});w.unmount()
})
test('cost save stays in the dialog footer outside the scroller and follows dirty, saving and read-only states',async()=>{
const save=vi.fn(),costStub=defineComponent({props:{footerActions:Boolean},emits:['busy','dirty','changed'],setup(_,{expose}){expose({save});return()=>h('div',{class:'cost-fixture'})}})
const dialog=defineComponent({template:'
'})
const button=defineComponent({props:['disabled','loading'],template:''})
const costProject={...project,items:[{id:9,item_key:'costAnalysis',title:'项目成本分析表',state:'MISSING',applicable:1,required:1}]}
api.archiveDetail.mockResolvedValue({data:costProject})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElDialog:dialog,ElButton:button,ElTable:tableStub,ElTableColumn:true,ArchiveCost:costStub}}})
await flushPromises();const state=w.vm.$.setupState;await state.open(21,'costAnalysis');await flushPromises()
const cost=w.findComponent(costStub);expect(cost.props('footerActions')).toBe(true)
const saveButton=()=>w.findAll('.workbench-footer button').find(b=>b.text()==='保存成本分析')
expect(saveButton().element.closest('.workbench-scroll')).toBeNull();expect(saveButton().element.disabled).toBe(true)
expect(w.get('.workbench-footer').text()).not.toContain('提交管理员核对')
cost.vm.$emit('dirty',true);await flushPromises();expect(saveButton().element.disabled).toBe(false);await saveButton().trigger('click');expect(save).toHaveBeenCalledTimes(1)
cost.vm.$emit('busy',true);await flushPromises();expect(saveButton().element.disabled).toBe(true);expect(w.get('.workbench-footer').text()).toContain('正在保存')
state.detail={...costProject,canEdit:false};await flushPromises();expect(saveButton()).toBeUndefined();expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('cost confirmation reports the exact missing date, still calculates profit, then saves a complete draft',async()=>{
api.archiveCost.mockResolvedValue({code:200});const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{complete:false,data:{formatVersion:3,income:10000,travel:[{userId:2,name:'经理甲',purpose:'出差',date:null,amount:100}]}}});await flushPromises();const state=w.vm.$.setupState
expect(state.summaryRows.find(row=>row.key==='totalCost').amount).toBe(100);expect(state.summaryRows.find(row=>row.key==='profit').amount).toBe(9900);expect(state.summaryRows.find(row=>row.key==='margin').amount).toBe(.99)
expect(await state.prepareConfirmation()).toBe(false);expect(state.issuesOpen).toBe(true);expect(state.issues.map(issue=>issue.label)).toEqual(['差旅费第 1 行:请选择出差日期']);expect(api.archiveCost).not.toHaveBeenCalled();expect(w.find('.cost-top').exists()).toBe(false);expect(w.find('.summary-add').text()).toBe('补充费用项目')
state.form.travel[0].date='2026-10-26';expect(await state.prepareConfirmation()).toBe(true);expect(api.archiveCost).toHaveBeenCalledWith(21,expect.objectContaining({version:3}));expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
})
test('travel uses a multi-person picker, resolves all selected ids, saves one expense and clears without restoring a legacy person',async()=>{
api.archiveCost.mockResolvedValue({code:200});api.archiveCostPeople.mockResolvedValue({data:[{id:2,name:'经理甲',account:'manager'},{id:5,name:'普通成员',account:'member'}]});
const w=realMount(Cost,{props:{projectId:21,version:3,editable:true,cost:{complete:true,userNames:{2:'经理甲'},data:{formatVersion:3,income:1000,travel:[{userId:2,name:'经理甲',purpose:'出差',date:'2026-10-28',amount:125.5}]}}},global:{plugins:[ElementPlus]}});await flushPromises();const state=w.vm.$.setupState,row=state.form.travel[0];expect(row.userIds).toEqual([2]);expect(row.userId).toBeNull();
const person=w.findAllComponents({name:'ElSelect'}).find(s=>s.props('ariaLabel')==='出差人');expect(person.props('multiple')).toBe(true);expect(person.props('clearable')).toBe(true);
person.vm.$emit('update:modelValue',[2,5]);person.vm.$emit('change',[2,5]);await flushPromises();expect(row.name).toBe('经理甲、普通成员');expect(state.summaryRows.find(r=>r.key==='totalCost').amount).toBe(125.5);expect(state.summaryRows.find(r=>r.key==='profit').amount).toBe(874.5);expect(await state.prepareConfirmation()).toBe(true);expect(api.archiveCost.mock.calls.at(-1)[1].data.travel[0].userIds).toEqual([2,5]);
await w.setProps({cost:{complete:true,userNames:{2:'经理甲',5:'普通成员'},data:{formatVersion:3,income:1000,travel:[{userIds:[2,5],name:'经理甲、普通成员',purpose:'出差',date:'2026-10-28',amount:125.5}]}}});await flushPromises();expect(api.archiveCostPeople).toHaveBeenLastCalledWith(21,expect.objectContaining({ids:'2,5'}),expect.anything());expect(state.form.travel[0].userIds).toEqual([2,5]);
state.selectTravelPeople(state.form.travel[0],[]);await flushPromises();expect(state.form.travel[0].name).toBe('');expect(state.issues.map(i=>i.label)).toEqual(['差旅费第 1 行:请选择出差人']);expect(await state.prepareConfirmation()).toBe(false);w.unmount();
})
test('cost confirmation is clickable for incomplete forms and uses the refreshed project version after preparation',async()=>{
const prepare=vi.fn().mockResolvedValue(false),costStub=defineComponent({setup(_,{expose}){expose({prepareConfirmation:prepare});return()=>h('div')}})
const button=defineComponent({props:['disabled','loading'],template:''}),dialog=defineComponent({template:'
'})
const own={...project,cost:{complete:false},items:[{id:9,item_key:'costAnalysis',title:'成本',state:'PARTIAL',applicable:1}]};api.archiveDetail.mockResolvedValue({data:own});api.archiveItem.mockResolvedValue({code:200})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElDialog:dialog,ElButton:button,ElTable:tableStub,ElTableColumn:true,ArchiveCost:costStub}}});await flushPromises();const state=w.vm.$.setupState;await state.open(21,'costAnalysis');await flushPromises()
const confirm=w.findAll('.workbench-footer button').find(b=>b.text()==='确认成本齐全');expect(confirm.element.disabled).toBe(false);await state.confirmCost();expect(prepare).toHaveBeenCalledOnce();expect(api.archiveItem).not.toHaveBeenCalled()
prepare.mockResolvedValue(true);api.archiveDetail.mockResolvedValue({data:{...own,version:4,cost:{complete:true}}});await state.confirmCost();expect(api.archiveItem).toHaveBeenCalledWith(21,9,expect.objectContaining({version:4,state:'DONE'}));w.unmount()
})
test('person search hides unrelated selected users and discards stale remote responses',async()=>{
api.archiveCostPeople.mockResolvedValue({data:[{id:2,name:'经理甲',account:'manager',rate:1000},{id:7,name:'王一',account:'wangyi',rate:1000}]});const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{data:{formatVersion:3,income:100,labor:[{userId:2,name:'经理甲',duty:'设计',days:1,rate:1000}]}}});await flushPromises();const state=w.vm.$.setupState;await state.loadPeople('王');expect(state.matchingPeople.map(person=>person.name)).toEqual(['王一']);expect(state.form.labor[0].name).toBe('经理甲')
let resolveFirst;api.archiveCostPeople.mockReturnValueOnce(new Promise(resolve=>{resolveFirst=resolve})).mockResolvedValueOnce({data:[{id:8,name:'李一',account:'liyi',rate:1000}]});const stale=state.loadPeople('王');await state.loadPeople('李');resolveFirst({data:[{id:7,name:'王一',account:'wangyi'}]});await stale;expect(state.matchingPeople.map(person=>person.name)).toEqual(['李一']);w.unmount()
})
test('rate search is debounced, has no pagination and keeps unsaved changes across searches',async()=>{
vi.useFakeTimers();let w;try{api.archiveLaborRates.mockImplementation(({keyword,page})=>Promise.resolve({data:{rows:keyword==='李'?[{id:5,name:'李一',account:'li',rate:1000}]:[{id:2,name:'王一',account:'wang',rate:1000}],page,total:1,version:1}}));w=mount(LaborRates);await flushPromises();const state=w.vm.$.setupState;state.rows[0].rate=1200;state.keyword='李';await flushPromises();expect(api.archiveLaborRates).toHaveBeenCalledTimes(1);await vi.advanceTimersByTimeAsync(300);await flushPromises();expect(state.rows[0].id).toBe(5);expect(w.find('el-pagination-stub').exists()).toBe(false);expect(w.text()).not.toContain('查询');state.keyword='王';await flushPromises();await vi.advanceTimersByTimeAsync(300);await flushPromises();expect(state.rows[0].rate).toBe(1200);expect(state.rows[0].savedRate).toBe(1000)}finally{w?.unmount();vi.useRealTimers()}
})
test('rates load all matched users without an exposed page control',async()=>{
api.archiveLaborRates.mockImplementation(({page})=>Promise.resolve({data:{rows:Array.from({length:page===3?5:100},(_,index)=>({id:(page-1)*100+index+1,name:'人员',account:'user',rate:1000})),page,total:205,version:1}}));const w=mount(LaborRates);await flushPromises();expect(w.vm.$.setupState.rows).toHaveLength(205);expect(api.archiveLaborRates).toHaveBeenCalledTimes(3);expect(w.find('el-pagination-stub').exists()).toBe(false);w.unmount()
})
test('submission issues mirror required completion and final attachment checks without blocking optional unfinished or inapplicable items',()=>{
const items=[
{id:1,item_key:'technical',title:'技术方案',required:1,applicable:1,state:'MISSING'},
{id:2,item_key:'costAnalysis',title:'项目成本分析表',required:1,applicable:1,state:'PARTIAL'},
{id:3,item_key:'optional',required:0,applicable:1,state:'PARTIAL'},
{id:4,item_key:'notApplicable',required:1,applicable:0,state:'MISSING'},
{id:5,item_key:'noFinal',required:0,applicable:1,state:'DONE',documents:[{current_file_id:'working',final_file_id:null}]},
{id:6,item_key:'finished',required:1,applicable:1,state:'DONE',documents:[{final_file_id:'final'}]}
]
expect(archiveSubmitIssues(items).map(issue=>issue.item.id)).toEqual([1,2,5])
expect(archiveSubmitIssues(items)[1].reason).toContain('成本分析尚未确认完成')
expect(archiveSubmitIssues(items.slice(2,4))).toEqual([])
expect(archiveSubmitIssues([{...items[0],state:'DONE',documents:[{final_file_id:'final'}]},{...items[1],state:'DONE'}])).toEqual([])
expect(archiveSubmitIssues([{...items[5],documents:[{deleted:1,final_file_id:'deleted'}]}])).toHaveLength(1)
})
test('submission is disabled with missing count, links to the exact cost issue, and enables only after saved confirmations',async()=>{
const items=[{id:1,item_key:'technical',title:'技术方案',required:1,applicable:1,state:'MISSING'},{id:2,item_key:'costAnalysis',title:'项目成本分析表',required:1,applicable:1,state:'PARTIAL'}]
api.archiveDetail.mockResolvedValue({data:{...project,items}})
const dialog=defineComponent({template:'