diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java index 22c70c9..f330d97 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java @@ -50,6 +50,10 @@ public class BomController extends BaseController { public AjaxResult items(ProductInfo query) { startPage(); return success(items.selectProductInfoList(query)); } + @PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,production:product:list,production:product:edit,project:project:list,project:project:edit,project:project:manage')") + @GetMapping("/items-page") + public TableDataInfo itemsPage(ProductInfo query) { startPage(); return getDataTable(items.selectProductInfoList(query)); } + @PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,project:project:list,project:project:edit,project:project:manage')") @GetMapping("/{id}") public AjaxResult get(@PathVariable Long id) { return success(service.get(id)); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionProductController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionProductController.java index a890058..3d82902 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionProductController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionProductController.java @@ -23,6 +23,10 @@ public class ProductionProductController extends BaseController { @GetMapping("/options") public AjaxResult options(String keyword) { startPage(); return success(service.products(keyword)); } + @PreAuthorize("@ss.hasAnyPermi('production:product:list,production:product:edit,production:bom:list,production:bom:edit,project:project:list,project:project:edit,project:project:manage')") + @GetMapping("/options-page") + public TableDataInfo optionsPage(String keyword) { startPage(); return getDataTable(service.products(keyword)); } + @PreAuthorize("@ss.hasPermi('production:product:edit')") @Log(title="产品档案", businessType=BusinessType.UPDATE) @PostMapping diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionTaskController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionTaskController.java index 653f424..67b094d 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionTaskController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionTaskController.java @@ -18,6 +18,12 @@ public class ProductionTaskController extends BaseController { public AjaxResult list(Long projectId,Long itemId){return success(service.tasks(projectId,itemId));} @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/page") public AjaxResult page(Long projectId,Long itemId,String status,String keyword,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return success(service.page(projectId,itemId,status,keyword,pageNum,pageSize));} + @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/options") + public AjaxResult options(Long projectId,String operation,String keyword,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="50") int pageSize){return success(service.operationPage(projectId,null,null,keyword,operation,pageNum,pageSize));} + @PreAuthorize("@ss.hasPermi('warehouse:stock:list')") @GetMapping("/project-summary/{projectId}") + public AjaxResult projectSummary(@PathVariable Long projectId){return success(service.projectSummary(projectId));} + @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/product-totals/{projectId}") + public AjaxResult productTotals(@PathVariable Long projectId){return success(service.productTotals(projectId));} @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list') && @ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:manage')") @GetMapping("/shortages") public AjaxResult shortages(@RequestParam List taskIds){return success(service.shortages(taskIds));} @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/{id}") @@ -47,14 +53,18 @@ public class ProductionTaskController extends BaseController { public AjaxResult costHistory(@RequestParam Long itemId,Long bomId,Long projectId){return success(service.costHistory(itemId,bomId,projectId));} @PreAuthorize("@ss.hasAnyPermi('production:bom:list,project:project:list')") @PostMapping("/cost-history/export") public void costHistoryExport(jakarta.servlet.http.HttpServletResponse response,@RequestParam Long itemId,Long bomId,Long projectId)throws java.io.IOException{ - ProductionExcel.write(response,service.costHistory(itemId,bomId,projectId),new String[][]{{"project_name","项目"},{"task_no","任务"},{"version_tag","BOM版本"},{"project_adjusted","项目独立用料"},{"planned_quantity","计划"},{"good_quantity","合格"},{"scrap_quantity","组装报废"},{"material_cost","材料总成本"},{"unit_cost","单位成本"},{"status","结算状态"},{"settled_time","结算时间"}}); + ProductionExcel.write(response,service.costHistory(itemId,bomId,projectId),new String[][]{{"project_name","项目"},{"task_no","任务"},{"version_tag","BOM版本"},{"project_adjusted","项目独立用料"},{"planned_quantity","计划"},{"good_quantity","合格"},{"scrap_quantity","组装报废"},{"material_cost","材料总成本"},{"cost_status_text","材料成本状态"},{"unit_cost","单位成本"},{"unit_cost_status_text","单位成本状态"},{"status","结算状态"},{"settled_time","结算时间"}}); } @PreAuthorize("@ss.hasPermi('project:project:list')") @PostMapping("/export") - public void export(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long itemId)throws java.io.IOException{ - ProductionExcel.write(response,service.tasks(projectId,itemId),new String[][]{{"task_no","任务编号"},{"project_name","项目"},{"item_name","产品"},{"version_tag","BOM版本"},{"planned_quantity","计划数量"},{"good_quantity","合格数量"},{"scrap_quantity","组装报废数量"},{"material_cost","实际材料成本"},{"unit_cost","单位材料成本"},{"status","状态"},{"settled_time","结算时间"}}); + public void exportFiltered(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long itemId,String status,String keyword)throws java.io.IOException{ + writeTasks(response,service.filteredTasks(projectId,itemId,status,keyword)); + } + public void export(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long itemId)throws java.io.IOException{writeTasks(response,service.tasks(projectId,itemId));} + private void writeTasks(jakarta.servlet.http.HttpServletResponse response,List> rows)throws java.io.IOException{ + ProductionExcel.write(response,rows,new String[][]{{"task_no","任务编号"},{"project_name","项目"},{"item_name","产品"},{"version_tag","BOM版本"},{"planned_quantity","计划数量"},{"good_quantity","合格数量"},{"scrap_quantity","组装报废数量"},{"material_cost","实际材料成本"},{"cost_status_text","材料成本状态"},{"unit_cost","单位材料成本"},{"unit_cost_status_text","单位成本状态"},{"status","状态"},{"settled_time","结算时间"}}); } @PreAuthorize("@ss.hasPermi('warehouse:stock:export')") @PostMapping("/actions/export") - public void exportActions(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long taskId)throws java.io.IOException{ - ProductionExcel.write(response,service.actions(projectId,taskId),new String[][]{{"project_name","项目"},{"task_no","任务"},{"item_name","物品"},{"kind","类型"},{"quantity","数量"},{"handled_quantity","已退回或报废"},{"area_name","库区"},{"original_cost","原始成本"},{"effective_cost","当前成本"},{"business_date","日期"},{"recipient","接收方"},{"reason","原因"},{"remark","备注"},{"active","有效"}}); + public void exportActions(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate)throws java.io.IOException{ + ProductionExcel.write(response,service.filteredActions(projectId,taskId,kind,active,keyword,beginDate,endDate),new String[][]{{"project_name","项目"},{"task_no","任务"},{"item_name","物品"},{"kind","类型"},{"quantity","数量"},{"handled_quantity","已退回或报废"},{"area_name","库区"},{"original_cost","原始成本"},{"effective_cost","当前成本"},{"business_date","日期"},{"recipient","接收方"},{"reason","原因"},{"remark","备注"},{"active","有效"}}); } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java index d7e1ea6..f2be069 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java @@ -33,5 +33,5 @@ import jakarta.servlet.http.HttpServletResponse; @PostMapping("/{id}/returns/revoke") @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasPermi('warehouse:stock:out')") @Log(title="撤销归还",businessType=BusinessType.UPDATE) public AjaxResult revokeReturn(@PathVariable Long id,@RequestBody Revoke r){service.revokeStockReturn(id,r.key(),r.reason());return success();} @PostMapping("/export") @PreAuthorize("@ss.hasPermi('warehouse:stock:export')") @Log(title="借还记录",businessType=BusinessType.EXPORT) - public void export(HttpServletResponse response,Long projectId,Long itemId){new ExcelUtil<>(ProjectLoan.class).exportExcel(response,service.list(projectId,itemId,false),"项目借还");} + public void export(HttpServletResponse response,Long projectId,Long itemId,@RequestParam(defaultValue="false") boolean outstandingOnly){new ExcelUtil<>(ProjectLoan.class).exportExcel(response,service.list(projectId,itemId,outstandingOnly),"项目借还");} } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java index f0a172e..d88ef88 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java @@ -29,6 +29,14 @@ public class ProductInfoController extends BaseController { @Autowired private IProductInfoService productInfoService; + @Autowired private com.ruoyi.warehouse.service.impl.ItemCategoryService itemCategories; + + @GetMapping("/category-options") + public AjaxResult categoryOptions() { return success(itemCategories.options()); } + + @PreAuthorize("@ss.hasPermi('warehouse:product:list')") + @GetMapping("/category-summary") + public AjaxResult categorySummary() { return success(itemCategories.summary()); } @Autowired private com.ruoyi.warehouse.service.impl.WarehouseImportReceiptService importReceipts; private List importRows(org.springframework.web.multipart.MultipartFile file)throws Exception{ com.ruoyi.warehouse.util.WarehouseFileUtils.validateUpload(file,10L*1024*1024,java.util.Set.of("xls","xlsx")); diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java index 0e8377a..db89e40 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java @@ -66,14 +66,17 @@ public class PurchaseRequestController extends BaseController public AjaxResult sheet(@PathVariable Long id) { return success(sheetService.load(id)); } @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:manage') && @ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @PostMapping("/sheet/prepare") @Log(title="采购组批",businessType=BusinessType.UPDATE) - public AjaxResult prepareSheet(@RequestBody Long[] ids){return success(sheetService.prepare(ids));} + public AjaxResult prepareSheet(@RequestBody Long[] ids,@org.springframework.web.bind.annotation.RequestParam(required=false) Long batchId){return success(sheetService.prepare(ids,batchId));} + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") + @GetMapping("/sheet/unbatched") + public AjaxResult unbatchedSheet(@org.springframework.web.bind.annotation.RequestParam Long[] ids){return success(sheetService.loadUnbatched(ids));} @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/sheet/plans") public AjaxResult sheetPlans(Long projectId,String keyword){ var args=new java.util.ArrayList();var where=new StringBuilder(" where t.status='OPEN'");if(projectId!=null){where.append(" and t.project_id=?");args.add(projectId);}if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,p.product_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword+"%");} return success(sheetDatabase.queryForList("select t.id,t.project_id projectId,t.task_no taskNo,p.product_name productName from production_task t left join product_info p on p.id=t.item_id"+where+" order by t.id desc limit 50",args.toArray())); } - @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage')") + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:remove,warehouse:purchase:manage')") @Log(title = "采购批次表格", businessType = BusinessType.UPDATE) @PostMapping("/sheet") public AjaxResult saveSheet(@RequestBody com.ruoyi.warehouse.domain.PurchaseSheet sheet) { return success(sheetService.save(sheet)); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java index 7978683..f83d2c5 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java @@ -12,6 +12,8 @@ public class PurchaseReturnController extends BaseController { @Autowired private PurchaseReturnService service; @PostMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @Log(title="采购退货",businessType=BusinessType.UPDATE) public AjaxResult returnGoods(@RequestBody PurchaseReturnService.Request request){service.returnGoods(request);return success();} - @GetMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") + @GetMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage')") public AjaxResult history(Long arrivalId){return success(service.history(arrivalId));} + @GetMapping("/{arrivalId}/availability") @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage')") + public AjaxResult availability(@PathVariable Long arrivalId){return success(service.availability(arrivalId));} } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java index 5b4eb0b..13b6108 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java @@ -69,8 +69,8 @@ public class StockInfoController extends BaseController int pageNum = pageDomain.getPageNum() == null || pageDomain.getPageNum() < 1 ? 1 : pageDomain.getPageNum(); int pageSize = pageDomain.getPageSize() == null || pageDomain.getPageSize() < 1 ? 10 : pageDomain.getPageSize(); int total = list == null ? 0 : list.size(); - int fromIndex = Math.min((pageNum - 1) * pageSize, total); - int toIndex = Math.min(fromIndex + pageSize, total); + int fromIndex = (int) Math.min(((long) pageNum - 1) * pageSize, total); + int toIndex = (int) Math.min((long) fromIndex + pageSize, total); TableDataInfo rspData = new TableDataInfo(); rspData.setCode(HttpStatus.SUCCESS); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java index d2e108b..9a9e27b 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java @@ -90,6 +90,8 @@ class BomDatabaseTest { assertTrue(projects.countProjectBusiness(project.getId()) > 0); var itemService = new ProductInfoServiceImpl(); ReflectionTestUtils.setField(itemService, "productInfoMapper", items); ReflectionTestUtils.setField(itemService, "catalogWriteLock", mock(CatalogWriteLock.class)); + var itemCategories=mock(com.ruoyi.warehouse.service.impl.ItemCategoryService.class);when(itemCategories.labels()).thenReturn(java.util.List.of());ReflectionTestUtils.setField(itemService,"itemCategories",itemCategories); + var dictTypes=mock(com.ruoyi.system.service.ISysDictTypeService.class);when(dictTypes.selectDictDataByType("wms_item_unit")).thenReturn(java.util.List.of());ReflectionTestUtils.setField(itemService,"dictTypes",dictTypes); assertThrows(ServiceException.class, () -> itemService.deleteProductInfoByIds(new Long[]{screw.getId()})); ProductInfo changedUnit = items.selectProductInfoById(screw.getId()); changedUnit.setUnit("包"); assertThrows(ServiceException.class, () -> itemService.updateProductInfo(changedUnit)); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessControllerContractTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessControllerContractTest.java new file mode 100644 index 0000000..daf6225 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessControllerContractTest.java @@ -0,0 +1,275 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.util.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.ruoyi.common.core.domain.entity.SysUser; +import com.ruoyi.common.core.domain.model.LoginUser; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.framework.web.exception.GlobalExceptionHandler; +import com.ruoyi.framework.web.service.PermissionService; +import com.ruoyi.production.domain.ProductionCommand; +import com.ruoyi.production.service.ProductionService; +import com.ruoyi.project.domain.ProjectLoan; +import com.ruoyi.project.service.ProjectLoanService; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.service.*; +import com.ruoyi.warehouse.service.impl.*; +import com.ruoyi.web.controller.production.ProductionTaskController; +import com.ruoyi.web.controller.project.ProjectLoanController; +import com.ruoyi.web.controller.warehouse.*; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentCaptor; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.*; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** Real HTTP binding for payloads sent by the Vue3 editors. Services are isolated mocks; + * database/state transitions are covered separately by the rollback lifecycle suites. */ +class BusinessControllerContractTest { + private final PurchaseSheetService sheets=mock(PurchaseSheetService.class); + private final PurchasePriceService prices=mock(PurchasePriceService.class); + private final IPurchaseArrivalService arrivals=mock(IPurchaseArrivalService.class); + private final ProductionService production=mock(ProductionService.class); + private final ProjectLoanService loans=mock(ProjectLoanService.class); + private final IStockCheckRecordService checks=mock(IStockCheckRecordService.class); + private final InventoryCostJournal inventory=mock(InventoryCostJournal.class); + private final IStockInfoService stocks=mock(IStockInfoService.class); + private final LocalValidatorFactoryBean validator=new LocalValidatorFactoryBean(); + private MockMvc mvc; + + @BeforeEach void setup() { + validator.afterPropertiesSet(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); + var purchases=new PurchaseRequestController(); + set(purchases,"sheetService",sheets);set(purchases,"purchaseArrivalService",arrivals); + var pricing=new PurchasePriceController();set(pricing,"priceService",prices); + var tasks=new ProductionTaskController();set(tasks,"service",production); + var borrowing=new ProjectLoanController();set(borrowing,"service",loans); + var counting=new StockCheckRecordController();set(counting,"stockCheckRecordService",checks); + var stock=new StockInfoController();set(stock,"journal",inventory);set(stock,"stockInfoService",stocks); + mvc=build(purchases,pricing,tasks,borrowing,counting,stock); + authenticate(Set.of("*:*:*")); + } + @AfterEach void cleanup() { + SecurityContextHolder.clearContext();RequestContextHolder.resetRequestAttributes(); + com.github.pagehelper.PageHelper.clearPage();validator.close(); + } + private MockMvc build(Object... controllers) { + var json=new ObjectMapper().findAndRegisterModules().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + return MockMvcBuilders.standaloneSetup(controllers).setControllerAdvice(new GlobalExceptionHandler()) + .setMessageConverters(new MappingJackson2HttpMessageConverter(json)).setValidator(validator).build(); + } + private static void set(Object target,String field,Object value){ReflectionTestUtils.setField(target,field,value);} + private static void authenticate(Set permissions) { + var user=new SysUser();user.setUserId(101L);user.setUserName("contract-user"); + var login=new LoginUser(101L,1L,user,permissions); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null,List.of())); + } + private ResultActions json(MockHttpServletRequestBuilder request,String body)throws Exception { + return mvc.perform(request.contentType(MediaType.APPLICATION_JSON).characterEncoding(StandardCharsets.UTF_8).content(body)); + } + + @Test void purchaseDraftQuoteAndConfirmPreserveVue3PayloadAndVersion()throws Exception { + when(sheets.save(any())).thenAnswer(i->i.getArgument(0)); + json(post("/warehouse/purchase/sheet"),""" + {"unbatched":true,"batch":{"supplierId":null,"businessDate":"2026-10-14"}, + "version":"draft-v1","deletedIds":[99],"rows":[{"id":81,"projectId":11,"productId":21, + "expenseCategoryId":3,"category":"机械件 / 紧固件","materialName":"螺丝","materialBrand":"国产", + "materialParams":"M4","unit":"个","quantity":12.5,"finalUnitPrice":1.234567, + "purchasePurpose":"SELF","purchaseLink":"https://example.com/item"}]} + """).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200)) + .andExpect(jsonPath("$.data.unbatched").value(true)); + var saved=ArgumentCaptor.forClass(PurchaseSheet.class);verify(sheets).save(saved.capture()); + assertNull(saved.getValue().getBatch().getSupplierId()); + assertEquals(LocalDate.of(2026,10,14),saved.getValue().getBatch().getBusinessDate()); + assertEquals(List.of(99L),saved.getValue().getDeletedIds()); + assertEquals(new BigDecimal("1.234567"),saved.getValue().getRows().get(0).getFinalUnitPrice()); + assertEquals("SELF",saved.getValue().getRows().get(0).getPurchasePurpose()); + json(post("/warehouse/purchase/sheet/6/confirm"),"{\"version\":\"saved-v2\"}") + .andExpect(jsonPath("$.code").value(200));verify(sheets).confirm(6L,"saved-v2"); + json(post("/warehouse/purchase/sheet/prepare").param("batchId","6"),"[81,82]") + .andExpect(jsonPath("$.code").value(200));verify(sheets).prepare(new Long[]{81L,82L},6L); + } + + @Test void priceLockReportsPerRowFailureAndDeduplicatesWithoutHidingResults()throws Exception { + when(prices.lockPrice(81L)).thenReturn("已锁定"); + when(prices.lockPrice(82L)).thenThrow(new ServiceException("请先填写报价")); + json(post("/warehouse/purchase/price-lock"),"[81,81,82]") + .andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.length()").value(2)) + .andExpect(jsonPath("$.data[0].success").value(true)).andExpect(jsonPath("$.data[1].success").value(false)) + .andExpect(jsonPath("$.data[1].message").value("请先填写报价")); + verify(prices,times(1)).lockPrice(81L);verify(prices,times(1)).lockPrice(82L); + clearInvocations(prices); + json(post("/warehouse/purchase/price-lock"),"[]").andExpect(jsonPath("$.code").value(500)); + verifyNoInteractions(prices); + } + + @Test void arrivalAcceptancePreservesPartialDefectAndRetryKey()throws Exception { + doAnswer(i->{PurchaseArrival row=i.getArgument(0);row.setId(91L);row.setArrivalNo("DH2026100001");return 1;}) + .when(arrivals).insertPurchaseArrival(any()); + when(arrivals.acceptPurchaseArrival(eq(91L),any())).thenReturn(1); + json(post("/warehouse/purchase/arrival"),""" + {"purchaseRequestId":81,"arrivalQuantity":4.125,"arrivalDate":"2026-10-14", + "requestKey":"batch-81-stable-retry-key","remark":"供应商分批送货"} + """).andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.id").value(91)) + .andExpect(jsonPath("$.data.arrivalNo").value("DH2026100001")); + var registered=ArgumentCaptor.forClass(PurchaseArrival.class);verify(arrivals).insertPurchaseArrival(registered.capture()); + assertEquals(81L,registered.getValue().getPurchaseRequestId()); + assertEquals("batch-81-stable-retry-key",registered.getValue().getRequestKey()); + assertEquals(new BigDecimal("4.125"),registered.getValue().getArrivalQuantity()); + json(put("/warehouse/purchase/arrival/91/accept"),""" + {"acceptanceStatus":1,"defectiveQuantity":0.125,"acceptanceRemark":"少量运输损坏"} + """).andExpect(jsonPath("$.code").value(200)); + var accepted=ArgumentCaptor.forClass(PurchaseArrivalAcceptanceRequest.class); + verify(arrivals).acceptPurchaseArrival(eq(91L),accepted.capture()); + assertEquals(1,accepted.getValue().getAcceptanceStatus()); + assertEquals(new BigDecimal("0.125"),accepted.getValue().getDefectiveQuantity()); + assertEquals("少量运输损坏",accepted.getValue().getAcceptanceRemark()); + } + + @Test void missingOrZeroArrivalAndMissingAcceptanceAreRejectedBeforeService()throws Exception { + for(String body:List.of("{}","{\"purchaseRequestId\":81,\"arrivalQuantity\":0,\"arrivalDate\":\"2026-10-14\"}")) + json(post("/warehouse/purchase/arrival"),body).andExpect(jsonPath("$.code").value(500)); + json(put("/warehouse/purchase/arrival/91/accept"),"{}").andExpect(jsonPath("$.code").value(500)) + .andExpect(jsonPath("$.msg").value("验收结果不能为空")); + verifyNoInteractions(arrivals); + } + + @Test void productionActionAndSettlementKeepVersionSourceAndExplicitPlanConsent()throws Exception { + json(post("/production/tasks"),""" + {"id":31,"projectId":11,"itemId":21,"bomId":41,"quantity":3,"version":7, + "date":"2026-10-14","editableIdentity":true,"remark":"任务界面维护计划"} + """).andExpect(jsonPath("$.code").value(200)); + var task=ArgumentCaptor.forClass(ProductionCommand.class);verify(production).save(task.capture()); + assertEquals(41L,task.getValue().bomId);assertEquals(7,task.getValue().version); + when(production.perform(any())).thenReturn(Map.of("id",111L,"kind","COMPLETE")); + json(post("/production/tasks/actions"),""" + {"kind":"COMPLETE","taskId":31,"projectId":11,"itemId":21,"quantity":3, + "adjustPlan":true,"version":7,"date":"2026-10-14","key":"batch-action-stable","remark":"追加完工"} + """).andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.id").value(111)); + var command=ArgumentCaptor.forClass(ProductionCommand.class);verify(production).perform(command.capture()); + assertEquals(31L,command.getValue().taskId);assertEquals(7,command.getValue().version); + assertEquals(Boolean.TRUE,command.getValue().adjustPlan);assertEquals(LocalDate.of(2026,10,14),command.getValue().date); + json(post("/production/tasks/actions"),""" + {"kind":"RETURN","taskId":31,"projectId":11,"itemId":21,"sourceId":110,"areaId":5, + "quantity":0.5,"date":"2026-10-14","key":"return-stable"} + """).andExpect(jsonPath("$.code").value(200)); + verify(production,times(2)).perform(command.capture()); + var returned=command.getValue();assertEquals("RETURN",returned.kind);assertEquals(110L,returned.sourceId);assertEquals(5L,returned.areaId); + json(post("/production/tasks/31/settle"),"{\"version\":8}").andExpect(jsonPath("$.code").value(200)); + json(post("/production/tasks/31/reopen"),"{\"version\":9}").andExpect(jsonPath("$.code").value(200)); + verify(production).settle(31L,8);verify(production).reopen(31L,9); + clearInvocations(production); + json(post("/production/tasks/31/settle"),"{}").andExpect(jsonPath("$.code").value(500)); + json(post("/production/tasks/31/reopen"),"{}").andExpect(jsonPath("$.code").value(500)); + verifyNoInteractions(production); + } + + @Test void productionInvalidEnumQuantityAndMissingKeyReturnActionableErrors()throws Exception { + // Exercise the actual early business guards, while the inventory lock itself is a mock. + var rules=new ProductionService();set(rules,"journal",inventory); + var controller=new ProductionTaskController();set(controller,"service",rules);mvc=build(controller); + json(post("/production/tasks/actions"),"{\"kind\":\"OUTPUT\",\"quantity\":1,\"key\":\"invalid-kind\"}") + .andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("操作类型不正确")); + for(String quantity:List.of("0","-1","0.00001")) + json(post("/production/tasks/actions"),"{\"kind\":\"ISSUE\",\"quantity\":"+quantity+",\"key\":\"invalid-quantity\"}") + .andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("数量必须大于0,最多4位小数")); + json(post("/production/tasks/actions"),"{\"kind\":\"ISSUE\",\"quantity\":1}") + .andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("业务标识无效,请重新打开操作窗口")); + verify(inventory,times(5)).lockInventory();verifyNoMoreInteractions(inventory); + } + + @Test void crossProjectBorrowReturnAndMoveKeepDistinctSourceAndDestination()throws Exception { + var row=new ProjectLoan();row.setId(121L);row.setOutstandingQuantity(new BigDecimal("2.5")); + when(loans.borrow(any(),any(),any(),any(),any(),any(),any(),any(),any())).thenReturn(row); + json(post("/project/loans"),""" + {"lenderProjectId":11,"borrowerProjectId":12,"itemId":21,"fromAreaId":5,"toAreaId":6, + "quantity":2.5,"key":"borrow-stable","date":"2026-10-14","remark":"先借用再采购归还"} + """).andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.id").value(121)); + verify(loans).borrow(11L,12L,21L,5L,6L,new BigDecimal("2.5"),"borrow-stable","先借用再采购归还",LocalDate.of(2026,10,14)); + json(post("/project/loans/121/return"),""" + {"fromAreaId":6,"toAreaId":5,"quantity":1.5,"key":"return-stable","date":"2026-10-14","remark":"部分归还"} + """).andExpect(jsonPath("$.code").value(200)); + verify(loans).returnStock(121L,6L,5L,new BigDecimal("1.5"),"return-stable",LocalDate.of(2026,10,14),"部分归还"); + json(post("/warehouse/stock/move"),""" + {"projectId":12,"itemId":21,"fromAreaId":6,"toAreaId":7,"quantity":1,"key":"MOVE:stable", + "date":"2026-10-14","remark":"调整存放位置"} + """).andExpect(jsonPath("$.code").value(200)); + verify(inventory).move(12L,21L,6L,7L,BigDecimal.ONE,"MOVE:stable",LocalDate.of(2026,10,14),"调整存放位置"); + } + + @Test void stockCountBindsPhysicalCountAndUsesAuthenticatedActor()throws Exception { + when(checks.insertStockCheckRecord(any())).thenReturn(1); + when(checks.confirmStockCheckRecord(eq(141L),anyString())).thenReturn(1); + json(post("/warehouse/check"),""" + {"projectId":11,"productId":21,"areaId":5,"realNum":0,"receiptUnitCost":12.345678, + "businessDate":"2026-10-14","reason":"现场盘点","checkUser":"forged-user"} + """).andExpect(jsonPath("$.code").value(200)); + var record=ArgumentCaptor.forClass(StockCheckRecord.class);verify(checks).insertStockCheckRecord(record.capture()); + assertEquals("contract-user",record.getValue().getCheckUser());assertEquals(BigDecimal.ZERO,record.getValue().getRealNum()); + assertEquals(11L,record.getValue().getProjectId());assertEquals(21L,record.getValue().getProductId()); + assertEquals(new BigDecimal("12.345678"),record.getValue().getReceiptUnitCost()); + json(put("/warehouse/check/confirm/141"),"").andExpect(jsonPath("$.code").value(200)); + verify(checks).confirmStockCheckRecord(141L,"contract-user"); + clearInvocations(checks); + json(post("/warehouse/check"),"{\"projectId\":11,\"productId\":21,\"areaId\":5,\"realNum\":-1}") + .andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("实际盘点数量不能小于0")); + verifyNoInteractions(checks); + } + + @Test void keywordStockPagingAcceptsOutOfRangePageWithoutIntegerOverflow()throws Exception { + when(stocks.selectStockInfoList(any())).thenReturn(List.of(new StockInfo(),new StockInfo(),new StockInfo())); + mvc.perform(get("/warehouse/stock/list").param("productName","螺丝").param("pageNum","2147483647").param("pageSize","20")) + .andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.total").value(3)).andExpect(jsonPath("$.rows.length()").value(0)); + mvc.perform(get("/warehouse/stock/list").param("productName","螺丝").param("pageNum","2").param("pageSize","2")) + .andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.rows.length()").value(1)); + } + + @Test void readOnlyRoleCannotInvokeBusinessMutationsAndCombinedPermissionsAreRequired()throws Exception { + var permissions=new PermissionService();var context=new StandardEvaluationContext(); + context.setBeanResolver((ctx,name)->{assertEquals("ss",name);return permissions;}); + var parser=new SpelExpressionParser(); + Map,Set> commands=Map.of( + PurchaseRequestController.class,Set.of("saveSheet","prepareSheet","confirmSheet","addArrival","acceptArrival"), + PurchasePriceController.class,Set.of("lock"),ProductionTaskController.class,Set.of("save","perform","settle","reopen","remove"), + ProjectLoanController.class,Set.of("borrow","returnStock","revoke","revokeReturn"), + StockInfoController.class,Set.of("move","revokeMove"),StockCheckRecordController.class,Set.of("add","edit","confirm","revoke","remove")); + int checked=0; + for(var entry:commands.entrySet())for(var method:entry.getKey().getDeclaredMethods())if(entry.getValue().contains(method.getName())){ + var policy=method.getAnnotation(PreAuthorize.class);assertNotNull(policy,method.toString()); + var expression=parser.parseExpression(policy.value()); + authenticate(Set.of("project:project:list","warehouse:stock:list","warehouse:purchase:list","warehouse:check:list")); + assertEquals(false,expression.getValue(context,Boolean.class),method.toString()); + authenticate(Set.of("*:*:*"));assertEquals(true,expression.getValue(context,Boolean.class),method.toString());checked++; + } + assertEquals(22,checked); + var action=ProductionTaskController.class.getMethod("perform",ProductionCommand.class).getAnnotation(PreAuthorize.class); + var expression=parser.parseExpression(action.value()); + authenticate(Set.of("project:inventory:use"));assertEquals(false,expression.getValue(context,Boolean.class)); + authenticate(Set.of("warehouse:stock:out"));assertEquals(false,expression.getValue(context,Boolean.class)); + authenticate(Set.of("project:inventory:use","warehouse:stock:out"));assertEquals(true,expression.getValue(context,Boolean.class)); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/GeneratorMissingRecordTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/GeneratorMissingRecordTest.java new file mode 100644 index 0000000..8de4888 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/GeneratorMissingRecordTest.java @@ -0,0 +1,63 @@ +package com.ruoyi.projectdev; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.generator.controller.GenController; +import com.ruoyi.generator.domain.GenTable; +import com.ruoyi.generator.domain.GenTableColumn; +import com.ruoyi.generator.mapper.GenTableMapper; +import com.ruoyi.generator.service.GenTableServiceImpl; +import com.ruoyi.generator.service.IGenTableService; +import com.ruoyi.generator.service.IGenTableColumnService; +import com.ruoyi.framework.web.exception.GlobalExceptionHandler; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.bind.annotation.PathVariable; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +class GeneratorMissingRecordTest { + @Test void missingRecordHasActionableMessageForAllEntryPoints() { + var service = new GenTableServiceImpl(); + ReflectionTestUtils.setField(service, "genTableMapper", mock(GenTableMapper.class)); + for (org.junit.jupiter.api.function.Executable operation : new org.junit.jupiter.api.function.Executable[]{ + () -> service.selectGenTableById(0L), () -> service.previewCode(0L), + () -> service.downloadCode("missing"), () -> service.synchDb("missing"), + () -> service.generatorCode("missing")}) { + assertEquals("生成配置不存在或已删除,请返回列表刷新", assertThrows(ServiceException.class, operation).getMessage()); + } + } + @Test void columnLookupBindsThePathTableId() throws Exception { + assertNotNull(GenController.class.getMethod("columnList", Long.class).getParameters()[0].getAnnotation(PathVariable.class)); + } + @Test void columnListUsesTheStandardSuccessfulResponseContract() throws Exception { + var tables = mock(IGenTableService.class); + var columns = mock(IGenTableColumnService.class); + var controller = new GenController(); + ReflectionTestUtils.setField(controller, "genTableService", tables); + ReflectionTestUtils.setField(controller, "genTableColumnService", columns); + when(tables.selectGenTableById(7L)).thenReturn(new GenTable()); + var column = new GenTableColumn();column.setColumnId(9L);column.setColumnName("name"); + when(columns.selectGenTableColumnListByTableId(7L)).thenReturn(List.of(column)); + var mvc = MockMvcBuilders.standaloneSetup(controller).build(); + mvc.perform(get("/tool/gen/column/7")).andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.msg").value("查询成功")) + .andExpect(jsonPath("$.total").value(1)).andExpect(jsonPath("$.rows[0].columnId").value(9)); + verify(tables).selectGenTableById(7L);verify(columns).selectGenTableColumnListByTableId(7L); + } + @Test void missingColumnTableIsRejectedBeforeReadingItsColumns() throws Exception { + var tables = mock(IGenTableService.class); + var columns = mock(IGenTableColumnService.class); + var controller = new GenController(); + ReflectionTestUtils.setField(controller, "genTableService", tables); + ReflectionTestUtils.setField(controller, "genTableColumnService", columns); + when(tables.selectGenTableById(0L)).thenThrow(new ServiceException("生成配置不存在或已删除,请返回列表刷新")); + MockMvcBuilders.standaloneSetup(controller).setControllerAdvice(new GlobalExceptionHandler()).build() + .perform(get("/tool/gen/column/0")).andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("生成配置不存在或已删除,请返回列表刷新")); + verifyNoInteractions(columns); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyDatabaseTest.java new file mode 100644 index 0000000..0212a70 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyDatabaseTest.java @@ -0,0 +1,47 @@ +package com.ruoyi.projectdev; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; +import org.springframework.test.util.ReflectionTestUtils; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import com.ruoyi.warehouse.domain.ProductInfo; +import com.ruoyi.warehouse.mapper.ProductInfoMapper; +import com.ruoyi.warehouse.service.impl.ItemCategoryService; +import static org.junit.jupiter.api.Assertions.*; + +@EnabledIfSystemProperty(named="projectDbTests",matches="true") +class ItemCategoryHierarchyDatabaseTest { + @Test void groupingFilteringAndSummaryUseSameRelationshipsAndRollback() throws Exception { + try(var connection=AuthorizedDatabaseTestSupport.connection()) { + var jdbc=new JdbcTemplate(new SingleConnectionDataSource(connection,true)); + String prefix="category-test-"+UUID.randomUUID().toString().substring(0,8); + long before=jdbc.queryForObject("select count(*) from product_info",Long.class); + try { + jdbc.update("insert into sys_dict_data(dict_label,dict_value,dict_type,status) values(?,?,?,'0')",prefix,prefix,ItemCategoryService.GROUP); + long group=jdbc.queryForObject("select dict_code from sys_dict_data where dict_type=? and dict_label=?",Long.class,ItemCategoryService.GROUP,prefix); + for(int i=0;i<2;i++){ + String label=prefix+"-"+i; + jdbc.update("insert into sys_dict_data(dict_label,dict_value,dict_type,status,parent_code) values(?,?,?,'0',?)",label,label,ItemCategoryService.LEAF,group); + jdbc.update("insert into product_info(product_code,product_name,category,unit) values(?,?,?,'个')",label,label,label); + } + var service=new ItemCategoryService();ReflectionTestUtils.setField(service,"jdbc",jdbc); + assertEquals(2,service.options().stream().filter(r->prefix.equals(r.get("parentLabel"))).count()); + assertEquals(2,service.summary().stream().filter(r->prefix.equals(r.get("parentLabel"))).mapToLong(r->((Number)r.get("itemCount")).longValue()).sum()); + var factory=new SqlSessionFactoryBuilder().build(AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/ProductInfoMapper.xml")); + try(var session=factory.openSession(connection)) { + var mapper=session.getMapper(ProductInfoMapper.class);var query=new ProductInfo();query.setCategoryGroupId(group); + var results=mapper.selectProductInfoList(query);assertEquals(2,results.size());assertTrue(results.stream().allMatch(p->prefix.equals(p.getCategoryGroupName()))); + query.setCategory(prefix+"-0");assertEquals(1,mapper.selectProductInfoList(query).size()); + jdbc.update("update sys_dict_data set status='1' where dict_code=?",group); + assertEquals(0,service.options().stream().filter(r->prefix.equals(r.get("parentLabel"))).count()); + query.setCategory(null);assertEquals(2,mapper.selectProductInfoList(query).size(),"Disabled groups still support historical queries"); + session.rollback(true); + } + } finally { if(!connection.isClosed())connection.rollback(); } + if(!connection.isClosed())assertEquals(before,jdbc.queryForObject("select count(*) from product_info",Long.class)); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyTest.java new file mode 100644 index 0000000..b45df15 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ItemCategoryHierarchyTest.java @@ -0,0 +1,24 @@ +package com.ruoyi.projectdev; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.common.core.domain.entity.SysDictData; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.service.impl.ItemCategoryService; +import com.ruoyi.warehouse.service.impl.CatalogWriteLock; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ItemCategoryHierarchyTest { + final JdbcTemplate jdbc=mock(JdbcTemplate.class); + final ItemCategoryService service=new ItemCategoryService(); + ItemCategoryHierarchyTest(){ReflectionTestUtils.setField(service,"jdbc",jdbc);ReflectionTestUtils.setField(service,"catalogLock",mock(CatalogWriteLock.class));when(jdbc.queryForObject(anyString(),eq(Long.class),any(Object[].class))).thenReturn(0L);} + SysDictData data(String type){var d=new SysDictData();d.setDictCode(2L);d.setDictType(type);d.setDictLabel("紧固件");d.setDictValue("紧固件");d.setStatus("0");return d;} + @Test void onlyTwoLevelsAndValidParents(){var d=data(ItemCategoryService.GROUP);d.setParentCode(1L);assertThrows(ServiceException.class,()->service.validate(d,null));d.setDictType(ItemCategoryService.LEAF);assertThrows(ServiceException.class,()->service.validate(d,null));when(jdbc.queryForObject(contains("dict_code=? and dict_type=?"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertThrows(ServiceException.class,()->service.validate(d,null));when(jdbc.queryForObject(contains("dict_code=? and status='0'"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertDoesNotThrow(()->service.validate(d,null));} + @Test void existingUngroupedLeavesCanBePreserved(){var d=data(ItemCategoryService.LEAF);assertDoesNotThrow(()->service.validate(d,d));verify(jdbc,never()).update(anyString(),any(Object[].class));} + @Test void cannotDeleteGroupWithChildrenOrReferencedLeaf(){when(jdbc.queryForObject(contains("parent_code=?"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertThrows(ServiceException.class,()->service.validateDelete(data(ItemCategoryService.GROUP)));when(jdbc.queryForObject(contains("product_info"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertThrows(ServiceException.class,()->service.validateDelete(data(ItemCategoryService.LEAF)));} + @Test void usedLeafMayMoveButCannotBeRenamed(){var old=data(ItemCategoryService.LEAF);var changed=data(ItemCategoryService.LEAF);changed.setDictLabel("新名称");when(jdbc.queryForObject(contains("product_info"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertThrows(ServiceException.class,()->service.validate(changed,old));changed.setDictLabel(old.getDictLabel());assertDoesNotThrow(()->service.validate(changed,old));} + @Test void duplicateNamesCannotCreateAmbiguousLegacyLabelLinks(){when(jdbc.queryForObject(contains("dict_code<>?"),eq(Long.class),any(Object[].class))).thenReturn(1L);assertThrows(ServiceException.class,()->service.validate(data(ItemCategoryService.LEAF),null));} +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductDictionaryValidationTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductDictionaryValidationTest.java new file mode 100644 index 0000000..a51eb5a --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductDictionaryValidationTest.java @@ -0,0 +1,43 @@ +package com.ruoyi.projectdev; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.common.core.domain.entity.SysDictData; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.system.service.ISysDictTypeService; +import com.ruoyi.warehouse.domain.ProductInfo; +import com.ruoyi.warehouse.mapper.ProductInfoMapper; +import com.ruoyi.warehouse.service.impl.ProductInfoServiceImpl; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ProductDictionaryValidationTest { + @Test void onlyMaintainedValuesCanBeIntroducedWhileHistoryIsPreserved() { + var service = new ProductInfoServiceImpl(); + var dictionaries = mock(ISysDictTypeService.class); + var mapper = mock(ProductInfoMapper.class); + ReflectionTestUtils.setField(service, "dictTypes", dictionaries); + var categories=mock(com.ruoyi.warehouse.service.impl.ItemCategoryService.class); + ReflectionTestUtils.setField(service,"itemCategories",categories); + when(categories.labels()).thenReturn(List.of("机械件")); + ReflectionTestUtils.setField(service, "productInfoMapper", mapper); + var category = new SysDictData(); category.setDictLabel("机械件"); category.setStatus("0"); + var unit = new SysDictData(); unit.setDictLabel("个"); unit.setStatus("0"); + when(dictionaries.selectDictDataByType("wms_item_category")).thenReturn(List.of(category)); + when(dictionaries.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit)); + var item = new ProductInfo(); item.setProductName("新物品"); item.setCategory("机械件"); item.setUnit("个"); + assertDoesNotThrow(() -> ReflectionTestUtils.invokeMethod(service, "validateFields", item)); + item.setCategory("临时分类"); + assertThrows(ServiceException.class, () -> ReflectionTestUtils.invokeMethod(service, "validateFields", item)); + item.setCategory("机械件"); item.setUnit("临时单位"); + assertThrows(ServiceException.class, () -> ReflectionTestUtils.invokeMethod(service, "validateFields", item)); + item.setUnit("个"); category.setStatus("1"); + when(categories.labels()).thenReturn(List.of()); + assertThrows(ServiceException.class, () -> ReflectionTestUtils.invokeMethod(service, "validateFields", item)); + var previous = new ProductInfo(); previous.setCategory("机械件"); previous.setUnit("个"); + item.setId(42L); when(mapper.selectProductInfoById(42L)).thenReturn(previous); + assertDoesNotThrow(() -> ReflectionTestUtils.invokeMethod(service, "validateFields", item)); + verify(mapper, never()).insertProductInfo(any()); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java index 23e97f0..4d3d23a 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java @@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class ProductImportTest { ProductInfo row(){var r=new ProductInfo();r.setProductName("测试螺丝");r.setUnit("个");r.setCategory("零件");return r;} - ProductInfoServiceImpl service(ProductInfoMapper mapper){var service=new ProductInfoServiceImpl();ReflectionTestUtils.setField(service,"productInfoMapper",mapper);ReflectionTestUtils.setField(service,"catalogWriteLock",mock(CatalogWriteLock.class));var numbers=mock(com.ruoyi.warehouse.service.impl.BusinessNumberService.class);when(numbers.reserve(eq("ITEM"),any(),any())).thenReturn("WP2026100001");ReflectionTestUtils.setField(service,"businessNumbers",numbers);return service;} + ProductInfoServiceImpl service(ProductInfoMapper mapper){var service=new ProductInfoServiceImpl();ReflectionTestUtils.setField(service,"productInfoMapper",mapper);ReflectionTestUtils.setField(service,"catalogWriteLock",mock(CatalogWriteLock.class));var numbers=mock(com.ruoyi.warehouse.service.impl.BusinessNumberService.class);when(numbers.reserve(eq("ITEM"),any(),any())).thenReturn("WP2026100001");ReflectionTestUtils.setField(service,"businessNumbers",numbers);var categories=mock(com.ruoyi.warehouse.service.impl.ItemCategoryService.class);when(categories.labels()).thenReturn(List.of("零件"));ReflectionTestUtils.setField(service,"itemCategories",categories);var dicts=mock(com.ruoyi.system.service.ISysDictTypeService.class);var unit=new com.ruoyi.common.core.domain.entity.SysDictData();unit.setDictLabel("个");unit.setStatus("0");when(dicts.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));ReflectionTestUtils.setField(service,"dictTypes",dicts);return service;} @Test void previewIsReadOnlyAndDetectsDuplicateFileRows(){var mapper=mock(ProductInfoMapper.class);var service=service(mapper);var result=service.previewImport(List.of(row(),row()));assertNull(result.get(0).get("error"));assertNotNull(result.get(1).get("error"));verify(mapper,never()).insertProductInfo(any());assertThrows(ServiceException.class,()->service.importNew(List.of(row(),row())));verify(mapper,never()).insertProductInfo(any());} @Test void newItemsReceiveCodesAndExistingCodesCannotBeOverwritten(){var mapper=mock(ProductInfoMapper.class);var service=service(mapper);var item=row();service.insertProductInfo(item);assertEquals("WP2026100001",item.getProductCode());var existing=row();existing.setId(9L);when(mapper.checkProductCodeUnique("OLD")).thenReturn(existing);var duplicate=row();duplicate.setProductCode("OLD");assertThrows(ServiceException.class,()->service.insertProductInfo(duplicate));var missing=row();missing.setUnit(null);assertThrows(ServiceException.class,()->service.insertProductInfo(missing));} } diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostExportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostExportTest.java new file mode 100644 index 0000000..0031f68 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostExportTest.java @@ -0,0 +1,43 @@ +package com.ruoyi.projectdev; + +import java.io.ByteArrayInputStream; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.production.service.ProductionCostView; +import com.ruoyi.production.service.ProductionService; +import com.ruoyi.web.controller.production.ProductionTaskController; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ProductionCostExportTest { + @Test void taskAndHistoryExportsIncludePendingCostStateInsteadOfZero() throws Exception { + var service = mock(ProductionService.class); + var row = ProductionCostView.of(Map.of("status", "SETTLED", "material_recorded", 0, + "material_cost", BigDecimal.ZERO, "unit_cost", BigDecimal.ZERO, "good_quantity", BigDecimal.ONE)); + when(service.tasks(null, null)).thenReturn(List.of(row)); + when(service.costHistory(3L, null, null)).thenReturn(List.of(row)); + var controller = new ProductionTaskController(); ReflectionTestUtils.setField(controller, "service", service); + for (boolean history : new boolean[]{false, true}) { + var response = new MockHttpServletResponse(); + if (history) controller.costHistoryExport(response, 3L, null, null); + else controller.export(response, null, null); + try (var workbook = new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))) { + var sheet = workbook.getSheetAt(0); var header = sheet.getRow(0); var data = sheet.getRow(1); + int stateCount = 0, emptyAmountCount = 0; + for (int c = 0; c < header.getLastCellNum(); c++) { + String title = header.getCell(c).getStringCellValue(); + if (title.endsWith("成本状态")) { assertEquals("用料待核对", data.getCell(c).getStringCellValue()); stateCount++; } + if (title.equals(history ? "材料总成本" : "实际材料成本") || title.equals(history ? "单位成本" : "单位材料成本")) { + assertEquals("", data.getCell(c).getStringCellValue()); emptyAmountCount++; + } + } + assertEquals(2, stateCount); assertEquals(2, emptyAmountCount); + } + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostViewTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostViewTest.java new file mode 100644 index 0000000..2b54502 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionCostViewTest.java @@ -0,0 +1,54 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import com.ruoyi.production.service.ProductionCostView; +import static org.junit.jupiter.api.Assertions.*; + +class ProductionCostViewTest { + private Map settled() { + return new LinkedHashMap<>(Map.of("status", "SETTLED", "material_recorded", 1, + "material_cost", BigDecimal.ZERO, "unit_cost", BigDecimal.ZERO, "good_quantity", BigDecimal.ONE)); + } + + @Test void legacyZeroWithoutMaterialRecordsIsNotAFreeProduct() { + var source = settled(); source.put("material_recorded", 0); + var view = ProductionCostView.of(source); + assertNull(view.get("material_cost")); assertNull(view.get("unit_cost")); + assertEquals("用料待核对", view.get("cost_status_text")); + assertEquals("用料待核对", view.get("unit_cost_status_text")); + assertEquals(BigDecimal.ZERO, source.get("material_cost"), "Read-only presentation must preserve history"); + } + + @Test void recordedZeroPriceIsAValidKnownCost() { + var view = ProductionCostView.of(settled()); + assertEquals("KNOWN", view.get("cost_status")); + assertEquals("KNOWN", view.get("unit_cost_status")); + assertEquals(BigDecimal.ZERO, view.get("material_cost")); + assertEquals(BigDecimal.ZERO, view.get("unit_cost")); + } + + @Test void materialWithUnknownPriceDoesNotExposeAStaleUnitPrice() { + var source = settled(); source.put("material_cost", null); + var view = ProductionCostView.of(source); + assertEquals("UNKNOWN", view.get("cost_status")); + assertNull(view.get("unit_cost")); + } + + @Test void reopenedTaskDoesNotShowPreviousSettlementAsCurrentFinalCost() { + var source = settled(); source.put("status", "OPEN"); + var view = ProductionCostView.of(source); + assertEquals("未结算", view.get("cost_status_text")); + assertNull(view.get("material_cost")); assertNull(view.get("unit_cost")); + } + + @Test void noGoodOutputPreservesTotalLossButHasNoUnitCost() { + var source = settled(); source.put("material_cost", new BigDecimal("20")); source.put("good_quantity", BigDecimal.ZERO); + var view = ProductionCostView.of(source); + assertEquals(new BigDecimal("20"), view.get("material_cost")); + assertNull(view.get("unit_cost")); + assertEquals("无合格产出", view.get("unit_cost_status_text")); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionQueryUsabilityTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionQueryUsabilityTest.java new file mode 100644 index 0000000..bfe3b8d --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionQueryUsabilityTest.java @@ -0,0 +1,76 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.production.service.ProductionService; +import com.ruoyi.project.service.IProjectInfoService; +import com.ruoyi.web.controller.production.ProductionTaskController; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ProductionQueryUsabilityTest { + private ProductionService service(JdbcTemplate db) { + when(db.queryForObject(anyString(),eq(Long.class),any(Object[].class))).thenReturn(0L); + var service=new ProductionService();ReflectionTestUtils.setField(service,"db",db); + ReflectionTestUtils.setField(service,"projects",mock(IProjectInfoService.class));return service; + } + private List lists(JdbcTemplate db) { + return mockingDetails(db).getInvocations().stream().filter(i->i.getMethod().getName().equals("queryForList")).toList(); + } + @Test void taskExportAndPageShareEveryFilterWithoutExportLimit() { + var db=mock(JdbcTemplate.class);var service=service(db); + service.page(2L,3L,"READY"," robot ",2,20);service.filteredTasks(2L,3L,"READY"," robot "); + var calls=lists(db);assertEquals(2,calls.size());String page=calls.get(0).getArgument(0),export=calls.get(1).getArgument(0); + assertEquals(page.substring(0,page.indexOf(" order by t.id desc")),export.substring(0,export.indexOf(" order by t.id desc"))); + assertTrue(page.endsWith("limit ? offset ?"));assertFalse(export.contains("limit ?")); + assertArrayEquals(new Object[]{2L,3L,"%robot%"},Arrays.copyOfRange(calls.get(1).getArguments(),1,4)); + } + @Test void actionExportAndPageShareTypeStatusKeywordAndDateRange() { + var db=mock(JdbcTemplate.class);var service=service(db); + service.actionPage(2L,3L,"SCRAP_STOCK",false," screw ","2026-10-01","2026-10-13",2,20); + service.filteredActions(2L,3L,"SCRAP_STOCK",false," screw ","2026-10-01","2026-10-13"); + var calls=lists(db);String page=calls.get(0).getArgument(0),export=calls.get(1).getArgument(0); + assertEquals(page.substring(0,page.indexOf(" order by a.id desc")),export.substring(0,export.indexOf(" order by a.id desc"))); + assertFalse(export.contains("limit ?"));var args=calls.get(1).getArguments(); + assertEquals(false,args[4]);assertEquals("%screw%",args[5]);assertEquals(java.time.LocalDate.of(2026,10,1),args[6]); + } + @Test void eligibleTaskConditionsApplyBeforePaging() { + var db=mock(JdbcTemplate.class);var service=service(db); + service.operationPage(2L,null,null,"robot","SCRAP_ASSEMBLY",1,50); + service.operationPage(2L,null,null,"screw","SCRAP_ISSUED",1,50); + String assembly=lists(db).get(0).getArgument(0),issued=lists(db).get(1).getArgument(0); + assertTrue(assembly.contains("and t.status='OPEN' and t.planned_quantity>")); + assertTrue(issued.contains("and exists(select 1 from production_action x where x.task_id=t.id and x.kind='ISSUE'")); + assertTrue(assembly.endsWith("limit ? offset ?"));assertTrue(issued.endsWith("limit ? offset ?")); + } + @Test void projectSummaryUsesFixedReadQueriesAndPreservesKnownAmountAndUnknownCount() { + var db=mock(JdbcTemplate.class);var service=service(db); + when(db.queryForMap(anyString(),any(Object[].class))).thenReturn(Map.of("amount",new BigDecimal("12.345678"),"unknown",2L)); + var summary=service.projectSummary(2L);var stock=(Map)summary.get("inventory"); + assertEquals(new BigDecimal("12.345678"),stock.get("amount"));assertEquals(2L,stock.get("unknown")); + assertEquals(1,lists(db).size());assertFalse(summary.containsKey("products")); + var inventory=mockingDetails(db).getInvocations().stream().filter(i->i.getMethod().getName().equals("queryForMap")).findFirst().orElseThrow(); + String sql=inventory.getArgument(0);assertTrue(sql.contains("sum(round(c.amount*s.quantity/nullif(c.quantity,0),6))"));assertTrue(sql.contains("s.quantity>0")); + assertTrue(mockingDetails(db).getInvocations().stream().noneMatch(i->i.getMethod().getName().startsWith("update"))); + } + @Test void summaryEndpointsRetainSeparateHistoricReadPermissions() throws Exception { + var summary=ProductionTaskController.class.getMethod("projectSummary",Long.class).getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class); + var totals=ProductionTaskController.class.getMethod("productTotals",Long.class).getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class); + assertEquals("@ss.hasPermi('warehouse:stock:list')",summary.value()); + assertEquals("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')",totals.value()); + var db=mock(JdbcTemplate.class);var service=service(db);service.productTotals(2L); + assertEquals(1,lists(db).size());String sql=lists(db).get(0).getArgument(0); + assertTrue(sql.contains("planned"));assertTrue(sql.contains("delivered")); + assertFalse(sql.contains("project_item_cost"));assertFalse(sql.contains("effective_cost"));assertFalse(sql.contains("stock_balance")); + } + @Test void exportControllerForwardsEveryFilter() throws Exception { + var service=mock(ProductionService.class);var controller=new ProductionTaskController();ReflectionTestUtils.setField(controller,"service",service); + controller.exportFiltered(new MockHttpServletResponse(),2L,3L,"READY","robot"); + controller.exportActions(new MockHttpServletResponse(),2L,3L,"DELIVERY",true,"robot","2026-10-01","2026-10-13"); + verify(service).filteredTasks(2L,3L,"READY","robot");verify(service).filteredActions(2L,3L,"DELIVERY",true,"robot","2026-10-01","2026-10-13"); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionSettlementHistoryTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionSettlementHistoryTest.java new file mode 100644 index 0000000..b981e4f --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionSettlementHistoryTest.java @@ -0,0 +1,33 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.production.service.ProductionService; +import static org.junit.jupiter.api.Assertions.*; + +class ProductionSettlementHistoryTest { + @Test void sameSecondWithdrawalCannotErasePersistedNonzeroSettlementCost() { + var source = Map.of("status", "SETTLED", "material_recorded", 0, + "material_cost", new BigDecimal("24"), "unit_cost", new BigDecimal("12"), "good_quantity", 2); + List> rows = ReflectionTestUtils.invokeMethod(new ProductionService(), "settlementCostViews", List.of(source)); + assertEquals(new BigDecimal("24"), rows.get(0).get("material_cost")); + assertEquals(new BigDecimal("12"), rows.get(0).get("unit_cost")); + assertEquals("KNOWN", rows.get(0).get("cost_status")); + assertEquals(0, source.get("material_recorded"), "Historical display must not mutate stored evidence"); + } + + @Test void AmbiguousHistoricalZeroStaysPendingButAnEarlierRecordedZeroIsKnown() { + var ambiguous = Map.of("status", "SETTLED", "material_recorded", 0, + "material_cost", BigDecimal.ZERO, "unit_cost", BigDecimal.ZERO, "good_quantity", 2); + var recorded = Map.of("status", "SETTLED", "material_recorded", 1, + "material_cost", BigDecimal.ZERO, "unit_cost", BigDecimal.ZERO, "good_quantity", 2); + List> rows = ReflectionTestUtils.invokeMethod(new ProductionService(), "settlementCostViews", List.of(ambiguous, recorded)); + assertNull(rows.get(0).get("material_cost")); assertNull(rows.get(0).get("unit_cost")); + assertEquals("PENDING_MATERIAL", rows.get(0).get("cost_status")); + assertEquals(BigDecimal.ZERO, rows.get(1).get("material_cost")); + assertEquals("KNOWN", rows.get(1).get("cost_status")); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java index ae4c512..7beeaf8 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java @@ -11,6 +11,81 @@ import com.ruoyi.warehouse.mapper.ProductInfoMapper; import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; class ProductionShortageTest { + @Test void repeatedBomItemConsumesSelfMadeCoverageOnlyOnce(){ + var service=duplicateBomService(0,10,false); + var needs=service.needs(1L);assertEquals(1,needs.size()); + assertAmount("20",needs.get(0),"required");assertAmount("10",needs.get(0),"selfMade"); + assertAmount("10",needs.get(0),"purchaseSuggestion"); + assertAmount("10",service.shortages(List.of(1L)).get(0),"purchaseSuggestion"); + assertEquals(List.of(31L,32L),needs.get(0).get("childBomIds")); + assertNull(needs.get(0).get("childBomId"),"Do not guess a child version when duplicate lines reference different versions"); + var choices=(List)needs.get(0).get("childBomOptions");assertEquals(2,choices.size()); + } + @Test void repeatedBomItemConsumesIssueReturnScrapAndPurchaseQuantitiesOnlyOnce(){ + var service=duplicateBomService(3,5,true);var row=service.needs(1L).get(0); + assertAmount("20",row,"required");assertAmount("6",row,"issued");assertAmount("2",row,"returned");assertAmount("1",row,"scrapped"); + assertAmount("17",row,"outstanding");assertAmount("4",row,"purchasing");assertAmount("5",row,"purchaseSuggestion"); + assertAmount("5",service.shortages(List.of(1L)).get(0),"purchaseSuggestion"); + } + @Test void repeatedBomLinesAndMultipleTasksAllocateSharedStockOnlyOnce(){ + var service=duplicateBomService(6,10,false);var rows=service.shortages(List.of(2L,1L)); + assertEquals(2,rows.size()); + assertAmount("6",rows.get(0),"allocatedStock");assertAmount("4",rows.get(0),"purchaseSuggestion"); + assertAmount("0",rows.get(1),"allocatedStock");assertAmount("20",rows.get(1),"purchaseSuggestion"); + } + private ProductionService duplicateBomService(int stock,int making,boolean movements){ + var service=spy(new ProductionService());var db=mock(JdbcTemplate.class);var boms=mock(BomService.class); + ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"boms",boms);ReflectionTestUtils.setField(service,"items",mock(ProductInfoMapper.class)); + doAnswer(call->Map.of("id",call.getArgument(0),"project_id",2L,"project_name","项目","task_no","SC1","bom_id",9L,"planned_quantity",BigDecimal.TEN,"status","OPEN")).when(service).task(anyLong()); + var first=new BomLine();first.setItemId(3L);first.setItemName("重复零件");first.setUnitQuantity(BigDecimal.ONE);first.setChildBomId(31L);first.setChildVersionTag("V1"); + var second=new BomLine();second.setItemId(3L);second.setItemName("重复零件");second.setUnitQuantity(BigDecimal.ONE);second.setChildBomId(32L);second.setChildVersionTag("V2"); + var bom=new BomVersion();bom.setLines(List.of(first,second));when(boms.get(9L)).thenReturn(bom); + when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->{ + String sql=call.getArgument(0);Long task=call.getArgument(1); + if(sql.startsWith("select t.item_id"))return task==1L?List.of(Map.of("item_id",3L,"quantity",BigDecimal.valueOf(making))):List.of(); + if(sql.startsWith("select item_id,sum(case when kind='ISSUE'"))return movements&&task==1L?List.of(Map.of("item_id",3L,"issued",new BigDecimal("6"),"returned",new BigDecimal("2"),"scrapped",BigDecimal.ONE)):List.of(); + if(sql.startsWith("select pr.product_id"))return movements&&task==1L?List.of(Map.of("product_id",3L,"purchasing",new BigDecimal("4"))):List.of(); + if(sql.contains("from project_stock_balance"))return List.of(Map.of("item_id",3L,"quantity",BigDecimal.valueOf(stock))); + throw new AssertionError(sql); + });return service; + } + @Test void selfMadeCoverageDoesNotConsumeStockNeededByAnotherTask(){ + var service=shortageService(); + doReturn(List.of(need(1,2,10,6,10,0))).when(service).needs(1L); + doReturn(List.of(need(2,2,10,6,0,0))).when(service).needs(2L); + var rows=service.shortages(List.of(2L,1L,1L)); + assertEquals(2,rows.size()); + assertAmount("0",rows.get(0),"allocatedStock");assertAmount("0",rows.get(0),"purchaseSuggestion"); + assertAmount("6",rows.get(1),"allocatedStock");assertAmount("4",rows.get(1),"purchaseSuggestion"); + } + @Test void partialSelfMadeAndAssignedPurchasesCoverDemandBeforeSharedStock(){ + var service=shortageService(); + doReturn(List.of(need(1,2,10,5,4,3))).when(service).needs(1L); + doReturn(List.of(need(2,2,10,5,0,2))).when(service).needs(2L); + var rows=service.shortages(List.of(1L,2L)); + assertAmount("3",rows.get(0),"allocatedStock");assertAmount("0",rows.get(0),"purchaseSuggestion"); + assertAmount("2",rows.get(1),"allocatedStock");assertAmount("6",rows.get(1),"purchaseSuggestion"); + } + @Test void differentProjectsDoNotShareStockAllocation(){ + var service=shortageService(); + doReturn(List.of(need(1,2,10,6,2,0))).when(service).needs(1L); + doReturn(List.of(need(2,3,10,6,0,0))).when(service).needs(2L); + var rows=service.shortages(List.of(1L,2L)); + assertAmount("6",rows.get(0),"allocatedStock");assertAmount("2",rows.get(0),"purchaseSuggestion"); + assertAmount("6",rows.get(1),"allocatedStock");assertAmount("4",rows.get(1),"purchaseSuggestion"); + } + private ProductionService shortageService(){ + var service=spy(new ProductionService()); + ReflectionTestUtils.setField(service,"items",mock(ProductInfoMapper.class)); + doReturn(Map.of("status","OPEN")).when(service).task(anyLong()); + return service; + } + private Map need(long task,long project,int outstanding,int available,int selfMade,int purchasing){ + var row=new LinkedHashMap();row.put("taskId",task);row.put("projectId",project);row.put("itemId",3L); + row.put("outstanding",BigDecimal.valueOf(outstanding));row.put("available",BigDecimal.valueOf(available)); + row.put("selfMade",BigDecimal.valueOf(selfMade));row.put("purchasing",BigDecimal.valueOf(purchasing));return row; + } + private void assertAmount(String expected,Map row,String field){assertEquals(0,new BigDecimal(expected).compareTo((BigDecimal)row.get(field)),field);} @Test void scrapAddsDemandPurchasesCoverOnlyAssignedTaskAndStockIsSharedOnce(){ var service=new ProductionService();var db=mock(JdbcTemplate.class);var boms=mock(BomService.class);var items=mock(ProductInfoMapper.class);var projects=mock(com.ruoyi.project.service.IProjectInfoService.class); ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"boms",boms);ReflectionTestUtils.setField(service,"items",items);ReflectionTestUtils.setField(service,"projects",projects); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionTaskBomTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionTaskBomTest.java new file mode 100644 index 0000000..7d10af1 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionTaskBomTest.java @@ -0,0 +1,41 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.production.domain.BomVersion; +import com.ruoyi.production.domain.ProductionCommand; +import com.ruoyi.production.service.BomService; +import com.ruoyi.production.service.ProductionService; +import com.ruoyi.project.service.IProjectInfoService; +import com.ruoyi.warehouse.service.impl.InventoryCostJournal; +import static org.mockito.Mockito.*; + +class ProductionTaskBomTest { + @Test void editingQuantityKeepsFrozenBomAndOnlyAnExplicitDifferentBomReplacesIt() { + var service = new ProductionService(); + var db = mock(JdbcTemplate.class); var boms = mock(BomService.class); + ReflectionTestUtils.setField(service, "db", db); + ReflectionTestUtils.setField(service, "boms", boms); + ReflectionTestUtils.setField(service, "journal", mock(InventoryCostJournal.class)); + ReflectionTestUtils.setField(service, "projects", mock(IProjectInfoService.class)); + Map task = Map.of("id", 1L, "project_id", 2L, "item_id", 3L, "bom_id", 91L, + "source_bom_id", 90L, "status", "OPEN", "version", 1, "editable_identity", 1); + when(db.queryForList(anyString(), any(Object[].class))).thenReturn(List.of(task)); + var command = new ProductionCommand(); command.id = 1L; command.projectId = 2L; + command.itemId = 3L; command.bomId = 91L; command.quantity = new BigDecimal("12"); command.version = 1; + service.save(command); + verify(boms, never()).snapshotForTask(anyLong(), anyLong(), anyLong()); + + var replacement = new BomVersion(); replacement.setId(92L); replacement.setItemId(3L); + var snapshot = new BomVersion(); snapshot.setId(93L); + when(boms.get(92L)).thenReturn(replacement); + when(boms.snapshotForTask(92L, 2L, 1L)).thenReturn(snapshot); + command.bomId = 92L; service.save(command); + verify(boms).snapshotForTask(92L, 2L, 1L); + verify(db).update("update production_task set project_id=?,item_id=?,source_bom_id=?,bom_id=? where id=?", 2L, 3L, 92L, 93L, 1L); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java index 4abdd26..8774997 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java @@ -45,6 +45,16 @@ class ProjectLoanDatabaseTest { var receipt=journal.append(event(p,i,a,"RECEIPT",n("10"),n("100"),null,key)); var first=loans.borrow(p,q,i,a,b,n("4"),key+"-BORROW",null);assertEquals(n("4.0000"),first.getOutstandingQuantity()); assertEquals(first.getId(),loans.borrow(p,q,i,a,b,n("4"),key+"-BORROW",null).getId());assertEquals(1,loans.list(p,i,false).size()); + // The purchase repayment selector applies all three filters together. Exercise every + // combination against MySQL so adjacent dynamic SQL fragments cannot break this entry point. + for(Long projectFilter:new Long[]{null,p})for(Long itemFilter:new Long[]{null,i})for(boolean outstanding:new boolean[]{false,true}){ + var filtered=loans.list(projectFilter,itemFilter,outstanding); + assertTrue(filtered.stream().anyMatch(row->row.getId().equals(first.getId())),"Missing loan for filters "+projectFilter+":"+itemFilter+":"+outstanding); + assertTrue(filtered.stream().allMatch(row->projectFilter==null||projectFilter.equals(row.getLenderProjectId())||projectFilter.equals(row.getBorrowerProjectId()))); + assertTrue(filtered.stream().allMatch(row->itemFilter==null||itemFilter.equals(row.getItemId()))); + assertTrue(filtered.stream().allMatch(row->!outstanding||Boolean.TRUE.equals(row.getActive())&&row.getOutstandingQuantity().signum()>0)); + } + assertTrue(loans.list(r,i,true).isEmpty()); var second=loans.borrow(q,r,i,b,a,n("2"),key+"-SECOND",null);var consumed=journal.append(event(r,i,a,"ISSUE",n("2"),null,null,key+"-CONSUME")); assertEquals(n("20.000000"),consumed.getOriginalCost());journal.reviseReceipt(receipt.getId(),n("200"),key+"-SETTLE",journal.balance(p,i).getVersion()); assertEquals(n("40.000000"),journal.balance(q,i).getAmount());assertEquals(n("40.000000"),costs.selectEvent(consumed.getId()).getEffectiveCost());assertEquals(n("20.000000"),costs.selectEvent(consumed.getId()).getOriginalCost()); @@ -56,6 +66,7 @@ class ProjectLoanDatabaseTest { assertThrows(ServiceException.class,()->loans.revokeLoan(first.getId(),"已有下游"));assertTrue(loans.get(first.getId()).getActive()); loans.revokeStockReturn(first.getId(),"LOAN-RETURN:"+key+"-RETURN","归还纠错");assertEquals(n("0.0000"),loans.get(first.getId()).getReturnedQuantity()); journal.voidLastEvent(consumed.getId(),"先撤销消耗");loans.revokeLoan(second.getId(),"撤销第二层借用");loans.revokeLoan(first.getId(),"撤销首层借用"); + assertTrue(loans.list(p,i,true).isEmpty());assertEquals(1,loans.list(p,i,false).size()); assertEquals(n("10.0000"),journal.balance(p,i).getQuantity());assertEquals(n("100.000000"),journal.balance(p,i).getAmount());assertEquals(n("0.0000"),journal.balance(q,i).getQuantity()); });assertNull(costs.selectEventByKey(key));}finally{connection.rollback();} } diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java index 16e014b..11b1368 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java @@ -218,10 +218,23 @@ class ProjectPurchaseDatabaseTest { db.update("update in_record set arrival_id=? where id=?",arrival.getId(),rootReceipt.getId()); var returns=new com.ruoyi.warehouse.service.impl.PurchaseReturnService(); ReflectionTestUtils.setField(returns,"db",db);ReflectionTestUtils.setField(returns,"journal",journal);ReflectionTestUtils.setField(returns,"purchases",purchases);ReflectionTestUtils.setField(returns,"arrivals",arrivals);ReflectionTestUtils.setField(returns,"receipts",receipts);ReflectionTestUtils.setField(returns,"prices",pricing); + var returnAvailability=returns.availability(arrival.getId()); + assertTrue(returnAvailability.supported()); + assertEquals(new BigDecimal("0.0019"),returnAvailability.acceptedQuantity()); + assertEquals(new BigDecimal("0.0014"),returnAvailability.receivedQuantity()); + assertEquals(new BigDecimal("0.0005"),returnAvailability.returnableQuantity()); + db.update("update in_record set receipt_root=0 where id=?",rootReceipt.getId()); + assertFalse(returns.availability(arrival.getId()).supported()); + db.update("update in_record set receipt_root=1 where id=?",rootReceipt.getId()); + assertThrows(com.ruoyi.common.exception.ServiceException.class,()->returns.availability(Long.MAX_VALUE)); var tooMany=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0006"),false,null,"超量",UUID.randomUUID().toString()); assertThrows(com.ruoyi.common.exception.ServiceException.class,()->returns.returnGoods(tooMany)); var replace=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0002"),false,null,"等补货",UUID.randomUUID().toString()); returns.returnGoods(replace);returns.returnGoods(replace); + assertEquals(new BigDecimal("0.0002"),returns.availability(arrival.getId()).returnedQuantity()); + assertEquals(new BigDecimal("0.0003"),returns.availability(arrival.getId()).returnableQuantity()); + var staleQuantity=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),returnAvailability.returnableQuantity(),false,null,"过期数量",UUID.randomUUID().toString()); + assertThrows(com.ruoyi.common.exception.ServiceException.class,()->returns.returnGoods(staleQuantity)); assertEquals(new BigDecimal("0.003800"),purchases.selectPurchaseRequestByIdForUpdate(row.getId()).getLockedAmount()); var cancelPart=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0003"),true,null,"取消部分",UUID.randomUUID().toString()); returns.returnGoods(cancelPart);returns.returnGoods(cancelPart); @@ -230,6 +243,15 @@ class ProjectPurchaseDatabaseTest { assertEquals(new BigDecimal("0.0014"),arrivals.selectAcceptedQuantityByRequestId(row.getId())); assertEquals(2,returns.history(arrival.getId()).size()); assertEquals(new BigDecimal("0.0014"),stocks.selectStockInfoByAreaProduct(areaId,productId).getStockNum()); + assertEquals(0,returns.availability(arrival.getId()).returnableQuantity().signum()); + assertEquals(new BigDecimal("0.0005"),returns.availability(arrival.getId()).returnedQuantity()); + receiptService.revokeInRecord(keptChild.getId(),"退回剩余库存验证可退量","rollback-test"); + assertEquals(new BigDecimal("0.0014"),returns.availability(arrival.getId()).returnableQuantity()); + var returnRemaining=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0014"),false,java.time.LocalDate.of(2026,10,14),"全部退回",UUID.randomUUID().toString()); + returns.returnGoods(returnRemaining);returns.returnGoods(returnRemaining); + assertEquals(new BigDecimal("0.0019"),returns.availability(arrival.getId()).returnedQuantity()); + assertEquals(0,returns.availability(arrival.getId()).returnableQuantity().signum()); + assertEquals(3,returns.history(arrival.getId()).size()); ProjectInfo stale = projects.selectProjectInfoById(project.getId(), null); assertEquals(1, projects.updateProjectInfo(stale)); assertEquals(0, projects.updateProjectInfo(stale)); session.rollback(true); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseReturnServiceTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseReturnServiceTest.java new file mode 100644 index 0000000..30e5805 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseReturnServiceTest.java @@ -0,0 +1,146 @@ +package com.ruoyi.projectdev; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.domain.InRecord; +import com.ruoyi.warehouse.domain.PurchaseArrival; +import com.ruoyi.warehouse.domain.PurchaseRequest; +import com.ruoyi.warehouse.mapper.InRecordMapper; +import com.ruoyi.warehouse.mapper.PurchaseArrivalMapper; +import com.ruoyi.warehouse.mapper.PurchaseRequestMapper; +import com.ruoyi.warehouse.service.impl.InventoryCostJournal; +import com.ruoyi.warehouse.service.impl.PurchasePriceService; +import com.ruoyi.warehouse.service.impl.PurchaseReturnService; +import com.ruoyi.web.controller.warehouse.PurchaseReturnController; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +class PurchaseReturnServiceTest { + private final PurchaseReturnService service = new PurchaseReturnService(); + private final JdbcTemplate db = mock(JdbcTemplate.class); + private final InventoryCostJournal journal = mock(InventoryCostJournal.class); + private final PurchaseRequestMapper purchases = mock(PurchaseRequestMapper.class); + private final PurchaseArrivalMapper arrivals = mock(PurchaseArrivalMapper.class); + private final InRecordMapper receipts = mock(InRecordMapper.class); + + @BeforeEach void setup() { + ReflectionTestUtils.setField(service,"db",db); + ReflectionTestUtils.setField(service,"journal",journal); + ReflectionTestUtils.setField(service,"purchases",purchases); + ReflectionTestUtils.setField(service,"arrivals",arrivals); + ReflectionTestUtils.setField(service,"receipts",receipts); + ReflectionTestUtils.setField(service,"prices",mock(PurchasePriceService.class)); + } + + private static BigDecimal n(String value) { return new BigDecimal(value); } + private Map snapshot(String accepted,String returned,String retained,String received) { + var row = new HashMap(); + row.put("acceptance_status",1);row.put("receipt_id",9L);row.put("receipt_root",true); + row.put("accepted_quantity",n(accepted));row.put("returned_quantity",n(returned)); + row.put("retained_quantity",n(retained));row.put("received_quantity",n(received)); + return row; + } + private PurchaseReturnService.Availability read(Map row) { + when(db.queryForList(anyString(),eq(5L))).thenReturn(List.of(row)); + return service.availability(5L); + } + private PurchaseReturnService.Request request(String quantity) { + return new PurchaseReturnService.Request(5L,n(quantity),false,LocalDate.of(2026,10,14),"备注","return-key"); + } + private void lockedFixture(String received) { + var arrival = new PurchaseArrival();arrival.setId(5L);arrival.setPurchaseRequestId(7L); + arrival.setArrivalQuantity(n("10"));arrival.setDefectiveQuantity(n("1"));arrival.setAcceptanceStatus(1); + var purchase = new PurchaseRequest();purchase.setId(7L);purchase.setQuantity(n("10")); + var root = new InRecord();root.setId(9L);root.setReceiptRoot(true);root.setInNum(n("7")); + when(arrivals.selectPurchaseArrivalByIdForUpdate(5L)).thenReturn(arrival); + when(purchases.selectPurchaseRequestByIdForUpdate(7L)).thenReturn(purchase); + when(receipts.selectInRecordByArrivalIdForUpdate(5L)).thenReturn(root); + when(receipts.receivedQuantity(9L)).thenReturn(n(received)); + when(db.queryForObject(anyString(),eq(BigDecimal.class),eq(5L))).thenReturn(n("2")); + } + + @Test void availabilitySubtractsPriorReturnsAndCurrentReceiptsWithoutLocking() { + var result = read(snapshot("9","2","7","4")); + assertTrue(result.supported());assertEquals(n("9"),result.acceptedQuantity()); + assertEquals(n("2"),result.returnedQuantity());assertEquals(n("4"),result.receivedQuantity()); + assertEquals(n("3"),result.returnableQuantity()); + verifyNoInteractions(journal,arrivals,purchases,receipts); + verify(db,times(1)).queryForList(anyString(),eq(5L)); + } + + @Test void fullReceiptAndFullReturnHaveZeroAvailabilityWhileWithdrawalRestoresIt() { + assertEquals(0,read(snapshot("9","2","7","7")).returnableQuantity().signum()); + assertEquals(n("1.2500"),read(snapshot("9","2","7","5.7500")).returnableQuantity()); + assertEquals(0,read(snapshot("9","9","0","0")).returnableQuantity().signum()); + } + + @Test void legacyAndInconsistentSourcesAreExplainedAndNeverAssumedReturnable() { + var legacy=snapshot("9","0","0","0");legacy.put("receipt_id",null);legacy.put("receipt_root",null); + var result=read(legacy);assertFalse(result.supported());assertEquals(0,result.returnableQuantity().signum()); + assertTrue(result.message().contains("历史验收")); + result=read(snapshot("9","2","8","0"));assertFalse(result.supported());assertTrue(result.message().contains("数量不一致")); + assertFalse(read(snapshot("9","2","7","8")).supported()); + } + + @Test void missingUnacceptedAndInvalidIdsFailBeforeAnyMutation() { + when(db.queryForList(anyString(),eq(5L))).thenReturn(List.of()); + assertThrows(ServiceException.class,()->service.availability(5L)); + var row=snapshot("9","0","9","0");row.put("acceptance_status",0); + when(db.queryForList(anyString(),eq(5L))).thenReturn(List.of(row)); + assertThrows(ServiceException.class,()->service.availability(5L)); + assertThrows(ServiceException.class,()->service.availability(null)); + assertThrows(ServiceException.class,()->service.availability(0L)); + verifyNoInteractions(journal,arrivals,purchases,receipts); + } + + @Test void invalidRequestQuantityDateAndRemarkAreRejectedBeforeInventoryLock() { + var invalid=new PurchaseReturnService.Request[]{null,request("0"),request("-1"),request("0.00001"),request("10000000000000000"), + new PurchaseReturnService.Request(null,n("1"),false,null,null,"key"), + new PurchaseReturnService.Request(5L,n("1"),false,LocalDate.of(999,1,1),null,"key"), + new PurchaseReturnService.Request(5L,n("1"),false,null,"x".repeat(501),"key"), + new PurchaseReturnService.Request(5L,n("1"),false,null,null," ")}; + for (var request:invalid) assertThrows(ServiceException.class,()->service.returnGoods(request)); + verifyNoInteractions(db,journal,arrivals,purchases,receipts); + } + + @Test void staleDisplayedMaximumCannotOverrideLockedCurrentAvailability() { + lockedFixture("6"); + var failure=assertThrows(ServiceException.class,()->service.returnGoods(request("3"))); + assertTrue(failure.getMessage().contains("超过待入库")); + verify(journal).lockInventory();verify(receipts).selectInRecordByArrivalIdForUpdate(5L); + assertTrue(mockingDetails(db).getInvocations().stream().noneMatch(i->i.getMethod().getName().equals("update"))); + } + + @Test void identicalLostResponseRetrySucceedsEvenWhenNothingRemainsButChangedPayloadFails() { + lockedFixture("7"); + var prior=Map.of("arrival_id",5L,"quantity",n("3"),"cancel_purchase",false, + "business_date",java.sql.Date.valueOf("2026-10-14"),"remark","备注"); + when(db.queryForList("select * from purchase_return where business_key=?","return-key")).thenReturn(List.of(prior)); + assertDoesNotThrow(()->service.returnGoods(request("3"))); + assertThrows(ServiceException.class,()->service.returnGoods(request("2"))); + assertThrows(ServiceException.class,()->service.returnGoods(new PurchaseReturnService.Request(5L,n("3"),false,LocalDate.of(2026,10,15),"备注","return-key"))); + verifyNoInteractions(receipts); + assertTrue(mockingDetails(db).getInvocations().stream().noneMatch(i->i.getMethod().getName().equals("update"))); + } + + @Test void availabilityHttpContractKeepsNumericFieldsAndAvailabilityBoolean() throws Exception { + read(snapshot("9","2","7","4")); + var controller=new PurchaseReturnController();ReflectionTestUtils.setField(controller,"service",service); + var mvc=org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(controller).build(); + mvc.perform(get("/warehouse/purchase/returns/5/availability")) + .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200)) + .andExpect(jsonPath("$.data.arrivalId").value(5)).andExpect(jsonPath("$.data.acceptedQuantity").value(9)) + .andExpect(jsonPath("$.data.returnedQuantity").value(2)).andExpect(jsonPath("$.data.receivedQuantity").value(4)) + .andExpect(jsonPath("$.data.returnableQuantity").value(3)).andExpect(jsonPath("$.data.supported").value(true)); + } +} 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 df2e0f7..90d8705 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,37 @@ 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 batchCombinedFiltersKeepWholeBatchTotalsAndDateBoundaries() 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.service.save(f.draft()); + var filter=new PurchaseBatch(); + filter.setKeyword(saved.getBatch().getBatchNo()); + filter.setSupplierId(saved.getBatch().getSupplierId()); + filter.setProjectId(saved.getRows().get(0).getProjectId()); + filter.setMaterialName(f.name); + filter.setBeginDate(saved.getBatch().getBusinessDate()); + filter.setEndDate(saved.getBatch().getBusinessDate()); + filter.setProgress("confirm"); + var result=f.batchMapper.selectPurchaseBatchList(filter); + assertEquals(1,result.size()); + assertEquals(saved.getBatch().getId(),result.get(0).getId()); + assertEquals(2,result.get(0).getRequestCount(),"Filtering by one project must not remove other projects from batch totals"); + assertEquals(0,new BigDecimal("5.00").compareTo(result.get(0).getTotalAmount())); + filter.setBeginDate(saved.getBatch().getBusinessDate().plusDays(1)); + assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty()); + filter.setBeginDate(null);filter.setEndDate(saved.getBatch().getBusinessDate().minusDays(1)); + assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty()); + }); + assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); + } + } + @Test void mixedProjectSaveDedupQuotesAndLockingAreAtomic() throws Exception { Fixture f = new Fixture(); try (var security = mockStatic(SecurityUtils.class)) { @@ -187,6 +218,31 @@ class PurchaseSheetDatabaseTest { } } + @Test void unbatchedSaveEditDeleteAndGroupingPreserveAtomicity() 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).execute(status->{try{ + long batchCount=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class); + var draft=f.draft();draft.setUnbatched(true);draft.getBatch().setSupplierId(null);draft.getRows().forEach(r->r.setFinalUnitPrice(null)); + var saved=f.service.save(draft);assertTrue(saved.isUnbatched());assertNull(saved.getBatch().getId());assertEquals(batchCount,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); + assertTrue(saved.getRows().stream().allMatch(r->r.getPurchaseBatchId()==null&&!Boolean.TRUE.equals(r.getPriceLocked()))); + var ids=saved.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new); + var stale=f.service.loadUnbatched(ids);saved.getRows().get(0).setQuantity(new BigDecimal("7"));f.service.save(saved); + stale.getRows().get(0).setQuantity(BigDecimal.TEN);assertThrows(ServiceException.class,()->f.service.save(stale)); + var batch=f.service.prepare(new Long[]{ids[0]},null);assertNotNull(batch.getBatch().getId());assertEquals(1,batch.getRows().size()); + assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[0]},batch.getBatch().getId())); + f.jdbc.update("update purchase_batch set purchase_status=2 where id=?",batch.getBatch().getId()); + assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId())); + assertNull(f.service.loadUnbatched(new Long[]{ids[1]}).getRows().get(0).getPurchaseBatchId()); + f.jdbc.update("update purchase_batch set purchase_status=1 where id=?",batch.getBatch().getId()); + assertEquals(2,f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId()).getRows().size()); + assertEquals(batchCount+1,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); + var more=new PurchaseSheet();more.setUnbatched(true);more.setBatch(new PurchaseBatch());more.setRows(draft.getRows());more.getRows().forEach(r->{r.setId(null);r.setPurchaseBatchId(null);});var deletion=f.service.save(more);var deleted=deletion.getRows().stream().map(PurchaseRequest::getId).toList();deletion.setDeletedIds(deleted);deletion.setRows(List.of());assertTrue(f.service.save(deletion).getRows().isEmpty()); + }finally{status.setRollbackOnly();}return null;}); + } + } + private static class Fixture { final String name="SHEET-CHECK-"+UUID.randomUUID(); final JdbcTemplate jdbc; @@ -228,6 +284,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); 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); } diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java index 6fd65f2..d35d754 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java @@ -22,8 +22,11 @@ class WebNavigationDatabaseTest { var mapper=mock(SysMenuMapper.class);when(mapper.selectMenuTreeAll()).thenReturn(menus);var service=new SysMenuServiceImpl();ReflectionTestUtils.setField(service,"menuMapper",mapper); var routes=service.buildMenus(service.selectMenuTreeByUserId(1L));var pages=new HashMap();var names=new HashSet();walk(routes,"",pages,names); var expected=Map.ofEntries(Map.entry("/project/info","project/info/index"),Map.entry("/procurement/details","warehouse/purchase/index"),Map.entry("/procurement/arrival","warehouse/arrival/index"),Map.entry("/warehouse/pending","warehouse/pending/index"),Map.entry("/warehouse/stock","warehouse/stock/index"),Map.entry("/warehouse/loans","warehouse/loans/index"),Map.entry("/production/tasks","production/tasks/index"),Map.entry("/production/operations","production/operations/index"),Map.entry("/costManagement/products","production/cost/index"),Map.entry("/businessBasics/product","warehouse/product/index"),Map.entry("/businessBasics/products","production/product/index"),Map.entry("/businessBasics/bom","production/bom/index"),Map.entry("/businessBasics/suppliers","warehouse/suppliers/index"),Map.entry("/businessBasics/area","warehouse/area/index"),Map.entry("/system/dict","system/businessDictionaries/index"),Map.entry("/system/initialization","system/initialization/index"),Map.entry("/system/operlog","monitor/operlog/index")); - Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-ui")))root=root.getParent(); - for(var e:expected.entrySet()){assertEquals(e.getValue(),pages.get(e.getKey()),e.getKey());assertTrue(Files.exists(root.resolve("ruoyi-ui/src/views/"+e.getValue()+".vue")),e.getValue());} + Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-ui-vue3")))root=root.getParent(); + for(var e:expected.entrySet()){assertEquals(e.getValue(),pages.get(e.getKey()),e.getKey());assertTrue(Files.exists(root.resolve("ruoyi-ui-vue3/src/views/"+e.getValue()+".vue")),e.getValue());} + assertEquals("project/manage/index",pages.get("/project/collaboration"),"Independently maintained collaboration entry must remain"); + assertTrue(Files.exists(root.resolve("ruoyi-ui-vue3/src/views/project/manage/index.vue"))); + try(var rows=statement.executeQuery("select count(*) from sys_menu where menu_id=2600 and parent_id=2100 and path='collaboration' and component='project/manage/index' and perms='project:manage:read'")){rows.next();assertEquals(1,rows.getInt(1));} assertEquals("项目管理",routes.get(0).getMeta().getTitle()); try(var rows=statement.executeQuery("select group_concat(menu_name order by order_num separator ',') from sys_menu where parent_id=0 and status='0' and visible='0'")){rows.next();assertEquals("项目管理,采购管理,库存管理,生产管理,材料成本,基础资料,系统管理",rows.getString(1));} try(var rows=statement.executeQuery("select count(*) from sys_menu where parent_id=0 and path in ('monitor','tool') and visible='1'")){rows.next();assertEquals(2,rows.getInt(1));} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/project/ProjectLoanExportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/project/ProjectLoanExportTest.java new file mode 100644 index 0000000..a795a23 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/project/ProjectLoanExportTest.java @@ -0,0 +1,40 @@ +package com.ruoyi.web.controller.project; + +import java.util.List; +import com.ruoyi.project.service.ProjectLoanService; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class ProjectLoanExportTest { + @Test + void exportUsesTheSameProjectItemAndOutstandingFiltersAsTheList() throws Exception { + var service = mock(ProjectLoanService.class); + var controller = new ProjectLoanController(); + ReflectionTestUtils.setField(controller, "service", service); + when(service.list(7L, 9L, true)).thenReturn(List.of()); + + var response = new MockHttpServletResponse(); + controller.export(response, 7L, 9L, true); + + verify(service).list(7L, 9L, true); + verifyNoMoreInteractions(service); + assertTrue(response.getContentAsByteArray().length > 0); + } + + @Test + void exportCanStillIncludeSettledLoansWhenOutstandingFilterIsOff() throws Exception { + var service = mock(ProjectLoanService.class); + var controller = new ProjectLoanController(); + ReflectionTestUtils.setField(controller, "service", service); + when(service.list(null, null, false)).thenReturn(List.of()); + + controller.export(new MockHttpServletResponse(), null, null, false); + + verify(service).list(null, null, false); + verifyNoMoreInteractions(service); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictData.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictData.java index 6b035a6..96db365 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictData.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictData.java @@ -22,6 +22,11 @@ public class SysDictData extends BaseEntity @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) private Long dictCode; + /** 物品小类所属大类;其他字典保持为空。 */ + private Long parentCode; + public Long getParentCode() { return parentCode; } + public void setParentCode(Long parentCode) { this.parentCode = parentCode; } + /** 字典排序 */ @Excel(name = "字典排序", cellType = ColumnType.NUMERIC) private Long dictSort; diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java index aa763f8..d74bd39 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/controller/GenController.java @@ -98,13 +98,11 @@ public class GenController extends BaseController */ @PreAuthorize("@ss.hasPermi('tool:gen:list')") @GetMapping(value = "/column/{tableId}") - public TableDataInfo columnList(Long tableId) + public TableDataInfo columnList(@PathVariable Long tableId) { - TableDataInfo dataInfo = new TableDataInfo(); + genTableService.selectGenTableById(tableId); List list = genTableColumnService.selectGenTableColumnListByTableId(tableId); - dataInfo.setRows(list); - dataInfo.setTotal(list.size()); - return dataInfo; + return getDataTable(list); } /** @@ -261,4 +259,4 @@ public class GenController extends BaseController response.setContentType("application/octet-stream; charset=UTF-8"); IOUtils.write(data, response.getOutputStream()); } -} \ No newline at end of file +} diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java index e851487..98436a5 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java @@ -63,7 +63,7 @@ public class GenTableServiceImpl implements IGenTableService @Override public GenTable selectGenTableById(Long id) { - GenTable genTable = genTableMapper.selectGenTableById(id); + GenTable genTable = requireTable(genTableMapper.selectGenTableById(id)); setTableFromOptions(genTable); return genTable; } @@ -209,7 +209,7 @@ public class GenTableServiceImpl implements IGenTableService { Map dataMap = new LinkedHashMap<>(); // 查询表信息 - GenTable table = genTableMapper.selectGenTableById(tableId); + GenTable table = requireTable(genTableMapper.selectGenTableById(tableId)); // 设置主子表信息 setSubTable(table); // 设置主键列信息 @@ -252,7 +252,7 @@ public class GenTableServiceImpl implements IGenTableService public void generatorCode(String tableName) { // 查询表信息 - GenTable table = genTableMapper.selectGenTableByName(tableName); + GenTable table = requireTable(genTableMapper.selectGenTableByName(tableName)); // 设置主子表信息 setSubTable(table); // 设置主键列信息 @@ -294,7 +294,7 @@ public class GenTableServiceImpl implements IGenTableService @Transactional public void synchDb(String tableName) { - GenTable table = genTableMapper.selectGenTableByName(tableName); + GenTable table = requireTable(genTableMapper.selectGenTableByName(tableName)); List tableColumns = table.getColumns(); Map tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity())); @@ -370,7 +370,7 @@ public class GenTableServiceImpl implements IGenTableService private void generatorCode(String tableName, ZipOutputStream zip, Map typeFiles) { // 查询表信息 - GenTable table = genTableMapper.selectGenTableByName(tableName); + GenTable table = requireTable(genTableMapper.selectGenTableByName(tableName)); // 设置主子表信息 setSubTable(table); // 设置主键列信息 @@ -409,9 +409,15 @@ public class GenTableServiceImpl implements IGenTableService } } + private static GenTable requireTable(GenTable table) + { + if (table == null) throw new ServiceException("生成配置不存在或已删除,请返回列表刷新"); + return table; + } + /** * 将字符串内容写入ZIP输出流 - * + * * @param zip ZIP输出流 * @param fileName ZIP条目名称(即文件名) * @param content 要写入的内容 @@ -561,4 +567,4 @@ public class GenTableServiceImpl implements IGenTableService } return genPath + File.separator + VelocityUtils.getFileName(template, table); } -} \ No newline at end of file +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionCostView.java b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionCostView.java new file mode 100644 index 0000000..52e419f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionCostView.java @@ -0,0 +1,51 @@ +package com.ruoyi.production.service; + +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Read-only cost presentation. Missing material records must never look like a free product. */ +public final class ProductionCostView { + private ProductionCostView() {} + + public static Map of(Map source) { + var row = new LinkedHashMap(source); + String state; + if (!"SETTLED".equals(row.get("status"))) state = "UNSETTLED"; + else if (isUnrecorded(row.get("material_recorded"))) state = "PENDING_MATERIAL"; + else if (row.get("material_cost") == null) state = "UNKNOWN"; + else state = "KNOWN"; + + if ("UNSETTLED".equals(state) || "PENDING_MATERIAL".equals(state)) { + row.put("material_cost", null); + row.put("unit_cost", null); + } + String unitState = state; + if ("KNOWN".equals(state)) { + Object good = row.get("good_quantity"); + if (good != null && new BigDecimal(good.toString()).signum() <= 0) { + row.put("unit_cost", null); + unitState = "NO_OUTPUT"; + } else if (row.get("unit_cost") == null) unitState = "UNKNOWN"; + } else if ("UNKNOWN".equals(state)) row.put("unit_cost", null); + row.put("cost_status", state); + row.put("cost_status_text", label(state)); + row.put("unit_cost_status", unitState); + row.put("unit_cost_status_text", label(unitState)); + return row; + } + + private static boolean isUnrecorded(Object value) { + return Boolean.FALSE.equals(value) || value instanceof Number n && n.intValue() == 0; + } + + private static String label(String state) { + return switch (state) { + case "UNSETTLED" -> "未结算"; + case "PENDING_MATERIAL" -> "用料待核对"; + case "UNKNOWN" -> "成本未知"; + case "NO_OUTPUT" -> "无合格产出"; + default -> "已核算"; + }; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java index a2a28f7..6e40504 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java @@ -32,7 +32,17 @@ public class ProductionService { private static final String TASK_SELECT="select t.*,case when t.status='OPEN' and not exists(select 1 from production_action x where x.task_id=t.id) and not exists(select 1 from production_task x where x.parent_task_id=t.id) and not exists(select 1 from purchase_request x where x.production_task_id=t.id) and not exists(select 1 from in_record x where x.production_task_id=t.id) and not exists(select 1 from production_settlement x where x.task_id=t.id) then 1 else 0 end editable_identity,p.project_name,i.product_name item_name,i.product_code,i.brand,i.spec,i.unit,b.version_tag,case when not exists(select 1 from bom_line bl where bl.bom_id=t.bom_id and bl.del_flag='0') or exists(select 1 from production_action pa where pa.task_id=t.id and pa.active=1 and pa.kind='ISSUE') then 1 else 0 end material_recorded,coalesce((select sum(quantity) from production_action where task_id=t.id and active=1 and kind='COMPLETE'),0) good_quantity,coalesce((select sum(quantity) from production_action where task_id=t.id and active=1 and kind='SCRAP_ASSEMBLY'),0) scrap_quantity from production_task t join project_info p on p.id=t.project_id join product_info i on i.id=t.item_id left join bom_version b on b.id=t.bom_id"; private static final String ACTION_SELECT="select a.*,p.project_name,i.product_name item_name,i.brand,i.spec,i.unit,w.area_name,e.original_cost,e.effective_cost,t.task_no,coalesce((select sum(r.quantity) from production_action r where r.source_id=a.id and r.active=1 and r.kind in ('RETURN','DELIVERY_RETURN','SCRAP_ISSUED')),0) handled_quantity from production_action a join project_info p on p.id=a.project_id join product_info i on i.id=a.item_id left join warehouse_area w on w.id=a.area_id left join inventory_cost_event e on e.id=a.cost_event_id left join production_task t on t.id=a.task_id"; - public List> tasks(Long projectId,Long itemId){return db.queryForList(TASK_SELECT+" where t.status<>'CANCELLED' and (? is null or t.project_id=?) and (? is null or t.item_id=?) order by t.id desc",projectId,projectId,itemId,itemId);} + public List> tasks(Long projectId,Long itemId){return costViews(db.queryForList(TASK_SELECT+" where t.status<>'CANCELLED' and (? is null or t.project_id=?) and (? is null or t.item_id=?) order by t.id desc",projectId,projectId,itemId,itemId));} + private List> costViews(List> rows){return rows.stream().map(ProductionCostView::of).toList();} + private List> settlementCostViews(List> rows){ + return rows.stream().map(source->{ + var row=new LinkedHashMap(source);BigDecimal stored=nullable(source,"material_cost"); + // A nonzero historical amount is evidence of recorded material even if second-resolution + // action timestamps cannot distinguish settlement from a withdrawal in the same second. + if(stored!=null&&stored.signum()!=0)row.put("material_recorded",1); + return ProductionCostView.of(row); + }).toList(); + } public List> costHistory(Long itemId,Long bomId,Long projectId){ var result=new ArrayList>(); for(var row:tasks(projectId,itemId)){ @@ -44,17 +54,27 @@ public class ProductionService { } public Map task(Long id){var rows=db.queryForList(TASK_SELECT+" where t.id=?",id);if(rows.isEmpty())throw fail("生产任务不存在");projects.requireProjectAccess(l(rows.get(0),"project_id"));return rows.get(0);} public List> actions(Long projectId,Long taskId){return db.queryForList(ACTION_SELECT+" where (? is null or a.project_id=?) and (? is null or a.task_id=?) order by a.id desc",projectId,projectId,taskId,taskId);} - public Map actionPage(Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate,int page,int size){ + private record QueryFilter(String sql,List args) {} + private QueryFilter actionFilter(Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate){ var where=new StringBuilder(" where 1=1");var args=new ArrayList(); if(projectId!=null){where.append(" and a.project_id=?");args.add(projectId);}if(taskId!=null){where.append(" and a.task_id=?");args.add(taskId);} if(kind!=null&&!kind.isBlank()){where.append(" and a.kind=?");args.add(kind);}if(active!=null){where.append(" and a.active=?");args.add(active);} - if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,i.product_name,i.brand,i.spec,p.project_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword+"%");} - if(beginDate!=null&&!beginDate.isBlank()){where.append(" and a.business_date>=?");args.add(java.time.LocalDate.parse(beginDate));}if(endDate!=null&&!endDate.isBlank()){where.append(" and a.business_date<=?");args.add(java.time.LocalDate.parse(endDate));} - String sql=ACTION_SELECT+where;long total=db.queryForObject("select count(*) from ("+sql+") counted",Long.class,args.toArray());size=Math.max(1,Math.min(100,size));args.add(size);args.add((Math.max(1,page)-1)*size); + if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,i.product_name,i.brand,i.spec,p.project_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword.trim()+"%");} + if(beginDate!=null&&!beginDate.isBlank()){where.append(" and a.business_date>=?");args.add(LocalDate.parse(beginDate));}if(endDate!=null&&!endDate.isBlank()){where.append(" and a.business_date<=?");args.add(LocalDate.parse(endDate));} + return new QueryFilter(where.toString(),args); + } + public List> filteredActions(Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate){ + var filter=actionFilter(projectId,taskId,kind,active,keyword,beginDate,endDate); + return db.queryForList(ACTION_SELECT+filter.sql()+" order by a.id desc",filter.args().toArray()); + } + public Map actionPage(Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate,int page,int size){ + var filter=actionFilter(projectId,taskId,kind,active,keyword,beginDate,endDate); + String sql=ACTION_SELECT+filter.sql();var args=new ArrayList(filter.args()); + long total=db.queryForObject("select count(*) from ("+sql+") counted",Long.class,args.toArray());size=Math.max(1,Math.min(100,size));args.add(size);args.add((long)(Math.max(1,page)-1)*size); return Map.of("rows",db.queryForList(sql+" order by a.id desc limit ? offset ?",args.toArray()),"total",total); } private Map action(Long id){var rows=db.queryForList(ACTION_SELECT+" where a.id=?",id);if(rows.isEmpty())throw fail("业务记录不存在");return rows.get(0);} - public Map detail(Long id){var result=new LinkedHashMap<>(task(id));result.put("children",db.queryForList(TASK_SELECT+" where t.parent_task_id=? order by t.id",id));result.put("openChildCount",db.queryForObject("select count(*) from production_task where parent_task_id=? and status='OPEN'",Long.class,id));result.put("pendingReceiptCount",db.queryForObject("select count(*) from in_record where production_task_id=? and in_status=0",Long.class,id));result.put("current_material_cost",material(id,null));result.put("actions",actions(null,id));result.put("needs",needs(id));result.put("settlements",db.queryForList("select * from production_settlement where task_id=? order by version desc",id));return result;} + public Map detail(Long id){var result=ProductionCostView.of(task(id));result.put("children",costViews(db.queryForList(TASK_SELECT+" where t.parent_task_id=? order by t.id",id)));result.put("openChildCount",db.queryForObject("select count(*) from production_task where parent_task_id=? and status='OPEN'",Long.class,id));result.put("pendingReceiptCount",db.queryForObject("select count(*) from in_record where production_task_id=? and in_status=0",Long.class,id));result.put("current_material_cost",material(id,null));result.put("actions",actions(null,id));result.put("needs",needs(id));result.put("settlements",settlementCostViews(db.queryForList("select s.*,'SETTLED' status,case when not exists(select 1 from bom_line bl where bl.bom_id=t.bom_id and bl.del_flag='0') or exists(select 1 from production_action a where a.task_id=s.task_id and a.kind='ISSUE' and a.create_times.create_time)) then 1 else 0 end material_recorded from production_settlement s join production_task t on t.id=s.task_id where s.task_id=? order by s.version desc",id)));return result;} @Transactional public Map save(ProductionCommand c){ journal.lockInventory();quantity(c.quantity);text(c.remark,500);LocalDate date=c.date==null?LocalDate.now():c.date; @@ -74,16 +94,42 @@ public class ProductionService { var snapshot=boms.snapshotForTask(c.bomId,c.projectId,id);db.update("update production_task set bom_id=? where id=?",snapshot.getId(),id);return task(id); } @Transactional public void remove(Long id,Integer version){journal.lockInventory();var t=task(id);checkTaskVersion(t,version);if(!Long.valueOf(1).equals(l(t,"editable_identity")))throw fail("任务已有业务,不能删除,请先按流程撤回");db.update("update production_task set status='CANCELLED',version=version+1 where id=?",id);} - public Map page(Long projectId,Long itemId,String status,String keyword,int page,int size) { - size=Math.max(1,Math.min(100,size));page=Math.max(1,page); - StringBuilder where=new StringBuilder(" where t.status<>'CANCELLED'");var args=new ArrayList(); + private QueryFilter taskFilter(Long projectId,Long itemId,String status,String keyword,String operation){ + var where=new StringBuilder(" where t.status<>'CANCELLED'");var args=new ArrayList(); if(projectId!=null){where.append(" and t.project_id=?");args.add(projectId);} if(itemId!=null){where.append(" and t.item_id=?");args.add(itemId);} if("READY".equals(status)){where.append(" and t.status='OPEN' and t.planned_quantity>0 and t.planned_quantity<=coalesce((select sum(a.quantity) from production_action a where a.task_id=t.id and a.active=1 and a.kind in ('COMPLETE','SCRAP_ASSEMBLY')),0) and not exists(select 1 from production_task c where c.parent_task_id=t.id and c.status='OPEN')");}else if(status!=null&&!status.isBlank()){where.append(" and t.status=?");args.add(status);} - if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,i.product_name,i.brand,i.spec,p.project_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword+"%");} - Long total=db.queryForObject("select count(*) from ("+TASK_SELECT+where+") counted",Long.class,args.toArray()); - var values=new ArrayList(args);values.add(size);values.add((long)(page-1)*size); - return Map.of("rows",db.queryForList(TASK_SELECT+where+" order by t.id desc limit ? offset ?",values.toArray()),"total",total); + if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,i.product_name,i.brand,i.spec,p.project_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword.trim()+"%");} + if("SCRAP_ASSEMBLY".equals(operation))where.append(" and t.status='OPEN' and t.planned_quantity>coalesce((select sum(a.quantity) from production_action a where a.task_id=t.id and a.active=1 and a.kind in ('COMPLETE','SCRAP_ASSEMBLY')),0)"); + else if("SCRAP_ISSUED".equals(operation))where.append(" and exists(select 1 from production_action x where x.task_id=t.id and x.kind='ISSUE' and x.active=1 and x.quantity>coalesce((select sum(r.quantity) from production_action r where r.source_id=x.id and r.active=1 and r.kind in ('RETURN','SCRAP_ISSUED')),0))"); + else if(operation!=null&&!operation.isBlank())throw fail("不支持的任务选择操作"); + return new QueryFilter(where.toString(),args); + } + public List> filteredTasks(Long projectId,Long itemId,String status,String keyword){ + var filter=taskFilter(projectId,itemId,status,keyword,null); + return costViews(db.queryForList(TASK_SELECT+filter.sql()+" order by t.id desc",filter.args().toArray())); + } + public Map page(Long projectId,Long itemId,String status,String keyword,int page,int size) { + return operationPage(projectId,itemId,status,keyword,null,page,size); + } + public Map operationPage(Long projectId,Long itemId,String status,String keyword,String operation,int page,int size) { + size=Math.max(1,Math.min(100,size));page=Math.max(1,page); + var filter=taskFilter(projectId,itemId,status,keyword,operation); + Long total=db.queryForObject("select count(*) from ("+TASK_SELECT+filter.sql()+") counted",Long.class,filter.args().toArray()); + var values=new ArrayList(filter.args());values.add(size);values.add((long)(page-1)*size); + return Map.of("rows",costViews(db.queryForList(TASK_SELECT+filter.sql()+" order by t.id desc limit ? offset ?",values.toArray())),"total",total); + } + /** Read-only aggregation: amounts use the identical per-area rounding as stock list. */ + public Map projectSummary(Long projectId){ + projects.requireProjectAccess(projectId); + var inventory=db.queryForMap("select coalesce(sum(round(c.amount*s.quantity/nullif(c.quantity,0),6)),0) amount,coalesce(sum(case when c.amount is null or c.quantity=0 then 1 else 0 end),0) unknown from project_stock_balance s left join project_item_cost c on c.project_id=s.project_id and c.item_id=s.item_id where s.project_id=? and s.quantity>0",projectId); + var losses=db.queryForList("select a.kind,coalesce(sum(e.effective_cost),0) amount,sum(case when e.effective_cost is null then 1 else 0 end) unknown from production_action a left join inventory_cost_event e on e.id=a.cost_event_id where a.project_id=? and a.active=1 and a.kind in ('SCRAP_STOCK','SCRAP_FINISHED') group by a.kind",projectId); + return Map.of("inventory",inventory,"losses",losses); + } + /** Counts only; retains the permissions of the former task/action reads. */ + public List> productTotals(Long projectId){ + projects.requireProjectAccess(projectId); + return db.queryForList("select i.id itemId,coalesce(t.planned,0) planned,coalesce(a.good,0) good,coalesce(a.delivered,0) delivered from product_info i left join (select item_id,sum(planned_quantity) planned from production_task where project_id=? and status<>'CANCELLED' group by item_id)t on t.item_id=i.id left join (select item_id,sum(case when kind='COMPLETE' then quantity else 0 end) good,sum(case when kind='DELIVERY' then quantity when kind='DELIVERY_RETURN' then -quantity else 0 end) delivered from production_action where project_id=? and active=1 group by item_id)a on a.item_id=i.id where t.item_id is not null or a.item_id is not null",projectId,projectId); } public List> needs(Long id) { var t=task(id);List> rows=new ArrayList<>(); @@ -94,12 +140,19 @@ public class ProductionService { for(var r:db.queryForList(purchaseSql,id))purchases.put(l(r,"product_id"),r); var selfMade=new HashMap();for(var child:db.queryForList("select t.item_id,sum(greatest(case when t.status=\'OPEN\' then t.planned_quantity else coalesce(a.good,0) end-coalesce(a.scrap,0)*(t.status=\'OPEN\')-coalesce(a.received,0),0)) quantity from production_task t left join(select task_id,sum(case when kind=\'COMPLETE\' then quantity else 0 end) good,sum(case when kind=\'SCRAP_ASSEMBLY\' then quantity else 0 end) scrap,sum(case when kind=\'OUTPUT\' then quantity else 0 end) received from production_action where active=1 group by task_id)a on a.task_id=t.id where t.parent_task_id=? and t.status<>\'CANCELLED\' group by t.item_id",id))selfMade.put(l(child,"item_id"),n(child,"quantity")); var stocks=new HashMap();for(var r:db.queryForList("select item_id,sum(quantity) quantity from project_stock_balance where project_id=? group by item_id",l(t,"project_id")))stocks.put(l(r,"item_id"),n(r,"quantity")); - for(var line:boms.get(l(t,"bom_id")).getLines()) { + // BOMs may repeat an item in different positions. Inventory and business coverage are + // recorded per item, so combine the demand first and consume each coverage amount once. + Map> groupedLines=new LinkedHashMap<>(); + for(var line:boms.get(l(t,"bom_id")).getLines())groupedLines.computeIfAbsent(line.getItemId(),key->new ArrayList<>()).add(line); + for(var lines:groupedLines.values()) { + var line=lines.get(0);var childChoices=new LinkedHashMap>(); + for(var source:lines)if(source.getChildBomId()!=null)childChoices.putIfAbsent(source.getChildBomId(),Map.of("id",source.getChildBomId(),"versionTag",Objects.toString(source.getChildVersionTag(),"任务下级BOM"))); + var childBoms=new ArrayList<>(childChoices.keySet()); var a=actions.getOrDefault(line.getItemId(),Map.of());var buy=purchases.getOrDefault(line.getItemId(),Map.of()); - BigDecimal needed=line.getUnitQuantity().multiply(n(t,"planned_quantity")).setScale(4,RoundingMode.HALF_UP),issued=n(a,"issued"),returned=n(a,"returned"),scrap=n(a,"scrapped"),available=stocks.getOrDefault(line.getItemId(),ZERO); + BigDecimal needed=lines.stream().map(value->value.getUnitQuantity().multiply(n(t,"planned_quantity")).setScale(4,RoundingMode.HALF_UP)).reduce(ZERO,BigDecimal::add),issued=n(a,"issued"),returned=n(a,"returned"),scrap=n(a,"scrapped"),available=stocks.getOrDefault(line.getItemId(),ZERO); BigDecimal outstanding=needed.subtract(issued).add(returned).add(scrap).max(ZERO); var row=new LinkedHashMap();row.put("taskId",id);row.put("taskNo",t.get("task_no"));row.put("projectId",t.get("project_id"));row.put("projectName",t.get("project_name")); - row.put("itemId",line.getItemId());row.put("itemName",line.getItemName());row.put("brand",line.getBrand());row.put("spec",line.getSpec());row.put("unit",line.getUnit());row.put("childBomId",line.getChildBomId());row.put("required",needed);row.put("issued",issued);row.put("returned",returned);row.put("scrapped",scrap);row.put("available",available);row.put("outstanding",outstanding); + row.put("itemId",line.getItemId());row.put("itemName",line.getItemName());row.put("brand",line.getBrand());row.put("spec",line.getSpec());row.put("unit",line.getUnit());row.put("childBomId",childBoms.size()==1?childBoms.get(0):null);row.put("childBomIds",childBoms);row.put("childBomOptions",new ArrayList<>(childChoices.values()));row.put("required",needed);row.put("issued",issued);row.put("returned",returned);row.put("scrapped",scrap);row.put("available",available);row.put("outstanding",outstanding); row.put("requested",n(buy,"requested"));row.put("purchasing",n(buy,"purchasing"));row.put("pendingAcceptance",n(buy,"pending_acceptance"));row.put("pendingReceipt",n(buy,"pending_receipt")); BigDecimal making=selfMade.getOrDefault(line.getItemId(),ZERO);row.put("selfMade",making); BigDecimal coverage=making.add(n(buy,"requested")).add(n(buy,"purchasing")).add(n(buy,"pending_acceptance")).add(n(buy,"pending_receipt")); @@ -114,7 +167,7 @@ public class ProductionService { var t=task(id);if(!"OPEN".equals(t.get("status")))throw fail("已结算任务请先恢复生产"); for(var row:needs(id)) { String key=row.get("projectId")+":"+row.get("itemId");BigDecimal stock=stockRemaining.computeIfAbsent(key,k->n(row,"available")); - BigDecimal covered=n(row,"requested").add(n(row,"purchasing")).add(n(row,"pendingAcceptance")).add(n(row,"pendingReceipt")); + BigDecimal covered=n(row,"selfMade").add(n(row,"requested")).add(n(row,"purchasing")).add(n(row,"pendingAcceptance")).add(n(row,"pendingReceipt")); BigDecimal net=n(row,"outstanding").subtract(covered).max(ZERO),assigned=net.min(stock); stockRemaining.put(key,stock.subtract(assigned));row.put("allocatedStock",assigned);row.put("purchaseSuggestion",net.subtract(assigned)); var item=items.selectProductInfoById(l(row,"itemId"));row.put("category",item==null?null:item.getCategory());row.put("productCode",item==null?null:item.getProductCode()); @@ -138,6 +191,7 @@ public class ProductionService { if(Set.of("SCRAP_STOCK","SCRAP_FINISHED","DELIVERY","DELIVERY_RETURN").contains(c.kind)&&t!=null)throw fail("库存报废及交付不直接分摊到生产任务"); projects.requireProjectAccess(c.projectId);if(c.itemId==null||items.selectProductInfoById(c.itemId)==null)throw fail("请选择物品"); var dup=db.queryForList("select * from production_action where business_key=?",c.key);if(!dup.isEmpty()){var d=dup.get(0);if(!active(d)||!Objects.equals(c.kind,d.get("kind"))||!Objects.equals(c.projectId,l(d,"project_id"))||!Objects.equals(c.taskId,l(d,"task_id"))||!Objects.equals(c.itemId,l(d,"item_id"))||!Objects.equals(c.areaId,l(d,"area_id"))||!Objects.equals(c.sourceId,l(d,"source_id"))||c.quantity.compareTo(n(d,"quantity"))!=0)throw fail("重复操作内容不一致或已撤销");return action(l(d,"id"));} + if(t!=null&&Set.of("COMPLETE","SCRAP_ASSEMBLY").contains(c.kind))checkTaskVersion(t,c.version); if(t!=null&&"CANCELLED".equals(t.get("status")))throw fail("任务已删除,不能新增业务"); if(t!=null&&"SETTLED".equals(t.get("status"))&&Set.of("ISSUE","COMPLETE","SCRAP_ASSEMBLY").contains(c.kind))throw fail("任务已结算,不能再新增领料、完工或组装报废"); if("ISSUE".equals(c.kind)&&boms.get(l(t,"bom_id")).getLines().stream().noneMatch(line->Objects.equals(line.getItemId(),c.itemId)))throw fail("所选物品不在该任务的BOM用料中"); 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 fced569..00d34fe 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 @@ -18,6 +18,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService { @Autowired private SysDictDataMapper dictDataMapper; + @Autowired private com.ruoyi.warehouse.service.impl.ItemCategoryService itemCategories; /** * 根据条件分页查询字典数据 @@ -62,8 +63,10 @@ public class SysDictDataServiceImpl implements ISysDictDataService * @param dictCodes 需要删除的字典数据ID */ @Override + @org.springframework.transaction.annotation.Transactional public void deleteDictDataByIds(Long[] dictCodes) { + for (Long code : dictCodes) itemCategories.validateDelete(selectDictDataById(code)); for (Long dictCode : dictCodes) { SysDictData data = selectDictDataById(dictCode); @@ -80,8 +83,10 @@ public class SysDictDataServiceImpl implements ISysDictDataService * @return 结果 */ @Override + @org.springframework.transaction.annotation.Transactional public int insertDictData(SysDictData data) { + itemCategories.validate(data, null); int row = dictDataMapper.insertDictData(data); if (row > 0) { @@ -98,8 +103,10 @@ public class SysDictDataServiceImpl implements ISysDictDataService * @return 结果 */ @Override + @org.springframework.transaction.annotation.Transactional public int updateDictData(SysDictData data) { + itemCategories.validate(data, selectDictDataById(data.getDictCode())); int row = dictDataMapper.updateDictData(data); if (row > 0) { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java index f51ec5b..dd85b78 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java @@ -23,6 +23,15 @@ public class ProductInfo extends BaseEntity @Excel(name = "类别") private String category; + /** 查询大类(0代表未分组),不是物品的独立录入字段。 */ + private Long categoryGroupId; + @Excel(name="物品大类", type=Excel.Type.EXPORT) + private String categoryGroupName; + public Long getCategoryGroupId() { return categoryGroupId; } + public void setCategoryGroupId(Long value) { categoryGroupId = value; } + public String getCategoryGroupName() { return categoryGroupName; } + public void setCategoryGroupName(String value) { categoryGroupName = value; } + @Excel(name = "规格型号") private String spec; diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java index 3c63d08..3640e6c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java @@ -9,6 +9,9 @@ public class PurchaseSheet private List rows; private List deletedIds; private String version; + private boolean unbatched; + public boolean isUnbatched() { return unbatched; } + public void setUnbatched(boolean value) { unbatched=value; } public PurchaseBatch getBatch() { return batch; } public void setBatch(PurchaseBatch value) { batch = value; } public List getRows() { return 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 new file mode 100644 index 0000000..27493a8 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ItemCategoryService.java @@ -0,0 +1,54 @@ +package com.ruoyi.warehouse.service.impl; + +import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import com.ruoyi.common.core.domain.entity.SysDictData; +import com.ruoyi.common.exception.ServiceException; + +/** Category hierarchy is metadata only: legacy item labels and historical references remain intact. */ +@Service +public class ItemCategoryService { + public static final String LEAF = "wms_item_category", GROUP = "wms_item_category_group"; + @Autowired private JdbcTemplate jdbc; + @Autowired private CatalogWriteLock catalogLock; + + public boolean managed(String type) { return LEAF.equals(type) || GROUP.equals(type); } + public void validate(SysDictData data, SysDictData old) { + if (!managed(data.getDictType()) && (old == null || !managed(old.getDictType()))) return; + catalogLock.acquire(); + if (old != null && !Objects.equals(old.getDictType(),data.getDictType())) throw new ServiceException("物品分类不能更换字典类型"); + if (data.getDictLabel() != null) data.setDictLabel(data.getDictLabel().trim()); + if (jdbc.queryForObject("select count(*) from sys_dict_data where dict_type=? and (dict_label=? or dict_value=?) and dict_code<>?", Long.class, + data.getDictType(),data.getDictLabel(),data.getDictValue(),data.getDictCode()==null?-1:data.getDictCode())>0) + throw new ServiceException("同级分类名称或数据值已存在"); + if (GROUP.equals(data.getDictType()) && data.getParentCode()!=null) throw new ServiceException("只支持大类和小类两级,大类不能设置上级"); + if (LEAF.equals(data.getDictType()) && data.getParentCode()!=null) { + if (jdbc.queryForObject("select count(*) from sys_dict_data where dict_code=? and dict_type=?",Long.class,data.getParentCode(),GROUP)!=1) + throw new ServiceException("所属大类不存在"); + if ("0".equals(data.getStatus()) && jdbc.queryForObject("select count(*) from sys_dict_data where dict_code=? and status='0'",Long.class,data.getParentCode())!=1) + throw new ServiceException("所属大类已停用,请先启用大类"); + } + if (old != null && LEAF.equals(old.getDictType()) && !Objects.equals(old.getDictLabel(),data.getDictLabel()) && used(old.getDictLabel())) + throw new ServiceException("小类已被物品或采购使用,不能改名;可以调整所属大类或停用"); + } + public void validateDelete(SysDictData data) { + if (data==null || !managed(data.getDictType())) return; + catalogLock.acquire(); + if (GROUP.equals(data.getDictType()) && jdbc.queryForObject("select count(*) from sys_dict_data where parent_code=?",Long.class,data.getDictCode())>0) + throw new ServiceException("大类下还有小类,请先调整小类归属,或停用大类"); + if (LEAF.equals(data.getDictType()) && used(data.getDictLabel())) throw new ServiceException("小类已被业务使用,请改为停用"); + } + private boolean used(String label) { + 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); + } + public List labels() { return options().stream().map(r->(String)r.get("label")).toList(); } + public List> summary() { + // Aggregate item counts only. Quantities with different units must not be added together. + return jdbc.queryForList("select g.dict_code as parentId,coalesce(g.dict_label,'未分组') as parentLabel,coalesce(nullif(p.category,''),'未分类') as category,count(*) as itemCount from product_info p left join sys_dict_data c on c.dict_type=? and c.dict_label=p.category left join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type=? group by g.dict_code,g.dict_label,p.category order by g.dict_code,p.category",LEAF,GROUP); + } +} 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 99f5e75..91ab8ab 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 @@ -25,6 +25,8 @@ public class ProductInfoServiceImpl implements IProductInfoService @Autowired private ProductInfoMapper productInfoMapper; @Autowired private CatalogWriteLock catalogWriteLock; + @Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes; + @Autowired private ItemCategoryService itemCategories; @Override public List selectProductInfoList(ProductInfo productInfo) @@ -43,8 +45,8 @@ public class ProductInfoServiceImpl implements IProductInfoService { Map> options = new LinkedHashMap<>(); options.put("brands", productInfoMapper.selectDistinctBrands()); - options.put("categories", productInfoMapper.selectDistinctCategories()); - options.put("units", productInfoMapper.selectDistinctUnits()); + options.put("categories", dictionaryLabels("wms_item_category")); + options.put("units", dictionaryLabels("wms_item_unit")); return options; } @@ -140,14 +142,24 @@ public class ProductInfoServiceImpl implements IProductInfoService productInfo.setCategory(trimToNull(productInfo.getCategory())); productInfo.setSpec(trimToNull(productInfo.getSpec())); productInfo.setUnit(trimToNull(productInfo.getUnit())); - if (StringUtils.isBlank(productInfo.getCategory()) && StringUtils.isNotBlank(productInfo.getProductName())) - { - productInfo.setCategory(inferProductCategory(productInfo)); - } } private void validateFields(ProductInfo item){ if(StringUtils.isBlank(item.getProductName())||StringUtils.isBlank(item.getUnit()))throw new ServiceException("物品名称和单位必填"); if(item.getProductName().length()>100||item.getUnit().length()>32||item.getProductCode()!=null&&item.getProductCode().length()>64)throw new ServiceException("物品名称最多100字,单位32字,编码64字"); + ProductInfo existing = item.getId() == null ? null : productInfoMapper.selectProductInfoById(item.getId()); + requireDictionary("wms_item_category", "物品类别", item.getCategory(), existing == null ? null : existing.getCategory()); + requireDictionary("wms_item_unit", "物品单位", item.getUnit(), existing == null ? null : existing.getUnit()); + } + private List dictionaryLabels(String type) { + if (ItemCategoryService.LEAF.equals(type)) return itemCategories.labels(); + return dictTypes.selectDictDataByType(type).stream().filter(d -> "0".equals(d.getStatus())) + .map(com.ruoyi.common.core.domain.entity.SysDictData::getDictLabel).toList(); + } + private void requireDictionary(String type, String label, String value, String previous) { + // Preserve historical values on unrelated edits, but never introduce an unmaintained value. + if (previous != null && previous.equals(value)) return; + if (StringUtils.isBlank(value) || !dictionaryLabels(type).contains(value)) + throw new ServiceException(label + "不存在或已停用,请先在业务字典维护后再选择"); } @Override public List> previewImport(List rows){ if(rows==null||rows.isEmpty()||rows.size()>2000)throw new ServiceException("请上传1至2000行物品"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java index 2d49ec4..c15ef14 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java @@ -2,35 +2,150 @@ package com.ruoyi.warehouse.service.impl; import java.math.BigDecimal; import java.time.LocalDate; -import java.util.*; +import java.util.List; +import java.util.Map; +import java.util.Objects; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; -import com.ruoyi.warehouse.mapper.*; +import com.ruoyi.warehouse.mapper.InRecordMapper; +import com.ruoyi.warehouse.mapper.PurchaseArrivalMapper; +import com.ruoyi.warehouse.mapper.PurchaseRequestMapper; @Service public class PurchaseReturnService { - @Autowired private JdbcTemplate db; - @Autowired private InventoryCostJournal journal; - @Autowired private PurchaseRequestMapper purchases; - @Autowired private PurchaseArrivalMapper arrivals; - @Autowired private InRecordMapper receipts; - @Autowired private PurchasePriceService prices; - public record Request(Long arrivalId,BigDecimal quantity,boolean cancelPurchase,LocalDate date,String remark,String key){} - @Transactional public void returnGoods(Request r){ - journal.lockInventory();if(r.key()==null||r.key().isBlank()||r.key().length()>120||r.quantity()==null||r.quantity().signum()<=0||r.quantity().stripTrailingZeros().scale()>4)throw new ServiceException("请填写有效数量并重新打开退货窗口"); - var arrival=arrivals.selectPurchaseArrivalByIdForUpdate(r.arrivalId());if(arrival==null||!Integer.valueOf(1).equals(arrival.getAcceptanceStatus()))throw new ServiceException("请选择已验收的到货记录"); - var purchase=purchases.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId());var dup=db.queryForList("select * from purchase_return where business_key=?",r.key());if(!dup.isEmpty()){var d=dup.get(0);boolean cancel=Boolean.TRUE.equals(d.get("cancel_purchase"))||"1".equals(String.valueOf(d.get("cancel_purchase")));if(((Number)d.get("arrival_id")).longValue()!=r.arrivalId()||new BigDecimal(d.get("quantity").toString()).compareTo(r.quantity())!=0||cancel!=r.cancelPurchase())throw new ServiceException("重复退货内容不一致");return;} - var root=receipts.selectInRecordByArrivalIdForUpdate(r.arrivalId());if(root==null||!Boolean.TRUE.equals(root.getReceiptRoot()))throw new ServiceException("该历史验收未建立分次入库来源,请先核对历史记录"); - BigDecimal received=receipts.receivedQuantity(root.getId()),pending=root.getInNum().subtract(received);if(r.quantity().compareTo(pending)>0)throw new ServiceException("退货超过待入库数量,请先撤销对应入库"); - BigDecimal remaining=root.getInNum().subtract(r.quantity());db.update("update in_record set in_num=?,in_status=?,update_time=current_timestamp where id=?",remaining,remaining.compareTo(received)==0?1:0,root.getId()); - db.update("update purchase_arrival set returned_quantity=returned_quantity+?,update_time=current_timestamp where id=?",r.quantity(),r.arrivalId()); - db.update("insert into purchase_return(business_key,arrival_id,quantity,cancel_purchase,business_date,remark,create_by) values(?,?,?,?,?,?,?)",r.key(),r.arrivalId(),r.quantity(),r.cancelPurchase(),r.date()==null?LocalDate.now():r.date(),r.remark(),SecurityUtils.getUsername()); - BigDecimal quantity=r.cancelPurchase()?purchase.getQuantity().subtract(r.quantity()):purchase.getQuantity();BigDecimal accepted=arrivals.selectAcceptedQuantityByRequestId(purchase.getId());int status=quantity.signum()==0?5:accepted.compareTo(quantity)>=0?4:accepted.signum()>0?3:2; - db.update("update purchase_request set quantity=?,purchase_status=?,update_time=current_timestamp where id=?",quantity,status,purchase.getId());var updated=purchases.selectPurchaseRequestByIdForUpdate(purchase.getId());prices.refreshLockedAmount(purchase,updated,"PURCHASE_RETURN"); - } - public List> history(Long arrivalId){return db.queryForList("select * from purchase_return where arrival_id=? order by id desc",arrivalId);} + private static final String LEGACY_MESSAGE = "该历史验收未建立分次入库来源,请先核对历史记录"; + private static final String INCONSISTENT_MESSAGE = "验收、退货与入库数量不一致,请先核对来源记录"; + @Autowired private JdbcTemplate db; + @Autowired private InventoryCostJournal journal; + @Autowired private PurchaseRequestMapper purchases; + @Autowired private PurchaseArrivalMapper arrivals; + @Autowired private InRecordMapper receipts; + @Autowired private PurchasePriceService prices; + + public record Request(Long arrivalId, BigDecimal quantity, boolean cancelPurchase, + LocalDate date, String remark, String key) {} + + /** Quantities describe the original accepted goods, prior returns and current receipts separately. */ + public record Availability(Long arrivalId, BigDecimal acceptedQuantity, BigDecimal returnedQuantity, + BigDecimal receivedQuantity, BigDecimal returnableQuantity, + boolean supported, String message) {} + + /** One non-locking snapshot avoids mixing quantities from concurrent receipt/return operations. */ + public Availability availability(Long arrivalId) { + requireArrivalId(arrivalId); + var rows = db.queryForList(""" + select pa.acceptance_status, + pa.arrival_quantity-coalesce(pa.defective_quantity,0) accepted_quantity, + coalesce(pa.returned_quantity,0) returned_quantity, + ir.id receipt_id,ir.receipt_root,ir.in_num retained_quantity, + coalesce((select sum(child.in_num) from in_record child + where child.parent_in_id=ir.id and child.in_status=1),0) received_quantity + from purchase_arrival pa + left join in_record ir on ir.arrival_id=pa.id and ir.parent_in_id is null + where pa.id=? + """, arrivalId); + if (rows.isEmpty() || !truth(rows.get(0).get("acceptance_status"))) { + throw new ServiceException("请选择已验收的到货记录"); + } + var row = rows.get(0); + boolean supported = rows.size() == 1 && row.get("receipt_id") != null && truth(row.get("receipt_root")); + return calculate(arrivalId, decimal(row.get("accepted_quantity")), decimal(row.get("returned_quantity")), + decimal(row.get("retained_quantity")), decimal(row.get("received_quantity")), supported); + } + + @Transactional + public void returnGoods(Request request) { + validate(request); + journal.lockInventory(); + var arrival = arrivals.selectPurchaseArrivalByIdForUpdate(request.arrivalId()); + if (arrival == null || !Integer.valueOf(1).equals(arrival.getAcceptanceStatus())) { + throw new ServiceException("请选择已验收的到货记录"); + } + var purchase = purchases.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId()); + if (purchase == null) throw new ServiceException("采购记录不存在,请刷新后重试"); + var duplicates = db.queryForList("select * from purchase_return where business_key=?", request.key()); + if (!duplicates.isEmpty()) { + var prior = duplicates.get(0); + if (((Number) prior.get("arrival_id")).longValue() != request.arrivalId() + || decimal(prior.get("quantity")).compareTo(request.quantity()) != 0 + || truth(prior.get("cancel_purchase")) != request.cancelPurchase() + || (request.date() != null && !request.date().toString().equals(String.valueOf(prior.get("business_date")))) + || !Objects.equals(request.remark(), prior.get("remark"))) { + throw new ServiceException("重复退货内容不一致"); + } + return; + } + var root = receipts.selectInRecordByArrivalIdForUpdate(request.arrivalId()); + boolean supported = root != null && Boolean.TRUE.equals(root.getReceiptRoot()); + BigDecimal received = supported ? receipts.receivedQuantity(root.getId()) : BigDecimal.ZERO; + BigDecimal returned = db.queryForObject("select returned_quantity from purchase_arrival where id=?", BigDecimal.class, request.arrivalId()); + Availability available = calculate(request.arrivalId(), + arrival.getArrivalQuantity().subtract(decimal(arrival.getDefectiveQuantity())), decimal(returned), + supported ? root.getInNum() : BigDecimal.ZERO, received, supported); + if (!available.supported()) throw new ServiceException(available.message()); + if (request.quantity().compareTo(available.returnableQuantity()) > 0) { + throw new ServiceException("退货超过待入库数量,请先撤销对应入库"); + } + BigDecimal quantity = request.cancelPurchase() ? purchase.getQuantity().subtract(request.quantity()) : purchase.getQuantity(); + if (quantity.signum() < 0) throw new ServiceException("取消数量超过采购数量,请先核对采购记录"); + BigDecimal remaining = root.getInNum().subtract(request.quantity()); + db.update("update in_record set in_num=?,in_status=?,update_time=current_timestamp where id=?", + remaining, remaining.compareTo(received) == 0 ? 1 : 0, root.getId()); + db.update("update purchase_arrival set returned_quantity=returned_quantity+?,update_time=current_timestamp where id=?", + request.quantity(), request.arrivalId()); + db.update("insert into purchase_return(business_key,arrival_id,quantity,cancel_purchase,business_date,remark,create_by) values(?,?,?,?,?,?,?)", + request.key(), request.arrivalId(), request.quantity(), request.cancelPurchase(), + request.date() == null ? LocalDate.now() : request.date(), request.remark(), SecurityUtils.getUsername()); + BigDecimal accepted = arrivals.selectAcceptedQuantityByRequestId(purchase.getId()); + int status = quantity.signum() == 0 ? 5 : accepted.compareTo(quantity) >= 0 ? 4 : accepted.signum() > 0 ? 3 : 2; + db.update("update purchase_request set quantity=?,purchase_status=?,update_time=current_timestamp where id=?", + quantity, status, purchase.getId()); + var updated = purchases.selectPurchaseRequestByIdForUpdate(purchase.getId()); + prices.refreshLockedAmount(purchase, updated, "PURCHASE_RETURN"); + } + + private Availability calculate(Long arrivalId, BigDecimal accepted, BigDecimal returned, + BigDecimal retained, BigDecimal received, boolean hasRoot) { + if (!hasRoot) return new Availability(arrivalId, accepted, returned, received, BigDecimal.ZERO, false, LEGACY_MESSAGE); + if (accepted.signum() < 0 || returned.signum() < 0 || retained.signum() < 0 || received.signum() < 0 + || accepted.subtract(returned).compareTo(retained) != 0 || received.compareTo(retained) > 0) { + return new Availability(arrivalId, accepted, returned, received, BigDecimal.ZERO, false, INCONSISTENT_MESSAGE); + } + return new Availability(arrivalId, accepted, returned, received, retained.subtract(received), true, ""); + } + + private void validate(Request request) { + if (request == null) throw new ServiceException("请填写退货信息"); + requireArrivalId(request.arrivalId()); + if (request.key() == null || request.key().isBlank() || request.key().length() > 120 + || request.quantity() == null || request.quantity().signum() <= 0 + || request.quantity().stripTrailingZeros().scale() > 4 + || (long) request.quantity().precision() - request.quantity().scale() > 16) { + throw new ServiceException("请填写有效数量并重新打开退货窗口"); + } + if (request.date() != null && (request.date().getYear() < 1000 || request.date().getYear() > 9999)) { + throw new ServiceException("请填写有效的退货日期"); + } + if (request.remark() != null && request.remark().length() > 500) throw new ServiceException("退货备注不能超过500字"); + } + + private void requireArrivalId(Long arrivalId) { + if (arrivalId == null || arrivalId <= 0) throw new ServiceException("请选择已验收的到货记录"); + } + + private static BigDecimal decimal(Object value) { + return value == null ? BigDecimal.ZERO : new BigDecimal(value.toString()); + } + + private static boolean truth(Object value) { + return Boolean.TRUE.equals(value) || "1".equals(String.valueOf(value)); + } + + public List> history(Long arrivalId) { + return db.queryForList("select * from purchase_return where arrival_id=? order by id desc", arrivalId); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java index 8576737..88f7f95 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java @@ -45,12 +45,20 @@ public class PurchaseSheetService @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) public PurchaseSheet prepare(Long[] ids) { + return prepare(ids,null); + } + + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) + public PurchaseSheet prepare(Long[] ids, Long targetId) { requirePermission("add");requirePermission("edit");catalogLock.acquire(); if(ids==null||ids.length==0||ids.length>2000||Arrays.stream(ids).anyMatch(Objects::isNull))throw new ServiceException("请选择1至2000条未分批明细"); ids=Arrays.stream(ids).distinct().sorted().toArray(Long[]::new); List rows=new ArrayList<>(); for(Long id:ids){var r=requests.selectPurchaseRequestByIdForUpdate(id);if(r==null||r.getPurchaseBatchId()!=null||Boolean.TRUE.equals(r.getHistorical())||Integer.valueOf(5).equals(r.getPurchaseStatus())||Boolean.TRUE.equals(r.getPriceLocked()))throw new ServiceException("仅未确认、未分批的采购可以组批");r=requests.selectPurchaseRequestById(id,null);if(r.getAcceptedQuantity()!=null&&r.getAcceptedQuantity().signum()>0||r.getPendingArrivalQuantity()!=null&&r.getPendingArrivalQuantity().signum()>0)throw new ServiceException("已有到货的明细请先退回");rows.add(r);} - var batch=new PurchaseBatch();batch.setBusinessDate(java.time.LocalDate.now());batch.setBatchNo(batchNumbers.next(batch.getBusinessDate()));batch.setPurchaseStatus(1);batch.setCreateBy(SecurityUtils.getUsername());batches.insertPurchaseBatch(batch);batches.assignRequests(ids,batch,SecurityUtils.getUsername()); + PurchaseBatch batch; + if(targetId==null){batch=new PurchaseBatch();batch.setBusinessDate(java.time.LocalDate.now());batch.setBatchNo(batchNumbers.next(batch.getBusinessDate()));batch.setPurchaseStatus(1);batch.setCreateBy(SecurityUtils.getUsername());batches.insertPurchaseBatch(batch);} + else {lockBatch(targetId);batch=batches.selectPurchaseBatchById(targetId);if(batch==null||!Integer.valueOf(1).equals(batch.getPurchaseStatus())||requests.selectPurchaseSheetRows(targetId).stream().anyMatch(this::committed))throw new ServiceException("只能加入尚未确认、没有到货的采购批次");} + batches.assignRequests(ids,batch,SecurityUtils.getUsername()); for(var r:rows)operationLogs.record(r.getId(),r.getRequestNo(),"BATCH_ASSIGN","采购组批","未分批 → "+batch.getBatchNo()); return load(batch.getId()); } @@ -58,6 +66,7 @@ public class PurchaseSheetService @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) public PurchaseSheet save(PurchaseSheet sheet) { + if(sheet!=null && sheet.isUnbatched())return saveUnbatched(sheet); if (sheet == null || sheet.getBatch() == null || sheet.getRows() == null || sheet.getRows().size() > 2000 || sheet.getBatch().getId() == null && sheet.getRows().isEmpty()) throw new ServiceException("请填写1至2000行采购明细"); @@ -163,6 +172,44 @@ public class PurchaseSheetService return load(id); } + @Transactional(readOnly=true) + public PurchaseSheet loadUnbatched(Long[] ids) { + if(ids==null||ids.length==0||ids.length>2000||Arrays.stream(ids).anyMatch(Objects::isNull))throw new ServiceException("请选择1至2000条明细"); + var rows=new ArrayList(); + for(Long id:Arrays.stream(ids).distinct().sorted().toList()) { + var row=requests.selectPurchaseRequestById(id,null); + if(row==null||row.getPurchaseBatchId()!=null)throw new ServiceException("明细已组批或已删除,请刷新列表"); + rows.add(row); + } + return unbatchedSnapshot(rows); + } + private PurchaseSheet unbatchedSnapshot(List rows){ + rows.sort(Comparator.comparing(PurchaseRequest::getId)); + var result=new PurchaseSheet();result.setUnbatched(true);result.setBatch(new PurchaseBatch());result.setRows(rows);result.setDeletedIds(List.of());result.setVersion(version(result.getBatch(),rows));return result; + } + private PurchaseSheet saveUnbatched(PurchaseSheet sheet){ + if(sheet.getRows()==null||sheet.getRows().size()>2000||sheet.getBatch()!=null&&sheet.getBatch().getId()!=null)throw new ServiceException("未组批明细格式不正确"); + catalogLock.acquire(); + var ids=new TreeSet(); + for(var row:sheet.getRows()){if(row==null)throw new ServiceException("明细不能为空");if(row.getId()!=null&&!ids.add(row.getId()))throw new ServiceException("明细重复");requirePermission(row.getId()==null?"add":"edit");} + var deleted=sheet.getDeletedIds()==null?List.of():sheet.getDeletedIds(); + for(Long id:deleted){requirePermission("remove");if(id==null||!ids.add(id))throw new ServiceException("删除明细重复");} + if(ids.size()>2000||sheet.getRows().isEmpty()&&deleted.isEmpty())throw new ServiceException("请填写采购明细"); + var old=new HashMap(); + 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("明细已被其他操作更新,请重新打开后再保存"); + var items=new ArrayList<>(catalog.selectProductInfoAll());var saved=new ArrayList();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()); + 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());} + } + if(!deleted.isEmpty())purchases.deletePurchaseRequestByIds(deleted.toArray(Long[]::new)); + return unbatchedSnapshot(saved); + } + private void resolveItem(PurchaseRequest row, List items) { ProductInfo match = null; diff --git a/ruoyi-system/src/main/resources/mapper/project/ProjectLoanMapper.xml b/ruoyi-system/src/main/resources/mapper/project/ProjectLoanMapper.xml index f71cdd8..cf671fe 100644 --- a/ruoyi-system/src/main/resources/mapper/project/ProjectLoanMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/project/ProjectLoanMapper.xml @@ -14,9 +14,29 @@ l.historical_returned+coalesce(r.returned_quantity,0) returned_quantity,l.quantity-l.historical_returned-coalesce(r.returned_quantity,0) outstanding_quantity from project_loan l join project_info p on p.id=l.lender_project_id join project_info b on b.id=l.borrower_project_id join product_info i on i.id=l.item_id left join (select loan_id,sum(quantity) returned_quantity from project_loan_return where active=1 group by loan_id) r on r.loan_id=l.id - - - + + + insert into project_loan(loan_no,lender_project_id,borrower_project_id,item_id,quantity,out_event_id,in_event_id,remark,create_by,business_date) values(#{loanNo},#{lenderProjectId},#{borrowerProjectId},#{itemId},#{quantity},#{outEventId},#{inEventId},#{remark},#{createBy},#{businessDate}) update project_loan set active=0 where id=#{id} and active=1 insert into project_loan_return(loan_id,quantity,business_key,return_type,out_event_id,in_event_id,create_by) values(#{loanId},#{quantity},#{key},#{type},#{outId},#{inId},#{actor}) diff --git a/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml index 3b94b7f..0083d20 100644 --- a/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/SysDictDataMapper.xml @@ -6,6 +6,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + @@ -21,7 +22,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - select dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark + select dict_code, parent_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark from sys_dict_data @@ -74,6 +75,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" update sys_dict_data + parent_code = #{parentCode}, dict_sort = #{dictSort}, dict_label = #{dictLabel}, dict_value = #{dictValue}, @@ -95,6 +97,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" insert into sys_dict_data( + parent_code, dict_sort, dict_label, dict_value, @@ -107,6 +110,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" create_by, create_time )values( + #{parentCode}, #{dictSort}, #{dictLabel}, #{dictValue}, @@ -121,4 +125,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" ) - \ No newline at end of file + diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml index 3a77c7f..a25eaa7 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml @@ -7,6 +7,7 @@ + @@ -15,7 +16,8 @@ - select id, product_code, product_name, brand, category, spec, unit, remark, create_time, update_time from product_info + 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