feat(assistant): 支持物品档案类别的更正与同步更新
- 在业务助手中添加对物品类别更正的支持,允许用户手动纠正类别 - 实现类别更正后的档案同步更新功能,确保数据一致性 - 添加权限控制验证,仅授权用户可执行类别更正操作 - 优化采购单编辑界面,显示类别更正的相关提示信息 - 修复批量项目设置时跳过已执行行的问题 - 增强物品档案匹配逻辑,保留显式类别更正而不被覆盖 - 完善单元测试覆盖类别更正的各种场景
This commit is contained in:
parent
7e6dafcaf5
commit
8bc6c3b10f
@ -36,7 +36,7 @@ public final class AssistantBusinessRules {
|
||||
case "budget.save" -> List.of("预算金额是该项目该经费科目的目标总额,不是本次增减额;若用户只给增减额,应先查询当前预算。", "已有预算未要求修改的预警比例、调整说明应保留;预警比例范围0至100。设置预算不代表确认采购或实际付款。");
|
||||
case "budget.query" -> List.of("查询所选项目各经费科目预算,区别预算总额、已锁定采购费用和剩余额度。");
|
||||
case "budget.ledger" -> List.of("查询预算和采购费用变动流水,不把它解释成实际银行收付款流水。");
|
||||
case "purchase.create", "purchase.update" -> List.of("采购与实际在线表格相同:按名称、品牌、规格精确匹配物品档案,未匹配时可在人工确认后自动建档;productId可不填,不得要求先手工建档才能采购。模糊同名多规格不能强行选中。", "维护物品名称、品牌、规格、类别、单位;品牌和规格是文本,类别和单位必须选择业务字典已有值,禁止自动新建字典。匹配已有档案时单位固定、已有非空类别沿用。", "采购报价可留空。purchaseBatchId选择已有批次;batchName非空表示新建批次,两者互斥,同名新批次行归入同批。均空表示未组批;更新未要求改批次时保留原批次。", "供应商在创建新批次时可选;采购日期省略时使用预览中固定的当天日期。保存采购清单不锁价、不下单、不登记到货。", "整张采购草稿一次事务提交,确认前可补齐或修改全部行,不能声称已执行或绕过未通过校验的行。");
|
||||
case "purchase.create", "purchase.update" -> List.of("采购与实际在线表格相同:按名称、品牌、规格精确匹配物品档案,未匹配时可在人工确认后自动建档;productId可不填,不得要求先手工建档才能采购。模糊同名多规格不能强行选中。", "维护物品名称、品牌、规格、类别、单位;品牌和规格是文本,类别和单位必须选择业务字典已有值,禁止自动新建字典。匹配已有档案时单位固定;未要求修改类别时沿用档案类别。用户明确更正类别时保留指定值,提示确认后同步更正物品档案,服务端校验物品维护权限和有效字典;不能悄悄覆盖用户的更正,也不能直接执行。", "采购报价可留空。purchaseBatchId选择已有批次;batchName非空表示新建批次,两者互斥,同名新批次行归入同批。均空表示未组批;更新未要求改批次时保留原批次。", "供应商在创建新批次时可选;采购日期省略时使用预览中固定的当天日期。保存采购清单不锁价、不下单、不登记到货。", "整张采购草稿一次事务提交,确认前可补齐或修改全部行,不能声称已执行或绕过未通过校验的行。");
|
||||
case "purchase.delete" -> List.of("按原采购明细删除,已有锁价、到货等业务须遵守业务校验,不自动删除关联记录。");
|
||||
case "purchase.query", "purchase.history" -> List.of("区分采购需求、采购锁价、到货验收与入库,不把采购数量当作当前库存;同物品不同项目、批次是不同明细。");
|
||||
case "purchase.totals" -> List.of("按采购筛选条件查询汇总数量和金额,统计以系统汇总结果为准,不将列表当前页相加冒充全部采购总额。");
|
||||
|
||||
@ -438,7 +438,7 @@ public class BusinessActionRegistry {
|
||||
Map<List<String>,Map<String,Object>> itemPlans=new HashMap<>();
|
||||
for(var row:rows) {
|
||||
if(row.get("id")!=null&&!ids.add(row.get("id").toString()))errors.add("同一采购明细不能在本次草稿中重复修改");
|
||||
if(row.get("_itemResolution") instanceof Map<?,?> resolution&&!"EXISTING".equals(resolution.get("kind"))) {
|
||||
if(row.get("_itemResolution") instanceof Map<?,?>) {
|
||||
List<String> identity=List.of("materialName","materialBrand","materialParams").stream().map(field->Objects.toString(row.get(field),"").trim().replaceAll("\\s+"," ").toLowerCase(Locale.ROOT)).toList();
|
||||
Map<String,Object> previous=itemPlans.putIfAbsent(identity,row);
|
||||
if(previous!=null&&(!Objects.equals(previous.get("unit"),row.get("unit"))||!Objects.equals(previous.get("category"),row.get("category"))))errors.add("物品【"+row.get("materialName")+"】名称、品牌、规格相同,单位或类别却不一致,请核对后统一");
|
||||
@ -473,7 +473,7 @@ public class BusinessActionRegistry {
|
||||
result.put("productId",match.getId());
|
||||
snapshots.put("purchaseCatalog",itemSnapshot(match));
|
||||
if(Objects.toString(result.get("unit"),"").isBlank())result.put("unit",match.getUnit());
|
||||
if(!Objects.toString(match.getCategory(),"").isBlank())result.put("category",match.getCategory());
|
||||
if(Objects.toString(result.get("category"),"").isBlank())result.put("category",match.getCategory());
|
||||
}
|
||||
} catch(ServiceException exception) { errors.add(exception.getMessage()); }
|
||||
return result;
|
||||
@ -492,12 +492,20 @@ public class BusinessActionRegistry {
|
||||
PurchaseSheetService sheets=context.getBean(PurchaseSheetService.class);
|
||||
try {
|
||||
if(!Objects.toString(row.get("materialName"),"").isBlank()&&!Objects.toString(row.get("unit"),"").isBlank()&&!Objects.toString(row.get("category"),"").isBlank()) {
|
||||
PurchaseRequest request=(PurchaseRequest)buildArguments(action,payload(action,row),false)[0];
|
||||
var preview=sheets.previewItem(request); ProductInfo item=preview.item();
|
||||
snapshots.put("itemResolution",Map.of("kind",preview.kind(),"item",itemSnapshot(item)));
|
||||
row.put("productId",item.getId());row.put("materialName",item.getProductName());row.put("materialBrand",item.getBrand());row.put("materialParams",item.getSpec());row.put("unit",item.getUnit());row.put("category",item.getCategory());
|
||||
row.put("_itemResolution",Map.of("kind",preview.kind(),"label",switch(preview.kind()){case "CREATE"->"确认后新增物品档案";case "FILL_CATEGORY"->"使用已有档案并补充类别";default->"使用已有物品档案";}));
|
||||
if(item.getId()!=null)labels.put("productId",label("item",itemSnapshot(item)));
|
||||
// Item preview must not deserialize unresolved supplier/project/batch
|
||||
// candidates as numeric IDs and misreport them as an item-format error.
|
||||
var itemValues=new LinkedHashMap<String,Object>();
|
||||
for(String key:List.of("productId","materialName","materialBrand","materialParams","unit","category"))
|
||||
if(row.containsKey(key))itemValues.put(key,row.get(key));
|
||||
if(itemValues.values().stream().noneMatch(value->value instanceof Map<?,?>||value instanceof Collection<?>)) {
|
||||
PurchaseRequest request=json.convertValue(itemValues,PurchaseRequest.class);
|
||||
var preview=sheets.previewItem(request); ProductInfo item=preview.item();
|
||||
snapshots.put("itemResolution",Map.of("kind",preview.kind(),"item",itemSnapshot(item)));
|
||||
row.put("productId",item.getId());row.put("materialName",item.getProductName());row.put("materialBrand",item.getBrand());row.put("materialParams",item.getSpec());row.put("unit",item.getUnit());row.put("category",item.getCategory());
|
||||
row.put("_itemResolution",Map.of("kind",preview.kind(),"label",switch(preview.kind()){case "CREATE"->"确认后新增物品档案";case "FILL_CATEGORY"->"使用已有档案并补充类别";case "UPDATE_CATEGORY"->"确认后同步更正物品档案类别";default->"使用已有物品档案";}));
|
||||
row.put("_assistantCanEditCategory",com.ruoyi.common.utils.SecurityUtils.isAdmin()||com.ruoyi.common.utils.SecurityUtils.hasPermi("warehouse:product:edit"));
|
||||
if(item.getId()!=null)labels.put("productId",label("item",itemSnapshot(item)));
|
||||
}
|
||||
}
|
||||
} catch(ServiceException exception) { errors.add(exception.getMessage()); }
|
||||
catch(IllegalArgumentException exception) { errors.add("物品资料格式不正确"); }
|
||||
|
||||
@ -38,6 +38,24 @@ import static org.mockito.Mockito.*;
|
||||
/** Real MySQL saves/locks run inside a rollback-only transaction, never against another database. */
|
||||
@EnabledIfSystemProperty(named="projectDbTests", matches="true")
|
||||
class PurchaseSheetDatabaseTest {
|
||||
@Test void savedPurchaseCategoryCanBeCorrectedWithoutChangingIdentityOrQuotesAndOldRowsDoNotUndoIt() throws Exception {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
new TransactionTemplate(f.manager).executeWithoutResult(status->{
|
||||
status.setRollbackOnly();var saved=f.save(f.draft());var before=f.copy(saved);Long productId=saved.getRows().get(0).getProductId();
|
||||
saved.getRows().get(0).setCategory("更正类别");var changed=f.save(saved);var reopened=f.service.load(changed.getBatch().getId());
|
||||
assertEquals("更正类别",reopened.getRows().get(0).getCategory());
|
||||
assertEquals("更正类别",f.jdbc.queryForObject("select category from product_info where id=?",String.class,productId));
|
||||
for(int i=0;i<2;i++) {assertEquals(before.getRows().get(i).getProductId(),reopened.getRows().get(i).getProductId());assertEquals(before.getRows().get(i).getQuantity(),reopened.getRows().get(i).getQuantity());assertEquals(before.getRows().get(i).getFinalUnitPrice(),reopened.getRows().get(i).getFinalUnitPrice());}
|
||||
reopened.getRows().get(1).setRemark("仅修改备注,不撤销档案类别更正");f.save(reopened);
|
||||
assertEquals("更正类别",f.jdbc.queryForObject("select category from product_info where id=?",String.class,productId));
|
||||
var invalid=f.service.load(changed.getBatch().getId());invalid.getRows().get(0).setCategory("不存在的类别");assertThrows(ServiceException.class,()->f.save(invalid));
|
||||
assertEquals("更正类别",f.jdbc.queryForObject("select category from product_info where id=?",String.class,productId));
|
||||
});
|
||||
}
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
||||
}
|
||||
@Test void supplierInquiryRoundTripSavesOnlyConfirmedPreviewPricesThroughNativeSheetService() throws Exception {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
@ -379,9 +397,10 @@ class PurchaseSheetDatabaseTest {
|
||||
SupplierService supplier=new SupplierService();set(supplier,"db",jdbc);
|
||||
set(purchaseTarget,"businessNumbers",allocator);
|
||||
ISysDictTypeService dict=mock(ISysDictTypeService.class);SysDictData unit=new SysDictData();unit.setDictLabel("件");unit.setStatus("0");when(dict.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));
|
||||
set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别"));set(productTarget,"itemCategories",itemCategories);
|
||||
set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别","更正类别"));set(productTarget,"itemCategories",itemCategories);
|
||||
PurchaseSheetService target=new PurchaseSheetService();set(target,"batches",session.getMapper(PurchaseBatchMapper.class));set(target,"requests",purchases);set(target,"catalog",catalog);set(target,"products",productService);set(target,"purchases",proxy(purchaseTarget));set(target,"prices",prices);set(target,"suppliers",supplier);set(target,"catalogLock",lock);set(target,"jdbc",jdbc);set(target,"json",new ObjectMapper().findAndRegisterModules());set(target,"dictTypes",dict);
|
||||
set(target,"batchNumbers",numbers);set(target,"operationLogs",logs); service=proxy(target);
|
||||
set(target,"itemCategories",itemCategories);
|
||||
}
|
||||
PurchaseSheet draft() {
|
||||
jdbc.update("insert into supplier_info(name,active,create_by) values(?,1,'sheet-rollback-test')",name);
|
||||
|
||||
@ -12,6 +12,7 @@ import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
import com.ruoyi.warehouse.service.IProductInfoService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
|
||||
import com.ruoyi.warehouse.service.impl.CatalogWriteLock;
|
||||
import com.ruoyi.warehouse.service.impl.ItemCategoryService;
|
||||
import com.ruoyi.web.controller.warehouse.PurchaseRequestController;
|
||||
import jakarta.validation.Validator;
|
||||
import java.math.BigDecimal;
|
||||
@ -42,6 +43,7 @@ class AssistantPurchaseSheetContractTest {
|
||||
final ISysDictTypeService dictionaries=mock(ISysDictTypeService.class);
|
||||
final PurchaseSheetService sheets=spy(new PurchaseSheetService());
|
||||
final CatalogWriteLock catalogLock=mock(CatalogWriteLock.class);
|
||||
final ItemCategoryService itemCategories=mock(ItemCategoryService.class);
|
||||
final List<ProductInfo> items=new ArrayList<>();
|
||||
final Map<Long,Map<String,Object>> purchases=new HashMap<>();
|
||||
BusinessActionRegistry registry;
|
||||
@ -60,6 +62,7 @@ class AssistantPurchaseSheetContractTest {
|
||||
when(context.getBean(CatalogWriteLock.class)).thenReturn(catalogLock);
|
||||
ReflectionTestUtils.setField(sheets,"catalog",catalog);ReflectionTestUtils.setField(sheets,"products",products);
|
||||
ReflectionTestUtils.setField(sheets,"dictTypes",dictionaries);ReflectionTestUtils.setField(sheets,"json",json);
|
||||
ReflectionTestUtils.setField(sheets,"itemCategories",itemCategories);when(itemCategories.labels()).thenReturn(List.of("零件","配件"));
|
||||
when(catalog.selectProductInfoAll()).thenAnswer(invocation->new ArrayList<>(items));
|
||||
when(products.previewImport(anyList())).thenReturn(List.of());
|
||||
SysDictData unit=new SysDictData();unit.setDictLabel("个");unit.setStatus("0");
|
||||
@ -80,7 +83,7 @@ class AssistantPurchaseSheetContractTest {
|
||||
if(sql.contains("from supplier_info"))return List.of(Map.of("id",3L,"name","测试供应商"));
|
||||
if(sql.contains("from product_info"))return items.stream().filter(item->!(referenceId instanceof Number)||Objects.equals(item.getId(),number(referenceId))).map(this::itemMap).toList();
|
||||
if(sql.contains("wms_item_unit"))return dictionaryEnabled?List.of(Map.of("id","个","name","个","code","UNIT")):List.of();
|
||||
if(sql.contains("wms_item_category"))return dictionaryEnabled?List.of(Map.of("id","零件","name","零件","code","PART")):List.of();
|
||||
if(sql.contains("wms_item_category"))return dictionaryEnabled?List.of(Map.of("id","零件","name","零件","code","PART"),Map.of("id","配件","name","配件","code","ACCESSORY")):List.of();
|
||||
return List.of();
|
||||
});
|
||||
when(controller.saveSheet(any())).thenAnswer(invocation->{
|
||||
@ -106,6 +109,26 @@ class AssistantPurchaseSheetContractTest {
|
||||
assertEquals("CREATE",kind(row));assertNull(row.get("productId"));assertEquals("SELF",row.get("purchasePurpose"));
|
||||
verify(products).previewImport(anyList());verify(products,never()).insertProductInfo(any());verify(products,never()).updateProductInfo(any());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void unrelatedUnresolvedReferencesDoNotTurnValidNewItemsIntoFormatErrors() {
|
||||
for(String field:List.of("projectId","expenseCategoryId","supplierId","purchaseBatchId")) {
|
||||
var input=raw("r-"+field);input.put(field,Map.of("keyword","待核对的名称"));
|
||||
if("supplierId".equals(field))input.put("batchName","待核对批次");
|
||||
var preview=registry.prepare("purchase.create",List.of(input));
|
||||
assertEquals(false,preview.get("ready"));
|
||||
var row=((List<Map<String,Object>>)preview.get("rows")).get(0);
|
||||
assertEquals("CREATE",kind(row),field);
|
||||
assertFalse(preview.get("errors").toString().contains("物品资料格式"),field);
|
||||
assertEquals(new BigDecimal("2"),row.get("quantity"));assertEquals("M4",row.get("materialParams"));
|
||||
}
|
||||
verify(products,never()).insertProductInfo(any());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void unresolvedItemDictionaryDoesNotSkipBatchChecksOrCreateAnItem() {
|
||||
dictionaryEnabled=false;var input=raw("r1");input.put("supplierId",3L);
|
||||
var preview=registry.prepare("purchase.create",List.of(input));
|
||||
assertEquals(false,preview.get("ready"));
|
||||
assertTrue(preview.get("errors").toString().contains("新批次名称"));
|
||||
verify(products,never()).insertProductInfo(any());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void exactIdentityAutofillsCatalogFieldsAndAllowsHistoricalDictionaryValues() {
|
||||
var existing=item(4L,"M4");existing.setUnit("旧单位");existing.setCategory("旧类别");items.add(existing);dictionaryEnabled=false;
|
||||
var input=raw("r1");input.remove("unit");input.remove("category");
|
||||
@ -113,6 +136,23 @@ class AssistantPurchaseSheetContractTest {
|
||||
assertEquals("EXISTING",kind(row));assertEquals(4L,row.get("productId"));assertEquals("旧单位",row.get("unit"));assertEquals("旧类别",row.get("category"));
|
||||
verify(products,never()).previewImport(anyList());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void categoryCorrectionIsPreviewOnlyPreservesIdentityAndRequiresArchiveEditPermission() {
|
||||
var existing=item(4L,"M4");items.add(existing);
|
||||
PurchaseRequest request=new PurchaseRequest();request.setProductId(4L);request.setMaterialName("螺丝");request.setMaterialBrand("标准");request.setMaterialParams("M4");request.setUnit("个");request.setCategory("配件");
|
||||
var preview=sheets.previewItem(request);assertEquals("UPDATE_CATEGORY",preview.kind());assertEquals("配件",preview.item().getCategory());assertEquals("零件",existing.getCategory());
|
||||
verify(products,never()).updateProductInfo(any());
|
||||
request.setCategory("未维护类别");assertThrows(ServiceException.class,()->sheets.previewItem(request));
|
||||
request.setCategory("配件");SysUser user=new SysUser();user.setUserId(8L);user.setUserName("purchase-only");
|
||||
var login=new LoginUser(8L,1L,user,Set.of("warehouse:purchase:edit"));SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null));
|
||||
assertTrue(assertThrows(ServiceException.class,()->sheets.previewItem(request)).getMessage().contains("物品维护权限"));
|
||||
}
|
||||
@Test void assistantKeepsExplicitCategoryCorrectionAndShowsArchiveSideEffectBeforeConfirmation() {
|
||||
items.add(item(4L,"M4"));var input=raw("r1");input.put("category","配件");
|
||||
var row=ready("purchase.create",List.of(input)).get(0);
|
||||
assertEquals("UPDATE_CATEGORY",kind(row));assertEquals("配件",row.get("category"));assertEquals(4L,row.get("productId"));
|
||||
assertTrue(row.get("_itemResolution").toString().contains("同步更正"));assertEquals(true,row.get("_assistantCanEditCategory"));
|
||||
assertEquals("零件",items.get(0).getCategory());verify(products,never()).updateProductInfo(any());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void newItemCannotInventDictionaryAndDifferentSpecIsNotMerged() {
|
||||
items.add(item(4L,"M5"));var valid=ready("purchase.create",List.of(raw("r1"))).get(0);
|
||||
assertEquals("CREATE",kind(valid));assertNull(valid.get("productId"));
|
||||
|
||||
@ -29,6 +29,7 @@ public class PurchaseSheetService
|
||||
@Autowired private JdbcTemplate jdbc;
|
||||
@Autowired private ObjectMapper json;
|
||||
@Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes;
|
||||
@Autowired private ItemCategoryService itemCategories;
|
||||
|
||||
@Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
|
||||
public PurchaseSheet load(Long id)
|
||||
@ -184,6 +185,7 @@ public class PurchaseSheetService
|
||||
if (row.getId() == null) requirePermission("add");
|
||||
}
|
||||
List<Long> deleted = sheet.getDeletedIds() == null ? List.of() : sheet.getDeletedIds();
|
||||
validateCategoryCorrections(sheet.getRows(),old);
|
||||
for (Long id : deleted) {
|
||||
if (!old.containsKey(id) || !submitted.add(id)) throw new ServiceException("删除明细不属于当前批次或重复提交");
|
||||
requirePermission("remove");
|
||||
@ -216,7 +218,7 @@ public class PurchaseSheetService
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
resolveItem(row, items);
|
||||
resolveItem(row, items, existing);
|
||||
row.setPurchaseBatchId(batch.getId());
|
||||
row.setEstimatedUnitPrice(row.getFinalUnitPrice());
|
||||
if (existing == null) {
|
||||
@ -298,11 +300,12 @@ public class PurchaseSheetService
|
||||
var old=new HashMap<Long,PurchaseRequest>();
|
||||
for(Long id:ids){var row=requests.selectPurchaseRequestByIdForUpdate(id);if(row==null||row.getPurchaseBatchId()!=null||committed(row)||Integer.valueOf(5).equals(row.getPurchaseStatus()))throw new ServiceException("明细已组批、已确认或已有到货,请刷新后处理");old.put(id,requests.selectPurchaseRequestById(id,null));}
|
||||
if(!ids.isEmpty()&&!Objects.equals(sheet.getVersion(),unbatchedSnapshot(new ArrayList<>(old.values())).getVersion()))throw new ServiceException("明细已被其他操作更新,请重新打开后再保存");
|
||||
validateCategoryCorrections(sheet.getRows(),old);
|
||||
var items=new ArrayList<>(catalog.selectProductInfoAll());var saved=new ArrayList<PurchaseRequest>();int line=0;
|
||||
for(var row:sheet.getRows()){
|
||||
line++;
|
||||
try{if(row.getId()==null||!sameEditable(old.get(row.getId()),row)){
|
||||
resolveItem(row,items);row.setPurchaseBatchId(null);row.setPurchaseBatchNo(null);row.setEstimatedUnitPrice(row.getFinalUnitPrice());
|
||||
resolveItem(row,items,old.get(row.getId()));row.setPurchaseBatchId(null);row.setPurchaseBatchNo(null);row.setEstimatedUnitPrice(row.getFinalUnitPrice());
|
||||
if(row.getId()==null){row.setRequestNo(null);row.setHistorical(false);purchases.insertPurchaseRequest(row);}else purchases.updatePurchaseRequest(row);
|
||||
}saved.add(requests.selectPurchaseRequestById(row.getId(),null));}catch(Exception e){throw new ServiceException("第"+line+"行:"+e.getMessage());}
|
||||
}
|
||||
@ -370,7 +373,15 @@ public class PurchaseSheetService
|
||||
} else if (!norm(row.getUnit()).isEmpty() && !norm(row.getUnit()).equals(norm(match.getUnit()))) {
|
||||
throw new ServiceException("单位与物品档案不一致,不能将不同单位混用");
|
||||
}
|
||||
if(norm(match.getCategory()).isEmpty()) {
|
||||
if(!norm(match.getCategory()).isEmpty() && !norm(row.getCategory()).isEmpty() && !norm(match.getCategory()).equals(norm(row.getCategory()))) {
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:product:edit"))
|
||||
throw new ServiceException("更正已有物品类别需要物品维护权限,可联系管理员协助处理");
|
||||
if(!itemCategories.labels().contains(clean(row.getCategory())))throw new ServiceException("物品类别不存在或已停用,请先在业务字典维护后再选择");
|
||||
match=json.convertValue(match,ProductInfo.class);match.setCategory(clean(row.getCategory()));
|
||||
ProductInfo duplicate=catalog.checkProductInfoUnique(match);
|
||||
if(duplicate!=null&&!Objects.equals(duplicate.getId(),match.getId()))throw new ServiceException("该类别下已存在相同物品,请选择已有档案");
|
||||
kind="UPDATE_CATEGORY";
|
||||
} else if(norm(match.getCategory()).isEmpty()) {
|
||||
if(norm(row.getCategory()).isEmpty())throw new ServiceException("请选择物品类别");
|
||||
// The preview must not mutate a shared mapper/cache result.
|
||||
match = json.convertValue(match, ProductInfo.class);
|
||||
@ -382,10 +393,19 @@ public class PurchaseSheetService
|
||||
|
||||
private void resolveItem(PurchaseRequest row, List<ProductInfo> items)
|
||||
{
|
||||
resolveItem(row,items,null);
|
||||
}
|
||||
private void resolveItem(PurchaseRequest row,List<ProductInfo> items,PurchaseRequest existing)
|
||||
{
|
||||
// An unchanged historical snapshot is not a request to undo a newer archive correction.
|
||||
if(existing!=null&&norm(existing.getCategory()).equals(norm(row.getCategory()))) {
|
||||
ProductInfo current=findItem(row,items);
|
||||
if(current!=null)row.setCategory(current.getCategory());
|
||||
}
|
||||
ItemPreview plan = planItem(row, items);
|
||||
ProductInfo match = plan.item();
|
||||
if ("CREATE".equals(plan.kind())) { products.insertProductInfo(match); items.add(match); }
|
||||
else if ("FILL_CATEGORY".equals(plan.kind())) {
|
||||
else if (Set.of("FILL_CATEGORY","UPDATE_CATEGORY").contains(plan.kind())) {
|
||||
products.updateProductInfo(match);
|
||||
items.replaceAll(item -> Objects.equals(item.getId(), match.getId()) ? match : item);
|
||||
}
|
||||
@ -394,6 +414,18 @@ public class PurchaseSheetService
|
||||
row.setMaterialParams(match.getSpec()); row.setCategory(match.getCategory()); row.setUnit(match.getUnit());
|
||||
}
|
||||
|
||||
private void validateCategoryCorrections(List<PurchaseRequest> rows,Map<Long,PurchaseRequest> old) {
|
||||
var corrections=new HashMap<List<String>,String>();
|
||||
for(var row:rows) {
|
||||
var previous=old.get(row.getId());
|
||||
if(previous!=null&&norm(previous.getCategory()).equals(norm(row.getCategory())))continue;
|
||||
String category=norm(row.getCategory());
|
||||
if(category.isEmpty())throw new ServiceException("请选择物品类别");
|
||||
String first=corrections.putIfAbsent(identity(row),category);
|
||||
if(first!=null&&!first.equals(category))throw new ServiceException("同一物品填写了不同类别,请统一后再保存,避免反复覆盖物品档案");
|
||||
}
|
||||
}
|
||||
|
||||
static List<String> identity(PurchaseRequest row) { return List.of(norm(row.getMaterialName()), norm(row.getMaterialBrand()), norm(row.getMaterialParams())); }
|
||||
static List<String> identity(ProductInfo row) { return List.of(norm(row.getProductName()), norm(row.getBrand()), norm(row.getSpec())); }
|
||||
private static String text(String value) { return value == null ? "" : value; }
|
||||
|
||||
1436
ruoyi-ui-vue3/package-lock.json
generated
1436
ruoyi-ui-vue3/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -10,7 +10,7 @@
|
||||
<assistant-purchase-project v-if="sharedProject && projectField" :action="draft.action" :field="projectField" :rows="rows" :draft="draft" :editable="editable" :busy="busy" @change="$emit('change',$event)" />
|
||||
<p v-else-if="purchase && projectField" class="assistant-purchase-note">本确认单存在多个项目或采购批次,保留逐行项目供核对,不会自动合并归属。</p>
|
||||
<div v-if="purchase" class="assistant-purchase-navigation"><el-radio-group v-model="fieldGroup" size="small" aria-label="采购确认单字段分组"><el-radio-button v-for="group in purchaseGroups" :key="group.key" :value="group.key">{{ group.label }}</el-radio-button><el-radio-button value="all">全部字段</el-radio-button></el-radio-group><span>{{ selectedIds.length ? `已选 ${selectedIds.length} 项 · ` : '' }}可横向滚动查看各列</span></div>
|
||||
<p v-if="purchase && editable && (fieldGroup === 'items' || fieldGroup === 'all')" class="assistant-purchase-note">选择已有物品可带入档案信息;新物品确认后建档。单位、类别须选用已维护的业务字典。</p>
|
||||
<p v-if="purchase && editable && (fieldGroup === 'items' || fieldGroup === 'all')" class="assistant-purchase-note">选择已有物品可带入档案信息;新物品确认后建档。单位、类别须选用业务字典。更正已有物品类别会同步修改物品档案,确认后才保存。</p>
|
||||
<p v-if="purchase && fieldGroup === 'batch'" class="assistant-purchase-note">{{ draft.action === 'purchase.update' ? '已有采购的所属批次保持不变;调整批次请使用采购界面的转批次功能。' : '选择已有批次,或填写新批次名称;两者均不填则保存为未组批明细。采购日期以校验预览为准,供应商可稍后补充。' }}</p>
|
||||
<el-table ref="draftTable" :data="pageRows" row-key="_rowId" border :max-height="tableHeight" class="assistant-data-table" :row-class-name="rowClass" @selection-change="setSelection">
|
||||
<el-table-column v-if="editable && bulkFields.length && rows.length > 1" type="selection" width="42" :fixed="tableLayout.fixed ? 'left' : false" reserve-selection :selectable="row => !busy && !isSucceeded(row)" />
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
<div class="assistant-purchase-project__control">
|
||||
<assistant-field v-if="editable" :action="action" :field="field" :row="valueRow" :disabled="busy" @change="apply" />
|
||||
<span v-else>{{ valueRow._labels.projectId || valueRow.projectId?.keyword || valueRow.projectId || '待填写' }}</span>
|
||||
<el-button v-if="editable && state.missing && state.value" :disabled="busy" size="small" @click="apply({ value:state.value, label:valueRow._labels.projectId })">统一应用到未填项</el-button>
|
||||
<el-button v-if="editable && state.missing && assistantRecordId(state.value)" :disabled="busy" size="small" @click="apply({ value:state.value, label:valueRow._labels.projectId })">统一应用到未填项</el-button>
|
||||
</div>
|
||||
<p v-if="state.missing" class="assistant-purchase-project__notice">{{ state.missing }} 项待填写项目,可在这里统一补充。</p>
|
||||
<p v-if="notice" class="assistant-purchase-project__notice" role="status">{{ notice }}</p>
|
||||
@ -15,16 +15,20 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import AssistantField from './AssistantField.vue'
|
||||
import { purchaseProjectState } from '@/utils/purchase-project'
|
||||
import { assistantBulkChanges } from '@/utils/assistant-draft-edit'
|
||||
import { assistantPurchaseProjectChanges, assistantRecordId } from '@/utils/assistant-draft-edit'
|
||||
const props=defineProps({action:String,field:{type:Object,required:true},rows:{type:Array,default:()=>[]},draft:{type:Object,required:true},editable:Boolean,busy:Boolean})
|
||||
const emit=defineEmits(['change']),notice=ref('')
|
||||
const state=computed(()=>purchaseProjectState(props.rows))
|
||||
const valueRow=computed(()=>({projectId:state.value.value,_labels:{projectId:props.rows.find(row=>String(row.projectId)===String(state.value.value))?._labels?.projectId||''},_candidates:{projectId:props.rows.flatMap(row=>row._candidates?.projectId||[]).filter((item,index,items)=>items.findIndex(other=>String(other.value)===String(item.value))===index)}}))
|
||||
function apply(event){
|
||||
if(props.busy||!props.editable)return
|
||||
const changes=assistantBulkChanges(props.rows,props.field,event,{action:props.action,draft:props.draft,overwrite:true})
|
||||
if(!changes.length)return
|
||||
emit('change',{changes});notice.value=`已统一设置 ${changes.length} 条可编辑明细;其他物品、数量、报价不变,请重新校验。`
|
||||
try {
|
||||
const changes=assistantPurchaseProjectChanges(props.rows,props.field,event,{action:props.action,draft:props.draft})
|
||||
if(!changes.length)return
|
||||
emit('change',{changes});notice.value=`已统一设置 ${changes.length} 条明细;其他物品、数量、报价不变,请重新校验。`
|
||||
} catch {
|
||||
notice.value='部分明细已执行或不可编辑,不能统一更换项目;原数据未改动,请按原项目继续处理。'
|
||||
}
|
||||
}
|
||||
watch(()=>[props.draft.id,props.draft.version],()=>{notice.value=''})
|
||||
</script>
|
||||
|
||||
@ -83,6 +83,7 @@
|
||||
<div class="sheet-filter-inputs"><el-input v-model="rowFilter" clearable placeholder="搜索物品、规格或项目" :disabled="saving"/><el-select v-model="rowSort" aria-label="采购明细排序" :disabled="saving"><el-option v-for="sort in sortOptions" :key="sort.value" :value="sort.value" :label="sort.label"/></el-select><el-button :disabled="saving" @click="resetRowView">重置</el-button></div>
|
||||
</div>
|
||||
<div class="sheet-selection"><span>{{ selected.length?'已选 '+selected.length+' 项':'筛选结果 '+visibleRows.length+' 项' }}</span><el-button v-if="rowQueue==='arrival'" link type="primary" :disabled="saving||isEditing" @click="selectEligible">选择可到货项</el-button><el-button v-if="selected.length" link :disabled="saving" @click="selected=[]">清空选择</el-button></div>
|
||||
<p v-if="isEditing" class="sheet-project-note">更正已有物品的类别将在保存时同步修改物品档案,其他业务中的档案分类也会更新;已有到货的明细仍需先按流程退回。</p>
|
||||
<div ref="tableStage" class="sheet-table" data-viewport-explicit>
|
||||
<el-table key="batch-sheet" ref="grid" :data="renderedRows" border size="small" :height="gridHeight" class="sheet-grid" :style="virtualStyle" @scroll="scrollGrid" row-key="_key" :empty-text="'没有符合当前筛选的数据'">
|
||||
<el-table-column key="selection" width="45" fixed="left" class-name="business-control-cell"><template #header><el-checkbox :model-value="allGridSelected" :indeterminate="someGridSelected" aria-label="选择全部筛选结果" @change="selectAllRows"/></template><template #default="s"><el-checkbox :model-value="selectedKeys.has(s.row._key)" :aria-label="'选择第'+(originalIndex(s.row)+1)+'行'" @change="toggleGridRow(s.row,$event)"/></template></el-table-column>
|
||||
@ -307,7 +308,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
brands(row){return [...new Set(candidates(this.items,row,'brand').map(i=>i.brand).filter(Boolean))]},specs(row){return candidates(this.items,row,'spec')},
|
||||
async searchPlans(row,keyword){const result=await purchasePlanOptions({projectId:row.projectId,keyword});const map=new Map(this.plans.map(p=>[p.id,p]));(result.data||[]).forEach(p=>map.set(p.id,p));this.plans=[...map.values()]},
|
||||
rowPlans(row){return this.plans.filter(p=>String(p.projectId)===String(row.projectId))},rowUnits(row){return [...new Set([...this.units,...(row.productId&&row.unit?[row.unit]:[])])]},
|
||||
canEditCategory(row){const item=this.itemMap.get(String(row.productId));return !item || !clean(item.category)},
|
||||
canEditCategory(row){const item=this.itemMap.get(String(row.productId));return !item || !clean(item.category) || this.$auth.hasPermiOr(['warehouse:product:edit'])},
|
||||
identityEditor(){return this._identityEditor||(this._identityEditor=createRowIdentityEditor({getItems:()=>this.items,loadName:name=>this.loadName(name),isCurrentRow:row=>this.isEditing&&!!this.sheet?.rows.includes(row),onDetach:row=>this.clearLoan(row)}))},
|
||||
nameChanged(row,value=row.materialName){return this.identityEditor().nameChanged(row,value)},
|
||||
brandChanged(row){this.identityEditor().brandChanged(row)},
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { isAssistantPending } from './business-assistant.js'
|
||||
import { purchaseBatchProjectChanges } from './purchase-project.js'
|
||||
|
||||
export function isAssistantPurchase(action) {
|
||||
return ['purchase.create', 'purchase.update'].includes(action)
|
||||
@ -45,6 +46,7 @@ export function assistantFieldLocked(action, row, field) {
|
||||
const boundItem = assistantRecordId(row.productId)
|
||||
if (boundItem && field.key === 'unit') return true
|
||||
if (boundItem && field.key === 'category') {
|
||||
if (row._assistantCanEditCategory === true) return false
|
||||
const category = row._assistantCatalogCategory
|
||||
if (category !== undefined) return !!category
|
||||
return (row._itemResolution?.kind || row._itemResolution) !== 'FILL_CATEGORY' && !!row.category
|
||||
@ -57,7 +59,8 @@ export function assistantItemResolution(row) {
|
||||
const states = {
|
||||
EXISTING: { label: '使用已有档案', type: 'success' },
|
||||
CREATE: { label: '确认后新建档案', type: 'warning' },
|
||||
FILL_CATEGORY: { label: '确认后补全档案类别', type: 'warning' }
|
||||
FILL_CATEGORY: { label: '确认后补全档案类别', type: 'warning' },
|
||||
UPDATE_CATEGORY: { label: '确认后同步更正物品档案类别', type: 'warning' }
|
||||
}
|
||||
const status = states[row._itemResolution?.kind || row._itemResolution]
|
||||
return status ? { ...status, label: row._itemResolution?.label || status.label } : null
|
||||
@ -132,6 +135,14 @@ export function assistantApplyDraftChanges(rows, event, { action, fields = [], d
|
||||
})
|
||||
}
|
||||
|
||||
// A common batch project must not silently skip rows already executed or locked.
|
||||
export function assistantPurchaseProjectChanges(rows, field, input, { action, draft } = {}) {
|
||||
if (field?.key !== 'projectId' || !isAssistantPurchase(action) || !assistantRecordId(input?.value)) return []
|
||||
if (!isAssistantPending(draft) || draft.readOnly || draft.permissionDenied) return []
|
||||
purchaseBatchProjectChanges(rows, input.value, row => !assistantRowSucceeded(draft, row) && !assistantFieldLocked(action, row, field))
|
||||
return assistantBulkChanges(rows, field, input, { action, draft, overwrite: true })
|
||||
}
|
||||
|
||||
export function assistantBulkChanges(rows, field, input, { action, draft, overwrite = false, selectedIds = null } = {}) {
|
||||
if (!field?.batch || field.hidden || field.key.startsWith('_') || field.type === 'table' || !scalarValue(input?.value) || input?.value == null || input.value === '') return []
|
||||
if (field.ref && !['unit', 'category'].includes(field.ref) && !assistantRecordId(input.value)) return []
|
||||
|
||||
@ -69,7 +69,8 @@ export function resolveRow(row, items) {
|
||||
if(!selected)throw new Error('相同物品存在多份档案,请明确选择规格编码')
|
||||
applyItem(row,selected)
|
||||
} else { row.productId=null;row.productCode=null }
|
||||
if(row.productId && !clean(row.category) && category)row.category=category
|
||||
// An explicit classification correction must survive archive matching and save.
|
||||
if(category)row.category=category
|
||||
return row
|
||||
}
|
||||
export function collectRowErrors(rows, items, lineNumbers = [], allowedUnits, allowedCategories) {
|
||||
@ -87,7 +88,7 @@ export function collectRowErrors(rows, items, lineNumbers = [], allowedUnits, al
|
||||
try { resolveRow(row,items) } catch(error) { add(error.message.includes('单位')?'unit':'materialParams',error.message) }
|
||||
if(!clean(row.category))add('category','请选择物品类别')
|
||||
const catalogItem=items.find(item=>String(item.id)===String(row.productId))
|
||||
if(clean(row.category) && (!catalogItem || !clean(catalogItem.category)) && allowedCategories && !allowedCategories.includes(clean(row.category)))add('category','物品类别不存在或已停用,请先在业务字典维护')
|
||||
if(clean(row.category) && (!catalogItem || !same(row.category,catalogItem.category)) && allowedCategories && !allowedCategories.includes(clean(row.category)))add('category','物品类别不存在或已停用,请先在业务字典维护')
|
||||
if(!row.productId && clean(row.unit) && allowedUnits && !allowedUnits.some(unit=>same(unit,row.unit)))add('unit','请选择字典中的单位')
|
||||
if(row.purchasePurpose==='REPAY'&&!row.loanId)add('loanId','请选择归还的借用记录')
|
||||
const key=itemKey(row), previous=units.get(key)
|
||||
|
||||
@ -84,6 +84,16 @@ test('catalog with no category allows filling it but never changing the catalog
|
||||
assert.equal(assistantItemResolution({ _itemResolution: { kind: 'CREATE' } }).label, '确认后新建档案')
|
||||
})
|
||||
|
||||
test('server-authorized category correction stays editable and does not release item identity or clear quotes', () => {
|
||||
const row={_rowId:'1',productId:7,category:'设备',unit:'个',quantity:2,finalUnitPrice:12,_assistantCanEditCategory:true,_assistantCatalogCategory:'设备'}
|
||||
const field=fields.find(field=>field.key==='category')
|
||||
assert.equal(assistantFieldLocked('purchase.update',row,field),false)
|
||||
const [changed]=assistantApplyDraftChanges([row],{rowId:'1',key:'category',value:'配件'},context({...readyDraft,action:'purchase.update'}))
|
||||
assert.equal(changed.category,'配件');assert.equal(changed.productId,7);assert.equal(changed.quantity,2);assert.equal(changed.finalUnitPrice,12)
|
||||
assert.equal(assistantFieldLocked('purchase.update',{...row,_assistantCanEditCategory:false},field),true)
|
||||
assert.match(assistantItemResolution({_itemResolution:{kind:'UPDATE_CATEGORY'}}).label,/同步更正/)
|
||||
})
|
||||
|
||||
test('batch setting defaults to filling missing and unresolved references without changing already selected projects or successful rows', () => {
|
||||
const rows = [{ _rowId: 'a', projectId: null }, { _rowId: 'b', projectId: { keyword: '1025底盘项目' } }, { _rowId: 'c', projectId: 6 }, { _rowId: 'done', projectId: null }]
|
||||
const draft = { ...readyDraft, rows, results: [{ rowId: 'done', status: 'SUCCEEDED' }] }
|
||||
|
||||
@ -2,7 +2,7 @@ import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import { purchaseProjectState, purchaseDraftBatchCount, purchaseBatchProjectChanges } from '../../src/utils/purchase-project.js'
|
||||
import { assistantApplyDraftChanges, assistantBulkChanges } from '../../src/utils/assistant-draft-edit.js'
|
||||
import { assistantApplyDraftChanges, assistantBulkChanges, assistantPurchaseProjectChanges } from '../../src/utils/assistant-draft-edit.js'
|
||||
|
||||
test('one batch has one common project and missing information can be distinguished from mixed history', () => {
|
||||
assert.deepEqual(purchaseProjectState([{projectId:1},{projectId:'1'}]), {mixed:false,count:1,missing:0,value:1})
|
||||
@ -38,3 +38,19 @@ test('both procurement screens expose a common project while retaining mixed-his
|
||||
const ai=fs.readFileSync(new URL('../../src/components/BusinessAssistant/AssistantDraft.vue',import.meta.url),'utf8')
|
||||
assert.match(ai,/assistant-purchase-project/);assert.match(ai,/purchaseDraftBatchCount\(props\.rows\) <= 1/);assert.match(ai,/!sharedProject\.value \|\| field\.key !== 'projectId'/)
|
||||
})
|
||||
|
||||
test('AI common project never partially changes a batch containing executed rows', () => {
|
||||
const rows=[{_rowId:'done',projectId:17},{_rowId:'pending',projectId:17}]
|
||||
const field={key:'projectId',ref:'project',batch:true},draft={status:'PARTIAL',results:[{rowId:'done',status:'SUCCEEDED'}]}
|
||||
assert.throws(()=>assistantPurchaseProjectChanges(rows,field,{value:18},{action:'purchase.create',draft}),/不能统一更换项目/)
|
||||
assert.deepEqual(rows.map(row=>row.projectId),[17,17])
|
||||
assert.deepEqual(assistantPurchaseProjectChanges(rows,field,{value:17},{action:'purchase.create',draft}),[])
|
||||
rows[1].projectId=null
|
||||
assert.deepEqual(assistantPurchaseProjectChanges(rows,field,{value:17},{action:'purchase.create',draft}).map(change=>change.rowId),['pending'])
|
||||
})
|
||||
|
||||
test('AI common project ignores unresolved selections and terminal or readonly drafts', () => {
|
||||
const rows=[{_rowId:'1',projectId:null}],field={key:'projectId',ref:'project',batch:true}
|
||||
for(const value of [null,'',{keyword:'研发项目'},'未匹配项目'])assert.deepEqual(assistantPurchaseProjectChanges(rows,field,{value},{action:'purchase.create',draft:{status:'WAIT_CONFIRM'}}),[])
|
||||
for(const draft of [{status:'SUCCEEDED'},{status:'CANCELLED'},{status:'WAIT_CONFIRM',readOnly:true},{status:'WAIT_CONFIRM',permissionDenied:true}])assert.deepEqual(assistantPurchaseProjectChanges(rows,field,{value:17},{action:'purchase.create',draft}),[])
|
||||
})
|
||||
|
||||
@ -44,3 +44,13 @@ test('resolved item categories and zero price remain valid, conflicting units ma
|
||||
const conflict=collectRowErrors([row,{...row,_key:'b',unit:'件'}],[])
|
||||
assert.deepEqual(new Set(conflict.filter(e=>e.field==='unit').map(e=>e.rowKey)),new Set(['a','b']))
|
||||
})
|
||||
|
||||
test('saved catalog category corrections survive matching and paste while invalid dictionary values are rejected', () => {
|
||||
const item={id:1,productName:'电机',brand:'A',spec:'10',unit:'个',category:'设备'}
|
||||
const row={_key:'saved',id:8,productId:1,materialName:'电机',materialBrand:'A',materialParams:'10',unit:'个',category:'配件',projectId:1,expenseCategoryId:1,quantity:2,finalUnitPrice:12}
|
||||
assert.deepEqual(collectRowErrors([row],[item],[],['个'],['设备','配件']),[])
|
||||
validateRows([row],[item]);assert.equal(row.category,'配件');assert.equal(row.productId,1);assert.equal(row.quantity,2);assert.equal(row.finalUnitPrice,12)
|
||||
const pasted=pasteRectangle([row],'设备',0,0,['category'],{readonly:()=>false,items:[item],units:['个']})
|
||||
assert.equal(pasted[0].category,'设备');assert.equal(row.category,'配件')
|
||||
assert.equal(collectRowErrors([{...row,category:'未维护类别'}],[item],[],['个'],['设备','配件'])[0].field,'category')
|
||||
})
|
||||
|
||||
Loading…
Reference in New Issue
Block a user