From e3860a3fd9b2edc10936b5c12ca3c77444592714 Mon Sep 17 00:00:00 2001 From: lixiaolong <702156524@qq.com> Date: Tue, 13 Oct 2026 09:41:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(production):=20=E4=BC=98=E5=8C=96=E7=94=9F?= =?UTF-8?q?=E4=BA=A7=E4=BB=BB=E5=8A=A1=E6=93=8D=E4=BD=9C=E6=9D=83=E9=99=90?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E4=B8=8E=E6=95=B0=E6=8D=AE=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加权限检查功能,防止未授权操作 - 实现远程搜索功能优化任务选择体验 - 集成分页查询提高大数据量性能表现 - 增强批量操作界面增加搜索筛选功能 - 完善表单验证与错误处理机制 - 重构数据过滤逻辑支持多条件组合查询 --- README.md | 5 +- .../production/ProductionTaskController.java | 8 + .../warehouse/HomeSummaryController.java | 13 ++ .../warehouse/InRecordController.java | 5 + .../warehouse/PurchaseRequestController.java | 22 ++- .../warehouse/SupplierQuoteImport.java | 43 +++++ .../projectdev/HomeSummaryDatabaseTest.java | 27 +++ .../projectdev/ProductionShortageTest.java | 23 +++ .../projectdev/PurchaseArrivalRulesTest.java | 22 +++ .../projectdev/PurchaseSheetDatabaseTest.java | 35 +++- .../projectdev/SupplierQuoteImportTest.java | 21 +++ .../production/service/ProductionService.java | 86 ++++++++-- .../com/ruoyi/warehouse/domain/InRecord.java | 6 + .../ruoyi/warehouse/domain/PurchaseBatch.java | 9 + .../warehouse/domain/PurchaseRequest.java | 5 + .../com/ruoyi/warehouse/domain/StockInfo.java | 3 + .../warehouse/mapper/ProductInfoMapper.java | 1 + .../warehouse/mapper/PurchaseBatchMapper.java | 1 + .../service/IPurchaseArrivalService.java | 1 + .../service/impl/HomeSummaryService.java | 50 ++++++ .../service/impl/InitializationService.java | 2 +- .../service/impl/PendingReceiptService.java | 30 ++++ .../impl/PurchaseArrivalServiceImpl.java | 15 +- .../impl/PurchaseBatchServiceImpl.java | 19 ++- .../impl/PurchaseRequestServiceImpl.java | 6 + .../service/impl/PurchaseSheetService.java | 22 ++- .../mapper/warehouse/InRecordMapper.xml | 4 + .../mapper/warehouse/ProductInfoMapper.xml | 1 + .../mapper/warehouse/PurchaseBatchMapper.xml | 11 +- .../warehouse/PurchaseRequestMapper.xml | 4 +- .../mapper/warehouse/StockInfoMapper.xml | 1 + ruoyi-ui/src/api/production/tasks.js | 6 +- ruoyi-ui/src/api/project/loan.js | 2 +- ruoyi-ui/src/api/warehouse/inRecord.js | 2 +- ruoyi-ui/src/api/warehouse/purchase.js | 9 +- .../components/InventoryAssistant/index.vue | 15 +- .../components/Production/ActionDialog.vue | 8 +- .../components/Production/ActionHistory.vue | 37 +++-- .../components/Production/BatchActions.vue | 9 +- .../src/components/Production/CostHistory.vue | 4 +- .../Production/ShortagePurchase.vue | 26 +++ .../components/Production/StockOperations.vue | 10 +- .../components/ProjectLoans/BatchReturn.vue | 14 +- .../src/components/ProjectLoans/index.vue | 18 +- .../components/ProjectWorkspace/Budget.vue | 12 +- .../src/components/ProjectWorkspace/index.vue | 42 +++-- .../src/components/PurchaseSheet/Lookup.vue | 46 ++++++ .../src/components/PurchaseSheet/index.vue | 155 +++++++++++------- .../src/components/ReceiptDialog/Batch.vue | 36 ++-- .../src/components/ReceiptDialog/index.vue | 2 +- ruoyi-ui/src/directive/index.js | 2 + .../src/directive/permission/hasAllPermi.js | 3 + ruoyi-ui/src/router/index.js | 2 +- ruoyi-ui/src/utils/business-home.js | 6 +- ruoyi-ui/src/utils/business-permissions.js | 3 + ruoyi-ui/src/utils/material-allocation.js | 2 + ruoyi-ui/src/utils/purchase-sheet.js | 5 +- ruoyi-ui/src/views/businessHome/index.vue | 55 +++---- ruoyi-ui/src/views/production/bom/index.vue | 12 +- ruoyi-ui/src/views/production/tasks/index.vue | 74 +++++---- ruoyi-ui/src/views/project/detail/index.vue | 2 +- ruoyi-ui/src/views/project/info/index.vue | 30 +--- ruoyi-ui/src/views/warehouse/area/index.vue | 3 +- .../src/views/warehouse/inRecord/index.vue | 53 +++--- .../src/views/warehouse/product/index.vue | 3 +- .../src/views/warehouse/purchase/index.vue | 45 ++--- ruoyi-ui/src/views/warehouse/stock/index.vue | 19 +-- .../src/views/warehouse/stockCheck/index.vue | 3 +- scripts/projectdev/Build-Android.ps1 | 6 +- scripts/projectdev/Start-Local.ps1 | 6 +- scripts/projectdev/audit-fixes-ui-check.cjs | 91 ++++++++++ .../projectdev/desktop-workbench-check.cjs | 12 +- scripts/projectdev/migrate-vue3.cjs | 79 +++++++++ scripts/projectdev/mobile-update.cjs | 2 +- .../operations-optimization-ui-check.cjs | 61 +++++++ scripts/projectdev/purchase-sheet-check.cjs | 3 + .../projectdev/purchase-sheet-ui-check.cjs | 12 +- .../projectdev/vue3-interactions-check.cjs | 29 ++++ scripts/projectdev/vue3-migration-check.cjs | 26 +++ scripts/projectdev/web-design-checks.cjs | 6 +- 80 files changed, 1248 insertions(+), 361 deletions(-) create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/HomeSummaryController.java create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/HomeSummaryDatabaseTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseArrivalRulesTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/SupplierQuoteImportTest.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/HomeSummaryService.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PendingReceiptService.java create mode 100644 ruoyi-ui/src/components/Production/ShortagePurchase.vue create mode 100644 ruoyi-ui/src/components/PurchaseSheet/Lookup.vue create mode 100644 ruoyi-ui/src/directive/permission/hasAllPermi.js create mode 100644 ruoyi-ui/src/utils/business-permissions.js create mode 100644 ruoyi-ui/src/utils/material-allocation.js create mode 100644 scripts/projectdev/audit-fixes-ui-check.cjs create mode 100644 scripts/projectdev/migrate-vue3.cjs create mode 100644 scripts/projectdev/operations-optimization-ui-check.cjs create mode 100644 scripts/projectdev/vue3-interactions-check.cjs create mode 100644 scripts/projectdev/vue3-migration-check.cjs diff --git a/README.md b/README.md index 64a9fed..58c7d9c 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,13 @@ mvn clean package -DskipTests 前端: ```bash -cd ruoyi-ui +cd ruoyi-ui-vue3 +npm ci npm run build:prod ``` +前端使用 Vue3、Element Plus 和 Pinia,开发启动执行 `cd ruoyi-ui-vue3` 后运行 `npm run dev`,默认地址为 `http://localhost:8088`。本地前后端统一启动可执行 `scripts/projectdev/Start-Local.ps1`。原 `ruoyi-ui` 目录保留,后续前端开发与安卓页面包构建使用 `ruoyi-ui-vue3`。 + 后端启动包输出为 `ruoyi-admin/target/cmvr-wms.jar`。 ## 数据库升级 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 e1dfdac..653f424 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 @@ -16,14 +16,22 @@ public class ProductionTaskController extends BaseController { @Autowired private ProductionService service; @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping 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') && @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}") public AjaxResult get(@PathVariable Long id){return success(service.detail(id));} @PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @PostMapping @Log(title="生产任务",businessType=BusinessType.UPDATE) public AjaxResult save(@RequestBody ProductionCommand command){return success(service.save(command));} + @PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @DeleteMapping("/{id}") @Log(title="删除未开始生产任务",businessType=BusinessType.DELETE) + public AjaxResult remove(@PathVariable Long id,@RequestParam Integer version){service.remove(id,version);return success();} @PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasPermi('warehouse:stock:out')") @PostMapping("/actions") @Log(title="生产报废与交付",businessType=BusinessType.UPDATE) public AjaxResult perform(@RequestBody ProductionCommand command){return success(service.perform(command));} @PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasPermi('warehouse:stock:out')") @PostMapping("/actions/{id}/revoke") @Log(title="撤销生产报废交付",businessType=BusinessType.UPDATE) public AjaxResult revoke(@PathVariable Long id,@RequestBody Map request){service.revoke(id,request.get("reason"));return success();} + @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/actions/page") + public AjaxResult actionPage(Long projectId,Long taskId,String kind,Boolean active,String keyword,String beginDate,String endDate,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return success(service.actionPage(projectId,taskId,kind,active,keyword,beginDate,endDate,pageNum,pageSize));} @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/actions") public AjaxResult actions(Long projectId,Long taskId){return success(service.actions(projectId,taskId));} @PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @PostMapping("/{id}/settle") @Log(title="生产成本结算",businessType=BusinessType.UPDATE) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/HomeSummaryController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/HomeSummaryController.java new file mode 100644 index 0000000..c17e5d8 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/HomeSummaryController.java @@ -0,0 +1,13 @@ +package com.ruoyi.web.controller.warehouse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.warehouse.service.impl.HomeSummaryService; +@RestController @RequestMapping("/business/home") public class HomeSummaryController { + @Autowired private HomeSummaryService service; + @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:purchase:list,warehouse:purchase:manage,warehouse:in:list,warehouse:stock:list,warehouse:check:list,warehouse:out:list')") @GetMapping + public AjaxResult summary(Long projectId){return AjaxResult.success(service.summary(projectId));} + @PreAuthorize("@ss.hasPermi('project:project:list')") @GetMapping("/projects") + public AjaxResult projects(String keyword){return AjaxResult.success(service.projects(keyword));} +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java index 68b731e..f5d5544 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java @@ -29,6 +29,11 @@ public class InRecordController extends BaseController { @Autowired private IInRecordService inRecordService; + @Autowired private com.ruoyi.warehouse.service.impl.PendingReceiptService pending; + @PreAuthorize("@ss.hasPermi('warehouse:in:list')") @GetMapping("/pending-groups") + public AjaxResult pendingGroups(InRecord query,@org.springframework.web.bind.annotation.RequestParam(defaultValue="1") int pageNum,@org.springframework.web.bind.annotation.RequestParam(defaultValue="20") int pageSize){return success(pending.page(query,pageNum,pageSize));} + @PreAuthorize("@ss.hasPermi('warehouse:in:list')") @GetMapping("/pending-groups/{key}") + public AjaxResult pendingGroup(@PathVariable String key,InRecord query){return success(pending.group(key,query));} public record ReceiptRequest(Long areaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark){} @PreAuthorize("@ss.hasPermi('warehouse:in:confirm')") @PostMapping("/receive/{id}") @Log(title="分次入库",businessType=BusinessType.UPDATE) public AjaxResult receive(@PathVariable Long id,@RequestBody ReceiptRequest request){return toAjax(inRecordService.receive(id,request.areaId(),request.quantity(),request.key(),getUsername(),request.date(),request.remark()));} 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 8715bdc..0e8377a 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 @@ -48,21 +48,30 @@ public class PurchaseRequestController extends BaseController @Autowired private com.ruoyi.warehouse.service.impl.PurchaseSheetService sheetService; @Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes; @Autowired private org.springframework.jdbc.core.JdbcTemplate sheetDatabase; + @Autowired private com.ruoyi.warehouse.mapper.ProductInfoMapper sheetCatalog; @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/sheet/options") - public AjaxResult sheetOptions() + public AjaxResult sheetOptions(String keyword,String name) { var result = new java.util.LinkedHashMap(); - result.put("items", productInfoService.selectProductInfoAll()); - result.put("units", dictTypes.selectDictDataByType("wms_item_unit")); - result.put("plans", 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 order by t.id desc")); + if(name!=null)result.put("items",sheetCatalog.selectProductVariants(name.trim())); + else {var filter=new com.ruoyi.warehouse.domain.ProductInfo();filter.setProductName(keyword);com.github.pagehelper.PageHelper.startPage(1,100,false);try{result.put("items",productInfoService.selectProductInfoList(filter));}finally{com.github.pagehelper.PageHelper.clearPage();}} + if(name==null&&keyword==null){result.put("units", dictTypes.selectDictDataByType("wms_item_unit"));result.put("plans", 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 t.status='OPEN' order by t.id desc limit 100"));} return success(result); } @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/sheet/{id}") 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));} + @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')") @Log(title = "采购批次表格", businessType = BusinessType.UPDATE) @@ -73,6 +82,11 @@ public class PurchaseRequestController extends BaseController @Log(title = "确认整批采购", businessType = BusinessType.UPDATE) @PostMapping("/sheet/{id}/confirm") public AjaxResult confirmSheet(@PathVariable Long id, @RequestBody java.util.Map data) { return success(sheetService.confirm(id, data.get("version"))); } + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @PostMapping("/sheet/{id}/quote-preview") + public AjaxResult quotePreview(@PathVariable Long id,MultipartFile file)throws Exception { + WarehouseFileUtils.validateUpload(file,10L*1024*1024,Set.of("xls","xlsx")); + try(var input=file.getInputStream()){return success(SupplierQuoteImport.preview(input,sheetService.load(id)));} + } @Autowired private com.ruoyi.warehouse.service.impl.WarehouseImportReceiptService importReceipts; @PostMapping("/importPreview") @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:import,warehouse:purchase:manage')") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java new file mode 100644 index 0000000..fbbf2ff --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierQuoteImport.java @@ -0,0 +1,43 @@ +package com.ruoyi.web.controller.warehouse; + +import java.io.InputStream; +import java.math.BigDecimal; +import java.util.*; +import org.apache.poi.ss.usermodel.*; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.domain.PurchaseSheet; + +/** Read-only preview. Match by batch and item code, never by spreadsheet row order. */ +public final class SupplierQuoteImport { + private SupplierQuoteImport(){} + public static List> preview(InputStream input,PurchaseSheet sheet)throws Exception { + try(var workbook=WorkbookFactory.create(input)) { + var tab=workbook.getSheetAt(0);var formatter=new DataFormatter();var header=tab.getRow(tab.getFirstRowNum()); + if(header==null)throw new ServiceException("报价文件为空"); + Map columns=new HashMap<>();for(var cell:header)columns.put(formatter.formatCellValue(cell).trim(),cell.getColumnIndex()); + for(String key:List.of("采购批次","物品编码","最终单价"))if(!columns.containsKey(key))throw new ServiceException("请使用导出给供应商的文件,缺少列:"+key); + if(tab.getLastRowNum()>2000)throw new ServiceException("报价文件最多2000行"); + Set seen=new HashSet<>();List> result=new ArrayList<>(); + for(int n=header.getRowNum()+1;n<=tab.getLastRowNum();n++) { + var row=tab.getRow(n);if(row==null)continue; + String batch=text(row,columns.get("采购批次"),formatter),code=text(row,columns.get("物品编码"),formatter),price=text(row,columns.get("最终单价"),formatter); + if(code.isEmpty()&&price.isEmpty())continue; + var item=new LinkedHashMap();item.put("line",n+1);item.put("productCode",code);item.put("price",price);String error=null; + BigDecimal value=null;List ids=new ArrayList<>(); + if(!Objects.equals(batch,sheet.getBatch().getBatchNo()))error="批次不一致"; + else if(!seen.add(code))error="物品重复,请合并为同一报价"; + else { + try {value=new BigDecimal(price.replace(",",""));if(value.signum()<0||value.stripTrailingZeros().scale()>6)throw new NumberFormatException();} + catch(Exception e){error="请填写非负单价,最多6位小数";} + var matches=sheet.getRows().stream().filter(r->Objects.equals(code,r.getProductCode())&&!Integer.valueOf(5).equals(r.getPurchaseStatus())).toList(); + if(matches.isEmpty())error="当前批次找不到该物品"; + else if(matches.stream().anyMatch(r->Boolean.TRUE.equals(r.getHistorical())||r.getReceivedQuantity()!=null&&r.getReceivedQuantity().signum()>0))error="已有入库或属于历史记录,请先按流程退回"; + else {ids=matches.stream().map(r->r.getId()).toList();item.put("name",matches.get(0).getMaterialName());} + } + item.put("rowIds",ids);item.put("unitPrice",value);item.put("error",error);result.add(item); + } + if(result.isEmpty())throw new ServiceException("没有可读取的报价");return result; + } + } + private static String text(Row row,int column,DataFormatter formatter){var cell=row.getCell(column);return cell==null?"":formatter.formatCellValue(cell).trim();} +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/HomeSummaryDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/HomeSummaryDatabaseTest.java new file mode 100644 index 0000000..7076dc4 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/HomeSummaryDatabaseTest.java @@ -0,0 +1,27 @@ +package com.ruoyi.projectdev; +import java.util.*; +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 com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.service.impl.HomeSummaryService; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +@EnabledIfSystemProperty(named="projectDbTests",matches="true") class HomeSummaryDatabaseTest { + @Test void aggregatesAreBoundedAndRespectEachSourcePermission()throws Exception{ + try(var connection=AuthorizedDatabaseTestSupport.connection();var security=mockStatic(SecurityUtils.class)){ + var service=new HomeSummaryService();ReflectionTestUtils.setField(service,"db",new JdbcTemplate(new SingleConnectionDataSource(connection,true))); + var production=new com.ruoyi.production.service.ProductionService();ReflectionTestUtils.setField(production,"db",new JdbcTemplate(new SingleConnectionDataSource(connection,true)));assertTrue(((List)production.page(null,null,null,null,1,1).get("rows")).size()<=1);assertTrue(((List)production.page(null,null,"OPEN","测试",1,20).get("rows")).size()<=20); + var pending=new com.ruoyi.warehouse.service.impl.PendingReceiptService();ReflectionTestUtils.setField(pending,"db",new JdbcTemplate(new SingleConnectionDataSource(connection,true)));assertTrue(((List)pending.page(new com.ruoyi.warehouse.domain.InRecord(),1,20).get("rows")).size()<=20);assertTrue(((List)production.page(null,null,"READY",null,1,20).get("rows")).size()<=20);assertTrue(((List)production.actionPage(null,null,null,null,"测试",null,null,1,20).get("rows")).size()<=20); + ReflectionTestUtils.setField(service,"pending",pending); + security.when(SecurityUtils::isAdmin).thenReturn(true); + var all=service.summary(null);var queues=(List>)all.get("queues");assertEquals(7,queues.size());for(var q:queues){assertTrue(((List)q.get("rows")).size()<=6);assertTrue(((Number)q.get("count")).longValue()>=((List)q.get("rows")).size());} + var empty=service.summary(Long.MAX_VALUE);for(var q:(List>)empty.get("queues"))assertEquals(0,((Number)q.get("count")).intValue());assertTrue(service.projects(null).size()<=50); + security.when(SecurityUtils::isAdmin).thenReturn(false);security.when(()->SecurityUtils.hasPermi(anyString())).thenAnswer(a->"warehouse:purchase:list".equals(a.getArgument(0))); + var restricted=service.summary(null);assertEquals(4,((List)restricted.get("queues")).size());assertFalse(restricted.containsKey("projects"));assertTrue(((Map)restricted.get("warehouse")).isEmpty());assertFalse(((Map)restricted.get("overview")).containsKey("budget")); + connection.rollback(); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java new file mode 100644 index 0000000..ae4c512 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionShortageTest.java @@ -0,0 +1,23 @@ +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.test.util.ReflectionTestUtils; +import com.ruoyi.production.service.*; +import com.ruoyi.production.domain.*; +import com.ruoyi.warehouse.domain.ProductInfo; +import com.ruoyi.warehouse.mapper.ProductInfoMapper; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +class ProductionShortageTest { + @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); + var bom=new BomVersion();var line=new BomLine();line.setItemId(3L);line.setItemName("螺丝");line.setUnitQuantity(BigDecimal.ONE);bom.setLines(List.of(line));when(boms.get(9L)).thenReturn(bom);var item=new ProductInfo();item.setCategory("零件");when(items.selectProductInfoById(3L)).thenReturn(item); + var cover=new java.util.concurrent.atomic.AtomicInteger();var stock=new java.util.concurrent.atomic.AtomicInteger(); + when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(a->{String sql=a.getArgument(0);if(sql.startsWith("select t.*"))return List.of(Map.of("id",1L,"project_id",2L,"project_name","项目","task_no","SC1","bom_id",9L,"planned_quantity",new BigDecimal("100"),"status","OPEN"));if(sql.contains("from production_action"))return List.of(Map.of("item_id",3L,"issued",new BigDecimal("100"),"returned",BigDecimal.ZERO,"scrapped",new BigDecimal("20")));if(sql.contains("from purchase_request"))return List.of(Map.of("product_id",3L,"purchasing",BigDecimal.valueOf(cover.get())));if(sql.contains("from project_stock_balance"))return List.of(Map.of("item_id",3L,"quantity",BigDecimal.valueOf(stock.get())));throw new AssertionError(sql);}); + assertEquals(0,new BigDecimal("20").compareTo((BigDecimal)service.needs(1L).get(0).get("shortage")));cover.set(15);assertEquals(0,new BigDecimal("5").compareTo((BigDecimal)service.needs(1L).get(0).get("purchaseSuggestion"))); + cover.set(0);stock.set(10);var rows=service.shortages(List.of(1L,2L));assertEquals(2,rows.size());assertEquals(0,new BigDecimal("10").compareTo((BigDecimal)rows.get(0).get("allocatedStock")));assertEquals(0,BigDecimal.ZERO.compareTo((BigDecimal)rows.get(1).get("allocatedStock")));assertEquals(0,new BigDecimal("30").compareTo(rows.stream().map(r->(BigDecimal)r.get("purchaseSuggestion")).reduce(BigDecimal.ZERO,BigDecimal::add))); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseArrivalRulesTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseArrivalRulesTest.java new file mode 100644 index 0000000..95118e9 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseArrivalRulesTest.java @@ -0,0 +1,22 @@ +package com.ruoyi.projectdev; +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.mapper.*; +import com.ruoyi.warehouse.service.impl.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +class PurchaseArrivalRulesTest { + @Test void ordinaryArrivalAndAcceptanceRequireConfirmedPrice(){ + var service=new PurchaseArrivalServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class); + ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals); + var request=new PurchaseRequest();request.setId(1L);request.setPriceLocked(false);request.setFinalUnitPrice(BigDecimal.TEN);request.setPurchaseStatus(0); + when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request); + var arrival=new PurchaseArrival();arrival.setId(2L);arrival.setPurchaseRequestId(1L);arrival.setArrivalQuantity(BigDecimal.ONE);arrival.setAcceptanceStatus(0); + assertThrows(ServiceException.class,()->service.insertPurchaseArrival(arrival));verify(arrivals,never()).insertPurchaseArrival(any()); + when(arrivals.selectPurchaseArrivalByIdForUpdate(2L)).thenReturn(arrival);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1); + assertThrows(ServiceException.class,()->service.acceptPurchaseArrival(2L,acceptance)); + } +} 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 3904e66..df2e0f7 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java @@ -74,8 +74,10 @@ class PurchaseSheetDatabaseTest { f.service.confirm(locked.getBatch().getId(),locked.getVersion()); assertEquals(2,f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Integer.class,locked.getRows().get(0).getId(),locked.getRows().get(1).getId())); locked.getRows().get(0).setQuantity(new BigDecimal("10")); - assertThrows(ServiceException.class,()->f.service.save(locked)); - assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("3"))); + PurchaseSheet maintained=f.service.save(locked); + assertTrue(maintained.getRows().get(0).getPriceLocked()); + assertEquals(0,maintained.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("12.50"))); + assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("10"))); } finally { status.setRollbackOnly(); } return null; }); @@ -160,6 +162,31 @@ class PurchaseSheetDatabaseTest { assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name)); } + @Test void confirmedTransfersKeepFeesAndRejectChangedSupplierOrExistingArrival()throws Exception { + Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) { + security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test"); + new TransactionTemplate(f.manager).execute(status->{try { + var saved=f.service.save(f.draft());var locked=f.service.confirm(saved.getBatch().getId(),saved.getVersion());var row=locked.getRows().get(0);Long supplier=locked.getBatch().getSupplierId(); + f.jdbc.update("insert into purchase_batch(batch_no,batch_name,supplier_id,purchase_status,business_date) values(?,?,?,1,current_date())",f.name+"-target",f.name+"-target",supplier);Long target=f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-target"); + var raw=new PurchaseBatchServiceImpl();f.set(raw,"purchaseBatchMapper",f.batchMapper);f.set(raw,"purchaseRequestMapper",f.purchaseRows);f.set(raw,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));var lock=new CatalogWriteLock();f.set(lock,"jdbc",f.jdbc);f.set(raw,"catalogWriteLock",lock);var service=f.proxy(raw); + var command=new PurchaseBatchAssignRequest();command.setRequestIds(new Long[]{row.getId()});command.setBatchId(target);assertEquals(1,service.assignPurchaseBatch(command));var moved=f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId());assertEquals(target,moved.getPurchaseBatchId());assertTrue(moved.getPriceLocked());assertEquals(row.getLockedAmount(),moved.getLockedAmount()); + f.jdbc.update("insert into supplier_info(name,active) values(?,1)",f.name+"-other");Long other=f.jdbc.queryForObject("select id from supplier_info where name=?",Long.class,f.name+"-other");f.jdbc.update("insert into purchase_batch(batch_no,supplier_id,purchase_status) values(?,?,1)",f.name+"-wrong",other);command.setBatchId(f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-wrong"));assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId()); + f.jdbc.update("insert into purchase_arrival(arrival_no,purchase_request_id,arrival_quantity,arrival_date,acceptance_status,create_by) values(?,?,2,current_date(),1,'sheet-rollback-test')","ARR-"+UUID.randomUUID(),row.getId());f.jdbc.update("update purchase_request set purchase_status=4 where id=?",row.getId());var appended=f.service.load(target);appended.getRows().get(0).setQuantity(new BigDecimal("3"));var updated=f.service.save(appended);assertEquals(3,updated.getRows().get(0).getPurchaseStatus());assertEquals(0,new BigDecimal("3.75").compareTo(updated.getRows().get(0).getLockedAmount()));command.setBatchId(locked.getBatch().getId());assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId()); + } finally{status.setRollbackOnly();}return null;}); + } + assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_no like ?",Integer.class,f.name+"%")); + } + @Test void preparingUnbatchedRowsIsAtomicAndPreservesIds()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 initial=f.service.save(f.draft());Long[] ids=initial.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new); + for(Long id:ids)f.jdbc.update("update purchase_request set purchase_batch_id=null,purchase_batch_no=null where id=?",id); + var prepared=f.service.prepare(ids);assertEquals(2,prepared.getRows().size());assertNull(prepared.getBatch().getSupplierId());assertEquals(Set.of(ids),new HashSet<>(prepared.getRows().stream().map(PurchaseRequest::getId).toList())); + long count=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class);assertThrows(ServiceException.class,()->f.service.prepare(ids));assertEquals(count,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); + }); + } + } + private static class Fixture { final String name="SHEET-CHECK-"+UUID.randomUUID(); final JdbcTemplate jdbc; @@ -168,6 +195,7 @@ class PurchaseSheetDatabaseTest { final ProjectInfoMapper projects; final ProjectBudgetMapper budgets; final PurchaseRequestMapper purchaseRows; + final PurchaseBatchMapper batchMapper; Fixture() throws Exception { Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent(); Map yaml;try(var input=Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))){yaml=new Yaml().load(input);} @@ -186,6 +214,7 @@ class PurchaseSheetDatabaseTest { projects=session.getMapper(ProjectInfoMapper.class);budgets=session.getMapper(ProjectBudgetMapper.class); var purchases=session.getMapper(PurchaseRequestMapper.class);var catalog=session.getMapper(ProductInfoMapper.class); purchaseRows=purchases; + batchMapper=session.getMapper(PurchaseBatchMapper.class); IProjectInfoService projectAccess=mock(IProjectInfoService.class); IPurchaseOperationLogService logs=mock(IPurchaseOperationLogService.class); CatalogWriteLock lock=new CatalogWriteLock();set(lock,"jdbc",jdbc); @@ -200,7 +229,7 @@ class PurchaseSheetDatabaseTest { 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)); 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); service=proxy(target); + set(target,"batchNumbers",numbers);set(target,"operationLogs",logs); service=proxy(target); } PurchaseSheet draft() { jdbc.update("insert into supplier_info(name,active,create_by) values(?,1,'sheet-rollback-test')",name); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/SupplierQuoteImportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/SupplierQuoteImportTest.java new file mode 100644 index 0000000..860c958 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/SupplierQuoteImportTest.java @@ -0,0 +1,21 @@ +package com.ruoyi.projectdev; +import java.math.BigDecimal; +import java.io.*; +import java.util.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.Test; +import com.ruoyi.web.controller.warehouse.SupplierQuoteImport; +import com.ruoyi.warehouse.domain.*; +import static org.junit.jupiter.api.Assertions.*; +class SupplierQuoteImportTest { + private PurchaseSheet sheet(){var s=new PurchaseSheet();var b=new PurchaseBatch();b.setBatchNo("CG2026100001");s.setBatch(b);var rows=new ArrayList();for(long i=1;i<=3;i++){var r=new PurchaseRequest();r.setId(i);r.setProductCode(i==3?"WP2":"WP1");r.setMaterialName("物品"+i);r.setPurchaseStatus(0);rows.add(r);}s.setRows(rows);return s;} + private byte[] file(String[][] data)throws Exception{try(var b=new XSSFWorkbook();var out=new ByteArrayOutputStream()){var s=b.createSheet();String[] h={"采购批次","物品编码","最终单价"};var header=s.createRow(0);for(int i=0;ir.get("error")!=null)); + } +} 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 6285299..a2a28f7 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 @@ -29,10 +29,10 @@ public class ProductionService { @Autowired private ProductInfoMapper items; @Autowired private IProjectInfoService projects; private static final BigDecimal ZERO=BigDecimal.ZERO; - private static final String TASK_SELECT="select t.*,p.project_name,i.product_name item_name,i.product_code,i.brand,i.spec,i.unit,b.version_tag,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 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 (? 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 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> costHistory(Long itemId,Long bomId,Long projectId){ var result=new ArrayList>(); for(var row:tasks(projectId,itemId)){ @@ -44,12 +44,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){ + 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); + 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("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=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;} @Transactional public Map save(ProductionCommand c){ journal.lockInventory();quantity(c.quantity);text(c.remark,500);LocalDate date=c.date==null?LocalDate.now():c.date; - if(c.id!=null){var t=task(c.id);if("SETTLED".equals(t.get("status")))throw fail("已结算任务不能修改;如需调整,请新建任务");if(c.version==null||c.version.intValue()!=l(t,"version").intValue())throw fail("任务已变化,请刷新");if(c.quantity.compareTo(n(t,"good_quantity").add(n(t,"scrap_quantity")))<0)throw fail("计划数量不能低于已经合格及报废数量");db.update("update production_task set planned_quantity=?,business_date=?,remark=?,version=version+1 where id=?",c.quantity,date,c.remark,c.id);return task(c.id);} + if(c.id!=null){var t=task(c.id);if(!"OPEN".equals(t.get("status")))throw fail("当前任务不能修改,请先继续生产");if(c.version==null||c.version.intValue()!=l(t,"version").intValue())throw fail("任务已变化,请刷新");if(c.quantity.compareTo(n(t,"good_quantity").add(n(t,"scrap_quantity")))<0)throw fail("计划数量不能低于已经合格及报废数量");boolean identityChanged=c.projectId!=null&&!Objects.equals(c.projectId,l(t,"project_id")) || c.itemId!=null&&!Objects.equals(c.itemId,l(t,"item_id")) || c.bomId!=null&&!Objects.equals(c.bomId,l(t,"bom_id"))&&!Objects.equals(c.bomId,l(t,"source_bom_id")); + if(identityChanged){ + if(!Long.valueOf(1).equals(l(t,"editable_identity")) || l(t,"parent_task_id")!=null)throw fail("已有业务或下级关联,不能更换项目、产品或BOM"); + projects.requireProjectAccess(c.projectId);var source=boms.get(c.bomId);if(!Objects.equals(source.getItemId(),c.itemId))throw fail("产品与BOM不一致"); + var snapshot=boms.snapshotForTask(c.bomId,c.projectId,c.id);db.update("update production_task set project_id=?,item_id=?,source_bom_id=?,bom_id=? where id=?",c.projectId,c.itemId,c.bomId,snapshot.getId(),c.id); + } + db.update("update production_task set planned_quantity=?,business_date=?,remark=?,version=version+1 where id=?",c.quantity,date,c.remark,c.id);return task(c.id);} key(c.key);projects.requireProjectAccess(c.projectId);var source=boms.get(c.bomId);if(!Objects.equals(source.getItemId(),c.itemId))throw fail("产品与BOM不一致"); if(c.parentTaskId!=null){var parent=task(c.parentTaskId);if(!Objects.equals(c.projectId,l(parent,"project_id")))throw fail("子任务须在父任务项目中");boolean found=boms.get(l(parent,"bom_id")).getLines().stream().anyMatch(line->Objects.equals(line.getItemId(),c.itemId)&&Objects.equals(line.getChildBomId(),c.bomId));if(!found)throw fail("请选择父任务用料对应的下级BOM");} String no="TASK-"+UUID.nameUUIDFromBytes(c.key.getBytes(java.nio.charset.StandardCharsets.UTF_8));var duplicate=db.queryForList("select * from production_task where task_no=?",no); @@ -58,10 +73,56 @@ public class ProductionService { Long id=insert("insert into production_task(task_no,project_id,item_id,source_bom_id,parent_task_id,planned_quantity,business_date,remark,create_by) values(?,?,?,?,?,?,?,?,?)",no,c.projectId,c.itemId,c.bomId,c.parentTaskId,c.quantity,date,c.remark,actor()); 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); } - public List> needs(Long id){var t=task(id);List> rows=new ArrayList<>();for(var line:boms.get(l(t,"bom_id")).getLines()){ - BigDecimal needed=line.getUnitQuantity().multiply(n(t,"planned_quantity")).setScale(4,RoundingMode.HALF_UP),issued=sum(id,line.getItemId(),"ISSUE"),returned=sum(id,line.getItemId(),"RETURN"),scrap=sum(id,line.getItemId(),"SCRAP_ISSUED");var stock=journal.balance(l(t,"project_id"),line.getItemId());BigDecimal available=stock==null?ZERO:stock.getQuantity(); - var row=new LinkedHashMap();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("shortage",needed.subtract(issued.subtract(returned)).subtract(available).max(ZERO));rows.add(row); - }return rows;} + @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(); + 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); + } + public List> needs(Long id) { + var t=task(id);List> rows=new ArrayList<>(); + // Aggregate each source once per task rather than querying every BOM line. + Map> actions=new HashMap<>(),purchases=new HashMap<>(); + for(var r:db.queryForList("select item_id,sum(case when kind='ISSUE' then quantity else 0 end) issued,sum(case when kind='RETURN' then quantity else 0 end) returned,sum(case when kind='SCRAP_ISSUED' then quantity else 0 end) scrapped from production_action where task_id=? and active=1 group by item_id",id))actions.put(l(r,"item_id"),r); + String purchaseSql="select pr.product_id,sum(case when pr.price_locked=0 then greatest(pr.quantity-coalesce(pa.arrived,0),0) else 0 end) requested,sum(case when pr.price_locked=1 then greatest(pr.quantity-coalesce(pa.arrived,0),0) else 0 end) purchasing,sum(coalesce(pa.pending,0)) pending_acceptance,sum(greatest(coalesce(pa.accepted,0)-coalesce(ir.received,0),0)) pending_receipt from purchase_request pr left join (select purchase_request_id,sum(case when acceptance_status in (0,1) then arrival_quantity-defective_quantity-returned_quantity else 0 end) arrived,sum(case when acceptance_status=0 then arrival_quantity else 0 end) pending,sum(case when acceptance_status=1 then arrival_quantity-defective_quantity-returned_quantity else 0 end) accepted from purchase_arrival group by purchase_request_id) pa on pa.purchase_request_id=pr.id left join (select purchase_request_id,sum(in_num) received from in_record where in_status=1 and receipt_root=0 group by purchase_request_id) ir on ir.purchase_request_id=pr.id where pr.production_task_id=? and pr.del_flag='0' and pr.purchase_status<>5 and pr.historical=0 and pr.purchase_purpose='SELF' group by pr.product_id"; + 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()) { + 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 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("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")); + row.put("shortage",outstanding.subtract(available).max(ZERO));row.put("purchaseSuggestion",outstanding.subtract(available).subtract(coverage).max(ZERO));rows.add(row); + } + return rows; + } + public List> shortages(List ids) { + if(ids==null||ids.isEmpty()||ids.size()>200)throw fail("请选择1至200个生产任务"); + Map stockRemaining=new HashMap<>();List> rows=new ArrayList<>(); + for(Long id:ids.stream().distinct().sorted().toList()) { + 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 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()); + if(n(row,"outstanding").signum()>0)rows.add(row); + } + } + return rows; + } private BigDecimal sum(Long taskId,Long itemId,String kind){return db.queryForObject("select coalesce(sum(quantity),0) from production_action where task_id=? and (? is null or item_id=?) and active=1 and kind=?",BigDecimal.class,taskId,itemId,itemId,kind);} @Transactional public Map perform(ProductionCommand c){ @@ -77,6 +138,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&&"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用料中"); boolean finishedProduct=db.queryForObject("select count(*) from production_product where item_id=? and del_flag='0'",Integer.class,c.itemId)>0; @@ -125,7 +187,7 @@ public class ProductionService { @Transactional public void receiptRevoked(Long eventId){db.update("update production_task set version=version+1 where id in (select task_id from production_action where cost_event_id=? and kind='OUTPUT' and active=1)",eventId);db.update("update production_action set active=0,void_reason='撤销入库',void_by=?,void_time=current_timestamp where cost_event_id=? and kind='OUTPUT'",actor(),eventId);} @Transactional public Map settle(Long id){return settle(id,null);} @Transactional public Map settle(Long id,Integer version){ - journal.lockInventory();var t=task(id);checkTaskVersion(t,version); + journal.lockInventory();var t=task(id);checkTaskVersion(t,version);if("CANCELLED".equals(t.get("status")))throw fail("任务已删除,不能结算"); db.update("update production_task set status='SETTLED',version=version+1 where id=?",id);recalculateSettled();return detail(id); } /** Resume without deleting quantities, settlements or inventory cost revisions. */ @@ -154,13 +216,13 @@ public class ProductionService { }if(!changed)return; }throw fail("任务成本存在循环依赖,无法完成结算,请检查相互领料记录"); } - private BigDecimal material(Long taskId,Long itemId){var rows=db.queryForList("select a.kind,e.effective_cost from production_action a join inventory_cost_event e on e.id=a.cost_event_id where a.task_id=? and a.active=1 and a.kind in ('ISSUE','RETURN') and (? is null or a.item_id=?)",taskId,itemId,itemId);BigDecimal total=ZERO;for(var row:rows){BigDecimal value=nullable(row,"effective_cost");if(value==null)return null;total="RETURN".equals(row.get("kind"))?total.subtract(value):total.add(value);}return total.setScale(6);} + private BigDecimal material(Long taskId,Long itemId){var rows=db.queryForList("select a.kind,e.effective_cost from production_action a join inventory_cost_event e on e.id=a.cost_event_id where a.task_id=? and a.active=1 and a.kind in ('ISSUE','RETURN') and (? is null or a.item_id=?)",taskId,itemId,itemId);if(rows.isEmpty()&&itemId==null&&!boms.get(l(task(taskId),"bom_id")).getLines().isEmpty())return null;BigDecimal total=ZERO;for(var row:rows){BigDecimal value=nullable(row,"effective_cost");if(value==null)return null;total="RETURN".equals(row.get("kind"))?total.subtract(value):total.add(value);}return total.setScale(6);} public Map reference(Long bomId,Long projectId,Long taskId){if(taskId!=null){var t=task(taskId);if(!Objects.equals(bomId,l(t,"bom_id"))||!Objects.equals(projectId,l(t,"project_id")))throw fail("任务、项目与BOM不一致");}return reference(bomId,projectId,taskId,new HashSet<>());} private Map reference(Long bomId,Long projectId,Long taskId,Set path){if(!path.add(bomId))throw fail("BOM存在循环");var bom=boms.get(bomId);var lines=new ArrayList>();BigDecimal total=ZERO;boolean complete=true; for(var line:bom.getLines()){BigDecimal unit=null,partial=null;String source="缺价"; if(taskId!=null){BigDecimal net=sum(taskId,line.getItemId(),"ISSUE").subtract(sum(taskId,line.getItemId(),"RETURN")),amount=material(taskId,line.getItemId());if(net.signum()>0&&amount!=null){unit=amount.divide(net,6,RoundingMode.HALF_UP);source="任务净领料";}} if(unit==null&&projectId!=null){var balance=journal.balance(projectId,line.getItemId());if(balance!=null&&balance.getQuantity().signum()>0&&balance.getAmount()!=null){unit=balance.getAmount().divide(balance.getQuantity(),6,RoundingMode.HALF_UP);source="项目库存";}} - if(unit==null){boolean selfMade=line.getChildBomId()!=null;var prices=selfMade?db.queryForList("select unit_cost price from production_task where item_id=? and status='SETTLED' and unit_cost is not null order by settled_time desc,id desc limit 1",line.getItemId()):db.queryForList("select final_unit_price price from purchase_request where product_id=? and del_flag='0' and price_locked=1 and purchase_status<>5 and final_unit_price is not null order by coalesce(original_date,create_time) desc,id desc limit 1",line.getItemId());if(!prices.isEmpty()){unit=nullable(prices.get(0),"price");source=selfMade?"最近结算成本":"最近锁价采购";}} + if(unit==null){boolean selfMade=line.getChildBomId()!=null;var prices=selfMade?db.queryForList("select t.unit_cost price from production_task t where t.item_id=? and t.status='SETTLED' and t.unit_cost is not null and (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')) order by t.settled_time desc,t.id desc limit 1",line.getItemId()):db.queryForList("select final_unit_price price from purchase_request where product_id=? and del_flag='0' and price_locked=1 and purchase_status<>5 and final_unit_price is not null order by coalesce(original_date,create_time) desc,id desc limit 1",line.getItemId());if(!prices.isEmpty()){unit=nullable(prices.get(0),"price");source=selfMade?"最近结算成本":"最近锁价采购";}} if(unit==null&&line.getChildBomId()!=null){var child=reference(line.getChildBomId(),projectId,null,new HashSet<>(path));if(Boolean.TRUE.equals(child.get("complete"))){unit=(BigDecimal)child.get("amount");source="下级BOM";}else{partial=(BigDecimal)child.get("amount");source="下级BOM已知部分(缺价)";}} BigDecimal amount=unit==null?(partial==null?null:partial.multiply(line.getUnitQuantity()).setScale(6,RoundingMode.HALF_UP)):unit.multiply(line.getUnitQuantity()).setScale(6,RoundingMode.HALF_UP);if(unit==null)complete=false;if(amount!=null)total=total.add(amount);var row=new LinkedHashMap();row.put("itemId",line.getItemId());row.put("itemName",line.getItemName());row.put("unitQuantity",line.getUnitQuantity());row.put("unitCost",unit);row.put("amount",amount);row.put("source",source);row.put("complete",unit!=null);lines.add(row); }var result=new LinkedHashMap();result.put("amount",total);result.put("complete",complete);result.put("lines",lines);return result; @@ -172,7 +234,7 @@ public class ProductionService { result.put("openTasks",db.queryForObject("select count(*) from production_task where project_id=? and status='OPEN'",Long.class,projectId)); result.put("outstandingLoans",db.queryForObject("select count(*) from project_loan l 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 where l.active=1 and (l.lender_project_id=? or l.borrower_project_id=?) and l.quantity>l.historical_returned+coalesce(r.returned_quantity,0)",Long.class,projectId,projectId)); result.put("remainingStocks",db.queryForObject("select count(*) from project_stock_balance where project_id=? and quantity>0",Long.class,projectId)); - result.put("tasks",tasks(projectId,null));result.put("actions",actions(projectId,null));return result; + return result; } private Long insert(String sql,Object... values){var holder=new GeneratedKeyHolder();db.update(connection->{var statement=connection.prepareStatement(sql,java.sql.Statement.RETURN_GENERATED_KEYS);for(int i=0;i row,String key){Object value=row.get(key);return value==null?null:value instanceof Boolean b?(b?1L:0L):((Number)value).longValue();} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java index f9e1f65..e9ff0ae 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java @@ -28,6 +28,12 @@ public class InRecord extends BaseEntity private Long purchaseRequestId; private String sourceKind; + private String keyword; + private Long supplierId; + private Long purchaseBatchId; + public Long getPurchaseBatchId(){return purchaseBatchId;}public void setPurchaseBatchId(Long v){purchaseBatchId=v;} + public String getKeyword(){return keyword;}public void setKeyword(String v){keyword=v;} + public Long getSupplierId(){return supplierId;}public void setSupplierId(Long v){supplierId=v;} private String purchaseProjectName; private String purchaseBatchNo; public String getSourceKind(){return sourceKind;} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java index 4c46cf1..12c1138 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java @@ -17,6 +17,15 @@ public class PurchaseBatch extends BaseEntity private Integer openCount; private Integer pendingCount; private Integer partialCount; + private Integer arrivableCount; + public Integer getArrivableCount(){return arrivableCount;}public void setArrivableCount(Integer v){arrivableCount=v;} + private String keyword; + private String progress; + private java.time.LocalDate beginDate,endDate; + public String getKeyword(){return keyword;}public void setKeyword(String v){keyword=v;} + public String getProgress(){return progress;}public void setProgress(String v){progress=v;} + public java.time.LocalDate getBeginDate(){return beginDate;}public void setBeginDate(java.time.LocalDate v){beginDate=v;} + public java.time.LocalDate getEndDate(){return endDate;}public void setEndDate(java.time.LocalDate v){endDate=v;} public Integer getPartialCount(){return partialCount;} public void setPartialCount(Integer value){partialCount=value;} public Long getProjectId(){return projectId;} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java index b3d14be..7e78db0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java @@ -20,6 +20,8 @@ public class PurchaseRequest extends BaseEntity @Excel(name="采购用途",readConverterExp="SELF=本项目使用,REPAY=归还借用") private String purchasePurpose; private Long loanId; private Long productionTaskId; + private String productionTaskNo; + public String getProductionTaskNo(){return productionTaskNo;}public void setProductionTaskNo(String v){productionTaskNo=v;} private Boolean historical; private java.time.LocalDate originalDate; public Boolean getHistorical(){return historical;} @@ -29,6 +31,9 @@ public class PurchaseRequest extends BaseEntity private Long supplierId; private String supplierName; private Boolean notArrived; + private Boolean arrivalReady; + public Boolean getArrivalReady(){return arrivalReady;} + public void setArrivalReady(Boolean value){arrivalReady=value;} private Boolean unbatched; public Boolean getUnbatched(){return unbatched;} public void setUnbatched(Boolean value){unbatched=value;} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java index 5cb4842..117744b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java @@ -54,6 +54,9 @@ public class StockInfo extends BaseEntity /** 是否为产品档案中启用的成品。只有成品库存可以办理成品报废和交付。 */ private Boolean finishedProduct; + private Long excludeProjectId; + public Long getExcludeProjectId() { return excludeProjectId; } + public void setExcludeProjectId(Long excludeProjectId) { this.excludeProjectId = excludeProjectId; } private Boolean includeZero = false; public Boolean getIncludeZero() { return includeZero; } public void setIncludeZero(Boolean includeZero) { this.includeZero = includeZero; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java index 998eae3..34da5cd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java @@ -5,6 +5,7 @@ import com.ruoyi.warehouse.domain.ProductInfo; public interface ProductInfoMapper { + java.util.List selectProductVariants(@org.apache.ibatis.annotations.Param("name") String name); public List selectProductInfoList(ProductInfo productInfo); public List selectProductInfoAll(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseBatchMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseBatchMapper.java index 4a3f1f6..2906805 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseBatchMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseBatchMapper.java @@ -10,6 +10,7 @@ public interface PurchaseBatchMapper List selectPurchaseBatchOptions(@Param("keyword") String keyword); List selectPurchaseBatchFilterOptions(@Param("keyword") String keyword); PurchaseBatch selectPurchaseBatchById(Long id); + PurchaseBatch selectPurchaseBatchForUpdate(Long id); PurchaseBatch selectPurchaseBatchByNo(String batchNo); int insertPurchaseBatch(PurchaseBatch batch); int updatePurchaseBatch(PurchaseBatch batch); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseArrivalService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseArrivalService.java index 1260df8..9d2c206 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseArrivalService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseArrivalService.java @@ -9,6 +9,7 @@ public interface IPurchaseArrivalService { List selectPurchaseArrivalList(Long purchaseRequestId); int insertPurchaseArrival(PurchaseArrival arrival); + int importAcceptedArrival(PurchaseArrival arrival); int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest request); int revokePurchaseArrivalAcceptance(Long id, PurchaseArrivalRevokeRequest request); int deletePurchaseArrival(Long id); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/HomeSummaryService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/HomeSummaryService.java new file mode 100644 index 0000000..a1ad6f0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/HomeSummaryService.java @@ -0,0 +1,50 @@ +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 org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.utils.SecurityUtils; + +/** SQL counts + six preview rows per queue. Never send full business ledgers to the homepage. */ +@Service public class HomeSummaryService { + @Autowired private JdbcTemplate db; + @Autowired private PendingReceiptService pending; + private boolean can(String... codes){return SecurityUtils.isAdmin()||Arrays.stream(codes).anyMatch(SecurityUtils::hasPermi);} + private Map queue(String key,String label,String action,String sql,List args){var q=new LinkedHashMap();q.put("key",key);q.put("label",label);q.put("action",action);q.put("count",db.queryForObject("select count(*) from ("+sql+") counted",Long.class,args.toArray()));q.put("rows",db.queryForList(sql+" limit 6",args.toArray()));return q;} + public List> projects(String keyword){if(!can("project:project:list"))return List.of();return db.queryForList("select id,project_name projectName,project_code projectCode from project_info where del_flag='0' and (? is null or concat_ws(' ',project_name,project_code) like ?) order by id desc limit 50",keyword,keyword==null?null:"%"+keyword+"%");} + @Transactional(readOnly=true) public Map summary(Long projectId){ + var result=new LinkedHashMap();var overview=new LinkedHashMap();var warehouse=new LinkedHashMap();List> queues=new ArrayList<>(); + if(can("project:project:list")){ + var p=db.queryForMap("select count(case when p.project_code<>'LEGACY' then 1 end) projectCount,coalesce(sum(p.total_amount),0) budget,coalesce(sum(c.locked),0) locked,coalesce(sum(p.total_amount-coalesce(c.locked,0)),0) remaining,count(distinct p.currency) currencies,min(p.currency) currency,sum(case when p.total_amount5 and price_locked=1 group by project_id)c on c.project_id=p.id where p.del_flag='0' and (? is null or p.id=?)",projectId,projectId);overview.putAll(p);if(p.get("currency")==null)overview.put("currency","CNY"); + boolean mixed=((Number)p.get("currencies")).intValue()>1;overview.put("mixedCurrency",mixed);double budget=((Number)p.get("budget")).doubleValue();overview.put("budgetRate",!mixed&&budget>0?((Number)p.get("locked")).doubleValue()/budget*100:null);if(mixed)for(String field:List.of("budget","locked","remaining"))overview.put(field,null); + var statuses=new ArrayList>();for(int i=0;i<4;i++){final int value=i;long count=db.queryForObject("select count(*) from project_info where del_flag='0' and project_code<>'LEGACY' and project_status=? and (? is null or id=?)",Long.class,i,projectId,projectId);statuses.add(Map.of("label",List.of("立项","进行中","结题","终止").get(value),"value",value,"count",count));}overview.put("statuses",statuses); + result.put("projects",projects(null)); + } + if(can("warehouse:purchase:list","warehouse:purchase:manage")){ + String base=" from purchase_request pr left join project_info p on p.id=pr.project_id left join purchase_batch b on b.id=pr.purchase_batch_id left join supplier_info s on s.id=b.supplier_id left join (select purchase_request_id,sum(case when acceptance_status=0 then arrival_quantity else 0 end) pending,sum(case when acceptance_status in (0,1) then arrival_quantity-defective_quantity-returned_quantity else 0 end) arrived from purchase_arrival group by purchase_request_id)a on a.purchase_request_id=pr.id where pr.del_flag='0' and pr.historical=0 and pr.purchase_status<>5 and (? is null or pr.project_id=?)"; + List args=Arrays.asList(projectId,projectId); + String groupBase=base.replace("(? is null or pr.project_id=?)","(? is null or pr.project_id=? and pr.purchase_batch_id is null or exists(select 1 from purchase_request member where member.purchase_batch_id=pr.purchase_batch_id and member.project_id=? and member.del_flag=\'0\'))"); + List groupArgs=Arrays.asList(projectId,projectId,projectId); + String grouped="select coalesce(cast(pr.purchase_batch_id as char),concat('unbatched-',min(pr.project_id),'-',coalesce(min(b.supplier_id),0))) id,'purchase' source,pr.purchase_batch_id purchaseBatchId,max(pr.purchase_batch_no) purchaseBatchNo,case when count(distinct pr.project_id)=1 then min(pr.project_id) else null end projectId,group_concat(distinct p.project_name separator '、') project,coalesce(max(b.batch_name),max(pr.purchase_batch_no),'未分批采购') item,coalesce(max(pr.purchase_batch_no),'未分批采购') record,coalesce(max(s.name),'—') supplier,concat(count(*),' 项明细') quantityText,substring_index(group_concat(distinct pr.material_name separator '、'),'、',2) detail,min(pr.create_time) date,sum(case when pr.price_locked=0 and pr.final_unit_price is null then 1 else 0 end) unpriced,sum(case when pr.price_locked=0 then 1 else 0 end) unlocked,sum(case when pr.price_locked=1 and b.supplier_id is not null and coalesce(a.pending,0)>0 then 1 else 0 end) pending,sum(case when pr.price_locked=1 and b.supplier_id is not null and pr.quantity>coalesce(a.arrived,0) then 1 else 0 end) remaining"+groupBase+" group by pr.purchase_batch_id,case when pr.purchase_batch_id is null then pr.project_id end,case when pr.purchase_batch_id is null then b.supplier_id end"; + for(var def:List.of(new String[]{"quote","待补报价","录入报价","unpriced>0"},new String[]{"confirm","待确认采购","确认采购","unpriced=0 and unlocked>0"},new String[]{"acceptance","待验收","去验收","pending>0"},new String[]{"arrival","未到齐","查看到货","remaining>0"})){var q=queue(def[0],def[1],def[2],grouped+" having "+def[3]+" order by date",groupArgs);for(var r:(List>)q.get("rows"))r.put("progress",r.get("unpriced")+" 项待报价 · "+r.get("pending")+" 项待验收 · "+r.get("remaining")+" 项未到齐");queues.add(q);} + overview.putAll(db.queryForMap("select count(*) purchaseCount,count(distinct pr.purchase_batch_id) batchCount,coalesce(sum(case when pr.purchase_batch_id is null then 1 else 0 end),0) unbatchedCount"+base+" and (pr.price_locked=0 or coalesce(a.pending,0)>0 or pr.quantity>coalesce(a.arrived,0))",args.toArray())); + } + if(can("warehouse:in:list")){ + var filter=new com.ruoyi.warehouse.domain.InRecord();filter.setSourceProjectId(projectId);var grouped=pending.page(filter,1,6);var q=new LinkedHashMap();q.put("key","receipt");q.put("label","待入库");q.put("action","去入库");q.put("unit","批");q.put("count",grouped.get("total"));q.put("itemCount",grouped.get("itemTotal"));var previews=new ArrayList>(); + for(var group:(List>)grouped.get("rows")){var row=new LinkedHashMap();row.put("id",group.get("key"));row.put("source","receipt");row.put("sourceGroup",group.get("key"));row.put("record",group.get("title"));row.put("item",group.get("title"));row.put("project",group.get("projects"));row.put("sourceProjectId",projectId);row.put("supplier",group.get("supplierName"));row.put("quantityText",group.get("recordCount")+" 项待入库");row.put("progress","选择库区,整组办理");previews.add(row);} + q.put("rows",previews);queues.add(q);warehouse.put("receiptCount",grouped.get("itemTotal"));warehouse.put("receiptGroups",grouped.get("total")); + } + if(can("project:project:list","warehouse:stock:list")){ + String production="select t.id,'task' source,t.project_id project_id,t.task_no record,p.project_name project,i.product_name item,'—' supplier,t.create_time date,'产出已完成,待核对用料和结算' progress 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 (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 from production_action where active=1 group by task_id)a on a.task_id=t.id where t.status='OPEN' and t.planned_quantity>0 and coalesce(a.good,0)+coalesce(a.scrap,0)>=t.planned_quantity and not exists(select 1 from production_task c where c.parent_task_id=t.id and c.status='OPEN') and (? is null or t.project_id=?) order by t.id"; + queues.add(queue("production","待结算生产","核对结算",production,Arrays.asList(projectId,projectId)));overview.put("productionCount",db.queryForObject("select count(*) from production_task where status='OPEN' and (? is null or project_id=?)",Long.class,projectId,projectId)); + String loan="select l.id,'loan' source,l.borrower_project_id borrowerProjectId,l.item_id itemId,l.loan_no record,p.project_name project,i.product_name item,'—' supplier,l.create_time date,concat('待还 ',l.quantity-coalesce(l.historical_returned,0)-coalesce(r.returned,0),' ',i.unit) quantityText,'借用未归还' progress from project_loan l join project_info p on p.id=l.borrower_project_id join product_info i on i.id=l.item_id left join(select loan_id,sum(quantity) returned from project_loan_return where active=1 group by loan_id)r on r.loan_id=l.id where l.active=1 and l.quantity>coalesce(l.historical_returned,0)+coalesce(r.returned,0) and (? is null or l.borrower_project_id=? or l.lender_project_id=?) order by l.id"; + queues.add(queue("loan","未归还借用","查看借还",loan,Arrays.asList(projectId,projectId,projectId))); + } + if(can("warehouse:stock:list"))warehouse.put("stockTotal",db.queryForObject("select count(*) from project_stock_balance where quantity>0 and (? is null or project_id=?)",Long.class,projectId,projectId)); + if(can("warehouse:check:list"))warehouse.put("pendingCheck",db.queryForObject("select count(*) from stock_check_record where check_status=0 and (? is null or project_id=?)",Long.class,projectId,projectId)); + if(can("warehouse:out:list"))warehouse.put("outTotal",db.queryForObject("select count(*) from out_record where (? is null or usage_project_id=?)",Long.class,projectId,projectId)); + result.put("overview",overview);result.put("warehouse",warehouse);result.put("queues",queues);return result; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java index 560e81a..76e0fbb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java @@ -49,7 +49,7 @@ import com.ruoyi.warehouse.service.*; Long batch=insert("insert into purchase_batch(batch_no,batch_name,purchase_status,progress_remark,supplier_id,business_date,create_by,create_time) values(?,?,1,?,?,?,?,current_timestamp)",businessNumbers.reserve("CG",row.date,"history:"+row.sourceKey),row.sourceKey,row.remark,r.supplier,row.date,SecurityUtils.getUsername()); id=null; if(received.signum()>0){id=purchase(row,r,received,batch,true);} - if(remaining.signum()>0){related=purchase(row,r,remaining,batch,false);if(accepted.signum()>0){var arrival=new PurchaseArrival();arrival.setPurchaseRequestId(related);arrival.setArrivalQuantity(accepted);arrival.setArrivalDate(java.sql.Date.valueOf(row.date));arrival.setRequestKey("HISTORY:"+UUID.nameUUIDFromBytes(row.sourceKey.getBytes(java.nio.charset.StandardCharsets.UTF_8)));arrivals.insertPurchaseArrival(arrival);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1);acceptance.setDefectiveQuantity(BigDecimal.ZERO);arrivals.acceptPurchaseArrival(arrival.getId(),acceptance);}} + if(remaining.signum()>0){related=purchase(row,r,remaining,batch,false);if(accepted.signum()>0){var arrival=new PurchaseArrival();arrival.setPurchaseRequestId(related);arrival.setArrivalQuantity(accepted);arrival.setArrivalDate(java.sql.Date.valueOf(row.date));arrival.setRequestKey("HISTORY:"+UUID.nameUUIDFromBytes(row.sourceKey.getBytes(java.nio.charset.StandardCharsets.UTF_8)));arrivals.importAcceptedArrival(arrival);}} if(id==null){id=related;related=null;} } db.update("insert into initialization_record(kind,source_key,content_hash,business_id,related_id,create_by) values(?,?,?,?,?,?)",kind,row.sourceKey,hash,id,related,SecurityUtils.getUsername()); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PendingReceiptService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PendingReceiptService.java new file mode 100644 index 0000000..1c7cfb4 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PendingReceiptService.java @@ -0,0 +1,30 @@ +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.exception.ServiceException; +import com.ruoyi.warehouse.domain.InRecord; +import com.ruoyi.warehouse.mapper.InRecordMapper; +/** Paginate source groups, then read only the group the operator opens. */ +@Service public class PendingReceiptService { + @Autowired private JdbcTemplate db; + @Autowired private InRecordMapper records; + public Map page(InRecord q,int page,int size){ + var args=new ArrayList();var where=new StringBuilder(" where ir.in_status=0"); + if(q.getPurchaseBatchId()!=null){where.append(" and pr.purchase_batch_id=?");args.add(q.getPurchaseBatchId());}if(q.getProductionTaskId()!=null){where.append(" and ir.production_task_id=?");args.add(q.getProductionTaskId());} + if(q.getSourceProjectId()!=null){where.append(" and ir.source_project_id=?");args.add(q.getSourceProjectId());}if(q.getSupplierId()!=null){where.append(" and pb.supplier_id=?");args.add(q.getSupplierId());} + for(var filter:List.of(new String[]{"ir.in_no",Objects.toString(q.getInNo(),"")},new String[]{"concat_ws(' ',ir.source_no,pr.purchase_batch_no)",Objects.toString(q.getSourceNo(),"")},new String[]{"i.product_name",Objects.toString(q.getProductName(),"")},new String[]{"i.brand",Objects.toString(q.getBrand(),"")},new String[]{"i.category",Objects.toString(q.getCategory(),"")},new String[]{"i.spec",Objects.toString(q.getSpec(),"")},new String[]{"ir.in_operator",Objects.toString(q.getInOperator(),"")},new String[]{"concat_ws(' ',ir.in_no,ir.source_no,pr.purchase_batch_no,i.product_name,i.brand,i.spec)",Objects.toString(q.getKeyword(),"")})){if(!filter[1].isBlank()){where.append(" and ").append(filter[0]).append(" like ?");args.add("%"+filter[1]+"%");}} + if(q.getAreaId()!=null){where.append(" and ir.area_id=?");args.add(q.getAreaId());} + if("PURCHASE".equals(q.getSourceKind()))where.append(" and ir.purchase_request_id is not null");if("PRODUCTION".equals(q.getSourceKind()))where.append(" and ir.production_task_id is not null");if("OTHER".equals(q.getSourceKind()))where.append(" and ir.purchase_request_id is null and ir.production_task_id is null"); + String key="case when pr.purchase_batch_id is not null then concat('B:',pr.purchase_batch_id) when ir.production_task_id is not null then concat('P:',ir.production_task_id) else concat('O:',ir.id) end"; + String sql="select "+key+" `key`,coalesce(max(pr.purchase_batch_no),max(ir.source_no),max(ir.in_no)) title,group_concat(distinct p.project_name separator '、') projects,max(s.name) supplierName,count(*) recordCount from in_record ir left join purchase_request pr on pr.id=ir.purchase_request_id left join purchase_batch pb on pb.id=pr.purchase_batch_id left join supplier_info s on s.id=pb.supplier_id left join project_info p on p.id=ir.source_project_id left join product_info i on i.id=ir.product_id"+where+" group by "+key; + long total=db.queryForObject("select count(*) from ("+sql+") grouped",Long.class,args.toArray());var values=new ArrayList<>(args);values.add(Math.max(1,Math.min(100,size)));values.add((Math.max(1,page)-1)*Math.max(1,Math.min(100,size))); + long itemTotal=db.queryForObject("select coalesce(sum(recordCount),0) from ("+sql+") grouped",Long.class,args.toArray());return Map.of("rows",db.queryForList(sql+" order by title limit ? offset ?",values.toArray()),"total",total,"itemTotal",itemTotal); + } + public List group(String key,InRecord q){ + if(key==null||!key.matches("[BPO]:[0-9]{1,18}"))throw new ServiceException("来源编号无效");long id=Long.parseLong(key.substring(2));q.setInStatus(0); + if(key.startsWith("B:"))q.setPurchaseBatchId(id);else if(key.startsWith("P:"))q.setProductionTaskId(id);else {var row=records.selectInRecordById(id);return row!=null&&Integer.valueOf(0).equals(row.getInStatus())?List.of(row):List.of();} + return records.selectInRecordList(q); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java index 8b91515..68430c1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java @@ -58,7 +58,14 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Override @Transactional - public int insertPurchaseArrival(PurchaseArrival arrival) + public int insertPurchaseArrival(PurchaseArrival arrival) { return insertArrival(arrival,false); } + + @Override @Transactional + public int importAcceptedArrival(PurchaseArrival arrival) { + if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:import")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有历史补录权限"); + int rows=insertArrival(arrival,true);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1);acceptance.setDefectiveQuantity(BigDecimal.ZERO);acceptArrival(arrival.getId(),acceptance,true);return rows; + } + private int insertArrival(PurchaseArrival arrival,boolean historicalImport) { journal.lockInventory(); if (arrival == null || arrival.getPurchaseRequestId() == null) @@ -83,6 +90,8 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService { throw new ServiceException("已取消的采购申请不能登记到货"); } + if ((!historicalImport&&!Boolean.TRUE.equals(request.getPriceLocked())) || request.getFinalUnitPrice()==null) throw new ServiceException("请先确认采购并锁定报价,再登记到货"); + if(request.getPurchaseBatchId()==null || database.queryForObject("select count(*) from purchase_batch where id=? and supplier_id is not null",Long.class,request.getPurchaseBatchId())==0) throw new ServiceException("请先选择供应商并确认采购批次"); if (arrival.getArrivalQuantity() == null || arrival.getArrivalQuantity().signum() <= 0 || arrival.getArrivalQuantity().stripTrailingZeros().scale()>4) { throw new ServiceException("到货数量必须大于0"); @@ -115,7 +124,8 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Override @Transactional - public int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest acceptance) + public int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest acceptance) { return acceptArrival(id,acceptance,false); } + private int acceptArrival(Long id,PurchaseArrivalAcceptanceRequest acceptance,boolean historicalImport) { journal.lockInventory(); PurchaseArrival arrival = purchaseArrivalMapper.selectPurchaseArrivalByIdForUpdate(id); @@ -135,6 +145,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService String username = SecurityUtils.getUsername(); PurchaseRequest request = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId()); + if ((!historicalImport&&!Boolean.TRUE.equals(request.getPriceLocked())) || request.getFinalUnitPrice()==null) throw new ServiceException("请先确认采购并锁定报价,再验收"); BigDecimal defective=acceptance.getDefectiveQuantity()==null ? BigDecimal.ZERO : acceptance.getDefectiveQuantity(); if (defective.signum()<0 || defective.stripTrailingZeros().scale()>4 || defective.compareTo(arrival.getArrivalQuantity())>0) throw new ServiceException("不合格数量不能为负数或超过到货数量,最多4位小数"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java index 6ad75d4..69e4ed0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java @@ -29,6 +29,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService private IPurchaseOperationLogService purchaseOperationLogService; @Autowired private SupplierService suppliers; @Autowired private PurchaseBatchNumber batchNumbers; + @Autowired private CatalogWriteLock catalogWriteLock; @Override public List selectPurchaseBatchList(PurchaseBatch batch) @@ -108,7 +109,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService } @Override - @Transactional + @Transactional(isolation=org.springframework.transaction.annotation.Isolation.READ_COMMITTED) public int assignPurchaseBatch(PurchaseBatchAssignRequest request) { checkManager(); @@ -120,6 +121,13 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService { throw new ServiceException("请选择目标采购批次"); } + if(request.getRequestIds().length>2000)throw new ServiceException("一次最多转移2000条明细"); + if(java.util.Arrays.stream(request.getRequestIds()).anyMatch(java.util.Objects::isNull))throw new ServiceException("采购明细编号不能为空"); + request.setRequestIds(java.util.Arrays.stream(request.getRequestIds()).distinct().sorted().toArray(Long[]::new)); + catalogWriteLock.acquire(); + var batchIds=new java.util.TreeSet();batchIds.add(request.getBatchId()); + for(Long id:request.getRequestIds()){var row=purchaseRequestMapper.selectPurchaseRequestById(id,null);if(row==null)throw new ServiceException("采购明细不存在");if(row.getPurchaseBatchId()!=null)batchIds.add(row.getPurchaseBatchId());} + for(Long id:batchIds)purchaseBatchMapper.selectPurchaseBatchForUpdate(id); PurchaseBatch batch = purchaseBatchMapper.selectPurchaseBatchById(request.getBatchId()); if (batch == null) { @@ -132,7 +140,14 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService List requests = new ArrayList<>(); for (Long requestId : request.getRequestIds()) { - requests.add(purchaseRequestMapper.selectPurchaseRequestById(requestId, null)); + var row=purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(requestId); + // The locking projection has no supplier/arrival aggregates. Re-read the full + // projection only after its lock has been acquired and the session cache flushed. + if(row!=null)row=purchaseRequestMapper.selectPurchaseRequestById(requestId,null); + if(row==null||Boolean.TRUE.equals(row.getHistorical())||Integer.valueOf(5).equals(row.getPurchaseStatus()))throw new ServiceException("历史或取消的采购不能转批次"); + if(row.getAcceptedQuantity()!=null&&row.getAcceptedQuantity().signum()>0||row.getPendingArrivalQuantity()!=null&&row.getPendingArrivalQuantity().signum()>0)throw new ServiceException("已有到货的采购请先退回再转批次"); + if(Boolean.TRUE.equals(row.getPriceLocked())&&!java.util.Objects.equals(row.getSupplierId(),batch.getSupplierId()))throw new ServiceException("已确认采购只能转入同一供应商的批次"); + requests.add(row); } purchaseBatchMapper.assignRequests(request.getRequestIds(), batch, SecurityUtils.getUsername()); for (PurchaseRequest purchaseRequest : requests) diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java index 7c170d3..4c34474 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java @@ -174,6 +174,12 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("采购明细已变化,请刷新后重试"); } + if(!Integer.valueOf(5).equals(existing.getPurchaseStatus())&&existing.getQuantity().compareTo(purchaseRequest.getQuantity())!=0){ + BigDecimal accepted=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(existing.getId()); + int progress=accepted.signum()>0?(accepted.compareTo(purchaseRequest.getQuantity())>=0?4:3): + (Integer.valueOf(3).equals(existing.getPurchaseStatus())||Integer.valueOf(4).equals(existing.getPurchaseStatus())?(Boolean.TRUE.equals(existing.getPriceLocked())?1:0):existing.getPurchaseStatus()); + purchaseRequest.setPurchaseStatus(progress);purchaseRequestMapper.updatePurchaseStatus(existing.getId(),progress,existing.getProgressRemark(),SecurityUtils.getUsername()); + } adjustPurchaseCommitment(existing, purchaseRequest); purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "UPDATE", "修改采购申请", buildChangeDetail(existing, purchaseRequest)); 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 e66bd2d..8576737 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 @@ -24,6 +24,7 @@ public class PurchaseSheetService @Autowired private PurchasePriceService prices; @Autowired private SupplierService suppliers; @Autowired private CatalogWriteLock catalogLock; + @Autowired private IPurchaseOperationLogService operationLogs; @Autowired private PurchaseBatchNumber batchNumbers; @Autowired private JdbcTemplate jdbc; @Autowired private ObjectMapper json; @@ -42,6 +43,18 @@ public class PurchaseSheetService return result; } + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) + public PurchaseSheet prepare(Long[] ids) { + 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()); + for(var r:rows)operationLogs.record(r.getId(),r.getRequestNo(),"BATCH_ASSIGN","采购组批","未分批 → "+batch.getBatchNo()); + return load(batch.getId()); + } + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) public PurchaseSheet save(PurchaseSheet sheet) { @@ -106,10 +119,6 @@ public class PurchaseSheetService if (!sameEditable(existing, row)) throw new ServiceException("第" + line + "行已完成或取消,不能修改"); continue; } - if (existing != null && Boolean.TRUE.equals(existing.getPriceLocked())) { - if (!sameEditable(existing, row)) throw new ServiceException("第" + line + "行已确认采购,请在明细维护中按现有退回规则修改"); - continue; - } try { resolveItem(row, items); row.setPurchaseBatchId(batch.getId()); @@ -123,8 +132,8 @@ public class PurchaseSheetService } catch (Exception e) { throw new ServiceException("第" + line + "行:" + e.getMessage()); } } if (!deleted.isEmpty()) { - if (deleted.stream().map(old::get).anyMatch(this::committed)) - throw new ServiceException("已确认采购或已有到货的明细不能在表格中删除"); + if (deleted.stream().map(old::get).anyMatch(r->Boolean.TRUE.equals(r.getHistorical()) || r.getAcceptedQuantity()!=null&&r.getAcceptedQuantity().signum()>0 || r.getPendingArrivalQuantity()!=null&&r.getPendingArrivalQuantity().signum()>0)) + throw new ServiceException("已有到货或历史明细不能删除,请从到货记录先退回"); purchases.deletePurchaseRequestByIds(deleted.toArray(Long[]::new)); } return load(batch.getId()); @@ -138,6 +147,7 @@ public class PurchaseSheetService for (PurchaseRequest row : sheet.getRows()) requests.selectPurchaseRequestByIdForUpdate(row.getId()); sheet = load(id); if (!Objects.equals(expectedVersion, sheet.getVersion())) throw new ServiceException("批次已更新,请刷新后确认"); + if(Integer.valueOf(2).equals(sheet.getBatch().getPurchaseStatus())&&!sheet.getRows().isEmpty()&&sheet.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked())||Boolean.TRUE.equals(r.getHistorical())||Integer.valueOf(5).equals(r.getPurchaseStatus())))return sheet; suppliers.requireActive(sheet.getBatch().getSupplierId()); if (sheet.getRows().isEmpty()) throw new ServiceException("批次没有采购明细"); for (PurchaseRequest row : sheet.getRows()) { diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml index ceb66f3..b2dfe05 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml @@ -60,6 +60,7 @@ left join product_info pi on pi.id = ir.product_id left join project_info project on project.id = ir.source_project_id left join purchase_request purchase on purchase.id=ir.purchase_request_id + left join purchase_batch pb on pb.id=purchase.purchase_batch_id left join project_info purchase_project on purchase_project.id=purchase.project_id left join expense_category ec on ec.id = ir.expense_category_id left join sys_user operator_user on operator_user.user_name = ir.operator @@ -71,6 +72,9 @@ not (ir.receipt_root=1 and ir.in_status=1) and ir.in_no like concat('%', #{inNo}, '%') + and concat_ws(' ',ir.in_no,ir.source_no,purchase.purchase_batch_no,pi.product_name,pi.brand,pi.spec) like concat('%',#{keyword},'%') + and pb.supplier_id=#{supplierId} + and purchase.purchase_batch_id=#{purchaseBatchId} and ir.area_id = #{areaId} and ir.product_id = #{productId} and ir.production_task_id = #{productionTaskId} diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml index fb48886..3a77c7f 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml @@ -36,6 +36,7 @@ + @@ -87,6 +95,7 @@ from purchase_batch where batch_no = #{batchNo} limit 1 + insert into purchase_batch(batch_no, batch_name, purchase_status, progress_remark, create_by, create_time,supplier_id,business_date) values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate(),#{supplierId},#{businessDate}) diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml index e5ba2ed..8a9f82b 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml @@ -6,6 +6,7 @@ + @@ -65,7 +66,7 @@ - select pr.id, pr.request_no, pr.product_id, pr.purchase_batch_id,pb.supplier_id,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name, + select pr.id, pr.request_no, pr.product_id, pr.purchase_batch_id,pb.supplier_id,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,(select task_no from production_task where id=pr.production_task_id) production_task_no, pr.purchase_purpose,pr.loan_id,pr.production_task_id,pr.historical,pr.original_date, pr.project_id, project.project_code, project.project_name, pr.expense_category_id, ec.category_code as expense_category_code, @@ -128,6 +129,7 @@ or applicant_user.nick_name like concat('%', #{applicantName}, '%')) and pr.purchase_status = #{purchaseStatus} + and pr.price_locked=1 and pb.supplier_id is not null and pr.historical=0 and pr.purchase_status<>5 and pr.price_locked = #{priceLocked} and coalesce(pa.pending_quantity, 0) > 0 and pr.purchase_batch_no like concat('%', #{purchaseBatchNo}, '%') diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml index 51bb77d..64bcc64 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml @@ -47,6 +47,7 @@ and si.area_id = #{areaId} and si.item_id = #{productId} and si.project_id = #{projectId} + and si.project_id != #{excludeProjectId} and wa.area_name like concat('%', #{areaName}, '%') and lower(concat_ws(' ', pi.product_name, pi.brand, pi.category, pi.spec, pi.unit, wa.area_name)) diff --git a/ruoyi-ui/src/api/production/tasks.js b/ruoyi-ui/src/api/production/tasks.js index 89cf8fd..844d0b6 100644 --- a/ruoyi-ui/src/api/production/tasks.js +++ b/ruoyi-ui/src/api/production/tasks.js @@ -1,12 +1,16 @@ import request from '@/utils/request' export function costHistory(params) { return request({url:'/production/tasks/cost-history',method:'get',params}) } export const listTasks = params => request({ url: '/production/tasks', params }) +export const listTaskPage = params => request({url:'/production/tasks/page',params}) +export const productionShortages = taskIds => request({url:'/production/tasks/shortages',params:{taskIds:taskIds.join(',')}}) export const getTask = id => request({ url: '/production/tasks/' + id }) export const saveTask = data => request({ url: '/production/tasks', method: 'post', data }) -export const taskAction = data => request({ url: '/production/tasks/actions', method: 'post', data }) +export const taskAction = data => request({ url: '/production/tasks/actions', method: 'post', headers:{repeatSubmit:false}, data }) export const listActions = params => request({ url: '/production/tasks/actions', params }) export const revokeAction = (id, reason) => request({ url: `/production/tasks/actions/${id}/revoke`, method: 'post', data: { reason } }) export const settleTask = (id, version) => request({ url: `/production/tasks/${id}/settle`, method: 'post', data: { version } }) export const reopenTask = (id, version) => request({ url: `/production/tasks/${id}/reopen`, method: 'post', data: { version } }) export const referenceCost = params => request({ url: '/production/tasks/reference', params }) export const projectOverview = id => request({ url: '/production/tasks/overview/' + id }) +export const listActionPage = params => request({url:'/production/tasks/actions/page',params}) +export const removeTask = (id,version) => request({url:'/production/tasks/'+id,method:'delete',params:{version}}) diff --git a/ruoyi-ui/src/api/project/loan.js b/ruoyi-ui/src/api/project/loan.js index 01991e7..dc2ba66 100644 --- a/ruoyi-ui/src/api/project/loan.js +++ b/ruoyi-ui/src/api/project/loan.js @@ -1,7 +1,7 @@ import request from '@/utils/request' export const listLoans = params => request({ url: '/project/loans', method: 'get', params }) export const loanOptions = params => request({ url: '/project/loans/options', method: 'get', params }) -export const borrowStock = data => request({ url: '/project/loans', method: 'post', data }) +export const borrowStock = data => request({ url: '/project/loans', method: 'post', headers:{repeatSubmit:false}, data }) export const returnLoan = (id, data) => request({ url: `/project/loans/${id}/return`, method: 'post', data }) export const loanReturns = id => request({ url: `/project/loans/${id}/returns`, method: 'get' }) export const revokeLoan = (id, reason) => request({ url: `/project/loans/${id}/revoke`, method: 'post', data: { reason } }) diff --git a/ruoyi-ui/src/api/warehouse/inRecord.js b/ruoyi-ui/src/api/warehouse/inRecord.js index 4de9732..1335c95 100644 --- a/ruoyi-ui/src/api/warehouse/inRecord.js +++ b/ruoyi-ui/src/api/warehouse/inRecord.js @@ -25,7 +25,7 @@ export function confirmInRecord(id) { } export function receiveInRecord(id, data) { - return request({ url: '/warehouse/in/receive/' + id, method: 'post', data }) + return request({ url: '/warehouse/in/receive/' + id, method: 'post', headers:{repeatSubmit:false}, data }) } export function revokeInRecord(id, reason) { diff --git a/ruoyi-ui/src/api/warehouse/purchase.js b/ruoyi-ui/src/api/warehouse/purchase.js index a2677d5..7be205e 100644 --- a/ruoyi-ui/src/api/warehouse/purchase.js +++ b/ruoyi-ui/src/api/warehouse/purchase.js @@ -1,5 +1,7 @@ import request from '@/utils/request' -export const purchaseSheetOptions = () => request({url:'/warehouse/purchase/sheet/options',method:'get'}) +export const purchaseSheetOptions = params => request({url:'/warehouse/purchase/sheet/options',method:'get',params}) +export const purchasePlanOptions = params => request({url:'/warehouse/purchase/sheet/plans',params}) +export const previewSupplierQuotes = (id,file) => {const data=new FormData();data.append('file',file);return request({url:`/warehouse/purchase/sheet/${id}/quote-preview`,method:'post',data,headers:{'Content-Type':'multipart/form-data',repeatSubmit:false}})} export const getPurchaseSheet = id => request({url:`/warehouse/purchase/sheet/${id}`,method:'get'}) export const savePurchaseSheet = data => request({url:'/warehouse/purchase/sheet',method:'post',data}) export const confirmPurchaseSheet = (id, version) => request({url:`/warehouse/purchase/sheet/${id}/confirm`,method:'post',data:{version}}) @@ -58,11 +60,11 @@ export function listPurchaseArrival(requestId) { } export function addPurchaseArrival(data) { - return request({ url: '/warehouse/purchase/arrival', method: 'post', data }) + return request({ url: '/warehouse/purchase/arrival', method: 'post', headers:{repeatSubmit:false}, data }) } export function acceptPurchaseArrival(id, data) { - return request({ url: '/warehouse/purchase/arrival/' + id + '/accept', method: 'put', data }) + return request({ url: '/warehouse/purchase/arrival/' + id + '/accept', method: 'put', headers:{repeatSubmit:false}, data }) } export function revokePurchaseArrival(id, data) { @@ -104,3 +106,4 @@ export function delPurchaseBatch(id) { export function delPurchase(ids) { return request({ url: '/warehouse/purchase/' + ids, method: 'delete' }) } +export const preparePurchaseSheet = ids => request({url:'/warehouse/purchase/sheet/prepare',method:'post',data:ids}) diff --git a/ruoyi-ui/src/components/InventoryAssistant/index.vue b/ruoyi-ui/src/components/InventoryAssistant/index.vue index 81a3924..f75d08d 100644 --- a/ruoyi-ui/src/components/InventoryAssistant/index.vue +++ b/ruoyi-ui/src/components/InventoryAssistant/index.vue @@ -1,8 +1,8 @@ diff --git a/ruoyi-ui/src/components/ProjectWorkspace/index.vue b/ruoyi-ui/src/components/ProjectWorkspace/index.vue index f635a4c..0588776 100644 --- a/ruoyi-ui/src/components/ProjectWorkspace/index.vue +++ b/ruoyi-ui/src/components/ProjectWorkspace/index.vue @@ -1,34 +1,44 @@ - + diff --git a/ruoyi-ui/src/components/PurchaseSheet/Lookup.vue b/ruoyi-ui/src/components/PurchaseSheet/Lookup.vue new file mode 100644 index 0000000..04a1041 --- /dev/null +++ b/ruoyi-ui/src/components/PurchaseSheet/Lookup.vue @@ -0,0 +1,46 @@ + + + diff --git a/ruoyi-ui/src/components/PurchaseSheet/index.vue b/ruoyi-ui/src/components/PurchaseSheet/index.vue index 719507c..8853268 100644 --- a/ruoyi-ui/src/components/PurchaseSheet/index.vue +++ b/ruoyi-ui/src/components/PurchaseSheet/index.vue @@ -1,31 +1,36 @@ + +
取消回填到清单
+
取消确认转批次

{{ recordsItem }}

@@ -98,14 +112,17 @@ diff --git a/ruoyi-ui/src/components/ReceiptDialog/index.vue b/ruoyi-ui/src/components/ReceiptDialog/index.vue index 9586c30..bde70ec 100644 --- a/ruoyi-ui/src/components/ReceiptDialog/index.vue +++ b/ruoyi-ui/src/components/ReceiptDialog/index.vue @@ -1,6 +1,6 @@ diff --git a/ruoyi-ui/src/views/project/info/index.vue b/ruoyi-ui/src/views/project/info/index.vue index 9ada05f..17927af 100644 --- a/ruoyi-ui/src/views/project/info/index.vue +++ b/ruoyi-ui/src/views/project/info/index.vue @@ -30,7 +30,7 @@ - + @@ -39,16 +39,7 @@ - - - + @@ -67,17 +58,7 @@
- - 配置科目预算 - 查看流水 - - - - - - - - + @@ -139,7 +120,7 @@ import ProjectLoans from '@/components/ProjectLoans' export default { name: 'ProjectInfo', - components: { ProjectProducts, ProjectLoans, ProjectWorkspace: () => import('@/components/ProjectWorkspace'), Initialization: () => import('@/components/Initialization') }, + components: { ProjectBudget:()=>import('@/components/ProjectWorkspace/Budget'),ProjectProducts, ProjectLoans, ProjectWorkspace: () => import('@/components/ProjectWorkspace'), Initialization: () => import('@/components/Initialization') }, data() { return { loading: false, showSearch: true, total: 0, projectList: [], ids: [], single: true, @@ -166,7 +147,8 @@ export default { handleUpdate(row) { const id = row.id || this.ids[0]; getProject(id).then(res => { this.form = res.data; this.originalProjectStatus = Number(this.form.projectStatus); this.title = '修改项目'; this.open = true }) }, submitForm() { this.$refs.form.validate(async valid => { if (!valid || this.savingProject) return; const closing = this.form.id && [2, 3].includes(Number(this.form.projectStatus)) && ![2, 3].includes(Number(this.originalProjectStatus)); this.savingProject = true; try { if (closing) { const summary = (await projectOverview(this.form.id)).data || {}; await this.$confirm(`当前还有:\n未到齐采购 ${summary.pendingPurchases || 0} 条\n待入库 ${summary.pendingReceipts || 0} 条\n未结算任务 ${summary.openTasks || 0} 个\n未归还借用 ${summary.outstandingLoans || 0} 条\n剩余库存 ${summary.remainingStocks || 0} 条\n\n状态变更不会取消或清空这些业务,后续仍可继续处理。`, Number(this.form.projectStatus) === 2 ? '结题前核对' : '终止前核对', { type: 'warning', confirmButtonText: '确认保存', cancelButtonText: '返回检查', whiteSpace: 'pre-line' }) } await (this.form.id ? updateProject(this.form) : addProject(this.form)); this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功'); this.open = false; this.getList() } catch (error) { return } finally { this.savingProject = false } }) }, handleDelete(row) { const id = row.id || this.ids[0]; const item = row.id ? row : this.projectList.find(p => p.id === id); this.$modal.confirm('确认删除项目“' + (item ? item.projectName : id) + '”?').then(() => delProject(id)).then(() => { this.$modal.msgSuccess('删除成功'); this.getList() }).catch(() => {}) }, - openBudget(row) { this.currentProject = row; this.budgetTitle = `项目经费:${row.projectName}`; this.budgetOpen = true; this.loadBudget(); categoryOptions().then(res => { this.categoryOptionList = res.data || [] }) }, + projectCommand(command,row){if(command==='budget')this.openBudget(row);if(command==='products')this.$refs.projectProducts.open(row);if(command==='loans')this.$refs.projectLoans.open(row);if(command==='edit')this.handleUpdate(row);if(command==='delete')this.handleDelete(row)}, + openBudget(row) { this.currentProject = row; this.budgetTitle = `项目经费:${row.projectName}`; this.budgetOpen = true }, loadBudget() { listProjectBudget(this.currentProject.id).then(res => { this.budgetList = res.data || [] }) }, openBudgetEdit(row) { this.budgetForm = row ? { ...row } : { projectId: this.currentProject.id, expenseCategoryId: undefined, budgetAmount: 0, alertPercent: 80, remark: undefined }; this.budgetEditOpen = true; this.$nextTick(() => this.$refs.budgetForm && this.$refs.budgetForm.clearValidate()) }, submitBudget() { this.budgetForm.projectId = this.currentProject.id; this.$refs.budgetForm.validate(valid => { if (!valid) return; saveProjectBudget(this.budgetForm).then(() => { this.$modal.msgSuccess('经费预算已保存'); this.budgetEditOpen = false; this.loadBudget(); this.getList() }) }) }, diff --git a/ruoyi-ui/src/views/warehouse/area/index.vue b/ruoyi-ui/src/views/warehouse/area/index.vue index 16ae83f..0d97831 100644 --- a/ruoyi-ui/src/views/warehouse/area/index.vue +++ b/ruoyi-ui/src/views/warehouse/area/index.vue @@ -93,8 +93,7 @@ export default { listArea(this.queryParams).then(response => { this.areaList = response.rows this.total = response.total - this.loading = false - }) + }).catch(() => {}).finally(() => { this.loading = false }) }, cancel() { this.open = false; this.reset() }, reset() { diff --git a/ruoyi-ui/src/views/warehouse/inRecord/index.vue b/ruoyi-ui/src/views/warehouse/inRecord/index.vue index 0bb4b48..63c1f33 100644 --- a/ruoyi-ui/src/views/warehouse/inRecord/index.vue +++ b/ruoyi-ui/src/views/warehouse/inRecord/index.vue @@ -2,31 +2,32 @@
- - + + + - + - + - + - + - + - + @@ -43,20 +44,24 @@ 搜索 - 重置 + 重置{{ advancedSearch?'收起':'更多筛选' }} - 其他入库 - 修改 - 删除 + 其他入库 + 修改 + 删除 导出 - 批量入库 + 批量入库 - + + + + + @@ -154,6 +159,7 @@