import {beforeEach,expect,test,vi} from 'vitest' import {shallowMount,flushPromises} from '@vue/test-utils' import {defineComponent,provide,inject,computed,h,onBeforeUnmount} from 'vue' import {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 {countDocuments,summary,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','archiveCost','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:[]})}) 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.text()).toContain('项目资料');expect(w.text()).toContain('与采购、库存及项目协作独立');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}],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 / 30') 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()).toContain('更多设置');expect(row.findComponent(ItemStatus).props('editable')).toBe(true);expect(w.findComponent(Files).props('compact')).toBe(true);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:2})}));expect(api.archiveItem).not.toHaveBeenCalled();w.unmount() }) test('cost form follows the source summary and detail columns with free text personnel only',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.sections.map(s=>s.fields.map(f=>f.label))).toEqual([ ['项目参与人员','职责分工','投入工时(天)','费用标准(元/人日)','费用小计(元)'], ['供应商名称','采购项目','采购成本(含税)'],['出差事项','出差人','出差日期','差旅费用'],['申请人','日期','费用']]) expect(costSignerFields.map(f=>f[1])).toEqual(['编制人','财务部门审核人','项目负责人','外包外协/佣金代理','需求部门负责人','管理部门审核人']) expect(api.archivePeople).not.toHaveBeenCalled();expect(w.findAll('el-select-stub')).toHaveLength(0) state.form.income=1000;state.add('labor');state.form.labor[0]={name:'非系统姓名',duty:'设计',days:2,rate:50} 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(800) state.add('travel');await flushPromises();expect(state.summaryRows.find(r=>r.key==='profit').amount).toBeNull();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.preparer).toBe('历史姓名');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]).not.toHaveProperty('userId');expect(JSON.stringify(source)).toBe(before) const modern=normalizeCost({data:{formatVersion:2,income:0,signers:{preparer:'123'},labor:[{name:'外部顾问'}]}});expect(modern.signers.preparer).toBe('123');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('.cost-entry').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').at(-1).attributes('disabled')).toBe('true') 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(false);expect(na.text()).toContain('不适用');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()=>'' 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('{ 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() })