feat(item-category): 添加物品分类申请与审核管理功能

- 新增物品分类申请及审核记录相关数据库表结构
- 添加物品分类管理菜单及对应的角色权限配置
- 实现物品分类申请组件支持新增申请与历史记录查询
- 开发批量AI分类组件以支持采购明细的智能分类推荐
- 新增批量确认小类组件以便管理员快速处理待确认分类
- 构建物品分类管理页面提供分类审核调整及关联记录查看
This commit is contained in:
lixiaolong 2026-11-04 17:13:10 +08:00
parent e1915bed8b
commit 1dffc220a6
57 changed files with 1234 additions and 82 deletions

Binary file not shown.

View File

@ -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));}
}

View File

@ -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));}
}

View File

@ -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);}
}
}

View File

@ -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<labels.length;i++){box(x,y,WIDTHS[i],16,.85f);center(labels[i],x,y,WIDTHS[i],16,i==2?5.5f:6.2f,font);x+=WIDTHS[i];}y+=16;
}
private void row(int index,Line row,Photos source)throws IOException{
var pictures=new ArrayList<BufferedImage>();
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<java.util.List<String>>();int lines=1;
for(int i=0;i<values.length;i++){var wrapped=wrap(values[i],WIDTHS[i]-3,sizes[i]);texts.add(wrapped);lines=Math.max(lines,wrapped.size());}
int imageRows=(pictures.size()+5)/6;float total=Math.max(ROW,Math.max(lines*7.2f+2,imageRows*13f));
if(y+total>bottom())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;i<pictures.size();i++){
var image=pictures.get(i);int columns=Math.min(6,pictures.size());float slot=WIDTHS[6]/columns;float maxH=Math.min(26,(h-1)/Math.max(1,imageRows));
float scale=Math.min((slot-2)/image.getWidth(),maxH/image.getHeight());float iw=image.getWidth()*scale,ih=image.getHeight()*scale;
float px=X+cell+(i%columns)*slot+(slot-iw)/2,py=y+(i/columns)*maxH+(maxH-ih)/2;
pen.drawImage(JPEGFactory.createFromImage(doc,image,.85f),px,H-py-ih,iw,ih);
}
}
y+=h;offset+=take;first=false;if(offset<lines)newPage();
}while(offset<lines);
}
private void footer(Fields f)throws IOException{
if(y+13<=bottom()){box(X,y,W,13,1);y+=13;}y+=7;
if(y+26>bottom())newPage();
checkRow("内容","OK","N.OK",true);
for(int i=0;i<PurchaseAcceptanceReportService.CHECKS.size();i++){
if(y+13>bottom())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<String> 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<lines.size();i++){String line=lines.get(i);float w=font.getStringWidth(line)*size/1000;text(line,centered?x+(width-w)/2:x+1.5f,start+i*leading,size,font);}
}
private void text(String value,float x,float baseline,float size,PDFont face)throws IOException{pen.beginText();pen.setFont(face,size);pen.setTextMatrix(Matrix.getTranslateInstance(x,H-baseline));pen.showText(value);pen.endText();}
private java.util.List<String> 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<String>();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();}
}
}
}

View File

@ -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<String> 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<String> checks) { }
public record Line(long id,String name,String spec,String unit,BigDecimal quantity,BigDecimal accepted,List<String> 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<Line> lines,List<Issue> issues) { public boolean ready(){return !lines.isEmpty()&&issues.isEmpty();} }
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Map<String,Object> preview(long id){
var report=load(id);var documents=documents(id);var out=new LinkedHashMap<String,Object>();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<DocumentCheck> 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<Line>();var issues=new ArrayList<Issue>();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());}
}

View File

@ -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<Object> args){}
private Filter filter(PurchaseBatch q){
var sql=new StringBuilder(" where 1=1");var args=new ArrayList<Object>();
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<String,Object> 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<Map<String,Object>>();
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<String,Object> 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<String,Object> 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<Map<String,Object>> 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);
}
}

View File

@ -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.

View File

@ -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.

View File

@ -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)));

View File

@ -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);}
}
}

View File

@ -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);

View File

@ -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<Map<String,Object>>)board.get("rows")).stream().filter(r->Objects.equals(r.get("id"),batch.getId())).findFirst().orElseThrow();
var stages=(List<Map<String,Object>>)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<Map<String,Object>>)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<Map<String,Object>>)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());
}
}

View File

@ -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<String,Object>();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);
}
}
}

View File

@ -42,7 +42,7 @@ class PurchaseDocumentsDatabaseTest {
List<String> 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());

View File

@ -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);

View File

@ -21,14 +21,14 @@ class PurchaseDocumentsTest {
static final byte[] PDF="%PDF-1.7\n1 0 obj<</Type/Catalog>>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.<org.springframework.jdbc.core.RowMapper<PurchaseDocumentService.Attachment>>any(),eq(5L))).thenReturn(List.of(requestFile));
when(db.query(anyString(),org.mockito.ArgumentMatchers.<org.springframework.jdbc.core.RowMapper<PurchaseDocumentService.Attachment>>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);

View File

@ -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<byte[]>();
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);}
}
}

View File

@ -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<Line>();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));}
}
}

View File

@ -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));}
}

View File

@ -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 {
/** 返回已鉴权后的安全业务详情,包括阻塞原因、影响任务和依赖路径。 */

View File

@ -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; }

View File

@ -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);
}
}

View File

@ -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<PurchaseBatch> 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<Long>();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())

View File

@ -26,7 +26,7 @@ public class PurchaseDocumentService {
static final int MAX_BYTES = 10 * 1024 * 1024, MAX_FILES = 10;
static final Map<String, String> 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<Group> 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<Attachment>();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<Attachment> 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);

View File

@ -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<String,Object>(oldMap);entry.changes().forEach(patch::put);PurchaseRequest next=json.convertValue(patch,PurchaseRequest.class);

View File

@ -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());

View File

@ -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<PurchaseRequest> confirming=sheet.getRows();
if(selectedIds!=null){
Set<Long> wanted=new HashSet<>(selectedIds);

View File

@ -3,6 +3,7 @@
<mapper namespace="com.ruoyi.warehouse.mapper.PurchaseBatchMapper">
<resultMap type="PurchaseBatch" id="PurchaseBatchResult">
<id property="id" column="id"/>
<result property="expenseCategoryId" column="expense_category_id"/>
<result property="supplierId" column="supplier_id"/><result property="supplierName" column="supplier_name"/><result property="businessDate" column="business_date"/>
<result property="batchNo" column="batch_no"/>
<result property="batchName" column="batch_name"/>
@ -97,26 +98,26 @@
</select>
<select id="selectPurchaseBatchById" parameterType="Long" resultMap="PurchaseBatchResult">
select id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
select id,expense_category_id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
from purchase_batch where id = #{id}
</select>
<select id="selectPurchaseBatchByNo" parameterType="String" resultMap="PurchaseBatchResult">
select id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
select id,expense_category_id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
from purchase_batch where batch_no = #{batchNo} limit 1
</select>
<select id="selectPurchaseBatchForUpdate" resultMap="PurchaseBatchResult">select * from purchase_batch where id=#{id} for update</select>
<insert id="insertPurchaseBatch" parameterType="PurchaseBatch" useGeneratedKeys="true" keyProperty="id">
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})
</insert>
<update id="updateBatchRemark">update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id}</update>
<update id="updatePurchaseBatch" parameterType="PurchaseBatch">
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}
</update>

View File

@ -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})

View File

@ -21,7 +21,7 @@
<el-table-column label="状态" width="90" align="center" class-name="business-status-cell"><template #default="{row}"><el-tag :type="states[row.status]?.type" size="small">{{ states[row.status]?.label||row.status }}</el-tag></template></el-table-column>
<el-table-column prop="effectiveName" label="当前分类" min-width="130" show-overflow-tooltip/><el-table-column prop="reviewNote" label="处理说明" min-width="130" show-overflow-tooltip/>
<el-table-column label="申请时间" width="150"><template #default="{row}">{{ formatDateTime(row.createTime) }}</template></el-table-column>
<el-table-column label="操作" width="105" fixed="right" align="center"><template #default="{row}"><el-button v-if="row.type==='LEAF'&&['PENDING','APPROVED','ADJUSTED'].includes(row.status)" link type="primary" @click="useCategory(row)">使用分类</el-button><span v-else>—</span></template></el-table-column>
<el-table-column label="操作" width="105" fixed="right" align="center" class-name="business-operation-cell"><template #default="{row}"><el-button v-if="row.type==='LEAF'&&['PENDING','APPROVED','ADJUSTED'].includes(row.status)" link type="primary" @click="useCategory(row)">使用分类</el-button><span v-else>—</span></template></el-table-column>
</el-table>
<el-pagination v-if="total>query.pageSize" class="category-application-pages" background layout="total, prev, pager, next" :total="total" :page-size="query.pageSize" v-model:current-page="query.pageNum" @current-change="load"/>
</template>

View File

@ -1,14 +1,15 @@
<template>
<el-drawer v-model="visible" :title="title" size="min(1000px,96vw)" append-to-body destroy-on-close :close-on-click-modal="false" :before-close="beforeClose" @closed="releasePreview">
<div class="purchase-documents" :aria-busy="busy" v-loading="loading">
<div class="purchase-documents__context">{{ context }}<span>可选资料,不影响采购、到货、验收或付款流程。</span></div>
<div class="purchase-documents__context">{{ context }}<span>生成验收资料前需补齐采购申请、合同的编号及PDF附件;资料维护不改变采购、到货或付款状态。</span></div>
<el-alert v-if="error" :title="error" type="error" show-icon :closable="false"><el-button link @click="load">重新加载</el-button></el-alert>
<template v-if="!error">
<div v-if="type==='batch'" class="purchase-documents__kinds" role="tablist" aria-label="采购资料分类">
<el-button v-for="item in visibleKinds" :key="item.kind" :type="activeKind===item.kind?'primary':''" :plain="activeKind!==item.kind" :disabled="busy" role="tab" :aria-selected="activeKind===item.kind" @click="switchKind(item.kind)">{{ item.label }} <span class="purchase-documents__count">{{ groups.find(g=>g.kind===item.kind)?.files.length || 0 }}</span></el-button>
</div>
<template v-if="current">
<div class="purchase-documents__heading"><h3>{{ current.label }}</h3><span>{{ current.files.length }} / 10 个附件</span></div>
<div class="purchase-documents__heading"><h3>{{ current.label }}</h3><span>{{ current.files.length }} / {{ fileLimit }} 个附件</span></div>
<el-alert v-if="type==='batch'&&activeKind==='ACCEPTANCE'" title="生成待签章PDF后,请从下方附件下载,盖章签字后再点“上传PDF”补回签章版。重新生成不会覆盖已有附件。" type="info" :closable="false"/>
<el-form v-if="numberLabel" label-position="top" class="purchase-documents__number" @submit.prevent="saveNumber">
<el-form-item :label="numberLabel">
<div class="purchase-documents__number-input"><el-input v-if="editable" v-model="current.draft" maxlength="100" show-word-limit placeholder="选填,可独立保存编号" :disabled="busy" @keyup.enter="saveNumber"/><span v-else>{{ current.number || '未填写' }}</span><el-button v-if="editable" type="primary" plain :disabled="busy || !purchaseNumberDirty(current)" @click="saveNumber">保存编号</el-button></div>
@ -16,9 +17,11 @@
</el-form>
<el-alert v-if="current.conflict" type="warning" :closable="false" show-icon :title="`编号已被其他人修改,最新编号:${current.serverNumber || '未填写'}。当前输入已保留。`"><el-button link type="primary" @click="acceptLatestNumber">采用最新编号</el-button></el-alert>
<div v-if="editable" class="purchase-documents__upload">
<el-upload :show-file-list="false" :accept="activeKind==='OTHER'?purchaseAttachmentAccept:'.pdf'" :disabled="busy || current.files.length>=10" :before-upload="beforeUpload" :http-request="upload">
<el-button type="primary" :loading="uploading" :disabled="busy || current.files.length>=10" icon="el-icon-upload">上传{{ activeKind==='OTHER'?'附件':'PDF' }}</el-button>
<el-upload :show-file-list="false" :accept="activeKind==='OTHER'?purchaseAttachmentAccept:'.pdf'" :disabled="busy || current.files.length>=fileLimit" :before-upload="beforeUpload" :http-request="upload">
<el-button type="primary" :loading="uploading" :disabled="busy || current.files.length>=fileLimit" icon="el-icon-upload">上传{{ activeKind==='OTHER'?'附件':'PDF' }}</el-button>
</el-upload>
<el-button v-if="type==='batch'&&activeKind==='ACCEPTANCE'" type="primary" plain :disabled="busy||loading||generating||unsavedNumbers||current.files.length>=fileLimit" @click="$refs.acceptanceReport.open()">生成验收资料</el-button>
<span v-if="type==='batch'&&activeKind==='ACCEPTANCE'&&unsavedNumbers">请先保存已修改的编号</span>
<span>{{ activeKind==='OTHER'?'PDF、图片、Word、Excel、TXT、ZIP':'PDF格式' }},单个文件不超过10 MB;上传后立即保存。</span>
</div>
<el-empty v-if="!current.files.length && !loading" :description="editable?'暂无附件,可按需上传':'暂无附件'" :image-size="72"/>
@ -36,12 +39,13 @@
</template>
</template>
</div>
<acceptance-report ref="acceptanceReport" :sheet="{batch:{id:targetId,batchName:context}}" :disabled="busy||loading||unsavedNumbers" @busy="generating=$event" @generated="generated"/>
<template #footer><div class="purchase-documents__footer"><span v-if="closeWarning" role="alert">还有未保存的编号。</span><el-button v-if="closeWarning" :disabled="busy" @click="discardClose">放弃未保存编号并关闭</el-button><el-button :disabled="busy" @click="beforeClose(()=>visible=false)">关闭</el-button></div></template>
</el-drawer>
</template>
<script setup>
import { canViewPurchaseQuotes } from '@/utils/purchase-quote-permission'
import AcceptanceReport from '@/components/PurchaseSheet/AcceptanceReport.vue'
import { formatDateTime } from '@/utils/display-format'
import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
@ -51,10 +55,12 @@ import { listPurchaseDocuments, savePurchaseDocumentNumber, uploadPurchaseDocume
import { purchaseDocumentKinds, purchaseAttachmentAccept, purchaseAttachmentError, purchaseDocumentSize, purchaseNumberDirty, mergePurchaseDocuments, purchaseUploadId } from '@/utils/purchase-documents'
const DocumentPdfPreview = defineAsyncComponent(()=>import('@/components/SupplierLicenseAttachment/PdfPreview.vue'))
const emit=defineEmits(['updated'])
const user = useUserStore()
const visibleKinds = computed(()=>purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||canViewPurchaseQuotes(user.id,user.roles)))
const visibleKinds = computed(()=>purchaseDocumentKinds)
const visible = ref(false), type = ref('batch'), targetId = ref(), context = ref(''), activeKind = ref('REQUEST'), groups = ref([])
const loading = ref(false), busy = ref(false), uploading = ref(false), error = ref(''), closeWarning = ref(false)
const generating=ref(false),unsavedNumbers=computed(()=>groups.value.some(purchaseNumberDirty)),fileLimit=computed(()=>activeKind.value==='REQUEST'?20:10)
const previewFile = ref(null), previewBlob = shallowRef(null), previewUrl = ref('')
const title = computed(()=>type.value==='batch'?'采购批次资料':'采购明细附件')
const current = computed(()=>groups.value.find(group=>group.kind===activeKind.value))
@ -63,9 +69,9 @@ const editable = computed(()=>user.permissions.includes('*:*:*') || user.permiss
let disposed = false, generation = 0, controller
async function open(targetType, id, name, kind='REQUEST') {
if (busy.value) return
if (busy.value||generating.value) return
generation++; controller?.abort(); releasePreview()
type.value=targetType; targetId.value=id; context.value=name || ''; activeKind.value=targetType==='detail'?'OTHER':kind
type.value=targetType; targetId.value=id; context.value=name || ''; activeKind.value=targetType==='detail'?'OTHER':kind==='QUOTE'?'REQUEST':kind
groups.value=[]; error.value=''; closeWarning.value=false; visible.value=true
await load()
}
@ -77,6 +83,7 @@ async function load() {
finally { if (stamp===generation) loading.value=false }
}
function switchKind(kind) { activeKind.value=kind; releasePreview(); closeWarning.value=false }
async function generated(){generating.value=false;activeKind.value='ACCEPTANCE';releasePreview();await load();emit('updated')}
function canPreview(file) { return ['application/pdf','image/png','image/jpeg'].includes(file.contentType) }
function acceptLatestNumber() { const group=current.value;group.number=group.draft=group.serverNumber;group.version=group.serverVersion;group.conflict=false;closeWarning.value=false }
function beforeUpload(file) { const reason=purchaseAttachmentError(file,activeKind.value); if (reason) {ElMessage.warning(reason);return false} return true }
@ -85,7 +92,7 @@ async function perform(operation, message) {
if (busy.value || loading.value) return
busy.value=true; controller=new AbortController()
try { await operation(controller.signal); if (!disposed) ElMessage.success(message) }
finally { busy.value=false; if (!disposed && visible.value) await load() }
finally { busy.value=false; if (!disposed && visible.value) {await load();emit('updated')} }
}
async function saveNumber() {
const group=current.value
@ -121,7 +128,7 @@ async function download(file) {
}
function releasePreview() { if(previewUrl.value)URL.revokeObjectURL(previewUrl.value);previewUrl.value='';previewFile.value=null;previewBlob.value=null }
function beforeClose(done) {
if (busy.value) {ElMessage.info('附件正在处理,请稍候');return}
if (busy.value||generating.value) {ElMessage.info('附件正在处理,请稍候');return}
if (groups.value.some(purchaseNumberDirty)) {closeWarning.value=true;return}
generation++;controller?.abort();loading.value=false;done()
}

View File

@ -0,0 +1,68 @@
<template>
<el-dialog v-model="opened" title="生成验收资料" width="min(820px,96vw)" append-to-body :close-on-click-modal="!exporting" :close-on-press-escape="!exporting" :show-close="!exporting">
<div v-loading="loading" class="acceptance-report">
<el-alert v-if="failure" :title="failure" type="error" :closable="false"/>
<template v-if="preview">
<el-alert :type="preview.ready?'success':'warning'" :closable="false" show-icon :title="preview.ready?`整批 ${preview.count} 条明细验收通过,前置资料齐全`:'请先补全采购申请、合同并完成整批验收'"/>
<div v-if="preview.documents?.length" class="acceptance-report__documents"><div v-for="item in preview.documents" :key="item.label" :class="{'is-complete':item.numbered&&item.files>0}"><strong>{{ item.label }}</strong><span>{{ item.numbered?item.numberLabel+'已填写':'缺少'+item.numberLabel }} · {{ item.files>0?item.files+' 份PDF':'缺少PDF附件' }}</span></div></div>
<p class="acceptance-report__note">生成整批有效明细;已取消明细不计入。照片取自验收通过的到货记录,没有照片时留空。</p>
<el-table v-if="preview.issues.length" :data="preview.issues" max-height="240" size="small" border>
<el-table-column prop="line" label="序号" width="65"/><el-table-column prop="name" label="物品名称" min-width="180" show-overflow-tooltip/><el-table-column prop="reason" label="未通过原因" min-width="240"/>
</el-table>
<template v-else-if="preview.ready">
<el-form label-position="top" size="small" class="acceptance-report__fields" :disabled="exporting">
<el-form-item label="甲方"><el-input v-model="fields.purchaser" maxlength="100"/></el-form-item>
<el-form-item label="乙方"><el-input v-model="fields.supplier" maxlength="100"/></el-form-item>
<el-form-item label="合同号"><el-input :model-value="fields.contractNo" readonly placeholder="批次资料未维护,将留空"/><span class="acceptance-report__source">自动读取批次资料中的合同编号</span></el-form-item>
<el-form-item label="项目号"><el-input v-model="fields.projectNo" maxlength="100" placeholder="选填"/></el-form-item>
<el-form-item label="项目描述" class="wide"><el-input v-model="fields.description" maxlength="200"/></el-form-item>
<el-form-item label="验收日期"><el-date-picker v-model="fields.date" type="date" value-format="YYYY-MM-DD" placeholder="选填" style="width:100%"/></el-form-item>
</el-form>
<div class="acceptance-report__fixed"><span>地址</span><p>{{ preview.fields.address }}</p><span>配送位置</span><p>{{ preview.fields.deliveryLocation }}</p></div>
<div class="acceptance-report__checks"><div v-for="(label,index) in preview.checkLabels" :key="label"><span>{{ label }}</span><el-radio-group v-model="fields.checks[index]" size="small" :disabled="exporting"><el-radio-button value="">留空</el-radio-button><el-radio-button value="OK">OK</el-radio-button><el-radio-button value="N.OK">N.OK</el-radio-button></el-radio-group></div></div>
<p class="acceptance-report__note">生成的待签章PDF会自动存入本批次“验收资料”。请下载盖章签字后,回到验收资料上传签章版;已有附件会保留。</p>
</template>
</template>
</div>
<template #footer><el-button :disabled="exporting" @click="opened=false">关闭</el-button><el-button v-if="failure||preview&&!preview.ready" :disabled="loading||exporting" @click="open">重新检查</el-button><el-button type="primary" :loading="exporting" :disabled="loading||disabled||!preview?.ready" @click="generate">生成并保存</el-button></template>
</el-dialog>
</template>
<script setup>
import {ref,watch,onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import request from '@/utils/request'
import {purchaseUploadId} from '@/utils/purchase-documents'
const props=defineProps({sheet:Object,disabled:Boolean})
const emit=defineEmits(['generated','busy'])
const opened=ref(false),loading=ref(false),exporting=ref(false),failure=ref(''),preview=ref(null),fields=ref({})
let controller,batchId,disposed=false,serial=0,attempt=null
watch(exporting,value=>emit('busy',value))
async function open(){
if(props.disabled||exporting.value||!props.sheet?.batch?.id)return
controller?.abort();controller=new AbortController();const ticket=++serial;batchId=props.sheet.batch.id
opened.value=true;preview.value=null;failure.value='';loading.value=true;attempt=null
try{const response=await request({url:`/warehouse/purchase/sheet/${batchId}/acceptance-report`,signal:controller.signal});if(disposed||ticket!==serial)return;preview.value=response.data;fields.value=structuredClone(response.data.fields)}
catch(error){if(!disposed&&ticket===serial&&error.code!=='ERR_CANCELED')failure.value=error.message||'验收状态读取失败,请重试'}
finally{if(ticket===serial)loading.value=false}
}
async function generate(){
if(props.disabled||loading.value||exporting.value||!preview.value?.ready)return
if(props.sheet?.batch?.id!==batchId){ElMessage.warning('已切换采购批次,请重新打开验收资料');opened.value=false;return}
exporting.value=true;controller=new AbortController()
try{
const key=JSON.stringify({version:preview.value.version,fields:fields.value});if(!attempt||attempt.key!==key)attempt={key,requestId:purchaseUploadId(),fields:JSON.parse(JSON.stringify(fields.value))}
const response=await request({url:`/warehouse/purchase/sheet/${batchId}/acceptance-generate`,method:'post',params:{version:preview.value.version},data:{requestId:attempt.requestId,fields:attempt.fields},signal:controller.signal,timeout:180000})
if(disposed)return
if(!response.data?.id)throw new Error('未收到已保存附件,请刷新验收资料核对')
exporting.value=false;opened.value=false;emit('generated',response.data);ElMessage.success('验收资料已生成,请下载盖章签字后上传签章版')
}catch(error){if(!disposed&&error.code!=='ERR_CANCELED')ElMessage.error(error.message||'验收资料生成失败,请重新检查')}
finally{exporting.value=false}
}
onBeforeUnmount(()=>{disposed=true;serial++;controller?.abort();emit('busy',false)})
defineExpose({open})
</script>
<style scoped>
.acceptance-report__documents{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}.acceptance-report__documents>div{border:1px solid var(--el-color-warning-light-5);background:var(--el-color-warning-light-9);border-radius:4px;padding:10px 12px;display:flex;flex-direction:column;gap:4px;font-size:12px}.acceptance-report__documents>div.is-complete{border-color:var(--el-color-success-light-5);background:var(--el-color-success-light-9)}
.acceptance-report__source{font-size:12px;color:var(--el-text-color-secondary);line-height:1.6;margin-top:4px}.acceptance-report__fixed{display:grid;grid-template-columns:68px 1fr;gap:6px 12px;background:var(--el-fill-color-light);padding:10px 12px;border-radius:4px;font-size:12px;line-height:1.6;margin-bottom:14px}.acceptance-report__fixed>span{color:var(--el-text-color-secondary)}.acceptance-report__fixed p{margin:0;overflow-wrap:anywhere}
.acceptance-report{min-height:96px}.acceptance-report__note{color:var(--el-text-color-secondary);font-size:12px;line-height:1.7;margin:10px 0}.acceptance-report__fields{display:grid;grid-template-columns:1fr 1fr;gap:0 16px;margin-top:14px}.acceptance-report__fields .wide{grid-column:1/-1}.acceptance-report__fields .el-form-item{margin-bottom:12px}.acceptance-report__checks{border:1px solid var(--el-border-color-lighter);border-radius:4px;overflow:hidden}.acceptance-report__checks>div{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;gap:12px}.acceptance-report__checks>div+div{border-top:1px solid var(--el-border-color-lighter)}.acceptance-report__checks>div>span{font-size:13px}@media(max-width:600px){.acceptance-report__fields{grid-template-columns:1fr}.acceptance-report__checks>div{flex-wrap:wrap}}
</style>

View File

@ -9,11 +9,11 @@
<div v-if="started" class="category-batch-progress"><el-progress :percentage="progress" :stroke-width="6" :show-text="false"/><span>{{ running?'正在推荐':stopped?'已停止':completed===targets.length?'推荐完成':'待继续推荐' }} {{ completed }} / {{ targets.length }} 行</span></div>
<div class="category-batch-selection"><el-checkbox :model-value="allSelected" :indeterminate="someSelected" :disabled="!available.length||applying" @change="selectAll">全选可用结果</el-checkbox><span>已选 {{ chosen.length }} 行<span v-if="newCount"> · {{ newCount }} 个新小类将申请后使用</span></span></div>
<el-table :data="pageRows" row-key="key" size="small" border max-height="52vh" :empty-text="rows.length&&onlyEmpty?'没有未分类明细,请切换到“全部明细(含已有分类)”':'当前范围没有需要分类的明细'">
<el-table-column width="45" align="center"><template #default="{row}"><el-checkbox v-model="row.checked" :disabled="!row.value||applying" :aria-label="'选用第'+row.line+'行分类'"/></template></el-table-column>
<el-table-column width="45" align="center" class-name="business-control-cell"><template #default="{row}"><el-checkbox v-model="row.checked" :disabled="!row.value||applying" :aria-label="'选用第'+row.line+'行分类'"/></template></el-table-column>
<el-table-column prop="line" label="行" width="55" align="center"/>
<el-table-column label="物品" min-width="200"><template #default="{row}"><strong>{{ row.name }}</strong><div class="category-batch-spec">{{ [row.spec,row.brand].filter(Boolean).join(' · ')||'—' }}</div></template></el-table-column>
<el-table-column prop="category" label="原分类" width="125"><template #default="{row}">{{ row.category||'未分类' }}</template></el-table-column>
<el-table-column label="本次分类 · 可修改" min-width="330"><template #default="{row}">
<el-table-column label="本次分类 · 可修改" min-width="330" class-name="business-control-cell"><template #default="{row}">
<div v-if="row.value===newValue&&row.proposed" class="category-batch-new">
<div class="category-batch-choice-heading"><el-tag type="warning" size="small" effect="light">新分类</el-tag><el-button link type="primary" :disabled="applying" @click="chooseExisting(row)">改用已有分类</el-button></div>
<div class="category-batch-new-fields">

View File

@ -31,7 +31,7 @@ import HistoryPreview from './HistoryPreview.vue'
export default {
components:{HistoryPreview},props:{projects:Array,categories:Array,units:Array,plans:Array},emits:['changed'],
data:()=>({visible:false,busy:false,attempted:false,rows:[],selectedFields:['remark'],reason:'',preview:null,acknowledgeArchiveOnly:false,bulkField:'',bulkValue:'',frozen:null,submissionKey:'',needsAck:false}),
computed:{historyFields:()=>historyFields,fields(){return historyFields.filter(field=>this.selectedFields.includes(field.key))},bulkType(){return this.fields.find(field=>field.key===this.bulkField)?.type},bulkOptions(){if(!this.rows.length||this.bulkField==='loanId')return [];const first=this.options(this.bulkField,this.rows[0]);return first.filter(option=>this.rows.every(row=>this.options(this.bulkField,row).some(candidate=>String(candidate.value)===String(option.value))))}},
computed:{historyFields(){return historyFields.filter(field=>field.key!=='expenseCategoryId'||this.rows.every(row=>!row.original.purchaseBatchId))},fields(){return this.historyFields.filter(field=>this.selectedFields.includes(field.key))},bulkType(){return this.fields.find(field=>field.key===this.bulkField)?.type},bulkOptions(){if(!this.rows.length||this.bulkField==='loanId')return [];const first=this.options(this.bulkField,this.rows[0]);return first.filter(option=>this.rows.every(row=>this.options(this.bulkField,row).some(candidate=>String(candidate.value)===String(option.value))))}},
methods:{
open(selected){if(this.busy)return;this.rows=selected.map(row=>({id:row.id,original:{...row},values:{...row},loans:[]}));this.selectedFields=['remark'];this.reason='';this.preview=null;this.attempted=false;this.frozen=null;this.acknowledgeArchiveOnly=false;this.needsAck=false;this.submissionKey='history-'+(globalThis.crypto?.randomUUID?.()||Date.now()+'-'+Math.random().toString(36).slice(2));this.visible=true},
invalidate(){this.preview=null},fieldsChanged(){this.bulkField='';this.invalidate()},

View File

@ -53,7 +53,7 @@
<template v-else>
<div class="sheet-heading">
<el-button class="sheet-heading__back" size="small" :disabled="saving" icon="el-icon-back" @click="back">{{ sheet.unbatched?'待组批':'返回' }}</el-button>
<div class="sheet-heading__identity"><h2 :title="sheet.unbatched?'未组批采购明细':[sheet.batch.batchName,sheet.batch.batchNo,'供应商:'+supplierName,'项目:'+(batchProject.mixed?'历史多项目批次':projectName(batchProject.value)),formatDateTime(sheet.batch.businessDate)].filter(Boolean).join(' · ')">{{ sheet.unbatched?'未组批采购明细':sheet.batch.batchName||sheet.batch.batchNo||'新采购批次' }}</h2><span v-if="!sheet.unbatched&&!isEditing" class="sheet-heading__meta" :title="supplierName">{{ supplierName }}</span><el-tag v-if="isEditing" size="small" effect="plain" class="sheet-heading__state">编辑中</el-tag></div>
<div class="sheet-heading__identity"><h2 :title="sheet.unbatched?'未组批采购明细':[sheet.batch.batchName,sheet.batch.batchNo,'供应商:'+supplierName,'项目:'+(batchProject.mixed?'历史多项目批次':projectName(batchProject.value)),formatDateTime(sheet.batch.businessDate)].filter(Boolean).join(' · ')">{{ sheet.unbatched?'未组批采购明细':sheet.batch.batchName||sheet.batch.batchNo||'新采购批次' }}</h2><span v-if="!sheet.unbatched&&!isEditing" class="sheet-heading__meta" :title="supplierName">{{ supplierName }}</span><el-tag v-if="!sheet.unbatched&&!isEditing" size="small" effect="plain">{{ categories.find(c=>String(c.id)===String(sheet.batch.expenseCategoryId))?.categoryName||'费用类别待统一' }}</el-tag><el-tag v-if="isEditing" size="small" effect="plain" class="sheet-heading__state">编辑中</el-tag></div>
<div class="sheet-toolbar">
<el-button v-if="canEdit && !editing" type="primary" plain size="small" icon="el-icon-edit" :disabled="saving" @click="startEditing">编辑</el-button>
<template v-if="isEditing">
@ -65,7 +65,7 @@
<el-button size="small" icon="el-icon-refresh-left" title="Ctrl / ⌘ + Z" @mousedown.prevent @click="undo" :disabled="saving || !canUndo || !canEdit">撤销</el-button>
<el-button size="small" title="Ctrl + Y / ⌘ + Shift + Z" @mousedown.prevent @click="redo" :disabled="saving || !canRedo || !canEdit">重做</el-button>
<el-button size="small" :disabled="saving" @click="openBatchCategories">批量 AI 分类</el-button>
<el-popover trigger="click" width="320" placement="bottom"><template #reference><el-button size="small" :disabled="saving||!selected.length">批量设置<business-icon name="arrow-down"/></el-button></template><el-form label-width="80px" size="small"><el-form-item v-if="sheet.unbatched || batchProject.mixed" label="项目"><el-select v-model="commonProject" filterable clearable placeholder="选择项目" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'projectId')||r.id&&r.productionTaskId)" @change="setProjects"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item><el-form-item label="费用分类"><el-select v-model="commonCategory" filterable clearable placeholder="选择费用分类" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'expenseCategoryId'))" @change="setCategories"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select></el-form-item></el-form></el-popover>
<el-popover trigger="click" width="320" placement="bottom"><template #reference><el-button size="small" :disabled="saving||!selected.length">批量设置<business-icon name="arrow-down"/></el-button></template><el-form label-width="80px" size="small"><el-form-item v-if="sheet.unbatched || batchProject.mixed" label="项目"><el-select v-model="commonProject" filterable clearable placeholder="选择项目" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'projectId')||r.id&&r.productionTaskId)" @change="setProjects"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item><el-form-item v-if="sheet.unbatched" label="费用分类"><el-select v-model="commonCategory" filterable clearable placeholder="选择费用分类" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'expenseCategoryId'))" @change="setCategories"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select></el-form-item></el-form></el-popover>
</template>
<el-button v-if="!isEditing&&canExportInquiry && !sheet.unbatched" size="small" icon="el-icon-download" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryExportRows.length" @click="$refs.quotation.exportInquiry()">导出询价单</el-button>
<el-button v-if="!isEditing&&canEdit && canViewQuotes && !sheet.unbatched" size="small" icon="el-icon-upload" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="quoteImportOpen=true">回填供应商报价</el-button>
@ -84,7 +84,8 @@
<el-form-item v-if="!sheet.unbatched" label="供应商"><supplier-picker v-if="isEditing && !supplierLocked" v-model="sheet.batch.supplierId" /><table-text v-else :value="supplierName" /></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="所属项目" required><el-select v-if="isEditing && !batchProject.mixed" ref="batchProjectSelect" :model-value="batchProject.value" filterable placeholder="选择一次,整批明细沿用" aria-label="批次所属项目" :disabled="!!projectId" @change="setBatchProject"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName"/></el-select><span v-else>{{ batchProject.mixed?'历史多项目批次(按明细保留)':batchProject.value?projectName(batchProject.value):'待选择' }}</span></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="日期"><el-date-picker v-if="isEditing" v-model="sheet.batch.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false" /><span v-else>{{ formatDateTime(sheet.batch.businessDate) }}</span></el-form-item>
<el-form-item v-if="isEditing" label="默认分类"><el-select v-model="commonCategory" filterable><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-if="sheet.unbatched" label="默认分类"><el-select v-model="commonCategory" filterable><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-else label="费用类别" required><el-select ref="batchCategorySelect" :model-value="sheet.batch.expenseCategoryId" filterable placeholder="整批使用一个费用类别" :disabled="!!sheet.batch.id&&!$can(['warehouse:purchase:manage'])" aria-label="批次费用类别" @change="setBatchCategory"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="名称"><el-input v-if="isEditing" v-model="sheet.batch.batchName" maxlength="100" placeholder="选填" /><table-text v-else :value="sheet.batch.batchName" /></el-form-item>
</el-form>
@ -156,11 +157,11 @@
<el-radio-group v-model="moveMode" :disabled="saving||moveAttempted"><el-radio-button value="existing">转入已有批次</el-radio-button><el-radio-button value="new">新建批次并转入</el-radio-button></el-radio-group>
<el-form label-width="90px" class="mt16" :disabled="saving||moveAttempted">
<el-form-item v-if="moveMode==='existing'" label="目标批次"><el-select v-model="moveBatchId" filterable remote :remote-method="searchMove" :loading="moveLoading" style="width:100%" placeholder="搜索同项目批次编号或名称"><el-option v-for="batch in moveBatches" :key="batch.id" :value="batch.id" :label="[batch.batchNo,batch.batchName,batch.supplierName,batch.projectNames].filter(Boolean).join(' / ')"/></el-select><span v-if="!moveBatches.length&&!moveLoading">没有合适的批次?可切换“新建批次并转入”。</span></el-form-item>
<template v-else><el-form-item label="批次编号"><span>确认转入后自动生成,无需提前创建</span></el-form-item><el-form-item label="批次名称"><el-input v-model="moveNew.batchName" maxlength="100" placeholder="选填,便于辨认"/></el-form-item><el-form-item label="供应商"><span v-if="moveSupplierLocked">{{ sheet.batch.supplierName||supplierName||'原供应商' }}(保持不变)</span><supplier-picker v-else v-model="moveNew.supplierId" style="width:100%" :show-manage="false"/></el-form-item><el-form-item label="日期" required><el-date-picker v-model="moveNew.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false"/></el-form-item></template>
<template v-else><el-form-item label="批次编号"><span>确认转入后自动生成,无需提前创建</span></el-form-item><el-form-item label="批次名称"><el-input v-model="moveNew.batchName" maxlength="100" placeholder="选填,便于辨认"/></el-form-item><el-form-item label="供应商"><span v-if="moveSupplierLocked">{{ sheet.batch.supplierName||supplierName||'原供应商' }}(保持不变)</span><supplier-picker v-else v-model="moveNew.supplierId" style="width:100%" :show-manage="false"/></el-form-item><el-form-item label="费用类别" required><el-select v-model="moveNew.expenseCategoryId" filterable placeholder="整批使用一个费用类别"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item><el-form-item label="日期" required><el-date-picker v-model="moveNew.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false"/></el-form-item></template>
</el-form><p class="sheet-project-note">一批对应一个项目。已确认、已有到货和历史明细只可转同供应商批次,无需退货或撤销确认。原批次转空后保留,附件和流程编号仍留在原批次。</p><el-alert v-if="moveAttempted&&!saving" title="上次结果未确认,重试只发送原请求。也可关闭后刷新核对批次,勿重复新建。" type="warning" :closable="false"/>
<template #footer><el-button :disabled="saving" @click="moveOpen=false">取消</el-button><el-button type="primary" :disabled="saving || (moveMode==='existing'?!moveBatchId:!moveNew.businessDate)" @click="moveRows">{{ moveMode==='new'?'新建并转入':'确认转批次' }}</el-button></template>
<template #footer><el-button :disabled="saving" @click="moveOpen=false">取消</el-button><el-button type="primary" :disabled="saving || (moveMode==='existing'?!moveBatchId:!moveNew.businessDate||!moveNew.expenseCategoryId)" @click="moveRows">{{ moveMode==='new'?'新建并转入':'确认转批次' }}</el-button></template>
</el-dialog>
<batch-arrival ref="arrival" @changed="arrivalChanged" />
<batch-arrival ref="arrival" separate-acceptance @changed="arrivalChanged" />
<el-dialog title="到货记录" v-model="recordsOpen" width="900px" append-to-body>
<p>{{ recordsItem }}</p><el-table :data="arrivalRecords" size="small"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="arrivalDate" label="日期" show-overflow-tooltip min-width="100"/><el-table-column prop="arrivalQuantity" label="数量" show-overflow-tooltip min-width="100"/><el-table-column label="验收" show-overflow-tooltip min-width="100"><template #default="s">{{ ['待验收','合格','不合格'][s.row.acceptanceStatus] || '已撤销' }}</template></el-table-column><el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos :model-value="s.row.photos||[]" readonly compact/></template></el-table-column><el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="160"/></el-table>
<template #footer><div ><el-button @click="recordsOpen=false">关闭</el-button><el-button type="primary" @click="goArrival">去到货验收</el-button></div></template>
@ -260,13 +261,13 @@ rowErrors(){if(!this.validationEnabled||!this.sheet||!this.isEditing)return [];c
supplierLocked(){return !!this.sheet.batch.supplierId && this.sheet.rows.some(r=>r.priceLocked || r.historical || Number(r.acceptedQuantity)>0 || Number(r.pendingArrivalQuantity)>0)},
supplierName(){return this.sheet?.batch?.supplierName || this.sheet?.rows?.find(r=>r.supplierName)?.supplierName || '待定'},
nameItems(){return this.nameOptions || this.items},
columns(){const columns=[{field:'materialName',label:'物品名称',width:180,required:true},{field:'materialBrand',label:'品牌',width:110},{field:'materialParams',label:'规格型号',width:210},{field:'quantity',label:'数量',width:100,required:true},{field:'unit',label:'单位',width:75,required:true},{field:'finalUnitPrice',label:'报价单价',width:115},{field:'projectId',label:'项目',width:210,required:true},{field:'expenseCategoryId',label:'费用分类',width:150,required:true},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(5,0,{field:'actualUnitPrice',label:'实际单价',width:115});if(this.extras)columns.push({field:'productionTaskId',label:'生产计划',width:200},{field:'purchasePurpose',label:'用途',width:130},{field:'loanId',label:'归还借用',width:200},{field:'remark',label:'备注',width:180});return columns.filter(column=>!['purchasePurpose','loanId'].includes(column.field)&&(column.field!=='finalUnitPrice'||this.canViewQuotes)&&(column.field!=='projectId'||this.sheet?.unbatched||this.batchProject.mixed))},
columns(){const columns=[{field:'materialName',label:'物品名称',width:180,required:true},{field:'materialBrand',label:'品牌',width:110},{field:'materialParams',label:'规格型号',width:210},{field:'quantity',label:'数量',width:100,required:true},{field:'unit',label:'单位',width:75,required:true},{field:'finalUnitPrice',label:'报价单价',width:115},{field:'projectId',label:'项目',width:210,required:true},{field:'expenseCategoryId',label:'费用分类',width:150,required:true},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(5,0,{field:'actualUnitPrice',label:'实际单价',width:115});if(this.extras)columns.push({field:'productionTaskId',label:'生产计划',width:200},{field:'purchasePurpose',label:'用途',width:130},{field:'loanId',label:'归还借用',width:200},{field:'remark',label:'备注',width:180});return columns.filter(column=>!['purchasePurpose','loanId'].includes(column.field)&&(column.field!=='finalUnitPrice'||this.canViewQuotes)&&(column.field!=='projectId'||this.sheet?.unbatched||this.batchProject.mixed)&&(column.field!=='expenseCategoryId'||this.sheet?.unbatched))},
amount(){return this.sheet.rows.reduce((sum,r)=>sum+(Number(r.purchaseStatus)!==5?Number(r.quantity||0)*Number(r.finalUnitPrice||0):0),0)},
unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Number(r.purchaseStatus)!==5).length},
confirmationRows(){return (this.selected.length?this.selected:this.visibleRows).filter(r=>!r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5)},
canConfirm(){return this.canViewQuotes && this.sheet.batch.id && !this.dirty && this.confirmationRows.length>0 && this.confirmationRows.every(this.hasPrice)},
},
watch:{sheet(){this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},virtualCount(count,previous){if(!this.sheet||!this.virtualized)return;const end=Math.max(0,this.visibleRows.length-count),previousEnd=Math.max(0,this.visibleRows.length-previous);if(this.virtualStart>=previousEnd||this.virtualStart>end)this.virtualStart=end},editing(value){if(value){this.snapshotView();this.batchDetailsOpen=!this.sheet?.unbatched&&(!this.sheet?.batch.id||!this.batchProject.value&&!this.batchProject.mixed)}else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
watch:{sheet(){this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},virtualCount(count,previous){if(!this.sheet||!this.virtualized)return;const end=Math.max(0,this.visibleRows.length-count),previousEnd=Math.max(0,this.visibleRows.length-previous);if(this.virtualStart>=previousEnd||this.virtualStart>end)this.virtualStart=end},editing(value){if(value){this.snapshotView();this.batchDetailsOpen=!this.sheet?.unbatched&&(!this.sheet?.batch.id||!this.sheet?.batch.expenseCategoryId||!this.batchProject.value&&!this.batchProject.mixed)}else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
async created(){this.changedKeys=new Set();this.headerDirty=false;this.structureDirty=false;this._editor=createSheetEditor(this);this.loading=true;try{this.refreshDrafts();await this.references();if(this.embedded||this.$route.path!=='/procurement/details')await this.loadBatches();else await this.applyRoute()}finally{this.loading=false}},
async activated(){this._pageInactive=false;if(this._routeStamp===undefined||this.loading||this.creating)return;const identity=this._routeIdentity;await this.applyRoute();if(!this._refreshOnActivate)return;this._refreshOnActivate=false;if(identity!==this._routeIdentity||this.saving||this.editing||this.dirty)return;if(this.sheet){const filter=this.rowFilter;if(this.sheet.unbatched){if(this.sheet.rows.length)await this.openUnbatched(this.sheet.rows,false)}else await this.openBatch(this.sheet.batch);this.rowFilter=filter}else if(this.viewMode==='batches')await this.loadBatches();else await this.$refs.lookup?.load()},
unmounted(){this.endCellSelection()},
@ -325,7 +326,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
clearDraft(id){try{removeSheetDraft(this.draftPrefix()+(id||'new'));this.draftSavedAt=null;this.draftError='';this.refreshDrafts()}catch(e){this.draftError='无法清除本机草稿,请勿重复提交,先核对线上保存结果。'}},
async restoreDraft(key){if(this.dirty){try{await this.$confirm('保留当前草稿并打开所选草稿?','恢复草稿')}catch(e){return}if(!this.persistDraft())return}let draft;try{draft=readSheetDraft(key)}catch(e){return this.$modal.msgError('该草稿内容不完整,已保留原文件,请勿清理浏览器数据')}if(!draft?.sheet)return;this.editing=false;this.sheet=draft.sheet;this.baseline=draft.baseline;this._editor.reset();this.editing=true;this.selected=[];this.history=[];this.redoHistory=[];this.rowFilter='';this.layout();this.$modal.msgSuccess('已恢复本机草稿;保存时仍会核对线上版本,防止覆盖他人修改')},
applyQuotes({quotes,batchId,version}){const ready=quotes.filter(quotationReady);if(!ready.length||!this.canEdit||this.saving)return;if(!this.sheet||this.sheet.batch.id!==batchId||this.sheet.version!==version||this.dirty)return this.$modal.msgWarning('清单已更新,请保存后重新读取报价');this.resetRowView();this.startEditing();const ids=new Set(ready.flatMap(r=>r.rowIds));this.remember(this.sheet.rows.filter(r=>ids.has(r.id)));for(const quote of ready)for(const id of quote.rowIds){const row=this.sheet.rows.find(r=>r.id===id);if(row&&!this.readonly(row)&&!this.fieldLocked(row,'finalUnitPrice'))row.finalUnitPrice=quote.unitPrice}this.quoteImportOpen=false;this.$modal.msgSuccess('供应商报价已回填,核对后请点击“保存清单”')},
async openMove(){if(!this.canMoveSelection)return;this._moveRequest=null;this._moveKey=globalThis.crypto?.randomUUID?.()||'move-'+Date.now()+'-'+Math.random().toString(36).slice(2);this.moveAttempted=false;this.moveBatchId=null;this.moveMode='existing';this.moveNew={batchName:'',supplierId:this.sheet.batch.supplierId,businessDate:this.parseTime(new Date(),'{y}-{m}-{d}')};this.moveOpen=true;await this.searchMove('')},
async openMove(){if(!this.canMoveSelection)return;this._moveRequest=null;this._moveKey=globalThis.crypto?.randomUUID?.()||'move-'+Date.now()+'-'+Math.random().toString(36).slice(2);this.moveAttempted=false;this.moveBatchId=null;this.moveMode='existing';this.moveNew={batchName:'',supplierId:this.sheet.batch.supplierId,expenseCategoryId:this.sheet.batch.expenseCategoryId||null,businessDate:this.parseTime(new Date(),'{y}-{m}-{d}')};this.moveOpen=true;await this.searchMove('')},
async searchMove(keyword){const source=this.sheet?.batch.id;return runLatest(this,'moveBatches',()=>listPurchaseBatch({pageNum:1,pageSize:100,keyword}),{start:()=>{this.moveLoading=true},success:r=>{if(source!==this.sheet?.batch.id)return;const project=this.projectName(this.selected[0]?.projectId);this.moveBatches=(r.rows||[]).filter(b=>b.id!==source&&![4,5].includes(Number(b.purchaseStatus))&&(!b.projectNames||b.projectNames===project)&&(!this.moveSupplierLocked||String(b.supplierId)===String(this.sheet.batch.supplierId)))},finish:()=>{this.moveLoading=false}})},
async moveRows(){if(!this.canMoveSelection||this.saving||(this.moveMode==='existing'&&!this.moveBatchId))return;this.saving=true;this.moveAttempted=true;this._moveRequest||={requestIds:this.selected.map(r=>r.id),requestKey:this._moveKey,...(this.moveMode==='new'?{newBatch:{...this.moveNew}}:{batchId:this.moveBatchId})};try{const result=await assignPurchaseBatch(this._moveRequest);const target=result.data?.batchId||this.moveBatchId;this.moveOpen=false;await this.openBatch(this.sheet.batch);this.moveOutcome=target;this.$modal.msgSuccess('已转批次,业务状态和历史记录未改变')}finally{this.saving=false}},
async viewMoveTarget(){const id=this.moveOutcome;if(!id||this.saving)return;this.moveOutcome=null;if(!this.embedded&&this.$route.path==='/procurement/details'&&String(this.$route.query.purchaseBatchId)===String(id)){await this.openBatch({id});return}await this.$router.push({path:'/procurement/details',query:{purchaseBatchId:String(id)}})},
@ -375,7 +376,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
event.preventDefault();const buttons=[...event.currentTarget.querySelectorAll('button:not(:disabled)')],index=buttons.indexOf(document.activeElement)
if(buttons.length)buttons[event.key==='Home'?0:event.key==='End'?buttons.length-1:(index+(event.key==='ArrowDown'?1:-1)+buttons.length)%buttons.length].focus()
},
rowDefaults(row){return {projectId:!this.sheet.unbatched&&!this.batchProject.mixed?this.batchProject.value||this.projectId||null:row?.projectId||this.commonProject||this.projectId||null,expenseCategoryId:row?.expenseCategoryId||this.commonCategory||null}},
rowDefaults(row){return {projectId:!this.sheet.unbatched&&!this.batchProject.mixed?this.batchProject.value||this.projectId||null:row?.projectId||this.commonProject||this.projectId||null,expenseCategoryId:!this.sheet.unbatched?this.sheet.batch.expenseCategoryId:row?.expenseCategoryId||this.commonCategory||null}},
async installInsertedRows(result){
this.remember();if(this.rowFilter||this.onlyInvalid||this.rowQueue!=='all'||this.rowSort!=='original')this.resetRowView();this.sheet.rows=result.rows;this.selected=[]
await this.$nextTick();const row=result.inserted[0],field=this.columns.find(column=>this.editableCell(row,column.field))?.field
@ -461,7 +462,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
},
async loadBatches(){await loadAmountDisplay();const query={...this.query,onlyMine:this.onlyMine,beginDate:(this.queryDates||[])[0],endDate:(this.queryDates||[])[1]};return runLatest(this,'batches',()=>listPurchaseBatch(query),{start:()=>{this.loading=true},success:result=>{this.batches=result.rows||[];this.total=result.total||0;this.summary=result.summary||null},error:()=>{this.batches=[];this.total=0;this.summary=null},finish:()=>{this.loading=false}})},
search(){this.query.pageNum=1;this.loadBatches()},resetQuery(){this.resetForm('query');this.query.projectId=this.projectId;this.queryDates=[];this.search()},
emptyRow(){return {_key:'new-'+Date.now()+'-'+Math.random(),id:null,projectId:this.projectId||(this.sheet&&!this.sheet.unbatched?this.batchProject.value:this.commonProject)||null,expenseCategoryId:this.commonCategory||null,materialName:'',materialBrand:'',materialParams:'',productId:null,productCode:null,unit:'',category:'',quantity:1,finalUnitPrice:null,actualUnitPrice:null,purchaseLink:'',remark:'',purchasePurpose:'SELF',productionTaskId:null,purchaseStatus:0}},
emptyRow(){return {_key:'new-'+Date.now()+'-'+Math.random(),id:null,projectId:this.projectId||(this.sheet&&!this.sheet.unbatched?this.batchProject.value:this.commonProject)||null,expenseCategoryId:(!this.sheet?.unbatched?this.sheet?.batch?.expenseCategoryId:null)||this.commonCategory||null,materialName:'',materialBrand:'',materialParams:'',productId:null,productCode:null,unit:'',category:'',quantity:1,finalUnitPrice:null,actualUnitPrice:null,purchaseLink:'',remark:'',purchasePurpose:'SELF',productionTaskId:null,purchaseStatus:0}},
async create(unbatched=false){return createPurchaseDraft(this,unbatched)},
async openBatch(batch){const seq=this._sheetSequence=(this._sheetSequence||0)+1;this.loading=true;try{await loadAmountDisplay();const result=(await getPurchaseSheet(batch.id)).data;if(seq===this._sheetSequence)this.install(result)}finally{if(seq===this._sheetSequence)this.loading=false}},
install(sheet){const view=String(this.sheet?.batch?.id)===String(sheet.batch?.id)?{queue:this.rowQueue,sort:this.rowSort,keyword:this.rowFilter}:{queue:'all',sort:'original',keyword:''};sheet.submissionKey=null;sheet.rows=sheet.rows.map(r=>({...this.emptyRow(),...r,_key:'saved-'+r.id}));sheet.deletedIds=[];this.sheet=sheet;this.editCell=null;this.validationEnabled=false;this.onlyInvalid=false;this.baseline=this.serialize(sheet);this.editing=false;this.rowQueue=view.queue;this.rowSort=view.sort;this.rowFilter=view.keyword;this.viewSnapshot=null;this.mergeItems(sheet.rows.map(r=>({id:r.productId,productCode:r.productCode,productName:r.materialName,brand:r.materialBrand,spec:r.materialParams,unit:r.unit,category:r.category})).filter(r=>r.id));this.history=[];this.selected=[];this.commonProject=null;const categoryIds=[...new Set(sheet.rows.map(r=>r.expenseCategoryId).filter(Boolean))];this.commonCategory=categoryIds.length===1?categoryIds[0]:(this.categories.find(c=>c.categoryCode==='MATERIAL')||this.categories[0]||{}).id;this._activeCell=null;this.refreshDrafts?.();this.layout()},
@ -499,6 +500,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
remove(){if(!this.canRemoveSelection)return;this.remember(this.selected);const keys=new Set(this.selected.map(r=>r._key));this.sheet.deletedIds.push(...this.selected.filter(r=>r.id).map(r=>r.id));this.sheet.rows=this.sheet.rows.filter(r=>!keys.has(r._key));this.selected=[]},
removeOne(row){if(this.readonly(row) || row.id || !this.canAdd || this.saving)return;this.remember([row]);this.sheet.rows=this.sheet.rows.filter(r=>r._key!==row._key)},
setProjects(id){if(!id || !this.isEditing || this.saving || this.selected.some(r=>this.readonly(r)||this.fieldLocked(r,'projectId')))return;if(this.selected.some(r=>r.id && r.productionTaskId && String(r.projectId)!==String(id)))return this.$modal.msgWarning('已关联生产计划的明细不能更换项目');this.remember(this.selected);this.selected.forEach(r=>{if(String(r.projectId)!==String(id))this.projectChanged(r);r.projectId=id})},
setBatchCategory(id){if(!this.isEditing||this.saving||this.sheet.batch.id&&!this.$can(['warehouse:purchase:manage']))return;this.remember(this.sheet.rows);this.sheet.batch.expenseCategoryId=id;this.commonCategory=id;this.sheet.rows.filter(r=>r.purchaseStatus!==5).forEach(r=>r.expenseCategoryId=id)},
setCategories(id){if(!id || !this.isEditing || this.saving || this.selected.some(r=>this.readonly(r)||this.fieldLocked(r,'expenseCategoryId')))return;this.remember(this.selected);this.selected.forEach(r=>{r.expenseCategoryId=id})},
clearLoan(row){row.loanId=null;this.loans[row._key]=[];this._loanRequests?.delete(row._key)},
projectChanged(row){row.productionTaskId=null;this.clearLoan(row)},
@ -594,6 +596,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
activeRows(){return this.sheet.rows.filter(r=>r.id||clean(r.materialName)||clean(r.materialBrand)||clean(r.materialParams)||clean(r.purchaseLink))},
async save(){
if(this.saving || !this.isEditing || !this.dirty)return
if(!this.sheet.unbatched&&!this.sheet.batch.expenseCategoryId){this.batchDetailsOpen=true;await this.$nextTick();this.$refs.batchCategorySelect?.focus();return this.$modal.msgWarning('请先选择批次费用类别')}
this.validationEnabled=true
if(this.rowErrors.length){this.focusError(this.rowErrors[0]);return}
try{
@ -635,7 +638,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
}catch{/* Cancellation keeps all local changes; request failures are shown globally. */}
finally{this.saving=false}
},
async confirm(){if(this.saving || this.isEditing || !this.canConfirm)return;if(!this.sheet.batch.supplierId)return this.$modal.msgWarning('清单可以先保存;请编辑并补选供应商后再确认采购');const id=this.sheet.batch.id,version=this.sheet.version,rowIds=(this.selected.length||this.rowQueue!=='all'||this.rowFilter||this.onlyInvalid)?this.confirmationRows.map(r=>r.id):undefined,count=this.confirmationRows.length;this.saving=true;try{await this.$confirm(`确认${this.selected.length?'选中':rowIds?'当前筛选':'整批'} ${count} 行报价并开始采购?费用按每行项目和分类计入,未选行不变,重复确认不会重复计费。`,'确认采购');this.install((await confirmPurchaseSheet(id,version,rowIds)).data);this.$modal.msgSuccess('已确认采购')}catch(e){/* Request handler displays server errors. */}finally{this.saving=false}},
async confirm(){if(this.saving || this.isEditing || !this.canConfirm)return;if(!this.sheet.batch.supplierId)return this.$modal.msgWarning('清单可以先保存;请编辑并补选供应商后再确认采购');const id=this.sheet.batch.id,version=this.sheet.version,rowIds=(this.selected.length||this.rowQueue!=='all'||this.rowFilter||this.onlyInvalid)?this.confirmationRows.map(r=>r.id):undefined,count=this.confirmationRows.length;this.saving=true;try{await this.$confirm(`确认${this.selected.length?'选中':rowIds?'当前筛选':'整批'} ${count} 行报价并开始采购?费用按明细所属项目和批次费用类别计入,未选行不变,重复确认不会重复计费。`,'确认采购');this.install((await confirmPurchaseSheet(id,version,rowIds)).data);this.$modal.msgSuccess('已确认采购')}catch(e){/* Request handler displays server errors. */}finally{this.saving=false}},
exportBatch(){this.download('warehouse/purchase/supplier-export',{purchaseBatchId:this.sheet.batch.id},`${this.sheet.batch.batchNo}.xlsx`)},
async batchArrival(batch){const loaded=(await getPurchaseSheet(batch.id)).data;if(!loaded.batch.supplierId)return this.$modal.msgWarning('请先选择供应商');await this.arrival(loaded.rows.filter(r=>r.id&&r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5&&Number(r.remainingQuantity)>0))},
async arrival(rows){if(this.isEditing || this.dirty)return this.$modal.msgWarning('请先保存或取消编辑,再登记到货');if(rows.some(r=>!r.priceLocked))return this.$modal.msgWarning('请先确认采购报价,再登记到货');await this.$refs.arrival.open(rows,'arrival')},

View File

@ -7,7 +7,7 @@
<el-form-item v-if="mode==='receipt'" label="统一库区"><el-select v-model="commonArea" filterable placeholder="选择后应用到勾选明细" @change="setArea"><el-option v-for="a in areas" :key="a.id" :label="a.areaName" :value="a.id" /></el-select></el-form-item>
<el-form-item v-if="mode!=='acceptance'" label="日期"><el-date-picker v-model="date" type="date" value-format="YYYY-MM-DD" :clearable="false"/></el-form-item>
<el-form-item label="备注"><el-input v-model="remark" maxlength="500" placeholder="选填,记录本次操作说明"/></el-form-item>
<el-form-item v-if="mode==='arrival'" label="验收方式"><el-checkbox v-model="acceptAll">同时按全部合格验收</el-checkbox></el-form-item>
<el-form-item v-if="mode==='arrival'&&!separateAcceptance" label="验收方式"><el-checkbox v-model="acceptAll">同时按全部合格验收</el-checkbox></el-form-item>
</el-form>
<div class="batch-dialog-toolbar"><el-input v-model="keyword" clearable :disabled="saving||opening" placeholder="搜索批次、项目、物品" class="batch-dialog-search"/><div v-if="mode!=='acceptance'" class="batch-dialog-toolbar__actions"><el-button type="primary" plain :disabled="saving||opening" @click="selectedRows.filter(r=>!r.arrivalIdCreated).forEach(r=>r.quantity=r.maximum)">{{ mode==='receipt'?'本次全部入库':'本次全部到齐' }}</el-button><el-button :disabled="saving||opening" @click="selectedRows.filter(r=>!r.arrivalIdCreated).forEach(r=>r.quantity=0)">清空数量</el-button></div></div>
<batch-progress v-if="runRows.length" :total="runRows.length" :completed="completedCount" :failed="failedCount" :running="saving" v-model:onlyFailed="onlyFailed"/>
@ -58,6 +58,7 @@ import ItemSummary from '@/components/ItemSummary'
import TableText from '@/components/TableText'
import { useCompactLayout } from '@/utils/use-compact-layout'
export default {
props:{separateAcceptance:Boolean},
components:{ArrivalPhotos,BatchProgress,DialogWorkspace,ItemSummary,TableText},setup:useCompactLayout,
data:()=>({visible:false,saving:false,opening:false,mode:'receipt',rows:[],runRows:[],onlyFailed:false,areas:[],commonArea:undefined,date:'',remark:'',acceptAll:true,keyword:'',pageNum:1,pageSize:20}),
watch:{keyword(){this.pageNum=1;const visible=new Set(this.filteredRows);this.rows.forEach(r=>{if(!visible.has(r)&&!r.done)r.chosen=false})},onlyFailed(){this.pageNum=1},'filteredRows.length'(count){this.pageNum=Math.min(this.pageNum,Math.max(1,Math.ceil(count/this.pageSize)))}},
@ -80,7 +81,7 @@ export default {
if(this.saving||this.opening)return
this.opening=true;this.visible=true;this.runRows=[];this.onlyFailed=false
try {
this.mode=mode;this.keyword='';this.pageNum=1;this.date=this.parseTime(new Date(),'{y}-{m}-{d}');this.remark='';this.acceptAll=true;this.commonArea=undefined;this.rows=[]
this.mode=mode;this.keyword='';this.pageNum=1;this.date=this.parseTime(new Date(),'{y}-{m}-{d}');this.remark='';this.acceptAll=!this.separateAcceptance;this.commonArea=undefined;this.rows=[]
this.areas=mode==='receipt'?((await optionselectArea()).data||[]):[]
if(mode==='acceptance') {
const requests=[...new Map(input.filter(r=>!r.historical&&Number(r.purchaseStatus)!==5).map(r=>[r.id,r])).values()]

View File

@ -49,7 +49,7 @@ export function homeTarget(row, queue) {
const projectId = row.projectId || row.sourceProjectId || row.project_id || row.borrowerProjectId
const query = projectId ? { projectId } : {}
if (row.source === 'purchase') {
if (queue === 'acceptance' || queue === 'arrival') return { path: '/procurement/arrival', query: { ...query, purchaseBatchNo: row.purchaseBatchNo || undefined, requestNo: row.requestNo, queue: queue === 'acceptance' ? 'pending' : 'open' } }
if (queue === 'acceptance' || queue === 'arrival') return { path: queue==='acceptance'?'/procurement/acceptance':'/procurement/arrival', query: { ...query, purchaseBatchNo: row.purchaseBatchNo || undefined, requestNo: row.requestNo, queue: queue === 'acceptance' ? 'pending' : 'open' } }
return { path: '/procurement/details', query: { ...query, purchaseBatchId: row.purchaseBatchId || undefined, legacy: row.purchaseBatchId ? undefined : '1', requestNo: row.requestNo } }
}
if (row.source === 'receipt') return { path: '/warehouse/pending', query: { ...query, sourceGroup:row.sourceGroup, inNo:row.sourceGroup?(row.sourceGroup.startsWith('O:')?row.record:undefined):row.inNo } }
@ -81,7 +81,7 @@ export function homeOverview(projects, purchases, tasks) {
export function homeQueueTarget(key, projectId) {
const query = projectId ? { projectId } : {}
if (key === 'quote' || key === 'confirm') return { path: '/procurement/details', query:{...query,progress:key} }
if (key === 'arrival' || key === 'acceptance') return { path: '/procurement/arrival', query: { ...query, queue: key === 'acceptance' ? 'pending' : 'open' } }
if (key === 'arrival' || key === 'acceptance') return { path: key==='acceptance'?'/procurement/acceptance':'/procurement/arrival', query: { ...query, queue: key === 'acceptance' ? 'pending' : 'open' } }
if (key === 'receipt') return { path: '/warehouse/pending', query }
if (key === 'production') return { path: '/production/tasks', query:{...query,status:'READY'} }
return { path: '/warehouse/loans', query: { ...query, outstandingOnly: '1' } }

View File

@ -0,0 +1,6 @@
// Projects are paged as units; keep their first two cells merged without quadratic scans.
export function mergeProjectRows(rows){
const result=rows.map(row=>({...row,_span:0}))
for(let start=0;start<result.length;){let end=start+1;while(end<result.length&&result[end].projectId===result[start].projectId)end++;result[start]._span=end-start;start=end}
return result
}

View File

@ -1,6 +1,5 @@
export const purchaseDocumentKinds = Object.freeze([
{ kind: 'REQUEST', label: '采购申请', numberLabel: '随行编号' },
{ kind: 'QUOTE', label: '报价资料', numberLabel: '报价编号' },
{ kind: 'CONTRACT', label: '合同', numberLabel: '合同编号' },
{ kind: 'ACCEPTANCE', label: '验收资料', numberLabel: '验收流程编号' },
{ kind: 'PAYMENT', label: '付款资料', numberLabel: '付款流程编号' },

View File

@ -33,7 +33,7 @@ export async function createPurchaseDraft(vm, unbatched = false) {
vm.commonProject = vm.projectId || null
vm.sheet = {
unbatched,
batch: { id: null, supplierId: null, batchName: '', businessDate: vm.parseTime(new Date(), '{y}-{m}-{d}') },
batch: { id: null, supplierId: null, expenseCategoryId:vm.commonCategory||null, batchName: '', businessDate: vm.parseTime(new Date(), '{y}-{m}-{d}') },
rows: Array.from({ length: 5 }, () => vm.emptyRow()), deletedIds: [], version: null
}
vm.baseline = ''

View File

@ -12,7 +12,7 @@
</template>
<template #default="{tableHeight}"><business-table v-loading="loading" :data="rows" :height="tableHeight" empty-text="暂无安装包,上传本系统打包的 APK 后即可发布新版">
<el-table-column label="版本" width="110"><template #default="{row}"><strong>{{ row.versionName }}</strong></template></el-table-column>
<el-table-column label="状态" width="120"><template #default="{row}"><el-tag :type="row.current?'success':row.canPublish?'primary':'info'" effect="light">{{ row.current?'当前发布':row.canPublish?'待发布':'较早版本' }}</el-tag></template></el-table-column>
<el-table-column label="状态" width="120" class-name="business-status-cell"><template #default="{row}"><el-tag :type="row.current?'success':row.canPublish?'primary':'info'" effect="light">{{ row.current?'当前发布':row.canPublish?'待发布':'较早版本' }}</el-tag></template></el-table-column>
<el-table-column label="安装包" prop="name" min-width="260" show-overflow-tooltip/>
<el-table-column label="大小" width="100" align="right"><template #default="{row}">{{ fileSize(row.size) }}</template></el-table-column>
<el-table-column label="上传人" prop="uploadedBy" width="120" show-overflow-tooltip/>

View File

@ -0,0 +1,5 @@
<template><purchase-request initial-view="acceptance" /></template>
<script>
import PurchaseRequest from '@/views/warehouse/purchase'
export default {name:'PurchaseAcceptance',components:{PurchaseRequest}}
</script>

View File

@ -4,8 +4,8 @@
<el-alert v-if="error" type="error" :title="error" :closable="false" class="batch-review-error"/>
<el-table :data="rows" v-loading="loading" size="small" border max-height="58vh" row-key="id">
<el-table-column type="index" label="序号" width="60" align="center"/>
<el-table-column label="小类名称" min-width="190"><template #default="{row}"><el-input v-model="row.name" maxlength="100" placeholder="填写小类名称" :disabled="saving"/></template></el-table-column>
<el-table-column label="所属大类" min-width="180"><template #default="{row}"><el-select v-model="row.parentCode" filterable placeholder="选择已有大类" :disabled="saving"><el-option v-for="group in groups" :key="group.id" :value="group.id" :label="group.label"/></el-select></template></el-table-column>
<el-table-column label="小类名称" min-width="190" class-name="business-control-cell"><template #default="{row}"><el-input v-model="row.name" maxlength="100" placeholder="填写小类名称" :disabled="saving"/></template></el-table-column>
<el-table-column label="所属大类" min-width="180" class-name="business-control-cell"><template #default="{row}"><el-select v-model="row.parentCode" filterable placeholder="选择已有大类" :disabled="saving"><el-option v-for="group in groups" :key="group.id" :value="group.id" :label="group.label"/></el-select></template></el-table-column>
<el-table-column prop="exampleName" label="参考物品" min-width="160" show-overflow-tooltip/>
<el-table-column prop="purchaseCount" label="采购明细" width="100" align="center"/>
<el-table-column prop="productCount" label="物品档案" width="100" align="center"/>

View File

@ -17,7 +17,7 @@
<el-table-column prop="applicantName" label="申请人" width="100"/>
<el-table-column label="申请时间" width="160"><template #default="{row}">{{ formatDateTime(row.createTime) }}</template></el-table-column>
<el-table-column prop="reviewNote" label="处理说明" min-width="160" show-overflow-tooltip/>
<el-table-column label="操作" width="130" fixed="right" align="center"><template #default="{row}"><el-button link type="primary" @click="openReview(row)">{{ row.status==='PENDING'?'确认 / 调整':'查看记录' }}</el-button></template></el-table-column>
<el-table-column label="操作" width="130" fixed="right" align="center" class-name="business-operation-cell"><template #default="{row}"><el-button link type="primary" @click="openReview(row)">{{ row.status==='PENDING'?'确认 / 调整':'查看记录' }}</el-button></template></el-table-column>
</business-table></template>
<template #footer><pagination v-show="total>0" :total="total" v-model:page="query.pageNum" v-model:limit="query.pageSize" @pagination="load"/></template>
<template #dialogs>

View File

@ -46,7 +46,7 @@
<el-table-column label="物品名称" prop="productName" show-overflow-tooltip min-width="160"/>
<el-table-column label="品牌" prop="brand" show-overflow-tooltip min-width="100"/>
<el-table-column label="大类" prop="categoryGroupName" show-overflow-tooltip min-width="100"/>
<el-table-column label="小类" prop="category" show-overflow-tooltip min-width="150"><template #default="{row}">{{ row.category }}<el-tag v-if="pendingCategory(row.category)" size="small" type="warning" style="margin-left:6px">待确认</el-tag></template></el-table-column>
<el-table-column label="小类" prop="category" show-overflow-tooltip min-width="150" class-name="business-status-cell"><template #default="{row}">{{ row.category }}<el-tag v-if="pendingCategory(row.category)" size="small" type="warning" style="margin-left:6px">待确认</el-tag></template></el-table-column>
<el-table-column label="规格型号" prop="spec" show-overflow-tooltip min-width="180"/>
<el-table-column label="单位" prop="unit" show-overflow-tooltip width="70"/>
<el-table-column label="备注" prop="remark" show-overflow-tooltip min-width="160"/>

View File

@ -20,9 +20,8 @@
<template #actions><el-form-item>
<el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
</el-form-item><right-toolbar :gutter="0" @queryTable="refreshPurchaseData()" /><business-page-header title="到货验收" guide="先确认采购,再登记实际到货数量并验收;验收合格后到「待入库」办理入库,支持分次到货。" /></template>
</el-form-item><right-toolbar :gutter="0" @queryTable="refreshPurchaseData()" /><business-page-header :title="pageTitle" guide="先确认采购,再登记实际到货数量并验收;验收合格后到「待入库」办理入库,支持分次到货。" /></template>
<template #advanced>
<el-form-item v-if="arrivalMode" label="到货队列"><el-radio-group v-model="arrivalQueue" size="small" @change="applyArrivalQueue(arrivalQueueCards.find(item=>item.key===$event))"><el-radio-button v-for="item in arrivalQueueCards" :key="item.key" :value="item.key">{{ item.label }}</el-radio-button></el-radio-group></el-form-item>
<el-form-item v-if="!arrivalMode" label="采购状态" prop="purchaseStatus">
<el-select v-model="queryParams.purchaseStatus" placeholder="请选择状态" clearable @change="handleAdvancedStatusChange">
<el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
@ -42,10 +41,10 @@
</el-collapse-transition>
<div class="list-actions arrival-actions">
<el-button type="primary" size="small" icon="el-icon-box" :disabled="!canBatchArrivalSelection" @click="$refs.batchArrival.open(selectedPurchaseRows,'arrival')" v-if="$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">登记到货</el-button>
<el-button type="primary" plain size="small" :disabled="!selectedPurchaseRows.some(r=>Number(r.pendingArrivalQuantity)>0)" @click="$refs.batchArrival.open(selectedPurchaseRows,'acceptance')" v-if="$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">验收到货</el-button>
<el-button v-if="arrivalQueue !== 'completed' && canOperate()" size="small" :loading="choosingFiltered&&selectionPurpose==='arrival'" :disabled="loading||choosingFiltered" @click="chooseFiltered('arrival')">选择待到货项</el-button>
<el-button v-if="arrivalQueue !== 'completed' && canOperate()" size="small" :loading="choosingFiltered&&selectionPurpose==='acceptance'" :disabled="loading||choosingFiltered" @click="chooseFiltered('acceptance')">选择待验收项</el-button>
<el-button type="primary" size="small" icon="el-icon-box" :disabled="!canBatchArrivalSelection" @click="$refs.batchArrival.open(selectedPurchaseRows,'arrival')" v-if="initialView!=='acceptance'&&$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">批量登记到货</el-button>
<el-button type="primary" plain size="small" :disabled="!selectedPurchaseRows.some(r=>Number(r.pendingArrivalQuantity)>0)" @click="$refs.batchArrival.open(selectedPurchaseRows,'acceptance')" v-if="initialView==='acceptance'&&$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">批量验收</el-button>
<el-button v-if="initialView!=='acceptance' && canOperate()" size="small" :loading="choosingFiltered&&selectionPurpose==='arrival'" :disabled="loading||choosingFiltered" @click="chooseFiltered('arrival')">选择待到货项</el-button>
<el-button v-if="initialView==='acceptance' && canOperate()" size="small" :loading="choosingFiltered&&selectionPurpose==='acceptance'" :disabled="loading||choosingFiltered" @click="chooseFiltered('acceptance')">选择待验收项</el-button>
<div class="arrival-list-summary">
<table-text v-if="queryParams.purchaseBatchNo" :value="'当前批次:'+selectedBatchLabel" />
<table-text v-else-if="queryParams.requestNo" :value="'当前定位:'+queryParams.requestNo" />
@ -282,7 +281,7 @@
<el-button type="primary" :loading="formSubmitting" :disabled="projectBudgetLoading" @click="submitForm">{{ form.id ? '保存修改' : '提交申请' }}</el-button>
<el-button :disabled="formSubmitting" @click="cancel">取消</el-button>
</div></template>
</el-dialog><batch-arrival ref="batchArrival" @changed="refreshPurchaseData()" /><el-dialog title="分配或转移采购批次" v-model="assignOpen" width="520px" append-to-body :close-on-click-modal="!assignSubmitting" :close-on-press-escape="!assignSubmitting" :show-close="!assignSubmitting">
</el-dialog><batch-arrival ref="batchArrival" separate-acceptance @changed="refreshPurchaseData()" /><el-dialog title="分配或转移采购批次" v-model="assignOpen" width="520px" append-to-body :close-on-click-modal="!assignSubmitting" :close-on-press-escape="!assignSubmitting" :show-close="!assignSubmitting">
<el-form ref="assignForm" :model="assignForm" :rules="assignRules" label-width="auto">
<el-form-item label="目标批次" prop="batchId">
<el-select v-model="assignForm.batchId" filterable remote :remote-method="searchBatchOptions" :loading="batchOptionLoading" :disabled="assignSubmitting" placeholder="输入编号或名称搜索可用批次">
@ -418,7 +417,7 @@
<el-form-item label="进度说明" prop="progressRemark"><el-input v-model="statusForm.progressRemark" type="textarea" :rows="3" :disabled="statusSubmitting" /></el-form-item>
</el-form>
<template #footer><div class="dialog-footer"><el-button type="primary" :loading="statusSubmitting" @click="submitStatus">确定</el-button><el-button :disabled="statusSubmitting" @click="statusOpen = false">取消</el-button></div></template>
</el-dialog><el-dialog title="到货与验收" v-model="arrivalOpen" width="min(1180px,96vw)" top="5vh" class="arrival-dialog" append-to-body :close-on-click-modal="!arrivalBusy" :close-on-press-escape="!arrivalBusy" :show-close="!arrivalBusy" @closed="handleArrivalClosed">
</el-dialog><el-dialog :title="initialView==='acceptance'?'验收到货':'登记到货'" v-model="arrivalOpen" width="min(1180px,96vw)" top="5vh" class="arrival-dialog" append-to-body :close-on-click-modal="!arrivalBusy" :close-on-press-escape="!arrivalBusy" :show-close="!arrivalBusy" @closed="handleArrivalClosed">
<div v-if="arrivalRequest" class="arrival-header">
<strong>{{ arrivalRequest.materialName }}</strong><span>{{ arrivalRequest.purchaseBatchNo }} · {{ arrivalRequest.supplierName }}</span>
<span>{{ arrivalRequest.projectName }} / {{ arrivalRequest.expenseCategoryName }}</span>
@ -427,7 +426,7 @@
<span>待验收 {{ arrivalRequest.pendingArrivalQuantity || 0 }}</span>
<span>可登记 {{ arrivalRequest.remainingQuantity || 0 }}</span>
</div>
<el-form v-if="arrivalRequest && canOperate(arrivalRequest) && arrivalRequest.priceLocked && Number(arrivalRequest.remainingQuantity)>0" ref="arrivalForm" :model="arrivalForm" :rules="arrivalRules" :inline="true" size="small" class="arrival-form">
<el-form v-if="initialView!=='acceptance' && arrivalRequest && canOperate(arrivalRequest) && arrivalRequest.priceLocked && Number(arrivalRequest.remainingQuantity)>0" ref="arrivalForm" :model="arrivalForm" :rules="arrivalRules" :inline="true" size="small" class="arrival-form">
<el-form-item label="本次到货" prop="arrivalQuantity"><el-input-number v-model="arrivalForm.arrivalQuantity" :min="0" :max="Number(arrivalRequest.remainingQuantity || 0)" :precision="4" :controls="false" :disabled="arrivalBusy" /></el-form-item>
<el-form-item><el-button :disabled="arrivalBusy" @click="arrivalForm.arrivalQuantity=Number(arrivalRequest.remainingQuantity)">全部剩余数量</el-button></el-form-item><el-form-item label="到货日期" prop="arrivalDate"><el-date-picker v-model="arrivalForm.arrivalDate" type="date" value-format="YYYY-MM-DD" :disabled="arrivalBusy" /></el-form-item>
<el-form-item label="备注" prop="remark"><el-input v-model="arrivalForm.remark" :disabled="arrivalBusy" /></el-form-item>
@ -444,7 +443,7 @@
<el-table-column label="验收状态" width="100" align="center" class-name="business-status-cell"><template #default="scope"><el-tag :type="(acceptanceType(scope.row.acceptanceStatus)) || 'primary'" size="small">{{ acceptanceLabel(scope.row.acceptanceStatus) }}</el-tag></template></el-table-column>
<el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos :model-value="s.row.photos||[]" readonly compact/></template></el-table-column>
<el-table-column label="验收人" prop="acceptedBy" width="100" show-overflow-tooltip/>
<el-table-column label="操作" width="190" align="center" fixed="right" class-name="business-operation-cell">
<el-table-column v-if="initialView==='acceptance'" label="操作" width="190" align="center" fixed="right" class-name="business-operation-cell">
<template #default="scope">
<template v-if="scope.row.acceptanceStatus === 0 && arrivalRequest && canOperate(arrivalRequest) && arrivalRequest.priceLocked">
<el-button link type="primary" icon="el-icon-check" :loading="arrivalActionLoading('accept', scope.row.id)" :disabled="arrivalBusy" @click="handleAcceptance(scope.row, 1)">通过</el-button>
@ -610,8 +609,8 @@ export default {
},
computed: {
selectedBatchLabel(){const batch=this.batchFilterOptions.find(b=>b.batchNo===this.queryParams.purchaseBatchNo);return batch?this.batchLabel(batch):this.queryParams.purchaseBatchNo},
arrivalMode() { return this.initialView === 'arrival' },
pageTitle() { return this.arrivalMode ? '到货验收' : '采购明细' },
arrivalMode() { return ['arrival','acceptance'].includes(this.initialView) },
pageTitle() { return this.initialView==='acceptance'?'验收':this.arrivalMode?'到货':'采购申请' },
pageDescription() { return this.arrivalMode ? '集中处理未到齐、待验收和部分到货明细;支持单条、批量及多次到货。' : '按项目、供应商或批次筛选,直接维护明细;同一批次可分次到货。' },
selectedPurchaseRows() { return this.allFilteredSelected ? this.allFilteredRows : this.purchaseList.filter(r=>this.ids.includes(r.id)) },
canBatchArrivalSelection() { return this.selectedPurchaseRows.some(r=>r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5&&Number(r.remainingQuantity)>0) },
@ -691,7 +690,7 @@ export default {
watch:{'$route.fullPath'(){if(!this._pageInactive)this.applyHomeNavigation()}},
methods: {formatDateTime,
applyHomeFilters(){this._homeRoute=this.$route.fullPath;const q=this.$route.query;this.queryParams.projectId=this.projectId||Number(q.projectId)||undefined;this.queryParams.requestNo=q.requestNo||undefined;if(q.queue==='pending'){this.arrivalQueue='pendingAcceptance';this.queryParams.pendingAcceptance=true;this.queryParams.notArrived=false}},
applyHomeNavigation(){if(this._homeRoute===this.$route.fullPath)return;if(this.arrivalMode && this.$route.path==='/procurement/arrival'){this.applyHomeFilters();this.queryParams.purchaseBatchNo=this.$route.query.purchaseBatchNo||undefined;if(this.$route.query.queue!=='pending'){this.queryParams.pendingAcceptance=false;this.queryParams.notArrived=!this.queryParams.purchaseBatchNo;this.arrivalQueue=this.queryParams.purchaseBatchNo?'all':'open'}this.queryParams.pageNum=1;this.getList()}},
applyHomeNavigation(){if(this._homeRoute===this.$route.fullPath)return;if(this.arrivalMode && ['/procurement/arrival','/procurement/acceptance'].includes(this.$route.path)){this.applyHomeFilters();this.queryParams.purchaseBatchNo=this.$route.query.purchaseBatchNo||undefined;if(this.$route.query.queue!=='pending'){this.queryParams.pendingAcceptance=false;this.queryParams.notArrived=!this.queryParams.purchaseBatchNo;this.arrivalQueue=this.queryParams.purchaseBatchNo?'all':'open'}this.queryParams.pageNum=1;this.getList()}},
openLegacy(view='details'){this.purchaseView=view;this.legacyMode=true;this.queryParams.unbatched=view==='unbatched';if(this.queryParams.unbatched)this.queryParams.purchaseBatchNo=undefined;this.queryParams.pageNum=1;this.queryParams.projectId=this.projectId||Number(this.$route.query.projectId)||undefined;this.getList();this.getTaskStats();this.getProductFilterOptions();this.getFundingOptions();this.searchBatchFilterOptions('');if(this.canManageAll)this.getBatchOptions()},
async changePurchaseView(view){
const previous=this.legacyMode?(this.queryParams.unbatched?'unbatched':'details'):'batches',sheet=this.$refs.sheet
@ -881,7 +880,7 @@ export default {
},
getList() {
if(this.projectId)this.queryParams.projectId=this.projectId
if(this.arrivalMode){this.queryParams.priceLocked=this.arrivalQueue==='all'?undefined:true;this.queryParams.arrivalReady=this.arrivalQueue!=='all'}
if(this.arrivalMode){const acceptance=this.initialView==='acceptance';this.queryParams.priceLocked=true;this.queryParams.arrivalReady=true;this.queryParams.pendingAcceptance=acceptance;this.queryParams.pendingRegistration=!acceptance;this.queryParams.notArrived=false;this.arrivalQueue=acceptance?'pendingAcceptance':'open'}
invalidateQuery(this,"filteredSelection");this.choosingFiltered=false;
this.allFilteredSelected=false;this.allFilteredRows=[];this.ids=[];
const requestId = ++this.listRequestId
@ -1011,6 +1010,8 @@ export default {
this.refreshArrival(row.id)
},
arrivalActionLabel(row) {
if(this.initialView==='acceptance')return this.canOperate(row)?'验收到货':'到货记录'
if(this.initialView==='arrival')return this.canOperate(row)?'登记到货':'到货记录'
if (!this.canOperate(row) || !row.priceLocked) return '到货记录'
const pending = Number(row && row.pendingArrivalQuantity || 0)
const remaining = Number(row && row.remainingQuantity || 0)

View File

@ -0,0 +1,83 @@
<template>
<div class="app-container purchase-board" :aria-busy="loading">
<div class="board-toolbar">
<el-radio-group v-model="view" @change="changeView"><el-radio-button value="board">资料进度</el-radio-button><el-radio-button value="ledger">采购台账</el-radio-button><el-radio-button v-if="canQuote" value="costs">项目费用统计</el-radio-button></el-radio-group>
<span class="board-guide">{{ view==='costs'?'报价金额汇总 · 按项目分页':view==='ledger'?'金额按有效明细的报价合计':'点击节点维护资料,资料齐全后自动打勾' }}</span>
<el-button type="primary" plain @click="goRequest()">采购申请</el-button>
</div>
<el-form inline class="board-filters" size="small" @submit.prevent="search">
<el-form-item label="项目"><el-select v-model="query.projectId" filterable clearable placeholder="全部项目" @change="search"><el-option v-for="p in projects" :key="p.id" :label="p.projectName" :value="p.id"/></el-select></el-form-item>
<el-form-item label="费用类别"><el-select v-model="query.expenseCategoryId" filterable clearable placeholder="全部类别" @change="search"><el-option label="待统一" :value="0"/><el-option v-for="c in categories" :key="c.id" :label="c.categoryName" :value="c.id"/></el-select></el-form-item>
<el-form-item label="批次 / 供应商"><el-input v-model="query.keyword" clearable placeholder="名称、编号或备注" @keyup.enter="search"/></el-form-item>
<el-form-item label="批次日期"><el-date-picker v-model="dates" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" @change="search"/></el-form-item>
<el-form-item><el-tooltip content="包含我创建明细的批次,金额按整批统计"><el-checkbox v-model="query.onlyMine" @change="search">只看我的</el-checkbox></el-tooltip></el-form-item>
<el-form-item><el-button type="primary" @click="search">查询</el-button><el-button @click="reset">重置</el-button></el-form-item>
</el-form>
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon><el-button link @click="load">重试</el-button></el-alert>
<div class="board-table" v-loading="loading" data-viewport-explicit>
<el-table v-if="view==='board'" :data="rows" height="100%" row-key="id" size="small">
<el-table-column label="采购批次" min-width="205"><template #default="{row}"><el-link type="primary" underline="never" class="batch-title" @click="goRequest(row)">{{ row.batchName||row.batchNo }}</el-link><div class="muted">{{ row.supplierName||'供应商待定' }}</div></template></el-table-column>
<el-table-column label="项目" prop="projectNames" min-width="145" show-overflow-tooltip/>
<el-table-column label="费用类别" min-width="145" class-name="business-operation-cell"><template #default="{row}"><el-button v-if="canManage" link :type="row.expenseCategoryId?'primary':'warning'" class="category-link" @click="editCategory(row)">{{ row.expenseCategoryName }}</el-button><span v-else>{{ row.expenseCategoryName }}</span></template></el-table-column>
<el-table-column v-if="canQuote" label="报价合计(元)" width="145" align="right"><template #default="{row}">{{ money(row.quoteAmount) }}<div v-if="row.unpricedCount" class="unpriced">{{ row.unpricedCount }} 项未报价</div></template></el-table-column>
<el-table-column label="资料进度" min-width="410" class-name="business-control-cell"><template #default="{row}"><div class="document-steps"><el-tooltip v-for="(step,index) in row.stages" :key="step.kind" :content="stageHint(step)" placement="top"><button class="document-step" :class="{'is-complete':step.complete,'has-files':step.files>0}" :aria-label="`${row.batchName||row.batchNo} ${labels[step.kind]}资料 ${step.complete?'齐全':'待补充'}`" @click="openDocuments(row,step.kind)"><span class="step-dot">{{ step.complete?'✓':index+1 }}</span><span class="step-label">{{ labels[step.kind] }}</span><span class="step-count">{{ step.complete?'已齐全':step.files?step.files+' 份附件':'待补充' }}</span></button></el-tooltip></div></template></el-table-column>
</el-table>
<el-table v-else-if="view==='ledger'" :data="rows" height="100%" row-key="id" size="small" border>
<el-table-column label="采购批次" min-width="185" fixed><template #default="{row}"><el-link type="primary" underline="never" @click="goRequest(row)">{{ row.batchName||row.batchNo }}</el-link></template></el-table-column>
<el-table-column label="采购人" prop="purchasers" min-width="100" show-overflow-tooltip/>
<el-table-column label="费用类别" min-width="170" class-name="business-operation-cell"><template #default="{row}"><el-button v-if="canManage" link type="primary" class="category-link" @click="editCategory(row)">{{ row.expenseCategoryName }}</el-button><span v-else>{{ row.expenseCategoryName }}</span></template></el-table-column>
<el-table-column v-if="canQuote" label="合同/直接采购金额(元)" width="185" align="right"><template #default="{row}">{{ money(row.quoteAmount) }}<span v-if="row.unpricedCount" class="unpriced"> · 含未报价</span></template></el-table-column>
<el-table-column label="供应商全称" prop="supplierName" min-width="220" show-overflow-tooltip/>
<el-table-column label="备注" prop="remark" min-width="220" show-overflow-tooltip/>
<el-table-column v-for="kind in ['REQUEST','CONTRACT','PAYMENT']" :key="kind" :label="numberLabels[kind]" min-width="170" class-name="business-operation-cell"><template #default="{row}"><el-link type="primary" underline="never" @click="openDocuments(row,kind)">{{ stage(row,kind)?.number||'填写编号 / 上传资料' }}</el-link></template></el-table-column>
</el-table>
<el-table v-else-if="canQuote" :data="costRows" height="100%" :span-method="mergeProject" size="small" border>
<el-table-column label="项目编号" prop="projectCode" width="180"/>
<el-table-column label="项目名称" prop="projectName" min-width="280"/>
<el-table-column label="费用类别" prop="expenseCategoryName" min-width="260"/>
<el-table-column label="费用统计(元)" min-width="190" align="right"><template #default="{row}">{{ money(row.quoteAmount) }}<span v-if="row.unpricedCount" class="unpriced"> · {{ row.unpricedCount }} 项未报价</span></template></el-table-column>
</el-table>
</div>
<div class="board-footer"><span v-if="canQuote">{{ view==='costs'?'项目费用合计':'筛选批次报价合计' }}:<strong>{{ money(summary.quoteAmount) }}</strong><span v-if="summary.unpricedCount" class="unpriced"> · {{ summary.unpricedCount }} 项未报价未计入</span></span><span v-else class="muted">报价金额仅采购管理员可见</span><el-pagination v-model:current-page="query.pageNum" v-model:page-size="query.pageSize" :page-sizes="[20,50,100]" :total="total" layout="total, sizes, prev, pager, next" @current-change="load" @size-change="search"/></div>
<purchase-documents ref="documents" @updated="load"/>
<el-dialog v-model="categoryOpen" title="统一批次费用类别" width="480px" :close-on-click-modal="!categorySaving" :show-close="!categorySaving">
<p class="category-context">{{ categoryRow?.batchName||categoryRow?.batchNo }}</p><el-select v-model="categoryId" filterable placeholder="选择整批使用的费用类别" :disabled="categorySaving" style="width:100%"><el-option v-for="c in categories" :key="c.id" :label="c.categoryName" :value="c.id"/></el-select><p class="muted category-note">整批有效采购、关联入库分类和预算占用同步调整;不改变报价、数量和库存成本。</p>
<template #footer><el-button :disabled="categorySaving" @click="categoryOpen=false">取消</el-button><el-button type="primary" :loading="categorySaving" :disabled="!categoryId" @click="saveCategory">统一整批</el-button></template>
</el-dialog>
</div>
</template>
<script setup>
import {ref,computed,onMounted,onActivated,onBeforeUnmount,watch} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import useUserStore from '@/store/modules/user'
import {canViewPurchaseQuotes} from '@/utils/purchase-quote-permission'
import {getPurchaseBoard,getPurchaseCostSummary,setBatchExpenseCategory} from '@/api/warehouse/purchase-board'
import {projectOptions,categoryOptions} from '@/api/project/project'
import PurchaseDocuments from '@/components/PurchaseDocuments'
import {mergeProjectRows} from '@/utils/purchase-board'
const user=useUserStore(),router=useRouter(),canQuote=computed(()=>canViewPurchaseQuotes(user.id,user.roles)),canManage=computed(()=>user.permissions.includes('*:*:*')||user.permissions.includes('warehouse:purchase:manage'))
const view=ref('board'),query=ref({pageNum:1,pageSize:20,keyword:'',projectId:null,expenseCategoryId:null,onlyMine:false}),dates=ref([]),projects=ref([]),categories=ref([]),rows=ref([]),total=ref(0),summary=ref({}),loading=ref(false),error=ref(''),documents=ref()
const categoryOpen=ref(false),categoryRow=ref(),categoryId=ref(),categorySaving=ref(false)
const labels={REQUEST:'申请',CONTRACT:'合同',ACCEPTANCE:'验收',PAYMENT:'付款'},numberLabels={REQUEST:'采购流程编号',CONTRACT:'合同编号',PAYMENT:'付款流程编号'}
let controller,serial=0,mounted=false
const money=value=>value==null?'—':Number(value).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})
const stage=(row,kind)=>row.stages?.find(s=>s.kind===kind)
function stageHint(step){return step.complete?'资料齐全,点击查看或补充':`${step.files?step.files+' 份PDF':'缺少PDF附件'}${step.kind!=='ACCEPTANCE'&&!step.number?';缺少'+numberLabels[step.kind]:''},点击维护`}
const costRows=computed(()=>mergeProjectRows(rows.value))
function mergeProject({row,columnIndex}){if(columnIndex<2)return row._span?[row._span,1]:[0,0]}
async function load(){const ticket=++serial;controller?.abort();controller=new AbortController();loading.value=true;error.value='';try{const response=await (view.value==='costs'?getPurchaseCostSummary:getPurchaseBoard)({...query.value,beginDate:dates.value?.[0],endDate:dates.value?.[1]},controller.signal);if(ticket!==serial)return;rows.value=response.data.rows;total.value=response.data.total;summary.value=response.data.summary||{}}catch(e){if(ticket===serial&&e.code!=='ERR_CANCELED'){rows.value=[];total.value=0;summary.value={};error.value=e.message||'加载失败,请重试'}}finally{if(ticket===serial)loading.value=false}}
watch(canQuote,value=>{if(!value&&view.value==='costs'){view.value='board';rows.value=[];summary.value={};if(mounted)search()}})
function search(){query.value.pageNum=1;load()}
function changeView(){rows.value=[];total.value=0;summary.value={};search()}
function reset(){query.value={pageNum:1,pageSize:20,keyword:'',projectId:null,expenseCategoryId:null,onlyMine:false};dates.value=[];load()}
function goRequest(row){router.push({path:'/procurement/details',query:row?{purchaseBatchId:row.id}:{}})}
function openDocuments(row,kind){documents.value.open('batch',row.id,row.batchName||row.batchNo,kind)}
function editCategory(row){categoryRow.value=row;categoryId.value=row.expenseCategoryId;categoryOpen.value=true}
async function saveCategory(){if(categorySaving.value||!categoryId.value)return;categorySaving.value=true;try{await setBatchExpenseCategory(categoryRow.value.id,{categoryId:categoryId.value,expectedCategoryId:categoryRow.value.expenseCategoryId});categoryOpen.value=false;ElMessage.success('整批费用类别已统一');await load()}catch{/* shared request handler */}finally{categorySaving.value=false}}
onMounted(async()=>{const results=await Promise.allSettled([projectOptions('',true),categoryOptions()]);if(results[0].status==='fulfilled')projects.value=results[0].value.data||[];if(results[1].status==='fulfilled')categories.value=results[1].value.data||[];mounted=true;load()})
onActivated(()=>{if(mounted)load()});onBeforeUnmount(()=>{serial++;controller?.abort()})
</script>
<style scoped>
.purchase-board{display:flex;flex-direction:column;gap:12px;height:calc(100dvh - 88px);min-height:420px;padding:16px 20px}.board-toolbar{display:flex;align-items:center;gap:16px;flex-wrap:wrap}.board-toolbar>.el-button{margin-left:auto}.board-guide,.muted{color:var(--el-text-color-secondary);font-size:12px;line-height:1.7}.board-filters{background:var(--el-fill-color-light);border-radius:8px;padding:14px 14px 2px}.board-filters .el-form-item{margin-right:18px;margin-bottom:12px}.board-filters .el-select{width:190px}.board-filters :deep(.el-date-editor){width:250px}.board-table{flex:1;min-height:180px;overflow:hidden;border:1px solid var(--el-border-color-lighter);border-radius:6px}.board-footer{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;font-size:13px}.board-footer strong{font-size:17px;font-variant-numeric:tabular-nums;color:var(--el-text-color-primary)}.batch-title{font-weight:600;max-width:100%;justify-content:flex-start}.category-link{white-space:normal;text-align:left;height:auto;line-height:1.6}.unpriced{color:var(--el-color-warning);font-size:12px}.document-steps{display:flex;padding:4px 0;min-width:380px}.document-step{position:relative;display:flex;flex:1;flex-direction:column;align-items:center;gap:1px;border:0;background:none;color:var(--el-text-color-regular);cursor:pointer;padding:0 8px;font:inherit}.document-step:not(:last-child)::after{content:'';height:2px;background:var(--el-border-color-lighter);position:absolute;top:12px;left:calc(50% + 18px);width:calc(100% - 36px)}.step-dot{position:relative;z-index:1;display:grid;place-items:center;width:24px;height:24px;border-radius:50%;border:1px solid var(--el-border-color);color:var(--el-text-color-secondary);background:var(--el-bg-color);font-size:13px}.step-label{font-size:13px;line-height:1.4;font-weight:500}.step-count{font-size:11px;line-height:1.4;color:var(--el-text-color-secondary)}.is-complete .step-dot{background:var(--el-color-success-light-9);border-color:var(--el-color-success);color:var(--el-color-success);font-weight:700}.is-complete:not(:last-child)::after{background:var(--el-color-success-light-5)}.has-files:not(.is-complete) .step-dot{color:var(--el-color-warning);border-color:var(--el-color-warning);background:var(--el-color-warning-light-9)}.document-step:hover .step-label{color:var(--el-color-primary)}.document-step:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:4px;border-radius:4px}.category-context{margin-top:0;font-weight:600}.category-note{margin-top:14px}@media(max-width:1000px){.board-guide{display:none}.purchase-board{padding:12px}.board-footer :deep(.el-pagination){max-width:100%;overflow:auto}}
</style>

View File

@ -6,6 +6,8 @@ import {parse} from '@vue/compiler-sfc'
import Borrow from '../../src/components/ProjectLoans/BatchBorrow.vue'
import Receipt from '../../src/components/ReceiptDialog/Batch.vue'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
const purchaseFlow=vi.hoisted(()=>({add:vi.fn(),accept:vi.fn(),list:vi.fn()}))
vi.mock('@/api/warehouse/purchase',()=>({addPurchaseArrival:purchaseFlow.add,acceptPurchaseArrival:purchaseFlow.accept,listPurchaseArrival:purchaseFlow.list}))
vi.mock('@/utils/use-compact-layout',()=>({useCompactLayout:()=>({compact:false})}))
const mounted=[]
afterEach(()=>{for(const w of mounted.splice(0))w.unmount()})
@ -35,3 +37,10 @@ it('all updated batch dialogs opt into shared styles without altering submission
expect(sfc.errors).toHaveLength(0);expect(source).toContain('class="batch-dialog');expect(source).toContain('batch-dialog-form');expect(source).toContain('label-position="top"');expect(source).toContain(':loading="saving"');expect(source).toContain(':disabled="saving');
}
})
it('the separated arrival page registers arrivals without automatically accepting them',async()=>{
purchaseFlow.add.mockResolvedValue({data:{id:91}});purchaseFlow.accept.mockClear();purchaseFlow.list.mockClear()
const w=shallowMount(Receipt,{props:{separateAcceptance:true},global:{...globals,mocks:{parseTime:()=> '2026-11-04',$modal:{msgWarning:vi.fn()}}}});mounted.push(w)
await w.vm.open([{id:7,remainingQuantity:2,purchaseStatus:1,priceLocked:true}], 'arrival')
expect(w.vm.acceptAll).toBe(false);expect(w.text()).not.toContain('同时按全部合格验收');w.vm.rows[0].quantity=2
await w.vm.submit();expect(purchaseFlow.add).toHaveBeenCalledOnce();expect(purchaseFlow.accept).not.toHaveBeenCalled();expect(purchaseFlow.list).not.toHaveBeenCalled();expect(w.vm.rows[0].done).toBe(true)
})

View File

@ -0,0 +1,17 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import AcceptanceReport from '../../src/components/PurchaseSheet/AcceptanceReport.vue'
const api=vi.hoisted(()=>({request:vi.fn()}))
vi.mock('@/utils/request',()=>({default:api.request}))
const mounted=[];afterEach(()=>{mounted.splice(0).forEach(w=>w.unmount());document.body.innerHTML='';vi.resetAllMocks()})
const fields={purchaser:'甲方',supplier:'乙方',description:'材料',address:'重庆市九龙坡区金凤镇招商局检测车辆技术研究院有限公司',contractNo:'HT-2026-001',projectNo:'',deliveryLocation:'招商车研',date:null,checks:Array(7).fill('')}
const snapshot=(ready=true)=>({data:{ready,count:2,version:'fresh-version',fields,documents:[{label:'采购申请',numberLabel:'随行编号',numbered:true,files:1},{label:'合同',numberLabel:'合同编号',numbered:true,files:1}],checkLabels:['供货范围是否与合同/技术协议一致','机械安装','电气安装','系统调试','运行结果','培训','资料'],issues:ready?[]:[{line:2,name:'试验物品B',reason:'尚未全部验收通过'}]}})
function render(disabled=false){const w=mount(AcceptanceReport,{props:{sheet:{batch:{id:7,batchName:'验收批次'},version:'old-ui-version'},disabled},global:{plugins:[ElementPlus]},attachTo:document.body});mounted.push(w);return w}
const button=text=>[...document.querySelectorAll('button')].find(b=>b.textContent.trim()===text)
it('shows the exact incomplete row and blocks generation for partially accepted goods',async()=>{api.request.mockResolvedValue(snapshot(false));const w=render();await w.vm.open();await flushPromises();expect(document.body.textContent).toContain('试验物品B');expect(button('生成并保存').disabled).toBe(true)})
it('saves the whole batch as an attachment and emits the saved file',async()=>{api.request.mockResolvedValueOnce(snapshot()).mockResolvedValueOnce({data:{id:'saved-file',name:'验收资料_待签章.pdf'}});const w=render();await w.vm.open();await flushPromises();button('生成并保存').click();await flushPromises();const call=api.request.mock.calls[1][0];expect(call).toMatchObject({url:'/warehouse/purchase/sheet/7/acceptance-generate',params:{version:'fresh-version'},data:{fields:{contractNo:'HT-2026-001',projectNo:'',deliveryLocation:'招商车研'}}});expect(call.data.requestId).toMatch(/^[0-9a-f-]{36}$/);expect(call.data).not.toHaveProperty('rowIds');expect(w.emitted('generated')[0][0].id).toBe('saved-file')})
it('requires request and contract documents even when all goods passed',async()=>{const data=snapshot();data.data.ready=false;data.data.documents[0]={label:'采购申请',numberLabel:'随行编号',numbered:false,files:0};api.request.mockResolvedValue(data);const w=render();await w.vm.open();await flushPromises();expect(document.body.textContent).toContain('缺少随行编号');expect(document.body.textContent).toContain('缺少PDF附件');expect(button('生成并保存').disabled).toBe(true)})
it('reuses the generation identity after a failed response',async()=>{api.request.mockResolvedValueOnce(snapshot()).mockRejectedValueOnce(new Error('response lost')).mockResolvedValueOnce({data:{id:'saved-file'}});const w=render();await w.vm.open();await flushPromises();button('生成并保存').click();await flushPromises();button('生成并保存').click();await flushPromises();expect(api.request.mock.calls[1][0].data.requestId).toBe(api.request.mock.calls[2][0].data.requestId)})
it('reads the contract number and fixes both destinations',async()=>{api.request.mockResolvedValue(snapshot());const w=render();await w.vm.open();await flushPromises();const inputs=[...document.querySelectorAll('input')];expect(inputs.find(input=>input.value==='HT-2026-001').readOnly).toBe(true);expect(inputs.some(input=>[fields.address,fields.deliveryLocation].includes(input.value))).toBe(false);expect(document.querySelector('.acceptance-report__fixed').textContent).toContain('招商车研')})
it('blocks unsaved documents and batch switches',async()=>{const blocked=render(true);await blocked.vm.open();expect(api.request).not.toHaveBeenCalled();api.request.mockResolvedValue(snapshot());const w=render();await w.vm.open();await flushPromises();await w.setProps({sheet:{batch:{id:8}}});button('生成并保存').click();await flushPromises();expect(api.request).toHaveBeenCalledTimes(1)})

View File

@ -0,0 +1,17 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Board from '../../src/views/warehouse/purchaseBoard/index.vue'
const api=vi.hoisted(()=>({board:vi.fn(),costs:vi.fn(),category:vi.fn(),open:vi.fn(),push:vi.fn(),user:{id:1,roles:['purchase_manager'],permissions:['*:*:*']}}))
vi.mock('@/components/PurchaseDocuments',()=>({default:{name:'PurchaseDocuments',template:'<div/>',methods:{open(...args){api.open(...args)}}}}))
vi.mock('@/store/modules/user',()=>({default:()=>api.user}))
vi.mock('vue-router',()=>({useRouter:()=>({push:api.push})}))
vi.mock('@/api/warehouse/purchase-board',()=>({getPurchaseBoard:api.board,getPurchaseCostSummary:api.costs,setBatchExpenseCategory:api.category}))
vi.mock('@/api/project/project',()=>({projectOptions:()=>Promise.resolve({data:[]}),categoryOptions:()=>Promise.resolve({data:[{id:4,categoryName:'材料费'}]})}))
const row={id:7,batchName:'机器人部件',supplierName:'供应商甲',expenseCategoryId:4,expenseCategoryName:'材料费',quoteAmount:12345.67,stages:['REQUEST','CONTRACT','ACCEPTANCE','PAYMENT'].map((kind,i)=>({kind,files:i<2?1:0,number:i<2?'N-1':'',complete:i<2}))}
let wrapper
afterEach(()=>{wrapper?.unmount();document.body.innerHTML='';vi.clearAllMocks();api.user.id=1;api.user.roles=['purchase_manager'];api.user.permissions=['*:*:*']})
async function render(){api.board.mockResolvedValue({data:{rows:[row],total:1,summary:{quoteAmount:12345.67}}});wrapper=mount(Board,{global:{plugins:[ElementPlus]},attachTo:document.body});await flushPromises();return wrapper}
it('opens each progress stage directly and marks only complete stages',async()=>{await render();expect(document.querySelectorAll('.document-step')).toHaveLength(4);expect(document.querySelectorAll('.document-step.is-complete')).toHaveLength(2);await wrapper.findAll('.document-step')[2].trigger('click');await flushPromises();expect(api.open).toHaveBeenCalledWith('batch',7,'机器人部件','ACCEPTANCE');expect(document.body.textContent).toContain('12,345.67')})
it('shows exactly the requested four columns in project cost totals',async()=>{api.costs.mockResolvedValue({data:{rows:[{projectId:1,projectCode:'P-1',projectName:'机器人',expenseCategoryName:'材料费',quoteAmount:200},{projectId:1,projectCode:'P-1',projectName:'机器人',expenseCategoryName:'服务费',quoteAmount:300}],total:1,summary:{quoteAmount:500}}});await render();[...document.querySelectorAll('.el-radio-button')].find(b=>b.textContent.includes('项目费用统计')).click();await flushPromises();expect([...document.querySelectorAll('th .cell')].map(e=>e.textContent.trim())).toEqual(['项目编号','项目名称','费用类别','费用统计(元)']);expect(document.querySelector('td[rowspan="2"]')).toBeTruthy();expect(api.costs).toHaveBeenCalled()})
it('never offers quote totals to an ordinary employee',async()=>{api.user.id=2;api.user.roles=['common'];api.user.permissions=['warehouse:purchase:list'];await render();expect(document.body.textContent).not.toContain('项目费用统计');expect(document.body.textContent).not.toContain('12,345.67');expect(document.body.textContent).toContain('报价金额仅采购管理员可见')})

View File

@ -0,0 +1,17 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Documents from '../../src/components/PurchaseDocuments/index.vue'
const api=vi.hoisted(()=>({list:vi.fn(),request:vi.fn()}))
vi.mock('@/utils/request',()=>({default:api.request}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['warehouse:purchase:list','warehouse:purchase:edit']})}))
vi.mock('@/api/warehouse/purchase-documents',()=>({listPurchaseDocuments:api.list,savePurchaseDocumentNumber:vi.fn(),uploadPurchaseDocument:vi.fn(),removePurchaseDocument:vi.fn(),readPurchaseDocument:vi.fn()}))
const groups=()=>['REQUEST','CONTRACT','ACCEPTANCE','PAYMENT','OTHER'].map(kind=>({kind,label:{REQUEST:'采购申请',CONTRACT:'合同',ACCEPTANCE:'验收资料',PAYMENT:'付款资料',OTHER:'其他附件'}[kind],number:kind==='REQUEST'?'SX-1':kind==='CONTRACT'?'HT-1':'',version:1,files:[]}))
let wrapper;afterEach(()=>{wrapper?.unmount();document.body.innerHTML='';vi.resetAllMocks()})
const button=text=>[...document.querySelectorAll('button')].find(b=>b.textContent.trim()===text)
it('generates inside acceptance documents and refreshes the saved attachment list',async()=>{
const next=groups();next.find(g=>g.kind==='ACCEPTANCE').files=[{id:'saved-file',name:'验收资料_待签章.pdf',size:1000,contentType:'application/pdf'}]
api.list.mockResolvedValueOnce({data:groups()}).mockResolvedValueOnce({data:next});api.request.mockResolvedValueOnce({data:{ready:true,count:1,version:'v1',issues:[],documents:[{label:'采购申请',numberLabel:'随行编号',numbered:true,files:1},{label:'合同',numberLabel:'合同编号',numbered:true,files:1}],fields:{purchaser:'甲方',supplier:'乙方',contractNo:'HT-1',address:'固定地址',deliveryLocation:'招商车研',checks:Array(7).fill('')},checkLabels:Array(7).fill('检查项')}}).mockResolvedValueOnce({data:{id:'saved-file'}})
wrapper=mount(Documents,{global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open('batch',7,'批次','ACCEPTANCE');await flushPromises();expect(document.querySelectorAll('[role="tab"]')).toHaveLength(5);expect(document.body.textContent).not.toContain('报价编号');button('生成验收资料').click();await flushPromises();button('生成并保存').click();await flushPromises();expect(api.list).toHaveBeenCalledTimes(2);expect(document.body.textContent).toContain('验收资料_待签章.pdf');expect(button('下载')).toBeTruthy();expect(button('上传PDF')).toBeTruthy()
})
it('retains the request number and prevents generation with an unsaved number',async()=>{api.list.mockResolvedValue({data:groups()});wrapper=mount(Documents,{global:{plugins:[ElementPlus]},attachTo:document.body});await wrapper.vm.open('batch',7,'批次','REQUEST');await flushPromises();expect(document.body.textContent).toContain('随行编号');const input=document.querySelector('.purchase-documents__number input');input.value='UNSAVED';input.dispatchEvent(new Event('input',{bubbles:true}));await flushPromises();[...document.querySelectorAll('[role="tab"]')].find(b=>b.textContent.includes('验收资料')).click();await flushPromises();expect(button('生成验收资料').disabled).toBe(true)})

View File

@ -20,7 +20,7 @@ function fixture(){
for(const name of ['readonly','editableCell','isGridSelected','isGridTypingCell','focusGridCell','startCellSelection','extendCellSelection','endCellSelection','focusSelectedCell','originalIndex','activateCell','typeGridCell','navigate','finishCellEdit','clearGridSelection','remember','undo','redo','displayCell','applyGridText','paste','fillGrid','serialize','rowDefaults','emptyRow','installInsertedRows','appendAfterTab','rowCommand','insertManyRows','remove','applyPastePreview','resetRowView'])vm[name]=Sheet.methods[name].bind(vm)
Object.defineProperties(vm,{visibleRows:{get:()=>vm.sheet.rows},rowIndexMap:{get:()=>new Map(vm.sheet.rows.map((r,i)=>[r._key,i]))},visibleRowIndexMap:{get:()=>vm.rowIndexMap},cellRange:{get:()=>Sheet.computed.cellRange.call(vm)},contextRow:{get:()=>Sheet.computed.contextRow.call(vm)},canRemoveSelection:{get:()=>Sheet.computed.canRemoveSelection.call(vm)}})
vm._editor=createSheetEditor(vm)
vm.sheet={batch:{},deletedIds:[],rows:[{_key:'r1',materialName:'原物品',materialBrand:'原品牌',quantity:2,unit:'个',finalUnitPrice:3,actualUnitPrice:4},{_key:'r2',materialName:'第二项',materialBrand:'乙品牌',quantity:5,unit:'个',finalUnitPrice:6,actualUnitPrice:7}]}
vm.sheet={batch:{expenseCategoryId:9},deletedIds:[],rows:[{_key:'r1',materialName:'原物品',materialBrand:'原品牌',quantity:2,unit:'个',finalUnitPrice:3,actualUnitPrice:4},{_key:'r2',materialName:'第二项',materialBrand:'乙品牌',quantity:5,unit:'个',finalUnitPrice:6,actualUnitPrice:7}]}
vm.baseline=JSON.stringify(vm.sheet)
const wrapper=mount({components:{Cell},setup:()=>({vm}),template:'<div tabindex="-1"><template v-for="(row,index) in vm.sheet.rows" :key="row._key"><Cell v-for="column in vm.columns" :key="column.field" :row="row" :column="column" :index="index" :owner="vm" :selected="vm.isGridSelected(row,column.field)" :typing="vm.isGridTypingCell(row,column.field)" :active="vm.editCell===row._key+\'|\'+column.field"/></template></div>'},{attachTo:document.body,global:{plugins:[ElementPlus],stubs:{ItemCategorySelect:true}}})
vm.$el=wrapper.element

View File

@ -0,0 +1,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {mergeProjectRows} from '../../src/utils/purchase-board.js'
test('merges only adjacent rows of the same project and leaves source rows unchanged',()=>{
const rows=[{projectId:1,expenseCategoryId:2},{projectId:1,expenseCategoryId:3},{projectId:2},{projectId:3},{projectId:3}]
assert.deepEqual(mergeProjectRows(rows).map(r=>r._span),[2,0,1,2,0]);assert(!('_span' in rows[0]));assert.deepEqual(mergeProjectRows([]),[])
})

View File

@ -3,10 +3,10 @@ import assert from 'node:assert/strict'
import fs from 'node:fs'
import {purchaseDocumentKinds,purchaseAttachmentError,purchaseDocumentPath,purchaseDocumentId,purchaseUploadId,purchaseNumberDirty,mergePurchaseDocuments} from '../../src/utils/purchase-documents.js'
test('six optional batch groups and business numbers are presented in business order',()=>{
assert.deepEqual(purchaseDocumentKinds.map(g=>g.kind),['REQUEST','QUOTE','CONTRACT','ACCEPTANCE','PAYMENT','OTHER'])
test('five batch groups keep the request number and merge quotation documents',()=>{
assert.deepEqual(purchaseDocumentKinds.map(g=>g.kind),['REQUEST','CONTRACT','ACCEPTANCE','PAYMENT','OTHER'])
assert.equal(purchaseDocumentKinds[0].numberLabel,'随行编号')
assert.equal(purchaseDocumentKinds[2].numberLabel,'合同编号')
assert.equal(purchaseDocumentKinds[1].numberLabel,'合同编号')
})
test('workflow groups accept PDF and other/detail attachments allow ordinary office formats',()=>{
assert.equal(purchaseAttachmentError({name:'合同.pdf',size:1024},'CONTRACT'),'')
@ -41,11 +41,10 @@ test('attachment reload preserves unsaved numbers and their version and reports
test('purchase sheet exposes batch buttons and saved-line attachment entry without gating business actions',()=>{
const sheet=fs.readFileSync(new URL('../../src/components/PurchaseSheet/index.vue',import.meta.url),'utf8')
assert.match(sheet,/v-for="document in documentKinds"/)
assert.match(sheet,/documents\.open\('detail',s\.row\.id/)
assert.match(sheet,/保存批次后可维护附件及编号/)
assert.match(sheet,/documents\.open\('detail',row\.id/)
const drawer=fs.readFileSync(new URL('../../src/components/PurchaseDocuments/index.vue',import.meta.url),'utf8')
assert.doesNotMatch(drawer,/<el-dialog/)
assert.match(drawer,/可选资料,不影响采购、到货、验收或付款流程/)
assert.match(drawer,/生成验收资料前需补齐采购申请、合同/)
assert.match(drawer,/user\.permissions/)
assert.match(drawer,/groups\.value\.some\(purchaseNumberDirty\)/)
})

View File

@ -0,0 +1,9 @@
-- target-database: cmvr-project-dev
-- Apply once; back up purchase_batch and navigation first. Mixed historical categories remain pending.
ALTER TABLE purchase_batch ADD COLUMN expense_category_id bigint NULL, ADD INDEX idx_purchase_batch_expense (expense_category_id);
UPDATE purchase_batch b JOIN (SELECT purchase_batch_id,MIN(expense_category_id) category_id FROM purchase_request WHERE del_flag='0' AND purchase_status<>5 AND purchase_batch_id IS NOT NULL GROUP BY purchase_batch_id HAVING COUNT(DISTINCT expense_category_id)=1 AND COUNT(*)=COUNT(expense_category_id)) r ON r.purchase_batch_id=b.id SET b.expense_category_id=r.category_id WHERE b.expense_category_id IS NULL;
UPDATE sys_menu SET menu_name='采购申请',order_num=2 WHERE component='warehouse/purchase/index';
UPDATE sys_menu SET menu_name='到货',order_num=3 WHERE component='warehouse/arrival/index';
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,route_name,menu_type,visible,status,perms,icon,create_by,create_time) SELECT '采购看板',p.menu_id,1,'board','warehouse/purchaseBoard/index','PurchaseBoard','C','0','0','warehouse:purchase:list','chart','projectdev-migration',CURRENT_TIMESTAMP FROM sys_menu p WHERE p.parent_id=0 AND p.path='procurement' AND NOT EXISTS(SELECT 1 FROM sys_menu WHERE component='warehouse/purchaseBoard/index');
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,route_name,menu_type,visible,status,perms,icon,create_by,create_time) SELECT '验收',p.menu_id,4,'acceptance','warehouse/acceptance/index','PurchaseAcceptance','C','0','0','warehouse:purchase:list','checkbox','projectdev-migration',CURRENT_TIMESTAMP FROM sys_menu p WHERE p.parent_id=0 AND p.path='procurement' AND NOT EXISTS(SELECT 1 FROM sys_menu WHERE component='warehouse/acceptance/index');
INSERT INTO sys_role_menu(role_id,menu_id) SELECT DISTINCT a.role_id,n.menu_id FROM sys_role_menu a JOIN sys_menu o ON o.menu_id=a.menu_id JOIN sys_menu n ON n.component IN ('warehouse/purchaseBoard/index','warehouse/acceptance/index') WHERE o.component='warehouse/purchase/index' AND NOT EXISTS(SELECT 1 FROM sys_role_menu x WHERE x.role_id=a.role_id AND x.menu_id=n.menu_id);