cmvr-wms/ruoyi-ui-vue3/tests/runtime/purchase-grid.spec.js
lixiaolong 771574fef7 feat: 完善采购协同、到货照片及验收发票流程
优化采购实时编辑与权限,支持先到货后补报价、按批次补录照片和批量附件上传。更新验收报告模板及明细选择,增加验收发票独立管理和付款前置校验。完善 BOM 数据权限及 App 更新兼容性。
2026-11-23 14:41:42 +08:00

188 lines
18 KiB
JavaScript

import {expect,it,vi} from 'vitest'
import {reactive,nextTick,computed,watch} from 'vue'
import {createRouter,createMemoryHistory} from 'vue-router'
import Sheet from '../../src/components/PurchaseSheet/index.vue'
import request from '@/utils/request'
import {createSheetEditor} from '../../src/utils/purchase-sheet-editor'
import {writeClipboardText} from '../../src/utils/purchase-grid-clipboard'
it('holding Enter or Space over add-row cannot generate repeated rows',()=>{
const vm={add:vi.fn()},preventDefault=vi.fn()
Sheet.methods.addKeydown.call(vm,{key:'Enter',repeat:false,preventDefault})
for(let i=0;i<30;i++)Sheet.methods.addKeydown.call(vm,{key:i%2?'Enter':' ',repeat:true,preventDefault})
expect(vm.add).toHaveBeenCalledOnce();expect(preventDefault).toHaveBeenCalledTimes(31)
})
it('a user add-row action moves focus into the new row and ignores reentry until focused',async()=>{
let finish;const vm={isEditing:true,canAdd:true,saving:false,sheet:{rows:[],batch:{},unbatched:false},batchProject:{value:2},remember:vi.fn(),emptyRow:()=>({_key:'one'}),columns:[{field:'materialName'}],editableCell:()=>true,$nextTick:()=>new Promise(resolve=>{finish=resolve}),focusSelectedCell:vi.fn(async()=>{})}
const pending=Sheet.methods.add.call(vm,{type:'click'});await Sheet.methods.add.call(vm,{type:'click'});expect(vm.sheet.rows).toHaveLength(1)
finish();await pending;expect(vm.cellSelection.focus).toEqual({key:'one',field:'materialName'});expect(vm.focusSelectedCell).toHaveBeenCalledOnce();expect(vm._addingRow).toBe(false)
})
it('adding rows at a scrolled position retains the rendered window and scroll anchor',()=>{
const rows=Array.from({length:134},(_,i)=>({_key:'row-'+i})),setScrollTop=vi.fn(),vm={virtualRowHeight:40,gridHeight:600,_gridScrollTop:3500,virtualStart:81,virtualized:true,virtualCount:27,visibleRows:[...rows,{_key:'mine'}],$refs:{grid:{setScrollTop}},$nextTick:fn=>fn()}
vm.scrollGrid=Sheet.methods.scrollGrid.bind(vm)
Sheet.methods.reconcileGridRows.call(vm,vm.visibleRows,rows)
expect(vm.virtualStart).toBe(81);expect(vm._gridScrollTop).toBe(3500);expect(setScrollTop).not.toHaveBeenCalled()
vm.visibleRows=rows.slice(0,34);vm.virtualized=false
Sheet.methods.reconcileGridRows.call(vm,vm.visibleRows,rows)
expect(vm._gridScrollTop).toBe(800);expect(setScrollTop).toHaveBeenCalledWith(800)
})
it('a render between row removal and its watcher never slices beyond the remaining data',()=>{
const vm={virtualStart:180,virtualCount:25,visibleRows:Array.from({length:60},(_,i)=>i),virtualized:true}
vm.windowStart=Sheet.computed.windowStart.call(vm)
expect(Sheet.computed.renderedRows.call(vm)).toEqual(vm.visibleRows.slice(35))
})
it('remote unfinished rows are visible but never selected, exported or included in business saves',()=>{
const vm={live:{clientId:'me',peers:[{clientId:'other',name:'同事',draftRows:[{key:'new-1',materialName:'尚未填完',quantity:2,finalUnitPrice:999}]}]},sheet:{rows:[{id:1,_key:'saved-1',materialName:'已保存',purchaseStatus:0}]},selected:[],rowFilter:'',rowQueue:'all',rowSort:'original',onlyInvalid:false,compactAmounts:false,isEditing:true,viewReference:r=>r,projectName:()=>'',amountRowVisible:()=>true}
vm.sharedDraftRows=Sheet.computed.sharedDraftRows.call(vm);vm.visibleRows=Sheet.computed.visibleRows.call(vm)
expect(vm.visibleRows).toHaveLength(2);expect(Sheet.methods.activeRows.call(vm)).toHaveLength(1)
expect(Sheet.computed.inquiryExportSourceRows.call(vm)).toHaveLength(1)
Sheet.methods.selectAllRows.call(vm,true);expect(vm.selected.map(row=>row.id)).toEqual([1]);expect(Sheet.methods.rowState.call(vm,vm.sharedDraftRows[0]).label).toBe('新增草稿')
vm.isEditing=false;vm.compactAmounts=true;expect(Sheet.methods.amountRowVisible.call(vm,{_liveRemote:true,quantity:1,finalUnitPrice:null})).toBe(true)
})
it('new row identifiers use a format accepted by collaboration',()=>{
const vm={projectId:1,commonCategory:1,sheet:{batch:{expenseCategoryId:1}},batchProject:{value:1}}
for(let count=0;count<10;count++)expect(Sheet.methods.emptyRow.call(vm)._key).toMatch(/^[A-Za-z0-9_-]{1,100}$/)
})
it('unquoted saved rows can arrive and accept their first quote while later quote changes stay protected',()=>{
const row={id:1,_key:'saved-1',editable:true,priceLocked:false,finalUnitPrice:null,pendingArrivalQuantity:2,remainingQuantity:3},vm={sheet:{batch:{supplierId:4}},canViewQuotes:true,baselineRowMap:new Map([['saved-1',{...row}]])};
expect(Sheet.methods.canArrive.call(vm,row)).toBe(true);expect(Sheet.methods.fieldLocked.call(vm,row,'finalUnitPrice')).toBe(false);expect(Sheet.methods.fieldLocked.call(vm,row,'materialName')).toBe(true);
row.finalUnitPrice=12;expect(Sheet.methods.fieldLocked.call(vm,row,'finalUnitPrice')).toBe(false);vm.baselineRowMap.set(row._key,{...row});expect(Sheet.methods.fieldLocked.call(vm,row,'finalUnitPrice')).toBe(true);vm.canViewQuotes=false;expect(Sheet.methods.fieldLocked.call(vm,row,'finalUnitPrice')).toBe(true);
})
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
it('deleting an empty batch stops collaboration and removes its URL before returning to the list',async()=>{
const vm={saving:false,isEditing:false,deletingBatchId:null,loading:false,batches:[],query:{pageNum:1},sheet:{batch:{id:328,createBy:'owner'},rows:[]},$store:{getters:{name:'owner'}},$auth:{hasPermiOr:()=>true},$confirm:vi.fn(async()=>{}),clearDraft:vi.fn(),draftId:()=> '328',_live:{stop:vi.fn()},$route:{path:'/procurement/details',query:{purchaseBatchId:'328',projectId:'100'}},$router:{replace:vi.fn(async()=>{})},loadBatches:vi.fn(async()=>{}),$modal:{msgSuccess:vi.fn()}}
vm.canDeleteBatch=Sheet.methods.canDeleteBatch.bind(vm);vm.deleteBatch=Sheet.methods.deleteBatch.bind(vm)
await Sheet.methods.deleteEmptyBatch.call(vm)
expect(vm.sheet).toBeNull();expect(vm._live.stop).toHaveBeenCalledOnce();expect(vm.$router.replace).toHaveBeenCalledWith({path:'/procurement/details',query:{projectId:'100'}});expect(vm.loadBatches).toHaveBeenCalledOnce();expect(vm.saving).toBe(false)
})
it('batch deletion requires the actual creator even when the viewer has management permissions',()=>{
const vm={$store:{getters:{name:'owner'}},$auth:{hasPermiOr:()=>true}},canDelete=row=>Sheet.methods.canDeleteBatch.call(vm,row)
expect(canDelete({id:1,createBy:'owner'})).toBe(true);expect(canDelete({id:1,createBy:'someone-else'})).toBe(false);expect(canDelete({id:1})).toBe(false)
vm.$auth.hasPermiOr=()=>false;expect(canDelete({id:1,createBy:'owner'})).toBe(false)
})
it('a rejected batch deletion keeps the sheet, collaboration and draft available',async()=>{
const batch={id:329,createBy:'owner'},vm={saving:false,deletingBatchId:null,loading:false,sheet:{batch,rows:[{id:8}]},canDeleteBatch:()=>true,$confirm:vi.fn(async()=>{}),clearDraft:vi.fn(),_live:{stop:vi.fn()}}
vi.mocked(request).mockRejectedValueOnce(new Error('有关联业务,禁止删除'))
await Sheet.methods.deleteBatch.call(vm,batch)
expect(vm.sheet.batch).toBe(batch);expect(vm.clearDraft).not.toHaveBeenCalled();expect(vm._live.stop).not.toHaveBeenCalled();expect(vm.saving).toBe(false);expect(vm.deletingBatchId).toBeNull()
})
it('using an active cell recommendation button does not tear down its editor or start a grid drag',()=>{
const root=document.createElement('div'),button=document.createElement('button');root.append(button)
const event={button:0,shiftKey:false,target:button,currentTarget:root,preventDefault:vi.fn()},vm={editCell:'row|category',saving:false,_editor:{flush:vi.fn()}}
Sheet.methods.startCellSelection.call(vm,{_key:'row'},'category',event)
expect(vm.editCell).toBe('row|category');expect(event.preventDefault).not.toHaveBeenCalled();expect(vm._editor.flush).not.toHaveBeenCalled();expect(vm._gridDragging).toBeUndefined()
})
it.each(['number','text'])('typing into a %s grid input does not invoke unsupported native text selection',async type=>{
const root=document.createElement('div'),cell=document.createElement('div'),input=document.createElement('input')
cell.className='sheet-cell';cell.dataset.row='0';cell.dataset.field='quantity';input.type=type;cell.append(input);root.append(cell)
const entered=vi.fn();input.addEventListener('input',entered)
const vm={$el:root,editableCell:()=>true,activateCell:vi.fn(),originalIndex:()=>0}
await expect(Sheet.methods.typeGridCell.call(vm,{},'quantity','12')).resolves.toBeUndefined()
expect(input.value).toBe('12');expect(entered).toHaveBeenCalledOnce();expect(vm._typingGrid).toBe(false)
if(type==='text')expect(input.selectionStart).toBe(2)
})
it('compact display filters rows without removing them from complete purchase saves',()=>{
const rows=[{_key:'zero',id:1,finalUnitPrice:0,purchaseStatus:0},{_key:'priced',id:2,finalUnitPrice:3,purchaseStatus:0}]
const vm={sheet:{rows},rowFilter:'',rowQueue:'all',rowSort:'original',onlyInvalid:false,compactAmounts:true,isEditing:false,viewReference:r=>r,projectName:()=>''}
vm.amountRowVisible=Sheet.methods.amountRowVisible.bind(vm)
expect(Sheet.computed.visibleRows.call(vm).map(r=>r.id)).toEqual([2])
expect(Sheet.methods.activeRows.call(vm).map(r=>r.id)).toEqual([1,2])
vm.isEditing=true;expect(vm.amountRowVisible({_key:'new',finalUnitPrice:0})).toBe(true)
})
it('viewing a moved target navigates to the full procurement route, not an embedded sheet replacement',async()=>{
const push=vi.fn(),openBatch=vi.fn(),vm={moveOutcome:72,saving:false,embedded:true,$route:{path:'/project/detail/1501',query:{}},$router:{push},openBatch}
await Sheet.methods.viewMoveTarget.call(vm)
expect(push).toHaveBeenCalledWith({path:'/procurement/details',query:{purchaseBatchId:'72'}})
expect(openBatch).not.toHaveBeenCalled();expect(vm.moveOutcome).toBeNull()
})
it('returning from a deep-linked batch removes its route parameter so reload and reopen work',async()=>{
const replace=vi.fn(),loadBatches=vi.fn(),vm={saving:false,dirty:false,sheet:{batch:{id:72}},embedded:false,$route:{path:'/procurement/details',query:{purchaseBatchId:'72',projectId:'9'}},$router:{replace},loadBatches}
await Sheet.methods.back.call(vm)
expect(replace).toHaveBeenCalledWith({path:'/procurement/details',query:{projectId:'9'}})
expect(vm.sheet).toBeNull();expect(loadBatches).not.toHaveBeenCalled()
})
it('target route navigation and back cooperate with the actual route watcher and query restoration',async()=>{
const router=createRouter({history:createMemoryHistory(),routes:[{path:'/procurement/details',component:{template:'<div/>'}}]})
await router.push('/procurement/details?purchaseBatchId=11');await router.isReady()
const vm=reactive({moveOutcome:72,saving:false,dirty:false,embedded:false,sheet:{batch:{id:11}},query:{},projectId:null,$router:router,_routeStamp:undefined,loadBatches:vi.fn(),openBatch:vi.fn(async batch=>{vm.sheet={batch}})})
Object.defineProperty(vm,'$route',{get:()=>router.currentRoute.value})
const stop=watch(()=>router.currentRoute.value.fullPath,()=>Sheet.methods.applyRoute.call(vm))
try{await Sheet.methods.viewMoveTarget.call(vm);await nextTick();expect(router.currentRoute.value.query.purchaseBatchId).toBe('72');expect(vm.sheet.batch.id).toBe(72)
await Sheet.methods.back.call(vm);await nextTick();expect(router.currentRoute.value.query.purchaseBatchId).toBeUndefined();expect(vm.sheet).toBeNull();expect(vm.loadBatches).toHaveBeenCalled()
}finally{stop()}
})
it('the actual undo/redo handlers commit buffered inputs and retain editor focus for repeated shortcuts',async()=>{
const root=document.createElement('div'),input=document.createElement('input');root.tabIndex=-1;root.append(input);document.body.append(root)
const vm=reactive({sheet:null,baseline:'',editing:true,isEditing:true,saving:false,history:[],redoHistory:[],selected:[],changedKeys:new Set(),persistDraft(){},$el:root,$nextTick:nextTick,focusSelectedCell:vi.fn()})
const editor=createSheetEditor(vm);vm._editor=editor;vm.finishCellEdit=Sheet.methods.finishCellEdit.bind(vm)
vm.sheet={batch:{},rows:[{_key:'r',quantity:1}],deletedIds:[]};vm.baseline=JSON.stringify(vm.sheet)
const canUndo=computed(()=>Sheet.computed.canUndo.call(vm))
try{editor.beginCell(vm.sheet.rows[0],'quantity');input.focus();input.addEventListener('blur',()=>{vm.sheet.rows[0].quantity=4},{once:true})
await Sheet.methods.undo.call(vm);expect(vm.sheet.rows[0].quantity).toBe(1);expect(document.activeElement).toBe(root)
await Sheet.methods.redo.call(vm);expect(vm.sheet.rows[0].quantity).toBe(4);expect(canUndo.value).toBe(true)
await Sheet.methods.undo.call(vm);expect(canUndo.value).toBe(false)
}finally{editor.stop();root.remove()}
})
it('spreadsheet copy uses the modern clipboard in secure contexts and falls back on internal HTTP',async()=>{
const copy=vi.fn(),exec=vi.fn(()=>true)
vi.stubGlobal('isSecureContext',true);Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:copy}})
try{await writeClipboardText('A\tB');expect(copy).toHaveBeenCalledWith('A\tB')
vi.stubGlobal('isSecureContext',false);Object.defineProperty(document,'execCommand',{configurable:true,value:exec});await writeClipboardText('C\tD');expect(exec).toHaveBeenCalledWith('copy');expect(document.querySelector('textarea')).toBeNull()
}finally{vi.unstubAllGlobals();delete navigator.clipboard;delete document.execCommand}
})
it('search input retains native shortcuts while grid shortcuts are intercepted exactly once',()=>{
const root=document.createElement('div'),field=document.createElement('input');field.className='search';root.append(field)
const undo=vi.fn(),redo=vi.fn(),vm={isEditing:true,saving:false,$el:root,undo,redo}
const event={target:field,key:'z',ctrlKey:true,preventDefault:vi.fn(),stopPropagation:vi.fn()}
Sheet.methods.editorShortcut.call(vm,event);expect(undo).not.toHaveBeenCalled();expect(event.preventDefault).not.toHaveBeenCalled()
event.target=root;Sheet.methods.editorShortcut.call(vm,event);expect(undo).toHaveBeenCalledOnce()
event.shiftKey=true;Sheet.methods.editorShortcut.call(vm,event);expect(redo).toHaveBeenCalledOnce()
})
it('a virtual window at the end retains the last row when density changes its capacity',()=>{
const vm={sheet:{},virtualized:true,visibleRows:Array.from({length:500}),virtualStart:476}
Sheet.watch.virtualCount.call(vm,23,24)
expect(vm.virtualStart).toBe(477);expect(vm.virtualStart+23).toBe(500)
vm.virtualStart=200;Sheet.watch.virtualCount.call(vm,25,23);expect(vm.virtualStart).toBe(200)
vm.virtualStart=477;Sheet.watch.virtualCount.call(vm,28,23);expect(vm.virtualStart).toBe(472)
})
it('closing a sheet leaves an empty virtual view without dereferencing its old rows',()=>{expect(Sheet.computed.visibleRows.call({sheet:null,rowFilter:'',rowSort:'original'})).toEqual([]);expect(()=>Sheet.watch.virtualCount.call({sheet:null},24,23)).not.toThrow()})
it('medium-size sheets use a window while their full row and clipboard scope stays available',()=>{
const rows=Array.from({length:100},(_,i)=>({_key:'row-'+i,quantity:i})),vm={visibleRows:rows,virtualStart:20,virtualCount:24}
vm.windowStart=Sheet.computed.windowStart.call(vm);vm.virtualized=Sheet.computed.virtualized.call(vm)
expect(vm.virtualized).toBe(true);expect(Sheet.computed.renderedRows.call(vm)).toEqual(rows.slice(20,44));expect(vm.visibleRows).toHaveLength(100)
})
it('draft-list discovery waits until leaving editing without deferring the draft write',()=>{
const vm={isEditing:true,drafts:[{key:'old'}],draftPrefix:vi.fn()}
Sheet.methods.refreshDrafts.call(vm);expect(vm.draftPrefix).not.toHaveBeenCalled();expect(vm.drafts).toEqual([{key:'old'}])
})
it('validation opens collapsed batch fields before focusing a missing required project',async()=>{
const focus=vi.fn(),vm={sheet:{unbatched:false},batchProject:{mixed:false},batchDetailsOpen:false,$nextTick:nextTick,$refs:{batchProjectSelect:{focus}}}
await Sheet.methods.focusError.call(vm,{field:'projectId'})
expect(vm.batchDetailsOpen).toBe(true);expect(focus).toHaveBeenCalledOnce()
})
it('foreign rows stay read-only including actual price, reopening, and confirmation selection',()=>{
const foreign={editable:false,id:1,purchaseStatus:0,historical:false,priceLocked:false},own={...foreign,editable:true,id:2}
const vm={isEditing:true,saving:false,compactAmounts:false}
expect(Sheet.methods.readonly.call(vm,foreign)).toBe(true)
expect(Sheet.methods.editableCell.call(vm,foreign,'actualUnitPrice')).toBe(false)
expect(Sheet.methods.canReopen.call(vm,foreign)).toBe(false)
expect(Sheet.computed.confirmationRows.call({selected:[foreign,own],visibleRows:[foreign,own]})).toEqual([own])
})
it('Escape removes only the active unfinished collaborative identity draft',async()=>{
const root=document.createElement('div'),vm={$el:root,editCell:'row|materialParams',sheet:{rows:[],liveText:{'row|materialParams':{value:'取消的输入'},'other|materialName':{value:'保留的输入'}}},$nextTick:nextTick,_editor:{cancelCell:vi.fn()},_identityEditor:{invalidate:vi.fn()}}
await Sheet.methods.finishCellEdit.call(vm,true)
expect(vm.sheet.liveText['row|materialParams']).toBeUndefined();expect(vm.sheet.liveText['other|materialName'].value).toBe('保留的输入');expect(vm.editCell).toBeNull()
})
it('ending live editing resolves the last save and never discards an uncertain receipt',async()=>{
const vm={live:{enabled:true},sheet:{batch:{id:1}},saving:false,editing:true,dirty:true,finishCellEdit:vi.fn(),_live:{settle:vi.fn(async()=>false)},save:vi.fn(),layout:vi.fn(),$modal:{msgWarning:vi.fn()}}
await Sheet.methods.cancelEditing.call(vm);expect(vm.save).not.toHaveBeenCalled();expect(vm.editing).toBe(true)
vm._live.settle.mockResolvedValue(true);vm.save.mockImplementation(async()=>{vm.dirty=false})
await Sheet.methods.cancelEditing.call(vm);expect(vm.save).toHaveBeenCalledOnce();expect(vm.editing).toBe(false)
})