diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseBoardController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseBoardController.java index 26e61c4..5360433 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseBoardController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseBoardController.java @@ -14,6 +14,11 @@ public class PurchaseBoardController { private final PurchaseBoardService service;private final PurchaseBatchFundingService funding; public PurchaseBoardController(PurchaseBoardService service,PurchaseBatchFundingService funding){this.service=service;this.funding=funding;} public record Category(Long categoryId,Long expectedCategoryId){} + public record Order(java.util.List ids,java.util.List expectedIds){} + @PutMapping("/order") + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") + @Log(title="采购看板排序",businessType=BusinessType.UPDATE) + public AjaxResult order(@RequestBody Order input){service.saveOrder(input.ids(),input.expectedIds());return AjaxResult.success();} @PutMapping("/{id}/category") @PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')") @Log(title="采购批次费用类别",businessType=BusinessType.UPDATE) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java index 3fb4f9f..42e1e6c 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java @@ -26,7 +26,9 @@ public class PurchaseAcceptanceGenerationService { if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage")&&!SecurityUtils.hasPermi("warehouse:purchase:edit"))throw new ServiceException("没有采购资料维护权限",403); if(input==null||input.requestId()==null||!input.requestId().matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))throw new ServiceException("生成请求标识无效,请重新打开验收资料"); // 与清单保存、资料上传保持批次→采购明细的锁顺序;验收变更不能穿过生成校验。 - if(db.queryForList("select id from purchase_batch where id=? for update",id).isEmpty())throw new ServiceException("采购批次不存在"); + var owners=db.queryForList("select id,create_by from purchase_batch where id=? and del_flag='0' for update",id); + if(owners.isEmpty())throw new ServiceException("采购批次不存在"); + if(!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以生成批次验收资料",403); db.queryForList("select id from purchase_request where purchase_batch_id=? and del_flag='0' order by id for update",id); var report=reports.export(id,version,input.fields());String fingerprint=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsBytes(report))); var previous=db.queryForList("select a.owner_id,cast(a.deleted as signed) deleted,g.target_type,g.target_id,g.document_kind from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=?",input.requestId()); @@ -35,14 +37,14 @@ public class PurchaseAcceptanceGenerationService { if(((Number)p.get("owner_id")).longValue()!=SecurityUtils.getUserId()||((Number)p.get("deleted")).intValue()!=0||!"batch".equals(p.get("target_type"))||((Number)p.get("target_id")).longValue()!=id||!"ACCEPTANCE".equals(p.get("document_kind")))throw new ServiceException("生成请求已失效,请重新打开验收资料"); var file=documents.content("batch",id,input.requestId()); try(var pdf=Loader.loadPDF(file.bytes())){if(!fingerprint.equals(pdf.getDocumentInformation().getCustomMetadataValue("CMVR-Acceptance-Fingerprint")))throw new ServiceException("本次生成内容已变化,请重新生成");} - return new PurchaseDocumentService.Attachment(input.requestId(),file.name(),file.contentType(),file.bytes().length,SecurityUtils.getUsername(),null); + return new PurchaseDocumentService.Attachment(input.requestId(),file.name(),file.contentType(),file.bytes().length,SecurityUtils.getUsername(),null,true); } var temporary=Files.createTempFile("purchase-acceptance-",".pdf"); try{ try(var output=Files.newOutputStream(temporary)){PurchaseAcceptancePdf.write(report,photoId->photos.content(photoId).bytes(),output,fingerprint);} if(Files.size(temporary)>10L*1024*1024)throw new ServiceException("生成的验收资料超过单个附件10 MB限制,请联系管理员处理"); byte[] bytes=Files.readAllBytes(temporary);String label=report.batchName().replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]","_");if(label.length()>120)label=label.substring(0,120); - return documents.upload("batch",id,"ACCEPTANCE",input.requestId(),new GeneratedFile(label+"_验收资料_待签章.pdf",bytes)); + return documents.uploadGenerated("batch",id,"ACCEPTANCE",input.requestId(),new GeneratedFile(label+"_验收资料_待签章.pdf",bytes)); }finally{Files.deleteIfExists(temporary);} } private record GeneratedFile(String name,byte[] bytes) implements MultipartFile { diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseBoardService.java b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseBoardService.java index 8f7c240..c42a553 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseBoardService.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseBoardService.java @@ -4,6 +4,7 @@ import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.warehouse.domain.PurchaseBatch; import com.ruoyi.warehouse.util.PurchaseQuoteAccess; +import com.ruoyi.warehouse.util.AmountDisplayPolicy; import java.util.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @@ -12,7 +13,7 @@ import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.warehouse.service.impl.PurchaseBatchFundingService; import com.ruoyi.warehouse.service.impl.CatalogWriteLock; -/** All money in this workbench is quotation money. Never aggregate a batch amount once per project. */ +/** Board-only ordering and filtered totals. Never aggregate a batch amount once per project. */ @Service public class PurchaseBoardService { private final JdbcTemplate db;private final CatalogWriteLock catalog; @@ -25,9 +26,33 @@ public class PurchaseBoardService { funding.change(id,category);return AjaxResult.success(); } private record Filter(String sql,List args){} + private static final String BOARD_ORDER="b.board_sort_order is null desc,b.board_sort_order,b.business_date desc,b.create_time desc,b.id desc"; + private boolean compact(){return PurchaseQuoteAccess.allowed()&&db.queryForObject("select count(*) from sys_config where config_key=? and config_value='true'",Integer.class,AmountDisplayPolicy.KEY)>0;} + private String visibleLines(String alias){return PurchaseQuoteAccess.allowed()?" and "+AmountDisplayPolicy.visibleSql(alias+".final_unit_price"):"";} + /** Only replaces the occupied positions of the submitted page/filter, retaining all other batches. */ + @Transactional + public void saveOrder(List ids,List expected){ + PurchaseQuoteAccess.require(); + if(ids==null||expected==null||ids.size()<2||ids.size()>100||ids.size()!=expected.size() + ||ids.stream().anyMatch(id->id==null||id<=0)||new HashSet<>(ids).size()!=ids.size() + ||!new HashSet<>(ids).equals(new HashSet<>(expected)))throw new ServiceException("排序数据无效,请刷新看板后重试"); + catalog.acquire(); + var current=db.queryForList("select b.id,b.board_sort_order sortOrder from purchase_batch b where b.del_flag='0' order by "+BOARD_ORDER+" for update"); + var selected=new HashSet<>(ids); + var original=current.stream().map(row->((Number)row.get("id")).longValue()).toList(); + if(!original.stream().filter(selected::contains).toList().equals(expected))throw new ServiceException("看板顺序或批次已发生变化,请刷新后重新排序"); + var ordered=new ArrayList<>(original);int cursor=0; + for(int i=0;i();for(int i=0;i(); + if(PurchaseQuoteAccess.allowed())sql.append(" and (exists(select 1 from purchase_request av where av.purchase_batch_id=b.id and av.del_flag='0'").append(visibleLines("av")).append(") or not exists(select 1 from purchase_request av where av.purchase_batch_id=b.id and av.del_flag='0'))"); if(q.getKeyword()!=null&&!q.getKeyword().isBlank()){if(q.getKeyword().length()>100)throw new ServiceException("搜索内容最多100字");sql.append(" and concat_ws(' ',b.batch_name,b.batch_no,s.name,b.progress_remark) like ?");args.add("%"+q.getKeyword().trim()+"%");} if(q.getProjectId()!=null){sql.append(" and exists(select 1 from purchase_request x where x.purchase_batch_id=b.id and x.del_flag='0' and x.project_id=?)");args.add(q.getProjectId());} if(q.getExpenseCategoryId()!=null){if(q.getExpenseCategoryId()==0)sql.append(" and b.expense_category_id is null");else{sql.append(" and b.expense_category_id=?");args.add(q.getExpenseCategoryId());}} @@ -45,9 +70,11 @@ public class PurchaseBoardService { public Map batches(PurchaseBatch q,int page,int limit){ int size=size(limit);long offset=offset(page,size);var f=filter(q); long total=db.queryForObject("select count(*)"+FROM+f.sql(),Long.class,f.args().toArray()); - String aggregate=" left join (select r.purchase_batch_id,count(*) itemCount,group_concat(distinct p.project_name order by p.id separator '、') projectNames,group_concat(distinct coalesce(nullif(u.nick_name,''),r.create_by) order by r.create_by separator '、') purchasers,sum(case when r.purchase_status<>5 then round(r.quantity*r.final_unit_price,6) end) quoteAmount,sum(case when r.purchase_status<>5 and r.final_unit_price is null then 1 else 0 end) unpricedCount from purchase_request r left join project_info p on p.id=r.project_id left join sys_user u on u.user_id=r.applicant_id where r.del_flag='0' group by r.purchase_batch_id) a on a.purchase_batch_id=b.id "; + boolean quotes=PurchaseQuoteAccess.allowed(),compact=compact(); + String sums="sum(case when r.purchase_status<>5 then round(r.actual_unit_price*r.quantity,2) end) actualTotalAmount,sum(case when r.purchase_status<>5 then round(r.quantity*r.final_unit_price,6) end) quoteAmount,sum(case when r.purchase_status<>5 and r.final_unit_price is null then 1 else 0 end) unpricedCount"; + String aggregate=" left join (select r.purchase_batch_id,count(*) itemCount,group_concat(distinct p.project_name order by p.id separator '、') projectNames,group_concat(distinct coalesce(nullif(u.nick_name,''),r.create_by) order by r.create_by separator '、') purchasers,"+sums+" from purchase_request r left join project_info p on p.id=r.project_id left join sys_user u on u.user_id=r.applicant_id where r.del_flag='0'"+visibleLines("r")+" group by r.purchase_batch_id) a on a.purchase_batch_id=b.id "; var args=new ArrayList<>(f.args());args.add(size);args.add(offset); - var rows=db.queryForList("select b.create_by createBy,b.id,b.batch_no batchNo,b.batch_name batchName,b.expense_category_id expenseCategoryId,coalesce(e.category_name,'待统一') expenseCategoryName,b.progress_remark remark,b.business_date businessDate,s.name supplierName,a.projectNames,a.purchasers,coalesce(a.itemCount,0) itemCount,a.quoteAmount,coalesce(a.unpricedCount,0) unpricedCount"+FROM+aggregate+" left join expense_category e on e.id=b.expense_category_id "+f.sql()+" order by b.business_date desc,b.create_time desc,b.id desc limit ? offset ?",args.toArray()); + var rows=db.queryForList("select b.create_by createBy,b.id,b.batch_no batchNo,b.batch_name batchName,b.expense_category_id expenseCategoryId,coalesce(e.category_name,'待统一') expenseCategoryName,b.progress_remark remark,b.business_date businessDate,s.name supplierName,a.projectNames,a.purchasers,coalesce(a.itemCount,0) itemCount,a.actualTotalAmount,a.quoteAmount,coalesce(a.unpricedCount,0) unpricedCount"+FROM+aggregate+" left join expense_category e on e.id=b.expense_category_id "+f.sql()+" order by "+BOARD_ORDER+" limit ? offset ?",args.toArray()); if(!rows.isEmpty()){ var ids=rows.stream().map(r->r.get("id")).toList();String marks=String.join(",",Collections.nCopies(ids.size(),"?")); var docs=db.queryForList("select g.target_id batchId,g.document_kind kind,g.document_no number,count(a.id) files from purchase_document_group g left join purchase_document_attachment a on a.group_id=g.id and a.deleted=0 and a.content_type='application/pdf' where g.target_type='batch' and g.target_id in ("+marks+") group by g.id,g.target_id,g.document_kind,g.document_no",ids.toArray()); @@ -59,17 +86,17 @@ public class PurchaseBoardService { if("REQUEST".equals(kind))files+=docs.stream().filter(d->Objects.equals(d.get("batchId"),row.get("id"))&&"QUOTE".equals(d.get("kind"))).mapToInt(d->((Number)d.get("files")).intValue()).sum(); stages.add(Map.of("kind",kind,"number",number,"files",files,"complete",files>0&&("ACCEPTANCE".equals(kind)||!number.isBlank()))); } - row.put("editable",com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)row.get("createBy"),null));row.put("stages",stages);if(!PurchaseQuoteAccess.allowed()){row.remove("quoteAmount");row.remove("unpricedCount");} + row.put("editable",com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)row.get("createBy"),null));row.put("stages",stages);if(!quotes){row.remove("quoteAmount");row.remove("unpricedCount");}if(compact)row.remove("actualTotalAmount"); } } - Map totals=Map.of(); - if(PurchaseQuoteAccess.allowed())totals=db.queryForMap("select sum(case when r.purchase_status<>5 then round(r.quantity*r.final_unit_price,6) end) quoteAmount,sum(case when r.purchase_status<>5 and r.final_unit_price is null then 1 else 0 end) unpricedCount"+FROM+" join purchase_request r on r.purchase_batch_id=b.id and r.del_flag='0' "+f.sql(),f.args().toArray()); + var totals=db.queryForMap("select "+sums+FROM+" join purchase_request r on r.purchase_batch_id=b.id and r.del_flag='0' "+visibleLines("r")+f.sql(),f.args().toArray()); + if(!quotes){totals.remove("quoteAmount");totals.remove("unpricedCount");}if(compact)totals.remove("actualTotalAmount"); return Map.of("rows",rows,"total",total,"summary",totals); } @Transactional(readOnly=true,isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) public Map costs(PurchaseBatch q,int page,int limit){ PurchaseQuoteAccess.require();int size=size(limit);long offset=offset(page,size);var f=filter(q); - String joins=FROM+" join purchase_request r on r.purchase_batch_id=b.id and r.del_flag='0' and r.purchase_status<>5 join project_info p on p.id=r.project_id "; + String joins=FROM+" join purchase_request r on r.purchase_batch_id=b.id and r.del_flag='0' and r.purchase_status<>5"+visibleLines("r")+" join project_info p on p.id=r.project_id "; String where=f.sql()+(q.getProjectId()==null?"":" and r.project_id=?");var params=new ArrayList<>(f.args());if(q.getProjectId()!=null)params.add(q.getProjectId()); long total=db.queryForObject("select count(distinct p.id)"+joins+where,Long.class,params.toArray()); var pageArgs=new ArrayList<>(params);pageArgs.add(size);pageArgs.add(offset); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchMergeGuardTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchMergeGuardTest.java new file mode 100644 index 0000000..254cd0a --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchMergeGuardTest.java @@ -0,0 +1,39 @@ +package com.ruoyi.projectdev; + +import java.util.*; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import com.ruoyi.warehouse.mapper.PurchaseBatchMapper; +import static org.junit.jupiter.api.Assertions.*; + +class PurchaseBatchMergeGuardTest { + @Test void actualMapperProtectsEveryBusinessReferenceIncludingDeletedDetailsAndEmptyStageBindings()throws Exception { + var source=new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""); + var db=new JdbcTemplate(source); + db.execute("create table purchase_batch(id bigint primary key,del_flag char(1),create_by varchar(64),update_by varchar(64),update_time timestamp)"); + db.execute("create table purchase_request(id bigint primary key,purchase_batch_id bigint,historical int,del_flag char(1))"); + db.execute("create table pm_collab_stage_purchase_batch(purchase_batch_id bigint)"); + for(String table:List.of("purchase_arrival","in_record","stock_lot","purchase_price_ledger"))db.execute("create table "+table+"(purchase_request_id bigint)"); + db.execute("insert into purchase_batch values(2,'0','owner',null,null)"); + db.execute("insert into purchase_request values(10,2,0,'2')"); + var config=AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/PurchaseBatchMapper.xml"); + config.setEnvironment(new Environment("isolated-merge-regression",new JdbcTransactionFactory(),source)); + try(var session=new SqlSessionFactoryBuilder().build(config).openSession(true)){ + var mapper=session.getMapper(PurchaseBatchMapper.class); + assertFalse(mapper.hasBatchBusinessReferences(2L)); + for(String table:List.of("purchase_arrival","in_record","stock_lot","purchase_price_ledger")){ + db.update("insert into "+table+" values(10)");assertTrue(mapper.hasBatchBusinessReferences(2L),table+" must protect even a deleted detail"); + db.update("delete from "+table);assertFalse(mapper.hasBatchBusinessReferences(2L)); + } + db.update("update purchase_request set historical=1 where id=10");assertTrue(mapper.hasBatchBusinessReferences(2L)); + db.update("delete from purchase_request");db.update("insert into pm_collab_stage_purchase_batch values(2)");assertTrue(mapper.hasBatchBusinessReferences(2L)); + db.update("delete from pm_collab_stage_purchase_batch");assertFalse(mapper.hasBatchBusinessReferences(2L)); + assertEquals(1,mapper.deletePurchaseBatchById(2L));assertEquals("2",db.queryForObject("select del_flag from purchase_batch where id=2",String.class)); + assertEquals(1,db.queryForObject("select count(*) from purchase_batch where id=2",Integer.class));assertEquals(0,mapper.deletePurchaseBatchById(2L)); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java index abf6806..6456954 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java @@ -71,6 +71,20 @@ class PurchaseBatchTransferTest { verify(f.batches,never()).countBatchDocuments(any()); } } + @Test void referencedBatchIsRejectedBeforeDeletingAnyRowsOrPublishingChanges(){ + Fixture f=new Fixture();f.target.setCreateBy("owner"); + var details=mock(com.ruoyi.warehouse.service.IPurchaseRequestService.class); + ReflectionTestUtils.setField(f.service,"purchaseRequestService",details); + when(f.batches.selectPurchaseBatchForUpdate(2L)).thenReturn(f.target); + when(f.requests.selectPurchaseRequestIdsByBatchForUpdate(2L)).thenReturn(List.of(10L)); + when(f.batches.hasBatchBusinessReferences(2L)).thenReturn(true); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::getUsername).thenReturn("owner"); + security.when(()->SecurityUtils.hasPermi("warehouse:purchase:remove")).thenReturn(true); + assertThrows(ServiceException.class,()->f.service.deletePurchaseBatchById(2L)); + verifyNoInteractions(details);verify(f.batches,never()).deletePurchaseBatchById(any());verifyNoInteractions(f.liveEvents); + } + } private static class Fixture{ final PurchaseBatchMapper batches=mock(PurchaseBatchMapper.class);final PurchaseRequestMapper requests=mock(PurchaseRequestMapper.class);final PurchaseBatchNumber numbers=mock(PurchaseBatchNumber.class); final PurchaseBatchServiceImpl service=new PurchaseBatchServiceImpl();final PurchaseRequest row=new PurchaseRequest();final PurchaseBatch target=new PurchaseBatch(); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java index 472c085..18819aa 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java @@ -44,7 +44,7 @@ class PurchaseBoardDatabaseTest { q.setProjectId(one.getProjectId());assertMoney("5.00",((Map)service.costs(q,1,20).get("summary")).get("quoteAmount"));q.setProjectId(null); q.setKeyword("' or 1=1 --");assertEquals(0L,service.batches(q,1,20).get("total"));q.setKeyword(f.name); security.when(SecurityUtils::isAdmin).thenReturn(false); - var privateBoard=service.batches(q,1,20);assertTrue(((Map)privateBoard.get("summary")).isEmpty());assertTrue(((List>)privateBoard.get("rows")).stream().noneMatch(r->r.containsKey("quoteAmount")));assertThrows(ServiceException.class,()->service.costs(q,1,20)); + var privateBoard=service.batches(q,1,20);assertFalse(((Map)privateBoard.get("summary")).containsKey("quoteAmount"));assertTrue(((Map)privateBoard.get("summary")).containsKey("actualTotalAmount"));assertTrue(((List>)privateBoard.get("rows")).stream().noneMatch(r->r.containsKey("quoteAmount")));assertThrows(ServiceException.class,()->service.costs(q,1,20)); }); } assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name like ?",Integer.class,f.name+"%")); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentsTest.java b/ruoyi-admin/src/test/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentsTest.java index ec54192..5967e54 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentsTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentsTest.java @@ -21,6 +21,21 @@ class PurchaseDocumentsTest { static final byte[] PDF="%PDF-1.7\n1 0 obj<>endobj\nstartxref\n0\n%%EOF\n".getBytes(StandardCharsets.US_ASCII); @TempDir Path temp; + @Test void deletedBatchHistoryIsReadOnlyAndStaleUploadsCannotWrite(){ + JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); + when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->{ + String sql=call.getArgument(0,String.class); + if(sql.startsWith("select id,create_by")&&!sql.contains("for update"))return List.of(Map.of("id",1L,"create_by","owner","del_flag","2")); + return List.of(); + }); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("owner"); + assertTrue(service.list("batch",1L).stream().noneMatch(PurchaseDocumentService.Group::editable)); + assertThrows(ServiceException.class,()->service.saveNumber("batch",1L,"CONTRACT","HT-1",0)); + verify(db,never()).update(anyString(),any(Object[].class)); + } + } + @Test void fiveBatchGroupsMergeRequestAndQuoteAndDetailHasOnlyAttachments() { JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->call.getArgument(0,String.class).startsWith("select id,create_by")?List.of(Map.of("id",1)):List.of()); @@ -60,7 +75,7 @@ class PurchaseDocumentsTest { var quoteFile=new PurchaseDocumentService.Attachment("22222222-2222-4222-8222-222222222222","报价.pdf","application/pdf",60,"editor",null); when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->{ String sql=call.getArgument(0,String.class); - if(sql.startsWith("select id,create_by from purchase_batch"))return List.of(Map.of("id",1L)); + if(sql.startsWith("select id,create_by"))return List.of(Map.of("id",1L)); if(sql.contains("document_kind='QUOTE'"))return List.of(Map.of("id",6L)); if(sql.startsWith("select id,document_no")&&"REQUEST".equals(call.getArgument(3)))return List.of(Map.of("id",5L,"document_no","SX-001","version",3)); return List.of(); @@ -109,7 +124,7 @@ class PurchaseDocumentsTest { @Test void staleNumberDoesNotSilentlyOverwriteAnotherEditor() { JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); - when(db.queryForList(startsWith("select id,create_by from purchase_batch"),eq(1L))).thenReturn(List.of(Map.of("id",1L))); + when(db.queryForList(startsWith("select id,create_by"),eq(1L))).thenReturn(List.of(Map.of("id",1L))); when(db.queryForObject(startsWith("select id from purchase_document_group"),eq(Long.class),eq("batch"),eq(1L),eq("CONTRACT"))).thenReturn(5L); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("editor"); @@ -152,7 +167,7 @@ class PurchaseDocumentsTest { @Test void missingAndWrongTargetFilesNeverReachDiskOrLeakContent() { JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); - when(db.queryForList(startsWith("select id,create_by from purchase_batch"),eq(1L))).thenReturn(List.of(Map.of("id",1L))); + when(db.queryForList(startsWith("select id,create_by"),eq(1L))).thenReturn(List.of(Map.of("id",1L))); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); assertThrows(ServiceException.class,()->service.content("batch",1L,ID)); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseBoardDisplayTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseBoardDisplayTest.java new file mode 100644 index 0000000..8a23e77 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseBoardDisplayTest.java @@ -0,0 +1,81 @@ +package com.ruoyi.web.service.warehouse; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.domain.PurchaseBatch; +import com.ruoyi.warehouse.service.impl.CatalogWriteLock; +import java.math.BigDecimal; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class PurchaseBoardDisplayTest { + private static class Fixture { + final JdbcTemplate db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa","")); + final CatalogWriteLock lock=mock(CatalogWriteLock.class); + final PurchaseBoardService service=new PurchaseBoardService(db,lock); + Fixture(){ + db.execute("create table purchase_batch(id bigint primary key,del_flag char(1) default '0',create_by varchar(64) default 'owner',batch_no varchar(64),batch_name varchar(100),expense_category_id bigint,supplier_id bigint,progress_remark varchar(100),business_date date,create_time timestamp,update_time timestamp,board_sort_order bigint)"); + db.execute("create table purchase_request(id bigint primary key,purchase_batch_id bigint,project_id bigint,applicant_id bigint,create_by varchar(64),del_flag char(1) default '0',purchase_status int default 0,quantity decimal(20,4),actual_unit_price decimal(20,6),final_unit_price decimal(20,6))"); + db.execute("create table supplier_info(id bigint primary key,name varchar(100))"); + db.execute("create table project_info(id bigint primary key,project_name varchar(100),project_code varchar(64),create_time timestamp)"); + db.execute("create table expense_category(id bigint primary key,category_name varchar(100),sort_order int)"); + db.execute("create table sys_user(user_id bigint primary key,nick_name varchar(64))"); + db.execute("create table sys_config(config_key varchar(100),config_value varchar(100))"); + db.execute("create table purchase_document_group(id bigint primary key,target_type varchar(30),target_id bigint,document_kind varchar(30),document_no varchar(100))"); + db.execute("create table purchase_document_attachment(id bigint primary key,group_id bigint,deleted int,content_type varchar(100))"); + db.update("insert into sys_config values('wms.display.compactAmounts','false')"); + db.update("insert into project_info values(1,'机器人','P-1','2026-01-01')"); + for(long id=1;id<=5;id++)db.update("insert into purchase_batch(id,batch_no,batch_name,business_date,create_time,update_time) values(?,?,?,'2026-01-01','2026-01-01','2026-01-02')",id,"CG"+id,id==5?"其他批次":"测试批次"+id); + } + void line(long id,long batch,int status,String quantity,String actual,String quote){db.update("insert into purchase_request(id,purchase_batch_id,project_id,create_by,purchase_status,quantity,actual_unit_price,final_unit_price) values(?,?,1,'owner',?,?,?,?)",id,batch,status,new BigDecimal(quantity),actual==null?null:new BigDecimal(actual),quote==null?null:new BigDecimal(quote));} + List order(){return db.queryForList("select id from purchase_batch where del_flag='0' order by board_sort_order is null desc,board_sort_order,business_date desc,create_time desc,id desc",Long.class);} + } + @SuppressWarnings("unchecked") private static Map totals(Map value){return (Map)value.get("summary");} + private static void money(String expected,Object value){assertNotNull(value);assertEquals(0,new BigDecimal(expected).compareTo(new BigDecimal(value.toString())));} + @Test void persistedOrderReplacesFilteredPositionsAndNeverChangesBusinessTimestamps(){ + var f=new Fixture();var timestamps=f.db.queryForList("select id,create_time,update_time from purchase_batch order by id"); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true); + assertEquals(List.of(5L,4L,3L,2L,1L),f.order()); + f.service.saveOrder(List.of(1L,4L),List.of(4L,1L)); + assertEquals(List.of(5L,1L,3L,2L,4L),f.order()); + assertEquals(timestamps,f.db.queryForList("select id,create_time,update_time from purchase_batch order by id")); + var loaded=f.service.batches(new PurchaseBatch(),1,2); + assertEquals(List.of(5L,1L),((List>)loaded.get("rows")).stream().map(r->((Number)r.get("id")).longValue()).toList()); + // New batches remain discoverable at the front, without resetting an existing saved order. + f.db.update("insert into purchase_batch(id,batch_name,business_date) values(6,'新增','2026-01-02')"); + assertEquals(List.of(6L,5L,1L,3L,2L,4L),f.order()); + } + } + @Test void staleDeletedOrMalformedOrdersCannotOverwriteAnotherEditorsOrder(){ + var f=new Fixture();try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true); + f.service.saveOrder(List.of(1L,2L),List.of(2L,1L));var before=f.order(); + assertThrows(ServiceException.class,()->f.service.saveOrder(List.of(1L,2L),List.of(2L,1L))); + assertThrows(ServiceException.class,()->f.service.saveOrder(List.of(1L,1L),List.of(1L,2L))); + f.db.update("update purchase_batch set del_flag='2' where id=3"); + assertThrows(ServiceException.class,()->f.service.saveOrder(List.of(3L,4L),List.of(4L,3L))); + assertEquals(before.stream().filter(id->id!=3).toList(),f.order()); + } + } + @Test void twoTotalsCoverAllFilteredPagesIgnoreCanceledRowsAndHonorTheGlobalSwitch(){ + var f=new Fixture();f.line(1,1,0,"2","10.123","20");f.line(2,2,0,"3","5","0");f.line(3,3,5,"1","9999","9999");f.line(4,4,0,"1",null,null);f.line(5,5,0,"1","777","888"); + var query=new PurchaseBatch();query.setKeyword("测试批次"); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true); + var normal=f.service.batches(query,1,1);assertEquals(4L,normal.get("total"));money("35.25",totals(normal).get("actualTotalAmount"));money("40",totals(normal).get("quoteAmount")); + f.db.update("update sys_config set config_value='true'"); + var compact=f.service.batches(query,1,100);assertEquals(3L,compact.get("total"));assertFalse(totals(compact).containsKey("actualTotalAmount"));money("40",totals(compact).get("quoteAmount")); + assertTrue(((List>)compact.get("rows")).stream().noneMatch(row->row.containsKey("actualTotalAmount")||Objects.equals(row.get("id"),2L))); + money("40",totals(f.service.costs(query,1,20)).get("quoteAmount")); + security.when(SecurityUtils::isAdmin).thenReturn(false); + var employee=f.service.batches(query,1,1);assertEquals(4L,employee.get("total"));money("35.25",totals(employee).get("actualTotalAmount"));assertFalse(totals(employee).containsKey("quoteAmount"));assertFalse(totals(employee).containsKey("unpricedCount")); + assertTrue(((List>)employee.get("rows")).stream().noneMatch(row->row.containsKey("quoteAmount"))); + assertThrows(ServiceException.class,()->f.service.saveOrder(List.of(1L,2L),List.of(2L,1L))); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java index e06c13e..b7c8930 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java @@ -20,9 +20,11 @@ public class PurchaseBatchFundingService { public void validate(Long category){if(category==null||db.queryForList("select id from expense_category where id=? and status=0",category).isEmpty())throw new ServiceException("请在采购批次选择有效的费用类别");} @Transactional public void change(long batch,Long category){ - if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("仅采购批次管理员可统一已保存批次的费用类别",403); + if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage")&&!SecurityUtils.hasPermi("warehouse:purchase:edit"))throw new ServiceException("仅采购批次管理员可统一已保存批次的费用类别",403); validate(category);catalog.acquire();inventory.lockInventory(); - if(db.queryForList("select id from purchase_batch where id=? for update",batch).isEmpty())throw new ServiceException("采购批次不存在"); + var owners=db.queryForList("select create_by from purchase_batch where id=? and del_flag='0' for update",batch); + if(owners.isEmpty())throw new ServiceException("采购批次不存在"); + if(!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以统一费用类别",403); var ids=db.queryForList("select id from purchase_request where purchase_batch_id=? and del_flag='0' and purchase_status<>5 order by id for update",Long.class,batch); for(Long id:ids){ var old=requests.selectPurchaseRequestByIdForUpdate(id);if(Objects.equals(old.getExpenseCategoryId(),category))continue; 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 e9cb98c..2c391ec 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 @@ -15,6 +15,7 @@ import com.ruoyi.warehouse.mapper.PurchaseBatchMapper; import com.ruoyi.warehouse.mapper.PurchaseRequestMapper; import com.ruoyi.warehouse.service.IPurchaseOperationLogService; import com.ruoyi.warehouse.service.IPurchaseBatchService; +import com.ruoyi.warehouse.service.IPurchaseRequestService; @Service public class PurchaseBatchServiceImpl implements IPurchaseBatchService @@ -31,6 +32,8 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService @Autowired private PurchaseBatchNumber batchNumbers; @Autowired private CatalogWriteLock catalogWriteLock; @Autowired private PurchaseBatchFundingService funding; + @Autowired private IPurchaseRequestService purchaseRequestService; + @Autowired private org.springframework.context.ApplicationEventPublisher liveEvents; @Override public List selectPurchaseBatchList(PurchaseBatch batch) @@ -79,6 +82,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService { throw new ServiceException("采购批次不存在"); } + com.ruoyi.warehouse.util.PurchaseDataAccess.require(existing); if(batch.getExpenseCategoryId()==null)batch.setExpenseCategoryId(existing.getExpenseCategoryId()); if(!java.util.Objects.equals(existing.getExpenseCategoryId(),batch.getExpenseCategoryId()))funding.change(batch.getId(),batch.getExpenseCategoryId()); if (existing.getSupplierId() != null && !java.util.Objects.equals(existing.getSupplierId(), batch.getSupplierId())) { @@ -99,6 +103,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService String username = SecurityUtils.getUsername(); batch.setUpdateBy(username); int rows = purchaseBatchMapper.updatePurchaseBatch(batch); + if (rows != 1) throw new ServiceException("采购批次已变化或已删除,请刷新后重试"); purchaseBatchMapper.syncRequestBatchNo(batch.getId(), batch.getBatchNo(), username); PurchaseRequest query = new PurchaseRequest(); query.setPurchaseBatchId(batch.getId()); @@ -109,6 +114,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService + ";状态:" + batchStatusText(existing.getPurchaseStatus()) + " → " + batchStatusText(batch.getPurchaseStatus())); } + if(liveEvents!=null)liveEvents.publishEvent(new com.ruoyi.warehouse.domain.PurchaseSheetChanged(batch.getId(),null)); return rows; } @@ -144,7 +150,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService // projection only after its lock has been acquired and the session cache flushed. if(row!=null)row=purchaseRequestMapper.selectPurchaseRequestById(requestId,null); if(row==null||Integer.valueOf(5).equals(row.getPurchaseStatus()))throw new ServiceException("已取消或不存在的采购不能转批次"); - requests.add(row); + com.ruoyi.warehouse.util.PurchaseDataAccess.require(row);requests.add(row); } var projects=requests.stream().map(PurchaseRequest::getProjectId).collect(java.util.stream.Collectors.toSet()); if(projects.size()!=1||projects.contains(null))throw new ServiceException("一批采购对应一个项目,请按项目分别转批次"); @@ -172,6 +178,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService }else{ batch=purchaseBatchMapper.selectPurchaseBatchById(request.getBatchId()); if(batch==null)throw new ServiceException("目标采购批次不存在"); + com.ruoyi.warehouse.util.PurchaseDataAccess.require(batch); if(Integer.valueOf(4).equals(batch.getPurchaseStatus())||Integer.valueOf(5).equals(batch.getPurchaseStatus()))throw new ServiceException("目标批次已归档或取消,请选择其他批次"); if(requests.stream().anyMatch(row->java.util.Objects.equals(row.getPurchaseBatchId(),batch.getId())))throw new ServiceException("所选明细已在目标批次,无需转入"); if(purchaseBatchMapper.selectBatchProjectIds(batch.getId()).stream().anyMatch(id->!projects.contains(id)))throw new ServiceException("目标批次属于其他项目,请选择同项目批次或新建批次"); @@ -192,25 +199,45 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "BATCH_ASSIGN", "分配采购批次", "批次:" + previous + " → " + batchDisplay(batch)+";仅调整归组,确认状态、报价、费用及到货入库关联不变"); } + // Moving a row invalidates both rooms, including the room it has just left. + batchIds.add(batch.getId()); + if(liveEvents!=null)for(Long id:batchIds)liveEvents.publishEvent(new com.ruoyi.warehouse.domain.PurchaseSheetChanged(id,null)); return request.getRequestIds().length; } + /** + * 仅由批次创建者整批软删除,保留批次、明细的历史数据和附件。 + * 目录锁阻止新增/转批次,批次及明细行锁覆盖业务校验和级联删除;任何一步失败均回滚。 + * 所有下游业务引用(含历史记录)必须先排除;允许删除时复用明细服务保留原审计逻辑,不按明细创建者拆分。 + * @param id 要删除的采购批次主键,创建者从持锁读取的数据库记录取得 + * @return 本次标记删除的批次数;不存在、已删除、无权限或已有关联业务时抛出业务异常 + */ @Override - @Transactional + @Transactional(isolation=org.springframework.transaction.annotation.Isolation.READ_COMMITTED) public int deletePurchaseBatchById(Long id) { - checkManager(); + if (id == null || id <= 0) throw new ServiceException("请选择采购批次"); + if (!SecurityUtils.hasPermi("warehouse:purchase:remove") && !SecurityUtils.hasPermi("warehouse:purchase:manage")) + throw new ServiceException("没有采购删除权限"); catalogWriteLock.acquire(); - if (purchaseBatchMapper.selectPurchaseBatchForUpdate(id) == null) + PurchaseBatch batch = purchaseBatchMapper.selectPurchaseBatchForUpdate(id); + if (batch == null) { - throw new ServiceException("采购批次不存在"); + throw new ServiceException("采购批次不存在或已删除,请刷新列表"); } - if (purchaseBatchMapper.countRequestsByBatchId(id) > 0) + // 管理角色和系统管理员也不能代替真实创建者;缺失历史创建者时拒绝推断归属。 + if (StringUtils.isBlank(batch.getCreateBy()) || !batch.getCreateBy().equals(SecurityUtils.getUsername())) + throw new ServiceException("只有采购批次的创建者可以删除"); + List requestIds = purchaseRequestMapper.selectPurchaseRequestIdsByBatchForUpdate(id); + if (purchaseBatchMapper.hasBatchBusinessReferences(id)) { - throw new ServiceException("该批次仍有关联的采购申请,不能删除"); + throw new ServiceException("该批次已有关联的到货、验收、入库、库存、费用台账、历史业务或项目流程记录,禁止删除"); } - if(purchaseBatchMapper.countBatchDocuments(id)>0)throw new ServiceException("该空批次仍有附件或流程编号,请保留批次用于追溯,不会自动删除"); - return purchaseBatchMapper.deletePurchaseBatchById(id); + if (!requestIds.isEmpty()) purchaseRequestService.deletePurchaseRequestByIds(requestIds.toArray(Long[]::new)); + int rows = purchaseBatchMapper.deletePurchaseBatchById(id); + if (rows != 1) throw new ServiceException("采购批次已变化,删除未完成,请刷新后重试"); + if(liveEvents!=null)liveEvents.publishEvent(new com.ruoyi.warehouse.domain.PurchaseSheetChanged(id,null)); + return rows; } private void validateSupplier(List rows,PurchaseBatch batch){ diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentService.java index fc57894..820ecaa 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentService.java @@ -35,14 +35,18 @@ public class PurchaseDocumentService { @Autowired private com.ruoyi.common.storage.BusinessFileStorage storage; @Value("${purchase.documents-path:}") private String configuredPath; - public record Attachment(String id, String name, String contentType, int size, String uploadedBy, String uploadedAt) { } - public record Group(String kind, String label, String number, int version, List files) { } + public record Attachment(String id,String name,String contentType,int size,String uploadedBy,String uploadedAt,boolean serverGenerated) { + public Attachment(String id,String name,String contentType,int size,String uploadedBy,String uploadedAt){this(id,name,contentType,size,uploadedBy,uploadedAt,false);} + } + public record Group(String kind, String label, String number, int version, List files, boolean editable) { + public Group(String kind,String label,String number,int version,List files){this(kind,label,number,version,files,false);} + } public record Content(byte[] bytes, String name, String contentType, boolean previewable) { } public record Validated(byte[] bytes, String type) { } @Transactional(readOnly = true) public List list(String type, Long targetId) { - requirePermission(false); requireTarget(type, targetId, false); + requirePermission(false); boolean editable=requireTarget(type, targetId, false); List result = new ArrayList<>(); for (var kind : kinds(type).entrySet()) { var groups = db.queryForList("select id,document_no,version from purchase_document_group where target_type=? and target_id=? and document_kind=?", type, targetId, kind.getKey()); @@ -54,11 +58,11 @@ public class PurchaseDocumentService { // 合并展示历史报价附件,保留原归属与报价访问门禁;报价编号不再展示或维护。 if("REQUEST".equals(kind.getKey())&&com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed()) for(var legacy:db.queryForList("select id from purchase_document_group where target_type=? and target_id=? and document_kind='QUOTE'",type,targetId))attachments.addAll(files(legacy.get("id"))); - result.add(new Group(kind.getKey(),kind.getValue(),number,version,List.copyOf(attachments))); + result.add(new Group(kind.getKey(),kind.getValue(),number,version,List.copyOf(attachments),editable)); } return result; } - private List files(Object group){return db.query("select id,original_name,content_type,byte_size,create_by,create_time from purchase_document_attachment where group_id=? and deleted=0 order by create_time desc,id",(r,n)->new Attachment(r.getString(1),r.getString(2),r.getString(3),r.getInt(4),r.getString(5),r.getString(6)),group);} + private List files(Object group){return db.query("select id,original_name,content_type,byte_size,create_by,create_time,server_generated from purchase_document_attachment where group_id=? and deleted=0 order by create_time desc,id desc",(r,n)->new Attachment(r.getString(1),r.getString(2),r.getString(3),r.getInt(4),r.getString(5),r.getString(6),r.getBoolean(7)),group);} @Transactional public void saveNumber(String type, Long targetId, String kind, String number, Integer version) { @@ -74,7 +78,9 @@ public class PurchaseDocumentService { } @Transactional - public Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file) { + public Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file) {return upload(type,targetId,kind,uploadId,file,false);} + @Transactional public Attachment uploadGenerated(String type,Long targetId,String kind,String uploadId,MultipartFile file){return upload(type,targetId,kind,uploadId,file,true);} + private Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file,boolean generated) { requirePermission(true); requireKind(type, kind); requireId(uploadId); if (file == null || file.isEmpty() || file.getSize() > MAX_BYTES) throw new ServiceException("请上传不超过10 MB的附件"); String name = safeName(file.getOriginalFilename()); @@ -90,13 +96,13 @@ public class PurchaseDocumentService { String sha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(valid.bytes())); requireTarget(type, targetId, true); long group = ensureGroup(type, targetId, kind); - var prior = db.queryForList("select group_id,owner_id,sha256,original_name,content_type,byte_size,deleted from purchase_document_attachment where id=?", uploadId); + var prior = db.queryForList("select group_id,owner_id,sha256,original_name,content_type,byte_size,deleted,server_generated from purchase_document_attachment where id=?", uploadId); if (!prior.isEmpty()) { var row = prior.get(0); if (((Number) row.get("group_id")).longValue() != group || ((Number) row.get("owner_id")).longValue() != SecurityUtils.getUserId() - || !sha.equals(row.get("sha256")) || !name.equals(row.get("original_name")) || ((Number) row.get("deleted")).intValue() != 0) + || !sha.equals(row.get("sha256")) || !name.equals(row.get("original_name")) || ((Number) row.get("deleted")).intValue() != 0 || truth(row.get("server_generated"))!=generated) throw new ServiceException("上传请求已变化,请重新选择附件"); - return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null); + return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null,generated); } int limit="REQUEST".equals(kind)?20:MAX_FILES; int count="REQUEST".equals(kind)?db.queryForObject("select count(*) from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where g.target_type=? and g.target_id=? and g.document_kind in ('REQUEST','QUOTE') and a.deleted=0",Integer.class,type,targetId):db.queryForObject("select count(*) from purchase_document_attachment where group_id=? and deleted=0",Integer.class,group); @@ -109,9 +115,9 @@ public class PurchaseDocumentService { if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { if (status != STATUS_COMMITTED) deleteFailed(rollbackFile); } }); - db.update("insert into purchase_document_attachment(id,group_id,original_name,content_type,byte_size,sha256,owner_id,create_by) values(?,?,?,?,?,?,?,?)", - uploadId, group, name, valid.type(), valid.bytes().length, sha, SecurityUtils.getUserId(), SecurityUtils.getUsername()); - return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null); + db.update("insert into purchase_document_attachment(id,group_id,original_name,content_type,byte_size,sha256,owner_id,create_by,server_generated) values(?,?,?,?,?,?,?,?,?)", + uploadId, group, name, valid.type(), valid.bytes().length, sha, SecurityUtils.getUserId(), SecurityUtils.getUsername(),generated); + return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null,generated); } catch (RuntimeException e) { deleteFailed(stored); throw e; } catch (Exception e) { deleteFailed(stored); throw new ServiceException("附件读取或保存失败,请检查文件后重试"); } } @@ -120,6 +126,8 @@ public class PurchaseDocumentService { public void remove(String type, Long targetId, String id) { requirePermission(true); requireId(id); requireTarget(type, targetId, true); requireFileAccess(type,targetId,id); + if(!db.queryForList("select id from purchase_acceptance_confirmation where attachment_id=? limit 1",id).isEmpty()) + throw new ServiceException("该签章附件已用于验收确认,请保留原件;需要补充时请上传新版本"); if (db.update("update purchase_document_attachment a join purchase_document_group g on g.id=a.group_id set a.deleted=1,a.deleted_by=?,a.deleted_time=current_timestamp where a.id=? and a.deleted=0 and g.target_type=? and g.target_id=?", SecurityUtils.getUsername(), id, type, targetId) != 1) throw new ServiceException("附件不存在或已移除,请刷新资料"); // Keep private bytes and removal metadata for audit. Never delete another business record. @@ -153,11 +161,16 @@ public class PurchaseDocumentService { return db.queryForObject("select id from purchase_document_group where target_type=? and target_id=? and document_kind=?", Long.class, type, targetId, kind); } - private void requireTarget(String type, Long id, boolean lock) { + private static boolean truth(Object value){return Boolean.TRUE.equals(value)||value instanceof Number n&&n.intValue()!=0;} + private boolean requireTarget(String type, Long id, boolean lock) { kinds(type); if (id == null || id <= 0) throw new ServiceException("请先保存采购批次或明细,再上传附件"); String table = "batch".equals(type) ? "purchase_batch" : "purchase_request"; - if (db.queryForList("select id from " + table + " where id=?" + (lock ? " for update" : ""), id).isEmpty()) throw new ServiceException("采购批次或明细不存在,请刷新页面"); + var targets=db.queryForList("select id,create_by,del_flag"+("detail".equals(type)?",(select b.create_by from purchase_batch b where b.id=purchase_request.purchase_batch_id) batch_create_by":"")+" from " + table + " where id=?" + (("detail".equals(type)||lock)?" and del_flag='0'":"") + (lock ? " for update" : ""),id); + if(targets.isEmpty())throw new ServiceException("采购批次或明细不存在,请刷新页面"); + boolean editable="0".equals(Objects.toString(targets.get(0).get("del_flag"),"0"))&&com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)targets.get(0).get("create_by"),(String)targets.get(0).get("batch_create_by")); + if(lock&&!editable)throw new ServiceException("只能维护自己创建的批次或采购明细附件",403); + return editable; } static Map kinds(String type) { diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml index edb9b9b..3eb04f9 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml @@ -3,6 +3,7 @@ + @@ -27,7 +28,7 @@ - select pb.id, pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark, + select (select u.nick_name from sys_user u where convert(u.user_name using utf8mb4) collate utf8mb4_unicode_ci=convert(pb.create_by using utf8mb4) collate utf8mb4_unicode_ci limit 1) creator_name, pb.id, pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark, pb.create_by, pb.create_time, pb.update_by, pb.update_time, count(pr.id) as request_count, group_concat(distinct pj.project_name order by pj.project_name separator '、') project_names, coalesce(sum(case when pr.purchase_status<>5 then pr.estimated_amount else 0 end),0) total_amount, @@ -44,6 +45,7 @@ and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or pr.final_unit_price is null or pr.final_unit_price<>0) left join project_info pj on pj.id=pr.project_id + pb.del_flag='0' and exists(select 1 from purchase_request mine where mine.purchase_batch_id=pb.id and mine.del_flag='0' and mine.create_by=#{createBy} and mine.project_id=#{projectId} @@ -65,7 +67,8 @@ having unpriced_count=0 and unlocked_count>0 having open_count>0 having open_count=0 - order by pb.id desc + order by case when pending_count>0 then 0 when open_count>0 or request_count=0 then 1 else 2 end, + pb.business_date desc, pb.create_time desc, pb.id desc @@ -73,33 +76,33 @@ - + insert into purchase_batch(batch_no, batch_name, purchase_status, progress_remark, create_by, create_time,supplier_id,business_date,expense_category_id) values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate(),#{supplierId},#{businessDate},#{expenseCategoryId}) - update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id} + update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id} and del_flag='0' update purchase_batch set supplier_id=#{supplierId},business_date=#{businessDate}, batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus}, expense_category_id=#{expenseCategoryId}, progress_remark = #{progressRemark}, update_by = #{updateBy}, update_time = sysdate() - where id = #{id} + where id = #{id} and del_flag='0' + + + update purchase_request set purchase_batch_id = #{batch.id}, purchase_batch_no = #{batch.batchNo}, @@ -151,7 +170,7 @@ where purchase_batch_id = #{batchId} - - delete from purchase_batch where id = #{id} - + + update purchase_batch set del_flag='2',update_by=create_by,update_time=current_timestamp where id=#{id} and del_flag='0' + diff --git a/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js b/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js index 355f6b0..94e1411 100644 --- a/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js +++ b/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js @@ -2,3 +2,4 @@ import request from '@/utils/request' export const getPurchaseBoard=(params,signal)=>request({url:'/warehouse/purchase/board',params,signal}) export const getPurchaseCostSummary=(params,signal)=>request({url:'/warehouse/purchase/board/costs',params,signal}) export const setBatchExpenseCategory=(id,data)=>request({url:`/warehouse/purchase/board/${id}/category`,method:'put',data}) +export const savePurchaseBoardOrder=data=>request({url:'/warehouse/purchase/board/order',method:'put',data}) diff --git a/ruoyi-ui-vue3/src/components/Production/ActionHistory.vue b/ruoyi-ui-vue3/src/components/Production/ActionHistory.vue index 4ad173d..cab500e 100644 --- a/ruoyi-ui-vue3/src/components/Production/ActionHistory.vue +++ b/ruoyi-ui-vue3/src/components/Production/ActionHistory.vue @@ -2,7 +2,7 @@