cmvr-wms/ruoyi-ui-vue3/tests/runtime/archive-module.spec.js
lixiaolong d37b4ff379 refactor(mobile): 重构移动端应用结构和配置
- 将 Account 组件中的 Text 导入移动到顶部
- 移除 App.tsx 中的 expo-updates 相关代码
- 添加 PackageUpdates 相关组件和 hooks
- 更新应用名称从 "CMVR 物资管理" 为 "车研物资"
- 添加应用图标和自适应图标配置
- 更新 Android 权限配置,添加 REQUEST_INSTALL_PACKAGES 权限
- 修改堆栈导航数据结构,支持路由参数传递
- 添加阅读尺寸偏好设置功能
- 重构登录界面为独立组件 LoginView
- 添加文件库界面组件 FileLibrary
- 更新状态栏样式逻辑
- 调整 Tab 栏样式和尺寸
- 集成包更新和应用更新对话框
- 修复导入语句顺序和类型引用
- 优化业务列表组件的路由参数处理
- 添加作用域参数用于 API 请求区分
2026-10-28 17:30:35 +08:00

538 lines
66 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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:'<div class="test-table"/>'})
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:'<div><slot/><footer class="dialog-footer"><slot name="footer"/></footer></div>'})
const button=defineComponent({props:['disabled','loading'],template:'<button :disabled="disabled"><slot/></button>'})
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:'<button :disabled="disabled"><slot/></button>'}),dialog=defineComponent({template:'<div><slot/><footer><slot name="footer"/></footer></div>'})
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:'<div><slot/><footer><slot name="footer"/></footer></div>'})
const button=defineComponent({props:['disabled','loading'],template:'<button :disabled="disabled"><slot/></button>'})
const popover=defineComponent({template:'<div><slot name="reference"/><slot/></div>'})
const w=shallowMount(Archive,{global:{directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElDialog:dialog,ElButton:button,ElPopover:popover,ElTable:tableStub,ElTableColumn:true}}})
await flushPromises();const state=w.vm.$.setupState;await state.open(21);await flushPromises()
const submit=()=>w.findAll('.workbench-footer button').find(b=>b.text().startsWith('提交管理员核对'))
expect(submit().element.disabled).toBe(true);expect(submit().text()).toContain('还缺 2 项');expect(w.get('.submission-issues').text()).toContain('项目成本分析表')
await state.changeState('SUBMIT');expect(api.archiveState).not.toHaveBeenCalled()
state.submitIssuesOpen=true;const costIssue=w.findAll('.submission-issues button').find(b=>b.text().includes('项目成本分析表'));await costIssue.trigger('click');expect(state.tab).toBe('cost');expect(state.submitIssuesOpen).toBe(false)
state.showChecklist();state.detail={...project,items:[{...items[0],state:'DONE',documents:[{final_file_id:'final'}]},{...items[1],state:'DONE'}]};await flushPromises()
expect(submit().element.disabled).toBe(false);expect(submit().text()).not.toContain('还缺');expect(w.find('.submission-issues').exists()).toBe(false)
for(const key of ['detailLoading','materialBusy','costDirty','busy']){state[key]=true;await flushPromises();expect(submit().element.disabled).toBe(true);state[key]=false;await flushPromises()}
state.detail={...state.detail,archive_state:'REVIEW'};await flushPromises();expect(submit().element.disabled).toBe(true)
expect(api.archiveState).not.toHaveBeenCalled();w.unmount()
})
test('cost form uses system personnel, hides rates and removes the six signer inputs',async()=>{
const w=mount(Cost,{projectId:21,version:3,editable:true,cost:{}});await flushPromises();const state=w.vm.$.setupState
expect(state.summaryRows.map(r=>r.label)).toEqual(['项目收入','项目成本费用',...costCategories,'毛利润','利润率'])
expect(state.summaryRows.filter(r=>r.kind==='summary').map(r=>r.seq)).toEqual(['一','二','三','四']);expect(state.summaryRows.filter(r=>r.kind!=='summary').map(r=>r.seq)).toEqual(Array.from({length:13},(_,i)=>i+1))
expect(state.sections.map(s=>s.fields.map(f=>f.label))).toEqual([
['项目参与人员','职责分工','投入工时(天)','费用小计(元)'],
['供应商名称','采购项目','采购成本(含税)'],['出差事项','出差人','出差日期','差旅费用'],['申请人','日期','费用']])
expect(w.find('.signers').exists()).toBe(false);expect(api.archiveCostPeople).toHaveBeenCalledWith(21,expect.objectContaining({keyword:''}),expect.any(AbortSignal))
expect(api.archivePeople).not.toHaveBeenCalled()
state.form.income=3000;state.add('labor');state.form.labor[0].duty='设计';state.form.labor[0].days=2;state.form.labor[0].userId=2;state.selectPerson(state.form.labor[0],2,'labor');expect(state.form.labor[0].rate).toBe(1000)
state.add('materials');state.form.materials[0]={supplier:'隔离供应商',content:'材料',gross:113}
await flushPromises();expect(state.summaryRows.find(r=>r.key==='材料及耗材').amount).toBe(100);expect(state.summaryRows.find(r=>r.key==='profit').amount).toBe(900)
state.add('travel');await flushPromises();expect(state.summaryRows.find(r=>r.key==='profit').amount).toBe(900);expect(state.issues.some(issue=>issue.label.includes('出差日期'))).toBe(true);w.unmount()
})
test('historical names are resolved from saved snapshots without system lookups or mutation',()=>{
const source={userNames:{2:'历史姓名'},data:{incomeGross:113,incomeTax:13,labor:[{userId:2,duty:'研发',days:1,rate:100}],materials:[{supplier:'供应商',content:'材料',gross:113,tax:13}],travel:[{userId:2}],entertainment:[{userId:2}],signers:{preparer:2},expenses:[]}}
const before=JSON.stringify(source),form=normalizeCost(source);expect(form.income).toBe(100);expect(form.signers).toEqual({});expect(form.labor[0].name).toBe('历史姓名');expect(form.travel[0].name).toBe('历史姓名');expect(form.entertainment[0].name).toBe('历史姓名');expect(form.materials[0]).not.toHaveProperty('tax');expect(form.labor[0].userId).toBe(2);expect(JSON.stringify(source)).toBe(before)
const modern=normalizeCost({data:{formatVersion:2,income:0,signers:{preparer:'123'},labor:[{name:'外部顾问'}]}});expect(modern.signers).toEqual({});expect(modern.income).toBe(0);expect(modern.labor[0].name).toBe('外部顾问')
})
test('physical versions do not count as multiple contract documents and nonapplicable items are separate',()=>{
const item={required:1,applicable:1,state:'DONE',documents:[{current_file_id:'a',files:[{id:'a'},{id:'b'}]},{current_file_id:null}]};expect(countDocuments(item)).toBe(1)
expect(summary([item,{required:1,applicable:0,state:'MISSING'}])).toMatchObject({required:1,done:1,missing:0,na:1});expect(MAX_ARCHIVE_FILE).toBe(1073741824)
})
test('catalog dictionaries roundtrip real lines rather than backslash text',async()=>{
api.archiveMetadata.mockResolvedValue({data:{actorId:1,canConfigure:true,catalog}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.showCatalog()
state.catalogCustomers='高校\r\n检测机构\r\n高校';api.archiveCatalog.mockResolvedValue({code:200});await state.saveCatalog()
expect(api.archiveCatalog).toHaveBeenCalledWith(expect.objectContaining({customerTypes:['高校','检测机构']}));w.unmount()
})
test('admin template sorting, add and removal are local until saved and cancel restores the catalog',async()=>{
const source={...catalog,formatVersion:2,items:[...catalog.items,{key:'preQuote',title:'预报价',category:'前期',required:false}]}
api.archiveMetadata.mockResolvedValue({data:{actorId:1,canConfigure:true,catalog:source}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.showCatalog()
state.moveCatalogItem(1,-1);expect(state.catalogForm.items.map(i=>i.key)).toEqual(['preQuote','technical'])
state.addCatalogItem();const added=state.catalogForm.items.at(-1);expect(added.key).toMatch(/^custom_[a-f0-9]{32}$/);expect(added.required).toBe(false)
const confirmation=vi.spyOn(ElMessageBox,'confirm').mockResolvedValue('confirm');await state.removeCatalogItem('technical');expect(state.catalogForm.items.map(i=>i.key)).toEqual(['preQuote',added.key]);confirmation.mockRestore()
expect(source.items.map(i=>i.key)).toEqual(['technical','preQuote']);expect(api.archiveCatalog).not.toHaveBeenCalled();expect(api.archiveRemove).not.toHaveBeenCalled()
state.catalogDialog=false;state.showCatalog();expect(state.catalogForm.items.map(i=>i.key)).toEqual(['technical','preQuote'])
state.moveCatalogItem(0,-1);state.moveCatalogItem(1,1);expect(state.catalogForm.items.map(i=>i.key)).toEqual(['technical','preQuote'])
state.moveCatalogItem(0,1);api.archiveCatalog.mockResolvedValue({code:200});await state.saveCatalog();expect(api.archiveCatalog).toHaveBeenCalledWith(expect.objectContaining({items:expect.arrayContaining([expect.objectContaining({key:'preQuote'})])}));expect(api.archiveCatalog.mock.calls.at(-1)[0].items[0].key).toBe('preQuote');w.unmount()
})
test('nonadmin cannot open or mutate template through handlers and empty fields are not sent',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
state.showCatalog();expect(state.catalogDialog).toBe(false);state.addCatalogItem();state.moveCatalogItem(0,1);await state.removeCatalogItem('technical');await state.saveCatalog();expect(api.archiveCatalog).not.toHaveBeenCalled()
state.metadata={actorId:1,canConfigure:true,catalog};state.showCatalog();state.addCatalogItem();await state.saveCatalog();expect(api.archiveCatalog).not.toHaveBeenCalled()
state.catalogForm.items=[{...catalog.items[0]}];const confirmation=vi.spyOn(ElMessageBox,'confirm');await state.removeCatalogItem('technical');expect(confirmation).not.toHaveBeenCalled();confirmation.mockRestore();w.unmount()
})
test('comparison preserves admin labels and keeps old-only materials without treating absent items as failed loads',async()=>{
const custom={key:'technical',category:'管理员的分类',title:'管理员的名称',required:false}
const old=[{item_key:'preQuote',title:'预报价',category:'旧分类',required:0,state:'MISSING',applicable:1}]
expect(comparisonRows([custom],true,[old]).map(i=>i.key)).toEqual(['technical','preQuote'])
expect(comparisonRows([custom],true)[0]).toEqual(custom);expect(comparisonRows([custom],true,[old])[1].historical).toBe(true)
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
state.metadata.catalog={...catalog,formatVersion:2,items:[custom]};state.matrix={21:old,22:[]};expect(state.comparisonItems.map(i=>i.key)).toEqual(['technical','preQuote'])
expect(state.matrixAbsent(21,'technical')).toBe(true);expect(state.matrixAbsent(21,'preQuote')).toBe(false);expect(state.matrixAbsent(22,'preQuote')).toBe(true);expect(state.matrixAbsent(23,'preQuote')).toBe(false)
w.unmount()
})
test('comparison has three colored status cells, no visible view suffix, and whole-cell clicks only open details',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
const items=['MISSING','PARTIAL','DONE'].map((status,index)=>({item_key:'key'+index,title:'资料'+index,state:status,applicable:1,documents:[]}))
state.matrix={21:[...items,{item_key:'na',applicable:0,state:'DONE'}]}
expect(items.map(item=>state.matrixText(21,item.item_key))).toEqual(['✘','◐','✔'])
expect(items.map(item=>state.matrixStatusLabel(21,item.item_key))).toEqual(['未开始/缺失','维护中(部分完成)','已确认齐全'])
for(const item of items)expect(state.matrixCellClass({row:{key:item.item_key},column:{property:'project:21'}})).toBe('comparison-state state-'+item.state)
expect(state.matrixCellClass({row:{key:'na'},column:{property:'project:21'}})).toBe('comparison-state state-na')
expect(state.matrixText(21,'na')).toBe('—');expect(state.matrixCellClass({row:{key:'missing'},column:{property:'project:21'}})).toBe('')
expect(state.matrixCellClass({row:{key:'key0'},column:{property:'category'}})).toBe('')
state.matrixCellClick({key:'key0'},{property:'category'});state.matrixCellClick({key:'missing'},{property:'project:21'});expect(api.archiveDetail).not.toHaveBeenCalled()
api.archiveDetail.mockResolvedValue({data:{...project,items}});state.matrixCellClick({key:'key1'},{property:'project:21'});await flushPromises();expect(state.focusedItemKey).toBe('key1');expect(api.archiveDetail).toHaveBeenCalledOnce()
expect(api.archiveItem).not.toHaveBeenCalled();expect(api.archiveState).not.toHaveBeenCalled();state.view='matrix';await flushPromises();expect(w.get('.archive-page').classes()).toContain('is-comparison');expect(w.get('[aria-label="清单状态图例"]').text()).toContain('部分完成');w.unmount()
})
test('an oversized archive file is rejected before creating an empty document',async()=>{
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[]},editable:true})
await w.vm.$.setupState.selectFiles({target:{files:[{name:'large.zip',size:MAX_ARCHIVE_FILE+1}],value:'large.zip'}})
expect(api.archiveDocument).not.toHaveBeenCalled();expect(api.archiveUpload).not.toHaveBeenCalled();w.unmount()
})
test('a completed transfer does not show the paused upload recovery message',async()=>{
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[]},editable:true});w.vm.$.setupState.transfer={name:'done.txt',percent:100,label:'上传完成',done:true}
await flushPromises();expect(w.find('.archive-transfer-panel').exists()).toBe(false);expect(w.text()).not.toContain('重新选择同一文件可继续');w.unmount()
})
test('a batch has one monotonic progress scale and refreshes files only once after completion',async()=>{
const phases=[{phase:'hashing',percent:0},{phase:'hashing',percent:100},{phase:'uploading',percent:0},{phase:'uploading',percent:100},{phase:'finalizing',percent:100},{phase:'complete',percent:100}]
const percentages=phases.map(transferPercent);expect(percentages).toEqual([...percentages].sort((a,b)=>a-b));expect(percentages.at(-1)).toBe(100)
api.archiveDocument.mockResolvedValueOnce({data:{id:11}}).mockResolvedValueOnce({data:{id:12}})
const pending=[];api.archiveUpload.mockImplementation((id,file,options)=>new Promise(resolve=>pending.push({id,file,options,resolve})))
const w=mount(Files,{projectId:21,item:{id:1,title:'预报价',documents:[]},editable:true,compact:true});const state=w.vm.$.setupState
const job=state.selectFiles({target:{files:[{name:'first.txt',size:100},{name:'second.txt',size:100}],value:''}});await flushPromises()
const observed=[];for(const p of phases){pending[0].options.onProgress(p);observed.push(state.transfer.percent)}
pending[0].resolve({code:200});await flushPromises();expect(state.transfer.index).toBe(2);expect(state.transfer.percent).toBe(50)
pending[0].options.onProgress({phase:'uploading',percent:20});expect(state.transfer.name).toBe('second.txt')
for(const p of phases){pending[1].options.onProgress(p);observed.push(state.transfer.percent)}
expect(observed).toEqual([...observed].sort((a,b)=>a-b));expect(w.find('.file-content .archive-transfer-panel').exists()).toBe(false)
pending[1].resolve({code:200});await job;await flushPromises();expect(state.transfer.done).toBe(true);expect(w.find('.archive-transfer-panel').exists()).toBe(false)
expect(w.emitted('changed')).toHaveLength(1);w.unmount()
})
test('table and comparison clicks open one material or cost detail and cannot abandon active edits',async()=>{
const items=[{id:1,item_key:'technical',title:'技术方案',category:'前期',required:1,applicable:1,state:'MISSING',documents:[]},{id:2,item_key:'costAnalysis',title:'成本分析表',category:'交付',required:1,applicable:1,state:'MISSING',documents:[]}]
api.archiveDetail.mockResolvedValue({data:{...project,items}});const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState
await state.open(21,'technical');await flushPromises();expect(w.find('.focused-material').exists()).toBe(true);expect(w.findAllComponents(Files)).toHaveLength(1)
state.materialBusy=true;state.showChecklist();expect(state.focusedItemKey).toBe('technical');state.materialBusy=false;state.showChecklist();await flushPromises()
expect(w.find('.attachment-table').exists()).toBe(true);expect(w.findAll('tr.attachment-item')).toHaveLength(2)
state.showItem(items[1]);await flushPromises();expect(state.tab).toBe('cost');expect(state.focusedItemKey).toBe('costAnalysis')
state.costDirty=true;state.showChecklist();expect(state.tab).toBe('cost');state.costDirty=false;state.showChecklist();expect(state.focusedItemKey).toBe('')
state.matrix={21:items};expect(state.matrixText(21,'costAnalysis')).toBe('✘');expect(api.archiveCost).not.toHaveBeenCalled();w.unmount()
})
test('the complete checklist includes cost once with an online form instead of an attachment uploader',async()=>{
const items=[{id:1,item_key:'technical',title:'技术方案',category:'前期',required:1,applicable:1,state:'PARTIAL',documents:[{title:'方案',current_file_id:'f1',files:[{id:'f1',name:'特殊规格说明.pdf'}]}]},{id:2,item_key:'archiveChecklist',title:'项目归档清单',category:'交付',required:1,applicable:1,state:'MISSING',documents:[]},{id:3,item_key:'costAnalysis',title:'项目成本分析表',category:'交付',required:1,applicable:1,state:'MISSING',documents:[]}]
api.archiveDetail.mockResolvedValue({data:{...project,items}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21);await flushPromises()
expect(state.category).toBe('');expect(state.attachmentItems).toHaveLength(2);expect(w.findAllComponents(Files)).toHaveLength(2)
expect(state.visibleItems).toHaveLength(3);expect(state.progress.total).toBe(3);expect(w.find('[data-item-key="costAnalysis"] .cost-entry').exists()).toBe(true)
expect(w.find('[data-item-key="costAnalysis"]').findComponent(Files).exists()).toBe(false)
const dialog=w.findAll('el-dialog-stub').find(e=>e.classes().includes('archive-workbench'));expect(dialog.attributes('fullscreen')).toBeUndefined();expect(dialog.attributes('width')).toBe('min(1480px,94vw)')
expect(state.costItem.item_key).toBe('costAnalysis')
state.itemKeyword='特殊规格';await flushPromises();expect(state.visibleItems.map(i=>i.id)).toEqual([1])
expect(w.text()).not.toContain('上传/查看');w.unmount()
})
test('all-item totals include optional items and cost while not-applicable counts as checked exactly once',async()=>{
const items=[{id:1,item_key:'technical',title:'方案',category:'前期',required:1,applicable:1,state:'DONE',documents:[]},{id:2,item_key:'preQuote',title:'预报价',category:'前期',required:0,applicable:0,state:'DONE',documents:[]},{id:3,item_key:'costAnalysis',title:'成本分析',category:'交付',required:1,applicable:1,state:'MISSING',documents:[]}]
expect(summary(items)).toMatchObject({total:3,resolved:2,required:2,done:1,missing:1,na:1})
api.archiveDetail.mockResolvedValue({data:{...project,items}});const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21,'missing');await flushPromises()
expect(state.visibleItems.map(i=>i.item_key)).toEqual(['costAnalysis']);expect(state.categoryDone('前期')).toBe('2/2')
expect(state.progress).toMatchObject({resolved:2,total:3})
const button=w.get('[data-item-key="costAnalysis"] .requirement-actions').findAll('el-button-stub').find(e=>e.text()==='填写成本');await button.trigger('click');expect(state.tab).toBe('cost');expect(api.archiveCost).not.toHaveBeenCalled();w.unmount()
})
test('one-click completion remains an explicit action and rejects pending documents',async()=>{
const item={id:1,item_key:'technical',title:'技术方案',required:1,applicable:1,state:'PARTIAL',expected_count:2,note:'两份资料',documents:[{current_file_id:'a'},{current_file_id:'b'}]}
api.archiveDetail.mockResolvedValue({data:{...project,items:[item]}});api.archiveItem.mockResolvedValue({code:200})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21);await flushPromises()
expect(api.archiveItem).not.toHaveBeenCalled();expect(state.canConfirm({...item,documents:[{current_file_id:null}]})).toBe(false);expect(state.canConfirm({...item,expected_count:3})).toBe(false)
await state.setItemState(item,'DONE');expect(api.archiveItem).toHaveBeenCalledWith(21,1,{version:3,state:'DONE',applicable:true,exceptionReason:'',expectedCount:2,note:'两份资料'});w.unmount()
})
test('material status is editable in place and readonly users never receive a selector',async()=>{
const item={id:1,title:'技术方案',state:'MISSING',applicable:1}
const editable=mount(ItemStatus,{item,editable:true,canComplete:false});expect(editable.find('el-select-stub').exists()).toBe(true)
expect(editable.findAll('el-option-stub').map(e=>e.attributes('label'))).toEqual(['未开始/缺失','部分完成','已确认齐全','说明、份数与适用性…'])
expect(editable.findAll('el-option-stub')[2].attributes('disabled')).toBe('true')
editable.getComponent({name:'ElSelect'}).vm.$emit('change','__details');expect(editable.emitted('inspect')).toHaveLength(1);expect(editable.emitted('change')).toBeUndefined()
editable.getComponent({name:'ElSelect'}).vm.$emit('change','PARTIAL');expect(editable.emitted('change')).toEqual([['PARTIAL']]);expect(item.state).toBe('MISSING')
await editable.setProps({blocked:true});expect(editable.get('el-select-stub').attributes('disabled')).toBe('true');editable.unmount()
const readonly=mount(ItemStatus,{item,editable:false});expect(readonly.find('el-select-stub').exists()).toBe(false);readonly.unmount()
const na=mount(ItemStatus,{item:{...item,applicable:0},editable:true});expect(na.find('el-select-stub').exists()).toBe(true);expect(na.findAll('el-option-stub').at(-1).attributes('value')).toBe('__details');na.unmount()
})
test('quick partial status preserves notes and expected counts while upload, readonly and dirty cost guards remain',async()=>{
const item={id:1,item_key:'technical',title:'技术方案',state:'MISSING',applicable:1,expected_count:3,note:'还差两份',documents:[{current_file_id:'a'}]}
api.archiveDetail.mockResolvedValue({data:{...project,items:[item]}});api.archiveItem.mockResolvedValue({code:200})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.open(21,'technical');await flushPromises()
expect(w.find('.focused-heading').findComponent(ItemStatus).props('editable')).toBe(true);expect(state.canSetComplete(item)).toBe(false)
await state.setItemState(item,'DONE');expect(api.archiveItem).not.toHaveBeenCalled()
state.materialBusy=true;await state.setItemState(item,'PARTIAL');expect(api.archiveItem).not.toHaveBeenCalled();state.materialBusy=false
state.detail.canEdit=false;await state.setItemState(item,'PARTIAL');expect(api.archiveItem).not.toHaveBeenCalled();state.detail.canEdit=true
await state.setItemState(item,'PARTIAL');expect(api.archiveItem).toHaveBeenCalledWith(21,1,{version:3,state:'PARTIAL',applicable:true,exceptionReason:'',expectedCount:3,note:'还差两份'})
api.archiveItem.mockClear();await state.setItemState({...item,applicable:0},'PARTIAL');await state.setItemState(item,'UNKNOWN');expect(api.archiveItem).not.toHaveBeenCalled()
state.costDirty=true;state.detail.cost={complete:true};const cost={...item,item_key:'costAnalysis'};expect(state.canSetComplete(cost)).toBe(false);await state.setItemState(cost,'PARTIAL');expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
})
test('comparison legend shares the toolbar row and does not consume a separate heading row',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.view='matrix';await flushPromises()
expect(w.get('.list-toolbar').find('[aria-label="清单状态图例"]').exists()).toBe(true)
expect(w.get('.matrix-view').find('.matrix-legend').exists()).toBe(false);expect(w.find('.page-heading p').exists()).toBe(false)
expect(w.get('.list-toolbar').find('.export-actions').exists()).toBe(true);expect(w.get('.list-toolbar').find('.project-total').exists()).toBe(true)
w.unmount()
})
test('returning from material detail safely handles uploader teardown without reading a cleared focused item',async()=>{
const errors=vi.fn(),items=[{id:1,item_key:'technical',title:'技术方案',category:'前期',applicable:1,state:'MISSING',documents:[]}]
const files=defineComponent({name:'ArchiveFiles',props:['item'],emits:['busy'],setup(props,{emit}){onBeforeUnmount(()=>emit('busy',false,props.item.id));return()=>h('div','test uploader')}})
api.archiveDetail.mockResolvedValue({data:{...project,items}})
const w=shallowMount(Archive,{global:{config:{errorHandler:errors},directives:{loading:()=>{}},renderStubDefaultSlot:true,stubs:{...widgetStubs,ElTable:tableStub,ElTableColumn:true,ArchiveFiles:files}}})
await flushPromises();const state=w.vm.$.setupState;await state.open(21,'technical');await flushPromises();expect(w.find('.focused-material').exists()).toBe(true)
state.showChecklist();await flushPromises();expect(errors).not.toHaveBeenCalled();expect(w.find('.focused-material').exists()).toBe(false);expect(w.find('.attachment-table').exists()).toBe(true)
state.setMaterialBusy(2,true);state.setMaterialBusy(1,false);expect(state.materialBusy).toBe(true);expect(state.activeMaterial).toBe(2);state.setMaterialBusy(2,false)
expect(api.archiveItem).not.toHaveBeenCalled();w.unmount();expect(errors).not.toHaveBeenCalled()
})
test('comparison receives a bounded lightweight page without fanout detail requests',async()=>{
api.archiveProjects.mockResolvedValue({data:{rows:[project],total:120,size:20,matrix:{21:[{item_key:'technical',state:'PARTIAL',applicable:1,document_count:2}]}}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.query.size=100;state.query.page=3;state.view='matrix';await flushPromises()
expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({comparison:true,page:1,size:20}),expect.any(AbortSignal));expect(api.archiveDetail).not.toHaveBeenCalled();expect(state.matrixText(21,'technical')).toBe('◐');expect(countDocuments(state.matrixItem(21,'technical'))).toBe(2)
state.query.page=2;await state.load();expect(api.archiveDetail).not.toHaveBeenCalled();expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({page:2}),expect.any(AbortSignal));w.unmount()
})
test('admin manager dropdown searches role candidates and ignores late search responses',async()=>{
api.archiveMetadata.mockResolvedValue({data:{actorId:1,all:true,canAssign:true,canBeManager:false,catalog}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;expect(w.get('.project-filters').findAll('el-form-item-stub').map(e=>e.attributes('label'))).toContain('项目经理')
const pending=[];api.archiveManagers.mockImplementation((keyword,signal)=>new Promise(resolve=>pending.push({keyword,signal,resolve})))
const first=state.searchManagers('甲'),second=state.searchManagers('乙');expect(pending[0].signal.aborted).toBe(true)
pending[1].resolve({data:[{id:4,name:'经理乙',account:'other'}]});await second;pending[0].resolve({data:[{id:2,name:'经理甲',account:'manager'}]});await first;expect(state.managerOptions.map(p=>p.id)).toEqual([4])
state.query.managerId=4;state.search();await flushPromises();expect(api.archiveProjects).toHaveBeenLastCalledWith(expect.objectContaining({managerId:4}),expect.any(AbortSignal));state.reset();await flushPromises();expect(state.query.managerId).toBe(null)
state.editProject();expect(state.projectForm.managerId).toBe(null);w.unmount()
})
test('manager view has no manager filter and new projects default to the eligible current manager',async()=>{
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;await state.searchManagers('其他');expect(api.archiveManagers).not.toHaveBeenCalled()
expect(w.get('.project-filters').findAll('el-form-item-stub').map(e=>e.attributes('label'))).not.toContain('项目经理')
state.editProject();expect(state.projectForm.managerId).toBe(2);w.unmount()
})
test('historical owner is only retained as a disabled current value and never leaks into a transfer candidate list',async()=>{
api.archiveMetadata.mockResolvedValue({data:{actorId:1,all:true,canAssign:true,canBeManager:false,catalog}})
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.editProject({...project,manager_id:99,manager_name:'历史经理'});await flushPromises()
expect(state.people).toEqual([expect.objectContaining({id:99,legacy:true})]);expect(state.projectForm.managerId).toBe(99)
state.projectDialog=false;state.detail=project;state.transferManager();await flushPromises();expect(state.people).toEqual([]);expect(api.archiveSave).not.toHaveBeenCalled();w.unmount()
})
test('file name opens the preview directly and text is rendered as text, never HTML',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'],{type:'application/octet-stream'});blob.text=async()=>'<img src=x onerror="bad()">'
api.archiveRead.mockResolvedValue(blob)
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[doc]},editable:true});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)
expect(w.vm.$.setupState.previewText).toContain('<img');expect(w.find('.text-preview img').exists()).toBe(false);w.unmount()
})
test('another active upload blocks new file targets without discarding the current target',async()=>{
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[]},editable:true,blocked:true})
await w.vm.$.setupState.selectFiles({target:{files:[{name:'ok.txt',size:20}],value:'ok.txt'}})
expect(api.archiveDocument).not.toHaveBeenCalled();expect(api.archiveUpload).not.toHaveBeenCalled();w.unmount()
})
test('read-only reviewers see file names and history without upload or maintenance actions',async()=>{
const doc={id:8,title:'资料说明.txt',current_file_id:'v2',files:[{id:'v2',name:'很长的项目归档材料文件名称及规格说明.txt',revision:2,byte_size:10,content_type:'application/octet-stream'},{id:'v1',name:'资料说明.txt',revision:1,byte_size:10,content_type:'application/octet-stream'}]}
const w=mount(Files,{projectId:21,item:{id:1,title:'技术方案',documents:[doc]},editable:false,compact:true})
expect(w.get('.file-name').text()).toContain('很长的项目归档材料文件名称及规格说明.txt')
expect(w.text()).not.toContain('上传附件');expect(w.text()).not.toContain('移除材料');expect(w.text()).toContain('版本 2');w.unmount()
})