Commit 0dce29dfce590af5cdaec4c52bcff313773694a4

Authored by 房远帅
1 parent c212bd8e

采购-入库:原料化验报告单打印

@@ -121,6 +121,9 @@ public class GetProcurementAssayReportBo extends BaseBo<ProcurementAssayReport> @@ -121,6 +121,9 @@ public class GetProcurementAssayReportBo extends BaseBo<ProcurementAssayReport>
121 @ApiModelProperty("是否展示审核详情按钮") 121 @ApiModelProperty("是否展示审核详情按钮")
122 private Boolean showExamineDetail; 122 private Boolean showExamineDetail;
123 123
  124 + @ApiModelProperty("取样人(明细关联送样单的创建人,多人中文逗号分隔)")
  125 + private String sampler;
  126 +
124 @ApiModelProperty("创建人") 127 @ApiModelProperty("创建人")
125 private String createBy; 128 private String createBy;
126 129
@@ -154,7 +157,7 @@ public class GetProcurementAssayReportBo extends BaseBo<ProcurementAssayReport> @@ -154,7 +157,7 @@ public class GetProcurementAssayReportBo extends BaseBo<ProcurementAssayReport>
154 @ApiModelProperty("样品:过磅品种ID") 157 @ApiModelProperty("样品:过磅品种ID")
155 private String productId; 158 private String productId;
156 159
157 - @ApiModelProperty("样品名称") 160 + @ApiModelProperty("样品(品种关系表代号)")
158 private String productName; 161 private String productName;
159 162
160 @ApiModelProperty("数量(自动带出过磅明细,单位公斤)") 163 @ApiModelProperty("数量(自动带出过磅明细,单位公斤)")
1 package com.lframework.xingyun.sc.procurement.controller.weighing; 1 package com.lframework.xingyun.sc.procurement.controller.weighing;
2 2
  3 +import cn.hutool.core.io.resource.ClassPathResource;
  4 +import com.lframework.starter.common.exceptions.impl.DefaultClientException;
3 import com.lframework.starter.web.core.annotations.security.HasPermission; 5 import com.lframework.starter.web.core.annotations.security.HasPermission;
4 import com.lframework.starter.web.core.components.resp.InvokeResult; 6 import com.lframework.starter.web.core.components.resp.InvokeResult;
5 import com.lframework.starter.web.core.components.resp.InvokeResultBuilder; 7 import com.lframework.starter.web.core.components.resp.InvokeResultBuilder;
@@ -18,17 +20,38 @@ import com.lframework.xingyun.sc.procurement.vo.weighing.QueryAssaySelectableTic @@ -18,17 +20,38 @@ import com.lframework.xingyun.sc.procurement.vo.weighing.QueryAssaySelectableTic
18 import com.lframework.xingyun.sc.procurement.vo.weighing.QueryProcurementAssayReportVo; 20 import com.lframework.xingyun.sc.procurement.vo.weighing.QueryProcurementAssayReportVo;
19 import com.lframework.xingyun.sc.procurement.vo.weighing.UpdateAssayReportQualityVo; 21 import com.lframework.xingyun.sc.procurement.vo.weighing.UpdateAssayReportQualityVo;
20 import com.lframework.xingyun.sc.procurement.vo.weighing.UpdateProcurementAssayReportVo; 22 import com.lframework.xingyun.sc.procurement.vo.weighing.UpdateProcurementAssayReportVo;
  23 +import com.lframework.xingyun.sc.utils.ExcelUtil;
  24 +import com.lframework.xingyun.sc.utils.ResponseUtil;
21 import io.swagger.annotations.Api; 25 import io.swagger.annotations.Api;
22 import io.swagger.annotations.ApiImplicitParam; 26 import io.swagger.annotations.ApiImplicitParam;
23 import io.swagger.annotations.ApiOperation; 27 import io.swagger.annotations.ApiOperation;
24 28
  29 +import java.io.File;
  30 +import java.io.FileInputStream;
  31 +import java.io.FileNotFoundException;
  32 +import java.io.FileOutputStream;
  33 +import java.io.IOException;
  34 +import java.io.InputStream;
  35 +import java.math.BigDecimal;
  36 +import java.nio.file.Files;
  37 +import java.time.format.DateTimeFormatter;
  38 +import java.util.HashMap;
25 import java.util.List; 39 import java.util.List;
  40 +import java.util.Map;
  41 +import java.util.function.Function;
26 import java.util.stream.Collectors; 42 import java.util.stream.Collectors;
27 import javax.annotation.Resource; 43 import javax.annotation.Resource;
  44 +import javax.servlet.http.HttpServletResponse;
28 import javax.validation.Valid; 45 import javax.validation.Valid;
29 import javax.validation.constraints.NotBlank; 46 import javax.validation.constraints.NotBlank;
30 47
31 import lombok.extern.slf4j.Slf4j; 48 import lombok.extern.slf4j.Slf4j;
  49 +import org.apache.poi.ss.usermodel.Cell;
  50 +import org.apache.poi.ss.usermodel.CellType;
  51 +import org.apache.poi.ss.usermodel.Row;
  52 +import org.apache.poi.ss.usermodel.Sheet;
  53 +import org.apache.poi.ss.usermodel.Workbook;
  54 +import org.apache.poi.xssf.usermodel.XSSFWorkbook;
32 import org.springframework.util.CollectionUtils; 55 import org.springframework.util.CollectionUtils;
33 import org.springframework.validation.annotation.Validated; 56 import org.springframework.validation.annotation.Validated;
34 import org.springframework.web.bind.annotation.GetMapping; 57 import org.springframework.web.bind.annotation.GetMapping;
@@ -48,6 +71,42 @@ import org.springframework.web.bind.annotation.RestController; @@ -48,6 +71,42 @@ import org.springframework.web.bind.annotation.RestController;
48 @RequestMapping("/procurement/assay/report") 71 @RequestMapping("/procurement/assay/report")
49 public class ProcurementAssayReportController extends DefaultBaseController { 72 public class ProcurementAssayReportController extends DefaultBaseController {
50 73
  74 + /**
  75 + * 明细表头行(Excel第4行):样品/数量/样号/各成分代号
  76 + */
  77 + private static final int ASSAY_HEADER_ROW = 3;
  78 +
  79 + /**
  80 + * 明细首行(Excel第5行),模板固定预留15行(第5~19行,样号1~15已预填)
  81 + */
  82 + private static final int ASSAY_LINE_START_ROW = 4;
  83 +
  84 + /**
  85 + * 明细表头文本 -> 取值函数(表头:样品/数量/样号/各成分代号,4个模板成分列不同按表头自动匹配)
  86 + */
  87 + private static final Map<String, Function<GetProcurementAssayReportBo.LineBo, Object>> LINE_VALUE_GETTERS;
  88 +
  89 + static {
  90 + Map<String, Function<GetProcurementAssayReportBo.LineBo, Object>> map = new HashMap<>();
  91 + map.put("样品", GetProcurementAssayReportBo.LineBo::getProductName);
  92 + map.put("数量", GetProcurementAssayReportBo.LineBo::getQuantity);
  93 + map.put("样号", GetProcurementAssayReportBo.LineBo::getSampleNo);
  94 + map.put("Cu", GetProcurementAssayReportBo.LineBo::getCu);
  95 + map.put("Zn", GetProcurementAssayReportBo.LineBo::getZn);
  96 + map.put("Pb", GetProcurementAssayReportBo.LineBo::getPb);
  97 + map.put("Fe", GetProcurementAssayReportBo.LineBo::getFe);
  98 + map.put("P", GetProcurementAssayReportBo.LineBo::getP);
  99 + map.put("Sn", GetProcurementAssayReportBo.LineBo::getSn);
  100 + map.put("Ni", GetProcurementAssayReportBo.LineBo::getNi);
  101 + map.put("Al", GetProcurementAssayReportBo.LineBo::getAl);
  102 + map.put("Cd", GetProcurementAssayReportBo.LineBo::getCd);
  103 + map.put("Cr6+", GetProcurementAssayReportBo.LineBo::getCr6);
  104 + map.put("Cr6", GetProcurementAssayReportBo.LineBo::getCr6);
  105 + map.put("Hg", GetProcurementAssayReportBo.LineBo::getHg);
  106 + map.put("Bi", GetProcurementAssayReportBo.LineBo::getBi);
  107 + LINE_VALUE_GETTERS = map;
  108 + }
  109 +
51 @Resource 110 @Resource
52 private ProcurementAssayReportService procurementAssayReportService; 111 private ProcurementAssayReportService procurementAssayReportService;
53 112
@@ -171,4 +230,211 @@ public class ProcurementAssayReportController extends DefaultBaseController { @@ -171,4 +230,211 @@ public class ProcurementAssayReportController extends DefaultBaseController {
171 procurementAssayReportService.delete(id); 230 procurementAssayReportService.delete(id);
172 return InvokeResultBuilder.success(); 231 return InvokeResultBuilder.success();
173 } 232 }
  233 +
  234 + /**
  235 + * 打印原料化验报告单
  236 + *
  237 + * @param exportType 导出类型 PDF-导出PDF文件,其他/默认-导出Excel文件
  238 + */
  239 + @ApiOperation("打印原料化验报告单(exportType=PDF导出PDF文件,默认Excel;按分厂选择模板:一分厂1/二分厂2/三分厂3/紫铜分厂4)")
  240 + @HasPermission({"warehouse-manage:material-test:print"})
  241 + @ApiImplicitParam(value = "ID", name = "id", paramType = "query", required = true)
  242 + @GetMapping("/export")
  243 + public void export(@NotBlank(message = "ID不能为空!") String id, String exportType,
  244 + HttpServletResponse response) throws IOException {
  245 +
  246 + GetProcurementAssayReportBo data = procurementAssayReportService.findDetail(id);
  247 +
  248 + // 模板按分厂编号选择:一分厂yfc-1、二分厂efc-2、三分厂sfc-3、紫铜分厂ztfc-4
  249 + String workshopCode = data.getWorkshopCode();
  250 + String templateFile;
  251 + if ("yfc".equals(workshopCode)) {
  252 + templateFile = "templates/assayReportTemplate1.xlsx";
  253 + } else if ("efc".equals(workshopCode)) {
  254 + templateFile = "templates/assayReportTemplate2.xlsx";
  255 + } else if ("sfc".equals(workshopCode)) {
  256 + templateFile = "templates/assayReportTemplate3.xlsx";
  257 + } else if ("ztfc".equals(workshopCode)) {
  258 + templateFile = "templates/assayReportTemplate4.xlsx";
  259 + } else {
  260 + throw new DefaultClientException("该分厂未配置化验报告单打印模板!");
  261 + }
  262 +
  263 + try {
  264 + try (InputStream inputStream = new ClassPathResource(templateFile).getStream();
  265 + Workbook workbook = new XSSFWorkbook(inputStream)) {
  266 + Sheet sheet = workbook.getSheetAt(0);
  267 +
  268 + // 化验明细:最多15条(超出取前15条);模板固定预留15行(Excel第5~19行),样号1~15已预填
  269 + List<GetProcurementAssayReportBo.LineBo> lines = data.getLines();
  270 + int lineSize = lines == null ? 0 : Math.min(lines.size(), 15);
  271 +
  272 + // 表头信息分布在两行(Excel第3~4行:样品/数量/样号纵向合并、值在第3行,成分代号在第4行);
  273 + // 表头文本去所有空白(如"样 品"),4个模板成分列不同按表头自动适配
  274 + Map<String, Integer> columnMap = new HashMap<>();
  275 + for (int headerRowIdx : new int[]{ASSAY_HEADER_ROW - 1, ASSAY_HEADER_ROW}) {
  276 + Row headerRow = sheet.getRow(headerRowIdx);
  277 + if (headerRow == null) {
  278 + continue;
  279 + }
  280 + for (Cell cell : headerRow) {
  281 + if (cell.getCellTypeEnum() == CellType.STRING) {
  282 + String head = cell.getStringCellValue().replaceAll("\\s+", "");
  283 + if (!head.isEmpty() && !columnMap.containsKey(head)) {
  284 + columnMap.put(head, cell.getColumnIndex());
  285 + }
  286 + }
  287 + }
  288 + }
  289 +
  290 + // 逐行填充明细(无数据的行保持模板空白)
  291 + for (int i = 0; i < lineSize; i++) {
  292 + fillAssayReportLineRow(sheet, ASSAY_LINE_START_ROW + i, columnMap, lines.get(i));
  293 + }
  294 +
  295 + // 主表占位符替换(${字段} / #{字段},模板里用到哪个替换哪个)
  296 + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  297 + Map<String, Object> dataMap = new HashMap<>();
  298 + dataMap.put("weighingTicketCode", nvl(data.getWeighingTicketCode()));
  299 + dataMap.put("planCode", nvl(data.getPlanCode()));
  300 + dataMap.put("supplierName", nvl(data.getSupplierName()));
  301 + dataMap.put("workshopName", nvl(data.getWorkshopName()));
  302 + dataMap.put("productName", nvl(data.getProductName()));
  303 + dataMap.put("reportDate", data.getReportDate() == null ? ""
  304 + : data.getReportDate().format(dateFormatter));
  305 + dataMap.put("sampler", nvl(data.getSampler()));
  306 + dataMap.put("hasQualityProblem", data.getHasQualityProblem() == null ? ""
  307 + : (data.getHasQualityProblem() ? "是" : "否"));
  308 + dataMap.put("processOpinion", nvl(data.getProcessOpinion()));
  309 + dataMap.put("continueApproval", data.getContinueApproval() == null ? ""
  310 + : (data.getContinueApproval() ? "是" : "否"));
  311 + dataMap.put("ckzgName", nvl(data.getCkzgName()));
  312 + dataMap.put("ckzgOpinion", nvl(data.getCkzgOpinion()));
  313 + dataMap.put("gyglkzgName", nvl(data.getGyglkzgName()));
  314 + dataMap.put("gyglkzgOpinion", nvl(data.getGyglkzgOpinion()));
  315 + dataMap.put("gybzgName", nvl(data.getGybzgName()));
  316 + dataMap.put("gybzgOpinion", nvl(data.getGybzgOpinion()));
  317 + dataMap.put("fczgName", nvl(data.getFczgName()));
  318 + dataMap.put("fczgOpinion", nvl(data.getFczgOpinion()));
  319 + dataMap.put("zjlName", nvl(data.getZjlName()));
  320 + dataMap.put("zjlOpinion", nvl(data.getZjlOpinion()));
  321 + dataMap.put("createBy", nvl(data.getCreateBy()));
  322 + processTemplateSheet(sheet, dataMap);
  323 +
  324 + if ("PDF".equals(exportType)) {
  325 + // 导出 PDF:先写临时 .xlsx 文件,再调 LibreOffice 转换输出
  326 + ResponseUtil.setPDFResponseHead(response,
  327 + nvl(data.getWeighingTicketCode()) + "-原料化验报告单.pdf");
  328 + File tempExcel = File.createTempFile(
  329 + "assay_report_" + nvl(data.getWeighingTicketCode()), ".xlsx");
  330 + try {
  331 + try (FileOutputStream fos = new FileOutputStream(tempExcel)) {
  332 + workbook.write(fos);
  333 + }
  334 + File pdfFile = ExcelUtil.convertExcelToPdf(tempExcel,
  335 + "/usr/bin/libreoffice --headless --convert-to pdf --outdir %s %s");
  336 + try (InputStream pdfIn = new FileInputStream(pdfFile)) {
  337 + byte[] buffer = new byte[8192];
  338 + int len;
  339 + while ((len = pdfIn.read(buffer)) != -1) {
  340 + response.getOutputStream().write(buffer, 0, len);
  341 + }
  342 + response.getOutputStream().flush();
  343 + } finally {
  344 + if (pdfFile != null && pdfFile.exists()) {
  345 + Files.delete(pdfFile.toPath());
  346 + }
  347 + }
  348 + } finally {
  349 + if (tempExcel != null && tempExcel.exists()) {
  350 + Files.delete(tempExcel.toPath());
  351 + }
  352 + }
  353 + } else {
  354 + // 默认导出 Excel
  355 + ResponseUtil.setExcelResponseHead(response,
  356 + nvl(data.getWeighingTicketCode()) + "-原料化验报告单.xlsx");
  357 + workbook.write(response.getOutputStream());
  358 + response.getOutputStream().flush();
  359 + }
  360 + } catch (FileNotFoundException e) {
  361 + throw new RuntimeException("模板文件不存在: " + templateFile, e);
  362 + } catch (IOException e) {
  363 + throw new RuntimeException("无法读取模板文件: " + templateFile, e);
  364 + }
  365 + } catch (Exception e) {
  366 + log.error("打印原料化验报告单失败, id={}, {}", id, e.getMessage(), e);
  367 + }
  368 + }
  369 +
  370 + /**
  371 + * 填充一行化验明细(按表头文本映射的列取值,无数据的列保持模板空白)
  372 + */
  373 + private void fillAssayReportLineRow(Sheet sheet, int rowIdx, Map<String, Integer> columnMap,
  374 + GetProcurementAssayReportBo.LineBo line) {
  375 + if (line == null) {
  376 + return;
  377 + }
  378 + for (Map.Entry<String, Integer> entry : columnMap.entrySet()) {
  379 + Function<GetProcurementAssayReportBo.LineBo, Object> getter = LINE_VALUE_GETTERS.get(entry.getKey());
  380 + if (getter == null) {
  381 + continue;
  382 + }
  383 + Object value = getter.apply(line);
  384 + if (value != null) {
  385 + ExcelUtil.setCellValue(sheet, rowIdx, entry.getValue(), value);
  386 + }
  387 + }
  388 + }
  389 +
  390 + /**
  391 + * 按单 Sheet 替换模板占位符(${...} / #{...})
  392 + */
  393 + private void processTemplateSheet(Sheet sheet, Map<String, Object> dataMap) {
  394 + for (Row row : sheet) {
  395 + for (Cell cell : row) {
  396 + if (cell.getCellTypeEnum() == CellType.STRING) {
  397 + String cellValue = cell.getStringCellValue();
  398 + String newValue = replacePlaceholders(cellValue, dataMap);
  399 + if (!cellValue.equals(newValue)) {
  400 + cell.setCellValue(newValue);
  401 + }
  402 + }
  403 + }
  404 + }
  405 + }
  406 +
  407 + private String replacePlaceholders(String text, Map<String, Object> dataMap) {
  408 + if (text == null || text.isEmpty()) {
  409 + return text;
  410 + }
  411 +
  412 + String result = text;
  413 + for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
  414 + String placeholder = "${" + entry.getKey() + "}";
  415 + String value = entry.getValue() != null ? entry.getValue().toString() : "";
  416 + value = value.replace("\\n", "\n");
  417 + result = result.replace(placeholder, value);
  418 + }
  419 +
  420 + for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
  421 + String placeholder = "#{" + entry.getKey() + "}";
  422 + String value = entry.getValue() != null ? entry.getValue().toString() : "";
  423 + value = value.replace("\\n", "\n");
  424 + result = result.replace(placeholder, value);
  425 + }
  426 +
  427 + return result;
  428 + }
  429 +
  430 + private String formatDecimal(BigDecimal bd) {
  431 + if (bd == null) {
  432 + return "";
  433 + }
  434 + return bd.stripTrailingZeros().toPlainString();
  435 + }
  436 +
  437 + private String nvl(Object o) {
  438 + return o == null ? "" : o.toString();
  439 + }
174 } 440 }
@@ -23,7 +23,9 @@ import com.lframework.starter.web.core.utils.OpLogUtil; @@ -23,7 +23,9 @@ import com.lframework.starter.web.core.utils.OpLogUtil;
23 import com.lframework.starter.web.core.utils.PageHelperUtil; 23 import com.lframework.starter.web.core.utils.PageHelperUtil;
24 import com.lframework.starter.web.core.utils.PageResultUtil; 24 import com.lframework.starter.web.core.utils.PageResultUtil;
25 import com.lframework.starter.web.inner.components.oplog.OtherOpLogType; 25 import com.lframework.starter.web.inner.components.oplog.OtherOpLogType;
  26 +import com.lframework.xingyun.basedata.entity.BreedRelationship;
26 import com.lframework.xingyun.basedata.entity.Workshop; 27 import com.lframework.xingyun.basedata.entity.Workshop;
  28 +import com.lframework.xingyun.basedata.service.breed.BreedRelationshipService;
27 import com.lframework.xingyun.basedata.service.workshop.WorkshopService; 29 import com.lframework.xingyun.basedata.service.workshop.WorkshopService;
28 import com.lframework.xingyun.sc.bo.procurement.GetAssayReportApplyOptionBo; 30 import com.lframework.xingyun.sc.bo.procurement.GetAssayReportApplyOptionBo;
29 import com.lframework.xingyun.sc.bo.procurement.GetAssayReportPlanOptionBo; 31 import com.lframework.xingyun.sc.bo.procurement.GetAssayReportPlanOptionBo;
@@ -56,6 +58,7 @@ import java.util.Arrays; @@ -56,6 +58,7 @@ import java.util.Arrays;
56 import java.util.Collections; 58 import java.util.Collections;
57 import java.util.HashSet; 59 import java.util.HashSet;
58 import java.util.LinkedHashMap; 60 import java.util.LinkedHashMap;
  61 +import java.util.LinkedHashSet;
59 import java.util.List; 62 import java.util.List;
60 import java.util.Map; 63 import java.util.Map;
61 import java.util.Objects; 64 import java.util.Objects;
@@ -135,6 +138,9 @@ public class ProcurementAssayReportServiceImpl @@ -135,6 +138,9 @@ public class ProcurementAssayReportServiceImpl
135 private WorkshopService workshopService; 138 private WorkshopService workshopService;
136 139
137 @Resource 140 @Resource
  141 + private BreedRelationshipService breedRelationshipService;
  142 +
  143 + @Resource
138 private FlowInstanceWrapperService flowInstanceWrapperService; 144 private FlowInstanceWrapperService flowInstanceWrapperService;
139 145
140 @Resource 146 @Resource
@@ -189,6 +195,42 @@ public class ProcurementAssayReportServiceImpl @@ -189,6 +195,42 @@ public class ProcurementAssayReportServiceImpl
189 } 195 }
190 } 196 }
191 197
  198 + // 样品名称改为品种关系表代号(productId 即品种关系表ID)
  199 + List<String> productIds = lines == null ? new ArrayList<>()
  200 + : lines.stream().map(ProcurementAssayReportLine::getProductId)
  201 + .filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());
  202 + if (CollectionUtil.isNotEmpty(productIds)) {
  203 + Map<String, String> codeMap = breedRelationshipService.listByIds(productIds).stream()
  204 + .filter(Objects::nonNull)
  205 + .collect(Collectors.toMap(BreedRelationship::getId, BreedRelationship::getCode, (a, b) -> a));
  206 + for (GetProcurementAssayReportBo.LineBo line : bo.getLines()) {
  207 + line.setProductName(codeMap.get(line.getProductId()));
  208 + }
  209 + }
  210 +
  211 + // 取样人 = 明细关联送样单的创建人(按明细顺序去重,中文逗号分隔)
  212 + List<String> applyIds = lines == null ? new ArrayList<>()
  213 + : lines.stream().map(ProcurementAssayReportLine::getAssayApplyId)
  214 + .filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());
  215 + if (CollectionUtil.isNotEmpty(applyIds)) {
  216 + List<ProcurementAssayApply> applies = assayApplyMapper.selectList(
  217 + Wrappers.lambdaQuery(ProcurementAssayApply.class)
  218 + .in(ProcurementAssayApply::getId, applyIds)
  219 + .select(ProcurementAssayApply::getId, ProcurementAssayApply::getCreateBy));
  220 + Map<String, String> applySamplerMap = applies == null ? new LinkedHashMap<>()
  221 + : applies.stream().filter(a -> a != null && StringUtil.isNotBlank(a.getCreateBy()))
  222 + .collect(Collectors.toMap(ProcurementAssayApply::getId,
  223 + ProcurementAssayApply::getCreateBy, (a, b) -> a));
  224 + Set<String> samplerSet = new LinkedHashSet<>();
  225 + for (String applyId : applyIds) {
  226 + String sampler = applySamplerMap.get(applyId);
  227 + if (sampler != null) {
  228 + samplerSet.add(sampler);
  229 + }
  230 + }
  231 + bo.setSampler(String.join(",", samplerSet));
  232 + }
  233 +
192 return bo; 234 return bo;
193 } 235 }
194 236