From c9dccdae5cc07f5cfe4ff9019d8104dc436bd1fa Mon Sep 17 00:00:00 2001 From: lixiaolong <702156524@qq.com> Date: Tue, 3 Nov 2026 09:16:55 +0800 Subject: [PATCH] =?UTF-8?q?feat(app):=20=E4=BC=98=E5=8C=96=E7=A7=BB?= =?UTF-8?q?=E5=8A=A8=E7=AB=AF=E5=BA=94=E7=94=A8=E9=85=8D=E7=BD=AE=E5=92=8C?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加生产环境服务器地址配置支持内外网切换 - 实现采购列表只看我创建的功能开关 - 更新构建脚本中的默认生产环境API地址 - 优化采购单表格单元格编辑体验改用自动补全组件 - 调整应用更新检查逻辑增强生产环境兼容性 - 修复开发服务器切换时的一些验证问题 - 增强应用启动时的服务地址配置灵活性 --- mobile-app/app.config.js | 4 +- .../warehouse/SupplierInquiryExport.java | 58 +++++- .../warehouse/SupplierQuoteImport.java | 26 +-- .../projectdev/PurchaseSheetDatabaseTest.java | 40 +++- .../SupplierInquiryRoundTripTest.java | 28 ++- .../service/impl/SysDictDataServiceImpl.java | 16 +- .../service/impl/ItemCategoryService.java | 16 +- .../service/impl/ProductInfoServiceImpl.java | 5 +- .../PurchaseHistoryCorrectionService.java | 1 + .../impl/PurchaseRequestServiceImpl.java | 4 + .../mapper/warehouse/ProductInfoMapper.xml | 6 +- .../components/ItemCategorySelect/index.vue | 32 +++- .../src/components/PurchaseSheet/Cell.vue | 13 +- .../PurchaseSheet/SupplierQuotation.vue | 4 +- .../src/components/PurchaseSheet/index.vue | 178 ++++++++++++------ ruoyi-ui-vue3/src/utils/item-categories.js | 16 +- .../src/utils/purchase-sheet-editor.js | 22 ++- .../src/views/businessHome/index.vue | 5 +- ruoyi-ui-vue3/src/views/mobile/index.vue | 2 +- .../system/businessDictionaries/index.vue | 10 +- .../src/views/warehouse/product/index.vue | 6 +- .../src/views/warehouse/purchase/index.vue | 2 +- .../runtime/purchase-amount-order.spec.js | 4 +- .../runtime/purchase-edit-operations.spec.js | 27 ++- .../tests/runtime/purchase-excel-edit.spec.js | 2 +- .../tests/runtime/purchase-grid.spec.js | 20 ++ .../runtime/supplier-inquiry-export.spec.js | 8 + .../unit/purchase-draft-durability.test.mjs | 12 ++ 28 files changed, 429 insertions(+), 138 deletions(-) diff --git a/mobile-app/app.config.js b/mobile-app/app.config.js index 9e2b40d..dd271de 100644 --- a/mobile-app/app.config.js +++ b/mobile-app/app.config.js @@ -5,9 +5,9 @@ module.exports = () => { return { name: env.variant === 'prod' ? '设备科综合管理系统' : '设备科综合管理系统·开发', icon: `./assets/brand/app-icon-blue-${env.variant}.png`, - slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.1', orientation: 'portrait', userInterfaceStyle: 'automatic', + slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.2', orientation: 'portrait', userInterfaceStyle: 'automatic', platforms: ['android', 'web'], - android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 6, + android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 7, adaptiveIcon: { foregroundImage: `./assets/brand/app-icon-blue-${env.variant}-adaptive.png`, backgroundColor: '#ffffff' }, permissions: ['android.permission.REQUEST_INSTALL_PACKAGES'], blockedPermissions: ['android.permission.RECORD_AUDIO'] }, plugins: ['./plugins/with-apk-installer.cjs', 'expo-sharing', 'expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }], diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierInquiryExport.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierInquiryExport.java index d7d47c0..f6be463 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierInquiryExport.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierInquiryExport.java @@ -5,6 +5,7 @@ import com.ruoyi.warehouse.domain.PurchaseRequest; import com.ruoyi.warehouse.domain.PurchaseSheet; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.math.BigDecimal; import java.math.RoundingMode; @@ -75,7 +76,7 @@ public final class SupplierInquiryExport { public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts) { return workbook(purchase,includeActualAmounts,null); } - private static final Set COLUMN_KEYS=Set.of("name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","remark"); + private static final Set COLUMN_KEYS=Set.of("index","name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","remark"); public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts,String selectedColumns) { Set selected; if(selectedColumns==null) selected=COLUMN_KEYS; @@ -86,6 +87,7 @@ public final class SupplierInquiryExport { selected.add(key); } } + if(selectedColumns!=null)return selectedWorkbook(purchase,includeActualAmounts,selected); var items = items(purchase); if (items.isEmpty()) throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填"); var book = new XSSFWorkbook(); var sheet = book.createSheet("供应商询价单"); sheet.setDisplayGridlines(false); @@ -151,6 +153,60 @@ public final class SupplierInquiryExport { book.setPrintArea(0,0,remarkColumn,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true); return book; } + private record Column(String key,String label,int width) { } + private static final List EXPORT_COLUMNS=List.of(new Column("index","序号",8),new Column("name","物品名称",26),new Column("spec","规格型号",40),new Column("brand","品牌",18),new Column("unit","单位",9),new Column("quantity","采购数量",14),new Column("quoteUnitPrice","报价单价(元)",18),new Column("quoteAmount","报价金额(元)",18),new Column("actualUnitPrice","实际单价(元)",18),new Column("actualAmount","实际金额(元)",18),new Column("link","采购链接",38),new Column("remark","备注",38)); + private static XSSFWorkbook selectedWorkbook(PurchaseSheet purchase,boolean includeActual,Set selected){ + var columns=EXPORT_COLUMNS.stream().filter(c->selected.contains(c.key())&&(includeActual||!c.key().startsWith("actual"))).toList(); + if(columns.isEmpty())throw new ServiceException("请至少选择一个可导出的字段"); + var items=items(purchase);if(items.isEmpty())throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填"); + var book=new XSSFWorkbook();var sheet=book.createSheet("供应商询价单");sheet.setDisplayGridlines(false);SupplierInquiryMetadata.mark(book); + var font=book.createFont();font.setFontName("Arial");font.setFontHeightInPoints((short)11); + var body=book.createCellStyle();body.setFont(font);body.setAlignment(HorizontalAlignment.CENTER);body.setVerticalAlignment(VerticalAlignment.CENTER);body.setWrapText(true); + var titleFont=book.createFont();titleFont.setFontName("Arial");titleFont.setFontHeightInPoints((short)16);titleFont.setBold(true); + var title=book.createCellStyle();title.cloneStyleFrom(body);title.setFont(titleFont); + var headerFont=book.createFont();headerFont.setFontName("Arial");headerFont.setColor(IndexedColors.WHITE.getIndex());headerFont.setBold(true); + var headerStyle=book.createCellStyle();headerStyle.cloneStyleFrom(body);headerStyle.setFont(headerFont);headerStyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + var numeric=book.createCellStyle();numeric.cloneStyleFrom(body);numeric.setDataFormat(book.createDataFormat().getFormat("#,##0.00####")); + var whole=book.createCellStyle();whole.cloneStyleFrom(body);whole.setDataFormat(book.createDataFormat().getFormat("#,##0")); + var fractional=book.createCellStyle();fractional.cloneStyleFrom(body);fractional.setDataFormat(book.createDataFormat().getFormat("#,##0.####")); + var amount=book.createCellStyle();amount.cloneStyleFrom(body);amount.setDataFormat(book.createDataFormat().getFormat("#,##0.00")); + var input=book.createCellStyle();input.cloneStyleFrom(numeric);input.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());input.setFillPattern(FillPatternType.SOLID_FOREGROUND);input.setLocked(false); + var positions=new HashMap();for(int c=0;cclean(r.getSupplierName())).filter(s->!s.isEmpty()).findFirst().orElse("待定"); + var context=sheet.createRow(2);context.createCell(0).setCellValue("采购批次:"+purchase.getBatch().getBatchNo()+" 供应商:"+supplier);context.getCell(0).setCellStyle(body);context.setHeightInPoints(last<2?60:28); + var note=sheet.createRow(3);note.createCell(0).setCellValue(positions.containsKey("quoteUnitPrice")?"填写说明:仅填写黄色报价单价,未报价留空。请勿修改物品信息及单元格匹配批注,填写后回传原文件。":"说明:本次未导出报价单价填写列;如需报价回填,请重新导出时勾选报价单价。");note.getCell(0).setCellStyle(body);note.setHeightInPoints(last<2?96:44); + for(int r:List.of(1,2,3))if(last>0)sheet.addMergedRegion(new CellRangeAddress(r,r,0,last)); + var head=sheet.createRow(5);head.setHeightInPoints(28);for(int c=0;c35||selected.contains("name")&&item.name().length()>20?44:32,selected.contains("remark")?remarkHeight(item.remark()):0))); + for(int c=0;c cell.setCellValue(index-5); + case "name" -> setText(cell,item.name());case "spec" -> setText(cell,item.spec());case "brand" -> setText(cell,item.brand());case "unit" -> setText(cell,item.unit()); + case "quantity" -> {cell.setCellValue(item.quantity().doubleValue());cell.setCellStyle(item.quantity().stripTrailingZeros().scale()<=0?whole:fractional);} + case "quoteUnitPrice" -> cell.setCellStyle(input); + case "quoteAmount" -> {cell.setCellStyle(amount);if(positions.containsKey("quoteUnitPrice")){String price=CellReference.convertNumToColString(positions.get("quoteUnitPrice"))+(index+1),quantity=positions.containsKey("quantity")?CellReference.convertNumToColString(positions.get("quantity"))+(index+1):item.quantity().toPlainString();cell.setCellFormula("IF(ISNUMBER("+price+"),ROUND("+quantity+"*"+price+",2),\"\")");}} + case "actualUnitPrice" -> {cell.setCellStyle(numeric);if(item.mixedActualPrices())setText(cell,"多种实际单价");else if(item.actualUnitPrice()!=null)cell.setCellValue(item.actualUnitPrice().doubleValue());} + case "actualAmount" -> {cell.setCellStyle(amount);if(item.actualAmount()!=null)cell.setCellValue(item.actualAmount().doubleValue());} + case "link" -> setText(cell,item.link());case "remark" -> setText(cell,item.remark()); + } + } + SupplierInquiryMetadata.write(row,0,new SupplierInquiryMetadata.Match(purchase.getBatch().getBatchNo(),item.snapshot(),item.rowIds()));index++; + } + if(positions.containsKey("quoteUnitPrice")){int c=positions.get("quoteUnitPrice");var helper=sheet.getDataValidationHelper();var validation=helper.createValidation(helper.createDecimalConstraint(DataValidationConstraint.OperatorType.BETWEEN,"0","999999999999.999999"),new org.apache.poi.ss.util.CellRangeAddressList(6,index-1,c,c));validation.setEmptyCellAllowed(true);validation.setShowErrorBox(true);validation.createErrorBox("请填写有效单价","报价单价需为非负数,最多6位小数;不报价请留空。");sheet.addValidationData(validation);} + sheet.setAutoFilter(new CellRangeAddress(5,index-1,0,last)); + if(positions.containsKey("actualAmount")){ + int c=positions.get("actualAmount");if(last==0){var label=sheet.createRow(index++).createCell(0);label.setCellValue("实际金额合计");label.setCellStyle(body);SupplierInquiryMetadata.total(label);} + var total=sheet.createRow(index);total.setHeightInPoints(36);if(last>0){var label=total.createCell(c==0?1:0);label.setCellValue("实际金额合计");label.setCellStyle(body);} + var cell=total.createCell(c);String range=CellReference.convertNumToColString(c)+"7:"+CellReference.convertNumToColString(c)+(items.size()+6);cell.setCellFormula("IF(COUNT("+range+")="+items.size()+",SUM("+range+"),\"\")");cell.setCellStyle(amount);SupplierInquiryMetadata.total(cell);index++; + } + sheet.createFreezePane(last>0?1:0,6);sheet.setRepeatingRows(new CellRangeAddress(5,5,-1,-1));sheet.getPrintSetup().setLandscape(true);sheet.getPrintSetup().setPaperSize(PrintSetup.A3_PAPERSIZE);sheet.getPrintSetup().setFitWidth((short)1);sheet.getPrintSetup().setFitHeight((short)0);sheet.setFitToPage(true); + book.setPrintArea(0,0,last,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);return book; + } private static float remarkHeight(String remark) { int lines=0; for(String line:remark.split("\n",-1)) { diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java index 3fa98cd..dd09ffc 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java @@ -15,7 +15,8 @@ public final class SupplierQuoteImport { public static List> preview(InputStream input, PurchaseSheet sheet) throws Exception { var current = SupplierInquiryExport.items(sheet); try (var workbook=WorkbookFactory.create(input)) { - var formatter=new DataFormatter(Locale.ROOT); Header header=findHeader(workbook,formatter); + boolean metadataRequired=SupplierInquiryMetadata.required(workbook); + var formatter=new DataFormatter(Locale.ROOT); Header header=findHeader(workbook,formatter,metadataRequired); Sheet tab=header.sheet();Map columns=header.columns(); if(tab.getLastRowNum()-header.row()>2000)throw new ServiceException("报价文件最多2000行,请按批次分别回传"); String contextBatch=contextBatch(tab,header.row(),formatter); @@ -23,15 +24,18 @@ public final class SupplierQuoteImport { var evaluator=workbook.getCreationHelper().createFormulaEvaluator(); for(int n=header.row()+1;n<=tab.getLastRowNum();n++) { var row=tab.getRow(n);if(row==null)continue; + if(metadataRequired&&SupplierInquiryMetadata.isTotal(row))continue; + SupplierInquiryMetadata.Match metadata=null;String error=null; + if(metadataRequired)try{metadata=SupplierInquiryMetadata.read(row);if(metadata==null)error="所选采购明细匹配标记缺失,请重新导出询价单";}catch(ServiceException invalid){error=invalid.getMessage();} String code=text(row,columns.get("物品编码"),formatter), name=text(row,columns.get("物品名称"),formatter), rawPrice=text(row,columns.get("最终单价"),formatter); - if(code.isEmpty()&&name.isEmpty()&&rawPrice.isEmpty())continue; - String batch=text(row,columns.get("采购批次"),formatter);if(batch.isEmpty())batch=contextBatch; + if(code.isEmpty()&&name.isEmpty()&&rawPrice.isEmpty()&&metadata==null){boolean content=false;for(var cell:row)if(!formatter.formatCellValue(cell).isBlank()){content=true;break;}if(!metadataRequired||!content)continue;} + String batch=metadata==null?text(row,columns.get("采购批次"),formatter):metadata.batch();if(batch.isEmpty())batch=contextBatch; var item=new LinkedHashMap();item.put("line",n+1);item.put("productCode",code);item.put("name",name);item.put("spec",text(row,columns.get("规格型号"),formatter));item.put("brand",text(row,columns.get("品牌"),formatter));item.put("unit",text(row,columns.get("单位"),formatter));item.put("price",rawPrice);item.put("rowIds",List.of());item.put("unitPrice",null);item.put("skipped",rawPrice.isEmpty()); - String error=null; var candidates=current; - if(columns.containsKey("采购明细标识")) { + if(metadataRequired||columns.containsKey("采购明细标识")) { try { - var ids=Arrays.stream(text(row,columns.get("采购明细标识"),formatter).split(",",-1)).map(String::trim).map(Long::valueOf).toList(); + if(metadataRequired&&(metadata==null||error!=null))throw new IllegalArgumentException(); + var ids=metadataRequired?metadata.rowIds():Arrays.stream(text(row,columns.get("采购明细标识"),formatter).split(",",-1)).map(String::trim).map(Long::valueOf).toList(); if(new HashSet<>(ids).size()!=ids.size())throw new IllegalArgumentException(); var subset=SupplierInquiryExport.selected(sheet,ids); if(subset.getRows().stream().anyMatch(value->!SupplierInquiryExport.eligible(value)))throw new IllegalArgumentException(); @@ -39,15 +43,15 @@ public final class SupplierQuoteImport { if(candidates.size()!=1)throw new IllegalArgumentException(); }catch(Exception invalid){error="所选采购明细已变化或匹配信息缺失,请重新导出询价单";candidates=List.of();} } - var matches=candidates.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList(); + var matches=metadataRequired?candidates:candidates.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList(); SupplierInquiryExport.Item match=matches.size()==1?matches.get(0):null; if(error!=null) { /* Keep the selection error; never widen to the whole batch. */ } else if(!Objects.equals(batch,sheet.getBatch().getBatchNo()))error="采购批次不一致,请回传当前批次的询价单"; - else if(match==null)error=matches.size()>1?"存在同名物品,请保留原表隐藏列,或补全品牌、规格和单位":"当前批次找不到可回填的物品,或该物品已入库、为历史/取消明细"; + else if(match==null)error=matches.size()>1?"存在同名物品,请回传原表,或补全品牌、规格和单位":"当前批次找不到可回填的物品,或该物品已入库、为历史/取消明细"; else { item.put("productCode",match.productCode());item.put("name",match.name());item.put("spec",match.spec());item.put("brand",match.brand());item.put("unit",match.unit());item.put("quantity",match.quantity());item.put("previousPrice",match.previousPrice());item.put("rowIds",match.rowIds()); if(!identityMatches(row,columns,formatter,match))error="物品名称、规格、品牌或单位与采购清单不一致,请勿修改询价单物品信息"; - String snapshot=text(row,columns.get("清单校验"),formatter); + String snapshot=metadata==null?text(row,columns.get("清单校验"),formatter):metadata.snapshot(); if(error==null&&!snapshot.isEmpty()&&!snapshot.equals(match.snapshot()))error="采购清单已变化,请重新导出当前批次询价单后报价"; if(error==null&&columns.containsKey("采购数量")) { try { if(number(row.getCell(columns.get("采购数量")),evaluator).compareTo(match.quantity())!=0)error="采购数量与当前清单不一致,请重新导出询价单"; } @@ -66,7 +70,7 @@ public final class SupplierQuoteImport { return result; } } - private static Header findHeader(Workbook workbook,DataFormatter formatter) { + private static Header findHeader(Workbook workbook,DataFormatter formatter,boolean metadataRequired) { List
found=new ArrayList<>(); if(workbook.getNumberOfSheets()>50)throw new ServiceException("报价工作表过多,请仅保留本批次询价单"); for(int s=0;s columns=new HashMap<>();Set duplicates=new HashSet<>(); for(var cell:row) {String key=canonical(formatter.formatCellValue(cell).trim());if(key!=null&&columns.putIfAbsent(key,cell.getColumnIndex())!=null)duplicates.add(key);} - if(columns.containsKey("最终单价")&&(columns.containsKey("物品编码")||columns.containsKey("物品名称"))){if(!duplicates.isEmpty())throw new ServiceException("报价表存在重复列:"+String.join("、",duplicates));found.add(new Header(tab,r,columns));break;} + if(columns.containsKey("最终单价")&&(metadataRequired||columns.containsKey("物品编码")||columns.containsKey("物品名称"))){if(!duplicates.isEmpty())throw new ServiceException("报价表存在重复列:"+String.join("、",duplicates));found.add(new Header(tab,r,columns));break;} } } var preferred=found.stream().filter(header->"供应商询价单".equals(header.sheet().getSheetName())).toList(); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java index 06403cb..45b5e63 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java @@ -38,6 +38,44 @@ 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 provisionalCategoryCanSaveAndConfirmPurchasesThenReclassifiesOnlyLinkedRecords()throws Exception { + Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) { + security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("category-flow-rollback");security.when(SecurityUtils::getUserId).thenReturn(1L); + new TransactionTemplate(f.manager).executeWithoutResult(status->{status.setRollbackOnly(); + var raw=(PurchaseSheetService)org.springframework.test.util.AopTestUtils.getUltimateTargetObject(f.service); + var categories=new ItemCategoryService();f.set(categories,"jdbc",f.jdbc);f.set(categories,"catalogLock",ReflectionTestUtils.getField(raw,"catalogLock")); + f.set(raw,"itemCategories",categories); + f.set(org.springframework.test.util.AopTestUtils.getUltimateTargetObject(ReflectionTestUtils.getField(raw,"products")),"itemCategories",categories); + f.set(org.springframework.test.util.AopTestUtils.getUltimateTargetObject(ReflectionTestUtils.getField(raw,"purchases")),"itemCategories",categories); + var dictionaries=mock(com.ruoyi.system.service.ISysDictDataService.class); + var applications=new ItemCategoryApplicationService();f.set(applications,"jdbc",f.jdbc);f.set(applications,"catalogLock",ReflectionTestUtils.getField(raw,"catalogLock"));f.set(applications,"categories",categories);f.set(applications,"dictionaries",dictionaries); + var parent=applications.groups().get(0);long group=((Number)parent.get("id")).longValue();String temporary=f.name+"临时分类",temporaryGroup=parent.get("label").toString(); + long application=((Number)applications.submit(new ItemCategoryApplicationService.Application("LEAF",temporary,group,"先使用,后确认",f.name,"")).get("id")).longValue(); + var draft=f.draft();draft.getRows().get(1).setProjectId(draft.getRows().get(0).getProjectId());draft.getRows().forEach(row->row.setCategory(temporary)); + var saved=f.save(draft);assertEquals(2,saved.getRows().size());assertTrue(saved.getRows().stream().allMatch(row->temporary.equals(row.getCategory()))); + assertEquals(3,f.jdbc.queryForObject("select count(*) from item_category_usage where application_id=?",Integer.class,application)); + assertEquals(temporaryGroup,categories.options().stream().filter(row->temporary.equals(row.get("label"))).findFirst().orElseThrow().get("parentLabel")); + assertEquals(temporaryGroup,((com.ruoyi.warehouse.service.IProductInfoService)ReflectionTestUtils.getField(raw,"products")).selectProductInfoById(saved.getRows().get(0).getProductId()).getCategoryGroupName()); + var purchased=f.service.confirm(saved.getBatch().getId(),saved.getVersion());assertTrue(purchased.getRows().stream().allMatch(row->Boolean.TRUE.equals(row.getPriceLocked()))); + var before=f.jdbc.queryForList("select id,quantity,final_unit_price,estimated_amount,purchase_status,price_locked,product_id from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId()); + int events=f.jdbc.queryForObject("select count(*) from inventory_cost_event",Integer.class); + f.jdbc.update("insert into product_info(product_code,product_name,category,unit) values(?,?,?,'件')",f.name+"unlinked",f.name+"unlinked",temporary); + var target=categories.confirmedOptions().get(0);long targetId=((Number)target.get("id")).longValue();String targetName=(String)target.get("label"); + assertThrows(ServiceException.class,()->applications.review(application,new ItemCategoryApplicationService.Review(false,null,null,"分类整理",targetId,"outdated"))); + var version=(String)applications.usage(application,1,20).get("version"); + var result=applications.review(application,new ItemCategoryApplicationService.Review(false,null,null,"归入已有分类",targetId,version));assertEquals("ADJUSTED",result.get("status"));assertEquals(2,result.get("purchaseCount"));assertEquals(1,result.get("productCount")); + assertTrue(f.service.load(saved.getBatch().getId()).getRows().stream().allMatch(row->targetName.equals(row.getCategory()))); + assertEquals(targetName,f.jdbc.queryForObject("select category from product_info where id=?",String.class,saved.getRows().get(0).getProductId())); + assertEquals(temporary,f.jdbc.queryForObject("select category from product_info where product_code=?",String.class,f.name+"unlinked")); + assertEquals(before,f.jdbc.queryForList("select id,quantity,final_unit_price,estimated_amount,purchase_status,price_locked,product_id from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId())); + assertEquals(events,f.jdbc.queryForObject("select count(*) from inventory_cost_event",Integer.class)); + assertEquals(3,f.jdbc.queryForObject("select count(*) from item_category_adjustment where application_id=?",Integer.class,application)); + assertThrows(ServiceException.class,()->f.save(f.copy(purchased))); + }); + } + assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); + } + @Test void historyCorrectionChecksEveryBaselineAndRetriesWithoutDuplicateWrites()throws Exception { Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("history-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); @@ -603,7 +641,7 @@ 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);set(purchaseTarget,"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); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierInquiryRoundTripTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierInquiryRoundTripTest.java index 2502b81..8167d47 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierInquiryRoundTripTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierInquiryRoundTripTest.java @@ -127,30 +127,28 @@ class SupplierInquiryRoundTripTest { var result=preview(bytes.toByteArray(),purchase);assertTrue(ready(result.get(0)));assertEquals(List.of(1L,2L),result.get(0).get("rowIds")); } } - @Test void selectedColumnsHideRequiredIdentityButNeverWriteUnselectedOptionalValues() throws Exception { + @Test void selectedColumnsOnlyExistInTheFileAndNeverWriteUnselectedValues() throws Exception { var purchase=purchase();purchase.getRows().forEach(r->{r.setRemark("敏感备注");r.setActualUnitPrice(BigDecimal.TEN);}); for(boolean includeActual:List.of(true,false))try(var book=SupplierInquiryExport.workbook(purchase,includeActual,"name,quoteUnitPrice");var bytes=new ByteArrayOutputStream()) { - var tab=book.getSheetAt(0);int link=includeActual?10:8,remark=includeActual?14:12; - assertTrue(tab.isColumnHidden(2));assertFalse(tab.isColumnHidden(1));assertFalse(tab.isColumnHidden(6)); - assertEquals(CellType.BLANK,tab.getRow(6).getCell(link).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(remark).getCellType()); - assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType()); - if(includeActual){assertEquals(CellType.BLANK,tab.getRow(6).getCell(8).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(9).getCellType());} - tab.getRow(6).getCell(6).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0))); + var tab=book.getSheetAt(0);assertEquals(2,tab.getRow(5).getLastCellNum());assertEquals("物品名称",tab.getRow(5).getCell(0).getStringCellValue());assertEquals("报价单价(元)",tab.getRow(5).getCell(1).getStringCellValue()); + for(var row:tab){assertTrue(row.getLastCellNum()<=2);for(var cell:row)if(cell.getCellType()==CellType.STRING)assertFalse(cell.getStringCellValue().contains("敏感备注"));} + for(int c=0;c<16;c++)assertFalse(tab.isColumnHidden(c)); + tab.getRow(6).getCell(1).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0))); } - try(var book=SupplierInquiryExport.workbook(purchase,true,"name")){assertTrue(book.getSheetAt(0).isColumnHidden(6));assertEquals(CellType.BLANK,book.getSheetAt(0).getRow(6).getCell(7).getCellType());} + try(var book=SupplierInquiryExport.workbook(purchase,true,"name")){assertEquals(1,book.getSheetAt(0).getRow(5).getLastCellNum());assertNull(book.getSheetAt(0).getRow(6).getCell(1));assertFalse(book.getSheetAt(0).isColumnHidden(0));} assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"quoteUnitPrice,bogus")); } @Test void totalLabelRemainsVisibleWhenActualUnitPriceIsOmitted() throws Exception { var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN)); try(var book=SupplierInquiryExport.workbook(purchase,true,"name,quoteUnitPrice,actualAmount,remark")) { - var sheet=book.getSheetAt(0);assertTrue(sheet.isColumnHidden(8));assertFalse(sheet.isColumnHidden(6)); - assertEquals("实际金额合计",sheet.getRow(8).getCell(6).getStringCellValue()); - assertEquals(60,sheet.getRow(8).getCell(9).getNumericCellValue()); - assertEquals("A6:O8",sheet.getCTWorksheet().getAutoFilter().getRef()); + var sheet=book.getSheetAt(0);assertEquals(4,sheet.getRow(5).getLastCellNum()); + assertEquals("实际金额合计",sheet.getRow(8).getCell(0).getStringCellValue()); + assertEquals(60,sheet.getRow(8).getCell(2).getNumericCellValue()); + assertEquals("A6:D8",sheet.getCTWorksheet().getAutoFilter().getRef()); } try(var book=SupplierInquiryExport.workbook(purchase,false,"name,quoteUnitPrice,remark")) { - assertEquals("A6:M8",book.getSheetAt(0).getCTWorksheet().getAutoFilter().getRef()); + assertEquals("A6:C8",book.getSheetAt(0).getCTWorksheet().getAutoFilter().getRef()); } } @@ -173,7 +171,7 @@ class SupplierInquiryRoundTripTest { @Test void exportedCellsAreCenteredAndQuoteInputIsOptional() throws Exception { var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN)); try(var book=SupplierInquiryExport.workbook(purchase,true,"name,actualAmount")) { - var tab=book.getSheetAt(0);assertTrue(tab.isColumnHidden(6));assertTrue(tab.isColumnHidden(7));assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType());assertFalse(tab.isColumnHidden(1));assertEquals("实际金额合计",tab.getRow(8).getCell(1).getStringCellValue()); + var tab=book.getSheetAt(0);assertEquals(2,tab.getRow(5).getLastCellNum());assertEquals("实际金额合计",tab.getRow(8).getCell(0).getStringCellValue());assertFalse(tab.isColumnHidden(0));assertFalse(tab.isColumnHidden(1)); for(var row:tab)for(var cell:row){assertEquals(HorizontalAlignment.CENTER,cell.getCellStyle().getAlignment());assertEquals(VerticalAlignment.CENTER,cell.getCellStyle().getVerticalAlignment());} } } @@ -183,7 +181,7 @@ class SupplierInquiryRoundTripTest { try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.warehouse.util.PurchaseQuoteAccess.class,org.mockito.Mockito.CALLS_REAL_METHODS)) { security.when(com.ruoyi.warehouse.util.PurchaseQuoteAccess::allowed).thenReturn(true); var response=new org.springframework.mock.web.MockHttpServletResponse();controller.inquiryExport(1L,"snapshot-1","name,quantity",new PurchaseRequestController.InquiryExportSelection(List.of(2L)),response); - try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){assertEquals(2,book.getSheetAt(0).getRow(6).getCell(5).getNumericCellValue());assertNull(book.getSheetAt(0).getRow(7));assertTrue(book.getSheetAt(0).isColumnHidden(6));} + try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){assertEquals(2,book.getSheetAt(0).getRow(6).getCell(1).getNumericCellValue());assertNull(book.getSheetAt(0).getRow(7));assertEquals(2,book.getSheetAt(0).getRow(5).getLastCellNum());assertFalse(book.getSheetAt(0).isColumnHidden(0));assertFalse(book.getSheetAt(0).isColumnHidden(1));} assertThrows(ServiceException.class,()->controller.inquiryExport(1L,"snapshot-1","name",new PurchaseRequestController.InquiryExportSelection(List.of(999L)),new org.springframework.mock.web.MockHttpServletResponse())); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java index 00d34fe..a14ba37 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java @@ -72,7 +72,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService SysDictData data = selectDictDataById(dictCode); dictDataMapper.deleteDictDataById(dictCode); List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); - DictUtils.setDictCache(data.getDictType(), dictDatas); + cacheAfterCategoryCommit(data.getDictType(), dictDatas); } } @@ -91,7 +91,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService if (row > 0) { List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); - DictUtils.setDictCache(data.getDictType(), dictDatas); + cacheAfterCategoryCommit(data.getDictType(), dictDatas); } return row; } @@ -111,8 +111,18 @@ public class SysDictDataServiceImpl implements ISysDictDataService if (row > 0) { List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); - DictUtils.setDictCache(data.getDictType(), dictDatas); + cacheAfterCategoryCommit(data.getDictType(), dictDatas); } return row; } + + /** A category approved in a transaction must not leak through the dictionary cache before commit. */ + private void cacheAfterCategoryCommit(String type, List rows) + { + if (itemCategories.managed(type) && org.springframework.transaction.support.TransactionSynchronizationManager.isSynchronizationActive()) { + org.springframework.transaction.support.TransactionSynchronizationManager.registerSynchronization(new org.springframework.transaction.support.TransactionSynchronization() { + @Override public void afterCommit() { DictUtils.setDictCache(type, rows); } + }); + } else DictUtils.setDictCache(type, rows); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ItemCategoryService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ItemCategoryService.java index 27493a8..4cf4791 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ItemCategoryService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ItemCategoryService.java @@ -44,7 +44,21 @@ public class ItemCategoryService { return jdbc.queryForObject("select (select count(*) from product_info where category=?)+(select count(*) from purchase_request where category=?)",Long.class,label,label)>0; } public List> options() { - return jdbc.queryForList("select c.dict_code as id,c.dict_label as label,c.parent_code as parentId,g.dict_label as parentLabel from sys_dict_data c left join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type=? where c.dict_type=? and c.status='0' and (c.parent_code is null or g.status='0') order by coalesce(g.dict_sort,2147483647),g.dict_code,c.dict_sort,c.dict_code",GROUP,LEAF); + var result=new ArrayList<>(confirmedOptions()); + result.addAll(jdbc.queryForList("select concat('pending-',a.id) as id,a.category_name as label,coalesce(g.dict_code,concat('pending-group-',pg.id)) as parentId,coalesce(g.dict_label,pg.effective_name,pg.category_name) as parentLabel,case when g.dict_code is null then 'PENDING' else 'CONFIRMED' end as parentReviewStatus,a.description,'PENDING' as reviewStatus,a.id as applicationId from item_category_application a left join item_category_application pg on pg.id=a.parent_application_id and pg.category_type='GROUP' left join sys_dict_data g on g.dict_code=coalesce(a.parent_code,pg.resolved_dict_code) and g.dict_type=? where (g.status='0' or pg.status='PENDING' and g.dict_code is null) and a.category_type='LEAF' and a.status='PENDING' and not exists(select 1 from sys_dict_data c where c.dict_type=? and c.dict_label=a.category_name collate utf8mb4_unicode_ci)",GROUP,LEAF)); + return result; + } + public List> confirmedOptions() { + return jdbc.queryForList("select c.dict_code as id,c.dict_label as label,c.parent_code as parentId,g.dict_label as parentLabel,c.remark as description,'CONFIRMED' as reviewStatus from sys_dict_data c left join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type=? where c.dict_type=? and c.status='0' and (c.parent_code is null or g.status='0') order by coalesce(g.dict_sort,2147483647),g.dict_code,c.dict_sort,c.dict_code",GROUP,LEAF); + } + public void lockCatalog() { catalogLock.acquire(); } + /** Called inside the same transaction as the actual record save, never from a preview. */ + public void recordUsage(String type,Long entityId,String category) { + if(!Set.of("PRODUCT","PURCHASE").contains(type)||entityId==null)throw new IllegalArgumentException("Invalid category usage identity"); + catalogLock.acquire(); + var pending=jdbc.queryForList("select id from item_category_application where category_type='LEAF' and category_name=? and status='PENDING'",category); + if(!pending.isEmpty())jdbc.update("insert into item_category_usage(entity_type,entity_id,application_id) values(?,?,?) on duplicate key update application_id=values(application_id)",type,entityId,pending.get(0).get("id")); + else jdbc.update("delete u from item_category_usage u join item_category_application a on a.id=u.application_id where u.entity_type=? and u.entity_id=? and coalesce(a.effective_name,a.category_name)<>?",type,entityId,category); } public List labels() { return options().stream().map(r->(String)r.get("label")).toList(); } public List> summary() { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java index 91ab8ab..09e25c4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java @@ -94,7 +94,9 @@ public class ProductInfoServiceImpl implements IProductInfoService validateProductInfoUnique(productInfo); productInfo.setProductCode(businessNumbers.reserve("ITEM",null,StringUtils.isBlank(productInfo.getProductCode())?null:"archive:"+productInfo.getProductCode())); if(!checkProductCodeUnique(productInfo))throw new ServiceException("该物品已建档,请使用已有物品"); - return productInfoMapper.insertProductInfo(productInfo); + int rows=productInfoMapper.insertProductInfo(productInfo); + if(rows>0)itemCategories.recordUsage("PRODUCT",productInfo.getId(),productInfo.getCategory()); + return rows; } @Override @@ -112,6 +114,7 @@ public class ProductInfoServiceImpl implements IProductInfoService throw new ServiceException("物品已被业务引用,不能更换计量单位;不同单位请分别建档"); validateProductInfoUnique(productInfo); int rows = productInfoMapper.updateProductInfo(productInfo); + if(rows>0)itemCategories.recordUsage("PRODUCT",productInfo.getId(),productInfo.getCategory()); invalidateCategoryHistory(); return rows; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java index 1fb7fcf..86a592a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java @@ -177,6 +177,7 @@ public class PurchaseHistoryCorrectionService { // Save all other fields first; native audited price correction then sees the final quantity/funding. next.setFinalUnitPrice(old.getFinalUnitPrice());next.setEstimatedUnitPrice(old.getFinalUnitPrice());next.setEstimatedAmount(old.getFinalUnitPrice()==null?null:PurchasePriceRules.amount(next.getQuantity(),old.getFinalUnitPrice()));next.setUpdateBy(SecurityUtils.getUsername()); if(requests.updatePurchaseRequest(next,null)!=1)throw new ServiceException("采购已变化,更正未完成"); + categories.recordUsage("PURCHASE",next.getId(),next.getCategory()); commitments.refreshLockedAmount(old,next,"HISTORY_CORRECTION"); if(changePrice){var input=new PurchasePriceCorrectionService.Correction(targetPrice,command.reason(),null,command.acknowledgeArchiveOnly());var preview=prices.preview(old.getId(),input);prices.correct(old.getId(),new PurchasePriceCorrectionService.Correction(targetPrice,command.reason(),preview.get("version").toString(),command.acknowledgeArchiveOnly()));} next.setFinalUnitPrice(targetPrice); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java index 9e569f5..0f6a2af 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java @@ -90,6 +90,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService @Transactional public int insertPurchaseRequest(PurchaseRequest purchaseRequest) { + itemCategories.lockCatalog(); com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(purchaseRequest, null); normalize(purchaseRequest); resolveFunding(purchaseRequest); @@ -109,6 +110,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService purchaseRequest.setRequestNo(businessNumbers.reserve("PR",null,StringUtils.isBlank(purchaseRequest.getRequestNo())?null:"request:"+purchaseRequest.getRequestNo())); if(purchaseRequestMapper.checkRequestNoUnique(purchaseRequest.getRequestNo())!=null)throw new ServiceException("该采购明细已提交,请勿重复导入"); int rows = purchaseRequestMapper.insertPurchaseRequest(purchaseRequest); + if(rows>0)itemCategories.recordUsage("PURCHASE",purchaseRequest.getId(),purchaseRequest.getCategory()); purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "CREATE", "创建采购申请", "物料:" + purchaseRequest.getMaterialName() + ";数量:" + decimalText(purchaseRequest.getQuantity()) + unitText(purchaseRequest.getUnit()) @@ -120,6 +122,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService @Transactional public int updatePurchaseRequest(PurchaseRequest purchaseRequest) { + itemCategories.lockCatalog(); if (purchaseRequest.getId() == null) { throw new ServiceException("采购申请ID不能为空"); @@ -181,6 +184,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("采购明细已变化,请刷新后重试"); } + itemCategories.recordUsage("PURCHASE",purchaseRequest.getId(),purchaseRequest.getCategory()); if(!Integer.valueOf(5).equals(existing.getPurchaseStatus())&&existing.getQuantity().compareTo(purchaseRequest.getQuantity())!=0){ BigDecimal accepted=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(existing.getId()); int progress=accepted.signum()>0?(accepted.compareTo(purchaseRequest.getQuantity())>=0?4:3): diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml index a25eaa7..7f021b1 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml @@ -17,7 +17,7 @@ select id, product_code, product_name, brand, category, spec, unit, remark, create_time, update_time, - coalesce((select g.dict_label from sys_dict_data c join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type='wms_item_category_group' where c.dict_type='wms_item_category' and c.dict_label=product_info.category limit 1),'未分组') as category_group_name from product_info + coalesce((select g.dict_label from sys_dict_data c join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type='wms_item_category_group' where c.dict_type='wms_item_category' and c.dict_label=product_info.category limit 1),(select coalesce(g.dict_label,pg.effective_name,pg.category_name) from item_category_application a left join item_category_application pg on pg.id=a.parent_application_id left join sys_dict_data g on g.dict_code=coalesce(a.parent_code,pg.resolved_dict_code) where a.category_type='LEAF' and a.status='PENDING' and a.category_name collate utf8mb4_unicode_ci=product_info.category limit 1),'未分组') as category_group_name from product_info