import { afterEach, expect, it, vi } from 'vitest' import { mount, flushPromises } from '@vue/test-utils' import { computed, nextTick, reactive } from 'vue' import ElementPlus from 'element-plus' import Sheet from '@/components/PurchaseSheet/index.vue' import Cell from '@/components/PurchaseSheet/Cell.vue' import { createSheetEditor } from '@/utils/purchase-sheet-editor' import { clearPurchaseGrid } from '@/utils/purchase-grid-edit' vi.mock('@/utils/request',()=>({default:vi.fn()})) vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})})) vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})})) const cleanup=[] afterEach(()=>{cleanup.splice(0).forEach(fn=>fn());vi.restoreAllMocks()}) function fixture(){ const vm=reactive({sheet:null,baseline:'',editing:true,isEditing:true,saving:false,history:[],redoHistory:[],selected:[],changedKeys:new Set(),cellSelection:null,editCell:null,items:[],categories:[],projects:[],plans:[],units:['个'],rowFilter:'',onlyInvalid:false,rowQueue:'all',rowSort:'original',canAdd:true,compactAmounts:false, columns:[{field:'materialName',label:'物品名称'},{field:'materialBrand',label:'品牌'},{field:'quantity',label:'数量'},{field:'finalUnitPrice',label:'报价单价'},{field:'actualUnitPrice',label:'实际单价'}], batchProject:{mixed:false,value:71},commonCategory:9,projectId:null,rowMenu:null,pastePreviewOpen:false,pasteApplying:false,pasteText:'',pasteStartField:'',insertRowsOpen:false,insertRowsCount:5,persistDraft(){},revealRow:async()=>nextTick(),$nextTick:nextTick,$modal:{msgWarning:vi.fn(),msgError:vi.fn()},fieldLocked:()=>false,canEditCategory:()=>true,$auth:{hasPermiOr:()=>true},cellError:()=>'',nameChoices:()=>[],rememberCell(index,field){this._editor.beginCell(this.sheet.rows[index],field)},menu(){},menuOpen:()=>false,brands:()=>[],currentSpec:()=>[],identityEditor:()=>({}),nameMenu(){},nameChanged(row,value){row.materialName=value},brandChanged(){}, }) for(const name of ['readonly','editableCell','isGridSelected','isGridTypingCell','focusGridCell','startCellSelection','extendCellSelection','endCellSelection','focusSelectedCell','originalIndex','activateCell','typeGridCell','navigate','finishCellEdit','clearGridSelection','remember','undo','redo','displayCell','applyGridText','paste','fillGrid','serialize','rowDefaults','emptyRow','installInsertedRows','appendAfterTab','rowCommand','insertManyRows','remove','applyPastePreview','resetRowView'])vm[name]=Sheet.methods[name].bind(vm) Object.defineProperties(vm,{visibleRows:{get:()=>vm.sheet.rows},rowIndexMap:{get:()=>new Map(vm.sheet.rows.map((r,i)=>[r._key,i]))},visibleRowIndexMap:{get:()=>vm.rowIndexMap},cellRange:{get:()=>Sheet.computed.cellRange.call(vm)},contextRow:{get:()=>Sheet.computed.contextRow.call(vm)},canRemoveSelection:{get:()=>Sheet.computed.canRemoveSelection.call(vm)}}) vm._editor=createSheetEditor(vm) vm.sheet={batch:{},deletedIds:[],rows:[{_key:'r1',materialName:'原物品',materialBrand:'原品牌',quantity:2,unit:'个',finalUnitPrice:3,actualUnitPrice:4},{_key:'r2',materialName:'第二项',materialBrand:'乙品牌',quantity:5,unit:'个',finalUnitPrice:6,actualUnitPrice:7}]} vm.baseline=JSON.stringify(vm.sheet) const wrapper=mount({components:{Cell},setup:()=>({vm}),template:'
'},{attachTo:document.body,global:{plugins:[ElementPlus],stubs:{ItemCategorySelect:true}}}) vm.$el=wrapper.element Object.defineProperty(Element.prototype,'scrollIntoView',{configurable:true,value:vi.fn()}) cleanup.push(()=>{vm._editor.stop();wrapper.unmount()}) return {vm,wrapper,cell:(r,f)=>wrapper.find(`.sheet-cell[data-row="${r}"][data-field="${f}"]`)} } async function select(cell){await cell.trigger('mousedown',{button:0});window.dispatchEvent(new MouseEvent('mouseup'));await flushPromises()} it('a single selected cell accepts replacement text without double-click and Escape cancels only that edit',async()=>{ const {vm,cell}=fixture();await select(cell(0,'materialBrand')) const proxy=cell(0,'materialBrand').find('.sheet-keyboard-input') expect(document.activeElement).toBe(proxy.element) await proxy.setValue('新品牌');await flushPromises() expect(cell(0,'materialBrand').find('input').element.value).toBe('新品牌') await cell(0,'materialBrand').find('input').trigger('keydown',{key:'Escape'});await flushPromises() expect(vm.sheet.rows[0].materialBrand).toBe('原品牌');expect(vm.history).toHaveLength(0) }) it('Chinese IME stays in one input until composition ends, then commits the complete replacement',async()=>{ const {vm,cell}=fixture();await select(cell(0,'materialBrand'));const input=cell(0,'materialBrand').find('.sheet-keyboard-input') await input.trigger('compositionstart');input.element.value='zhong';await input.trigger('input',{isComposing:true});expect(vm.editCell).toBeNull() input.element.value='中文品牌';await input.trigger('compositionend');await flushPromises() expect(cell(0,'materialBrand').find('input').element.value).toBe('中文品牌') await cell(0,'materialBrand').find('input').trigger('keydown',{key:'Enter',code:'Enter'});await flushPromises() expect(vm.sheet.rows[0].materialBrand).toBe('中文品牌') }) it('Delete clears the selected rectangle without deleting rows, and undo/redo covers the whole rectangle',async()=>{ const {vm,cell}=fixture();await select(cell(0,'materialBrand')) vm.cellSelection.focus={key:'r2',field:'materialBrand'};await nextTick() await cell(1,'materialBrand').trigger('keydown',{key:'Delete'});await flushPromises() expect(vm.sheet.rows.map(r=>r.materialBrand)).toEqual(['','']);expect(vm.sheet.deletedIds).toEqual([]) await vm.undo();expect(vm.sheet.rows.map(r=>r.materialBrand)).toEqual(['原品牌','乙品牌']) await vm.redo();expect(vm.sheet.rows.map(r=>r.materialBrand)).toEqual(['','']) }) it('a protected cell aborts the entire clear operation, including earlier editable cells',()=>{ const rows=[{_key:'a',quantity:1},{_key:'b',quantity:2}] expect(()=>clearPurchaseGrid(rows,[{field:'quantity',label:'数量'}],{top:0,bottom:1,left:0,right:0},row=>row._key==='a')).toThrow('当前不可修改') expect(rows.map(r=>r.quantity)).toEqual([1,2]) }) it('clearing an identity detaches the archive; read-only mode cannot clear or type',async()=>{ const {vm}=fixture();vm.sheet.rows[0].productId=9;vm.sheet.rows[0].productCode='WP9';vm.sheet.rows[0].loanId=7 vm.cellSelection={anchor:{key:'r1',field:'materialBrand'},focus:{key:'r1',field:'materialBrand'}} await vm.clearGridSelection();expect(vm.sheet.rows[0].productId).toBeNull();expect(vm.sheet.rows[0].loanId).toBeNull() vm.isEditing=false;await vm.typeGridCell(vm.sheet.rows[0],'materialBrand','禁止修改');expect(vm.sheet.rows[0].materialBrand).toBe('') }) it('typing numeric values, Enter down, Tab across, and Shift+Tab work without losing buffered prices',async()=>{ const {vm,cell}=fixture();await select(cell(0,'actualUnitPrice')) await cell(0,'actualUnitPrice').find('.sheet-keyboard-input').setValue('12.34');await flushPromises() await cell(0,'actualUnitPrice').find('input').trigger('keydown',{key:'Enter'});await flushPromises() expect(vm.sheet.rows[0].actualUnitPrice).toBe('12.34');expect(vm.cellSelection.focus).toEqual({key:'r2',field:'actualUnitPrice'}) await cell(1,'actualUnitPrice').find('input').trigger('keydown',{key:'Tab',shiftKey:true});await flushPromises() expect(vm.cellSelection.focus.field).toBe('finalUnitPrice') }) it('fill-down uses the first selected row, is undoable, and does not touch unselected values',async()=>{ const {vm}=fixture();vm.cellSelection={anchor:{key:'r1',field:'finalUnitPrice'},focus:{key:'r2',field:'finalUnitPrice'}} await vm.fillGrid('down');expect(vm.sheet.rows.map(r=>r.finalUnitPrice)).toEqual([3,3]);expect(vm.sheet.rows[1].quantity).toBe(5) await vm.undo();expect(vm.sheet.rows[1].finalUnitPrice).toBe(6) vm.cellSelection={anchor:{key:'r1',field:'finalUnitPrice'},focus:{key:'r1',field:'actualUnitPrice'}} await vm.fillGrid('right');expect(vm.sheet.rows[0].actualUnitPrice).toBe(3) }) it('Home/End and Shift+arrows extend the rectangular selection',async()=>{ const {vm,cell}=fixture();await select(cell(0,'quantity')) await cell(0,'quantity').find('input').trigger('keydown',{key:'ArrowDown',shiftKey:true});await flushPromises() expect(vm.cellRange).toEqual({top:0,bottom:1,left:2,right:2}) await cell(1,'quantity').trigger('keydown',{key:'End',ctrlKey:true});await flushPromises() expect(vm.cellSelection.focus).toEqual({key:'r2',field:'actualUnitPrice'}) }) it('Escape in the next selected cell never reverts an already committed price',async()=>{ const {vm,cell}=fixture();await select(cell(0,'actualUnitPrice')) await cell(0,'actualUnitPrice').find('input').setValue('88');await flushPromises() await cell(0,'actualUnitPrice').find('input').trigger('keydown',{key:'Enter'});await flushPromises() await cell(1,'actualUnitPrice').find('input').trigger('keydown',{key:'Escape'});await flushPromises() expect(vm.sheet.rows[0].actualUnitPrice).toBe('88') await vm.undo();expect(vm.sheet.rows[0].actualUnitPrice).toBe(4) }) it('forward Tab at the final editable cell commits the value and creates one undoable blank row',async()=>{ const {vm,cell}=fixture();await select(cell(1,'actualUnitPrice')) await cell(1,'actualUnitPrice').find('input').setValue('12.34');await flushPromises() await cell(1,'actualUnitPrice').find('input').trigger('keydown',{key:'Tab'});await flushPromises() expect(vm.sheet.rows).toHaveLength(3);expect(vm.sheet.rows[1].actualUnitPrice).toBe('12.34') expect(vm.sheet.rows[2]).toMatchObject({id:null,projectId:71,expenseCategoryId:9,materialName:'',finalUnitPrice:null}) expect(vm.cellSelection.focus).toEqual({key:vm.sheet.rows[2]._key,field:'materialName'}) await vm.undo();expect(vm.sheet.rows).toHaveLength(2);expect(vm.sheet.rows[1].actualUnitPrice).toBe('12.34') await vm.redo();expect(vm.sheet.rows).toHaveLength(3) await select(cell(2,'actualUnitPrice'));await cell(2,'actualUnitPrice').find('input').trigger('keydown',{key:'Tab'});await flushPromises();expect(vm.sheet.rows).toHaveLength(3) }) it.each(['filtered','sorted','no-add'])('final Tab does not silently append when the view or permission is %s',async kind=>{ const {vm,cell}=fixture();if(kind==='filtered')vm.rowFilter='物品';if(kind==='sorted')vm.rowSort='nameAsc';if(kind==='no-add')vm.canAdd=false await select(cell(1,'actualUnitPrice'));await cell(1,'actualUnitPrice').find('input').trigger('keydown',{key:'Tab'});await flushPromises();expect(vm.sheet.rows).toHaveLength(2) }) it('row menu insertion, copying and deletion each remain local and undoable',async()=>{ const {vm}=fixture();vm.rowMenu={key:'r1'};await vm.rowCommand('after');expect(vm.sheet.rows).toHaveLength(3);expect(vm.sheet.rows[1].materialName).toBe('') await vm.undo();expect(vm.sheet.rows.map(r=>r._key)).toEqual(['r1','r2']) vm.selected=[vm.sheet.rows[0]];vm.rowMenu={key:'r2'};await vm.rowCommand('duplicate');expect(vm.sheet.rows).toHaveLength(3);expect(vm.sheet.rows[2]).toMatchObject({materialName:'原物品',id:null,finalUnitPrice:null,actualUnitPrice:null}) await vm.undo();vm.selected=[vm.sheet.rows[0]];vm.rowMenu={key:'r1'};await vm.rowCommand('remove');expect(vm.sheet.rows.map(r=>r._key)).toEqual(['r2']) await vm.undo();expect(vm.sheet.rows.map(r=>r._key)).toEqual(['r1','r2']) }) it('protected rows block menu deletion and lost add permission blocks insertion',async()=>{ const {vm}=fixture();vm.sheet.rows[0].historical=true;vm.selected=[vm.sheet.rows[0]];vm.rowMenu={key:'r1'};await vm.rowCommand('remove');expect(vm.sheet.rows).toHaveLength(2) vm.canAdd=false;vm.rowMenu={key:'r1'};await vm.rowCommand('before');expect(vm.sheet.rows).toHaveLength(2);expect(vm.history).toHaveLength(0) }) it('inserting several rows validates the count and stale anchor before changing the sheet',async()=>{ const {vm}=fixture();vm.rowMenu={key:'r1'};await vm.rowCommand('many');expect(vm.insertRowsOpen).toBe(true);vm.insertRowsCount=3;await vm.insertManyRows();expect(vm.sheet.rows).toHaveLength(5) await vm.undo();expect(vm.sheet.rows).toHaveLength(2) vm._insertContext={sheet:vm.sheet,key:'removed'};vm.insertRowsCount=1;await vm.insertManyRows();expect(vm.sheet.rows).toHaveLength(2);expect(vm.$modal.msgWarning).toHaveBeenCalled() }) it('rectangular clipboard text opens a preview without changing any row until explicitly applied',async()=>{ const {vm}=fixture();const before=vm.serialize(vm.sheet),event={clipboardData:{getData:()=> '数量\t品牌\n3\t新品牌\n4\t乙品牌'},target:{matches:()=>false},preventDefault:vi.fn()} await vm.paste(event,0,'materialName');expect(vm.pastePreviewOpen).toBe(true);expect(vm.serialize(vm.sheet)).toBe(before);expect(vm.history).toHaveLength(0) await vm.applyPastePreview({fields:['materialBrand','quantity'],text:'新品牌\t3\n乙品牌\t4'});expect(vm.pastePreviewOpen).toBe(false) expect(vm.sheet.rows.map(r=>[r.materialBrand,r.quantity,r.finalUnitPrice])).toEqual([['新品牌',3,3],['乙品牌',4,6]]) await vm.undo();expect(vm.serialize(vm.sheet)).toBe(before) }) it('a locked target or forged field leaves the entire paste unapplied and the preview open',async()=>{ const {vm}=fixture();vm.pastePreviewOpen=true;vm._pasteContext={sheet:vm.sheet,key:'r1'};vm.fieldLocked=row=>row._key==='r2' const before=vm.serialize(vm.sheet);await vm.applyPastePreview({fields:['quantity'],text:'3\n4'});expect(vm.serialize(vm.sheet)).toBe(before);expect(vm.pastePreviewOpen).toBe(true);expect(vm.history).toHaveLength(0) await vm.applyPastePreview({fields:['id'],text:'777'});expect(vm.serialize(vm.sheet)).toBe(before) }) it('unit failures stay in the editable paste preview and a corrected retry applies once with one undo',async()=>{ const {vm}=fixture();vm.columns.push({field:'unit',label:'单位'});vm.items=[{id:1,productName:'原物品',brand:'原品牌',unit:'个'},{id:2,productName:'第二项',brand:'乙品牌',unit:'个'}];vm.pastePreviewOpen=true;vm._pasteContext={sheet:vm.sheet,key:'r1'};const before=vm.serialize(vm.sheet) await vm.applyPastePreview({fields:['unit'],text:'台\n件',sourceStartLine:2});expect(vm.pasteIssues.map(issue=>[issue.sourceLine,issue.line,issue.materialName,issue.currentValue,issue.expectedValue])).toEqual([[2,1,'原物品','台','个'],[3,2,'第二项','件','个']]);expect(vm.pastePreviewOpen).toBe(true);expect(vm.serialize(vm.sheet)).toBe(before);expect(vm.history).toHaveLength(0);expect(vm.$modal.msgError).not.toHaveBeenCalled() await vm.applyPastePreview({fields:['unit'],text:'个\n个',sourceStartLine:2});expect(vm.pasteIssues).toEqual([]);expect(vm.pastePreviewOpen).toBe(false);expect(vm.sheet.rows.map(row=>row.productId)).toEqual([1,2]);expect(vm.history).toHaveLength(1);await vm.undo();expect(vm.serialize(vm.sheet)).toBe(before) })