cmvr-wms/ruoyi-ui-vue3/tests/runtime/purchase-category-batch.spec.js
lixiaolong 35bd4736e1 feat(item-category): 添加物品分类申请与审核管理功能
- 新增物品分类申请及审核记录相关数据库表结构
- 添加物品分类管理菜单及对应的角色权限配置
- 实现物品分类申请组件支持新增申请与历史记录查询
- 开发批量AI分类组件以支持采购明细的智能分类推荐
- 新增批量确认小类组件以便管理员快速处理待确认分类
- 构建物品分类管理页面提供分类审核调整及关联记录查看
2026-11-03 09:36:09 +08:00

117 lines
16 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 {it,expect,vi,afterEach} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Batch from '../../src/components/PurchaseSheet/BatchCategory.vue'
import Sheet from '../../src/components/PurchaseSheet/index.vue'
import {categoryBatchSource,runCategoryBatches,checkCategoryBatch} from '../../src/utils/purchase-category-batch'
import {recommendCategories,categoryGroups,submitCategoryApplications} from '../../src/api/warehouse/item-category'
import request from '../../src/utils/request'
import {invalidateItemCategories} from '../../src/utils/item-categories'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
vi.mock('@/api/warehouse/item-category',()=>({recommendCategories:vi.fn(),categoryGroups:vi.fn(),submitCategoryApplications:vi.fn()}))
const options=[{id:1,label:'电机',parentId:10,parentLabel:'机械与传动'}]
const source=(count=1)=>Array.from({length:count},(_,i)=>({_key:'r'+i,materialName:'伺服电机'+i,materialParams:'M1',materialBrand:'测试',category:i===1?'电机':''}))
const snapshot=rows=>categoryBatchSource(rows,()=>true,row=>rows.indexOf(row)).rows
afterEach(()=>{vi.clearAllMocks();invalidateItemCategories();document.body.innerHTML=''})
it('scope skips unnamed and locked rows and retains original line numbers',()=>{
const rows=source(4);rows[1].materialName=' ';const batch=categoryBatchSource(rows,row=>row._key!=='r2',row=>rows.indexOf(row))
expect(batch.skipped).toEqual({unnamed:1,locked:1});expect(batch.rows.map(row=>row.line)).toEqual([1,4]);expect(batch.rows[0].name).toBe('伺服电机0')
})
it('packets deduplicate all descriptions, limit concurrency and map shuffled/missing results by key',async()=>{
const rows=snapshot(source(40));rows.push({...rows[0],key:'duplicate',line:99});let active=0,max=0;const sent=[];const results=new Map()
const request=vi.fn(async items=>{active++;max=Math.max(max,active);sent.push(...items);await new Promise(resolve=>setTimeout(resolve,5));active--;return {data:{rows:items.filter(item=>item.key!=='r3').reverse().map(item=>({key:item.key,recommendations:[{label:item.name}]}))}}})
const result=await runCategoryBatches(rows,{request,onResult:(key,answer)=>results.set(key,answer)})
expect(result).toEqual({total:41,uniqueCount:40});expect(sent).toHaveLength(40);expect(request).toHaveBeenCalledTimes(4);expect(max).toBe(3)
expect(results.size).toBe(41);expect(results.get('r3').error).toBeTruthy();expect(results.get('r8').recommendations[0].label).toBe('伺服电机8');expect(results.get('duplicate')).toEqual(results.get('r0'))
})
it('cancellation preserves completed packets and suppresses late responses',async()=>{
const rows=snapshot(source(5)),controller=new AbortController(),answers=[];let finish
const request=vi.fn().mockResolvedValueOnce({data:{rows:[{key:'r0'},{key:'r1'}]}}).mockImplementation(()=>new Promise(resolve=>finish=resolve))
const work=runCategoryBatches(rows,{request,signal:controller.signal,packetSize:2,concurrency:1,onResult:key=>answers.push(key)})
await vi.waitFor(()=>expect(request).toHaveBeenCalledTimes(2));controller.abort();finish({data:{rows:[{key:'r2'},{key:'r3'}]}});await work;expect(answers).toEqual(['r0','r1']);expect(request).toHaveBeenCalledTimes(2)
})
it('large selections are split into packets without silently truncating any row',async()=>{
const rows=snapshot(source(1001)),completed=[];let sent=0
await runCategoryBatches(rows,{request:async items=>{sent+=items.length;expect(items.length).toBeLessThanOrEqual(12);return {data:{rows:items.map(item=>({key:item.key,recommendations:[{label:'电机'}]}))}}},onResult:key=>completed.push(key)})
expect(sent).toBe(1001);expect(new Set(completed).size).toBe(1001)
})
it('all rows are checked for stale identities and permission changes before applying',()=>{
const rows=source(2),entries=snapshot(rows).map(row=>({...row,value:'电机'}))
expect(checkCategoryBatch(entries,rows,()=>true)).toHaveLength(2);rows[1].materialParams='changed';expect(()=>checkCategoryBatch(entries,rows,()=>true)).toThrow('第 2 行已变化');expect(rows[0].category).toBe('')
rows[1].materialParams='M1';expect(()=>checkCategoryBatch(entries,rows,row=>row._key!=='r0')).toThrow('第 1 行');expect(()=>checkCategoryBatch([...entries,entries[0]],rows,()=>true)).toThrow()
})
it('only-unclassified mode preserves existing categories and allows editing suggestions before one apply',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]});recommendCategories.mockResolvedValue({data:{rows:[{key:'r0',suggestions:[{label:'夹爪',group:'机械与传动',reason:'末端执行器'}]}]}})
const apply=vi.fn().mockResolvedValue(),wrapper=mount(Batch,{props:{apply},global:{plugins:[ElementPlus]},attachTo:document.body})
await wrapper.vm.open({rows:snapshot(source(2)),scope:'所选明细',skipped:{locked:1}});await flushPromises()
const scopeOption=[...document.body.querySelectorAll('.el-radio-button')].find(option=>option.textContent==='仅未分类');scopeOption.click();await flushPromises()
let button=[...document.body.querySelectorAll('button')].find(b=>b.textContent.includes('开始推荐'));expect(button.textContent).toContain('1');button.click();await flushPromises()
expect(recommendCategories).toHaveBeenCalledWith([expect.objectContaining({key:'r0'})],expect.any(AbortSignal));expect(document.body.textContent).toContain('1 个新小类')
expect(document.body.querySelector('.category-batch-new').textContent).toContain('新分类名称');expect(document.body.querySelector('.category-batch-new').textContent).toContain('所属大类');expect(document.body.querySelector('.category-batch-new').querySelectorAll('.el-select')).toHaveLength(1)
const name=document.body.querySelector('input[placeholder="填写新小类名称"]');name.value='气动夹爪';name.dispatchEvent(new Event('input',{bubbles:true}));await flushPromises()
button=[...document.body.querySelectorAll('button')].find(b=>b.textContent.includes('应用所选'));button.click();await flushPromises();expect(apply).toHaveBeenCalledOnce();expect(apply.mock.calls[0][0]).toHaveLength(1);expect(apply.mock.calls[0][0][0].proposed.label).toBe('气动夹爪');wrapper.unmount()
})
it('switching between new and existing categories retains manual edits and submits only the chosen mode',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]});recommendCategories.mockResolvedValue({data:{rows:[{key:'r0',recommendations:[{label:'电机'}]}]}})
const apply=vi.fn().mockResolvedValue(),wrapper=mount(Batch,{props:{apply},global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open({rows:snapshot(source()),scope:'所选明细'});await flushPromises()
const button=label=>[...document.body.querySelectorAll('button')].find(b=>b.textContent.trim()===label)
button('开始推荐(1)').click();await flushPromises();expect(document.body.querySelector('.category-batch-existing').textContent).toContain('电机')
button('申请新分类').click();await flushPromises();const name=document.body.querySelector('input[placeholder="填写新小类名称"]');name.value='微型传动件';name.dispatchEvent(new Event('input',{bubbles:true}));await flushPromises()
button('改用已有分类').click();await flushPromises();expect(document.body.querySelector('.category-batch-new')).toBeNull();expect(document.body.querySelector('.category-batch-existing').textContent).toContain('电机')
button('申请新分类').click();await flushPromises();expect(document.body.querySelector('input[placeholder="填写新小类名称"]').value).toBe('微型传动件')
button('改用已有分类').click();await flushPromises();button('应用所选(1)').click();await flushPromises();expect(apply.mock.calls[0][0][0]).toMatchObject({value:'电机',proposed:null});wrapper.unmount()
})
it('the batch form only uses existing groups and does not accept an AI-created group',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]});recommendCategories.mockResolvedValue({data:{rows:[{key:'r0',suggestions:[{label:'亲和填料',group:'生物材料',newGroup:true}]}]}})
const wrapper=mount(Batch,{props:{apply:vi.fn()},global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open({rows:snapshot(source()),scope:'所选明细'});await flushPromises()
const button=label=>[...document.body.querySelectorAll('button')].find(b=>b.textContent.trim()===label);button('开始推荐(1)').click();await flushPromises();expect(document.body.querySelector('.category-batch-new')).toBeNull();expect(button('应用所选(0)').disabled).toBe(true)
button('申请新分类').click();await flushPromises();expect(document.body.textContent).toContain('所属大类');expect(document.body.textContent).not.toContain('申请新大类');expect(document.body.textContent).not.toContain('新大类名称');wrapper.unmount()
})
it('parent applies a bulk request once, keeps quantities and prices, and records one undo step',async()=>{
const rows=source(2);rows[0].quantity=3;rows[0].finalUnitPrice=55;rows[0].actualUnitPrice=40
const entries=snapshot(rows).map(row=>({...row,value:'__new_category__',proposed:{label:'夹爪',parentCode:10,reason:'测试分类'}}))
request.mockResolvedValueOnce({data:options}).mockResolvedValueOnce({data:[...options,{id:'pending-1',label:'夹爪',reviewStatus:'PENDING'}]});submitCategoryApplications.mockResolvedValue({data:[{label:'夹爪',canUse:true}]})
const sheet={rows},remember=vi.fn(),vm={sheet,_batchCategorySheet:sheet,isEditing:true,saving:false,editableCell:()=>true,remember,_identityEditor:{invalidate:vi.fn()},$modal:{msgSuccess:vi.fn()}}
await Sheet.methods.applyBatchCategories.call(vm,entries);expect(submitCategoryApplications).toHaveBeenCalledOnce();expect(submitCategoryApplications.mock.calls[0][0]).toHaveLength(1);expect(remember).toHaveBeenCalledOnce();expect(remember.mock.calls[0][0]).toHaveLength(2)
expect(rows.map(row=>row.category)).toEqual(['夹爪','夹爪']);expect(rows[0]).toMatchObject({quantity:3,finalUnitPrice:55,actualUnitPrice:40})
})
it('existing classifications are included by default and can be recommended and applied together',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]})
const original=source(2);original.forEach(row=>row.category='配件');recommendCategories.mockImplementation(async items=>({data:{rows:items.map(item=>({key:item.key,recommendations:[{label:'电机'}]}))}}))
const apply=vi.fn().mockResolvedValue(),wrapper=mount(Batch,{props:{apply},global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open({rows:snapshot(original),scope:'所选明细'});await flushPromises()
expect(document.body.querySelector('.el-radio-button.is-active').textContent).toBe('全部明细(含已有分类)')
const button=label=>[...document.body.querySelectorAll('button')].find(b=>b.textContent.includes(label));button('开始推荐(2)').click();await flushPromises()
expect(recommendCategories.mock.calls[0][0].map(row=>row.key)).toEqual(['r0','r1']);expect(original.map(row=>row.category)).toEqual(['配件','配件'])
button('应用所选(2)').click();await flushPromises();expect(apply.mock.calls[0][0].map(row=>({original:row.category,next:row.value}))).toEqual([{original:'配件',next:'电机'},{original:'配件',next:'电机'}]);wrapper.unmount()
})
it('completed recommendations survive scope changes and remaining classified rows can be processed',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]});recommendCategories.mockImplementation(async items=>({data:{rows:items.map(item=>({key:item.key,recommendations:[{label:'电机'}]}))}}))
const wrapper=mount(Batch,{props:{apply:vi.fn()},global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open({rows:snapshot(source(2)),scope:'所选明细'});await flushPromises()
const mode=label=>[...document.body.querySelectorAll('.el-radio-button')].find(option=>option.textContent===label),button=label=>[...document.body.querySelectorAll('button')].find(b=>b.textContent.includes(label))
mode('仅未分类').click();await flushPromises();button('开始推荐(1)').click();await flushPromises();expect(document.body.textContent).toContain('推荐完成 1 / 1')
mode('全部明细(含已有分类)').click();await flushPromises();expect(document.body.textContent).toContain('待继续推荐 1 / 2');expect(button('继续 / 重试推荐(1)').disabled).toBe(false)
button('继续 / 重试推荐(1)').click();await flushPromises();expect(recommendCategories.mock.calls[1][0].map(row=>row.key)).toEqual(['r1']);expect(document.body.textContent).toContain('推荐完成 2 / 2');expect(button('应用所选(2)').disabled).toBe(false);wrapper.unmount()
})
it('parent can replace existing classifications without creating another category or changing other fields',async()=>{
const rows=source(2);rows.forEach(row=>{row.id=10+Number(row._key.slice(1));row.productId=20;row.category='配件';row.quantity=2;row.finalUnitPrice=9})
const entries=snapshot(rows).map(row=>({...row,value:'电机'})),sheet={rows},remember=vi.fn();request.mockResolvedValue({data:options})
const vm={sheet,_batchCategorySheet:sheet,isEditing:true,saving:false,editableCell:()=>true,remember,_identityEditor:{invalidate:vi.fn()},$modal:{msgSuccess:vi.fn()}}
await Sheet.methods.applyBatchCategories.call(vm,entries);expect(rows.map(row=>row.category)).toEqual(['电机','电机']);expect(submitCategoryApplications).not.toHaveBeenCalled();expect(remember).toHaveBeenCalledOnce();expect(rows.every(row=>row.quantity===2&&row.finalUnitPrice===9&&row.productId===20)).toBe(true)
})
it('retrying after stop is not completed or overwritten by the previous request',async()=>{
request.mockResolvedValue({data:options});categoryGroups.mockResolvedValue({data:[{id:10,label:'机械与传动'}]});const resolvers=[]
recommendCategories.mockImplementation(()=>new Promise(resolve=>resolvers.push(resolve)))
const wrapper=mount(Batch,{props:{apply:vi.fn()},global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open({rows:snapshot(source()),scope:'所选明细'});await flushPromises()
const button=label=>[...document.body.querySelectorAll('button')].find(b=>b.textContent.includes(label))
button('开始推荐').click();await flushPromises();const firstSignal=recommendCategories.mock.calls[0][1];button('停止推荐').click();await flushPromises();expect(firstSignal.aborted).toBe(true)
button('继续 / 重试推荐').click();await flushPromises();resolvers[0]({data:{rows:[{key:'r0',recommendations:[{label:'错误旧结果'}]}]}});await flushPromises();expect(button('停止推荐')).toBeTruthy()
resolvers[1]({data:{rows:[{key:'r0',recommendations:[{label:'电机'}]}]}});await flushPromises();expect(document.body.textContent).toContain('推荐完成 1 / 1');expect(document.body.textContent).not.toContain('错误旧结果');wrapper.unmount()
})
it('stale rows after a network wait leave every local category unchanged',async()=>{
const rows=source(2),entries=snapshot(rows).map(row=>({...row,value:'电机'})),sheet={rows};let finish
request.mockImplementation(()=>new Promise(resolve=>finish=resolve));const vm={sheet,_batchCategorySheet:sheet,isEditing:true,saving:false,editableCell:()=>true,remember:vi.fn(),$modal:{msgSuccess:vi.fn()}}
const operation=Sheet.methods.applyBatchCategories.call(vm,entries);rows[1].materialBrand='changed';finish({data:options});await expect(operation).rejects.toThrow('第 2 行已变化');expect(vm.remember).not.toHaveBeenCalled();expect(rows[0].category).toBe('');expect(submitCategoryApplications).not.toHaveBeenCalled()
})