diff --git a/output/pdf/验收单版式示例.pdf b/output/pdf/验收单版式示例.pdf new file mode 100644 index 0000000..cb5a3e7 Binary files /dev/null and b/output/pdf/验收单版式示例.pdf differ diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseAcceptanceReportController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseAcceptanceReportController.java new file mode 100644 index 0000000..c8ecc9b --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseAcceptanceReportController.java @@ -0,0 +1,23 @@ +package com.ruoyi.web.controller.warehouse; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceGenerationService; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/warehouse/purchase/sheet/{id}") +public class PurchaseAcceptanceReportController { + private final PurchaseAcceptanceReportService reports;private final PurchaseAcceptanceGenerationService generation; + public PurchaseAcceptanceReportController(PurchaseAcceptanceReportService reports,PurchaseAcceptanceGenerationService generation){this.reports=reports;this.generation=generation;} + @GetMapping("/acceptance-report") + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") + public AjaxResult preview(@PathVariable long id){return AjaxResult.success(reports.preview(id));} + @PostMapping("/acceptance-generate") + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") + @Log(title="生成采购验收资料",businessType=BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false) + public AjaxResult generate(@PathVariable long id,@RequestParam String version,@RequestBody PurchaseAcceptanceGenerationService.Input input)throws Exception{return AjaxResult.success(generation.generate(id,version,input));} +} 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 new file mode 100644 index 0000000..26e61c4 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseBoardController.java @@ -0,0 +1,31 @@ +package com.ruoyi.web.controller.warehouse; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.warehouse.domain.PurchaseBatch; +import com.ruoyi.web.service.warehouse.PurchaseBoardService; +import com.ruoyi.warehouse.service.impl.PurchaseBatchFundingService; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.enums.BusinessType; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +@RestController +@RequestMapping("/warehouse/purchase/board") +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){} + @PutMapping("/{id}/category") + @PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')") + @Log(title="采购批次费用类别",businessType=BusinessType.UPDATE) + @Transactional + public AjaxResult category(@PathVariable long id,@RequestBody Category input){ + // Acquire the same catalog lock in the service before checking the expected value. + return service.changeCategory(id,input.categoryId(),input.expectedCategoryId(),funding); + } + @GetMapping + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") + public AjaxResult list(PurchaseBatch query,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return AjaxResult.success(service.batches(query,pageNum,pageSize));} + @GetMapping("/costs") + @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") + public AjaxResult costs(PurchaseBatch query,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return AjaxResult.success(service.costs(query,pageNum,pageSize));} +} 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 new file mode 100644 index 0000000..3fb4f9f --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java @@ -0,0 +1,51 @@ +package com.ruoyi.web.service.warehouse; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.service.impl.PurchaseArrivalPhotoService; +import com.ruoyi.warehouse.service.impl.PurchaseDocumentService; +import java.io.*; +import java.nio.file.*; +import java.security.MessageDigest; +import java.util.*; +import org.apache.pdfbox.Loader; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +/** 生成待签章验收资料并作为私有采购附件保存;文件和数据库失败时一并回滚。 */ +@Service +public class PurchaseAcceptanceGenerationService { + private final PurchaseAcceptanceReportService reports;private final PurchaseArrivalPhotoService photos;private final PurchaseDocumentService documents;private final JdbcTemplate db;private final ObjectMapper json; + public record Input(String requestId,PurchaseAcceptanceReportService.Fields fields) { } + public PurchaseAcceptanceGenerationService(PurchaseAcceptanceReportService reports,PurchaseArrivalPhotoService photos,PurchaseDocumentService documents,JdbcTemplate db,ObjectMapper json){this.reports=reports;this.photos=photos;this.documents=documents;this.db=db;this.json=json;} + @Transactional(rollbackFor=Exception.class,isolation=Isolation.READ_COMMITTED) + public PurchaseDocumentService.Attachment generate(long id,String version,Input input)throws Exception{ + 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("采购批次不存在"); + 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()); + if(!previous.isEmpty()){ + var p=previous.get(0); + 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); + } + 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)); + }finally{Files.deleteIfExists(temporary);} + } + private record GeneratedFile(String name,byte[] bytes) implements MultipartFile { + public String getName(){return "file";}public String getOriginalFilename(){return name;}public String getContentType(){return "application/pdf";}public boolean isEmpty(){return bytes.length==0;}public long getSize(){return bytes.length;}public byte[] getBytes(){return bytes;}public InputStream getInputStream(){return new ByteArrayInputStream(bytes);}public void transferTo(File target)throws IOException{Files.write(target.toPath(),bytes);} + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdf.java b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdf.java new file mode 100644 index 0000000..08cd1e0 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdf.java @@ -0,0 +1,137 @@ +package com.ruoyi.web.service.warehouse; + +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.*; +import javax.imageio.ImageIO; +import org.apache.pdfbox.io.IOUtils; +import org.apache.pdfbox.pdmodel.*; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.font.*; +import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; +import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; +import org.apache.pdfbox.util.Matrix; + +/** 按原验收单重绘 A4 七列表格,照片仅取已通过验收的到货凭证,不含扫描章和签名。 */ +public final class PurchaseAcceptancePdf { + @FunctionalInterface public interface Photos { byte[] read(String id); } + private static final float X=62,W=464,H=841.92f,ROW=13; + private static final float[] WIDTHS={28,86,58,47,57,32,156}; + private static final PDFont ENGLISH=new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD_OBLIQUE); + private final PDDocument doc;private final PDType0Font font;private PDPageContentStream pen;private float y;private int page; + private PurchaseAcceptancePdf(PDDocument doc)throws IOException{ + this.doc=doc; + try(var input=PurchaseAcceptancePdf.class.getResourceAsStream("/fonts/NotoSerifSC-Regular.ttf")){ + if(input==null)throw new IOException("验收单中文字体未安装");font=PDType0Font.load(doc,input,true); + } + } + public static void write(Report report,Photos photos,OutputStream output)throws IOException{ + write(report,photos,output,null); + } + public static void write(Report report,Photos photos,OutputStream output,String fingerprint)throws IOException{ + try(var doc=new PDDocument(IOUtils.createTempFileOnlyStreamCache())){ + var pdf=new PurchaseAcceptancePdf(doc);pdf.newPage();pdf.header(report.fields());pdf.tableHeader(); + int index=0;for(var row:report.lines())pdf.row(++index,row,photos); + pdf.footer(report.fields());pdf.pen.close();doc.getDocumentInformation().setTitle(report.batchName()+"材料及部件验收单");doc.getDocumentInformation().setCreator("设备仪器科综合管理系统");if(fingerprint!=null)doc.getDocumentInformation().setCustomMetadataValue("CMVR-Acceptance-Fingerprint",fingerprint);doc.save(output); + } + } + private void newPage()throws IOException{ + if(pen!=null)pen.close();var p=new PDPage(new PDRectangle(595.2f,H));doc.addPage(p);pen=new PDPageContentStream(doc,p);pen.setLineWidth(.45f);page++;y=page==1?66:74; + } + private float bottom(){return page==1?761:777;} + private void header(Fields f)throws IOException{ + box(X,y,W,26,1);center("FINAL ACCEPTANCEREPORT",X,y+2,W,12,9.5f,ENGLISH);boldCenter("终验收报告",X,y+14,W,11,9);y+=26; + float a=114,b=162,c=188; + float r1=Math.max(15,Math.max(height("甲方:"+f.purchaser(),a,5.4f),height("乙方:"+f.supplier(),b,5.8f))); + float r2=Math.max(15,Math.max(height("合同号:"+f.contractNo(),a,6),height("项目号:"+f.projectNo(),b,6))); + float address=height("地址:\n"+f.address(),c,7);if(address>r1+r2)r1+=address-r1-r2; + cell("甲方:"+f.purchaser(),X,y,a,r1,5.4f,false);cell("乙方:"+f.supplier(),X+a,y,b,r1,5.8f,false);cell("地址:\n"+f.address(),X+a+b,y,c,r1+r2,7,false);y+=r1; + cell("合同号:"+f.contractNo(),X,y,a,r2,6,false);cell("项目号:"+f.projectNo(),X+a,y,b,r2,6,false);y+=r2; + float r3=Math.max(15,Math.max(height("项目描述:"+f.description(),a+b,7),height("配送位置:"+f.deliveryLocation(),c,6))); + cell("项目描述:"+f.description(),X,y,a+b,r3,7,false);cell("配送位置:"+f.deliveryLocation(),X+a+b,y,c,r3,6,false);y+=r3+9; + } + private void tableHeader()throws IOException{ + String[] labels={"序号","名称","规格型号/参数要求","采购数量","是否已到货","到货记录","图片"};float x=X; + for(int i=0;i(); + for(String id:row.photos()){byte[] bytes=source.read(id);if(bytes==null)throw new IOException("到货照片读取失败");pictures.add(thumbnail(bytes));} + String[] values={String.valueOf(index),row.name(),row.spec(),number(row.quantity()),"Y","已到货"+number(row.accepted())+row.unit()}; + float[] sizes={6,5.5f,5.3f,6,6,5};var texts=new ArrayList>();int lines=1; + for(int i=0;ibottom())newPage(); + int offset=0;boolean first=true; + // 特长规格可跨页续行,不裁掉文本;普通明细保持原单的紧凑行高。 + do{ + int remaining=texts.stream().mapToInt(java.util.List::size).max().orElse(1)-offset; + int capacity=Math.max(1,(int)((bottom()-y-2)/7.2f));int take=Math.min(Math.max(1,remaining),capacity); + float h=Math.max(ROW,take*7.2f+2);if(first)h=Math.max(h,Math.min(imageRows*13f,bottom()-y));float x=X; + for(int i=0;i<7;i++){box(x,y,WIDTHS[i],h,1);if(i<6){var all=texts.get(i);var part=all.subList(Math.min(offset,all.size()),Math.min(offset+take,all.size()));drawLines(part,x,y,WIDTHS[i],h,sizes[i],i!=1&&i!=2);}x+=WIDTHS[i];} + if(first&&!pictures.isEmpty()){ + float cell=W-WIDTHS[6];for(int i=0;ibottom())newPage(); + checkRow("内容","OK","N.OK",true); + for(int i=0;ibottom())newPage();String value=f.checks().get(i);checkRow(PurchaseAcceptanceReportService.CHECKS.get(i),"OK".equals(value)?"yes":"","N.OK".equals(value)?"yes":"",false); + } + float companies=Math.max(21,Math.max(height(f.purchaser(),172,8),height(f.supplier(),292,8)));float block=21+12+22+8+35+companies+36+8; + if(y+block>bottom())newPage();y+=21; + box(X,y,W,12,.9f);boldCenter("验收结论",X,y,W,12,10);y+=12; + text("1. 供货产品数量与合同一致,满足要求。",X+1,y+9,8,font);text("2. 同意验收",X+1,y+19,8,font);y+=30; + box(X,y,W,35,.65f);boldCenter("ACCEPTANCE SIGNATURE验收签字",X,y,W,35,10);y+=35; + cell(f.purchaser(),X,y,172,companies,8,true);cell(f.supplier(),X+172,y,292,companies,8,true);y+=companies; + box(X,y,172,36,1);box(X+172,y,292,36,1);y+=36; + String date=f.date()==null?"":f.date().toString();cell("Date日期:"+date,X,y,172,8,6.5f,true);cell("Date日期:"+date,X+172,y,292,8,6.5f,true);y+=8; + } + private void checkRow(String label,String ok,String no,boolean header)throws IOException{ + cell(label,X,y,276,13,6.5f,header); + if(header){cell(ok,X+276,y,32,13,7,false);cell(no,X+308,y,156,13,7,false);}else{ + box(X+276,y,32,13,1);box(X+308,y,156,13,1);checkbox(X+280,y+4,"yes".equals(ok));checkbox(X+312,y+4,"yes".equals(no)); + }y+=13; + } + private void checkbox(float x,float top,boolean selected)throws IOException{ + box(x,top,4,4,1);if(selected){pen.moveTo(x,H-top-2);pen.lineTo(x+2,H-top-4);pen.lineTo(x+6,H-top+2);pen.stroke();} + } + private void box(float x,float top,float w,float h,float gray)throws IOException{ + pen.setNonStrokingColor(gray);pen.addRect(x,H-top-h,w,h);pen.fill();pen.setStrokingColor(0f);pen.addRect(x,H-top-h,w,h);pen.stroke();pen.setNonStrokingColor(0f); + } + private float height(String value,float width,float size)throws IOException{return wrap(value,width-4,size).size()*size*1.15f+2;} + private void cell(String value,float x,float top,float width,float height,float size,boolean centered)throws IOException{box(x,top,width,height,1);drawLines(wrap(value,width-4,size),x,top,width,height,size,centered);} + private void center(String value,float x,float top,float width,float height,float size,PDFont face)throws IOException{float w=face.getStringWidth(value)*size/1000;text(value,x+(width-w)/2,top+(height-size)/2+size*.82f,size,face);} + private void boldCenter(String value,float x,float top,float width,float height,float size)throws IOException{pen.setRenderingMode(RenderingMode.FILL_STROKE);pen.setLineWidth(.18f);center(value,x,top,width,height,size,font);pen.setRenderingMode(RenderingMode.FILL);pen.setLineWidth(.45f);} + private void drawLines(java.util.List lines,float x,float top,float width,float height,float size,boolean centered)throws IOException{ + float leading=size*1.2f,start=top+Math.max(1,(height-lines.size()*leading)/2)+size*.87f; + for(int i=0;i wrap(String raw,float width,float size)throws IOException{ + StringBuilder safe=new StringBuilder();for(int cp:Objects.toString(raw,"").codePoints().toArray()){if(cp=='\n'){safe.append('\n');continue;}if(cp<32||cp==127)cp=' ';String value=new String(Character.toChars(cp));try{font.encode(value);safe.append(value);}catch(IllegalArgumentException missing){safe.append('?');}} + var lines=new ArrayList();StringBuilder current=new StringBuilder();float used=0; + for(int cp:safe.toString().codePoints().toArray()){ + String part=new String(Character.toChars(cp));if(cp=='\n'){lines.add(current.toString());current.setLength(0);used=0;continue;} + float advance=font.getStringWidth(part)*size/1000;if(used+advance>width&&!current.isEmpty()){lines.add(current.toString());current.setLength(0);used=0;}current.append(part);used+=advance; + }lines.add(current.toString());return lines; + } + private static String number(java.math.BigDecimal value){return value==null?"":value.stripTrailingZeros().toPlainString();} + private static BufferedImage thumbnail(byte[] bytes)throws IOException{ + try(var stream=ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))){ + var readers=ImageIO.getImageReaders(stream);if(!readers.hasNext())throw new IOException("到货照片格式无效");var reader=readers.next(); + try{reader.setInput(stream,true,true);int width=reader.getWidth(0),height=reader.getHeight(0);if((long)width*height>40_000_000L)throw new IOException("到货照片尺寸过大");var param=reader.getDefaultReadParam();int factor=Math.max(1,(int)Math.ceil(Math.max(width,height)/450d));param.setSourceSubsampling(factor,factor,0,0);var raw=reader.read(0,param);var rgb=new BufferedImage(raw.getWidth(),raw.getHeight(),BufferedImage.TYPE_INT_RGB);var graphics=rgb.createGraphics();try{graphics.setColor(Color.WHITE);graphics.fillRect(0,0,rgb.getWidth(),rgb.getHeight());graphics.drawImage(raw,0,0,null);}finally{graphics.dispose();}return rgb;}finally{reader.dispose();} + } + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportService.java b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportService.java new file mode 100644 index 0000000..7dcfca5 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportService.java @@ -0,0 +1,80 @@ +package com.ruoyi.web.service.warehouse; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.service.impl.PurchaseSheetService; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.*; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.*; + +/** 验收单只读整批真实验收记录;不接受客户端提交物品、数量或验收状态。 */ +@Service +public class PurchaseAcceptanceReportService { + public static final String COMPANY="招商局检测车辆技术研究院有限公司"; + public static final String ADDRESS="重庆市九龙坡区金凤镇"+COMPANY; + public static final String DELIVERY_LOCATION="招商车研"; + public static final List CHECKS=List.of("供货范围是否与合同/技术协议一致","机械安装","电气安装","系统调试","运行结果","培训","资料"); + private final PurchaseSheetService sheets; private final JdbcTemplate db; + public PurchaseAcceptanceReportService(PurchaseSheetService sheets,JdbcTemplate db){this.sheets=sheets;this.db=db;} + public record Fields(String purchaser,String supplier,String address,String contractNo,String projectNo,String description,String deliveryLocation,LocalDate date,List checks) { } + public record Line(long id,String name,String spec,String unit,BigDecimal quantity,BigDecimal accepted,List photos) { } + public record Issue(int line,String name,String reason) { } + public record DocumentCheck(String label,String numberLabel,boolean numbered,int files) { public boolean complete(){return numbered&&files>0;} } + public record Report(String version,String batchName,Fields fields,List lines,List issues) { public boolean ready(){return !lines.isEmpty()&&issues.isEmpty();} } + + @Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ) + public Map preview(long id){ + var report=load(id);var documents=documents(id);var out=new LinkedHashMap();out.put("version",report.version());out.put("ready",report.ready()&&documents.stream().allMatch(DocumentCheck::complete));out.put("count",report.lines().size());out.put("issues",report.issues());out.put("documents",documents);out.put("fields",report.fields());out.put("checkLabels",CHECKS);return out; + } + @Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ) + public Report export(long id,String version,Fields fields){ + var report=load(id); + if(!Objects.equals(report.version(),version))throw new ServiceException("采购清单已变化,请刷新后重新导出验收单"); + if(!report.ready())throw new ServiceException("整批采购明细全部验收通过后才能导出验收单:"+(report.issues().isEmpty()?"没有可导出的明细":report.issues().get(0).reason())); + for(var document:documents(id))if(!document.complete())throw new ServiceException("请先补全"+document.label()+":"+(!document.numbered()?"缺少"+document.numberLabel()+";":"")+(document.files()==0?"缺少PDF附件":"")); + return new Report(report.version(),report.batchName(),validate(fields,report.fields().contractNo()),report.lines(),List.of()); + } + private List documents(long id){ + var rows=db.queryForList("select g.document_kind kind,g.document_no number,(select count(*) from purchase_document_attachment a where a.group_id=g.id and a.deleted=0 and a.content_type='application/pdf') files from purchase_document_group g where g.target_type='batch' and g.target_id=? and g.document_kind in ('REQUEST','QUOTE','CONTRACT')",id); + boolean requestNumber=false,contractNumber=false;int requests=0,contracts=0; + for(var row:rows){String kind=Objects.toString(row.get("kind"),"");int files=((Number)row.get("files")).intValue();boolean numbered=!Objects.toString(row.get("number"),"").isBlank();if("REQUEST".equals(kind)){requestNumber=numbered;requests+=files;}else if("QUOTE".equals(kind))requests+=files;else if("CONTRACT".equals(kind)){contractNumber=numbered;contracts=files;}} + return List.of(new DocumentCheck("采购申请","随行编号",requestNumber,requests),new DocumentCheck("合同","合同编号",contractNumber,contracts)); + } + private Report load(long id){ + var sheet=sheets.load(id);var rows=sheet.getRows().stream().filter(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())).toList(); + var evidence=db.queryForList("select a.id,a.purchase_request_id request_id,cast(a.acceptance_status as signed) status,a.arrival_quantity quantity,a.defective_quantity defective,a.returned_quantity returned,a.accepted_time from purchase_arrival a join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' order by a.id",id); + var photoRows=db.queryForList("select p.id,p.purchase_request_id request_id from purchase_arrival_photo p join purchase_arrival a on a.id=p.arrival_id join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' and a.acceptance_status=1 and a.arrival_quantity-a.defective_quantity-a.returned_quantity>0 order by a.id,p.sort_no,p.id",id); + var lines=new ArrayList();var issues=new ArrayList();LocalDate latest=null; + for(var row:rows){ + var records=evidence.stream().filter(a->((Number)a.get("request_id")).longValue()==row.getId()).toList(); + var accepted=records.stream().filter(a->((Number)a.get("status")).intValue()==1).map(a->decimal(a.get("quantity")).subtract(decimal(a.get("defective"))).subtract(decimal(a.get("returned")))).reduce(BigDecimal.ZERO,BigDecimal::add); + boolean pending=records.stream().anyMatch(a->((Number)a.get("status")).intValue()==0); + String name=Objects.toString(row.getProductName(),"");if(name.isBlank())name=Objects.toString(row.getMaterialName(),""); + String spec=Objects.toString(row.getProductSpec(),"");if(spec.isBlank())spec=Objects.toString(row.getMaterialParams(),""); + lines.add(new Line(row.getId(),name,spec,Objects.toString(row.getUnit(),""),row.getQuantity(),accepted,photoRows.stream().filter(p->((Number)p.get("request_id")).longValue()==row.getId()).map(p->p.get("id").toString()).toList())); + boolean quantityMatches=row.getQuantity()!=null&&row.getQuantity().signum()>0&&accepted.compareTo(row.getQuantity())==0; + if(!quantityMatches||pending)issues.add(new Issue(lines.size(),name,Boolean.TRUE.equals(row.getHistorical())&&records.isEmpty()?"历史完成明细没有真实验收通过记录":pending?"仍有待验收的到货记录":"验收通过数量与采购数量不一致")); + for(var record:records)if(((Number)record.get("status")).intValue()==1&&record.get("accepted_time") instanceof java.sql.Timestamp time){var date=time.toLocalDateTime().toLocalDate();if(latest==null||date.isAfter(latest))latest=date;} + } + var batch=sheet.getBatch();String projectNo="",supplier="";var projectIds=rows.stream().map(PurchaseRequest::getProjectId).filter(Objects::nonNull).distinct().toList(); + if(projectIds.size()==1){var codes=db.queryForList("select project_code from project_info where id=?",String.class,projectIds.get(0));if(!codes.isEmpty())projectNo=Objects.toString(codes.get(0),"");} + if(batch.getSupplierId()!=null){var names=db.queryForList("select name from supplier_info where id=?",String.class,batch.getSupplierId());if(!names.isEmpty())supplier=Objects.toString(names.get(0),"");} + // 合同编号可独立于附件维护;只读取现有批次合同组,不初始化或修改资料记录。 + var contracts=db.queryForList("select document_no from purchase_document_group where target_type='batch' and target_id=? and document_kind='CONTRACT'",String.class,id); + String contractNo=contracts.isEmpty()?"":Objects.toString(contracts.get(0),"").trim(); + var fields=new Fields(COMPANY,supplier,ADDRESS,contractNo,projectNo,Objects.toString(batch.getBatchName(),""),DELIVERY_LOCATION,latest,Collections.nCopies(CHECKS.size(),"")); + return new Report(sheet.getVersion(),Objects.toString(batch.getBatchName(),batch.getBatchNo()),fields,List.copyOf(lines),List.copyOf(issues)); + } + private static Fields validate(Fields f,String contractNo){ + if(f==null)throw new ServiceException("请补充验收单信息"); + if(!Objects.equals(text(f.contractNo(),100),contractNo))throw new ServiceException("批次资料中的合同编号已变化,请重新打开验收单核对"); + var checks=f.checks()==null?Collections.nCopies(CHECKS.size(),""):f.checks(); + if(checks.size()!=CHECKS.size()||checks.stream().anyMatch(s->s==null||!Set.of("","OK","N.OK").contains(s)))throw new ServiceException("验收检查项无效"); + return new Fields(text(f.purchaser(),100),text(f.supplier(),100),ADDRESS,contractNo,text(f.projectNo(),100),text(f.description(),200),DELIVERY_LOCATION,f.date(),List.copyOf(checks)); + } + private static String text(String s,int max){s=s==null?"":s.trim();if(s.length()>max)throw new ServiceException("验收单填写内容过长");return s;} + private static BigDecimal decimal(Object value){return value==null?BigDecimal.ZERO:new BigDecimal(value.toString());} +} 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 new file mode 100644 index 0000000..e34c85d --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseBoardService.java @@ -0,0 +1,83 @@ +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.util.PurchaseQuoteAccess; +import java.util.*; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +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. */ +@Service +public class PurchaseBoardService { + private final JdbcTemplate db;private final CatalogWriteLock catalog; + public PurchaseBoardService(JdbcTemplate db,CatalogWriteLock catalog){this.db=db;this.catalog=catalog;} + public AjaxResult changeCategory(long id,Long category,Long expected,PurchaseBatchFundingService funding){ + catalog.acquire();var rows=db.queryForList("select expense_category_id from purchase_batch where id=? for update",Long.class,id); + if(rows.isEmpty())throw new ServiceException("采购批次不存在"); + if(!Objects.equals(rows.get(0),expected)&&!Objects.equals(rows.get(0),category))throw new ServiceException("费用类别已被其他人修改,请刷新核对"); + funding.change(id,category);return AjaxResult.success(); + } + private record Filter(String sql,List args){} + private Filter filter(PurchaseBatch q){ + var sql=new StringBuilder(" where 1=1");var args=new ArrayList(); + 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());}} + if(q.getSupplierId()!=null){sql.append(" and b.supplier_id=?");args.add(q.getSupplierId());} + if(q.getBeginDate()!=null){sql.append(" and b.business_date>=?");args.add(q.getBeginDate());} + if(q.getEndDate()!=null){sql.append(" and b.business_date<=?");args.add(q.getEndDate());} + if(q.getBeginDate()!=null&&q.getEndDate()!=null&&q.getBeginDate().isAfter(q.getEndDate()))throw new ServiceException("开始日期不能晚于结束日期"); + if(Boolean.TRUE.equals(q.getOnlyMine())){sql.append(" and exists(select 1 from purchase_request mine where mine.purchase_batch_id=b.id and mine.del_flag='0' and mine.create_by=?)");args.add(SecurityUtils.getUsername());} + return new Filter(sql.toString(),args); + } + private static final String FROM=" from purchase_batch b left join supplier_info s on s.id=b.supplier_id "; + private static int size(int value){return Math.max(1,Math.min(100,value));} + private static long offset(int page,int size){if(page<1||page>1000000)throw new ServiceException("页码无效");return (long)(page-1)*size;} + @Transactional(readOnly=true,isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) + 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 "; + var args=new ArrayList<>(f.args());args.add(size);args.add(offset); + var rows=db.queryForList("select 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.id desc 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()); + for(var row:rows){ + var stages=new ArrayList>(); + for(String kind:List.of("REQUEST","CONTRACT","ACCEPTANCE","PAYMENT")){ + var doc=docs.stream().filter(d->Objects.equals(d.get("batchId"),row.get("id"))&&kind.equals(d.get("kind"))).findFirst().orElse(Map.of()); + String number=Objects.toString(doc.get("number"),"");int files=((Number)doc.getOrDefault("files",0)).intValue(); + 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("stages",stages);if(!PurchaseQuoteAccess.allowed()){row.remove("quoteAmount");row.remove("unpricedCount");} + } + } + 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()); + 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 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); + var projects=db.queryForList("select distinct p.id"+joins+where+" order by p.id desc limit ? offset ?",Long.class,pageArgs.toArray()); + List> rows=List.of(); + if(!projects.isEmpty()){ + String marks=String.join(",",Collections.nCopies(projects.size(),"?"));var rowArgs=new ArrayList<>(params);rowArgs.addAll(projects); + rows=db.queryForList("select p.id projectId,p.project_code projectCode,p.project_name projectName,b.expense_category_id expenseCategoryId,coalesce(e.category_name,'待统一') expenseCategoryName,sum(round(r.quantity*r.final_unit_price,6)) quoteAmount,sum(case when r.final_unit_price is null then 1 else 0 end) unpricedCount"+joins+" left join expense_category e on e.id=b.expense_category_id "+where+" and p.id in ("+marks+") group by p.id,p.project_code,p.project_name,b.expense_category_id,e.category_name order by p.id desc,coalesce(min(e.sort_order),99999),b.expense_category_id",rowArgs.toArray()); + } + var summary=db.queryForMap("select sum(round(r.quantity*r.final_unit_price,6)) quoteAmount,sum(case when r.final_unit_price is null then 1 else 0 end) unpricedCount"+joins+where,params.toArray()); + return Map.of("rows",rows,"total",total,"summary",summary); + } +} diff --git a/ruoyi-admin/src/main/resources/fonts/NotoSerifSC-Regular.ttf b/ruoyi-admin/src/main/resources/fonts/NotoSerifSC-Regular.ttf new file mode 100644 index 0000000..a2f6c41 Binary files /dev/null and b/ruoyi-admin/src/main/resources/fonts/NotoSerifSC-Regular.ttf differ diff --git a/ruoyi-admin/src/main/resources/fonts/OFL-NotoSerifSC.txt b/ruoyi-admin/src/main/resources/fonts/OFL-NotoSerifSC.txt new file mode 100644 index 0000000..94d1bf7 --- /dev/null +++ b/ruoyi-admin/src/main/resources/fonts/OFL-NotoSerifSC.txt @@ -0,0 +1,94 @@ +Copyright 2012 Google Inc. All Rights Reserved. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/ruoyi-admin/src/main/resources/fonts/README.txt b/ruoyi-admin/src/main/resources/fonts/README.txt new file mode 100644 index 0000000..61cf441 --- /dev/null +++ b/ruoyi-admin/src/main/resources/fonts/README.txt @@ -0,0 +1,8 @@ +Noto Serif SC (SIL Open Font License 1.1) + +Source: https://github.com/google/fonts/tree/main/ofl/notoserifsc +NotoSerifSC-Regular.ttf was instantiated at wght=400 from the upstream variable +TrueType font with FontTools. See OFL-NotoSerifSC.txt for the distribution license. + +The acceptance-report PDF embeds only the glyphs it uses. Shipping this font keeps +Chinese table layout consistent on Windows and Linux without system font installs. diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PartialPurchaseConfirmTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PartialPurchaseConfirmTest.java index a3856c0..97481b0 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PartialPurchaseConfirmTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PartialPurchaseConfirmTest.java @@ -21,7 +21,7 @@ class PartialPurchaseConfirmTest { @BeforeEach void setup(){ var user=new SysUser();user.setUserId(1L);user.setUserName("admin");var login=new LoginUser(1L,null,user,Set.of("*:*:*"));SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null)); service=new PurchaseSheetService();var batches=mock(PurchaseBatchMapper.class);var requests=mock(PurchaseRequestMapper.class);prices=mock(PurchasePriceService.class);var jdbc=mock(JdbcTemplate.class); - var batch=new PurchaseBatch();batch.setId(5L);batch.setSupplierId(8L);batch.setPurchaseStatus(1); + var batch=new PurchaseBatch();batch.setId(5L);batch.setSupplierId(8L);batch.setPurchaseStatus(1);batch.setExpenseCategoryId(2L); var quoted=new PurchaseRequest();quoted.setId(10L);quoted.setPurchaseStatus(0);quoted.setFinalUnitPrice(BigDecimal.ONE); var draft=new PurchaseRequest();draft.setId(11L);draft.setPurchaseStatus(0); when(batches.selectPurchaseBatchById(5L)).thenReturn(batch);when(requests.selectPurchaseSheetRows(5L)).thenAnswer(call->new ArrayList<>(List.of(quoted,draft)));when(jdbc.queryForList("select id from purchase_batch where id=? for update",5L)).thenReturn(List.of(Map.of("id",5L))); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseAcceptanceGenerationDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseAcceptanceGenerationDatabaseTest.java new file mode 100644 index 0000000..d34d52f --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseAcceptanceGenerationDatabaseTest.java @@ -0,0 +1,44 @@ +package com.ruoyi.projectdev; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ruoyi.common.config.RuoYiConfig; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.service.impl.*; +import com.ruoyi.web.service.warehouse.*; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*; +import java.math.BigDecimal; +import java.nio.file.*; +import java.util.*; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.*; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** 只用虚构报告验证真实附件事务;采购行不修改,附件与私有文件均在测试后回滚。 */ +@EnabledIfSystemProperty(named="projectDbTests",matches="true") +class PurchaseAcceptanceGenerationDatabaseTest { + @TempDir Path temp; + @Test void generatedAttachmentRetryAndSignedUploadShareTheExistingPrivateFileWorkflow()throws Exception{ + String oldProfile=RuoYiConfig.getProfile(); + try(var connection=AuthorizedDatabaseTestSupport.connection();var security=mockStatic(SecurityUtils.class)){ + var source=new SingleConnectionDataSource(connection,true);var db=new JdbcTemplate(source);var manager=new DataSourceTransactionManager(source);var documents=new PurchaseDocumentService();ReflectionTestUtils.setField(documents,"db",db);ReflectionTestUtils.setField(documents,"configuredPath",temp.resolve("private").toString());new RuoYiConfig().setProfile(temp.resolve("public").toString()); + security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("acceptance-rollback-test"); + long batch=db.queryForObject("select b.id from purchase_batch b where (select count(*) from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where g.target_type='batch' and g.target_id=b.id and g.document_kind='ACCEPTANCE' and a.deleted=0)<8 order by b.id limit 1",Long.class); + var beforeBatch=db.queryForMap("select * from purchase_batch where id=?",batch);long count=db.queryForObject("select count(*) from purchase_document_attachment",Long.class),groups=db.queryForObject("select count(*) from purchase_document_group",Long.class); + var reports=mock(PurchaseAcceptanceReportService.class);var fields=new Fields("甲方","乙方","地址","HT-TEST","","虚构报告","招商车研",null,Collections.nCopies(7,""));when(reports.export(batch,"v-test",fields)).thenReturn(new Report("v-test","回滚验证",fields,List.of(new Line(1,"虚构物品","测试规格","个",BigDecimal.ONE,BigDecimal.ONE,List.of())),List.of())); + var target=new PurchaseAcceptanceGenerationService(reports,mock(PurchaseArrivalPhotoService.class),documents,db,new ObjectMapper());var proxy=new org.springframework.aop.framework.ProxyFactory(target);proxy.setProxyTargetClass(true);proxy.addAdvice(new org.springframework.transaction.interceptor.TransactionInterceptor(manager,new org.springframework.transaction.annotation.AnnotationTransactionAttributeSource()));var service=(PurchaseAcceptanceGenerationService)proxy.getProxy(); + String id=UUID.randomUUID().toString(),signed=UUID.randomUUID().toString(); + new TransactionTemplate(manager).executeWithoutResult(status->{status.setRollbackOnly();try{ + var input=new PurchaseAcceptanceGenerationService.Input(id,fields);var saved=service.generate(batch,"v-test",input);assertTrue(saved.name().endsWith("待签章.pdf"));assertEquals(id,service.generate(batch,"v-test",input).id());assertEquals(1,db.queryForObject("select count(*) from purchase_document_attachment where id=?",Integer.class,id));assertTrue(documents.content("batch",batch,id).bytes().length>1000); + documents.upload("batch",batch,"ACCEPTANCE",signed,new MockMultipartFile("file","验收资料_签章版.pdf","application/pdf",documents.content("batch",batch,id).bytes())); + var files=documents.list("batch",batch).stream().filter(g->g.kind().equals("ACCEPTANCE")).findFirst().orElseThrow().files();assertTrue(files.stream().anyMatch(f->f.id().equals(id)));assertTrue(files.stream().anyMatch(f->f.id().equals(signed)));assertEquals(beforeBatch,db.queryForMap("select * from purchase_batch where id=?",batch)); + }catch(Exception error){throw new RuntimeException(error);}}); + assertEquals(count,db.queryForObject("select count(*) from purchase_document_attachment",Long.class));assertEquals(groups,db.queryForObject("select count(*) from purchase_document_group",Long.class));assertFalse(Files.exists(temp.resolve("private/"+id+".bin")));assertFalse(Files.exists(temp.resolve("private/"+signed+".bin")));assertEquals(beforeBatch,db.queryForMap("select * from purchase_batch where id=?",batch)); + }finally{new RuoYiConfig().setProfile(oldProfile);} + } +} 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 3b907d7..577ffc1 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchTransferTest.java @@ -63,6 +63,7 @@ class PurchaseBatchTransferTest { 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(); Fixture(){ + row.setExpenseCategoryId(8L);target.setExpenseCategoryId(8L);ReflectionTestUtils.setField(service,"funding",mock(PurchaseBatchFundingService.class)); row.setId(10L);row.setProjectId(1501L);row.setPurchaseBatchId(1L);row.setSupplierId(7L);row.setPriceLocked(true);row.setPurchaseStatus(4); target.setId(2L);target.setSupplierId(7L);target.setPurchaseStatus(1);target.setBatchNo("CG2026100002"); when(requests.selectPurchaseRequestById(eq(10L),isNull())).thenReturn(row);when(requests.selectPurchaseRequestByIdForUpdate(10L)).thenReturn(row); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java new file mode 100644 index 0000000..472c085 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDatabaseTest.java @@ -0,0 +1,82 @@ +package com.ruoyi.projectdev; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.service.IPurchaseOperationLogService; +import com.ruoyi.warehouse.service.impl.*; +import com.ruoyi.web.service.warehouse.PurchaseBoardService; +import java.math.BigDecimal; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.beans.BeanUtils; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@EnabledIfSystemProperty(named="projectDbTests",matches="true") +class PurchaseBoardDatabaseTest { + @Test void boardStagesAndProjectPaginationNeverMultiplyQuotedAmountsAndQuotesStayPrivate()throws Exception{ + var f=new PurchaseSheetDatabaseTest.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).executeWithoutResult(status->{status.setRollbackOnly(); + var draft=f.draft();long secondProject=draft.getRows().get(1).getProjectId();draft.getRows().get(1).setProjectId(draft.getRows().get(0).getProjectId()); + var saved=f.save(draft);var batch=saved.getBatch();var one=saved.getRows().get(0);var two=saved.getRows().get(1); + // A legacy multi-project batch must be split by its actual lines in project totals. + f.jdbc.update("update purchase_request set project_id=? where id=?",secondProject,two.getId()); + long otherCategory=f.jdbc.queryForObject("select id from expense_category where status=0 and id<>? order by id limit 1",Long.class,one.getExpenseCategoryId()); + var other=new PurchaseBatch();other.setBatchNo(f.name+"-extra");other.setBatchName(f.name+"-extra");other.setExpenseCategoryId(otherCategory);other.setPurchaseStatus(1);other.setBusinessDate(java.time.LocalDate.now());f.batchMapper.insertPurchaseBatch(other); + extra(f,one,other.getId(),otherCategory,0,new BigDecimal("1.25"));extra(f,one,other.getId(),otherCategory,5,new BigDecimal("99999"));extra(f,one,other.getId(),otherCategory,0,null); + for(String kind:List.of("REQUEST","QUOTE","CONTRACT","ACCEPTANCE","PAYMENT")){ + f.jdbc.update("insert into purchase_document_group(target_type,target_id,document_kind,document_no,update_by) values('batch',?,?,?,'sheet-rollback-test')",batch.getId(),kind,Set.of("REQUEST","CONTRACT").contains(kind)?"NO-1":""); + long group=f.jdbc.queryForObject("select id from purchase_document_group where target_type='batch' and target_id=? and document_kind=?",Long.class,batch.getId(),kind); + f.jdbc.update("insert into purchase_document_attachment(id,group_id,original_name,content_type,byte_size,sha256,owner_id,create_by) values(?,?,'test.pdf','application/pdf',1,?,1,'sheet-rollback-test')",UUID.randomUUID().toString(),group,"0".repeat(64)); + } + var service=new PurchaseBoardService(f.jdbc,mock(CatalogWriteLock.class));var q=new PurchaseBatch();q.setKeyword(f.name); + var board=service.batches(q,1,20);assertEquals(2L,board.get("total"));assertMoney("7.50",((Map)board.get("summary")).get("quoteAmount")); + var row=((List>)board.get("rows")).stream().filter(r->Objects.equals(r.get("id"),batch.getId())).findFirst().orElseThrow(); + var stages=(List>)row.get("stages");assertEquals(List.of(true,true,true,false),stages.stream().map(r->r.get("complete")).toList());assertEquals(2,stages.get(0).get("files")); + var costs=service.costs(q,1,20);assertEquals(2L,costs.get("total"));assertEquals(3,((List)costs.get("rows")).size());assertMoney("7.50",((Map)costs.get("summary")).get("quoteAmount")); + for(int page:List.of(1,2)){var single=service.costs(q,page,1);var projectRows=(List>)single.get("rows");assertEquals(1,projectRows.stream().map(r->r.get("projectId")).distinct().count());} + 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)); + }); + } + assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name like ?",Integer.class,f.name+"%")); + } + @Test void changingWholeBatchCategoryPreservesQuantitiesAndPricesAndMovesFundingAndReceiptClassification()throws Exception{ + var f=new PurchaseSheetDatabaseTest.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).executeWithoutResult(status->{status.setRollbackOnly(); + var draft=f.draft();draft.getRows().get(1).setProjectId(draft.getRows().get(0).getProjectId());var saved=f.save(draft);saved=f.service.confirm(saved.getBatch().getId(),saved.getVersion()); + var row=saved.getRows().get(0);long category=f.jdbc.queryForObject("select id from expense_category where status=0 and id<>? order by id limit 1",Long.class,row.getExpenseCategoryId()); + long area=f.jdbc.queryForObject("select id from warehouse_area order by id limit 1",Long.class); + f.jdbc.update("insert into in_record(in_no,product_id,purchase_request_id,source_project_id,expense_category_id,in_type,in_num,in_status) values(?,?,?,?,?,3,1,0)",f.name,row.getProductId(),row.getId(),row.getProjectId(),row.getExpenseCategoryId()); + long receipt=f.jdbc.queryForObject("select id from in_record where in_no=?",Long.class,f.name); + f.jdbc.update("insert into stock_lot(lot_no,area_id,product_id,source_project_id,expense_category_id,purchase_request_id,in_record_id,received_quantity,available_quantity,unit_cost) values(?,?,?,?,?,?,?,1,1,1.25)",f.name,area,row.getProductId(),row.getProjectId(),row.getExpenseCategoryId(),row.getId(),receipt); + var before=f.jdbc.queryForList("select id,quantity,final_unit_price,actual_unit_price,locked_amount,purchase_status from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId()); + f.history();var funding=new PurchaseBatchFundingService(f.jdbc,(CatalogWriteLock)ReflectionTestUtils.getField(f.service,"catalogLock"),f.historyJournal,f.purchaseRows,f.priceService,mock(IPurchaseOperationLogService.class)); + funding.change(saved.getBatch().getId(),category); + assertEquals(before,f.jdbc.queryForList("select id,quantity,final_unit_price,actual_unit_price,locked_amount,purchase_status from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId())); + assertEquals(2,f.jdbc.queryForObject("select count(*) from purchase_request where purchase_batch_id=? and expense_category_id=?",Integer.class,saved.getBatch().getId(),category)); + assertEquals(category,f.jdbc.queryForObject("select expense_category_id from in_record where id=?",Long.class,receipt));assertEquals(category,f.jdbc.queryForObject("select expense_category_id from stock_lot where in_record_id=?",Long.class,receipt)); + assertMoney("1.25",f.jdbc.queryForObject("select unit_cost from stock_lot where in_record_id=?",BigDecimal.class,receipt)); + var invalid=f.service.load(saved.getBatch().getId()).getRows().get(0);invalid.setExpenseCategoryId(row.getExpenseCategoryId()); + var nativePurchases=(com.ruoyi.warehouse.service.IPurchaseRequestService)ReflectionTestUtils.getField(f.service,"purchases");assertThrows(ServiceException.class,()->nativePurchases.updatePurchaseRequest(invalid)); + long count=f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Long.class,saved.getRows().get(0).getId(),saved.getRows().get(1).getId());funding.change(saved.getBatch().getId(),category);assertEquals(count,f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Long.class,saved.getRows().get(0).getId(),saved.getRows().get(1).getId())); + security.when(SecurityUtils::isAdmin).thenReturn(false);long id=saved.getBatch().getId();assertThrows(ServiceException.class,()->funding.change(id,category)); + }); + } + assertEquals(0,f.jdbc.queryForObject("select count(*) from stock_lot where lot_no=?",Integer.class,f.name)); + } + private static void assertMoney(String expected,Object value){assertEquals(0,new BigDecimal(expected).compareTo(new BigDecimal(value.toString())));} + private static void extra(PurchaseSheetDatabaseTest.Fixture f,PurchaseRequest source,long batch,long category,int status,BigDecimal price){ + var row=new PurchaseRequest();BeanUtils.copyProperties(source,row);row.setId(null);row.setRequestNo("TEST-"+UUID.randomUUID());row.setExpenseCategoryId(category);row.setFinalUnitPrice(price);row.setEstimatedUnitPrice(price);row.setPurchaseStatus(status);f.purchaseRows.insertPurchaseRequest(row);f.jdbc.update("update purchase_request set purchase_batch_id=? where id=?",batch,row.getId()); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDevelopmentMigrationTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDevelopmentMigrationTest.java new file mode 100644 index 0000000..cf0a2e0 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBoardDevelopmentMigrationTest.java @@ -0,0 +1,33 @@ +package com.ruoyi.projectdev; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.*; +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 static org.junit.jupiter.api.Assertions.*; + +/** Explicit operator-only development migration. Never runs in the ordinary suite or against production. */ +@EnabledIfSystemProperty(named="applyPurchaseBoardMigration",matches="true") +class PurchaseBoardDevelopmentMigrationTest { + @Test void backupAndApplyDevelopmentStructureAndNavigation()throws Exception{ + try(var c=AuthorizedDatabaseTestSupport.connection()){ + var db=new JdbcTemplate(new SingleConnectionDataSource(c,true)); + Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent(); + var backup=new LinkedHashMap();backup.put("database",c.getCatalog()); + for(String table:List.of("purchase_batch","sys_menu","sys_role_menu")){backup.put(table+"Structure",db.queryForList("show create table "+table));backup.put(table,db.queryForList("select * from "+table));} + Path directory=root.resolve(".codex-tmp/purchase-board-20261104");Files.createDirectories(directory); + Path file=directory.resolve("before-"+System.currentTimeMillis()+".json");new ObjectMapper().findAndRegisterModules().writeValue(file.toFile(),backup);assertTrue(Files.size(file)>100); + String sql=Files.readString(root.resolve("sql/projectdev/20261104_purchase_board.sql")); + boolean hasColumn=db.queryForObject("select count(*) from information_schema.columns where table_schema=database() and table_name='purchase_batch' and column_name='expense_category_id'",Integer.class)>0; + for(String part:sql.replaceAll("(?m)^--.*$","").split(";")){ + String statement=part.trim();if(statement.isEmpty()||hasColumn&&statement.startsWith("ALTER TABLE"))continue; + try(var s=c.createStatement()){s.execute(statement);} + } + assertEquals(1,db.queryForObject("select count(*) from information_schema.columns where table_schema=database() and table_name='purchase_batch' and column_name='expense_category_id'",Integer.class)); + assertEquals(4,db.queryForObject("select count(*) from sys_menu where component in ('warehouse/purchase/index','warehouse/purchaseBoard/index','warehouse/arrival/index','warehouse/acceptance/index')",Integer.class)); + c.commit();System.out.println("Development purchase board migration complete; backup: "+file); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseDocumentsDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseDocumentsDatabaseTest.java index 99e904d..26ef823 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseDocumentsDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseDocumentsDatabaseTest.java @@ -42,7 +42,7 @@ class PurchaseDocumentsDatabaseTest { List uploadedIds=new ArrayList<>(); new TransactionTemplate(manager).executeWithoutResult(status->{ status.setRollbackOnly(); - for(String kind:List.of("REQUEST","QUOTE","CONTRACT","ACCEPTANCE","PAYMENT","OTHER")) { + for(String kind:List.of("REQUEST","CONTRACT","ACCEPTANCE","PAYMENT","OTHER")) { String id=UUID.randomUUID().toString();uploadedIds.add(id); var uploaded=service.upload("batch",batch,kind,id,pdf()); assertEquals(id,uploaded.id()); 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 45b5e63..4b7b68a 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java @@ -468,7 +468,7 @@ class PurchaseSheetDatabaseTest { new TransactionTemplate(f.manager).execute(status->{try { var saved=f.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 raw=new PurchaseBatchServiceImpl();f.set(raw,"purchaseBatchMapper",f.batchMapper);f.set(raw,"funding",mock(PurchaseBatchFundingService.class));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.save(appended);assertEquals(3,updated.getRows().get(0).getPurchaseStatus());assertEquals(0,new BigDecimal("3.75").compareTo(updated.getRows().get(0).getLockedAmount())); @@ -588,7 +588,7 @@ class PurchaseSheetDatabaseTest { assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_sheet_submission where submission_key=?",Integer.class,key)); } - private static class Fixture { + static class Fixture { final String name="SHEET-CHECK-"+UUID.randomUUID(); final JdbcTemplate jdbc; final DataSourceTransactionManager manager; @@ -644,7 +644,7 @@ class PurchaseSheetDatabaseTest { set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别","更正类别"));set(productTarget,"itemCategories",itemCategories);set(purchaseTarget,"itemCategories",itemCategories); PurchaseSheetService target=new PurchaseSheetService();set(target,"batches",session.getMapper(PurchaseBatchMapper.class));set(target,"requests",purchases);set(target,"catalog",catalog);set(target,"products",productService);set(target,"purchases",proxy(purchaseTarget));set(target,"prices",prices);set(target,"suppliers",supplier);set(target,"catalogLock",lock);set(target,"jdbc",jdbc);set(target,"json",new ObjectMapper().findAndRegisterModules());set(target,"dictTypes",dict); set(target,"batchNumbers",numbers);set(target,"operationLogs",logs); service=proxy(target); - set(target,"itemCategories",itemCategories); + set(target,"itemCategories",itemCategories);set(target,"batchFunding",mock(PurchaseBatchFundingService.class)); } 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/warehouse/service/impl/PurchaseDocumentsTest.java b/ruoyi-admin/src/test/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentsTest.java index 0f9e350..0883810 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,14 +21,14 @@ 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 allSixBatchGroupsAreOptionalAndDetailHasOnlyAttachments() { + @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 from ")?List.of(Map.of("id",1)):List.of()); try(var security=mockStatic(SecurityUtils.class)) { security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true); security.when(SecurityUtils::isAdmin).thenReturn(true); - var groups=service.list("batch",1L);assertEquals(6,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty())); - assertEquals(List.of("REQUEST","QUOTE","CONTRACT","ACCEPTANCE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList()); + var groups=service.list("batch",1L);assertEquals(5,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty())); + assertEquals(List.of("REQUEST","CONTRACT","ACCEPTANCE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList()); assertEquals("OTHER",service.list("detail",1L).get(0).kind()); } verify(db,never()).update(anyString(),any(Object[].class)); @@ -54,6 +54,30 @@ class PurchaseDocumentsTest { verify(db,never()).update(anyString(),any(Object[].class)); } + @Test void mergedRequestKeepsRequestNumberAndExistingFilesWithoutExposingLegacyQuoteToOrdinaryUsers() { + JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); + var requestFile=new PurchaseDocumentService.Attachment(ID,"采购申请.pdf","application/pdf",50,"editor",null); + 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 from purchase_batch"))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(); + }); + when(db.query(anyString(),org.mockito.ArgumentMatchers.>any(),eq(5L))).thenReturn(List.of(requestFile)); + when(db.query(anyString(),org.mockito.ArgumentMatchers.>any(),eq(6L))).thenReturn(List.of(quoteFile)); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true); + var merged=service.list("batch",1L).get(0); + assertEquals("REQUEST",merged.kind());assertEquals("SX-001",merged.number());assertEquals(3,merged.version());assertEquals(List.of(requestFile,quoteFile),merged.files()); + security.when(SecurityUtils::isAdmin).thenReturn(false); + security.when(()->SecurityUtils.hasPermi("warehouse:purchase:list")).thenReturn(true); + assertEquals(List.of(requestFile),service.list("batch",1L).get(0).files()); + } + verify(db,never()).update(anyString(),any(Object[].class)); + } + @Test void deniedRequestsNeverReadMetadataAndReadersCannotUploadChangeOrRemove() { JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db); try(var security=mockStatic(SecurityUtils.class)) { @@ -99,6 +123,7 @@ class PurchaseDocumentsTest { when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->call.getArgument(0,String.class).startsWith("select id from ")?List.of(Map.of("id",1)):List.of()); when(db.queryForObject(startsWith("select id from purchase_document_group"),eq(Long.class),eq("batch"),eq(1L),eq("REQUEST"))).thenReturn(5L); when(db.queryForObject(startsWith("select count(*)"),eq(Integer.class),eq(5L))).thenReturn(0); + when(db.queryForObject(startsWith("select count(*)"),eq(Integer.class),eq("batch"),eq(1L))).thenReturn(0); Files.createDirectories(temp.resolve("private"));Path file=temp.resolve("private/"+ID+".bin");Files.writeString(file,"original-private-bytes"); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("editor");security.when(SecurityUtils::getUserId).thenReturn(1L); diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationTest.java new file mode 100644 index 0000000..ed35e7c --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationTest.java @@ -0,0 +1,43 @@ +package com.ruoyi.web.service.warehouse; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.service.impl.*; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*; +import java.math.BigDecimal; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.pdfbox.Loader; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.multipart.MultipartFile; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; + +class PurchaseAcceptanceGenerationTest { + private static final String ID="11111111-1111-4111-8111-111111111111"; + private final Fields fields=new Fields("甲方","乙方","地址","HT-1","","试验材料","招商车研",null,Collections.nCopies(7,"")); + private Report report(Fields value){return new Report("v1","测试批次",value,List.of(new Line(11,"试验物品","M2","个",BigDecimal.ONE,BigDecimal.ONE,List.of())),List.of());} + @Test void generatedPdfBecomesAnAcceptanceAttachmentAndLostResponseRetryDoesNotDuplicate()throws Exception{ + var reports=mock(PurchaseAcceptanceReportService.class);var photos=mock(PurchaseArrivalPhotoService.class);var documents=mock(PurchaseDocumentService.class);var db=mock(JdbcTemplate.class);var bytes=new AtomicReference(); + when(db.queryForList(startsWith("select id from purchase_batch"),eq(1L))).thenReturn(List.of(Map.of("id",1L))); + when(reports.export(eq(1L),eq("v1"),any())).thenAnswer(call->report(call.getArgument(2))); + when(documents.upload(eq("batch"),eq(1L),eq("ACCEPTANCE"),eq(ID),any())).thenAnswer(call->{MultipartFile file=call.getArgument(4);bytes.set(file.getBytes());return new PurchaseDocumentService.Attachment(ID,file.getOriginalFilename(),"application/pdf",bytes.get().length,"tester",null);}); + var service=new PurchaseAcceptanceGenerationService(reports,photos,documents,db,new ObjectMapper()); + try(var security=mockStatic(SecurityUtils.class)){ + security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(7L);security.when(SecurityUtils::getUsername).thenReturn("tester"); + var saved=service.generate(1,"v1",new PurchaseAcceptanceGenerationService.Input(ID,fields));assertEquals(ID,saved.id());assertTrue(saved.name().endsWith("_待签章.pdf")); + try(var pdf=Loader.loadPDF(bytes.get())){assertNotNull(pdf.getDocumentInformation().getCustomMetadataValue("CMVR-Acceptance-Fingerprint"));} + when(db.queryForList(startsWith("select a.owner_id"),eq(ID))).thenReturn(List.of(Map.of("owner_id",7L,"deleted",0,"target_type","batch","target_id",1L,"document_kind","ACCEPTANCE"))); + when(documents.content("batch",1L,ID)).thenReturn(new PurchaseDocumentService.Content(bytes.get(),saved.name(),"application/pdf",true)); + assertEquals(ID,service.generate(1,"v1",new PurchaseAcceptanceGenerationService.Input(ID,fields)).id());verify(documents,times(1)).upload(eq("batch"),eq(1L),eq("ACCEPTANCE"),eq(ID),any()); + var changed=new Fields("甲方","乙方","地址","HT-1","","内容已变","招商车研",null,Collections.nCopies(7,""));assertThrows(ServiceException.class,()->service.generate(1,"v1",new PurchaseAcceptanceGenerationService.Input(ID,changed))); + verify(documents,times(1)).upload(anyString(),anyLong(),anyString(),anyString(),any()); + } + } + @Test void missingPrerequisitesAndWrongActorNeverCreateFiles()throws Exception{ + var reports=mock(PurchaseAcceptanceReportService.class);var photos=mock(PurchaseArrivalPhotoService.class);var documents=mock(PurchaseDocumentService.class);var db=mock(JdbcTemplate.class);when(db.queryForList(startsWith("select id from purchase_batch"),eq(1L))).thenReturn(List.of(Map.of("id",1L)));when(reports.export(1L,"v1",fields)).thenThrow(new ServiceException("缺少采购申请")); + var service=new PurchaseAcceptanceGenerationService(reports,photos,documents,db,new ObjectMapper());try(var security=mockStatic(SecurityUtils.class)){assertThrows(ServiceException.class,()->service.generate(1,"v1",new PurchaseAcceptanceGenerationService.Input(ID,fields)));security.when(SecurityUtils::isAdmin).thenReturn(true);assertThrows(ServiceException.class,()->service.generate(1,"v1",new PurchaseAcceptanceGenerationService.Input(ID,fields)));verifyNoInteractions(documents,photos);} + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdfTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdfTest.java new file mode 100644 index 0000000..065a692 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptancePdfTest.java @@ -0,0 +1,28 @@ +package com.ruoyi.web.service.warehouse; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*; +import java.io.*; +import java.math.BigDecimal; +import java.nio.file.*; +import java.util.*; +import javax.imageio.ImageIO; +import org.apache.pdfbox.Loader; +import org.apache.pdfbox.text.PDFTextStripper; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class PurchaseAcceptancePdfTest { + @Test void reproducesSixPageFormWithPhotosAndBlankSignatureArea()throws Exception{ + var rows=new ArrayList();for(int i=1;i<=254;i++)rows.add(new Line(i,"内六角螺钉","M2*20","个",BigDecimal.valueOf(200),BigDecimal.valueOf(200),i<10?List.of("photo"):List.of())); + var fields=new Fields(PurchaseAcceptanceReportService.COMPANY,"上海则龙信息科技有限公司",PurchaseAcceptanceReportService.ADDRESS,"","","第二代座舱机器人材料及部件(版式示例)",PurchaseAcceptanceReportService.DELIVERY_LOCATION,null,Collections.nCopies(7,"OK")); + var picture=new java.awt.image.BufferedImage(64,64,java.awt.image.BufferedImage.TYPE_INT_RGB);var paint=picture.createGraphics();paint.setColor(java.awt.Color.LIGHT_GRAY);paint.fillRect(0,0,64,64);paint.setColor(java.awt.Color.DARK_GRAY);paint.fillOval(12,12,40,40);paint.dispose();var image=new ByteArrayOutputStream();ImageIO.write(picture,"png",image); + var output=new ByteArrayOutputStream();PurchaseAcceptancePdf.write(new Report("v1","第二代座舱机器人",fields,rows,List.of()),id->image.toByteArray(),output); + var path=Path.of("../.codex-tmp/acceptance-pdf-20261104/验收单版式示例.pdf");Files.createDirectories(path.getParent());Files.write(path,output.toByteArray()); + try(var pdf=Loader.loadPDF(output.toByteArray())){assertEquals(6,pdf.getNumberOfPages());String text=new PDFTextStripper().getText(pdf).replaceAll("\\s","");for(String label:List.of("FINALACCEPTANCEREPORT","终验收报告","合同号","项目号","采购数量","到货记录","培训","资料","验收结论","同意验收","验收签字","254"))assertTrue(text.contains(label),label);assertFalse(text.contains("单价"));assertFalse(text.contains("金额"));assertTrue(pdf.getPage(0).getResources().getXObjectNames().iterator().hasNext());} + } + @Test void veryLongSpecificationsAndSupplementalInformationAreNotClipped()throws Exception{ + String tail="规格末尾完整保留";var spec="超长规格用于验证自动换行及跨页内容".repeat(180)+tail; + var fields=new Fields(PurchaseAcceptanceReportService.COMPANY,"供应商","地址","合同号".repeat(20),"项目号","项目描述","配送位置",null,Collections.nCopies(7,"")); + var output=new ByteArrayOutputStream();PurchaseAcceptancePdf.write(new Report("v1","边界示例",fields,List.of(new Line(1,"试验物品",spec,"个",BigDecimal.ONE,BigDecimal.ONE,List.of())),List.of()),id->null,output); + try(var pdf=Loader.loadPDF(output.toByteArray())){assertTrue(pdf.getNumberOfPages()>1);assertTrue(new PDFTextStripper().getText(pdf).replaceAll("\\s","").contains(tail));} + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportTest.java new file mode 100644 index 0000000..ae2dd5f --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceReportTest.java @@ -0,0 +1,50 @@ +package com.ruoyi.web.service.warehouse; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.service.impl.PurchaseSheetService; +import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*; +import java.math.BigDecimal; +import java.util.*; +import org.junit.jupiter.api.*; +import org.springframework.jdbc.core.JdbcTemplate; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; + +class PurchaseAcceptanceReportTest { + private PurchaseSheet sheet;private PurchaseAcceptanceReportService service;private JdbcTemplate db; + private final Fields fields=new Fields("甲方","乙方","地址","HT-2026-001","","材料及部件","",null,Collections.nCopies(7,"")); + @BeforeEach void setup(){ + sheet=new PurchaseSheet();var batch=new PurchaseBatch();batch.setId(1L);batch.setBatchName("验收测试");sheet.setBatch(batch);sheet.setVersion("v1");sheet.setRows(new ArrayList<>(List.of(row(11,1)))); + var sheets=mock(PurchaseSheetService.class);when(sheets.load(1L)).thenReturn(sheet);db=mock(JdbcTemplate.class);service=new PurchaseAcceptanceReportService(sheets,db); + when(db.queryForList(contains("select document_no from purchase_document_group"),eq(String.class),eq(1L))).thenReturn(List.of("HT-2026-001")); + prerequisites(true,1,true,1); + } + private PurchaseRequest row(long id,int quantity){var row=new PurchaseRequest();row.setId(id);row.setMaterialName("试验物品");row.setMaterialParams("M2*20");row.setQuantity(BigDecimal.valueOf(quantity));row.setPurchaseStatus(4);row.setUnit("个");row.setAcceptedQuantity(BigDecimal.valueOf(quantity));return row;} + private void evidence(int status,int quantity,int defective,int returned){when(db.queryForList(contains("from purchase_arrival a"),eq(1L))).thenReturn(List.of(Map.of("id",1L,"request_id",11L,"status",status,"quantity",quantity,"defective",defective,"returned",returned)));} + private void prerequisites(boolean request,int requestFiles,boolean contract,int contractFiles){when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","REQUEST","number",request?"SX-1":"","files",requestFiles),Map.of("kind","CONTRACT","number",contract?"HT-2026-001":"","files",contractFiles)));} + @Test void acceptsOnlyRealPassedEvidenceAndKeepsOptionalFieldsBlank(){evidence(1,1,0,0);assertTrue(service.export(1,"v1",fields).ready());assertEquals("",service.export(1,"v1",fields).fields().projectNo());assertEquals(1,service.export(1,"v1",fields).lines().size());} + @Test void completedFlagAndSyntheticHistoricalQuantityDoNotSubstituteForAcceptance(){sheet.getRows().get(0).setHistorical(true);assertFalse((Boolean)service.preview(1).get("ready"));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void pendingOrFailedArrivalCannotExport(){evidence(0,1,0,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));evidence(2,1,0,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void returnAndDefectQuantitiesAreNotAcceptedGoods(){evidence(1,2,1,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void overAcceptanceCannotClaimContractQuantitiesMatch(){evidence(1,2,0,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void onePassedRowCannotBypassAnIncompleteBatch(){evidence(1,1,0,0);sheet.getRows().add(row(12,2));assertEquals(1,((List)service.preview(1).get("issues")).size());assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void cancelledRowsAreExcludedButEmptyBatchIsNeverReady(){evidence(1,1,0,0);var cancelled=row(12,2);cancelled.setPurchaseStatus(5);sheet.getRows().add(cancelled);assertEquals(1,service.export(1,"v1",fields).lines().size());sheet.getRows().get(0).setPurchaseStatus(5);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void staleVersionAndInvalidChecklistAreRejected(){evidence(1,1,0,0);assertThrows(ServiceException.class,()->service.export(1,"old",fields));assertThrows(ServiceException.class,()->service.export(1,"v1",new Fields("","","","","","","",null,List.of("OK"))));} + @Test void contractNumberComesFromBatchContractGroup(){ + evidence(1,1,0,0);when(db.queryForList(contains("from purchase_document_group"),eq(String.class),eq(1L))).thenReturn(List.of("HT-2026-001")); + var loaded=(Fields)service.preview(1).get("fields");assertEquals("HT-2026-001",loaded.contractNo());assertEquals("HT-2026-001",service.export(1,"v1",loaded).fields().contractNo()); + } + @Test void fixedAddressesCannotBeOverriddenByRequest(){ + evidence(1,1,0,0);var result=service.export(1,"v1",new Fields("甲方","乙方","伪造地址","HT-2026-001","","材料","伪造配送位置",null,Collections.nCopies(7,""))).fields(); + assertEquals(PurchaseAcceptanceReportService.ADDRESS,result.address());assertEquals(PurchaseAcceptanceReportService.DELIVERY_LOCATION,result.deliveryLocation()); + } + @Test void changedOrForgedContractNumberMustBeReloaded(){ + evidence(1,1,0,0);when(db.queryForList(contains("from purchase_document_group"),eq(String.class),eq(1L))).thenReturn(List.of("HT-A"));var loaded=(Fields)service.preview(1).get("fields"); + when(db.queryForList(contains("from purchase_document_group"),eq(String.class),eq(1L))).thenReturn(List.of("HT-B"));assertThrows(ServiceException.class,()->service.export(1,"v1",loaded)); + var fresh=(Fields)service.preview(1).get("fields");assertEquals("HT-B",service.export(1,"v1",fresh).fields().contractNo()); + } + @Test void completeAcceptanceStillRequiresRequestNumberAndPdf(){evidence(1,1,0,0);prerequisites(false,1,true,1);assertFalse((Boolean)service.preview(1).get("ready"));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));prerequisites(true,0,true,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void contractNumberAloneDoesNotReplaceContractPdf(){evidence(1,1,0,0);prerequisites(true,1,true,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));prerequisites(true,1,false,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} + @Test void mergedLegacyQuoteFilesUseRequestNumberAndNeverQuoteNumber(){evidence(1,1,0,0);when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","REQUEST","number","SX-1","files",0),Map.of("kind","QUOTE","number","Q-OLD","files",1),Map.of("kind","CONTRACT","number","HT-2026-001","files",1)));assertTrue(service.export(1,"v1",fields).ready());when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","QUOTE","number","Q-OLD","files",1),Map.of("kind","CONTRACT","number","HT-2026-001","files",1)));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));} +} diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/exception/PmErrorHandler.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/exception/PmErrorHandler.java index b9ed2d2..260ba42 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/exception/PmErrorHandler.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/exception/PmErrorHandler.java @@ -6,6 +6,7 @@ import com.ruoyi.project.manage.controller.PmIterationController; import com.ruoyi.project.manage.controller.PmReworkController; import com.ruoyi.project.manage.controller.PmScheduleController; import com.ruoyi.project.manage.controller.PmProjectCatalogController; +import com.ruoyi.project.manage.controller.PmFlowLayoutController; import static com.ruoyi.project.manage.util.PmValues.*; @@ -21,7 +22,7 @@ import org.springframework.web.method.annotation.MethodArgumentTypeMismatchExcep import org.springframework.web.multipart.MaxUploadSizeExceededException; /** 局部异常处理优先于旧全局处理,保留 HTTP 状态和结构化冲突,且不暴露 SQL。 */ -@RestControllerAdvice(assignableTypes={PmController.class,PmStageController.class,PmIterationController.class,PmReworkController.class,PmScheduleController.class,PmProjectCatalogController.class}) +@RestControllerAdvice(assignableTypes={PmController.class,PmStageController.class,PmIterationController.class,PmReworkController.class,PmScheduleController.class,PmProjectCatalogController.class,PmFlowLayoutController.class}) @Order(Ordered.HIGHEST_PRECEDENCE) public class PmErrorHandler { /** 返回已鉴权后的安全业务详情,包括阻塞原因、影响任务和依赖路径。 */ 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 26945f5..649b6d1 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 @@ -7,6 +7,9 @@ public class PurchaseBatch extends BaseEntity private static final long serialVersionUID = 1L; private Long id; + private Long expenseCategoryId; + public Long getExpenseCategoryId(){return expenseCategoryId;} + public void setExpenseCategoryId(Long value){expenseCategoryId=value;} private Boolean onlyMine; public Boolean getOnlyMine() { return onlyMine; } public void setOnlyMine(Boolean onlyMine) { this.onlyMine = onlyMine; } 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 new file mode 100644 index 0000000..e06c13e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java @@ -0,0 +1,41 @@ +package com.ruoyi.warehouse.service.impl; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.warehouse.domain.PurchaseRequest; +import com.ruoyi.warehouse.mapper.PurchaseRequestMapper; +import com.ruoyi.warehouse.service.IPurchaseOperationLogService; +import java.util.*; +import org.springframework.beans.BeanUtils; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** 批次费用类别的唯一维护入口。分类变更同步预算占用及入库分类,不改变库存数量或单价。 */ +@Service +public class PurchaseBatchFundingService { + private final JdbcTemplate db;private final CatalogWriteLock catalog;private final InventoryCostJournal inventory; + private final PurchaseRequestMapper requests;private final PurchasePriceService prices;private final IPurchaseOperationLogService logs; + public PurchaseBatchFundingService(JdbcTemplate db,CatalogWriteLock catalog,InventoryCostJournal inventory,PurchaseRequestMapper requests,PurchasePriceService prices,IPurchaseOperationLogService logs){this.db=db;this.catalog=catalog;this.inventory=inventory;this.requests=requests;this.prices=prices;this.logs=logs;} + 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); + validate(category);catalog.acquire();inventory.lockInventory(); + if(db.queryForList("select id from purchase_batch where id=? for update",batch).isEmpty())throw new ServiceException("采购批次不存在"); + 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; + var next=new PurchaseRequest();BeanUtils.copyProperties(old,next);next.setExpenseCategoryId(category); + String actor=SecurityUtils.getUsername(); + db.update("update purchase_request set expense_category_id=?,update_by=?,update_time=current_timestamp where id=?",category,actor,id); + db.update("update in_record set expense_category_id=?,update_time=current_timestamp where purchase_request_id=? and in_status in (0,1)",category,id); + db.update("update stock_lot l left join in_record r on r.id=l.in_record_id set l.expense_category_id=?,l.update_by=?,l.update_time=current_timestamp where l.lot_status in (0,1) and (l.purchase_request_id=? or r.purchase_request_id=?)",category,actor,id,id); + prices.refreshLockedAmount(old,next,"BATCH_CATEGORY"); + logs.record(id,old.getRequestNo(),"BATCH_CATEGORY","统一批次费用类别","费用类别:"+old.getExpenseCategoryId()+" → "+category+";批次:"+batch); + } + db.update("update purchase_batch set expense_category_id=?,update_by=?,update_time=current_timestamp where id=?",category,SecurityUtils.getUsername(),batch); + // Flush mapper cache after JDBC changes; the next sheet snapshot must see the new category. + for(Long id:ids)requests.selectPurchaseRequestByIdForUpdate(id); + } +} 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 44f6147..e9cb98c 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 @@ -30,6 +30,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService @Autowired private SupplierService suppliers; @Autowired private PurchaseBatchNumber batchNumbers; @Autowired private CatalogWriteLock catalogWriteLock; + @Autowired private PurchaseBatchFundingService funding; @Override public List selectPurchaseBatchList(PurchaseBatch batch) @@ -58,6 +59,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService batch.setPurchaseStatus(1); } batch.setBatchNo(null); // New batches use CG + year/month + shared sequence. + if(batch.getExpenseCategoryId()!=null)funding.validate(batch.getExpenseCategoryId()); normalizeAndValidate(batch); if (purchaseBatchMapper.selectPurchaseBatchByNo(batch.getBatchNo()) != null) { @@ -77,6 +79,8 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService { throw new ServiceException("采购批次不存在"); } + 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())) { PurchaseRequest query = new PurchaseRequest(); query.setPurchaseBatchId(batch.getId()); if (purchaseRequestMapper.selectPurchaseRequestList(query).stream().anyMatch(row -> @@ -149,11 +153,13 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService // Creation and assignment share this transaction: a failed move leaves no orphan batch. PurchaseBatch input=request.getNewBatch();batch=new PurchaseBatch(); batch.setBatchName(input.getBatchName());batch.setBusinessDate(input.getBusinessDate()); + batch.setExpenseCategoryId(input.getExpenseCategoryId()); + if(batch.getExpenseCategoryId()==null){var categories=requests.stream().map(PurchaseRequest::getExpenseCategoryId).collect(java.util.stream.Collectors.toSet());if(categories.size()==1)batch.setExpenseCategoryId(categories.iterator().next());} batch.setSupplierId(input.getSupplierId());batch.setPurchaseStatus(1); validateSupplier(requests,batch); if(request.getRequestKey()==null||!request.getRequestKey().matches("[A-Za-z0-9-]{8,100}"))throw new ServiceException("新建转批次缺少安全重试标识,请重新打开转批次窗口"); if(batch.getBusinessDate()==null)throw new ServiceException("请选择新批次日期"); - String payload=SecurityUtils.getUsername()+"|"+request.getRequestKey()+"|"+java.util.Arrays.toString(request.getRequestIds())+"|"+batch.getSupplierId()+"|"+batch.getBusinessDate()+"|"+StringUtils.trim(batch.getBatchName()); + String payload=SecurityUtils.getUsername()+"|"+request.getRequestKey()+"|"+java.util.Arrays.toString(request.getRequestIds())+"|"+batch.getSupplierId()+"|"+batch.getBusinessDate()+"|"+StringUtils.trim(batch.getBatchName())+"|"+batch.getExpenseCategoryId(); String digest; try{digest=java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(payload.getBytes(java.nio.charset.StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);} batch.setBatchNo(batchNumbers.reserve(batch.getBusinessDate(),"batch-move:"+digest)); @@ -171,7 +177,14 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService if(purchaseBatchMapper.selectBatchProjectIds(batch.getId()).stream().anyMatch(id->!projects.contains(id)))throw new ServiceException("目标批次属于其他项目,请选择同项目批次或新建批次"); validateSupplier(requests,batch); } + if(batch.getExpenseCategoryId()==null){ + var categories=new java.util.HashSet();requests.forEach(row->categories.add(row.getExpenseCategoryId())); + purchaseRequestMapper.selectPurchaseSheetRows(batch.getId()).stream().filter(row->!Integer.valueOf(5).equals(row.getPurchaseStatus())).forEach(row->categories.add(row.getExpenseCategoryId())); + if(categories.size()==1&&!categories.contains(null))batch.setExpenseCategoryId(categories.iterator().next()); + } + if(batch.getExpenseCategoryId()==null)throw new ServiceException("请先为目标批次选择统一费用类别"); purchaseBatchMapper.assignRequests(request.getRequestIds(), batch, SecurityUtils.getUsername()); + funding.change(batch.getId(),batch.getExpenseCategoryId()); for (PurchaseRequest purchaseRequest : requests) { String previous = StringUtils.isBlank(purchaseRequest.getPurchaseBatchNo()) 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 90d0c36..fc57894 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 @@ -26,7 +26,7 @@ public class PurchaseDocumentService { static final int MAX_BYTES = 10 * 1024 * 1024, MAX_FILES = 10; static final Map BATCH_KINDS = new LinkedHashMap<>(); static { - BATCH_KINDS.put("REQUEST", "采购申请"); BATCH_KINDS.put("QUOTE", "报价资料"); + BATCH_KINDS.put("REQUEST", "采购申请"); BATCH_KINDS.put("CONTRACT", "合同"); BATCH_KINDS.put("ACCEPTANCE", "验收资料"); BATCH_KINDS.put("PAYMENT", "付款资料"); BATCH_KINDS.put("OTHER", "其他附件"); } @@ -45,17 +45,20 @@ public class PurchaseDocumentService { requirePermission(false); requireTarget(type, targetId, false); List result = new ArrayList<>(); for (var kind : kinds(type).entrySet()) { - if("QUOTE".equals(kind.getKey())&&!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())continue; 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()); - if (groups.isEmpty()) result.add(new Group(kind.getKey(), kind.getValue(), "", 0, List.of())); - else { + var attachments=new ArrayList();String number="";int version=0; + if (!groups.isEmpty()) { var group = groups.get(0); - var files = 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.get("id")); - result.add(new Group(kind.getKey(), kind.getValue(), Objects.toString(group.get("document_no"), ""), ((Number) group.get("version")).intValue(), files)); + number=Objects.toString(group.get("document_no"),"");version=((Number)group.get("version")).intValue();attachments.addAll(files(group.get("id"))); } + // 合并展示历史报价附件,保留原归属与报价访问门禁;报价编号不再展示或维护。 + 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))); } 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);} @Transactional public void saveNumber(String type, Long targetId, String kind, String number, Integer version) { @@ -95,8 +98,9 @@ public class PurchaseDocumentService { throw new ServiceException("上传请求已变化,请重新选择附件"); return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null); } - if (db.queryForObject("select count(*) from purchase_document_attachment where group_id=? and deleted=0", Integer.class, group) >= MAX_FILES) - throw new ServiceException("每类资料最多保留10个附件,请移除不再需要的文件后上传"); + 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); + if(count>=limit)throw new ServiceException("本类资料最多保留"+limit+"个附件,请移除不再需要的文件后上传"); Path candidate = root().resolve(uploadId + ".bin"); if (storage != null) storage.save("purchase/" + uploadId + ".bin", valid.bytes(), valid.type(), candidate); else Files.write(candidate, valid.bytes(), StandardOpenOption.CREATE_NEW); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java index 86a592a..0f5d072 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseHistoryCorrectionService.java @@ -95,6 +95,7 @@ public class PurchaseHistoryCorrectionService { } private Plan plan(Entry entry,Command command){ PurchaseRequest old=requests.selectPurchaseRequestById(entry.id(),null);if(old==null)throw new ServiceException("采购明细不存在");projects.requireProjectAccess(old.getProjectId()); + if(old.getPurchaseBatchId()!=null&&entry.changes().containsKey("expenseCategoryId"))throw new ServiceException("费用类别已按批次管理,请在采购看板统一整批费用类别"); if(Integer.valueOf(5).equals(old.getPurchaseStatus()))throw new ServiceException("已取消明细请先核对业务状态,不能通过历史更正恢复采购"); var oldMap=json.convertValue(old,LinkedHashMap.class); var patch=new LinkedHashMap(oldMap);entry.changes().forEach(patch::put);PurchaseRequest next=json.convertValue(patch,PurchaseRequest.class); 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 0f6a2af..6def938 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 @@ -128,6 +128,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService throw new ServiceException("采购申请ID不能为空"); } PurchaseRequest existing = requireRequestForUpdate(purchaseRequest.getId()); + purchaseRequest.setPurchaseBatchId(existing.getPurchaseBatchId()); com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(purchaseRequest, existing); if(!purchaseRequest.isActualUnitPriceProvided())purchaseRequest.setActualUnitPrice(existing.getActualUnitPrice()); if(existing.getProductionTaskId()!=null)purchaseRequest.setProductionTaskId(existing.getProductionTaskId()); @@ -619,6 +620,12 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService projectInfoService.requireActiveProject(project.getId()); ExpenseCategory category = null; + if(request.getPurchaseBatchId()!=null){ + var batchCategories=taskDatabase.queryForList("select expense_category_id from purchase_batch where id=?",Long.class,request.getPurchaseBatchId()); + if(batchCategories.isEmpty()||batchCategories.get(0)==null)throw new ServiceException("请先在采购批次统一费用类别"); + if(request.getExpenseCategoryId()!=null&&!java.util.Objects.equals(request.getExpenseCategoryId(),batchCategories.get(0)))throw new ServiceException("费用类别已按批次管理,请在采购看板统一整批费用类别"); + request.setExpenseCategoryId(batchCategories.get(0)); + } if (request.getExpenseCategoryId() != null) { category = projectBudgetMapper.selectExpenseCategoryById(request.getExpenseCategoryId()); 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 9da82d6..b54d17b 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 @@ -30,6 +30,7 @@ public class PurchaseSheetService @Autowired private ObjectMapper json; @Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes; @Autowired private ItemCategoryService itemCategories; + @Autowired private PurchaseBatchFundingService batchFunding; @Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) public PurchaseSheet load(Long id) @@ -60,6 +61,8 @@ public class PurchaseSheetService if(targetId==null){batch=new PurchaseBatch();batch.setBusinessDate(java.time.LocalDate.now());batch.setBatchNo(batchNumbers.next(batch.getBusinessDate()));batch.setPurchaseStatus(1);batch.setCreateBy(SecurityUtils.getUsername());batches.insertPurchaseBatch(batch);} else {lockBatch(targetId);batch=batches.selectPurchaseBatchById(targetId);if(batch==null||!Integer.valueOf(1).equals(batch.getPurchaseStatus())||requests.selectPurchaseSheetRows(targetId).stream().anyMatch(this::committed))throw new ServiceException("只能加入尚未确认、没有到货的采购批次");} batches.assignRequests(ids,batch,SecurityUtils.getUsername()); + if(batch.getExpenseCategoryId()==null){var categories=requests.selectPurchaseSheetRows(batch.getId()).stream().map(PurchaseRequest::getExpenseCategoryId).collect(java.util.stream.Collectors.toSet());if(categories.size()==1&&!categories.contains(null)){batch.setExpenseCategoryId(categories.iterator().next());batches.updatePurchaseBatch(batch);}} + if(batch.getExpenseCategoryId()!=null)batchFunding.change(batch.getId(),batch.getExpenseCategoryId()); for(var r:rows)operationLogs.record(r.getId(),r.getRequestNo(),"BATCH_ASSIGN","采购组批","未分批 → "+batch.getBatchNo()); return load(batch.getId()); } @@ -133,7 +136,7 @@ public class PurchaseSheetService private String submissionFingerprint(PurchaseSheet sheet) { var payload = json.createObjectNode(); payload.put("unbatched",sheet.isUnbatched());payload.put("version",sheet.getVersion()); - payload.set("batch",submissionFields(sheet.getBatch(),List.of("id","supplierId","batchName","businessDate","progressRemark"))); + payload.set("batch",submissionFields(sheet.getBatch(),List.of("id","supplierId","batchName","businessDate","progressRemark","expenseCategoryId"))); var rows = payload.putArray("rows"); if (sheet.getRows() != null) for (var row : sheet.getRows()) { var fields = submissionFields(row,List.of("id","requestNo","projectId","projectCode","expenseCategoryId","expenseCategoryCode", @@ -191,6 +194,18 @@ public class PurchaseSheetService requirePermission("remove"); } if (!submitted.equals(old.keySet())) throw new ServiceException("采购明细不完整,请重新打开批次"); + if(batch.getExpenseCategoryId()==null&&oldBatch!=null)batch.setExpenseCategoryId(oldBatch.getExpenseCategoryId()); + if(batch.getExpenseCategoryId()==null){ + var categories=sheet.getRows().stream().filter(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())).map(PurchaseRequest::getExpenseCategoryId).collect(java.util.stream.Collectors.toSet()); + if(categories.size()==1&&!categories.contains(null))batch.setExpenseCategoryId(categories.iterator().next()); + } + if(batch.getExpenseCategoryId()==null)throw new ServiceException("请在批次信息选择统一的费用类别"); + if(oldBatch==null||!Objects.equals(oldBatch.getExpenseCategoryId(),batch.getExpenseCategoryId()))batchFunding.validate(batch.getExpenseCategoryId()); + if(oldBatch!=null&&oldRows.stream().anyMatch(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())&&!Objects.equals(r.getExpenseCategoryId(),batch.getExpenseCategoryId()))) { + batchFunding.change(batch.getId(),batch.getExpenseCategoryId()); + old.values().stream().filter(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())).forEach(r->r.setExpenseCategoryId(batch.getExpenseCategoryId())); + } + sheet.getRows().stream().filter(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())).forEach(r->r.setExpenseCategoryId(batch.getExpenseCategoryId())); // A saved preparation list may not have a supplier until the quote is confirmed. if (batch.getSupplierId() != null) suppliers.requireActive(batch.getSupplierId()); if (oldBatch != null && oldBatch.getSupplierId() != null && !Objects.equals(batch.getSupplierId(), oldBatch.getSupplierId()) @@ -259,6 +274,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(sheet.getBatch().getExpenseCategoryId()==null)throw new ServiceException("请先在批次信息统一费用类别,再确认采购"); List confirming=sheet.getRows(); if(selectedIds!=null){ Set wanted=new HashSet<>(selectedIds); diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml index 5283bea..edb9b9b 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 @@ + @@ -97,26 +98,26 @@ - 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}) + 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 supplier_id=#{supplierId},business_date=#{businessDate}, batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus}, - progress_remark = #{progressRemark}, update_by = #{updateBy}, update_time = sysdate() + expense_category_id=#{expenseCategoryId}, progress_remark = #{progressRemark}, update_by = #{updateBy}, update_time = sysdate() where id = #{id} diff --git a/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js b/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js new file mode 100644 index 0000000..355f6b0 --- /dev/null +++ b/ruoyi-ui-vue3/src/api/warehouse/purchase-board.js @@ -0,0 +1,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}) diff --git a/ruoyi-ui-vue3/src/components/ItemCategorySelect/Applications.vue b/ruoyi-ui-vue3/src/components/ItemCategorySelect/Applications.vue index c379391..de40ca7 100644 --- a/ruoyi-ui-vue3/src/components/ItemCategorySelect/Applications.vue +++ b/ruoyi-ui-vue3/src/components/ItemCategorySelect/Applications.vue @@ -21,7 +21,7 @@ - + diff --git a/ruoyi-ui-vue3/src/components/PurchaseDocuments/index.vue b/ruoyi-ui-vue3/src/components/PurchaseDocuments/index.vue index 1a7cbf5..1d267ce 100644 --- a/ruoyi-ui-vue3/src/components/PurchaseDocuments/index.vue +++ b/ruoyi-ui-vue3/src/components/PurchaseDocuments/index.vue @@ -1,14 +1,15 @@ + diff --git a/ruoyi-ui-vue3/src/components/PurchaseSheet/BatchCategory.vue b/ruoyi-ui-vue3/src/components/PurchaseSheet/BatchCategory.vue index 3044e14..edebd39 100644 --- a/ruoyi-ui-vue3/src/components/PurchaseSheet/BatchCategory.vue +++ b/ruoyi-ui-vue3/src/components/PurchaseSheet/BatchCategory.vue @@ -9,11 +9,11 @@
{{ running?'正在推荐':stopped?'已停止':completed===targets.length?'推荐完成':'待继续推荐' }} {{ completed }} / {{ targets.length }} 行
全选可用结果已选 {{ chosen.length }} 行 · {{ newCount }} 个新小类将申请后使用
- + -